@zitadel/cli 0.1.0-alpha.8 → 0.1.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 (45) hide show
  1. package/README.md +2758 -210
  2. package/bin/run.js +8 -0
  3. package/dist/index.mjs +25199 -0
  4. package/dist/index.mjs.map +1 -0
  5. package/dist/lib/oclif/help.mjs +71 -0
  6. package/dist/lib/oclif/help.mjs.map +1 -0
  7. package/dist/skills-hint-BSspFzhr.mjs +173 -0
  8. package/dist/skills-hint-BSspFzhr.mjs.map +1 -0
  9. package/oclif.manifest.json +5846 -250
  10. package/package.json +73 -13
  11. package/skills/zitadel-cli/SKILL.md +442 -0
  12. package/skills/zitadel-cli/references/driving-login-ui.md +89 -0
  13. package/SKILLS.md +0 -152
  14. package/dist/commands/apply.mjs +0 -62
  15. package/dist/commands/apply.mjs.map +0 -1
  16. package/dist/commands/doctor.mjs +0 -490
  17. package/dist/commands/doctor.mjs.map +0 -1
  18. package/dist/commands/eject.mjs +0 -145
  19. package/dist/commands/eject.mjs.map +0 -1
  20. package/dist/commands/logs.mjs +0 -58
  21. package/dist/commands/logs.mjs.map +0 -1
  22. package/dist/commands/plan.mjs +0 -52
  23. package/dist/commands/plan.mjs.map +0 -1
  24. package/dist/commands/reset.mjs +0 -71
  25. package/dist/commands/reset.mjs.map +0 -1
  26. package/dist/commands/setup.mjs +0 -916
  27. package/dist/commands/setup.mjs.map +0 -1
  28. package/dist/commands/start.mjs +0 -221
  29. package/dist/commands/start.mjs.map +0 -1
  30. package/dist/commands/status.mjs +0 -112
  31. package/dist/commands/status.mjs.map +0 -1
  32. package/dist/commands/stop.mjs +0 -52
  33. package/dist/commands/stop.mjs.map +0 -1
  34. package/dist/docker-BA78SdC2.mjs +0 -383
  35. package/dist/docker-BA78SdC2.mjs.map +0 -1
  36. package/dist/docker-guidance-BvfpmsDj.mjs +0 -21
  37. package/dist/docker-guidance-BvfpmsDj.mjs.map +0 -1
  38. package/dist/oclif-VkCTGIEk.mjs +0 -818
  39. package/dist/oclif-VkCTGIEk.mjs.map +0 -1
  40. package/dist/orca-CfKDQRop.mjs +0 -2556
  41. package/dist/orca-CfKDQRop.mjs.map +0 -1
  42. package/dist/project-CKAHtHML.mjs +0 -87
  43. package/dist/project-CKAHtHML.mjs.map +0 -1
  44. package/dist/sync-B5lqgQO3.mjs +0 -733
  45. package/dist/sync-B5lqgQO3.mjs.map +0 -1
@@ -1,916 +0,0 @@
1
- import { D as ZitadelError, O as toZitadelError, n as DEFAULT_SERVER, t as BaseCommand, x as publicCliCommand } from "../oclif-VkCTGIEk.mjs";
2
- import { n as RENDERER_IDS, r as issuerFromPort, t as createOrca } from "../orca-CfKDQRop.mjs";
3
- import { n as hasZitadelSecret, t as hasZitadelConfig } from "../project-CKAHtHML.mjs";
4
- import { cancel, confirm, intro, isCancel, outro, select, spinner, text } from "@clack/prompts";
5
- import { Flags } from "@oclif/core";
6
- import { createZitadelClient } from "@zitadel/api/client";
7
- import { consola as consola$1 } from "consola";
8
- import { basename, join } from "node:path";
9
- import { readFile, stat } from "node:fs/promises";
10
- import { execFile, spawn } from "node:child_process";
11
- import pc from "picocolors";
12
- //#region src/lib/package-manager.ts
13
- async function detectPackageManager(cwd) {
14
- const declared = await packageManagerFromManifest(cwd);
15
- if (declared) return declared;
16
- if (await exists(join(cwd, "pnpm-lock.yaml"))) return "pnpm";
17
- if (await exists(join(cwd, "yarn.lock"))) return "yarn";
18
- if (await exists(join(cwd, "bun.lock"))) return "bun";
19
- if (await exists(join(cwd, "bun.lockb"))) return "bun";
20
- if (await exists(join(cwd, "package-lock.json"))) return "npm";
21
- return "npm";
22
- }
23
- function installCommandFor(packageManager) {
24
- return command(packageManager, ["install"]);
25
- }
26
- function devCommandFor(packageManager) {
27
- switch (packageManager) {
28
- case "npm": return command("npm", ["run", "dev"]);
29
- case "pnpm": return command("pnpm", ["dev"]);
30
- case "yarn": return command("yarn", ["dev"]);
31
- case "bun": return command("bun", ["run", "dev"]);
32
- }
33
- }
34
- async function runPackageCommand(packageCommand, options) {
35
- await new Promise((resolve, reject) => {
36
- const child = spawn(packageCommand.command, packageCommand.args, {
37
- cwd: options.cwd,
38
- env: options.env ?? process.env,
39
- stdio: options.redirectStdoutToStderr ? [
40
- "ignore",
41
- "pipe",
42
- "pipe"
43
- ] : "inherit"
44
- });
45
- if (options.redirectStdoutToStderr) {
46
- child.stdout?.on("data", (chunk) => process.stderr.write(chunk));
47
- child.stderr?.on("data", (chunk) => process.stderr.write(chunk));
48
- }
49
- child.on("error", reject);
50
- child.on("close", (code, signal) => {
51
- if (code === 0) {
52
- resolve();
53
- return;
54
- }
55
- const detail = signal ? `signal ${signal}` : `exit ${String(code ?? 1)}`;
56
- const error = /* @__PURE__ */ new Error(`${packageCommand.display} failed with ${detail}`);
57
- Object.assign(error, {
58
- code: code ?? 1,
59
- signal
60
- });
61
- reject(error);
62
- });
63
- });
64
- }
65
- function command(packageManager, args) {
66
- return {
67
- command: packageManager,
68
- args,
69
- display: [packageManager, ...args].join(" ")
70
- };
71
- }
72
- async function packageManagerFromManifest(cwd) {
73
- try {
74
- const raw = await readFile(join(cwd, "package.json"), "utf8");
75
- const parsed = JSON.parse(raw);
76
- return typeof parsed.packageManager === "string" ? packageManagerFromString(parsed.packageManager) : void 0;
77
- } catch {
78
- return;
79
- }
80
- }
81
- function packageManagerFromString(value) {
82
- const name = value.split("@")[0];
83
- return name === "npm" || name === "pnpm" || name === "yarn" || name === "bun" ? name : void 0;
84
- }
85
- async function exists(path) {
86
- try {
87
- await stat(path);
88
- return true;
89
- } catch {
90
- return false;
91
- }
92
- }
93
- //#endregion
94
- //#region src/commands/setup/install.ts
95
- async function installDependenciesForSetup(input) {
96
- const packageManager = await detectPackageManager(input.cwd);
97
- const installCommand = installCommandFor(packageManager);
98
- const devCommand = devCommandFor(packageManager);
99
- if (!(input.scaffoldedFramework || input.depsAdded.length > 0)) return outcome({
100
- install: {
101
- status: "not-needed",
102
- package_manager: packageManager,
103
- command: installCommand.display,
104
- reason: "no-dependency-changes"
105
- },
106
- devCommand: devCommand.display,
107
- issuer: input.issuer,
108
- includeInstallCommand: false
109
- });
110
- if (input.dryRun || input.skipInstall) return outcome({
111
- install: {
112
- status: "skipped",
113
- package_manager: packageManager,
114
- command: installCommand.display,
115
- reason: input.dryRun ? "dry-run" : "skip-install"
116
- },
117
- devCommand: devCommand.display,
118
- issuer: input.issuer,
119
- includeInstallCommand: true
120
- });
121
- consola$1.start(`Installing dependencies with ${installCommand.display}`);
122
- try {
123
- await (input.run ?? runPackageCommand)(installCommand, {
124
- cwd: input.cwd,
125
- env: input.env,
126
- redirectStdoutToStderr: input.json
127
- });
128
- } catch (error) {
129
- throw installFailed(error, installCommand, devCommand, input.cwd);
130
- }
131
- consola$1.success("Installed dependencies");
132
- return outcome({
133
- install: {
134
- status: "completed",
135
- package_manager: packageManager,
136
- command: installCommand.display
137
- },
138
- devCommand: devCommand.display,
139
- issuer: input.issuer,
140
- includeInstallCommand: false
141
- });
142
- }
143
- function outcome(input) {
144
- const startAction = `Start your project: ${input.devCommand} (then open ${input.issuer})`;
145
- const verifyAction = "Verify auth in the browser: register a user, log out, log in again with the same user, and confirm /profile shows Signed in.";
146
- return {
147
- install: input.install,
148
- devCommand: input.devCommand,
149
- nextActions: input.includeInstallCommand ? [
150
- `Install dependencies: ${input.install.command}`,
151
- startAction,
152
- verifyAction
153
- ] : [startAction, verifyAction],
154
- nextCommands: input.includeInstallCommand ? [input.install.command, input.devCommand] : [input.devCommand]
155
- };
156
- }
157
- function installFailed(error, installCommand, devCommand, cwd) {
158
- return new ZitadelError("E_VALIDATION", `Dependency install failed: ${installCommand.display}`, {
159
- hint: `Run ${installCommand.display} in ${cwd}, then start the app with ${devCommand.display}.`,
160
- nextCommands: [installCommand.display],
161
- details: {
162
- command: installCommand.display,
163
- cwd,
164
- original: errorShape(error)
165
- }
166
- });
167
- }
168
- function errorShape(error) {
169
- if (error instanceof Error) return {
170
- name: error.name,
171
- message: error.message,
172
- code: error.code
173
- };
174
- return { message: String(error) };
175
- }
176
- //#endregion
177
- //#region src/commands/setup/prompts/cancel.ts
178
- /**
179
- * Converts a clack cancellation (Ctrl-C) into a thrown `E_VALIDATION` rather
180
- * than a partial answer. Every prompt funnels its clack return value through
181
- * this so the wizard never proceeds with a sentinel or missing value.
182
- */
183
- function bail(value) {
184
- if (isCancel(value)) {
185
- cancel("Setup cancelled.");
186
- throw new ZitadelError("E_VALIDATION", "Setup cancelled by user");
187
- }
188
- }
189
- //#endregion
190
- //#region src/commands/setup/prompts/dev-port.ts
191
- /**
192
- * "Dev server port" — defaults to the detected port. The validated answer
193
- * becomes the issuer URL (`http://localhost:<port>`) via `issuerFromPort`.
194
- */
195
- var DevPortPrompt = class {
196
- async ask(answers, ctx) {
197
- if (ctx.devPortFromFlag) return answers;
198
- const value = await text({
199
- message: "Dev server port",
200
- placeholder: String(answers.devPort),
201
- initialValue: String(answers.devPort),
202
- validate: (input) => {
203
- const num = Number.parseInt(input ?? "", 10);
204
- return Number.isFinite(num) && num > 0 && num < 65536 ? void 0 : "Must be a port number";
205
- }
206
- });
207
- bail(value);
208
- return {
209
- ...answers,
210
- devPort: Number.parseInt(String(value), 10)
211
- };
212
- }
213
- };
214
- //#endregion
215
- //#region src/commands/setup/prompts/framework-confirm.ts
216
- /**
217
- * "Detected `<framework>`. Proceed?" — the wizard's first question. Accepting
218
- * leaves answers unchanged; declining throws `E_UNSUPPORTED_PROJECT_SHAPE`
219
- * (the user should re-run with an explicit `--framework`).
220
- */
221
- var FrameworkConfirmPrompt = class {
222
- async ask(answers, ctx) {
223
- const ack = await confirm({
224
- message: `Detected ${ctx.framework.id}. Proceed?`,
225
- initialValue: true
226
- });
227
- bail(ack);
228
- if (ack === false) throw new ZitadelError("E_UNSUPPORTED_PROJECT_SHAPE", "Setup cancelled — framework declined", { hint: `Re-run with --framework ${ctx.framework.id} when ready.` });
229
- return answers;
230
- }
231
- };
232
- //#endregion
233
- //#region src/lib/prober/ports.ts
234
- /**
235
- * Enumerate TCP ports currently in LISTEN state on the loopback interface
236
- * (`127.0.0.1`, `::1`, or the wildcard `*`). Spawns `lsof -iTCP -sTCP:LISTEN
237
- * -P -n -F n` and parses its machine-readable output. Returns the unique,
238
- * numerically-sorted list of ports.
239
- *
240
- * Never throws. Returns `[]` whenever lsof is unavailable (e.g. Windows,
241
- * unusual PATH), the spawn errors, exits non-zero, or the call exceeds
242
- * `timeoutMs` (default 1000ms). The caller treats an empty list the same as
243
- * "no listeners worth probing."
244
- */
245
- async function listListeningPorts(opts) {
246
- const timeoutMs = opts?.timeoutMs ?? 1e3;
247
- try {
248
- return parseLsofPorts(await runLsof(timeoutMs));
249
- } catch {
250
- return [];
251
- }
252
- }
253
- /**
254
- * Spawn `lsof` with the canned argv and resolve to its stdout. Hand-rolled
255
- * rather than `util.promisify(execFile)` because the latter resolves with a
256
- * `{stdout, stderr}` object via its custom-promisify symbol — a heavier shape
257
- * to mock and worse to read at the call site, where we only ever want stdout.
258
- */
259
- function runLsof(timeoutMs) {
260
- return new Promise((resolve, reject) => {
261
- execFile("lsof", [
262
- "-iTCP",
263
- "-sTCP:LISTEN",
264
- "-P",
265
- "-n",
266
- "-F",
267
- "n"
268
- ], {
269
- timeout: timeoutMs,
270
- encoding: "utf8"
271
- }, (err, stdout) => {
272
- if (err) {
273
- reject(err);
274
- return;
275
- }
276
- resolve(stdout);
277
- });
278
- });
279
- }
280
- /**
281
- * Parse the `n` records emitted by `lsof -F n`. Each record is a single line
282
- * `n<address>` where `<address>` ends in `:<port>` (e.g. `n*:8080`,
283
- * `n127.0.0.1:3000`, `n[::1]:5050`). Only loopback/wildcard hosts are kept;
284
- * external interface bindings are ignored.
285
- */
286
- function parseLsofPorts(stdout) {
287
- const ports = /* @__PURE__ */ new Set();
288
- for (const line of stdout.split(/\r?\n/)) {
289
- if (!line.startsWith("n")) continue;
290
- const address = line.slice(1);
291
- const colon = address.lastIndexOf(":");
292
- if (colon < 0) continue;
293
- const host = address.slice(0, colon);
294
- const portStr = address.slice(colon + 1);
295
- if (!isLoopback(host)) continue;
296
- const port = Number.parseInt(portStr, 10);
297
- if (Number.isFinite(port) && port > 0 && port < 65536) ports.add(port);
298
- }
299
- return [...ports].sort((a, b) => a - b);
300
- }
301
- /** Recognised loopback host strings as emitted by `lsof -F n`. */
302
- function isLoopback(host) {
303
- return host === "*" || host === "127.0.0.1" || host === "[::1]" || host === "::1";
304
- }
305
- //#endregion
306
- //#region src/lib/prober/http.ts
307
- /**
308
- * Fetch `url` with a per-call timeout and pass the resulting `Response` to
309
- * `predicate`. Returns the predicate's value, or `null` on any failure: a
310
- * network error, an `AbortError` from the timeout, a thrown predicate, or the
311
- * predicate returning `null`.
312
- *
313
- * Never throws. The predicate decides what counts as a match — it gets the
314
- * raw `Response` and may read `.json()` / `.headers` / `.status` as needed.
315
- *
316
- * `timeoutMs` defaults to 500ms. The implementation uses
317
- * `AbortSignal.timeout`, so the underlying fetch is cancelled when the
318
- * timeout fires (no orphaned sockets).
319
- */
320
- async function probeUrl(url, predicate, opts) {
321
- const timeoutMs = opts?.timeoutMs ?? 500;
322
- try {
323
- return await predicate(await fetch(url, { signal: AbortSignal.timeout(timeoutMs) }));
324
- } catch {
325
- return null;
326
- }
327
- }
328
- /**
329
- * Probe many URLs in parallel and return the non-null matches, preserving
330
- * the input order. Each URL is bounded by `timeoutMs` independently — one
331
- * slow target can't hold up the others.
332
- */
333
- async function probeUrls(urls, predicate, opts) {
334
- const list = [...urls];
335
- return (await Promise.all(list.map(async (url) => {
336
- const value = await probeUrl(url, predicate, opts);
337
- return value === null ? null : {
338
- url,
339
- value
340
- };
341
- }))).filter((match) => match !== null);
342
- }
343
- //#endregion
344
- //#region src/commands/setup/prompts/server.ts
345
- /** Sentinel returned by the choice select when the user picks "Custom URL". */
346
- const CUSTOM = "__custom__";
347
- /** Per-probe timeout for the localhost OIDC scan — generous enough for a TLS handshake on a busy laptop. */
348
- const OIDC_PROBE_TIMEOUT_MS = 300;
349
- /**
350
- * "Which server should `zitadel.json` point to?" — Zitadel Cloud, a localhost
351
- * OIDC server we discovered, or a custom URL.
352
- *
353
- * Before asking, it scans the loopback for listening ports (via the generic
354
- * `lib/prober`) and `GET`s `/.well-known/openid-configuration` on each. Every
355
- * 2xx response with a string `issuer` becomes an extra option in the choice
356
- * list. Picking a discovered URL writes it directly to `answers.server` and
357
- * skips the follow-up text prompt. Picking "Custom URL" still asks for a
358
- * validated URL exactly as before.
359
- */
360
- var ServerPrompt = class {
361
- async ask(answers, ctx) {
362
- if (ctx.serverFlag) return answers;
363
- const discovered = await discoverLocalOidc();
364
- const choice = await select({
365
- message: "Which server should zitadel.json point to?",
366
- options: [
367
- {
368
- value: DEFAULT_SERVER,
369
- label: "Zitadel Cloud (api.zitadel.cloud)",
370
- hint: "recommended for real projects"
371
- },
372
- ...discovered.map((server) => ({
373
- value: server,
374
- label: server,
375
- hint: "detected — OIDC"
376
- })),
377
- {
378
- value: CUSTOM,
379
- label: "Custom URL (self-hosted)"
380
- }
381
- ],
382
- initialValue: answers.server ?? "https://api.zitadel.cloud"
383
- });
384
- bail(choice);
385
- if (choice !== CUSTOM) return {
386
- ...answers,
387
- server: choice
388
- };
389
- const custom = await text({
390
- message: "Server URL",
391
- placeholder: "https://zitadel.internal",
392
- validate: (value) => {
393
- try {
394
- new URL(value ?? "");
395
- return;
396
- } catch {
397
- return "Must be a valid URL";
398
- }
399
- }
400
- });
401
- bail(custom);
402
- return {
403
- ...answers,
404
- server: custom
405
- };
406
- }
407
- };
408
- /**
409
- * Returns the loopback origins (`http://localhost:<port>`) whose
410
- * `/.well-known/openid-configuration` endpoint responds with a valid OIDC
411
- * discovery document. Sniffs purely via the generic prober — the only
412
- * Zitadel-shaped detail here is the OIDC predicate, which is the standard
413
- * "any OIDC server" contract (no `zitadel`-keyword check), so Keycloak/dex/
414
- * etc. also surface and the user picks the right one.
415
- */
416
- async function discoverLocalOidc() {
417
- const s = spinner();
418
- s.start("Scanning localhost for OIDC servers");
419
- try {
420
- const ports = await listListeningPorts();
421
- if (ports.length === 0) {
422
- s.stop("No local servers detected.");
423
- return [];
424
- }
425
- const origins = (await probeUrls(ports.map((port) => `http://localhost:${port}/.well-known/openid-configuration`), async (response) => {
426
- if (!response.ok) return null;
427
- try {
428
- const body = await response.json();
429
- return typeof body.issuer === "string" ? body.issuer : null;
430
- } catch {
431
- return null;
432
- }
433
- }, { timeoutMs: OIDC_PROBE_TIMEOUT_MS })).map((match) => new URL(match.url).origin);
434
- s.stop(origins.length === 0 ? "No local OIDC servers found." : `Found ${origins.length} local OIDC server${origins.length === 1 ? "" : "s"}.`);
435
- return origins;
436
- } catch (error) {
437
- s.stop("Discovery skipped.");
438
- throw error;
439
- }
440
- }
441
- //#endregion
442
- //#region src/commands/setup/prompts/pick-framework.ts
443
- /**
444
- * "Choose a framework to scaffold" — the only prompt outside the main wizard.
445
- * Runs at the empty-directory branch (before any other detection), so it owns
446
- * its own `intro` heading. Returns the chosen framework id; choices come from
447
- * `Orca.availableFrameworks`.
448
- */
449
- var PickFrameworkPrompt = class {
450
- async ask(choices) {
451
- intro("Zitadel setup — new project");
452
- const picked = await select({
453
- message: "Choose a framework to scaffold",
454
- options: choices.map((choice) => ({
455
- value: choice.id,
456
- label: choice.displayName
457
- }))
458
- });
459
- bail(picked);
460
- return picked;
461
- }
462
- };
463
- //#endregion
464
- //#region src/commands/setup/prompts/index.ts
465
- /**
466
- * Public surface for the setup wizard prompts. The `setup` command imports
467
- * {@link SETUP_PROMPTS} and iterates every entry, threading the answers
468
- * through each prompt's `ask` so they decide whether to actually ask the
469
- * user. Add a new question by writing a class and appending an instance to
470
- * the registry below.
471
- *
472
- * {@link PickFrameworkPrompt} is intentionally **not** in {@link SETUP_PROMPTS}
473
- * — it runs at the empty-directory scaffold branch, before the main wizard
474
- * starts.
475
- */
476
- /** Every question the main setup wizard asks, in ask order. */
477
- const SETUP_PROMPTS = [
478
- new FrameworkConfirmPrompt(),
479
- new ServerPrompt(),
480
- new DevPortPrompt()
481
- ];
482
- //#endregion
483
- //#region src/commands/setup/summary.ts
484
- /**
485
- * Renders the section list as a single multi-line string. Labels are
486
- * padded to a common width per section so the `✓ label value` columns
487
- * line up, the title prints in dim gray, and `✓` is green. Values come
488
- * in pre-styled — use the helpers below ({@link path}, {@link url},
489
- * {@link id}, {@link dim}) to keep the colour palette consistent with
490
- * the mock.
491
- */
492
- function renderSummary(sections) {
493
- const lines = [];
494
- for (const section of sections) {
495
- if (section.rows.length === 0) continue;
496
- if (lines.length > 0) lines.push("");
497
- lines.push(pc.dim(section.title.toUpperCase()));
498
- const labelWidth = Math.max(...section.rows.map((r) => r.label.length)) + 3;
499
- for (const row of section.rows) {
500
- const labelCol = row.label.padEnd(labelWidth);
501
- const secondary = row.secondary ? ` ${pc.dim("→")} ${row.secondary}` : "";
502
- lines.push(`${pc.green("✓")} ${labelCol}${row.value}${secondary}`);
503
- }
504
- }
505
- return lines.join("\n");
506
- }
507
- /** Cyan, for filesystem paths the user can open. */
508
- const path = (s) => pc.cyan(s);
509
- /** Cyan, for URLs (browser-clickable in most terminals). */
510
- const url = (s) => pc.cyan(s);
511
- /** Yellow, for opaque ids the user shouldn't try to read. */
512
- const id = (s) => pc.yellow(s);
513
- /**
514
- * Reads the project root to identify the framework version, TS presence,
515
- * and which package manager the user runs. Returns safe defaults (npm
516
- * fallback, no version) on any error so summary rendering can always proceed.
517
- */
518
- async function detectProjectFacts(cwd, frameworkId) {
519
- const facts = {
520
- framework: frameworkId,
521
- typescript: await fileExists(join(cwd, "tsconfig.json")),
522
- packageManager: await detectPackageManager(cwd)
523
- };
524
- try {
525
- const raw = await readFile(join(cwd, "package.json"), "utf8");
526
- const pj = JSON.parse(raw);
527
- const depPkg = depFromFramework(frameworkId);
528
- const range = pj.dependencies?.[depPkg] ?? pj.devDependencies?.[depPkg];
529
- if (range) facts.frameworkVersion = stripRange(range);
530
- } catch {}
531
- return facts;
532
- }
533
- /** Formats the project facts as the "Next.js 15 · TypeScript · npm" string the mock shows. */
534
- function formatFrameworkLine(facts) {
535
- const segments = [];
536
- const pretty = prettyFramework(facts.framework);
537
- segments.push(facts.frameworkVersion ? `${pretty} ${facts.frameworkVersion}` : pretty);
538
- if (facts.typescript) segments.push("TypeScript");
539
- segments.push(facts.packageManager);
540
- return segments.join(` ${pc.dim("·")} `);
541
- }
542
- async function fileExists(p) {
543
- try {
544
- await stat(p);
545
- return true;
546
- } catch {
547
- return false;
548
- }
549
- }
550
- function depFromFramework(framework) {
551
- switch (framework) {
552
- case "next": return "next";
553
- case "nuxt": return "nuxt";
554
- default: return framework;
555
- }
556
- }
557
- function prettyFramework(framework) {
558
- switch (framework) {
559
- case "next": return "Next.js";
560
- case "nuxt": return "Nuxt";
561
- default: return framework;
562
- }
563
- }
564
- /** Strips `^`/`~`/`>=`/`v` prefixes from an npm range so the version reads cleanly in the summary. */
565
- function stripRange(range) {
566
- const trimmed = range.replace(/^([\^~]|>=?|v)/, "").trim();
567
- return trimmed.split(/\s+/)[0] ?? trimmed;
568
- }
569
- /** Returns just the file name from a relative path, for the `→ filename` secondary detail in PACKAGE rows. */
570
- function fileNameOf(p) {
571
- return basename(p);
572
- }
573
- //#endregion
574
- //#region src/commands/setup/index.ts
575
- /**
576
- * The frameworks `--framework` accepts, derived from Orca's registry so the
577
- * flag can't drift from what the CLI can actually scaffold. `createOrca` is
578
- * pure (it only builds the in-memory registries), so this is safe at module
579
- * load.
580
- */
581
- const FRAMEWORK_OPTIONS = createOrca().availableFrameworks().map((framework) => framework.id);
582
- /** `zitadel setup` — create a project and scaffold local auth.
583
- *
584
- * Detects (or, for an empty directory, scaffolds then re-detects) the
585
- * framework, runs the wizard prompts to fill in any answers not pre-supplied
586
- * by flags, creates the remote project (whose default user schema and login
587
- * flow are provisioned server-side), and patches the local files via
588
- * `Orca`'s framework patcher.
589
- *
590
- * Every interactive question lives in {@link SETUP_PROMPTS} (the main wizard
591
- * — each entry is a small class) and {@link PickFrameworkPrompt} (the
592
- * empty-directory framework choice, before the main wizard).
593
- */
594
- var Setup = class Setup extends BaseCommand {
595
- static description = "Create a Zitadel project and scaffold local auth.";
596
- static examples = ["<%= config.bin %> setup --framework next", "<%= config.bin %> setup --framework react --dev-port 3000"];
597
- static flags = {
598
- framework: Flags.string({
599
- description: "Framework to target.",
600
- options: FRAMEWORK_OPTIONS
601
- }),
602
- renderer: Flags.string({
603
- description: "Renderer (default: react).",
604
- options: [...RENDERER_IDS]
605
- }),
606
- "dev-port": Flags.integer({ description: "Dev-server port; also the issuer origin registered with Zitadel. Defaults to the detected port. Use distinct ports to run several scaffolded apps side by side." }),
607
- "skip-install": Flags.boolean({ description: "Do not install dependencies after setup updates package.json." })
608
- };
609
- async run() {
610
- const { flags } = await this.parse(Setup);
611
- try {
612
- await this.toMeta(flags);
613
- } catch (error) {
614
- throw localSetupHint(error, flags.framework, this.config.version);
615
- }
616
- const { cwd, nonInteractive, dryRun, force } = this.meta;
617
- if (await hasZitadelConfig(cwd)) return this.emit({
618
- status: "skipped",
619
- reason: "already-initialized"
620
- });
621
- if (await hasZitadelSecret(cwd)) throw new ZitadelError("E_CONFLICT", ".zitadel/secret exists without zitadel.json", { hint: "Move the secret aside or restore zitadel.json before running setup." });
622
- const orca = createOrca();
623
- consola$1.start(`Detecting framework in ${shortPath(cwd)}`);
624
- let framework;
625
- let scaffoldedFramework = false;
626
- try {
627
- framework = await orca.detect(cwd, flags.framework);
628
- consola$1.success(`Detected ${framework.id}${framework.devPort ? ` (dev port ${framework.devPort})` : ""}`);
629
- } catch (error) {
630
- if (error instanceof ZitadelError && error.code === "E_FRAMEWORK_NOT_DETECTED" && await orca.isFreshScaffoldTarget(cwd)) {
631
- consola$1.info("Fresh app directory — scaffolding a fresh project");
632
- framework = await orca.scaffold(cwd, await resolveScaffoldFramework(flags.framework, nonInteractive, orca));
633
- scaffoldedFramework = true;
634
- consola$1.success(`Scaffolded ${framework.id} skeleton`);
635
- } else throw error;
636
- }
637
- if (flags["dev-port"] !== void 0) {
638
- const devPort = flags["dev-port"];
639
- if (!Number.isInteger(devPort) || devPort < 1 || devPort > 65535) throw new ZitadelError("E_VALIDATION", `--dev-port must be an integer in 1..65535, got ${devPort}`);
640
- framework = {
641
- ...framework,
642
- devPort,
643
- url: issuerFromPort(devPort)
644
- };
645
- }
646
- let answers = {
647
- server: this.meta.source,
648
- devPort: framework.devPort
649
- };
650
- if (!nonInteractive && !dryRun) {
651
- intro("Zitadel setup");
652
- const promptCtx = {
653
- framework,
654
- serverFlag: this.meta.serverFlag,
655
- devPortFromFlag: flags["dev-port"] !== void 0
656
- };
657
- for (const prompt of SETUP_PROMPTS) answers = await prompt.ask(answers, promptCtx);
658
- outro("Configuration captured");
659
- }
660
- const issuer = issuerFromPort(answers.devPort);
661
- framework = {
662
- ...framework,
663
- devPort: answers.devPort,
664
- url: issuer
665
- };
666
- consola$1.start(`Creating project on ${answers.server}${dryRun ? " (dry run)" : ""}`);
667
- const unauthClient = createZitadelClient({ baseUrl: answers.server });
668
- const project = dryRun ? dryRunProject(issuer) : await createProjectWithLocalHint(unauthClient, answers.server, this.meta.cliVersion, issuer, framework.id);
669
- consola$1.success(`Created project ${project.id}`);
670
- const ctx = {
671
- framework,
672
- rendererId: flags.renderer ?? "react",
673
- project,
674
- issuer,
675
- server: answers.server,
676
- cliVersion: this.meta.cliVersion,
677
- scaffoldedFramework
678
- };
679
- consola$1.start(`Patching project files${dryRun ? " (dry run)" : ""}`);
680
- const result = await orca.patcherFor(framework.id).patch(ctx, {
681
- cwd,
682
- dryRun,
683
- force
684
- });
685
- for (const file of result.filesWritten) {
686
- const sentence = describeWrittenFile(relativeDisplay(cwd, file), dryRun);
687
- if (sentence) consola$1.info(sentence);
688
- }
689
- for (const file of result.filesSkipped) consola$1.info(`Left ${relativeDisplay(cwd, file)} unchanged (already matches target)`);
690
- consola$1.success(`Patched ${result.filesWritten.length} file${result.filesWritten.length === 1 ? "" : "s"}` + (result.filesSkipped.length > 0 ? ` (${result.filesSkipped.length} unchanged)` : ""));
691
- const installOutcome = await installDependenciesForSetup({
692
- cwd,
693
- depsAdded: result.depsAdded,
694
- dryRun,
695
- env: this.meta.env,
696
- issuer,
697
- json: this.jsonEnabled(),
698
- scaffoldedFramework,
699
- skipInstall: Boolean(flags["skip-install"])
700
- });
701
- const writtenRel = result.filesWritten.map((file) => relativeDisplay(cwd, file));
702
- if (!this.jsonEnabled()) {
703
- const sections = buildSummary({
704
- projectFacts: await detectProjectFacts(cwd, framework.id),
705
- writtenRel,
706
- project,
707
- server: answers.server,
708
- issuer,
709
- scaffoldedFramework
710
- });
711
- consola$1.box({
712
- title: "Zitadel is ready",
713
- message: [
714
- renderSummary(sections),
715
- "",
716
- installOutcome.nextActions.join("\n")
717
- ].join("\n"),
718
- style: {
719
- padding: 1,
720
- borderStyle: "rounded",
721
- borderColor: "green"
722
- }
723
- });
724
- }
725
- return this.emit({
726
- status: "ok",
727
- pretty: "",
728
- data: {
729
- title: "Zitadel is ready.",
730
- project: {
731
- project_id: project.id,
732
- issuer
733
- },
734
- framework: framework.id,
735
- server: answers.server,
736
- files_written: result.filesWritten.map((file) => relativeDisplay(cwd, file)),
737
- files_skipped: result.filesSkipped.map((file) => relativeDisplay(cwd, file)),
738
- install: installOutcome.install,
739
- next_actions: installOutcome.nextActions,
740
- next_commands: installOutcome.nextCommands
741
- }
742
- });
743
- }
744
- };
745
- /**
746
- * Resolves which framework to scaffold into an empty directory: the explicit
747
- * `--framework`, else PickFrameworkPrompt, else a hard error in non-interactive
748
- * mode (an agent must pass `--framework`).
749
- */
750
- async function resolveScaffoldFramework(framework, nonInteractive, orca) {
751
- if (framework) return framework;
752
- if (nonInteractive) throw new ZitadelError("E_FRAMEWORK_NOT_DETECTED", "Empty directory — pass --framework", { hint: "Run without --json/--non-interactive to choose from a prompt, or pass --framework for scripted setup." });
753
- return new PickFrameworkPrompt().ask(orca.availableFrameworks());
754
- }
755
- /** A deterministic stand-in project for `--dry-run`, so no remote call is made. */
756
- function dryRunProject(issuer) {
757
- return {
758
- id: "dry-run-0000",
759
- projectSecret: "sk_proj_dry_run_full",
760
- previewSecret: "sk_proj_dry_run_preview",
761
- previewOrigins: [issuer],
762
- createdAt: "2026-04-21T14:03:11.000Z"
763
- };
764
- }
765
- async function createProjectWithLocalHint(client, server, cliVersion, issuer, framework) {
766
- try {
767
- return await client.createProject({ previewOrigins: [issuer] });
768
- } catch (error) {
769
- const normalized = toZitadelError(error);
770
- throw new ZitadelError(normalized.code, normalized.message, {
771
- hint: `${normalized.hint ? `${normalized.hint} ` : ""}If you meant to use a local Zitadel server, start it first and retry setup with --framework ${framework} --server local.`,
772
- nextCommands: [publicCliCommand("start", cliVersion), publicCliCommand(`setup --framework ${framework} --server local`, cliVersion)],
773
- details: {
774
- server,
775
- original: normalized.details
776
- }
777
- });
778
- }
779
- }
780
- function localSetupHint(error, framework, cliVersion) {
781
- const normalized = toZitadelError(error);
782
- if (normalized.code !== "E_LOCAL_SERVER_NOT_RUNNING") return error;
783
- const setupCommand = framework ? `setup --framework ${framework} --server local` : "setup --server local";
784
- return new ZitadelError(normalized.code, normalized.message, {
785
- hint: `${normalized.hint ? `${normalized.hint} ` : ""}Start local Zitadel first, then rerun setup. After setup succeeds, follow its next_commands to start the app and verify registration, logout, and login in the browser.`,
786
- nextCommands: [publicCliCommand("start", cliVersion), publicCliCommand(setupCommand, cliVersion)],
787
- details: normalized.details
788
- });
789
- }
790
- /** Renders an absolute path relative to `cwd` for human-readable output. */
791
- function relativeDisplay(cwd, path) {
792
- return path.startsWith(cwd) ? path.slice(cwd.length + 1) : path;
793
- }
794
- /**
795
- * Replaces the user's `$HOME` with `~` in a path for compact terminal output.
796
- * Falls back to the raw path when `HOME` isn't set or doesn't match.
797
- */
798
- function shortPath(absolute) {
799
- const home = process.env.HOME;
800
- if (home && absolute.startsWith(home)) return `~${absolute.slice(home.length)}`;
801
- return absolute;
802
- }
803
- /**
804
- * Picks one written file by suffix so the corresponding INSTALLED row can
805
- * reference it without hard-coding the path the patcher chose. Returns
806
- * the first match; falls back to `undefined` when the patcher didn't
807
- * write that artifact (e.g. a renderer without a register page).
808
- */
809
- function pickWrittenFile(written, suffix) {
810
- return written.find((file) => file.endsWith(suffix));
811
- }
812
- /**
813
- * Translates a patcher-written path into a single sentence the user can
814
- * read at narration speed. Returns `null` for directories and other
815
- * scaffolding artefacts that aren't worth narrating individually — the
816
- * file count in the closing `success(...)` and the summary's INSTALLED
817
- * section already cover them. The verb tense flips for `--dry-run` so
818
- * the user sees a preview ("Would write ...") instead of a claim that
819
- * something happened.
820
- */
821
- function describeWrittenFile(relPath, dryRun) {
822
- if (relPath === ".zitadel" || relPath === ".zitadel/flows" || relPath === ".zitadel/schemas") return null;
823
- const verb = dryRun ? "Would write" : "Wrote";
824
- const sentence = SENTENCE_BY_PATH[relPath];
825
- if (sentence) return `${verb} ${sentence.subject} (${path(relPath)})`;
826
- return `${verb} ${path(relPath)}`;
827
- }
828
- /**
829
- * Map from the patcher's deterministic output paths to a short noun
830
- * phrase describing what the file is for. Anything not in the map falls
831
- * back to the bare path in the narration; add an entry here when a new
832
- * scaffolded file deserves a clearer label.
833
- */
834
- const SENTENCE_BY_PATH = {
835
- ".gitignore": { subject: "the project's .gitignore additions" },
836
- ".zitadel/secret": { subject: "the local project secret" },
837
- "zitadel.json": { subject: "the Zitadel project configuration" },
838
- ".env.example": { subject: "the .env example template" },
839
- ".env.local": { subject: "the local development environment variables" },
840
- ".zitadel/state.json": { subject: "the empty sync state file" },
841
- "app/page.tsx": { subject: "the auth home page" },
842
- "app/login/page.tsx": { subject: "the login page" },
843
- "app/register/page.tsx": { subject: "the registration page" },
844
- "app/profile/page.tsx": { subject: "the profile page" },
845
- "middleware.ts": { subject: "the Next.js middleware" },
846
- "proxy.ts": { subject: "the Next.js proxy" },
847
- "custom-elements.d.ts": { subject: "the web-component type declarations" },
848
- "package.json": { subject: "package.json with the SDK dependency" }
849
- };
850
- /** Builds the section list driving {@link renderSummary} for the setup command. */
851
- function buildSummary(opts) {
852
- const { projectFacts, writtenRel, project, server, issuer, scaffoldedFramework } = opts;
853
- const sdkPackage = "@zitadel/sdk-next";
854
- const packageJsonHit = pickWrittenFile(writtenRel, "package.json");
855
- const detected = [{
856
- label: "Framework",
857
- value: formatFrameworkLine(projectFacts)
858
- }];
859
- if (scaffoldedFramework) detected.push({
860
- label: "Scaffold",
861
- value: "fresh project (no existing files)"
862
- });
863
- const installedRows = [];
864
- if (packageJsonHit) installedRows.push({
865
- label: "Package",
866
- value: sdkPackage,
867
- secondary: path(fileNameOf(packageJsonHit))
868
- });
869
- for (const [label, suffix] of [
870
- ["Home page", "app/page.tsx"],
871
- ["Login page", "app/login/page.tsx"],
872
- ["Register page", "app/register/page.tsx"],
873
- ["Profile page", "app/profile/page.tsx"],
874
- ["Request proxy", "proxy.ts"],
875
- ["Middleware", "middleware.ts"],
876
- ["Env vars", ".env.local"]
877
- ]) {
878
- const hit = pickWrittenFile(writtenRel, suffix);
879
- if (hit) installedRows.push({
880
- label,
881
- value: path(hit)
882
- });
883
- }
884
- const projectRows = [
885
- {
886
- label: "Project id",
887
- value: id(project.id)
888
- },
889
- {
890
- label: "Server",
891
- value: url(server)
892
- },
893
- {
894
- label: "App will run",
895
- value: url(issuer)
896
- }
897
- ];
898
- return [
899
- {
900
- title: "Detected",
901
- rows: detected
902
- },
903
- {
904
- title: "Installed",
905
- rows: installedRows
906
- },
907
- {
908
- title: "Project",
909
- rows: projectRows
910
- }
911
- ];
912
- }
913
- //#endregion
914
- export { Setup as default };
915
-
916
- //# sourceMappingURL=setup.mjs.map