|
| 1 | +import { describe, test, expect, beforeAll, afterAll } from "bun:test"; |
| 2 | +import { mkdtempSync, readFileSync } from "fs"; |
| 3 | +import { tmpdir } from "os"; |
| 4 | +import { join, resolve } from "path"; |
| 5 | +import { createServer, type Server } from "http"; |
| 6 | + |
| 7 | +/** |
| 8 | + * The org selector must survive BUNDLING, not just module wiring (#357). |
| 9 | + * |
| 10 | + * Every other org-scope test spawns `bin/postgres-ai.ts` through bun, where each |
| 11 | + * module exists once. `bun build` emits `lib/org-scope.ts` more than once, so a |
| 12 | + * module-level binding is per-copy: the preAction hook wrote one copy and the |
| 13 | + * request path read another, and `x-pgai-org` was silently dropped from most |
| 14 | + * commands while every source-level test passed. These tests run the BUILT |
| 15 | + * artifact -- the thing users actually execute -- against a stub server. |
| 16 | + */ |
| 17 | + |
| 18 | +const CLI_DIR = resolve(import.meta.dir, ".."); |
| 19 | +const ALIAS = "acme-test-org"; |
| 20 | +const GLOBAL_TOKEN = "pai_global_0000000000000000000000000000000000000000"; |
| 21 | + |
| 22 | +let bundlePath: string; |
| 23 | +let server: Server; |
| 24 | +let port: number; |
| 25 | +/** Headers of the first request of the current spawn, reset per command. */ |
| 26 | +let firstHeaders: Record<string, string> | null = null; |
| 27 | + |
| 28 | +function buildBundle(): string { |
| 29 | + const outDir = mkdtempSync(join(tmpdir(), "pgai-bundle-")); |
| 30 | + const result = Bun.spawnSync( |
| 31 | + [process.execPath, "build", "./bin/postgres-ai.ts", "--outdir", outDir, "--target", "node"], |
| 32 | + { cwd: CLI_DIR } |
| 33 | + ); |
| 34 | + if (result.exitCode !== 0) { |
| 35 | + throw new Error(`bun build failed: ${new TextDecoder().decode(result.stderr)}`); |
| 36 | + } |
| 37 | + return join(outDir, "postgres-ai.js"); |
| 38 | +} |
| 39 | + |
| 40 | +/** |
| 41 | + * Async, never spawnSync: the stub server lives in THIS process, so a blocking |
| 42 | + * spawn would deadlock -- the CLI waits for a response the blocked event loop |
| 43 | + * cannot send. |
| 44 | + */ |
| 45 | +async function runBuilt(args: string[], env: Record<string, string> = {}): Promise<void> { |
| 46 | + firstHeaders = null; |
| 47 | + const proc = Bun.spawn([process.execPath, bundlePath, ...args, "--api-base-url", `http://127.0.0.1:${port}/`], { |
| 48 | + env: { ...process.env, PGAI_API_KEY: GLOBAL_TOKEN, PGAI_ORG: "", PGAI_ORG_ID: "", ...env }, |
| 49 | + cwd: CLI_DIR, |
| 50 | + stdout: "ignore", |
| 51 | + stderr: "ignore", |
| 52 | + }); |
| 53 | + await proc.exited; |
| 54 | +} |
| 55 | + |
| 56 | +beforeAll(async () => { |
| 57 | + bundlePath = buildBundle(); |
| 58 | + server = createServer((req, res) => { |
| 59 | + if (firstHeaders === null) { |
| 60 | + firstHeaders = req.headers as Record<string, string>; |
| 61 | + } |
| 62 | + res.writeHead(200, { "Content-Type": "application/json" }); |
| 63 | + // An empty array is a valid, terminal answer for every listing below, so |
| 64 | + // the CLI exits instead of following up with a second request. |
| 65 | + res.end("[]"); |
| 66 | + }); |
| 67 | + await new Promise<void>((done) => server.listen(0, "127.0.0.1", done)); |
| 68 | + port = (server.address() as { port: number }).port; |
| 69 | +}); |
| 70 | + |
| 71 | +afterAll(() => { |
| 72 | + server?.close(); |
| 73 | +}); |
| 74 | + |
| 75 | +/** |
| 76 | + * One command per org-scoped transport module. `issues list` used to be the |
| 77 | + * only passing command and was the one the feature's manual e2e sampled, so it |
| 78 | + * is deliberately NOT representative on its own -- each module gets an entry. |
| 79 | + */ |
| 80 | +const COMMANDS: Array<{ label: string; argv: string[] }> = [ |
| 81 | + { label: "projects (lib/joe)", argv: ["projects"] }, |
| 82 | + { label: "issues list (lib/issues)", argv: ["issues", "list"] }, |
| 83 | + { label: "issues view (lib/issues)", argv: ["issues", "view", "1"] }, |
| 84 | + { label: "reports list (lib/reports)", argv: ["reports", "list"] }, |
| 85 | + { label: "joe activity (lib/joe)", argv: ["joe", "activity", "--project", "1"] }, |
| 86 | + { label: "dblab clone list (lib/dblab)", argv: ["dblab", "clone", "list", "--project", "1"] }, |
| 87 | +]; |
| 88 | + |
| 89 | +describe("the org selector survives bundling", () => { |
| 90 | + for (const { label, argv } of COMMANDS) { |
| 91 | + test(`${label} sends x-pgai-org from the built bundle`, async () => { |
| 92 | + await runBuilt([...argv, "--org", ALIAS]); |
| 93 | + |
| 94 | + expect(firstHeaders).not.toBeNull(); |
| 95 | + expect(firstHeaders?.["x-pgai-org"]).toBe(ALIAS); |
| 96 | + }); |
| 97 | + } |
| 98 | + |
| 99 | + test("--org-id rides the same path", async () => { |
| 100 | + await runBuilt(["projects", "--org-id", "5225"]); |
| 101 | + |
| 102 | + expect(firstHeaders?.["x-pgai-org-id"]).toBe("5225"); |
| 103 | + }); |
| 104 | + |
| 105 | + test("PGAI_ORG reaches the wire from the built bundle too", async () => { |
| 106 | + await runBuilt(["projects"], { PGAI_ORG: ALIAS }); |
| 107 | + |
| 108 | + expect(firstHeaders?.["x-pgai-org"]).toBe(ALIAS); |
| 109 | + }); |
| 110 | +}); |
| 111 | + |
| 112 | +describe("the scope is not held in a per-copy module binding", () => { |
| 113 | + test("the built bundle declares no module-level activeOrgScope", () => { |
| 114 | + const src = readFileSync(bundlePath, "utf8"); |
| 115 | + |
| 116 | + // A bare `let activeOrgScope;` (or a renamed `activeOrgScope2`) means the |
| 117 | + // selection is back in module state, which the duplicate-module emit makes |
| 118 | + // per-copy. The registry symbol is the only form shared across copies. |
| 119 | + expect(src).not.toMatch(/\n\s*(?:let|var)\s+activeOrgScope\d*\s*[;=]/); |
| 120 | + expect(src).toContain("postgres-ai.cli.activeOrgScope"); |
| 121 | + }); |
| 122 | +}); |
0 commit comments