@zitadel/testing 0.6.0 → 0.8.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.
- package/README.md +92 -22
- package/dist/app-runner.cjs +3 -4
- package/dist/app-runner.mjs +3 -4
- package/dist/{handshake-D6MXSUcd.cjs → handshake-BEhxJx4Z.cjs} +21 -5
- package/dist/handshake-BEhxJx4Z.cjs.map +1 -0
- package/dist/{handshake-CwlxMjW0.mjs → handshake-CZWS5b2X.mjs} +17 -7
- package/dist/handshake-CZWS5b2X.mjs.map +1 -0
- package/dist/index-KrNefxOo.d.mts +77 -0
- package/dist/index.cjs +3 -2
- package/dist/index.d.mts +3 -81
- package/dist/index.mjs +3 -3
- package/dist/{orchestration-Clldecyr.mjs → orchestration-Cf4M8lil.mjs} +2 -3
- package/dist/{orchestration-Clldecyr.mjs.map → orchestration-Cf4M8lil.mjs.map} +1 -1
- package/dist/{orchestration-gIDANMcF.cjs → orchestration-SELq6dmD.cjs} +2 -3
- package/dist/{orchestration-gIDANMcF.cjs.map → orchestration-SELq6dmD.cjs.map} +1 -1
- package/dist/playwright.cjs +10 -13
- package/dist/playwright.cjs.map +1 -1
- package/dist/playwright.d.mts +3 -13
- package/dist/playwright.mjs +11 -15
- package/dist/playwright.mjs.map +1 -1
- package/dist/{session-B84nOEiv.d.mts → session-DueRCvrq.d.mts} +9 -10
- package/dist/{src-DOMrJlOH.cjs → src-DZ46zEll.cjs} +3577 -2769
- package/dist/src-DZ46zEll.cjs.map +1 -0
- package/dist/{src-Ck7eLkah.mjs → src-DkwAAu0O.mjs} +96 -42
- package/dist/src-DkwAAu0O.mjs.map +1 -0
- package/dist/supervisor.cjs +4 -5
- package/dist/supervisor.mjs +4 -5
- package/dist/vitest.d.mts +33 -0
- package/dist/vitest.mjs +65 -0
- package/dist/vitest.mjs.map +1 -0
- package/package.json +19 -11
- package/dist/handshake-CwlxMjW0.mjs.map +0 -1
- package/dist/handshake-D6MXSUcd.cjs.map +0 -1
- package/dist/src-Ck7eLkah.mjs.map +0 -1
- package/dist/src-DOMrJlOH.cjs.map +0 -1
|
@@ -1,15 +1,16 @@
|
|
|
1
|
-
import { a as nextAppEnv, i as applyAppEnvTemplate } from "./handshake-
|
|
1
|
+
import { a as nextAppEnv, i as applyAppEnvTemplate } from "./handshake-CZWS5b2X.mjs";
|
|
2
2
|
import { createRequire } from "node:module";
|
|
3
3
|
import { createZitadelClient } from "@zitadel/api/client";
|
|
4
4
|
import { DEFAULT_FLOW_SCHEMA_URI, getDefaultHumanUserSchemaBody, getDefaultLoginFlow } from "@zitadel/config/defaults";
|
|
5
|
+
import { rmSync } from "node:fs";
|
|
5
6
|
import { mkdtemp, rm } from "node:fs/promises";
|
|
6
7
|
import { tmpdir } from "node:os";
|
|
7
8
|
import { dirname, join } from "node:path";
|
|
8
|
-
import { spawn } from "node:child_process";
|
|
9
|
+
import { spawn, spawnSync } from "node:child_process";
|
|
9
10
|
import { createServer } from "node:net";
|
|
10
11
|
import { randomUUID } from "node:crypto";
|
|
11
12
|
import { apiBaseUrl } from "@zitadel/api/runtime/base-url";
|
|
12
|
-
|
|
13
|
+
// src/bootstrap.ts
|
|
13
14
|
const DEFAULT_PROJECT_NAME = "zitadel-testing";
|
|
14
15
|
/**
|
|
15
16
|
* Server-side half of `zitadel setup`, without any file scaffolding:
|
|
@@ -40,12 +41,12 @@ async function bootstrapProject(options) {
|
|
|
40
41
|
preset: options.preset,
|
|
41
42
|
useCase: options.useCase
|
|
42
43
|
});
|
|
43
|
-
const schema = await client.
|
|
44
|
+
const schema = await client.publishSchema(schemaBody, { project_id: project.id });
|
|
44
45
|
const flowBody = getDefaultLoginFlow({
|
|
45
46
|
preset: options.preset,
|
|
46
47
|
useCase: options.useCase
|
|
47
48
|
});
|
|
48
|
-
const flow = await client.
|
|
49
|
+
const flow = await client.publishFlowDefinition({
|
|
49
50
|
project_id: project.id,
|
|
50
51
|
schema_uri: DEFAULT_FLOW_SCHEMA_URI,
|
|
51
52
|
flow_definition: flowBody
|
|
@@ -69,8 +70,7 @@ async function bootstrapProject(options) {
|
|
|
69
70
|
flowId: flow.id
|
|
70
71
|
};
|
|
71
72
|
}
|
|
72
|
-
|
|
73
|
-
//#region src/cli.ts
|
|
73
|
+
// src/cli.ts
|
|
74
74
|
const DEFAULT_TIMEOUT_MS = 12e4;
|
|
75
75
|
function resolveCliBin() {
|
|
76
76
|
const require = createRequire(import.meta.url);
|
|
@@ -123,11 +123,37 @@ function runCli(options) {
|
|
|
123
123
|
});
|
|
124
124
|
});
|
|
125
125
|
}
|
|
126
|
+
/**
|
|
127
|
+
* Blocking variant of {@link runCli}, for the one caller that cannot await: a
|
|
128
|
+
* signal handler whose process exits on the next tick.
|
|
129
|
+
*/
|
|
130
|
+
function runCliSync(options) {
|
|
131
|
+
const bin = options.bin ?? resolveCliBin();
|
|
132
|
+
const result = spawnSync(process.execPath, [bin, ...options.args], {
|
|
133
|
+
env: {
|
|
134
|
+
...process.env,
|
|
135
|
+
...options.env
|
|
136
|
+
},
|
|
137
|
+
stdio: [
|
|
138
|
+
"ignore",
|
|
139
|
+
"pipe",
|
|
140
|
+
"pipe"
|
|
141
|
+
],
|
|
142
|
+
encoding: "utf8",
|
|
143
|
+
timeout: options.timeoutMs ?? DEFAULT_TIMEOUT_MS,
|
|
144
|
+
killSignal: "SIGKILL"
|
|
145
|
+
});
|
|
146
|
+
if (result.error) throw result.error;
|
|
147
|
+
return {
|
|
148
|
+
exitCode: result.status ?? -1,
|
|
149
|
+
stdout: result.stdout,
|
|
150
|
+
stderr: result.stderr
|
|
151
|
+
};
|
|
152
|
+
}
|
|
126
153
|
function tail(text, lines = 20) {
|
|
127
154
|
return text.split("\n").slice(-lines).join("\n").trim();
|
|
128
155
|
}
|
|
129
|
-
|
|
130
|
-
//#region src/envelope.ts
|
|
156
|
+
// src/envelope.ts
|
|
131
157
|
/**
|
|
132
158
|
* Render an error envelope's remediation fields for humans — the CLI's
|
|
133
159
|
* `hint`/`next_commands` are the actionable part of a failure (e.g. "Reinstall
|
|
@@ -154,8 +180,7 @@ function parseCliEnvelope(stdout, context) {
|
|
|
154
180
|
if (typeof parsed !== "object" || parsed === null || typeof parsed.status !== "string") throw new Error(`${context}: stdout JSON is not a CLI envelope:\n${stdout.trim()}`);
|
|
155
181
|
return parsed;
|
|
156
182
|
}
|
|
157
|
-
|
|
158
|
-
//#region src/ports.ts
|
|
183
|
+
// src/ports.ts
|
|
159
184
|
/**
|
|
160
185
|
* Ask the OS for a free TCP port. The port is released before returning, so a
|
|
161
186
|
* racing process could grab it; the CLI's own preflight surfaces that as
|
|
@@ -184,8 +209,9 @@ function getFreePort() {
|
|
|
184
209
|
});
|
|
185
210
|
});
|
|
186
211
|
}
|
|
187
|
-
|
|
188
|
-
|
|
212
|
+
// src/lifecycle.ts
|
|
213
|
+
/** How many ports a start on an unspecified port tries before giving up. */
|
|
214
|
+
const PORT_RACE_ATTEMPTS = 5;
|
|
189
215
|
/**
|
|
190
216
|
* Boot an ephemeral local server by shelling out to `zitadel start` and parse
|
|
191
217
|
* its JSON envelope. The CLI owns the subtle parts (port preflight, health
|
|
@@ -195,23 +221,27 @@ function getFreePort() {
|
|
|
195
221
|
async function bootLocalServer(options = {}) {
|
|
196
222
|
const ownsDir = options.dir === void 0;
|
|
197
223
|
const dir = options.dir ?? await mkdtemp(join(tmpdir(), "zitadel-testing-"));
|
|
198
|
-
const
|
|
199
|
-
const
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
224
|
+
const env = cliEnv(options);
|
|
225
|
+
const attempts = options.port === void 0 ? PORT_RACE_ATTEMPTS : 1;
|
|
226
|
+
let result;
|
|
227
|
+
for (let attempt = 1;; attempt += 1) {
|
|
228
|
+
const port = options.port ?? await getFreePort();
|
|
229
|
+
result = await runCli({
|
|
230
|
+
args: [
|
|
231
|
+
"start",
|
|
232
|
+
"--port",
|
|
233
|
+
String(port),
|
|
234
|
+
"--non-interactive",
|
|
235
|
+
"--json",
|
|
236
|
+
"-c",
|
|
237
|
+
dir
|
|
238
|
+
],
|
|
239
|
+
bin: options.cliBin,
|
|
240
|
+
env,
|
|
241
|
+
timeoutMs: options.timeoutMs
|
|
242
|
+
});
|
|
243
|
+
if (result.exitCode === 0 || attempt >= attempts || !result.stdout.concat(result.stderr).includes("E_PORT_IN_USE")) break;
|
|
244
|
+
}
|
|
215
245
|
if (result.exitCode !== 0) throw new Error(`zitadel start exited with code ${result.exitCode}.\n${failureDetail(result)}\nstate dir kept for inspection: ${dir}`);
|
|
216
246
|
const stopViaCli = async () => {
|
|
217
247
|
const stopResult = await runCli({
|
|
@@ -269,6 +299,34 @@ async function bootLocalServer(options = {}) {
|
|
|
269
299
|
};
|
|
270
300
|
}
|
|
271
301
|
/**
|
|
302
|
+
* Stop the server `bootLocalServer(options)` booted in `dir`, blocking until
|
|
303
|
+
* the CLI returns, and remove the dir when the boot owned it. For a signal
|
|
304
|
+
* handler, where the process exits before an awaited stop could finish;
|
|
305
|
+
* everywhere else use `BootedServer.stop`.
|
|
306
|
+
*/
|
|
307
|
+
function stopLocalServerSync(dir, options = {}) {
|
|
308
|
+
const result = runCliSync({
|
|
309
|
+
args: [
|
|
310
|
+
"stop",
|
|
311
|
+
"--non-interactive",
|
|
312
|
+
"--json",
|
|
313
|
+
"-c",
|
|
314
|
+
dir
|
|
315
|
+
],
|
|
316
|
+
bin: options.cliBin,
|
|
317
|
+
env: cliEnv(options),
|
|
318
|
+
timeoutMs: options.timeoutMs
|
|
319
|
+
});
|
|
320
|
+
if (result.exitCode !== 0) throw new Error(`zitadel stop exited with code ${result.exitCode}.\n${failureDetail(result)}\nstate dir kept for inspection: ${dir}`);
|
|
321
|
+
if (options.dir === void 0 && !options.keep) rmSync(dir, {
|
|
322
|
+
recursive: true,
|
|
323
|
+
force: true
|
|
324
|
+
});
|
|
325
|
+
}
|
|
326
|
+
function cliEnv(options) {
|
|
327
|
+
return options.serverBinary ? { ZITADEL_SERVER_BINARY: options.serverBinary } : {};
|
|
328
|
+
}
|
|
329
|
+
/**
|
|
272
330
|
* A failed CLI run usually still prints an error envelope; its
|
|
273
331
|
* message/hint/next_commands beat raw output tails (e.g. a fresh install
|
|
274
332
|
* missing @zitadel/server gets "Reinstall @zitadel/cli" instead of a stack).
|
|
@@ -280,8 +338,7 @@ function failureDetail(result) {
|
|
|
280
338
|
} catch {}
|
|
281
339
|
return `stdout: ${tail(result.stdout) || "(empty)"}\nstderr: ${tail(result.stderr) || "(empty)"}`;
|
|
282
340
|
}
|
|
283
|
-
|
|
284
|
-
//#region src/seed.ts
|
|
341
|
+
// src/seed.ts
|
|
285
342
|
/**
|
|
286
343
|
* A unique unused email + password. Nothing is created on the instance —
|
|
287
344
|
* this is the input for registration-flow specs, which must prove the flow
|
|
@@ -324,7 +381,7 @@ async function seedUser(client, context, input = {}) {
|
|
|
324
381
|
/**
|
|
325
382
|
* Seed `count` users sequentially. The template makes fixture data
|
|
326
383
|
* deterministic per index (stable emails/names keep screenshot diffs about
|
|
327
|
-
* code, not reshuffled data — the
|
|
384
|
+
* code, not reshuffled data — the `@zitadel/console#dev:real` pattern); untemplated
|
|
328
385
|
* fields fall back to the unique defaults. Name-like attributes need a
|
|
329
386
|
* schema that declares them (`useCase: "consumer"` or wider).
|
|
330
387
|
*/
|
|
@@ -337,8 +394,7 @@ async function seedUsers(client, context, count, template = {}) {
|
|
|
337
394
|
}));
|
|
338
395
|
return users;
|
|
339
396
|
}
|
|
340
|
-
|
|
341
|
-
//#region src/session.ts
|
|
397
|
+
// src/session.ts
|
|
342
398
|
/**
|
|
343
399
|
* The server's session cookie under its canonical name
|
|
344
400
|
* (internal/api/session.go, ADR 083): the name a direct call to the server
|
|
@@ -414,7 +470,7 @@ async function mintSession(client, handle, context, user, options = {}) {
|
|
|
414
470
|
};
|
|
415
471
|
const jar = new FlowCookieJar();
|
|
416
472
|
const origin = options.origin;
|
|
417
|
-
let response = await flowFetch(handle, jar, origin, "/
|
|
473
|
+
let response = await flowFetch(handle, jar, origin, "/flows", {
|
|
418
474
|
project_id: context.projectId,
|
|
419
475
|
purpose: "login",
|
|
420
476
|
...options.flowDefinitionName ? { flow_definition_name: options.flowDefinitionName } : {}
|
|
@@ -436,7 +492,7 @@ async function mintSession(client, handle, context, user, options = {}) {
|
|
|
436
492
|
}
|
|
437
493
|
};
|
|
438
494
|
}
|
|
439
|
-
response = await flowFetch(handle, jar, origin, `/
|
|
495
|
+
response = await flowFetch(handle, jar, origin, `/flows/${encodeURIComponent(response.id)}/submit`, {
|
|
440
496
|
session_token: response.session_token,
|
|
441
497
|
action: "submit",
|
|
442
498
|
fields: collectFields(response, values)
|
|
@@ -505,8 +561,7 @@ function describeStep(response) {
|
|
|
505
561
|
const declared = (response.step.fields ?? []).map((field) => field.name).join(", ");
|
|
506
562
|
return `"${name}"${declared ? ` [fields: ${declared}]` : ""}`;
|
|
507
563
|
}
|
|
508
|
-
|
|
509
|
-
//#region src/index.ts
|
|
564
|
+
// src/index.ts
|
|
510
565
|
/**
|
|
511
566
|
* Attach to an already-bootstrapped instance/project. Lifecycle-free on
|
|
512
567
|
* purpose: this is the entry point for Playwright workers (via the handshake
|
|
@@ -576,7 +631,6 @@ async function startLocalZitadel(options = {}) {
|
|
|
576
631
|
[Symbol.asyncDispose]: server.stop
|
|
577
632
|
};
|
|
578
633
|
}
|
|
579
|
-
|
|
580
|
-
export { secureSessionCookie as a, bootLocalServer as c, browserSessionCookieName as i, bootstrapProject as l, startLocalZitadel as n, sessionCookieName as o, SESSION_COOKIE_NAME as r, identity as s, connectZitadel as t };
|
|
634
|
+
export { secureSessionCookie as a, bootLocalServer as c, browserSessionCookieName as i, stopLocalServerSync as l, startLocalZitadel as n, sessionCookieName as o, SESSION_COOKIE_NAME as r, identity as s, connectZitadel as t, bootstrapProject as u };
|
|
581
635
|
|
|
582
|
-
//# sourceMappingURL=src-
|
|
636
|
+
//# sourceMappingURL=src-DkwAAu0O.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"src-DkwAAu0O.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.publishSchema(schemaBody, { project_id: project.id });\n\n const flowBody = getDefaultLoginFlow({\n preset: options.preset,\n useCase: options.useCase,\n });\n const flow = await client.publishFlowDefinition({\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, spawnSync } 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\n/**\n * Blocking variant of {@link runCli}, for the one caller that cannot await: a\n * signal handler whose process exits on the next tick.\n */\nexport function runCliSync(options: RunCliOptions): RunCliResult {\n const bin = options.bin ?? resolveCliBin();\n const result = spawnSync(process.execPath, [bin, ...options.args], {\n env: { ...process.env, ...options.env },\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n encoding: \"utf8\",\n timeout: options.timeoutMs ?? DEFAULT_TIMEOUT_MS,\n killSignal: \"SIGKILL\",\n });\n if (result.error) {\n throw result.error;\n }\n return { exitCode: result.status ?? -1, stdout: result.stdout, stderr: result.stderr };\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 { rmSync } from \"node:fs\";\nimport { mkdtemp, rm } from \"node:fs/promises\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\n\nimport { runCli, runCliSync, 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\n/** How many ports a start on an unspecified port tries before giving up. */\nconst PORT_RACE_ATTEMPTS = 5;\n\nexport interface BootServerOptions {\n /**\n * TCP port for the instance. Defaults to an OS-assigned free port; when\n * another process takes it before the server binds, the start is retried on\n * a fresh one. An explicit port is never retried.\n */\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 env = cliEnv(options);\n\n // The free port is released before the server binds it, so a parallel\n // process can take it in between; the CLI then refuses with E_PORT_IN_USE.\n const attempts = options.port === undefined ? PORT_RACE_ATTEMPTS : 1;\n let result: RunCliResult;\n for (let attempt = 1; ; attempt += 1) {\n const port = options.port ?? (await getFreePort());\n 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 (\n result.exitCode === 0 ||\n attempt >= attempts ||\n !result.stdout.concat(result.stderr).includes(\"E_PORT_IN_USE\")\n ) {\n break;\n }\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 * Stop the server `bootLocalServer(options)` booted in `dir`, blocking until\n * the CLI returns, and remove the dir when the boot owned it. For a signal\n * handler, where the process exits before an awaited stop could finish;\n * everywhere else use `BootedServer.stop`.\n */\nexport function stopLocalServerSync(dir: string, options: BootServerOptions = {}): void {\n const result = runCliSync({\n args: [\"stop\", \"--non-interactive\", \"--json\", \"-c\", dir],\n bin: options.cliBin,\n env: cliEnv(options),\n timeoutMs: options.timeoutMs,\n });\n if (result.exitCode !== 0) {\n throw new Error(\n `zitadel stop exited with code ${result.exitCode}.\\n${failureDetail(result)}\\n` +\n `state dir kept for inspection: ${dir}`,\n );\n }\n if (options.dir === undefined && !options.keep) {\n rmSync(dir, { recursive: true, force: true });\n }\n}\n\nfunction cliEnv(options: BootServerOptions): NodeJS.ProcessEnv {\n return options.serverBinary ? { ZITADEL_SERVER_BINARY: options.serverBinary } : {};\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 `@zitadel/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 /flows`; 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, \"/flows\", {\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 `/flows/${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, viteAppEnv } 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,SAC8B;CAC9B,MAAM,EAAE,YAAY;CAEpB,MAAM,UAAU,MADQ,oBAAoB,EAAE,QAAQ,CAClB,CAAC,CAAC,cAAc;EAClD,MAAM,QAAQ,eAAe;EAC7B,UAAU,QAAQ,YAAY,SAAS,QAAQ,aAAa,CAAC,mBAAmB,EAAA,CAAG,KAChF,aAAa;GACZ;GACA,MAAM;EACR,EACF;EACA,eAAe;CACjB,CAAC;CACD,MAAM,SAAS,oBAAoB;EAAE;EAAS,OAAO,QAAQ;CAAe,CAAC;CAE7E,MAAM,aAAa,8BAA8B;EAC/C,QAAQ,QAAQ;EAChB,SAAS,QAAQ;CACnB,CAAC;CACD,MAAM,SAAS,MAAM,OAAO,cAAc,YAAY,EAAE,YAAY,QAAQ,GAAG,CAAC;CAEhF,MAAM,WAAW,oBAAoB;EACnC,QAAQ,QAAQ;EAChB,SAAS,QAAQ;CACnB,CAAC;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Q,SAAS,MAAM;IAC7C;IACA,QAAQ,UAAU,OAAO;GAC3B,CAAC;EACH;CAEa;AACjB;;;;;;AAOA,eAAsB,kBACpB,UAAoC,CAAC,GACd;CACvB,MAAM,SAAS,MAAM,gBAAgB,OAAO;CAC5C,IAAI;CACJ,IAAI;EACF,eAAe,MAAM,iBAAiB;GACpC,SAAS,OAAO;GAChB,aAAa,QAAQ;GACrB,YAAY,QAAQ;GACpB,QAAQ,QAAQ;GAChB,SAAS,QAAQ;EACnB,CAAC;CACH,SAAS,OAAO;EACd,IAAI;GACF,MAAM,OAAO,KAAK;EACpB,SAAS,WAAW;GAGlB,MAAM,IAAI,eACR,CAAC,OAAO,SAAS,GACjB,gEACF;EACF;EACA,MAAM;CACR;CASA,OAAO;EACL,GAAG,eAAe;GARlB,SAAS,OAAO;GAChB,WAAW,aAAa;GACxB,eAAe,aAAa;GAC5B,UAAU,aAAa;GACvB,eAAe,aAAa;GAC5B,WAAW,QAAQ,aAAa;EAGT,CAAC;EACxB,SAAS,OAAO;EAChB,MAAM,OAAO;GACZ,OAAO,eAAe,OAAO;CAChC;AACF"}
|
package/dist/supervisor.cjs
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
const
|
|
2
|
-
const
|
|
3
|
-
const require_orchestration = require("./orchestration-
|
|
1
|
+
const require_handshake = require("./handshake-BEhxJx4Z.cjs");
|
|
2
|
+
const require_src = require("./src-DZ46zEll.cjs");
|
|
3
|
+
const require_orchestration = require("./orchestration-SELq6dmD.cjs");
|
|
4
4
|
let node_fs_promises = require("node:fs/promises");
|
|
5
|
-
|
|
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
|
package/dist/supervisor.mjs
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { r as writeHandshake } from "./handshake-
|
|
2
|
-
import { n as startLocalZitadel } from "./src-
|
|
3
|
-
import { a as parseSupervisorConfig, o as requireHandshakePath, r as SUPERVISOR_CONFIG_ENV } from "./orchestration-
|
|
1
|
+
import { r as writeHandshake } from "./handshake-CZWS5b2X.mjs";
|
|
2
|
+
import { n as startLocalZitadel } from "./src-DkwAAu0O.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
|
-
|
|
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-KrNefxOo.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
|
package/dist/vitest.mjs
ADDED
|
@@ -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-DkwAAu0O.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.
|
|
3
|
+
"version": "0.8.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.
|
|
41
|
-
"@zitadel/cli": "0.
|
|
42
|
-
"@zitadel/config": "0.
|
|
46
|
+
"@zitadel/api": "0.8.0",
|
|
47
|
+
"@zitadel/cli": "0.8.0",
|
|
48
|
+
"@zitadel/config": "0.8.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.
|
|
54
|
-
"@types/node": "^24.19.
|
|
63
|
+
"@playwright/test": "^1.65.0",
|
|
64
|
+
"@types/node": "^24.19.2",
|
|
55
65
|
"@zitadel/vitest-config": "0.0.0",
|
|
56
|
-
"msw": "^2.
|
|
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,QAAQ,OAAO;EACrB,IAAI,OAAO,UAAU,YAAY,MAAM,WAAW,GAGhD,MAAM,IAAI,MACR,0BAA0B,KAAK,qBAAqB,MAAM,4CAC5D;EAEF,IAAI,QAAQ;CACd;CACA,OAAO;AACT;;;;;;;;ACtCA,eAAsB,eAAe,MAAc,QAAuC;CACxF,MAAM,MAAM,QAAQ,IAAI,GAAG,EAAE,WAAW,KAAK,CAAC;CAC9C,MAAM,UAAU,MAAM,GAAG,KAAK,UAAU,QAAQ,MAAM,CAAC,EAAE,KAAK,EAAE,MAAM,IAAM,CAAC;AAC/E;AAEA,SAAgB,kBAAkB,MAA8B;CAC9D,MAAM,WAAW,aAAa,MAAM,MAAM;CAC1C,IAAI;CACJ,IAAI;EACF,QAAQ,KAAK,MAAM,QAAQ;CAC7B,SAAS,OAAO;EACd,MAAM,IAAI,MAAM,kBAAkB,KAAK,0BAA2B,MAAgB,WAAW,EAC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AY,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,MAAM,IAAI,MACR,0BAA0B,KAAK,qBAAqB,MAAM,4CAC5D;EAEF,IAAI,QAAQ;CACd;CACA,OAAO;AACT;;;;;;;;ACtCA,eAAsB,eAAe,MAAc,QAAuC;CACxF,OAAA,GAAMA,iBAAAA,MAAAA,EAAAA,GAAMC,UAAAA,QAAAA,CAAQ,IAAI,GAAG,EAAE,WAAW,KAAK,CAAC;CAC9C,OAAA,GAAMC,iBAAAA,UAAAA,CAAU,MAAM,GAAG,KAAK,UAAU,QAAQ,MAAM,CAAC,EAAE,KAAK,EAAE,MAAM,IAAM,CAAC;AAC/E;AAEA,SAAgB,kBAAkB,MAA8B;CAC9D,MAAM,YAAA,GAAWC,QAAAA,aAAAA,CAAa,MAAM,MAAM;CAC1C,IAAI;CACJ,IAAI;EACF,QAAQ,KAAK,MAAM,QAAQ;CAC7B,SAAS,OAAO;EACd,MAAM,IAAI,MA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