@zitadel/testing 0.5.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/README.md +92 -22
  2. package/dist/app-runner.cjs +3 -4
  3. package/dist/app-runner.mjs +3 -4
  4. package/dist/{handshake-D6MXSUcd.cjs → handshake-BEhxJx4Z.cjs} +21 -5
  5. package/dist/handshake-BEhxJx4Z.cjs.map +1 -0
  6. package/dist/{handshake-CwlxMjW0.mjs → handshake-CZWS5b2X.mjs} +17 -7
  7. package/dist/handshake-CZWS5b2X.mjs.map +1 -0
  8. package/dist/index-B9tztG3_.d.mts +73 -0
  9. package/dist/index.cjs +3 -2
  10. package/dist/index.d.mts +3 -81
  11. package/dist/index.mjs +3 -3
  12. package/dist/{orchestration-Clldecyr.mjs → orchestration-Cf4M8lil.mjs} +2 -3
  13. package/dist/{orchestration-Clldecyr.mjs.map → orchestration-Cf4M8lil.mjs.map} +1 -1
  14. package/dist/{orchestration-gIDANMcF.cjs → orchestration-SELq6dmD.cjs} +2 -3
  15. package/dist/{orchestration-gIDANMcF.cjs.map → orchestration-SELq6dmD.cjs.map} +1 -1
  16. package/dist/playwright.cjs +10 -13
  17. package/dist/playwright.cjs.map +1 -1
  18. package/dist/playwright.d.mts +3 -13
  19. package/dist/playwright.mjs +11 -15
  20. package/dist/playwright.mjs.map +1 -1
  21. package/dist/{session-B84nOEiv.d.mts → session-DueRCvrq.d.mts} +9 -10
  22. package/dist/{src-Ck7eLkah.mjs → src-DImgqUUu.mjs} +74 -27
  23. package/dist/src-DImgqUUu.mjs.map +1 -0
  24. package/dist/{src-DXVDJLrV.cjs → src-EogQCM5q.cjs} +4713 -2307
  25. package/dist/src-EogQCM5q.cjs.map +1 -0
  26. package/dist/supervisor.cjs +4 -5
  27. package/dist/supervisor.mjs +4 -5
  28. package/dist/vitest.d.mts +33 -0
  29. package/dist/vitest.mjs +65 -0
  30. package/dist/vitest.mjs.map +1 -0
  31. package/package.json +19 -11
  32. package/dist/handshake-CwlxMjW0.mjs.map +0 -1
  33. package/dist/handshake-D6MXSUcd.cjs.map +0 -1
  34. package/dist/src-Ck7eLkah.mjs.map +0 -1
  35. package/dist/src-DXVDJLrV.cjs.map +0 -1
@@ -1,8 +1,8 @@
1
- const require_src = require("./src-DXVDJLrV.cjs");
2
- const require_handshake = require("./handshake-D6MXSUcd.cjs");
3
- const require_orchestration = require("./orchestration-gIDANMcF.cjs");
1
+ const require_handshake = require("./handshake-BEhxJx4Z.cjs");
2
+ const require_src = require("./src-EogQCM5q.cjs");
3
+ const require_orchestration = require("./orchestration-SELq6dmD.cjs");
4
4
  let node_fs_promises = require("node:fs/promises");
5
- //#region src/supervisor.ts
5
+ // src/supervisor.ts
6
6
  /**
7
7
  * Playwright webServer entry generated by `withZitadel()`: boots an ephemeral
8
8
  * seeded Zitadel and writes the handshake file that the app runner and the
@@ -71,6 +71,5 @@ main().catch((error) => {
71
71
  console.error(`${LOG} ${error instanceof Error ? error.message : String(error)}`);
72
72
  process.exit(1);
73
73
  });
74
- //#endregion
75
74
 
76
75
  //# sourceMappingURL=supervisor.cjs.map
@@ -1,8 +1,8 @@
1
- import { r as writeHandshake } from "./handshake-CwlxMjW0.mjs";
2
- import { n as startLocalZitadel } from "./src-Ck7eLkah.mjs";
3
- import { a as parseSupervisorConfig, o as requireHandshakePath, r as SUPERVISOR_CONFIG_ENV } from "./orchestration-Clldecyr.mjs";
1
+ import { r as writeHandshake } from "./handshake-CZWS5b2X.mjs";
2
+ import { n as startLocalZitadel } from "./src-DImgqUUu.mjs";
3
+ import { a as parseSupervisorConfig, o as requireHandshakePath, r as SUPERVISOR_CONFIG_ENV } from "./orchestration-Cf4M8lil.mjs";
4
4
  import { access, rm } from "node:fs/promises";
5
- //#region src/supervisor.ts
5
+ // src/supervisor.ts
6
6
  /**
7
7
  * Playwright webServer entry generated by `withZitadel()`: boots an ephemeral
8
8
  * seeded Zitadel and writes the handshake file that the app runner and the
@@ -71,7 +71,6 @@ main().catch((error) => {
71
71
  console.error(`${LOG} ${error instanceof Error ? error.message : String(error)}`);
72
72
  process.exit(1);
73
73
  });
74
- //#endregion
75
74
  export {};
76
75
 
77
76
  //# sourceMappingURL=supervisor.mjs.map
@@ -0,0 +1,33 @@
1
+ import { t as StartLocalZitadelOptions } from "./index-B9tztG3_.mjs";
2
+ import { _ as SeedUserInput, d as InstanceHandle, g as SeedSessionInput, i as identity, l as ConnectedZitadel, m as MintedSession, n as browserSessionCookieName, r as sessionCookieName, t as SESSION_COOKIE_NAME, u as Identity, v as SeedUsersTemplate, y as SeededUser } from "./session-DueRCvrq.mjs";
3
+ import { TestProject } from "vitest/node";
4
+ /**
5
+ * Boot options for the instance: exactly what `startLocalZitadel` takes.
6
+ */
7
+ export type ZitadelGlobalSetupOptions = StartLocalZitadelOptions;
8
+ /**
9
+ * Vitest global setup that boots a local instance with
10
+ * `startLocalZitadel(options)`, provides its serializable handle to the test
11
+ * files, and stops it when the run ends or is interrupted (SIGINT, SIGTERM).
12
+ * Vitest runs a global setup once per project that lists it, so list it in
13
+ * one place. Default-export its result from the module the config names in
14
+ * `test.globalSetup`:
15
+ *
16
+ * ```ts
17
+ * // zitadel.global-setup.ts
18
+ * import { zitadelGlobalSetup } from "@zitadel/testing/vitest";
19
+ * export default zitadelGlobalSetup({ appOrigins: ["http://localhost:3000"] });
20
+ * ```
21
+ *
22
+ * Tests read the instance with {@link injectZitadel}.
23
+ */
24
+ export declare function zitadelGlobalSetup(options?: ZitadelGlobalSetupOptions): (project: TestProject) => Promise<() => Promise<void>>;
25
+ /**
26
+ * The instance the global setup provided, connected in this test worker: the
27
+ * same `seedUser` / `seedUsers` / `seedSession` / `identity` / `api` surface
28
+ * `connectZitadel` returns. Call it in a test or hook; seed a fresh user per
29
+ * test, since the test files share the instance.
30
+ */
31
+ export declare function injectZitadel(): ConnectedZitadel;
32
+ export { type ConnectedZitadel, type Identity, type InstanceHandle, type MintedSession, SESSION_COOKIE_NAME, type SeedSessionInput, type SeedUserInput, type SeedUsersTemplate, type SeededUser, browserSessionCookieName, identity, sessionCookieName };
33
+ //# sourceMappingURL=vitest.d.mts.map
@@ -0,0 +1,65 @@
1
+ import { i as browserSessionCookieName, l as stopLocalServerSync, n as startLocalZitadel, o as sessionCookieName, r as SESSION_COOKIE_NAME, s as identity, t as connectZitadel } from "./src-DImgqUUu.mjs";
2
+ import { inject } from "vitest";
3
+ // src/vitest.ts
4
+ /**
5
+ * The `provide`/`inject` key the global setup hands the handle over under.
6
+ * Not exported: `injectZitadel()` is the only reader, so the key can change
7
+ * without breaking a consumer.
8
+ */
9
+ const HANDLE_KEY = "@zitadel/testing:handle";
10
+ const LOG = "[zitadel-testing]";
11
+ const SIGNALS = ["SIGINT", "SIGTERM"];
12
+ /**
13
+ * Vitest global setup that boots a local instance with
14
+ * `startLocalZitadel(options)`, provides its serializable handle to the test
15
+ * files, and stops it when the run ends or is interrupted (SIGINT, SIGTERM).
16
+ * Vitest runs a global setup once per project that lists it, so list it in
17
+ * one place. Default-export its result from the module the config names in
18
+ * `test.globalSetup`:
19
+ *
20
+ * ```ts
21
+ * // zitadel.global-setup.ts
22
+ * import { zitadelGlobalSetup } from "@zitadel/testing/vitest";
23
+ * export default zitadelGlobalSetup({ appOrigins: ["http://localhost:3000"] });
24
+ * ```
25
+ *
26
+ * Tests read the instance with {@link injectZitadel}.
27
+ */
28
+ function zitadelGlobalSetup(options = {}) {
29
+ return async (project) => {
30
+ const othersExit = new Map(SIGNALS.map((signal) => [signal, process.listenerCount(signal) > 0]));
31
+ const zitadel = await startLocalZitadel(options);
32
+ const onSignal = (signal) => {
33
+ removeHandlers();
34
+ try {
35
+ stopLocalServerSync(zitadel.runtime.dir, options);
36
+ } catch (error) {
37
+ console.error(`${LOG} ${signal} received; stopping the instance failed: ${error instanceof Error ? error.message : String(error)}\n${LOG} \`zitadel stop --all\` stops every instance the CLI started.`);
38
+ }
39
+ if (!othersExit.get(signal)) process.kill(process.pid, signal);
40
+ };
41
+ const removeHandlers = () => {
42
+ for (const signal of SIGNALS) process.off(signal, onSignal);
43
+ };
44
+ for (const signal of SIGNALS) process.once(signal, onSignal);
45
+ project.provide(HANDLE_KEY, zitadel.handle);
46
+ return async () => {
47
+ removeHandlers();
48
+ await zitadel.stop();
49
+ };
50
+ };
51
+ }
52
+ /**
53
+ * The instance the global setup provided, connected in this test worker: the
54
+ * same `seedUser` / `seedUsers` / `seedSession` / `identity` / `api` surface
55
+ * `connectZitadel` returns. Call it in a test or hook; seed a fresh user per
56
+ * test, since the test files share the instance.
57
+ */
58
+ function injectZitadel() {
59
+ const handle = inject(HANDLE_KEY);
60
+ if (!handle) throw new Error("injectZitadel() found no instance. Add a globalSetup module that default-exports zitadelGlobalSetup() to the Vitest config's `test.globalSetup` (see the @zitadel/testing README).");
61
+ return connectZitadel(handle);
62
+ }
63
+ export { SESSION_COOKIE_NAME, browserSessionCookieName, identity, injectZitadel, sessionCookieName, zitadelGlobalSetup };
64
+
65
+ //# sourceMappingURL=vitest.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"vitest.mjs","names":[],"sources":["../src/vitest.ts"],"sourcesContent":["// Peer floor `vitest >=4.0`: Vitest 3.2.4 reads worker state when `vitest` is\n// imported, so this entry would throw inside global setup; 4.0.0 made it lazy.\nimport { inject } from \"vitest\";\nimport type { TestProject } from \"vitest/node\";\n\nimport { connectZitadel, startLocalZitadel, type StartLocalZitadelOptions } from \"./index\";\nimport { stopLocalServerSync } from \"./lifecycle\";\nimport type { ConnectedZitadel, InstanceHandle } from \"./types\";\n\n/**\n * The `provide`/`inject` key the global setup hands the handle over under.\n * Not exported: `injectZitadel()` is the only reader, so the key can change\n * without breaking a consumer.\n */\nconst HANDLE_KEY = \"@zitadel/testing:handle\";\n\nconst LOG = \"[zitadel-testing]\";\nconst SIGNALS = [\"SIGINT\", \"SIGTERM\"] as const;\n\n/**\n * Boot options for the instance: exactly what `startLocalZitadel` takes.\n */\nexport type ZitadelGlobalSetupOptions = StartLocalZitadelOptions;\n\n/**\n * Vitest global setup that boots a local instance with\n * `startLocalZitadel(options)`, provides its serializable handle to the test\n * files, and stops it when the run ends or is interrupted (SIGINT, SIGTERM).\n * Vitest runs a global setup once per project that lists it, so list it in\n * one place. Default-export its result from the module the config names in\n * `test.globalSetup`:\n *\n * ```ts\n * // zitadel.global-setup.ts\n * import { zitadelGlobalSetup } from \"@zitadel/testing/vitest\";\n * export default zitadelGlobalSetup({ appOrigins: [\"http://localhost:3000\"] });\n * ```\n *\n * Tests read the instance with {@link injectZitadel}.\n */\nexport function zitadelGlobalSetup(\n options: ZitadelGlobalSetupOptions = {},\n): (project: TestProject) => Promise<() => Promise<void>> {\n return async (project) => {\n // Whether something else already ends the process on each signal (the\n // Vitest CLI does). Read before adding ours, which would otherwise turn\n // off Node's default exit for that signal.\n const othersExit = new Map(\n SIGNALS.map((signal) => [signal, process.listenerCount(signal) > 0]),\n );\n const zitadel = await startLocalZitadel(options);\n\n // `vitest run` skips global teardown on SIGINT and SIGTERM and exits a\n // tick after the signal, so an awaited stop never finishes and the\n // detached server would outlive the run. Stop it synchronously instead,\n // as the Playwright supervisor stops its instance on the same signals.\n const onSignal = (signal: NodeJS.Signals): void => {\n removeHandlers();\n try {\n stopLocalServerSync(zitadel.runtime.dir, options);\n } catch (error) {\n console.error(\n `${LOG} ${signal} received; stopping the instance failed: ` +\n `${error instanceof Error ? error.message : String(error)}\\n` +\n `${LOG} \\`zitadel stop --all\\` stops every instance the CLI started.`,\n );\n }\n if (!othersExit.get(signal as (typeof SIGNALS)[number])) {\n // Nobody else ends the process: restore Node's default for the signal.\n process.kill(process.pid, signal);\n }\n };\n const removeHandlers = (): void => {\n for (const signal of SIGNALS) {\n process.off(signal, onSignal);\n }\n };\n for (const signal of SIGNALS) {\n process.once(signal, onSignal);\n }\n\n // The handle is the cross-process contract (JSON-serializable), which is\n // what provide() requires. The key is not declared on ProvidedContext so\n // the entry adds nothing to the consumer's vitest types.\n (project.provide as (key: string, value: InstanceHandle) => void)(HANDLE_KEY, zitadel.handle);\n return async () => {\n removeHandlers();\n await zitadel.stop();\n };\n };\n}\n\n/**\n * The instance the global setup provided, connected in this test worker: the\n * same `seedUser` / `seedUsers` / `seedSession` / `identity` / `api` surface\n * `connectZitadel` returns. Call it in a test or hook; seed a fresh user per\n * test, since the test files share the instance.\n */\nexport function injectZitadel(): ConnectedZitadel {\n const handle = (inject as (key: string) => InstanceHandle | undefined)(HANDLE_KEY);\n if (!handle) {\n throw new Error(\n \"injectZitadel() found no instance. Add a globalSetup module that default-exports \" +\n \"zitadelGlobalSetup() to the Vitest config's `test.globalSetup` \" +\n \"(see the @zitadel/testing README).\",\n );\n }\n return connectZitadel(handle);\n}\n\nexport { identity } from \"./seed\";\nexport { browserSessionCookieName, SESSION_COOKIE_NAME, sessionCookieName } from \"./session\";\nexport type {\n ConnectedZitadel,\n Identity,\n InstanceHandle,\n MintedSession,\n SeededUser,\n SeedSessionInput,\n SeedUserInput,\n SeedUsersTemplate,\n} from \"./types\";\n"],"mappings":";;;;;;;;AAcA,MAAM,aAAa;AAEnB,MAAM,MAAM;AACZ,MAAM,UAAU,CAAC,UAAU,SAAS;;;;;;;;;;;;;;;;;AAuBpC,SAAgB,mBACd,UAAqC,CAAC,GACkB;CACxD,OAAO,OAAO,YAAY;EAIxB,MAAM,aAAa,IAAI,IACrB,QAAQ,KAAK,WAAW,CAAC,QAAQ,QAAQ,cAAc,MAAM,IAAI,CAAC,CAAC,CACrE;EACA,MAAM,UAAU,MAAM,kBAAkB,OAAO;EAM/C,MAAM,YAAY,WAAiC;GACjD,eAAe;GACf,IAAI;IACF,oBAAoB,QAAQ,QAAQ,KAAK,OAAO;GAClD,SAAS,OAAO;IACd,QAAQ,MACN,GAAG,IAAI,GAAG,OAAO,2CACZ,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,EAAE,IACvD,IAAI,8DACX;GACF;GACA,IAAI,CAAC,WAAW,IAAI,MAAkC,GAEpD,QAAQ,KAAK,QAAQ,KAAK,MAAM;EAEpC;EACA,MAAM,uBAA6B;GACjC,KAAK,MAAM,UAAU,SACnB,QAAQ,IAAI,QAAQ,QAAQ;EAEhC;EACA,KAAK,MAAM,UAAU,SACnB,QAAQ,KAAK,QAAQ,QAAQ;EAM/B,QAAS,QAAyD,YAAY,QAAQ,MAAM;EAC5F,OAAO,YAAY;GACjB,eAAe;GACf,MAAM,QAAQ,KAAK;EACrB;CACF;AACF;;;;;;;AAQA,SAAgB,gBAAkC;CAChD,MAAM,SAAU,OAAuD,UAAU;CACjF,IAAI,CAAC,QACH,MAAM,IAAI,MACR,oLAGF;CAEF,OAAO,eAAe,MAAM;AAC9B"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zitadel/testing",
3
- "version": "0.5.0",
3
+ "version": "0.7.0",
4
4
  "description": "Test-kit for seeded ephemeral local Zitadel instances",
5
5
  "homepage": "https://github.com/zitadel/nextgen/tree/main/packages/testing#readme",
6
6
  "bugs": {
@@ -34,26 +34,36 @@
34
34
  "require": "./dist/playwright.cjs",
35
35
  "default": "./dist/playwright.mjs"
36
36
  },
37
+ "./vitest": {
38
+ "@zitadel/source": "./src/vitest.ts",
39
+ "types": "./dist/vitest.d.mts",
40
+ "import": "./dist/vitest.mjs",
41
+ "default": "./dist/vitest.mjs"
42
+ },
37
43
  "./package.json": "./package.json"
38
44
  },
39
45
  "dependencies": {
40
- "@zitadel/api": "0.5.0",
41
- "@zitadel/cli": "0.5.0",
42
- "@zitadel/config": "0.5.0"
46
+ "@zitadel/api": "0.7.0",
47
+ "@zitadel/cli": "0.7.0",
48
+ "@zitadel/config": "0.7.0"
43
49
  },
44
50
  "peerDependencies": {
45
- "@playwright/test": ">=1.60"
51
+ "@playwright/test": ">=1.60",
52
+ "vitest": ">=4.0"
46
53
  },
47
54
  "peerDependenciesMeta": {
48
55
  "@playwright/test": {
49
56
  "optional": true
57
+ },
58
+ "vitest": {
59
+ "optional": true
50
60
  }
51
61
  },
52
62
  "devDependencies": {
53
- "@playwright/test": "^1.64.1",
54
- "@types/node": "^24.19.1",
63
+ "@playwright/test": "^1.65.0",
64
+ "@types/node": "^24.19.2",
55
65
  "@zitadel/vitest-config": "0.0.0",
56
- "msw": "^2.14.6",
66
+ "msw": "^2.15.0",
57
67
  "tsdown": "^0.23.0",
58
68
  "tslib": "^2.8.1",
59
69
  "typescript": "^6.0.3",
@@ -63,10 +73,8 @@
63
73
  "build": "tsdown && attw --pack . --profile=esm-only --ignore-rules=false-esm",
64
74
  "typecheck": "tsc --noEmit -p tsconfig.lib.json && tsc --noEmit -p tsconfig.spec.json",
65
75
  "test": "vitest run",
66
- "test:all": "pnpm run test",
67
76
  "test:integration": "ZITADEL_SERVER_BINARY=${ZITADEL_SERVER_BINARY-$PWD/../../dist/server/nextgen} NEXTGEN_SERVER_CONSOLE_ENABLED=${NEXTGEN_SERVER_CONSOLE_ENABLED-false} vitest run --config vitest.integration.config.ts",
68
77
  "install-browsers": "playwright install chromium",
69
- "lint": "biome check .",
70
- "build-release": "node ../../scripts/release-clean.mjs local-dist && pnpm run build"
78
+ "lint": "biome check ."
71
79
  }
72
80
  }
@@ -1 +0,0 @@
1
- {"version":3,"file":"handshake-CwlxMjW0.mjs","names":["sleep"],"sources":["../src/app-env.ts","../src/handshake.ts"],"sourcesContent":["import type { InstanceHandle } from \"./types\";\n\n/**\n * Handle fields a template may reference: the flat string facts. Structured\n * fields (e.g. `platform`) are not env-var material — consumers read those\n * from the handle directly.\n */\ntype StringHandleField = {\n [K in keyof InstanceHandle]-?: InstanceHandle[K] extends string | undefined ? K : never;\n}[keyof InstanceHandle];\n\n/**\n * Declarative mapping from an app's env var names to InstanceHandle fields.\n * A template (not a function) so it can cross process boundaries: the\n * Playwright config serializes it into the app-runner's environment, where it\n * is applied to the handle read from the handshake file.\n */\nexport type AppEnvTemplate = Record<string, StringHandleField>;\n\n/**\n * The env shape `@zitadel/sdk-next` apps read, as `zitadel setup` writes it.\n * The server reads `ZITADEL_PROJECT_ID` to hold sessions to the project, the\n * widgets the public copy. Other frameworks pass their own template — the\n * console maps the same handle fields to `VITE_*`/`CONSOLE_*` names, for\n * example.\n */\nexport const nextAppEnv: AppEnvTemplate = {\n ZITADEL_URL: \"baseUrl\",\n ZITADEL_PROJECT_ID: \"projectId\",\n NEXT_PUBLIC_ZITADEL_PROJECT_ID: \"projectId\",\n ZITADEL_PROJECT_SECRET: \"projectSecret\",\n};\n\nexport function applyAppEnvTemplate(\n template: AppEnvTemplate,\n handle: InstanceHandle,\n): Record<string, string> {\n const env: Record<string, string> = {};\n for (const [name, field] of Object.entries(template)) {\n const value = handle[field];\n if (typeof value !== \"string\" || value.length === 0) {\n // Fail instead of silently dropping the var: an app booted without one\n // of its env vars produces a much harder-to-read failure downstream.\n throw new Error(\n `app env template maps \"${name}\" to handle field \"${field}\", which the instance handle does not carry`,\n );\n }\n env[name] = value;\n }\n return env;\n}\n","import { readFileSync } from \"node:fs\";\nimport { mkdir, readFile, writeFile } from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\nimport { setTimeout as sleep } from \"node:timers/promises\";\n\nimport type { InstanceHandle, PlatformCredentials } from \"./types\";\n\n/**\n * The handshake file carries an InstanceHandle across process boundaries:\n * written by the script that boots + bootstraps the instance, read by\n * Playwright workers (fixtures) and the app dev-server wrapper.\n */\nexport async function writeHandshake(path: string, handle: InstanceHandle): Promise<void> {\n await mkdir(dirname(path), { recursive: true });\n await writeFile(path, `${JSON.stringify(handle, null, 2)}\\n`, { mode: 0o600 });\n}\n\nexport function readHandshakeSync(path: string): InstanceHandle {\n const contents = readFileSync(path, \"utf8\");\n let value: unknown;\n try {\n value = JSON.parse(contents);\n } catch (error) {\n throw new Error(`handshake file ${path} contains invalid JSON: ${(error as Error).message}`, {\n cause: error,\n });\n }\n return validateHandle(value, path);\n}\n\nexport async function waitForHandshake(path: string, timeoutMs = 60_000): Promise<InstanceHandle> {\n const deadline = Date.now() + timeoutMs;\n for (;;) {\n try {\n return validateHandle(JSON.parse(await readFile(path, \"utf8\")), path);\n } catch (error) {\n if (Date.now() >= deadline) {\n throw new Error(\n `handshake file not readable within ${timeoutMs}ms: ${path} (${(error as Error).message})`,\n { cause: error },\n );\n }\n await sleep(250);\n }\n }\n}\n\nfunction validateHandle(value: unknown, source: string): InstanceHandle {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new Error(`handshake file ${source} is not an object`);\n }\n const handle = value as Partial<InstanceHandle>;\n for (const field of [\"baseUrl\", \"projectId\", \"projectSecret\", \"schemaId\"] as const) {\n if (typeof handle[field] !== \"string\" || handle[field].length === 0) {\n throw new Error(`handshake file ${source} is missing \"${field}\"`);\n }\n }\n if (!URL.canParse(handle.baseUrl as string)) {\n throw new Error(`handshake file ${source} has a malformed \"baseUrl\": ${handle.baseUrl}`);\n }\n if (handle.platform !== undefined) {\n validatePlatform(handle.platform, source);\n }\n return handle as InstanceHandle;\n}\n\n/**\n * The handshake is the cross-process contract, so a malformed platform block\n * must fail here with the field name, not later with a less actionable error.\n */\nfunction validatePlatform(value: unknown, source: string): void {\n const fail = (detail: string): never => {\n throw new Error(`handshake file ${source} has a malformed \"platform\" block: ${detail}`);\n };\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n fail(\"not an object\");\n }\n const platform = value as Partial<PlatformCredentials>;\n for (const field of [\"projectId\", \"publishableKey\"] as const) {\n if (typeof platform[field] !== \"string\" || platform[field].length === 0) {\n fail(`\"${field}\" is required`);\n }\n }\n // Unknown extra fields pass through on purpose: future platform\n // credentials join additively, and an older reader must not reject a\n // newer producer's handle.\n}\n"],"mappings":";;;;;;;;;;;;AA0BA,MAAa,aAA6B;CACxC,aAAa;CACb,oBAAoB;CACpB,gCAAgC;CAChC,wBAAwB;AAC1B;AAEA,SAAgB,oBACd,UACA,QACwB;CACxB,MAAM,MAA8B,CAAC;CACrC,KAAK,MAAM,CAAC,MAAM,UAAU,OAAO,QAAQ,QAAQ,GAAG;EACpD,MAAM,QA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AAO,MAAM,CAAC,WAAW,GAChE,MAAM,IAAI,MAAM,kBAAkB,OAAO,eAAe,MAAM,EAAE;CAGpE,IAAI,CAAC,IAAI,SAAS,OAAO,OAAiB,GACxC,MAAM,IAAI,MAAM,kBAAkB,OAAO,8BAA8B,OAAO,SAAS;CAEzF,IAAI,OAAO,aAAa,KAAA,GACtB,iBAAiB,OAAO,UAAU,MAAM;CAE1C,OAAO;AACT;;;;;AAMA,SAAS,iBAAiB,OAAgB,QAAsB;CAC9D,MAAM,QAAQ,WAA0B;EACtC,MAAM,IAAI,MAAM,kBAAkB,OAAO,qCAAqC,QAAQ;CACxF;CACA,IAAI,OAAO,UAAU,YAAY,UAAU,QAAQ,MAAM,QAAQ,KAAK,GACpE,KAAK,eAAe;CAEtB,MAAM,WAAW;CACjB,KAAK,MAAM,SAAS,CAAC,aAAa,gBAAgB,GAChD,IAAI,OAAO,SAAS,WAAW,YAAY,SAAS,MAAM,CAAC,WAAW,GACpE,KAAK,IAAI,MAAM,cAAc;AAMnC"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"handshake-D6MXSUcd.cjs","names":["mkdir","dirname","writeFile","readFileSync","readFile","sleep"],"sources":["../src/app-env.ts","../src/handshake.ts"],"sourcesContent":["import type { InstanceHandle } from \"./types\";\n\n/**\n * Handle fields a template may reference: the flat string facts. Structured\n * fields (e.g. `platform`) are not env-var material — consumers read those\n * from the handle directly.\n */\ntype StringHandleField = {\n [K in keyof InstanceHandle]-?: InstanceHandle[K] extends string | undefined ? K : never;\n}[keyof InstanceHandle];\n\n/**\n * Declarative mapping from an app's env var names to InstanceHandle fields.\n * A template (not a function) so it can cross process boundaries: the\n * Playwright config serializes it into the app-runner's environment, where it\n * is applied to the handle read from the handshake file.\n */\nexport type AppEnvTemplate = Record<string, StringHandleField>;\n\n/**\n * The env shape `@zitadel/sdk-next` apps read, as `zitadel setup` writes it.\n * The server reads `ZITADEL_PROJECT_ID` to hold sessions to the project, the\n * widgets the public copy. Other frameworks pass their own template — the\n * console maps the same handle fields to `VITE_*`/`CONSOLE_*` names, for\n * example.\n */\nexport const nextAppEnv: AppEnvTemplate = {\n ZITADEL_URL: \"baseUrl\",\n ZITADEL_PROJECT_ID: \"projectId\",\n NEXT_PUBLIC_ZITADEL_PROJECT_ID: \"projectId\",\n ZITADEL_PROJECT_SECRET: \"projectSecret\",\n};\n\nexport function applyAppEnvTemplate(\n template: AppEnvTemplate,\n handle: InstanceHandle,\n): Record<string, string> {\n const env: Record<string, string> = {};\n for (const [name, field] of Object.entries(template)) {\n const value = handle[field];\n if (typeof value !== \"string\" || value.length === 0) {\n // Fail instead of silently dropping the var: an app booted without one\n // of its env vars produces a much harder-to-read failure downstream.\n throw new Error(\n `app env template maps \"${name}\" to handle field \"${field}\", which the instance handle does not carry`,\n );\n }\n env[name] = value;\n }\n return env;\n}\n","import { readFileSync } from \"node:fs\";\nimport { mkdir, readFile, writeFile } from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\nimport { setTimeout as sleep } from \"node:timers/promises\";\n\nimport type { InstanceHandle, PlatformCredentials } from \"./types\";\n\n/**\n * The handshake file carries an InstanceHandle across process boundaries:\n * written by the script that boots + bootstraps the instance, read by\n * Playwright workers (fixtures) and the app dev-server wrapper.\n */\nexport async function writeHandshake(path: string, handle: InstanceHandle): Promise<void> {\n await mkdir(dirname(path), { recursive: true });\n await writeFile(path, `${JSON.stringify(handle, null, 2)}\\n`, { mode: 0o600 });\n}\n\nexport function readHandshakeSync(path: string): InstanceHandle {\n const contents = readFileSync(path, \"utf8\");\n let value: unknown;\n try {\n value = JSON.parse(contents);\n } catch (error) {\n throw new Error(`handshake file ${path} contains invalid JSON: ${(error as Error).message}`, {\n cause: error,\n });\n }\n return validateHandle(value, path);\n}\n\nexport async function waitForHandshake(path: string, timeoutMs = 60_000): Promise<InstanceHandle> {\n const deadline = Date.now() + timeoutMs;\n for (;;) {\n try {\n return validateHandle(JSON.parse(await readFile(path, \"utf8\")), path);\n } catch (error) {\n if (Date.now() >= deadline) {\n throw new Error(\n `handshake file not readable within ${timeoutMs}ms: ${path} (${(error as Error).message})`,\n { cause: error },\n );\n }\n await sleep(250);\n }\n }\n}\n\nfunction validateHandle(value: unknown, source: string): InstanceHandle {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new Error(`handshake file ${source} is not an object`);\n }\n const handle = value as Partial<InstanceHandle>;\n for (const field of [\"baseUrl\", \"projectId\", \"projectSecret\", \"schemaId\"] as const) {\n if (typeof handle[field] !== \"string\" || handle[field].length === 0) {\n throw new Error(`handshake file ${source} is missing \"${field}\"`);\n }\n }\n if (!URL.canParse(handle.baseUrl as string)) {\n throw new Error(`handshake file ${source} has a malformed \"baseUrl\": ${handle.baseUrl}`);\n }\n if (handle.platform !== undefined) {\n validatePlatform(handle.platform, source);\n }\n return handle as InstanceHandle;\n}\n\n/**\n * The handshake is the cross-process contract, so a malformed platform block\n * must fail here with the field name, not later with a less actionable error.\n */\nfunction validatePlatform(value: unknown, source: string): void {\n const fail = (detail: string): never => {\n throw new Error(`handshake file ${source} has a malformed \"platform\" block: ${detail}`);\n };\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n fail(\"not an object\");\n }\n const platform = value as Partial<PlatformCredentials>;\n for (const field of [\"projectId\", \"publishableKey\"] as const) {\n if (typeof platform[field] !== \"string\" || platform[field].length === 0) {\n fail(`\"${field}\" is required`);\n }\n }\n // Unknown extra fields pass through on purpose: future platform\n // credentials join additively, and an older reader must not reject a\n // newer producer's handle.\n}\n"],"mappings":";;;;;;;;;;;;AA0BA,MAAa,aAA6B;CACxC,aAAa;CACb,oBAAoB;CACpB,gCAAgC;CAChC,wBAAwB;AAC1B;AAEA,SAAgB,oBACd,UACA,QACwB;CACxB,MAAM,MAA8B,CAAC;CACrC,KAAK,MAAM,CAAC,MAAM,UAAU,OAAO,QAAQ,QAAQ,GAAG;EACpD,MAAM,QAAQ,OAAO;EACrB,IAAI,OAAO,UAAU,YAAY,MAAM,WAAW,GAGhD,MA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AS;EAAC;EAAW;EAAa;EAAiB;CAAU,GACtE,IAAI,OAAO,OAAO,WAAW,YAAY,OAAO,MAAM,CAAC,WAAW,GAChE,MAAM,IAAI,MAAM,kBAAkB,OAAO,eAAe,MAAM,EAAE;CAGpE,IAAI,CAAC,IAAI,SAAS,OAAO,OAAiB,GACxC,MAAM,IAAI,MAAM,kBAAkB,OAAO,8BAA8B,OAAO,SAAS;CAEzF,IAAI,OAAO,aAAa,KAAA,GACtB,iBAAiB,OAAO,UAAU,MAAM;CAE1C,OAAO;AACT;;;;;AAMA,SAAS,iBAAiB,OAAgB,QAAsB;CAC9D,MAAM,QAAQ,WAA0B;EACtC,MAAM,IAAI,MAAM,kBAAkB,OAAO,qCAAqC,QAAQ;CACxF;CACA,IAAI,OAAO,UAAU,YAAY,UAAU,QAAQ,MAAM,QAAQ,KAAK,GACpE,KAAK,eAAe;CAEtB,MAAM,WAAW;CACjB,KAAK,MAAM,SAAS,CAAC,aAAa,gBAAgB,GAChD,IAAI,OAAO,SAAS,WAAW,YAAY,SAAS,MAAM,CAAC,WAAW,GACpE,KAAK,IAAI,MAAM,cAAc;AAMnC"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"src-Ck7eLkah.mjs","names":[],"sources":["../src/bootstrap.ts","../src/cli.ts","../src/envelope.ts","../src/ports.ts","../src/lifecycle.ts","../src/seed.ts","../src/session.ts","../src/index.ts"],"sourcesContent":["import { createZitadelClient } from \"@zitadel/api/client\";\nimport {\n DEFAULT_FLOW_SCHEMA_URI,\n getDefaultHumanUserSchemaBody,\n getDefaultLoginFlow,\n type SetupPreset,\n type SetupUseCase,\n} from \"@zitadel/config/defaults\";\n\nexport interface BootstrapProjectOptions {\n baseUrl: string;\n projectName?: string;\n /**\n * Origins of the apps that will proxy to this instance. The backend's\n * origin check rejects forwarded requests from unregistered origins.\n */\n appOrigins?: string[];\n preset?: SetupPreset;\n useCase?: SetupUseCase;\n}\n\nexport interface BootstrappedProject {\n projectId: string;\n projectSecret: string;\n /** The browser-plane credential the server issues with every project. */\n previewSecret: string;\n schemaId: string;\n flowId: string;\n}\n\nconst DEFAULT_PROJECT_NAME = \"zitadel-testing\";\n\n/**\n * Server-side half of `zitadel setup`, without any file scaffolding:\n * `POST /projects` is unauthenticated and mints the projectSecret used as the\n * bearer for everything else; the schema is uploaded without `$id` so the\n * server assigns an opaque id, which the flow must then reference.\n */\n/**\n * A deployment needs a primary origin. A loopback origin is always admitted, so\n * listing this one opens nothing up.\n */\nconst FALLBACK_APP_ORIGIN = \"http://localhost:3000\";\n\nexport async function bootstrapProject(\n options: BootstrapProjectOptions,\n): Promise<BootstrappedProject> {\n const { baseUrl } = options;\n const unauthenticated = createZitadelClient({ baseUrl });\n const project = await unauthenticated.createProject({\n name: options.projectName ?? DEFAULT_PROJECT_NAME,\n origins: (options.appOrigins?.length ? options.appOrigins : [FALLBACK_APP_ORIGIN]).map(\n (pattern) => ({\n pattern,\n kind: \"primary\" as const,\n }),\n ),\n seed_defaults: false,\n });\n const client = createZitadelClient({ baseUrl, token: project.project_secret });\n\n const schemaBody = getDefaultHumanUserSchemaBody({\n preset: options.preset,\n useCase: options.useCase,\n });\n const schema = await client.createSchema(schemaBody, { project_id: project.id });\n\n const flowBody = getDefaultLoginFlow({\n preset: options.preset,\n useCase: options.useCase,\n });\n const flow = await client.createFlowDefinition({\n project_id: project.id,\n schema_uri: DEFAULT_FLOW_SCHEMA_URI,\n flow_definition: flowBody,\n });\n\n const release = await client.createRelease(\n {\n pointers: [\n { kind: \"schema\", revision_id: schema.id },\n { kind: \"flow_definition\", revision_id: flow.id },\n ],\n },\n { project_id: project.id },\n );\n await client.createDeployment(\n { release_id: release.id, targets: \"primary\" },\n { project_id: project.id },\n );\n\n return {\n projectId: project.id,\n projectSecret: project.project_secret,\n previewSecret: project.preview_secret,\n schemaId: schema.id,\n flowId: flow.id,\n };\n}\n","import { spawn } from \"node:child_process\";\nimport { createRequire } from \"node:module\";\nimport { dirname, join } from \"node:path\";\n\nexport interface RunCliOptions {\n args: string[];\n env?: NodeJS.ProcessEnv;\n /** Test seam / escape hatch: alternative CLI entry script. */\n bin?: string;\n timeoutMs?: number;\n}\n\nexport interface RunCliResult {\n exitCode: number;\n stdout: string;\n stderr: string;\n}\n\nconst DEFAULT_TIMEOUT_MS = 120_000;\n\nexport function resolveCliBin(): string {\n const require = createRequire(import.meta.url);\n const pkgPath = require.resolve(\"@zitadel/cli/package.json\");\n const pkg = require(pkgPath) as { bin?: Record<string, string> };\n const rel = pkg.bin?.zitadel;\n if (!rel) {\n throw new Error(\"@zitadel/cli does not declare a `zitadel` bin entry\");\n }\n return join(dirname(pkgPath), rel);\n}\n\nexport function runCli(options: RunCliOptions): Promise<RunCliResult> {\n const bin = options.bin ?? resolveCliBin();\n const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n return new Promise((resolve, reject) => {\n const child = spawn(process.execPath, [bin, ...options.args], {\n env: { ...process.env, ...options.env },\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n });\n let stdout = \"\";\n let stderr = \"\";\n child.stdout.setEncoding(\"utf8\");\n child.stdout.on(\"data\", (chunk: string) => {\n stdout += chunk;\n });\n child.stderr.setEncoding(\"utf8\");\n child.stderr.on(\"data\", (chunk: string) => {\n stderr += chunk;\n });\n const timer = setTimeout(() => {\n child.kill(\"SIGKILL\");\n reject(\n new Error(\n `zitadel ${options.args[0] ?? \"\"} timed out after ${timeoutMs}ms\\n${tail(stderr)}`,\n ),\n );\n }, timeoutMs);\n timer.unref();\n child.on(\"error\", (error) => {\n clearTimeout(timer);\n reject(error);\n });\n child.on(\"close\", (code) => {\n clearTimeout(timer);\n resolve({ exitCode: code ?? -1, stdout, stderr });\n });\n });\n}\n\nexport function tail(text: string, lines = 20): string {\n return text.split(\"\\n\").slice(-lines).join(\"\\n\").trim();\n}\n","export interface CliEnvelope<TData> {\n cli_version?: string;\n command?: string;\n source?: string;\n status: string;\n data: TData;\n warnings?: string[];\n /** Error envelopes (`status: \"error\"`) carry remediation guidance. */\n code?: string;\n message?: string;\n hint?: string;\n next_commands?: string[];\n}\n\n/**\n * Render an error envelope's remediation fields for humans — the CLI's\n * `hint`/`next_commands` are the actionable part of a failure (e.g. \"Reinstall\n * @zitadel/cli so npm can install @zitadel/server\"), so surface them instead\n * of a raw stdout dump. Returns undefined when the envelope has no message.\n */\nexport function describeEnvelopeError(envelope: CliEnvelope<unknown>): string | undefined {\n if (typeof envelope.message !== \"string\" || envelope.message.length === 0) {\n return undefined;\n }\n const lines = [envelope.code ? `${envelope.code}: ${envelope.message}` : envelope.message];\n if (envelope.hint) {\n lines.push(`hint: ${envelope.hint}`);\n }\n if (envelope.next_commands && envelope.next_commands.length > 0) {\n lines.push(`next: ${envelope.next_commands.join(\" | \")}`);\n }\n return lines.join(\"\\n\");\n}\n\nexport interface StartEnvelopeData {\n runtime: {\n backend: string;\n pid: number;\n port: number;\n data_dir: string;\n log_path: string;\n };\n urls: {\n api: string;\n console: string;\n };\n}\n\nexport function parseCliEnvelope<TData>(stdout: string, context: string): CliEnvelope<TData> {\n const start = stdout.indexOf(\"{\");\n const end = stdout.lastIndexOf(\"}\");\n if (start === -1 || end <= start) {\n throw new Error(\n `${context}: expected a JSON envelope on stdout, got:\\n${stdout.trim() || \"(empty)\"}`,\n );\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(stdout.slice(start, end + 1));\n } catch (error) {\n throw new Error(\n `${context}: failed to parse JSON envelope: ${(error as Error).message}\\n${stdout.trim()}`,\n { cause: error },\n );\n }\n if (\n typeof parsed !== \"object\" ||\n parsed === null ||\n typeof (parsed as { status?: unknown }).status !== \"string\"\n ) {\n throw new Error(`${context}: stdout JSON is not a CLI envelope:\\n${stdout.trim()}`);\n }\n return parsed as CliEnvelope<TData>;\n}\n","import { createServer } from \"node:net\";\n\n/**\n * Ask the OS for a free TCP port. The port is released before returning, so a\n * racing process could grab it; the CLI's own preflight surfaces that as\n * E_PORT_IN_USE, which is loud rather than corrupting.\n */\nexport function getFreePort(): Promise<number> {\n return new Promise((resolve, reject) => {\n const server = createServer();\n server.unref();\n server.on(\"error\", reject);\n server.listen(0, \"127.0.0.1\", () => {\n const address = server.address();\n if (address === null || typeof address === \"string\") {\n server.close();\n reject(new Error(\"could not determine a free port\"));\n return;\n }\n const { port } = address;\n server.close((err) => {\n if (err) {\n reject(err);\n return;\n }\n resolve(port);\n });\n });\n });\n}\n","import { mkdtemp, rm } from \"node:fs/promises\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\n\nimport { runCli, tail, type RunCliResult } from \"./cli\";\nimport {\n describeEnvelopeError,\n parseCliEnvelope,\n type CliEnvelope,\n type StartEnvelopeData,\n} from \"./envelope\";\nimport { getFreePort } from \"./ports\";\nimport type { LocalZitadelRuntime } from \"./types\";\n\nexport interface BootServerOptions {\n /** TCP port for the instance; defaults to an OS-assigned free port. */\n port?: number;\n /**\n * State directory. Defaults to a fresh temp dir that is removed on stop;\n * a caller-provided dir is never removed.\n */\n dir?: string;\n /** Forwarded as ZITADEL_SERVER_BINARY (in-repo runs use dist/server/nextgen). */\n serverBinary?: string;\n /** Keep the owned temp dir after stop (debugging). */\n keep?: boolean;\n /** Test seam: alternative CLI entry script. */\n cliBin?: string;\n timeoutMs?: number;\n}\n\nexport interface BootedServer {\n baseUrl: string;\n runtime: LocalZitadelRuntime;\n stop(): Promise<void>;\n}\n\n/**\n * Boot an ephemeral local server by shelling out to `zitadel start` and parse\n * its JSON envelope. The CLI owns the subtle parts (port preflight, health\n * wait, process-group stop), so this module stays a thin adapter; swapping it\n * for direct library calls later must not change the shape returned here.\n */\nexport async function bootLocalServer(options: BootServerOptions = {}): Promise<BootedServer> {\n const ownsDir = options.dir === undefined;\n const dir = options.dir ?? (await mkdtemp(join(tmpdir(), \"zitadel-testing-\")));\n const port = options.port ?? (await getFreePort());\n const env: NodeJS.ProcessEnv = {};\n if (options.serverBinary) {\n env.ZITADEL_SERVER_BINARY = options.serverBinary;\n }\n\n const result = await runCli({\n args: [\"start\", \"--port\", String(port), \"--non-interactive\", \"--json\", \"-c\", dir],\n bin: options.cliBin,\n env,\n timeoutMs: options.timeoutMs,\n });\n if (result.exitCode !== 0) {\n // Keep the dir on failure: server.log inside it is the diagnostic.\n throw new Error(\n `zitadel start exited with code ${result.exitCode}.\\n` +\n `${failureDetail(result)}\\n` +\n `state dir kept for inspection: ${dir}`,\n );\n }\n const stopViaCli = async (): Promise<void> => {\n const stopResult = await runCli({\n args: [\"stop\", \"--non-interactive\", \"--json\", \"-c\", dir],\n bin: options.cliBin,\n env,\n timeoutMs: options.timeoutMs,\n });\n if (stopResult.exitCode !== 0) {\n throw new Error(\n `zitadel stop exited with code ${stopResult.exitCode}.\\n` +\n `${failureDetail(stopResult)}\\n` +\n `state dir kept for inspection: ${dir}`,\n );\n }\n };\n\n let envelope: CliEnvelope<StartEnvelopeData>;\n try {\n envelope = parseCliEnvelope<StartEnvelopeData>(result.stdout, \"zitadel start\");\n if (envelope.status !== \"ok\") {\n throw new Error(\n `zitadel start reported status \"${envelope.status}\":\\n` +\n `${describeEnvelopeError(envelope) ?? tail(result.stdout)}`,\n );\n }\n } catch (error) {\n const startError = new Error(\n `zitadel start produced unusable output.\\n` +\n `reason: ${error instanceof Error ? error.message : String(error)}\\n` +\n `stdout: ${tail(result.stdout) || \"(empty)\"}\\n` +\n `stderr: ${tail(result.stderr) || \"(empty)\"}\\n` +\n `state dir kept for inspection: ${dir}`,\n { cause: error },\n );\n // start exited 0, so a server may well be running despite the unusable\n // output — stop it instead of orphaning it.\n try {\n await stopViaCli();\n } catch (stopError) {\n // Both errors are preserved in AggregateError.errors, which the rule\n // below cannot model.\n throw new AggregateError(\n [startError, stopError],\n `${startError.message}\\nStopping the possibly-running instance also failed: ${\n stopError instanceof Error ? stopError.message : String(stopError)\n }`,\n );\n }\n throw startError;\n }\n\n const { runtime, urls } = envelope.data;\n const runStop = async (): Promise<void> => {\n await stopViaCli();\n if (ownsDir && !options.keep) {\n await rm(dir, { recursive: true, force: true });\n }\n };\n // Memoize the in-flight stop so concurrent callers await the same cleanup,\n // and reset on failure so a failed stop can be retried instead of silently\n // leaving the server behind.\n let stopPromise: Promise<void> | undefined;\n const stop = (): Promise<void> => {\n stopPromise ??= runStop().catch((error: unknown) => {\n stopPromise = undefined;\n throw error;\n });\n return stopPromise;\n };\n\n return {\n baseUrl: urls.api,\n runtime: {\n port: runtime.port,\n pid: runtime.pid,\n dir,\n logPath: runtime.log_path,\n },\n stop,\n };\n}\n\n/**\n * A failed CLI run usually still prints an error envelope; its\n * message/hint/next_commands beat raw output tails (e.g. a fresh install\n * missing @zitadel/server gets \"Reinstall @zitadel/cli\" instead of a stack).\n */\nfunction failureDetail(result: RunCliResult): string {\n try {\n const described = describeEnvelopeError(parseCliEnvelope<unknown>(result.stdout, \"zitadel\"));\n if (described) {\n return described;\n }\n } catch {\n // stdout carried no envelope; fall back to the raw tails.\n }\n return `stdout: ${tail(result.stdout) || \"(empty)\"}\\nstderr: ${tail(result.stderr) || \"(empty)\"}`;\n}\n","import { randomUUID } from \"node:crypto\";\n\nimport type { ZitadelClient } from \"@zitadel/api/client\";\n\nimport type { Identity, SeededUser, SeedUserInput, SeedUsersTemplate } from \"./types\";\n\nexport interface SeedContext {\n projectId: string;\n schemaId: string;\n}\n\n/**\n * A unique unused email + password. Nothing is created on the instance —\n * this is the input for registration-flow specs, which must prove the flow\n * creates the user. It needs no instance either, so both entry points export\n * it for specs that run without `withZitadel()`; `seed.identity()` and\n * `zitadel.identity()` call this function.\n */\nexport function identity(): Identity {\n return {\n email: `e2e-${randomUUID().slice(0, 8)}@example.com`,\n password: `Pw!${randomUUID()}`,\n };\n}\n\n/**\n * Create a user that can immediately complete the password login flow:\n * `POST /users` (the body carries `schema: <schema id>` and the schema-defined\n * content under `attributes`) followed by `PUT /users/{id}/password`.\n *\n * Defaults mint a unique email per call (email is x-unique per project), which\n * is what makes per-test seeding parallel-safe on a shared instance.\n */\nexport async function seedUser(\n client: ZitadelClient,\n context: SeedContext,\n input: SeedUserInput = {},\n): Promise<SeededUser> {\n const fresh = identity();\n const email = input.email ?? fresh.email;\n const password = input.password ?? fresh.password;\n // `email` wins over the templated attributes: the returned SeededUser must\n // never disagree with what was actually created, since a silently overridden\n // email would yield credentials that cannot log in.\n const { id } = await client.createUser(\n {\n schema: context.schemaId,\n attributes: { ...input.attributes, email },\n },\n { project_id: context.projectId },\n );\n await client.setUserPassword(id, { password });\n return { id, email, password };\n}\n\n/**\n * Seed `count` users sequentially. The template makes fixture data\n * deterministic per index (stable emails/names keep screenshot diffs about\n * code, not reshuffled data — the `console:dev-real` pattern); untemplated\n * fields fall back to the unique defaults. Name-like attributes need a\n * schema that declares them (`useCase: \"consumer\"` or wider).\n */\nexport async function seedUsers(\n client: ZitadelClient,\n context: SeedContext,\n count: number,\n template: SeedUsersTemplate = {},\n): Promise<SeededUser[]> {\n const users: SeededUser[] = [];\n for (let index = 0; index < count; index += 1) {\n users.push(\n await seedUser(client, context, {\n email: template.email?.(index),\n password: template.password?.(index),\n attributes: template.attributes?.(index),\n }),\n );\n }\n return users;\n}\n","import type { ZitadelClient } from \"@zitadel/api/client\";\nimport type { CreateFlow201, CreateFlow201StepFieldsItem } from \"@zitadel/api/generated/model\";\n\nimport { apiBaseUrl } from \"@zitadel/api/runtime/base-url\";\n\nimport type { SeedContext } from \"./seed\";\nimport type { InstanceHandle, MintedSession, SeededUser } from \"./types\";\n\n/**\n * The server's session cookie under its canonical name\n * (internal/api/session.go, ADR 083): the name a direct call to the server\n * sends, over any transport. A browser holds it under\n * {@link browserSessionCookieName}.\n */\nexport const SESSION_COOKIE_NAME = \"__Host-zitadel_session\";\n\n/**\n * Whether a session cookie a browser holds for `url` is `Secure`, and so\n * carries the `__Host-` prefix: always, but over plain http to a loopback host,\n * where the server leaves `Secure` out for Safari. Without a URL, a local dev\n * server's answer: no.\n */\nexport function secureSessionCookie(url?: string | URL): boolean {\n if (url === undefined) {\n return false;\n }\n let parsed: URL;\n try {\n parsed = new URL(url);\n } catch {\n return true;\n }\n const host = parsed.hostname.toLowerCase();\n return (\n parsed.protocol !== \"http:\" ||\n !(host === \"localhost\" || host === \"[::1]\" || /^127(?:\\.\\d{1,3}){3}$/.test(host))\n );\n}\n\n/**\n * The server's session cookie as a browser at `url` holds it: the canonical\n * `__Host-zitadel_session`, or `zitadel_session` over plain http to a loopback\n * host (ADR 083). Without a URL, the loopback name. An app behind a proxy that\n * passes the server's cookie through, such as an SPA's in production, keeps\n * its session under this name.\n */\nexport function browserSessionCookieName(url?: string | URL): string {\n return secureSessionCookie(url) ? SESSION_COOKIE_NAME : \"zitadel_session\";\n}\n\n/**\n * The cookie an app at `url` keeps its session in on its own origin behind a\n * server SDK (Next.js, Nuxt, SvelteKit, SolidStart, TanStack Start, Qwik\n * Router) or the dev proxy `zitadel setup` writes for an SPA: the browser's\n * name of the server's cookie with the project id appended,\n * `zitadel_session_<projectId>` over plain http to a loopback host and\n * `__Host-zitadel_session_<projectId>` otherwise. Without a URL, the loopback\n * name. The proxy renames the server's cookie, so the apps and the Console on\n * one host keep a session each (ADR 073, ADR 083).\n *\n * Mirrors `sessionCookieName` in `@zitadel/sdk-core`, including the\n * percent-encoding of every byte outside `[A-Za-z0-9_-]`.\n */\nexport function sessionCookieName(projectId: string, url?: string | URL): string {\n let name = `${browserSessionCookieName(url)}_`;\n for (const byte of new TextEncoder().encode(projectId)) {\n const char = String.fromCharCode(byte);\n name += /[A-Za-z0-9_-]/.test(char)\n ? char\n : `%${byte.toString(16).toUpperCase().padStart(2, \"0\")}`;\n }\n return name;\n}\n\nconst MAX_FLOW_STEPS = 6;\n\nexport interface MintSessionOptions {\n /** Forwarded to `POST /flow`; the project's default flow when omitted. */\n flowDefinitionName?: string;\n /** Origin header for flow calls (the project's origin check enforces it). */\n origin?: string;\n}\n\n/**\n * Drive the real login flow headlessly for a seeded password user and\n * exchange the terminal handoff for a session: exactly what `<zitadel-login>`\n * does, minus the rendering. Supports flows whose steps only ask for the\n * user's email and password (the shipped `password-first` presets); any step\n * demanding more — a challenge, an unknown field — fails loudly by design.\n *\n * Flow calls use raw fetch instead of the typed client because the flow is\n * stateless through the sealed `_zflow` cookie (internal/api/flow.go): every\n * response re-seals the flow state into Set-Cookie, and submits are rejected\n * without it. Browsers round-trip it implicitly; here a one-cookie jar does.\n */\nexport async function mintSession(\n client: ZitadelClient,\n handle: Pick<InstanceHandle, \"baseUrl\" | \"projectSecret\">,\n context: SeedContext,\n user: SeededUser,\n options: MintSessionOptions = {},\n): Promise<MintedSession> {\n const values: Record<string, string> = { email: user.email, password: user.password };\n const jar = new FlowCookieJar();\n const origin = options.origin;\n\n let response = await flowFetch(handle, jar, origin, \"/flow\", {\n project_id: context.projectId,\n purpose: \"login\",\n ...(options.flowDefinitionName ? { flow_definition_name: options.flowDefinitionName } : {}),\n });\n\n for (let hop = 0; hop < MAX_FLOW_STEPS; hop += 1) {\n if (response.handoff_token) {\n const exchanged = await client.exchangeHandoff(\n { handoff_token: response.handoff_token },\n { project_id: context.projectId },\n );\n return {\n user,\n sessionToken: exchanged.session_token,\n expiresAt: exchanged.session.expires_at,\n cookie: {\n name: SESSION_COOKIE_NAME,\n value: exchanged.session_token,\n httpOnly: true,\n secure: true,\n sameSite: \"Lax\",\n path: \"/\",\n },\n };\n }\n response = await flowFetch(\n handle,\n jar,\n origin,\n `/flow/${encodeURIComponent(response.id)}/submit`,\n {\n session_token: response.session_token,\n action: \"submit\",\n fields: collectFields(response, values),\n },\n );\n }\n\n throw new Error(\n `seed.session: flow did not complete within ${MAX_FLOW_STEPS} steps ` +\n `(last step: ${describeStep(response)}).`,\n );\n}\n\n/** One-cookie jar for the sealed `_zflow` flow-state cookie. */\nclass FlowCookieJar {\n private cookie: string | undefined;\n\n absorb(response: Response): void {\n for (const raw of response.headers.getSetCookie()) {\n const [pair] = raw.split(\";\", 1);\n if (pair?.startsWith(\"_zflow=\")) {\n this.cookie = pair;\n }\n }\n }\n\n header(): Record<string, string> {\n return this.cookie ? { cookie: this.cookie } : {};\n }\n}\n\nasync function flowFetch(\n handle: Pick<InstanceHandle, \"baseUrl\" | \"projectSecret\">,\n jar: FlowCookieJar,\n origin: string | undefined,\n path: string,\n body: Record<string, unknown>,\n): Promise<CreateFlow201> {\n const response = await fetch(`${apiBaseUrl(handle.baseUrl)}${path}`, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n authorization: `Bearer ${handle.projectSecret}`,\n // The project's origin allowlist applies to flow calls; send the app\n // origin the way a browser request through the app would carry it.\n ...(origin ? { origin } : {}),\n ...jar.header(),\n },\n body: JSON.stringify(body),\n });\n jar.absorb(response);\n const parsed = (await response.json().catch(() => undefined)) as CreateFlow201 | undefined;\n if (!response.ok || !parsed) {\n const detail = parsed && typeof parsed === \"object\" ? ` — ${JSON.stringify(parsed)}` : \"\";\n // An origin-allowlist rejection without an Origin header is a\n // configuration gap, not a flow problem — say how to close it. A request\n // with no Origin is served the newest primary deployment, which a project\n // may not have.\n const hint =\n !origin && /origin/i.test(detail)\n ? \"\\nNo Origin header was sent: pass `origin` to seedSession() (the Playwright \" +\n \"fixtures pass the suite's baseURL) or `appOrigins` to startLocalZitadel().\"\n : \"\";\n throw new Error(`seed.session: POST ${path} returned ${response.status}${detail}${hint}`);\n }\n return parsed;\n}\n\n/**\n * Fill exactly the fields the current step declares — the orchestrator's\n * convention — from the known email/password values. An unknown required\n * field means this flow needs more than a password login can provide.\n */\nfunction collectFields(\n response: CreateFlow201,\n values: Record<string, string>,\n): Record<string, string> {\n const fields: Record<string, string> = {};\n for (const field of response.step.fields ?? []) {\n const value = values[fieldKey(field)];\n if (value === undefined) {\n throw new Error(\n `seed.session supports password flows only; step ${describeStep(response)} ` +\n `declares field \"${field.name}\", which the kit cannot fill. ` +\n `Log in through the UI for flows with additional factors.`,\n );\n }\n fields[field.name] = value;\n }\n return fields;\n}\n\n/**\n * Steps name credential fields with schema pointers (e.g.\n * `x-auth-methods#password`); match on the trailing segment so the value map\n * stays the plain `{ email, password }` a caller thinks in.\n */\nfunction fieldKey(field: CreateFlow201StepFieldsItem): string {\n const name = field.name;\n const tail = name.split(/[#/.]/).at(-1) ?? name;\n return tail.toLowerCase();\n}\n\nfunction describeStep(response: CreateFlow201): string {\n const name = response.step.name ?? \"(unnamed)\";\n const declared = (response.step.fields ?? []).map((field) => field.name).join(\", \");\n return `\"${name}\"${declared ? ` [fields: ${declared}]` : \"\"}`;\n}\n","import { createZitadelClient } from \"@zitadel/api/client\";\n\nimport { applyAppEnvTemplate, nextAppEnv } from \"./app-env\";\nimport { bootstrapProject, type BootstrapProjectOptions } from \"./bootstrap\";\nimport { bootLocalServer, type BootServerOptions } from \"./lifecycle\";\nimport { identity, seedUser, seedUsers } from \"./seed\";\nimport { mintSession } from \"./session\";\nimport type { ConnectedZitadel, InstanceHandle, LocalZitadel } from \"./types\";\n\nexport type StartLocalZitadelOptions = BootServerOptions & Omit<BootstrapProjectOptions, \"baseUrl\">;\n\n/**\n * Attach to an already-bootstrapped instance/project. Lifecycle-free on\n * purpose: this is the entry point for Playwright workers (via the handshake\n * file) and, later, for seeding remote instances.\n */\nexport function connectZitadel(handle: InstanceHandle): ConnectedZitadel {\n const api = createZitadelClient({ baseUrl: handle.baseUrl, token: handle.projectSecret });\n const context = { projectId: handle.projectId, schemaId: handle.schemaId };\n const connected: ConnectedZitadel = {\n handle,\n api,\n // The Next-shaped convenience view; other frameworks apply their own\n // template to `handle` (see AppEnvTemplate).\n appEnv: applyAppEnvTemplate(nextAppEnv, handle),\n seedUser: (input) => seedUser(api, context, input),\n seedUsers: (count, template) => seedUsers(api, context, count, template),\n identity,\n seedSession: async (input = {}) => {\n const { user: existing, flowDefinitionName, origin, ...userInput } = input;\n const user = existing ?? (await seedUser(api, context, userInput));\n return mintSession(api, handle, context, user, {\n flowDefinitionName,\n origin: origin ?? handle.appOrigin,\n });\n },\n };\n return connected;\n}\n\n/**\n * Boot an ephemeral local instance (binary runtime + SQLite by default, no\n * Docker) and bootstrap a project + default schema + login flow on it. The\n * result can seed loginable password users immediately.\n */\nexport async function startLocalZitadel(\n options: StartLocalZitadelOptions = {},\n): Promise<LocalZitadel> {\n const server = await bootLocalServer(options);\n let bootstrapped: Awaited<ReturnType<typeof bootstrapProject>>;\n try {\n bootstrapped = await bootstrapProject({\n baseUrl: server.baseUrl,\n projectName: options.projectName,\n appOrigins: options.appOrigins,\n preset: options.preset,\n useCase: options.useCase,\n });\n } catch (error) {\n try {\n await server.stop();\n } catch (stopError) {\n // Both errors are preserved in AggregateError.errors, which the rule\n // below cannot model.\n throw new AggregateError(\n [error, stopError],\n \"bootstrap failed, and stopping the booted instance also failed\",\n );\n }\n throw error;\n }\n const handle: InstanceHandle = {\n baseUrl: server.baseUrl,\n projectId: bootstrapped.projectId,\n projectSecret: bootstrapped.projectSecret,\n schemaId: bootstrapped.schemaId,\n previewSecret: bootstrapped.previewSecret,\n appOrigin: options.appOrigins?.[0],\n };\n return {\n ...connectZitadel(handle),\n runtime: server.runtime,\n stop: server.stop,\n [Symbol.asyncDispose]: server.stop,\n };\n}\n\nexport { applyAppEnvTemplate, nextAppEnv } from \"./app-env\";\nexport type { AppEnvTemplate } from \"./app-env\";\nexport { bootstrapProject } from \"./bootstrap\";\nexport type { BootstrapProjectOptions, BootstrappedProject } from \"./bootstrap\";\nexport { readHandshakeSync, waitForHandshake, writeHandshake } from \"./handshake\";\nexport { bootLocalServer } from \"./lifecycle\";\nexport type { BootedServer, BootServerOptions } from \"./lifecycle\";\nexport { identity } from \"./seed\";\nexport { browserSessionCookieName, SESSION_COOKIE_NAME, sessionCookieName } from \"./session\";\nexport type {\n ConnectedZitadel,\n Identity,\n InstanceHandle,\n LocalZitadel,\n LocalZitadelRuntime,\n MintedSession,\n PlatformCredentials,\n SeededUser,\n SeedSessionInput,\n SeedUserInput,\n SeedUsersTemplate,\n SessionCookie,\n} from \"./types\";\n"],"mappings":";;;;;;;;;;;;AA8BA,MAAM,uBAAuB;;;;;;;;;;;AAY7B,MAAM,sBAAsB;AAE5B,eAAsB,iBACpB,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