@zitadel/cli 0.1.0-alpha.1 → 0.1.0-alpha.10
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 +116 -26
- package/SKILLS.md +102 -24
- package/dist/commands/apply.mjs +4 -5
- package/dist/commands/apply.mjs.map +1 -1
- package/dist/commands/doctor.mjs +214 -50
- package/dist/commands/doctor.mjs.map +1 -1
- package/dist/commands/eject.mjs +14 -7
- package/dist/commands/eject.mjs.map +1 -1
- package/dist/commands/logs.mjs +15 -7
- package/dist/commands/logs.mjs.map +1 -1
- package/dist/commands/plan.mjs +4 -5
- package/dist/commands/plan.mjs.map +1 -1
- package/dist/commands/reset.mjs +28 -12
- package/dist/commands/reset.mjs.map +1 -1
- package/dist/commands/setup.mjs +266 -106
- package/dist/commands/setup.mjs.map +1 -1
- package/dist/commands/start.mjs +180 -24
- package/dist/commands/start.mjs.map +1 -1
- package/dist/commands/status.mjs +40 -16
- package/dist/commands/status.mjs.map +1 -1
- package/dist/commands/stop.mjs +72 -11
- package/dist/commands/stop.mjs.map +1 -1
- package/dist/docker-CnGQK3ZK.mjs +432 -0
- package/dist/docker-CnGQK3ZK.mjs.map +1 -0
- package/dist/docker-guidance-ypN3IM3o.mjs +21 -0
- package/dist/docker-guidance-ypN3IM3o.mjs.map +1 -0
- package/dist/{oclif-DSPO9Sck.mjs → oclif-B7lBzh3R.mjs} +158 -63
- package/dist/oclif-B7lBzh3R.mjs.map +1 -0
- package/dist/orca-BoTFU8SI.mjs +2581 -0
- package/dist/orca-BoTFU8SI.mjs.map +1 -0
- package/dist/ports-B09RjuHx.mjs +111 -0
- package/dist/ports-B09RjuHx.mjs.map +1 -0
- package/dist/processes-Cw8TO1SY.mjs +120 -0
- package/dist/processes-Cw8TO1SY.mjs.map +1 -0
- package/dist/{project-Dwb9WVAT.mjs → project-Cd0L3PtM.mjs} +3 -3
- package/dist/{project-Dwb9WVAT.mjs.map → project-Cd0L3PtM.mjs.map} +1 -1
- package/dist/{sync-DmtTYNmq.mjs → sync-BojoQm2P.mjs} +3 -3
- package/dist/{sync-DmtTYNmq.mjs.map → sync-BojoQm2P.mjs.map} +1 -1
- package/oclif.manifest.json +49 -5
- package/package.json +8 -41
- package/dist/docker-C0aVpJqm.mjs +0 -209
- package/dist/docker-C0aVpJqm.mjs.map +0 -1
- package/dist/oclif-DSPO9Sck.mjs.map +0 -1
- package/dist/orca-DOxshV9n.mjs +0 -1009
- package/dist/orca-DOxshV9n.mjs.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"orca-BoTFU8SI.mjs","names":["dirExists","SDK_DEPENDENCY","SDK_DEPENDENCY","appTemplate","SDK_DEPENDENCY","appTemplate"],"sources":["../src/lib/orca/detectors/package-json.ts","../src/lib/orca/detectors/port.ts","../src/lib/orca/detectors/angular.ts","../src/lib/orca/detectors/next.ts","../src/lib/orca/detectors/nuxt.ts","../src/lib/orca/detectors/react.ts","../src/lib/orca/detectors/vue.ts","../src/lib/orca/detectors/index.ts","../src/lib/orca/patchers/rule/file-writer/index.ts","../src/lib/orca/patchers/rule/reclaim.ts","../src/lib/orca/patchers/rule/base.ts","../src/lib/orca/patchers/rule/angular/angular-json.ts","../src/lib/orca/patchers/rule/utils/magicast.ts","../src/lib/orca/patchers/rule/angular/angular-routes.ts","../src/lib/orca/patchers/rule/proxy.ts","../src/lib/orca/patchers/rule/angular/templates.ts","../src/lib/orca/patchers/rule/angular/index.ts","../src/lib/orca/patchers/rule/next/renderers/lit/index.ts","../src/lib/orca/patchers/rule/next/renderers/react/index.ts","../src/lib/orca/patchers/rule/next/renderers/registry.ts","../src/lib/orca/patchers/rule/next/index.ts","../src/lib/orca/patchers/rule/config-paths.ts","../src/lib/orca/patchers/rule/nuxt/nuxt-config.ts","../src/lib/orca/patchers/rule/nuxt/templates.ts","../src/lib/orca/patchers/rule/nuxt/index.ts","../src/lib/orca/patchers/rule/vite-support.ts","../src/lib/orca/patchers/rule/react/templates.ts","../src/lib/orca/patchers/rule/react/index.ts","../src/lib/orca/patchers/rule/vue/templates.ts","../src/lib/orca/patchers/rule/vue/index.ts","../src/lib/orca/patchers/index.ts","../src/lib/orca/scaffolders/cli.ts","../src/lib/orca/scaffolders/angular.ts","../src/lib/orca/scaffolders/next.ts","../src/lib/orca/scaffolders/nuxt.ts","../src/lib/orca/scaffolders/react.ts","../src/lib/orca/scaffolders/vue.ts","../src/lib/orca/scaffolders/index.ts","../src/lib/orca/index.ts"],"sourcesContent":["import { readFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\n\n/**\n * Minimal shape of the `package.json` fields detectors read. Intentionally\n * partial: only the keys detection logic depends on are modeled, all optional\n * since a project may omit any of them.\n */\nexport type PackageJson = {\n name?: string;\n scripts?: Record<string, string>;\n dependencies?: Record<string, string>;\n devDependencies?: Record<string, string>;\n};\n\n/**\n * Reads and parses the `package.json` at `cwd`. Rejects if the file is absent\n * or malformed; callers that treat those as \"not a project\" are expected to\n * catch and fall back rather than have detection swallow the error here.\n */\nexport async function readPackageJson(cwd: string): Promise<PackageJson> {\n const contents = await readFile(join(cwd, \"package.json\"), \"utf8\");\n return JSON.parse(contents) as PackageJson;\n}\n\n/**\n * Reports whether `name` appears in either `dependencies` or `devDependencies`.\n * Both are checked because framework packages may legitimately live in either.\n */\nexport function hasDependency(pkg: PackageJson, name: string): boolean {\n return Boolean(pkg.dependencies?.[name] ?? pkg.devDependencies?.[name]);\n}\n\nexport function dependencyVersionMajor(pkg: PackageJson, name: string): number | undefined {\n const spec = pkg.dependencies?.[name] ?? pkg.devDependencies?.[name];\n if (!spec) {\n return undefined;\n }\n const match = spec.match(/\\d+/);\n return match ? Number(match[0]) : undefined;\n}\n","import { readFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\n\nimport type { PackageJson } from \"./package-json\";\n\n/**\n * Port assumed when no explicit dev port can be discovered. Matches Next.js's\n * own default so the inferred issuer URL lines up with `next dev`.\n */\nexport const DEFAULT_DEV_PORT = 3000;\n\n/**\n * Determines the local dev-server port for `cwd`. The `dev` script is the most\n * authoritative source, then a `PORT` declaration in an env file, falling back\n * to {@link DEFAULT_DEV_PORT}. Used to derive the local issuer URL.\n */\nexport async function detectDevPort(cwd: string, pkg: PackageJson): Promise<number> {\n const dev = pkg.scripts?.dev;\n const fromScript = typeof dev === \"string\" ? extractPort(dev) : undefined;\n if (fromScript) {\n return fromScript;\n }\n\n const fromEnvFile = await portFromEnvFile(cwd);\n if (fromEnvFile) {\n return fromEnvFile;\n }\n\n return DEFAULT_DEV_PORT;\n}\n\nasync function portFromEnvFile(cwd: string): Promise<number | undefined> {\n for (const candidate of [\".env.local\", \".env\"]) {\n try {\n const contents = await readFile(join(cwd, candidate), \"utf8\");\n const match = contents.match(/^\\s*PORT\\s*=\\s*(\\d+)/m);\n const rawPort = match?.[1];\n if (rawPort) {\n return Number.parseInt(rawPort, 10);\n }\n } catch {\n continue;\n }\n }\n return undefined;\n}\n\n/**\n * Parses a dev port out of an npm `dev` script string, recognizing both flag\n * forms (`-p`/`--port`) and a leading `PORT=` env assignment. Returns\n * `undefined` when no valid positive port is present so callers can fall back.\n */\nexport function extractPort(script: string): number | undefined {\n const inline = script.match(/-p\\s+(\\d+)|--port[=\\s]+(\\d+)/);\n if (inline) {\n const raw = inline[1] ?? inline[2];\n if (!raw) {\n return undefined;\n }\n const value = Number.parseInt(raw, 10);\n if (Number.isFinite(value) && value > 0) {\n return value;\n }\n }\n const env = script.match(/(?:^|\\s)PORT=(\\d+)/);\n const rawEnvPort = env?.[1];\n if (rawEnvPort) {\n return Number.parseInt(rawEnvPort, 10);\n }\n return undefined;\n}\n\n/**\n * Builds the local OIDC issuer URL for a given dev port. Centralized so the\n * `localhost` origin convention is defined in exactly one place.\n */\nexport function issuerFromPort(port: number): string {\n return `http://localhost:${port}`;\n}\n","import { ZitadelError } from \"../../errors\";\nimport { hasDependency, readPackageJson } from \"./package-json\";\nimport { detectDevPort, issuerFromPort } from \"./port\";\nimport type { Detector, FrameworkFacts } from \"./types\";\n\n/** The lowest Angular major the generated templates compile on. */\nconst MIN_ANGULAR_MAJOR = 17;\n\n/** Best-effort major version from a dependency range (`^17.3.0` → 17). */\nfunction angularMajor(spec: string): number | undefined {\n const match = spec.match(/\\d+/);\n return match ? Number.parseInt(match[0], 10) : undefined;\n}\n\n/**\n * Detects an Angular project by its `@angular/core` dependency. The app dir is\n * `src/app` (where the patcher writes `app.ts`/`app.html`), the dev port comes\n * from the project (else the default), and the issuer is derived from it.\n * Angular's dev server (`@angular/build:dev-server`)\n * is Vite-based but configured via `angular.json` + a `proxy.conf.cjs`, not a\n * `vite.config.ts` — handled by the Angular patcher.\n *\n * The managed templates use Angular 17+ control flow (`@if`), so a clearly\n * older project fails fast with `E_VALIDATION` instead of scaffolding files\n * that won't compile.\n */\nexport class AngularDetector implements Detector {\n readonly framework = \"angular\";\n\n async detect(cwd: string): Promise<FrameworkFacts | null> {\n const pkg = await readPackageJson(cwd).catch(() => undefined);\n if (!pkg || !hasDependency(pkg, \"@angular/core\")) {\n return null;\n }\n\n const spec = pkg.dependencies?.[\"@angular/core\"] ?? pkg.devDependencies?.[\"@angular/core\"];\n const major = spec ? angularMajor(spec) : undefined;\n if (major !== undefined && major < MIN_ANGULAR_MAJOR) {\n throw new ZitadelError(\n \"E_VALIDATION\",\n `Angular ${major} is unsupported — the generated auth templates use Angular ${MIN_ANGULAR_MAJOR}+ control flow (@if).`,\n {\n hint: `Upgrade to Angular ${MIN_ANGULAR_MAJOR} or newer before running setup, or add the Zitadel components to your templates manually.`,\n },\n );\n }\n\n const devPort = await detectDevPort(cwd, pkg);\n return { id: \"angular\", appDir: \"src/app\", devPort, url: issuerFromPort(devPort) };\n }\n}\n","import { stat } from \"node:fs/promises\";\nimport { join } from \"node:path\";\n\nimport { ZitadelError } from \"../../errors\";\nimport { dependencyVersionMajor, hasDependency, readPackageJson } from \"./package-json\";\nimport { detectDevPort, issuerFromPort } from \"./port\";\nimport type { Detector, FrameworkFacts } from \"./types\";\n\n/**\n * Detects a Next.js App Router project and extracts its facts: the App Router\n * directory (`app` vs `src/app`), the dev-server port (parsed from the `dev`\n * script / env file, else 3000), and the derived local issuer URL. Owns every\n * Next-specific assumption so the orchestrator and commands stay generic.\n */\nexport class NextDetector implements Detector {\n readonly framework = \"next\";\n\n /**\n * Returns `null` when `cwd` is not a Next.js project (no `next` dependency),\n * so the orchestrator can try other detectors. Throws\n * `E_UNSUPPORTED_PROJECT_SHAPE` when it is Next.js but lacks an App Router\n * directory (e.g. a Pages Router project), which is a hard error rather than\n * an empty directory to scaffold.\n */\n async detect(cwd: string): Promise<FrameworkFacts | null> {\n const pkg = await readPackageJson(cwd).catch(() => undefined);\n if (!pkg || !hasDependency(pkg, \"next\")) {\n return null;\n }\n\n const appDir = (await dirExists(join(cwd, \"app\")))\n ? \"app\"\n : (await dirExists(join(cwd, \"src/app\")))\n ? \"src/app\"\n : undefined;\n if (!appDir) {\n throw new ZitadelError(\n \"E_UNSUPPORTED_PROJECT_SHAPE\",\n \"Next.js Pages Router projects are not supported in v1\",\n { hint: \"Create an App Router project with an app/ or src/app/ directory.\" },\n );\n }\n\n const devPort = await detectDevPort(cwd, pkg);\n return {\n id: \"next\",\n appDir,\n devPort,\n url: issuerFromPort(devPort),\n versionMajor: dependencyVersionMajor(pkg, \"next\"),\n };\n }\n}\n\nasync function dirExists(path: string): Promise<boolean> {\n try {\n return (await stat(path)).isDirectory();\n } catch (error) {\n if (\n typeof error === \"object\" &&\n error !== null &&\n \"code\" in error &&\n (error as { code?: string }).code === \"ENOENT\"\n ) {\n return false;\n }\n throw error;\n }\n}\n","import { stat } from \"node:fs/promises\";\nimport { join } from \"node:path\";\n\nimport { hasDependency, readPackageJson } from \"./package-json\";\nimport { detectDevPort, issuerFromPort } from \"./port\";\nimport type { Detector, FrameworkFacts } from \"./types\";\n\n/**\n * Detects a Nuxt project by its `nuxt` dependency. Like Next.js, Nuxt proxies\n * the auth backend through server middleware (`@zitadel/sdk-nuxt`), not a Vite\n * dev-server proxy — so the patcher wires the module + a `nuxt.config.ts` edit.\n * Runs before the Vue detector (which excludes Nuxt) since Nuxt ships Vue.\n *\n * `appDir` tracks the Nuxt srcDir: Nuxt 4 (what `nuxi init` now scaffolds) keeps\n * `app.vue`/`pages/`/`plugins/` under `app/`, while Nuxt 3 keeps them at the\n * root — so the patcher writes its files relative to whichever this project uses.\n */\nexport class NuxtDetector implements Detector {\n readonly framework = \"nuxt\";\n\n async detect(cwd: string): Promise<FrameworkFacts | null> {\n const pkg = await readPackageJson(cwd).catch(() => undefined);\n if (!pkg || !hasDependency(pkg, \"nuxt\")) {\n return null;\n }\n\n const appDir = (await dirExists(join(cwd, \"app\"))) ? \"app\" : \".\";\n const devPort = await detectDevPort(cwd, pkg);\n return { id: \"nuxt\", appDir, devPort, url: issuerFromPort(devPort) };\n }\n}\n\nasync function dirExists(path: string): Promise<boolean> {\n return stat(path).then(\n (s) => s.isDirectory(),\n () => false,\n );\n}\n","import { hasDependency, readPackageJson } from \"./package-json\";\nimport { detectDevPort, issuerFromPort } from \"./port\";\nimport type { Detector, FrameworkFacts } from \"./types\";\n\n/**\n * Detects a Vite + React single-page app and extracts its facts: the source\n * directory (`src`), the dev-server port (parsed from the `dev` script / env\n * file, else the framework default), and the derived local issuer URL.\n *\n * Recognises a project that depends on both `react` and `vite` but NOT `next`\n * — Next.js ships React too, so the {@link import(\"./next\").NextDetector} must\n * run first (and does, by registry order) and this detector excludes it.\n */\nexport class ReactDetector implements Detector {\n readonly framework = \"react\";\n\n async detect(cwd: string): Promise<FrameworkFacts | null> {\n const pkg = await readPackageJson(cwd).catch(() => undefined);\n if (\n !pkg ||\n hasDependency(pkg, \"next\") ||\n !hasDependency(pkg, \"react\") ||\n !hasDependency(pkg, \"vite\")\n ) {\n return null;\n }\n\n const devPort = await detectDevPort(cwd, pkg);\n return { id: \"react\", appDir: \"src\", devPort, url: issuerFromPort(devPort) };\n }\n}\n","import { hasDependency, readPackageJson } from \"./package-json\";\nimport { detectDevPort, issuerFromPort } from \"./port\";\nimport type { Detector, FrameworkFacts } from \"./types\";\n\n/**\n * Detects a Vite + Vue single-page app: depends on `vue` and `vite` but NOT\n * `nuxt` (Nuxt is its own meta-framework and ships Vue) — so the source dir is\n * `src`, the dev port comes from the project, and the issuer is derived from it.\n */\nexport class VueDetector implements Detector {\n readonly framework = \"vue\";\n\n async detect(cwd: string): Promise<FrameworkFacts | null> {\n const pkg = await readPackageJson(cwd).catch(() => undefined);\n if (\n !pkg ||\n hasDependency(pkg, \"nuxt\") ||\n !hasDependency(pkg, \"vue\") ||\n !hasDependency(pkg, \"vite\")\n ) {\n return null;\n }\n\n const devPort = await detectDevPort(cwd, pkg);\n return { id: \"vue\", appDir: \"src\", devPort, url: issuerFromPort(devPort) };\n }\n}\n","import { AngularDetector } from \"./angular\";\nimport { NextDetector } from \"./next\";\nimport { NuxtDetector } from \"./nuxt\";\nimport { ReactDetector } from \"./react\";\nimport { VueDetector } from \"./vue\";\nimport type { Detector } from \"./types\";\n\n/**\n * Active detectors, in probe order. The orchestrator tries each until one\n * recognises the project. Add a framework by appending its detector here — no\n * orchestrator changes needed. Meta-frameworks run before their base: Next\n * before React (Next ships React), and the Vue detector excludes Nuxt — so a\n * Next/Nuxt project is never mistaken for a bare React/Vue SPA.\n */\nexport const detectors = [\n new NextDetector(),\n new NuxtDetector(),\n new ReactDetector(),\n new VueDetector(),\n new AngularDetector(),\n] as const satisfies ReadonlyArray<Detector>;\n","import { chmod, mkdir, readFile, rename, stat, writeFile } from \"node:fs/promises\";\nimport { dirname, join } from \"node:path\";\n\nimport { ZitadelError } from \"../../../../errors\";\nimport { isObject, parseJsonObject, stableStringify } from \"../../../../json\";\nimport type { FileOp, ScaffoldPlan, ScaffoldResult } from \"./types\";\n\n/**\n * The executor's private, mutable accumulator. Handlers push into it as each\n * op is applied; {@link scaffold} returns it as the readonly\n * {@link ScaffoldResult} so the public result stays immutable.\n */\ntype ScaffoldAccumulator = {\n dryRun: boolean;\n filesWritten: string[];\n filesSkipped: string[];\n depsAdded: string[];\n};\n\n/**\n * Applies a {@link ScaffoldPlan} to disk, executing its operations in order.\n *\n * Operations are idempotent: writes whose target already matches the desired\n * contents are recorded as skipped rather than rewritten, so re-running setup\n * is safe. With `dryRun` no filesystem changes are made but the result still\n * reflects what would have been written. Existing files are only overwritten\n * when `force` is set; otherwise an `E_CONFLICT` is thrown to protect\n * user-authored content. Paths in the plan are resolved relative to `cwd`.\n */\nexport async function scaffold(\n plan: ScaffoldPlan,\n opts: { cwd: string; dryRun: boolean; force: boolean },\n): Promise<ScaffoldResult> {\n const result: ScaffoldAccumulator = {\n dryRun: opts.dryRun,\n filesWritten: [],\n filesSkipped: [],\n depsAdded: [],\n };\n\n for (const op of plan.ops) {\n await applyOp(op, opts, result);\n }\n\n return result;\n}\n\nasync function applyOp(\n op: FileOp,\n opts: { cwd: string; dryRun: boolean; force: boolean },\n result: ScaffoldAccumulator,\n): Promise<void> {\n switch (op.kind) {\n case \"mkdir\":\n await ensureDir(abs(opts.cwd, op.path), op.mode, opts.dryRun, result);\n break;\n case \"write\":\n await writeText(\n abs(opts.cwd, op.path),\n op.contents,\n { mode: op.mode, force: opts.force, dryRun: opts.dryRun },\n result,\n );\n break;\n case \"append\":\n await appendText(abs(opts.cwd, op.path), op.contents, op.ifMissing, opts.dryRun, result);\n break;\n case \"merge-env\":\n await mergeEnv(abs(opts.cwd, op.path), op.entries, opts.dryRun, result);\n break;\n case \"merge-json\":\n await mergeJson(abs(opts.cwd, op.path), op.patch, opts.dryRun, result);\n break;\n case \"append-gitignore\":\n await appendGitignore(abs(opts.cwd, \".gitignore\"), op.entries, opts.dryRun, result);\n break;\n case \"add-dep\":\n await addDependency(abs(opts.cwd, \"package.json\"), op, opts.dryRun, result);\n break;\n case \"edit\":\n await editFile(opts.cwd, op.path, op.edit, opts.dryRun, result);\n break;\n }\n}\n\n/**\n * Generic content edit: read the file, run the patcher-supplied transform, write\n * the result. Framework knowledge lives entirely in `edit` (next to its\n * patcher); this executor only owns candidate resolution, idempotency, dry-run,\n * and the atomic write. `pathOrPaths` may be a single path or a priority list of\n * candidates — the first that exists wins, else the first candidate.\n */\nasync function editFile(\n cwd: string,\n pathOrPaths: string | ReadonlyArray<string>,\n edit: (source: string | undefined) => string,\n dryRun: boolean,\n result: ScaffoldAccumulator,\n): Promise<void> {\n const candidates = (typeof pathOrPaths === \"string\" ? [pathOrPaths] : pathOrPaths).map((p) =>\n abs(cwd, p),\n );\n if (candidates.length === 0) {\n throw new ZitadelError(\"E_VALIDATION\", \"An edit op needs at least one candidate path\", {\n hint: \"This is an internal patcher error — please report it if you hit it.\",\n });\n }\n let path = candidates[0];\n let source: string | undefined;\n let mode: number | undefined;\n for (const candidate of candidates) {\n const contents = await readIfExists(candidate);\n if (contents !== undefined) {\n path = candidate;\n source = contents;\n // Preserve the existing file's permission bits across the temp-file swap\n // (mask off the file-type bits `stat` includes so `chmod` gets only perms).\n mode = (await stat(candidate)).mode & 0o777;\n break;\n }\n }\n const next = edit(source);\n if (next === source) {\n result.filesSkipped.push(path);\n return;\n }\n if (dryRun) {\n result.filesWritten.push(path);\n return;\n }\n await mkdir(dirname(path), { recursive: true });\n const tmp = `${path}.tmp-${process.pid}-${Date.now()}`;\n await writeFile(tmp, next);\n if (mode !== undefined) {\n await chmod(tmp, mode).catch(() => undefined);\n }\n await rename(tmp, path);\n result.filesWritten.push(path);\n}\n\nasync function ensureDir(\n path: string,\n mode: number | undefined,\n dryRun: boolean,\n result: ScaffoldAccumulator,\n): Promise<void> {\n if (dryRun) {\n result.filesWritten.push(path);\n return;\n }\n await mkdir(path, { recursive: true, mode });\n if (mode) {\n await chmod(path, mode).catch(() => undefined);\n }\n result.filesWritten.push(path);\n}\n\nasync function writeText(\n path: string,\n contents: string,\n opts: { mode?: number; force: boolean; dryRun: boolean },\n result: ScaffoldAccumulator,\n): Promise<void> {\n const existing = await readIfExists(path);\n if (existing === contents) {\n result.filesSkipped.push(path);\n return;\n }\n\n if (existing !== undefined && !opts.force) {\n throw new ZitadelError(\"E_CONFLICT\", `Refusing to overwrite ${path}`, {\n hint: \"Re-run with --force if you want the CLI to replace this file.\",\n details: { path },\n });\n }\n\n if (opts.dryRun) {\n result.filesWritten.push(path);\n return;\n }\n\n await mkdir(dirname(path), { recursive: true });\n const tmp = `${path}.tmp-${process.pid}-${Date.now()}`;\n await writeFile(tmp, contents, { mode: opts.mode });\n if (opts.mode) {\n await chmod(tmp, opts.mode).catch(() => undefined);\n }\n await rename(tmp, path);\n result.filesWritten.push(path);\n}\n\nasync function appendText(\n path: string,\n contents: string,\n ifMissing: string | undefined,\n dryRun: boolean,\n result: ScaffoldAccumulator,\n): Promise<void> {\n const existing = (await readIfExists(path)) ?? \"\";\n if (ifMissing && existing.includes(ifMissing)) {\n result.filesSkipped.push(path);\n return;\n }\n\n const next = `${existing}${existing && !existing.endsWith(\"\\n\") ? \"\\n\" : \"\"}${contents}`;\n if (next === existing) {\n result.filesSkipped.push(path);\n return;\n }\n\n if (dryRun) {\n result.filesWritten.push(path);\n return;\n }\n await mkdir(dirname(path), { recursive: true });\n await writeFile(path, next);\n result.filesWritten.push(path);\n}\n\nasync function mergeEnv(\n path: string,\n entries: Readonly<Record<string, string>>,\n dryRun: boolean,\n result: ScaffoldAccumulator,\n): Promise<void> {\n const existing = (await readIfExists(path)) ?? \"\";\n const present = new Set(\n existing\n .split(/\\r?\\n/g)\n .map((line) => line.match(/^\\s*([A-Za-z_][A-Za-z0-9_]*)=/)?.[1])\n .filter((value): value is string => Boolean(value)),\n );\n const additions = Object.entries(entries).filter(([key]) => !present.has(key));\n if (additions.length === 0) {\n result.filesSkipped.push(path);\n return;\n }\n\n const block = additions.map(([key, value]) => `${key}=${value}`).join(\"\\n\");\n const next = `${existing}${existing && !existing.endsWith(\"\\n\") ? \"\\n\" : \"\"}${block}\\n`;\n if (dryRun) {\n result.filesWritten.push(path);\n return;\n }\n await mkdir(dirname(path), { recursive: true });\n await writeFile(path, next);\n result.filesWritten.push(path);\n}\n\nasync function mergeJson(\n path: string,\n patch: Readonly<Record<string, unknown>>,\n dryRun: boolean,\n result: ScaffoldAccumulator,\n): Promise<void> {\n const existing = await readIfExists(path);\n const current = existing ? parseJsonObject(existing, path) : {};\n const next = deepMerge(current, patch);\n const contents = `${stableStringify(next)}\\n`;\n if (existing === contents) {\n result.filesSkipped.push(path);\n return;\n }\n if (dryRun) {\n result.filesWritten.push(path);\n return;\n }\n await mkdir(dirname(path), { recursive: true });\n await writeFile(path, contents);\n result.filesWritten.push(path);\n}\n\nasync function appendGitignore(\n path: string,\n entries: ReadonlyArray<string>,\n dryRun: boolean,\n result: ScaffoldAccumulator,\n): Promise<void> {\n const existing = (await readIfExists(path)) ?? \"\";\n const lines = new Set(existing.split(/\\r?\\n/g).map((line) => line.trim()));\n const missing = entries.filter((entry) => !lines.has(entry));\n if (missing.length === 0) {\n result.filesSkipped.push(path);\n return;\n }\n const next = `${existing}${existing && !existing.endsWith(\"\\n\") ? \"\\n\" : \"\"}${missing.join(\"\\n\")}\\n`;\n if (dryRun) {\n result.filesWritten.push(path);\n return;\n }\n await writeFile(path, next);\n result.filesWritten.push(path);\n}\n\nasync function addDependency(\n path: string,\n op: { name: string; version: string; dev?: boolean },\n dryRun: boolean,\n result: ScaffoldAccumulator,\n): Promise<void> {\n const existing = await readIfExists(path);\n if (!existing) {\n throw new ZitadelError(\"E_VALIDATION\", \"package.json is required to add Zitadel dependencies\");\n }\n const current = parseJsonObject(existing, path);\n const key = op.dev ? \"devDependencies\" : \"dependencies\";\n const deps = isObject(current[key]) ? (current[key] as Record<string, unknown>) : {};\n if (deps[op.name] === op.version) {\n result.filesSkipped.push(path);\n return;\n }\n current[key] = { ...deps, [op.name]: op.version };\n const contents = `${stableStringify(current)}\\n`;\n if (dryRun) {\n result.filesWritten.push(path);\n result.depsAdded.push(op.name);\n return;\n }\n await writeFile(path, contents);\n result.filesWritten.push(path);\n result.depsAdded.push(op.name);\n}\n\nasync function readIfExists(path: string): Promise<string | undefined> {\n try {\n return await readFile(path, \"utf8\");\n } catch (error) {\n if (typeof error === \"object\" && error !== null && \"code\" in error && error.code === \"ENOENT\") {\n return undefined;\n }\n throw error;\n }\n}\n\nfunction abs(cwd: string, path: string): string {\n return join(cwd, path);\n}\n\nfunction deepMerge(\n target: Record<string, unknown>,\n patch: Readonly<Record<string, unknown>>,\n): Record<string, unknown> {\n const out = { ...target };\n for (const [key, value] of Object.entries(patch)) {\n if (isObject(value) && isObject(out[key])) {\n out[key] = deepMerge(out[key] as Record<string, unknown>, value);\n } else {\n out[key] = value;\n }\n }\n return out;\n}\n","import { MANAGED_MARKER } from \"../../../paths\";\nimport type { FileOp, ScaffoldPlan } from \"./file-writer/types\";\n\n/**\n * The subset of a patcher plan's operations that `doctor --fix` re-applies:\n * env merges, gitignore entries, dependency additions, marker-bearing managed\n * files (framework routes/middleware), and the `edit` transforms — the\n * `/__nextgen` dev proxy merged into `vite.config`/`nuxt.config`/`angular.json`\n * and the Angular `dev` script added to `package.json`. Every `edit` transform\n * is idempotent and only adds what is missing (an existing value is left as-is,\n * the transform returning the source unchanged), so replaying one restores a\n * removed managed block without clobbering the user's own edits. Deliberately\n * excludes the unmarked `.zitadel/` resource writes and `zitadel.json` — those\n * are user-editable and synced by `apply`, so `--fix` must not clobber them.\n *\n * Pure: filters a freshly-allocated list; the input plan is not mutated.\n */\nexport function reclaimableOps(plan: ScaffoldPlan): FileOp[] {\n return plan.ops.filter(\n (op) =>\n op.kind === \"merge-env\" ||\n op.kind === \"append-gitignore\" ||\n op.kind === \"add-dep\" ||\n op.kind === \"edit\" ||\n (op.kind === \"write\" && op.contents.includes(MANAGED_MARKER)),\n );\n}\n","import { stableStringify } from \"../../../json\";\nimport { DEFAULT_SERVER } from \"../../../server\";\nimport { scaffold } from \"./file-writer\";\nimport type { FileOp, ScaffoldPlan } from \"./file-writer/types\";\nimport type {\n EjectActions,\n Patcher,\n PatchContext,\n PatchExecOptions,\n PatchResult,\n PatchView,\n} from \"../types\";\nimport { reclaimableOps } from \"./reclaim\";\n\n/**\n * Base for rule-based (deterministic, template-driven) patchers, as opposed to\n * a future LLM-driven family. It applies the integration by building a\n * file-operation plan and running the file-writer — that strategy stays\n * entirely inside this family, so callers only ever see the family-neutral\n * {@link Patcher} surface. Owns the framework-agnostic `.zitadel/` base files\n * and the shared eject classification; subclasses contribute only their\n * framework-specific routes/middleware.\n */\nexport abstract class AbstractRulePatcher implements Patcher {\n abstract canPatch(framework: string): boolean;\n\n /** Apply the full plan (base `.zitadel/` files + framework routes). */\n async patch(ctx: PatchContext, opts: PatchExecOptions): Promise<PatchResult> {\n return scaffold(this.plan(ctx), opts);\n }\n\n /**\n * Re-apply only the reclaimable subset — env files, gitignore, the SDK\n * dependency, and marker-bearing routes — leaving the user-editable\n * `.zitadel/` resources untouched. Backs `doctor --fix`.\n */\n async repair(ctx: PatchContext, opts: PatchExecOptions): Promise<PatchResult> {\n const plan = this.plan(ctx);\n return scaffold({ ops: reclaimableOps(plan), summary: plan.summary }, opts);\n }\n\n /** Shared base artifacts plus the subclass's marker-bearing route files. */\n artifacts(view: PatchView): EjectActions {\n return {\n markedFiles: this.routeFiles(view),\n rootConfigFiles: [\"zitadel.json\"],\n directories: [\".zitadel\"],\n envBackups: [\".env.local\"],\n dependencies: this.routeDeps(view),\n configEdits: this.routeConfigEdits(view),\n };\n }\n\n /**\n * User config files this patcher merges into via an `edit` op (e.g.\n * `vite.config.ts`). `eject` can't reverse an in-place merge, so it lists\n * these as manual cleanup steps. Defaults to none; patchers that edit a config\n * (React/Vue/Angular/Nuxt) override it. Next writes whole marker-bearing files\n * instead, so it has none.\n */\n protected routeConfigEdits(_view: PatchView): ReadonlyArray<string> {\n return [];\n }\n\n /**\n * The full file-operation plan this patcher would apply. Public so rule-family\n * unit tests can assert the planned ops directly; the generic {@link Patcher}\n * interface deliberately does not expose it (an LLM patcher has no such plan).\n */\n plan(ctx: PatchContext): ScaffoldPlan {\n return {\n ops: [...this.baseOps(ctx), ...this.routeOps(ctx)],\n summary: [this.summary(ctx)],\n };\n }\n\n /**\n * The framework-agnostic `.zitadel/` base files every rule patcher writes:\n * the project secret, `zitadel.json`, env templates, and an empty sync\n * state. The `schemas/` and `flows/` directories are created empty — the\n * server provisions the default user schema and flow definition when the\n * project is created, so nothing is scaffolded into them here. Pure: no\n * filesystem or network.\n */\n private baseOps(ctx: PatchContext): ReadonlyArray<FileOp> {\n return [\n { kind: \"mkdir\", path: \".zitadel\", mode: 0o700 },\n { kind: \"mkdir\", path: \".zitadel/flows\" },\n { kind: \"mkdir\", path: \".zitadel/schemas\" },\n { kind: \"append-gitignore\", entries: [\".zitadel/secret\", \".env*\", \"!.env.example\"] },\n {\n kind: \"write\",\n path: \".zitadel/secret\",\n mode: 0o600,\n contents: `${stableStringify({\n project_id: ctx.project.id,\n project_secret: ctx.project.projectSecret,\n preview_secret: ctx.project.previewSecret,\n preview_origins: ctx.project.previewOrigins,\n created_at: ctx.project.createdAt,\n })}\\n`,\n },\n { kind: \"write\", path: \"zitadel.json\", contents: `${stableStringify(projectConfig(ctx))}\\n` },\n {\n kind: \"merge-env\",\n path: \".env.example\",\n entries: {\n ZITADEL_PROJECT_ID: \"\",\n ZITADEL_ENVIRONMENT: \"\",\n ZITADEL_ISSUER: \"\",\n ZITADEL_URL: \"\",\n },\n },\n {\n kind: \"merge-env\",\n path: \".env.local\",\n entries: {\n ZITADEL_PROJECT_ID: ctx.project.id,\n ZITADEL_ENVIRONMENT: \"development\",\n ZITADEL_ISSUER: ctx.issuer,\n ZITADEL_URL: ctx.server,\n },\n },\n {\n kind: \"write\",\n path: \".zitadel/state.json\",\n contents: `${stableStringify({ framework: ctx.framework.id, resources: {} })}\\n`,\n },\n ];\n }\n\n /** Framework-specific route/middleware write ops plus the SDK dependency. */\n protected abstract routeOps(ctx: PatchContext): ReadonlyArray<FileOp>;\n /** Framework-specific managed (marker-bearing) file paths, for ejection. */\n protected abstract routeFiles(view: PatchView): ReadonlyArray<string>;\n /**\n * The package-manager dependencies the integration added, surfaced in\n * `eject`'s `next_commands` so the user can uninstall them themselves.\n */\n protected abstract routeDeps(view: PatchView): ReadonlyArray<string>;\n /** One-line summary of what the integration scaffolded. */\n protected abstract summary(ctx: PatchContext): { title: string; detail: string };\n}\n\n/** Builds the `zitadel.json` body persisted at the project root. */\nfunction projectConfig(ctx: PatchContext): Record<string, unknown> {\n const environments: Record<string, unknown> = { development: { issuer: ctx.issuer } };\n if (ctx.project.previewOrigins.length > 0) {\n // previewOrigins are already full origins (scheme://host[:port]); don't\n // prepend a scheme or it doubles up (https://http://localhost:3000).\n environments.preview = {\n issuer_pattern: [...ctx.project.previewOrigins],\n };\n }\n return {\n $schema: \"https://schemas.zitadel.com/v2/project.schema.json\",\n project: ctx.project.id,\n server: resolveServerOrigin(ctx.server),\n framework: { id: ctx.framework.id },\n branding: { renderer: ctx.rendererId, attribution: \"visible\" },\n environments,\n };\n}\n\n/** Normalizes a server URL to its origin, falling back to {@link DEFAULT_SERVER}. */\nfunction resolveServerOrigin(source: string): string {\n try {\n return new URL(source).origin;\n } catch {\n return DEFAULT_SERVER;\n }\n}\n","import { ZitadelError } from \"../../../../errors\";\nimport { isObject, parseJsonObject } from \"../../../../json\";\n\n/**\n * Builds the pure `edit` transform the file-writer applies to `angular.json`:\n * wires a dev-server `proxyConfig` (and optional `port`) into the project's\n * `serve` target. The project name is discovered from the file (`defaultProject`,\n * else the sole project) rather than hardcoded, since it varies per app.\n * Idempotent — already-set values are left as-is. Throws `E_VALIDATION` when the\n * file is absent, the project/serve target cannot be located, or the workspace\n * has several projects with no `defaultProject` to disambiguate (rather than\n * guessing and wiring the proxy into an arbitrary one).\n */\nexport function angularProxyEdit(opts: {\n proxyConfig: string;\n port?: number;\n}): (source: string | undefined) => string {\n return (source) => {\n if (source === undefined) {\n throw new ZitadelError(\"E_VALIDATION\", \"Cannot wire Angular proxy: angular.json not found\", {\n hint: \"Run setup from an Angular project.\",\n });\n }\n const root = parseJsonObject(source, \"angular.json\");\n const projects = isObject(root.projects)\n ? (root.projects as Record<string, unknown>)\n : undefined;\n const projectNames = Object.keys(projects ?? {});\n let projectName: string | undefined;\n if (typeof root.defaultProject === \"string\") {\n projectName = root.defaultProject;\n } else if (projectNames.length === 1) {\n projectName = projectNames[0];\n } else if (projectNames.length > 1) {\n throw new ZitadelError(\n \"E_VALIDATION\",\n \"angular.json has multiple projects and no defaultProject to choose from\",\n {\n hint: `Set \"defaultProject\" in angular.json, or add \"proxyConfig\" to the right project's serve target manually. Projects: ${projectNames.join(\", \")}.`,\n },\n );\n }\n const project = projects && projectName ? projects[projectName] : undefined;\n if (!isObject(project)) {\n throw new ZitadelError(\"E_VALIDATION\", \"No project found in angular.json\", {\n hint: 'Add \"proxyConfig\" to your serve target manually.',\n });\n }\n // Angular CLI has used both \"architect\" and \"targets\" for the target map.\n const targets = isObject(project.architect)\n ? (project.architect as Record<string, unknown>)\n : isObject(project.targets)\n ? (project.targets as Record<string, unknown>)\n : undefined;\n const serve =\n targets && isObject(targets.serve) ? (targets.serve as Record<string, unknown>) : undefined;\n if (!serve) {\n throw new ZitadelError(\"E_VALIDATION\", \"No serve target in angular.json\", {\n hint: 'Add \"proxyConfig\" to your serve options manually.',\n });\n }\n const options = isObject(serve.options) ? (serve.options as Record<string, unknown>) : {};\n let changed = false;\n if (options.proxyConfig === undefined) {\n options.proxyConfig = opts.proxyConfig;\n changed = true;\n }\n if (opts.port !== undefined && options.port === undefined) {\n options.port = opts.port;\n changed = true;\n }\n // Nothing to add — return the source untouched so the edit op skips it\n // instead of reformatting (re-indenting) the user's angular.json.\n if (!changed) {\n return source;\n }\n serve.options = options;\n // Preserve the user's key order (JSON, no comments) instead of sorting.\n return `${JSON.stringify(root, null, 2)}\\n`;\n };\n}\n","import { parseModule } from \"magicast\";\n\nimport { ZitadelError } from \"../../../../errors\";\n\n/**\n * Generic magicast helpers shared by the config-editing patchers (Vite, Nuxt).\n * They navigate a module's default export — they carry no framework knowledge\n * beyond \"find the config object literal\" and \"is this import present\".\n */\n\n/**\n * Parses a config file with magicast, throwing a clean `E_VALIDATION` (instead\n * of a raw parse error) when the source is missing or unparseable. `filename` is\n * only used in the error message, so each patcher can name its own config file.\n */\nexport function parseConfigModule(\n source: string | undefined,\n filename: string,\n): ReturnType<typeof parseModule> {\n if (source === undefined) {\n throw new ZitadelError(\"E_VALIDATION\", `Cannot edit ${filename}: file not found`, {\n hint: `Run setup from a project that has ${filename}.`,\n });\n }\n let mod: ReturnType<typeof parseModule>;\n try {\n mod = parseModule(source);\n } catch (error) {\n throw new ZitadelError(\"E_VALIDATION\", `Could not parse ${filename}`, {\n hint: `Ensure ${filename} is valid, or apply the Zitadel changes manually.`,\n details: { cause: error instanceof Error ? error.message : String(error) },\n });\n }\n // A CommonJS config (e.g. a `*.cjs` file or a `*.js` with `module.exports`)\n // can't evaluate the ESM `import`/`import.meta.url` these edits inject, so\n // reject it with a clear message instead of producing a broken config. Check\n // the parsed AST for a real `module.exports`/`exports.x` assignment — scanning\n // raw text would false-positive on the same string in a comment or literal.\n if (hasCommonJsExport(mod)) {\n throw new ZitadelError(\"E_VALIDATION\", `${filename} is a CommonJS module, which can't be edited`, {\n hint: `The Zitadel edits use ESM imports. Convert the config to ESM (a .ts/.mts file, or set \"type\": \"module\"), or add the Zitadel block manually.`,\n });\n }\n return mod;\n}\n\n/**\n * Whether the module has a top-level CommonJS export assignment —\n * `module.exports = …`, `module.exports.x = …`, or `exports.x = …` — read from\n * the parsed AST so comments and string literals can't trigger a false match.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction hasCommonJsExport(mod: any): boolean {\n // magicast's `$ast` may be a babel `File` (with `.program.body`) or the\n // `Program` node itself (`.body`) — handle both.\n const program = mod?.$ast?.program ?? mod?.$ast;\n const body = program?.body ?? [];\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return body.some((node: any) => {\n if (node?.type !== \"ExpressionStatement\" || node.expression?.type !== \"AssignmentExpression\") {\n return false;\n }\n const left = node.expression.left;\n if (left?.type !== \"MemberExpression\") {\n return false;\n }\n const object = left.object;\n // `exports.x = …`\n if (object?.type === \"Identifier\" && object.name === \"exports\") {\n return true;\n }\n // `module.exports = …`\n if (object?.type === \"Identifier\" && object.name === \"module\" && left.property?.name === \"exports\") {\n return true;\n }\n // `module.exports.x = …`\n return (\n object?.type === \"MemberExpression\" &&\n object.object?.name === \"module\" &&\n object.property?.name === \"exports\"\n );\n });\n}\n\n/**\n * Reaches the object literal of a module's default export — the argument of\n * `export default <call>({...})` (e.g. `defineConfig`/`defineNuxtConfig`) or a\n * bare `export default {...}`. Throws `E_VALIDATION` for shapes magicast cannot\n * safely edit (function-form, configs built elsewhere) so the caller can fall\n * back to manual steps.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function resolveDefaultExportObject(mod: any, filename: string): any {\n const def = mod.exports?.default;\n const unreachable = () =>\n new ZitadelError(\"E_VALIDATION\", `Could not locate the config object in ${filename}`, {\n hint: `Add the Zitadel configuration to ${filename} manually (see the SDK README).`,\n });\n if (!def) {\n throw unreachable();\n }\n if (def.$type === \"function-call\") {\n const arg = def.$args?.[0];\n if (!arg || arg.$type !== \"object\") {\n throw unreachable();\n }\n return arg;\n }\n if (def.$type === \"object\") {\n return def;\n }\n throw unreachable();\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function importIsPresent(mod: any, local: string, from?: string): boolean {\n try {\n const items: ReadonlyArray<{ local?: string; from?: string }> = mod.imports?.$items ?? [];\n // Match the source module too when given, so a same-named local imported\n // from a different module isn't mistaken for the one we need.\n return items.some((item) => item.local === local && (from === undefined || item.from === from));\n } catch {\n return false;\n }\n}\n\n/**\n * Appends `item` to a string array at `parent[key]`, creating the array when\n * absent and skipping it when already present. Reads the proxified array by\n * index so primitive elements compare as plain values. Returns `true` when it\n * actually added the item, so callers can tell whether the edit changed\n * anything (and skip rewriting an already-complete config).\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function ensureArrayItem(parent: any, key: string, item: string): boolean {\n if (parent[key] === undefined) {\n parent[key] = [item];\n return true;\n }\n const arr = parent[key];\n // The existing value is something other than an array literal (e.g. an\n // identifier or spread), which magicast cannot safely append to. Surface a\n // clean E_VALIDATION instead of letting `arr.push` throw a raw TypeError.\n if (typeof arr?.push !== \"function\" || typeof arr?.length !== \"number\") {\n throw new ZitadelError(\"E_VALIDATION\", `Could not add \"${item}\" to \"${key}\"`, {\n hint: `Add \"${item}\" to \"${key}\" in your config manually.`,\n });\n }\n const present = Array.from({ length: arr.length as number }, (_unused, i) => arr[i]).includes(\n item,\n );\n if (!present) {\n arr.push(item);\n return true;\n }\n return false;\n}\n\n/**\n * Returns the object literal at `parent[key]`, creating an empty one when\n * absent, so callers can safely descend into it. Throws `E_VALIDATION` when the\n * key already holds something that is not an inline object literal (an\n * identifier, spread, or function call) — magicast cannot edit those, and\n * assigning into them otherwise throws a raw proxy `TypeError`. The object\n * sibling of {@link ensureArrayItem}.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function ensureEditableObject(parent: any, key: string): any {\n if (parent[key] === undefined) {\n parent[key] = {};\n }\n const value = parent[key];\n if (value?.$type !== \"object\") {\n throw new ZitadelError(\"E_VALIDATION\", `Could not edit \"${key}\" in the config`, {\n hint: `Set \"${key}\" to an inline object literal, or add the Zitadel settings manually.`,\n });\n }\n return value;\n}\n","import { builders, generateCode } from \"magicast\";\n\nimport { ZitadelError } from \"../../../../errors\";\nimport { parseConfigModule } from \"../utils/magicast\";\n\nconst AUTH_ROUTE_PATHS = [\"login\", \"register\", \"profile\"] as const;\n\n/**\n * Angular's default `ng new` app enables the router with an empty route table.\n * That router rejects direct `/login` and `/profile` navigations, then rewrites\n * the URL back to `/`. Add componentless routes for the auth paths so the root\n * component can keep rendering based on `window.location.pathname` without\n * requiring a router outlet.\n */\nexport function angularRoutesEdit(): (source: string | undefined) => string {\n return (source) => {\n const label = \"src/app/app.routes.ts\";\n const mod = parseConfigModule(source, label);\n const routes = mod.exports?.routes;\n if (routes?.$type !== \"array\" || typeof routes.push !== \"function\") {\n throw new ZitadelError(\"E_VALIDATION\", \"Cannot wire Angular auth routes\", {\n hint: `Set \"routes\" in ${label} to an inline Routes array, or add /login, /register, and /profile manually.`,\n });\n }\n\n const present = new Set(\n Array.from({ length: routes.length as number }, (_unused, index) => routes[index]?.path).filter(\n (path): path is string => typeof path === \"string\",\n ),\n );\n let changed = false;\n for (const path of AUTH_ROUTE_PATHS) {\n if (present.has(path)) {\n continue;\n }\n routes.push(builders.raw(`{ path: ${JSON.stringify(path)}, children: [] }`));\n changed = true;\n }\n\n if (!changed && source !== undefined) {\n return source;\n }\n const code = generateCode(mod).code;\n return code.endsWith(\"\\n\") ? code : `${code}\\n`;\n };\n}\n","/**\n * The same-origin path the SDK widgets call (`configureZitadel({ proxyPath })`),\n * which every framework's dev proxy forwards to the backend. Framework-agnostic:\n * Vite (React/Vue), Angular's dev-server proxy, and Nuxt's server middleware all\n * key off the same prefix, so it lives here rather than in any one framework's\n * patcher.\n */\nexport const PROXY_PATH = \"/__nextgen\";\n","import { MANAGED_MARKER } from \"../../../../paths\";\nimport { PROXY_PATH } from \"../proxy\";\n\n/**\n * The managed root component `src/app/app.ts`: a standalone component that\n * renders the `@zitadel/sdk-angular` widgets based on the current path. The\n * project id (public, not secret) is inlined; the dev proxy in `proxy.conf.cjs`\n * attaches the `sk_<project_id>` bearer (derived from that public id)\n * server-side, and no secret reaches the browser.\n */\nexport function appComponentTemplate(projectId: string): string {\n return `${MANAGED_MARKER}\nimport { Component } from \"@angular/core\";\nimport {\n ZitadelLoginComponent,\n ZitadelLogoutComponent,\n configureZitadel,\n} from \"@zitadel/sdk-angular\";\n\n@Component({\n selector: \"app-root\",\n standalone: true,\n imports: [ZitadelLoginComponent, ZitadelLogoutComponent],\n templateUrl: \"./app.html\",\n})\nexport class App {\n protected readonly project = configureZitadel({\n projectId: ${JSON.stringify(projectId)},\n proxyPath: \"${PROXY_PATH}\",\n });\n protected readonly path = window.location.pathname;\n}\n`;\n}\n\n/**\n * The managed `src/app/app.html`. The marker lives in an HTML comment that still\n * contains the literal managed-marker text, so eject/doctor stay marker-aware.\n */\nexport function appTemplateHtml(): string {\n return `<!-- ${MANAGED_MARKER} -->\n@if (path.startsWith('/profile')) {\n <zitadel-auth-logout [project]=\"project\" [postSignOutUrl]=\"'/login'\"></zitadel-auth-logout>\n} @else if (path.startsWith('/register')) {\n <zitadel-auth-login\n [project]=\"project\"\n purpose=\"register\"\n [postSignInUrl]=\"'/profile'\"\n ></zitadel-auth-login>\n} @else {\n <zitadel-auth-login\n [project]=\"project\"\n purpose=\"login\"\n [postSignInUrl]=\"'/profile'\"\n ></zitadel-auth-login>\n}\n`;\n}\n\n/**\n * The managed `proxy.conf.cjs` for `ng serve`: forwards `/__nextgen/*` to the\n * backend (from `zitadel.json`), strips the prefix, and attaches the project's\n * `sk_<project_id>` bearer to every proxied request. The prefix strip and the\n * bearer are each provided in both the http-proxy-middleware form\n * (`pathRewrite`/`onProxyReq`) and the Vite form (`rewrite`/`configure`), so\n * both fire whichever proxy layer Angular's dev server uses.\n */\nexport function proxyConfTemplate(): string {\n return `${MANAGED_MARKER}\nconst { readFileSync } = require(\"node:fs\");\n\nconst config = JSON.parse(readFileSync(\"zitadel.json\", \"utf8\"));\nif (!config.project || !config.server) {\n throw new Error(\"zitadel.json is missing \\\\\"project\\\\\" or \\\\\"server\\\\\"; re-run zitadel setup.\");\n}\nconst bearer = \\`Bearer sk_\\${config.project}\\`;\n\nfunction setBearer(proxyReq) {\n proxyReq.setHeader(\"authorization\", bearer);\n}\n\nfunction stripPrefix(path) {\n return path.replace(/^\\\\${PROXY_PATH}/, \"\").replace(/^(?!\\\\/)/, \"/\");\n}\n\nmodule.exports = {\n \"${PROXY_PATH}\": {\n target: config.server,\n changeOrigin: false,\n pathRewrite: stripPrefix,\n rewrite: stripPrefix,\n onProxyReq: setBearer,\n configure: (proxy) => proxy.on(\"proxyReq\", setBearer),\n },\n};\n`;\n}\n","import { ZitadelError } from \"../../../../errors\";\nimport { isObject, parseJsonObject, stableStringify } from \"../../../../json\";\nimport { npmDistTagForCliVersion } from \"../../../../public-cli\";\nimport type { FileOp } from \"../file-writer/types\";\nimport type { PatchContext, PatchView } from \"../../types\";\nimport { AbstractRulePatcher } from \"../base\";\nimport { angularProxyEdit } from \"./angular-json\";\nimport { angularRoutesEdit } from \"./angular-routes\";\nimport { appComponentTemplate, appTemplateHtml, proxyConfTemplate } from \"./templates\";\n\nconst SDK_DEPENDENCY = \"@zitadel/sdk-angular\";\n\n/**\n * Adds a `dev: \"ng serve\"` script only when the project does not already define\n * one. `ng new` ships only a `start` script, but the CLI tells every framework\n * to run `npm run dev` (and `ng serve` reads the proxy + port from\n * `angular.json`). Non-destructive: an existing `dev` script is preserved, so\n * patching a project that already wires its own `dev` leaves it untouched.\n */\nfunction ensureDevScript(source: string | undefined): string {\n if (source === undefined) {\n throw new ZitadelError(\"E_VALIDATION\", \"package.json is required to add the dev script\", {\n hint: \"Run setup from a project that has a package.json.\",\n });\n }\n const pkg = parseJsonObject(source, \"package.json\");\n const scripts = isObject(pkg.scripts) ? pkg.scripts : undefined;\n // Leave an existing dev script untouched, returning the source unchanged so\n // the edit op skips the file instead of reformatting the user's package.json.\n if (scripts?.dev !== undefined) {\n return source;\n }\n pkg.scripts = { ...(scripts ?? {}), dev: \"ng serve\" };\n return `${stableStringify(pkg)}\\n`;\n}\n\n/**\n * Rule-based patcher for an Angular app. Inherits the shared `.zitadel/` base\n * files from {@link AbstractRulePatcher} and contributes the managed root\n * component (`app.ts`/`app.html`) that renders the `@zitadel/sdk-angular`\n * widgets, a `proxy.conf.cjs` dev proxy (attaching the `sk_<project_id>` bearer\n * to every proxied request) wired into `angular.json`, and the SDK dep.\n *\n * Unlike React/Vue (whose dev proxy lives in `vite.config.ts`), Angular owns its\n * Vite config, so the proxy is a separate `proxy.conf.cjs` referenced from the\n * `serve` target. Production still needs `@zitadel/edge-proxy`.\n */\nexport class AngularPatcher extends AbstractRulePatcher {\n canPatch(framework: string): boolean {\n return framework === \"angular\";\n }\n\n protected routeOps(ctx: PatchContext): FileOp[] {\n return [\n {\n kind: \"write\",\n path: \"src/app/app.ts\",\n contents: appComponentTemplate(ctx.project.id),\n },\n { kind: \"write\", path: \"src/app/app.html\", contents: appTemplateHtml() },\n { kind: \"edit\", path: \"src/app/app.routes.ts\", edit: angularRoutesEdit() },\n { kind: \"write\", path: \"proxy.conf.cjs\", contents: proxyConfTemplate() },\n {\n kind: \"edit\",\n path: \"angular.json\",\n edit: angularProxyEdit({ proxyConfig: \"proxy.conf.cjs\", port: ctx.framework.devPort }),\n },\n { kind: \"edit\", path: \"package.json\", edit: ensureDevScript },\n {\n kind: \"add-dep\",\n name: SDK_DEPENDENCY,\n version: npmDistTagForCliVersion(ctx.cliVersion),\n },\n ];\n }\n\n protected routeFiles(_view: PatchView): ReadonlyArray<string> {\n return [\"src/app/app.ts\", \"src/app/app.html\", \"proxy.conf.cjs\"];\n }\n\n protected routeDeps(_view: PatchView): ReadonlyArray<string> {\n return [SDK_DEPENDENCY];\n }\n\n protected override routeConfigEdits(_view: PatchView): ReadonlyArray<string> {\n // These files are touched via `edit` ops eject can't auto-revert: the proxy\n // wired into angular.json, auth paths added to app.routes.ts, and the `dev`\n // script added to package.json.\n return [\"angular.json\", \"src/app/app.routes.ts\", \"package.json\"];\n }\n\n protected summary(_ctx: PatchContext): { title: string; detail: string } {\n return {\n title: \"Angular integration\",\n detail:\n \"Wrote the app root component + proxy.conf.cjs, added auth routes, and wired the /__nextgen dev proxy into angular.json.\",\n };\n }\n}\n","import { MANAGED_MARKER } from \"../../../../../../paths\";\nimport type { RendererSpec } from \"../types\";\n\n/**\n * Placeholder renderer for the `<zitadel-flow>` Lit web component. Declared\n * so the `web-component` renderer id resolves and surfaces a clear\n * \"not yet published\" error, while reserving the integration shape for when\n * `@zitadel/ui-lit` ships. The `authPage` template emits an illustrative\n * page only; this renderer is never selected for real scaffolding because\n * `getRenderer` rejects any `status: \"not-implemented\"` spec.\n */\nexport const litRenderer: RendererSpec = {\n id: \"web-component\",\n displayName: \"Web component (<zitadel-flow>)\",\n status: \"not-implemented\",\n frameworks: [\"next\", \"astro\", \"remix\", \"sveltekit\", \"nuxt\", \"vanilla\"],\n dependency: { name: \"@zitadel/ui-lit\", version: \"workspace:*\" },\n templates: {\n authPage(mode) {\n const purpose = mode === \"login\" ? \"login\" : \"register\";\n return {\n mode,\n contents: `${MANAGED_MARKER}\n// The web component renderer ships a <zitadel-flow> element. Until\n// @zitadel/ui-lit is published, this template only declares the\n// intended integration point. See docs/design/cli/bdui-renderer.md.\nimport \"@zitadel/ui-lit\";\n\nconst environment =\n process.env.ZITADEL_ENVIRONMENT ??\n (process.env.NODE_ENV === \"production\" ? \"production\" : \"development\");\n\nexport default function ${mode === \"login\" ? \"LoginPage\" : \"RegisterPage\"}() {\n return (\n <zitadel-flow\n purpose=\"${purpose}\"\n project-id={process.env.ZITADEL_PROJECT_ID}\n issuer={process.env.ZITADEL_ISSUER}\n environment={environment}\n />\n );\n}\n`,\n };\n },\n },\n};\n","import { MANAGED_MARKER } from \"../../../../../../paths\";\nimport type { RendererSpec } from \"../types\";\n\n/**\n * The Next.js App Router renderer scaffolds `/login`, `/register`, and\n * `/profile` pages that drive the `<zitadel-login>` and `<zitadel-logout>`\n * Lit web components.\n *\n * Each page is a single client component (`\"use client\"`) that, inside a\n * `next/dynamic({ ssr: false })` loader, builds the SDK project handle with\n * `configureZitadel({ projectId, proxyPath: \"/__nextgen\" })` and passes it to\n * the widget via `project={...}`. It also imports\n * `@zitadel/sdk-next/client` for its `customElements.define`\n * side-effect — importing `@zitadel/components` directly would fail on\n * strict-resolution package managers (pnpm, yarn PnP) because the app only\n * declares `sdk-next` as a direct dep. SSR is disabled because Lit's element\n * registration needs a browser.\n *\n * The handle is passed as the `project` DOM property, which relies on React\n * 19's custom-element property binding (the scaffold targets the latest Next /\n * React). The backend URL never reaches the browser: the client talks to the\n * same-origin `/__nextgen` proxy path, and the scaffolded Next request boundary\n * forwards it to `ZITADEL_URL` server-side. `NEXT_PUBLIC_ZITADEL_PROJECT_ID` is\n * public — the project id is not sensitive and the widget needs it to start a\n * flow.\n */\nexport const reactRenderer: RendererSpec = {\n id: \"react\",\n displayName: \"React (Next.js App Router)\",\n status: \"available\",\n frameworks: [\"next\"],\n dependency: { name: \"@zitadel/sdk-next\", version: \"latest\" },\n templates: {\n authPage(mode) {\n const componentName = mode === \"login\" ? \"LoginPage\" : \"RegisterPage\";\n const elementName = mode === \"login\" ? \"ZitadelLogin\" : \"ZitadelRegister\";\n return {\n mode,\n contents: `${MANAGED_MARKER}\n\"use client\";\n\nimport dynamic from \"next/dynamic\";\nimport Link from \"next/link\";\n\nconst ${elementName} = dynamic(\n async () => {\n const { configureZitadel } = await import(\"@zitadel/sdk-next/client\");\n // Build the SDK project handle and pass it to the component via the\n // \\`project\\` prop. The component reads config from this prop directly, so\n // it works regardless of how the SDK packages are bundled. The backend URL\n // stays server-side: requests go through the proxy path \"/__nextgen\",\n // which the scaffolded request boundary forwards to the Zitadel server.\n const project = configureZitadel({\n projectId: process.env.NEXT_PUBLIC_ZITADEL_PROJECT_ID ?? \"\",\n proxyPath: \"/__nextgen\",\n });\n return function ${elementName}Element() {\n return (\n <zitadel-login\n project={project}\n purpose=\"${mode}\"\n post-sign-in-url=\"/profile\"\n />\n );\n };\n },\n { ssr: false },\n);\n\nexport default function ${componentName}() {\n return (\n <main style={{ minHeight: \"100vh\", position: \"relative\", background: \"#0f0f11\" }}>\n <nav aria-label=\"Authentication\" style={{ position: \"absolute\", top: \"24px\", right: \"24px\", zIndex: 1, display: \"flex\", gap: \"12px\" }}>\n <Link href=\"${mode === \"login\" ? \"/register\" : \"/login\"}\" style={{ color: \"#f4f4f6\", fontWeight: 700, textDecoration: \"none\" }}>\n ${mode === \"login\" ? \"Create account\" : \"Sign in\"}\n </Link>\n </nav>\n <${elementName} />\n </main>\n );\n}\n`,\n };\n },\n profilePage() {\n return {\n contents: `${MANAGED_MARKER}\n\"use client\";\n\nimport dynamic from \"next/dynamic\";\nimport { useEffect, useState } from \"react\";\n\ntype SessionProof = {\n session_id?: string;\n state?: string;\n user_id?: string;\n};\n\nconst ZitadelLogout = dynamic(\n async () => {\n const { configureZitadel } = await import(\"@zitadel/sdk-next/client\");\n const project = configureZitadel({\n projectId: process.env.NEXT_PUBLIC_ZITADEL_PROJECT_ID ?? \"\",\n proxyPath: \"/__nextgen\",\n });\n return function ZitadelLogoutElement() {\n return (\n <zitadel-logout\n project={project}\n post-sign-out-url=\"/login\"\n />\n );\n };\n },\n { ssr: false },\n);\n\nexport default function ProfilePage() {\n const [session, setSession] = useState<SessionProof | null>(null);\n const [sessionError, setSessionError] = useState(\"\");\n\n useEffect(() => {\n let cancelled = false;\n\n fetch(\"/__nextgen/sessions/me\", { cache: \"no-store\" })\n .then(async (response) => {\n if (!response.ok) {\n throw new Error(\"Session check failed: \" + String(response.status));\n }\n return response.json() as Promise<SessionProof>;\n })\n .then((nextSession) => {\n if (!cancelled) {\n setSession(nextSession);\n }\n })\n .catch((error: unknown) => {\n if (!cancelled) {\n setSessionError(error instanceof Error ? error.message : \"Session check failed\");\n }\n });\n\n return () => {\n cancelled = true;\n };\n }, []);\n\n return (\n <main style={{ padding: \"48px\", maxWidth: \"680px\", margin: \"0 auto\" }}>\n <div style={{ display: \"flex\", alignItems: \"center\", justifyContent: \"space-between\", marginBottom: \"24px\" }}>\n <h1 style={{ fontSize: \"24px\", fontWeight: 700, margin: 0 }}>Signed in</h1>\n <ZitadelLogout />\n </div>\n <p style={{ color: \"#166534\", fontWeight: 600 }}>Signed in profile loaded.</p>\n {session ? (\n <dl style={{ display: \"grid\", gap: \"12px\", marginTop: \"24px\" }}>\n <div>\n <dt style={{ color: \"#6b7280\", fontSize: \"14px\" }}>Session state</dt>\n <dd style={{ margin: 0, fontWeight: 600 }}>{session.state ?? \"active\"}</dd>\n </div>\n <div>\n <dt style={{ color: \"#6b7280\", fontSize: \"14px\" }}>User id</dt>\n <dd style={{ margin: 0, fontFamily: \"monospace\" }}>{session.user_id ?? \"available\"}</dd>\n </div>\n </dl>\n ) : (\n <p style={{ color: sessionError ? \"#b91c1c\" : \"#6b7280\" }}>\n {sessionError || \"Checking session...\"}\n </p>\n )}\n </main>\n );\n}\n`,\n };\n },\n customElementsDts() {\n return {\n contents: `${MANAGED_MARKER}\nimport type React from \"react\";\nimport type { ZitadelProject } from \"@zitadel/sdk-next/client\";\n\ndeclare module \"react\" {\n namespace JSX {\n interface IntrinsicElements {\n \"zitadel-login\": React.HTMLAttributes<HTMLElement> & {\n project?: ZitadelProject;\n \"session-exchange-path\"?: string;\n \"post-sign-in-url\"?: string;\n purpose?: string;\n };\n \"zitadel-logout\": React.HTMLAttributes<HTMLElement> & {\n project?: ZitadelProject;\n \"post-sign-out-url\"?: string;\n };\n }\n }\n}\n`,\n };\n },\n },\n};\n","import { ZitadelError } from \"../../../../../errors\";\nimport { litRenderer } from \"./lit\";\nimport { reactRenderer } from \"./react\";\nimport type { RendererId, RendererSpec } from \"./types\";\n\n/**\n * Runtime mirror of the {@link RendererId} union, used by {@link isRendererId}\n * to validate untrusted strings (a TS union has no runtime presence). Must stay\n * in sync with the {@link RendererId} type.\n */\nexport const RENDERER_IDS: RendererId[] = [\"react\", \"web-component\"];\n\n/**\n * Type guard narrowing an arbitrary value to a {@link RendererId}, used to\n * validate renderer ids read from config before indexing {@link RENDERERS}.\n */\nexport function isRendererId(value: unknown): value is RendererId {\n return typeof value === \"string\" && (RENDERER_IDS as string[]).includes(value);\n}\n\n/**\n * The single source of truth mapping each {@link RendererId} to its spec.\n * Keyed by id so {@link getRenderer} can look up and validate a renderer\n * chosen from persisted config (an arbitrary string) at runtime.\n */\nexport const RENDERERS: Record<RendererId, RendererSpec> = {\n react: reactRenderer,\n \"web-component\": litRenderer,\n};\n\n/**\n * Resolves a renderer id (an untrusted string from config) to its spec,\n * throwing a typed {@link ZitadelError} rather than returning `undefined`\n * so callers get an actionable message. Rejects ids that are unknown\n * (`E_VALIDATION`) or declared-but-unpublished (`E_NOT_IMPLEMENTED`),\n * guaranteeing the returned spec is safe to scaffold from.\n */\nexport function getRenderer(id: string): RendererSpec {\n if (!isRendererId(id)) {\n throw new ZitadelError(\"E_VALIDATION\", `Unknown renderer \"${id}\"`, {\n hint: `Available renderers: ${Object.keys(RENDERERS).join(\", \")}`,\n });\n }\n const renderer = RENDERERS[id];\n if (renderer.status === \"not-implemented\") {\n throw new ZitadelError(\n \"E_NOT_IMPLEMENTED\",\n `Renderer \"${id}\" is declared but not yet published`,\n {\n hint: \"Use --renderer react for now; the <zitadel-flow> web component ships in a later package.\",\n },\n );\n }\n return renderer;\n}\n","import { join } from \"node:path\";\n\nimport { MANAGED_MARKER } from \"../../../../paths\";\nimport type { FileOp } from \"../file-writer/types\";\nimport type { PatchContext, PatchView } from \"../../types\";\nimport { AbstractRulePatcher } from \"../base\";\nimport { getRenderer } from \"./renderers/registry\";\nimport type { RendererSpec } from \"./renderers/types\";\n\n/**\n * Next.js request-boundary file at the project root. Wires `nextgenMiddleware` so the\n * generated project config's `/__nextgen` proxy path is same-origin proxied\n * to `ZITADEL_URL` and `/profile` is gated. Next 16 renamed this convention to\n * `proxy.ts`; older projects keep `middleware.ts`.\n * Carries the managed marker so `doctor --fix` reclaims it and `eject` removes it.\n */\nfunction requestBoundaryTemplate(functionName: \"middleware\" | \"proxy\"): string {\n return `${MANAGED_MARKER}\nimport { nextgenMiddleware } from \"@zitadel/sdk-next/middleware\";\nimport type { NextRequest } from \"next/server\";\n\nexport function ${functionName}(req: NextRequest) {\n return nextgenMiddleware(req, {\n url: process.env.ZITADEL_URL,\n protectedRoutes: [\"/profile\"],\n loginPath: \"/login\",\n });\n}\n\nexport const config = {\n matcher: [\"/__nextgen/:path*\", \"/profile/:path*\"],\n};\n`;\n}\n\n/**\n * Rule-based patcher for the Next.js App Router. Inherits the shared\n * `.zitadel/` base files from {@link AbstractRulePatcher} and contributes the\n * Next routes and request boundary whose templates come from the chosen renderer.\n */\nexport class NextPatcher extends AbstractRulePatcher {\n /** Returns true for Next.js projects. */\n canPatch(framework: string): boolean {\n return framework === \"next\";\n }\n\n protected routeOps(ctx: PatchContext): FileOp[] {\n return nextCodeOps(ctx, getRenderer(ctx.rendererId));\n }\n\n protected routeFiles(view: PatchView): ReadonlyArray<string> {\n return nextCodeFilePaths(view.framework, getRenderer(view.rendererId));\n }\n\n protected routeDeps(view: PatchView): ReadonlyArray<string> {\n return [getRenderer(view.rendererId).dependency.name];\n }\n\n protected summary(ctx: PatchContext): { title: string; detail: string } {\n return {\n title: \"Next.js integration\",\n detail: `Scaffolded login/register/profile routes with renderer \"${ctx.rendererId}\".`,\n };\n }\n}\n\n/**\n * Ordered paths of the framework code files the patcher writes. All carry the\n * managed marker. Shared by {@link NextPatcher.routeOps} (which adds contents)\n * and {@link NextPatcher.routeFiles} (which only needs the paths) so the two\n * cannot drift.\n */\nfunction nextCodeFilePaths(\n framework: PatchView[\"framework\"],\n renderer: RendererSpec,\n): ReadonlyArray<string> {\n const appDir = framework.appDir;\n const paths = [\n join(appDir, \"page.tsx\"),\n join(appDir, \"login/page.tsx\"),\n join(appDir, \"register/page.tsx\"),\n ];\n if (renderer.templates.profilePage) {\n paths.push(join(appDir, \"profile/page.tsx\"));\n }\n paths.push(join(appDir, `../${requestBoundaryFile(framework).filename}`));\n if (renderer.templates.provider) {\n paths.push(join(appDir, renderer.templates.provider.filename));\n }\n if (renderer.templates.customElementsDts) {\n paths.push(join(appDir, \"../custom-elements.d.ts\"));\n }\n return paths;\n}\n\n/** The Next route/request-boundary write ops plus the SDK dependency. */\nfunction nextCodeOps(ctx: PatchContext, renderer: RendererSpec): FileOp[] {\n const appDir = ctx.framework.appDir;\n const profile = renderer.templates.profilePage?.();\n const provider = renderer.templates.provider;\n const dts = renderer.templates.customElementsDts?.();\n const boundary = requestBoundaryFile(ctx.framework);\n return [\n ctx.scaffoldedFramework\n ? {\n kind: \"edit\",\n path: join(appDir, \"page.tsx\"),\n edit: () => homePageTemplate(),\n }\n : undefined,\n {\n kind: \"write\",\n path: join(appDir, \"login/page.tsx\"),\n contents: renderer.templates.authPage(\"login\").contents,\n },\n {\n kind: \"write\",\n path: join(appDir, \"register/page.tsx\"),\n contents: renderer.templates.authPage(\"register\").contents,\n },\n profile\n ? { kind: \"write\", path: join(appDir, \"profile/page.tsx\"), contents: profile.contents }\n : undefined,\n {\n kind: \"write\",\n path: join(appDir, `../${boundary.filename}`),\n contents: requestBoundaryTemplate(boundary.functionName),\n },\n provider\n ? { kind: \"write\", path: join(appDir, provider.filename), contents: provider.contents }\n : undefined,\n dts\n ? { kind: \"write\", path: join(appDir, \"../custom-elements.d.ts\"), contents: dts.contents }\n : undefined,\n // Next.js exposes NEXT_PUBLIC_-prefixed vars to client code.\n { kind: \"merge-env\", path: \".env.example\", entries: { NEXT_PUBLIC_ZITADEL_PROJECT_ID: \"\" } },\n {\n kind: \"merge-env\",\n path: \".env.local\",\n entries: { NEXT_PUBLIC_ZITADEL_PROJECT_ID: ctx.project.id },\n },\n {\n kind: \"add-dep\",\n name: renderer.dependency.name,\n version: dependencyVersionForCli(ctx.cliVersion, renderer.dependency.version),\n },\n ].filter((op): op is FileOp => op !== undefined);\n}\n\nfunction homePageTemplate(): string {\n return `${MANAGED_MARKER}\nimport Link from \"next/link\";\n\nexport default function Home() {\n return (\n <main style={{ minHeight: \"100vh\", padding: \"48px\", display: \"flex\", alignItems: \"center\", justifyContent: \"center\" }}>\n <section style={{ width: \"100%\", maxWidth: \"560px\" }}>\n <p style={{ margin: \"0 0 12px\", color: \"#4b5563\", fontSize: \"14px\" }}>Zitadel auth</p>\n <h1 style={{ margin: \"0 0 24px\", fontSize: \"32px\", lineHeight: 1.15 }}>Sign in, create an account, or open your profile.</h1>\n <div style={{ display: \"flex\", flexWrap: \"wrap\", gap: \"12px\" }}>\n <Link href=\"/login\" style={{ padding: \"10px 16px\", borderRadius: \"8px\", background: \"#111827\", color: \"#ffffff\", textDecoration: \"none\", fontWeight: 600 }}>\n Sign in\n </Link>\n <Link href=\"/register\" style={{ padding: \"10px 16px\", borderRadius: \"8px\", border: \"1px solid #d1d5db\", color: \"#111827\", textDecoration: \"none\", fontWeight: 600 }}>\n Create account\n </Link>\n <Link href=\"/profile\" style={{ padding: \"10px 16px\", borderRadius: \"8px\", border: \"1px solid #d1d5db\", color: \"#111827\", textDecoration: \"none\", fontWeight: 600 }}>\n Profile\n </Link>\n </div>\n </section>\n </main>\n );\n}\n`;\n}\n\nfunction requestBoundaryFile(framework: PatchContext[\"framework\"]): {\n filename: \"middleware.ts\" | \"proxy.ts\";\n functionName: \"middleware\" | \"proxy\";\n} {\n if ((framework.versionMajor ?? 0) >= 16) {\n return { filename: \"proxy.ts\", functionName: \"proxy\" };\n }\n return { filename: \"middleware.ts\", functionName: \"middleware\" };\n}\n\nfunction dependencyVersionForCli(cliVersion: string, fallback: string): string {\n const normalized = cliVersion.trim().replace(/^v/, \"\");\n if (/^\\d+\\.\\d+\\.\\d+-alpha\\.\\d+$/.test(normalized)) {\n return normalized;\n }\n const prerelease = normalized.match(/^\\d+\\.\\d+\\.\\d+-([0-9A-Za-z]+)(?:[.-]|$)/)?.[1];\n return prerelease ?? fallback;\n}\n","/**\n * The module extensions the config edits can actually write, in resolution\n * priority. magicast injects ESM `import`/`import.meta.url`, so only ESM-capable\n * extensions are editable; CommonJS (`cts`/`cjs`) is not.\n */\nconst CONFIG_EXTENSIONS = [\"ts\", \"mts\", \"js\", \"mjs\"] as const;\n\n/**\n * The CommonJS extensions we still *probe* (after the ESM ones) so a project\n * whose only config is `*.cjs`/`*.cts` is found and rejected with a targeted\n * \"CommonJS is unsupported\" error, rather than a misleading \"file not found\".\n * {@link parseConfigModule} surfaces that error when it sees CommonJS source.\n */\nconst COMMONJS_EXTENSIONS = [\"cts\", \"cjs\"] as const;\n\n/**\n * Candidate config filenames for `basename`, ESM extensions first then the\n * CommonJS ones, e.g. `configCandidates(\"vite.config\")` → `[\"vite.config.ts\",\n * \"vite.config.mts\", \"vite.config.js\", \"vite.config.mjs\", \"vite.config.cts\",\n * \"vite.config.cjs\"]`. Handed to the\n * generic `edit` file-op, which patches the first one that exists — an ESM\n * config wins, and a CommonJS-only project is still read so the edit can emit a\n * clear unsupported-format error.\n */\nexport function configCandidates(basename: string): string[] {\n return [...CONFIG_EXTENSIONS, ...COMMONJS_EXTENSIONS].map((ext) => `${basename}.${ext}`);\n}\n","import { builders, generateCode } from \"magicast\";\n\nimport {\n ensureArrayItem,\n ensureEditableObject,\n parseConfigModule,\n resolveDefaultExportObject,\n} from \"../utils/magicast\";\nimport { PROXY_PATH } from \"../proxy\";\n\nconst NUXT_MODULE = \"@zitadel/sdk-nuxt/module\";\n\n/**\n * Builds the pure `edit` transform the file-writer applies to the project's Nuxt\n * config (`nuxt.config.*`): registers the `@zitadel/sdk-nuxt` module (which wires\n * the server-side proxy + session middleware), sets the login path, seeds\n * `runtimeConfig` with the backend URL, the proxy path, and the project id, and\n * marks the `zitadel-*` Lit elements as custom elements for the Vue compiler —\n * preserving the user's existing config via magicast. Idempotent. Throws\n * `E_VALIDATION` when the file is absent or `defineNuxtConfig` cannot be reached.\n */\nexport function nuxtConfigEdit(opts: {\n projectId: string;\n server: string;\n}): (source: string | undefined) => string {\n return (source) => {\n const label = \"the Nuxt config (nuxt.config.*)\";\n const mod = parseConfigModule(source, label);\n const config = resolveDefaultExportObject(mod, label);\n\n let changed = ensureArrayItem(config, \"modules\", NUXT_MODULE);\n\n const nextgen = ensureEditableObject(config, \"nextgen\");\n if (nextgen.url === undefined) {\n nextgen.url = builders.raw(\n `process.env.ZITADEL_URL ?? ${JSON.stringify(opts.server)}`,\n );\n changed = true;\n }\n if (nextgen.loginPath === undefined) {\n nextgen.loginPath = \"/login\";\n changed = true;\n }\n if (nextgen.protectedRoutes === undefined) {\n nextgen.protectedRoutes = [\"/profile\"];\n changed = true;\n }\n\n const runtimeConfig = ensureEditableObject(config, \"runtimeConfig\");\n if (runtimeConfig.zitadelUrl === undefined) {\n runtimeConfig.zitadelUrl = builders.raw(\n `process.env.ZITADEL_URL ?? ${JSON.stringify(opts.server)}`,\n );\n changed = true;\n }\n const publicConfig = ensureEditableObject(runtimeConfig, \"public\");\n if (publicConfig.nextgenProxyPath === undefined) {\n publicConfig.nextgenProxyPath = PROXY_PATH;\n changed = true;\n }\n if (publicConfig.zitadelProjectId === undefined) {\n publicConfig.zitadelProjectId = builders.raw(\n `process.env.NUXT_PUBLIC_ZITADEL_PROJECT_ID ?? ${JSON.stringify(opts.projectId)}`,\n );\n changed = true;\n }\n\n // The Lit components and their style/token deps must be transpiled for SSR\n // (matching the repo's own demo-nuxt config) or the build fails on the\n // untranspiled ESM those transitive packages ship.\n const build = ensureEditableObject(config, \"build\");\n for (const dep of [\n \"@zitadel/api\",\n \"@zitadel/components\",\n \"@zitadel/shared-component-styles\",\n \"@zitadel/design-tokens\",\n ]) {\n if (ensureArrayItem(build, \"transpile\", dep)) {\n changed = true;\n }\n }\n\n // Tell Vue's template compiler the `zitadel-*` Lit elements are custom\n // elements, not Vue components, so it renders them as native elements\n // instead of logging \"Failed to resolve component\" and mis-binding props.\n const vue = ensureEditableObject(config, \"vue\");\n const compilerOptions = ensureEditableObject(vue, \"compilerOptions\");\n if (compilerOptions.isCustomElement === undefined) {\n compilerOptions.isCustomElement = builders.raw(`(tag) => tag.startsWith(\"zitadel-\")`);\n changed = true;\n }\n\n // Nothing was missing — return the source untouched so the file-writer skips\n // it instead of letting magicast reformat an already-patched config.\n if (!changed && source !== undefined) {\n return source;\n }\n const code = generateCode(mod).code;\n return code.endsWith(\"\\n\") ? code : `${code}\\n`;\n };\n}\n","import { MANAGED_MARKER } from \"../../../../paths\";\n\nconst MAIN_STYLE =\n \"min-height: 100vh; background: #0f0f11\";\n\n/** `app.vue` — renders the page router. Marker in an HTML comment. */\nexport function appVueTemplate(): string {\n return `<!-- ${MANAGED_MARKER} -->\n<template>\n <NuxtPage />\n</template>\n\n<style>\nbody {\n margin: 0;\n font-family: sans-serif;\n}\n</style>\n`;\n}\n\n/** A login/register page rendering `<zitadel-login>` inside `<ClientOnly>`. */\nfunction authPage(purpose: \"login\" | \"register\"): string {\n const purposeAttr = purpose === \"register\" ? '\\n purpose=\"register\"' : \"\";\n return `<script setup lang=\"ts\">\n${MANAGED_MARKER}\nimport { useZitadelProject } from \"@zitadel/sdk-nuxt\";\n\nconst project = useZitadelProject();\n</script>\n\n<template>\n <main style=\"${MAIN_STYLE}\">\n <ClientOnly>\n <zitadel-login\n :project=\"project\"${purposeAttr}\n post-sign-in-url=\"/profile\"\n />\n </ClientOnly>\n </main>\n</template>\n`;\n}\n\nexport function loginPageTemplate(): string {\n return authPage(\"login\");\n}\n\nexport function registerPageTemplate(): string {\n return authPage(\"register\");\n}\n\n/** `pages/profile.vue` — the signed-in view with the logout widget. */\nexport function profilePageTemplate(): string {\n return `<script setup lang=\"ts\">\n${MANAGED_MARKER}\nimport { useZitadelProject } from \"@zitadel/sdk-nuxt\";\n\nconst project = useZitadelProject();\n</script>\n\n<template>\n <main style=\"padding: 24px\">\n <h1>Signed in (Nuxt)</h1>\n <ClientOnly>\n <zitadel-logout :project=\"project\" post-sign-out-url=\"/login\" />\n </ClientOnly>\n </main>\n</template>\n`;\n}\n\n/** `plugins/zitadel-components.client.ts` — register the Lit elements client-side. */\nexport function componentsPluginTemplate(): string {\n return `${MANAGED_MARKER}\n// Register Lit custom elements on the client only. Importing @zitadel/components\n// from a page <script setup> would run during SSR and break the widgets.\nimport \"@zitadel/components\";\n\nexport default defineNuxtPlugin(() => {});\n`;\n}\n\n/** `plugins/auth.server.ts` — seed the client auth state from the server context. */\nexport function authPluginTemplate(): string {\n return `${MANAGED_MARKER}\nimport { defineNuxtPlugin, useRequestEvent, useState } from \"#imports\";\nimport type { ClientAuthResult } from \"@zitadel/sdk-nuxt\";\n\nexport default defineNuxtPlugin(() => {\n const event = useRequestEvent();\n const auth = event?.context.nextgenAuth ?? {\n isAuthenticated: false as const,\n session: null,\n };\n\n // Strip the raw JWT before seeding useState — it must not appear in the SSR\n // payload where client-side scripts could read it.\n const clientAuth: ClientAuthResult = auth.isAuthenticated\n ? {\n isAuthenticated: true,\n session: {\n userId: auth.session.userId,\n email: auth.session.email,\n name: auth.session.name,\n },\n }\n : { isAuthenticated: false, session: null };\n\n useState<ClientAuthResult>(\"nextgen-auth\", () => clientAuth);\n});\n`;\n}\n","import { join } from \"node:path\";\n\nimport { npmDistTagForCliVersion } from \"../../../../public-cli\";\nimport { configCandidates } from \"../config-paths\";\nimport type { FileOp } from \"../file-writer/types\";\nimport type { PatchContext, PatchView } from \"../../types\";\nimport { AbstractRulePatcher } from \"../base\";\nimport { nuxtConfigEdit } from \"./nuxt-config\";\nimport {\n appVueTemplate,\n authPluginTemplate,\n componentsPluginTemplate,\n loginPageTemplate,\n profilePageTemplate,\n registerPageTemplate,\n} from \"./templates\";\n\nconst SDK_DEPENDENCY = \"@zitadel/sdk-nuxt\";\n\nconst NUXT_CONFIG_PATHS = configCandidates(\"nuxt.config\");\n\n/**\n * Rule-based patcher for a Nuxt app. Like Next.js, Nuxt proxies the backend and\n * verifies the session through server middleware — here the `@zitadel/sdk-nuxt`\n * module, registered via a non-destructive `nuxt.config.*` edit. Contributes\n * the login/register/profile pages (the raw `<zitadel-login>`/`<zitadel-logout>`\n * elements), the client/server plugins, the `app.vue` router, and the SDK dep.\n */\nexport class NuxtPatcher extends AbstractRulePatcher {\n canPatch(framework: string): boolean {\n return framework === \"nuxt\";\n }\n\n protected routeOps(ctx: PatchContext): FileOp[] {\n const src = (rel: string) => join(ctx.framework.appDir, rel);\n return [\n // app.vue/pages/plugins live under the Nuxt srcDir (`app/` on Nuxt 4, the\n // root on Nuxt 3); nuxt.config, env, and the dep stay at the project root.\n { kind: \"write\", path: src(\"app.vue\"), contents: appVueTemplate() },\n { kind: \"write\", path: src(\"pages/login.vue\"), contents: loginPageTemplate() },\n { kind: \"write\", path: src(\"pages/register.vue\"), contents: registerPageTemplate() },\n { kind: \"write\", path: src(\"pages/profile.vue\"), contents: profilePageTemplate() },\n {\n kind: \"write\",\n path: src(\"plugins/zitadel-components.client.ts\"),\n contents: componentsPluginTemplate(),\n },\n { kind: \"write\", path: src(\"plugins/auth.server.ts\"), contents: authPluginTemplate() },\n {\n kind: \"edit\",\n path: [...NUXT_CONFIG_PATHS],\n edit: nuxtConfigEdit({ projectId: ctx.project.id, server: ctx.server }),\n },\n { kind: \"merge-env\", path: \".env.example\", entries: { NUXT_PUBLIC_ZITADEL_PROJECT_ID: \"\" } },\n {\n kind: \"merge-env\",\n path: \".env.local\",\n entries: { NUXT_PUBLIC_ZITADEL_PROJECT_ID: ctx.project.id },\n },\n {\n kind: \"add-dep\",\n name: SDK_DEPENDENCY,\n version: npmDistTagForCliVersion(ctx.cliVersion),\n },\n ];\n }\n\n protected routeFiles(view: PatchView): ReadonlyArray<string> {\n const src = (rel: string) => join(view.framework.appDir, rel);\n return [\n src(\"app.vue\"),\n src(\"pages/login.vue\"),\n src(\"pages/register.vue\"),\n src(\"pages/profile.vue\"),\n src(\"plugins/zitadel-components.client.ts\"),\n src(\"plugins/auth.server.ts\"),\n ];\n }\n\n protected routeDeps(_view: PatchView): ReadonlyArray<string> {\n return [SDK_DEPENDENCY];\n }\n\n protected override routeConfigEdits(_view: PatchView): ReadonlyArray<string> {\n return [\"nuxt.config.*\"];\n }\n\n protected summary(_ctx: PatchContext): { title: string; detail: string } {\n return {\n title: \"Nuxt integration\",\n detail:\n \"Wrote login/register/profile pages + plugins and registered @zitadel/sdk-nuxt in nuxt.config.*.\",\n };\n }\n}\n","import { builders, generateCode } from \"magicast\";\n\nimport { configCandidates } from \"./config-paths\";\nimport type { FileOp } from \"./file-writer/types\";\nimport {\n ensureEditableObject,\n importIsPresent,\n parseConfigModule,\n resolveDefaultExportObject,\n} from \"./utils/magicast\";\nimport { PROXY_PATH } from \"./proxy\";\n\n/**\n * Shared Vite dev-server proxy merged into the project's Vite config for the SPA\n * frameworks (React, Vue). It forwards same-origin `/__nextgen/*` calls to the\n * backend, strips the prefix, and attaches the project's `sk_<project_id>`\n * bearer (read from `ZITADEL_PROJECT_ID` in the env) to every proxied request.\n */\nfunction proxyEntryCode(server: string): string {\n return `{\n target: ${JSON.stringify(server)},\n changeOrigin: false,\n rewrite: (path) => path.replace(/^\\\\${PROXY_PATH}/, \"\").replace(/^(?!\\\\/)/, \"/\"),\n configure: (proxy) => {\n const projectId = loadEnv(\"development\", process.cwd(), \"ZITADEL_\").ZITADEL_PROJECT_ID;\n if (!projectId) {\n throw new Error(\"ZITADEL_PROJECT_ID is not set; add it to .env.local (zitadel setup writes it).\");\n }\n const bearer = \\`Bearer sk_\\${projectId}\\`;\n proxy.on(\"proxyReq\", (proxyReq) => {\n proxyReq.setHeader(\"authorization\", bearer);\n });\n },\n}`;\n}\n\n/** The imports that the injected proxy entry depends on. */\nconst PROXY_IMPORTS = [{ from: \"vite\", imported: \"loadEnv\", local: \"loadEnv\" }] as const;\n\n/**\n * Builds the pure `edit` transform the file-writer applies to the project's Vite\n * config (`vite.config.*`): a non-destructive magicast merge that adds the\n * `/__nextgen` proxy and sets `server.port`/`strictPort` when they are unset,\n * preserving the user's plugins, options, and formatting. Leaves `server.host`\n * alone so the user can still opt into network binding (`--host`/`host: true`);\n * the issuer/origin requirement is about the port, not the bind host. Idempotent\n * — entries already present are left as-is. Throws `E_VALIDATION` when the file\n * is absent or the config object cannot be reached (function-built/exotic\n * configs), with a hint to add the block manually.\n */\nexport function viteProxyEdit(\n devPort: number,\n server: string,\n): (source: string | undefined) => string {\n return (source) => {\n const label = \"the Vite config (vite.config.*)\";\n const mod = parseConfigModule(source, label);\n const config = resolveDefaultExportObject(mod, label);\n let changed = false;\n const serverConfig = ensureEditableObject(config, \"server\");\n if (serverConfig.port === undefined) {\n serverConfig.port = devPort;\n changed = true;\n }\n if (serverConfig.strictPort === undefined) {\n serverConfig.strictPort = true;\n changed = true;\n }\n const proxyConfig = ensureEditableObject(serverConfig, \"proxy\");\n if (proxyConfig[PROXY_PATH] === undefined) {\n proxyConfig[PROXY_PATH] = builders.raw(proxyEntryCode(server));\n changed = true;\n }\n for (const imp of PROXY_IMPORTS) {\n if (!importIsPresent(mod, imp.local, imp.from)) {\n mod.imports.$add({ ...imp });\n changed = true;\n }\n }\n // Nothing was missing — return the source untouched so the file-writer skips\n // it instead of letting magicast reformat an already-patched config.\n if (!changed && source !== undefined) {\n return source;\n }\n const code = generateCode(mod).code;\n return code.endsWith(\"\\n\") ? code : `${code}\\n`;\n };\n}\n\n/**\n * Candidate Vite config filenames, in resolution priority. The patcher hands\n * this list to the generic `edit` file-op, which patches the first one that\n * exists — so any project layout (`vite.config.ts`, `.mts`, `.js`, …) is covered.\n */\nexport const VITE_CONFIG_PATHS = configCandidates(\"vite.config\");\n\n/**\n * Capability shared by every Vite-based patcher (React, Vue, and any future\n * Vite framework): contributes the file-op that non-destructively merges the\n * `/__nextgen` dev proxy into the project's Vite config. A patcher opts in by\n * declaring `implements ViteSupport` and spreading {@link viteProxyOp} into its\n * `routeOps`, so the proxy logic is written once and reused everywhere — no\n * per-framework duplication.\n */\nexport interface ViteSupport {\n /** The `edit` file-op that merges the `/__nextgen` proxy into the Vite config. */\n viteProxyOp(devPort: number, server: string): FileOp;\n}\n\n/** Builds the shared Vite-config proxy {@link FileOp} for a {@link ViteSupport} patcher. */\nexport function buildViteProxyOp(devPort: number, server: string): FileOp {\n return { kind: \"edit\", path: [...VITE_CONFIG_PATHS], edit: viteProxyEdit(devPort, server) };\n}\n","import { MANAGED_MARKER } from \"../../../../paths\";\n\nimport { PROXY_PATH } from \"../proxy\";\n\n/**\n * The managed `src/App.tsx`: a minimal path-based router that renders the\n * `@zitadel/sdk-react` widgets — login at `/login` (and `/`), register at\n * `/register`, and the logout widget at `/profile`. The project id comes from\n * `VITE_ZITADEL_PROJECT_ID` (Vite only exposes `VITE_`-prefixed env to the\n * client). No secret reaches the browser: the dev proxy in `vite.config.*`\n * attaches the `sk_<project_id>` bearer (derived from the public project id)\n * server-side.\n */\nexport function appTemplate(): string {\n return `${MANAGED_MARKER}\nimport { ZitadelLogin, ZitadelLogout, configureZitadel } from \"@zitadel/sdk-react\";\n\nconst project = configureZitadel({\n projectId: import.meta.env.VITE_ZITADEL_PROJECT_ID,\n proxyPath: \"${PROXY_PATH}\",\n});\n\nexport default function App() {\n const path = window.location.pathname;\n\n if (path.startsWith(\"/profile\")) {\n return <ZitadelLogout project={project} postSignOutUrl=\"/login\" />;\n }\n if (path.startsWith(\"/register\")) {\n return <ZitadelLogin project={project} purpose=\"register\" postSignInUrl=\"/profile\" />;\n }\n return <ZitadelLogin project={project} purpose=\"login\" postSignInUrl=\"/profile\" />;\n}\n`;\n}\n","import { npmDistTagForCliVersion } from \"../../../../public-cli\";\nimport type { FileOp } from \"../file-writer/types\";\nimport type { PatchContext, PatchView } from \"../../types\";\nimport { AbstractRulePatcher } from \"../base\";\nimport { type ViteSupport, buildViteProxyOp } from \"../vite-support\";\nimport { appTemplate } from \"./templates\";\n\nconst SDK_DEPENDENCY = \"@zitadel/sdk-react\";\n\n/**\n * Rule-based patcher for a Vite + React single-page app. Inherits the shared\n * `.zitadel/` base files from {@link AbstractRulePatcher} and contributes the\n * managed `src/App.tsx` auth entry, a non-destructive `vite.config.*` merge\n * that adds the `/__nextgen` dev proxy (attaching the `sk_<project_id>` bearer\n * from `ZITADEL_PROJECT_ID` to every proxied request), the `VITE_`-prefixed\n * project id, and the SDK dep.\n *\n * Unlike Next.js — whose middleware runs the proxy and token exchange\n * server-side — a SPA has no server, so the dev proxy stands in for\n * `@zitadel/edge-proxy` locally. Production deployments still need that proxy.\n */\nexport class ReactPatcher extends AbstractRulePatcher implements ViteSupport {\n canPatch(framework: string): boolean {\n return framework === \"react\";\n }\n\n viteProxyOp(devPort: number, server: string): FileOp {\n return buildViteProxyOp(devPort, server);\n }\n\n protected routeOps(ctx: PatchContext): FileOp[] {\n return [\n { kind: \"write\", path: \"src/App.tsx\", contents: appTemplate() },\n this.viteProxyOp(ctx.framework.devPort, ctx.server),\n // Vite only exposes VITE_-prefixed vars to client code (import.meta.env).\n { kind: \"merge-env\", path: \".env.example\", entries: { VITE_ZITADEL_PROJECT_ID: \"\" } },\n {\n kind: \"merge-env\",\n path: \".env.local\",\n entries: { VITE_ZITADEL_PROJECT_ID: ctx.project.id },\n },\n {\n kind: \"add-dep\",\n name: SDK_DEPENDENCY,\n version: npmDistTagForCliVersion(ctx.cliVersion),\n },\n ];\n }\n\n protected routeFiles(_view: PatchView): ReadonlyArray<string> {\n return [\"src/App.tsx\"];\n }\n\n protected routeDeps(_view: PatchView): ReadonlyArray<string> {\n return [SDK_DEPENDENCY];\n }\n\n protected override routeConfigEdits(_view: PatchView): ReadonlyArray<string> {\n return [\"vite.config.*\"];\n }\n\n protected summary(_ctx: PatchContext): { title: string; detail: string } {\n return {\n title: \"React (Vite) integration\",\n detail:\n \"Wrote src/App.tsx auth entry and merged the /__nextgen dev proxy into vite.config.*.\",\n };\n }\n}\n","import { MANAGED_MARKER } from \"../../../../paths\";\nimport { PROXY_PATH } from \"../proxy\";\n\n/**\n * The managed `src/App.vue`: a minimal path-based router that renders the\n * `@zitadel/sdk-vue` widgets — login at `/login` (and `/`), register at\n * `/register`, and the logout widget at `/profile`. The managed marker lives in\n * the `<script setup>` block (a JS comment) so eject/doctor stay marker-aware.\n * The project id comes from `VITE_ZITADEL_PROJECT_ID`. No secret reaches the\n * browser: the dev proxy in `vite.config.*` attaches the `sk_<project_id>`\n * bearer (derived from the public project id) server-side.\n */\nexport function appTemplate(): string {\n return `<script setup lang=\"ts\">\n${MANAGED_MARKER}\nimport { ZitadelLogin, ZitadelLogout, configureZitadel } from \"@zitadel/sdk-vue\";\n\nconst project = configureZitadel({\n projectId: import.meta.env.VITE_ZITADEL_PROJECT_ID,\n proxyPath: \"${PROXY_PATH}\",\n});\n\nconst path = window.location.pathname;\n</script>\n\n<template>\n <ZitadelLogout\n v-if=\"path.startsWith('/profile')\"\n :project=\"project\"\n postSignOutUrl=\"/login\"\n />\n <ZitadelLogin\n v-else-if=\"path.startsWith('/register')\"\n :project=\"project\"\n purpose=\"register\"\n postSignInUrl=\"/profile\"\n />\n <ZitadelLogin v-else :project=\"project\" purpose=\"login\" postSignInUrl=\"/profile\" />\n</template>\n`;\n}\n","import { npmDistTagForCliVersion } from \"../../../../public-cli\";\nimport type { FileOp } from \"../file-writer/types\";\nimport type { PatchContext, PatchView } from \"../../types\";\nimport { AbstractRulePatcher } from \"../base\";\nimport { type ViteSupport, buildViteProxyOp } from \"../vite-support\";\nimport { appTemplate } from \"./templates\";\n\nconst SDK_DEPENDENCY = \"@zitadel/sdk-vue\";\n\n/**\n * Rule-based patcher for a Vite + Vue single-page app. Inherits the shared\n * `.zitadel/` base files from {@link AbstractRulePatcher} and contributes the\n * managed `src/App.vue` auth entry, a non-destructive `vite.config.*` merge\n * that adds the `/__nextgen` dev proxy (attaching the `sk_<project_id>` bearer\n * from `ZITADEL_PROJECT_ID` to every proxied request), the `VITE_`-prefixed\n * project id, and the SDK dep.\n */\nexport class VuePatcher extends AbstractRulePatcher implements ViteSupport {\n canPatch(framework: string): boolean {\n return framework === \"vue\";\n }\n\n viteProxyOp(devPort: number, server: string): FileOp {\n return buildViteProxyOp(devPort, server);\n }\n\n protected routeOps(ctx: PatchContext): FileOp[] {\n return [\n { kind: \"write\", path: \"src/App.vue\", contents: appTemplate() },\n this.viteProxyOp(ctx.framework.devPort, ctx.server),\n { kind: \"merge-env\", path: \".env.example\", entries: { VITE_ZITADEL_PROJECT_ID: \"\" } },\n {\n kind: \"merge-env\",\n path: \".env.local\",\n entries: { VITE_ZITADEL_PROJECT_ID: ctx.project.id },\n },\n {\n kind: \"add-dep\",\n name: SDK_DEPENDENCY,\n version: npmDistTagForCliVersion(ctx.cliVersion),\n },\n ];\n }\n\n protected routeFiles(_view: PatchView): ReadonlyArray<string> {\n return [\"src/App.vue\"];\n }\n\n protected routeDeps(_view: PatchView): ReadonlyArray<string> {\n return [SDK_DEPENDENCY];\n }\n\n protected override routeConfigEdits(_view: PatchView): ReadonlyArray<string> {\n return [\"vite.config.*\"];\n }\n\n protected summary(_ctx: PatchContext): { title: string; detail: string } {\n return {\n title: \"Vue (Vite) integration\",\n detail:\n \"Wrote src/App.vue auth entry and merged the /__nextgen dev proxy into vite.config.*.\",\n };\n }\n}\n","import { AngularPatcher } from \"./rule/angular\";\nimport { NextPatcher } from \"./rule/next\";\nimport { NuxtPatcher } from \"./rule/nuxt\";\nimport { ReactPatcher } from \"./rule/react\";\nimport { VuePatcher } from \"./rule/vue\";\nimport type { Patcher } from \"./types\";\n\n/**\n * Active patchers, in priority order; the first whose `canPatch` matches wins.\n *\n * Patchers are grouped by family under subdirectories: `rule/` holds the\n * deterministic, template-driven patchers (extending\n * {@link import(\"./rule/base\").AbstractRulePatcher}). A future LLM-driven\n * family lives under `llm/` and registers its concrete patchers here — no\n * orchestrator or command changes needed. Only Next.js is supported today.\n */\nexport const patchers = [\n new NextPatcher(),\n new NuxtPatcher(),\n new ReactPatcher(),\n new VuePatcher(),\n new AngularPatcher(),\n] as const satisfies ReadonlyArray<Patcher>;\n","import { spawnSync } from \"node:child_process\";\n\nimport { ZitadelError } from \"../../errors\";\nimport type { Scaffolder } from \"./types\";\n\n/**\n * Base for scaffolders that delegate to an external CLI (e.g. create-next-app).\n * Subclasses implement {@link scaffold} and call {@link runCommand}.\n */\nexport abstract class AbstractCLIScaffolder implements Scaffolder {\n abstract readonly displayName: string;\n abstract readonly supportedFrameworks: ReadonlyArray<string>;\n\n /** True when the requested framework is in {@link supportedFrameworks}. */\n canScaffold(framework: string): boolean {\n return this.supportedFrameworks.includes(framework);\n }\n\n abstract scaffold(cwd: string, framework: string): Promise<void>;\n\n /**\n * Runs an external command in `cwd`, throwing a typed {@link ZitadelError} on\n * failure so the cause surfaces as a categorized CLI error. Distinguishes\n * \"binary not on PATH\" (`ENOENT` from the spawn itself) from \"binary ran but\n * exited non-zero\" — the former previously got masked as a generic\n * `exited with status 1`, leaving users to guess. Tests stub\n * `node:child_process` to assert the command without spawning.\n */\n protected runCommand(command: string, args: ReadonlyArray<string>, cwd: string): void {\n const result = spawnSync(command, [...args], { cwd, encoding: \"utf8\" });\n if (result.error) {\n const err = result.error as NodeJS.ErrnoException;\n const notFound = err.code === \"ENOENT\";\n throw new ZitadelError(\n \"E_VALIDATION\",\n notFound ? `Command not found: ${command}` : `Failed to spawn \"${command}\": ${err.message}`,\n {\n hint: notFound ? `Ensure '${command}' is installed and on PATH.` : undefined,\n details: { command, args: [...args], code: err.code },\n },\n );\n }\n const status = result.status ?? 1;\n if (status !== 0) {\n const stdout = String(result.stdout ?? \"\");\n const stderr = String(result.stderr ?? \"\");\n const output = truncateCommandOutput([stderr, stdout].filter(Boolean).join(\"\\n\").trim());\n throw new ZitadelError(\n \"E_VALIDATION\",\n `Command \"${command} ${args.join(\" \")}\" exited with status ${String(status)}`,\n {\n hint: output ? `Command output:\\n${output}` : \"Run the command directly for more detail.\",\n details: { command, args: [...args], cwd, stdout, stderr },\n },\n );\n }\n }\n}\n\nfunction truncateCommandOutput(output: string): string {\n const limit = 4000;\n if (output.length <= limit) {\n return output;\n }\n return `${output.slice(0, limit)}\\n... output truncated ...`;\n}\n","import { rm } from \"node:fs/promises\";\nimport { basename, join } from \"node:path\";\n\nimport { AbstractCLIScaffolder } from \"./cli\";\n\n/**\n * Derives a valid Angular project name from the target directory. `ng new`\n * validates the name against `^[a-zA-Z0-9-~][a-zA-Z0-9-._~]*$` and rejects `.`,\n * so we slugify the directory's basename (lowercase, non-alphanumerics → `-`)\n * and guarantee a leading letter by prefixing `app-` when the slug does not\n * start with one (`app-zitadel` when the basename slugifies to nothing).\n */\nfunction angularProjectName(cwd: string): string {\n const slug = basename(cwd)\n .toLowerCase()\n .replace(/[^a-z0-9-]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\");\n return /^[a-z]/.test(slug) ? slug : `app-${slug || \"zitadel\"}`;\n}\n\n/**\n * Scaffolds a new Angular app with the Angular CLI, then removes the starter\n * `app.ts`/`app.html` root component (and its now-unreferenced `app.css`) so the\n * patcher can write the managed ones without colliding with boilerplate. The\n * managed component uses only `templateUrl`, so `app.css` would otherwise be a\n * dangling file eject never cleans up. Unlike `create-vite`/`nuxi`, `ng new`\n * needs a real project name plus `--directory .` to populate the current dir.\n * Requires a Node version Angular supports (^22.22.3 || ^24.15.0 || >=26).\n */\nexport class AngularScaffolder extends AbstractCLIScaffolder {\n readonly displayName = \"Angular\";\n readonly supportedFrameworks: ReadonlyArray<string> = [\"angular\"];\n\n async scaffold(cwd: string, _framework: string): Promise<void> {\n this.runCommand(\n \"npx\",\n [\n \"-y\",\n \"@angular/cli@latest\",\n \"new\",\n angularProjectName(cwd),\n \"--directory\",\n \".\",\n \"--defaults\",\n \"--style=css\",\n \"--ssr=false\",\n \"--skip-git\",\n ],\n cwd,\n );\n await rm(join(cwd, \"src/app/app.ts\"), { force: true });\n await rm(join(cwd, \"src/app/app.html\"), { force: true });\n await rm(join(cwd, \"src/app/app.css\"), { force: true });\n }\n}\n","import { AbstractCLIScaffolder } from \"./cli\";\n\nconst CREATE_NEXT_APP_VERSION = \"16.2.4\";\n\n/** Scaffolds a new Next.js App Router project with `create-next-app`. */\nexport class NextScaffolder extends AbstractCLIScaffolder {\n readonly displayName = \"Next.js\";\n readonly supportedFrameworks: ReadonlyArray<string> = [\"next\"];\n\n /**\n * Runs the pinned `create-next-app` version in `cwd`, creating a TypeScript\n * App Router project in place. `--yes` accepts all defaults so the command\n * runs unattended, and `--skip-install` leaves dependency installation to the\n * setup command's explicit next step after Zitadel patches package.json.\n */\n async scaffold(cwd: string, _framework: string): Promise<void> {\n this.runCommand(\n \"npx\",\n [\n \"--yes\",\n `create-next-app@${CREATE_NEXT_APP_VERSION}`,\n \".\",\n \"--ts\",\n \"--app\",\n \"--use-npm\",\n \"--disable-git\",\n \"--yes\",\n \"--skip-install\",\n ],\n cwd,\n );\n }\n}\n","import { rm } from \"node:fs/promises\";\nimport { join } from \"node:path\";\n\nimport { AbstractCLIScaffolder } from \"./cli\";\n\n/**\n * Scaffolds a new Nuxt app with `nuxi init`, then removes the starter `app.vue`\n * so the patcher can write the managed one without colliding with boilerplate.\n * Nuxt 4 (what `nuxi init` scaffolds today) puts it under `app/`; older Nuxt put\n * it at the root, so both are removed. `nuxt.config.ts` is left in place — the\n * patcher merges into it via an `edit`, which preserves whatever `nuxi` generated.\n */\nexport class NuxtScaffolder extends AbstractCLIScaffolder {\n readonly displayName = \"Nuxt\";\n readonly supportedFrameworks: ReadonlyArray<string> = [\"nuxt\"];\n\n async scaffold(cwd: string, _framework: string): Promise<void> {\n this.runCommand(\n \"npx\",\n [\n \"-y\",\n \"nuxi@latest\",\n \"init\",\n \".\",\n \"--template\",\n \"minimal\",\n \"--packageManager\",\n \"npm\",\n \"--no-gitInit\",\n \"--force\",\n ],\n cwd,\n );\n await rm(join(cwd, \"app/app.vue\"), { force: true });\n await rm(join(cwd, \"app.vue\"), { force: true });\n }\n}\n","import { rm } from \"node:fs/promises\";\nimport { join } from \"node:path\";\n\nimport { AbstractCLIScaffolder } from \"./cli\";\n\n/**\n * Scaffolds a new Vite + React (TypeScript) single-page app with `create-vite`,\n * then removes the starter `App.tsx`/`App.css` demo so the patcher can write the\n * managed `src/App.tsx` without colliding with boilerplate. `index.css` and\n * `main.tsx` are left in place — the patched `App.tsx` keeps the same entry.\n */\nexport class ReactScaffolder extends AbstractCLIScaffolder {\n readonly displayName = \"React (Vite)\";\n readonly supportedFrameworks: ReadonlyArray<string> = [\"react\"];\n\n async scaffold(cwd: string, _framework: string): Promise<void> {\n this.runCommand(\"npm\", [\"create\", \"vite@latest\", \".\", \"--\", \"--template\", \"react-ts\"], cwd);\n await rm(join(cwd, \"src/App.tsx\"), { force: true });\n await rm(join(cwd, \"src/App.css\"), { force: true });\n }\n}\n","import { rm } from \"node:fs/promises\";\nimport { join } from \"node:path\";\n\nimport { AbstractCLIScaffolder } from \"./cli\";\n\n/**\n * Scaffolds a new Vite + Vue (TypeScript) single-page app with `create-vite`,\n * then removes the starter `App.vue`/`components/HelloWorld.vue` demo so the\n * patcher can write the managed `src/App.vue` without colliding with boilerplate.\n */\nexport class VueScaffolder extends AbstractCLIScaffolder {\n readonly displayName = \"Vue (Vite)\";\n readonly supportedFrameworks: ReadonlyArray<string> = [\"vue\"];\n\n async scaffold(cwd: string, _framework: string): Promise<void> {\n this.runCommand(\"npm\", [\"create\", \"vite@latest\", \".\", \"--\", \"--template\", \"vue-ts\"], cwd);\n await rm(join(cwd, \"src/App.vue\"), { force: true });\n await rm(join(cwd, \"src/components/HelloWorld.vue\"), { force: true });\n }\n}\n","import { AngularScaffolder } from \"./angular\";\nimport { NextScaffolder } from \"./next\";\nimport { NuxtScaffolder } from \"./nuxt\";\nimport { ReactScaffolder } from \"./react\";\nimport { VueScaffolder } from \"./vue\";\nimport type { Scaffolder } from \"./types\";\n\n/**\n * Active scaffolders, in priority order. The framework picker derives its\n * choices from this list. Add a new framework by appending its scaffolder\n * here — no orchestrator changes needed.\n */\nexport const scaffolders = [\n new NextScaffolder(),\n new NuxtScaffolder(),\n new ReactScaffolder(),\n new VueScaffolder(),\n new AngularScaffolder(),\n] as const satisfies ReadonlyArray<Scaffolder>;\n","import { mkdir, readdir, readFile, rename, rm, writeFile } from \"node:fs/promises\";\nimport { basename, dirname, join } from \"node:path\";\n\nimport { ZitadelError } from \"../errors\";\nimport { detectors } from \"./detectors\";\nimport type { Detector, FrameworkFacts } from \"./detectors/types\";\nimport { patchers } from \"./patchers\";\nimport type { Patcher } from \"./patchers/types\";\nimport { scaffolders } from \"./scaffolders\";\nimport type { Scaffolder } from \"./scaffolders/types\";\n\nexport type { Detector, FrameworkFacts } from \"./detectors/types\";\nexport { issuerFromPort } from \"./detectors/port\";\n\n/** One framework the CLI can scaffold from scratch, surfaced to the picker. */\nexport type FrameworkChoice = Readonly<{ id: string; displayName: string }>;\n\nexport type ScaffoldTarget = Readonly<{\n scaffoldable: boolean;\n hasGitignore: boolean;\n hasRuntimeOnlyZitadel: boolean;\n reason?: string;\n entries: ReadonlyArray<string>;\n}>;\n\ntype ScaffoldStash = Readonly<{\n gitignore?: string;\n root: string;\n zitadel?: string;\n}>;\n\n/**\n * Orchestrates the three per-framework strategies — detectors (recognise an\n * existing project and extract its facts), scaffolders (create a project), and\n * patchers (integrate Zitadel) — over their respective registries. It resolves\n * the right strategy for a framework and drives the detect/scaffold lifecycle;\n * how a patcher applies its work (file operations vs an LLM agent) stays\n * internal to that patcher. Registries are injected so tests can supply fakes.\n */\nexport class Orca {\n constructor(\n private readonly detectors: ReadonlyArray<Detector>,\n private readonly scaffolders: ReadonlyArray<Scaffolder>,\n private readonly patchers: ReadonlyArray<Patcher>,\n ) {}\n\n /**\n * Detects the framework in `cwd` and extracts its {@link FrameworkFacts},\n * honouring an explicit `requested` framework. Throws\n * `E_FRAMEWORK_NOT_DETECTED` when nothing matches; a detector's\n * `E_UNSUPPORTED_PROJECT_SHAPE` (recognised but unsupported) propagates.\n */\n async detect(cwd: string, requested?: string): Promise<FrameworkFacts> {\n const candidates = requested\n ? this.detectors.filter((detector) => detector.framework === requested)\n : this.detectors;\n if (requested && candidates.length === 0) {\n throw new ZitadelError(\"E_FRAMEWORK_NOT_DETECTED\", `Unsupported framework \"${requested}\"`, {\n hint: `Supported frameworks: ${this.frameworkIds().join(\", \")}.`,\n });\n }\n for (const detector of candidates) {\n const facts = await detector.detect(cwd);\n if (facts) {\n return facts;\n }\n }\n throw new ZitadelError(\n \"E_FRAMEWORK_NOT_DETECTED\",\n \"Could not detect a supported app framework\",\n {\n hint: \"Run setup from your app project directory, pass --cwd <path-to-app>, or run setup from an empty directory to scaffold a new app.\",\n },\n );\n }\n\n /**\n * Non-throwing detection: returns `undefined` instead of raising for a\n * project that is absent, unrecognised, or recognised-but-unsupported, so\n * callers (e.g. `eject`) can probe and degrade gracefully.\n */\n async tryDetect(cwd: string): Promise<FrameworkFacts | undefined> {\n try {\n return await this.detect(cwd);\n } catch (error) {\n if (\n error instanceof ZitadelError &&\n (error.code === \"E_FRAMEWORK_NOT_DETECTED\" || error.code === \"E_UNSUPPORTED_PROJECT_SHAPE\")\n ) {\n return undefined;\n }\n throw error;\n }\n }\n\n /** Whether `cwd` is safe for an in-place framework scaffold. */\n async isFreshScaffoldTarget(cwd: string): Promise<boolean> {\n return (await inspectScaffoldTarget(cwd)).scaffoldable;\n }\n\n /**\n * Creates a new `framework` project in `cwd`, then re-detects it to return\n * the resulting {@link FrameworkFacts}. Throws `E_CONFLICT` when the directory\n * already contains a project (\"already scaffolded\") and `E_VALIDATION` when no\n * scaffolder supports the framework.\n */\n async scaffold(cwd: string, framework: string): Promise<FrameworkFacts> {\n const target = await inspectScaffoldTarget(cwd);\n if (!target.scaffoldable) {\n throw new ZitadelError(\"E_CONFLICT\", `Cannot scaffold: ${cwd} is not empty`, {\n hint:\n target.reason ??\n \"Run setup in an empty directory, or run setup from an existing supported app project.\",\n details: { entries: target.entries },\n });\n }\n assertNpmSafeScaffoldDirectoryName(cwd);\n const stash = await stashFreshScaffoldArtifacts(cwd, target);\n try {\n await this.scaffolderFor(framework).scaffold(cwd, framework);\n } finally {\n await restoreFreshScaffoldArtifacts(cwd, stash);\n }\n return this.detect(cwd, framework);\n }\n\n /**\n * Resolves the scaffolder for a framework, throwing `E_VALIDATION` (with the\n * available list) when none matches.\n */\n scaffolderFor(framework: string): Scaffolder {\n const scaffolder = this.scaffolders.find((candidate) => candidate.canScaffold(framework));\n if (!scaffolder) {\n throw new ZitadelError(\"E_VALIDATION\", `No scaffolder supports \"${framework}\"`, {\n hint: `Available frameworks: ${this.availableFrameworks()\n .map((f) => f.id)\n .join(\", \")}.`,\n });\n }\n return scaffolder;\n }\n\n /**\n * Resolves the patcher for a framework, throwing `E_VALIDATION` when none\n * matches (e.g. a framework that can be scaffolded but not yet integrated).\n */\n patcherFor(framework: string): Patcher {\n const patcher = this.patchers.find((candidate) => candidate.canPatch(framework));\n if (!patcher) {\n throw new ZitadelError(\"E_VALIDATION\", `No patcher supports \"${framework}\"`, {\n hint: \"Zitadel integration currently supports Next.js.\",\n });\n }\n return patcher;\n }\n\n /** The frameworks that can be scaffolded, derived from the scaffolder registry. */\n availableFrameworks(): ReadonlyArray<FrameworkChoice> {\n return this.scaffolders.map((scaffolder) => ({\n id: scaffolder.supportedFrameworks[0] ?? scaffolder.displayName,\n displayName: scaffolder.displayName,\n }));\n }\n\n private frameworkIds(): ReadonlyArray<string> {\n return this.detectors.map((detector) => detector.framework);\n }\n}\n\nfunction assertNpmSafeScaffoldDirectoryName(cwd: string): void {\n const name = basename(cwd);\n const errors = npmPackageNameErrors(name);\n if (errors.length === 0) {\n return;\n }\n\n throw new ZitadelError(\n \"E_VALIDATION\",\n `Fresh app directory name \"${name}\" is not npm-package-safe`,\n {\n hint:\n \"Rename the directory to a lowercase npm-package-safe name, for example `my-zitadel-app`, then rerun setup.\",\n details: { cwd, name, validation_errors: errors },\n },\n );\n}\n\nfunction npmPackageNameErrors(name: string): string[] {\n // This local preflight catches common package-name failures before the\n // scaffolder mutates disk; framework generators still own stricter checks.\n const errors: string[] = [];\n if (name.length === 0) {\n errors.push(\"name is empty\");\n }\n if (name.length > 214) {\n errors.push(\"name is longer than 214 characters\");\n }\n if (name !== name.trim()) {\n errors.push(\"name contains leading or trailing whitespace\");\n }\n if (/[A-Z]/.test(name)) {\n errors.push(\"name can no longer contain capital letters\");\n }\n if (name.startsWith(\".\") || name.startsWith(\"_\")) {\n errors.push(\"name cannot start with a period or underscore\");\n }\n if (!/^[a-z0-9][a-z0-9._~-]*$/.test(name)) {\n errors.push(\"name may only contain lowercase letters, numbers, dots, underscores, tildes, and hyphens\");\n }\n if (name === \"node_modules\" || name === \"favicon.ico\") {\n errors.push(`name \"${name}\" is reserved`);\n }\n return [...new Set(errors)];\n}\n\n/** {@link Orca} wired with the default detector, scaffolder, and patcher registries. */\nexport function createOrca(): Orca {\n return new Orca(detectors, scaffolders, patchers);\n}\n\nexport async function inspectScaffoldTarget(cwd: string): Promise<ScaffoldTarget> {\n const entries = await readdir(cwd, { withFileTypes: true });\n const names = entries.map((entry) => entry.name).sort();\n let hasGitignore = false;\n let hasRuntimeOnlyZitadel = false;\n\n for (const entry of entries) {\n if (entry.name === \".gitignore\") {\n if (!entry.isFile()) {\n return {\n scaffoldable: false,\n hasGitignore: false,\n hasRuntimeOnlyZitadel: false,\n reason: \".gitignore exists but is not a file.\",\n entries: names,\n };\n }\n hasGitignore = true;\n continue;\n }\n\n if (entry.name === \".zitadel\") {\n if (!entry.isDirectory() || !(await isRuntimeOnlyZitadelDir(join(cwd, \".zitadel\")))) {\n return {\n scaffoldable: false,\n hasGitignore,\n hasRuntimeOnlyZitadel: false,\n reason:\n \".zitadel contains project state. Move it aside or run setup from an empty app directory.\",\n entries: names,\n };\n }\n hasRuntimeOnlyZitadel = true;\n continue;\n }\n\n return {\n scaffoldable: false,\n hasGitignore,\n hasRuntimeOnlyZitadel: false,\n reason: `Directory contains ${entry.name}. Run setup from an empty directory to scaffold a new app.`,\n entries: names,\n };\n }\n\n return { scaffoldable: true, hasGitignore, hasRuntimeOnlyZitadel, entries: names };\n}\n\nasync function isRuntimeOnlyZitadelDir(path: string): Promise<boolean> {\n const entries = await readdir(path, { withFileTypes: true });\n if (entries.length !== 1 || entries[0]?.name !== \"local\" || !entries[0].isDirectory()) {\n return false;\n }\n return true;\n}\n\nasync function stashFreshScaffoldArtifacts(\n cwd: string,\n target: ScaffoldTarget,\n): Promise<ScaffoldStash | undefined> {\n if (!target.hasGitignore && !target.hasRuntimeOnlyZitadel) {\n return undefined;\n }\n\n const parent = dirname(cwd);\n const root = join(\n parent,\n `.${basename(cwd)}.fresh-scaffold-stash-${String(process.pid)}-${String(Date.now())}`,\n );\n await mkdir(root, { mode: 0o700 });\n\n const stash: { gitignore?: string; root: string; zitadel?: string } = { root };\n if (target.hasRuntimeOnlyZitadel) {\n stash.zitadel = join(root, \".zitadel\");\n await rename(join(cwd, \".zitadel\"), stash.zitadel);\n }\n if (target.hasGitignore) {\n stash.gitignore = join(root, \".gitignore\");\n await rename(join(cwd, \".gitignore\"), stash.gitignore);\n }\n return stash;\n}\n\nasync function restoreFreshScaffoldArtifacts(\n cwd: string,\n stash: ScaffoldStash | undefined,\n): Promise<void> {\n if (!stash) {\n return;\n }\n\n try {\n await restoreRuntimeOnlyZitadel(cwd, stash.zitadel);\n await restoreGitignore(cwd, stash.gitignore);\n } finally {\n await rm(stash.root, { recursive: true, force: true });\n }\n}\n\nasync function restoreRuntimeOnlyZitadel(cwd: string, stash: string | undefined): Promise<void> {\n if (!stash) {\n return;\n }\n\n const target = join(cwd, \".zitadel\");\n try {\n await rename(stash, target);\n await appendGitignoreEntry(cwd, \".zitadel/local/\");\n return;\n } catch (error) {\n if (!isErrno(error, \"EEXIST\")) {\n throw error;\n }\n }\n\n await mkdir(target, { recursive: true, mode: 0o700 });\n await rename(join(stash, \"local\"), join(target, \"local\"));\n await rm(stash, { recursive: true, force: true });\n await appendGitignoreEntry(cwd, \".zitadel/local/\");\n}\n\nasync function restoreGitignore(cwd: string, stash: string | undefined): Promise<void> {\n if (!stash) {\n return;\n }\n\n const path = join(cwd, \".gitignore\");\n const stashed = await readFile(stash, \"utf8\");\n let current = \"\";\n try {\n current = await readFile(path, \"utf8\");\n } catch (error) {\n if (!isErrno(error, \"ENOENT\")) {\n throw error;\n }\n }\n\n const existingLines = new Set(\n current\n .split(/\\r?\\n/g)\n .map((line) => line.trim())\n .filter(Boolean),\n );\n const missingLines = stashed\n .split(/\\r?\\n/g)\n .map((line) => line.trim())\n .filter((line) => line.length > 0 && !existingLines.has(line));\n if (missingLines.length === 0) {\n return;\n }\n\n const prefix = current.length === 0 || current.endsWith(\"\\n\") ? \"\" : \"\\n\";\n await writeFile(path, `${current}${prefix}${missingLines.join(\"\\n\")}\\n`);\n}\n\nasync function appendGitignoreEntry(cwd: string, entry: string): Promise<void> {\n const path = join(cwd, \".gitignore\");\n let existing = \"\";\n try {\n existing = await readFile(path, \"utf8\");\n } catch (error) {\n if (!isErrno(error, \"ENOENT\")) {\n throw error;\n }\n }\n\n const lines = existing.split(/\\r?\\n/g).map((line) => line.trim());\n if (lines.includes(entry)) {\n return;\n }\n const prefix = existing.length === 0 || existing.endsWith(\"\\n\") ? \"\" : \"\\n\";\n await writeFile(path, `${existing}${prefix}${entry}\\n`);\n}\n\nfunction isErrno(error: unknown, code: string): boolean {\n return (\n typeof error === \"object\" &&\n error !== null &&\n \"code\" in error &&\n (error as { code?: unknown }).code === code\n );\n}\n"],"mappings":";;;;;;;;;;;AAoBA,eAAsB,gBAAgB,KAAmC;CACvE,MAAM,WAAW,MAAM,SAAS,KAAK,KAAK,eAAe,EAAE,OAAO;AAClE,QAAO,KAAK,MAAM,SAAS;;;;;;AAO7B,SAAgB,cAAc,KAAkB,MAAuB;AACrE,QAAO,QAAQ,IAAI,eAAe,SAAS,IAAI,kBAAkB,MAAM;;AAGzE,SAAgB,uBAAuB,KAAkB,MAAkC;CACzF,MAAM,OAAO,IAAI,eAAe,SAAS,IAAI,kBAAkB;AAC/D,KAAI,CAAC,KACH;CAEF,MAAM,QAAQ,KAAK,MAAM,MAAM;AAC/B,QAAO,QAAQ,OAAO,MAAM,GAAG,GAAG,KAAA;;;;;;;;AC9BpC,MAAa,mBAAmB;;;;;;AAOhC,eAAsB,cAAc,KAAa,KAAmC;CAClF,MAAM,MAAM,IAAI,SAAS;CACzB,MAAM,aAAa,OAAO,QAAQ,WAAW,YAAY,IAAI,GAAG,KAAA;AAChE,KAAI,WACF,QAAO;CAGT,MAAM,cAAc,MAAM,gBAAgB,IAAI;AAC9C,KAAI,YACF,QAAO;AAGT,QAAO;;AAGT,eAAe,gBAAgB,KAA0C;AACvE,MAAK,MAAM,aAAa,CAAC,cAAc,OAAO,CAC5C,KAAI;EAGF,MAAM,WADQ,MADS,SAAS,KAAK,KAAK,UAAU,EAAE,OAAO,EACtC,MAAM,wBACR,GAAG;AACxB,MAAI,QACF,QAAO,OAAO,SAAS,SAAS,GAAG;SAE/B;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WAAW,KAAK,QAAQ,SAAS,KAAK,GAAG,KAAK;AACrE,OAAM,UAAU,MAAM,GAAG,UAAU,SAAS,aAAa,KAAK,KAAK,CAAC,IAAI;;AAG1E,eAAe,qBAAqB,KAAa,OAA8B;CAC7E,MAAM,OAAO,KAAK,KAAK,aAAa;CACpC,IAAI,WAAW;AACf,KAAI;AACF,aAAW,MAAM,SAAS,MAAM,OAAO;UAChC,OAAO;AACd,MAAI,CAAC,QAAQ,OAAO,SAAS,CAC3B,OAAM;;AAKV,KADc,SAAS,MAAM,SAAS,CAAC,KAAK,SAAS,KAAK,MAAM,CACvD,CAAC,SAAS,MAAM,CACvB;CAEF,MAAM,SAAS,SAAS,WAAW,KAAK,SAAS,SAAS,KAAK,GAAG,KAAK;AACvE,OAAM,UAAU,MAAM,GAAG,WAAW,SAAS,MAAM,IAAI;;AAGzD,SAAS,QAAQ,OAAgB,MAAuB;AACtD,QACE,OAAO,UAAU,YACjB,UAAU,QACV,UAAU,SACT,MAA6B,SAAS"}
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import { execFile } from "node:child_process";
|
|
2
|
+
//#region src/lib/prober/ports.ts
|
|
3
|
+
/**
|
|
4
|
+
* Enumerate TCP ports currently in LISTEN state on the loopback interface
|
|
5
|
+
* (`127.0.0.1`, `::1`, or the wildcard `*`). Spawns `lsof -iTCP -sTCP:LISTEN
|
|
6
|
+
* -P -n -F n` and parses its machine-readable output. Returns the unique,
|
|
7
|
+
* numerically-sorted list of ports.
|
|
8
|
+
*
|
|
9
|
+
* Never throws. Returns `[]` whenever lsof is unavailable (e.g. Windows,
|
|
10
|
+
* unusual PATH), the spawn errors, exits non-zero, or the call exceeds
|
|
11
|
+
* `timeoutMs` (default 1000ms). The caller treats an empty list the same as
|
|
12
|
+
* "no listeners worth probing."
|
|
13
|
+
*/
|
|
14
|
+
async function listListeningPorts(opts) {
|
|
15
|
+
return uniqueSortedPorts(await listListeningTcpListeners(opts));
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Enumerate TCP LISTEN sockets on loopback/wildcard interfaces with enough
|
|
19
|
+
* metadata for CLI diagnostics. Never throws; an empty array means either no
|
|
20
|
+
* visible listeners or that process inspection is unavailable.
|
|
21
|
+
*/
|
|
22
|
+
async function listListeningTcpListeners(opts) {
|
|
23
|
+
const timeoutMs = opts?.timeoutMs ?? 1e3;
|
|
24
|
+
try {
|
|
25
|
+
return parseLsofListeners(await runLsof(timeoutMs));
|
|
26
|
+
} catch {
|
|
27
|
+
return [];
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
async function listenersForPort(port, opts) {
|
|
31
|
+
return (await listListeningTcpListeners(opts)).filter((listener) => listener.port === port);
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Spawn `lsof` with the canned argv and resolve to its stdout. Hand-rolled
|
|
35
|
+
* rather than `util.promisify(execFile)` because the latter resolves with a
|
|
36
|
+
* `{stdout, stderr}` object via its custom-promisify symbol — a heavier shape
|
|
37
|
+
* to mock and worse to read at the call site, where we only ever want stdout.
|
|
38
|
+
*/
|
|
39
|
+
function runLsof(timeoutMs) {
|
|
40
|
+
return new Promise((resolve, reject) => {
|
|
41
|
+
execFile("lsof", [
|
|
42
|
+
"-iTCP",
|
|
43
|
+
"-sTCP:LISTEN",
|
|
44
|
+
"-P",
|
|
45
|
+
"-n",
|
|
46
|
+
"-F",
|
|
47
|
+
"pcn"
|
|
48
|
+
], {
|
|
49
|
+
timeout: timeoutMs,
|
|
50
|
+
encoding: "utf8"
|
|
51
|
+
}, (err, stdout) => {
|
|
52
|
+
if (err) {
|
|
53
|
+
reject(err);
|
|
54
|
+
return;
|
|
55
|
+
}
|
|
56
|
+
resolve(stdout);
|
|
57
|
+
});
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Parse the pid (`p`), command (`c`), and name/address (`n`) records emitted by
|
|
62
|
+
* `lsof -F pcn`. Address records end in `:<port>` (e.g. `n*:8080`,
|
|
63
|
+
* `n127.0.0.1:3000`, `n[::1]:5050`). Only loopback/wildcard hosts are kept;
|
|
64
|
+
* external interface bindings are ignored.
|
|
65
|
+
*/
|
|
66
|
+
function parseLsofListeners(stdout) {
|
|
67
|
+
const listeners = [];
|
|
68
|
+
let pid;
|
|
69
|
+
let command;
|
|
70
|
+
for (const line of stdout.split(/\r?\n/)) {
|
|
71
|
+
if (line.startsWith("p")) {
|
|
72
|
+
const parsed = Number.parseInt(line.slice(1), 10);
|
|
73
|
+
pid = Number.isFinite(parsed) && parsed > 0 ? parsed : void 0;
|
|
74
|
+
command = void 0;
|
|
75
|
+
continue;
|
|
76
|
+
}
|
|
77
|
+
if (line.startsWith("c")) {
|
|
78
|
+
command = line.slice(1) || void 0;
|
|
79
|
+
continue;
|
|
80
|
+
}
|
|
81
|
+
if (!line.startsWith("n")) continue;
|
|
82
|
+
const address = line.slice(1);
|
|
83
|
+
const colon = address.lastIndexOf(":");
|
|
84
|
+
if (colon < 0) continue;
|
|
85
|
+
const host = address.slice(0, colon);
|
|
86
|
+
const portStr = address.slice(colon + 1);
|
|
87
|
+
if (!isLoopback(host)) continue;
|
|
88
|
+
const port = Number.parseInt(portStr, 10);
|
|
89
|
+
if (Number.isFinite(port) && port > 0 && port < 65536) listeners.push({
|
|
90
|
+
address,
|
|
91
|
+
command,
|
|
92
|
+
host,
|
|
93
|
+
pid,
|
|
94
|
+
port
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
return listeners.sort((a, b) => a.port - b.port || (a.pid ?? 0) - (b.pid ?? 0));
|
|
98
|
+
}
|
|
99
|
+
function uniqueSortedPorts(listeners) {
|
|
100
|
+
const ports = /* @__PURE__ */ new Set();
|
|
101
|
+
for (const listener of listeners) ports.add(listener.port);
|
|
102
|
+
return [...ports].sort((a, b) => a - b);
|
|
103
|
+
}
|
|
104
|
+
/** Recognised loopback host strings as emitted by `lsof -F n`. */
|
|
105
|
+
function isLoopback(host) {
|
|
106
|
+
return host === "*" || host === "127.0.0.1" || host === "[::1]" || host === "::1";
|
|
107
|
+
}
|
|
108
|
+
//#endregion
|
|
109
|
+
export { listenersForPort as n, listListeningPorts as t };
|
|
110
|
+
|
|
111
|
+
//# sourceMappingURL=ports-B09RjuHx.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ports-B09RjuHx.mjs","names":[],"sources":["../src/lib/prober/ports.ts"],"sourcesContent":["import { execFile } from \"node:child_process\";\n\nexport type TcpListener = Readonly<{\n address: string;\n command?: string;\n host: string;\n pid?: number;\n port: number;\n}>;\n\n/**\n * Enumerate TCP ports currently in LISTEN state on the loopback interface\n * (`127.0.0.1`, `::1`, or the wildcard `*`). Spawns `lsof -iTCP -sTCP:LISTEN\n * -P -n -F n` and parses its machine-readable output. Returns the unique,\n * numerically-sorted list of ports.\n *\n * Never throws. Returns `[]` whenever lsof is unavailable (e.g. Windows,\n * unusual PATH), the spawn errors, exits non-zero, or the call exceeds\n * `timeoutMs` (default 1000ms). The caller treats an empty list the same as\n * \"no listeners worth probing.\"\n */\nexport async function listListeningPorts(opts?: {\n readonly timeoutMs?: number;\n}): Promise<ReadonlyArray<number>> {\n const listeners = await listListeningTcpListeners(opts);\n return uniqueSortedPorts(listeners);\n}\n\n/**\n * Enumerate TCP LISTEN sockets on loopback/wildcard interfaces with enough\n * metadata for CLI diagnostics. Never throws; an empty array means either no\n * visible listeners or that process inspection is unavailable.\n */\nexport async function listListeningTcpListeners(opts?: {\n readonly timeoutMs?: number;\n}): Promise<ReadonlyArray<TcpListener>> {\n const timeoutMs = opts?.timeoutMs ?? 1000;\n try {\n const stdout = await runLsof(timeoutMs);\n return parseLsofListeners(stdout);\n } catch {\n return [];\n }\n}\n\nexport async function listenersForPort(\n port: number,\n opts?: { readonly timeoutMs?: number },\n): Promise<ReadonlyArray<TcpListener>> {\n return (await listListeningTcpListeners(opts)).filter((listener) => listener.port === port);\n}\n\n/**\n * Spawn `lsof` with the canned argv and resolve to its stdout. Hand-rolled\n * rather than `util.promisify(execFile)` because the latter resolves with a\n * `{stdout, stderr}` object via its custom-promisify symbol — a heavier shape\n * to mock and worse to read at the call site, where we only ever want stdout.\n */\nfunction runLsof(timeoutMs: number): Promise<string> {\n return new Promise<string>((resolve, reject) => {\n execFile(\n \"lsof\",\n [\"-iTCP\", \"-sTCP:LISTEN\", \"-P\", \"-n\", \"-F\", \"pcn\"],\n { timeout: timeoutMs, encoding: \"utf8\" },\n (err, stdout) => {\n if (err) {\n reject(err);\n return;\n }\n resolve(stdout);\n },\n );\n });\n}\n\n/**\n * Parse the pid (`p`), command (`c`), and name/address (`n`) records emitted by\n * `lsof -F pcn`. Address records end in `:<port>` (e.g. `n*:8080`,\n * `n127.0.0.1:3000`, `n[::1]:5050`). Only loopback/wildcard hosts are kept;\n * external interface bindings are ignored.\n */\nfunction parseLsofListeners(stdout: string): ReadonlyArray<TcpListener> {\n const listeners: TcpListener[] = [];\n let pid: number | undefined;\n let command: string | undefined;\n for (const line of stdout.split(/\\r?\\n/)) {\n if (line.startsWith(\"p\")) {\n const parsed = Number.parseInt(line.slice(1), 10);\n pid = Number.isFinite(parsed) && parsed > 0 ? parsed : undefined;\n command = undefined;\n continue;\n }\n if (line.startsWith(\"c\")) {\n command = line.slice(1) || undefined;\n continue;\n }\n if (!line.startsWith(\"n\")) {\n continue;\n }\n const address = line.slice(1);\n const colon = address.lastIndexOf(\":\");\n if (colon < 0) {\n continue;\n }\n const host = address.slice(0, colon);\n const portStr = address.slice(colon + 1);\n if (!isLoopback(host)) {\n continue;\n }\n const port = Number.parseInt(portStr, 10);\n if (Number.isFinite(port) && port > 0 && port < 65536) {\n listeners.push({ address, command, host, pid, port });\n }\n }\n return listeners.sort((a, b) => a.port - b.port || (a.pid ?? 0) - (b.pid ?? 0));\n}\n\nfunction uniqueSortedPorts(listeners: ReadonlyArray<TcpListener>): ReadonlyArray<number> {\n const ports = new Set<number>();\n for (const listener of listeners) {\n ports.add(listener.port);\n }\n return [...ports].sort((a, b) => a - b);\n}\n\n/** Recognised loopback host strings as emitted by `lsof -F n`. */\nfunction isLoopback(host: string): boolean {\n return host === \"*\" || host === \"127.0.0.1\" || host === \"[::1]\" || host === \"::1\";\n}\n"],"mappings":";;;;;;;;;;;;;AAqBA,eAAsB,mBAAmB,MAEN;AAEjC,QAAO,kBAAkB,MADD,0BAA0B,KAAK,CACpB;;;;;;;AAQrC,eAAsB,0BAA0B,MAER;CACtC,MAAM,YAAY,MAAM,aAAa;AACrC,KAAI;AAEF,SAAO,mBAAmB,MADL,QAAQ,UAAU,CACN;SAC3B;AACN,SAAO,EAAE;;;AAIb,eAAsB,iBACpB,MACA,MACqC;AACrC,SAAQ,MAAM,0BAA0B,KAAK,EAAE,QAAQ,aAAa,SAAS,SAAS,KAAK;;;;;;;;AAS7F,SAAS,QAAQ,WAAoC;AACnD,QAAO,IAAI,SAAiB,SAAS,WAAW;AAC9C,WACE,QACA;GAAC;GAAS;GAAgB;GAAM;GAAM;GAAM;GAAM,EAClD;GAAE,SAAS;GAAW,UAAU;GAAQ,GACvC,KAAK,WAAW;AACf,OAAI,KAAK;AACP,WAAO,IAAI;AACX;;AAEF,WAAQ,OAAO;IAElB;GACD;;;;;;;;AASJ,SAAS,mBAAmB,QAA4C;CACtE,MAAM,YAA2B,EAAE;CACnC,IAAI;CACJ,IAAI;AACJ,MAAK,MAAM,QAAQ,OAAO,MAAM,QAAQ,EAAE;AACxC,MAAI,KAAK,WAAW,IAAI,EAAE;GACxB,MAAM,SAAS,OAAO,SAAS,KAAK,MAAM,EAAE,EAAE,GAAG;AACjD,SAAM,OAAO,SAAS,OAAO,IAAI,SAAS,IAAI,SAAS,KAAA;AACvD,aAAU,KAAA;AACV;;AAEF,MAAI,KAAK,WAAW,IAAI,EAAE;AACxB,aAAU,KAAK,MAAM,EAAE,IAAI,KAAA;AAC3B;;AAEF,MAAI,CAAC,KAAK,WAAW,IAAI,CACvB;EAEF,MAAM,UAAU,KAAK,MAAM,EAAE;EAC7B,MAAM,Q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