vela 0.10.12 → 0.10.13

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/dist/bin.js.map CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../src/bin.ts", "../package.json", "../src/lib/argv.ts", "../src/lib/delegate.ts", "../src/program.ts", "../src/lib/help.ts", "../src/lib/stub.ts", "../src/lib/run.ts", "../src/lib/errors.ts", "../src/lib/workspace.ts", "../src/lib/constants.ts", "../src/lib/package-json.ts", "../src/commands/bless.ts", "../src/lib/options.ts", "../src/lib/templates.ts", "../src/lib/package-manager.ts", "../src/lib/pocketbase.ts", "../src/lib/env.ts", "../src/lib/config-merge.ts", "../src/lib/config-target.ts", "../src/lib/scaffold-detect.ts", "../src/lib/result-report.ts", "../src/lib/template-files.ts", "../src/commands/create.ts", "../src/commands/generate.ts", "../src/commands/generate/form.ts", "../src/lib/pattern-runner.ts", "../src/lib/ai-flow.ts", "../src/lib/config.ts", "../src/lib/project-config.ts", "../src/lib/ai-client.ts", "../src/lib/ai-loop.ts", "../src/lib/ai-existing-models.ts", "../src/lib/ai-to-argv.ts", "../src/lib/ai-grid.ts", "../src/commands/generate/schema.ts", "../src/commands/generate/resource.ts", "../src/commands/generate/scaffold.ts", "../src/commands/generate/migration.ts", "../src/commands/enable.ts", "../src/commands/enable/auth.ts", "../src/commands/enable/api.ts", "../src/commands/enable/api-keys.ts", "../src/commands/enable/backend.ts", "../src/commands/enable/i18n.ts", "../src/commands/enable/teams.ts", "../src/commands/enable/payments.ts", "../src/commands/enable/subscriptions.ts", "../src/commands/enable/s3.ts", "../src/lib/server-command.ts", "../src/lib/deploy-config.ts", "../src/lib/instance.ts", "../src/lib/ssh-options.ts", "../src/lib/ssh.ts", "../src/lib/remote.ts", "../src/lib/remote-env.ts", "../src/lib/target.ts", "../src/lib/backup-target.ts", "../src/lib/local-env.ts", "../src/lib/remote-pocketbase.ts", "../src/lib/s3-settings.ts", "../src/commands/enable/smtp.ts", "../src/commands/enable/cms.ts", "../src/commands/enable/blog.ts", "../src/commands/enable/content-negotiation.ts", "../src/commands/disable.ts", "../src/commands/disable/auth.ts", "../src/commands/disable/_shared.ts", "../src/commands/disable/api.ts", "../src/commands/disable/api-keys.ts", "../src/commands/disable/backend.ts", "../src/commands/disable/content-negotiation.ts", "../src/commands/disable/i18n.ts", "../src/commands/disable/teams.ts", "../src/commands/disable/payments.ts", "../src/commands/disable/s3.ts", "../src/commands/disable/smtp.ts", "../src/commands/destroy.ts", "../src/commands/destroy/form.ts", "../src/commands/destroy/_shared.ts", "../src/commands/destroy/schema.ts", "../src/commands/destroy/resource.ts", "../src/commands/destroy/scaffold.ts", "../src/commands/destroy/deployment.ts", "../src/commands/ui.ts", "../src/commands/ui/add.ts", "../src/commands/ui/base.ts", "../src/commands/legal.ts", "../src/commands/legal/terms.ts", "../src/commands/legal/shared.ts", "../src/commands/legal/privacy.ts", "../src/commands/fixtures.ts", "../src/commands/fixtures/load.ts", "../src/commands/fixtures/clear.ts", "../src/lib/collections.ts", "../src/commands/fixtures/reset.ts", "../src/commands/fixtures/generate.ts", "../src/commands/fixtures/regen.ts", "../src/commands/seeds.ts", "../src/commands/seeds/load.ts", "../src/commands/seeds/save.ts", "../src/commands/seeds/clear.ts", "../src/commands/signup.ts", "../src/commands/login.ts", "../src/commands/logout.ts", "../src/commands/whoami.ts", "../src/commands/migrate.ts", "../src/commands/migrate/up.ts", "../src/lib/migrate.ts", "../src/commands/migrate/down.ts", "../src/commands/migrate/create.ts", "../src/commands/migrate/collections.ts", "../src/commands/migrate/history-sync.ts", "../src/commands/dev.ts", "../src/lib/vite.ts", "../src/commands/build.ts", "../src/lib/build-env.ts", "../src/lib/origin.ts", "../src/commands/preview.ts", "../src/commands/sync.ts", "../src/commands/provision.ts", "../src/commands/deploy.ts", "../src/lib/pocketbase-settings.ts", "../src/lib/artifact.ts", "../src/commands/link.ts", "../src/lib/velastack-api.ts", "../src/commands/env.ts", "../src/commands/env/list.ts", "../src/commands/env/set.ts", "../src/commands/env/unset.ts", "../src/commands/env/import.ts", "../src/commands/status.ts", "../src/commands/rollback.ts", "../src/commands/logs.ts", "../src/commands/admin.ts", "../src/commands/admin/create.ts", "../src/commands/backup.ts", "../src/commands/backup/create.ts", "../src/lib/backups.ts", "../src/commands/backup/list.ts", "../src/commands/backup/download.ts", "../src/commands/backup/delete.ts", "../src/commands/backup/schedule.ts", "../src/commands/restore.ts", "../src/commands/targets.ts", "../src/commands/test.ts", "../src/commands/routes.ts", "../src/commands/i18n.ts", "../src/commands/oauth.ts", "../src/commands/schemas.ts", "../src/commands/cms.ts", "../src/commands/cms/editor.ts", "../src/commands/cms/editor/add.ts", "../src/lib/cms-backend.ts", "../src/commands/cms/editor/password.ts", "../src/commands/cms/editor/list.ts"],
4
- "sourcesContent": ["import process from 'node:process';\nimport { fileURLToPath } from 'node:url';\nimport pkg from '../package.json' with { type: 'json' };\nimport { normalizeArgv } from './lib/argv.ts';\nimport { delegateToLocalCli } from './lib/delegate.ts';\nimport { program } from './program.ts';\n\n// Normalized before delegating so a pinned CLI is handed the same arguments.\nconst argv = normalizeArgv(process.argv.slice(2));\n\nconst delegatedExitCode = delegateToLocalCli({\n\targv,\n\tselfPath: fileURLToPath(import.meta.url),\n\tselfVersion: pkg.version\n});\n\nif (delegatedExitCode !== null) {\n\tprocess.exit(delegatedExitCode);\n}\n\nprogram.parse(argv, { from: 'user' });\n", "{\n\t\"name\": \"vela\",\n\t\"version\": \"0.10.12\",\n\t\"type\": \"module\",\n\t\"description\": \"A CLI for creating and updating SvelteKit projects\",\n\t\"license\": \"MIT\",\n\t\"repository\": {\n\t\t\"type\": \"git\",\n\t\t\"url\": \"git+https://github.com/velastack/vela.git\"\n\t},\n\t\"homepage\": \"https://velastack.dev\",\n\t\"engines\": {\n\t\t\"node\": \">=20\"\n\t},\n\t\"bin\": {\n\t\t\"vela\": \"./dist/bin.js\",\n\t\t\"velastack\": \"./dist/bin.js\"\n\t},\n\t\"files\": [\n\t\t\"dist\",\n\t\t\"templates\"\n\t],\n\t\"scripts\": {\n\t\t\"build\": \"node --experimental-strip-types scripts/build.ts\",\n\t\t\"dev\": \"node --experimental-strip-types scripts/build.ts --watch\",\n\t\t\"clean\": \"rm -rf dist\",\n\t\t\"lint\": \"npm run lint:ts && npm run lint:format\",\n\t\t\"lint:ts\": \"tsc --noEmit\",\n\t\t\"lint:format\": \"prettier --check .\",\n\t\t\"format\": \"prettier --write .\",\n\t\t\"test\": \"vitest run\",\n\t\t\"prepare\": \"npm run build\"\n\t},\n\t\"dependencies\": {\n\t\t\"@clack/prompts\": \"^1.7.0\",\n\t\t\"@faker-js/faker\": \"^10.6.0\",\n\t\t\"@velastack/patterns\": \"^0.1.9\",\n\t\t\"@velastack/pocketbase-codegen\": \"^0.1.0\",\n\t\t\"annotate-json-schema\": \"^0.1.0\",\n\t\t\"commander\": \"^13.1.0\",\n\t\t\"cross-spawn\": \"^7.0.6\",\n\t\t\"dedent\": \"^1.7.2\",\n\t\t\"dotenv\": \"^17.4.2\",\n\t\t\"fetch-cookie\": \"^3.2.0\",\n\t\t\"json-schema-faker\": \"^0.6.3\",\n\t\t\"magic-string\": \"^0.30.21\",\n\t\t\"package-manager-detector\": \"^1.8.0\",\n\t\t\"picocolors\": \"^1.1.1\",\n\t\t\"pocketbase\": \"^0.28.0\",\n\t\t\"pocketbase-server\": \"^0.39.11\",\n\t\t\"stripe\": \"^19.3.0\",\n\t\t\"svelte\": \"^5.56.10\",\n\t\t\"tinyexec\": \"^1.3.0\",\n\t\t\"ts-morph\": \"^28.0.0\",\n\t\t\"valibot\": \"^1.4.2\"\n\t},\n\t\"devDependencies\": {\n\t\t\"@types/cross-spawn\": \"^6.0.6\",\n\t\t\"@types/node\": \"^22.0.0\",\n\t\t\"esbuild\": \"^0.28.2\",\n\t\t\"prettier\": \"^3.9.6\",\n\t\t\"typescript\": \"^5.6.0\",\n\t\t\"vite\": \"^8.2.2\",\n\t\t\"vitest\": \"^4.1.11\"\n\t},\n\t\"peerDependencies\": {\n\t\t\"@sveltejs/kit\": \"^2.57.1\",\n\t\t\"vite\": \"^8.0.8\"\n\t},\n\t\"peerDependenciesMeta\": {\n\t\t\"@sveltejs/kit\": {\n\t\t\t\"optional\": true\n\t\t},\n\t\t\"vite\": {\n\t\t\t\"optional\": true\n\t\t}\n\t},\n\t\"keywords\": [\n\t\t\"svelte\",\n\t\t\"sveltekit\",\n\t\t\"velastack\",\n\t\t\"pocketbase\",\n\t\t\"cli\",\n\t\t\"starter\",\n\t\t\"template\"\n\t]\n}\n", "/**\n * Drop one `--` separator from the arguments.\n *\n * `npm run dev -- --open` is the idiom for forwarding flags through npm, and npm\n * strips the separator before the script sees it \u2014 so a template script running\n * `vela dev` receives a plain `--open`. Typed straight at the CLI the separator\n * survives, and commander reads everything after it as a positional argument, so\n * `vela dev -- --open` fails with \"too many arguments\" instead of opening a\n * browser.\n *\n * No vela command takes an argument that could be mistaken for a flag, so the\n * separator carries no meaning here. Removing it makes both spellings agree.\n */\nexport function normalizeArgv(argv: string[]): string[] {\n\tconst separator = argv.indexOf('--');\n\tif (separator === -1) return argv;\n\treturn [...argv.slice(0, separator), ...argv.slice(separator + 1)];\n}\n", "import fs from 'node:fs';\nimport path from 'node:path';\nimport process from 'node:process';\nimport { spawnSync } from 'node:child_process';\n\n/**\n * The CLI is normally installed globally, but a project pins its own copy as a\n * dev dependency so that generated source, migrations, and builds are\n * reproducible across machines and CI. When a global `vela` is invoked inside a\n * project that pins a different version, hand off to the pinned one \u2014 otherwise\n * the same command produces different output depending on who ran it.\n *\n * `create` and `bless` are exempt: they bootstrap or convert a project, so they\n * should use the version the user actually invoked rather than inherit the pin\n * of whatever project happens to be above the working directory.\n */\nconst NO_DELEGATE_COMMANDS = new Set(['create', 'bless']);\n\n/** Set on the delegated child so it can never hand off again. */\nexport const NO_DELEGATE_ENV = 'VELA_NO_DELEGATE';\n\nexport interface LocalCli {\n\tbinPath: string;\n\tversion: string;\n}\n\nfunction realpath(target: string): string {\n\ttry {\n\t\treturn fs.realpathSync(target);\n\t} catch {\n\t\treturn path.resolve(target);\n\t}\n}\n\n/**\n * Find a project-local `vela` at or above `cwd` that differs from the running\n * one. Returns null when there is nothing to hand off to: no local install, the\n * local install *is* the running one, or the two are the same version.\n */\nexport function findLocalCli(cwd: string, selfPath: string): LocalCli | null {\n\tconst self = realpath(selfPath);\n\tlet dir = path.resolve(cwd);\n\n\tfor (;;) {\n\t\tconst pkgPath = path.join(dir, 'node_modules', 'vela', 'package.json');\n\t\tif (fs.existsSync(pkgPath)) {\n\t\t\tconst local = readLocalCli(pkgPath);\n\t\t\tif (local && realpath(local.binPath) !== self) return local;\n\t\t\treturn null;\n\t\t}\n\t\tconst parent = path.dirname(dir);\n\t\tif (parent === dir) return null;\n\t\tdir = parent;\n\t}\n}\n\nfunction readLocalCli(pkgPath: string): LocalCli | null {\n\tlet pkg: { version?: unknown; bin?: unknown };\n\ttry {\n\t\tpkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8'));\n\t} catch {\n\t\treturn null;\n\t}\n\n\tconst version = typeof pkg.version === 'string' ? pkg.version : null;\n\tconst bin = pkg.bin;\n\tconst rel = typeof bin === 'string' ? bin : isRecord(bin) ? bin.vela : undefined;\n\tif (!version || typeof rel !== 'string') return null;\n\n\tconst binPath = path.resolve(path.dirname(pkgPath), rel);\n\tif (!fs.existsSync(binPath)) return null;\n\treturn { binPath, version };\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === 'object' && value !== null;\n}\n\n/** True when `argv` names a command that must not be handed off. */\nexport function isDelegatable(argv: string[]): boolean {\n\tconst first = argv.find((arg) => !arg.startsWith('-'));\n\treturn first === undefined || !NO_DELEGATE_COMMANDS.has(first);\n}\n\nexport interface DelegateOptions {\n\targv?: string[];\n\tcwd?: string;\n\tselfPath: string;\n\tselfVersion: string;\n\tenv?: NodeJS.ProcessEnv;\n}\n\n/**\n * Hand off to a project-local CLI when one is pinned at a different version.\n * Returns the child's exit code, or null when the running CLI should handle the\n * command itself.\n */\nexport function delegateToLocalCli(opts: DelegateOptions): number | null {\n\tconst env = opts.env ?? process.env;\n\tif (env[NO_DELEGATE_ENV]) return null;\n\n\tconst argv = opts.argv ?? process.argv.slice(2);\n\tif (!isDelegatable(argv)) return null;\n\n\tconst local = findLocalCli(opts.cwd ?? process.cwd(), opts.selfPath);\n\tif (!local || local.version === opts.selfVersion) return null;\n\n\tconst result = spawnSync(process.execPath, [local.binPath, ...argv], {\n\t\tstdio: 'inherit',\n\t\tenv: { ...env, [NO_DELEGATE_ENV]: '1' }\n\t});\n\n\tif (result.error) return null;\n\tif (result.signal) return 1;\n\treturn result.status ?? 0;\n}\n", "import process from 'node:process';\nimport * as p from '@clack/prompts';\nimport { Command } from 'commander';\nimport nodePath from 'node:path';\nimport dotenv from 'dotenv';\nimport pc from 'picocolors';\nimport pkg from '../package.json' with { type: 'json' };\nimport { helpConfig } from './lib/help.ts';\nimport { isStub } from './lib/stub.ts';\nimport { findWorkspaceRoot, hasBackend } from './lib/workspace.ts';\nimport { bless } from './commands/bless.ts';\nimport { create } from './commands/create.ts';\nimport { generate } from './commands/generate.ts';\nimport { enable } from './commands/enable.ts';\nimport { disable } from './commands/disable.ts';\nimport { destroy } from './commands/destroy.ts';\nimport { ui } from './commands/ui.ts';\nimport { legal } from './commands/legal.ts';\nimport { fixtures } from './commands/fixtures.ts';\nimport { seeds } from './commands/seeds.ts';\nimport { signup } from './commands/signup.ts';\nimport { login } from './commands/login.ts';\nimport { logout } from './commands/logout.ts';\nimport { whoami } from './commands/whoami.ts';\nimport { migrate } from './commands/migrate.ts';\nimport { dev } from './commands/dev.ts';\nimport { build } from './commands/build.ts';\nimport { preview } from './commands/preview.ts';\nimport { sync } from './commands/sync.ts';\nimport { provision } from './commands/provision.ts';\nimport { deploy } from './commands/deploy.ts';\nimport { link } from './commands/link.ts';\nimport { env } from './commands/env.ts';\nimport { status } from './commands/status.ts';\nimport { rollback } from './commands/rollback.ts';\nimport { logs } from './commands/logs.ts';\nimport { admin } from './commands/admin.ts';\nimport { backup } from './commands/backup.ts';\nimport { restore } from './commands/restore.ts';\nimport { targets } from './commands/targets.ts';\nimport { testServer } from './commands/test.ts';\nimport { routes } from './commands/routes.ts';\nimport { i18n } from './commands/i18n.ts';\nimport { oauth } from './commands/oauth.ts';\nimport { schemas } from './commands/schemas.ts';\nimport { cms } from './commands/cms.ts';\n\n/**\n * Commands that never touch the database, whether or not the project has one.\n */\nconst NO_BACKEND_COMMMANDS = new Set([\n\t'bless',\n\t'create',\n\t'signup',\n\t'login',\n\t'logout',\n\t'whoami',\n\t'legal',\n\t'ui',\n\t'routes',\n\t'i18n',\n\t'generate schema',\n\t'generate form',\n\t// The CMS keeps its own SQLite database and editors; PocketBase is never involved.\n\t'enable cms',\n\t'cms',\n\t// Server commands talk to a VPS over SSH, never to the local database.\n\t'provision',\n\t'env',\n\t'status',\n\t'rollback',\n\t'logs',\n\t'admin',\n\t'targets',\n\t'link',\n\t// Acts on whichever target `-t` names; the local path reads the project's\n\t// own credentials rather than requiring them in this process.\n\t'backup',\n\t'restore'\n]);\n\n/**\n * Commands that drive the frontend build and so work with or without a backend.\n * In a backend project they still start PocketBase, which is why they are not in\n * NO_BACKEND_COMMMANDS.\n */\nconst BACKEND_OPTIONAL_COMMANDS = new Set(['dev', 'build', 'preview', 'deploy']);\n\nexport const program = new Command()\n\t.name(pkg.name)\n\t.description(pkg.description)\n\t.version(pkg.version, '-v, --version')\n\t.configureHelp(helpConfig);\n\nprogram.hook('preAction', (_thisCommand, actionCommand) => {\n\tif (isStub(actionCommand)) return;\n\n\t// Resolved from the workspace root rather than the cwd: dotenv's default\n\t// would miss `.env` for anything run from a subdirectory, which `-t local`\n\t// makes visible the moment a command reads or writes it.\n\tconst envRoot = findWorkspaceRoot() ?? process.cwd();\n\tdotenv.config({ path: nodePath.join(envRoot, '.env'), quiet: true });\n\n\tconst path = getCommandPath(actionCommand);\n\tif (NO_BACKEND_COMMMANDS.has(path)) return;\n\tconst top = path.split(' ', 1)[0];\n\tif (NO_BACKEND_COMMMANDS.has(top)) return;\n\n\t// A static project has no PocketBase, so there are no credentials to ask for.\n\t// Frontend commands carry on; anything that needs the database says so plainly\n\t// rather than sending the user off to look for a .env that would not help.\n\tif (!hasBackend()) {\n\t\tif (BACKEND_OPTIONAL_COMMANDS.has(top)) return;\n\n\t\tp.log.error(\n\t\t\t`${pc.cyan(`vela ${path}`)} needs a backend, and this project does not have one.\\n\\n` +\n\t\t\t\t`Static projects have no database to talk to.\\n\\n` +\n\t\t\t\t`To add a backend to this project, run ${pc.cyan('vela bless')}.`\n\t\t);\n\t\tp.log.message();\n\t\tp.cancel('Operation failed.');\n\t\tprocess.exit(1);\n\t}\n\n\tif (!process.env.POCKETBASE_SUPERUSER_EMAIL || !process.env.POCKETBASE_SUPERUSER_PASSWORD) {\n\t\tp.log.error(\n\t\t\t`PocketBase superuser credentials are required.\\n\\n` +\n\t\t\t\t`Set ${pc.cyan('POCKETBASE_SUPERUSER_EMAIL')} and ${pc.cyan('POCKETBASE_SUPERUSER_PASSWORD')} in your .env file.\\n\\n` +\n\t\t\t\t`To set up a new project, run ${pc.cyan('vela create')}.\\n` +\n\t\t\t\t`To set up an existing project, run ${pc.cyan('vela bless')}.`\n\t\t);\n\t\tp.log.message();\n\t\tp.cancel('Operation failed.');\n\t\tprocess.exit(1);\n\t}\n});\n\nfunction getCommandPath(cmd: Command): string {\n\tconst names: string[] = [];\n\tlet current: Command | null = cmd;\n\twhile (current && current.parent) {\n\t\tnames.unshift(current.name());\n\t\tcurrent = current.parent;\n\t}\n\treturn names.join(' ');\n}\n\nfor (const command of [\n\tbless,\n\tcreate,\n\tgenerate,\n\tenable,\n\tdisable,\n\tdestroy,\n\tui,\n\tlegal,\n\tfixtures,\n\tseeds,\n\tsignup,\n\tlogin,\n\tlogout,\n\twhoami,\n\tmigrate,\n\tdev,\n\tbuild,\n\tpreview,\n\tsync,\n\tprovision,\n\tdeploy,\n\trollback,\n\tstatus,\n\tlogs,\n\tenv,\n\tadmin,\n\tbackup,\n\trestore,\n\ttargets,\n\tlink,\n\ttestServer,\n\troutes,\n\ti18n,\n\toauth,\n\tschemas,\n\tcms\n]) {\n\tprogram.addCommand(command);\n}\n", "import pc from 'picocolors';\nimport type { Argument, HelpConfiguration, Option } from 'commander';\n\nconst NO_PREFIX = '--no-';\nlet currentOptions: readonly Option[] = [];\n\nfunction getLongFlag(flags: string) {\n\treturn flags\n\t\t.split(',')\n\t\t.map((f) => f.trim())\n\t\t.find((f) => f.startsWith('--'));\n}\n\nfunction formatDescription(arg: Option | Argument): string {\n\tlet output = arg.description;\n\tif (arg.defaultValue !== undefined && String(arg.defaultValue)) {\n\t\toutput += pc.dim(` (default: ${JSON.stringify(arg.defaultValue)})`);\n\t}\n\tif (arg.argChoices !== undefined && String(arg.argChoices)) {\n\t\toutput += pc.dim(` (choices: ${arg.argChoices.join(', ')})`);\n\t}\n\treturn output;\n}\n\nexport const helpConfig: HelpConfiguration = {\n\targumentDescription: formatDescription,\n\toptionDescription: formatDescription,\n\tvisibleOptions(cmd) {\n\t\tcurrentOptions = cmd.options;\n\n\t\tconst visible = cmd.options.filter((o) => !o.hidden);\n\t\tconst show: Option[] = [];\n\t\tfor (const option of visible) {\n\t\t\tconst flag = getLongFlag(option.flags);\n\t\t\tif (flag?.startsWith(NO_PREFIX)) {\n\t\t\t\tconst stripped = flag.slice(NO_PREFIX.length);\n\t\t\t\tconst isNoVariant = visible.some((o) => getLongFlag(o.flags)?.startsWith(`--${stripped}`));\n\t\t\t\tif (isNoVariant) continue;\n\t\t\t}\n\t\t\tshow.push(option);\n\t\t}\n\t\treturn show;\n\t},\n\tsubcommandTerm: (cmd) => {\n\t\treturn cmd.name() + ' ' + cmd.usage().replace(/\\[options\\]\\s?/, '');\n\t},\n\toptionTerm(option) {\n\t\tconst longFlag = getLongFlag(option.flags);\n\t\tconst flag = longFlag?.split(' ').at(0);\n\t\tif (!flag || !longFlag) return option.flags;\n\n\t\tconst noVariant = `--no-${flag.slice(2)}`;\n\t\tconst hasVariant = currentOptions.some((o) => getLongFlag(o.flags) === noVariant);\n\t\tif (hasVariant) {\n\t\t\treturn `--[no-]${longFlag.slice(2)}`;\n\t\t}\n\n\t\treturn option.flags;\n\t},\n\tstyleTitle: (str) => pc.underline(str),\n\tstyleCommandText: (str) => pc.redBright(str),\n\tstyleDescriptionText: (str) => pc.gray(str),\n\tstyleOptionText: (str) => pc.white(str),\n\tstyleArgumentText: (str) => pc.white(str),\n\tstyleSubcommandText: (str) => pc.redBright(str)\n};\n", "import { Command } from 'commander';\nimport { helpConfig } from './help.ts';\nimport { notImplemented } from './run.ts';\n\nexport const STUB = Symbol('stub');\n\ninterface StubCommand extends Command {\n\t[STUB]?: true;\n}\n\nexport function isStub(cmd: Command): boolean {\n\treturn (cmd as StubCommand)[STUB] === true;\n}\n\nexport function stubCommand(name: string, description: string, fullName?: string): Command {\n\tconst cmd: StubCommand = new Command(name)\n\t\t.description(description)\n\t\t.configureHelp(helpConfig)\n\t\t.action(() => notImplemented(fullName ?? name));\n\tcmd[STUB] = true;\n\treturn cmd;\n}\n", "import * as p from '@clack/prompts';\nimport pc from 'picocolors';\nimport { UnsupportedError } from './errors.ts';\n\ntype MaybePromise = () => Promise<void> | void;\n\nexport async function runCommand(action: MaybePromise, failureMessage?: string): Promise<void> {\n\ttry {\n\t\tawait action();\n\t} catch (e) {\n\t\tif (e instanceof UnsupportedError) {\n\t\t\tconst padding = Math.max(...e.reasons.map((r) => r.id.length), 0);\n\t\t\tconst message = e.reasons\n\t\t\t\t.map((r) => ` ${r.id.padEnd(padding)} ${pc.redBright(r.reason)}`)\n\t\t\t\t.join('\\n');\n\t\t\tp.log.error(`${e.name}\\n\\n${message}`);\n\t\t\tp.log.message();\n\t\t} else if (e instanceof Error) {\n\t\t\tconst prefix = failureMessage ? `${failureMessage} ` : '';\n\t\t\tp.log.error(`${prefix}${e.message}`);\n\t\t\tp.log.message();\n\t\t}\n\t\tp.cancel('Operation failed.');\n\t\tprocess.exitCode = 1;\n\t}\n}\n\nexport function notImplemented(name: string) {\n\treturn runCommand(async () => {\n\t\tp.log.warn(`\\`${name}\\` is not yet implemented \u2014 see ${pc.cyan('https://docs.velastack.dev')}`);\n\t});\n}\n", "type Reason = { id: string; reason: string };\n\nexport class UnsupportedError extends Error {\n\toverride name = 'Unsupported Environment';\n\treasons: Reason[];\n\tconstructor(reasons: Reason[]) {\n\t\tsuper();\n\t\tthis.reasons = reasons;\n\t}\n}\n", "import fs from 'node:fs';\nimport path from 'node:path';\nimport process from 'node:process';\nimport { APP_DIR, PUBLIC_DIR, DATA_DIR } from './constants.ts';\nimport { readPackageJson } from './package-json.ts';\n\nexport interface Features {\n\tauth: boolean;\n\tapi: boolean;\n\tapiKeys: boolean;\n\tbackend: boolean;\n\ti18n: boolean;\n\tteams: boolean;\n\tpayments: boolean;\n\tblog: boolean;\n\tcontentNegotiation: boolean;\n\tcms: boolean;\n}\n\nexport interface Workspace {\n\tworkspaceRootDir: string;\n\troutesDir: string;\n\tpublicRoutesDir: string;\n\tappRoutesDir?: string;\n\tisAppMode: boolean;\n\tisPaymentsMode: boolean;\n\tfeatures: Features;\n}\n\n/**\n * Nearest ancestor holding a package.json, or null when there is none.\n */\nexport function findWorkspaceRoot(from: string = process.cwd()): string | null {\n\tlet currentDir = from;\n\n\twhile (currentDir !== path.parse(currentDir).root) {\n\t\tif (fs.existsSync(path.join(currentDir, 'package.json'))) return currentDir;\n\t\tcurrentDir = path.dirname(currentDir);\n\t}\n\n\treturn null;\n}\n\n/**\n * Whether the project has a PocketBase backend at all.\n *\n * The `data` directory is the marker: `vela create` writes it for backend\n * templates and `vela bless` adds it to an existing project, while the static\n * template has none. Commands that would start or talk to PocketBase have to\n * check this first \u2014 a static project has no database, and therefore no\n * credentials to ask for.\n *\n * Kept in step with `Features.backend`, which is derived from the same marker.\n */\nexport function hasBackend(from: string = process.cwd()): boolean {\n\tconst root = findWorkspaceRoot(from);\n\treturn root !== null && fs.existsSync(path.join(root, DATA_DIR));\n}\n\n/**\n * Where this project keeps the state that is not source.\n *\n * The same directory on a server is `shared/pb_data`, which is the whole reason\n * `vela` puts it in the environment as `VELA_DATA_DIR` instead of letting an app\n * work it out from its own working directory. That one is the project root here\n * and a release directory there, so an app that derives the path lands its\n * database inside a release \u2014 where the next deploy leaves it behind and the\n * pruner eventually deletes it.\n */\nexport function localDataDir(from: string = process.cwd()): string {\n\treturn path.join(findWorkspaceRoot(from) ?? from, DATA_DIR);\n}\n\nexport async function getWorkspace(): Promise<Workspace> {\n\tconst workspaceRootDir = findWorkspaceRoot();\n\n\tif (!workspaceRootDir) {\n\t\tthrow new Error('Could not find workspace root (no package.json found)');\n\t}\n\n\tconst routesDir = path.join('src', 'routes');\n\tconst fullRoutesPath = path.join(workspaceRootDir, routesDir);\n\n\tif (!fs.existsSync(fullRoutesPath)) {\n\t\tthrow new Error('Could not find src/routes directory');\n\t}\n\n\tlet publicRoutesDir = path.join(routesDir, PUBLIC_DIR);\n\tif (!fs.existsSync(path.join(workspaceRootDir, publicRoutesDir))) {\n\t\tpublicRoutesDir = routesDir;\n\t}\n\n\tlet appRoutesDir: string | undefined;\n\tconst appRoutesPath = path.join(fullRoutesPath, APP_DIR);\n\tconst isAppMode = fs.existsSync(appRoutesPath);\n\tif (isAppMode) appRoutesDir = path.join(routesDir, APP_DIR);\n\n\tconst isPaymentsMode = fs.existsSync(\n\t\tpath.join(workspaceRootDir, routesDir, 'webhooks', 'stripe')\n\t);\n\n\tconst features = detectFeatures(workspaceRootDir, { isAppMode, isPaymentsMode });\n\n\treturn {\n\t\tworkspaceRootDir,\n\t\troutesDir,\n\t\tpublicRoutesDir,\n\t\tappRoutesDir,\n\t\tisAppMode,\n\t\tisPaymentsMode,\n\t\tfeatures\n\t};\n}\n\nfunction detectFeatures(\n\troot: string,\n\t{ isAppMode, isPaymentsMode }: { isAppMode: boolean; isPaymentsMode: boolean }\n): Features {\n\tconst has = (rel: string) => fs.existsSync(path.join(root, rel));\n\tconst pkg = readPackageJson(path.join(root, 'package.json'));\n\tconst hasDep = (name: string) => Boolean(pkg.dependencies?.[name] || pkg.devDependencies?.[name]);\n\n\treturn {\n\t\tauth: isAppMode,\n\t\tapi: has('src/routes/api'),\n\t\tapiKeys: has('src/routes/api/api-keys') || has('src/routes/(app)/api-keys'),\n\t\tbackend: has(DATA_DIR),\n\t\ti18n: has('wuchale.config.js') || hasDep('wuchale'),\n\t\tteams: has('src/routes/(app)/teams') || has('src/lib/teams'),\n\t\tpayments: isPaymentsMode,\n\t\tblog: hasDep('mdsvex'),\n\t\tcontentNegotiation: hasDep('sveltekit-negotiate'),\n\t\tcms: hasDep('@velastack/cms')\n\t};\n}\n", "export const DATA_DIR = 'data';\nexport const MIGRATIONS_DIR = 'migrations';\nexport const PUBLIC_DIR = '(public)';\nexport const APP_DIR = '(app)';\nexport const LEGAL_DIR = '(legal)';\nexport const API_URL = 'https://velastack.dev';\nexport const FIXTURE_PREFIX = 'vela';\n", "import fs from 'node:fs';\n\nexport type DepKind = 'dependencies' | 'devDependencies';\nconst DEP_KINDS: DepKind[] = ['dependencies', 'devDependencies'];\n\nexport interface MergeChange {\n\tkind: DepKind | 'scripts';\n\tname: string;\n\ttemplateValue: string;\n\tuserValue?: string;\n}\n\nexport interface MergeResult {\n\tmerged: Record<string, unknown>;\n\tadded: MergeChange[];\n\tconflicts: MergeChange[];\n\treplaced: MergeChange[];\n}\n\ntype PkgJson = Record<string, unknown> & {\n\tdependencies?: Record<string, string>;\n\tdevDependencies?: Record<string, string>;\n\tscripts?: Record<string, string>;\n};\n\nexport function mergePackageJson(user: PkgJson, template: PkgJson): MergeResult {\n\tconst merged: PkgJson = structuredClone(user);\n\tconst added: MergeChange[] = [];\n\tconst conflicts: MergeChange[] = [];\n\tconst replaced: MergeChange[] = [];\n\n\tfor (const kind of DEP_KINDS) {\n\t\tconst templateDeps = template[kind];\n\t\tif (!templateDeps) continue;\n\n\t\tconst userDeps = (merged[kind] ??= {}) as Record<string, string>;\n\t\tconst otherKind: DepKind = kind === 'dependencies' ? 'devDependencies' : 'dependencies';\n\t\tconst userOther = (user[otherKind] ?? {}) as Record<string, string>;\n\n\t\tfor (const [name, templateValue] of Object.entries(templateDeps)) {\n\t\t\tif (name in userDeps) {\n\t\t\t\tif (userDeps[name] !== templateValue) {\n\t\t\t\t\tconflicts.push({ kind, name, templateValue, userValue: userDeps[name] });\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (name in userOther) {\n\t\t\t\t// already pinned in the other bucket \u2014 leave it there, don't duplicate.\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tuserDeps[name] = templateValue;\n\t\t\tadded.push({ kind, name, templateValue });\n\t\t}\n\t}\n\n\tconst templateScripts = template.scripts;\n\tif (templateScripts) {\n\t\tconst userScripts = (merged.scripts ??= {}) as Record<string, string>;\n\t\tfor (const [name, templateValue] of Object.entries(templateScripts)) {\n\t\t\tconst existing = userScripts[name];\n\t\t\tif (existing === undefined) {\n\t\t\t\tuserScripts[name] = templateValue;\n\t\t\t\tadded.push({ kind: 'scripts', name, templateValue });\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (existing === templateValue) continue;\n\t\t\tuserScripts[name] = templateValue;\n\t\t\treplaced.push({ kind: 'scripts', name, templateValue, userValue: existing });\n\t\t}\n\t}\n\n\tfor (const kind of DEP_KINDS) {\n\t\tconst deps = merged[kind];\n\t\tif (deps) merged[kind] = sortKeys(deps);\n\t}\n\n\treturn { merged, added, conflicts, replaced };\n}\n\nexport function readPackageJson(path: string): PkgJson {\n\treturn JSON.parse(fs.readFileSync(path, 'utf8')) as PkgJson;\n}\n\n/**\n * Placeholders a template file carries so it stays valid on disk while still\n * being parameterized. `~TODO~` becomes the npm-safe package name and\n * `~APP_NAME~` the name the user actually typed; the CLI writes its own version\n * into `~VELA_VERSION~` so a generated project pins the exact CLI that produced\n * it, rather than whatever was hardcoded when the template was last edited.\n *\n * `~APP_NAME~` is escaped for a single-quoted JS string, which is the only place\n * a template uses it.\n */\nconst PACKAGE_NAME_PLACEHOLDER = /~TODO~/g;\nconst APP_NAME_PLACEHOLDER = /~APP_NAME~/g;\nconst CLI_VERSION_PLACEHOLDER = /~VELA_VERSION~/g;\n\nexport interface TemplateValues {\n\tappName: string;\n\tcliVersion: string;\n}\n\n/** Substitute template placeholders in a raw template source string. */\nexport function fillTemplatePlaceholders(raw: string, values: TemplateValues): string {\n\tconst packageName = toValidPackageName(values.appName);\n\tconst appName = escapeSingleQuoted(values.appName);\n\t// Function replacements: `$&` and friends in an app name are literal text.\n\treturn raw\n\t\t.replace(PACKAGE_NAME_PLACEHOLDER, () => packageName)\n\t\t.replace(APP_NAME_PLACEHOLDER, () => appName)\n\t\t.replace(CLI_VERSION_PLACEHOLDER, () => values.cliVersion);\n}\n\nfunction escapeSingleQuoted(value: string): string {\n\treturn value.replace(/\\\\/g, '\\\\\\\\').replace(/'/g, \"\\\\'\");\n}\n\nexport function readTemplatePackageJson(path: string, values: TemplateValues): PkgJson {\n\tconst raw = fillTemplatePlaceholders(fs.readFileSync(path, 'utf8'), values);\n\treturn JSON.parse(raw) as PkgJson;\n}\n\nexport function writePackageJson(path: string, pkg: Record<string, unknown>): void {\n\tfs.writeFileSync(path, JSON.stringify(pkg, null, '\\t') + '\\n');\n}\n\nexport function toValidPackageName(name: string): string {\n\treturn name\n\t\t.trim()\n\t\t.toLowerCase()\n\t\t.replace(/\\s+/g, '-')\n\t\t.replace(/^[._]/, '')\n\t\t.replace(/[^a-z0-9~.-]+/g, '-');\n}\n\nfunction sortKeys<T extends Record<string, string>>(obj: T): T {\n\tconst sorted: Record<string, string> = {};\n\tfor (const key of Object.keys(obj).sort()) sorted[key] = obj[key]!;\n\treturn sorted as T;\n}\n", "import fs from 'node:fs';\nimport path from 'node:path';\nimport process from 'node:process';\nimport * as v from 'valibot';\nimport { Command } from 'commander';\nimport * as p from '@clack/prompts';\nimport pc from 'picocolors';\nimport { resolveCommand } from 'package-manager-detector';\nimport { helpConfig } from '../lib/help.ts';\nimport { runCommand } from '../lib/run.ts';\nimport { parseOptions } from '../lib/options.ts';\nimport { DEFAULT_TEMPLATE, findProjectTemplate, projectTemplateNames } from '../lib/templates.ts';\nimport {\n\tAGENT_NAMES,\n\taddPnpmBuildDependencies,\n\tgetUserAgent,\n\tinstallDependencies,\n\tinstallOption,\n\tpackageManagerPrompt\n} from '../lib/package-manager.ts';\nimport pkg from '../../package.json' with { type: 'json' };\nimport { createSuperuser } from '../lib/pocketbase.ts';\nimport { writeEnvFile } from '../lib/env.ts';\nimport {\n\tmergePackageJson,\n\treadPackageJson,\n\treadTemplatePackageJson,\n\twritePackageJson\n} from '../lib/package-json.ts';\nimport {\n\tmergeGitignore,\n\tmergeSvelteConfig,\n\tmergeTsconfig,\n\tmergeViteConfig\n} from '../lib/config-merge.ts';\nimport { isVanillaRoutes } from '../lib/scaffold-detect.ts';\nimport { getWorkspace } from '../lib/workspace.ts';\nimport { reportResult } from '../lib/result-report.ts';\nimport { templateName } from '../lib/template-files.ts';\n\n/**\n * Only backend templates: blessing is what adds PocketBase to a project, so a\n * frontend-only template has nothing to bless a project with. Read per run so\n * the list can't drift from the templates directory.\n */\nfunction optionsSchema() {\n\tconst templates = projectTemplateNames({ backend: true });\n\treturn v.strictObject({\n\t\tinstall: v.union([v.boolean(), v.picklist(AGENT_NAMES)], 'must be a package manager'),\n\t\ttemplate: v.optional(v.picklist(templates, `must be one of: ${templates.join(', ')}`)),\n\t\temail: v.optional(v.pipe(v.string(), v.email('must be a valid email address'))),\n\t\tpassword: v.optional(v.pipe(v.string(), v.minLength(8, 'must be at least 8 characters long'))),\n\t\tskipRoutes: v.optional(v.boolean()),\n\t\tforceRoutes: v.optional(v.boolean())\n\t});\n}\ntype Options = v.InferOutput<ReturnType<typeof optionsSchema>>;\n\ninterface VelaFile {\n\t/** Path in the blessed project. */\n\tpath: string;\n\t/** What vela's copy carries, shown when the project already has its own. */\n\tadds: string;\n}\n\n/**\n * Files vela owns outright. A real project may already have some of them, so each\n * one records what would be missed by keeping the existing version.\n */\nconst VELA_ONLY_FILES: VelaFile[] = [\n\t{\n\t\tpath: 'src/hooks.server.ts',\n\t\tadds: 'the handlePocketbase hook \u2014 the backend is not wired up without it'\n\t},\n\t{ path: 'src/app.css', adds: \"vela's Tailwind imports and theme tokens\" },\n\t{ path: 'src/lib/index.ts', adds: 'a $lib placeholder comment' },\n\t{ path: 'src/lib/utils.ts', adds: 'the cn helper and the component type utilities' },\n\t{ path: 'components.json', adds: 'the shadcn-svelte config that `vela ui add` reads' },\n\t{ path: '.npmrc', adds: 'engine-strict=true' },\n\t{ path: '.ignore', adds: 'search ignores for generated files' }\n];\nconst VELA_ONLY_DIRS = ['src/lib/components', 'data', 'test', 'static'];\n\nexport const bless = new Command('bless')\n\t.description('upgrade a vanilla SvelteKit project into a VelaStack project')\n\t.argument('[path]', 'path to the existing SvelteKit project')\n\t.option('--template <type>', 'template to scaffold from', 'minimal')\n\t.option('--email <email>', 'email of the admin user')\n\t.option('--password <password>', 'password of the admin user')\n\t.option('--no-install', 'skip installing dependencies')\n\t.addOption(installOption)\n\t.option('--skip-routes', 'preserve src/routes even if it looks untouched')\n\t.option('--force-routes', 'replace src/routes with the vela template without detection')\n\t.configureHelp(helpConfig)\n\t.action((projectPath: string | undefined, rawOpts) => {\n\t\treturn runCommand(async () => {\n\t\t\tconst options = parseOptions(optionsSchema(), rawOpts);\n\t\t\tif (options.skipRoutes && options.forceRoutes) {\n\t\t\t\tthrow new Error('--skip-routes and --force-routes are mutually exclusive');\n\t\t\t}\n\t\t\tawait blessProject(projectPath, options);\n\t\t}, 'Failed to bless project.');\n\t});\n\nasync function blessProject(cwdArg: string | undefined, options: Options) {\n\tconst projectPath = cwdArg ? resolveProjectPath(cwdArg) : (await getWorkspace()).workspaceRootDir;\n\n\tassertNotAlreadyBlessed(projectPath);\n\n\tconst templateDir = findProjectTemplate(options.template ?? DEFAULT_TEMPLATE).dir;\n\n\tconst { email, password } = await p.group(\n\t\t{\n\t\t\temail: () => {\n\t\t\t\tif (options.email) return Promise.resolve(options.email);\n\t\t\t\treturn p.text({\n\t\t\t\t\tmessage: 'Enter an email for the admin user',\n\t\t\t\t\tdefaultValue: 'admin@example.com',\n\t\t\t\t\tvalidate: (value) =>\n\t\t\t\t\t\t!value ? 'Email is required' : !value.includes('@') ? 'Invalid email' : undefined\n\t\t\t\t});\n\t\t\t},\n\t\t\tpassword: () => {\n\t\t\t\tif (options.password) return Promise.resolve(options.password);\n\t\t\t\treturn p.password({\n\t\t\t\t\tmessage: 'Enter a password for the admin user (at least 8 characters)',\n\t\t\t\t\tvalidate: (value) =>\n\t\t\t\t\t\t!value\n\t\t\t\t\t\t\t? 'Password is required'\n\t\t\t\t\t\t\t: value.length < 8\n\t\t\t\t\t\t\t\t? 'Password must be at least 8 characters long'\n\t\t\t\t\t\t\t\t: undefined\n\t\t\t\t});\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tonCancel: () => {\n\t\t\t\tp.cancel('Operation cancelled.');\n\t\t\t\tprocess.exit(0);\n\t\t\t}\n\t\t}\n\t);\n\n\tmergeDependencies(projectPath, templateDir);\n\tcopyVelaOnlyFiles(templateDir, projectPath);\n\tmergeConfigFiles(projectPath);\n\tmergeAppDts(templateDir, projectPath);\n\tmaybeReplaceRoutes(projectPath, templateDir, options);\n\n\tp.log.success('Vela files in place');\n\n\tlet packageManager: ReturnType<typeof getUserAgent> | undefined;\n\tif (options.install !== false) {\n\t\tconst pm =\n\t\t\ttypeof options.install === 'string'\n\t\t\t\t? options.install\n\t\t\t\t: await packageManagerPrompt(projectPath);\n\n\t\tif (pm) {\n\t\t\taddPnpmBuildDependencies(projectPath, pm, ['esbuild', 'pocketbase-server']);\n\t\t\tawait installDependencies(pm, projectPath);\n\t\t\tpackageManager = pm;\n\t\t}\n\t}\n\n\tp.log.step('Initializing PocketBase...');\n\tawait createSuperuser(projectPath, email, password);\n\n\twriteEnvFile(\n\t\tprojectPath,\n\t\t{\n\t\t\tPOCKETBASE_SUPERUSER_EMAIL: email,\n\t\t\tPOCKETBASE_SUPERUSER_PASSWORD: password\n\t\t},\n\t\t['PocketBase superuser credentials \u2014 used by `vela` commands']\n\t);\n\n\tp.log.success('PocketBase initialized');\n\n\tprintNextSteps(projectPath, packageManager);\n}\n\nfunction resolveProjectPath(cwdArg: string): string {\n\tconst projectPath = path.resolve(cwdArg);\n\tif (!fs.existsSync(projectPath)) {\n\t\tthrow new Error(`Path does not exist: ${projectPath}`);\n\t}\n\tif (!fs.existsSync(path.join(projectPath, 'package.json'))) {\n\t\tthrow new Error(`No package.json found at ${projectPath}`);\n\t}\n\tif (!fs.existsSync(path.join(projectPath, 'src', 'routes'))) {\n\t\tthrow new Error(`No src/routes directory found at ${projectPath}`);\n\t}\n\treturn projectPath;\n}\n\nfunction assertNotAlreadyBlessed(projectPath: string) {\n\tconst hooksPath = path.join(projectPath, 'src', 'hooks.server.ts');\n\tif (!fs.existsSync(hooksPath)) return;\n\tconst content = fs.readFileSync(hooksPath, 'utf8');\n\tif (content.includes('@velastack/pocketbase')) {\n\t\tthrow new Error(\n\t\t\t'This project already looks blessed (src/hooks.server.ts imports @velastack/pocketbase). Run `vela sync` instead.'\n\t\t);\n\t}\n}\n\nfunction mergeDependencies(projectPath: string, templateDir: string) {\n\tconst userPkgPath = path.join(projectPath, 'package.json');\n\tconst templatePkgPath = path.join(templateDir, 'package.template.json');\n\n\tconst userPkg = readPackageJson(userPkgPath);\n\tconst appName = typeof userPkg.name === 'string' ? userPkg.name : 'sveltekit';\n\tconst templatePkg = readTemplatePackageJson(templatePkgPath, {\n\t\tappName,\n\t\tcliVersion: pkg.version\n\t});\n\n\tconst { merged, added, conflicts, replaced } = mergePackageJson(userPkg, templatePkg);\n\twritePackageJson(userPkgPath, merged);\n\n\tif (added.length > 0) {\n\t\tp.log.info(\n\t\t\t`Added ${added.length} entries to package.json (${summarize(added.map((c) => c.name))}).`\n\t\t);\n\t}\n\tif (replaced.length > 0) {\n\t\tconst lines = replaced.map(\n\t\t\t(c) =>\n\t\t\t\t` script ${pc.bold(c.name)}: ${pc.gray(c.userValue ?? '')} \u2192 ${pc.cyan(c.templateValue)}`\n\t\t);\n\t\tp.log.info(`Updated ${replaced.length} script(s):\\n${lines.join('\\n')}`);\n\t}\n\tif (conflicts.length > 0) {\n\t\tconst lines = conflicts.map(\n\t\t\t(c) =>\n\t\t\t\t` dep ${pc.bold(c.name)}: kept ${pc.cyan(c.userValue ?? '')} (template wants ${pc.gray(c.templateValue)})`\n\t\t);\n\t\tp.log.warn(`Kept ${conflicts.length} dependency version(s) on conflict:\\n${lines.join('\\n')}`);\n\t}\n}\n\nfunction copyVelaOnlyFiles(templateDir: string, projectPath: string) {\n\tconst kept: VelaFile[] = [];\n\n\tfor (const file of VELA_ONLY_FILES) {\n\t\tconst src = path.join(templateDir, templateName(file.path));\n\t\tconst dest = path.join(projectPath, file.path);\n\t\tif (!fs.existsSync(src)) continue;\n\t\tif (fs.existsSync(dest)) {\n\t\t\tkept.push(file);\n\t\t\tcontinue;\n\t\t}\n\t\tfs.mkdirSync(path.dirname(dest), { recursive: true });\n\t\tfs.copyFileSync(src, dest);\n\t}\n\n\treportKeptFiles(kept);\n\n\tfor (const rel of VELA_ONLY_DIRS) {\n\t\tconst src = path.join(templateDir, rel);\n\t\tconst dest = path.join(projectPath, rel);\n\t\tif (!fs.existsSync(src)) continue;\n\t\tcopyDirShallow(src, dest);\n\t}\n}\n\n/**\n * Keeping a file the project already had is the expected outcome of blessing a\n * real project \u2014 but vela's version carries things the generators rely on, so\n * name what was skipped instead of leaving the difference invisible.\n */\nfunction reportKeptFiles(kept: VelaFile[]) {\n\tif (kept.length === 0) return;\n\tconst padding = Math.max(...kept.map((f) => f.path.length));\n\tconst lines = kept.map((f) => ` ${pc.bold(f.path.padEnd(padding))} ${pc.gray(f.adds)}`);\n\tp.log.info(\n\t\t`Kept ${kept.length} file(s) you already had. Merge by hand to pick up what vela adds:\\n${lines.join('\\n')}`\n\t);\n}\n\nfunction copyDirShallow(src: string, dest: string) {\n\tfs.mkdirSync(dest, { recursive: true });\n\tfor (const entry of fs.readdirSync(src, { withFileTypes: true })) {\n\t\tif (entry.name === '.DS_Store') continue;\n\t\tconst srcChild = path.join(src, entry.name);\n\t\tconst destChild = path.join(dest, entry.name);\n\t\tif (entry.isDirectory()) {\n\t\t\tcopyDirShallow(srcChild, destChild);\n\t\t} else if (entry.isFile() && !fs.existsSync(destChild)) {\n\t\t\tfs.copyFileSync(srcChild, destChild);\n\t\t}\n\t}\n}\n\nfunction mergeConfigFiles(projectPath: string) {\n\tconst runes = mergeSvelteConfig(projectPath);\n\tconst outcomes = [\n\t\t[runes.file ?? 'svelte.config', runes],\n\t\t['vite.config.ts', mergeViteConfig(path.join(projectPath, 'vite.config.ts'))],\n\t\t['tsconfig.json', mergeTsconfig(path.join(projectPath, 'tsconfig.json'))],\n\t\t['.gitignore', mergeGitignore(path.join(projectPath, '.gitignore'))]\n\t] as const;\n\n\tfor (const [name, outcome] of outcomes) {\n\t\tif (outcome.applied) {\n\t\t\tp.log.info(`${name}: ${outcome.reason}`);\n\t\t\tcontinue;\n\t\t}\n\t\tif (outcome.snippet) {\n\t\t\tp.log.warn(\n\t\t\t\t`${name}: ${outcome.reason}\\n${pc.gray('Add this manually:')}\\n${pc.cyan(outcome.snippet)}`\n\t\t\t);\n\t\t}\n\t}\n}\n\nfunction mergeAppDts(templateDir: string, projectPath: string) {\n\tconst dest = path.join(projectPath, 'src', 'app.d.ts');\n\tconst templateFile = path.join(templateDir, 'src', 'app.d.ts');\n\tif (!fs.existsSync(dest)) {\n\t\tif (!fs.existsSync(templateFile)) return;\n\t\tfs.copyFileSync(templateFile, dest);\n\t\treturn;\n\t}\n\tconst current = fs.readFileSync(dest, 'utf8');\n\tif (current.includes('namespace Superforms')) return;\n\tconst block = `\\tnamespace Superforms {\\n\\t\\ttype Message = {\\n\\t\\t\\ttype: 'error' | 'success';\\n\\t\\t\\ttext: string;\\n\\t\\t};\\n\\t}\\n`;\n\tconst match = current.match(/declare global\\s*\\{\\s*\\n/);\n\tif (!match || match.index === undefined) {\n\t\tp.log.warn(\n\t\t\t`src/app.d.ts: non-standard shape \u2014 add this namespace manually:\\n${pc.cyan(block)}`\n\t\t);\n\t\treturn;\n\t}\n\tconst insertAt = match.index + match[0].length;\n\tconst updated = current.slice(0, insertAt) + block + current.slice(insertAt);\n\tfs.writeFileSync(dest, updated);\n}\n\nfunction maybeReplaceRoutes(projectPath: string, templateDir: string, options: Options) {\n\tif (options.skipRoutes) {\n\t\tp.log.info('Skipping src/routes (--skip-routes).');\n\t\treturn;\n\t}\n\n\tif (!options.forceRoutes && !isVanillaRoutes(projectPath)) {\n\t\tp.log.info('Leaving src/routes alone (looks customized).');\n\t\treturn;\n\t}\n\n\tconst target = path.join(projectPath, 'src', 'routes');\n\tfs.rmSync(target, { recursive: true, force: true });\n\tconst src = path.join(templateDir, 'src', 'routes');\n\tfs.cpSync(src, target, {\n\t\trecursive: true,\n\t\tfilter: (s) => path.basename(s) !== '.DS_Store'\n\t});\n\tp.log.success('Replaced src/routes with the vela template.');\n}\n\nfunction summarize(names: string[]): string {\n\tif (names.length <= 4) return names.join(', ');\n\treturn `${names.slice(0, 3).join(', ')}, and ${names.length - 3} more`;\n}\n\nfunction printNextSteps(projectPath: string, packageManager: ReturnType<typeof getUserAgent>) {\n\tconst relative = path.relative(process.cwd(), projectPath);\n\tconst pm = packageManager ?? getUserAgent() ?? 'npm';\n\n\tconst nextSteps: string[] = [];\n\tif (relative !== '') {\n\t\tconst hasSpaces = relative.includes(' ');\n\t\tnextSteps.push(`\\`cd ${hasSpaces ? `\"${relative}\"` : relative}\\``);\n\t}\n\tconst runDev = resolveCommand(pm, 'run', ['dev', '--open']);\n\tif (runDev) {\n\t\tnextSteps.push(\n\t\t\t`\\`${runDev.command} ${runDev.args.join(' ')}\\` to start the dev server (Ctrl-C to stop)`\n\t\t);\n\t}\n\tnextSteps.push(\n\t\t'Run `vela enable auth` to layer on sign-in flows, or `vela generate scaffold <model>` to scaffold a CRUD page.'\n\t);\n\tnextSteps.push('Stuck? Visit https://docs.velastack.dev');\n\n\treportResult({\n\t\tsummary: `Blessed project at ${projectPath}.`,\n\t\tnextSteps\n\t});\n}\n", "import * as v from 'valibot';\n\n/**\n * Validate commander's raw options against a schema, reporting failures as a\n * plain `Error`.\n *\n * `v.parse` throws a `ValiError`, and commander invokes actions outside any\n * handler of ours, so calling it directly puts a valibot stack trace in front of\n * a user who merely mistyped a flag. Called inside `runCommand`, this instead\n * surfaces every bad flag through the CLI's normal error reporting.\n */\nexport function parseOptions<S extends v.GenericSchema>(schema: S, raw: unknown): v.InferOutput<S> {\n\tconst result = v.safeParse(schema, raw);\n\tif (result.success) return result.output;\n\tconst seen = new Set<string>();\n\tconst lines = result.issues.map(describeIssue).filter((line) => {\n\t\tif (seen.has(line)) return false;\n\t\tseen.add(line);\n\t\treturn true;\n\t});\n\tthrow new Error(lines.join('\\n'));\n}\n\nfunction describeIssue(issue: v.BaseIssue<unknown>): string {\n\tconst key = optionKey(issue);\n\treturn key ? `--${toFlag(key)}: ${issue.message}` : issue.message;\n}\n\n/** The option a nested issue belongs to \u2014 the first string key on its path. */\nfunction optionKey(issue: v.BaseIssue<unknown>): string | undefined {\n\tfor (const item of issue.path ?? []) {\n\t\tif (typeof item.key === 'string') return item.key;\n\t}\n\treturn undefined;\n}\n\n/** `skipRoutes` is what valibot sees; `--skip-routes` is what the user typed. */\nfunction toFlag(key: string): string {\n\treturn key.replace(/[A-Z]/g, (char) => `-${char.toLowerCase()}`);\n}\n", "import fs from 'node:fs';\nimport path from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\n/** Marks a directory under `templates/` as something `vela create` can scaffold. */\nexport const TEMPLATE_MANIFEST = 'template.json';\n\nexport const DEFAULT_TEMPLATE = 'minimal';\n\nexport interface ProjectTemplate {\n\t/** Directory name under `templates/`, and the value `--template` takes. */\n\tname: string;\n\tdescription: string;\n\t/**\n\t * Whether the template scaffolds a PocketBase backend. A template without one\n\t * is a frontend-only project: no superuser, no `.env`, no `vela dev`/`sync`.\n\t */\n\tbackend: boolean;\n\tdir: string;\n}\n\nlet cached: ProjectTemplate[] | undefined;\n\n/**\n * The packaged `templates/` directory, found by walking up from this module so\n * it resolves the same whether the CLI runs from `src/` or from `dist/`.\n *\n * A bare `templates` name is too common to match on alone, so a candidate only\n * counts once it holds at least one template manifest.\n */\nexport function templatesDir(): string {\n\tlet dir = path.dirname(fileURLToPath(import.meta.url));\n\tconst { root } = path.parse(dir);\n\twhile (dir !== root) {\n\t\tconst candidate = path.join(dir, 'templates');\n\t\tif (holdsManifest(candidate)) return candidate;\n\t\tdir = path.dirname(dir);\n\t}\n\tthrow new Error('Could not locate the templates directory');\n}\n\nfunction holdsManifest(dir: string): boolean {\n\tif (!fs.existsSync(dir)) return false;\n\treturn fs\n\t\t.readdirSync(dir, { withFileTypes: true })\n\t\t.some(\n\t\t\t(entry) => entry.isDirectory() && fs.existsSync(path.join(dir, entry.name, TEMPLATE_MANIFEST))\n\t\t);\n}\n\n/**\n * Every scaffoldable template, read from disk rather than hardcoded so adding a\n * template directory is all it takes to make `--template` accept it.\n */\nexport function listProjectTemplates(): ProjectTemplate[] {\n\tif (cached) return cached;\n\tconst root = templatesDir();\n\tcached = fs\n\t\t.readdirSync(root, { withFileTypes: true })\n\t\t.filter((entry) => entry.isDirectory())\n\t\t.map((entry) => readManifest(root, entry.name))\n\t\t.filter((template): template is ProjectTemplate => template !== undefined)\n\t\t.sort((a, b) => a.name.localeCompare(b.name));\n\treturn cached;\n}\n\n/** Template names accepted by `--template`, in the order they should be listed. */\nexport function projectTemplateNames(options: { backend?: boolean } = {}): string[] {\n\tconst templates = listProjectTemplates();\n\tconst matching =\n\t\toptions.backend === undefined\n\t\t\t? templates\n\t\t\t: templates.filter((template) => template.backend === options.backend);\n\treturn matching.map((template) => template.name);\n}\n\nexport function findProjectTemplate(name: string): ProjectTemplate {\n\tconst template = listProjectTemplates().find((candidate) => candidate.name === name);\n\tif (!template) throw new Error(`Template not found: ${name}`);\n\treturn template;\n}\n\nfunction readManifest(root: string, name: string): ProjectTemplate | undefined {\n\tconst manifestPath = path.join(root, name, TEMPLATE_MANIFEST);\n\tif (!fs.existsSync(manifestPath)) return undefined;\n\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));\n\t} catch (e) {\n\t\tthrow new Error(\n\t\t\t`Template ${name} has an unreadable ${TEMPLATE_MANIFEST}: ${(e as Error).message}`\n\t\t);\n\t}\n\n\tconst manifest = parsed as { description?: unknown; backend?: unknown };\n\tif (typeof manifest.description !== 'string' || typeof manifest.backend !== 'boolean') {\n\t\tthrow new Error(\n\t\t\t`Template ${name} has an invalid ${TEMPLATE_MANIFEST} (needs description and backend)`\n\t\t);\n\t}\n\n\treturn {\n\t\tname,\n\t\tdescription: manifest.description,\n\t\tbackend: manifest.backend,\n\t\tdir: path.join(root, name)\n\t};\n}\n", "import fs from 'node:fs';\nimport path from 'node:path';\nimport process from 'node:process';\nimport { exec } from 'tinyexec';\nimport { Option } from 'commander';\nimport * as p from '@clack/prompts';\nimport {\n\tAGENTS,\n\tCOMMANDS,\n\tconstructCommand,\n\tdetect,\n\ttype AgentName\n} from 'package-manager-detector';\n\nexport const AGENT_NAMES = AGENTS.filter((agent): agent is AgentName => !agent.includes('@'));\n\nexport const installOption = new Option(\n\t'--install <package-manager>',\n\t'installs dependencies with a specified package manager'\n).choices(AGENT_NAMES);\n\nexport function getUserAgent(): AgentName | undefined {\n\tconst userAgent = process.env.npm_config_user_agent;\n\tif (!userAgent) return undefined;\n\tconst pmSpec = userAgent.split(' ')[0]!;\n\tconst separatorPos = pmSpec.lastIndexOf('/');\n\tconst name = pmSpec.substring(0, separatorPos) as AgentName;\n\treturn AGENTS.includes(name) ? name : undefined;\n}\n\nexport async function packageManagerPrompt(cwd: string): Promise<AgentName | undefined> {\n\tconst detected = await detect({ cwd });\n\tconst agent = detected?.name ?? getUserAgent();\n\n\tif (!process.stdout.isTTY) return agent;\n\n\tconst options: Array<{ value: AgentName | undefined; label: AgentName | 'None' }> = [\n\t\t{ label: 'None', value: undefined },\n\t\t...AGENT_NAMES.map((pm) => ({ value: pm, label: pm }))\n\t];\n\n\tconst pm = await p.select({\n\t\tmessage: 'Which package manager do you want to install dependencies with?',\n\t\toptions,\n\t\tinitialValue: agent\n\t});\n\tif (p.isCancel(pm)) {\n\t\tp.cancel('Operation cancelled.');\n\t\tprocess.exit(1);\n\t}\n\treturn pm;\n}\n\nexport async function installDependencies(agent: AgentName, cwd: string): Promise<void> {\n\tconst task = p.taskLog({\n\t\ttitle: `Installing dependencies with ${agent}...`,\n\t\tlimit: Math.ceil(process.stdout.rows / 2),\n\t\tspacing: 0,\n\t\tretainLog: true\n\t});\n\n\ttry {\n\t\tconst { command, args } = constructCommand(COMMANDS[agent].install, [])!;\n\t\tconst proc = exec(command, args, {\n\t\t\tnodeOptions: { cwd, stdio: 'pipe' },\n\t\t\tthrowOnError: true\n\t\t});\n\n\t\tproc.process?.stdout?.on('data', (data) => task.message(data.toString(), { raw: true }));\n\t\tproc.process?.stderr?.on('data', (data) => task.message(data.toString(), { raw: true }));\n\n\t\tawait proc;\n\t\ttask.success('Successfully installed dependencies');\n\t} catch {\n\t\ttask.error('Failed to install dependencies');\n\t\tp.cancel('Operation failed.');\n\t\tprocess.exit(2);\n\t}\n}\n\nexport function addPnpmBuildDependencies(\n\tcwd: string,\n\tpackageManager: AgentName | null | undefined,\n\tallowedPackages: string[]\n) {\n\tif (!packageManager || packageManager !== 'pnpm') return;\n\n\tconst pkgPath = path.join(cwd, 'package.json');\n\tif (!fs.existsSync(pkgPath)) return;\n\n\tconst pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'));\n\tpkg.pnpm ??= {};\n\tpkg.pnpm.onlyBuiltDependencies ??= [];\n\tfor (const name of allowedPackages) {\n\t\tif (!pkg.pnpm.onlyBuiltDependencies.includes(name)) {\n\t\t\tpkg.pnpm.onlyBuiltDependencies.push(name);\n\t\t}\n\t}\n\tfs.writeFileSync(pkgPath, JSON.stringify(pkg, null, '\\t') + '\\n');\n}\n", "import fs from 'node:fs';\nimport net from 'node:net';\nimport path from 'node:path';\nimport process from 'node:process';\nimport { createRequire } from 'node:module';\nimport { spawn, type ChildProcess } from 'node:child_process';\nimport PocketBase from 'pocketbase';\nimport { detect } from 'package-manager-detector';\nimport { resolveCommand } from 'package-manager-detector/commands';\nimport { x } from 'tinyexec';\nimport { DATA_DIR, MIGRATIONS_DIR } from './constants.ts';\n\nexport function findFreePort(host = 'localhost'): Promise<number> {\n\treturn new Promise((resolve, reject) => {\n\t\tconst server = net.createServer();\n\t\tserver.unref();\n\t\tserver.once('error', reject);\n\t\tserver.listen(0, host, () => {\n\t\t\tconst addr = server.address() as net.AddressInfo | null;\n\t\t\tserver.close((err) => {\n\t\t\t\tif (err) reject(err);\n\t\t\t\telse if (!addr) reject(new Error('Failed to obtain a free port'));\n\t\t\t\telse resolve(addr.port);\n\t\t\t});\n\t\t});\n\t});\n}\n\nfunction waitForReadyOrExit(proc: ChildProcess, url: string, maxAttempts = 40): Promise<void> {\n\treturn new Promise((resolve, reject) => {\n\t\tlet settled = false;\n\t\tconst onExit = (code: number | null, signal: NodeJS.Signals | null) => {\n\t\t\tif (settled) return;\n\t\t\tsettled = true;\n\t\t\treject(\n\t\t\t\tnew Error(`PocketBase exited before becoming healthy (code=${code}, signal=${signal})`)\n\t\t\t);\n\t\t};\n\t\tproc.once('exit', onExit);\n\n\t\tlet attempts = 0;\n\t\tconst check = async () => {\n\t\t\tif (settled) return;\n\t\t\tattempts++;\n\t\t\ttry {\n\t\t\t\tconst r = await fetch(`${url}/api/health`);\n\t\t\t\tif (r.status === 200) {\n\t\t\t\t\tif (settled) return;\n\t\t\t\t\tsettled = true;\n\t\t\t\t\tproc.removeListener('exit', onExit);\n\t\t\t\t\tresolve();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t} catch {\n\t\t\t\t/* retry */\n\t\t\t}\n\t\t\tif (attempts >= maxAttempts) {\n\t\t\t\tif (settled) return;\n\t\t\t\tsettled = true;\n\t\t\t\tproc.removeListener('exit', onExit);\n\t\t\t\treject(new Error(`Timed out waiting for health at ${url}`));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tsetTimeout(check, 250);\n\t\t};\n\t\tcheck();\n\t});\n}\n\nexport interface StartPocketbaseServeOptions {\n\tdataDir: string;\n\tmigrationsDir: string;\n\thooksDir?: string;\n\tdev?: boolean;\n\tstdio?: 'inherit' | 'pipe' | 'ignore';\n\thost?: string;\n\tmaxAttempts?: number;\n}\n\nexport async function startPocketbaseServe(opts: StartPocketbaseServeOptions): Promise<{\n\tproc: ChildProcess;\n\tport: number;\n\turl: string;\n}> {\n\tconst { getBinaryPath } = await import('pocketbase-server');\n\tconst binaryPath = getBinaryPath();\n\tconst host = opts.host ?? 'localhost';\n\tconst stdio = opts.stdio ?? 'inherit';\n\tconst maxAttempts = opts.maxAttempts ?? 5;\n\n\tlet lastErr: unknown;\n\tfor (let attempt = 1; attempt <= maxAttempts; attempt++) {\n\t\tconst port = await findFreePort(host);\n\t\tconst args = [\n\t\t\t'serve',\n\t\t\t'--dir',\n\t\t\topts.dataDir,\n\t\t\t'--migrationsDir',\n\t\t\topts.migrationsDir,\n\t\t\t...(opts.hooksDir ? ['--hooksDir', opts.hooksDir] : []),\n\t\t\t...(opts.dev ? ['--dev'] : []),\n\t\t\t'--http',\n\t\t\t`${host}:${port}`\n\t\t];\n\t\tconst proc = spawn(binaryPath, args, { stdio });\n\n\t\ttry {\n\t\t\tawait waitForReadyOrExit(proc, `http://${host}:${port}`);\n\t\t\treturn { proc, port, url: `http://${host}:${port}` };\n\t\t} catch (err) {\n\t\t\tlastErr = err;\n\t\t\tif (proc.exitCode === null && proc.signalCode === null) {\n\t\t\t\tawait new Promise<void>((resolve) => {\n\t\t\t\t\tproc.once('exit', () => resolve());\n\t\t\t\t\tproc.kill();\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}\n\tthrow lastErr instanceof Error ? lastErr : new Error('Failed to start PocketBase');\n}\n\nexport async function authWithRetries(\n\tpb: PocketBase,\n\temail: string,\n\tpassword: string,\n\tattempts = 3\n) {\n\tfor (let attempt = 1; attempt <= attempts; attempt++) {\n\t\ttry {\n\t\t\tawait pb.collection('_superusers').authWithPassword(email, password);\n\t\t\treturn;\n\t\t} catch (e) {\n\t\t\tif (attempt === attempts) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t'Failed to authenticate with PocketBase. Check your superuser credentials.'\n\t\t\t\t);\n\t\t\t}\n\t\t\tawait new Promise((r) => setTimeout(r, 100));\n\t\t}\n\t}\n}\n\nexport function getPocketbaseMetadata(\n\tcwd: string\n): { pocketbaseUrl: string; vitePort: number; viteHost: string } | null {\n\tconst metadataPath = path.join(cwd, 'node_modules', '.vite', '_pocketbase_metadata.json');\n\tif (fs.existsSync(metadataPath)) {\n\t\treturn JSON.parse(fs.readFileSync(metadataPath, 'utf8'));\n\t}\n\treturn null;\n}\n\nasync function execPackageBin(cwd: string, args: string[], stdio: 'inherit' | 'pipe' = 'pipe') {\n\tconst packageManager = (await detect({ cwd }))?.name ?? 'npm';\n\tconst resolved = resolveCommand(packageManager, 'execute', args);\n\tif (!resolved) throw new Error(`Could not resolve command for ${packageManager}`);\n\tconst { command, args: resolvedArgs } = resolved;\n\tif (packageManager === 'npm') resolvedArgs.unshift('--yes');\n\treturn x(command, resolvedArgs, { nodeOptions: { cwd, stdio }, throwOnError: true });\n}\n\nexport async function withPocketbase(\n\tcwd: string,\n\tfn: (pb: PocketBase) => Promise<void>,\n\tcreds?: { email: string; password: string }\n) {\n\tconst dir = path.join(cwd, DATA_DIR);\n\tconst migrationsDir = path.join(cwd, MIGRATIONS_DIR);\n\tconst host = 'localhost';\n\tconst email = creds?.email ?? process.env.POCKETBASE_SUPERUSER_EMAIL!;\n\tconst password = creds?.password ?? process.env.POCKETBASE_SUPERUSER_PASSWORD!;\n\n\tif (!fs.existsSync(dir)) {\n\t\tthrow new Error('PocketBase data directory does not exist');\n\t}\n\n\tconst metadata = getPocketbaseMetadata(cwd);\n\tif (metadata?.pocketbaseUrl) {\n\t\tconst pb = new PocketBase(metadata.pocketbaseUrl);\n\t\tawait authWithRetries(pb, email, password);\n\t\tawait fn(pb);\n\t\treturn;\n\t}\n\n\tconst { proc, url } = await startPocketbaseServe({\n\t\tdataDir: dir,\n\t\tmigrationsDir,\n\t\thost,\n\t\tstdio: 'ignore'\n\t});\n\n\ttry {\n\t\tconst pb = new PocketBase(url);\n\t\tawait authWithRetries(pb, email, password);\n\t\tawait fn(pb);\n\t} finally {\n\t\tproc.kill();\n\t}\n}\n\nexport async function createSuperuser(cwd: string, email: string, password: string): Promise<void> {\n\tconst dir = path.join(cwd, DATA_DIR);\n\tconst migrationsDir = path.join(cwd, MIGRATIONS_DIR);\n\tfs.mkdirSync(dir, { recursive: true });\n\tfs.mkdirSync(migrationsDir, { recursive: true });\n\n\tawait execPackageBin(\n\t\tcwd,\n\t\t[\n\t\t\t'pocketbase-server',\n\t\t\t'--dir',\n\t\t\tdir,\n\t\t\t'--migrationsDir',\n\t\t\tmigrationsDir,\n\t\t\t'superuser',\n\t\t\t'create',\n\t\t\temail,\n\t\t\tpassword\n\t\t],\n\t\t'pipe'\n\t);\n}\n\nexport async function launchPocketbase(\n\tcwd: string,\n\t{\n\t\tdir,\n\t\tmigrationsDir,\n\t\thooksDir,\n\t\temail,\n\t\tpassword\n\t}: { dir: string; migrationsDir: string; hooksDir?: string; email: string; password: string }\n) {\n\tconst host = 'localhost';\n\tfs.mkdirSync(dir, { recursive: true });\n\tfs.mkdirSync(migrationsDir, { recursive: true });\n\n\tawait execPackageBin(\n\t\tcwd,\n\t\t[\n\t\t\t'pocketbase-server',\n\t\t\t'--dir',\n\t\t\tdir,\n\t\t\t'--migrationsDir',\n\t\t\tmigrationsDir,\n\t\t\t'superuser',\n\t\t\t'create',\n\t\t\temail,\n\t\t\tpassword\n\t\t],\n\t\t'pipe'\n\t);\n\n\tawait execPackageBin(\n\t\tcwd,\n\t\t['pocketbase-server', '--dir', dir, '--migrationsDir', migrationsDir, 'migrate', 'up'],\n\t\t'inherit'\n\t);\n\n\tconst { proc, url } = await startPocketbaseServe({\n\t\tdataDir: dir,\n\t\tmigrationsDir,\n\t\thooksDir,\n\t\thost,\n\t\tstdio: 'pipe'\n\t});\n\n\treturn {\n\t\tstop: () => proc.kill(),\n\t\turl\n\t};\n}\n\n/**\n * The PocketBase version this CLI develops against.\n *\n * Servers install the same build, so a deployed app and a developer's machine\n * never differ on the database engine.\n */\nexport function pocketbaseVersion(): string {\n\tconst require = createRequire(import.meta.url);\n\tconst pkg = require('pocketbase-server/package.json') as { version: string };\n\treturn pkg.version;\n}\n\n/**\n * Make sure the configured superuser exists in the local database.\n *\n * A vela app authenticates as its superuser while rendering, so a build needs\n * one to exist. On a developer's machine it always does; on a fresh checkout \u2014\n * CI, a new clone, a wiped `data/` \u2014 the database is empty and the build fails\n * at prerendering with \"invalid login credentials\". `upsert` is idempotent, so\n * this is a no-op everywhere else.\n */\nexport async function ensureSuperuser(cwd: string): Promise<void> {\n\tconst email = process.env.POCKETBASE_SUPERUSER_EMAIL;\n\tconst password = process.env.POCKETBASE_SUPERUSER_PASSWORD;\n\tif (!email || !password) return;\n\n\tconst dir = path.join(cwd, DATA_DIR);\n\tif (!fs.existsSync(dir)) return;\n\n\tconst { getBinaryPath } = await import('pocketbase-server');\n\tawait x(\n\t\tgetBinaryPath(),\n\t\t[\n\t\t\t'--dir',\n\t\t\tdir,\n\t\t\t'--migrationsDir',\n\t\t\tpath.join(cwd, MIGRATIONS_DIR),\n\t\t\t'superuser',\n\t\t\t'upsert',\n\t\t\temail,\n\t\t\tpassword\n\t\t],\n\t\t{ nodeOptions: { cwd, stdio: 'ignore' } }\n\t);\n}\n", "import fs from 'node:fs';\nimport path from 'node:path';\n\nexport function addEnvVar(content: string, key: string, value: string): string {\n\tif (content.includes(`${key}=`)) return content;\n\treturn appendLine(content, `${key}=${value}`);\n}\n\nexport function addEnvComment(content: string, comment: string): string {\n\tconst commented = `# ${comment}`;\n\tif (content.includes(commented)) return content;\n\treturn appendLine(content, commented);\n}\n\nfunction appendLine(existing: string, line: string): string {\n\tconst withNewline = !existing.length || existing.endsWith('\\n') ? existing : existing + '\\n';\n\treturn withNewline + line + '\\n';\n}\n\nexport function writeEnvFile(\n\tcwd: string,\n\tvars: Record<string, string>,\n\tcomments: string[] = []\n): void {\n\tconst envPath = path.join(cwd, '.env');\n\tlet content = fs.existsSync(envPath) ? fs.readFileSync(envPath, 'utf8') : '';\n\tfor (const comment of comments) content = addEnvComment(content, comment);\n\tfor (const [key, value] of Object.entries(vars)) content = addEnvVar(content, key, value);\n\tfs.writeFileSync(envPath, content);\n}\n\n/**\n * Set a value in a `.env` file, in place.\n *\n * `addEnvVar` above is append-only and silently does nothing when the key is\n * already present, which is right for scaffolding and wrong for `vela env set`.\n * This rewrites the existing line where there is one and appends otherwise, so\n * the comments, ordering and spacing a person put in the file survive being\n * edited by the CLI.\n */\nexport function upsertEnvVar(content: string, key: string, value: string): string {\n\tconst line = `${key}=${quoteEnvValue(value)}`;\n\tconst pattern = keyPattern(key);\n\n\tlet replaced = false;\n\tconst lines = content.split('\\n').map((existing) => {\n\t\tif (replaced || !pattern.test(existing)) return existing;\n\t\treplaced = true;\n\t\t// `export KEY=` is valid dotenv, and dropping the prefix would change how\n\t\t// the file behaves when it is sourced by a shell.\n\t\treturn existing.trimStart().startsWith('export ') ? `export ${line}` : line;\n\t});\n\n\treturn replaced ? lines.join('\\n') : appendLine(content, line);\n}\n\n/** Remove a key from a `.env` file, leaving the rest of it alone. */\nexport function removeEnvVar(content: string, key: string): string {\n\tconst pattern = keyPattern(key);\n\tconst lines = content.split('\\n');\n\tconst kept = lines.filter((line) => !pattern.test(line));\n\tif (kept.length === lines.length) return content;\n\treturn kept.join('\\n');\n}\n\nexport function hasEnvVar(content: string, key: string): boolean {\n\tconst pattern = keyPattern(key);\n\treturn content.split('\\n').some((line) => pattern.test(line));\n}\n\nfunction keyPattern(key: string): RegExp {\n\treturn new RegExp(`^\\\\s*(?:export\\\\s+)?${escapeRegExp(key)}\\\\s*=`);\n}\n\nfunction escapeRegExp(value: string): string {\n\treturn value.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n\n/**\n * Quote only what dotenv would otherwise misread.\n *\n * Deliberately not the systemd quoting `vela env` uses for the server: this file\n * is read by dotenv and by people, and quoting every value would churn lines\n * that did not need to change.\n */\nfunction quoteEnvValue(value: string): string {\n\tif (/^[A-Za-z0-9_./:@+-]*$/.test(value)) return value;\n\tconst escaped = value.replaceAll('\\\\', '\\\\\\\\').replaceAll('\"', '\\\\\"').replaceAll('\\n', '\\\\n');\n\treturn `\"${escaped}\"`;\n}\n", "import fs from 'node:fs';\nimport path from 'node:path';\nimport type { ObjectLiteralExpression } from 'ts-morph';\nimport {\n\tcreateSveltekitArg,\n\tgetOrCreateObjectLiteralProperty,\n\tinspectViteSveltekit,\n\tprobeFirstExisting,\n\tSVELTE_CONFIG_CANDIDATES,\n\ttype ViteSveltekit\n} from './config-target.ts';\n\nexport interface MergeOutcome {\n\tapplied: boolean;\n\treason: string;\n\tsnippet?: string;\n\t/** Basename of the config file the merge targeted, for reporting. */\n\tfile?: string;\n}\n\nconst RUNES_VALUE = `({ filename }) => (filename.split(/[/\\\\\\\\]/).includes('node_modules') ? undefined : true)`;\n\nconst RUNES_SNIPPET = `\\tcompilerOptions: {\n\\t\\trunes: ${RUNES_VALUE}\n\\t},\\n`;\n\nconst TAILWIND_IMPORT = `import tailwindcss from '@tailwindcss/vite';`;\n\n/**\n * Ensure the Svelte `runes` compiler option is set. Defaults to the inline\n * `sveltekit()` arg in vite.config (the new SvelteKit approach), falling back to\n * `svelte.config.*` when that's where the project keeps its config. Resolution\n * mirrors SvelteKit's own precedence.\n */\nexport function mergeSvelteConfig(projectRoot: string): MergeOutcome {\n\tconst vite = inspectViteSveltekit(projectRoot);\n\n\t// Rule 1: vite.config has an inline sveltekit() arg \u2192 inject runes there.\n\tif (vite?.inlineArg) {\n\t\treturn mergeRunesIntoViteArg(vite, vite.inlineArg);\n\t}\n\n\t// Rule 2: a svelte.config.* file exists \u2192 use the legacy in-place injector.\n\tconst sveltePath = probeFirstExisting(projectRoot, SVELTE_CONFIG_CANDIDATES);\n\tif (sveltePath) {\n\t\treturn mergeRunesIntoSvelteConfig(sveltePath);\n\t}\n\n\t// Rule 3: bare sveltekit() \u2192 create an arg and inject runes into it.\n\tif (vite?.sveltekitCall && !vite.nonObjectArg) {\n\t\tconst arg = createSveltekitArg(vite);\n\t\tif (arg) return mergeRunesIntoViteArg(vite, arg);\n\t}\n\n\treturn {\n\t\tapplied: false,\n\t\treason: 'no svelte.config or vite.config sveltekit() found',\n\t\tsnippet: RUNES_SNIPPET\n\t};\n}\n\nfunction mergeRunesIntoViteArg(vite: ViteSveltekit, arg: ObjectLiteralExpression): MergeOutcome {\n\tconst file = path.basename(vite.filePath);\n\tconst compilerOptions = getOrCreateObjectLiteralProperty(arg, 'compilerOptions', '{}');\n\tif (!compilerOptions) {\n\t\treturn {\n\t\t\tapplied: false,\n\t\t\treason: 'could not access sveltekit() compilerOptions',\n\t\t\tsnippet: RUNES_SNIPPET,\n\t\t\tfile\n\t\t};\n\t}\n\tif (compilerOptions.getProperty('runes')) {\n\t\treturn { applied: false, reason: 'runes already configured', file };\n\t}\n\tcompilerOptions.addPropertyAssignment({ name: 'runes', initializer: RUNES_VALUE });\n\tvite.sourceFile.formatText();\n\tvite.sourceFile.saveSync();\n\treturn { applied: true, reason: 'added runes compilerOption', file };\n}\n\nfunction mergeRunesIntoSvelteConfig(filePath: string): MergeOutcome {\n\tconst file = path.basename(filePath);\n\tconst original = fs.readFileSync(filePath, 'utf8');\n\tif (/runes\\s*:/m.test(original)) {\n\t\treturn { applied: false, reason: 'runes already configured', file };\n\t}\n\tif (/compilerOptions\\s*:/m.test(original)) {\n\t\treturn {\n\t\t\tapplied: false,\n\t\t\treason: 'compilerOptions already present \u2014 add `runes` manually',\n\t\t\tsnippet: `runes: ${RUNES_VALUE}`,\n\t\t\tfile\n\t\t};\n\t}\n\n\tconst anchor = original.match(/^(const\\s+config\\s*=\\s*\\{)\\s*\\n/m);\n\tif (!anchor || anchor.index === undefined) {\n\t\treturn {\n\t\t\tapplied: false,\n\t\t\treason: `${file} has a non-standard shape`,\n\t\t\tsnippet: RUNES_SNIPPET,\n\t\t\tfile\n\t\t};\n\t}\n\n\tconst insertAt = anchor.index + anchor[0].length;\n\tconst updated = original.slice(0, insertAt) + RUNES_SNIPPET + original.slice(insertAt);\n\tfs.writeFileSync(filePath, updated);\n\treturn { applied: true, reason: 'added runes compilerOption', file };\n}\n\nexport function mergeViteConfig(filePath: string): MergeOutcome {\n\tif (!fs.existsSync(filePath)) {\n\t\treturn {\n\t\t\tapplied: false,\n\t\t\treason: 'vite.config.ts not found',\n\t\t\tsnippet: `${TAILWIND_IMPORT}\\n// then add tailwindcss() to the plugins array`\n\t\t};\n\t}\n\n\tconst original = fs.readFileSync(filePath, 'utf8');\n\tif (original.includes('@tailwindcss/vite')) {\n\t\treturn { applied: false, reason: 'tailwindcss plugin already present' };\n\t}\n\n\tconst pluginsMatch = original.match(/plugins\\s*:\\s*\\[/);\n\tif (!pluginsMatch || pluginsMatch.index === undefined) {\n\t\treturn {\n\t\t\tapplied: false,\n\t\t\treason: 'vite.config.ts has a non-standard shape \u2014 no plugins array found',\n\t\t\tsnippet: `import tailwindcss from '@tailwindcss/vite';\\n// plugins: [tailwindcss(), sveltekit()]`\n\t\t};\n\t}\n\n\tconst withImport = addImport(original, TAILWIND_IMPORT);\n\n\tconst newPluginsMatch = withImport.match(/plugins\\s*:\\s*\\[/)!;\n\tconst insertAt = newPluginsMatch.index! + newPluginsMatch[0].length;\n\tconst trailing = withImport.slice(insertAt);\n\tconst prefix = /^\\s*\\]/.test(trailing) ? 'tailwindcss()' : 'tailwindcss(), ';\n\tconst updated = withImport.slice(0, insertAt) + prefix + withImport.slice(insertAt);\n\n\tfs.writeFileSync(filePath, updated);\n\treturn { applied: true, reason: 'added @tailwindcss/vite plugin' };\n}\n\nexport function mergeTsconfig(filePath: string): MergeOutcome {\n\tif (!fs.existsSync(filePath)) {\n\t\treturn { applied: false, reason: 'tsconfig.json not found' };\n\t}\n\tconst original = fs.readFileSync(filePath, 'utf8');\n\tif (/rewriteRelativeImportExtensions/.test(original)) {\n\t\treturn { applied: false, reason: 'rewriteRelativeImportExtensions already set' };\n\t}\n\n\tconst match = original.match(/\"compilerOptions\"\\s*:\\s*\\{/);\n\tif (!match || match.index === undefined) {\n\t\treturn {\n\t\t\tapplied: false,\n\t\t\treason: 'tsconfig.json has no compilerOptions block',\n\t\t\tsnippet: `\"compilerOptions\": { \"rewriteRelativeImportExtensions\": true }`\n\t\t};\n\t}\n\n\tconst insertAt = match.index + match[0].length;\n\tconst indent = detectIndent(original, insertAt);\n\tconst updated =\n\t\toriginal.slice(0, insertAt) +\n\t\t`\\n${indent}\"rewriteRelativeImportExtensions\": true,` +\n\t\toriginal.slice(insertAt);\n\tfs.writeFileSync(filePath, updated);\n\treturn { applied: true, reason: 'added rewriteRelativeImportExtensions' };\n}\n\nconst GITIGNORE_ENTRIES = [\n\t'.env',\n\t'.env.*',\n\t'!.env.example',\n\t'!.env.test',\n\t'vite.config.js.timestamp-*',\n\t'vite.config.ts.timestamp-*'\n];\n\nexport function mergeGitignore(filePath: string): MergeOutcome {\n\tconst existing = fs.existsSync(filePath) ? fs.readFileSync(filePath, 'utf8') : '';\n\tconst lines = existing.split('\\n').map((l) => l.trim());\n\tconst missing = GITIGNORE_ENTRIES.filter((entry) => !lines.includes(entry));\n\tif (missing.length === 0) {\n\t\treturn { applied: false, reason: '.gitignore already has vela entries' };\n\t}\n\n\tconst needsNewline = existing.length > 0 && !existing.endsWith('\\n');\n\tconst appended = `${existing}${needsNewline ? '\\n' : ''}${missing.join('\\n')}\\n`;\n\tfs.writeFileSync(filePath, appended);\n\treturn { applied: true, reason: `added ${missing.length} gitignore entries` };\n}\n\nfunction addImport(source: string, importLine: string): string {\n\tif (source.includes(importLine)) return source;\n\tconst importRegex = /^import\\s[^\\n]+;?\\s*$/gm;\n\tlet lastImportEnd = 0;\n\tlet match: RegExpExecArray | null;\n\twhile ((match = importRegex.exec(source)) !== null) {\n\t\tlastImportEnd = match.index + match[0].length;\n\t}\n\tif (lastImportEnd === 0) {\n\t\treturn `${importLine}\\n${source}`;\n\t}\n\treturn source.slice(0, lastImportEnd) + `\\n${importLine}` + source.slice(lastImportEnd);\n}\n\nfunction detectIndent(source: string, atOffset: number): string {\n\tconst rest = source.slice(atOffset);\n\tconst nextLine = rest.match(/\\n([ \\t]+)\"/);\n\treturn nextLine ? nextLine[1]! : '\\t';\n}\n", "import fs from 'node:fs';\nimport path from 'node:path';\nimport {\n\tProject,\n\tQuoteKind,\n\tSyntaxKind,\n\ttype CallExpression,\n\ttype ObjectLiteralExpression,\n\ttype SourceFile\n} from 'ts-morph';\n\nexport const VITE_CONFIG_CANDIDATES = [\n\t'vite.config.ts',\n\t'vite.config.js',\n\t'vite.config.mjs',\n\t'vite.config.cjs'\n];\n\nexport const SVELTE_CONFIG_CANDIDATES = [\n\t'svelte.config.ts',\n\t'svelte.config.js',\n\t'svelte.config.mjs',\n\t'svelte.config.cjs'\n];\n\n/** First candidate that exists under `root`, or null. */\nexport function probeFirstExisting(root: string, candidates: string[]): string | null {\n\tfor (const rel of candidates) {\n\t\tconst abs = path.join(root, rel);\n\t\tif (fs.existsSync(abs)) return abs;\n\t}\n\treturn null;\n}\n\nexport interface ViteSveltekit {\n\tfilePath: string;\n\tsourceFile: SourceFile;\n\tsveltekitCall: CallExpression | null;\n\t/** Inline object argument of `sveltekit(...)`, if it's an object literal. */\n\tinlineArg: ObjectLiteralExpression | null;\n\t/** True when `sveltekit(...)` has a non-object argument we mustn't touch. */\n\tnonObjectArg: boolean;\n}\n\n/**\n * Load the project's `vite.config.*` (if any) and locate the `sveltekit()` call\n * plus its inline argument. Returns null when there is no vite config file.\n */\nexport function inspectViteSveltekit(root: string): ViteSveltekit | null {\n\tconst filePath = probeFirstExisting(root, VITE_CONFIG_CANDIDATES);\n\tif (!filePath) return null;\n\n\tconst project = new Project({\n\t\tcompilerOptions: { allowJs: true },\n\t\tmanipulationSettings: { quoteKind: QuoteKind.Single }\n\t});\n\tconst sourceFile = project.addSourceFileAtPath(filePath);\n\tconst sveltekitCall =\n\t\tsourceFile\n\t\t\t.getDescendantsOfKind(SyntaxKind.CallExpression)\n\t\t\t.find((ce) => ce.getExpression().getText() === 'sveltekit') ?? null;\n\n\tlet inlineArg: ObjectLiteralExpression | null = null;\n\tlet nonObjectArg = false;\n\tconst arg = sveltekitCall?.getArguments()[0];\n\tif (arg) {\n\t\tif (arg.getKind() === SyntaxKind.ObjectLiteralExpression) {\n\t\t\tinlineArg = arg as ObjectLiteralExpression;\n\t\t} else {\n\t\t\tnonObjectArg = true;\n\t\t}\n\t}\n\n\treturn { filePath, sourceFile, sveltekitCall, inlineArg, nonObjectArg };\n}\n\n/** Add an empty `{}` argument to a bare `sveltekit()` call and return it. */\nexport function createSveltekitArg(vite: ViteSveltekit): ObjectLiteralExpression | null {\n\tif (!vite.sveltekitCall || vite.nonObjectArg) return null;\n\treturn vite.sveltekitCall.addArgument('{}').asKind(SyntaxKind.ObjectLiteralExpression) ?? null;\n}\n\n/**\n * Get the object-literal value of property `name`, creating it as an empty\n * object when missing. Returns null if it can't be coerced to an object literal.\n */\nexport function getOrCreateObjectLiteralProperty(\n\tobj: ObjectLiteralExpression,\n\tname: string,\n\tinitializer: string\n): ObjectLiteralExpression | null {\n\tconst prop = obj.getProperty(name);\n\tif (!prop) {\n\t\tobj.addPropertyAssignment({ name, initializer });\n\t\tconst added = obj.getProperty(name);\n\t\tif (!added || added.getKind() !== SyntaxKind.PropertyAssignment) return null;\n\t\tconst init = (added as import('ts-morph').PropertyAssignment).getInitializer();\n\t\treturn init && init.getKind() === SyntaxKind.ObjectLiteralExpression\n\t\t\t? (init as ObjectLiteralExpression)\n\t\t\t: null;\n\t}\n\n\tif (prop.getKind() !== SyntaxKind.PropertyAssignment) return null;\n\tconst init = (prop as import('ts-morph').PropertyAssignment).getInitializer();\n\tif (!init) return null;\n\tif (init.getKind() !== SyntaxKind.ObjectLiteralExpression) {\n\t\t(prop as import('ts-morph').PropertyAssignment).setInitializer(initializer);\n\t\tconst init2 = (prop as import('ts-morph').PropertyAssignment).getInitializer();\n\t\treturn init2 && init2.getKind() === SyntaxKind.ObjectLiteralExpression\n\t\t\t? (init2 as ObjectLiteralExpression)\n\t\t\t: null;\n\t}\n\n\treturn init as ObjectLiteralExpression;\n}\n", "import fs from 'node:fs';\nimport path from 'node:path';\n\nconst VANILLA_MARKER = 'Welcome to SvelteKit';\nconst PAGE_REL = path.join('src', 'routes', '+page.svelte');\n\nexport function isVanillaRoutes(cwd: string): boolean {\n\tconst pagePath = path.join(cwd, PAGE_REL);\n\tif (!fs.existsSync(pagePath)) return false;\n\treturn fs.readFileSync(pagePath, 'utf8').includes(VANILLA_MARKER);\n}\n", "import * as p from '@clack/prompts';\n\n/**\n * A file a pattern could not change, and what the user should do about it.\n *\n * Modifiers do best-effort surgery on files the project owns, so they meet\n * shapes they don't recognise \u2014 a renamed export, a different wrapper, a config\n * that isn't an object literal. When that happens they refuse to touch the file\n * and hand back a paste-ready snippet instead. That snippet is the whole point\n * of the failure path, so it gets printed, not counted.\n */\nexport interface ReportFailure {\n\tpath: string;\n\tstatus: 'failed' | 'not-found';\n\tmessage?: string;\n}\n\nexport interface ResultReport {\n\tsummary: string;\n\tfilesCreated?: string[];\n\tfilesModified?: string[];\n\tfilesDeleted?: string[];\n\tcomponentsAdded?: string[];\n\tpackagesInstalled?: string[];\n\tcollectionsAdded?: string[];\n\trecordsLoaded?: string[];\n\trecordsCleared?: string[];\n\tsections?: Array<{ label: string; items: string[] }>;\n\tfailures?: ReportFailure[];\n\tnextSteps?: string[];\n}\n\nexport function reportResult(report: ResultReport): void {\n\tconst sections: Array<[string, string[] | undefined]> = [\n\t\t['Files created', report.filesCreated],\n\t\t['Files modified', report.filesModified],\n\t\t['Files deleted', report.filesDeleted],\n\t\t['UI components added', report.componentsAdded],\n\t\t['Packages installed', report.packagesInstalled],\n\t\t['Collections added', report.collectionsAdded],\n\t\t['Records loaded', report.recordsLoaded],\n\t\t['Records cleared', report.recordsCleared]\n\t];\n\tfor (const extra of report.sections ?? []) {\n\t\tsections.push([extra.label, extra.items]);\n\t}\n\n\tconst body: string[] = [];\n\tfor (const [label, items] of sections) {\n\t\tif (!items || items.length === 0) continue;\n\t\tif (body.length > 0) body.push('');\n\t\tbody.push(`${label}:`);\n\t\tfor (const item of items) body.push(`- ${item}`);\n\t}\n\n\tconst failures = report.failures ?? [];\n\n\t// Anything changed is still a success; the failures are reported separately\n\t// rather than folded into the summary, so a partial application reads as\n\t// exactly that.\n\tif (body.length > 0) {\n\t\tp.log.success(`${report.summary}\\n\\n${body.join('\\n')}`);\n\t} else if (failures.length === 0) {\n\t\tp.log.success(report.summary);\n\t}\n\n\tfor (const failure of failures) {\n\t\tconst headline =\n\t\t\tfailure.status === 'not-found'\n\t\t\t\t? `Could not find ${failure.path}`\n\t\t\t\t: `Could not update ${failure.path}`;\n\t\tp.log.warn(failure.message ? `${headline}\\n\\n${failure.message}` : headline);\n\t}\n\n\tif (report.nextSteps && report.nextSteps.length > 0) {\n\t\tp.note(report.nextSteps.map((s) => `- ${s}`).join('\\n'), 'Next steps', {\n\t\t\tformat: (line) => line\n\t\t});\n\t}\n}\n", "import fs from 'node:fs';\nimport path from 'node:path';\nimport { fillTemplatePlaceholders, type TemplateValues } from './package-json.ts';\n\n/**\n * npm never publishes files named `.gitignore` or `.npmrc` inside a package, so\n * templates store them under a publish-safe name and the real name is restored\n * when a template is copied into a project.\n *\n * Keyed by the name the file must have in the generated project.\n */\nconst PUBLISH_SAFE_NAMES: Record<string, string> = {\n\t'.gitignore': '_gitignore',\n\t'.npmrc': '_npmrc'\n};\n\n/** Template-relative path for a file that must land at `projectRelPath`. */\nexport function templateName(projectRelPath: string): string {\n\tconst safe = PUBLISH_SAFE_NAMES[path.basename(projectRelPath)];\n\tif (!safe) return projectRelPath;\n\tconst dir = path.dirname(projectRelPath);\n\treturn dir === '.' ? safe : path.join(dir, safe);\n}\n\n/** Restore publish-safe names to their real ones after copying a template tree. */\nexport function restoreTemplateNames(target: string): void {\n\tfor (const [real, safe] of Object.entries(PUBLISH_SAFE_NAMES)) {\n\t\tconst from = path.join(target, safe);\n\t\tif (!fs.existsSync(from)) continue;\n\t\tfs.renameSync(from, path.join(target, real));\n\t}\n}\n\n/**\n * A template ships parameterized files under a `.template.` infix \u2014 the reason\n * being that `package.template.json` has to stay valid JSON (and installable\n * TypeScript) while it still holds `~TODO~` placeholders.\n */\nconst TEMPLATE_SOURCE = /\\.template\\.([^.]+)$/;\n\n/**\n * Fill placeholders in every `*.template.*` file a copied template left behind,\n * write each to its real name, and remove the source.\n *\n * Returns the project-relative paths written, so a caller can assert the files a\n * template must produce.\n */\nexport function applyTemplateFiles(target: string, values: TemplateValues): string[] {\n\tconst written: string[] = [];\n\tfor (const source of findTemplateSources(target)) {\n\t\tconst raw = fs.readFileSync(source, 'utf8');\n\t\tconst dest = source.replace(TEMPLATE_SOURCE, '.$1');\n\t\tfs.writeFileSync(dest, fillTemplatePlaceholders(raw, values));\n\t\tfs.unlinkSync(source);\n\t\twritten.push(path.relative(target, dest));\n\t}\n\treturn written.sort();\n}\n\nfunction findTemplateSources(dir: string): string[] {\n\tconst found: string[] = [];\n\tfor (const entry of fs.readdirSync(dir, { withFileTypes: true })) {\n\t\tconst full = path.join(dir, entry.name);\n\t\tif (entry.isDirectory()) {\n\t\t\tif (entry.name === 'node_modules' || entry.name === '.git') continue;\n\t\t\tfound.push(...findTemplateSources(full));\n\t\t} else if (entry.isFile() && TEMPLATE_SOURCE.test(entry.name)) {\n\t\t\tfound.push(full);\n\t\t}\n\t}\n\treturn found;\n}\n", "import fs from 'node:fs';\nimport path from 'node:path';\nimport process from 'node:process';\nimport * as v from 'valibot';\nimport { Command } from 'commander';\nimport * as p from '@clack/prompts';\nimport { detect, resolveCommand } from 'package-manager-detector';\nimport { helpConfig } from '../lib/help.ts';\nimport { runCommand } from '../lib/run.ts';\nimport { parseOptions } from '../lib/options.ts';\nimport {\n\tDEFAULT_TEMPLATE,\n\tTEMPLATE_MANIFEST,\n\tfindProjectTemplate,\n\tprojectTemplateNames,\n\ttype ProjectTemplate\n} from '../lib/templates.ts';\nimport {\n\tAGENT_NAMES,\n\tgetUserAgent,\n\tinstallOption,\n\tinstallDependencies,\n\tpackageManagerPrompt,\n\taddPnpmBuildDependencies\n} from '../lib/package-manager.ts';\nimport { createSuperuser, withPocketbase } from '../lib/pocketbase.ts';\nimport { writeEnvFile } from '../lib/env.ts';\nimport pkg from '../../package.json' with { type: 'json' };\nimport { applyTemplateFiles, restoreTemplateNames } from '../lib/template-files.ts';\nimport { reportResult } from '../lib/result-report.ts';\n\n/**\n * Built per run rather than at module load: the accepted templates come from the\n * templates directory, so adding one can't leave `--template` behind, and the\n * directory is only read once a command that needs it actually runs.\n */\nfunction optionsSchema() {\n\tconst templates = projectTemplateNames();\n\treturn v.strictObject({\n\t\tinstall: v.union([v.boolean(), v.picklist(AGENT_NAMES)], 'must be a package manager'),\n\t\ttemplate: v.optional(v.picklist(templates, `must be one of: ${templates.join(', ')}`)),\n\t\tname: v.optional(v.pipe(v.string(), v.trim(), v.minLength(1, 'must not be empty'))),\n\t\temail: v.optional(v.pipe(v.string(), v.email('must be a valid email address'))),\n\t\tpassword: v.optional(v.pipe(v.string(), v.minLength(8, 'must be at least 8 characters long')))\n\t});\n}\ntype Options = v.InferOutput<ReturnType<typeof optionsSchema>>;\n\nexport const create = new Command('create')\n\t.description('scaffold a new velastack project')\n\t.argument('[path]', 'where the project will be created')\n\t.option('--template <type>', 'template to scaffold', 'minimal')\n\t.option('--no-install', 'skip installing dependencies')\n\t.option('--name <name>', 'app name (used for emails, etc)')\n\t.option('--email <email>', 'email of the admin user')\n\t.option('--password <password>', 'password of the admin user')\n\t.addOption(installOption)\n\t.configureHelp(helpConfig)\n\t.action((projectPath: string | undefined, rawOpts) => {\n\t\treturn runCommand(async () => {\n\t\t\tconst options = parseOptions(optionsSchema(), rawOpts);\n\t\t\tconst { directory, packageManager, name, template } = await createProject(\n\t\t\t\tprojectPath,\n\t\t\t\toptions\n\t\t\t);\n\n\t\t\tconst relative = path.relative(process.cwd(), directory);\n\t\t\tconst pm =\n\t\t\t\tpackageManager ?? (await detect({ cwd: directory }))?.name ?? getUserAgent() ?? 'npm';\n\n\t\t\tconst nextSteps: string[] = [];\n\t\t\tif (relative !== '') {\n\t\t\t\tconst hasSpaces = relative.includes(' ');\n\t\t\t\tnextSteps.push(`\\`cd ${hasSpaces ? `\"${relative}\"` : relative}\\``);\n\t\t\t}\n\t\t\tif (!packageManager) {\n\t\t\t\tconst resolved = resolveCommand(pm, 'install', []);\n\t\t\t\tif (resolved) {\n\t\t\t\t\tnextSteps.push(\n\t\t\t\t\t\t`\\`${resolved.command} ${resolved.args.join(' ')}\\` to install dependencies`\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst runDev = resolveCommand(pm, 'run', ['dev', '--open']);\n\t\t\tif (runDev) {\n\t\t\t\tnextSteps.push(\n\t\t\t\t\t`\\`${runDev.command} ${runDev.args.join(' ')}\\` to start the dev server (Ctrl-C to stop)`\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (template.backend) {\n\t\t\t\tnextSteps.push('Run `vela generate scaffold <model>` to generate your first CRUD pages.');\n\t\t\t} else {\n\t\t\t\tnextSteps.push(\n\t\t\t\t\t'Set your deployed URL in `src/lib/site.ts` before building for production.'\n\t\t\t\t);\n\t\t\t\tnextSteps.push('Run `vela ui add <component>` to add UI components.');\n\t\t\t}\n\t\t\tnextSteps.push('Stuck? Visit https://docs.velastack.dev');\n\n\t\t\treportResult({\n\t\t\t\tsummary: `Created ${name} at ${directory}.`,\n\t\t\t\tnextSteps\n\t\t\t});\n\t\t}, 'Failed to create project.');\n\t});\n\nasync function createProject(cwdArg: string | undefined, options: Options) {\n\tconst onCancel = () => {\n\t\tp.cancel('Operation cancelled.');\n\t\tprocess.exit(0);\n\t};\n\n\tconst template = findProjectTemplate(options.template ?? DEFAULT_TEMPLATE);\n\tif (!template.backend && (options.email || options.password)) {\n\t\tthrow new Error(\n\t\t\t`--email and --password don't apply to the ${template.name} template \u2014 it has no backend.`\n\t\t);\n\t}\n\n\tlet directory: string;\n\tif (cwdArg) {\n\t\tdirectory = path.resolve(cwdArg);\n\t} else {\n\t\tconst answer = await p.text({\n\t\t\tmessage: 'Where would you like your project to be created?',\n\t\t\tplaceholder: ' (hit Enter to use current directory)',\n\t\t\tdefaultValue: './'\n\t\t});\n\t\tif (p.isCancel(answer)) onCancel();\n\t\tdirectory = path.resolve(answer as string);\n\t}\n\n\tif (\n\t\tfs.existsSync(directory) &&\n\t\tfs.readdirSync(directory).filter((f) => !f.startsWith('.git')).length > 0\n\t) {\n\t\tconst force = await p.confirm({\n\t\t\tmessage: 'Directory not empty. Continue?',\n\t\t\tinitialValue: false\n\t\t});\n\t\tif (p.isCancel(force) || !force) onCancel();\n\t}\n\n\tconst dirName = path.basename(directory);\n\n\tconst { name } = await p.group(\n\t\t{\n\t\t\tname: () => {\n\t\t\t\tif (options.name) return Promise.resolve(options.name);\n\t\t\t\treturn p.text({\n\t\t\t\t\tmessage: 'App name (used for emails, etc)',\n\t\t\t\t\tinitialValue: dirName || 'SvelteKit',\n\t\t\t\t\tvalidate: (value) => (value?.trim() ? undefined : 'App name is required')\n\t\t\t\t});\n\t\t\t}\n\t\t},\n\t\t{ onCancel }\n\t);\n\n\tconst credentials = template.backend ? await promptCredentials(options, onCancel) : undefined;\n\n\tconst projectPath = directory;\n\n\tcopyTemplate(template, projectPath);\n\tapplyTemplateFiles(projectPath, { appName: name, cliVersion: pkg.version });\n\tif (!fs.existsSync(path.join(projectPath, 'package.json'))) {\n\t\tthrow new Error(`Template ${template.name} is missing package.template.json`);\n\t}\n\n\tp.log.success('Project created');\n\n\tlet packageManager: ReturnType<typeof getUserAgent> | undefined;\n\tif (options.install !== false) {\n\t\tconst pm =\n\t\t\ttypeof options.install === 'string'\n\t\t\t\t? options.install\n\t\t\t\t: await packageManagerPrompt(projectPath);\n\n\t\tif (pm) {\n\t\t\tconst builds = template.backend ? ['esbuild', 'pocketbase-server'] : ['esbuild'];\n\t\t\taddPnpmBuildDependencies(projectPath, pm, builds);\n\t\t\tawait installDependencies(pm, projectPath);\n\t\t\tpackageManager = pm;\n\t\t}\n\t}\n\n\tif (credentials) {\n\t\tconst { email, password } = credentials;\n\n\t\tp.log.step('Initializing PocketBase...');\n\t\tawait createSuperuser(projectPath, email, password);\n\n\t\tawait withPocketbase(\n\t\t\tprojectPath,\n\t\t\tasync (pb) => {\n\t\t\t\tawait pb.settings.update({\n\t\t\t\t\tmeta: { appName: name, appURL: 'http://localhost:5173' }\n\t\t\t\t});\n\t\t\t},\n\t\t\t{ email, password }\n\t\t);\n\n\t\twriteEnvFile(\n\t\t\tprojectPath,\n\t\t\t{\n\t\t\t\tPOCKETBASE_SUPERUSER_EMAIL: email,\n\t\t\t\tPOCKETBASE_SUPERUSER_PASSWORD: password\n\t\t\t},\n\t\t\t['PocketBase superuser credentials \u2014 used by `vela` commands']\n\t\t);\n\n\t\tp.log.success('PocketBase initialized');\n\t}\n\n\treturn { directory: projectPath, packageManager, name, template };\n}\n\nfunction promptCredentials(options: Options, onCancel: () => void) {\n\treturn p.group(\n\t\t{\n\t\t\temail: () => {\n\t\t\t\tif (options.email) return Promise.resolve(options.email);\n\t\t\t\treturn p.text({\n\t\t\t\t\tmessage: 'Enter an email for the admin user',\n\t\t\t\t\tinitialValue: 'admin@example.com',\n\t\t\t\t\tvalidate: (value) =>\n\t\t\t\t\t\t!value ? 'Email is required' : !value.includes('@') ? 'Invalid email' : undefined\n\t\t\t\t});\n\t\t\t},\n\t\t\tpassword: () => {\n\t\t\t\tif (options.password) return Promise.resolve(options.password);\n\t\t\t\treturn p.password({\n\t\t\t\t\tmessage: 'Enter a password for the admin user (at least 8 characters)',\n\t\t\t\t\tvalidate: (value) =>\n\t\t\t\t\t\t!value\n\t\t\t\t\t\t\t? 'Password is required'\n\t\t\t\t\t\t\t: value.length < 8\n\t\t\t\t\t\t\t\t? 'Password must be at least 8 characters long'\n\t\t\t\t\t\t\t\t: undefined\n\t\t\t\t});\n\t\t\t}\n\t\t},\n\t\t{ onCancel }\n\t);\n}\n\nfunction copyTemplate(template: ProjectTemplate, target: string): void {\n\tfs.mkdirSync(target, { recursive: true });\n\tfs.cpSync(template.dir, target, {\n\t\trecursive: true,\n\t\t// The manifest describes the template to the CLI; it isn't part of the project.\n\t\tfilter: (src) =>\n\t\t\tpath.basename(src) !== '.DS_Store' && path.relative(template.dir, src) !== TEMPLATE_MANIFEST\n\t});\n\trestoreTemplateNames(target);\n}\n", "import { Command } from 'commander';\nimport { helpConfig } from '../lib/help.ts';\nimport { form } from './generate/form.ts';\nimport { schema } from './generate/schema.ts';\nimport { resource } from './generate/resource.ts';\nimport { scaffold } from './generate/scaffold.ts';\nimport { migration } from './generate/migration.ts';\n\nexport const generate = new Command('generate')\n\t.description('generate scaffolding for database models and forms')\n\t.configureHelp(helpConfig)\n\t.addCommand(form)\n\t.addCommand(schema)\n\t.addCommand(resource)\n\t.addCommand(scaffold)\n\t.addCommand(migration);\n", "import { Command } from 'commander';\nimport * as p from '@clack/prompts';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand } from '../../lib/run.ts';\nimport { runPattern } from '../../lib/pattern-runner.ts';\nimport {\n\trunSchemaStage,\n\trunLayoutStage,\n\tspecToArgv,\n\twriteLayoutSidecar\n} from '../../lib/ai-flow.ts';\n\nexport const form = new Command('form')\n\t.description('generate a form from a model')\n\t.argument('[model]', 'model name (e.g. \"contact\")')\n\t.argument('[fields...]', 'field definitions (e.g. \"name:text\", \"email:email\")')\n\t.option('--remote', 'generate a form backed by a remote PocketBase collection')\n\t.option(\n\t\t'--route <route>',\n\t\t'place the form at a custom route (e.g. \"(app)/[team_id]/projects/new\"). Defaults to the model name under (app)/(public).'\n\t)\n\t.option(\n\t\t'--ai <description>',\n\t\t'design the form with AI from a natural-language description (two stages: schema \u2192 layout)'\n\t)\n\t.allowUnknownOption(true)\n\t.configureHelp(helpConfig)\n\t.action(\n\t\t(\n\t\t\tmodel: string | undefined,\n\t\t\tfields: string[],\n\t\t\toptions: { remote?: boolean; route?: string; ai?: string }\n\t\t) =>\n\t\t\trunCommand(async () => {\n\t\t\t\tlet argv: string[];\n\t\t\t\tlet modelName: string;\n\t\t\t\tlet sidecarPath: string | null = null;\n\n\t\t\t\tif (options.ai) {\n\t\t\t\t\tif (model) {\n\t\t\t\t\t\tthrow new Error('Pass either a model name or --ai, not both.');\n\t\t\t\t\t}\n\t\t\t\t\tconst stage = await runSchemaStage({ prompt: options.ai, useCase: 'form' });\n\t\t\t\t\tif (!stage) {\n\t\t\t\t\t\tp.cancel('Aborted before any files were written.');\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tconst layout = await runLayoutStage(stage.workspaceRootDir, stage.model);\n\t\t\t\t\tif (!layout) {\n\t\t\t\t\t\tp.cancel('Aborted before any files were written.');\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\targv = specToArgv(stage.model);\n\t\t\t\t\tmodelName = stage.model.name;\n\t\t\t\t\tsidecarPath = writeLayoutSidecar(stage.workspaceRootDir, modelName, layout);\n\t\t\t\t} else {\n\t\t\t\t\tif (!model) {\n\t\t\t\t\t\tthrow new Error('Missing required argument: model. Pass a model name or use --ai.');\n\t\t\t\t\t}\n\t\t\t\t\targv = [model, ...fields];\n\t\t\t\t\tmodelName = model;\n\t\t\t\t}\n\n\t\t\t\tconst slug = options.remote ? 'generate-form-remote' : 'generate-form';\n\t\t\t\tconst nextSteps: string[] = [\n\t\t\t\t\t'Edit the form fields and validation in the generated +page.svelte.',\n\t\t\t\t\t'Run `vela dev` to preview the form in the browser.'\n\t\t\t\t];\n\t\t\t\tif (sidecarPath) {\n\t\t\t\t\tnextSteps.unshift(\n\t\t\t\t\t\t`Apply the AI-designed form layout from ${sidecarPath} to the generated +page.svelte.`\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tawait runPattern(\n\t\t\t\t\tslug,\n\t\t\t\t\targv,\n\t\t\t\t\t{ route: options.route },\n\t\t\t\t\t{\n\t\t\t\t\t\tsummary: `Created ${modelName} form.`,\n\t\t\t\t\t\tnextSteps,\n\t\t\t\t\t\ttask: {\n\t\t\t\t\t\t\ttitle: 'Generating form',\n\t\t\t\t\t\t\tsuccess: 'Generated form',\n\t\t\t\t\t\t\terror: 'Failed to generate form'\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t);\n\t\t\t}, 'Failed to generate form.')\n\t);\n", "import path from 'node:path';\nimport * as p from '@clack/prompts';\nimport { bySlug, type Slug } from '@velastack/patterns';\nimport { withPocketbase } from './pocketbase.ts';\nimport { getWorkspace } from './workspace.ts';\nimport { reportResult, type ReportFailure } from './result-report.ts';\n\nexport interface PatternReport {\n\tsummary?: string;\n\tnextSteps?: string[];\n\ttask: {\n\t\ttitle: string;\n\t\tsuccess: string;\n\t\terror: string;\n\t};\n}\n\nfunction toRelative(root: string, filePath: string): string {\n\treturn path.isAbsolute(filePath) ? path.relative(root, filePath) : filePath;\n}\n\n/**\n * What a pattern hands back for one file.\n *\n * A modifier that refuses to touch a file it doesn't recognise reports\n * `failed` / `not-found` plus a remediation snippet. Those entries are new\n * here: `writeResult` used to drop them, so a partial application was reported\n * as a clean success and the snippet was never seen. Partitioning on `status`\n * is what keeps a failure out of the \"created\"/\"modified\" lists.\n */\ninterface ResultFile {\n\tpath: string;\n\tstatus?: 'success' | 'failed' | 'not-found';\n\tmessage?: string;\n}\n\nconst isSuccess = (f: ResultFile) => (f.status ?? 'success') === 'success';\n\nexport async function runPattern(\n\tslug: Slug,\n\targv: string[],\n\tinput: Record<string, unknown>,\n\treport: PatternReport\n): Promise<void> {\n\tconst pattern = bySlug[slug];\n\tif (!pattern) {\n\t\tthrow new Error(`Unknown pattern: ${slug}`);\n\t}\n\n\tconst { workspaceRootDir, features } = await getWorkspace();\n\n\tconst log = p.taskLog({ title: report.task.title });\n\n\tlet result;\n\ttry {\n\t\tresult = await pattern.generate({\n\t\t\targv,\n\t\t\tenv: 'runtime',\n\t\t\troot: workspaceRootDir,\n\t\t\tfeatures,\n\t\t\tinput,\n\t\t\t// Patterns no longer read the schema themselves: @velastack/pocketbase-codegen\n\t\t\t// takes an injected client, and only the CLI knows how to reach (or spawn)\n\t\t\t// a PocketBase for this workspace.\n\t\t\tgetCollections: async () => {\n\t\t\t\tconst { getCollections } = await import('@velastack/pocketbase-codegen');\n\t\t\t\tlet collections: Awaited<ReturnType<typeof getCollections>> = [];\n\t\t\t\tawait withPocketbase(workspaceRootDir, async (pb) => {\n\t\t\t\t\tcollections = await getCollections(pb);\n\t\t\t\t});\n\t\t\t\treturn collections;\n\t\t\t},\n\t\t\tlogger: { info: (message: string) => log.message(message) }\n\t\t});\n\t\tlog.success(report.task.success);\n\t} catch (e) {\n\t\tlog.error(report.task.error);\n\t\tthrow e;\n\t}\n\n\tconst rel = (f: string) => toRelative(workspaceRootDir, f);\n\n\tconst files: ResultFile[] = [...result.creates, ...result.modifies, ...result.deletes];\n\tconst failures: ReportFailure[] = files\n\t\t.filter((f) => !isSuccess(f))\n\t\t.map((f) => ({\n\t\t\tpath: rel(f.path),\n\t\t\tstatus: f.status === 'not-found' ? 'not-found' : 'failed',\n\t\t\tmessage: f.message\n\t\t}));\n\n\tconst created = result.creates.filter(isSuccess);\n\tconst modified = result.modifies.filter(isSuccess);\n\tconst deleted = result.deletes.filter(isSuccess);\n\n\tconst totalChanges =\n\t\tcreated.length +\n\t\tmodified.length +\n\t\tdeleted.length +\n\t\tresult.components.length +\n\t\tresult.packages.length +\n\t\tresult.collections.length;\n\n\t// A run that only produced failures still has something to say.\n\tif (totalChanges === 0 && failures.length === 0) {\n\t\tp.log.info(`${pattern.title ?? slug} produced no changes.`);\n\t\treturn;\n\t}\n\n\treportResult({\n\t\tsummary: report.summary ?? `Applied ${pattern.title ?? slug}.`,\n\t\tfilesCreated: created.map((f: { path: string }) => rel(f.path)),\n\t\tfilesModified: modified.map((f: { path: string }) => rel(f.path)),\n\t\tfilesDeleted: deleted.map((f: { path: string }) => rel(f.path)),\n\t\tcomponentsAdded: result.components,\n\t\tpackagesInstalled: result.packages,\n\t\tcollectionsAdded: result.collections.map((c: { name: string }) => c.name),\n\t\tfailures,\n\t\t// Next steps assume the pattern applied; when part of it didn't, the\n\t\t// remediation snippets above are the actual next step.\n\t\tnextSteps: failures.length > 0 ? undefined : report.nextSteps\n\t});\n}\n", "import fs from 'node:fs';\nimport path from 'node:path';\nimport * as p from '@clack/prompts';\nimport pc from 'picocolors';\nimport { aiSchema, aiForm, type CollectionSpec, type FormLayout } from './ai-client.ts';\nimport { aiLoop } from './ai-loop.ts';\nimport { loadExistingModels } from './ai-existing-models.ts';\nimport { collectionSpecToArgv } from './ai-to-argv.ts';\nimport { renderGrid } from './ai-grid.ts';\nimport { getWorkspace } from './workspace.ts';\n\nexport type AiUseCase = 'scaffold' | 'form' | 'schema';\n\nconst USE_CASE_HINT: Record<AiUseCase, string> = {\n\tscaffold:\n\t\t'Use case: scaffold \u2014 designing a new persisted PocketBase collection. Lean toward forward-thinking field choices.',\n\tform: 'Use case: form \u2014 designing fields for a Svelte form with no DB persistence. Focus on user-input fields; relations only to existing collections.',\n\tschema: 'Use case: schema \u2014 designing a standalone zod schema. Same considerations as form.'\n};\n\nfunction renderModel(spec: CollectionSpec): void {\n\tconst lines: string[] = [];\n\tlines.push(`${pc.bold(spec.name)} (${spec.type})`);\n\tconst nameWidth = Math.max(...spec.fields.map((f) => f.name.length), 4);\n\tconst typeWidth = Math.max(...spec.fields.map((f) => f.type.length), 4);\n\tfor (const f of spec.fields) {\n\t\tconst required = f.required ? pc.yellow('!') : ' ';\n\t\tconst extra: string[] = [];\n\t\tif (f.values && f.values.length > 0) extra.push(`values=[${f.values.join(',')}]`);\n\t\tif (f.collectionName) extra.push(`\u2192 ${f.collectionName}`);\n\t\tconst tail = extra.length > 0 ? ' ' + pc.dim(extra.join(' ')) : '';\n\t\tlines.push(` ${f.name.padEnd(nameWidth)} ${f.type.padEnd(typeWidth)} ${required}${tail}`);\n\t}\n\tp.log.message(lines.join('\\n'));\n}\n\nfunction renderLayout(layout: FormLayout): void {\n\tp.log.message(renderGrid(layout));\n}\n\nexport interface RunSchemaStageOptions {\n\tprompt: string;\n\tuseCase: AiUseCase;\n}\n\nexport interface RunSchemaStageResult {\n\tmodel: CollectionSpec;\n\tworkspaceRootDir: string;\n}\n\nexport async function runSchemaStage(\n\topts: RunSchemaStageOptions\n): Promise<RunSchemaStageResult | null> {\n\tconst { workspaceRootDir } = await getWorkspace();\n\tconst existingModels = await loadExistingModels(workspaceRootDir);\n\n\tconst initialPrompt = `${USE_CASE_HINT[opts.useCase]}\\n\\nDescribe and design a model for: ${opts.prompt}`;\n\n\tconst model = await aiLoop<CollectionSpec>({\n\t\tinitialPrompt,\n\t\tstageLabel: 'Designing schema',\n\t\trefinePlaceholder: 'e.g. \"make role required and add a hire_date field\"',\n\t\tcall: ({ prompt, history }) =>\n\t\t\taiSchema(workspaceRootDir, {\n\t\t\t\tprompt,\n\t\t\t\thistory,\n\t\t\t\tcontext: { existingModels }\n\t\t\t}),\n\t\trenderPreview: renderModel\n\t});\n\n\tif (!model) return null;\n\treturn { model, workspaceRootDir };\n}\n\nexport async function runLayoutStage(\n\tworkspaceRootDir: string,\n\tmodel: CollectionSpec\n): Promise<FormLayout | null> {\n\treturn aiLoop<FormLayout>({\n\t\tinitialPrompt: '',\n\t\tstageLabel: 'Designing layout',\n\t\trefinePlaceholder: 'e.g. \"single column on mobile\" or \"group address fields\"',\n\t\tcall: ({ prompt, history }) =>\n\t\t\taiForm(workspaceRootDir, {\n\t\t\t\tprompt: prompt || undefined,\n\t\t\t\thistory,\n\t\t\t\tcontext: { model }\n\t\t\t}),\n\t\trenderPreview: renderLayout\n\t});\n}\n\nexport function specToArgv(spec: CollectionSpec): string[] {\n\treturn collectionSpecToArgv(spec);\n}\n\n/**\n * Persist the chosen layout as a sidecar file at\n * `data/ai-form-layouts/<model>.json`. Returns the relative path.\n */\nexport function writeLayoutSidecar(\n\tworkspaceRootDir: string,\n\tmodelName: string,\n\tlayout: FormLayout\n): string {\n\tconst dir = path.join(workspaceRootDir, 'data', 'ai-form-layouts');\n\tfs.mkdirSync(dir, { recursive: true });\n\tconst file = path.join(dir, `${modelName}.json`);\n\tfs.writeFileSync(file, JSON.stringify(layout, null, 2) + '\\n');\n\treturn path.relative(workspaceRootDir, file);\n}\n", "import fs from 'node:fs';\nimport os from 'node:os';\nimport path from 'node:path';\n\nexport interface VelaConfig {\n\tapiKey?: string;\n}\n\nconst CONFIG_DIR = path.join(os.homedir(), '.vela');\nconst CONFIG_PATH = path.join(CONFIG_DIR, 'config.json');\n\nexport function readConfig(): VelaConfig | null {\n\tif (!fs.existsSync(CONFIG_PATH)) return null;\n\ttry {\n\t\treturn JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf8')) as VelaConfig;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nexport function writeConfig(config: VelaConfig): void {\n\tfs.mkdirSync(CONFIG_DIR, { recursive: true });\n\tfs.writeFileSync(CONFIG_PATH, JSON.stringify(config, null, 2));\n}\n\nexport function clearConfig(): void {\n\tif (fs.existsSync(CONFIG_PATH)) fs.unlinkSync(CONFIG_PATH);\n}\n\nexport function requireApiKey(): string {\n\tconst config = readConfig();\n\tif (!config?.apiKey) {\n\t\tthrow new Error('Not logged in. Run `vela login` to login.');\n\t}\n\treturn config.apiKey;\n}\n", "import fs from 'node:fs';\nimport path from 'node:path';\n\nexport interface ProjectConfig {\n\tprojectId: string;\n\tteamId: string;\n\tprojectName: string;\n}\n\nexport function projectConfigPath(workspaceRootDir: string): string {\n\treturn path.join(workspaceRootDir, '.vela', 'project.json');\n}\n\nexport function readProjectConfig(workspaceRootDir: string): ProjectConfig | null {\n\tconst file = projectConfigPath(workspaceRootDir);\n\tif (!fs.existsSync(file)) return null;\n\ttry {\n\t\tconst parsed = JSON.parse(fs.readFileSync(file, 'utf8')) as Partial<ProjectConfig>;\n\t\tif (\n\t\t\ttypeof parsed.projectId !== 'string' ||\n\t\t\ttypeof parsed.teamId !== 'string' ||\n\t\t\ttypeof parsed.projectName !== 'string'\n\t\t) {\n\t\t\treturn null;\n\t\t}\n\t\treturn {\n\t\t\tprojectId: parsed.projectId,\n\t\t\tteamId: parsed.teamId,\n\t\t\tprojectName: parsed.projectName\n\t\t};\n\t} catch {\n\t\treturn null;\n\t}\n}\n\n/**\n * Record the velastack.dev link, keeping everything else in the file.\n *\n * `.vela/project.json` is written by two modules: this one for the link, and\n * `deploy-config.ts` for the app id and target bindings. Replacing the file\n * wholesale here would drop the app id \u2014 which server paths, systemd units and\n * databases all hang off \u2014 and strand the deployment on the server.\n */\nexport function writeProjectConfig(workspaceRootDir: string, config: ProjectConfig): void {\n\tconst file = projectConfigPath(workspaceRootDir);\n\tfs.mkdirSync(path.dirname(file), { recursive: true });\n\n\tlet existing: Record<string, unknown> = {};\n\tif (fs.existsSync(file)) {\n\t\ttry {\n\t\t\texisting = JSON.parse(fs.readFileSync(file, 'utf8')) as Record<string, unknown>;\n\t\t} catch {\n\t\t\t// A corrupt file is replaced rather than merged into.\n\t\t}\n\t}\n\n\tfs.writeFileSync(file, JSON.stringify({ ...existing, ...config }, null, 2) + '\\n');\n}\n", "import { API_URL } from './constants.ts';\nimport { requireApiKey } from './config.ts';\nimport { readProjectConfig } from './project-config.ts';\n\nexport interface AiTurn {\n\trole: 'user' | 'assistant';\n\tcontent: string;\n}\n\nexport interface CollectionFieldSpec {\n\tname: string;\n\ttype: string;\n\trequired?: boolean;\n\tvalues?: string[];\n\tcollectionName?: string;\n\tmaxSelect?: number;\n\tmin?: number;\n\tmax?: number;\n}\n\nexport interface CollectionSpec {\n\tname: string;\n\ttype: string;\n\tfields: CollectionFieldSpec[];\n}\n\nexport interface FormLayoutCol {\n\tspan: 1 | 2 | 3 | 4 | 6 | 12;\n\tfield: string;\n}\n\nexport interface FormLayoutRow {\n\tcols: FormLayoutCol[];\n}\n\nexport interface FormLayout {\n\trows: FormLayoutRow[];\n}\n\nexport interface AiResult<T> {\n\tresult: T;\n\tturn: AiTurn[];\n}\n\ninterface AiSchemaRequest {\n\tprompt: string;\n\thistory?: AiTurn[];\n\tcontext?: { existingModels?: CollectionSpec[] };\n}\n\ninterface AiFormRequest {\n\tprompt?: string;\n\thistory?: AiTurn[];\n\tcontext: { model: CollectionSpec };\n}\n\nasync function aiPost<T>(\n\tworkspaceRootDir: string,\n\tendpoint: 'schema' | 'form',\n\tbody: AiSchemaRequest | AiFormRequest\n): Promise<AiResult<T>> {\n\tconst apiKey = requireApiKey();\n\tconst project = readProjectConfig(workspaceRootDir);\n\tif (!project) {\n\t\tthrow new Error(\n\t\t\t\"This isn't a velastack project (no .vela/project.json). Run `vela create` first.\"\n\t\t);\n\t}\n\n\tconst res = await fetch(`${API_URL}/v1/projects/${project.projectId}/ai/${endpoint}`, {\n\t\tmethod: 'POST',\n\t\theaders: {\n\t\t\t'Content-Type': 'application/json',\n\t\t\tAuthorization: `Bearer ${apiKey}`\n\t\t},\n\t\tbody: JSON.stringify(body)\n\t});\n\n\tif (res.status === 401 || res.status === 403) {\n\t\tthrow new Error('API key invalid \u2014 run `vela login`');\n\t}\n\tif (res.status === 502) {\n\t\tconst msg = await res.text().catch(() => '');\n\t\tthrow new Error(`AI request failed: ${msg || 'upstream error'}`);\n\t}\n\tif (!res.ok) {\n\t\tconst msg = await res.text().catch(() => '');\n\t\tthrow new Error(`Velastack API error (${res.status}): ${msg || res.statusText}`);\n\t}\n\treturn (await res.json()) as AiResult<T>;\n}\n\nexport const aiSchema = (workspaceRootDir: string, body: AiSchemaRequest) =>\n\taiPost<CollectionSpec>(workspaceRootDir, 'schema', body);\n\nexport const aiForm = (workspaceRootDir: string, body: AiFormRequest) =>\n\taiPost<FormLayout>(workspaceRootDir, 'form', body);\n", "import * as p from '@clack/prompts';\nimport type { AiTurn } from './ai-client.ts';\n\nexport interface AiLoopCallContext {\n\tprompt: string;\n\thistory: AiTurn[];\n}\n\nexport interface AiLoopCallResult<T> {\n\tresult: T;\n\tturn: AiTurn[];\n}\n\nexport interface AiLoopOptions<T> {\n\tinitialPrompt: string;\n\tstageLabel: string;\n\trefinePlaceholder: string;\n\tcall: (ctx: AiLoopCallContext) => Promise<AiLoopCallResult<T>>;\n\trenderPreview: (result: T) => void;\n}\n\n/**\n * Run a preview-and-refine loop. Calls `call` with the current prompt + history,\n * renders the preview, then asks the user to refine (non-empty input) or apply\n * (empty input). Cancel exits the loop with `null`.\n */\nexport async function aiLoop<T>(opts: AiLoopOptions<T>): Promise<T | null> {\n\tlet prompt = opts.initialPrompt;\n\tlet history: AiTurn[] = [];\n\tlet attempt = 0;\n\n\twhile (true) {\n\t\tattempt++;\n\t\tconst spinner = p.spinner();\n\t\tspinner.start(`${opts.stageLabel} (${attempt > 1 ? 'iteration ' + attempt : 'first pass'})\u2026`);\n\t\tlet result: T;\n\t\tlet turn: AiTurn[];\n\t\ttry {\n\t\t\tconst out = await opts.call({ prompt, history });\n\t\t\tresult = out.result;\n\t\t\tturn = out.turn;\n\t\t\tspinner.stop(`${opts.stageLabel} ready.`);\n\t\t} catch (e) {\n\t\t\tspinner.stop(`${opts.stageLabel} failed.`);\n\t\t\tthrow e;\n\t\t}\n\n\t\topts.renderPreview(result);\n\n\t\tconst next = await p.text({\n\t\t\tmessage: 'Refine the result, or press Enter to apply.',\n\t\t\tplaceholder: opts.refinePlaceholder,\n\t\t\tdefaultValue: ''\n\t\t});\n\n\t\tif (p.isCancel(next)) return null;\n\t\tconst trimmed = (typeof next === 'string' ? next : '').trim();\n\t\tif (trimmed === '') return result;\n\n\t\thistory = turn;\n\t\tprompt = trimmed;\n\t}\n}\n", "import * as p from '@clack/prompts';\nimport { withPocketbase } from './pocketbase.ts';\nimport type { CollectionFieldSpec, CollectionSpec } from './ai-client.ts';\n\ninterface PbField {\n\tname: string;\n\ttype: string;\n\tsystem?: boolean;\n\trequired?: boolean;\n\tvalues?: string[];\n\tcollectionId?: string;\n\tmaxSelect?: number;\n\tmin?: number;\n\tmax?: number;\n}\n\ninterface PbCollection {\n\tid: string;\n\tname: string;\n\ttype: string;\n\tsystem?: boolean;\n\tfields: PbField[];\n}\n\n/**\n * Load existing user-defined collections from the project's PocketBase.\n * Returns [] (with a warning) if PocketBase is unreachable.\n */\nexport async function loadExistingModels(workspaceRootDir: string): Promise<CollectionSpec[]> {\n\tlet result: CollectionSpec[] = [];\n\ttry {\n\t\tawait withPocketbase(workspaceRootDir, async (pb) => {\n\t\t\tconst all = (await pb.collections.getFullList()) as unknown as PbCollection[];\n\t\t\tconst userCollections = all.filter((c) => !c.system);\n\t\t\tconst byId = new Map(userCollections.map((c) => [c.id, c.name]));\n\t\t\tresult = userCollections.map((c) => ({\n\t\t\t\tname: c.name,\n\t\t\t\ttype: c.type,\n\t\t\t\tfields: c.fields\n\t\t\t\t\t.filter((f) => !f.system)\n\t\t\t\t\t.map<CollectionFieldSpec>((f) => ({\n\t\t\t\t\t\tname: f.name,\n\t\t\t\t\t\ttype: f.type,\n\t\t\t\t\t\trequired: f.required,\n\t\t\t\t\t\tvalues: f.values,\n\t\t\t\t\t\tcollectionName: f.collectionId ? byId.get(f.collectionId) : undefined,\n\t\t\t\t\t\tmaxSelect: f.maxSelect,\n\t\t\t\t\t\tmin: f.min,\n\t\t\t\t\t\tmax: f.max\n\t\t\t\t\t}))\n\t\t\t}));\n\t\t});\n\t} catch (e) {\n\t\tconst msg = e instanceof Error ? e.message : String(e);\n\t\tp.log.warn(\n\t\t\t`Could not load existing schema from PocketBase (${msg}). The AI agent will design without that context.`\n\t\t);\n\t\treturn [];\n\t}\n\treturn result;\n}\n", "import * as p from '@clack/prompts';\nimport type { CollectionFieldSpec, CollectionSpec } from './ai-client.ts';\n\nconst PRIMITIVE_TYPES = new Set(['text', 'number', 'bool', 'email', 'date', 'url', 'file']);\n\nfunction singularize(name: string): string {\n\tif (name.endsWith('ies') && name.length > 3) return `${name.slice(0, -3)}y`;\n\tif (name.endsWith('s') && !name.endsWith('ss')) return name.slice(0, -1);\n\treturn name;\n}\n\nfunction typeArg(field: CollectionFieldSpec): string | null {\n\tif (field.type === 'select' && field.values && field.values.length > 0) {\n\t\treturn `select(${field.values.join(',')})`;\n\t}\n\tif (field.type === 'relation') {\n\t\tif (!field.collectionName) return null;\n\t\treturn singularize(field.collectionName);\n\t}\n\tif (PRIMITIVE_TYPES.has(field.type)) return field.type;\n\treturn null;\n}\n\n/**\n * Convert a CollectionSpec to argv for the patterns package.\n * Drops + warns on fields that can't be expressed cleanly.\n */\nexport function collectionSpecToArgv(spec: CollectionSpec): string[] {\n\tconst argv: string[] = [spec.name];\n\tfor (const field of spec.fields) {\n\t\tconst type = typeArg(field);\n\t\tif (type === null) {\n\t\t\tp.log.warn(\n\t\t\t\t`Skipping field \"${field.name}\" (type \"${field.type}\" cannot be represented as a pattern argument)`\n\t\t\t);\n\t\t\tcontinue;\n\t\t}\n\t\tconst required = field.required ? '!' : '';\n\t\targv.push(`${field.name}:${type}${required}`);\n\t}\n\treturn argv;\n}\n", "import type { FormLayout } from './ai-client.ts';\n\nconst TOTAL_COLS = 12;\nconst MIN_TERM_WIDTH = 60;\n\nfunction pad(s: string, width: number): string {\n\tif (s.length >= width) return s.slice(0, width);\n\treturn s + ' '.repeat(width - s.length);\n}\n\nfunction colWidths(layout: FormLayout, terminalWidth: number): number[][] {\n\tconst innerWidth = Math.max(MIN_TERM_WIDTH, terminalWidth) - 2;\n\treturn layout.rows.map((row) => {\n\t\tconst cellWidths: number[] = [];\n\t\tlet used = 0;\n\t\tfor (let i = 0; i < row.cols.length; i++) {\n\t\t\tconst col = row.cols[i]!;\n\t\t\tconst isLast = i === row.cols.length - 1;\n\t\t\tconst target = Math.round((innerWidth * col.span) / TOTAL_COLS);\n\t\t\tconst w = isLast ? innerWidth - used : Math.max(target, col.field.length + 2);\n\t\t\tcellWidths.push(w);\n\t\t\tused += w;\n\t\t}\n\t\treturn cellWidths;\n\t});\n}\n\n/**\n * Render a FormLayout as an ASCII grid. Falls back to a list view when\n * the terminal is narrower than MIN_TERM_WIDTH.\n */\nexport function renderGrid(\n\tlayout: FormLayout,\n\tterminalWidth = process.stdout.columns ?? 80\n): string {\n\tif (terminalWidth < MIN_TERM_WIDTH) {\n\t\treturn layout.rows\n\t\t\t.map((row, i) => `row ${i + 1}: ${row.cols.map((c) => `${c.field}(${c.span})`).join(' | ')}`)\n\t\t\t.join('\\n');\n\t}\n\n\tconst widths = colWidths(layout, terminalWidth);\n\tconst lines: string[] = [];\n\n\tfor (let r = 0; r < layout.rows.length; r++) {\n\t\tconst row = layout.rows[r]!;\n\t\tconst w = widths[r]!;\n\n\t\tconst top = r === 0 ? '\u250C' + w.map((width) => '\u2500'.repeat(width)).join('\u252C') + '\u2510' : '';\n\t\tif (top) lines.push(top);\n\n\t\tconst content = '\u2502' + row.cols.map((c, i) => ' ' + pad(c.field, w[i]! - 1)).join('\u2502') + '\u2502';\n\t\tlines.push(content);\n\n\t\tconst isLast = r === layout.rows.length - 1;\n\t\tif (isLast) {\n\t\t\tlines.push('\u2514' + w.map((width) => '\u2500'.repeat(width)).join('\u2534') + '\u2518');\n\t\t} else {\n\t\t\tconst nextW = widths[r + 1]!;\n\t\t\tlines.push(buildSeparator(w, nextW));\n\t\t}\n\t}\n\n\treturn lines.join('\\n');\n}\n\nfunction buildSeparator(curr: number[], next: number[]): string {\n\tconst currBoundaries = new Set<number>();\n\tlet pos = 0;\n\tfor (let i = 0; i < curr.length - 1; i++) {\n\t\tpos += curr[i]!;\n\t\tcurrBoundaries.add(pos);\n\t}\n\n\tconst nextBoundaries = new Set<number>();\n\tpos = 0;\n\tfor (let i = 0; i < next.length - 1; i++) {\n\t\tpos += next[i]!;\n\t\tnextBoundaries.add(pos);\n\t}\n\n\tconst total = curr.reduce((a, b) => a + b, 0);\n\tlet line = '\u251C';\n\tfor (let i = 0; i < total; i++) {\n\t\tconst inCurr = currBoundaries.has(i);\n\t\tconst inNext = nextBoundaries.has(i);\n\t\tif (inCurr && inNext) line += '\u253C';\n\t\telse if (inCurr) line += '\u2534';\n\t\telse if (inNext) line += '\u252C';\n\t\telse line += '\u2500';\n\t}\n\tline += '\u2524';\n\treturn line;\n}\n", "import { Command } from 'commander';\nimport * as p from '@clack/prompts';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand } from '../../lib/run.ts';\nimport { runPattern } from '../../lib/pattern-runner.ts';\nimport { runSchemaStage, specToArgv } from '../../lib/ai-flow.ts';\n\nexport const schema = new Command('schema')\n\t.description('generate a schema from a model')\n\t.argument('[model]', 'model name')\n\t.argument('[fields...]', 'field definitions')\n\t.option('--ai <description>', 'design the schema with AI from a natural-language description')\n\t.allowUnknownOption(true)\n\t.configureHelp(helpConfig)\n\t.action((model: string | undefined, fields: string[], options: { ai?: string }) =>\n\t\trunCommand(async () => {\n\t\t\tlet argv: string[];\n\t\t\tlet modelName: string;\n\n\t\t\tif (options.ai) {\n\t\t\t\tif (model) {\n\t\t\t\t\tthrow new Error('Pass either a model name or --ai, not both.');\n\t\t\t\t}\n\t\t\t\tconst stage = await runSchemaStage({ prompt: options.ai, useCase: 'schema' });\n\t\t\t\tif (!stage) {\n\t\t\t\t\tp.cancel('Aborted before any files were written.');\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\targv = specToArgv(stage.model);\n\t\t\t\tmodelName = stage.model.name;\n\t\t\t} else {\n\t\t\t\tif (!model) {\n\t\t\t\t\tthrow new Error('Missing required argument: model. Pass a model name or use --ai.');\n\t\t\t\t}\n\t\t\t\targv = [model, ...fields];\n\t\t\t\tmodelName = model;\n\t\t\t}\n\n\t\t\tawait runPattern(\n\t\t\t\t'generate-schema',\n\t\t\t\targv,\n\t\t\t\t{},\n\t\t\t\t{\n\t\t\t\t\tsummary: `Created ${modelName} schema.`,\n\t\t\t\t\tnextSteps: [\n\t\t\t\t\t\t`Edit field types and validation in src/lib/schemas/${modelName}.ts.`,\n\t\t\t\t\t\t`Run \\`vela generate form ${modelName}\\` to add a form for this schema.`\n\t\t\t\t\t],\n\t\t\t\t\ttask: {\n\t\t\t\t\t\ttitle: 'Generating schema',\n\t\t\t\t\t\tsuccess: 'Generated schema',\n\t\t\t\t\t\terror: 'Failed to generate schema'\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t);\n\t\t}, 'Failed to generate schema.')\n\t);\n", "import { Command } from 'commander';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand } from '../../lib/run.ts';\nimport { runPattern } from '../../lib/pattern-runner.ts';\n\nexport const resource = new Command('resource')\n\t.description('generate a resource (model + CRUD pages)')\n\t.argument('<model>', 'model name')\n\t.argument('[fields...]', 'field definitions')\n\t.allowUnknownOption(true)\n\t.configureHelp(helpConfig)\n\t.action((model: string, fields: string[]) =>\n\t\trunCommand(\n\t\t\t() =>\n\t\t\t\trunPattern(\n\t\t\t\t\t'generate-resource',\n\t\t\t\t\t[model, ...fields],\n\t\t\t\t\t{},\n\t\t\t\t\t{\n\t\t\t\t\t\tsummary: `Created ${model} resource.`,\n\t\t\t\t\t\tnextSteps: [\n\t\t\t\t\t\t\t`Run \\`vela fixtures generate\\` to create some ${model} records for development.`,\n\t\t\t\t\t\t\t`Run \\`vela dev\\` and visit /${model} to see the CRUD pages.`,\n\t\t\t\t\t\t\t`Customize the UI in src/routes/${model}/+page.svelte.`\n\t\t\t\t\t\t],\n\t\t\t\t\t\ttask: {\n\t\t\t\t\t\t\ttitle: 'Generating resource',\n\t\t\t\t\t\t\tsuccess: 'Generated resource',\n\t\t\t\t\t\t\terror: 'Failed to generate resource'\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t),\n\t\t\t'Failed to generate resource.'\n\t\t)\n\t);\n", "import { Command } from 'commander';\nimport * as p from '@clack/prompts';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand } from '../../lib/run.ts';\nimport { runPattern } from '../../lib/pattern-runner.ts';\nimport {\n\trunSchemaStage,\n\trunLayoutStage,\n\tspecToArgv,\n\twriteLayoutSidecar\n} from '../../lib/ai-flow.ts';\n\nexport const scaffold = new Command('scaffold')\n\t.description('generate a full CRUD scaffold (model, forms, list, detail)')\n\t.argument('[model]', 'model name')\n\t.argument('[fields...]', 'field definitions')\n\t.option('--remote', 'generate a scaffold backed by a remote PocketBase collection')\n\t.option(\n\t\t'--route <route>',\n\t\t'place the scaffold at a custom route (e.g. \"(app)/[team_id]/projects\"). Defaults to the pluralized model name under (app)/(public).'\n\t)\n\t.option(\n\t\t'--ai <description>',\n\t\t'design the scaffold with AI from a natural-language description (two stages: schema \u2192 layout)'\n\t)\n\t.allowUnknownOption(true)\n\t.configureHelp(helpConfig)\n\t.action(\n\t\t(\n\t\t\tmodel: string | undefined,\n\t\t\tfields: string[],\n\t\t\toptions: { remote?: boolean; route?: string; ai?: string }\n\t\t) =>\n\t\t\trunCommand(async () => {\n\t\t\t\tlet argv: string[];\n\t\t\t\tlet modelName: string;\n\t\t\t\tlet sidecarPath: string | null = null;\n\n\t\t\t\tif (options.ai) {\n\t\t\t\t\tif (model) {\n\t\t\t\t\t\tthrow new Error('Pass either a model name or --ai, not both.');\n\t\t\t\t\t}\n\t\t\t\t\tconst stage = await runSchemaStage({ prompt: options.ai, useCase: 'scaffold' });\n\t\t\t\t\tif (!stage) {\n\t\t\t\t\t\tp.cancel('Aborted before any files were written.');\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tconst layout = await runLayoutStage(stage.workspaceRootDir, stage.model);\n\t\t\t\t\tif (!layout) {\n\t\t\t\t\t\tp.cancel('Aborted before any files were written.');\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\targv = specToArgv(stage.model);\n\t\t\t\t\tmodelName = stage.model.name;\n\t\t\t\t\tsidecarPath = writeLayoutSidecar(stage.workspaceRootDir, modelName, layout);\n\t\t\t\t} else {\n\t\t\t\t\tif (!model) {\n\t\t\t\t\t\tthrow new Error('Missing required argument: model. Pass a model name or use --ai.');\n\t\t\t\t\t}\n\t\t\t\t\targv = [model, ...fields];\n\t\t\t\t\tmodelName = model;\n\t\t\t\t}\n\n\t\t\t\tconst slug = options.remote ? 'generate-scaffold-remote' : 'generate-scaffold';\n\t\t\t\tconst nextSteps: string[] = [\n\t\t\t\t\t`Run \\`vela fixtures generate\\` to create 10 ${modelName} records for development.`,\n\t\t\t\t\t'Run `vela dev` and visit the generated route to use the scaffold.',\n\t\t\t\t\t'Tweak list columns and detail layout in the generated +page.svelte files.'\n\t\t\t\t];\n\t\t\t\tif (sidecarPath) {\n\t\t\t\t\tnextSteps.unshift(\n\t\t\t\t\t\t`Apply the AI-designed form layout from ${sidecarPath} to the generated new/edit +page.svelte files.`\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tawait runPattern(\n\t\t\t\t\tslug,\n\t\t\t\t\targv,\n\t\t\t\t\t{ route: options.route },\n\t\t\t\t\t{\n\t\t\t\t\t\tsummary: `Created ${modelName} scaffold.`,\n\t\t\t\t\t\tnextSteps,\n\t\t\t\t\t\ttask: {\n\t\t\t\t\t\t\ttitle: 'Generating scaffold',\n\t\t\t\t\t\t\tsuccess: 'Generated scaffold',\n\t\t\t\t\t\t\terror: 'Failed to generate scaffold'\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t);\n\t\t\t}, 'Failed to generate scaffold.')\n\t);\n", "import { Command } from 'commander';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand } from '../../lib/run.ts';\nimport { runPattern } from '../../lib/pattern-runner.ts';\n\nexport const migration = new Command('migration')\n\t.description('generate a migration for an existing collection')\n\t.argument('<collection>', 'collection name')\n\t.argument('<op>', 'operation (add, remove, rename, references)')\n\t.argument('[args...]', 'operation arguments (e.g. \"birthday:date\")')\n\t.allowUnknownOption(true)\n\t.configureHelp(helpConfig)\n\t.action((collection: string, op: string, args: string[]) =>\n\t\trunCommand(\n\t\t\t() =>\n\t\t\t\trunPattern(\n\t\t\t\t\t'generate-migration',\n\t\t\t\t\t[collection, op, ...args],\n\t\t\t\t\t{},\n\t\t\t\t\t{\n\t\t\t\t\t\tsummary: `Created ${op} migration for ${collection}.`,\n\t\t\t\t\t\tnextSteps: [\n\t\t\t\t\t\t\t'Review the generated migration file in migrations/.',\n\t\t\t\t\t\t\t'Run `vela migrate up` to apply the migration.'\n\t\t\t\t\t\t],\n\t\t\t\t\t\ttask: {\n\t\t\t\t\t\t\ttitle: 'Generating migration',\n\t\t\t\t\t\t\tsuccess: 'Generated migration',\n\t\t\t\t\t\t\terror: 'Failed to generate migration'\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t),\n\t\t\t'Failed to generate migration.'\n\t\t)\n\t);\n", "import { Command } from 'commander';\nimport { helpConfig } from '../lib/help.ts';\nimport { auth } from './enable/auth.ts';\nimport { api } from './enable/api.ts';\nimport { apiKeys } from './enable/api-keys.ts';\nimport { backend } from './enable/backend.ts';\nimport { i18n } from './enable/i18n.ts';\nimport { teams } from './enable/teams.ts';\nimport { payments } from './enable/payments.ts';\nimport { subscriptions } from './enable/subscriptions.ts';\nimport { s3 } from './enable/s3.ts';\nimport { smtp } from './enable/smtp.ts';\nimport { cms } from './enable/cms.ts';\nimport { blog } from './enable/blog.ts';\nimport { contentNegotiation } from './enable/content-negotiation.ts';\n\nexport const enable = new Command('enable')\n\t.description('enable features')\n\t.configureHelp(helpConfig)\n\t.addCommand(auth)\n\t.addCommand(api)\n\t.addCommand(apiKeys)\n\t.addCommand(backend)\n\t.addCommand(contentNegotiation)\n\t.addCommand(i18n)\n\t.addCommand(teams)\n\t.addCommand(payments)\n\t.addCommand(subscriptions)\n\t.addCommand(s3)\n\t.addCommand(smtp)\n\t.addCommand(cms)\n\t.addCommand(blog);\n", "import { Command } from 'commander';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand } from '../../lib/run.ts';\nimport { runPattern } from '../../lib/pattern-runner.ts';\n\nexport const auth = new Command('auth')\n\t.description('enable authentication (email/password + OAuth scaffold)')\n\t.allowUnknownOption(true)\n\t.configureHelp(helpConfig)\n\t.action((_opts, cmd) =>\n\t\trunCommand(\n\t\t\t() =>\n\t\t\t\trunPattern(\n\t\t\t\t\t'enable-auth',\n\t\t\t\t\tcmd.args,\n\t\t\t\t\t{},\n\t\t\t\t\t{\n\t\t\t\t\t\tsummary: 'Enabled authentication.',\n\t\t\t\t\t\tnextSteps: [\n\t\t\t\t\t\t\t'Run `vela dev` and visit /login to try the new sign-in flow.',\n\t\t\t\t\t\t\t'Customize sign-in copy and providers in src/routes/(public)/(auth)/.',\n\t\t\t\t\t\t\t'Add OAuth providers via `vela oauth` (coming soon) or in the PocketBase admin UI.'\n\t\t\t\t\t\t],\n\t\t\t\t\t\ttask: {\n\t\t\t\t\t\t\ttitle: 'Enabling auth',\n\t\t\t\t\t\t\tsuccess: 'Enabled auth',\n\t\t\t\t\t\t\terror: 'Failed to enable auth'\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t),\n\t\t\t'Failed to enable auth.'\n\t\t)\n\t);\n", "import { Command } from 'commander';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand } from '../../lib/run.ts';\nimport { runPattern } from '../../lib/pattern-runner.ts';\n\nexport const api = new Command('api')\n\t.description('enable the PocketBase REST API')\n\t.allowUnknownOption(true)\n\t.configureHelp(helpConfig)\n\t.action((_opts, cmd) =>\n\t\trunCommand(\n\t\t\t() =>\n\t\t\t\trunPattern(\n\t\t\t\t\t'enable-api',\n\t\t\t\t\tcmd.args,\n\t\t\t\t\t{},\n\t\t\t\t\t{\n\t\t\t\t\t\tsummary: 'Enabled the PocketBase REST API.',\n\t\t\t\t\t\tnextSteps: [\n\t\t\t\t\t\t\t'Run `vela dev` to try the API at /api/collections/*.',\n\t\t\t\t\t\t\t'Adjust collection-level rules in the PocketBase admin UI or via migrations.',\n\t\t\t\t\t\t\t'Run `vela enable api-keys` if you want to issue machine-to-machine tokens.'\n\t\t\t\t\t\t],\n\t\t\t\t\t\ttask: {\n\t\t\t\t\t\t\ttitle: 'Enabling api',\n\t\t\t\t\t\t\tsuccess: 'Enabled api',\n\t\t\t\t\t\t\terror: 'Failed to enable api'\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t),\n\t\t\t'Failed to enable API.'\n\t\t)\n\t);\n", "import { Command } from 'commander';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand } from '../../lib/run.ts';\nimport { runPattern } from '../../lib/pattern-runner.ts';\n\nexport const apiKeys = new Command('api-keys')\n\t.description('enable API key management')\n\t.allowUnknownOption(true)\n\t.configureHelp(helpConfig)\n\t.action((_opts, cmd) =>\n\t\trunCommand(\n\t\t\t() =>\n\t\t\t\trunPattern(\n\t\t\t\t\t'enable-api-keys',\n\t\t\t\t\tcmd.args,\n\t\t\t\t\t{},\n\t\t\t\t\t{\n\t\t\t\t\t\tsummary: 'Enabled API key management.',\n\t\t\t\t\t\tnextSteps: [\n\t\t\t\t\t\t\t'Run `vela dev` and visit /account/api-keys to issue your first key.',\n\t\t\t\t\t\t\t'Customize the API key UI in src/routes/(app)/account/api-keys/.',\n\t\t\t\t\t\t\t'Protect API routes by reading `locals.apiKey` in your +server.ts handlers.'\n\t\t\t\t\t\t],\n\t\t\t\t\t\ttask: {\n\t\t\t\t\t\t\ttitle: 'Enabling api keys',\n\t\t\t\t\t\t\tsuccess: 'Enabled api keys',\n\t\t\t\t\t\t\terror: 'Failed to enable api keys'\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t),\n\t\t\t'Failed to enable API keys.'\n\t\t)\n\t);\n", "import { Command } from 'commander';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand } from '../../lib/run.ts';\nimport { runPattern } from '../../lib/pattern-runner.ts';\n\nexport const backend = new Command('backend')\n\t.description('enable the PocketBase backend')\n\t.allowUnknownOption(true)\n\t.configureHelp(helpConfig)\n\t.action((_opts, cmd) =>\n\t\trunCommand(\n\t\t\t() =>\n\t\t\t\trunPattern(\n\t\t\t\t\t'enable-backend',\n\t\t\t\t\tcmd.args,\n\t\t\t\t\t{},\n\t\t\t\t\t{\n\t\t\t\t\t\tsummary: 'Enabled the PocketBase backend.',\n\t\t\t\t\t\tnextSteps: [\n\t\t\t\t\t\t\t'Set POCKETBASE_URL, POCKETBASE_SUPERUSER_EMAIL, and POCKETBASE_SUPERUSER_PASSWORD in your environment.',\n\t\t\t\t\t\t\t'Run `vela dev` to start with PocketBase wired up.',\n\t\t\t\t\t\t\t'Run `vela enable auth` to add user authentication on top of the backend.'\n\t\t\t\t\t\t],\n\t\t\t\t\t\ttask: {\n\t\t\t\t\t\t\ttitle: 'Enabling backend',\n\t\t\t\t\t\t\tsuccess: 'Enabled backend',\n\t\t\t\t\t\t\terror: 'Failed to enable backend'\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t),\n\t\t\t'Failed to enable backend.'\n\t\t)\n\t);\n", "import { Command } from 'commander';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand } from '../../lib/run.ts';\nimport { runPattern } from '../../lib/pattern-runner.ts';\n\nexport const i18n = new Command('i18n')\n\t.description('enable internationalization')\n\t.allowUnknownOption(true)\n\t.configureHelp(helpConfig)\n\t.action((_opts, cmd) =>\n\t\trunCommand(\n\t\t\t() =>\n\t\t\t\trunPattern(\n\t\t\t\t\t'enable-i18n',\n\t\t\t\t\tcmd.args,\n\t\t\t\t\t{},\n\t\t\t\t\t{\n\t\t\t\t\t\tsummary: 'Enabled internationalization.',\n\t\t\t\t\t\tnextSteps: [\n\t\t\t\t\t\t\t'Add or adjust locales in wuchale.config.js.',\n\t\t\t\t\t\t\t'Run `vela i18n extract` to pull translatable strings from your components.',\n\t\t\t\t\t\t\t'Edit the generated .po files under locales/ to add translations.'\n\t\t\t\t\t\t],\n\t\t\t\t\t\ttask: {\n\t\t\t\t\t\t\ttitle: 'Enabling i18n',\n\t\t\t\t\t\t\tsuccess: 'Enabled i18n',\n\t\t\t\t\t\t\terror: 'Failed to enable i18n'\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t),\n\t\t\t'Failed to enable i18n.'\n\t\t)\n\t);\n", "import { Command } from 'commander';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand } from '../../lib/run.ts';\nimport { runPattern } from '../../lib/pattern-runner.ts';\n\nexport const teams = new Command('teams')\n\t.description('enable team / multi-tenant support')\n\t.allowUnknownOption(true)\n\t.configureHelp(helpConfig)\n\t.action((_opts, cmd) =>\n\t\trunCommand(\n\t\t\t() =>\n\t\t\t\trunPattern(\n\t\t\t\t\t'enable-teams',\n\t\t\t\t\tcmd.args,\n\t\t\t\t\t{},\n\t\t\t\t\t{\n\t\t\t\t\t\tsummary: 'Enabled teams.',\n\t\t\t\t\t\tnextSteps: [\n\t\t\t\t\t\t\t'Run `vela dev` and visit /account/teams to create a team and invite members.',\n\t\t\t\t\t\t\t'Scope your queries by `team_id` when reading or writing tenant data.',\n\t\t\t\t\t\t\t'Customize the team settings pages in src/routes/(app)/account/teams/.'\n\t\t\t\t\t\t],\n\t\t\t\t\t\ttask: {\n\t\t\t\t\t\t\ttitle: 'Enabling teams',\n\t\t\t\t\t\t\tsuccess: 'Enabled teams',\n\t\t\t\t\t\t\terror: 'Failed to enable teams'\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t),\n\t\t\t'Failed to enable teams.'\n\t\t)\n\t);\n", "import process from 'node:process';\nimport { Command } from 'commander';\nimport * as p from '@clack/prompts';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand } from '../../lib/run.ts';\nimport { runPattern } from '../../lib/pattern-runner.ts';\n\ntype Provider = 'stripe';\n\nconst PROVIDERS: Array<{ value: Provider; label: string }> = [{ value: 'stripe', label: 'Stripe' }];\n\nexport const payments = new Command('payments')\n\t.description('enable payments')\n\t.option('--provider <provider>', 'payment provider', 'stripe')\n\t.allowUnknownOption(true)\n\t.configureHelp(helpConfig)\n\t.action((opts, cmd) =>\n\t\trunCommand(async () => {\n\t\t\tconst provider = await resolveProvider(opts.provider, cmd.getOptionValueSource('provider'));\n\n\t\t\tconst input = {\n\t\t\t\tprovider,\n\t\t\t\tstripeSecretKey: await ensureKey('STRIPE_SECRET_KEY', 'Stripe secret key (sk_...)'),\n\t\t\t\tstripePublishableKey: await ensureKey(\n\t\t\t\t\t'PUBLIC_STRIPE_PUBLISHABLE_KEY',\n\t\t\t\t\t'Stripe publishable key (pk_...)'\n\t\t\t\t),\n\t\t\t\tstripeWebhookSecret: await ensureWebhookSecret(),\n\t\t\t\tstripePriceId: await ensurePriceId()\n\t\t\t};\n\t\t\tawait runPattern('enable-payments', cmd.args, input, {\n\t\t\t\tsummary: 'Enabled Stripe payments.',\n\t\t\t\tnextSteps: [\n\t\t\t\t\t'Forward Stripe webhooks locally with `stripe listen --forward-to localhost:5173/webhooks/stripe`.',\n\t\t\t\t\t'Run `vela dev` and visit /payment to run through the checkout flow.',\n\t\t\t\t\t'Add products and prices in the Stripe dashboard.'\n\t\t\t\t],\n\t\t\t\ttask: {\n\t\t\t\t\ttitle: 'Enabling payments',\n\t\t\t\t\tsuccess: 'Enabled payments',\n\t\t\t\t\terror: 'Failed to enable payments'\n\t\t\t\t}\n\t\t\t});\n\t\t}, 'Failed to enable payments.')\n\t);\n\nasync function resolveProvider(value: string, source: string | undefined): Promise<Provider> {\n\tif (source && source !== 'default') {\n\t\tif (!PROVIDERS.some((o) => o.value === value)) {\n\t\t\tthrow new Error(`Unknown payment provider: ${value}`);\n\t\t}\n\t\treturn value as Provider;\n\t}\n\n\tconst selected = await p.select<Provider>({\n\t\tmessage: 'Which payment provider?',\n\t\toptions: PROVIDERS,\n\t\tinitialValue: 'stripe'\n\t});\n\tif (p.isCancel(selected)) {\n\t\tp.cancel('Operation cancelled.');\n\t\tprocess.exit(0);\n\t}\n\treturn selected;\n}\n\nasync function ensureWebhookSecret(): Promise<string> {\n\tconst existing = process.env.STRIPE_WEBHOOK_SECRET;\n\tif (existing) return existing;\n\n\tp.note(\n\t\t[\n\t\t\t'Download the Stripe CLI (https://stripe.com/docs/stripe-cli), then run:',\n\t\t\t' stripe listen --forward-to localhost:5173/webhooks/stripe',\n\t\t\t'Copy the whsec_... value it prints and paste it below.'\n\t\t].join('\\n'),\n\t\t'Stripe webhook signing secret',\n\t\t{ format: (line) => line }\n\t);\n\n\treturn promptPassword('Stripe webhook signing secret (whsec_...)');\n}\n\nasync function ensurePriceId(): Promise<string> {\n\tp.note(\n\t\t[\n\t\t\t'Stripe checkout requires a product and price_id.',\n\t\t\t'If you have a demo product price_id, enter it below, or leave blank to create a demo one for you.'\n\t\t].join('\\n'),\n\t\t'Stripe demo product',\n\t\t{ format: (line) => line }\n\t);\n\n\tconst value = await p.text({\n\t\tmessage: 'Stripe price_id (price_...)',\n\t\tplaceholder: 'leave blank to create a demo product'\n\t});\n\tif (p.isCancel(value)) {\n\t\tp.cancel('Operation cancelled.');\n\t\tprocess.exit(0);\n\t}\n\treturn (value ?? '').trim();\n}\n\nasync function ensureKey(envVar: string, message: string): Promise<string> {\n\tconst existing = process.env[envVar];\n\tif (existing) return existing;\n\treturn promptPassword(message);\n}\n\nasync function promptPassword(message: string): Promise<string> {\n\tconst value = await p.password({\n\t\tmessage,\n\t\tvalidate: (v) => (v && v.length ? undefined : 'Required')\n\t});\n\tif (p.isCancel(value)) {\n\t\tp.cancel('Operation cancelled.');\n\t\tprocess.exit(0);\n\t}\n\treturn value;\n}\n", "import { Command } from 'commander';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand } from '../../lib/run.ts';\nimport { runPattern } from '../../lib/pattern-runner.ts';\n\nexport const subscriptions = new Command('subscriptions')\n\t.description('enable Stripe subscriptions (requires auth and payments)')\n\t.allowUnknownOption(true)\n\t.configureHelp(helpConfig)\n\t.action((_opts, cmd) =>\n\t\trunCommand(\n\t\t\t() =>\n\t\t\t\trunPattern(\n\t\t\t\t\t'enable-subscriptions',\n\t\t\t\t\tcmd.args,\n\t\t\t\t\t{},\n\t\t\t\t\t{\n\t\t\t\t\t\tsummary: 'Enabled subscriptions.',\n\t\t\t\t\t\tnextSteps: [\n\t\t\t\t\t\t\t'Create a recurring price in the Stripe dashboard and add its price_id where users can select a plan.',\n\t\t\t\t\t\t\t'Forward webhooks locally with `stripe listen --forward-to localhost:5173/webhooks/stripe`.',\n\t\t\t\t\t\t\t'Run `vela dev` and visit /billing to subscribe, cancel, or resume a plan.'\n\t\t\t\t\t\t],\n\t\t\t\t\t\ttask: {\n\t\t\t\t\t\t\ttitle: 'Enabling subscriptions',\n\t\t\t\t\t\t\tsuccess: 'Enabled subscriptions',\n\t\t\t\t\t\t\terror: 'Failed to enable subscriptions'\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t),\n\t\t\t'Failed to enable subscriptions.'\n\t\t)\n\t);\n", "import process from 'node:process';\nimport { Command } from 'commander';\nimport * as p from '@clack/prompts';\nimport pc from 'picocolors';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand } from '../../lib/run.ts';\nimport { reportResult } from '../../lib/result-report.ts';\nimport { addTargetOptions } from '../../lib/server-command.ts';\nimport { withBackupTarget, type BackupContext } from '../../lib/backup-target.ts';\nimport {\n\tapplyS3,\n\tdefaultForcePathStyle,\n\thasLocalUploads,\n\treadS3,\n\ttype S3Config,\n\ttype S3Filesystem\n} from '../../lib/s3-settings.ts';\nimport { remotePaths } from '../../lib/remote.ts';\n\ninterface Options {\n\tbackups?: boolean;\n\tforce?: boolean;\n\tendpoint?: string;\n\tbucket?: string;\n\tregion?: string;\n\taccessKey?: string;\n\tsecret?: string;\n\tforcePathStyle?: boolean;\n}\n\nexport const s3 = addTargetOptions(\n\tnew Command('s3')\n\t\t.description('enable S3 file storage')\n\t\t.option('--backups', 'configure where backups are kept, not where uploads go')\n\t\t.option('--endpoint <url>', 'S3 endpoint URL')\n\t\t.option('--bucket <name>', 'S3 bucket name')\n\t\t.option('--region <region>', 'S3 region')\n\t\t.option('--access-key <key>', 'S3 access key')\n\t\t.option('--secret <secret>', 'S3 secret key \u2014 prefer VELA_S3_SECRET')\n\t\t.option('--force-path-style', 'address the bucket in the path (MinIO, Ceph)')\n\t\t.option('--no-force-path-style', 'address the bucket as a subdomain (AWS, R2)')\n\t\t.option('--force', 'enable it even though uploads already exist on disk')\n\t\t.configureHelp(helpConfig),\n\t'local'\n).action((raw: unknown) =>\n\trunCommand(() => {\n\t\tconst options = raw as Options;\n\t\tconst filesystem: S3Filesystem = options.backups ? 'backups' : 'storage';\n\n\t\treturn withBackupTarget(raw, 'enable s3', async (ctx) => {\n\t\t\tif (filesystem === 'storage') await guardExistingUploads(ctx, options);\n\n\t\t\tconst existing = await readS3(ctx.pb, filesystem);\n\t\t\tconst config = await promptConfig(options, existing);\n\n\t\t\tawait applyS3(ctx.pb, config, filesystem);\n\n\t\t\t// The old code swallowed this. A wrong path style is exactly what the\n\t\t\t// test reports, so throwing the message away threw away the diagnosis.\n\t\t\tlet failure = '';\n\t\t\ttry {\n\t\t\t\tawait ctx.pb.settings.testS3(filesystem);\n\t\t\t} catch (error) {\n\t\t\t\tfailure = error instanceof Error ? error.message : String(error);\n\t\t\t}\n\n\t\t\tif (failure) {\n\t\t\t\tp.log.warn(\n\t\t\t\t\t`The connection test failed \u2014 the settings are saved but may be wrong.\\n\\n` +\n\t\t\t\t\t\t`${pc.dim(failure)}\\n\\n` +\n\t\t\t\t\t\t`If the bucket is not on AWS or R2, try ${pc.cyan('--force-path-style')}.`\n\t\t\t\t);\n\t\t\t}\n\n\t\t\treportResult({\n\t\t\t\tsummary: failure\n\t\t\t\t\t? `Enabled S3 ${label(filesystem)} on ${ctx.targetName}.`\n\t\t\t\t\t: `Enabled S3 ${label(filesystem)} on ${ctx.targetName} (connection verified).`,\n\t\t\t\tnextSteps:\n\t\t\t\t\tfilesystem === 'backups'\n\t\t\t\t\t\t? [\n\t\t\t\t\t\t\t\t'`vela backup create` now writes archives to the bucket instead of the server.',\n\t\t\t\t\t\t\t\t'Run `vela disable s3 --backups` to keep them on the server again.'\n\t\t\t\t\t\t\t]\n\t\t\t\t\t\t: [\n\t\t\t\t\t\t\t\t'New uploads go to the bucket. Files already on disk are not moved.',\n\t\t\t\t\t\t\t\t'`vela backup create` no longer captures uploads \u2014 PocketBase leaves them out whenever S3 is on. Bucket versioning is what protects them now.',\n\t\t\t\t\t\t\t\t'Run `vela enable s3 --backups` to get backup archives off the server too.',\n\t\t\t\t\t\t\t\t'Run `vela disable s3` to go back to local storage.'\n\t\t\t\t\t\t\t]\n\t\t\t});\n\t\t});\n\t}, 'Failed to enable S3.')\n);\n\nfunction label(filesystem: S3Filesystem): string {\n\treturn filesystem === 'backups' ? 'backup storage' : 'file storage';\n}\n\n/**\n * Refuse to strand files that are already on disk.\n *\n * PocketBase does not migrate anything when the filesystem changes \u2014 it simply\n * starts reading somewhere else \u2014 so every existing upload 404s from the moment\n * this is switched on. The keys are identical on both sides, which makes the fix\n * a plain sync, and that is worth saying rather than leaving to be discovered.\n */\nasync function guardExistingUploads(ctx: BackupContext, options: Options): Promise<void> {\n\tif (options.force) return;\n\tif (!(await hasLocalUploads(ctx.session, ctx.instance, ctx.workspaceRootDir))) return;\n\n\tconst from = ctx.session ? `${remotePaths.storage(ctx.instance)}/` : 'data/storage/';\n\tthrow new Error(\n\t\t`${ctx.targetName} already has uploaded files on disk.\\n\\n` +\n\t\t\t`Turning on S3 changes where PocketBase reads from; it does not move anything,\\n` +\n\t\t\t`so every one of those files would stop resolving.\\n\\n` +\n\t\t\t`The layout is the same on both sides, so copying them across is a plain sync:\\n\\n` +\n\t\t\t` ${pc.cyan(`rclone copy ${from} <remote>:<bucket>/`)}\\n\\n` +\n\t\t\t`Do that first, then re-run with ${pc.cyan('--force')}.`\n\t);\n}\n\nasync function promptConfig(\n\toptions: Options,\n\texisting: { endpoint: string; bucket: string; region: string; accessKey: string }\n): Promise<S3Config> {\n\tconst endpoint =\n\t\toptions.endpoint ??\n\t\t(await text('S3 endpoint URL', existing.endpoint || 'https://s3.amazonaws.com'));\n\tconst bucket = options.bucket ?? (await text('S3 bucket name', existing.bucket));\n\tconst region = options.region ?? (await text('S3 region', existing.region || 'us-east-1'));\n\tconst accessKey = options.accessKey ?? (await text('S3 access key', existing.accessKey));\n\n\t// An access key on the command line is bad enough; a secret there lands in\n\t// shell history and in `ps` for every user on the machine.\n\tconst secret = options.secret ?? process.env.VELA_S3_SECRET ?? (await password('S3 secret key'));\n\n\tconst forcePathStyle =\n\t\toptions.forcePathStyle ??\n\t\t(await confirm(\n\t\t\t'Address the bucket in the path? (MinIO, Ceph and most self-hosted gateways need this)',\n\t\t\tdefaultForcePathStyle(endpoint)\n\t\t));\n\n\treturn { endpoint, bucket, region, accessKey, secret, forcePathStyle };\n}\n\nasync function text(message: string, initialValue = ''): Promise<string> {\n\tconst value = await p.text({\n\t\tmessage,\n\t\tinitialValue,\n\t\tvalidate: (input) => (input?.trim() ? undefined : `${message} is required`)\n\t});\n\tif (p.isCancel(value)) {\n\t\tp.cancel('Operation cancelled.');\n\t\tprocess.exit(0);\n\t}\n\treturn value.trim();\n}\n\nasync function password(message: string): Promise<string> {\n\tconst value = await p.password({\n\t\tmessage,\n\t\tvalidate: (input) => (input ? undefined : `${message} is required`)\n\t});\n\tif (p.isCancel(value)) {\n\t\tp.cancel('Operation cancelled.');\n\t\tprocess.exit(0);\n\t}\n\treturn value;\n}\n\nasync function confirm(message: string, initialValue: boolean): Promise<boolean> {\n\tconst value = await p.confirm({ message, initialValue });\n\tif (p.isCancel(value)) {\n\t\tp.cancel('Operation cancelled.');\n\t\tprocess.exit(0);\n\t}\n\treturn value;\n}\n", "import process from 'node:process';\nimport { Command } from 'commander';\nimport * as v from 'valibot';\nimport * as p from '@clack/prompts';\nimport pc from 'picocolors';\nimport { getWorkspace } from './workspace.ts';\nimport {\n\tloadDeployConfig,\n\treadBinding,\n\tresolveAppIdentity,\n\twriteBinding,\n\ttype TargetBinding,\n\ttype VelaAppConfig\n} from './deploy-config.ts';\nimport { instanceId } from './instance.ts';\nimport { addSshOptions, SSH_OPTION_SCHEMA, sshOptionsFrom } from './ssh-options.ts';\nimport { parseOptions } from './options.ts';\nimport { withSsh, type SshSession } from './ssh.ts';\nimport { requireProvisioned, syncServerScripts } from './remote.ts';\nimport { restartInstance, touchesSuperuser } from './remote-env.ts';\nimport {\n\tdescribeTarget,\n\tparseTarget,\n\ttype RemoteTarget,\n\ttype Target,\n\ttype TargetFallback\n} from './target.ts';\n\nexport const SERVER_OPTIONS_SCHEMA = {\n\t...SSH_OPTION_SCHEMA,\n\ttarget: v.optional(v.string()),\n\tserver: v.optional(v.string())\n};\n\nconst OptionsSchema = v.object(SERVER_OPTIONS_SCHEMA);\n\n/**\n * The one selector.\n *\n * `fallback` is registered as commander's default so `--help` states what the\n * command means with no `-t`, rather than leaving it to prose.\n */\nexport function addTargetOptions(command: Command, fallback: TargetFallback): Command {\n\treturn addSshOptions(command)\n\t\t.option('-t, --target <target>', 'which copy of the app to act on', fallback)\n\t\t.option('--server <ssh>', 'server this target runs on \u2014 recorded on first use');\n}\n\ninterface BaseContext {\n\tworkspaceRootDir: string;\n\tappName: string;\n\tappId: string;\n\tconfig: VelaAppConfig;\n}\n\nexport interface LocalContext extends BaseContext {\n\tkind: 'local';\n\t/** Always the workspace root's, never the cwd's. */\n\tenvFile: string;\n}\n\nexport interface ServerContext extends BaseContext {\n\tkind: 'remote';\n\tsession: SshSession;\n\tinstance: string;\n\tenvTag: string;\n\t/** The target as the user named it, for output. */\n\ttargetName: string;\n\t/** SSH destination behind that target. */\n\tserver: string;\n\tbinding: TargetBinding;\n}\n\nexport interface TargetHandlers {\n\tlocal?: (ctx: LocalContext) => Promise<void>;\n\tremote?: (ctx: ServerContext) => Promise<void>;\n}\n\nexport interface TargetRunOptions {\n\t/** `--project`, forwarded to identity resolution. */\n\tproject?: string;\n\t/** Ask for a domain when binding. Only `deploy` acts on one. */\n\taskDomain?: boolean;\n\t/** Command name for errors, e.g. `env set`. */\n\tlabel?: string;\n\t/** What to point at instead when there is no local mode. */\n\tlocalHint?: string;\n}\n\n/**\n * Run a command against whichever copy of the app `-t` names.\n *\n * A command declares what it supports by which handlers it passes, so the\n * declaration *is* the branch: a remote-only command writes one handler and gets\n * a good error for `-t local` for free, and `ctx.session` exists only inside the\n * remote handler, so a local path cannot reach SSH even by accident.\n */\nexport async function withTarget(\n\traw: unknown,\n\thandlers: TargetHandlers,\n\trun: TargetRunOptions = {}\n): Promise<void> {\n\tconst options = parseOptions(OptionsSchema, raw);\n\tconst target = parseTarget(options.target, 'production');\n\tconst label = run.label ? `vela ${run.label}` : 'this command';\n\n\tif (target.kind === 'preview') {\n\t\tthrow new Error(\n\t\t\t`Preview targets are not supported yet.\\n\\n` +\n\t\t\t\t`\\`${describeTarget(target)}\\` parses, but nothing deploys it: previews need wildcard\\n` +\n\t\t\t\t`DNS and certificates that \\`vela provision\\` does not set up yet.`\n\t\t);\n\t}\n\n\tconst { workspaceRootDir } = await getWorkspace();\n\tconst config = await loadDeployConfig(workspaceRootDir);\n\t// Minting the app id here rather than demanding a prior deploy is what lets\n\t// `vela env import` run before the first `vela deploy`, which is the order\n\t// that gets an app its secrets before it ever serves a request.\n\tconst app = resolveAppIdentity(workspaceRootDir, {\n\t\t...config,\n\t\tproject: run.project ?? config.project\n\t});\n\tconst base = {\n\t\tworkspaceRootDir,\n\t\tappName: app.name,\n\t\tappId: app.appId,\n\t\tconfig\n\t};\n\n\tif (target.kind === 'local') {\n\t\tif (!handlers.local) {\n\t\t\tthrow new Error(\n\t\t\t\t`${label} has no local target.` + (run.localHint ? `\\n\\n${run.localHint}` : '')\n\t\t\t);\n\t\t}\n\t\tawait handlers.local({\n\t\t\t...base,\n\t\t\tkind: 'local',\n\t\t\tenvFile: envFilePath(workspaceRootDir)\n\t\t});\n\t\treturn;\n\t}\n\n\tif (!handlers.remote) {\n\t\tthrow new Error(`${label} only acts on ${pc.cyan('local')}.`);\n\t}\n\n\tconst binding = await ensureBinding(workspaceRootDir, target, {\n\t\tserver: options.server,\n\t\taskDomain: run.askDomain\n\t});\n\n\tawait withSsh(binding.server, sshOptionsFrom(options), async (session) => {\n\t\tawait session.detectElevation();\n\t\tawait requireProvisioned(session);\n\t\t// Keep the server's copy of the scripts in step with this CLI, so a\n\t\t// command never runs against a script from an older version.\n\t\tawait syncServerScripts(session);\n\t\tawait handlers.remote!({\n\t\t\t...base,\n\t\t\tkind: 'remote',\n\t\t\tsession,\n\t\t\tinstance: instanceId(app.appId, target.envTag),\n\t\t\tenvTag: target.envTag,\n\t\t\ttargetName: target.name,\n\t\t\tserver: binding.server,\n\t\t\tbinding\n\t\t});\n\t});\n}\n\nexport interface BindingRequest {\n\tserver?: string;\n\tdomain?: string;\n\taskDomain?: boolean;\n}\n\n/**\n * Work out which server a target runs on, binding it on first use.\n *\n * A target is a name; the machine behind it is recorded once and then never\n * retyped. `--server` is the non-interactive way in, which is what CI passes; a\n * terminal is asked instead, so `vela create` straight into `vela deploy` works\n * with nothing to look up.\n */\nexport async function ensureBinding(\n\tworkspaceRootDir: string,\n\ttarget: RemoteTarget,\n\trequest: BindingRequest = {}\n): Promise<TargetBinding> {\n\tconst existing = readBinding(workspaceRootDir, target.envTag);\n\tconst moving = Boolean(request.server && existing && existing.server !== request.server);\n\n\tlet server = request.server ?? existing?.server;\n\tif (!server) {\n\t\tserver = await promptServer(target);\n\t}\n\n\tlet domain = request.domain ?? existing?.domain;\n\tif (!domain && request.askDomain && !request.server) {\n\t\tdomain = await promptDomain(target);\n\t}\n\n\tconst binding: TargetBinding = domain ? { server, domain } : { server };\n\tif (!existing || existing.server !== server || existing.domain !== domain) {\n\t\twriteBinding(workspaceRootDir, target.envTag, binding);\n\t}\n\n\tif (moving) {\n\t\tp.log.warn(\n\t\t\t`${pc.cyan(target.name)} now points at ${pc.cyan(server)}.\\n\\n` +\n\t\t\t\t`Whatever is running on ${existing!.server} is left there, and this project can no\\n` +\n\t\t\t\t`longer reach it. Remove it there first if that was not intended.`\n\t\t);\n\t}\n\n\treturn binding;\n}\n\nasync function promptServer(target: RemoteTarget): Promise<string> {\n\tif (!process.stdout.isTTY || process.env.CI) {\n\t\tthrow new Error(\n\t\t\t`${target.name} is not bound to a server yet, and there is no terminal to ask on.\\n\\n` +\n\t\t\t\t`Pass ${pc.cyan('--server user@host')}, or run the command once from your own machine\\n` +\n\t\t\t\t`and commit ${pc.cyan('.vela/project.json')}.`\n\t\t);\n\t}\n\n\tp.log.info(`${pc.cyan(target.name)} is not bound to a server yet.`);\n\tconst value = await p.text({\n\t\tmessage: `Which server should ${target.name} run on?`,\n\t\tplaceholder: 'root@203.0.113.10',\n\t\tvalidate: (input) => (input?.trim() ? undefined : 'An ssh_config alias, or user@host')\n\t});\n\tif (p.isCancel(value)) {\n\t\tp.cancel('Operation cancelled.');\n\t\tprocess.exit(0);\n\t}\n\treturn value.trim();\n}\n\nasync function promptDomain(target: RemoteTarget): Promise<string | undefined> {\n\tif (!process.stdout.isTTY || process.env.CI) return undefined;\n\n\tconst value = await p.text({\n\t\tmessage: `Which hostname should ${target.name} be served on?`,\n\t\tplaceholder: 'example.com \u2014 leave blank to decide later'\n\t});\n\tif (p.isCancel(value)) {\n\t\tp.cancel('Operation cancelled.');\n\t\tprocess.exit(0);\n\t}\n\treturn value.trim() || undefined;\n}\n\n/** Restart after a change, reporting the two outcomes separately. */\nexport async function applyRestart(ctx: ServerContext): Promise<void> {\n\tconst outcome = await restartInstance(ctx.session, ctx.instance);\n\tif (!outcome.deployed) return;\n\tif (outcome.restarted) {\n\t\tp.log.success('App restarted');\n\t\treturn;\n\t}\n\tp.log.error(\n\t\t`App restart failed.\\n\\n` +\n\t\t\t`The new value is stored and will be used the next time the app starts.\\n` +\n\t\t\t`${pc.dim(outcome.error ?? '')}`\n\t);\n}\n\n/**\n * Restart after an env change, unless it touched the PocketBase superuser.\n *\n * Those two values are only half of the credential \u2014 the other half is a record\n * in the instance's database, which `vela deploy` reconciles. Restarting here\n * would pick up a password the database does not know yet and fail every\n * request, so the change is stored and the restart deferred.\n */\nexport async function applyEnvRestart(ctx: ServerContext, changed: string[]): Promise<void> {\n\tif (touchesSuperuser(changed)) {\n\t\tp.log.warn(\n\t\t\t`PocketBase superuser credentials changed.\\n\\n` +\n\t\t\t\t`The database still holds the old ones, so the app has not been restarted.\\n` +\n\t\t\t\t`Run ${pc.cyan('vela deploy')} to push them into the database and restart.`\n\t\t);\n\t\treturn;\n\t}\n\tawait applyRestart(ctx);\n}\n\n/**\n * Open a session against a server without naming an instance \u2014 `vela status\n * --all` is a question about the machine, not about one app.\n */\nexport async function withServerSession(\n\traw: unknown,\n\tfn: (session: SshSession) => Promise<void>\n): Promise<void> {\n\tconst options = parseOptions(OptionsSchema, raw);\n\n\tlet server = options.server;\n\tif (!server) {\n\t\tconst { workspaceRootDir } = await getWorkspace();\n\t\tconst target = parseTarget(options.target, 'production');\n\t\tif (target.kind !== 'remote') {\n\t\t\tthrow new Error(`${describeTarget(target)} does not run on a server.`);\n\t\t}\n\t\tserver = (await ensureBinding(workspaceRootDir, target, { server: options.server })).server;\n\t}\n\n\tawait withSsh(server, sshOptionsFrom(options), async (session) => {\n\t\tawait session.detectElevation();\n\t\tawait requireProvisioned(session);\n\t\tawait syncServerScripts(session);\n\t\tawait fn(session);\n\t});\n}\n\nfunction envFilePath(workspaceRootDir: string): string {\n\treturn `${workspaceRootDir}/.env`;\n}\n", "import fs from 'node:fs';\nimport path from 'node:path';\nimport crypto from 'node:crypto';\nimport { pathToFileURL } from 'node:url';\nimport { readPackageJson } from './package-json.ts';\n\n/**\n * Per-project deploy settings, read from `velastack.config.{ts,js,mjs,json}` at\n * the workspace root. Every field is optional \u2014 a project with no config file at\n * all can still be deployed, it just has to pass `--domain` the first time.\n */\nexport interface VelaDeployConfig {\n\t/** Public hostname Caddy should serve this app on. */\n\tdomain?: string;\n\t/** Path the deploy health check hits on the app's own port. */\n\thealthCheckPath?: string;\n\t/** Build command run locally before packing the artifact. */\n\tbuildCommand?: string;\n\t/** Directory the adapter writes to. */\n\toutputDir?: string;\n\t/** Extra files or directories to include in the release artifact. */\n\tinclude?: string[];\n\t/** How many old releases to keep on the server. */\n\tkeepReleases?: number;\n\t/** PocketBase version to run. Defaults to the one this CLI develops against. */\n\tpocketbaseVersion?: string;\n\t/**\n\t * Render the build against the deployed instance's database rather than a\n\t * throwaway local one. Needed when pages are prerendered from data, which\n\t * would otherwise bake in the defaults of an empty database.\n\t */\n\tbuildAgainstRemote?: boolean;\n}\n\nexport interface VelaAppConfig {\n\tproject?: string;\n\tdeploy?: VelaDeployConfig;\n}\n\nconst CONFIG_BASENAMES = [\n\t'velastack.config.ts',\n\t'velastack.config.js',\n\t'velastack.config.mjs',\n\t'velastack.config.json'\n];\n\nexport function findConfigFile(workspaceRootDir: string): string | null {\n\tfor (const name of CONFIG_BASENAMES) {\n\t\tconst file = path.join(workspaceRootDir, name);\n\t\tif (fs.existsSync(file)) return file;\n\t}\n\treturn null;\n}\n\nexport async function loadDeployConfig(workspaceRootDir: string): Promise<VelaAppConfig> {\n\tconst file = findConfigFile(workspaceRootDir);\n\tif (!file) return {};\n\n\tif (file.endsWith('.json')) {\n\t\treturn JSON.parse(fs.readFileSync(file, 'utf8')) as VelaAppConfig;\n\t}\n\n\tconst url = file.endsWith('.ts') ? await transpileToTemp(file) : pathToFileURL(file).href;\n\ttry {\n\t\tconst mod = (await import(url)) as { default?: VelaAppConfig };\n\t\tconst config = mod.default;\n\t\tif (!config || typeof config !== 'object') {\n\t\t\tthrow new Error(`${path.basename(file)} must export a config object as its default export.`);\n\t\t}\n\t\treturn config;\n\t} finally {\n\t\tif (url !== pathToFileURL(file).href) fs.rmSync(new URL(url), { force: true });\n\t}\n}\n\n/**\n * Type annotations are stripped with the TypeScript compiler that ships with\n * ts-morph \u2014 already a dependency \u2014 rather than relying on the host Node having\n * type stripping enabled. The temp file sits beside the original so relative\n * imports still resolve.\n */\nasync function transpileToTemp(file: string): Promise<string> {\n\tconst { ts } = await import('ts-morph');\n\tconst source = fs.readFileSync(file, 'utf8');\n\tconst { outputText } = ts.transpileModule(source, {\n\t\tcompilerOptions: { module: ts.ModuleKind.ESNext, target: ts.ScriptTarget.ES2022 }\n\t});\n\tconst temp = path.join(\n\t\tpath.dirname(file),\n\t\t`.velastack.config.${crypto.randomBytes(4).toString('hex')}.mjs`\n\t);\n\tfs.writeFileSync(temp, outputText);\n\treturn pathToFileURL(temp).href;\n}\n\n/** Identity of a deployable app, stable for the lifetime of the project. */\nexport interface AppIdentity {\n\t/** Immutable id used for server paths and unit names. */\n\tappId: string;\n\t/** Human-readable name, used in output and for the `by-name` symlink. */\n\tname: string;\n}\n\ninterface ProjectFile {\n\tprojectId?: string;\n\tteamId?: string;\n\tprojectName?: string;\n\tappId?: string;\n\ttargets?: Record<string, TargetBinding>;\n\t/**\n\t * The shape before targets were named. Still read, never written: a project\n\t * deployed with an older CLI keeps working, and is rewritten into `targets`\n\t * the next time it deploys.\n\t */\n\tdeployments?: Record<string, LegacyDeployment>;\n}\n\nfunction projectFilePath(workspaceRootDir: string): string {\n\treturn path.join(workspaceRootDir, '.vela', 'project.json');\n}\n\nfunction readProjectFile(workspaceRootDir: string): ProjectFile {\n\tconst file = projectFilePath(workspaceRootDir);\n\tif (!fs.existsSync(file)) return {};\n\ttry {\n\t\treturn JSON.parse(fs.readFileSync(file, 'utf8')) as ProjectFile;\n\t} catch {\n\t\treturn {};\n\t}\n}\n\nfunction writeProjectFile(workspaceRootDir: string, data: ProjectFile): void {\n\tconst file = projectFilePath(workspaceRootDir);\n\tfs.mkdirSync(path.dirname(file), { recursive: true });\n\tfs.writeFileSync(file, JSON.stringify(data, null, 2) + '\\n');\n}\n\n/**\n * Resolve \u2014 and on first use, mint \u2014 the app's immutable id.\n *\n * A project already linked to velastack.dev reuses its project id. Everything\n * else gets a locally generated one, so deploying to your own VPS never\n * requires an account. Either way the id is written to `.vela/project.json` and\n * never recomputed: server paths and env files hang off it, so it has to\n * survive renames.\n */\nexport function resolveAppIdentity(\n\tworkspaceRootDir: string,\n\tconfig: VelaAppConfig = {}\n): AppIdentity {\n\tconst project = readProjectFile(workspaceRootDir);\n\tconst name = config.project ?? project.projectName ?? defaultProjectName(workspaceRootDir);\n\n\tif (project.appId) return { appId: project.appId, name };\n\n\tconst appId = project.projectId ?? `${slug(name)}-${crypto.randomBytes(4).toString('hex')}`;\n\twriteProjectFile(workspaceRootDir, {\n\t\t...project,\n\t\tappId,\n\t\tprojectName: project.projectName ?? name\n\t});\n\treturn { appId, name };\n}\n\n/** Read the app id without minting one \u2014 for commands that must not create state. */\nexport function readAppIdentity(\n\tworkspaceRootDir: string,\n\tconfig: VelaAppConfig = {}\n): AppIdentity | null {\n\tconst project = readProjectFile(workspaceRootDir);\n\tconst appId = project.appId ?? project.projectId;\n\tif (!appId) return null;\n\treturn {\n\t\tappId,\n\t\tname: config.project ?? project.projectName ?? defaultProjectName(workspaceRootDir)\n\t};\n}\n\nexport function defaultProjectName(workspaceRootDir: string): string {\n\ttry {\n\t\tconst pkg = readPackageJson(path.join(workspaceRootDir, 'package.json'));\n\t\tif (typeof pkg.name === 'string' && pkg.name.trim()) return pkg.name.trim();\n\t} catch {\n\t\t// fall through to the directory name\n\t}\n\treturn path.basename(workspaceRootDir);\n}\n\nfunction slug(value: string): string {\n\treturn (\n\t\tvalue\n\t\t\t.toLowerCase()\n\t\t\t.replace(/^@/, '')\n\t\t\t.replace(/[^a-z0-9]+/g, '-')\n\t\t\t.replace(/^-+|-+$/g, '')\n\t\t\t.slice(0, 32) || 'app'\n\t);\n}\n\nexport interface TargetBinding {\n\t/** SSH destination, exactly as `ssh` would take it. */\n\tserver: string;\n\t/** Hostname(s) Caddy serves this target on. */\n\tdomain?: string;\n}\n\ninterface LegacyDeployment {\n\ttarget: string;\n\tdomain?: string;\n}\n\n/**\n * Where a target runs.\n *\n * This is ordinary project metadata \u2014 a hostname, never a credential \u2014 and\n * belongs in version control beside the app id. Binding a target to a server\n * once is what lets every other command take `-t staging` and nothing else.\n */\nexport function readBinding(workspaceRootDir: string, envTag: string): TargetBinding | null {\n\tconst project = readProjectFile(workspaceRootDir);\n\tconst bound = project.targets?.[envTag];\n\tif (bound?.server) return bound;\n\n\tconst legacy = project.deployments?.[envTag];\n\tif (legacy?.target) return { server: legacy.target, domain: legacy.domain };\n\n\treturn null;\n}\n\n/** Every bound target, newest shape taking precedence over the old one. */\nexport function readBindings(workspaceRootDir: string): Record<string, TargetBinding> {\n\tconst project = readProjectFile(workspaceRootDir);\n\tconst bindings: Record<string, TargetBinding> = {};\n\n\tfor (const [envTag, legacy] of Object.entries(project.deployments ?? {})) {\n\t\tif (legacy?.target) bindings[envTag] = { server: legacy.target, domain: legacy.domain };\n\t}\n\tfor (const [envTag, bound] of Object.entries(project.targets ?? {})) {\n\t\tif (bound?.server) bindings[envTag] = bound;\n\t}\n\n\treturn bindings;\n}\n\nexport function writeBinding(\n\tworkspaceRootDir: string,\n\tenvTag: string,\n\tbinding: TargetBinding\n): void {\n\tconst project = readProjectFile(workspaceRootDir);\n\twriteProjectFile(workspaceRootDir, {\n\t\t...project,\n\t\ttargets: { ...project.targets, [envTag]: binding }\n\t});\n}\n", "/**\n * Instance identity.\n *\n * A deployed app is identified on the server by a single stable token that is\n * safe in a path, a systemd unit name, and a filename:\n *\n * prod -> `<appId>`\n * staging -> `<appId>--staging`\n * preview/feature-x -> `<appId>--preview--feature-x`\n *\n * Production deliberately has no suffix, so the common case reads as\n * `/var/lib/vela/apps/<appId>` \u2014 the layout `plans/vela-env-plan.md` describes.\n */\n\nexport const PROD_ENV = 'prod';\n\nconst MAX_SEGMENT = 48;\n\n/** Normalize a user-supplied environment tag to its canonical form. */\nexport function normalizeEnvTag(tag: string | undefined): string {\n\tconst raw = (tag ?? PROD_ENV).trim();\n\tif (!raw) return PROD_ENV;\n\tconst normalized = raw\n\t\t.toLowerCase()\n\t\t.replace(/\\//g, '--')\n\t\t.replace(/[^a-z0-9-]+/g, '-')\n\t\t.replace(/-{3,}/g, '--')\n\t\t.replace(/^-+|-+$/g, '');\n\tif (!normalized) throw new Error(`Invalid environment tag: ${tag}`);\n\t// `local` is the copy on this machine and has no instance on any server.\n\t// Closed here rather than in the target parser so that no future caller can\n\t// route around it and create `<appId>--local`.\n\tif (normalized === 'local') {\n\t\tthrow new Error('`local` is not a deployable environment \u2014 it is the copy on this machine.');\n\t}\n\treturn normalized === 'production' ? PROD_ENV : normalized;\n}\n\n/** Turn a git branch name into an environment tag: `feature/auth` -> `preview--feature-auth`. */\nexport function branchToEnvTag(branch: string): string {\n\tconst slug = branch\n\t\t.toLowerCase()\n\t\t.replace(/[^a-z0-9]+/g, '-')\n\t\t.replace(/^-+|-+$/g, '')\n\t\t.slice(0, MAX_SEGMENT);\n\treturn `preview--${slug}`;\n}\n\nexport function instanceId(appId: string, envTag: string = PROD_ENV): string {\n\tconst env = normalizeEnvTag(envTag);\n\treturn env === PROD_ENV ? appId : `${appId}--${env}`;\n}\n\nexport function isProd(envTag: string): boolean {\n\treturn normalizeEnvTag(envTag) === PROD_ENV;\n}\n\n/** A release id sorts lexicographically by time, which is how `latest` is found. */\nexport function releaseId(date = new Date()): string {\n\treturn date\n\t\t.toISOString()\n\t\t.replace(/[-:]/g, '')\n\t\t.replace(/\\.\\d+Z$/, 'Z');\n}\n", "import { Command } from 'commander';\nimport * as v from 'valibot';\nimport type { SshOptions } from './ssh.ts';\n\n/** Flags every server-facing command shares. */\nexport const SSH_OPTION_SCHEMA = {\n\tidentity: v.optional(v.string()),\n\tsshPort: v.optional(v.string()),\n\tacceptHostKeys: v.optional(v.boolean())\n};\n\nexport function addSshOptions(command: Command): Command {\n\treturn command\n\t\t.option('-i, --identity <file>', 'SSH private key to authenticate with')\n\t\t.option('--ssh-port <port>', 'SSH port')\n\t\t.option('--accept-host-keys', 'trust an unknown host key on first connect (CI)');\n}\n\nexport function sshOptionsFrom(options: {\n\tidentity?: string;\n\tsshPort?: string;\n\tacceptHostKeys?: boolean;\n}): SshOptions {\n\treturn {\n\t\tidentityFile: options.identity,\n\t\tport: options.sshPort ? Number(options.sshPort) : undefined,\n\t\tacceptNewHostKeys: options.acceptHostKeys\n\t};\n}\n", "import fs from 'node:fs';\nimport os from 'node:os';\nimport path from 'node:path';\nimport crypto from 'node:crypto';\nimport process from 'node:process';\nimport { spawn, type StdioOptions } from 'node:child_process';\n\nexport interface SshOptions {\n\t/** Extra identity file, for CI where there is no ~/.ssh/config entry. */\n\tidentityFile?: string;\n\tport?: number;\n\t/** Skip host key prompts. CI sets this after seeding known_hosts itself. */\n\tacceptNewHostKeys?: boolean;\n}\n\n/**\n * Whether remote work has to be wrapped in `sudo`. Set once per session after\n * looking at the remote uid, so a `root` alias never pays for sudo and a\n * non-root alias fails early and clearly if it cannot escalate.\n */\nexport type Elevation = 'none' | 'sudo';\n\nexport interface RunOptions {\n\t/** Stream stdout/stderr to the terminal instead of capturing it. */\n\tstream?: boolean;\n\t/** Throw when the remote command exits non-zero. Defaults to true. */\n\tcheck?: boolean;\n\t/** Positional arguments passed to the script as `$1`, `$2`, ... */\n\targs?: string[];\n}\n\nexport interface RunResult {\n\tstdout: string;\n\tstderr: string;\n\texitCode: number;\n}\n\nexport class RemoteCommandError extends Error {\n\texitCode: number;\n\tstdout: string;\n\tstderr: string;\n\n\tconstructor(message: string, result: RunResult) {\n\t\tsuper(message);\n\t\tthis.name = 'RemoteCommandError';\n\t\tthis.exitCode = result.exitCode;\n\t\tthis.stdout = result.stdout;\n\t\tthis.stderr = result.stderr;\n\t}\n}\n\n/**\n * A connection to one server, multiplexed over a single OpenSSH ControlMaster\n * socket. Everything the CLI does remotely goes through `script()`, which pipes\n * a bash program over stdin \u2014 nothing user-supplied ever reaches a remote shell\n * as a concatenated string, and secrets never appear in the remote process list.\n */\nexport class SshSession {\n\treadonly target: string;\n\televation: Elevation = 'none';\n\tprivate readonly options: SshOptions;\n\tprivate controlPath: string | null = null;\n\n\tconstructor(target: string, options: SshOptions = {}) {\n\t\tthis.target = target;\n\t\tthis.options = options;\n\t}\n\n\tprivate sshArgs(): string[] {\n\t\tconst args: string[] = [];\n\t\tif (this.controlPath) args.push('-o', `ControlPath=${this.controlPath}`);\n\t\tif (this.options.identityFile) {\n\t\t\targs.push('-i', this.options.identityFile, '-o', 'IdentitiesOnly=yes');\n\t\t}\n\t\tif (this.options.port) args.push('-p', String(this.options.port));\n\t\tif (this.options.acceptNewHostKeys) args.push('-o', 'StrictHostKeyChecking=accept-new');\n\t\targs.push('-o', 'BatchMode=yes');\n\t\treturn args;\n\t}\n\n\t/** The `ssh` invocation rsync should use, as a single shell word list. */\n\trsyncShell(): string {\n\t\tconst parts = ['ssh', ...this.sshArgs()];\n\t\treturn parts.map(shellQuote).join(' ');\n\t}\n\n\tasync open(): Promise<void> {\n\t\tif (this.controlPath) return;\n\t\tconst dir = path.join(os.tmpdir(), 'vela-ssh');\n\t\tfs.mkdirSync(dir, { recursive: true, mode: 0o700 });\n\t\t// Socket paths live under a 104-char limit on macOS, so keep it short.\n\t\tconst socket = path.join(dir, `${crypto.randomBytes(6).toString('hex')}.sock`);\n\t\tthis.controlPath = socket;\n\n\t\tconst args = [\n\t\t\t...this.sshArgs(),\n\t\t\t'-o',\n\t\t\t'ControlMaster=yes',\n\t\t\t'-o',\n\t\t\t'ControlPersist=60',\n\t\t\t'-N',\n\t\t\t'-f',\n\t\t\tthis.target\n\t\t];\n\t\tconst result = await spawnCapture('ssh', args);\n\t\tif (result.exitCode !== 0) {\n\t\t\tthis.controlPath = null;\n\t\t\tthrow new Error(\n\t\t\t\t`Could not connect to ${this.target} over SSH.\\n\\n${result.stderr.trim() || result.stdout.trim()}`\n\t\t\t);\n\t\t}\n\t}\n\n\tasync close(): Promise<void> {\n\t\tif (!this.controlPath) return;\n\t\tconst socket = this.controlPath;\n\t\tthis.controlPath = null;\n\t\tawait spawnCapture('ssh', ['-o', `ControlPath=${socket}`, '-O', 'exit', this.target]);\n\t}\n\n\t/**\n\t * Run a bash program on the server. The program is piped over stdin, so it can\n\t * safely embed anything \u2014 quoting, newlines, base64 blobs \u2014 and `args` arrive\n\t * as ordinary positional parameters.\n\t */\n\tasync script(source: string, opts: RunOptions = {}): Promise<RunResult> {\n\t\tconst shell = this.elevation === 'sudo' ? 'sudo -n bash -s' : 'bash -s';\n\t\t// ssh joins its remaining argv with spaces and hands the result to a\n\t\t// remote shell, which silently drops empty arguments and splits ones\n\t\t// containing spaces. Quoting here means the remote `$@` is exactly what\n\t\t// was passed in.\n\t\tconst remote = [shell, '--', ...(opts.args ?? []).map(shellQuote)].join(' ');\n\t\tconst args = [...this.sshArgs(), this.target, remote];\n\t\tconst result = await spawnCapture('ssh', args, {\n\t\t\tstdin: `set -euo pipefail\\n${source}`,\n\t\t\tstream: opts.stream\n\t\t});\n\t\tif (opts.check !== false && result.exitCode !== 0) {\n\t\t\tthrow new RemoteCommandError(remoteFailure(this.target, result), result);\n\t\t}\n\t\treturn result;\n\t}\n\n\t/** Attach the terminal to a remote command \u2014 used by `vela logs -f`. */\n\tasync interactive(command: string[]): Promise<number> {\n\t\tconst args = [...this.sshArgs(), '-t', this.target, command.map(shellQuote).join(' ')];\n\t\treturn await new Promise((resolve) => {\n\t\t\tconst child = spawn('ssh', args, { stdio: 'inherit' });\n\t\t\tchild.on('close', (code) => resolve(code ?? 1));\n\t\t});\n\t}\n\n\t/**\n\t * Write a file on the server atomically, with an explicit mode.\n\t *\n\t * The payload rides inside the piped script as base64, so it never lands in\n\t * argv (visible in `ps`) or in a shell history, and binary-unsafe characters\n\t * are not an issue.\n\t */\n\tasync writeFile(remotePath: string, content: string, mode = '0644'): Promise<void> {\n\t\tconst payload = Buffer.from(content, 'utf8').toString('base64');\n\t\tawait this.script(\n\t\t\t`dest=\"$1\"; mode=\"$2\"\nmkdir -p \"$(dirname \"$dest\")\"\ntmp=$(mktemp \"$(dirname \"$dest\")/.vela.XXXXXX\")\nprintf %s ${payload} | base64 -d > \"$tmp\"\nchmod \"$mode\" \"$tmp\"\nmv -f \"$tmp\" \"$dest\"`,\n\t\t\t{ args: [remotePath, mode] }\n\t\t);\n\t}\n\n\t/**\n\t * Tunnel a local port to a port on the server, through the connection that is\n\t * already open. Used to point a local build at the target's database.\n\t */\n\tasync forwardLocalPort(localPort: number, remoteHost: string, remotePort: number): Promise<void> {\n\t\tif (!this.controlPath) throw new Error('Cannot forward a port without an open session.');\n\t\tconst spec = `${localPort}:${remoteHost}:${remotePort}`;\n\t\tconst result = await spawnCapture('ssh', [\n\t\t\t...this.sshArgs(),\n\t\t\t'-O',\n\t\t\t'forward',\n\t\t\t'-L',\n\t\t\tspec,\n\t\t\tthis.target\n\t\t]);\n\t\tif (result.exitCode !== 0) {\n\t\t\tthrow new Error(\n\t\t\t\t`Could not forward port ${spec} to ${this.target}.\\n\\n${result.stderr.trim()}`\n\t\t\t);\n\t\t}\n\t}\n\n\tasync cancelForward(localPort: number, remoteHost: string, remotePort: number): Promise<void> {\n\t\tif (!this.controlPath) return;\n\t\tawait spawnCapture('ssh', [\n\t\t\t...this.sshArgs(),\n\t\t\t'-O',\n\t\t\t'cancel',\n\t\t\t'-L',\n\t\t\t`${localPort}:${remoteHost}:${remotePort}`,\n\t\t\tthis.target\n\t\t]);\n\t}\n\n\tasync readFile(remotePath: string): Promise<string | null> {\n\t\tconst result = await this.script(`cat \"$1\" 2>/dev/null || exit 44`, {\n\t\t\targs: [remotePath],\n\t\t\tcheck: false\n\t\t});\n\t\tif (result.exitCode === 44) return null;\n\t\tif (result.exitCode !== 0)\n\t\t\tthrow new RemoteCommandError(remoteFailure(this.target, result), result);\n\t\treturn result.stdout;\n\t}\n\n\t/** rsync a local directory (contents) into a remote directory. */\n\tasync uploadDir(localDir: string, remoteDir: string, extraArgs: string[] = []): Promise<void> {\n\t\tconst src = localDir.endsWith('/') ? localDir : `${localDir}/`;\n\t\tconst args = [\n\t\t\t'-az',\n\t\t\t'--delete',\n\t\t\t'-e',\n\t\t\tthis.rsyncShell(),\n\t\t\t...this.rsyncPath(),\n\t\t\t...extraArgs,\n\t\t\tsrc,\n\t\t\t`${this.target}:${remoteDir}`\n\t\t];\n\t\tconst result = await spawnCapture('rsync', args);\n\t\tif (result.exitCode !== 0) {\n\t\t\tthrow new Error(`rsync to ${this.target}:${remoteDir} failed.\\n\\n${result.stderr.trim()}`);\n\t\t}\n\t}\n\n\tprivate rsyncPath(): string[] {\n\t\treturn this.elevation === 'sudo' ? ['--rsync-path=sudo -n rsync'] : [];\n\t}\n\n\t/**\n\t * rsync one remote path down to a local one.\n\t *\n\t * No `-z`: the only thing this moves is a backup archive, which is already\n\t * compressed, and asking gzip to compress a zip costs CPU on both ends for\n\t * nothing. `--partial` keeps what arrived when a large transfer is\n\t * interrupted, so retrying resumes rather than starting over.\n\t *\n\t * The remote path reaches rsync through a login shell, so it is quoted here\n\t * even though the paths this is called with are vela's own.\n\t */\n\tasync download(remotePath: string, localPath: string, extraArgs: string[] = []): Promise<void> {\n\t\tconst args = [\n\t\t\t'-a',\n\t\t\t'--partial',\n\t\t\t'-e',\n\t\t\tthis.rsyncShell(),\n\t\t\t...this.rsyncPath(),\n\t\t\t...extraArgs,\n\t\t\t`${this.target}:${shellQuote(remotePath)}`,\n\t\t\tlocalPath\n\t\t];\n\t\tconst result = await spawnCapture('rsync', args);\n\t\tif (result.exitCode !== 0) {\n\t\t\tthrow new Error(`rsync from ${this.target}:${remotePath} failed.\\n\\n${result.stderr.trim()}`);\n\t\t}\n\t}\n\n\t/** rsync one or more local paths to a remote directory. */\n\tasync upload(localPaths: string[], remoteDir: string, extraArgs: string[] = []): Promise<void> {\n\t\tconst args = [\n\t\t\t'-az',\n\t\t\t'-e',\n\t\t\tthis.rsyncShell(),\n\t\t\t...this.rsyncPath(),\n\t\t\t...extraArgs,\n\t\t\t...localPaths,\n\t\t\t`${this.target}:${remoteDir}`\n\t\t];\n\t\tconst result = await spawnCapture('rsync', args);\n\t\tif (result.exitCode !== 0) {\n\t\t\tthrow new Error(`rsync to ${this.target}:${remoteDir} failed.\\n\\n${result.stderr.trim()}`);\n\t\t}\n\t}\n\n\t/**\n\t * Decide once whether remote commands need `sudo`, and fail with something\n\t * actionable if they do but cannot get it.\n\t */\n\tasync detectElevation(): Promise<Elevation> {\n\t\tconst uid = await this.script('id -u', { check: false });\n\t\tif (uid.stdout.trim() === '0') {\n\t\t\tthis.elevation = 'none';\n\t\t\treturn this.elevation;\n\t\t}\n\t\tconst sudo = await this.script('sudo -n true', { check: false });\n\t\tif (sudo.exitCode !== 0) {\n\t\t\tthrow new Error(\n\t\t\t\t`${this.target} connects as a non-root user without passwordless sudo.\\n\\n` +\n\t\t\t\t\t`Use an SSH target that logs in as root, or give the user NOPASSWD sudo.`\n\t\t\t);\n\t\t}\n\t\tthis.elevation = 'sudo';\n\t\treturn this.elevation;\n\t}\n}\n\nfunction remoteFailure(target: string, result: RunResult): string {\n\tconst detail = (result.stderr.trim() || result.stdout.trim()).split('\\n').slice(-12).join('\\n');\n\treturn `Remote command failed on ${target} (exit ${result.exitCode}).\\n\\n${detail}`;\n}\n\nexport async function withSsh<T>(\n\ttarget: string,\n\toptions: SshOptions,\n\tfn: (session: SshSession) => Promise<T>\n): Promise<T> {\n\tconst session = new SshSession(target, options);\n\tawait session.open();\n\ttry {\n\t\treturn await fn(session);\n\t} finally {\n\t\tawait session.close();\n\t}\n}\n\nexport function shellQuote(value: string): string {\n\tif (/^[A-Za-z0-9_@%+=:,./-]+$/.test(value)) return value;\n\treturn `'${value.replaceAll(\"'\", `'\\\\''`)}'`;\n}\n\nexport interface SpawnOptions {\n\tstdin?: string;\n\t/**\n\t * Show the child's stderr as it arrives. stdout stays captured either way:\n\t * the server scripts put progress on stderr and their machine-readable\n\t * result on stdout, so the user sees one and the CLI parses the other.\n\t */\n\tstream?: boolean;\n\t/** Also echo stdout \u2014 for local builds, where stdout is the interesting half. */\n\tstreamStdout?: boolean;\n\tcwd?: string;\n\t/** Extra environment for the child, merged over the current process env. */\n\tenv?: Record<string, string | undefined>;\n}\n\nexport function spawnCapture(\n\tcommand: string,\n\targs: string[],\n\topts: SpawnOptions = {}\n): Promise<RunResult> {\n\treturn new Promise((resolve, reject) => {\n\t\tconst stdio: StdioOptions = [opts.stdin === undefined ? 'ignore' : 'pipe', 'pipe', 'pipe'];\n\t\tconst child = spawn(command, args, {\n\t\t\tstdio,\n\t\t\tcwd: opts.cwd,\n\t\t\tenv: opts.env ? { ...process.env, ...opts.env } : undefined\n\t\t});\n\t\tlet stdout = '';\n\t\tlet stderr = '';\n\t\tchild.stdout?.on('data', (chunk) => {\n\t\t\tstdout += chunk;\n\t\t\tif (opts.streamStdout) process.stdout.write(chunk);\n\t\t});\n\t\tchild.stderr?.on('data', (chunk) => {\n\t\t\tstderr += chunk;\n\t\t\tif (opts.stream) process.stderr.write(chunk);\n\t\t});\n\t\tchild.on('error', reject);\n\t\tchild.on('close', (code) => resolve({ stdout, stderr, exitCode: code ?? 1 }));\n\t\tif (opts.stdin !== undefined) {\n\t\t\tchild.stdin!.end(opts.stdin);\n\t\t}\n\t});\n}\n", "import path from 'node:path';\nimport { templatesDir } from './templates.ts';\nimport { SshSession, type RunResult } from './ssh.ts';\n\nexport const VELA_ROOT = '/var/lib/vela';\nexport const VELA_ETC = '/etc/vela';\n/** The unprivileged account every app's files and processes belong to. */\nexport const VELA_USER = 'vela';\nexport const SCRIPTS_DIR = `${VELA_ROOT}/scripts`;\nexport const PROVISIONED_MARKER = `${VELA_ETC}/provisioned`;\n\nexport interface ServerInfo {\n\tcliVersion: string;\n\tpocketbaseVersion: string;\n\tprovisionedAt: string;\n\tlayoutVersion: number;\n}\n\nexport interface InstanceState {\n\tappId: string;\n\tname: string;\n\tenv: string;\n\tinstance: string;\n\tactiveRelease?: string;\n\tpreviousRelease?: string;\n\tdomain?: string;\n\thealthCheckPath?: string;\n\tpocketbaseVersion?: string;\n\tgitSha?: string;\n\twebPort?: number;\n\tpbPort?: number;\n\tbackend?: boolean;\n\tdeployedAt?: string;\n\trolledBackAt?: string;\n\trestoredAt?: string;\n\t/** Backup key or uploaded filename the last restore came from. */\n\trestoredFrom?: string;\n\t/** The pb_data the last restore set aside, kept as the only undo. */\n\tpreviousDataDir?: string;\n\tcurrent?: string;\n\treleases?: string[];\n\tservices?: { web: string; pocketbase: string };\n}\n\n/** The `templates/server` tree that gets uploaded to `/var/lib/vela/scripts`. */\nexport function serverTemplatesDir(): string {\n\treturn path.join(templatesDir(), 'server');\n}\n\n/**\n * Put this CLI's copy of the server scripts on the box.\n *\n * Uploaded on every provision *and* every deploy, so the scripts a server runs\n * always match the CLI driving it \u2014 upgrading the CLI is all it takes to pick\n * up a fixed deploy script.\n */\nexport async function syncServerScripts(session: SshSession): Promise<void> {\n\tawait session.script(`mkdir -p \"$1\" && chmod 0755 \"$1\"`, { args: [SCRIPTS_DIR] });\n\tawait session.uploadDir(serverTemplatesDir(), SCRIPTS_DIR, ['--chmod=D755,F755']);\n\t// rsync preserves the developer's uid otherwise, which leaves root-run\n\t// scripts owned by a uid that means nothing on the server.\n\tawait session.script(`chown -R root:root \"$1\"`, { args: [SCRIPTS_DIR] });\n}\n\nexport interface ScriptOptions {\n\targs?: string[];\n\tstream?: boolean;\n}\n\n/**\n * Run one of the uploaded server scripts and return whatever it emitted as its\n * `VELA_RESULT` line. Progress goes to stderr, so it can stream to the user\n * while the structured result still comes back cleanly.\n */\nexport async function runServerScript<T = Record<string, unknown>>(\n\tsession: SshSession,\n\tname: string,\n\topts: ScriptOptions = {}\n): Promise<T | null> {\n\t// `bash -s -- a b c` leaves $0 as \"bash\", so the script path is the first\n\t// positional and has to be shifted off before exec.\n\tconst result = await session.script(`script=\"$1\"; shift; exec \"$script\" \"$@\"`, {\n\t\targs: [`${SCRIPTS_DIR}/${name}`, ...(opts.args ?? [])],\n\t\tstream: opts.stream\n\t});\n\treturn parseResult<T>(result);\n}\n\nexport function parseResult<T>(result: RunResult): T | null {\n\tconst line = result.stdout\n\t\t.split('\\n')\n\t\t.reverse()\n\t\t.find((l) => l.startsWith('VELA_RESULT '));\n\tif (!line) return null;\n\ttry {\n\t\treturn JSON.parse(line.slice('VELA_RESULT '.length)) as T;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nexport async function readServerInfo(session: SshSession): Promise<ServerInfo | null> {\n\tconst raw = await session.readFile(PROVISIONED_MARKER);\n\tif (!raw) return null;\n\ttry {\n\t\treturn JSON.parse(raw) as ServerInfo;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nexport async function requireProvisioned(session: SshSession): Promise<ServerInfo> {\n\tconst info = await readServerInfo(session);\n\tif (!info) {\n\t\tthrow new Error(\n\t\t\t`${session.target} has not been provisioned for vela yet.\\n\\n` +\n\t\t\t\t`Run \\`vela provision ${session.target}\\` first.`\n\t\t);\n\t}\n\treturn info;\n}\n\nexport async function readInstanceStates(\n\tsession: SshSession,\n\tinstance?: string\n): Promise<InstanceState[]> {\n\tconst result = await runServerScript<InstanceState[]>(session, 'status.sh', {\n\t\targs: instance ? [instance] : []\n\t});\n\treturn Array.isArray(result) ? result : [];\n}\n\n/** Paths on the server, kept in one place so the scripts and CLI agree. */\nexport const remotePaths = {\n\tapp: (instance: string) => `${VELA_ROOT}/apps/${instance}`,\n\treleases: (instance: string) => `${VELA_ROOT}/apps/${instance}/releases`,\n\trelease: (instance: string, release: string) =>\n\t\t`${VELA_ROOT}/apps/${instance}/releases/${release}`,\n\tshared: (instance: string) => `${VELA_ROOT}/apps/${instance}/shared`,\n\tpbData: (instance: string) => `${VELA_ROOT}/apps/${instance}/shared/pb_data`,\n\tstorage: (instance: string) => `${VELA_ROOT}/apps/${instance}/shared/pb_data/storage`,\n\tbackups: (instance: string) => `${VELA_ROOT}/apps/${instance}/shared/pb_data/backups`,\n\tbackup: (instance: string, key: string) =>\n\t\t`${VELA_ROOT}/apps/${instance}/shared/pb_data/backups/${key}`,\n\t/** Where an archive uploaded from this machine waits, outside pb_data. */\n\trestoreStage: (instance: string) => `${VELA_ROOT}/apps/${instance}/shared/.restore`,\n\tenv: (instance: string) => `${VELA_ETC}/apps/${instance}/env`,\n\truntimeEnv: (instance: string) => `${VELA_ETC}/apps/${instance}/runtime.env`,\n\tcaddy: (instance: string) => `${VELA_ETC}/caddy/${instance}.caddy`,\n\twebUnit: (instance: string) => `vela-web@${instance}.service`,\n\tpbUnit: (instance: string) => `vela-pb@${instance}.service`\n};\n", "import fs from 'node:fs';\nimport dotenv from 'dotenv';\nimport { remotePaths } from './remote.ts';\nimport type { SshSession } from './ssh.ts';\n\nexport type EnvRecord = Record<string, string>;\n\nconst KEY_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/;\n\nexport function isValidKey(key: string): boolean {\n\treturn KEY_PATTERN.test(key);\n}\n\n/**\n * Parse a vela-managed env file.\n *\n * The file is read by systemd, not by dotenv, so quoting follows systemd's\n * `EnvironmentFile` rules: values are double-quoted and `\\\\`, `\\\"` and `\\n` are\n * the escapes. vela writes every value that way, and this reads it back.\n */\nexport function parseEnv(content: string): EnvRecord {\n\tconst result: EnvRecord = {};\n\tfor (const line of content.split('\\n')) {\n\t\tconst trimmed = line.trim();\n\t\tif (!trimmed || trimmed.startsWith('#')) continue;\n\t\tconst eq = trimmed.indexOf('=');\n\t\tif (eq < 1) continue;\n\t\tconst key = trimmed.slice(0, eq).trim();\n\t\tif (!isValidKey(key)) continue;\n\t\tresult[key] = unquote(trimmed.slice(eq + 1).trim());\n\t}\n\treturn result;\n}\n\nfunction unquote(raw: string): string {\n\tif (!raw.startsWith('\"')) return raw;\n\tconst body = raw.endsWith('\"') && raw.length > 1 ? raw.slice(1, -1) : raw.slice(1);\n\tlet out = '';\n\tfor (let i = 0; i < body.length; i++) {\n\t\tif (body[i] !== '\\\\' || i === body.length - 1) {\n\t\t\tout += body[i];\n\t\t\tcontinue;\n\t\t}\n\t\tconst next = body[++i];\n\t\tif (next === 'n') out += '\\n';\n\t\telse if (next === 't') out += '\\t';\n\t\telse out += next;\n\t}\n\treturn out;\n}\n\n/** Canonical, deterministic serialization: sorted keys, always quoted. */\nexport function serializeEnv(env: EnvRecord): string {\n\tconst keys = Object.keys(env).sort();\n\tconst lines = [\n\t\t'# Managed by `vela env`. Values are read by systemd at service start.',\n\t\t...keys.map((key) => `${key}=${quote(env[key]!)}`)\n\t];\n\treturn lines.join('\\n') + '\\n';\n}\n\nfunction quote(value: string): string {\n\tconst escaped = value\n\t\t.replaceAll('\\\\', '\\\\\\\\')\n\t\t.replaceAll('\"', '\\\\\"')\n\t\t.replaceAll('\\n', '\\\\n')\n\t\t.replaceAll('\\t', '\\\\t');\n\treturn `\"${escaped}\"`;\n}\n\n/** Read a local dotenv file, using dotenv's parser for whatever the user wrote. */\nexport function readLocalEnvFile(file: string): EnvRecord {\n\tconst parsed = dotenv.parse(fs.readFileSync(file));\n\tconst result: EnvRecord = {};\n\tfor (const [key, value] of Object.entries(parsed)) {\n\t\tif (isValidKey(key)) result[key] = value;\n\t}\n\treturn result;\n}\n\nexport async function readRemoteEnv(session: SshSession, instance: string): Promise<EnvRecord> {\n\tconst content = await session.readFile(remotePaths.env(instance));\n\treturn content ? parseEnv(content) : {};\n}\n\n/**\n * Replace the instance's env file. The contents travel inside the piped script\n * as base64, so no secret is ever an argument to a remote command.\n */\nexport async function writeRemoteEnv(\n\tsession: SshSession,\n\tinstance: string,\n\tenv: EnvRecord\n): Promise<void> {\n\tconst file = remotePaths.env(instance);\n\tawait session.writeFile(file, serializeEnv(env), '0600');\n\tawait session.script(`chown root:root \"$1\" && chmod 0600 \"$1\"`, { args: [file] });\n}\n\n/**\n * Credentials the app authenticates to its own PocketBase with.\n *\n * Not ordinary variables: the value here has to match a record in the\n * instance's database, and only a deploy can put it there. Changing one and\n * restarting on the spot would leave the app unable to authenticate, so the\n * env commands write the value and leave the restart to `vela deploy`.\n */\nexport const SUPERUSER_KEYS = [\n\t'POCKETBASE_SUPERUSER_EMAIL',\n\t'POCKETBASE_SUPERUSER_PASSWORD'\n] as const;\n\nexport function touchesSuperuser(keys: Iterable<string>): boolean {\n\tfor (const key of keys) {\n\t\tif ((SUPERUSER_KEYS as readonly string[]).includes(key)) return true;\n\t}\n\treturn false;\n}\n\nexport interface RestartOutcome {\n\tdeployed: boolean;\n\trestarted: boolean;\n\terror?: string;\n}\n\n/**\n * Restart an instance so new values take effect. An env change that lands but\n * fails to restart is reported as exactly that \u2014 the value is stored either way,\n * so it is never rolled back over a restart failure.\n */\nexport async function restartInstance(\n\tsession: SshSession,\n\tinstance: string\n): Promise<RestartOutcome> {\n\t// Only units this instance actually enabled \u2014 a frontend-only app has no\n\t// PocketBase service, and restarting a unit that was never deployed fails.\n\tconst result = await session.script(\n\t\t`instance=\"$1\"\nenabled=()\nfor unit in \"vela-pb@$instance.service\" \"vela-web@$instance.service\"; do\n\tif systemctl is-enabled \"$unit\" >/dev/null 2>&1; then enabled+=(\"$unit\"); fi\ndone\nif [ \\${#enabled[@]} -eq 0 ]; then echo NOT_DEPLOYED; exit 0; fi\nsystemctl restart \"\\${enabled[@]}\"`,\n\t\t{ args: [instance], check: false }\n\t);\n\n\tif (result.stdout.includes('NOT_DEPLOYED')) return { deployed: false, restarted: false };\n\tif (result.exitCode !== 0) {\n\t\treturn { deployed: true, restarted: false, error: result.stderr.trim() };\n\t}\n\treturn { deployed: true, restarted: true };\n}\n", "import { branchToEnvTag, normalizeEnvTag, PROD_ENV } from './instance.ts';\n\n/**\n * Which copy of the app a command acts on.\n *\n * A target never names a machine. `local` is the project on this computer;\n * everything else is an environment deployed somewhere, and the server behind it\n * is a binding recorded in `.vela/project.json` rather than something retyped on\n * every command.\n */\nexport interface LocalTarget {\n\tkind: 'local';\n}\n\nexport interface RemoteTarget {\n\tkind: 'remote';\n\t/** Canonical name, as typed and as shown back. */\n\tname: string;\n\t/** Server-side instance suffix. Derived, never stored. */\n\tenvTag: string;\n}\n\n/** Parsed so the grammar is settled, refused until previews are built. */\nexport interface PreviewTarget {\n\tkind: 'preview';\n\tbranch?: string;\n\tenvTag: string;\n}\n\nexport type Target = LocalTarget | RemoteTarget | PreviewTarget;\n\nexport const LOCAL_TARGET = 'local';\nexport const PRODUCTION_TARGET = 'production';\n\n/** What a command means when no `-t` is given. */\nexport type TargetFallback = 'local' | 'production';\n\nexport class TargetError extends Error {}\n\n/**\n * Values that are obviously a server rather than a target.\n *\n * `-t` used to mean the SSH host, so `vela env list -t root@1.2.3.4` parsed\n * happily before this change and would otherwise go on parsing \u2014 resolving to a\n * target named after a machine instead of failing. An ssh_config alias with no\n * dots (`myserver`) is indistinguishable from a custom target name and is not\n * caught here; the dotted, `@`-bearing and numeric forms cover what people\n * actually typed.\n */\nconst SERVER_SHAPED = /@|^\\d{1,3}(?:\\.\\d{1,3}){3}$|\\.[a-z]{2,}$/i;\n\nconst PREVIEW = 'preview';\n\nconst TARGET_NAME = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;\n\n/**\n * Read a `-t/--target` value.\n *\n * `preview:<branch>` is split before any normalization: `normalizeEnvTag` turns a\n * colon into a single dash, so `preview:feature/maps` would become\n * `preview-feature-maps` while `branchToEnvTag('feature/maps')` gives\n * `preview--feature-maps`. Two spellings of one branch pointing at two different\n * instances is the kind of thing that is only discovered on a server.\n */\nexport function parseTarget(raw: string | undefined, fallback: TargetFallback): Target {\n\tconst value = raw?.trim();\n\tif (!value) {\n\t\treturn fallback === 'local' ? { kind: 'local' } : production();\n\t}\n\n\tif (SERVER_SHAPED.test(value)) {\n\t\tthrow new TargetError(\n\t\t\t`${value} looks like a server, and ${bold('-t')} now selects a target rather than a machine.\\n\\n` +\n\t\t\t\t`Targets are ${bold('local')}, ${bold('production')}, or a name you choose such as ${bold('staging')}.\\n` +\n\t\t\t\t`To point a target at a server, pass ${bold('--server')} on \\`vela deploy\\`.`\n\t\t);\n\t}\n\n\tconst lower = value.toLowerCase();\n\tif (lower === LOCAL_TARGET) return { kind: 'local' };\n\n\tif (lower === PREVIEW || lower.startsWith(`${PREVIEW}:`)) {\n\t\tconst branch = lower.slice(PREVIEW.length + 1) || undefined;\n\t\treturn {\n\t\t\tkind: 'preview',\n\t\t\tbranch,\n\t\t\t// Held for when previews are built, so the grammar and the instance\n\t\t\t// naming cannot drift apart in the meantime.\n\t\t\tenvTag: branch ? branchToEnvTag(branch) : PREVIEW\n\t\t};\n\t}\n\n\tif (value.includes(':')) {\n\t\tthrow new TargetError(\n\t\t\t`${value} is not a target. Only ${bold('preview')} takes a \\`:branch\\` suffix.`\n\t\t);\n\t}\n\n\t// Validated, never scrubbed. `normalizeEnvTag` would quietly turn `pre view!`\n\t// into `pre-view`, and a selector that silently addresses a different \u2014 and\n\t// therefore empty \u2014 instance reports success for a typo.\n\tif (!TARGET_NAME.test(lower)) {\n\t\tthrow new TargetError(\n\t\t\t`${value} is not a target name.\\n\\n` +\n\t\t\t\t`Use lowercase letters, digits and single dashes, such as ${bold('staging')}.`\n\t\t);\n\t}\n\n\treturn { kind: 'remote', name: lower, envTag: normalizeEnvTag(lower) };\n}\n\nfunction production(): Target {\n\treturn { kind: 'remote', name: PRODUCTION_TARGET, envTag: PROD_ENV };\n}\n\n/** How a target reads back in output and errors. */\nexport function describeTarget(target: Target): string {\n\tswitch (target.kind) {\n\t\tcase 'local':\n\t\t\treturn LOCAL_TARGET;\n\t\tcase 'preview':\n\t\t\treturn target.branch ? `${PREVIEW}:${target.branch}` : PREVIEW;\n\t\tcase 'remote':\n\t\t\treturn target.name;\n\t}\n}\n\nfunction bold(text: string): string {\n\treturn `\\`${text}\\``;\n}\n", "import pc from 'picocolors';\nimport type PocketBase from 'pocketbase';\nimport { hasBackend } from './workspace.ts';\nimport { readLocalEnv } from './local-env.ts';\nimport { withPocketbase } from './pocketbase.ts';\nimport { withRemotePocketbase } from './remote-pocketbase.ts';\nimport { readInstanceStates } from './remote.ts';\nimport { withTarget } from './server-command.ts';\nimport type { SshSession } from './ssh.ts';\n\nexport interface BackupContext {\n\tpb: PocketBase;\n\t/** The deployed instance's session, or null for the local database. */\n\tsession: SshSession | null;\n\t/** Instance id on a server, app name locally. Names the archive either way. */\n\tinstance: string;\n\t/** How to refer to this copy of the app in output. */\n\ttargetName: string;\n\tworkspaceRootDir: string;\n}\n\n/**\n * Open whichever database `-t` names, for a command that acts on its backups.\n *\n * The two paths differ only in how PocketBase is reached \u2014 a subprocess against\n * `data/` here, a forwarded port there \u2014 so every backup subcommand is written\n * once against the handle this yields.\n */\nexport async function withBackupTarget(\n\traw: unknown,\n\tlabel: string,\n\tfn: (ctx: BackupContext) => Promise<void>\n): Promise<void> {\n\tawait withTarget(\n\t\traw,\n\t\t{\n\t\t\tlocal: async (ctx) => {\n\t\t\t\tif (!hasBackend(ctx.workspaceRootDir)) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`This project has no database, so there is nothing to back up.\\n\\n` +\n\t\t\t\t\t\t\t`Run ${pc.cyan('vela bless')} to add a backend.`\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\t// Read here rather than relying on the process environment: `backup`\n\t\t\t\t// is a NO_BACKEND command precisely so that acting on a server does\n\t\t\t\t// not require local credentials, which means nothing has loaded them.\n\t\t\t\tconst creds = readLocalEnv(ctx.envFile);\n\t\t\t\tconst email = creds.POCKETBASE_SUPERUSER_EMAIL;\n\t\t\t\tconst password = creds.POCKETBASE_SUPERUSER_PASSWORD;\n\t\t\t\tif (!email || !password) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`The local database has no superuser credentials to sign in with.\\n\\n` +\n\t\t\t\t\t\t\t`Set ${pc.cyan('POCKETBASE_SUPERUSER_EMAIL')} and ` +\n\t\t\t\t\t\t\t`${pc.cyan('POCKETBASE_SUPERUSER_PASSWORD')} in ${pc.cyan('.env')}.`\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tawait withPocketbase(\n\t\t\t\t\tctx.workspaceRootDir,\n\t\t\t\t\t(pb) =>\n\t\t\t\t\t\tfn({\n\t\t\t\t\t\t\tpb,\n\t\t\t\t\t\t\tsession: null,\n\t\t\t\t\t\t\tinstance: ctx.appName,\n\t\t\t\t\t\t\ttargetName: 'local',\n\t\t\t\t\t\t\tworkspaceRootDir: ctx.workspaceRootDir\n\t\t\t\t\t\t}),\n\t\t\t\t\t{ email, password }\n\t\t\t\t);\n\t\t\t},\n\t\t\tremote: async (ctx) => {\n\t\t\t\tconst [state] = await readInstanceStates(ctx.session, ctx.instance);\n\t\t\t\tif (state && state.backend === false) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`${ctx.targetName} was deployed without a database, so it has nothing to back up.`\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tawait withRemotePocketbase(ctx.session, ctx.instance, (pb) =>\n\t\t\t\t\tfn({\n\t\t\t\t\t\tpb,\n\t\t\t\t\t\tsession: ctx.session,\n\t\t\t\t\t\tinstance: ctx.instance,\n\t\t\t\t\t\ttargetName: ctx.targetName,\n\t\t\t\t\t\tworkspaceRootDir: ctx.workspaceRootDir\n\t\t\t\t\t})\n\t\t\t\t);\n\t\t\t}\n\t\t},\n\t\t{ label }\n\t);\n}\n", "import fs from 'node:fs';\nimport * as p from '@clack/prompts';\nimport pc from 'picocolors';\nimport { removeEnvVar, upsertEnvVar } from './env.ts';\nimport { readLocalEnvFile, touchesSuperuser, type EnvRecord } from './remote-env.ts';\nimport { ensureSuperuser, getPocketbaseMetadata } from './pocketbase.ts';\nimport type { LocalContext } from './server-command.ts';\n\n/** The project's `.env`, or an empty record when it has none yet. */\nexport function readLocalEnv(envFile: string): EnvRecord {\n\tif (!fs.existsSync(envFile)) return {};\n\treturn readLocalEnvFile(envFile);\n}\n\nexport function editLocalEnv(envFile: string, edit: (content: string) => string): void {\n\tconst before = fs.existsSync(envFile) ? fs.readFileSync(envFile, 'utf8') : '';\n\tconst after = edit(before);\n\tif (after !== before) fs.writeFileSync(envFile, after);\n}\n\nexport function setLocalEnv(envFile: string, key: string, value: string): void {\n\teditLocalEnv(envFile, (content) => upsertEnvVar(content, key, value));\n}\n\nexport function unsetLocalEnv(envFile: string, key: string): void {\n\teditLocalEnv(envFile, (content) => removeEnvVar(content, key));\n}\n\n/**\n * The local counterpart of `applyEnvRestart`.\n *\n * Remotely, superuser credentials in the environment have to match a record in\n * the instance's database and only a deploy reconciles them. The same hazard\n * exists here, except the fix is local and immediate: `ensureSuperuser` upserts\n * the account so `.env` and `data/` cannot disagree.\n */\nexport async function applyLocalEnvChange(ctx: LocalContext, changed: string[]): Promise<void> {\n\tif (touchesSuperuser(changed)) {\n\t\tconst env = readLocalEnv(ctx.envFile);\n\t\tconst email = env.POCKETBASE_SUPERUSER_EMAIL;\n\t\tconst password = env.POCKETBASE_SUPERUSER_PASSWORD;\n\n\t\tif (email && password) {\n\t\t\t// `ensureSuperuser` reads them from the environment of this process,\n\t\t\t// which was loaded before the file was edited.\n\t\t\tprocess.env.POCKETBASE_SUPERUSER_EMAIL = email;\n\t\t\tprocess.env.POCKETBASE_SUPERUSER_PASSWORD = password;\n\t\t\tawait ensureSuperuser(ctx.workspaceRootDir);\n\t\t\tp.log.success('Local superuser updated to match');\n\t\t} else {\n\t\t\tp.log.warn(\n\t\t\t\t`The local database still has the old superuser.\\n` +\n\t\t\t\t\t`Set both ${pc.cyan('POCKETBASE_SUPERUSER_EMAIL')} and ${pc.cyan('POCKETBASE_SUPERUSER_PASSWORD')} to reconcile it.`\n\t\t\t);\n\t\t}\n\t}\n\n\tif (getPocketbaseMetadata(ctx.workspaceRootDir)) {\n\t\tp.log.info(`Restart ${pc.cyan('vela dev')} to pick this up.`);\n\t}\n}\n", "import PocketBase from 'pocketbase';\nimport { findFreePort, authWithRetries } from './pocketbase.ts';\nimport { readInstanceStates } from './remote.ts';\nimport { readRemoteEnv } from './remote-env.ts';\nimport type { SshSession } from './ssh.ts';\n\nexport interface RemoteDatabase {\n\t/** Loopback URL on this machine, forwarded to the instance's PocketBase. */\n\turl: string;\n\temail: string;\n\tpassword: string;\n\tclose: () => Promise<void>;\n}\n\n/**\n * Forward a port to the PocketBase of a deployed instance and hand back the\n * credentials to talk to it.\n *\n * PocketBase listens on the server's loopback only, so the SSH connection that\n * is already open is the way in. The superuser credentials come off the server\n * itself: they are the app's own, and nothing about them has to be known here.\n */\nexport async function openRemoteDatabase(\n\tsession: SshSession,\n\tinstance: string\n): Promise<RemoteDatabase> {\n\tconst [state] = await readInstanceStates(session, instance);\n\tconst pbPort = state?.pbPort;\n\tif (!pbPort) {\n\t\tthrow new Error(\n\t\t\t`${instance} has no deployed database yet.\\n\\n` +\n\t\t\t\t`Run \\`vela deploy\\` first \u2014 the database is created by the first deploy.`\n\t\t);\n\t}\n\n\tconst env = await readRemoteEnv(session, instance);\n\tconst email = env.POCKETBASE_SUPERUSER_EMAIL;\n\tconst password = env.POCKETBASE_SUPERUSER_PASSWORD;\n\tif (!email || !password) {\n\t\tthrow new Error(\n\t\t\t`${instance} has no PocketBase superuser credentials in its environment.\\n\\n` +\n\t\t\t\t`A deploy creates them. Deploy again to repair this instance.`\n\t\t);\n\t}\n\n\tconst localPort = await findFreePort('127.0.0.1');\n\tawait session.forwardLocalPort(localPort, '127.0.0.1', pbPort);\n\n\treturn {\n\t\turl: `http://127.0.0.1:${localPort}`,\n\t\temail,\n\t\tpassword,\n\t\tclose: () => session.cancelForward(localPort, '127.0.0.1', pbPort)\n\t};\n}\n\n/** Run one piece of work against a deployed instance's database, authenticated. */\nexport async function withRemotePocketbase<T>(\n\tsession: SshSession,\n\tinstance: string,\n\tfn: (pb: PocketBase) => Promise<T>\n): Promise<T> {\n\tconst db = await openRemoteDatabase(session, instance);\n\ttry {\n\t\tconst pb = new PocketBase(db.url);\n\t\tawait authWithRetries(pb, db.email, db.password);\n\t\treturn await fn(pb);\n\t} finally {\n\t\tawait db.close();\n\t}\n}\n", "import fs from 'node:fs';\nimport path from 'node:path';\nimport type PocketBase from 'pocketbase';\nimport { DATA_DIR } from './constants.ts';\nimport { remotePaths } from './remote.ts';\nimport type { SshSession } from './ssh.ts';\n\nexport interface S3Config {\n\tendpoint: string;\n\tbucket: string;\n\tregion: string;\n\taccessKey: string;\n\tsecret: string;\n\tforcePathStyle: boolean;\n}\n\n/** Which of PocketBase's two independent S3 configurations to write. */\nexport type S3Filesystem = 'storage' | 'backups';\n\n/**\n * Providers that address buckets as a subdomain.\n *\n * Everything else \u2014 MinIO, Ceph, Garage, most self-hosted gateways \u2014 needs the\n * bucket in the path instead, and gets an opaque connection failure when it does\n * not. Guessing from the endpoint is right far more often than defaulting to\n * either answer outright.\n */\nconst VIRTUAL_HOSTED = [/\\.amazonaws\\.com$/i, /\\.r2\\.cloudflarestorage\\.com$/i];\n\nexport function defaultForcePathStyle(endpoint: string): boolean {\n\tlet host: string;\n\ttry {\n\t\thost = new URL(endpoint).hostname;\n\t} catch {\n\t\treturn false;\n\t}\n\treturn !VIRTUAL_HOSTED.some((pattern) => pattern.test(host));\n}\n\nexport async function applyS3(\n\tpb: PocketBase,\n\tconfig: S3Config,\n\tfilesystem: S3Filesystem\n): Promise<void> {\n\tconst s3 = { enabled: true, ...config };\n\tawait pb.settings.update(filesystem === 'backups' ? { backups: { s3 } } : { s3 });\n}\n\nexport async function disableS3(pb: PocketBase, filesystem: S3Filesystem): Promise<void> {\n\t// Only `enabled` is sent: PocketBase merges settings, so the credentials stay\n\t// on record and turning it back on does not mean retyping them.\n\tconst s3 = { enabled: false };\n\tawait pb.settings.update(filesystem === 'backups' ? { backups: { s3 } } : { s3 });\n}\n\nexport interface StoredS3 {\n\tenabled: boolean;\n\tendpoint: string;\n\tbucket: string;\n\tregion: string;\n\taccessKey: string;\n\tforcePathStyle: boolean;\n}\n\n/**\n * Read back what is already configured, to pre-fill the prompts.\n *\n * The secret is never included \u2014 PocketBase strips it from the settings it\n * serves \u2014 so it is the one value that always has to be typed again.\n */\nexport async function readS3(pb: PocketBase, filesystem: S3Filesystem): Promise<StoredS3> {\n\tconst settings = (await pb.settings.getAll()) as {\n\t\ts3?: Partial<StoredS3>;\n\t\tbackups?: { s3?: Partial<StoredS3> };\n\t};\n\tconst s3 = (filesystem === 'backups' ? settings.backups?.s3 : settings.s3) ?? {};\n\treturn {\n\t\tenabled: s3.enabled === true,\n\t\tendpoint: s3.endpoint ?? '',\n\t\tbucket: s3.bucket ?? '',\n\t\tregion: s3.region ?? '',\n\t\taccessKey: s3.accessKey ?? '',\n\t\tforcePathStyle: s3.forcePathStyle === true\n\t};\n}\n\n/**\n * Whether any upload is already sitting on local disk.\n *\n * Turning S3 on switches which filesystem PocketBase reads from; it moves\n * nothing. Every file already on disk stops resolving the moment it is enabled,\n * so this is the difference between a clean switch and a wall of broken images.\n *\n * The answer only has to be yes or no, so both paths stop at the first file\n * rather than counting a tree that may hold millions.\n */\nexport async function hasLocalUploads(\n\tsession: SshSession | null,\n\tinstance: string,\n\tworkspaceRootDir: string\n): Promise<boolean> {\n\tif (session) {\n\t\tconst result = await session.script(`[ -d \"$1\" ] || exit 0; find \"$1\" -type f -print -quit`, {\n\t\t\targs: [remotePaths.storage(instance)]\n\t\t});\n\t\treturn result.stdout.trim().length > 0;\n\t}\n\treturn hasFile(path.join(workspaceRootDir, DATA_DIR, 'storage'));\n}\n\nfunction hasFile(dir: string): boolean {\n\tlet entries: fs.Dirent[];\n\ttry {\n\t\tentries = fs.readdirSync(dir, { withFileTypes: true });\n\t} catch {\n\t\treturn false;\n\t}\n\tfor (const entry of entries) {\n\t\tif (entry.isFile()) return true;\n\t\tif (entry.isDirectory() && hasFile(path.join(dir, entry.name))) return true;\n\t}\n\treturn false;\n}\n", "import process from 'node:process';\nimport { Command } from 'commander';\nimport * as p from '@clack/prompts';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand } from '../../lib/run.ts';\nimport { withPocketbase } from '../../lib/pocketbase.ts';\nimport { getWorkspace } from '../../lib/workspace.ts';\nimport { reportResult } from '../../lib/result-report.ts';\n\nexport const smtp = new Command('smtp')\n\t.description('configure SMTP for transactional email')\n\t.configureHelp(helpConfig)\n\t.action(() =>\n\t\trunCommand(async () => {\n\t\t\tconst { workspaceRootDir } = await getWorkspace();\n\n\t\t\tconst config = await p.group(\n\t\t\t\t{\n\t\t\t\t\thost: () =>\n\t\t\t\t\t\tp.text({\n\t\t\t\t\t\t\tmessage: 'SMTP host',\n\t\t\t\t\t\t\tplaceholder: 'smtp.example.com',\n\t\t\t\t\t\t\tvalidate: (v) => (v ? undefined : 'Host is required')\n\t\t\t\t\t\t}),\n\t\t\t\t\tport: () =>\n\t\t\t\t\t\tp.text({\n\t\t\t\t\t\t\tmessage: 'SMTP port',\n\t\t\t\t\t\t\tinitialValue: '587',\n\t\t\t\t\t\t\tvalidate: (v) => {\n\t\t\t\t\t\t\t\tif (!v) return 'Port is required';\n\t\t\t\t\t\t\t\tconst n = Number(v);\n\t\t\t\t\t\t\t\tif (!Number.isInteger(n) || n <= 0 || n > 65535) return 'Invalid port';\n\t\t\t\t\t\t\t\treturn undefined;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}),\n\t\t\t\t\tusername: () => p.text({ message: 'SMTP username' }),\n\t\t\t\t\tpassword: () => p.password({ message: 'SMTP password' })\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tonCancel: () => {\n\t\t\t\t\t\tp.cancel('Operation cancelled.');\n\t\t\t\t\t\tprocess.exit(0);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t);\n\n\t\t\tawait withPocketbase(workspaceRootDir, async (pb) => {\n\t\t\t\tawait pb.settings.update({\n\t\t\t\t\tsmtp: {\n\t\t\t\t\t\tenabled: true,\n\t\t\t\t\t\thost: config.host,\n\t\t\t\t\t\tport: parseInt(config.port, 10),\n\t\t\t\t\t\tusername: config.username ?? '',\n\t\t\t\t\t\tpassword: config.password ?? ''\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t});\n\n\t\t\treportResult({\n\t\t\t\tsummary: 'Enabled SMTP for transactional email.',\n\t\t\t\tnextSteps: [\n\t\t\t\t\t'PocketBase will now send auth/verification email via your SMTP server.',\n\t\t\t\t\t'Send a test email from the PocketBase admin UI (Settings \u2192 Mail settings).',\n\t\t\t\t\t'Run `vela disable smtp` to revert to the built-in fallback sender.'\n\t\t\t\t]\n\t\t\t});\n\t\t}, 'Failed to enable SMTP.')\n\t);\n", "import process from 'node:process';\nimport { Command } from 'commander';\nimport * as p from '@clack/prompts';\nimport pc from 'picocolors';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand } from '../../lib/run.ts';\nimport { runPattern } from '../../lib/pattern-runner.ts';\nimport { hasBackend } from '../../lib/workspace.ts';\n\nexport const cms = new Command('cms')\n\t.description('enable an inline-editing CMS with an admin bar')\n\t.allowUnknownOption(true)\n\t.configureHelp(helpConfig)\n\t.action((_opts, cmd) =>\n\t\trunCommand(async () => {\n\t\t\t// The command is exempt from the PocketBase guard \u2014 the CMS keeps its own\n\t\t\t// database \u2014 but the backend it installs runs inside the app's server,\n\t\t\t// which a static project does not have.\n\t\t\tif (!hasBackend()) {\n\t\t\t\tp.log.error(\n\t\t\t\t\t`${pc.cyan('vela enable cms')} needs a server to host the CMS backend, and this project is static.\\n\\n` +\n\t\t\t\t\t\t`Run ${pc.cyan('vela bless')} to add a backend first.`\n\t\t\t\t);\n\t\t\t\tp.log.message();\n\t\t\t\tp.cancel('Operation failed.');\n\t\t\t\tprocess.exitCode = 1;\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tawait runPattern(\n\t\t\t\t'enable-cms',\n\t\t\t\tcmd.args,\n\t\t\t\t{},\n\t\t\t\t{\n\t\t\t\t\tsummary: 'Enabled CMS.',\n\t\t\t\t\tnextSteps: [\n\t\t\t\t\t\t'Run `vela cms editor add you@example.com` to create the first editor login.',\n\t\t\t\t\t\t'Run `vela dev`, open any page with `?edit` on the URL, and sign in from the admin bar.',\n\t\t\t\t\t\t'Wrap page copy in `<CmsText>` and images in `<CmsImage>` to make them editable.'\n\t\t\t\t\t],\n\t\t\t\t\ttask: {\n\t\t\t\t\t\ttitle: 'Enabling CMS',\n\t\t\t\t\t\tsuccess: 'Enabled CMS',\n\t\t\t\t\t\terror: 'Failed to enable CMS'\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t);\n\t\t}, 'Failed to enable CMS.')\n\t);\n", "import { Command } from 'commander';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand } from '../../lib/run.ts';\nimport { runPattern } from '../../lib/pattern-runner.ts';\n\nexport const blog = new Command('blog')\n\t.description('enable an mdsvex blog with posts, tags, and RSS')\n\t.allowUnknownOption(true)\n\t.configureHelp(helpConfig)\n\t.action((_opts, cmd) =>\n\t\trunCommand(\n\t\t\t() =>\n\t\t\t\trunPattern(\n\t\t\t\t\t'enable-blog',\n\t\t\t\t\tcmd.args,\n\t\t\t\t\t{},\n\t\t\t\t\t{\n\t\t\t\t\t\tsummary: 'Enabled blog.',\n\t\t\t\t\t\tnextSteps: [\n\t\t\t\t\t\t\t'Run `vela dev` and visit /blog to see the example posts.',\n\t\t\t\t\t\t\t'Add new posts as .svx files in src/lib/content/blog/.',\n\t\t\t\t\t\t\t'Customize the post layout in src/routes/(public)/blog/[slug]/+page.svelte.'\n\t\t\t\t\t\t],\n\t\t\t\t\t\ttask: {\n\t\t\t\t\t\t\ttitle: 'Enabling blog',\n\t\t\t\t\t\t\tsuccess: 'Enabled blog',\n\t\t\t\t\t\t\terror: 'Failed to enable blog'\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t),\n\t\t\t'Failed to enable blog.'\n\t\t)\n\t);\n", "import { Command } from 'commander';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand } from '../../lib/run.ts';\nimport { runPattern } from '../../lib/pattern-runner.ts';\n\nexport const contentNegotiation = new Command('content-negotiation')\n\t.description('enable content negotiation (sveltekit-negotiate)')\n\t.allowUnknownOption(true)\n\t.configureHelp(helpConfig)\n\t.action((_opts, cmd) =>\n\t\trunCommand(\n\t\t\t() =>\n\t\t\t\trunPattern(\n\t\t\t\t\t'enable-content-negotiation',\n\t\t\t\t\tcmd.args,\n\t\t\t\t\t{},\n\t\t\t\t\t{\n\t\t\t\t\t\tsummary: 'Enabled content negotiation.',\n\t\t\t\t\t\tnextSteps: [\n\t\t\t\t\t\t\t'Create `+page.json.ts` / `+page.xml.ts` siblings alongside your routes to serve JSON/XML representations.',\n\t\t\t\t\t\t\t'Visit a page with `Accept: application/json` to verify content negotiation is wired up.'\n\t\t\t\t\t\t],\n\t\t\t\t\t\ttask: {\n\t\t\t\t\t\t\ttitle: 'Enabling content negotiation',\n\t\t\t\t\t\t\tsuccess: 'Enabled content negotiation',\n\t\t\t\t\t\t\terror: 'Failed to enable content negotiation'\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t),\n\t\t\t'Failed to enable content negotiation.'\n\t\t)\n\t);\n", "import { Command } from 'commander';\nimport { helpConfig } from '../lib/help.ts';\nimport { auth } from './disable/auth.ts';\nimport { api } from './disable/api.ts';\nimport { apiKeys } from './disable/api-keys.ts';\nimport { backend } from './disable/backend.ts';\nimport { contentNegotiation } from './disable/content-negotiation.ts';\nimport { i18n } from './disable/i18n.ts';\nimport { teams } from './disable/teams.ts';\nimport { payments } from './disable/payments.ts';\nimport { s3 } from './disable/s3.ts';\nimport { smtp } from './disable/smtp.ts';\n\nexport const disable = new Command('disable')\n\t.description('disable features')\n\t.configureHelp(helpConfig)\n\t.addCommand(auth)\n\t.addCommand(api)\n\t.addCommand(apiKeys)\n\t.addCommand(backend)\n\t.addCommand(contentNegotiation)\n\t.addCommand(i18n)\n\t.addCommand(teams)\n\t.addCommand(payments)\n\t.addCommand(s3)\n\t.addCommand(smtp);\n", "import { Command } from 'commander';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand, runDisable } from './_shared.ts';\n\nexport const auth = new Command('auth')\n\t.description('disable authentication')\n\t.option('-y, --yes', 'skip confirmation prompt')\n\t.allowUnknownOption(true)\n\t.configureHelp(helpConfig)\n\t.action((opts, cmd) =>\n\t\trunCommand(\n\t\t\t() =>\n\t\t\t\trunDisable(\n\t\t\t\t\t{\n\t\t\t\t\t\tslug: 'disable-auth',\n\t\t\t\t\t\tconfirmMessage:\n\t\t\t\t\t\t\t'Disable auth? Removes auth routes, drops oauth_accounts, and reverts layout/hooks edits. The users collection and existing accounts are preserved.',\n\t\t\t\t\t\treport: {\n\t\t\t\t\t\t\tsummary: 'Disabled authentication.',\n\t\t\t\t\t\t\tnextSteps: [\n\t\t\t\t\t\t\t\t'Users collection and accounts are kept. Drop them manually in the PocketBase admin if you no longer need them.'\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\ttask: {\n\t\t\t\t\t\t\t\ttitle: 'Disabling auth',\n\t\t\t\t\t\t\t\tsuccess: 'Disabled auth',\n\t\t\t\t\t\t\t\terror: 'Failed to disable auth'\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\topts,\n\t\t\t\t\tcmd.args\n\t\t\t\t),\n\t\t\t'Failed to disable auth.'\n\t\t)\n\t);\n", "import process from 'node:process';\nimport * as p from '@clack/prompts';\nimport type { Slug } from '@velastack/patterns';\nimport { runCommand } from '../../lib/run.ts';\nimport { runPattern, type PatternReport } from '../../lib/pattern-runner.ts';\n\nexport interface DisableOptions {\n\tslug: Slug;\n\tconfirmMessage: string;\n\treport: PatternReport;\n}\n\nexport async function runDisable(\n\topts: DisableOptions,\n\tflags: { yes?: boolean },\n\tcmdArgs: string[]\n): Promise<void> {\n\tif (!flags.yes) {\n\t\tconst ok = await p.confirm({\n\t\t\tmessage: opts.confirmMessage,\n\t\t\tinitialValue: false\n\t\t});\n\t\tif (p.isCancel(ok) || !ok) {\n\t\t\tp.cancel('Operation cancelled.');\n\t\t\tprocess.exit(0);\n\t\t}\n\t}\n\tawait runPattern(opts.slug, cmdArgs, { destructive: true }, opts.report);\n}\n\nexport { runCommand };\n", "import { Command } from 'commander';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand, runDisable } from './_shared.ts';\n\nexport const api = new Command('api')\n\t.description('disable the REST API')\n\t.option('-y, --yes', 'skip confirmation prompt')\n\t.allowUnknownOption(true)\n\t.configureHelp(helpConfig)\n\t.action((opts, cmd) =>\n\t\trunCommand(\n\t\t\t() =>\n\t\t\t\trunDisable(\n\t\t\t\t\t{\n\t\t\t\t\t\tslug: 'disable-api',\n\t\t\t\t\t\tconfirmMessage: 'Disable the REST API? Removes the PocketBase API handler.',\n\t\t\t\t\t\treport: {\n\t\t\t\t\t\t\tsummary: 'Disabled the REST API.',\n\t\t\t\t\t\t\ttask: {\n\t\t\t\t\t\t\t\ttitle: 'Disabling API',\n\t\t\t\t\t\t\t\tsuccess: 'Disabled API',\n\t\t\t\t\t\t\t\terror: 'Failed to disable API'\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\topts,\n\t\t\t\t\tcmd.args\n\t\t\t\t),\n\t\t\t'Failed to disable API.'\n\t\t)\n\t);\n", "import { Command } from 'commander';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand, runDisable } from './_shared.ts';\n\nexport const apiKeys = new Command('api-keys')\n\t.description('disable API key management')\n\t.option('-y, --yes', 'skip confirmation prompt')\n\t.allowUnknownOption(true)\n\t.configureHelp(helpConfig)\n\t.action((opts, cmd) =>\n\t\trunCommand(\n\t\t\t() =>\n\t\t\t\trunDisable(\n\t\t\t\t\t{\n\t\t\t\t\t\tslug: 'disable-api-keys',\n\t\t\t\t\t\tconfirmMessage:\n\t\t\t\t\t\t\t'Disable API key management? Drops the api_keys collection, reverts hooks.server and nav-user, and removes generated API key routes.',\n\t\t\t\t\t\treport: {\n\t\t\t\t\t\t\tsummary: 'Disabled API key management.',\n\t\t\t\t\t\t\ttask: {\n\t\t\t\t\t\t\t\ttitle: 'Disabling API keys',\n\t\t\t\t\t\t\t\tsuccess: 'Disabled API keys',\n\t\t\t\t\t\t\t\terror: 'Failed to disable API keys'\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\topts,\n\t\t\t\t\tcmd.args\n\t\t\t\t),\n\t\t\t'Failed to disable API keys.'\n\t\t)\n\t);\n", "import { Command } from 'commander';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand, runDisable } from './_shared.ts';\n\nexport const backend = new Command('backend')\n\t.description('disable the PocketBase backend')\n\t.option('-y, --yes', 'skip confirmation prompt')\n\t.allowUnknownOption(true)\n\t.configureHelp(helpConfig)\n\t.action((opts, cmd) =>\n\t\trunCommand(\n\t\t\t() =>\n\t\t\t\trunDisable(\n\t\t\t\t\t{\n\t\t\t\t\t\tslug: 'disable-backend',\n\t\t\t\t\t\tconfirmMessage:\n\t\t\t\t\t\t\t'Disable the PocketBase backend? Removes hooks.server.ts, the data/ scaffold, and reverts the SvelteKit adapter. The @velastack/pocketbase and pocketbase-sveltekit packages stay installed.',\n\t\t\t\t\t\treport: {\n\t\t\t\t\t\t\tsummary: 'Disabled the PocketBase backend.',\n\t\t\t\t\t\t\ttask: {\n\t\t\t\t\t\t\t\ttitle: 'Disabling backend',\n\t\t\t\t\t\t\t\tsuccess: 'Disabled backend',\n\t\t\t\t\t\t\t\terror: 'Failed to disable backend'\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\topts,\n\t\t\t\t\tcmd.args\n\t\t\t\t),\n\t\t\t'Failed to disable backend.'\n\t\t)\n\t);\n", "import { Command } from 'commander';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand, runDisable } from './_shared.ts';\n\nexport const contentNegotiation = new Command('content-negotiation')\n\t.description('disable content negotiation')\n\t.option('-y, --yes', 'skip confirmation prompt')\n\t.allowUnknownOption(true)\n\t.configureHelp(helpConfig)\n\t.action((opts, cmd) =>\n\t\trunCommand(\n\t\t\t() =>\n\t\t\t\trunDisable(\n\t\t\t\t\t{\n\t\t\t\t\t\tslug: 'disable-content-negotiation',\n\t\t\t\t\t\tconfirmMessage:\n\t\t\t\t\t\t\t'Disable content negotiation? Unwraps hooks.server handle, reverts reroute, and removes <Negotiate /> from the root layout.',\n\t\t\t\t\t\treport: {\n\t\t\t\t\t\t\tsummary: 'Disabled content negotiation.',\n\t\t\t\t\t\t\ttask: {\n\t\t\t\t\t\t\t\ttitle: 'Disabling content negotiation',\n\t\t\t\t\t\t\t\tsuccess: 'Disabled content negotiation',\n\t\t\t\t\t\t\t\terror: 'Failed to disable content negotiation'\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\topts,\n\t\t\t\t\tcmd.args\n\t\t\t\t),\n\t\t\t'Failed to disable content negotiation.'\n\t\t)\n\t);\n", "import { Command } from 'commander';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand, runDisable } from './_shared.ts';\n\nexport const i18n = new Command('i18n')\n\t.description('disable internationalization')\n\t.option('-y, --yes', 'skip confirmation prompt')\n\t.allowUnknownOption(true)\n\t.configureHelp(helpConfig)\n\t.action((opts, cmd) =>\n\t\trunCommand(\n\t\t\t() =>\n\t\t\t\trunDisable(\n\t\t\t\t\t{\n\t\t\t\t\t\tslug: 'disable-i18n',\n\t\t\t\t\t\tconfirmMessage:\n\t\t\t\t\t\t\t'Disable i18n? Removes i18n scaffolding files and the Wuchale .gitignore block. Manual reverts are still required in vite.config, svelte.config, hooks.server, app.html, and +layout.ts.',\n\t\t\t\t\t\treport: {\n\t\t\t\t\t\t\tsummary: 'Disabled i18n scaffolding.',\n\t\t\t\t\t\t\tnextSteps: [\n\t\t\t\t\t\t\t\t'Manually revert the Wuchale wiring in vite.config, svelte.config, hooks.server, app.html, and +layout.ts.'\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\ttask: {\n\t\t\t\t\t\t\t\ttitle: 'Disabling i18n',\n\t\t\t\t\t\t\t\tsuccess: 'Disabled i18n',\n\t\t\t\t\t\t\t\terror: 'Failed to disable i18n'\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\topts,\n\t\t\t\t\tcmd.args\n\t\t\t\t),\n\t\t\t'Failed to disable i18n.'\n\t\t)\n\t);\n", "import { Command } from 'commander';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand, runDisable } from './_shared.ts';\n\nexport const teams = new Command('teams')\n\t.description('disable teams')\n\t.option('-y, --yes', 'skip confirmation prompt')\n\t.allowUnknownOption(true)\n\t.configureHelp(helpConfig)\n\t.action((opts, cmd) =>\n\t\trunCommand(\n\t\t\t() =>\n\t\t\t\trunDisable(\n\t\t\t\t\t{\n\t\t\t\t\t\tslug: 'disable-teams',\n\t\t\t\t\t\tconfirmMessage:\n\t\t\t\t\t\t\t'Disable teams? Drops teams, team_memberships, team_invites, and team_invite_links collections and removes team routes. app-sidebar and +layout.server.ts must be reverted manually.',\n\t\t\t\t\t\treport: {\n\t\t\t\t\t\t\tsummary: 'Disabled teams.',\n\t\t\t\t\t\t\tnextSteps: [\n\t\t\t\t\t\t\t\t'Manually revert the Teams nav item in app-sidebar and any team context loading in +layout.server.ts.'\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\ttask: {\n\t\t\t\t\t\t\t\ttitle: 'Disabling teams',\n\t\t\t\t\t\t\t\tsuccess: 'Disabled teams',\n\t\t\t\t\t\t\t\terror: 'Failed to disable teams'\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\topts,\n\t\t\t\t\tcmd.args\n\t\t\t\t),\n\t\t\t'Failed to disable teams.'\n\t\t)\n\t);\n", "import { Command } from 'commander';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand, runDisable } from './_shared.ts';\n\nexport const payments = new Command('payments')\n\t.description('disable payments')\n\t.option('-y, --yes', 'skip confirmation prompt')\n\t.allowUnknownOption(true)\n\t.configureHelp(helpConfig)\n\t.action((opts, cmd) =>\n\t\trunCommand(\n\t\t\t() =>\n\t\t\t\trunDisable(\n\t\t\t\t\t{\n\t\t\t\t\t\tslug: 'disable-payments',\n\t\t\t\t\t\tconfirmMessage:\n\t\t\t\t\t\t\t'Disable payments? Drops Stripe collections, strips Stripe env credentials, reverts nav/signup edits, and removes generated payment files. Stripe dashboard products/prices and the stripe packages are untouched.',\n\t\t\t\t\t\treport: {\n\t\t\t\t\t\t\tsummary: 'Disabled payments.',\n\t\t\t\t\t\t\tnextSteps: [\n\t\t\t\t\t\t\t\t'Products and prices in the Stripe dashboard are not deleted \u2014 archive them there if you no longer need them.',\n\t\t\t\t\t\t\t\t'The stripe and @stripe/stripe-js packages remain installed. Uninstall them manually if desired.'\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\ttask: {\n\t\t\t\t\t\t\t\ttitle: 'Disabling payments',\n\t\t\t\t\t\t\t\tsuccess: 'Disabled payments',\n\t\t\t\t\t\t\t\terror: 'Failed to disable payments'\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\topts,\n\t\t\t\t\tcmd.args\n\t\t\t\t),\n\t\t\t'Failed to disable payments.'\n\t\t)\n\t);\n", "import { Command } from 'commander';\nimport * as p from '@clack/prompts';\nimport pc from 'picocolors';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand } from '../../lib/run.ts';\nimport { reportResult } from '../../lib/result-report.ts';\nimport { addTargetOptions } from '../../lib/server-command.ts';\nimport { withBackupTarget } from '../../lib/backup-target.ts';\nimport { disableS3, readS3, type S3Filesystem } from '../../lib/s3-settings.ts';\n\nexport const s3 = addTargetOptions(\n\tnew Command('s3')\n\t\t.description('disable S3 file storage')\n\t\t.option('--backups', 'keep backups on the server again, rather than uploads')\n\t\t.configureHelp(helpConfig),\n\t'local'\n).action((raw: unknown) =>\n\trunCommand(() => {\n\t\tconst options = raw as { backups?: boolean };\n\t\tconst filesystem: S3Filesystem = options.backups ? 'backups' : 'storage';\n\n\t\treturn withBackupTarget(raw, 'disable s3', async (ctx) => {\n\t\t\tconst existing = await readS3(ctx.pb, filesystem);\n\t\t\tif (!existing.enabled) {\n\t\t\t\tp.log.info(`S3 ${label(filesystem)} is already off for ${ctx.targetName}.`);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tawait disableS3(ctx.pb, filesystem);\n\n\t\t\treportResult({\n\t\t\t\tsummary: `Disabled S3 ${label(filesystem)} on ${ctx.targetName}.`,\n\t\t\t\tnextSteps:\n\t\t\t\t\tfilesystem === 'backups'\n\t\t\t\t\t\t? ['New backups are written to the server again.']\n\t\t\t\t\t\t: [\n\t\t\t\t\t\t\t\t`Anything uploaded while S3 was on is still in ${pc.cyan(existing.bucket || 'the bucket')} and will now 404.`,\n\t\t\t\t\t\t\t\t'Copy it back first if you need it: `rclone copy <remote>:<bucket>/ <storage dir>/`.',\n\t\t\t\t\t\t\t\t'The credentials are kept, so `vela enable s3` does not mean retyping them.'\n\t\t\t\t\t\t\t]\n\t\t\t});\n\t\t});\n\t}, 'Failed to disable S3.')\n);\n\nfunction label(filesystem: S3Filesystem): string {\n\treturn filesystem === 'backups' ? 'backup storage' : 'file storage';\n}\n", "import { Command } from 'commander';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand } from '../../lib/run.ts';\nimport { withPocketbase } from '../../lib/pocketbase.ts';\nimport { getWorkspace } from '../../lib/workspace.ts';\nimport { reportResult } from '../../lib/result-report.ts';\n\nexport const smtp = new Command('smtp')\n\t.description('disable SMTP configuration')\n\t.configureHelp(helpConfig)\n\t.action(() =>\n\t\trunCommand(async () => {\n\t\t\tconst { workspaceRootDir } = await getWorkspace();\n\n\t\t\tawait withPocketbase(workspaceRootDir, async (pb) => {\n\t\t\t\tawait pb.settings.update({ smtp: { enabled: false } });\n\t\t\t});\n\n\t\t\treportResult({\n\t\t\t\tsummary: 'Disabled SMTP.',\n\t\t\t\tnextSteps: [\n\t\t\t\t\t'PocketBase will fall back to the built-in sender for transactional email.',\n\t\t\t\t\t'Run `vela enable smtp` to reconfigure.'\n\t\t\t\t]\n\t\t\t});\n\t\t}, 'Failed to disable SMTP.')\n\t);\n", "import { Command } from 'commander';\nimport { helpConfig } from '../lib/help.ts';\nimport { form } from './destroy/form.ts';\nimport { schema } from './destroy/schema.ts';\nimport { resource } from './destroy/resource.ts';\nimport { scaffold } from './destroy/scaffold.ts';\nimport { deployment } from './destroy/deployment.ts';\n\nexport const destroy = new Command('destroy')\n\t.description('destroy scaffolding, or a deployment')\n\t.configureHelp(helpConfig)\n\t.addCommand(form)\n\t.addCommand(schema)\n\t.addCommand(resource)\n\t.addCommand(scaffold)\n\t.addCommand(deployment);\n", "import { Command } from 'commander';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand, runDestroy } from './_shared.ts';\n\nexport const form = new Command('form')\n\t.description('destroy a form generated by `vela generate form`')\n\t.argument('<model>', 'model name used when the form was generated (e.g., contact, login)')\n\t.option('-y, --yes', 'skip confirmation prompt')\n\t.option(\n\t\t'--route <route>',\n\t\t'custom route the form was generated at (must match the --route used at generation)'\n\t)\n\t.allowUnknownOption(true)\n\t.configureHelp(helpConfig)\n\t.action((model: string, opts: { yes?: boolean; route?: string }) =>\n\t\trunCommand(\n\t\t\t() =>\n\t\t\t\trunDestroy(\n\t\t\t\t\t'destroy-form',\n\t\t\t\t\tmodel,\n\t\t\t\t\t`Destroy form \"${model}\"? Removes the route directory and the schema file.`,\n\t\t\t\t\t{\n\t\t\t\t\t\tsummary: `Destroyed form \"${model}\".`,\n\t\t\t\t\t\ttask: {\n\t\t\t\t\t\t\ttitle: `Destroying form \"${model}\"`,\n\t\t\t\t\t\t\tsuccess: `Destroyed form \"${model}\"`,\n\t\t\t\t\t\t\terror: `Failed to destroy form \"${model}\"`\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\topts\n\t\t\t\t),\n\t\t\t'Failed to destroy form.'\n\t\t)\n\t);\n", "import process from 'node:process';\nimport * as p from '@clack/prompts';\nimport type { Slug } from '@velastack/patterns';\nimport { runCommand } from '../../lib/run.ts';\nimport { runPattern, type PatternReport } from '../../lib/pattern-runner.ts';\n\nexport async function runDestroy(\n\tslug: Slug,\n\tmodel: string,\n\tconfirmMessage: string,\n\treport: PatternReport,\n\tflags: { yes?: boolean; route?: string }\n): Promise<void> {\n\tif (!flags.yes) {\n\t\tconst ok = await p.confirm({ message: confirmMessage, initialValue: false });\n\t\tif (p.isCancel(ok) || !ok) {\n\t\t\tp.cancel('Operation cancelled.');\n\t\t\tprocess.exit(0);\n\t\t}\n\t}\n\tawait runPattern(slug, [model], { destructive: true, route: flags.route }, report);\n}\n\nexport { runCommand };\n", "import { Command } from 'commander';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand, runDestroy } from './_shared.ts';\n\nexport const schema = new Command('schema')\n\t.description('destroy a zod schema generated by `vela generate schema`')\n\t.argument('<model>', 'schema model name (e.g., contact, login)')\n\t.option('-y, --yes', 'skip confirmation prompt')\n\t.allowUnknownOption(true)\n\t.configureHelp(helpConfig)\n\t.action((model: string, opts) =>\n\t\trunCommand(\n\t\t\t() =>\n\t\t\t\trunDestroy(\n\t\t\t\t\t'destroy-schema',\n\t\t\t\t\tmodel,\n\t\t\t\t\t`Destroy schema \"${model}\"? Removes the zod schema file.`,\n\t\t\t\t\t{\n\t\t\t\t\t\tsummary: `Destroyed schema \"${model}\".`,\n\t\t\t\t\t\ttask: {\n\t\t\t\t\t\t\ttitle: `Destroying schema \"${model}\"`,\n\t\t\t\t\t\t\tsuccess: `Destroyed schema \"${model}\"`,\n\t\t\t\t\t\t\terror: `Failed to destroy schema \"${model}\"`\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\topts\n\t\t\t\t),\n\t\t\t'Failed to destroy schema.'\n\t\t)\n\t);\n", "import { Command } from 'commander';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand, runDestroy } from './_shared.ts';\n\nexport const resource = new Command('resource')\n\t.description('destroy a resource generated by `vela generate resource`')\n\t.argument('<model>', 'model path used when the resource was generated (e.g., contacts, articles)')\n\t.option('-y, --yes', 'skip confirmation prompt')\n\t.allowUnknownOption(true)\n\t.configureHelp(helpConfig)\n\t.action((model: string, opts) =>\n\t\trunCommand(\n\t\t\t() =>\n\t\t\t\trunDestroy(\n\t\t\t\t\t'destroy-resource',\n\t\t\t\t\tmodel,\n\t\t\t\t\t`Destroy resource \"${model}\"? Drops the collection and removes the schema file.`,\n\t\t\t\t\t{\n\t\t\t\t\t\tsummary: `Destroyed resource \"${model}\".`,\n\t\t\t\t\t\ttask: {\n\t\t\t\t\t\t\ttitle: `Destroying resource \"${model}\"`,\n\t\t\t\t\t\t\tsuccess: `Destroyed resource \"${model}\"`,\n\t\t\t\t\t\t\terror: `Failed to destroy resource \"${model}\"`\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\topts\n\t\t\t\t),\n\t\t\t'Failed to destroy resource.'\n\t\t)\n\t);\n", "import { Command } from 'commander';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand, runDestroy } from './_shared.ts';\n\nexport const scaffold = new Command('scaffold')\n\t.description('destroy a scaffold generated by `vela generate scaffold`')\n\t.argument('<model>', 'model name used when the scaffold was generated (e.g., contact, todo)')\n\t.option('-y, --yes', 'skip confirmation prompt')\n\t.option(\n\t\t'--route <route>',\n\t\t'custom route the scaffold was generated at (must match the --route used at generation)'\n\t)\n\t.allowUnknownOption(true)\n\t.configureHelp(helpConfig)\n\t.action((model: string, opts: { yes?: boolean; route?: string }) =>\n\t\trunCommand(\n\t\t\t() =>\n\t\t\t\trunDestroy(\n\t\t\t\t\t'destroy-scaffold',\n\t\t\t\t\tmodel,\n\t\t\t\t\t`Destroy scaffold \"${model}\"? Removes the route directory, schema file, and drops the collection. Shadcn components are retained.`,\n\t\t\t\t\t{\n\t\t\t\t\t\tsummary: `Destroyed scaffold \"${model}\".`,\n\t\t\t\t\t\tnextSteps: [\n\t\t\t\t\t\t\t'Shadcn components added during scaffolding are preserved \u2014 remove them manually if nothing else uses them.'\n\t\t\t\t\t\t],\n\t\t\t\t\t\ttask: {\n\t\t\t\t\t\t\ttitle: `Destroying scaffold \"${model}\"`,\n\t\t\t\t\t\t\tsuccess: `Destroyed scaffold \"${model}\"`,\n\t\t\t\t\t\t\terror: `Failed to destroy scaffold \"${model}\"`\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\topts\n\t\t\t\t),\n\t\t\t'Failed to destroy scaffold.'\n\t\t)\n\t);\n", "import process from 'node:process';\nimport { Command } from 'commander';\nimport * as p from '@clack/prompts';\nimport pc from 'picocolors';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand } from '../../lib/run.ts';\nimport { addTargetOptions, withTarget } from '../../lib/server-command.ts';\nimport { runServerScript } from '../../lib/remote.ts';\nimport { isProd } from '../../lib/instance.ts';\n\nexport const deployment = addTargetOptions(\n\tnew Command('deployment')\n\t\t.description('remove a deployed environment from its server')\n\t\t.configureHelp(helpConfig),\n\t'production'\n)\n\t.option('--purge', 'also delete the database and uploaded files')\n\t.option('-y, --yes', 'skip the confirmation prompt')\n\t.action((raw: unknown) =>\n\t\trunCommand(async () => {\n\t\t\tconst options = raw as { purge?: boolean; yes?: boolean };\n\t\t\tawait withTarget(\n\t\t\t\traw,\n\t\t\t\t{\n\t\t\t\t\tremote: async (ctx) => {\n\t\t\t\t\t\t// Production is the one you cannot get back by redeploying, so it\n\t\t\t\t\t\t// always asks, and `--purge` on it asks for the name in full.\n\t\t\t\t\t\tif (!options.yes) {\n\t\t\t\t\t\t\tawait confirm(ctx.appName, ctx.targetName, ctx.envTag, options.purge === true);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst result = await runServerScript<{ purged: boolean }>(ctx.session, 'destroy.sh', {\n\t\t\t\t\t\t\targs: [ctx.instance, ...(options.purge ? ['--purge'] : [])],\n\t\t\t\t\t\t\tstream: true\n\t\t\t\t\t\t});\n\n\t\t\t\t\t\tp.log.success(\n\t\t\t\t\t\t\t`Removed ${pc.cyan(`${ctx.appName} (${ctx.targetName})`)} from ${ctx.server}.` +\n\t\t\t\t\t\t\t\t(result?.purged\n\t\t\t\t\t\t\t\t\t? ''\n\t\t\t\t\t\t\t\t\t: `\\n\\nThe database and uploads are still in the instance's shared directory. Pass ${pc.cyan('--purge')} to delete them.`)\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tlabel: 'destroy deployment',\n\t\t\t\t\tlocalHint: 'There is nothing deployed locally to remove.'\n\t\t\t\t}\n\t\t\t);\n\t\t}, 'Failed to remove the deployment.')\n\t);\n\nasync function confirm(\n\tappName: string,\n\ttargetName: string,\n\tenvTag: string,\n\tpurge: boolean\n): Promise<void> {\n\tif (isProd(envTag) || purge) {\n\t\tconst answer = await p.text({\n\t\t\tmessage: `This removes ${pc.cyan(`${appName} (${targetName})`)}${purge ? ' and its database' : ''}. Type the app name to confirm`,\n\t\t\tvalidate: (value) => (value === appName ? undefined : `Type ${appName} to confirm`)\n\t\t});\n\t\tif (p.isCancel(answer)) {\n\t\t\tp.cancel('Operation cancelled.');\n\t\t\tprocess.exit(0);\n\t\t}\n\t\treturn;\n\t}\n\n\tconst ok = await p.confirm({\n\t\tmessage: `Remove ${appName} (${targetName})?`,\n\t\tinitialValue: false\n\t});\n\tif (p.isCancel(ok) || !ok) {\n\t\tp.cancel('Operation cancelled.');\n\t\tprocess.exit(0);\n\t}\n}\n", "import { Command } from 'commander';\nimport { helpConfig } from '../lib/help.ts';\nimport { add } from './ui/add.ts';\nimport { base } from './ui/base.ts';\n\nexport const ui = new Command('ui')\n\t.description('generate ui components')\n\t.configureHelp(helpConfig)\n\t.addCommand(add)\n\t.addCommand(base);\n", "import { Command } from 'commander';\nimport { exec, NonZeroExitError } from 'tinyexec';\nimport { detect, resolveCommand } from 'package-manager-detector';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand } from '../../lib/run.ts';\nimport { getWorkspace } from '../../lib/workspace.ts';\nimport { reportResult } from '../../lib/result-report.ts';\n\nexport const add = new Command('add')\n\t.description('add ui components')\n\t.argument('<components...>', 'the components to add')\n\t.configureHelp(helpConfig)\n\t.action((components: string[]) =>\n\t\trunCommand(async () => {\n\t\t\tconst { workspaceRootDir } = await getWorkspace();\n\t\t\tconst packageManager = (await detect({ cwd: workspaceRootDir }))?.name ?? 'npm';\n\t\t\tconst resolved = resolveCommand(packageManager, 'execute', [\n\t\t\t\t'shadcn-svelte',\n\t\t\t\t'add',\n\t\t\t\t...components\n\t\t\t]);\n\t\t\tif (!resolved) {\n\t\t\t\tthrow new Error(`Unable to resolve execute command for ${packageManager}`);\n\t\t\t}\n\n\t\t\tconst args = [...resolved.args];\n\t\t\tif (packageManager === 'npm') args.unshift('--yes');\n\n\t\t\ttry {\n\t\t\t\tawait exec(resolved.command, args, {\n\t\t\t\t\tnodeOptions: { cwd: workspaceRootDir, stdio: 'inherit' },\n\t\t\t\t\tthrowOnError: true\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\tconst typed = error as NonZeroExitError;\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Failed to execute '${resolved.command} ${args.join(' ')}': ${typed.message}`,\n\t\t\t\t\t{ cause: typed.output }\n\t\t\t\t);\n\t\t\t}\n\n\t\t\treportResult({\n\t\t\t\tsummary: `Added ${components.length} UI component(s).`,\n\t\t\t\tcomponentsAdded: components,\n\t\t\t\tnextSteps: [\n\t\t\t\t\t`Import a component with: import { Button } from '$lib/components/ui/button';`,\n\t\t\t\t\t'Tweak styling in src/lib/components/ui/<component>/*.svelte.',\n\t\t\t\t\t'Run `vela ui base <color>` to change the palette (slate, gray, zinc, stone, neutral).'\n\t\t\t\t]\n\t\t\t});\n\t\t}, 'Failed to add UI components.')\n\t);\n", "import fs from 'node:fs';\nimport path from 'node:path';\nimport { Command, InvalidArgumentError } from 'commander';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand } from '../../lib/run.ts';\nimport { getWorkspace } from '../../lib/workspace.ts';\nimport { reportResult } from '../../lib/result-report.ts';\nimport { templatesDir } from '../../lib/templates.ts';\n\nconst VALID_COLORS = ['slate', 'gray', 'zinc', 'stone', 'neutral'] as const;\ntype BaseColor = (typeof VALID_COLORS)[number];\n\nfunction findThemeFile(color: BaseColor): string {\n\tconst candidate = path.join(templatesDir(), 'ui', 'css', `${color}.css`);\n\tif (!fs.existsSync(candidate)) {\n\t\tthrow new Error(`Theme file not found for color: ${color}`);\n\t}\n\treturn candidate;\n}\n\nfunction extractSelectors(css: string): { root: string; dark: string } {\n\tconst rootMatch = css.match(/:root\\s*{[^}]*}/);\n\tconst darkMatch = css.match(/\\.dark\\s*{[^}]*}/);\n\tif (!rootMatch || !darkMatch) {\n\t\tthrow new Error('Invalid theme file: missing :root or .dark selector');\n\t}\n\treturn { root: rootMatch[0], dark: darkMatch[0] };\n}\n\nfunction applyTheme(appCss: string, selectors: { root: string; dark: string }): string {\n\tlet out = appCss;\n\tout = out.match(/:root\\s*{[^}]*}/)\n\t\t? out.replace(/:root\\s*{[^}]*}/, selectors.root)\n\t\t: `${selectors.root}\\n\\n${out}`;\n\tout = out.match(/\\.dark\\s*{[^}]*}/)\n\t\t? out.replace(/\\.dark\\s*{[^}]*}/, selectors.dark)\n\t\t: `${out}\\n\\n${selectors.dark}`;\n\treturn out;\n}\n\nexport const base = new Command('base')\n\t.description('change the base color')\n\t.argument('<color>', 'base color to use', (value) => {\n\t\tif (!(VALID_COLORS as readonly string[]).includes(value)) {\n\t\t\tthrow new InvalidArgumentError(`Valid colors are: ${VALID_COLORS.join(', ')}`);\n\t\t}\n\t\treturn value as BaseColor;\n\t})\n\t.configureHelp(helpConfig)\n\t.action((color: BaseColor) =>\n\t\trunCommand(async () => {\n\t\t\tconst { workspaceRootDir } = await getWorkspace();\n\t\t\tconst appCssPath = path.join(workspaceRootDir, 'src', 'app.css');\n\t\t\tif (!fs.existsSync(appCssPath)) {\n\t\t\t\tthrow new Error(`Could not find ${path.relative(workspaceRootDir, appCssPath)}`);\n\t\t\t}\n\n\t\t\tconst themeContent = fs.readFileSync(findThemeFile(color), 'utf8');\n\t\t\tconst selectors = extractSelectors(themeContent);\n\t\t\tconst appCss = fs.readFileSync(appCssPath, 'utf8');\n\t\t\tfs.writeFileSync(appCssPath, applyTheme(appCss, selectors));\n\n\t\t\treportResult({\n\t\t\t\tsummary: `Set base color to ${color}.`,\n\t\t\t\tfilesModified: [path.relative(workspaceRootDir, appCssPath)],\n\t\t\t\tnextSteps: [\n\t\t\t\t\t'Run your dev server to preview the new palette.',\n\t\t\t\t\t'Tweak individual CSS variables in src/app.css if you want to customize the theme further.'\n\t\t\t\t]\n\t\t\t});\n\t\t}, 'Failed to change base color.')\n\t);\n", "import { Command } from 'commander';\nimport { helpConfig } from '../lib/help.ts';\nimport { terms } from './legal/terms.ts';\nimport { privacy } from './legal/privacy.ts';\n\nexport const legal = new Command('legal')\n\t.description('generate placeholder legal documents')\n\t.configureHelp(helpConfig)\n\t.addCommand(terms)\n\t.addCommand(privacy);\n", "import fs from 'node:fs';\nimport path from 'node:path';\nimport { Command } from 'commander';\nimport * as p from '@clack/prompts';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand } from '../../lib/run.ts';\nimport { getWorkspace } from '../../lib/workspace.ts';\nimport { LEGAL_DIR } from '../../lib/constants.ts';\nimport { reportResult } from '../../lib/result-report.ts';\nimport {\n\tarbitrationBlock,\n\tcontactMethods,\n\tdmcaBlock,\n\tescapeHtml,\n\tlist,\n\tonCancel,\n\tpageMetaTagsLoader,\n\tsharedFields,\n\ttitledSection,\n\ttype LegalCoreAnswers\n} from './shared.ts';\n\ntype TermsAnswers = {\n\tcore: LegalCoreAnswers;\n\taccounts: 'yes' | 'no';\n\tuserContent: 'yes' | 'no';\n\tinfringementEmail?: string;\n\tcanBuyGoods: 'yes' | 'no';\n\tsubscriptions: 'yes' | 'no';\n\tfreeTrial?: 'yes' | 'no';\n\texclusiveContent: 'yes' | 'no';\n\tfeedbackReuse: 'yes' | 'no';\n\tpromotions: 'yes' | 'no';\n\tmobileApp: Array<'apple' | 'google'>;\n\tcontact: { methods: string[]; details: Record<string, unknown> };\n};\n\ntype Computed = {\n\tcompanyName: string;\n\tcompanyLong: string;\n\twebsiteName: string;\n\twebsiteUrl: string;\n\tgoverningLocation: string;\n\teffectiveDate: string;\n};\n\nconst compute = (a: TermsAnswers): Computed => {\n\tconst effectiveDate = new Date(Date.now()).toLocaleDateString('en-US', {\n\t\tyear: 'numeric',\n\t\tmonth: 'long',\n\t\tday: 'numeric'\n\t});\n\tconst websiteName = a.core?.websiteName ?? 'our website';\n\tconst websiteUrl = a.core?.websiteUrl ?? '';\n\tconst companyName =\n\t\ta.core?.entityType === 'business'\n\t\t\t? (a.core?.businessName ?? websiteName)\n\t\t\t: (a.core?.websiteName ?? 'the website owner');\n\tconst companyLong =\n\t\ta.core?.entityType === 'business'\n\t\t\t? `${escapeHtml(a.core?.businessName ?? websiteName)}${\n\t\t\t\t\ta.core?.businessAddress ? `, ${escapeHtml(a.core?.businessAddress)}` : ''\n\t\t\t\t}`\n\t\t\t: 'the website owner';\n\tconst governingLocation = `${escapeHtml(a.core?.state ?? '')}${a.core?.state ? ', ' : ''}${escapeHtml(\n\t\ta.core?.country ?? ''\n\t)}`;\n\n\treturn {\n\t\tcompanyName,\n\t\tcompanyLong,\n\t\twebsiteName,\n\t\twebsiteUrl,\n\t\tgoverningLocation,\n\t\teffectiveDate\n\t};\n};\n\nconst sectionHeader = (c: Computed) =>\n\t`<section class=\"space-y-3\"><h1 class=\"text-3xl font-semibold\">Terms &amp; Conditions</h1><p class=\"text-base leading-7\">Last updated: ${escapeHtml(\n\t\tc.effectiveDate\n\t)}</p><p class=\"text-base leading-7\">These Terms &amp; Conditions (\"Terms\") govern your access to and use of ${escapeHtml(\n\t\tc.websiteName\n\t)} (${escapeHtml(c.websiteUrl)}) and any related software, mobile applications, content, products, and services (collectively, the \"Service\"). The Service is provided by ${\n\t\tc.companyLong\n\t} (\"Company\", \"we\", \"us\", or \"our\").</p><p class=\"text-base leading-7\">By accessing or using the Service, you agree to be bound by these Terms and our Privacy Policy. If you do not agree to these Terms, you must not access or use the Service. Your continued use of the Service after we post or send a notice about changes to these Terms means you accept and agree to the changes.</p></section>`;\n\nconst sectionEligibility = () =>\n\ttitledSection(\n\t\t'Eligibility and Age',\n\t\t'<p>You must be at least 13 years of age to use the Service (or 16 years of age if you are a resident of the European Economic Area, the United Kingdom, or another jurisdiction whose laws require a higher minimum age). By using the Service, you represent and warrant that you meet the minimum age requirement, that you have the legal capacity to enter into a binding agreement, and that you are not prohibited from receiving the Service under the laws of any applicable jurisdiction.</p><p>If you are using the Service on behalf of a company, organization, or other legal entity, you represent that you are authorized to bind that entity to these Terms, in which case \"you\" and \"your\" refer to that entity.</p>'\n\t);\n\nconst sectionDefinitions = (c: Computed) =>\n\ttitledSection(\n\t\t'Definitions',\n\t\t`<p>The following definitions apply throughout these Terms:</p><ul><li><strong>Service</strong> means ${escapeHtml(\n\t\t\tc.websiteName\n\t\t)}, our website at <a href=\"${escapeHtml(\n\t\t\tc.websiteUrl\n\t\t)}\" rel=\"external nofollow noopener\" target=\"_blank\">${escapeHtml(\n\t\t\tc.websiteUrl\n\t\t)}</a>, and any related applications, software, content, and online services we provide.</li><li><strong>Content</strong> means any information, text, graphics, images, music, audio, video, code, or other material that is made available through the Service, whether by us, our licensors, our users, or third parties.</li><li><strong>User Content</strong> means any Content that you or other users submit, upload, post, transmit, or otherwise make available through the Service.</li><li><strong>You</strong> and <strong>your</strong> refer to the individual or entity that accesses or uses the Service.</li></ul>`\n\t);\n\nconst sectionLicense = () =>\n\ttitledSection(\n\t\t'License to Use the Service',\n\t\t'<p>Subject to your compliance with these Terms, we grant you a limited, revocable, non-exclusive, non-transferable, non-sublicensable license to access and use the Service for your personal or internal business use. This license does not include any right to: (a) sell, resell, or commercially exploit the Service or its Content; (b) modify, adapt, translate, reverse engineer, decompile, or disassemble any portion of the Service; (c) use the Service or its Content in any manner that infringes our or any third party\u2019s rights; or (d) use any data mining, robots, or similar data gathering or extraction methods. We reserve all rights not expressly granted to you.</p>'\n\t);\n\nconst sectionAccounts = () =>\n\ttitledSection(\n\t\t'Accounts',\n\t\t'<p>To access certain features of the Service, you may be required to create an account. You agree to provide accurate, complete, and current information at all times and to update your information to keep it accurate, complete, and current. You are responsible for safeguarding your password and for any activities or actions taken under your account, whether or not you have authorized those activities. You agree not to disclose your password to any third party and to notify us immediately upon becoming aware of any breach of security or unauthorized use of your account. We may, in our sole discretion, refuse to grant you an account or suspend or terminate your account at any time.</p>'\n\t);\n\nconst sectionUserContent = () =>\n\ttitledSection(\n\t\t'User Content',\n\t\t`<p><strong>Your content remains your content.</strong> You retain all rights you have in the User Content you submit, upload, post, transmit, or otherwise make available through the Service. You are solely responsible for your User Content and the consequences of making it available through the Service.</p><p><strong>License to us.</strong> By submitting User Content through the Service, you grant us a worldwide, non-exclusive, royalty-free, fully paid-up, perpetual, irrevocable, sublicensable, and transferable license to use, host, store, cache, reproduce, publish, publicly display, publicly perform, distribute, modify, adapt, translate, and create derivative works of your User Content, solely in connection with operating, providing, promoting, and improving the Service, and to enable our service providers to do the same on our behalf. The license you grant survives termination of these Terms with respect to User Content that has been shared, distributed, or otherwise relied upon by us or third parties before termination.</p><p><strong>Your representations and warranties.</strong> You represent and warrant that: (a) you own or have all necessary rights, licenses, consents, releases, and permissions in your User Content; (b) your User Content does not and will not infringe, misappropriate, or violate any third party\u2019s intellectual property, privacy, publicity, contractual, or other rights, or any applicable law; and (c) your User Content is not unlawful, defamatory, obscene, threatening, harassing, abusive, or otherwise objectionable.</p><p><strong>Right to remove.</strong> We reserve the right, but are not obligated, to review, screen, or remove any User Content at any time, with or without notice, for any reason, including any User Content that we determine, in our sole discretion, violates these Terms or is otherwise objectionable. We are not responsible for any User Content posted by users.</p>`\n\t);\n\nconst sectionDmca = (c: Computed, infringementEmail: string) =>\n\ttitledSection('DMCA Notice and Counter-Notice', dmcaBlock(c.companyName, infringementEmail));\n\nconst sectionExclusiveIp = (c: Computed) =>\n\ttitledSection(\n\t\t'Intellectual Property of the Company',\n\t\t`<p>The Service and its original content (excluding User Content), features, functionality, software, source code, designs, text, graphics, images, logos, trademarks, service marks, trade dress, and trade names are and will remain the exclusive property of ${escapeHtml(\n\t\t\tc.companyName\n\t\t)} and its licensors, and are protected by copyright, trademark, and other intellectual property laws. Nothing in these Terms grants you any right or license to use any of our trademarks, service marks, logos, trade names, or trade dress without our prior written permission. All goodwill arising from the use of our trademarks inures to our exclusive benefit.</p>`\n\t);\n\nconst sectionFeedback = () =>\n\ttitledSection(\n\t\t'Feedback',\n\t\t'<p>If you provide us with any suggestions, ideas, comments, improvements, recommendations, or other feedback regarding the Service (\"Feedback\"), you grant us a worldwide, perpetual, irrevocable, royalty-free, fully paid-up, sublicensable, and transferable license to use, copy, modify, distribute, and otherwise commercially exploit the Feedback for any purpose, without restriction or compensation to you. You waive any moral rights or similar rights in the Feedback to the maximum extent permitted by applicable law.</p>'\n\t);\n\nconst sectionPurchases = () =>\n\ttitledSection(\n\t\t'Purchases and Payments',\n\t\t'<p>We may offer goods, items, or services for purchase through the Service. By placing an order, you represent and warrant that you are legally capable of entering into a binding contract and that the information you provide is accurate, current, and complete.</p><p><strong>Pricing and availability.</strong> Prices, features, and availability are subject to change without notice. We reserve the right to refuse or cancel any order at any time for any reason, including suspected fraud, errors in product or pricing information, or unavailability.</p><p><strong>Taxes.</strong> Unless otherwise stated, prices are exclusive of any applicable taxes, duties, or similar governmental assessments. You are responsible for any such taxes associated with your purchase.</p><p><strong>Payment authorization.</strong> By submitting payment information, you authorize us (or our payment processor) to charge the applicable amount to your selected payment method. You agree to keep your payment information current and accurate.</p><p><strong>Refunds.</strong> Refunds, if available, are described at the point of purchase or in our refund policy. Except where required by law, all sales are final.</p>'\n\t);\n\nconst sectionSubscriptions = (a: TermsAnswers) => {\n\tconst bullets: string[] = [];\n\tif (a.freeTrial === 'yes') {\n\t\tbullets.push(\n\t\t\t'<strong>Free trial.</strong> We may offer a free trial for certain subscription plans. If you do not cancel before the end of the free trial, you will be automatically charged for the applicable plan at the then-current rate. We will provide notice before charging your payment method where required by law.'\n\t\t);\n\t}\n\tbullets.push(\n\t\t'<strong>Recurring billing.</strong> Subscriptions are billed in advance on a recurring and periodic basis (such as weekly, monthly, or annually), depending on the plan you select. Each billing period begins on the date your subscription is established or renewed.',\n\t\t'<strong>Automatic renewal.</strong> Your subscription will automatically renew at the end of each billing period at the then-current rate, unless you cancel before the end of the current billing period. By starting a subscription, you authorize us to automatically charge your payment method for each renewal until you cancel. This authorization will continue until you cancel.',\n\t\t'<strong>Cancellation.</strong> You may cancel your subscription at any time by following the cancellation instructions in your account settings or by contacting us using the methods listed in the \"Contact Us\" section. Cancellation will take effect at the end of the current billing period; you will continue to have access to the subscription through the end of that period and will not receive a refund for the current period unless required by law.',\n\t\t'<strong>Price changes.</strong> We may change subscription fees and the features included in any subscription plan at any time. Where required by law, we will provide reasonable advance notice of any fee changes. If you do not agree to the changes, you may cancel your subscription before the change takes effect.',\n\t\t'<strong>Failed payments.</strong> If we are unable to charge your payment method for any reason, we may suspend or terminate your access to the subscription until payment is successfully processed.'\n\t);\n\tconst autoRenewalNotice = `<p><strong>Auto-renewal disclosure (California, New York, and other states).</strong> In accordance with the California Automatic Renewal Law (Cal. Bus. &amp; Prof. Code &sect; 17600 et seq.), New York General Business Law &sect; 527-a, and similar laws, you acknowledge that your subscription will continue until cancelled, that we will charge the payment method you provided on a recurring basis at the frequency described at the time of purchase, that your subscription will automatically renew unless you cancel, and that you may cancel at any time using the cancellation methods described above.</p>`;\n\treturn titledSection(\n\t\t'Subscriptions and Automatic Renewal',\n\t\t`<p>Some parts of the Service may be billed on a subscription basis.</p>${list(bullets)}${autoRenewalNotice}`\n\t);\n};\n\nconst sectionPromotions = () =>\n\ttitledSection(\n\t\t'Promotions',\n\t\t'<p>Any promotions, contests, sweepstakes, or similar offerings (\"Promotions\") made available through the Service may be governed by rules separate from these Terms. If you participate in any Promotion, please review the applicable rules as well as our Privacy Policy. If the rules for a Promotion conflict with these Terms, the Promotion rules will apply.</p>'\n\t);\n\nconst sectionProhibited = () =>\n\ttitledSection(\n\t\t'Prohibited Uses',\n\t\t`<p>You agree not to use the Service:</p>${list([\n\t\t\t'In any way that violates any applicable national, state, local, or international law or regulation (including, without limitation, any laws regarding the export of data or software to and from the United States or other countries).',\n\t\t\t'For the purpose of exploiting, harming, or attempting to exploit or harm minors in any way by exposing them to inappropriate content, asking for personally identifiable information, or otherwise.',\n\t\t\t'To transmit, or procure the sending of, any advertising or promotional material, including any \"junk mail,\" \"chain letter,\" \"spam,\" or any other similar solicitation, without our prior written consent.',\n\t\t\t'To impersonate or attempt to impersonate the Company, a Company employee, another user, or any other person or entity.',\n\t\t\t'To engage in any other conduct that restricts or inhibits anyone\u2019s use or enjoyment of the Service, or which, as determined by us, may harm the Company or users of the Service or expose them to liability.',\n\t\t\t'To use the Service in any manner that could disable, overburden, damage, or impair the Service or interfere with any other party\u2019s use of the Service.',\n\t\t\t'To use any robot, spider, or other automatic device, process, or means to access the Service for any purpose, including monitoring or copying any of the material on the Service.',\n\t\t\t'To introduce any viruses, Trojan horses, worms, logic bombs, or other material that is malicious or technologically harmful.',\n\t\t\t'To attempt to gain unauthorized access to, interfere with, damage, or disrupt any parts of the Service, the server on which the Service is stored, or any server, computer, or database connected to the Service.',\n\t\t\t'To attack the Service via a denial-of-service attack or a distributed denial-of-service attack.',\n\t\t\t'To otherwise attempt to interfere with the proper working of the Service.'\n\t\t])}`\n\t);\n\nconst sectionTermination = () =>\n\ttitledSection(\n\t\t'Termination',\n\t\t'<p>We may terminate or suspend your account and access to the Service immediately, without prior notice or liability, for any reason, including without limitation if you breach these Terms. Upon termination, your right to use the Service will cease immediately. If you wish to terminate your account, you may simply discontinue using the Service or follow the account-deletion process in your account settings.</p><p>All provisions of these Terms which by their nature should survive termination shall survive, including, without limitation, ownership provisions, warranty disclaimers, indemnity, limitations of liability, and dispute-resolution provisions.</p>'\n\t);\n\nconst sectionDisclaimer = (c: Computed) =>\n\ttitledSection(\n\t\t'Disclaimer of Warranties',\n\t\t`<p>YOUR USE OF THE SERVICE IS AT YOUR SOLE RISK. THE SERVICE IS PROVIDED ON AN \"AS IS\" AND \"AS AVAILABLE\" BASIS, WITH ALL FAULTS. TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, ${escapeHtml(\n\t\t\tc.companyName\n\t\t).toUpperCase()} EXPRESSLY DISCLAIMS ALL WARRANTIES OF ANY KIND, WHETHER EXPRESS, IMPLIED, STATUTORY, OR OTHERWISE, INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE, NON-INFRINGEMENT, AND ANY WARRANTIES ARISING OUT OF COURSE OF DEALING OR USAGE OF TRADE.</p><p>WITHOUT LIMITING THE FOREGOING, ${escapeHtml(\n\t\t\tc.companyName\n\t\t).toUpperCase()} MAKES NO WARRANTY THAT (A) THE SERVICE WILL MEET YOUR REQUIREMENTS, (B) THE SERVICE WILL BE UNINTERRUPTED, TIMELY, SECURE, OR ERROR-FREE, (C) THE RESULTS OBTAINED FROM THE USE OF THE SERVICE WILL BE ACCURATE OR RELIABLE, OR (D) THE QUALITY OF ANY PRODUCTS, SERVICES, INFORMATION, OR OTHER MATERIAL OBTAINED THROUGH THE SERVICE WILL MEET YOUR EXPECTATIONS.</p><p>SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION OF CERTAIN WARRANTIES, SO SOME OF THE ABOVE EXCLUSIONS MAY NOT APPLY TO YOU. IN SUCH JURISDICTIONS, OUR LIABILITY IS LIMITED TO THE GREATEST EXTENT PERMITTED BY LAW.</p>`\n\t);\n\nconst sectionLimitation = (c: Computed) =>\n\ttitledSection(\n\t\t'Limitation of Liability',\n\t\t`<p>TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, IN NO EVENT SHALL ${escapeHtml(\n\t\t\tc.companyName\n\t\t).toUpperCase()}, ITS DIRECTORS, EMPLOYEES, AGENTS, AFFILIATES, PARTNERS, SUPPLIERS, OR LICENSORS BE LIABLE FOR ANY INDIRECT, INCIDENTAL, SPECIAL, CONSEQUENTIAL, EXEMPLARY, OR PUNITIVE DAMAGES, INCLUDING WITHOUT LIMITATION LOSS OF PROFITS, REVENUE, DATA, USE, GOODWILL, OR OTHER INTANGIBLE LOSSES, ARISING OUT OF OR RELATING TO YOUR ACCESS TO OR USE OF, OR INABILITY TO ACCESS OR USE, THE SERVICE; ANY CONDUCT OR CONTENT OF ANY THIRD PARTY ON THE SERVICE; ANY CONTENT OBTAINED FROM THE SERVICE; OR UNAUTHORIZED ACCESS, USE, OR ALTERATION OF YOUR TRANSMISSIONS OR CONTENT, WHETHER BASED ON WARRANTY, CONTRACT, TORT (INCLUDING NEGLIGENCE), OR ANY OTHER LEGAL THEORY, AND WHETHER OR NOT WE HAVE BEEN INFORMED OF THE POSSIBILITY OF SUCH DAMAGE.</p><p>TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, OUR TOTAL CUMULATIVE LIABILITY TO YOU FOR ALL CLAIMS ARISING OUT OF OR RELATING TO THESE TERMS OR THE SERVICE WILL NOT EXCEED THE GREATER OF (A) ONE HUNDRED U.S. DOLLARS ($100) OR (B) THE AMOUNTS YOU PAID US IN THE TWELVE (12) MONTHS PRECEDING THE EVENT GIVING RISE TO THE CLAIM.</p><p>THE LIMITATIONS IN THIS SECTION DO NOT APPLY TO LIABILITY THAT CANNOT BE EXCLUDED OR LIMITED UNDER APPLICABLE LAW, INCLUDING LIABILITY FOR GROSS NEGLIGENCE, WILLFUL MISCONDUCT, OR FRAUD. SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION OR LIMITATION OF CERTAIN DAMAGES, SO THE ABOVE LIMITATIONS MAY NOT APPLY TO YOU.</p>`\n\t);\n\nconst sectionIndemnification = (c: Computed) =>\n\ttitledSection(\n\t\t'Indemnification',\n\t\t`<p>You agree to defend, indemnify, and hold harmless ${escapeHtml(\n\t\t\tc.companyName\n\t\t)}, its affiliates, licensors, and service providers, and its and their respective officers, directors, employees, contractors, agents, licensors, suppliers, successors, and assigns, from and against any claims, liabilities, damages, judgments, awards, losses, costs, expenses, or fees (including reasonable attorneys\u2019 fees) arising out of or relating to (a) your violation of these Terms, (b) your use or misuse of the Service, (c) your User Content, including any claim that your User Content infringes or violates the rights of a third party, or (d) your violation of any applicable law or the rights of any third party.</p>`\n\t);\n\nconst sectionForceMajeure = () =>\n\ttitledSection(\n\t\t'Force Majeure',\n\t\t'<p>We will not be liable for any failure or delay in performance under these Terms to the extent caused by circumstances beyond our reasonable control, including without limitation acts of God, natural disasters, war, terrorism, riots, civil unrest, governmental actions, labor disputes, epidemics or pandemics, fires, floods, power or telecommunications failures, internet or third-party service failures, or any other event of force majeure.</p>'\n\t);\n\nconst sectionGoverningLaw = (c: Computed) =>\n\ttitledSection(\n\t\t'Governing Law',\n\t\t`<p>These Terms shall be governed by and construed in accordance with the laws of ${\n\t\t\tc.governingLocation\n\t\t}, without regard to its conflict-of-laws provisions. The United Nations Convention on Contracts for the International Sale of Goods does not apply to these Terms. Subject to the \"Dispute Resolution\" section below, you agree to submit to the personal and exclusive jurisdiction of the courts located in ${\n\t\t\tc.governingLocation\n\t\t} for the resolution of any disputes not subject to arbitration.</p>`\n\t);\n\nconst sectionArbitration = (c: Computed) =>\n\ttitledSection(\n\t\t'Dispute Resolution; Binding Arbitration; Class-Action Waiver',\n\t\tarbitrationBlock(c.companyName, c.governingLocation)\n\t);\n\nconst sectionExport = (c: Computed) =>\n\ttitledSection(\n\t\t'Export Controls and Sanctions',\n\t\t`<p>The Service may be subject to U.S. and other export-control and economic-sanctions laws and regulations. You may not access, use, export, re-export, or transfer the Service in violation of those laws. You represent and warrant that you are not located in, under the control of, or a national or resident of any country or person subject to U.S. or other applicable economic sanctions or embargoes, and that you are not on any U.S. government list of restricted or prohibited parties. You agree to comply with all applicable export, re-export, and sanctions laws in your use of the Service. ${escapeHtml(\n\t\t\tc.companyName\n\t\t)} reserves the right to restrict access to the Service from any jurisdiction at any time.</p>`\n\t);\n\nconst sectionAppleRider = (c: Computed) =>\n\ttitledSection(\n\t\t'Additional Terms for Apple App Store',\n\t\t`<p>If you accessed or downloaded the Service from the Apple App Store, the following additional terms apply. You acknowledge that these Terms are concluded between you and ${escapeHtml(\n\t\t\tc.companyName\n\t\t)}, and not with Apple Inc. (\"Apple\"), and that ${escapeHtml(\n\t\t\tc.companyName\n\t\t)}, not Apple, is solely responsible for the Service and its content.</p><ul><li><strong>Scope of license.</strong> The license granted to you for the Service is limited to a non-transferable license to use the Service on any Apple-branded products that you own or control, as permitted by the Usage Rules in the Apple Media Services Terms and Conditions.</li><li><strong>Maintenance and support.</strong> ${escapeHtml(\n\t\t\tc.companyName\n\t\t)} is solely responsible for providing any maintenance and support services, as specified in these Terms or as required under applicable law. Apple has no obligation whatsoever to furnish any maintenance and support services with respect to the Service.</li><li><strong>Warranty.</strong> ${escapeHtml(\n\t\t\tc.companyName\n\t\t)} is solely responsible for any product warranties, whether express or implied by law, to the extent not effectively disclaimed. In the event of any failure of the Service to conform to any applicable warranty, you may notify Apple, and Apple will refund the purchase price for the Service to you (if any). To the maximum extent permitted by applicable law, Apple will have no other warranty obligation whatsoever with respect to the Service.</li><li><strong>Product claims.</strong> ${escapeHtml(\n\t\t\tc.companyName\n\t\t)}, not Apple, is responsible for addressing any claims by you or any third party relating to the Service, including: (i) product liability claims; (ii) any claim that the Service fails to conform to any applicable legal or regulatory requirement; and (iii) claims arising under consumer protection, privacy, or similar legislation.</li><li><strong>Intellectual property rights.</strong> In the event of any third-party claim that the Service or your possession and use of the Service infringes that third party\u2019s intellectual property rights, ${escapeHtml(\n\t\t\tc.companyName\n\t\t)}, not Apple, will be solely responsible for the investigation, defense, settlement, and discharge of any such claim, to the extent required by these Terms.</li><li><strong>Legal compliance.</strong> You represent and warrant that you are not located in a country that is subject to a U.S. Government embargo or that has been designated by the U.S. Government as a \"terrorist supporting\" country, and that you are not listed on any U.S. Government list of prohibited or restricted parties.</li><li><strong>Third-party beneficiary.</strong> You and ${escapeHtml(\n\t\t\tc.companyName\n\t\t)} acknowledge and agree that Apple, and Apple\u2019s subsidiaries, are third-party beneficiaries of these Terms, and that, upon your acceptance of these Terms, Apple will have the right (and will be deemed to have accepted the right) to enforce these Terms against you as a third-party beneficiary thereof.</li><li><strong>Contact.</strong> Any questions, complaints, or claims with respect to the Service should be directed to ${escapeHtml(\n\t\t\tc.companyName\n\t\t)} using the methods in the \"Contact Us\" section.</li></ul>`\n\t);\n\nconst sectionGoogleRider = (c: Computed) =>\n\ttitledSection(\n\t\t'Additional Terms for Google Play',\n\t\t`<p>If you accessed or downloaded the Service from Google Play, you acknowledge and agree that:</p><ul><li>${escapeHtml(\n\t\t\tc.companyName\n\t\t)}, not Google LLC (\"Google\"), is solely responsible for the Service and its content.</li><li>Google has no obligation or liability to you with respect to the Service or these Terms.</li><li>Your use of the Service must comply with the then-current Google Play Terms of Service.</li><li>Google is a third-party beneficiary of these Terms only to the extent necessary to enforce its rights under the Google Play Terms of Service.</li></ul>`\n\t);\n\nconst sectionSeverability = () =>\n\ttitledSection(\n\t\t'Severability and Waiver',\n\t\t'<p><strong>Severability.</strong> If any provision of these Terms is held by a court or other tribunal of competent jurisdiction to be invalid, illegal, or unenforceable for any reason, that provision will be modified to the minimum extent necessary to make it enforceable, or, if it cannot be modified, severed from these Terms. The remaining provisions will continue in full force and effect.</p><p><strong>Waiver.</strong> No waiver by us of any term or condition set forth in these Terms shall be deemed a further or continuing waiver of such term or condition or a waiver of any other term or condition. Our failure to assert a right or provision under these Terms shall not constitute a waiver of such right or provision.</p>'\n\t);\n\nconst sectionEntireAgreement = () =>\n\ttitledSection(\n\t\t'Entire Agreement',\n\t\t'<p>These Terms, together with our Privacy Policy and any other policies referenced herein, constitute the entire agreement between you and us regarding the Service and supersede all prior and contemporaneous agreements, proposals, or representations, whether written or oral, regarding the Service.</p>'\n\t);\n\nconst sectionAssignment = (c: Computed) =>\n\ttitledSection(\n\t\t'Assignment',\n\t\t`<p>You may not assign or transfer these Terms, by operation of law or otherwise, without our prior written consent. Any attempt by you to assign or transfer these Terms without such consent will be null and void. ${escapeHtml(\n\t\t\tc.companyName\n\t\t)} may freely assign or transfer these Terms without restriction. Subject to the foregoing, these Terms will bind and inure to the benefit of the parties, their successors, and permitted assigns.</p>`\n\t);\n\nconst sectionNotices = () =>\n\ttitledSection(\n\t\t'Notices',\n\t\t'<p>Any notices or other communications provided by us under these Terms will be given by posting to the Service or by email to the address associated with your account. Notices to us must be sent using the methods listed in the \"Contact Us\" section. A notice is deemed given on the date received or, if delivery is not accomplished by reason of some fault of the addressee, when tendered.</p>'\n\t);\n\nconst sectionLinks = () =>\n\ttitledSection(\n\t\t'Links to Other Websites',\n\t\t'<p>The Service may contain links to third-party websites or services that are not owned or controlled by us. We have no control over, and assume no responsibility for, the content, privacy policies, or practices of any third-party websites or services. You acknowledge and agree that we are not responsible or liable, directly or indirectly, for any damage or loss caused or alleged to be caused by or in connection with the use of or reliance on any such content, goods, or services available on or through any such websites or services.</p>'\n\t);\n\nconst sectionChanges = () =>\n\ttitledSection(\n\t\t'Changes to These Terms',\n\t\t'<p>We may update these Terms from time to time. We will notify you of any changes by posting the new Terms on this page and updating the \"Last updated\" date at the top. Where required by law, we will provide additional notice (such as by email) and give you the opportunity to review the changes before they take effect. Your continued use of the Service after the updated Terms become effective constitutes your acceptance of the changes. If you do not agree to the new Terms, you must stop using the Service.</p>'\n\t);\n\nconst sectionContact = (a: TermsAnswers) => {\n\tconst items: string[] = [];\n\tif (a.contact?.methods?.includes('email') && a.contact.details.email) {\n\t\titems.push(\n\t\t\t`By email: <a href=\"mailto:${escapeHtml(a.contact.details.email)}\">${escapeHtml(\n\t\t\t\ta.contact.details.email\n\t\t\t)}</a>`\n\t\t);\n\t}\n\tif (a.contact?.methods?.includes('page') && a.contact.details.page) {\n\t\titems.push(\n\t\t\t`By visiting this page on our website: <a href=\"${escapeHtml(\n\t\t\t\ta.contact.details.page\n\t\t\t)}\" rel=\"external nofollow noopener\" target=\"_blank\">${escapeHtml(a.contact.details.page)}</a>`\n\t\t);\n\t}\n\tif (a.contact?.methods?.includes('phone') && a.contact.details.phone) {\n\t\titems.push(`By phone number: ${escapeHtml(a.contact.details.phone)}`);\n\t}\n\tif (a.contact?.methods?.includes('mail') && a.contact.details.address) {\n\t\titems.push(`By mail: ${escapeHtml(a.contact.details.address)}`);\n\t}\n\treturn `<section class=\"space-y-3\"><h2 class=\"text-xl font-semibold\">Contact Us</h2><p class=\"text-base leading-7\">If you have any questions about these Terms, you can contact us:</p>${list(items)}</section>`;\n};\n\nexport const generateTermsHtml = (answers: TermsAnswers) => {\n\tconst c = compute(answers);\n\tconst sections: string[] = [];\n\n\tsections.push(sectionHeader(c));\n\tsections.push(sectionEligibility());\n\tsections.push(sectionDefinitions(c));\n\tsections.push(sectionLicense());\n\tif (answers.accounts === 'yes') sections.push(sectionAccounts());\n\tif (answers.userContent === 'yes') sections.push(sectionUserContent());\n\tif (answers.userContent === 'yes' && answers.infringementEmail) {\n\t\tsections.push(sectionDmca(c, answers.infringementEmail));\n\t}\n\tif (answers.exclusiveContent === 'yes') sections.push(sectionExclusiveIp(c));\n\tif (answers.feedbackReuse === 'yes') sections.push(sectionFeedback());\n\tif (answers.canBuyGoods === 'yes') sections.push(sectionPurchases());\n\tif (answers.subscriptions === 'yes') sections.push(sectionSubscriptions(answers));\n\tif (answers.promotions === 'yes') sections.push(sectionPromotions());\n\tsections.push(sectionProhibited());\n\tsections.push(sectionTermination());\n\tsections.push(sectionDisclaimer(c));\n\tsections.push(sectionLimitation(c));\n\tsections.push(sectionIndemnification(c));\n\tsections.push(sectionForceMajeure());\n\tsections.push(sectionGoverningLaw(c));\n\tsections.push(sectionArbitration(c));\n\tsections.push(sectionExport(c));\n\tif (answers.mobileApp.includes('apple')) sections.push(sectionAppleRider(c));\n\tif (answers.mobileApp.includes('google')) sections.push(sectionGoogleRider(c));\n\tsections.push(sectionSeverability());\n\tsections.push(sectionEntireAgreement());\n\tsections.push(sectionAssignment(c));\n\tsections.push(sectionNotices());\n\tsections.push(sectionLinks());\n\tsections.push(sectionChanges());\n\tsections.push(sectionContact(answers));\n\n\treturn `<section data-role=\"content\">${sections.filter(Boolean).join('')}</section>`;\n};\n\nasync function termsAction(): Promise<void> {\n\tconst { workspaceRootDir, publicRoutesDir } = await getWorkspace();\n\n\tconst core = await p.group(\n\t\t{\n\t\t\twebsiteUrl: sharedFields.websiteUrl,\n\t\t\twebsiteName: sharedFields.websiteName,\n\t\t\tentityType: sharedFields.entityType,\n\t\t\tbusinessName: sharedFields.businessName,\n\t\t\tbusinessAddress: sharedFields.businessAddress,\n\t\t\tcountry: sharedFields.country,\n\t\t\tstate: sharedFields.state\n\t\t},\n\t\t{ onCancel }\n\t);\n\n\tconst accounts = await p.select({\n\t\tmessage: 'Can users create accounts?',\n\t\toptions: [\n\t\t\t{ value: 'yes', label: 'Yes, users can create accounts' },\n\t\t\t{ value: 'no', label: 'No' }\n\t\t]\n\t});\n\tif (p.isCancel(accounts)) onCancel();\n\n\tconst userContent = await p.select({\n\t\tmessage: 'Can users create and/or upload content (ie. text, images)?',\n\t\toptions: [\n\t\t\t{ value: 'yes', label: 'Yes, users can create and/or upload content' },\n\t\t\t{ value: 'no', label: 'No' }\n\t\t]\n\t});\n\tif (p.isCancel(userContent)) onCancel();\n\n\tlet infringementEmail: string | undefined;\n\tif (userContent === 'yes') {\n\t\tconst email = await p.text({\n\t\t\tmessage: \"What's the email address where you will receive infringements notices?\",\n\t\t\tplaceholder: 'dmca@website.com',\n\t\t\tvalidate: (value: string | undefined) => {\n\t\t\t\tif (!value) {\n\t\t\t\t\treturn 'Please enter an email address';\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\tif (p.isCancel(email)) onCancel();\n\t\tinfringementEmail = email as string;\n\t}\n\n\tconst canBuyGoods = await p.select({\n\t\tmessage: 'Can users buy goods (products, items)?',\n\t\toptions: [\n\t\t\t{\n\t\t\t\tvalue: 'yes',\n\t\t\t\tlabel: 'Yes, users can buy goods, items or services (one-time payments only)'\n\t\t\t},\n\t\t\t{ value: 'no', label: 'No' }\n\t\t]\n\t});\n\tif (p.isCancel(canBuyGoods)) onCancel();\n\n\tconst subscriptions = await p.select({\n\t\tmessage: 'Do you offer subscription plans?',\n\t\toptions: [\n\t\t\t{ value: 'yes', label: 'Yes, we offer subscription plans' },\n\t\t\t{ value: 'no', label: 'No' }\n\t\t]\n\t});\n\tif (p.isCancel(subscriptions)) onCancel();\n\n\tlet freeTrial: 'yes' | 'no' | undefined;\n\tif (subscriptions === 'yes') {\n\t\tconst ft = await p.select({\n\t\t\tmessage: 'Do you offer a free trial?',\n\t\t\toptions: [\n\t\t\t\t{ value: 'yes', label: 'Yes' },\n\t\t\t\t{ value: 'no', label: 'No' }\n\t\t\t]\n\t\t});\n\t\tif (p.isCancel(ft)) onCancel();\n\t\tfreeTrial = ft as 'yes' | 'no';\n\t}\n\n\tconst exclusiveContent = await p.select({\n\t\tmessage:\n\t\t\t'Do you want to make it clear that your own content & trademarks are your exclusive property?',\n\t\toptions: [\n\t\t\t{\n\t\t\t\tvalue: 'yes',\n\t\t\t\tlabel: 'Yes, our content (logo, visual design, trademarks etc.) is our exclusive property'\n\t\t\t},\n\t\t\t{ value: 'no', label: 'No' }\n\t\t]\n\t});\n\tif (p.isCancel(exclusiveContent)) onCancel();\n\n\tconst feedbackReuse = await p.select({\n\t\tmessage:\n\t\t\t'If users provide you feedback & suggestions, do you want to use this feedback without compensation or credits given?',\n\t\toptions: [\n\t\t\t{ value: 'yes', label: 'Yes, we may implement any feedback or suggestions we receive' },\n\t\t\t{ value: 'no', label: 'No' }\n\t\t]\n\t});\n\tif (p.isCancel(feedbackReuse)) onCancel();\n\n\tconst promotions = await p.select({\n\t\tmessage: 'Do you plan to offer promotions, contests, sweepstakes?',\n\t\toptions: [\n\t\t\t{ value: 'yes', label: 'Yes, we may offer promotions, contests, sweepstakes' },\n\t\t\t{ value: 'no', label: 'No' }\n\t\t]\n\t});\n\tif (p.isCancel(promotions)) onCancel();\n\n\tconst mobileAppRaw = await p.multiselect({\n\t\tmessage: 'Is the Service distributed through any mobile app stores? Check all that apply',\n\t\toptions: [\n\t\t\t{ value: 'apple', label: 'Apple App Store' },\n\t\t\t{ value: 'google', label: 'Google Play' }\n\t\t],\n\t\trequired: false\n\t});\n\tif (p.isCancel(mobileAppRaw)) onCancel();\n\tconst mobileApp = (mobileAppRaw ?? []) as Array<'apple' | 'google'>;\n\n\tconst contact = await contactMethods('terms');\n\n\tconst html = generateTermsHtml({\n\t\tcore,\n\t\taccounts: accounts as 'yes' | 'no',\n\t\tuserContent: userContent as 'yes' | 'no',\n\t\tinfringementEmail,\n\t\tcanBuyGoods: canBuyGoods as 'yes' | 'no',\n\t\tsubscriptions: subscriptions as 'yes' | 'no',\n\t\tfreeTrial,\n\t\texclusiveContent: exclusiveContent as 'yes' | 'no',\n\t\tfeedbackReuse: feedbackReuse as 'yes' | 'no',\n\t\tpromotions: promotions as 'yes' | 'no',\n\t\tmobileApp,\n\t\tcontact\n\t});\n\n\tconst termsPage = path.join(\n\t\tworkspaceRootDir,\n\t\tpublicRoutesDir,\n\t\tLEGAL_DIR,\n\t\t'terms',\n\t\t'+page.svelte'\n\t);\n\tconst termsPageTs = path.join(workspaceRootDir, publicRoutesDir, LEGAL_DIR, 'terms', '+page.ts');\n\tfs.mkdirSync(path.dirname(termsPage), { recursive: true });\n\tfs.writeFileSync(termsPage, html);\n\tfs.writeFileSync(\n\t\ttermsPageTs,\n\t\tpageMetaTagsLoader('Terms of Service', `Terms of Service for ${core.websiteName}`)\n\t);\n\n\tconst relativeTermsPage = path.relative(workspaceRootDir, termsPage);\n\tconst relativeTermsPageTs = path.relative(workspaceRootDir, termsPageTs);\n\treportResult({\n\t\tsummary: 'Generated placeholder terms and conditions.',\n\t\tfilesCreated: [relativeTermsPage, relativeTermsPageTs],\n\t\tnextSteps: [\n\t\t\t`Review the generated copy in ${relativeTermsPage} and replace placeholder sections with details for your business.`,\n\t\t\t'Have the final document reviewed by a lawyer before publishing \u2014 this is a starter template, not legal advice.',\n\t\t\t'Link to /terms from your footer and sign-up flow.'\n\t\t]\n\t});\n}\n\nexport const terms = new Command('terms')\n\t.description('generate placeholder terms and conditions')\n\t.configureHelp(helpConfig)\n\t.action(() => runCommand(termsAction, 'Failed to generate terms and conditions.'));\n", "import process from 'node:process';\nimport * as p from '@clack/prompts';\n\nexport const sharedFields = {\n\twebsiteUrl: () =>\n\t\tp.text({\n\t\t\tmessage: 'What is your website URL?',\n\t\t\tplaceholder: 'http://www.mysite.com',\n\t\t\tvalidate: (value: string | undefined) => {\n\t\t\t\tif (!value || !value.startsWith('http')) {\n\t\t\t\t\treturn 'Please enter a valid URL starting with http or https';\n\t\t\t\t}\n\t\t\t}\n\t\t}),\n\twebsiteName: () =>\n\t\tp.text({\n\t\t\tmessage: 'What is your website name?',\n\t\t\tplaceholder: 'My Site',\n\t\t\tvalidate: (value: string | undefined) => {\n\t\t\t\tif (!value) {\n\t\t\t\t\treturn 'Please enter a website name';\n\t\t\t\t}\n\t\t\t}\n\t\t}),\n\tentityType: () =>\n\t\tp.select({\n\t\t\tmessage: 'Entity type',\n\t\t\toptions: [\n\t\t\t\t{\n\t\t\t\t\tvalue: 'business',\n\t\t\t\t\tlabel: \"I'm a Business\",\n\t\t\t\t\thint: 'e.g. Corporation, Limited Liability Company, Non-profit, Partnership, Sole Proprietor'\n\t\t\t\t},\n\t\t\t\t{ value: 'individual', label: \"I'm an Individual\" }\n\t\t\t]\n\t\t}),\n\tbusinessName: ({ results }: { results: { entityType?: 'business' | 'individual' } }) =>\n\t\tresults?.entityType === 'business'\n\t\t\t? p.text({\n\t\t\t\t\tmessage: 'What is the name of the business?',\n\t\t\t\t\tplaceholder: 'My Company LLC',\n\t\t\t\t\tvalidate: (value: string | undefined) => {\n\t\t\t\t\t\tif (!value) {\n\t\t\t\t\t\t\treturn 'Please enter a business name';\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t: undefined,\n\tbusinessAddress: ({ results }: { results: { entityType?: 'business' | 'individual' } }) =>\n\t\tresults?.entityType === 'business'\n\t\t\t? p.text({\n\t\t\t\t\tmessage: 'What is the address of the business?',\n\t\t\t\t\tplaceholder: '1 Cupertino, CA 95014',\n\t\t\t\t\tvalidate: (value: string | undefined) => {\n\t\t\t\t\t\tif (!value) {\n\t\t\t\t\t\t\treturn 'Please enter a business address';\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t: undefined,\n\tcountry: () =>\n\t\tp.text({\n\t\t\tmessage: 'Enter the country',\n\t\t\tvalidate: (value: string | undefined) => {\n\t\t\t\tif (!value) {\n\t\t\t\t\treturn 'Please enter a country';\n\t\t\t\t}\n\t\t\t}\n\t\t}),\n\tstate: () =>\n\t\tp.text({\n\t\t\tmessage: 'Enter the state',\n\t\t\tvalidate: (value: string | undefined) => {\n\t\t\t\tif (!value) {\n\t\t\t\t\treturn 'Please enter a state';\n\t\t\t\t}\n\t\t\t}\n\t\t})\n};\n\nexport const onCancel = () => {\n\tp.cancel('Operation cancelled.');\n\tprocess.exit(0);\n};\n\nexport async function contactMethods(type: 'terms' | 'privacy'): Promise<{\n\tmethods: Array<'email' | 'page' | 'phone' | 'mail'>;\n\tdetails: Record<string, string>;\n}> {\n\tconst selection = await p.multiselect({\n\t\tmessage: `How can users contact you for any questions regarding your ${type === 'privacy' ? 'Privacy Policy' : 'Terms & Conditions'}? Check all that apply`,\n\t\toptions: [\n\t\t\t{ value: 'email', label: 'By email' },\n\t\t\t{ value: 'page', label: 'By visiting a page on our website' },\n\t\t\t{ value: 'phone', label: 'By phone number' },\n\t\t\t{ value: 'mail', label: 'By sending post mail' }\n\t\t]\n\t});\n\n\tif (p.isCancel(selection)) onCancel();\n\n\tconst contact = selection as Array<'email' | 'page' | 'phone' | 'mail'>;\n\tconst details: Record<string, string> = {};\n\n\tif (contact.includes('email')) {\n\t\tconst email = await p.text({\n\t\t\tmessage: \"What's the email?\",\n\t\t\tplaceholder: 'office@mycompany.com',\n\t\t\tvalidate: (value: string | undefined) => {\n\t\t\t\tif (!value) {\n\t\t\t\t\treturn 'Please enter an email address';\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\tif (p.isCancel(email)) onCancel();\n\t\tdetails.email = email as string;\n\t}\n\tif (contact.includes('page')) {\n\t\tconst page = await p.text({\n\t\t\tmessage: \"What's the link?\",\n\t\t\tplaceholder: 'http://www.mycompany.com/contact',\n\t\t\tvalidate: (value: string | undefined) => {\n\t\t\t\tif (!value) {\n\t\t\t\t\treturn 'Please enter a link';\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\tif (p.isCancel(page)) onCancel();\n\t\tdetails.page = page as string;\n\t}\n\tif (contact.includes('phone')) {\n\t\tconst phone = await p.text({\n\t\t\tmessage: \"What's the phone number?\",\n\t\t\tplaceholder: '408.996.1010',\n\t\t\tvalidate: (value: string | undefined) => {\n\t\t\t\tif (!value) {\n\t\t\t\t\treturn 'Please enter a phone number';\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\tif (p.isCancel(phone)) onCancel();\n\t\tdetails.phone = phone as string;\n\t}\n\tif (contact.includes('mail')) {\n\t\tconst address = await p.text({\n\t\t\tmessage: \"What's the address?\",\n\t\t\tplaceholder: '767 Fifth Avenue New York, NY 10153, United States',\n\t\t\tvalidate: (value: string | undefined) => {\n\t\t\t\tif (!value) {\n\t\t\t\t\treturn 'Please enter an address';\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\tif (p.isCancel(address)) onCancel();\n\t\tdetails.address = address as string;\n\t}\n\n\treturn { methods: contact, details };\n}\n\nexport const escapeHtml = (value: unknown) =>\n\tString(value ?? '')\n\t\t.replaceAll('&', '&amp;')\n\t\t.replaceAll('<', '&lt;')\n\t\t.replaceAll('>', '&gt;')\n\t\t.replaceAll('\"', '&quot;')\n\t\t.replaceAll(\"'\", '&#39;');\n\nexport type LegalCoreAnswers = {\n\twebsiteUrl: string;\n\twebsiteName: string;\n\tentityType: 'business' | 'individual';\n\tbusinessName?: string;\n\tbusinessAddress?: string;\n\tcountry: string;\n\tstate: string;\n};\n\nexport const applyTypography = (html: string) =>\n\thtml\n\t\t.replaceAll('<p>', '<p class=\"text-base leading-7\">')\n\t\t.replaceAll('<ul>', '<ul class=\"list-disc pl-6 space-y-1 text-base leading-7\">')\n\t\t.replaceAll('<h3>', '<h3 class=\"text-lg font-semibold\">')\n\t\t.replaceAll('<h4>', '<h4 class=\"font-semibold\">');\n\nexport const list = (items: string[]) =>\n\titems.length\n\t\t? `<ul class=\"list-disc pl-6 space-y-1 text-base leading-7\">${items\n\t\t\t\t.map((i) => `<li>${i}</li>`)\n\t\t\t\t.join('')}</ul>`\n\t\t: '';\n\nexport const titledSection = (title: string, body: string) =>\n\tbody\n\t\t? `<section class=\"space-y-3\"><h2 class=\"text-xl font-semibold\">${escapeHtml(\n\t\t\t\ttitle\n\t\t\t)}</h2>${applyTypography(body)}</section>`\n\t\t: '';\n\nexport const subSection = (title: string, body: string) =>\n\tbody\n\t\t? `<div class=\"space-y-2\"><h3 class=\"text-lg font-semibold\">${escapeHtml(\n\t\t\t\ttitle\n\t\t\t)}</h3>${applyTypography(body)}</div>`\n\t\t: '';\n\nconst jsString = (s: string) =>\n\t`'${s.replace(/\\\\/g, '\\\\\\\\').replace(/'/g, \"\\\\'\").replace(/\\n/g, '\\\\n')}'`;\n\nexport const pageMetaTagsLoader = (title: string, description: string) =>\n\t`import { definePageMetaTags } from 'svelte-meta-tags';\n\nexport const load = async ({ parent }) => {\n\\tawait parent();\n\n\\tconst { pageMetaTags } = definePageMetaTags({\n\\t\\ttitle: ${jsString(title)},\n\\t\\tdescription: ${jsString(description)}\n\\t});\n\n\\treturn { pageMetaTags };\n};\n`;\n\nexport const ccpaCategoriesTable = (collected: {\n\tidentifiers: boolean;\n\tcustomerRecords: boolean;\n\tcommercialInfo: boolean;\n\tinternetActivity: boolean;\n\tgeolocation: boolean;\n\tsensitive: boolean;\n}) => {\n\tconst rows: Array<[string, string, boolean]> = [\n\t\t[\n\t\t\t'A. Identifiers',\n\t\t\t'A real name, alias, postal address, unique personal identifier, online identifier, IP address, email address, account name, or similar identifiers.',\n\t\t\tcollected.identifiers\n\t\t],\n\t\t[\n\t\t\t'B. Personal information categories listed in the California Customer Records statute (Cal. Civ. Code \u00A7 1798.80(e))',\n\t\t\t'A name, signature, address, telephone number, education, employment, employment history, financial information, or similar information. Some personal information included in this category may overlap with other categories.',\n\t\t\tcollected.customerRecords\n\t\t],\n\t\t[\n\t\t\t'C. Protected classification characteristics under California or federal law',\n\t\t\t'Age, race, color, ancestry, national origin, citizenship, religion, marital status, sex (including gender identity, gender expression), sexual orientation, veteran or military status, genetic information, or disability.',\n\t\t\tfalse\n\t\t],\n\t\t[\n\t\t\t'D. Commercial information',\n\t\t\t'Records and history of products or services purchased or considered.',\n\t\t\tcollected.commercialInfo\n\t\t],\n\t\t[\n\t\t\t'E. Biometric information',\n\t\t\t'Genetic, physiological, behavioral, and biological characteristics.',\n\t\t\tfalse\n\t\t],\n\t\t[\n\t\t\t'F. Internet or other similar network activity',\n\t\t\t'Browsing history, search history, interaction with our Service, advertisements, or other websites.',\n\t\t\tcollected.internetActivity\n\t\t],\n\t\t['G. Geolocation data', 'Approximate physical location.', collected.geolocation],\n\t\t[\n\t\t\t'H. Sensory data',\n\t\t\t'Audio, electronic, visual, thermal, olfactory, or similar information.',\n\t\t\tfalse\n\t\t],\n\t\t[\n\t\t\t'I. Professional or employment-related information',\n\t\t\t'Current or past job history or performance evaluations.',\n\t\t\tfalse\n\t\t],\n\t\t[\n\t\t\t'J. Non-public education information',\n\t\t\t'Education records directly related to a student maintained by an educational institution or party acting on its behalf, such as grades, transcripts, class lists, schedules, identification codes, financial information, or disciplinary records.',\n\t\t\tfalse\n\t\t],\n\t\t[\n\t\t\t'K. Inferences drawn from other personal information',\n\t\t\t'Profile reflecting a person\u2019s preferences, characteristics, predispositions, behavior, attitudes, intelligence, abilities, and aptitudes.',\n\t\t\tcollected.internetActivity\n\t\t]\n\t];\n\tconst items = rows.map(\n\t\t([cat, desc, yes]) =>\n\t\t\t`<li><p class=\"text-base leading-7\"><strong>${escapeHtml(cat)}</strong> &mdash; ${escapeHtml(\n\t\t\t\tdesc\n\t\t\t)} <em>Collected: ${yes ? 'Yes' : 'No'}.</em></p></li>`\n\t);\n\tlet body = `<p class=\"text-base leading-7\">In the past twelve (12) months, we may have collected the following categories of personal information:</p><ul class=\"list-disc pl-6 space-y-1 text-base leading-7\">${items.join('')}</ul>`;\n\tif (collected.sensitive) {\n\t\tbody += `<p class=\"text-base leading-7\"><strong>Sensitive Personal Information.</strong> We may collect a limited subset of sensitive personal information (such as account log-in credentials in combination with required security or access codes) as defined by the California Privacy Rights Act (\"CPRA\"). We do not use or disclose sensitive personal information for purposes other than those permitted under Cal. Civ. Code \u00A7 1798.121.</p>`;\n\t}\n\treturn body;\n};\n\nexport const legalBasesBlock = () =>\n\t`<p class=\"text-base leading-7\">If you are a resident of the European Economic Area (\"EEA\"), the United Kingdom, or Switzerland, our legal basis for collecting and using the personal information described in this Privacy Policy depends on the personal information we collect and the specific context in which we collect it. We may process your personal information because:</p><ul class=\"list-disc pl-6 space-y-1 text-base leading-7\"><li><p class=\"text-base leading-7\"><strong>Performance of a contract:</strong> processing is necessary to perform a contract with you or to take steps at your request before entering into a contract (Article 6(1)(b) GDPR).</p></li><li><p class=\"text-base leading-7\"><strong>Legitimate interests:</strong> processing is necessary for our legitimate interests or those of a third party, provided your interests and fundamental rights do not override those interests (Article 6(1)(f) GDPR). Our legitimate interests include securing the Service, preventing fraud, improving the Service, and direct marketing where permitted.</p></li><li><p class=\"text-base leading-7\"><strong>Compliance with legal obligation:</strong> processing is necessary for compliance with a legal obligation to which we are subject (Article 6(1)(c) GDPR).</p></li><li><p class=\"text-base leading-7\"><strong>Consent:</strong> we have your consent to do so for a specific purpose (Article 6(1)(a) GDPR). You may withdraw consent at any time by contacting us.</p></li><li><p class=\"text-base leading-7\"><strong>Vital interests:</strong> processing is necessary to protect your vital interests or those of another natural person (Article 6(1)(d) GDPR).</p></li><li><p class=\"text-base leading-7\"><strong>Public interest:</strong> processing is necessary for the performance of a task carried out in the public interest (Article 6(1)(e) GDPR).</p></li></ul>`;\n\nexport const internationalTransfersBlock = () =>\n\t`<p class=\"text-base leading-7\">Your information, including personal data, may be processed at our operating offices and in any other places where the parties involved in the processing are located. This means that this information may be transferred to \u2014 and maintained on \u2014 computers located outside of your state, province, country, or other governmental jurisdiction where the data protection laws may differ from those of your jurisdiction.</p><p class=\"text-base leading-7\">If we transfer personal information from the European Economic Area, the United Kingdom, or Switzerland to a country that has not been determined by the European Commission or the relevant authority to provide an adequate level of protection, we rely on appropriate safeguards. These safeguards include the European Commission\u2019s Standard Contractual Clauses (and the UK International Data Transfer Addendum, where applicable), supplementary technical and organizational measures, and, where appropriate, your explicit consent.</p><p class=\"text-base leading-7\">Your submission of personal information represents your agreement to that transfer. We will take all steps reasonably necessary to ensure that your data is treated securely and in accordance with this Privacy Policy and applicable law.</p>`;\n\nexport const usStateRightsBlock = (companyName: string) =>\n\t`<p class=\"text-base leading-7\">Residents of certain U.S. states (including California, Virginia, Colorado, Connecticut, Utah, Texas, Oregon, and others with comprehensive consumer privacy laws) have specific rights regarding their personal information. Subject to the requirements and exceptions of the applicable law, you may have the right to:</p><ul class=\"list-disc pl-6 space-y-1 text-base leading-7\"><li><p class=\"text-base leading-7\"><strong>Right to know / access:</strong> request that we disclose the categories and specific pieces of personal information we have collected about you, the categories of sources, the business or commercial purpose for collection, and the categories of third parties with whom we share your information.</p></li><li><p class=\"text-base leading-7\"><strong>Right to delete:</strong> request that we delete personal information we have collected from you, subject to certain exceptions.</p></li><li><p class=\"text-base leading-7\"><strong>Right to correct:</strong> request that we correct inaccurate personal information we maintain about you.</p></li><li><p class=\"text-base leading-7\"><strong>Right to opt out of sale or sharing:</strong> opt out of the sale of your personal information or sharing of your personal information for cross-context behavioral advertising.</p></li><li><p class=\"text-base leading-7\"><strong>Right to limit the use of sensitive personal information:</strong> direct us to limit our use and disclosure of sensitive personal information to those uses necessary to perform the services or provide the goods reasonably expected by an average consumer who requests them.</p></li><li><p class=\"text-base leading-7\"><strong>Right to non-discrimination:</strong> not be subjected to discriminatory treatment for exercising your privacy rights.</p></li><li><p class=\"text-base leading-7\"><strong>Right to appeal:</strong> if we deny your request, you may appeal our decision by contacting us. If your appeal is denied, you may contact your state attorney general.</p></li></ul><p class=\"text-base leading-7\"><strong>How to exercise your rights.</strong> You may submit a verifiable consumer request by contacting us using the methods listed in the \"Contact Us\" section. We will need to verify your identity before responding to your request. You may use an authorized agent to submit a request on your behalf, provided you give the agent written permission and verify your identity directly with us.</p><p class=\"text-base leading-7\"><strong>\"Do Not Sell or Share My Personal Information\" and Global Privacy Control.</strong> You may opt out of the \"sale\" or \"sharing\" of your personal information at any time. We honor opt-out preference signals, including the Global Privacy Control (\"GPC\"), as a valid request to opt out of sale and sharing for the browser or device on which the signal is detected.</p><p class=\"text-base leading-7\"><strong>California \"Shine the Light\" (Cal. Civ. Code &sect; 1798.83).</strong> California residents may request information about our disclosures of personal information to third parties for their direct marketing purposes once per calendar year. To make such a request, please contact us using the information in the \"Contact Us\" section.</p><p class=\"text-base leading-7\"><strong>CalOPPA disclosures.</strong> ${escapeHtml(\n\t\tcompanyName\n\t)} does not track its users over time and across third-party websites or services. We respond to Do Not Track (\"DNT\") signals as described above. We will notify users of material changes to this Privacy Policy by posting an updated policy on this page.</p>`;\n\nexport const gdprRightsBlock = (\n\tcompanyName: string,\n\tfacebookFanPage: { name: string; url: string } | null\n) => {\n\tlet body = `<p class=\"text-base leading-7\">If you are a resident of the European Economic Area (\"EEA\"), the United Kingdom, or Switzerland, you have the following rights under the General Data Protection Regulation (\"GDPR\") and the UK GDPR:</p><ul class=\"list-disc pl-6 space-y-1 text-base leading-7\"><li><p class=\"text-base leading-7\"><strong>Right of access:</strong> request a copy of the personal data we hold about you and information about how we process it.</p></li><li><p class=\"text-base leading-7\"><strong>Right to rectification:</strong> request that we correct inaccurate or complete incomplete personal data.</p></li><li><p class=\"text-base leading-7\"><strong>Right to erasure (\"right to be forgotten\"):</strong> request that we delete your personal data, where there is no compelling reason for us to continue processing it.</p></li><li><p class=\"text-base leading-7\"><strong>Right to restrict processing:</strong> request that we restrict the processing of your personal data in certain circumstances.</p></li><li><p class=\"text-base leading-7\"><strong>Right to data portability:</strong> receive the personal data you provided to us in a structured, commonly used, machine-readable format and have it transmitted to another controller.</p></li><li><p class=\"text-base leading-7\"><strong>Right to object:</strong> object to our processing of your personal data based on legitimate interests, including for direct marketing.</p></li><li><p class=\"text-base leading-7\"><strong>Right to withdraw consent:</strong> where processing is based on consent, withdraw that consent at any time without affecting the lawfulness of prior processing.</p></li><li><p class=\"text-base leading-7\"><strong>Right not to be subject to automated decision-making:</strong> not to be subject to a decision based solely on automated processing, including profiling, that produces legal effects concerning you or similarly significantly affects you.</p></li><li><p class=\"text-base leading-7\"><strong>Right to lodge a complaint:</strong> lodge a complaint with the supervisory authority in your country of residence, place of work, or place of the alleged infringement.</p></li></ul><p class=\"text-base leading-7\">To exercise any of these rights, please contact us using the methods listed in the \"Contact Us\" section. We will respond within one month, subject to any extensions permitted by law.</p>`;\n\tif (facebookFanPage) {\n\t\tconst name = escapeHtml(facebookFanPage.name);\n\t\tconst url = escapeHtml(facebookFanPage.url);\n\t\tbody += `<p class=\"text-base leading-7\"><strong>Facebook Fan Page \u2014 Joint Controller.</strong> ${escapeHtml(\n\t\t\tcompanyName\n\t\t)} operates the Facebook Fan Page${name ? ` \"${name}\"` : ''}${\n\t\t\turl ? ` at <a href=\"${url}\" rel=\"external nofollow noopener\" target=\"_blank\">${url}</a>` : ''\n\t\t}. As a result of the decision of the Court of Justice of the European Union in Case C-210/16, ${escapeHtml(\n\t\t\tcompanyName\n\t\t)} and Meta Platforms Ireland Limited are joint controllers in respect of personal data collected through the Page Insights service. The agreement between the parties governing this joint controllership is available on Meta\u2019s website. You may exercise your rights under the GDPR with either party.</p>`;\n\t}\n\treturn body;\n};\n\nexport const arbitrationBlock = (companyName: string, governingLocation: string) =>\n\t`<p class=\"text-base leading-7\"><strong>Informal resolution first.</strong> Before filing a claim against ${escapeHtml(\n\t\tcompanyName\n\t)}, you agree to try to resolve the dispute informally by contacting us. We will attempt to resolve the dispute by contacting you via email. If a dispute is not resolved within thirty (30) days of submission, you or ${escapeHtml(\n\t\tcompanyName\n\t)} may bring a formal proceeding.</p><p class=\"text-base leading-7\"><strong>Binding arbitration.</strong> Except for claims that may be properly brought in a small claims court of competent jurisdiction, all controversies, disputes, or claims arising out of or relating to these Terms or the Service shall be resolved by final and binding arbitration administered by the American Arbitration Association (\"AAA\") under its applicable rules then in effect (or, for users outside the United States, by an equivalent recognized arbitration body). The arbitration shall take place in ${escapeHtml(\n\t\tgoverningLocation\n\t)} or, at your election, by telephone or written submissions. The arbitrator\u2019s decision shall be final and binding, and judgment on the award may be entered in any court of competent jurisdiction.</p><p class=\"text-base leading-7\"><strong>Class-action waiver.</strong> You and ${escapeHtml(\n\t\tcompanyName\n\t)} agree that each may bring claims against the other only in your or its individual capacity and not as a plaintiff or class member in any purported class or representative proceeding. Unless both parties agree otherwise in writing, the arbitrator may not consolidate more than one person\u2019s claims and may not otherwise preside over any form of a representative or class proceeding.</p><p class=\"text-base leading-7\"><strong>Jury trial waiver.</strong> By agreeing to these Terms and to arbitration, you and ${escapeHtml(\n\t\tcompanyName\n\t)} are each waiving the right to a trial by jury or to participate in a class action.</p><p class=\"text-base leading-7\"><strong>30-day right to opt out.</strong> You may opt out of these arbitration and class-action waiver provisions by sending written notice of your decision to opt out to the contact address listed in the \"Contact Us\" section, postmarked within thirty (30) days of first accepting these Terms. Your notice must include your name, address, the email associated with your account, and a clear statement that you wish to opt out of arbitration. Opting out will not affect the other terms of this agreement.</p><p class=\"text-base leading-7\"><strong>Severability of class waiver.</strong> If the class-action waiver is found unenforceable in a particular case, then that proceeding shall be severed from any arbitration and brought in a court of competent jurisdiction; the remainder of these arbitration provisions shall continue to apply.</p>`;\n\nexport const dmcaBlock = (companyName: string, infringementEmail: string) =>\n\t`<p class=\"text-base leading-7\">${escapeHtml(\n\t\tcompanyName\n\t)} respects the intellectual property rights of others and expects users of the Service to do the same. We respond to clear notices of alleged copyright infringement that comply with the U.S. Digital Millennium Copyright Act (\"DMCA\"), 17 U.S.C. &sect; 512.</p><p class=\"text-base leading-7\"><strong>Submitting a notice of infringement.</strong> If you believe that material on the Service infringes your copyright, please send a written notice to our designated agent at <a href=\"mailto:${escapeHtml(\n\t\tinfringementEmail\n\t)}\">${escapeHtml(\n\t\tinfringementEmail\n\t)}</a>. To be effective under 17 U.S.C. &sect; 512(c)(3)(A), your notice must include substantially the following:</p><ul class=\"list-disc pl-6 space-y-1 text-base leading-7\"><li><p class=\"text-base leading-7\">A physical or electronic signature of a person authorized to act on behalf of the owner of an exclusive right that is allegedly infringed.</p></li><li><p class=\"text-base leading-7\">Identification of the copyrighted work claimed to have been infringed, or, if multiple copyrighted works are covered by a single notification, a representative list of such works.</p></li><li><p class=\"text-base leading-7\">Identification of the material that is claimed to be infringing or to be the subject of infringing activity, with information reasonably sufficient to permit us to locate the material (such as a URL).</p></li><li><p class=\"text-base leading-7\">Information reasonably sufficient to permit us to contact you, such as an address, telephone number, and an email address.</p></li><li><p class=\"text-base leading-7\">A statement that you have a good-faith belief that use of the material in the manner complained of is not authorized by the copyright owner, its agent, or the law.</p></li><li><p class=\"text-base leading-7\">A statement that the information in the notification is accurate, and under penalty of perjury, that you are authorized to act on behalf of the owner of an exclusive right that is allegedly infringed.</p></li></ul><p class=\"text-base leading-7\"><strong>Counter-notice.</strong> If you believe that your content was removed or disabled by mistake or misidentification, you may submit a written counter-notice to the same address. Under 17 U.S.C. &sect; 512(g)(3), the counter-notice must include your physical or electronic signature, identification of the material removed and its prior location, a statement under penalty of perjury that you have a good-faith belief that the material was removed or disabled as a result of mistake or misidentification, your name, address, telephone number, and a statement that you consent to the jurisdiction of the federal district court for your judicial district (or, if outside the United States, of any judicial district in which we may be found) and that you will accept service of process from the person who provided the original notification or an agent of such person.</p><p class=\"text-base leading-7\"><strong>Repeat infringers.</strong> It is our policy, in appropriate circumstances and at our sole discretion, to disable or terminate the accounts of users who are repeat infringers. Submitting false or misleading notices or counter-notices may result in liability for damages under 17 U.S.C. &sect; 512(f).</p>`;\n", "import fs from 'node:fs';\nimport path from 'node:path';\nimport { Command } from 'commander';\nimport * as p from '@clack/prompts';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand } from '../../lib/run.ts';\nimport { getWorkspace } from '../../lib/workspace.ts';\nimport { LEGAL_DIR } from '../../lib/constants.ts';\nimport { reportResult } from '../../lib/result-report.ts';\nimport {\n\tapplyTypography,\n\tccpaCategoriesTable,\n\tcontactMethods,\n\tescapeHtml,\n\tgdprRightsBlock,\n\tinternationalTransfersBlock,\n\tlegalBasesBlock,\n\tlist,\n\tonCancel,\n\tpageMetaTagsLoader,\n\tsharedFields,\n\tsubSection,\n\ttitledSection,\n\tusStateRightsBlock,\n\ttype LegalCoreAnswers\n} from './shared.ts';\n\nconst mapLabels = {\n\tpersonalInfo: {\n\t\temail: 'Email address',\n\t\tname: 'First name and last name',\n\t\tphone: 'Phone number',\n\t\taddress: 'Address, State, Province, ZIP/Postal code, City',\n\t\tsocial:\n\t\t\t'Social Media Profile information (e.g. from Connect with Facebook, Sign In With Twitter)',\n\t\tother: 'Other information you choose to provide'\n\t},\n\ttracking: {\n\t\tga: 'Google Analytics',\n\t\tfirebase: 'Firebase',\n\t\tmatomo: 'Matomo (formerly Piwik)',\n\t\tclicky: 'Clicky',\n\t\tstatcounter: 'Statcounter',\n\t\tflurry: 'Flurry Analytics',\n\t\tmixpanel: 'Mixpanel',\n\t\tunity: 'Unity Analytics'\n\t},\n\temailPlatforms: {\n\t\tmailchimp: 'Mailchimp',\n\t\t'constant-contact': 'Constant Contact',\n\t\taweber: 'AWeber',\n\t\tgetresponse: 'GetResponse'\n\t},\n\tads: {\n\t\tadsense: 'Google Ads (AdSense)',\n\t\tadmob: 'AdMob by Google',\n\t\tbing: 'Bing Ads',\n\t\tflurry: 'Flurry',\n\t\tinmobi: 'InMobi',\n\t\tmopub: 'MoPub',\n\t\tstartapp: 'StartApp',\n\t\tadcolony: 'AdColony',\n\t\tapplovin: 'AppLovin',\n\t\tvungle: 'Vungle',\n\t\tadbutler: 'AdButler',\n\t\t'unity-ads': 'Unity Ads'\n\t},\n\tpayments: {\n\t\t'apple-iap': 'Apple Store In-App Payments',\n\t\t'google-iap': 'Google Play In-App Payments',\n\t\tpaypal: 'PayPal',\n\t\tbraintree: 'Braintree',\n\t\tstripe: 'Stripe',\n\t\tfastspring: 'FastSpring',\n\t\tshopify: 'Shopify',\n\t\tsquare: 'Square',\n\t\t'2checkout': '2Checkout',\n\t\twepay: 'WePay',\n\t\tworldpay: 'WorldPay',\n\t\t'authorize-net': 'Authorize.net',\n\t\t'sage-pay': 'Sage Pay',\n\t\tgocardless: 'Go Cardless',\n\t\telavon: 'Elavon',\n\t\tverifone: 'Verifone',\n\t\tmoneris: 'Moneris',\n\t\twechat: 'WeChat',\n\t\talipay: 'Alipay',\n\t\tbank: 'Bank Transfer'\n\t},\n\tremarketing: {\n\t\t'google-ads': 'Google Ads (AdWords)',\n\t\ttwitter: 'Twitter',\n\t\tfacebook: 'Facebook',\n\t\tbing: 'Bing Ads',\n\t\tpinterest: 'Pinterest',\n\t\tadroll: 'AdRoll',\n\t\t'perfect-audience': 'Perfect Audience',\n\t\tappnexus: 'AppNexus'\n\t},\n\tproviders: {\n\t\trecaptcha: 'Invisible reCAPTCHA',\n\t\t'google-places': 'Google Places',\n\t\tmouseflow: 'Mouseflow',\n\t\tfreshdesk: 'FreshDesk'\n\t}\n} as const;\n\ntype PrivacyAnswers = {\n\tcore: LegalCoreAnswers;\n\tpersonalInfo: Array<'phone' | 'address' | 'email' | 'name' | 'social' | 'other'>;\n\tcontact: { methods: string[]; details: Record<string, unknown> };\n\ttracking: 'yes' | 'no';\n\ttrackingTools?: Array<keyof typeof mapLabels.tracking | string>;\n\tsendEmails: 'yes' | 'no';\n\temailPlatforms?: Array<keyof typeof mapLabels.emailPlatforms | string>;\n\tshowAds: 'yes' | 'no';\n\tadsPlatforms?: Array<keyof typeof mapLabels.ads | string>;\n\tcanPay: 'yes' | 'no';\n\tpaymentProcessors?: Array<keyof typeof mapLabels.payments | string>;\n\tremarketing: 'yes' | 'no';\n\tremarketingPlatforms?: Array<keyof typeof mapLabels.remarketing | string>;\n\tproviders?: Array<keyof typeof mapLabels.providers | string>;\n\tusStates: 'yes' | 'no';\n\tgdpr: 'yes' | 'no';\n\tfacebookFanPage?: 'yes' | 'no';\n\tfacebookDetails?: { name: string; url: string };\n\tkids: 'yes' | 'no';\n\tretention?: string;\n};\n\ntype Computed = {\n\tcompanyName: string;\n\tcompanyAddress: string;\n\twebsiteName: string;\n\twebsiteUrl: string;\n\tcountryText: string;\n\teffectiveDate: string;\n\tpiLabels: string[];\n\thasSocial: boolean;\n\ttrackingTools: string[];\n\temailPlatforms: string[];\n\tadsPlatforms: string[];\n\tpaymentProcessors: string[];\n\tremarketingPlatforms: string[];\n\tproviders: string[];\n\tretentionText: string;\n};\n\nconst compute = (a: PrivacyAnswers): Computed => {\n\tconst effectiveDate = new Date(Date.now()).toLocaleDateString('en-US', {\n\t\tyear: 'numeric',\n\t\tmonth: 'long',\n\t\tday: 'numeric'\n\t});\n\n\tconst piSelections = (a.personalInfo as string[] | undefined) ?? [];\n\tconst piLabels = piSelections.map(\n\t\t(v) => mapLabels.personalInfo[v as keyof typeof mapLabels.personalInfo] ?? v\n\t);\n\n\tconst lookup = <T extends Record<string, string>>(map: T, vs?: string[]) =>\n\t\t(vs ?? []).map((v) => map[v as keyof T] ?? v);\n\n\tconst companyName =\n\t\ta.core?.entityType === 'business'\n\t\t\t? (a.core?.businessName ?? a.core?.websiteName)\n\t\t\t: (a.core?.websiteName ?? 'Our Company');\n\tconst companyAddress = a.core?.entityType === 'business' ? (a.core?.businessAddress ?? '') : '';\n\tconst websiteName = a.core?.websiteName ?? 'our website';\n\tconst websiteUrl = a.core?.websiteUrl ?? '';\n\tconst countryText = `${a.core?.state ?? ''}${a.core?.state ? ', ' : ''}${a.core?.country ?? ''}`;\n\n\treturn {\n\t\tcompanyName,\n\t\tcompanyAddress,\n\t\twebsiteName,\n\t\twebsiteUrl,\n\t\tcountryText,\n\t\teffectiveDate,\n\t\tpiLabels,\n\t\thasSocial: piSelections.includes('social'),\n\t\ttrackingTools: lookup(mapLabels.tracking, a.trackingTools as string[] | undefined),\n\t\temailPlatforms: lookup(mapLabels.emailPlatforms, a.emailPlatforms as string[] | undefined),\n\t\tadsPlatforms: lookup(mapLabels.ads, a.adsPlatforms as string[] | undefined),\n\t\tpaymentProcessors: lookup(mapLabels.payments, a.paymentProcessors as string[] | undefined),\n\t\tremarketingPlatforms: lookup(\n\t\t\tmapLabels.remarketing,\n\t\t\ta.remarketingPlatforms as string[] | undefined\n\t\t),\n\t\tproviders: lookup(mapLabels.providers, a.providers as string[] | undefined),\n\t\tretentionText:\n\t\t\ta.retention && a.retention.trim().length > 0\n\t\t\t\t? a.retention.trim()\n\t\t\t\t: 'as long as is necessary to provide the Service and fulfil the purposes outlined in this Privacy Policy, and to comply with our legal obligations, resolve disputes, and enforce our agreements'\n\t};\n};\n\nconst sectionHeader = (c: Computed) =>\n\t`<section class=\"space-y-3\"><h1 class=\"text-3xl font-semibold\">Privacy Policy</h1><p class=\"text-base leading-7\">Last updated: ${escapeHtml(\n\t\tc.effectiveDate\n\t)}</p><p class=\"text-base leading-7\">This Privacy Policy describes the policies and procedures of ${escapeHtml(\n\t\tc.companyName\n\t)} (\"we\", \"us\", or \"our\") regarding the collection, use, and disclosure of your information when you use ${escapeHtml(\n\t\tc.websiteName\n\t)} (the \"Service\"), and tells you about your privacy rights and how applicable law protects you.</p><p class=\"text-base leading-7\">We use your personal data to provide and improve the Service. By using the Service, you agree to the collection and use of information in accordance with this Privacy Policy. If you do not agree with this Privacy Policy, please do not use the Service.</p></section>`;\n\nconst sectionDefinitions = (c: Computed) => {\n\tconst items: string[] = [];\n\tconst def = (term: string, body: string) =>\n\t\titems.push(`<li><p class=\"text-base leading-7\"><strong>${term}</strong> ${body}</p></li>`);\n\n\tdef(\n\t\t'Account',\n\t\t'means a unique account created for you to access our Service or parts of our Service.'\n\t);\n\tdef(\n\t\t'Affiliate',\n\t\t'means an entity that controls, is controlled by, or is under common control with a party, where \"control\" means ownership of 50% or more of the shares, equity interest, or other securities entitled to vote for election of directors or other managing authority.'\n\t);\n\tdef(\n\t\t'Business',\n\t\t`(referred to as either \"the Company\", \"We\", \"Us\", or \"Our\" in this Agreement) refers to ${escapeHtml(\n\t\t\tc.companyName\n\t\t)}${c.companyAddress ? `, ${escapeHtml(c.companyAddress)}` : ''}.`\n\t);\n\tdef(\n\t\t'Consumer',\n\t\t'for the purposes of U.S. state privacy laws, means a natural person who is a resident of a U.S. state with a comprehensive consumer privacy law.'\n\t);\n\tdef(\n\t\t'Cookies',\n\t\t'are small files that are placed on your computer, mobile device, or any other device by a website, containing details of your browsing history on that website among many other uses.'\n\t);\n\tdef('Country', `refers to: ${escapeHtml(c.countryText)}.`);\n\tdef(\n\t\t'Device',\n\t\t'means any device that can access the Service, such as a computer, a cellphone, or a digital tablet.'\n\t);\n\tdef(\n\t\t'Personal Data',\n\t\t'or Personal Information is any information that relates to an identified or identifiable individual, including any information that identifies, relates to, describes, or is reasonably capable of being associated with you.'\n\t);\n\tdef(\n\t\t'Sale',\n\t\t\"for the purposes of California, Colorado, Connecticut, Utah, and Virginia consumer privacy laws, means selling, renting, releasing, disclosing, disseminating, making available, transferring, or otherwise communicating orally, in writing, or by electronic means, a Consumer's Personal Information by the Business to a third party for valuable consideration.\"\n\t);\n\tdef(\n\t\t'Share',\n\t\t'for the purposes of the California Privacy Rights Act (\"CPRA\"), means sharing, renting, releasing, disclosing, disseminating, making available, transferring, or otherwise communicating orally, in writing, or by electronic or other means, a Consumer\\'s Personal Information by the Business to a third party for cross-context behavioral advertising, whether or not for monetary or other valuable consideration.'\n\t);\n\tdef(\n\t\t'Sensitive Personal Information',\n\t\t'has the meaning given in applicable U.S. state privacy laws (including the CPRA) and may include, where collected, government-issued identifiers, account log-in credentials, precise geolocation, racial or ethnic origin, religious beliefs, contents of communications, genetic data, biometric data, health information, and information concerning sex life or sexual orientation.'\n\t);\n\tdef(\n\t\t'Service',\n\t\t`refers to ${escapeHtml(c.websiteName)}, accessible from <a href=\"${escapeHtml(\n\t\t\tc.websiteUrl\n\t\t)}\" rel=\"external nofollow noopener\" target=\"_blank\">${escapeHtml(c.websiteUrl)}</a>.`\n\t);\n\tdef(\n\t\t'Service Provider',\n\t\t'means any natural or legal person who processes the data on behalf of the Company, including third-party companies or individuals employed by the Company to facilitate the Service.'\n\t);\n\tdef(\n\t\t'Third-party Social Media Service',\n\t\t'refers to any website or any social network website through which a user can log in or create an account to use the Service.'\n\t);\n\tdef(\n\t\t'Usage Data',\n\t\t'refers to data collected automatically, either generated by the use of the Service or from the Service infrastructure itself (for example, the duration of a page visit).'\n\t);\n\tdef(\n\t\t'You',\n\t\t'means the individual accessing or using the Service, or the company or other legal entity on behalf of which such individual is accessing or using the Service, as applicable.'\n\t);\n\n\tconst interpretation =\n\t\t'<p class=\"text-base leading-7\">The words of which the initial letter is capitalized have meanings defined under the following conditions. The following definitions shall have the same meaning regardless of whether they appear in singular or in plural.</p>';\n\tconst definitions = `<p class=\"text-base leading-7\">For the purposes of this Privacy Policy:</p><ul class=\"list-disc pl-6 space-y-1 text-base leading-7\">${items.join('')}</ul>`;\n\treturn `<section class=\"space-y-3\"><h2 class=\"text-xl font-semibold\">Interpretation and Definitions</h2><h3 class=\"text-lg font-semibold\">Interpretation</h3>${interpretation}<h3 class=\"text-lg font-semibold\">Definitions</h3>${definitions}</section>`;\n};\n\nconst sectionCategoriesCollected = (a: PrivacyAnswers, c: Computed) => {\n\tconst pi = (a.personalInfo as string[] | undefined) ?? [];\n\tconst internetActivity = a.tracking === 'yes' || (a.providers ?? []).length > 0;\n\tconst body = ccpaCategoriesTable({\n\t\tidentifiers: true,\n\t\tcustomerRecords: pi.includes('name') || pi.includes('address') || pi.includes('phone'),\n\t\tcommercialInfo: a.canPay === 'yes',\n\t\tinternetActivity,\n\t\tgeolocation: pi.includes('address'),\n\t\tsensitive: false\n\t});\n\n\tconst personal = `<h4 class=\"font-semibold\">Personal Data</h4><p class=\"text-base leading-7\">While using our Service, we may ask you to provide us with certain personally identifiable information that can be used to contact or identify you. Personally identifiable information may include, but is not limited to:</p>${list(\n\t\t(c.piLabels.length\n\t\t\t? c.piLabels\n\t\t\t: [\n\t\t\t\t\t'Email address',\n\t\t\t\t\t'First name and last name',\n\t\t\t\t\t'Phone number',\n\t\t\t\t\t'Address, State, Province, ZIP/Postal code, City',\n\t\t\t\t\t'Usage Data'\n\t\t\t\t]\n\t\t).map(escapeHtml)\n\t)}`;\n\n\tconst usage = `<h4 class=\"font-semibold\">Usage Data</h4><p class=\"text-base leading-7\">Usage Data is collected automatically when using the Service. It may include information such as your device\u2019s Internet Protocol address (e.g. IP address), browser type and version, the pages of our Service that you visit, the time and date of your visit, the time spent on those pages, unique device identifiers, and other diagnostic data.</p><p class=\"text-base leading-7\">When you access the Service by or through a mobile device, we may collect certain information automatically, including, but not limited to, the type of mobile device you use, your mobile device\u2019s unique ID, the IP address of your mobile device, your mobile operating system, the type of mobile Internet browser you use, unique device identifiers, and other diagnostic data.</p>`;\n\n\tlet social = '';\n\tif (c.hasSocial) {\n\t\tsocial = `<h4 class=\"font-semibold\">Information from Third-Party Social Media Services</h4><p class=\"text-base leading-7\">The Company allows you to create an account and log in to use the Service through Third-party Social Media Services such as Google, Facebook, Instagram, X (formerly Twitter), or LinkedIn. If you decide to register through or otherwise grant us access to a Third-party Social Media Service, we may collect personal data associated with your account, such as your name, email address, activities, or contact list.</p><p class=\"text-base leading-7\">You may also have the option of sharing additional information with the Company through your Third-party Social Media Service\u2019s account. If you choose to provide such information and Personal Data, during registration or otherwise, you are giving the Company permission to use, share, and store it in a manner consistent with this Privacy Policy.</p>`;\n\t}\n\n\treturn `<section class=\"space-y-3\"><h2 class=\"text-xl font-semibold\">Personal Information We Collect</h2>${applyTypography(\n\t\tbody\n\t)}${applyTypography(personal)}${applyTypography(usage)}${applyTypography(social)}</section>`;\n};\n\nconst sectionSources = () =>\n\ttitledSection(\n\t\t'Sources of Personal Information',\n\t\t`<p>We collect personal information from the following categories of sources:</p><ul><li><strong>Directly from you</strong> when you provide information to us, for example by creating an account, completing a form, contacting us, or making a purchase.</li><li><strong>Automatically</strong> as you navigate through the Service, including through cookies, log files, and similar tracking technologies.</li><li><strong>From third parties</strong>, such as analytics providers, advertising networks, payment processors, and Third-party Social Media Services that you use to log in.</li><li><strong>From publicly available sources</strong>, such as public records, public profile information, and public databases.</li><li><strong>From service providers and business partners</strong> that help us operate or improve the Service.</li></ul>`\n\t);\n\nconst sectionUse = (a: PrivacyAnswers, c: Computed) => {\n\tconst useBullets: string[] = [\n\t\t'<strong>To provide and maintain our Service,</strong> including to monitor the usage of our Service and to detect, prevent, and address technical issues.',\n\t\t'<strong>To manage your Account:</strong> to manage your registration as a user of the Service. The Personal Data you provide can give you access to different functionalities of the Service available to you as a registered user.'\n\t];\n\tif (a.canPay === 'yes') {\n\t\tuseBullets.push(\n\t\t\t'<strong>For the performance of a contract:</strong> the development, compliance, and undertaking of the purchase contract for products, items, or services you have purchased or of any other contract with us through the Service.'\n\t\t);\n\t}\n\tuseBullets.push(\n\t\t'<strong>To contact you:</strong> to contact you by email, telephone calls, SMS, or other equivalent forms of electronic communication, such as a mobile application\u2019s push notifications, regarding updates or informative communications related to the functionalities, products, or contracted services, including the security updates, when necessary or reasonable for their implementation.'\n\t);\n\tif (a.sendEmails === 'yes') {\n\t\tuseBullets.push(\n\t\t\t'<strong>To provide you</strong> with news, special offers, and general information about goods, services, and events that we offer, unless you have opted not to receive such information.'\n\t\t);\n\t}\n\tuseBullets.push(\n\t\t'<strong>To manage your requests:</strong> to attend to and manage your requests to us.',\n\t\t'<strong>For business transfers:</strong> we may use your information to evaluate or conduct a merger, divestiture, restructuring, reorganization, dissolution, or other sale or transfer of some or all of our assets, whether as a going concern or as part of bankruptcy, liquidation, or similar proceedings, in which Personal Data held by us about our Service users is among the assets transferred.',\n\t\t'<strong>For analytics and improvement:</strong> for data analysis, identifying usage trends, determining the effectiveness of our promotional campaigns, and improving our Service, products, services, marketing, and your experience.',\n\t\t'<strong>For security and fraud prevention:</strong> to protect the rights, property, or safety of the Company, our users, or others, including detecting, preventing, and responding to fraud, abuse, security risks, and technical issues.',\n\t\t'<strong>To comply with legal obligations:</strong> to comply with applicable laws, lawful requests, court orders, and legal processes.'\n\t);\n\n\tlet body = `<p class=\"text-base leading-7\">The Company may use Personal Data for the following purposes:</p>${list(useBullets)}`;\n\tif (a.showAds === 'yes') {\n\t\tbody += `<p class=\"text-base leading-7\">We may display advertising on the Service${\n\t\t\tc.adsPlatforms.length ? ' using the following platforms:' : '.'\n\t\t}</p>${c.adsPlatforms.length ? list(c.adsPlatforms.map(escapeHtml)) : ''}`;\n\t}\n\tif (a.canPay === 'yes' && c.paymentProcessors.length) {\n\t\tbody += `<p class=\"text-base leading-7\">If you make purchases, we may process payments via the following providers, who handle your payment information in accordance with their own privacy policies:</p>${list(\n\t\t\tc.paymentProcessors.map(escapeHtml)\n\t\t)}`;\n\t}\n\n\treturn titledSection('How We Use Your Personal Information', body);\n};\n\nconst sectionLegalBases = () =>\n\ttitledSection('Legal Bases for Processing (EEA, UK, Switzerland)', legalBasesBlock());\n\nconst sectionShare = (a: PrivacyAnswers, c: Computed) => {\n\tlet body =\n\t\t'<p>We may share your personal information in the following situations and with the following categories of recipients:</p><ul>';\n\tbody +=\n\t\t'<li><strong>With Service Providers:</strong> to monitor and analyze the use of our Service, host the Service, process payments, send emails, provide customer support, and contact you. These providers have access to your Personal Information only to perform these tasks on our behalf and are obligated not to disclose or use it for any other purpose.</li>';\n\tbody +=\n\t\t'<li><strong>For business transfers:</strong> we may share or transfer your Personal Information in connection with, or during negotiations of, any merger, sale of Company assets, financing, or acquisition of all or a portion of our business to another company.</li>';\n\tbody +=\n\t\t'<li><strong>With Affiliates:</strong> we may share your information with our affiliates, in which case we will require those affiliates to honor this Privacy Policy.</li>';\n\tbody +=\n\t\t'<li><strong>With business partners:</strong> we may share your information with our business partners to offer you certain products, services, or promotions.</li>';\n\tbody +=\n\t\t'<li><strong>With other users:</strong> when you share personal information or otherwise interact in public areas with other users, such information may be viewed by all users and may be publicly distributed outside.</li>';\n\tbody +=\n\t\t'<li><strong>For legal reasons:</strong> we may disclose your information where we believe in good faith that it is necessary to comply with a legal obligation, to protect our rights or property, to prevent fraud or harm, or to enforce our terms.</li>';\n\tbody += '<li><strong>With your consent:</strong> for any other purpose with your consent.</li>';\n\tbody += '</ul>';\n\tif (c.providers.length) {\n\t\tbody += `<p>We currently use the following service providers:</p>${list(c.providers.map(escapeHtml))}`;\n\t}\n\tvoid a;\n\treturn titledSection('How We Share or Disclose Personal Information', body);\n};\n\nconst sectionSaleSharing = (a: PrivacyAnswers, c: Computed) => {\n\tconst sells = a.showAds === 'yes' || a.remarketing === 'yes';\n\tconst intro = sells\n\t\t? `<p>For purposes of certain U.S. state privacy laws (including the California Consumer Privacy Act, as amended by the California Privacy Rights Act, and the Virginia, Colorado, Connecticut, Utah, Texas, and Oregon consumer privacy laws), our use of cookies, pixels, and similar advertising and analytics technologies \u2014 including for cross-context behavioral advertising and targeted advertising \u2014 may be considered a \"sale\" or \"share\" of personal information. The categories of personal information involved typically include online identifiers, IP addresses, internet or other electronic network activity information, and inferences derived from this information.</p>`\n\t\t: '<p>We do not \"sell\" your personal information for monetary consideration. We do not \"share\" your personal information for cross-context behavioral advertising as those terms are defined under the California Privacy Rights Act (\"CPRA\") or comparable U.S. state privacy laws. We do not knowingly sell or share personal information of consumers under 16 years of age.</p>';\n\n\tlet recipients = '';\n\tif (sells) {\n\t\tconst partners = [...c.adsPlatforms, ...c.remarketingPlatforms];\n\t\tconst list_ = partners.length\n\t\t\t? `<p>The categories of third parties to which we may disclose personal information for these purposes include advertising networks, analytics providers, and marketing partners, including:</p>${list(\n\t\t\t\t\tpartners.map(escapeHtml)\n\t\t\t\t)}`\n\t\t\t: '<p>The categories of third parties to which we may disclose personal information for these purposes include advertising networks, analytics providers, social media platforms, and marketing partners.</p>';\n\t\trecipients = list_;\n\t}\n\n\tconst optOut = `<p><strong>Your right to opt out.</strong> You have the right to opt out of the sale or sharing of your personal information at any time. To exercise this right, you may use the controls described in the \"Tracking Technologies and Cookies\" section, change the privacy settings in your browser or mobile device, contact us using the methods listed in the \"Contact Us\" section, or send an opt-out preference signal \u2014 we honor the Global Privacy Control (\"GPC\") signal as a request to opt out of sale and sharing for the browser or device on which the signal is detected.</p>`;\n\n\treturn titledSection(\n\t\t'Sale or Sharing of Personal Information; Targeted Advertising',\n\t\t`${intro}${recipients}${optOut}`\n\t);\n};\n\nconst sectionCookies = (a: PrivacyAnswers, c: Computed) => {\n\tlet body = `<p>We use Cookies and similar tracking technologies (such as web beacons, pixels, tags, scripts, and software development kits) to track the activity on our Service and hold certain information.</p><p>Cookies can be \"Persistent\" or \"Session\" Cookies. Persistent Cookies remain on your personal computer or mobile device when you go offline, while Session Cookies are deleted as soon as you close your web browser.</p><h4>Categories of Cookies We Use</h4><ul><li><strong>Strictly Necessary Cookies.</strong> These are required for the operation of the Service and to provide functionalities you request, such as logging in or accessing secure areas. The Service cannot function properly without them.</li><li><strong>Performance / Analytics Cookies.</strong> These cookies allow us to count visits and traffic sources so we can measure and improve the performance of the Service.</li><li><strong>Functional Cookies.</strong> These cookies enable enhanced functionality and personalization, such as remembering your preferences.</li><li><strong>Targeting / Advertising Cookies.</strong> These cookies may be set through our Service by our advertising partners to build a profile of your interests and show you relevant advertisements on other sites.</li><li><strong>Cookies Policy / Notice Acceptance Cookies.</strong> These cookies identify whether users have accepted the use of cookies on the Service.</li></ul>`;\n\tif (a.tracking === 'yes' && c.trackingTools.length) {\n\t\tbody += `<p>We currently use the following analytics and tracking tools:</p>${list(c.trackingTools.map(escapeHtml))}`;\n\t}\n\tbody += `<h4>Your Choices About Cookies</h4><p>You can instruct your browser to refuse all Cookies or to indicate when a Cookie is being sent. If you do not accept Cookies, you may not be able to use some parts of our Service. You can also manage your cookie preferences through any cookie banner or preference center we provide.</p><h4>Do Not Track and Global Privacy Control</h4><p>Some browsers transmit \"Do Not Track\" (\"DNT\") or Global Privacy Control (\"GPC\") signals. There is currently no industry standard for responding to DNT signals, but we honor GPC signals as an opt-out of the sale or sharing of personal information for the browser or device on which the signal is detected, as required by applicable law.</p>`;\n\treturn titledSection('Tracking Technologies and Cookies', body);\n};\n\nconst sectionEmail = (a: PrivacyAnswers, c: Computed) =>\n\ta.sendEmails === 'yes'\n\t\t? titledSection(\n\t\t\t\t'Email Communications',\n\t\t\t\tc.emailPlatforms.length\n\t\t\t\t\t? `<p>We may send transactional, account-related, and (where you have opted in) marketing emails using the following platforms, who process email information on our behalf as service providers:</p>${list(\n\t\t\t\t\t\t\tc.emailPlatforms.map(escapeHtml)\n\t\t\t\t\t\t)}<p>You may unsubscribe from marketing emails at any time using the unsubscribe link included in those emails. Even if you unsubscribe from marketing emails, we may still send you transactional or account-related emails (for example, to confirm a purchase or notify you of changes to the Service).</p>`\n\t\t\t\t\t: '<p>We may send you transactional, account-related, and (where you have opted in) marketing emails. You may unsubscribe from marketing emails at any time using the unsubscribe link included in those emails.</p>'\n\t\t\t)\n\t\t: '';\n\nconst sectionRemarketing = (a: PrivacyAnswers, c: Computed) =>\n\ta.remarketing === 'yes'\n\t\t? titledSection(\n\t\t\t\t'Remarketing and Targeted Advertising',\n\t\t\t\tc.remarketingPlatforms.length\n\t\t\t\t\t? `<p>We use remarketing services to advertise to visitors of our Service on third-party websites and applications after they have visited the Service. These services may use cookies and similar technologies to deliver advertisements based on your past visits. The remarketing services we use include:</p>${list(\n\t\t\t\t\t\t\tc.remarketingPlatforms.map(escapeHtml)\n\t\t\t\t\t\t)}<p>You may opt out of personalized advertising by visiting the Network Advertising Initiative opt-out page (<a href=\"https://www.networkadvertising.org/choices/\" rel=\"external nofollow noopener\" target=\"_blank\">https://www.networkadvertising.org/choices/</a>), the Digital Advertising Alliance opt-out page (<a href=\"https://www.aboutads.info/choices/\" rel=\"external nofollow noopener\" target=\"_blank\">https://www.aboutads.info/choices/</a>), or the European Interactive Digital Advertising Alliance (<a href=\"https://www.youronlinechoices.eu\" rel=\"external nofollow noopener\" target=\"_blank\">https://www.youronlinechoices.eu</a>).</p>`\n\t\t\t\t\t: '<p>We use remarketing services to advertise to visitors of our Service on third-party websites and applications after they have visited the Service.</p>'\n\t\t\t)\n\t\t: '';\n\nconst sectionRetention = (c: Computed) =>\n\ttitledSection(\n\t\t'Retention of Your Personal Information',\n\t\t`<p>The Company will retain your Personal Information ${escapeHtml(\n\t\t\tc.retentionText\n\t\t)}. We will retain and use your Personal Information to the extent necessary to comply with our legal obligations (for example, if we are required to retain your data to comply with applicable laws), resolve disputes, and enforce our agreements and policies.</p><p>The Company will also retain Usage Data for internal analysis purposes. Usage Data is generally retained for a shorter period of time, except when this data is used to strengthen the security or to improve the functionality of our Service, or we are legally obligated to retain this data for longer periods.</p><p>When we no longer have a legitimate business need to process your Personal Information, we will either delete or anonymize it or, if this is not possible (for example, because your Personal Information has been stored in backup archives), we will securely store your Personal Information and isolate it from any further processing until deletion is possible.</p>`\n\t);\n\nconst sectionTransfers = () =>\n\ttitledSection('International Data Transfers', internationalTransfersBlock());\n\nconst sectionSecurity = () =>\n\ttitledSection(\n\t\t'Data Security',\n\t\t'<p>The security of your Personal Information is important to us, and we use commercially reasonable administrative, technical, and organizational measures designed to protect Personal Information against unauthorized access, alteration, disclosure, or destruction. However, no method of transmission over the Internet or method of electronic storage is 100% secure. While we strive to use commercially acceptable means to protect your Personal Information, we cannot guarantee its absolute security.</p>'\n\t);\n\nconst sectionAutomated = () =>\n\ttitledSection(\n\t\t'Automated Decision-Making',\n\t\t'<p>We do not use your Personal Information to make decisions based solely on automated processing \u2014 including profiling \u2014 that produce legal effects concerning you or similarly significantly affect you, except as may be necessary for entering into or performing a contract with you, where authorized by applicable law, or where you have given your explicit consent. If we ever do, we will provide meaningful information about the logic involved and the significance and envisaged consequences of such processing, and you may request human review of any such decision.</p>'\n\t);\n\nconst sectionRights = (a: PrivacyAnswers, c: Computed) => {\n\tconst intro =\n\t\t'<p>This section describes your privacy rights under applicable laws and how to exercise them. Even if a particular section does not apply to you, you may always contact us using the methods in the \"Contact Us\" section to ask about your privacy choices.</p>';\n\tlet body = intro;\n\tif (a.usStates === 'yes') {\n\t\tbody += subSection('U.S. State Privacy Rights', usStateRightsBlock(c.companyName));\n\t}\n\tif (a.gdpr === 'yes') {\n\t\tconst fan =\n\t\t\ta.facebookFanPage === 'yes' && a.facebookDetails\n\t\t\t\t? { name: a.facebookDetails.name ?? '', url: a.facebookDetails.url ?? '' }\n\t\t\t\t: null;\n\t\tbody += subSection(\n\t\t\t'EEA, UK, and Swiss Privacy Rights (GDPR)',\n\t\t\tgdprRightsBlock(c.companyName, fan)\n\t\t);\n\t}\n\tbody += subSection(\n\t\t'Right to Delete',\n\t\t'<p>You have the right to delete or request that we assist in deleting Personal Information that we have collected about you. Our Service may give you the ability to delete certain information from within the Service. You may also contact us to request access to, correct, or delete any personal information that you have provided to us. We may need to retain certain information when we have a legal obligation or lawful basis to do so.</p>'\n\t);\n\treturn titledSection('Your Privacy Rights', body);\n};\n\nconst sectionChildren = (a: PrivacyAnswers) => {\n\tlet body =\n\t\t'<p>Our Service is not directed to children under the age of 13 (or such higher age threshold as required by applicable law, including 16 for residents of certain jurisdictions). We do not knowingly collect Personal Information from children under 13. If you are a parent or guardian and you become aware that your child has provided us with Personal Information without your consent, please contact us so that we can take appropriate action. If we become aware that we have collected Personal Information from a child under 13 without verification of parental consent, we will take steps to remove that information from our servers.</p><p>For users in the European Economic Area, the United Kingdom, or other jurisdictions where consent from a parent or legal guardian is required for the processing of personal data of minors, we will not knowingly collect or process such data without the appropriate consent.</p>';\n\tif (a.kids === 'yes') {\n\t\tbody +=\n\t\t\t'<p><strong>Verifiable parental consent.</strong> Where we knowingly collect Personal Information from a child under 13, we will obtain verifiable parental consent before collection in accordance with the Children\u2019s Online Privacy Protection Act (\"COPPA\"). Parents may review the Personal Information collected from their child, request that we delete such information, and refuse to permit further collection or use of the child\u2019s Personal Information by contacting us using the methods in the \"Contact Us\" section.</p>';\n\t}\n\treturn titledSection('Children\u2019s Privacy', body);\n};\n\nconst sectionLinks = () =>\n\ttitledSection(\n\t\t'Links to Other Websites',\n\t\t'<p>Our Service may contain links to other websites that are not operated by us. If you click on a third-party link, you will be directed to that third party\u2019s site. We strongly advise you to review the privacy policy of every site you visit. We have no control over and assume no responsibility for the content, privacy policies, or practices of any third-party sites or services.</p>'\n\t);\n\nconst sectionChanges = () =>\n\ttitledSection(\n\t\t'Changes to This Privacy Policy',\n\t\t'<p>We may update this Privacy Policy from time to time. We will notify you of any material changes by posting the new Privacy Policy on this page and updating the \"Last updated\" date at the top of this Privacy Policy. Where required by law, we will provide a more prominent notice or seek your consent. You are advised to review this Privacy Policy periodically for any changes. Changes to this Privacy Policy are effective when they are posted on this page.</p>'\n\t);\n\nconst sectionContact = (a: PrivacyAnswers) => {\n\tconst items: string[] = [];\n\tif (a.contact?.methods?.includes('email') && a.contact.details.email) {\n\t\titems.push(\n\t\t\t`By email: <a href=\"mailto:${escapeHtml(a.contact.details.email)}\">${escapeHtml(\n\t\t\t\ta.contact.details.email\n\t\t\t)}</a>`\n\t\t);\n\t}\n\tif (a.contact?.methods?.includes('page') && a.contact.details.page) {\n\t\titems.push(\n\t\t\t`By visiting this page on our website: <a href=\"${escapeHtml(\n\t\t\t\ta.contact.details.page\n\t\t\t)}\" rel=\"external nofollow noopener\" target=\"_blank\">${escapeHtml(a.contact.details.page)}</a>`\n\t\t);\n\t}\n\tif (a.contact?.methods?.includes('phone') && a.contact.details.phone) {\n\t\titems.push(`By phone number: ${escapeHtml(a.contact.details.phone)}`);\n\t}\n\tif (a.contact?.methods?.includes('mail') && a.contact.details.address) {\n\t\titems.push(`By mail: ${escapeHtml(a.contact.details.address)}`);\n\t}\n\treturn `<section class=\"space-y-3\"><h2 class=\"text-xl font-semibold\">Contact Us</h2><p class=\"text-base leading-7\">If you have any questions about this Privacy Policy, you can contact us:</p>${list(items)}</section>`;\n};\n\nexport const generatePrivacyHtml = (answers: PrivacyAnswers) => {\n\tconst c = compute(answers);\n\n\tconst sections: string[] = [\n\t\tsectionHeader(c),\n\t\tsectionDefinitions(c),\n\t\tsectionCategoriesCollected(answers, c),\n\t\tsectionSources(),\n\t\tsectionUse(answers, c),\n\t\tsectionLegalBases(),\n\t\tsectionShare(answers, c),\n\t\tsectionSaleSharing(answers, c),\n\t\tsectionCookies(answers, c),\n\t\tsectionEmail(answers, c),\n\t\tsectionRemarketing(answers, c),\n\t\tsectionRetention(c),\n\t\tsectionTransfers(),\n\t\tsectionSecurity(),\n\t\tsectionAutomated(),\n\t\tsectionRights(answers, c),\n\t\tsectionChildren(answers),\n\t\tsectionLinks(),\n\t\tsectionChanges(),\n\t\tsectionContact(answers)\n\t].filter(Boolean);\n\n\treturn `<section data-role=\"content\">${sections.join('')}</section>`;\n};\n\nasync function promptWithCustom(\n\tmessage: string,\n\toptions: Array<{ value: string; label: string }>,\n\tcustomMessage: string\n): Promise<string[]> {\n\tconst selection = await p.multiselect({ message, options });\n\tif (p.isCancel(selection)) onCancel();\n\tconst values = selection as string[];\n\tif (values.includes('custom')) {\n\t\tconst custom = await p.text({ message: customMessage });\n\t\tif (p.isCancel(custom)) onCancel();\n\t\tconst idx = values.indexOf('custom');\n\t\tif (idx !== -1) values.splice(idx, 1);\n\t\tif (custom) values.push(String(custom));\n\t}\n\treturn values;\n}\n\nasync function privacyAction(): Promise<void> {\n\tconst { workspaceRootDir, publicRoutesDir } = await getWorkspace();\n\n\tconst core = await p.group(\n\t\t{\n\t\t\twebsiteUrl: sharedFields.websiteUrl,\n\t\t\twebsiteName: sharedFields.websiteName,\n\t\t\tentityType: sharedFields.entityType,\n\t\t\tbusinessName: sharedFields.businessName,\n\t\t\tbusinessAddress: sharedFields.businessAddress,\n\t\t\tcountry: sharedFields.country,\n\t\t\tstate: sharedFields.state\n\t\t},\n\t\t{ onCancel }\n\t);\n\n\tconst personalInfo = await p.multiselect({\n\t\tmessage: 'What kind of personal information do you collect from users? Check all that apply',\n\t\toptions: [\n\t\t\t{ value: 'email', label: 'Email address' },\n\t\t\t{ value: 'name', label: 'First name and last name' },\n\t\t\t{ value: 'phone', label: 'Phone number' },\n\t\t\t{ value: 'address', label: 'Address, State, Province, ZIP/Postal code, City' },\n\t\t\t{\n\t\t\t\tvalue: 'social',\n\t\t\t\tlabel:\n\t\t\t\t\t'Social Media Profile information (ie. from Connect with Facebook, Sign In With Twitter)'\n\t\t\t},\n\t\t\t{ value: 'other', label: 'Others' }\n\t\t],\n\t\trequired: false\n\t});\n\tif (p.isCancel(personalInfo)) onCancel();\n\n\tconst contact = await contactMethods('privacy');\n\n\tconst tracking = await p.select({\n\t\tmessage: 'Do you use tracking and/or analytics tools, such as Google Analytics?',\n\t\toptions: [\n\t\t\t{ value: 'yes', label: 'Yes, we use Google Analytics or other related tools' },\n\t\t\t{ value: 'no', label: 'No' }\n\t\t]\n\t});\n\tif (p.isCancel(tracking)) onCancel();\n\n\tlet trackingTools: string[] | undefined;\n\tif (tracking === 'yes') {\n\t\ttrackingTools = await promptWithCustom(\n\t\t\t'Select the tools you use for tracking and/or analytics',\n\t\t\t[\n\t\t\t\t{ value: 'ga', label: 'Google Analytics' },\n\t\t\t\t{ value: 'firebase', label: 'Firebase' },\n\t\t\t\t{ value: 'matomo', label: 'Matomo (formely Piwik)' },\n\t\t\t\t{ value: 'clicky', label: 'Clicky' },\n\t\t\t\t{ value: 'statcounter', label: 'Statcounter' },\n\t\t\t\t{ value: 'flurry', label: 'Flurry Analytics' },\n\t\t\t\t{ value: 'mixpanel', label: 'Mixpanel' },\n\t\t\t\t{ value: 'unity', label: 'Unity Analytics' },\n\t\t\t\t{ value: 'custom', label: 'Add your own' }\n\t\t\t],\n\t\t\t'Enter your custom tracking/analytics tool name'\n\t\t);\n\t}\n\n\tconst sendEmails = await p.select({\n\t\tmessage: 'Do you send emails to users?',\n\t\toptions: [\n\t\t\t{\n\t\t\t\tvalue: 'yes',\n\t\t\t\tlabel: 'Yes, we send emails to users or users can opt-in to receive emails from us'\n\t\t\t},\n\t\t\t{ value: 'no', label: 'No' }\n\t\t]\n\t});\n\tif (p.isCancel(sendEmails)) onCancel();\n\n\tlet emailPlatforms: string[] | undefined;\n\tif (sendEmails === 'yes') {\n\t\temailPlatforms = await promptWithCustom(\n\t\t\t'Select the platforms you use to send emails',\n\t\t\t[\n\t\t\t\t{ value: 'mailchimp', label: 'Mailchimp' },\n\t\t\t\t{ value: 'constant-contact', label: 'Constant Contact' },\n\t\t\t\t{ value: 'aweber', label: 'AWeber' },\n\t\t\t\t{ value: 'getresponse', label: 'GetResponse' },\n\t\t\t\t{ value: 'custom', label: 'Add your own' }\n\t\t\t],\n\t\t\t'Enter your custom email platform'\n\t\t);\n\t}\n\n\tconst showAds = await p.select({\n\t\tmessage: 'Do you show ads?',\n\t\toptions: [\n\t\t\t{ value: 'yes', label: 'Yes, we show ads' },\n\t\t\t{ value: 'no', label: 'No' }\n\t\t]\n\t});\n\tif (p.isCancel(showAds)) onCancel();\n\n\tlet adsPlatforms: string[] | undefined;\n\tif (showAds === 'yes') {\n\t\tadsPlatforms = await promptWithCustom(\n\t\t\t'Select the platforms you use to show ads',\n\t\t\t[\n\t\t\t\t{ value: 'adsense', label: 'Google Ads (AdSense)' },\n\t\t\t\t{ value: 'admob', label: 'AdMob by Google' },\n\t\t\t\t{ value: 'bing', label: 'Bing Ads' },\n\t\t\t\t{ value: 'flurry', label: 'Flurry' },\n\t\t\t\t{ value: 'inmobi', label: 'InMobi' },\n\t\t\t\t{ value: 'mopub', label: 'MoPub' },\n\t\t\t\t{ value: 'startapp', label: 'StartApp' },\n\t\t\t\t{ value: 'adcolony', label: 'AdColony' },\n\t\t\t\t{ value: 'applovin', label: 'AppLovin' },\n\t\t\t\t{ value: 'vungle', label: 'Vungle' },\n\t\t\t\t{ value: 'adbutler', label: 'AdButler' },\n\t\t\t\t{ value: 'unity-ads', label: 'Unity Ads' },\n\t\t\t\t{ value: 'custom', label: 'Add your own' }\n\t\t\t],\n\t\t\t'Enter your custom ads platform'\n\t\t);\n\t}\n\n\tconst canPay = await p.select({\n\t\tmessage: 'Can users pay for products or services?',\n\t\toptions: [\n\t\t\t{ value: 'yes', label: 'Yes, users can pay for our products/services' },\n\t\t\t{\n\t\t\t\tvalue: 'no',\n\t\t\t\tlabel: 'No, we do not sell anything or allow users to pay for products/services'\n\t\t\t}\n\t\t]\n\t});\n\tif (p.isCancel(canPay)) onCancel();\n\n\tlet paymentProcessors: string[] | undefined;\n\tif (canPay === 'yes') {\n\t\tpaymentProcessors = await promptWithCustom(\n\t\t\t'Select the payment processors/methods',\n\t\t\t[\n\t\t\t\t{ value: 'apple-iap', label: 'Apple Store In-App Payments' },\n\t\t\t\t{ value: 'google-iap', label: 'Google Play In-App Payments' },\n\t\t\t\t{ value: 'paypal', label: 'PayPal' },\n\t\t\t\t{ value: 'braintree', label: 'Braintree' },\n\t\t\t\t{ value: 'stripe', label: 'Stripe' },\n\t\t\t\t{ value: 'fastspring', label: 'FastSpring' },\n\t\t\t\t{ value: 'shopify', label: 'Shopify' },\n\t\t\t\t{ value: 'square', label: 'Square' },\n\t\t\t\t{ value: '2checkout', label: '2Checkout' },\n\t\t\t\t{ value: 'wepay', label: 'WePay' },\n\t\t\t\t{ value: 'worldpay', label: 'WorldPay' },\n\t\t\t\t{ value: 'authorize-net', label: 'Authorize.net' },\n\t\t\t\t{ value: 'sage-pay', label: 'Sage Pay' },\n\t\t\t\t{ value: 'gocardless', label: 'Go Cardless' },\n\t\t\t\t{ value: 'elavon', label: 'Elavon' },\n\t\t\t\t{ value: 'verifone', label: 'Verifone' },\n\t\t\t\t{ value: 'moneris', label: 'Moneris' },\n\t\t\t\t{ value: 'wechat', label: 'WeChat' },\n\t\t\t\t{ value: 'alipay', label: 'Alipay' },\n\t\t\t\t{ value: 'bank', label: 'Bank Transfer' },\n\t\t\t\t{ value: 'custom', label: 'Add your own' }\n\t\t\t],\n\t\t\t'Enter your custom payment processor/method'\n\t\t);\n\t}\n\n\tconst remarketing = await p.select({\n\t\tmessage: 'Do you use remarketing services for marketing & advertising purposes?',\n\t\toptions: [\n\t\t\t{ value: 'yes', label: 'Yes, we use remarketing services to advertise our business' },\n\t\t\t{ value: 'no', label: 'No' }\n\t\t]\n\t});\n\tif (p.isCancel(remarketing)) onCancel();\n\n\tlet remarketingPlatforms: string[] | undefined;\n\tif (remarketing === 'yes') {\n\t\tremarketingPlatforms = await promptWithCustom(\n\t\t\t'Select the platforms you use for remarketing purposes',\n\t\t\t[\n\t\t\t\t{ value: 'google-ads', label: 'Google Ads (AdWords)' },\n\t\t\t\t{ value: 'twitter', label: 'Twitter' },\n\t\t\t\t{ value: 'facebook', label: 'Facebook' },\n\t\t\t\t{ value: 'bing', label: 'Bing Ads' },\n\t\t\t\t{ value: 'pinterest', label: 'Pinterest' },\n\t\t\t\t{ value: 'adroll', label: 'AdRoll' },\n\t\t\t\t{ value: 'perfect-audience', label: 'Perfect Audience' },\n\t\t\t\t{ value: 'appnexus', label: 'AppNexus' },\n\t\t\t\t{ value: 'custom', label: 'Add your own' }\n\t\t\t],\n\t\t\t'Enter your custom remarketing platform'\n\t\t);\n\t}\n\n\tconst providersRaw = await p.multiselect({\n\t\tmessage: 'Select if you use any of the following providers',\n\t\toptions: [\n\t\t\t{ value: 'recaptcha', label: 'Invisible reCAPTCHA' },\n\t\t\t{ value: 'google-places', label: 'Google Places' },\n\t\t\t{ value: 'mouseflow', label: 'Mouseflow' },\n\t\t\t{ value: 'freshdesk', label: 'FreshDesk' },\n\t\t\t{ value: 'custom', label: 'Add your own' }\n\t\t],\n\t\trequired: false\n\t});\n\tif (p.isCancel(providersRaw)) onCancel();\n\n\tconst providers = providersRaw as string[];\n\tif (providers.includes('custom')) {\n\t\tconst custom = await p.text({ message: 'Enter your custom provider' });\n\t\tif (p.isCancel(custom)) onCancel();\n\t\tconst idx = providers.indexOf('custom');\n\t\tif (idx !== -1) providers.splice(idx, 1);\n\t\tif (custom) providers.push(String(custom));\n\t}\n\n\tconst usStates = await p.select({\n\t\tmessage:\n\t\t\t'Include U.S. state privacy rights (CCPA/CPRA, VCDPA, CPA, CTDPA, UCPA, TX, OR, etc.)?',\n\t\toptions: [\n\t\t\t{\n\t\t\t\tvalue: 'yes',\n\t\t\t\tlabel: 'Yes. Include comprehensive U.S. state privacy rights and disclosures'\n\t\t\t},\n\t\t\t{ value: 'no', label: 'No' }\n\t\t],\n\t\tinitialValue: 'yes'\n\t});\n\tif (p.isCancel(usStates)) onCancel();\n\n\tconst gdpr = await p.select({\n\t\tmessage: 'Do you want your Privacy Policy to include GDPR / UK GDPR wording?',\n\t\toptions: [\n\t\t\t{ value: 'yes', label: 'Yes. Include GDPR rights for EEA, UK, and Swiss residents' },\n\t\t\t{ value: 'no', label: 'No' }\n\t\t]\n\t});\n\tif (p.isCancel(gdpr)) onCancel();\n\n\tlet facebookFanPage: 'yes' | 'no' = 'no';\n\tconst facebookDetails: { name: string; url: string } = { name: '', url: '' };\n\tif (gdpr === 'yes') {\n\t\tconst fan = await p.select({\n\t\t\tmessage: 'Do you have a Facebook Fan Page?',\n\t\t\toptions: [\n\t\t\t\t{ value: 'yes', label: 'Yes, we have a Facebook Fan Page' },\n\t\t\t\t{ value: 'no', label: 'No' }\n\t\t\t]\n\t\t});\n\t\tif (p.isCancel(fan)) onCancel();\n\t\tfacebookFanPage = fan as 'yes' | 'no';\n\t\tif (facebookFanPage === 'yes') {\n\t\t\tconst name = await p.text({\n\t\t\t\tmessage: 'What is the name of the Facebook Fan Page?',\n\t\t\t\tplaceholder: 'My Facebook Page'\n\t\t\t});\n\t\t\tif (p.isCancel(name)) onCancel();\n\t\t\tfacebookDetails.name = name as string;\n\t\t\tconst url = await p.text({\n\t\t\t\tmessage: 'What is the URL of the Facebook Fan Page?',\n\t\t\t\tplaceholder: 'https://facebook.com/my-facebook-page'\n\t\t\t});\n\t\t\tif (p.isCancel(url)) onCancel();\n\t\t\tfacebookDetails.url = url as string;\n\t\t}\n\t}\n\n\tconst kids = await p.select({\n\t\tmessage: 'Do you collect information from kids under the age of 13?',\n\t\toptions: [\n\t\t\t{ value: 'yes', label: 'Yes. We collect information from children under the age of 13' },\n\t\t\t{ value: 'no', label: 'No' }\n\t\t]\n\t});\n\tif (p.isCancel(kids)) onCancel();\n\n\tconst retention = await p.text({\n\t\tmessage: 'How long do you retain personal information? (leave blank for default wording)',\n\t\tplaceholder: 'e.g. 12 months after account closure'\n\t});\n\tif (p.isCancel(retention)) onCancel();\n\n\tconst html = generatePrivacyHtml({\n\t\tcore,\n\t\tpersonalInfo: (personalInfo ?? []) as Array<\n\t\t\t'phone' | 'address' | 'email' | 'name' | 'social' | 'other'\n\t\t>,\n\t\tcontact,\n\t\ttracking: tracking as 'yes' | 'no',\n\t\ttrackingTools: tracking === 'yes' ? trackingTools : [],\n\t\tsendEmails: sendEmails as 'yes' | 'no',\n\t\temailPlatforms: sendEmails === 'yes' ? emailPlatforms : [],\n\t\tshowAds: showAds as 'yes' | 'no',\n\t\tadsPlatforms: showAds === 'yes' ? adsPlatforms : [],\n\t\tcanPay: canPay as 'yes' | 'no',\n\t\tpaymentProcessors: canPay === 'yes' ? paymentProcessors : [],\n\t\tremarketing: remarketing as 'yes' | 'no',\n\t\tremarketingPlatforms: remarketing === 'yes' ? remarketingPlatforms : [],\n\t\tproviders,\n\t\tusStates: usStates as 'yes' | 'no',\n\t\tgdpr: gdpr as 'yes' | 'no',\n\t\tfacebookFanPage,\n\t\tfacebookDetails,\n\t\tkids: kids as 'yes' | 'no',\n\t\tretention: retention as string | undefined\n\t});\n\n\tconst privacyPage = path.join(\n\t\tworkspaceRootDir,\n\t\tpublicRoutesDir,\n\t\tLEGAL_DIR,\n\t\t'privacy',\n\t\t'+page.svelte'\n\t);\n\tconst privacyPageTs = path.join(\n\t\tworkspaceRootDir,\n\t\tpublicRoutesDir,\n\t\tLEGAL_DIR,\n\t\t'privacy',\n\t\t'+page.ts'\n\t);\n\tfs.mkdirSync(path.dirname(privacyPage), { recursive: true });\n\tfs.writeFileSync(privacyPage, html);\n\tfs.writeFileSync(\n\t\tprivacyPageTs,\n\t\tpageMetaTagsLoader('Privacy Policy', `Privacy Policy for ${core.websiteName}`)\n\t);\n\n\tconst relativePrivacyPage = path.relative(workspaceRootDir, privacyPage);\n\tconst relativePrivacyPageTs = path.relative(workspaceRootDir, privacyPageTs);\n\treportResult({\n\t\tsummary: 'Generated placeholder privacy policy.',\n\t\tfilesCreated: [relativePrivacyPage, relativePrivacyPageTs],\n\t\tnextSteps: [\n\t\t\t`Review the generated copy in ${relativePrivacyPage} and fill in company-specific details (data processors, retention, contact info).`,\n\t\t\t'Have the final document reviewed by a lawyer before publishing \u2014 this is a starter template, not legal advice.',\n\t\t\t'Link to /privacy from your footer and sign-up flow.'\n\t\t]\n\t});\n}\n\nexport const privacy = new Command('privacy')\n\t.description('generate placeholder privacy policy')\n\t.configureHelp(helpConfig)\n\t.action(() => runCommand(privacyAction, 'Failed to generate privacy policy.'));\n", "import { Command } from 'commander';\nimport { helpConfig } from '../lib/help.ts';\nimport { load } from './fixtures/load.ts';\nimport { clear } from './fixtures/clear.ts';\nimport { reset } from './fixtures/reset.ts';\nimport { generate } from './fixtures/generate.ts';\nimport { regen } from './fixtures/regen.ts';\n\nexport const fixtures = new Command('fixtures')\n\t.description('manage fixture data')\n\t.configureHelp(helpConfig)\n\t.addCommand(generate)\n\t.addCommand(load)\n\t.addCommand(clear)\n\t.addCommand(reset)\n\t.addCommand(regen);\n", "import fs from 'node:fs';\nimport path from 'node:path';\nimport { Command } from 'commander';\nimport type PocketBase from 'pocketbase';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand } from '../../lib/run.ts';\nimport { withPocketbase } from '../../lib/pocketbase.ts';\nimport { getWorkspace } from '../../lib/workspace.ts';\nimport { FIXTURE_PREFIX } from '../../lib/constants.ts';\nimport { reportResult } from '../../lib/result-report.ts';\n\nexport function getFixtureFiles(\n\tcwd: string\n): Array<{ collectionName: string; fixturePath: string }> {\n\tconst fixturesDir = path.join(cwd, 'data', 'fixtures');\n\tif (!fs.existsSync(fixturesDir)) return [];\n\treturn fs\n\t\t.readdirSync(fixturesDir)\n\t\t.filter((file) => file.endsWith('.json'))\n\t\t.map((file) => path.join(fixturesDir, file))\n\t\t.sort((a, b) => a.localeCompare(b))\n\t\t.map((fixturePath) => {\n\t\t\tconst file = path.basename(fixturePath);\n\t\t\tconst nameWithoutExt = file.replace(/\\.json$/i, '');\n\t\t\tconst collectionName = nameWithoutExt.replace(/^\\d+[-_]?/, '');\n\t\t\treturn { collectionName, fixturePath };\n\t\t});\n}\n\nexport async function loadFixtures(pb: PocketBase, workspaceRootDir: string): Promise<string[]> {\n\tconst fixtureFiles = getFixtureFiles(workspaceRootDir);\n\tif (fixtureFiles.length === 0) return [];\n\n\tconst loaded: string[] = [];\n\tfor (const { collectionName, fixturePath } of fixtureFiles) {\n\t\tconst shortName = collectionName.slice(0, 6);\n\t\tconst existing = await pb.collection(collectionName).getFullList({\n\t\t\tfilter: `id ~ \"${FIXTURE_PREFIX}${shortName}%\"`,\n\t\t\tfields: 'id'\n\t\t});\n\t\tif (existing.length > 0) {\n\t\t\tthrow new Error(\n\t\t\t\t`${collectionName} collection already has fixture records. ` +\n\t\t\t\t\t'Run `vela fixtures reset` to clear and reload, or `vela fixtures clear` first.'\n\t\t\t);\n\t\t}\n\n\t\tconst items = JSON.parse(fs.readFileSync(fixturePath, 'utf8')) as Array<\n\t\t\tRecord<string, unknown>\n\t\t>;\n\t\tfor (const fixture of items) {\n\t\t\tawait pb.collection(collectionName).create(fixture);\n\t\t}\n\t\tloaded.push(`${path.relative(workspaceRootDir, fixturePath)} (${items.length} records)`);\n\t}\n\treturn loaded;\n}\n\nexport const load = new Command('load')\n\t.description('load fixtures into the database')\n\t.configureHelp(helpConfig)\n\t.action(() =>\n\t\trunCommand(async () => {\n\t\t\tconst { workspaceRootDir } = await getWorkspace();\n\t\t\tlet loaded: string[] = [];\n\t\t\tawait withPocketbase(workspaceRootDir, async (pb) => {\n\t\t\t\tloaded = await loadFixtures(pb, workspaceRootDir);\n\t\t\t});\n\n\t\t\tif (loaded.length === 0) {\n\t\t\t\treportResult({\n\t\t\t\t\tsummary: 'No fixture files found in data/fixtures.',\n\t\t\t\t\tnextSteps: ['Run `vela fixtures generate` to create fixture files first.']\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\treportResult({\n\t\t\t\tsummary: `Loaded ${loaded.length} fixture file(s) into the database.`,\n\t\t\t\trecordsLoaded: loaded,\n\t\t\t\tnextSteps: [\n\t\t\t\t\t'Run `vela dev` to see the fixture data in the app.',\n\t\t\t\t\t'Run `vela fixtures clear` to remove the loaded fixture records.'\n\t\t\t\t]\n\t\t\t});\n\t\t}, 'Failed to load fixtures.')\n\t);\n", "import path from 'node:path';\nimport { Command } from 'commander';\nimport type PocketBase from 'pocketbase';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand } from '../../lib/run.ts';\nimport { withPocketbase } from '../../lib/pocketbase.ts';\nimport { getWorkspace } from '../../lib/workspace.ts';\nimport { dependencyOrder } from '../../lib/collections.ts';\nimport { FIXTURE_PREFIX } from '../../lib/constants.ts';\nimport { reportResult } from '../../lib/result-report.ts';\nimport { getFixtureFiles } from './load.ts';\n\nexport async function clearFixtures(pb: PocketBase, workspaceRootDir: string): Promise<string[]> {\n\tconst fixturePathByName = new Map(\n\t\tgetFixtureFiles(workspaceRootDir).map((f) => [f.collectionName, f.fixturePath])\n\t);\n\n\tconst cleared: string[] = [];\n\tconst fullList = await pb.collections.getFullList();\n\tconst collections = fullList.map((c) => ({\n\t\tid: c.id,\n\t\tname: c.name,\n\t\tfields: c.fields.map((f) => ({\n\t\t\ttype: f.type,\n\t\t\tcollectionId: (f as { collectionId?: string }).collectionId\n\t\t}))\n\t}));\n\n\tconst { names } = dependencyOrder(collections);\n\tconst reversed = [...names].reverse();\n\n\tfor (const collectionName of reversed) {\n\t\tconst shortName = collectionName.slice(0, 6);\n\t\tconst records = await pb.collection(collectionName).getFullList({\n\t\t\tfilter: `id ~ \"${FIXTURE_PREFIX}${shortName}%\"`,\n\t\t\tfields: 'id'\n\t\t});\n\n\t\tif (records.length === 0) continue;\n\n\t\tfor (const { id } of records) {\n\t\t\tawait pb.collection(collectionName).delete(id);\n\t\t}\n\t\tconst fixturePath = fixturePathByName.get(collectionName);\n\t\tconst label = fixturePath ? path.relative(workspaceRootDir, fixturePath) : collectionName;\n\t\tcleared.push(`${label} (${records.length} records)`);\n\t}\n\n\treturn cleared;\n}\n\nexport const clear = new Command('clear')\n\t.description('clear loaded fixtures')\n\t.configureHelp(helpConfig)\n\t.action(() =>\n\t\trunCommand(async () => {\n\t\t\tconst { workspaceRootDir } = await getWorkspace();\n\t\t\tlet cleared: string[] = [];\n\t\t\tawait withPocketbase(workspaceRootDir, async (pb) => {\n\t\t\t\tcleared = await clearFixtures(pb, workspaceRootDir);\n\t\t\t});\n\n\t\t\tif (cleared.length === 0) {\n\t\t\t\treportResult({\n\t\t\t\t\tsummary: 'No fixtures to clear.',\n\t\t\t\t\tnextSteps: [\n\t\t\t\t\t\t'Run `vela fixtures generate` to create fixture files.',\n\t\t\t\t\t\t'Run `vela fixtures load` to load them into the database.'\n\t\t\t\t\t]\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\treportResult({\n\t\t\t\tsummary: `Cleared ${cleared.length} fixture collection(s) from the database.`,\n\t\t\t\trecordsCleared: cleared,\n\t\t\t\tnextSteps: [\n\t\t\t\t\t'Run `vela fixtures load` to reload the existing fixture files.',\n\t\t\t\t\t'Run `vela fixtures generate --force` to regenerate fixture files from scratch.'\n\t\t\t\t]\n\t\t\t});\n\t\t}, 'Failed to clear fixtures.')\n\t);\n", "export interface CollectionLike {\n\tid: string;\n\tname: string;\n\tfields: Array<{ type: string; collectionId?: string }>;\n}\n\nexport function dependencyOrder(\n\tcollections: CollectionLike[],\n\tstartingCollectionId?: string\n): { ids: string[]; names: string[] } {\n\tconst order: string[] = [];\n\tconst visited: Record<string, boolean> = {};\n\tconst queue: string[] = [];\n\n\tconst eligible = collections.filter((c) => !c.name.startsWith('_'));\n\n\tif (startingCollectionId) {\n\t\tqueue.push(startingCollectionId);\n\t} else {\n\t\tfor (const collection of eligible) {\n\t\t\tif (!visited[collection.id]) {\n\t\t\t\tvisited[collection.id] = true;\n\t\t\t\tqueue.push(collection.id);\n\t\t\t}\n\t\t}\n\t}\n\n\twhile (queue.length > 0) {\n\t\tconst collectionId = queue.shift();\n\t\tif (!collectionId) continue;\n\t\torder.push(collectionId);\n\n\t\tconst source = collections.find((c) => c.id === collectionId);\n\t\tfor (const field of source?.fields ?? []) {\n\t\t\tif (field.type === 'relation' && field.collectionId && !visited[field.collectionId]) {\n\t\t\t\tvisited[field.collectionId] = true;\n\t\t\t\tqueue.push(field.collectionId);\n\t\t\t}\n\t\t}\n\t}\n\n\tconst nameById = Object.fromEntries(collections.map((c) => [c.id, c.name]));\n\treturn { ids: order, names: order.map((id) => nameById[id]!) };\n}\n", "import { Command } from 'commander';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand } from '../../lib/run.ts';\nimport { withPocketbase } from '../../lib/pocketbase.ts';\nimport { getWorkspace } from '../../lib/workspace.ts';\nimport { reportResult } from '../../lib/result-report.ts';\nimport { clearFixtures } from './clear.ts';\nimport { loadFixtures } from './load.ts';\n\nexport const reset = new Command('reset')\n\t.description('clear and reload fixtures')\n\t.configureHelp(helpConfig)\n\t.action(() =>\n\t\trunCommand(async () => {\n\t\t\tconst { workspaceRootDir } = await getWorkspace();\n\t\t\tlet cleared: string[] = [];\n\t\t\tlet loaded: string[] = [];\n\t\t\tawait withPocketbase(workspaceRootDir, async (pb) => {\n\t\t\t\tcleared = await clearFixtures(pb, workspaceRootDir);\n\t\t\t\tloaded = await loadFixtures(pb, workspaceRootDir);\n\t\t\t});\n\n\t\t\tif (loaded.length === 0) {\n\t\t\t\treportResult({\n\t\t\t\t\tsummary: 'No fixture files found in data/fixtures.',\n\t\t\t\t\trecordsCleared: cleared,\n\t\t\t\t\tnextSteps: ['Run `vela fixtures generate` to create fixture files first.']\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\treportResult({\n\t\t\t\tsummary: `Reset fixtures (${loaded.length} collection(s) reloaded).`,\n\t\t\t\trecordsCleared: cleared,\n\t\t\t\trecordsLoaded: loaded,\n\t\t\t\tnextSteps: [\n\t\t\t\t\t'Run `vela dev` to see the freshly reloaded fixture data.',\n\t\t\t\t\t'Run `vela fixtures regen` if you also want to regenerate the fixture files.'\n\t\t\t\t]\n\t\t\t});\n\t\t}, 'Failed to reset fixtures.')\n\t);\n", "import fs from 'node:fs';\nimport path from 'node:path';\nimport { Command, InvalidArgumentError } from 'commander';\nimport * as p from '@clack/prompts';\nimport type PocketBase from 'pocketbase';\nimport { annotate } from 'annotate-json-schema';\nimport { createGenerator, type JsonSchema } from 'json-schema-faker';\nimport { faker } from '@faker-js/faker';\nimport { collectionToJsonSchema } from '@velastack/pocketbase-codegen';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand } from '../../lib/run.ts';\nimport { withPocketbase } from '../../lib/pocketbase.ts';\nimport { getWorkspace } from '../../lib/workspace.ts';\nimport { dependencyOrder } from '../../lib/collections.ts';\nimport { FIXTURE_PREFIX } from '../../lib/constants.ts';\nimport { reportResult } from '../../lib/result-report.ts';\nimport { clearFixtures } from './clear.ts';\nimport { getFixtureFiles } from './load.ts';\n\nconst SKIP_TYPES = new Set(['autodate', 'file', 'relation']);\nconst AUTH_OVERRIDE_FIELDS = ['email', 'password', 'passwordConfirm', 'tokenKey'];\n\nfunction padZeros(num: number, length: number) {\n\treturn num.toString().padStart(length, '0');\n}\n\nfunction parseCount(value: string): number {\n\tconst n = parseInt(value, 10);\n\tif (!Number.isFinite(n) || n <= 0 || n > 999) {\n\t\tthrow new InvalidArgumentError('count must be between 1 and 999');\n\t}\n\treturn n;\n}\n\nfunction parseSeed(value: string): number {\n\tconst n = parseInt(value, 10);\n\tif (!Number.isFinite(n)) {\n\t\tthrow new InvalidArgumentError('seed must be an integer');\n\t}\n\treturn n;\n}\n\nexport async function hasLoadedFixtures(pb: PocketBase): Promise<boolean> {\n\tconst fullList = await pb.collections.getFullList();\n\tfor (const collection of fullList) {\n\t\tif (collection.name.startsWith('_')) continue;\n\t\tconst shortName = collection.name.slice(0, 6);\n\t\tconst page = await pb.collection(collection.name).getList(1, 1, {\n\t\t\tfilter: `id ~ \"${FIXTURE_PREFIX}${shortName}%\"`,\n\t\t\tfields: 'id'\n\t\t});\n\t\tif (page.totalItems > 0) return true;\n\t}\n\treturn false;\n}\n\ntype CollectionSummary = Parameters<typeof collectionToJsonSchema>[0];\ntype FieldSummary = CollectionSummary['fields'][number];\n\nasync function loadCollections(pb: PocketBase): Promise<CollectionSummary[]> {\n\tconst list = await pb.collections.getFullList();\n\treturn list.map((c) => ({\n\t\tid: c.id,\n\t\tname: c.name,\n\t\ttype: c.type as CollectionSummary['type'],\n\t\tfields: c.fields as FieldSummary[]\n\t}));\n}\n\nexport interface GenerateFixturesOptions {\n\tcount: number;\n\tseed?: number;\n}\n\nexport interface GenerateFixturesResult {\n\twrittenFiles: string[];\n\twarnings: string[];\n}\n\nexport async function generateFixtureFiles(\n\tpb: PocketBase,\n\tworkspaceRootDir: string,\n\topts: GenerateFixturesOptions\n): Promise<GenerateFixturesResult> {\n\tconst fixturesDir = path.join(workspaceRootDir, 'data', 'fixtures');\n\tfs.mkdirSync(fixturesDir, { recursive: true });\n\tfor (const file of fs.readdirSync(fixturesDir)) {\n\t\tif (file.endsWith('.json')) fs.unlinkSync(path.join(fixturesDir, file));\n\t}\n\n\tif (opts.seed !== undefined) faker.seed(opts.seed);\n\tconst generator = createGenerator({\n\t\textensions: { faker },\n\t\talwaysFakeOptionals: true,\n\t\t...(opts.seed !== undefined ? { seed: opts.seed } : {})\n\t});\n\n\tconst collections = await loadCollections(pb);\n\tconst eligible = collections.filter((c) => !c.name.startsWith('_') && c.type !== 'view');\n\tconst { ids } = dependencyOrder(eligible);\n\n\tconst recordIds = new Map<string, string[]>();\n\tids.forEach((id) => recordIds.set(id, []));\n\n\tconst writtenFiles: string[] = [];\n\tconst warnings: string[] = [];\n\tlet fileIndex = 1;\n\tfor (const collectionId of ids) {\n\t\tconst collection = eligible.find((c) => c.id === collectionId);\n\t\tif (!collection) continue;\n\n\t\tfor (const f of collection.fields) {\n\t\t\tif (f.type !== 'relation' || !f.required) continue;\n\t\t\tconst pool = f.collectionId ? recordIds.get(f.collectionId) : undefined;\n\t\t\tif (!pool || pool.length === 0) {\n\t\t\t\tconst target = collections.find((c) => c.id === f.collectionId);\n\t\t\t\tconst targetLabel = target?.name ?? f.collectionId ?? '<unknown>';\n\t\t\t\twarnings.push(\n\t\t\t\t\t`${collection.name}.${f.name} requires a ${targetLabel} record, but none were generated yet`\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\tconst schema = collectionToJsonSchema(collection);\n\t\tconst properties = schema.properties as Record<string, unknown>;\n\t\tdelete properties.id;\n\t\tfor (const f of collection.fields) {\n\t\t\tif (SKIP_TYPES.has(f.type)) delete properties[f.name];\n\t\t}\n\t\tif (collection.type === 'auth') {\n\t\t\tfor (const name of AUTH_OVERRIDE_FIELDS) delete properties[name];\n\t\t}\n\t\tschema.required = schema.required.filter((name) => name in properties);\n\n\t\tconst annotated = annotate(schema as JsonSchema, collection.name);\n\n\t\tconst items: Record<string, unknown>[] = [];\n\t\tfor (let idx = 0; idx < opts.count; idx++) {\n\t\t\tconst record = (await generator.generate(annotated)) as Record<string, unknown>;\n\n\t\t\tconst shortName = collection.name.slice(0, 6);\n\t\t\tconst remaining = 15 - shortName.length - FIXTURE_PREFIX.length;\n\t\t\tconst id = `${FIXTURE_PREFIX}${shortName}${padZeros(idx + 1, remaining)}`;\n\t\t\trecord.id = id;\n\t\t\trecordIds.get(collection.id)!.push(id);\n\n\t\t\tfor (const f of collection.fields) {\n\t\t\t\tif (f.type !== 'relation') continue;\n\t\t\t\tconst parentIds = f.collectionId ? (recordIds.get(f.collectionId) ?? []) : [];\n\t\t\t\tif (parentIds.length === 0) continue;\n\t\t\t\tconst multi = f.maxSelect !== undefined && f.maxSelect > 1;\n\t\t\t\trecord[f.name] = multi\n\t\t\t\t\t? [faker.helpers.arrayElement(parentIds)]\n\t\t\t\t\t: faker.helpers.arrayElement(parentIds);\n\t\t\t}\n\n\t\t\tif (collection.type === 'auth') {\n\t\t\t\trecord.email = `${faker.string.uuid()}@example.com`;\n\t\t\t\trecord.password = 'password';\n\t\t\t\trecord.passwordConfirm = 'password';\n\t\t\t}\n\n\t\t\titems.push(record);\n\t\t}\n\n\t\tconst filename = `${padZeros(fileIndex, 2)}-${collection.name}.json`;\n\t\tfs.writeFileSync(path.join(fixturesDir, filename), JSON.stringify(items, null, 2));\n\t\twrittenFiles.push(`${path.join('data', 'fixtures', filename)} (${items.length} records)`);\n\t\tfileIndex++;\n\t}\n\n\treturn { writtenFiles, warnings };\n}\n\nexport const generate = new Command('generate')\n\t.description('generate fixture data')\n\t.option('-c, --count <count>', 'number of records per collection', parseCount, 10)\n\t.option('-s, --seed <seed>', 'seed for deterministic output', parseSeed)\n\t.option('-f, --force', 'overwrite existing fixture files and clear loaded fixtures')\n\t.configureHelp(helpConfig)\n\t.action((opts: { count: number; seed?: number; force?: boolean }) =>\n\t\trunCommand(async () => {\n\t\t\tconst { workspaceRootDir } = await getWorkspace();\n\t\t\tconst existing = getFixtureFiles(workspaceRootDir);\n\n\t\t\tif (existing.length > 0 && !opts.force) {\n\t\t\t\tawait withPocketbase(workspaceRootDir, async (pb) => {\n\t\t\t\t\tconst loaded = await hasLoadedFixtures(pb);\n\t\t\t\t\tif (loaded) {\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t'Existing fixture files found and fixtures are loaded in the database. ' +\n\t\t\t\t\t\t\t\t'Run `vela fixtures reset` to clear + reload, or `vela fixtures clear` then `vela fixtures generate --force`.'\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t'Existing fixture files found in data/fixtures. Pass --force to overwrite.'\n\t\t\t\t\t);\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tlet result: GenerateFixturesResult = { writtenFiles: [], warnings: [] };\n\t\t\tlet cleared: string[] = [];\n\t\t\tawait withPocketbase(workspaceRootDir, async (pb) => {\n\t\t\t\tif (opts.force) {\n\t\t\t\t\tcleared = await clearFixtures(pb, workspaceRootDir);\n\t\t\t\t}\n\t\t\t\tresult = await generateFixtureFiles(pb, workspaceRootDir, {\n\t\t\t\t\tcount: opts.count,\n\t\t\t\t\tseed: opts.seed\n\t\t\t\t});\n\t\t\t});\n\n\t\t\tfor (const warning of result.warnings) p.log.warn(warning);\n\n\t\t\tif (result.writtenFiles.length === 0) {\n\t\t\t\treportResult({\n\t\t\t\t\tsummary: 'No eligible collections found to generate fixtures for.',\n\t\t\t\t\tnextSteps: [\n\t\t\t\t\t\t'Create collections with `vela generate scaffold <model>` or in the PocketBase admin UI.',\n\t\t\t\t\t\t'Run `vela fixtures generate` again once you have at least one collection.'\n\t\t\t\t\t]\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\treportResult({\n\t\t\t\tsummary: `Generated fixture files for ${result.writtenFiles.length} collection(s).`,\n\t\t\t\tfilesCreated: result.writtenFiles,\n\t\t\t\trecordsCleared: cleared,\n\t\t\t\tnextSteps: [\n\t\t\t\t\t'Run `vela fixtures load` to load the generated fixtures into the database.',\n\t\t\t\t\t'Edit the JSON files under data/fixtures/ to customize the generated data.'\n\t\t\t\t]\n\t\t\t});\n\t\t}, 'Failed to generate fixtures.')\n\t);\n", "import { Command, InvalidArgumentError } from 'commander';\nimport * as p from '@clack/prompts';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand } from '../../lib/run.ts';\nimport { withPocketbase } from '../../lib/pocketbase.ts';\nimport { getWorkspace } from '../../lib/workspace.ts';\nimport { reportResult } from '../../lib/result-report.ts';\nimport { clearFixtures } from './clear.ts';\nimport { loadFixtures } from './load.ts';\nimport { generateFixtureFiles, type GenerateFixturesResult } from './generate.ts';\n\nfunction parseCount(value: string): number {\n\tconst n = parseInt(value, 10);\n\tif (!Number.isFinite(n) || n <= 0 || n > 999) {\n\t\tthrow new InvalidArgumentError('count must be between 1 and 999');\n\t}\n\treturn n;\n}\n\nfunction parseSeed(value: string): number {\n\tconst n = parseInt(value, 10);\n\tif (!Number.isFinite(n)) {\n\t\tthrow new InvalidArgumentError('seed must be an integer');\n\t}\n\treturn n;\n}\n\nexport const regen = new Command('regen')\n\t.description('clear the database, regenerate fixture files, and reload them')\n\t.option('-c, --count <count>', 'number of records per collection', parseCount, 10)\n\t.option('-s, --seed <seed>', 'seed for deterministic output', parseSeed)\n\t.configureHelp(helpConfig)\n\t.action((opts: { count: number; seed?: number }) =>\n\t\trunCommand(async () => {\n\t\t\tconst { workspaceRootDir } = await getWorkspace();\n\t\t\tlet cleared: string[] = [];\n\t\t\tlet result: GenerateFixturesResult = { writtenFiles: [], warnings: [] };\n\t\t\tlet loaded: string[] = [];\n\t\t\tawait withPocketbase(workspaceRootDir, async (pb) => {\n\t\t\t\tcleared = await clearFixtures(pb, workspaceRootDir);\n\t\t\t\tresult = await generateFixtureFiles(pb, workspaceRootDir, {\n\t\t\t\t\tcount: opts.count,\n\t\t\t\t\tseed: opts.seed\n\t\t\t\t});\n\t\t\t\tloaded = await loadFixtures(pb, workspaceRootDir);\n\t\t\t});\n\n\t\t\tfor (const warning of result.warnings) p.log.warn(warning);\n\n\t\t\treportResult({\n\t\t\t\tsummary: `Regenerated fixtures (${loaded.length} collection(s) reloaded).`,\n\t\t\t\tfilesCreated: result.writtenFiles,\n\t\t\t\trecordsCleared: cleared,\n\t\t\t\trecordsLoaded: loaded,\n\t\t\t\tnextSteps: [\n\t\t\t\t\t'Run `vela dev` to see the new fixture data in the app.',\n\t\t\t\t\t'Edit data/fixtures/*.json or tweak `-c/--count` and re-run to adjust the dataset.'\n\t\t\t\t]\n\t\t\t});\n\t\t}, 'Failed to regenerate fixtures.')\n\t);\n", "import { Command } from 'commander';\nimport { helpConfig } from '../lib/help.ts';\nimport { load } from './seeds/load.ts';\nimport { save } from './seeds/save.ts';\nimport { clear } from './seeds/clear.ts';\n\nexport const seeds = new Command('seeds')\n\t.description('manage seed data')\n\t.configureHelp(helpConfig)\n\t.addCommand(load)\n\t.addCommand(save)\n\t.addCommand(clear);\n", "import fs from 'node:fs';\nimport path from 'node:path';\nimport { Command } from 'commander';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand } from '../../lib/run.ts';\nimport { withPocketbase } from '../../lib/pocketbase.ts';\nimport { getWorkspace } from '../../lib/workspace.ts';\nimport { reportResult } from '../../lib/result-report.ts';\n\nexport function getSeedFiles(cwd: string): Array<{ collectionName: string; seedPath: string }> {\n\tconst seedsDir = path.join(cwd, 'data', 'seeds');\n\tif (!fs.existsSync(seedsDir)) return [];\n\treturn fs\n\t\t.readdirSync(seedsDir)\n\t\t.filter((file) => file.endsWith('.json'))\n\t\t.map((file) => path.join(seedsDir, file))\n\t\t.sort((a, b) => a.localeCompare(b))\n\t\t.map((seedPath) => {\n\t\t\tconst file = path.basename(seedPath);\n\t\t\tconst nameWithoutExt = file.replace(/\\.json$/i, '');\n\t\t\tconst collectionName = nameWithoutExt.replace(/^\\d+[-_]?/, '');\n\t\t\treturn { collectionName, seedPath };\n\t\t});\n}\n\nexport const load = new Command('load')\n\t.description('load seeds into the database')\n\t.option('-f, --force', 'load even if target collections already have records')\n\t.configureHelp(helpConfig)\n\t.action((opts: { force?: boolean }) =>\n\t\trunCommand(async () => {\n\t\t\tconst { workspaceRootDir } = await getWorkspace();\n\t\t\tconst seedFiles = getSeedFiles(workspaceRootDir);\n\n\t\t\tif (seedFiles.length === 0) {\n\t\t\t\treportResult({\n\t\t\t\t\tsummary: 'No seed files found in data/seeds.',\n\t\t\t\t\tnextSteps: ['Run `vela seeds save` to snapshot the current database contents as seeds.']\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst loaded: string[] = [];\n\n\t\t\tawait withPocketbase(workspaceRootDir, async (pb) => {\n\t\t\t\tif (!opts.force) {\n\t\t\t\t\tfor (const { collectionName } of seedFiles) {\n\t\t\t\t\t\tconst page = await pb.collection(collectionName).getList(1, 1, { fields: 'id' });\n\t\t\t\t\t\tif (page.totalItems > 0) {\n\t\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t\t`${collectionName} collection already has records. Pass --force to load anyway.`\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tfor (const { collectionName, seedPath } of seedFiles) {\n\t\t\t\t\tconst seeds = JSON.parse(fs.readFileSync(seedPath, 'utf8')) as Array<\n\t\t\t\t\t\tRecord<string, unknown>\n\t\t\t\t\t>;\n\t\t\t\t\tfor (const seed of seeds) {\n\t\t\t\t\t\tawait pb.collection(collectionName).create(seed);\n\t\t\t\t\t}\n\t\t\t\t\tloaded.push(`${path.relative(workspaceRootDir, seedPath)} (${seeds.length} records)`);\n\t\t\t\t}\n\t\t\t});\n\n\t\t\treportResult({\n\t\t\t\tsummary: `Loaded ${loaded.length} seed file(s) into the database.`,\n\t\t\t\trecordsLoaded: loaded,\n\t\t\t\tnextSteps: [\n\t\t\t\t\t'Run `vela dev` to see the seeded data in the app.',\n\t\t\t\t\t'Run `vela seeds clear` to remove the seeded records.'\n\t\t\t\t]\n\t\t\t});\n\t\t}, 'Failed to load seeds.')\n\t);\n", "import fs from 'node:fs';\nimport path from 'node:path';\nimport { Command } from 'commander';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand } from '../../lib/run.ts';\nimport { withPocketbase } from '../../lib/pocketbase.ts';\nimport { getWorkspace } from '../../lib/workspace.ts';\nimport { dependencyOrder } from '../../lib/collections.ts';\nimport { reportResult } from '../../lib/result-report.ts';\nimport { getSeedFiles } from './load.ts';\n\nconst padZeros = (num: number, length: number) => num.toString().padStart(length, '0');\n\nfunction filterSystemFields(\n\trecord: Record<string, unknown>,\n\tsystemFieldNames: Set<string>\n): Record<string, unknown> {\n\tconst out: Record<string, unknown> = {};\n\tfor (const [key, value] of Object.entries(record)) {\n\t\tif (systemFieldNames.has(key)) continue;\n\t\tif (key === 'collectionId' || key === 'collectionName' || key === 'expand') continue;\n\t\tout[key] = value;\n\t}\n\treturn out;\n}\n\nexport const save = new Command('save')\n\t.description('save the current data as seeds')\n\t.option('-f, --force', 'overwrite existing seed files')\n\t.configureHelp(helpConfig)\n\t.action((opts: { force?: boolean }) =>\n\t\trunCommand(async () => {\n\t\t\tconst { workspaceRootDir } = await getWorkspace();\n\t\t\tconst seedsPath = path.join(workspaceRootDir, 'data', 'seeds');\n\n\t\t\tconst existing = getSeedFiles(workspaceRootDir);\n\t\t\tif (existing.length > 0 && !opts.force) {\n\t\t\t\tthrow new Error('Existing seed files found in data/seeds. Pass --force to overwrite.');\n\t\t\t}\n\n\t\t\tfs.mkdirSync(seedsPath, { recursive: true });\n\t\t\tif (opts.force) {\n\t\t\t\tfor (const file of fs.readdirSync(seedsPath)) {\n\t\t\t\t\tif (file.endsWith('.json')) fs.unlinkSync(path.join(seedsPath, file));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst saved: string[] = [];\n\n\t\t\tawait withPocketbase(workspaceRootDir, async (pb) => {\n\t\t\t\tconst fullList = await pb.collections.getFullList();\n\t\t\t\tconst collections = fullList.map((c) => ({\n\t\t\t\t\tid: c.id,\n\t\t\t\t\tname: c.name,\n\t\t\t\t\tfields: c.fields.map((f) => ({\n\t\t\t\t\t\tname: f.name,\n\t\t\t\t\t\ttype: f.type,\n\t\t\t\t\t\tsystem: f.system,\n\t\t\t\t\t\tcollectionId: (f as { collectionId?: string }).collectionId\n\t\t\t\t\t}))\n\t\t\t\t}));\n\n\t\t\t\tconst { names } = dependencyOrder(collections);\n\n\t\t\t\tlet count = 1;\n\t\t\t\tfor (const collectionName of names) {\n\t\t\t\t\tconst collection = collections.find((c) => c.name === collectionName);\n\t\t\t\t\tif (!collection) continue;\n\t\t\t\t\tconst systemFieldNames = new Set(\n\t\t\t\t\t\tcollection.fields.filter((f) => f.system && f.name !== 'id').map((f) => f.name)\n\t\t\t\t\t);\n\n\t\t\t\t\tconst records = await pb.collection(collectionName).getFullList();\n\t\t\t\t\tif (records.length === 0) continue;\n\n\t\t\t\t\tconst filtered = records.map((r) =>\n\t\t\t\t\t\tfilterSystemFields(r as Record<string, unknown>, systemFieldNames)\n\t\t\t\t\t);\n\n\t\t\t\t\tconst relativeSeedPath = path.join(\n\t\t\t\t\t\t'data',\n\t\t\t\t\t\t'seeds',\n\t\t\t\t\t\t`${padZeros(count, 2)}-${collectionName}.json`\n\t\t\t\t\t);\n\t\t\t\t\tconst seedPath = path.join(workspaceRootDir, relativeSeedPath);\n\t\t\t\t\tfs.writeFileSync(seedPath, JSON.stringify(filtered, null, 2));\n\t\t\t\t\tsaved.push(`${relativeSeedPath} (${filtered.length} records)`);\n\t\t\t\t\tcount++;\n\t\t\t\t}\n\t\t\t});\n\n\t\t\tif (saved.length === 0) {\n\t\t\t\treportResult({\n\t\t\t\t\tsummary: 'No records to save.',\n\t\t\t\t\tnextSteps: [\n\t\t\t\t\t\t'Create some records first (via the app, `vela fixtures load`, or the PocketBase admin UI), then rerun `vela seeds save`.'\n\t\t\t\t\t]\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\treportResult({\n\t\t\t\tsummary: `Saved ${saved.length} collection(s) as seeds.`,\n\t\t\t\tfilesCreated: saved,\n\t\t\t\tnextSteps: [\n\t\t\t\t\t'Commit the new files under data/seeds/ so teammates get the same starting data.',\n\t\t\t\t\t'Run `vela seeds load` on a fresh database to restore this snapshot.'\n\t\t\t\t]\n\t\t\t});\n\t\t}, 'Failed to save seeds.')\n\t);\n", "import fs from 'node:fs';\nimport path from 'node:path';\nimport { Command } from 'commander';\nimport type PocketBase from 'pocketbase';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand } from '../../lib/run.ts';\nimport { withPocketbase } from '../../lib/pocketbase.ts';\nimport { getWorkspace } from '../../lib/workspace.ts';\nimport { reportResult } from '../../lib/result-report.ts';\nimport { getSeedFiles } from './load.ts';\n\nexport async function clearSeeds(\n\tpb: PocketBase,\n\tworkspaceRootDir: string,\n\tseedFiles: Array<{ collectionName: string; seedPath: string }>\n): Promise<string[]> {\n\tconst cleared: string[] = [];\n\tfor (const { collectionName, seedPath } of seedFiles) {\n\t\tconst seeds = JSON.parse(fs.readFileSync(seedPath, 'utf8')) as Array<{ id: string }>;\n\t\tfor (const { id } of seeds) {\n\t\t\tawait pb.collection(collectionName).delete(id);\n\t\t}\n\t\tcleared.push(`${path.relative(workspaceRootDir, seedPath)} (${seeds.length} records)`);\n\t}\n\treturn cleared;\n}\n\nexport const clear = new Command('clear')\n\t.description('clear seeded records')\n\t.configureHelp(helpConfig)\n\t.action(() =>\n\t\trunCommand(async () => {\n\t\t\tconst { workspaceRootDir } = await getWorkspace();\n\t\t\tconst seedFiles = getSeedFiles(workspaceRootDir);\n\n\t\t\tif (seedFiles.length === 0) {\n\t\t\t\treportResult({\n\t\t\t\t\tsummary: 'No seed files found in data/seeds.',\n\t\t\t\t\tnextSteps: ['Run `vela seeds save` to create seed files from the current database.']\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tlet cleared: string[] = [];\n\t\t\tawait withPocketbase(workspaceRootDir, async (pb) => {\n\t\t\t\tcleared = await clearSeeds(pb, workspaceRootDir, seedFiles);\n\t\t\t});\n\n\t\t\tif (cleared.length === 0) {\n\t\t\t\treportResult({\n\t\t\t\t\tsummary: 'No seeded records found to clear.',\n\t\t\t\t\tnextSteps: ['Run `vela seeds load` to load seed records into the database.']\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\treportResult({\n\t\t\t\tsummary: `Cleared ${cleared.length} seed file(s) worth of records.`,\n\t\t\t\trecordsCleared: cleared,\n\t\t\t\tnextSteps: ['Run `vela seeds load` to reload seeds from the files in data/seeds.']\n\t\t\t});\n\t\t}, 'Failed to clear seeds.')\n\t);\n", "import { Command } from 'commander';\nimport * as p from '@clack/prompts';\nimport makeFetchCookie from 'fetch-cookie';\nimport { helpConfig } from '../lib/help.ts';\nimport { API_URL } from '../lib/constants.ts';\nimport { writeConfig } from '../lib/config.ts';\nimport { runCommand } from '../lib/run.ts';\nimport { issueApiKey } from './login.ts';\n\nexport const signup = new Command('signup')\n\t.description('signup to velastack.dev')\n\t.configureHelp(helpConfig)\n\t.action(() =>\n\t\trunCommand(async () => {\n\t\t\tconst { email, password, passwordConfirm } = await p.group({\n\t\t\t\temail: () => p.text({ message: 'Email' }),\n\t\t\t\tpassword: () => p.password({ message: 'Password' }),\n\t\t\t\tpasswordConfirm: () => p.password({ message: 'Confirm password' })\n\t\t\t});\n\n\t\t\tif (password !== passwordConfirm) {\n\t\t\t\tthrow new Error('Passwords do not match.');\n\t\t\t}\n\n\t\t\tconst fetchCookie = makeFetchCookie(fetch);\n\t\t\tconst res = await fetchCookie(`${API_URL}/signup`, {\n\t\t\t\tmethod: 'POST',\n\t\t\t\theaders: {\n\t\t\t\t\t'Content-Type': 'application/x-www-form-urlencoded',\n\t\t\t\t\tOrigin: API_URL\n\t\t\t\t},\n\t\t\t\tbody: new URLSearchParams({\n\t\t\t\t\ttype: 'password',\n\t\t\t\t\temail: email as string,\n\t\t\t\t\tpassword: password as string,\n\t\t\t\t\tpasswordConfirm: passwordConfirm as string\n\t\t\t\t}).toString()\n\t\t\t});\n\n\t\t\tif (!res.headers.get('Set-Cookie')) {\n\t\t\t\tthrow new Error('Failed to signup. Try again or contact support.');\n\t\t\t}\n\n\t\t\tconst apiKey = await issueApiKey(fetchCookie);\n\t\t\twriteConfig({ apiKey });\n\t\t\tp.log.success('Signed up to velastack.dev');\n\t\t\tp.log.info('Check your email for a confirmation link.');\n\t\t}, 'Failed to signup.')\n\t);\n", "import os from 'node:os';\nimport { Command } from 'commander';\nimport * as p from '@clack/prompts';\nimport makeFetchCookie, { type FetchCookieImpl } from 'fetch-cookie';\nimport { helpConfig } from '../lib/help.ts';\nimport { API_URL } from '../lib/constants.ts';\nimport { writeConfig } from '../lib/config.ts';\nimport { runCommand } from '../lib/run.ts';\n\nexport type FetchCookie = FetchCookieImpl<string | URL | Request, RequestInit, Response>;\n\nexport const login = new Command('login')\n\t.description('login to velastack.dev')\n\t.configureHelp(helpConfig)\n\t.action(() =>\n\t\trunCommand(async () => {\n\t\t\tconst { email, password } = await p.group({\n\t\t\t\temail: () => p.text({ message: 'Email' }),\n\t\t\t\tpassword: () => p.password({ message: 'Password' })\n\t\t\t});\n\n\t\t\tconst fetchCookie = makeFetchCookie(fetch);\n\t\t\tconst loginRes = await fetchCookie(`${API_URL}/login`, {\n\t\t\t\tmethod: 'POST',\n\t\t\t\theaders: {\n\t\t\t\t\t'Content-Type': 'application/x-www-form-urlencoded',\n\t\t\t\t\tOrigin: API_URL\n\t\t\t\t},\n\t\t\t\tbody: new URLSearchParams({\n\t\t\t\t\ttype: 'password',\n\t\t\t\t\temail: email as string,\n\t\t\t\t\tpassword: password as string\n\t\t\t\t}).toString()\n\t\t\t});\n\n\t\t\tif (!loginRes.headers.get('Set-Cookie')) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t'Run `vela signup` to create an account or reset at https://velastack.dev/reset'\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconst apiKey = await issueApiKey(fetchCookie);\n\t\t\twriteConfig({ apiKey });\n\t\t\tp.log.success('Logged in to velastack.dev');\n\t\t}, 'Failed to login.')\n\t);\n\nexport async function issueApiKey(fetchCookie: FetchCookie): Promise<string> {\n\tconst label = `CLI - ${os.hostname()}`;\n\n\tawait fetchCookie(`${API_URL}/api-keys/new`, {\n\t\tmethod: 'POST',\n\t\theaders: {\n\t\t\t'Content-Type': 'application/x-www-form-urlencoded',\n\t\t\tOrigin: API_URL\n\t\t},\n\t\tbody: new URLSearchParams({ label }).toString()\n\t});\n\n\tconst cookie = await fetchCookie.cookieJar.getCookieString(API_URL);\n\tconst apiKey = extractApiKey(cookie);\n\tif (!apiKey) {\n\t\tthrow new Error('Failed to create API key. Try again or contact support.');\n\t}\n\n\tconst [id] = apiKey.split('.');\n\tconst res = await fetchCookie(`${API_URL}/api/collections/api_keys/records`, {\n\t\theaders: { Authorization: `Bearer ${apiKey}` }\n\t});\n\tconst data = (await res.json()) as { items: Array<{ id: string; label: string }> };\n\tfor (const item of data.items) {\n\t\tif (item.label === label && item.id !== id) {\n\t\t\tawait fetchCookie(`${API_URL}/api/collections/api_keys/records/${item.id}`, {\n\t\t\t\tmethod: 'DELETE',\n\t\t\t\theaders: { Authorization: `Bearer ${apiKey}` }\n\t\t\t});\n\t\t}\n\t}\n\n\treturn apiKey;\n}\n\nfunction extractApiKey(cookie: string): string | null {\n\tconst flashCookie = cookie.split(';').find((c) => c.trim().startsWith('flash='));\n\tif (!flashCookie) return null;\n\tconst decoded = decodeURIComponent(flashCookie.split('=')[1]!);\n\treturn (JSON.parse(decoded) as { apiKey: string }).apiKey;\n}\n", "import { Command } from 'commander';\nimport * as p from '@clack/prompts';\nimport { helpConfig } from '../lib/help.ts';\nimport { clearConfig, readConfig } from '../lib/config.ts';\nimport { runCommand } from '../lib/run.ts';\n\nexport const logout = new Command('logout')\n\t.alias('signout')\n\t.description('logout from velastack.dev')\n\t.configureHelp(helpConfig)\n\t.action(() =>\n\t\trunCommand(() => {\n\t\t\tif (!readConfig()) {\n\t\t\t\tp.log.info('Not logged in');\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tclearConfig();\n\t\t\tp.log.success('Logged out of velastack.dev');\n\t\t})\n\t);\n", "import { Command } from 'commander';\nimport * as p from '@clack/prompts';\nimport { helpConfig } from '../lib/help.ts';\nimport { API_URL } from '../lib/constants.ts';\nimport { readConfig } from '../lib/config.ts';\nimport { runCommand } from '../lib/run.ts';\n\nexport const whoami = new Command('whoami')\n\t.description('show the current user')\n\t.configureHelp(helpConfig)\n\t.action(() =>\n\t\trunCommand(async () => {\n\t\t\tconst apiKey = readConfig()?.apiKey;\n\t\t\tif (!apiKey) {\n\t\t\t\tp.log.info('Not logged in. Run `vela login` to login.');\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst res = await fetch(`${API_URL}/api/collections/users/records`, {\n\t\t\t\theaders: { Authorization: `Bearer ${apiKey}` }\n\t\t\t});\n\t\t\tconst data = (await res.json()) as { items: Array<{ email: string }> };\n\t\t\tif (!data.items.length) throw new Error('No user found. Run `vela login` to login.');\n\t\t\tp.log.success(`Logged in as ${data.items[0]!.email}`);\n\t\t})\n\t);\n", "import { Command } from 'commander';\nimport { helpConfig } from '../lib/help.ts';\nimport { runCommand } from '../lib/run.ts';\nimport { up, runMigrateUp } from './migrate/up.ts';\nimport { down } from './migrate/down.ts';\nimport { create } from './migrate/create.ts';\nimport { collections } from './migrate/collections.ts';\nimport { historySync } from './migrate/history-sync.ts';\n\nexport const migrate = new Command('migrate')\n\t.description('manage database migrations')\n\t.configureHelp(helpConfig)\n\t.action(() => runCommand(runMigrateUp, 'Failed to run migrations.'))\n\t.addCommand(up)\n\t.addCommand(down)\n\t.addCommand(create)\n\t.addCommand(collections)\n\t.addCommand(historySync);\n", "import { Command } from 'commander';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand } from '../../lib/run.ts';\nimport { runPocketbaseMigrate } from '../../lib/migrate.ts';\nimport { reportResult } from '../../lib/result-report.ts';\n\nexport async function runMigrateUp(): Promise<void> {\n\tawait runPocketbaseMigrate(['up']);\n\treportResult({\n\t\tsummary: 'Ran pending migrations.',\n\t\tnextSteps: [\n\t\t\t'Run `vela sync` to refresh generated TypeScript types from the updated schema.',\n\t\t\t'Run `vela dev` to pick up the new schema in the running app.',\n\t\t\t'Run `vela migrate down` if you need to revert the last migration.'\n\t\t]\n\t});\n}\n\nexport const up = new Command('up')\n\t.description('apply all pending migrations')\n\t.configureHelp(helpConfig)\n\t.action(() => runCommand(runMigrateUp, 'Failed to run migrations.'));\n", "import path from 'node:path';\nimport process from 'node:process';\nimport { x } from 'tinyexec';\nimport { DATA_DIR, MIGRATIONS_DIR } from './constants.ts';\n\nexport async function runPocketbaseMigrate(args: string[]): Promise<void> {\n\tconst cwd = process.cwd();\n\tconst { getBinaryPath } = await import('pocketbase-server');\n\tconst binaryPath = getBinaryPath();\n\n\tawait x(\n\t\tbinaryPath,\n\t\t[\n\t\t\t'--dir',\n\t\t\tpath.join(cwd, DATA_DIR),\n\t\t\t'--migrationsDir',\n\t\t\tpath.join(cwd, MIGRATIONS_DIR),\n\t\t\t'migrate',\n\t\t\t...args\n\t\t],\n\t\t{\n\t\t\tnodeOptions: { cwd, stdio: 'inherit' },\n\t\t\tthrowOnError: true\n\t\t}\n\t);\n}\n", "import { Command, InvalidArgumentError } from 'commander';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand } from '../../lib/run.ts';\nimport { runPocketbaseMigrate } from '../../lib/migrate.ts';\nimport { reportResult } from '../../lib/result-report.ts';\n\nexport function parseSteps(value: string): number {\n\tconst n = parseInt(value, 10);\n\tif (!Number.isFinite(n) || n <= 0) {\n\t\tthrow new InvalidArgumentError('number must be a positive integer');\n\t}\n\treturn n;\n}\n\nexport const down = new Command('down')\n\t.alias('rollback')\n\t.description('revert the last N applied migrations')\n\t.argument('[number]', 'how many migrations to revert', parseSteps, 1)\n\t.configureHelp(helpConfig)\n\t.action((n: number) =>\n\t\trunCommand(async () => {\n\t\t\tawait runPocketbaseMigrate(['down', String(n)]);\n\t\t\treportResult({\n\t\t\t\tsummary: `Reverted the last ${n} migration(s).`,\n\t\t\t\tnextSteps: [\n\t\t\t\t\t'Run `vela sync` to regenerate TypeScript types after the rollback.',\n\t\t\t\t\t'Run `vela migrate up` to reapply reverted migrations when ready.'\n\t\t\t\t]\n\t\t\t});\n\t\t}, 'Failed to revert migrations.')\n\t);\n", "import fs from 'node:fs';\nimport path from 'node:path';\nimport process from 'node:process';\nimport { Command } from 'commander';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand } from '../../lib/run.ts';\nimport { runPocketbaseMigrate } from '../../lib/migrate.ts';\nimport { MIGRATIONS_DIR } from '../../lib/constants.ts';\nimport { reportResult } from '../../lib/result-report.ts';\n\nexport const create = new Command('create')\n\t.alias('new')\n\t.description('create a new blank migration')\n\t.argument('<name>', 'migration name (snake_case)')\n\t.configureHelp(helpConfig)\n\t.action((name: string) =>\n\t\trunCommand(async () => {\n\t\t\tconst cwd = process.cwd();\n\t\t\tconst before = listMigrationFiles(cwd);\n\t\t\tawait runPocketbaseMigrate(['create', name]);\n\t\t\tconst after = listMigrationFiles(cwd);\n\t\t\tconst added = [...after].filter((f) => !before.has(f));\n\n\t\t\treportResult({\n\t\t\t\tsummary: `Created blank migration ${name}.`,\n\t\t\t\tfilesCreated: added.map((f: string) => path.join(MIGRATIONS_DIR, f)),\n\t\t\t\tnextSteps: [\n\t\t\t\t\t`Open the new file in ${MIGRATIONS_DIR}/ and fill in the up/down handlers.`,\n\t\t\t\t\t'Run `vela migrate up` to apply the migration once the handlers are written.'\n\t\t\t\t]\n\t\t\t});\n\t\t}, 'Failed to create migration.')\n\t);\n\nfunction listMigrationFiles(cwd: string): Set<string> {\n\tconst dir = path.join(cwd, MIGRATIONS_DIR);\n\tif (!fs.existsSync(dir)) return new Set();\n\treturn new Set(fs.readdirSync(dir).filter((f) => /\\.[jt]s$/.test(f)));\n}\n", "import fs from 'node:fs';\nimport path from 'node:path';\nimport process from 'node:process';\nimport { Command } from 'commander';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand } from '../../lib/run.ts';\nimport { runPocketbaseMigrate } from '../../lib/migrate.ts';\nimport { MIGRATIONS_DIR } from '../../lib/constants.ts';\nimport { reportResult } from '../../lib/result-report.ts';\n\nexport const collections = new Command('collections')\n\t.alias('snapshot')\n\t.description('snapshot local collections into a new migration')\n\t.configureHelp(helpConfig)\n\t.action(() =>\n\t\trunCommand(async () => {\n\t\t\tconst cwd = process.cwd();\n\t\t\tconst before = listMigrationFiles(cwd);\n\t\t\tawait runPocketbaseMigrate(['collections']);\n\t\t\tconst after = listMigrationFiles(cwd);\n\t\t\tconst added = [...after].filter((f) => !before.has(f));\n\n\t\t\tif (added.length === 0) {\n\t\t\t\treportResult({\n\t\t\t\t\tsummary: 'No schema changes to snapshot \u2014 migrations are already up to date.'\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\treportResult({\n\t\t\t\tsummary: 'Snapshotted local collections into a new migration.',\n\t\t\t\tfilesCreated: added.map((f: string) => path.join(MIGRATIONS_DIR, f)),\n\t\t\t\tnextSteps: [\n\t\t\t\t\t`Review the generated snapshot in ${MIGRATIONS_DIR}/.`,\n\t\t\t\t\t'Commit the snapshot so teammates pick up the new schema.',\n\t\t\t\t\t'Run `vela migrate up` on other environments to apply the schema.'\n\t\t\t\t]\n\t\t\t});\n\t\t}, 'Failed to snapshot collections.')\n\t);\n\nfunction listMigrationFiles(cwd: string): Set<string> {\n\tconst dir = path.join(cwd, MIGRATIONS_DIR);\n\tif (!fs.existsSync(dir)) return new Set();\n\treturn new Set(fs.readdirSync(dir).filter((f) => /\\.[jt]s$/.test(f)));\n}\n", "import { Command } from 'commander';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand } from '../../lib/run.ts';\nimport { runPocketbaseMigrate } from '../../lib/migrate.ts';\nimport { reportResult } from '../../lib/result-report.ts';\n\nexport const historySync = new Command('history-sync')\n\t.description('drop _migrations rows whose files no longer exist')\n\t.configureHelp(helpConfig)\n\t.action(() =>\n\t\trunCommand(async () => {\n\t\t\tawait runPocketbaseMigrate(['history-sync']);\n\t\t\treportResult({\n\t\t\t\tsummary: 'Synced migration history with files on disk.',\n\t\t\t\tnextSteps: ['Run `vela migrate up` if any pending migrations surfaced after the sync.']\n\t\t\t});\n\t\t}, 'Failed to sync migration history.')\n\t);\n", "import fs from 'node:fs';\nimport path from 'node:path';\nimport process from 'node:process';\nimport { performance } from 'node:perf_hooks';\nimport type { ChildProcess } from 'node:child_process';\nimport type { AddressInfo } from 'node:net';\nimport { Command, InvalidArgumentError } from 'commander';\nimport type { InlineConfig } from 'vite';\nimport pc from 'picocolors';\nimport PocketBase from 'pocketbase';\nimport { helpConfig } from '../lib/help.ts';\nimport { DATA_DIR, MIGRATIONS_DIR } from '../lib/constants.ts';\nimport { startPocketbaseServe } from '../lib/pocketbase.ts';\nimport { hasBackend, localDataDir } from '../lib/workspace.ts';\nimport { loadVite } from '../lib/vite.ts';\n\n/**\n * Vite dev-server flags worth forwarding, spelled exactly as vite's own CLI\n * spells them so anything learned there carries over. `--open` is the one\n * `vela create` tells users to run.\n */\ninterface DevOptions {\n\topen?: boolean | string;\n\thost?: boolean | string;\n\tport?: number;\n\tcors?: boolean;\n\tstrictPort?: boolean;\n\tforce?: boolean;\n}\n\n/** Everything except `--force`, which vite routes outside `server`. */\ntype ServerFlags = Omit<DevOptions, 'force'>;\n\nfunction parsePort(value: string): number {\n\tconst port = Number(value);\n\tif (!Number.isInteger(port) || port < 1 || port > 65535) {\n\t\tthrow new InvalidArgumentError('must be a whole number between 1 and 65535.');\n\t}\n\treturn port;\n}\n\nexport const dev = new Command('dev')\n\t.description('start the development server')\n\t.option('--open [path]', 'open the app in a browser once the server is ready')\n\t.option('--host [host]', 'expose the server on the network')\n\t.option('--port <port>', 'port to listen on', parsePort)\n\t.option('--strictPort', 'exit if the port is already in use instead of taking the next one')\n\t.option('--cors', 'enable CORS')\n\t.option('--force', 're-bundle dependencies, ignoring the optimizer cache')\n\t.configureHelp(helpConfig)\n\t.action(async (options: DevOptions) => {\n\t\tconst cwd = process.cwd();\n\n\t\t// Every other context reads the data directory out of the environment, so\n\t\t// the one this machine uses has to be there too \u2014 otherwise the fallback\n\t\t// is the only code path local development ever exercises.\n\t\tprocess.env.VELA_DATA_DIR ??= localDataDir(cwd);\n\t\tconst startTime = performance.now();\n\n\t\tconst { createServer, version } = await loadVite(cwd);\n\n\t\tconst viteMetadataDir = path.join(cwd, 'node_modules', '.vite');\n\t\tconst viteMetadataFile = path.join(viteMetadataDir, '_pocketbase_metadata.json');\n\n\t\tlet pbProc: ChildProcess | undefined;\n\t\t// A static project has no PocketBase to start, and nothing to sync types from.\n\t\tconst backend = hasBackend(cwd);\n\t\tconst needsStart = backend && !process.env.POCKETBASE_URL;\n\n\t\tconst cleanup = () => {\n\t\t\tif (pbProc?.pid) pbProc.kill();\n\t\t\tif (fs.existsSync(viteMetadataFile)) fs.rmSync(viteMetadataFile);\n\t\t};\n\n\t\tif (needsStart) {\n\t\t\tconst dataDir = path.join(cwd, DATA_DIR);\n\t\t\tconst started = await startPocketbaseServe({\n\t\t\t\tdataDir,\n\t\t\t\tmigrationsDir: MIGRATIONS_DIR,\n\t\t\t\thooksDir: path.join(dataDir, 'hooks'),\n\t\t\t\tdev: true,\n\t\t\t\tstdio: 'pipe'\n\t\t\t});\n\t\t\tpbProc = started.proc;\n\t\t\tprocess.env.POCKETBASE_URL = started.url;\n\n\t\t\tpbProc.stdout?.pipe(process.stdout);\n\t\t\tpbProc.stderr?.pipe(process.stderr);\n\t\t\tpbProc.on('error', (err) => console.error('PocketBase error:', err));\n\t\t\tpbProc.on('exit', (code) => console.log(`PocketBase exited with code ${code}`));\n\n\t\t\tprocess.on('exit', cleanup);\n\t\t\tprocess.on('SIGINT', () => {\n\t\t\t\tcleanup();\n\t\t\t\tprocess.exit(0);\n\t\t\t});\n\t\t}\n\n\t\t// Only forward what was actually passed: an explicit `undefined` here would\n\t\t// still be merged over whatever vite.config.ts sets.\n\t\tconst serverOptions: ServerFlags = {};\n\t\tif (options.open !== undefined) serverOptions.open = options.open;\n\t\tif (options.host !== undefined) serverOptions.host = options.host;\n\t\tif (options.port !== undefined) serverOptions.port = options.port;\n\t\tif (options.cors !== undefined) serverOptions.cors = options.cors;\n\t\tif (options.strictPort !== undefined) serverOptions.strictPort = options.strictPort;\n\n\t\t// `--force` is not a server option: vite's CLI strips it from the server\n\t\t// config and passes it as `forceOptimizeDeps`. Typed as vite's own\n\t\t// `InlineConfig` so a renamed or dropped option fails `lint:ts` here\n\t\t// rather than being silently ignored at runtime.\n\t\tconst inlineConfig: InlineConfig = {\n\t\t\tserver: serverOptions\n\t\t};\n\t\tif (options.force !== undefined) inlineConfig.forceOptimizeDeps = options.force;\n\n\t\tconst server = await createServer(inlineConfig);\n\n\t\tserver.httpServer?.on('listening', async () => {\n\t\t\tif (!backend) return;\n\n\t\t\tconst { address, port: vitePort } = server.httpServer!.address() as AddressInfo;\n\t\t\tconst viteHost = address === '::1' ? 'localhost' : address;\n\t\t\tawait fs.promises.mkdir(viteMetadataDir, { recursive: true });\n\t\t\tawait fs.promises.writeFile(\n\t\t\t\tviteMetadataFile,\n\t\t\t\tJSON.stringify({\n\t\t\t\t\tpocketbaseUrl: process.env.POCKETBASE_URL,\n\t\t\t\t\tvitePort,\n\t\t\t\t\tviteHost\n\t\t\t\t})\n\t\t\t);\n\n\t\t\tconst pb = new PocketBase(process.env.POCKETBASE_URL!);\n\t\t\tawait pb\n\t\t\t\t.collection('_superusers')\n\t\t\t\t.authWithPassword(\n\t\t\t\t\tprocess.env.POCKETBASE_SUPERUSER_EMAIL!,\n\t\t\t\t\tprocess.env.POCKETBASE_SUPERUSER_PASSWORD!\n\t\t\t\t);\n\t\t\tawait pb.settings.update({ meta: { appURL: `http://${viteHost}:${vitePort}` } });\n\n\t\t\tawait startWatchingTypes(cwd, pb);\n\t\t});\n\n\t\tawait server.listen();\n\n\t\tconst hasExistingLogs = process.stdout.bytesWritten > 0 || process.stderr.bytesWritten > 0;\n\t\tconst startupDurationString = pc.dim(\n\t\t\t`ready in ${pc.reset(pc.bold(Math.ceil(performance.now() - startTime)))} ms`\n\t\t);\n\t\tserver.config.logger.info(\n\t\t\t`\\n ${pc.green(`${pc.bold('VITE')} v${version}`)} ${startupDurationString}\\n`,\n\t\t\t{ clear: !hasExistingLogs }\n\t\t);\n\t\tserver.printUrls();\n\t\tserver.bindCLIShortcuts({ print: true });\n\t});\n\nasync function startWatchingTypes(cwd: string, pb: PocketBase): Promise<void> {\n\tconst { processTypes } = await import('@velastack/pocketbase-codegen');\n\n\tconst typesDir = path.resolve(cwd, '.svelte-kit', 'types');\n\tconst pocketbaseDir = path.join(typesDir, 'pocketbase');\n\tconst pocketbaseTypes = path.join(pocketbaseDir, '$types.d.ts');\n\n\tconst regenerate = () => processTypes(pb, typesDir).catch(() => {});\n\n\t// Never let a first-run failure escape: this runs inside an async\n\t// `listening` listener, where a rejection takes the process down, and it\n\t// would also leave the session with no watcher at all. Both SvelteKit and\n\t// handlePocketbase rely on that watcher to rebuild $types.d.ts after they\n\t// delete it, so losing it silently disables type sync for the session.\n\tawait regenerate();\n\n\t// Re-arm on failure: the watch is bound to the directory's inode, so\n\t// `rm -rf .svelte-kit` would otherwise kill it permanently.\n\tvoid (async () => {\n\t\tfor (;;) {\n\t\t\ttry {\n\t\t\t\tawait fs.promises.mkdir(pocketbaseDir, { recursive: true });\n\t\t\t\tfor await (const event of fs.promises.watch(pocketbaseDir)) {\n\t\t\t\t\tif (\n\t\t\t\t\t\tevent.eventType === 'rename' &&\n\t\t\t\t\t\tevent.filename === '$types.d.ts' &&\n\t\t\t\t\t\t!fs.existsSync(pocketbaseTypes)\n\t\t\t\t\t) {\n\t\t\t\t\t\tsetTimeout(regenerate, 100);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} catch {\n\t\t\t\t// directory vanished or the watch broke \u2014 rebuild and re-watch\n\t\t\t\tawait new Promise((r) => setTimeout(r, 200));\n\t\t\t}\n\t\t}\n\t})();\n}\n", "import path from 'node:path';\nimport process from 'node:process';\nimport { createRequire } from 'node:module';\nimport { pathToFileURL } from 'node:url';\nimport pc from 'picocolors';\n\n/**\n * The vite major the inline server configs in `vela dev` and `vela test:server`\n * are written against.\n */\nexport const REQUIRED_VITE_MAJOR = 8;\n\n/**\n * Returns an error message when `version` is too old for those inline configs,\n * or null when it is usable.\n *\n * An unparseable version returns null. A prerelease or fork string is not\n * evidence of a problem, and refusing to start over one we simply failed to\n * read would be worse than letting vite speak for itself.\n */\nexport function viteVersionError(version: string): string | null {\n\tconst major = Number.parseInt(version, 10);\n\tif (!Number.isFinite(major) || major >= REQUIRED_VITE_MAJOR) return null;\n\n\treturn [\n\t\t`This project has vite ${version}, but vela needs vite ${REQUIRED_VITE_MAJOR} or newer.`,\n\t\t'',\n\t\t' npm install -D vite@^8 @sveltejs/vite-plugin-svelte@^7',\n\t\t'',\n\t\t'Both move together: @sveltejs/vite-plugin-svelte 7 requires vite 8, and',\n\t\t'version 6 is the last that supports vite 7.'\n\t].join('\\n');\n}\n\n/**\n * Resolves the `vite` entry point as seen from `cwd`, or null when the project\n * has none.\n */\nfunction resolveProjectVite(cwd: string): string | null {\n\ttry {\n\t\treturn createRequire(path.join(cwd, 'package.json')).resolve('vite');\n\t} catch {\n\t\treturn null;\n\t}\n}\n\n/**\n * Loads the vite the *project* will actually be built with, and checks we can\n * drive it.\n *\n * Resolving from `cwd` rather than importing `vite` bare matters: a bare import\n * resolves relative to this file, which is the project's own `node_modules` for\n * a normal install but the CLI's for a global install, an `npx` run, or a linked\n * dev checkout. Since `createServer` reads the project's `vite.config.ts` either\n * way, a bare import can pair the project's config with a different vite than\n * the project declares.\n *\n * Falls back to a bare import when the project has no vite of its own, which\n * keeps `--help`-shaped and scratch invocations working.\n */\nexport async function loadVite(cwd: string = process.cwd()): Promise<typeof import('vite')> {\n\tconst entry = resolveProjectVite(cwd);\n\tconst vite: typeof import('vite') = entry\n\t\t? await import(pathToFileURL(entry).href)\n\t\t: await import('vite');\n\n\tconst error = viteVersionError(vite.version);\n\tif (error) {\n\t\tconsole.error(`${pc.redBright('\u2717')} ${error}`);\n\t\tprocess.exit(1);\n\t}\n\treturn vite;\n}\n", "import fs from 'node:fs';\nimport path from 'node:path';\nimport process from 'node:process';\nimport type { ChildProcess } from 'node:child_process';\nimport { Command } from 'commander';\nimport * as p from '@clack/prompts';\nimport pc from 'picocolors';\nimport { x } from 'tinyexec';\nimport { detect } from 'package-manager-detector';\nimport { resolveCommand } from 'package-manager-detector/commands';\nimport { helpConfig } from '../lib/help.ts';\nimport { DATA_DIR, MIGRATIONS_DIR } from '../lib/constants.ts';\nimport { ensureSuperuser, startPocketbaseServe } from '../lib/pocketbase.ts';\nimport { findWorkspaceRoot, hasBackend } from '../lib/workspace.ts';\nimport { applyBuildEnv } from '../lib/build-env.ts';\nimport { loadDeployConfig } from '../lib/deploy-config.ts';\nimport { parseTarget, PRODUCTION_TARGET } from '../lib/target.ts';\nimport { resolveOrigin } from '../lib/origin.ts';\n\n/** Where SvelteKit leaves the pages it rendered at build time. */\nconst PRERENDERED_DIR = path.join('.svelte-kit', 'output', 'prerendered');\n\nexport const build = new Command('build')\n\t.description('build the app')\n\t.configureHelp(helpConfig)\n\t.option('-t, --target <target>', 'which copy of the app to build for', PRODUCTION_TARGET)\n\t.action(async (options: { target?: string }) => {\n\t\tconst cwd = process.cwd();\n\n\t\tapplyBuildEnv(cwd);\n\n\t\t// Prerendering has no request to take an origin from, so the domain the\n\t\t// app is served on has to arrive as configuration or not at all.\n\t\tconst origin = await originForBuild(cwd, options.target);\n\t\tif (origin) process.env.VELA_ORIGIN = origin;\n\n\t\tlet pbProc: ChildProcess | undefined;\n\t\t// A static project has no PocketBase to start, and no `data` dir to start it from.\n\t\tconst needsStart = hasBackend(cwd) && !process.env.POCKETBASE_URL;\n\n\t\tconst cleanup = () => {\n\t\t\tif (pbProc?.pid) pbProc.kill();\n\t\t};\n\n\t\tif (needsStart) {\n\t\t\tawait ensureSuperuser(cwd);\n\t\t\tconst dataDir = path.join(cwd, DATA_DIR);\n\t\t\tconst started = await startPocketbaseServe({\n\t\t\t\tdataDir,\n\t\t\t\tmigrationsDir: MIGRATIONS_DIR,\n\t\t\t\thooksDir: path.join(dataDir, 'hooks'),\n\t\t\t\tdev: true\n\t\t\t});\n\t\t\tpbProc = started.proc;\n\t\t\tprocess.env.POCKETBASE_URL = started.url;\n\n\t\t\tprocess.on('exit', cleanup);\n\t\t\tprocess.on('SIGINT', () => {\n\t\t\t\tcleanup();\n\t\t\t\tprocess.exit(0);\n\t\t\t});\n\t\t}\n\n\t\ttry {\n\t\t\tconst pm = (await detect({ cwd }))?.name ?? 'npm';\n\t\t\tconst resolved = resolveCommand(pm, 'execute', ['vite', 'build'])!;\n\t\t\tconst args = resolved.args.slice();\n\t\t\tif (pm === 'npm') args.unshift('--yes');\n\t\t\tawait x(resolved.command, args, {\n\t\t\t\tnodeOptions: { cwd, stdio: 'inherit' },\n\t\t\t\tthrowOnError: true\n\t\t\t});\n\t\t} finally {\n\t\t\tcleanup();\n\t\t}\n\n\t\tif (!origin) warnIfPrerendered(cwd);\n\t});\n\n/**\n * The origin to render this build's absolute URLs against, if one is knowable.\n *\n * Resolution needs the workspace root rather than the cwd, and neither is worth\n * failing a build over: a project outside a workspace, or one whose target has\n * no domain yet, simply builds the way it always has.\n */\nasync function originForBuild(cwd: string, target: string | undefined): Promise<string | null> {\n\tconst workspaceRootDir = findWorkspaceRoot(cwd);\n\tif (!workspaceRootDir) return null;\n\n\ttry {\n\t\tconst parsed = parseTarget(target, PRODUCTION_TARGET);\n\t\t// `local` is this machine, where `url.origin` is already the dev server's.\n\t\tif (parsed.kind !== 'remote') return null;\n\n\t\tconst config = await loadDeployConfig(workspaceRootDir);\n\t\treturn resolveOrigin(workspaceRootDir, parsed.envTag, config);\n\t} catch {\n\t\treturn null;\n\t}\n}\n\n/**\n * Say so when pages were rendered against SvelteKit's placeholder host.\n *\n * Checked against the output rather than guessed from the routes beforehand,\n * because whether anything prerenders is a property of the build. Silence here\n * is what shipped `<link rel=\"canonical\" href=\"http://sveltekit-prerender/\">` to\n * production.\n */\nfunction warnIfPrerendered(cwd: string): void {\n\tconst dir = path.join(cwd, PRERENDERED_DIR);\n\tif (!fs.existsSync(dir) || fs.readdirSync(dir).length === 0) return;\n\n\tp.log.warn(\n\t\t`Prerendered pages were built with no domain configured, so their canonical\\n` +\n\t\t\t`links point at SvelteKit's placeholder host rather than at this site.\\n\\n` +\n\t\t\t`Set one with ${pc.cyan('vela deploy --domain example.com')}, or pass ${pc.cyan('VELA_ORIGIN')}.`\n\t);\n}\n", "import { localDataDir } from './workspace.ts';\n\n/**\n * The environment a build needs beyond whatever the shell already provides.\n *\n * Gathered in one named place rather than set inline at the top of the command,\n * because that is how `VITE_BUILD` was lost: a refactor changed the action's\n * signature and took the assignment with it, and nothing failed until a\n * prerendered page 500'd on a deploy days later.\n */\nexport function applyBuildEnv(cwd: string, env: NodeJS.ProcessEnv = process.env): void {\n\t// `@velastack/pocketbase` reads this to point its admin client straight at\n\t// PocketBase for the duration of the build. Without it the client keeps its\n\t// default relative base, so a prerendered page calls back into the app's own\n\t// admin proxy \u2014 which reads `url.search`, something SvelteKit forbids on a\n\t// prerendered page. The build then fails as an opaque `[500] GET /`.\n\tenv.VITE_BUILD = 'true';\n\n\t// Every other context reads the data directory out of the environment, so the\n\t// one this machine uses has to be there too \u2014 otherwise the fallback is the\n\t// only code path local development ever exercises. An explicit value wins.\n\tenv.VELA_DATA_DIR ??= localDataDir(cwd);\n}\n", "import process from 'node:process';\nimport { readBinding, type VelaAppConfig } from './deploy-config.ts';\n\n/**\n * The public origin a build renders absolute URLs against.\n *\n * Prerendering happens with no request to take an origin from, so SvelteKit\n * substitutes `http://sveltekit-prerender` and every canonical link, `og:url`\n * and `hreflang` baked into a prerendered page points at a host that does not\n * exist. The domain the app is actually served on is already known here \u2014 it is\n * the one Caddy is configured with \u2014 so the build is told about it and\n * `kit.prerender.origin` takes over.\n *\n * Null rather than a guess: an origin invented from a default would be wrong in\n * a way that is invisible until someone reads the shipped HTML, which is exactly\n * the failure this exists to end.\n */\nexport function resolveOrigin(\n\tworkspaceRootDir: string,\n\tenvTag: string,\n\tconfig: VelaAppConfig = {}\n): string | null {\n\treturn normalizeOrigin(\n\t\tprocess.env.VELA_ORIGIN ??\n\t\t\treadBinding(workspaceRootDir, envTag)?.domain ??\n\t\t\tconfig.deploy?.domain\n\t);\n}\n\n/**\n * Turn a configured domain into an origin, or null if it cannot be one.\n *\n * `--domain` takes the comma-separated list Caddy serves, and the first host is\n * the canonical one \u2014 the same choice `velastack/action` makes when it reports a\n * deployment's URL. A bare hostname gets `https://`, because that is what Caddy\n * terminates; anything already carrying a scheme is left alone, so a local\n * `http://127.0.0.1:4100` survives.\n */\nexport function normalizeOrigin(value: string | null | undefined): string | null {\n\tconst first = value?.split(',')[0]?.trim();\n\tif (!first) return null;\n\n\tconst withScheme = /^[a-z][a-z0-9+.-]*:\\/\\//i.test(first) ? first : `https://${first}`;\n\n\ttry {\n\t\tconst url = new URL(withScheme);\n\t\t// `origin` is scheme + host + non-default port and nothing else, which\n\t\t// drops any path, query or trailing slash a hand-written domain carried.\n\t\treturn url.origin;\n\t} catch {\n\t\treturn null;\n\t}\n}\n", "import path from 'node:path';\nimport process from 'node:process';\nimport type { ChildProcess } from 'node:child_process';\nimport { Command } from 'commander';\nimport { x } from 'tinyexec';\nimport { detect } from 'package-manager-detector';\nimport { resolveCommand } from 'package-manager-detector/commands';\nimport { helpConfig } from '../lib/help.ts';\nimport { DATA_DIR, MIGRATIONS_DIR } from '../lib/constants.ts';\nimport { startPocketbaseServe } from '../lib/pocketbase.ts';\nimport { hasBackend, localDataDir } from '../lib/workspace.ts';\n\nexport const preview = new Command('preview')\n\t.description('preview the built app')\n\t.configureHelp(helpConfig)\n\t.action(async () => {\n\t\tconst cwd = process.cwd();\n\n\t\t// Every other context reads the data directory out of the environment, so\n\t\t// the one this machine uses has to be there too \u2014 otherwise the fallback\n\t\t// is the only code path local development ever exercises.\n\t\tprocess.env.VELA_DATA_DIR ??= localDataDir(cwd);\n\n\t\tlet pbProc: ChildProcess | undefined;\n\t\t// A static project has no PocketBase to start, and no `data` dir to start it from.\n\t\tconst needsStart = hasBackend(cwd) && !process.env.POCKETBASE_URL;\n\n\t\tconst cleanup = () => {\n\t\t\tif (pbProc?.pid) pbProc.kill();\n\t\t};\n\n\t\tif (needsStart) {\n\t\t\tconst dataDir = path.join(cwd, DATA_DIR);\n\t\t\tconst started = await startPocketbaseServe({\n\t\t\t\tdataDir,\n\t\t\t\tmigrationsDir: MIGRATIONS_DIR,\n\t\t\t\thooksDir: path.join(dataDir, 'hooks'),\n\t\t\t\tdev: true\n\t\t\t});\n\t\t\tpbProc = started.proc;\n\t\t\tprocess.env.POCKETBASE_URL = started.url;\n\n\t\t\tprocess.on('exit', cleanup);\n\t\t\tprocess.on('SIGINT', () => {\n\t\t\t\tcleanup();\n\t\t\t\tprocess.exit(0);\n\t\t\t});\n\t\t}\n\n\t\ttry {\n\t\t\tconst pm = (await detect({ cwd }))?.name ?? 'npm';\n\t\t\tconst resolved = resolveCommand(pm, 'execute', ['vite', 'preview'])!;\n\t\t\tconst args = resolved.args.slice();\n\t\t\tif (pm === 'npm') args.unshift('--yes');\n\t\t\tawait x(resolved.command, args, {\n\t\t\t\tnodeOptions: { cwd, stdio: 'inherit' },\n\t\t\t\tthrowOnError: true\n\t\t\t});\n\t\t} finally {\n\t\t\tcleanup();\n\t\t}\n\t});\n", "import path from 'node:path';\nimport { Command } from 'commander';\nimport { helpConfig } from '../lib/help.ts';\nimport { runCommand } from '../lib/run.ts';\nimport { getWorkspace } from '../lib/workspace.ts';\nimport { withPocketbase } from '../lib/pocketbase.ts';\n\nexport const sync = new Command('sync')\n\t.description('sync types from the database')\n\t.configureHelp(helpConfig)\n\t.action(() =>\n\t\trunCommand(async () => {\n\t\t\tconst { workspaceRootDir } = await getWorkspace();\n\t\t\tconst typesDir = path.join(workspaceRootDir, '.svelte-kit', 'types');\n\n\t\t\tconst { processTypes } = await import('@velastack/pocketbase-codegen');\n\n\t\t\tawait withPocketbase(workspaceRootDir, async (pb) => {\n\t\t\t\tawait processTypes(pb, typesDir);\n\t\t\t});\n\n\t\t\tconsole.log('types synced');\n\t\t}, 'Failed to sync types.')\n\t);\n", "import { Command } from 'commander';\nimport * as p from '@clack/prompts';\nimport pc from 'picocolors';\nimport * as v from 'valibot';\nimport pkg from '../../package.json' with { type: 'json' };\nimport { helpConfig } from '../lib/help.ts';\nimport { runCommand } from '../lib/run.ts';\nimport { parseOptions } from '../lib/options.ts';\nimport { withSsh } from '../lib/ssh.ts';\nimport { pocketbaseVersion } from '../lib/pocketbase.ts';\nimport { readServerInfo, runServerScript, syncServerScripts } from '../lib/remote.ts';\nimport { sshOptionsFrom, SSH_OPTION_SCHEMA, addSshOptions } from '../lib/ssh-options.ts';\n\nconst OptionsSchema = v.object({\n\t...SSH_OPTION_SCHEMA,\n\tpbVersion: v.optional(v.string()),\n\tnodeMajor: v.optional(v.string())\n});\n\nexport const provision = addSshOptions(\n\tnew Command('provision')\n\t\t.description('prepare a server to host vela apps')\n\t\t.argument('<target>', 'SSH target \u2014 an alias from ~/.ssh/config, or user@host')\n\t\t.configureHelp(helpConfig)\n)\n\t.option('--pb-version <version>', 'PocketBase version to install')\n\t.option('--node-major <version>', 'Node.js major version to install', '22')\n\t.action((target: string, raw: unknown) =>\n\t\trunCommand(async () => {\n\t\t\tconst options = parseOptions(OptionsSchema, raw);\n\t\t\tconst pbVersion = options.pbVersion ?? pocketbaseVersion();\n\n\t\t\tp.intro(pc.bgCyan(pc.black(' vela provision ')));\n\t\t\tp.log.info(`Target ${pc.cyan(target)}`);\n\n\t\t\tawait withSsh(target, sshOptionsFrom(options), async (session) => {\n\t\t\t\tawait session.detectElevation();\n\n\t\t\t\tconst existing = await readServerInfo(session);\n\t\t\t\tif (existing) {\n\t\t\t\t\tp.log.info(\n\t\t\t\t\t\t`Already provisioned by vela ${existing.cliVersion} on ${existing.provisionedAt}. Bringing it up to date.`\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tp.log.step('Uploading server scripts');\n\t\t\t\tawait syncServerScripts(session);\n\n\t\t\t\tp.log.step('Running provision');\n\t\t\t\tconst result = await runServerScript<{\n\t\t\t\t\tnode: string;\n\t\t\t\t\tcaddy: string;\n\t\t\t\t\tpocketbase: string;\n\t\t\t\t}>(session, 'provision.sh', {\n\t\t\t\t\targs: [\n\t\t\t\t\t\t'--pb-version',\n\t\t\t\t\t\tpbVersion,\n\t\t\t\t\t\t'--node-major',\n\t\t\t\t\t\toptions.nodeMajor ?? '22',\n\t\t\t\t\t\t'--cli-version',\n\t\t\t\t\t\tpkg.version\n\t\t\t\t\t],\n\t\t\t\t\tstream: true\n\t\t\t\t});\n\n\t\t\t\tp.log.success(\n\t\t\t\t\t`${target} is ready.\\n\\n` +\n\t\t\t\t\t\t` Node ${result?.node ?? 'installed'}\\n` +\n\t\t\t\t\t\t` Caddy ${result?.caddy ?? 'installed'}\\n` +\n\t\t\t\t\t\t` PocketBase ${result?.pocketbase ?? pbVersion}`\n\t\t\t\t);\n\t\t\t});\n\n\t\t\tp.outro(`Deploy with ${pc.cyan(`vela deploy --server ${target}`)}`);\n\t\t}, 'Failed to provision.')\n\t);\n", "import path from 'node:path';\nimport fs from 'node:fs';\nimport { Command, Option } from 'commander';\nimport * as p from '@clack/prompts';\nimport pc from 'picocolors';\nimport * as v from 'valibot';\nimport { helpConfig } from '../lib/help.ts';\nimport { runCommand } from '../lib/run.ts';\nimport { parseOptions } from '../lib/options.ts';\nimport { getWorkspace, hasBackend } from '../lib/workspace.ts';\nimport { withSsh, type SshSession } from '../lib/ssh.ts';\nimport { addSshOptions, SSH_OPTION_SCHEMA, sshOptionsFrom } from '../lib/ssh-options.ts';\nimport { writeBinding } from '../lib/deploy-config.ts';\nimport { addTargetOptions, withTarget } from '../lib/server-command.ts';\nimport { instanceId, normalizeEnvTag, releaseId } from '../lib/instance.ts';\nimport { ensureSuperuser, findFreePort, pocketbaseVersion } from '../lib/pocketbase.ts';\nimport { readLocalMeta, readRemoteAppURL, seedRemoteMeta } from '../lib/pocketbase-settings.ts';\nimport { normalizeOrigin } from '../lib/origin.ts';\nimport { restartInstance } from '../lib/remote-env.ts';\nimport {\n\treadInstanceStates,\n\tremotePaths,\n\ttype InstanceState,\n\trequireProvisioned,\n\trunServerScript,\n\tsyncServerScripts\n} from '../lib/remote.ts';\nimport { collectArtifact, gitSha, runBuild } from '../lib/artifact.ts';\nimport { readRemoteEnv } from '../lib/remote-env.ts';\n\nconst OptionsSchema = v.object({\n\t...SSH_OPTION_SCHEMA,\n\tenv: v.optional(v.string()),\n\tproject: v.optional(v.string()),\n\tremoteDb: v.optional(v.boolean()),\n\tdomain: v.optional(v.string()),\n\thealthPath: v.optional(v.string()),\n\tkeep: v.optional(v.string()),\n\tpbVersion: v.optional(v.string()),\n\tbuild: v.optional(v.boolean())\n});\n\nexport const deploy = addTargetOptions(\n\tnew Command('deploy').description('deploy the app').configureHelp(helpConfig),\n\t'production'\n)\n\t.option('--project <name>', 'override the project name')\n\t.option('--domain <hosts>', 'hostname(s) to serve on, comma separated')\n\t.option('--health-path <path>', 'path the health check requests')\n\t.option('--keep <count>', 'how many old releases to keep on the server')\n\t.option('--pb-version <version>', 'PocketBase version to run')\n\t.option('--no-build', 'deploy the existing build output without rebuilding')\n\t// Both spellings, with no default, so \"neither flag given\" stays\n\t// distinguishable from an explicit choice: commander would otherwise make\n\t// `--no-remote-db` alone default the value to true.\n\t.addOption(\n\t\tnew Option(\n\t\t\t'--remote-db',\n\t\t\t'render the build against the database on the server, over an SSH tunnel \u2014 on by default once the target has been deployed to'\n\t\t).default(undefined)\n\t)\n\t.addOption(\n\t\tnew Option('--no-remote-db', 'render the build against a throwaway local database').default(\n\t\t\tundefined\n\t\t)\n\t)\n\t.action((raw: unknown) =>\n\t\trunCommand(async () => {\n\t\t\tconst options = parseOptions(OptionsSchema, raw);\n\t\t\tconst backend = hasBackend();\n\t\t\tconst release = releaseId();\n\n\t\t\tp.intro(pc.bgCyan(pc.black(' vela deploy ')));\n\n\t\t\tawait withTarget(\n\t\t\t\traw,\n\t\t\t\t{\n\t\t\t\t\tremote: async (ctx) => {\n\t\t\t\t\t\tconst { session, instance, workspaceRootDir, config } = ctx;\n\t\t\t\t\t\tp.log.info(\n\t\t\t\t\t\t\t`${pc.cyan(ctx.appName)} ${pc.dim('\u2192')} ${pc.cyan(ctx.targetName)} ${pc.dim(`(${ctx.server})`)}`\n\t\t\t\t\t\t);\n\n\t\t\t\t\t\tconst [existing] = await readInstanceStates(session, instance);\n\t\t\t\t\t\t// The binding outranks the config file: one `deploy.domain` cannot\n\t\t\t\t\t\t// serve production and staging at once.\n\t\t\t\t\t\tconst domain =\n\t\t\t\t\t\t\toptions.domain ??\n\t\t\t\t\t\t\tctx.binding.domain ??\n\t\t\t\t\t\t\tconfig.deploy?.domain ??\n\t\t\t\t\t\t\texisting?.domain ??\n\t\t\t\t\t\t\t'';\n\t\t\t\t\t\t// Rendering against the database being deployed to is the default\n\t\t\t\t\t\t// once there is one to render against. Left off, a build quietly\n\t\t\t\t\t\t// used a throwaway local database instead, which is how prerendered\n\t\t\t\t\t\t// pages shipped with a developer's own data baked into them.\n\t\t\t\t\t\tconst askedForRemoteDb = options.remoteDb ?? config.deploy?.buildAgainstRemote;\n\t\t\t\t\t\tconst remoteDb = askedForRemoteDb ?? Boolean(existing?.pbPort);\n\n\t\t\t\t\t\tif (options.build !== false) {\n\t\t\t\t\t\t\t// Prerendering has no request to take an origin from, and the\n\t\t\t\t\t\t\t// binding is not written until further down, so a first deploy\n\t\t\t\t\t\t\t// learns its domain from here or not at all.\n\t\t\t\t\t\t\tconst origin = normalizeOrigin(process.env.VELA_ORIGIN ?? domain);\n\t\t\t\t\t\t\tlet buildEnv: Record<string, string | undefined> = origin\n\t\t\t\t\t\t\t\t? { VELA_ORIGIN: origin }\n\t\t\t\t\t\t\t\t: {};\n\t\t\t\t\t\t\tlet tunnel: Tunnel | null = null;\n\n\t\t\t\t\t\t\tif (backend && remoteDb) {\n\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\ttunnel = await openDatabaseTunnel(session, instance, existing);\n\t\t\t\t\t\t\t\t} catch (err) {\n\t\t\t\t\t\t\t\t\t// Asked for explicitly, the failure is the answer. Merely\n\t\t\t\t\t\t\t\t\t// defaulted on, it is only a reason to build the older way.\n\t\t\t\t\t\t\t\t\tif (askedForRemoteDb) throw err;\n\t\t\t\t\t\t\t\t\tp.log.warn(\n\t\t\t\t\t\t\t\t\t\t`Could not build against the ${pc.cyan(ctx.targetName)} database, ` +\n\t\t\t\t\t\t\t\t\t\t\t`using a local one instead.\\n${pc.dim(String(err))}`\n\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif (tunnel) {\n\t\t\t\t\t\t\t\tbuildEnv = { ...buildEnv, ...tunnel.env };\n\t\t\t\t\t\t\t\tp.log.info(\n\t\t\t\t\t\t\t\t\t`Building against the ${pc.cyan(ctx.targetName)} database on ${ctx.server} ${pc.dim(`(port ${tunnel.pbPort})`)}`\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t} else if (backend) {\n\t\t\t\t\t\t\t\t// The build renders pages against a local database, and on a fresh\n\t\t\t\t\t\t\t\t// checkout that database has no superuser yet. Done here as well as\n\t\t\t\t\t\t\t\t// in `vela build` so a project pinning an older CLI builds in CI.\n\t\t\t\t\t\t\t\tawait ensureSuperuser(workspaceRootDir);\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tp.log.step('Building');\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\tawait runBuild(workspaceRootDir, config.deploy?.buildCommand, buildEnv);\n\t\t\t\t\t\t\t} finally {\n\t\t\t\t\t\t\t\tif (tunnel) await tunnel.close();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst entries = collectArtifact(workspaceRootDir, config.deploy ?? {});\n\t\t\t\t\t\tconst sha = await gitSha(workspaceRootDir);\n\n\t\t\t\t\t\tp.log.step(`Uploading release ${pc.dim(release)}`);\n\t\t\t\t\t\tawait uploadRelease(session, instance, release, entries);\n\n\t\t\t\t\t\tp.log.step('Activating');\n\t\t\t\t\t\tconst result = await runServerScript<{\n\t\t\t\t\t\t\turl: string;\n\t\t\t\t\t\t\twebPort: number;\n\t\t\t\t\t\t\tpbPort: number;\n\t\t\t\t\t\t\tsuperuserCreated: boolean;\n\t\t\t\t\t\t}>(session, 'apply.sh', {\n\t\t\t\t\t\t\targs: [\n\t\t\t\t\t\t\t\tinstance,\n\t\t\t\t\t\t\t\trelease,\n\t\t\t\t\t\t\t\t'--name',\n\t\t\t\t\t\t\t\tctx.appName,\n\t\t\t\t\t\t\t\t'--app-id',\n\t\t\t\t\t\t\t\tctx.appId,\n\t\t\t\t\t\t\t\t'--env',\n\t\t\t\t\t\t\t\tctx.envTag,\n\t\t\t\t\t\t\t\t'--domain',\n\t\t\t\t\t\t\t\tdomain,\n\t\t\t\t\t\t\t\t'--health-path',\n\t\t\t\t\t\t\t\toptions.healthPath ?? config.deploy?.healthCheckPath ?? '/',\n\t\t\t\t\t\t\t\t'--keep',\n\t\t\t\t\t\t\t\toptions.keep ?? String(config.deploy?.keepReleases ?? 5),\n\t\t\t\t\t\t\t\t'--backend',\n\t\t\t\t\t\t\t\tbackend ? '1' : '0',\n\t\t\t\t\t\t\t\t'--pb-version',\n\t\t\t\t\t\t\t\toptions.pbVersion ?? config.deploy?.pocketbaseVersion ?? pocketbaseVersion(),\n\t\t\t\t\t\t\t\t'--git-sha',\n\t\t\t\t\t\t\t\tsha\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\tstream: true\n\t\t\t\t\t\t});\n\n\t\t\t\t\t\twriteBinding(workspaceRootDir, ctx.envTag, {\n\t\t\t\t\t\t\tserver: ctx.server,\n\t\t\t\t\t\t\tdomain: domain || undefined\n\t\t\t\t\t\t});\n\t\t\t\t\t\tif (!existing) await reportEmptyEnvironment(session, instance, workspaceRootDir);\n\n\t\t\t\t\t\tconst url = result?.url ?? '';\n\t\t\t\t\t\tp.log.success(\n\t\t\t\t\t\t\t`Deployed ${pc.cyan(ctx.appName)} ${pc.dim(release)}\\n\\n` +\n\t\t\t\t\t\t\t\t` URL ${url}\\n` +\n\t\t\t\t\t\t\t\t` Port ${result?.webPort ?? '?'}${backend ? ` (PocketBase ${result?.pbPort ?? '?'})` : ''}`\n\t\t\t\t\t\t);\n\n\t\t\t\t\t\t// Created by the server on the first deploy of a backend instance, and\n\t\t\t\t\t\t// never printed: the app reads it from the environment, and a human who\n\t\t\t\t\t\t// wants the admin UI sets their own with `vela env set`.\n\t\t\t\t\t\tif (result?.superuserCreated) {\n\t\t\t\t\t\t\tawait copyLocalBranding(\n\t\t\t\t\t\t\t\tsession,\n\t\t\t\t\t\t\t\tinstance,\n\t\t\t\t\t\t\t\tworkspaceRootDir,\n\t\t\t\t\t\t\t\tdomain ? (result?.url ?? '') : ''\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tp.log.info(\n\t\t\t\t\t\t\t\t`Created the PocketBase superuser this app authenticates as.\\n\\n` +\n\t\t\t\t\t\t\t\t\t`Its credentials are stored in the environment on the server. To use\\n` +\n\t\t\t\t\t\t\t\t\t`your own instead, ${pc.cyan('vela env set POCKETBASE_SUPERUSER_PASSWORD')}\\n` +\n\t\t\t\t\t\t\t\t\t`and deploy again.`\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t} else if (backend && domain) {\n\t\t\t\t\t\t\tawait reportAppURLDrift(session, instance, domain);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (!domain) {\n\t\t\t\t\t\t\tp.log.warn(\n\t\t\t\t\t\t\t\t`No domain configured, so nothing is proxied to this app yet.\\n` +\n\t\t\t\t\t\t\t\t\t`Redeploy with ${pc.cyan('--domain example.com')} once DNS points at ${ctx.server}.`\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t{ project: options.project, askDomain: true, label: 'deploy' }\n\t\t\t);\n\n\t\t\tp.outro(`${pc.cyan('vela status')} to see what is running`);\n\t\t}, 'Failed to deploy.')\n\t);\n\n/**\n * Point out an `appURL` that no longer matches the domain being deployed to.\n *\n * `appURL` is seeded once and belongs to the deployed admin panel from then on,\n * which is deliberate \u2014 it is how an app serves one canonical domain while being\n * deployed to another. That also makes it the one setting that can quietly go\n * stale after a domain change, taking password-reset emails and every other link\n * PocketBase renders with it. Reported rather than corrected, so the override\n * keeps working.\n */\nasync function reportAppURLDrift(\n\tsession: SshSession,\n\tinstance: string,\n\tdomain: string\n): Promise<void> {\n\tconst expected = normalizeOrigin(domain);\n\tif (!expected) return;\n\n\tconst current = await readRemoteAppURL(session, instance);\n\tif (!current || normalizeOrigin(current) === expected) return;\n\n\tp.log.warn(\n\t\t`This app's PocketBase ${pc.cyan('appURL')} is ${pc.dim(current)}, but it is served on ${pc.dim(expected)}.\\n\\n` +\n\t\t\t`Emails and anything else PocketBase links to will use the former. Update it in\\n` +\n\t\t\t`the admin panel if that is not deliberate.`\n\t);\n}\n\n/**\n * Give a database this deploy created the branding the project already has.\n *\n * A fresh PocketBase answers with its own defaults, which is how a new\n * deployment ends up calling itself \"Acme\" on every page that reads\n * `locals.meta`. Best-effort by design: the deploy has already succeeded, so\n * nothing here is worth failing it over.\n */\nasync function copyLocalBranding(\n\tsession: SshSession,\n\tinstance: string,\n\tworkspaceRootDir: string,\n\tappURL: string\n): Promise<void> {\n\tconst local = await readLocalMeta(workspaceRootDir);\n\tif (!local) return;\n\n\ttry {\n\t\tconst copied = await seedRemoteMeta(session, instance, local, appURL);\n\t\tif (copied.length === 0) return;\n\n\t\t// The app caches `meta` in process, and it read the defaults on the way up\n\t\t// a moment ago. Without this the site serves PocketBase's \"Acme\" until\n\t\t// something else happens to restart it.\n\t\tconst outcome = await restartInstance(session, instance);\n\t\tif (outcome.deployed && !outcome.restarted) {\n\t\t\tp.log.warn(\n\t\t\t\t`Copied ${copied.join(', ')}, but the app did not restart to pick them up.\\n` +\n\t\t\t\t\t`${pc.dim(outcome.error ?? '')}`\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tp.log.success(`Copied ${copied.join(', ')} from this project's database`);\n\t} catch (err) {\n\t\tp.log.warn(\n\t\t\t`Could not copy this project's PocketBase settings across.\\n` +\n\t\t\t\t`Set them in the admin panel instead. ${pc.dim(String(err))}`\n\t\t);\n\t}\n}\n\ninterface Tunnel {\n\tenv: Record<string, string>;\n\tpbPort: number;\n\tclose: () => Promise<void>;\n}\n\n/**\n * Point the build at the target's PocketBase through the SSH connection that is\n * already open.\n *\n * Pages that prerender from data are rendered at build time, so whatever\n * database the build can see is what gets baked into the static HTML. On a CI\n * runner that is an empty throwaway database, which silently produces pages\n * full of defaults. Building against the instance being deployed to is what a\n * developer's own machine approximates, and what makes CI output match.\n *\n * The superuser credentials come off the server itself, so nothing new has to be\n * stored in CI. The build should only ever read; a load function that writes\n * would write to the live database.\n */\nasync function openDatabaseTunnel(\n\tsession: SshSession,\n\tinstance: string,\n\tstate: InstanceState | undefined\n): Promise<Tunnel> {\n\tconst pbPort = state?.pbPort;\n\tif (!pbPort) {\n\t\tthrow new Error(\n\t\t\t`--remote-db needs an existing deployment to build against, and ${instance} has not been deployed yet.\\n\\n` +\n\t\t\t\t`Deploy once without it, then turn it on.`\n\t\t);\n\t}\n\n\tconst remoteEnv = await readRemoteEnv(session, instance);\n\tconst email = remoteEnv.POCKETBASE_SUPERUSER_EMAIL;\n\tconst password = remoteEnv.POCKETBASE_SUPERUSER_PASSWORD;\n\tif (!email || !password) {\n\t\t// Failing here beats failing thirty seconds later, inside the build, as an\n\t\t// \"invalid login credentials\" stack trace from the app's own hooks.\n\t\tthrow new Error(\n\t\t\t`--remote-db renders the build as the superuser of ${instance}, and that environment has no credentials for one.\\n\\n` +\n\t\t\t\t`Set them with \\`vela env set POCKETBASE_SUPERUSER_EMAIL\\` and \\`vela env set POCKETBASE_SUPERUSER_PASSWORD\\`.`\n\t\t);\n\t}\n\n\tconst localPort = await findFreePort('127.0.0.1');\n\tawait session.forwardLocalPort(localPort, '127.0.0.1', pbPort);\n\n\t// Having credentials is not the same as having ones the database accepts, and\n\t// the difference is invisible until the build is already running: the app\n\t// renders every page as an unauthenticated 500, and the deploy dies as\n\t// `[500] GET /` with nothing naming the cause.\n\t//\n\t// The two drift whenever the superuser password is changed in the admin panel,\n\t// because `$ETC/env` is what a deploy reconciles the database against, and\n\t// that reconciliation happens in `apply.sh` \u2014 after this build. So the first\n\t// deploy after such a change cannot repair itself; it fails here instead, and\n\t// this is where it has to be explained.\n\tif (!(await superuserAuthenticates(localPort, email, password))) {\n\t\tawait session.cancelForward(localPort, '127.0.0.1', pbPort);\n\t\tthrow new Error(\n\t\t\t`${instance} does not accept the superuser credentials in its own environment.\\n\\n` +\n\t\t\t\t`They are what \\`--remote-db\\` renders the build as. The usual cause is a password\\n` +\n\t\t\t\t`changed in the PocketBase admin panel, which leaves the database and\\n` +\n\t\t\t\t`${pc.cyan(`/etc/vela/apps/${instance}/env`)} disagreeing.\\n\\n` +\n\t\t\t\t`Point the environment at the password the database has:\\n` +\n\t\t\t\t` ${pc.cyan('vela env set POCKETBASE_SUPERUSER_PASSWORD')}\\n\\n` +\n\t\t\t\t`or build against a throwaway local database instead:\\n` +\n\t\t\t\t` ${pc.cyan('vela deploy --no-remote-db')}`\n\t\t);\n\t}\n\n\treturn {\n\t\tpbPort,\n\t\tenv: {\n\t\t\tPOCKETBASE_URL: `http://127.0.0.1:${localPort}`,\n\t\t\tPOCKETBASE_SUPERUSER_EMAIL: email,\n\t\t\tPOCKETBASE_SUPERUSER_PASSWORD: password\n\t\t},\n\t\tclose: () => session.cancelForward(localPort, '127.0.0.1', pbPort)\n\t};\n}\n\n/**\n * Whether the instance's own superuser credentials sign in to its database.\n *\n * A plain request rather than a PocketBase client: this runs before the build,\n * and all it needs to know is whether the password is the one on record.\n */\nasync function superuserAuthenticates(\n\tport: number,\n\tidentity: string,\n\tpassword: string\n): Promise<boolean> {\n\ttry {\n\t\tconst response = await fetch(\n\t\t\t`http://127.0.0.1:${port}/api/collections/_superusers/auth-with-password`,\n\t\t\t{\n\t\t\t\tmethod: 'POST',\n\t\t\t\theaders: { 'content-type': 'application/json' },\n\t\t\t\tbody: JSON.stringify({ identity, password })\n\t\t\t}\n\t\t);\n\t\treturn response.ok;\n\t} catch {\n\t\t// Unreachable is not the same as unauthorized, and the tunnel has its own\n\t\t// failure modes. Let the build proceed and report whatever it finds.\n\t\treturn true;\n\t}\n}\n\nasync function uploadRelease(\n\tsession: SshSession,\n\tinstance: string,\n\trelease: string,\n\tentries: { localPath: string; remoteDir: string }[]\n): Promise<void> {\n\tconst dir = remotePaths.release(instance, release);\n\tawait session.script(`mkdir -p \"$1\"`, { args: [dir] });\n\n\tconst byTarget = new Map<string, string[]>();\n\tfor (const entry of entries) {\n\t\tconst target = entry.remoteDir ? `${dir}/${entry.remoteDir}` : dir;\n\t\t// A trailing slash makes rsync copy a directory's contents rather than the\n\t\t// directory itself, which is what a renamed target (data/hooks -> hooks)\n\t\t// needs.\n\t\tconst source =\n\t\t\tentry.remoteDir && isDirectory(entry.localPath) ? `${entry.localPath}/` : entry.localPath;\n\t\tbyTarget.set(target, [...(byTarget.get(target) ?? []), source]);\n\t}\n\n\tfor (const [target, sources] of byTarget) {\n\t\tif (target !== dir) await session.script(`mkdir -p \"$1\"`, { args: [target] });\n\t\tawait session.upload(sources, target);\n\t}\n}\n\nfunction isDirectory(target: string): boolean {\n\ttry {\n\t\treturn fs.statSync(target).isDirectory();\n\t} catch {\n\t\treturn false;\n\t}\n}\n\n/**\n * A brand new instance starts with an empty production environment. Say so once,\n * rather than quietly shipping an app that cannot reach anything \u2014 but never\n * upload the local `.env`, which is a development file.\n */\nasync function reportEmptyEnvironment(\n\tsession: SshSession,\n\tinstance: string,\n\tworkspaceRootDir: string\n): Promise<void> {\n\tconst remote = await readRemoteEnv(session, instance);\n\tif (Object.keys(remote).length > 0) return;\n\tif (!fs.existsSync(path.join(workspaceRootDir, '.env'))) return;\n\n\tp.log.warn(\n\t\t`This app has no production environment variables yet.\\n\\n` +\n\t\t\t`Local ${pc.cyan('.env')} values are not uploaded by a deploy. Set them with\\n` +\n\t\t\t`${pc.cyan('vela env set KEY')}, or copy a file across with ${pc.cyan('vela env import .env.production')}.`\n\t);\n}\n", "import fs from 'node:fs';\nimport path from 'node:path';\nimport process from 'node:process';\nimport PocketBase from 'pocketbase';\nimport { DATA_DIR, MIGRATIONS_DIR } from './constants.ts';\nimport { authWithRetries, startPocketbaseServe } from './pocketbase.ts';\nimport { withRemotePocketbase } from './remote-pocketbase.ts';\nimport type { SshSession } from './ssh.ts';\n\n/**\n * Branding a new deployment inherits from the project's own database.\n *\n * Deliberately not everything under `meta`: `appURL` is per-deployment, and the\n * rest of PocketBase's settings \u2014 smtp, s3, backups \u2014 is either credentials or\n * an endpoint belonging to whichever machine it was configured on. Copying\n * those would push a developer's mail account into production silently.\n */\nconst COPIED_KEYS = ['appName', 'senderName', 'senderAddress'] as const;\n\ntype Meta = Record<string, unknown>;\n\n/**\n * Read the project's own PocketBase settings.\n *\n * The database is a file, so this starts a server against it just long enough\n * to ask. Returns null whenever that is not possible \u2014 no backend, no database\n * yet, no superuser to authenticate as \u2014 because none of those are reasons to\n * fail a deploy that has already succeeded.\n */\nexport async function readLocalMeta(cwd: string): Promise<Meta | null> {\n\tconst dataDir = path.join(cwd, DATA_DIR);\n\tif (!fs.existsSync(dataDir)) return null;\n\n\tconst email = process.env.POCKETBASE_SUPERUSER_EMAIL;\n\tconst password = process.env.POCKETBASE_SUPERUSER_PASSWORD;\n\tif (!email || !password) return null;\n\n\tlet proc: { kill: () => void } | undefined;\n\ttry {\n\t\tconst started = await startPocketbaseServe({\n\t\t\tdataDir,\n\t\t\tmigrationsDir: MIGRATIONS_DIR,\n\t\t\thooksDir: path.join(dataDir, 'hooks')\n\t\t});\n\t\tproc = started.proc;\n\n\t\tconst pb = new PocketBase(started.url);\n\t\tawait authWithRetries(pb, email, password);\n\t\tconst settings = (await pb.settings.getAll()) as { meta?: Meta };\n\t\treturn settings.meta ?? null;\n\t} catch {\n\t\treturn null;\n\t} finally {\n\t\tproc?.kill();\n\t}\n}\n\n/**\n * Read the `appURL` a deployment is currently telling itself it has.\n *\n * Only ever used to report a mismatch, so a database that cannot be reached is\n * not worth a word: the deploy has already succeeded either way.\n */\nexport async function readRemoteAppURL(\n\tsession: SshSession,\n\tinstance: string\n): Promise<string | null> {\n\ttry {\n\t\tlet appURL: string | null = null;\n\t\tawait withRemotePocketbase(session, instance, async (pb) => {\n\t\t\tconst settings = (await pb.settings.getAll()) as { meta?: Meta };\n\t\t\tconst value = settings.meta?.appURL;\n\t\t\tappURL = typeof value === 'string' && value.trim() ? value : null;\n\t\t});\n\t\treturn appURL;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\n/**\n * Give a freshly created deployment the project's branding.\n *\n * Only ever called for a database this deploy created: re-running it would\n * overwrite whatever had since been set in the deployed admin panel, and the\n * deployed value is the one that should win from then on.\n */\nexport async function seedRemoteMeta(\n\tsession: SshSession,\n\tinstance: string,\n\tlocal: Meta,\n\tappURL: string\n): Promise<string[]> {\n\tconst patch: Meta = {};\n\tfor (const key of COPIED_KEYS) {\n\t\tconst value = local[key];\n\t\tif (typeof value === 'string' && value.trim()) patch[key] = value;\n\t}\n\tif (appURL) patch.appURL = appURL;\n\tif (Object.keys(patch).length === 0) return [];\n\n\tawait withRemotePocketbase(session, instance, async (pb) => {\n\t\tconst settings = (await pb.settings.getAll()) as { meta?: Meta };\n\t\t// Merged rather than replaced: `meta` carries fields this does not set,\n\t\t// and PocketBase would take a bare object as the whole of it.\n\t\tawait pb.settings.update({ meta: { ...(settings.meta ?? {}), ...patch } });\n\t});\n\n\treturn Object.keys(patch);\n}\n", "import fs from 'node:fs';\nimport path from 'node:path';\nimport { detect } from 'package-manager-detector';\nimport { resolveCommand } from 'package-manager-detector/commands';\nimport { spawnCapture } from './ssh.ts';\nimport { DATA_DIR, MIGRATIONS_DIR } from './constants.ts';\nimport type { VelaDeployConfig } from './deploy-config.ts';\n\nexport const DEFAULT_OUTPUT_DIR = 'build';\n\n/** One entry in the release: a local path, and where it lands in the release. */\nexport interface ArtifactEntry {\n\tlocalPath: string;\n\t/** Remote subdirectory, or '' for the release root. */\n\tremoteDir: string;\n}\n\nexport class BuildError extends Error {}\n\n/**\n * Run the project's build. Defaults to the package manager's `build` script,\n * which in a vela project is `vela build` \u2014 the same command used locally, so\n * what ships is what was tested.\n */\nexport async function runBuild(\n\tcwd: string,\n\tbuildCommand?: string,\n\tenv?: Record<string, string | undefined>\n): Promise<void> {\n\tif (buildCommand) {\n\t\tconst result = await spawnCapture('bash', ['-lc', buildCommand], {\n\t\t\tcwd,\n\t\t\tstream: true,\n\t\t\tstreamStdout: true,\n\t\t\tenv\n\t\t});\n\t\tif (result.exitCode !== 0)\n\t\t\tthrow new BuildError(`\\`${buildCommand}\\` exited ${result.exitCode}.`);\n\t\treturn;\n\t}\n\n\tconst pm = (await detect({ cwd }))?.name ?? 'npm';\n\tconst resolved = resolveCommand(pm, 'run', ['build']);\n\tif (!resolved) throw new BuildError(`Could not work out how to run a build with ${pm}.`);\n\tconst result = await spawnCapture(resolved.command, resolved.args, {\n\t\tcwd,\n\t\tstream: true,\n\t\tstreamStdout: true,\n\t\tenv\n\t});\n\tif (result.exitCode !== 0) {\n\t\tthrow new BuildError(\n\t\t\t`\\`${resolved.command} ${resolved.args.join(' ')}\\` exited ${result.exitCode}.`\n\t\t);\n\t}\n}\n\n/**\n * Work out what goes into a release.\n *\n * The adapter output plus what PocketBase needs at runtime \u2014 nothing else. No\n * source, no dev dependencies, and deliberately no `.env`: production\n * environment lives on the server and is managed only by `vela env`.\n */\nexport function collectArtifact(cwd: string, config: VelaDeployConfig = {}): ArtifactEntry[] {\n\tconst outputDir = config.outputDir ?? DEFAULT_OUTPUT_DIR;\n\tconst entries: ArtifactEntry[] = [];\n\tconst add = (rel: string, remoteDir = '') => {\n\t\tconst localPath = path.join(cwd, rel);\n\t\tif (fs.existsSync(localPath)) entries.push({ localPath, remoteDir });\n\t};\n\n\tconst buildPath = path.join(cwd, outputDir);\n\tif (!fs.existsSync(path.join(buildPath, 'index.js'))) {\n\t\tthrow new BuildError(\n\t\t\t`No ${outputDir}/index.js after the build.\\n\\n` +\n\t\t\t\t`Deploying to a server needs @sveltejs/adapter-node. Install it and set it as\\n` +\n\t\t\t\t`the adapter in your Vite or Svelte config, then build again.`\n\t\t);\n\t}\n\tentries.push({ localPath: buildPath, remoteDir: '' });\n\n\tadd('package.json');\n\tadd('package-lock.json');\n\tadd('.npmrc');\n\tadd(MIGRATIONS_DIR);\n\t// PocketBase hooks live under `data/` locally but next to the release on the\n\t// server, where `data/` is the instance's private database directory.\n\tconst hooks = path.join(cwd, DATA_DIR, 'hooks');\n\tif (fs.existsSync(hooks)) entries.push({ localPath: hooks, remoteDir: 'hooks' });\n\n\tfor (const extra of config.include ?? []) add(extra);\n\n\treturn entries;\n}\n\nexport function hasLockfile(cwd: string): boolean {\n\treturn fs.existsSync(path.join(cwd, 'package-lock.json'));\n}\n\n/** Best-effort git metadata, recorded on the release for traceability. */\nexport async function gitSha(cwd: string): Promise<string> {\n\tconst result = await spawnCapture('git', ['rev-parse', 'HEAD'], { cwd });\n\treturn result.exitCode === 0 ? result.stdout.trim() : '';\n}\n", "import path from 'node:path';\nimport process from 'node:process';\nimport { Command } from 'commander';\nimport * as p from '@clack/prompts';\nimport { helpConfig } from '../lib/help.ts';\nimport { runCommand } from '../lib/run.ts';\nimport { requireApiKey } from '../lib/config.ts';\nimport { getWorkspace } from '../lib/workspace.ts';\nimport { readPackageJson } from '../lib/package-json.ts';\nimport { readProjectConfig, writeProjectConfig } from '../lib/project-config.ts';\nimport {\n\tcreateProject,\n\tgetCurrentUser,\n\tlistProjects,\n\tlistTeams,\n\ttype ProjectRecord,\n\ttype Team\n} from '../lib/velastack-api.ts';\n\nconst CREATE_NEW = '__new__';\n\nexport const link = new Command('link')\n\t.description('link this project to a velastack.dev project')\n\t.configureHelp(helpConfig)\n\t.action(() => runCommand(linkProject, 'Failed to link the project.'));\n\nasync function linkProject() {\n\tconst { workspaceRootDir } = await getWorkspace();\n\n\tconst existing = readProjectConfig(workspaceRootDir);\n\tif (existing) {\n\t\tp.log.success(`Linked to ${existing.projectName}.`);\n\t\treturn;\n\t}\n\n\tconst apiKey = requireApiKey();\n\tconst [user, teams, projects] = await Promise.all([\n\t\tgetCurrentUser(apiKey),\n\t\tlistTeams(apiKey),\n\t\tlistProjects(apiKey)\n\t]);\n\n\tlet projectId: string;\n\tlet teamId: string;\n\tlet projectName: string;\n\n\tconst picked = projects.length > 0 ? await pickExistingProject(projects) : CREATE_NEW;\n\tif (picked !== CREATE_NEW) {\n\t\tconst project = projects.find((pr) => pr.id === picked)!;\n\t\tprojectId = project.id;\n\t\tteamId = project.team;\n\t\tprojectName = project.name;\n\t} else {\n\t\tconst team = await pickTeam(teams);\n\t\tconst name = await promptProjectName(workspaceRootDir);\n\t\tconst created = await createProject(apiKey, { name, teamId: team.id, userId: user.id });\n\t\tprojectId = created.id;\n\t\tteamId = team.id;\n\t\tprojectName = created.name;\n\t}\n\n\twriteProjectConfig(workspaceRootDir, { projectId, teamId, projectName });\n\tp.log.success(`Linked to ${projectName}.`);\n}\n\nasync function pickExistingProject(projects: ProjectRecord[]): Promise<string> {\n\tconst choice = await p.select({\n\t\tmessage: 'Select a project',\n\t\toptions: [\n\t\t\t...projects.map((pr) => ({\n\t\t\t\tvalue: pr.id,\n\t\t\t\tlabel: `${pr.name} (${pr.expand?.team?.name ?? 'unknown team'})`\n\t\t\t})),\n\t\t\t{ value: CREATE_NEW, label: 'Create a new project' }\n\t\t]\n\t});\n\tif (p.isCancel(choice)) {\n\t\tp.cancel('Operation cancelled.');\n\t\tprocess.exit(0);\n\t}\n\treturn choice;\n}\n\nasync function pickTeam(teams: Team[]): Promise<Team> {\n\tif (teams.length === 1) return teams[0]!;\n\tconst choice = await p.select({\n\t\tmessage: 'Select a team',\n\t\toptions: teams.map((team) => ({\n\t\t\tvalue: team.id,\n\t\t\tlabel: team.is_personal ? `${team.name} (personal)` : team.name\n\t\t}))\n\t});\n\tif (p.isCancel(choice)) {\n\t\tp.cancel('Operation cancelled.');\n\t\tprocess.exit(0);\n\t}\n\treturn teams.find((team) => team.id === choice)!;\n}\n\nasync function promptProjectName(workspaceRootDir: string): Promise<string> {\n\tconst defaultValue = defaultProjectName(workspaceRootDir);\n\tconst value = await p.text({\n\t\tmessage: 'Project name',\n\t\tdefaultValue,\n\t\tinitialValue: defaultValue,\n\t\tplaceholder: defaultValue,\n\t\tvalidate: (v) => (!v?.trim() ? 'Required' : undefined)\n\t});\n\tif (p.isCancel(value)) {\n\t\tp.cancel('Operation cancelled.');\n\t\tprocess.exit(0);\n\t}\n\treturn value.trim();\n}\n\nfunction defaultProjectName(workspaceRootDir: string): string {\n\ttry {\n\t\tconst pkg = readPackageJson(path.join(workspaceRootDir, 'package.json'));\n\t\tconst name = pkg.name;\n\t\tif (typeof name === 'string' && name.trim()) return name.trim();\n\t} catch {\n\t\t// fall through\n\t}\n\treturn path.basename(workspaceRootDir);\n}\n", "import { API_URL } from './constants.ts';\n\nexport interface User {\n\tid: string;\n\temail: string;\n}\n\nexport interface Team {\n\tid: string;\n\tname: string;\n\tis_personal: boolean;\n\towner: string;\n}\n\nexport interface ProjectRecord {\n\tid: string;\n\tname: string;\n\tteam: string;\n\tuser?: string;\n\texpand?: { team?: Team };\n}\n\ninterface PaginatedResponse<T> {\n\titems: T[];\n\tpage: number;\n\tperPage: number;\n\ttotalItems: number;\n\ttotalPages: number;\n}\n\nasync function apiFetch<T>(apiKey: string, pathAndQuery: string, init?: RequestInit): Promise<T> {\n\tconst headers = new Headers(init?.headers);\n\theaders.set('Authorization', `Bearer ${apiKey}`);\n\tif (init?.body && !headers.has('Content-Type')) {\n\t\theaders.set('Content-Type', 'application/json');\n\t}\n\n\tconst res = await fetch(`${API_URL}${pathAndQuery}`, { ...init, headers });\n\tif (res.status === 401 || res.status === 403) {\n\t\tthrow new Error('API key invalid \u2014 run `vela login`');\n\t}\n\tif (!res.ok) {\n\t\tconst body = await res.text().catch(() => '');\n\t\tthrow new Error(`Velastack API error (${res.status}): ${body || res.statusText}`);\n\t}\n\treturn (await res.json()) as T;\n}\n\nexport async function getCurrentUser(apiKey: string): Promise<User> {\n\tconst data = await apiFetch<PaginatedResponse<User>>(\n\t\tapiKey,\n\t\t'/api/collections/users/records?perPage=1'\n\t);\n\tconst user = data.items[0];\n\tif (!user) throw new Error('No user found. Run `vela login` to login.');\n\treturn user;\n}\n\nexport async function listTeams(apiKey: string): Promise<Team[]> {\n\tconst data = await apiFetch<PaginatedResponse<Team>>(\n\t\tapiKey,\n\t\t'/api/collections/teams/records?perPage=200'\n\t);\n\treturn data.items;\n}\n\nexport async function listProjects(apiKey: string): Promise<ProjectRecord[]> {\n\tconst data = await apiFetch<PaginatedResponse<ProjectRecord>>(\n\t\tapiKey,\n\t\t'/api/collections/projects/records?perPage=200&expand=team'\n\t);\n\treturn data.items;\n}\n\nexport async function createProject(\n\tapiKey: string,\n\targs: { name: string; teamId: string; userId: string }\n): Promise<ProjectRecord> {\n\treturn apiFetch<ProjectRecord>(apiKey, '/api/collections/projects/records', {\n\t\tmethod: 'POST',\n\t\tbody: JSON.stringify({ name: args.name, team: args.teamId, user: args.userId })\n\t});\n}\n", "import { Command } from 'commander';\nimport { helpConfig } from '../lib/help.ts';\nimport { envList } from './env/list.ts';\nimport { envSet } from './env/set.ts';\nimport { envUnset } from './env/unset.ts';\nimport { envImport } from './env/import.ts';\n\nexport const env = new Command('env')\n\t.description('manage environment variables, locally or on a target')\n\t.configureHelp(helpConfig)\n\t.addCommand(envList)\n\t.addCommand(envSet)\n\t.addCommand(envUnset)\n\t.addCommand(envImport);\n", "import { Command } from 'commander';\nimport * as p from '@clack/prompts';\nimport pc from 'picocolors';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand } from '../../lib/run.ts';\nimport { addTargetOptions, withTarget } from '../../lib/server-command.ts';\nimport { readRemoteEnv } from '../../lib/remote-env.ts';\nimport { readLocalEnv } from '../../lib/local-env.ts';\n\nexport const envList = addTargetOptions(\n\tnew Command('list').description('list environment variable names').configureHelp(helpConfig),\n\t'local'\n).action((raw: unknown) =>\n\trunCommand(\n\t\t() =>\n\t\t\twithTarget(\n\t\t\t\traw,\n\t\t\t\t{\n\t\t\t\t\tlocal: async (ctx) => {\n\t\t\t\t\t\treport(Object.keys(readLocalEnv(ctx.envFile)), `${ctx.appName}, local (.env)`);\n\t\t\t\t\t},\n\t\t\t\t\tremote: async (ctx) => {\n\t\t\t\t\t\tconst env = await readRemoteEnv(ctx.session, ctx.instance);\n\t\t\t\t\t\treport(Object.keys(env), `${ctx.appName}, ${ctx.targetName}`);\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t{ label: 'env list' }\n\t\t\t),\n\t\t'Failed to read the environment.'\n\t)\n);\n\n// Names only, never values \u2014 the same rule on both sides, so that piping the\n// output of one into a screenshot or an issue is safe wherever it came from.\nfunction report(keys: string[], where: string): void {\n\tif (keys.length === 0) {\n\t\tp.log.info(`No environment variables configured ${pc.dim(`(${where})`)}.`);\n\t\treturn;\n\t}\n\tp.log.info(\n\t\t`Environment ${pc.dim(`(${where})`)}\\n\\n` +\n\t\t\tkeys\n\t\t\t\t.sort()\n\t\t\t\t.map((key) => ` ${key}`)\n\t\t\t\t.join('\\n')\n\t);\n}\n", "import process from 'node:process';\nimport { Command } from 'commander';\nimport * as p from '@clack/prompts';\nimport pc from 'picocolors';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand } from '../../lib/run.ts';\nimport { addTargetOptions, applyEnvRestart, withTarget } from '../../lib/server-command.ts';\nimport { isValidKey, readRemoteEnv, writeRemoteEnv } from '../../lib/remote-env.ts';\nimport { applyLocalEnvChange, setLocalEnv } from '../../lib/local-env.ts';\n\nexport const envSet = addTargetOptions(\n\tnew Command('set')\n\t\t.description('set an environment variable')\n\t\t.argument('<key>', 'variable name')\n\t\t.argument('[value]', 'value \u2014 prompted for, without echo, when omitted')\n\t\t.configureHelp(helpConfig),\n\t'local'\n).action((key: string, value: string | undefined, raw: unknown) =>\n\trunCommand(\n\t\t() =>\n\t\t\twithTarget(\n\t\t\t\traw,\n\t\t\t\t{\n\t\t\t\t\tlocal: async (ctx) => {\n\t\t\t\t\t\tconst resolved = await resolveValue(key, value);\n\t\t\t\t\t\tsetLocalEnv(ctx.envFile, key, resolved);\n\t\t\t\t\t\tp.log.success(`${key} updated ${pc.dim('(local)')}`);\n\t\t\t\t\t\tawait applyLocalEnvChange(ctx, [key]);\n\t\t\t\t\t},\n\t\t\t\t\tremote: async (ctx) => {\n\t\t\t\t\t\tconst resolved = await resolveValue(key, value);\n\t\t\t\t\t\tconst env = await readRemoteEnv(ctx.session, ctx.instance);\n\t\t\t\t\t\tawait writeRemoteEnv(ctx.session, ctx.instance, { ...env, [key]: resolved });\n\t\t\t\t\t\tp.log.success(`${key} updated ${pc.dim(`(${ctx.targetName})`)}`);\n\t\t\t\t\t\tawait applyEnvRestart(ctx, [key]);\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t{ label: 'env set' }\n\t\t\t),\n\t\t'Failed to set the variable.'\n\t)\n);\n\nasync function resolveValue(key: string, value: string | undefined): Promise<string> {\n\tif (!isValidKey(key)) throw new Error(`${key} is not a valid environment variable name.`);\n\treturn value ?? (await promptValue(key));\n}\n\nasync function promptValue(key: string): Promise<string> {\n\tconst value = await p.password({\n\t\tmessage: `Value for ${pc.cyan(key)}`,\n\t\tvalidate: (input) => (!input?.length ? 'Required' : undefined)\n\t});\n\tif (p.isCancel(value)) {\n\t\tp.cancel('Operation cancelled.');\n\t\tprocess.exit(0);\n\t}\n\treturn value;\n}\n", "import { Command } from 'commander';\nimport * as p from '@clack/prompts';\nimport pc from 'picocolors';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand } from '../../lib/run.ts';\nimport { addTargetOptions, applyEnvRestart, withTarget } from '../../lib/server-command.ts';\nimport { readRemoteEnv, writeRemoteEnv } from '../../lib/remote-env.ts';\nimport { applyLocalEnvChange, readLocalEnv, unsetLocalEnv } from '../../lib/local-env.ts';\n\nexport const envUnset = addTargetOptions(\n\tnew Command('unset')\n\t\t.description('remove an environment variable')\n\t\t.argument('<key>', 'variable name')\n\t\t.configureHelp(helpConfig),\n\t'local'\n).action((key: string, raw: unknown) =>\n\trunCommand(\n\t\t() =>\n\t\t\twithTarget(\n\t\t\t\traw,\n\t\t\t\t{\n\t\t\t\t\tlocal: async (ctx) => {\n\t\t\t\t\t\tif (!(key in readLocalEnv(ctx.envFile))) {\n\t\t\t\t\t\t\tp.log.info(`${key} is not set \u2014 nothing to remove.`);\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tunsetLocalEnv(ctx.envFile, key);\n\t\t\t\t\t\tp.log.success(`${key} removed ${pc.dim('(local)')}`);\n\t\t\t\t\t\tawait applyLocalEnvChange(ctx, [key]);\n\t\t\t\t\t},\n\t\t\t\t\tremote: async (ctx) => {\n\t\t\t\t\t\tconst env = await readRemoteEnv(ctx.session, ctx.instance);\n\t\t\t\t\t\tif (!(key in env)) {\n\t\t\t\t\t\t\tp.log.info(`${key} is not set \u2014 nothing to remove.`);\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tdelete env[key];\n\t\t\t\t\t\tawait writeRemoteEnv(ctx.session, ctx.instance, env);\n\t\t\t\t\t\tp.log.success(`${key} removed ${pc.dim(`(${ctx.targetName})`)}`);\n\t\t\t\t\t\tawait applyEnvRestart(ctx, [key]);\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t{ label: 'env unset' }\n\t\t\t),\n\t\t'Failed to remove the variable.'\n\t)\n);\n", "import fs from 'node:fs';\nimport path from 'node:path';\nimport process from 'node:process';\nimport { Command } from 'commander';\nimport * as p from '@clack/prompts';\nimport pc from 'picocolors';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand } from '../../lib/run.ts';\nimport { addTargetOptions, applyEnvRestart, withTarget } from '../../lib/server-command.ts';\nimport { readLocalEnvFile, readRemoteEnv, writeRemoteEnv } from '../../lib/remote-env.ts';\nimport { applyLocalEnvChange, editLocalEnv } from '../../lib/local-env.ts';\nimport { upsertEnvVar } from '../../lib/env.ts';\n\nexport const envImport = addTargetOptions(\n\tnew Command('import')\n\t\t.description('merge a dotenv file into the environment')\n\t\t.argument('<file>', 'dotenv file to read')\n\t\t.configureHelp(helpConfig),\n\t'local'\n).action((file: string, raw: unknown) =>\n\trunCommand(\n\t\t() =>\n\t\t\twithTarget(\n\t\t\t\traw,\n\t\t\t\t{\n\t\t\t\t\tlocal: async (ctx) => {\n\t\t\t\t\t\tconst source = resolve(file);\n\t\t\t\t\t\tif (source === ctx.envFile) {\n\t\t\t\t\t\t\tthrow new Error(`${file} is the file you would be importing into.`);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst incoming = read(source, file);\n\t\t\t\t\t\tconst keys = Object.keys(incoming);\n\t\t\t\t\t\tif (keys.length === 0) return;\n\n\t\t\t\t\t\tp.log.step(`Importing ${keys.length} variable(s) from ${pc.cyan(file)}`);\n\t\t\t\t\t\teditLocalEnv(ctx.envFile, (content) =>\n\t\t\t\t\t\t\tkeys.reduce((acc, key) => upsertEnvVar(acc, key, incoming[key]!), content)\n\t\t\t\t\t\t);\n\t\t\t\t\t\tp.log.success(`${keys.length} variable(s) updated ${pc.dim('(local)')}`);\n\t\t\t\t\t\tawait applyLocalEnvChange(ctx, keys);\n\t\t\t\t\t},\n\t\t\t\t\tremote: async (ctx) => {\n\t\t\t\t\t\tconst incoming = read(resolve(file), file);\n\t\t\t\t\t\tconst keys = Object.keys(incoming);\n\t\t\t\t\t\tif (keys.length === 0) return;\n\n\t\t\t\t\t\tp.log.step(`Importing ${keys.length} variable(s) from ${pc.cyan(file)}`);\n\t\t\t\t\t\t// Merge: values on the server that the file does not mention stay put.\n\t\t\t\t\t\tconst existing = await readRemoteEnv(ctx.session, ctx.instance);\n\t\t\t\t\t\tawait writeRemoteEnv(ctx.session, ctx.instance, { ...existing, ...incoming });\n\n\t\t\t\t\t\tp.log.success(`${keys.length} variable(s) updated ${pc.dim(`(${ctx.targetName})`)}`);\n\t\t\t\t\t\tawait applyEnvRestart(ctx, keys);\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t{ label: 'env import' }\n\t\t\t),\n\t\t'Failed to import the environment.'\n\t)\n);\n\nfunction resolve(file: string): string {\n\treturn path.resolve(process.cwd(), file);\n}\n\nfunction read(resolved: string, shown: string): Record<string, string> {\n\tif (!fs.existsSync(resolved)) throw new Error(`${shown} does not exist.`);\n\tconst incoming = readLocalEnvFile(resolved);\n\tif (Object.keys(incoming).length === 0) p.log.info(`${shown} has no variables to import.`);\n\treturn incoming;\n}\n", "import { Command } from 'commander';\nimport * as p from '@clack/prompts';\nimport pc from 'picocolors';\nimport { helpConfig } from '../lib/help.ts';\nimport { runCommand } from '../lib/run.ts';\nimport { addTargetOptions, withServerSession, withTarget } from '../lib/server-command.ts';\nimport { readInstanceStates, type InstanceState } from '../lib/remote.ts';\n\nexport const status = addTargetOptions(\n\tnew Command('status').description('show what is deployed').configureHelp(helpConfig),\n\t'production'\n)\n\t.option('--all', 'show every app on the server, not just this project')\n\t.option('--json', 'print raw JSON')\n\t.action((raw: unknown) =>\n\t\trunCommand(async () => {\n\t\t\tconst options = raw as { all?: boolean; json?: boolean };\n\n\t\t\t// `--all` is a question about the machine, so it needs a server but not\n\t\t\t// an instance \u2014 and `--server` alone answers it outside a project.\n\t\t\tif (options.all) {\n\t\t\t\tawait withServerSession(raw, async (session) => {\n\t\t\t\t\treport(await readInstanceStates(session), options.json);\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tawait withTarget(\n\t\t\t\traw,\n\t\t\t\t{\n\t\t\t\t\tremote: async (ctx) => {\n\t\t\t\t\t\treport(await readInstanceStates(ctx.session, ctx.instance), options.json);\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tlabel: 'status',\n\t\t\t\t\tlocalHint: 'Nothing is deployed locally \u2014 `vela dev` reports what it is running.'\n\t\t\t\t}\n\t\t\t);\n\t\t}, 'Failed to read status.')\n\t);\n\nfunction report(states: InstanceState[], json?: boolean): void {\n\tif (json) {\n\t\tconsole.log(JSON.stringify(states, null, 2));\n\t\treturn;\n\t}\n\tif (states.length === 0) {\n\t\tp.log.info('Nothing is deployed here yet.');\n\t\treturn;\n\t}\n\tfor (const state of states) {\n\t\tp.log.info(describe(state));\n\t}\n}\n\nfunction describe(state: InstanceState): string {\n\tconst health = (value?: string) =>\n\t\tvalue === 'active' ? pc.green(value) : pc.red(value || 'inactive');\n\tconst rows: [string, string][] = [\n\t\t['Instance', state.instance],\n\t\t['Environment', state.env],\n\t\t['Release', state.activeRelease ?? '\u2014'],\n\t\t['Previous', state.previousRelease || '\u2014'],\n\t\t['Domain', state.domain || '\u2014'],\n\t\t['Ports', `web ${state.webPort ?? '?'}${state.backend ? `, pb ${state.pbPort ?? '?'}` : ''}`],\n\t\t['App', health(state.services?.web)],\n\t\t...(state.backend\n\t\t\t? ([['PocketBase', health(state.services?.pocketbase)]] as [string, string][])\n\t\t\t: []),\n\t\t['Deployed', state.deployedAt ?? '\u2014'],\n\t\t...(state.rolledBackAt ? ([['Rolled back', state.rolledBackAt]] as [string, string][]) : []),\n\t\t...(state.gitSha ? ([['Commit', state.gitSha.slice(0, 12)]] as [string, string][]) : [])\n\t];\n\tconst width = Math.max(...rows.map(([label]) => label.length));\n\treturn (\n\t\tpc.cyan(state.name) +\n\t\t'\\n\\n' +\n\t\trows.map(([label, value]) => ` ${label.padEnd(width)} ${value}`).join('\\n')\n\t);\n}\n", "import { Command } from 'commander';\nimport * as p from '@clack/prompts';\nimport pc from 'picocolors';\nimport { helpConfig } from '../lib/help.ts';\nimport { runCommand } from '../lib/run.ts';\nimport { addTargetOptions, withTarget } from '../lib/server-command.ts';\nimport { runServerScript } from '../lib/remote.ts';\n\nexport const rollback = addTargetOptions(\n\tnew Command('rollback').description('put the previous release back').configureHelp(helpConfig),\n\t'production'\n)\n\t.option('--to <release>', 'roll back to a specific release instead of the previous one')\n\t.action((raw: unknown) =>\n\t\trunCommand(async () => {\n\t\t\tconst options = raw as { to?: string };\n\t\t\tawait withTarget(\n\t\t\t\traw,\n\t\t\t\t{\n\t\t\t\t\tremote: async (ctx) => {\n\t\t\t\t\t\tp.log.step(\n\t\t\t\t\t\t\t`Rolling back ${pc.cyan(ctx.appName)} ${pc.dim(`(${ctx.targetName})`)} on ${ctx.server}`\n\t\t\t\t\t\t);\n\n\t\t\t\t\t\tconst result = await runServerScript<{ release: string; from: string }>(\n\t\t\t\t\t\t\tctx.session,\n\t\t\t\t\t\t\t'rollback.sh',\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\targs: [ctx.instance, ...(options.to ? ['--to', options.to] : [])],\n\t\t\t\t\t\t\t\tstream: true\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t);\n\n\t\t\t\t\t\tp.log.success(\n\t\t\t\t\t\t\t`Rolled back to ${pc.cyan(result?.release ?? 'the previous release')}` +\n\t\t\t\t\t\t\t\t(result?.from ? ` ${pc.dim(`(was ${result.from})`)}` : '')\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tlabel: 'rollback',\n\t\t\t\t\tlocalHint: 'Nothing is released locally \u2014 `vela dev` always runs the working tree.'\n\t\t\t\t}\n\t\t\t);\n\t\t}, 'Failed to roll back.')\n\t);\n", "import { Command } from 'commander';\nimport { helpConfig } from '../lib/help.ts';\nimport { runCommand } from '../lib/run.ts';\nimport { addTargetOptions, withTarget } from '../lib/server-command.ts';\nimport { remotePaths } from '../lib/remote.ts';\n\nexport const logs = addTargetOptions(\n\tnew Command('logs').description('tail the logs of a deployed app').configureHelp(helpConfig),\n\t'production'\n)\n\t.option('-f, --follow', 'keep streaming new output')\n\t.option('-n, --lines <count>', 'how many lines of history to show', '100')\n\t.option('--pocketbase', 'show the PocketBase service instead of the app')\n\t.action((raw: unknown) =>\n\t\trunCommand(async () => {\n\t\t\tconst options = raw as { follow?: boolean; lines?: string; pocketbase?: boolean };\n\t\t\tawait withTarget(\n\t\t\t\traw,\n\t\t\t\t{\n\t\t\t\t\tremote: async (ctx) => {\n\t\t\t\t\t\tconst unit = options.pocketbase\n\t\t\t\t\t\t\t? remotePaths.pbUnit(ctx.instance)\n\t\t\t\t\t\t\t: remotePaths.webUnit(ctx.instance);\n\t\t\t\t\t\tconst command = [\n\t\t\t\t\t\t\t'journalctl',\n\t\t\t\t\t\t\t'-u',\n\t\t\t\t\t\t\tunit,\n\t\t\t\t\t\t\t'-n',\n\t\t\t\t\t\t\toptions.lines ?? '100',\n\t\t\t\t\t\t\t'--no-pager',\n\t\t\t\t\t\t\t...(options.follow ? ['-f'] : [])\n\t\t\t\t\t\t];\n\t\t\t\t\t\tconst code = await ctx.session.interactive(command);\n\t\t\t\t\t\tif (code !== 0 && !options.follow) {\n\t\t\t\t\t\t\tthrow new Error(`journalctl exited ${code}.`);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tlabel: 'logs',\n\t\t\t\t\tlocalHint:\n\t\t\t\t\t\t'There are no logs for the copy on this machine \u2014 `vela dev` prints them as it runs.'\n\t\t\t\t}\n\t\t\t);\n\t\t}, 'Failed to read logs.')\n\t);\n", "import { Command } from 'commander';\nimport { helpConfig } from '../lib/help.ts';\nimport { adminCreate } from './admin/create.ts';\n\nexport const admin = new Command('admin')\n\t.description('manage admin panel logins')\n\t.configureHelp(helpConfig)\n\t.addCommand(adminCreate);\n", "import process from 'node:process';\nimport type PocketBase from 'pocketbase';\nimport { Command } from 'commander';\nimport * as p from '@clack/prompts';\nimport pc from 'picocolors';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand } from '../../lib/run.ts';\nimport { addTargetOptions, withTarget } from '../../lib/server-command.ts';\nimport { withRemotePocketbase } from '../../lib/remote-pocketbase.ts';\nimport { readInstanceStates } from '../../lib/remote.ts';\nimport { getPocketbaseMetadata, withPocketbase } from '../../lib/pocketbase.ts';\nimport { readLocalEnv } from '../../lib/local-env.ts';\n\n/** PocketBase's own minimum for a superuser password. */\nconst MIN_PASSWORD = 10;\n\nexport const adminCreate = addTargetOptions(\n\tnew Command('create')\n\t\t.description('create a login for the admin panel')\n\t\t.argument('[email]', 'email to sign in with \u2014 prompted for when omitted')\n\t\t.configureHelp(helpConfig),\n\t'local'\n).action((email: string | undefined, raw: unknown) =>\n\trunCommand(\n\t\t() =>\n\t\t\twithTarget(\n\t\t\t\traw,\n\t\t\t\t{\n\t\t\t\t\tlocal: async (ctx) => {\n\t\t\t\t\t\tconst creds = readLocalEnv(ctx.envFile);\n\t\t\t\t\t\tconst address = email ?? (await promptEmail());\n\t\t\t\t\t\tconst password = await promptPassword();\n\n\t\t\t\t\t\tlet signIn = '';\n\t\t\t\t\t\tawait withPocketbase(\n\t\t\t\t\t\t\tctx.workspaceRootDir,\n\t\t\t\t\t\t\tasync (pb) => {\n\t\t\t\t\t\t\t\tawait upsertSuperuser(pb, address, password);\n\t\t\t\t\t\t\t\t// `vela dev` writes the real URL into PocketBase settings on every\n\t\t\t\t\t\t\t\t// boot, and it survives dev exiting \u2014 a better source than the\n\t\t\t\t\t\t\t\t// metadata file, which is deleted when dev stops.\n\t\t\t\t\t\t\t\tconst settings = (await pb.settings.getAll()) as {\n\t\t\t\t\t\t\t\t\tmeta?: { appURL?: string };\n\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t\tsignIn = settings.meta?.appURL ?? '';\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\temail: creds.POCKETBASE_SUPERUSER_EMAIL,\n\t\t\t\t\t\t\t\tpassword: creds.POCKETBASE_SUPERUSER_PASSWORD\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t);\n\n\t\t\t\t\t\tif (!signIn) {\n\t\t\t\t\t\t\tconst metadata = getPocketbaseMetadata(ctx.workspaceRootDir);\n\t\t\t\t\t\t\tif (metadata) signIn = `http://${metadata.viteHost}:${metadata.vitePort}`;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tp.log.info(\n\t\t\t\t\t\t\tsignIn\n\t\t\t\t\t\t\t\t? `Sign in at ${pc.cyan(`${signIn}/admin`)}`\n\t\t\t\t\t\t\t\t: `Sign in at ${pc.cyan('/admin')} once ${pc.cyan('vela dev')} is running.`\n\t\t\t\t\t\t);\n\t\t\t\t\t},\n\t\t\t\t\tremote: async (ctx) => {\n\t\t\t\t\t\tconst address = email ?? (await promptEmail());\n\t\t\t\t\t\tconst password = await promptPassword();\n\t\t\t\t\t\tconst [state] = await readInstanceStates(ctx.session, ctx.instance);\n\n\t\t\t\t\t\tawait withRemotePocketbase(ctx.session, ctx.instance, (pb) =>\n\t\t\t\t\t\t\tupsertSuperuser(pb, address, password)\n\t\t\t\t\t\t);\n\n\t\t\t\t\t\t// The panel is served by the app itself, at the adapter's `/admin`,\n\t\t\t\t\t\t// so it is reachable wherever the app is \u2014 PocketBase itself never\n\t\t\t\t\t\t// leaves the server's loopback.\n\t\t\t\t\t\tconst base = state?.domain ? `https://${state.domain.split(',')[0]!.trim()}` : '';\n\t\t\t\t\t\tp.log.info(\n\t\t\t\t\t\t\tbase\n\t\t\t\t\t\t\t\t? `Sign in at ${pc.cyan(`${base}/admin`)}`\n\t\t\t\t\t\t\t\t: `Sign in at ${pc.cyan('/admin')} once a domain is configured for this target.`\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t{ label: 'admin create' }\n\t\t\t),\n\t\t'Failed to create the admin login.'\n\t)\n);\n\n/**\n * Create the login, or reset its password when the email already signs in.\n *\n * Shared by both targets so a local account and a deployed one are made the same\n * way, against whichever PocketBase the caller opened.\n */\nasync function upsertSuperuser(pb: PocketBase, email: string, password: string): Promise<void> {\n\tconst existing = await findSuperuser(pb, email);\n\tif (existing) {\n\t\tconst confirmed = await p.confirm({\n\t\t\tmessage: `${email} already has an account, update its password?`,\n\t\t\tinitialValue: false\n\t\t});\n\t\tif (p.isCancel(confirmed) || !confirmed) {\n\t\t\tp.cancel('Operation cancelled.');\n\t\t\tprocess.exit(0);\n\t\t}\n\t\tawait pb.collection('_superusers').update(existing, { password, passwordConfirm: password });\n\t\tp.log.success(`Password updated for ${pc.cyan(email)}, you can sign in now`);\n\t\treturn;\n\t}\n\n\tawait pb.collection('_superusers').create({ email, password, passwordConfirm: password });\n\tp.log.success(`${pc.cyan(email)} can now sign in`);\n}\n\n/**\n * The account this creates is the human's, and deliberately separate from the\n * superuser the app authenticates as: that one is generated on the server, kept\n * in the instance environment and never printed. Two accounts, so a person can\n * be given or denied access without touching what the app runs on.\n */\nasync function findSuperuser(pb: PocketBase, email: string): Promise<string | null> {\n\ttry {\n\t\tconst record = await pb\n\t\t\t.collection('_superusers')\n\t\t\t.getFirstListItem(pb.filter('email = {:email}', { email }));\n\t\treturn record.id;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nasync function promptEmail(): Promise<string> {\n\tconst value = await p.text({\n\t\tmessage: 'Email to sign in with',\n\t\tvalidate: (input) => (input?.includes('@') ? undefined : 'An email address is required')\n\t});\n\tif (p.isCancel(value)) {\n\t\tp.cancel('Operation cancelled.');\n\t\tprocess.exit(0);\n\t}\n\treturn value.trim();\n}\n\nasync function promptPassword(): Promise<string> {\n\tconst value = await p.password({\n\t\tmessage: 'Password',\n\t\tvalidate: (input) =>\n\t\t\t(input?.length ?? 0) >= MIN_PASSWORD\n\t\t\t\t? undefined\n\t\t\t\t: `At least ${MIN_PASSWORD} characters is required`\n\t});\n\tif (p.isCancel(value)) {\n\t\tp.cancel('Operation cancelled.');\n\t\tprocess.exit(0);\n\t}\n\n\tconst again = await p.password({\n\t\tmessage: 'Password again',\n\t\tvalidate: (input) => (input === value ? undefined : 'The two do not match')\n\t});\n\tif (p.isCancel(again)) {\n\t\tp.cancel('Operation cancelled.');\n\t\tprocess.exit(0);\n\t}\n\treturn value;\n}\n", "import { Command } from 'commander';\nimport { helpConfig } from '../lib/help.ts';\nimport { backupCreate } from './backup/create.ts';\nimport { backupList } from './backup/list.ts';\nimport { backupDownload } from './backup/download.ts';\nimport { backupDelete } from './backup/delete.ts';\nimport { backupSchedule } from './backup/schedule.ts';\n\nexport const backup = new Command('backup')\n\t.description('back up the database and uploads, locally or on a target')\n\t.configureHelp(helpConfig)\n\t.addCommand(backupCreate)\n\t.addCommand(backupList)\n\t.addCommand(backupDownload)\n\t.addCommand(backupDelete)\n\t.addCommand(backupSchedule);\n", "import fs from 'node:fs';\nimport path from 'node:path';\nimport { Command } from 'commander';\nimport * as p from '@clack/prompts';\nimport pc from 'picocolors';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand } from '../../lib/run.ts';\nimport { reportResult } from '../../lib/result-report.ts';\nimport { addTargetOptions } from '../../lib/server-command.ts';\nimport { withBackupTarget, type BackupContext } from '../../lib/backup-target.ts';\nimport {\n\tbackupName,\n\tcheckpointAppDatabases,\n\tcreateBackup,\n\tformatBytes,\n\tisBackupKey,\n\tlistBackups,\n\treadStorageSettings\n} from '../../lib/backups.ts';\nimport { remotePaths } from '../../lib/remote.ts';\n\nexport const DEFAULT_BACKUP_DIR = 'backups';\n\nexport const backupCreate = addTargetOptions(\n\tnew Command('create')\n\t\t.description('take a backup of the database and uploads')\n\t\t.argument('[name]', 'name for the archive \u2014 generated when omitted')\n\t\t.option('-o, --output <dir>', 'where to save the archive', DEFAULT_BACKUP_DIR)\n\t\t.option('--no-download', 'leave the archive on the server')\n\t\t.configureHelp(helpConfig),\n\t'production'\n).action((name: string | undefined, raw: unknown) =>\n\trunCommand(() => {\n\t\tconst options = raw as { output: string; download: boolean };\n\t\treturn withBackupTarget(raw, 'backup create', async (ctx) => {\n\t\t\tconst key = name ?? backupName(ctx.instance);\n\t\t\tif (!isBackupKey(key)) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`${pc.cyan(key)} is not a name PocketBase will accept.\\n\\n` +\n\t\t\t\t\t\t`Backup names are lowercase letters, digits, ${pc.cyan('-')} and ${pc.cyan('_')}, ` +\n\t\t\t\t\t\t`ending in ${pc.cyan('.zip')}.`\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconst storage = await readStorageSettings(ctx.pb);\n\t\t\tif (storage.s3Enabled) {\n\t\t\t\tp.log.warn(\n\t\t\t\t\t`Uploads are stored in S3, so this archive holds the database only.\\n\\n` +\n\t\t\t\t\t\t`PocketBase leaves ${pc.cyan('storage/')} out of a backup whenever S3 is on.\\n` +\n\t\t\t\t\t\t`Your bucket's own versioning is what protects the uploaded files.`\n\t\t\t\t);\n\t\t\t}\n\n\t\t\t// PocketBase flushes the write-ahead logs of its own databases before it\n\t\t\t// archives the directory. Anything the app keeps alongside them has to be\n\t\t\t// asked separately, or the archive holds a database and a log that\n\t\t\t// describe different moments.\n\t\t\tif (ctx.session) await checkpointAppDatabases(ctx.session, ctx.instance);\n\n\t\t\tconst spinner = p.spinner();\n\t\t\tspinner.start(`Backing up ${ctx.targetName}`);\n\t\t\ttry {\n\t\t\t\tawait createBackup(ctx.pb, key);\n\t\t\t} catch (error) {\n\t\t\t\tspinner.stop(`Backup of ${ctx.targetName} failed.`);\n\t\t\t\tthrow error;\n\t\t\t}\n\n\t\t\tconst size = (await listBackups(ctx.pb)).find((b) => b.key === key)?.size ?? 0;\n\t\t\tspinner.stop(`Backed up ${ctx.targetName} \u2014 ${key} (${formatBytes(size)})`);\n\n\t\t\tif (storage.backupsS3Enabled) {\n\t\t\t\treportResult({\n\t\t\t\t\tsummary: `Backed up ${ctx.targetName} to your backups bucket.`,\n\t\t\t\t\tnextSteps: [\n\t\t\t\t\t\t`The archive is ${key} in the bucket configured for backups, not on the server.`,\n\t\t\t\t\t\t'Run `vela backup list` to see what is stored there.'\n\t\t\t\t\t]\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (!options.download) {\n\t\t\t\treportResult({\n\t\t\t\t\tsummary: `Backed up ${ctx.targetName}.`,\n\t\t\t\t\tnextSteps: [\n\t\t\t\t\t\t`${key} is on the server, in the directory it is a backup of.`,\n\t\t\t\t\t\t'Run `vela backup download ' + key + '` to keep a copy off the box.'\n\t\t\t\t\t]\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst saved = await download(ctx, key, options.output);\n\t\t\treportResult({\n\t\t\t\tsummary: `Backed up ${ctx.targetName} \u2014 ${formatBytes(size)}.`,\n\t\t\t\tfilesCreated: [saved],\n\t\t\t\tnextSteps: [`Restore it with \\`vela restore ${key}\\`.`]\n\t\t\t});\n\t\t});\n\t}, 'Failed to create the backup.')\n);\n\n/**\n * Bring the archive off the machine it protects.\n *\n * PocketBase writes it into `pb_data/backups`, inside the very directory being\n * backed up, so a backup that is never downloaded survives exactly the failures\n * that do not matter.\n */\nasync function download(ctx: BackupContext, key: string, outputDir: string): Promise<string> {\n\tconst dir = path.resolve(ctx.workspaceRootDir, outputDir);\n\tfs.mkdirSync(dir, { recursive: true });\n\tconst destination = path.join(dir, key);\n\n\tif (!ctx.session) {\n\t\tfs.copyFileSync(path.join(ctx.workspaceRootDir, 'data', 'backups', key), destination);\n\t\treturn path.relative(ctx.workspaceRootDir, destination);\n\t}\n\n\tconst spinner = p.spinner();\n\tspinner.start(`Downloading ${key}`);\n\ttry {\n\t\tawait ctx.session.download(remotePaths.backup(ctx.instance, key), destination);\n\t} catch (error) {\n\t\tspinner.stop(`Could not download ${key}.`);\n\t\tthrow error;\n\t}\n\tspinner.stop(`Downloaded ${key}`);\n\treturn path.relative(ctx.workspaceRootDir, destination);\n}\n", "import type PocketBase from 'pocketbase';\nimport { remotePaths, VELA_USER } from './remote.ts';\nimport type { SshSession } from './ssh.ts';\n\n/**\n * What PocketBase will accept as a backup name.\n *\n * `apis/backup_create.go` matches this exactly and rejects anything else, which\n * rules out the `20260901T134501Z` stamp releases use \u2014 no uppercase.\n */\nconst BACKUP_KEY = /^[a-z0-9_-]+\\.zip$/;\n\n/** PocketBase caps the name at 150; the stamp and affixes take 24 of them. */\nconst MAX_SLUG = 100;\n\nexport interface BackupFile {\n\tkey: string;\n\tsize: number;\n\tmodified: string;\n}\n\nexport interface StorageSettings {\n\t/** Uploads are in a bucket, so a backup archive will not contain them. */\n\ts3Enabled: boolean;\n\t/** Backup archives go to a bucket rather than to `pb_data/backups`. */\n\tbackupsS3Enabled: boolean;\n}\n\nexport function isBackupKey(value: string): boolean {\n\treturn BACKUP_KEY.test(value);\n}\n\n/**\n * Name a backup after the instance it came from.\n *\n * Deterministic on purpose: `createBackup` needs to be able to look the archive\n * up again after a request times out, and it has nothing else to look it up by.\n */\nexport function backupName(instance: string, now: Date = new Date()): string {\n\tconst slug = instance\n\t\t.toLowerCase()\n\t\t.replace(/[^a-z0-9_-]+/g, '-')\n\t\t.replace(/^-+|-+$/g, '')\n\t\t.slice(0, MAX_SLUG);\n\tconst stamp = now.toISOString().replace(/[-:T]/g, '').slice(0, 14);\n\treturn `vela_${slug || 'app'}_${stamp}.zip`;\n}\n\nexport async function readStorageSettings(pb: PocketBase): Promise<StorageSettings> {\n\tconst settings = (await pb.settings.getAll()) as {\n\t\ts3?: { enabled?: boolean };\n\t\tbackups?: { s3?: { enabled?: boolean } };\n\t};\n\treturn {\n\t\ts3Enabled: settings.s3?.enabled === true,\n\t\tbackupsS3Enabled: settings.backups?.s3?.enabled === true\n\t};\n}\n\nexport async function listBackups(pb: PocketBase): Promise<BackupFile[]> {\n\tconst list = await pb.backups.getFullList();\n\treturn [...list].sort((a, b) => b.modified.localeCompare(a.modified));\n}\n\n/**\n * True when a request died because the client gave up waiting, not because the\n * server said no.\n *\n * `POST /api/backups` archives the whole data directory before it answers, and\n * Node's fetch stops waiting for headers after five minutes. On a large\n * instance that fires while PocketBase carries on and finishes successfully, so\n * it has to be told apart from a real failure.\n */\nfunction isClientTimeout(error: unknown): boolean {\n\tfor (let e: unknown = error, depth = 0; e && depth < 5; depth++) {\n\t\tconst cause = e as { code?: string; name?: string; originalError?: unknown; cause?: unknown };\n\t\tif (cause.code === 'UND_ERR_HEADERS_TIMEOUT' || cause.name === 'HeadersTimeoutError')\n\t\t\treturn true;\n\t\te = cause.originalError ?? cause.cause;\n\t}\n\treturn false;\n}\n\nconst POLL_INTERVAL = 5_000;\n\n/**\n * Take a backup, tolerating a request that outlives the client's patience.\n *\n * The name is chosen here rather than by PocketBase so that a timed-out request\n * can be resolved by asking whether the archive turned up \u2014 the alternative is\n * reporting a failure for a backup that actually exists.\n */\nexport async function createBackup(\n\tpb: PocketBase,\n\tkey: string,\n\t{ pollTimeout = 30 * 60_000 }: { pollTimeout?: number } = {}\n): Promise<void> {\n\ttry {\n\t\tawait pb.backups.create(key);\n\t\treturn;\n\t} catch (error) {\n\t\tif (!isClientTimeout(error)) throw error;\n\t}\n\n\tconst deadline = Date.now() + pollTimeout;\n\twhile (Date.now() < deadline) {\n\t\tawait new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL));\n\t\tconst found = await listBackups(pb).catch(() => [] as BackupFile[]);\n\t\tif (found.some((b) => b.key === key)) return;\n\t}\n\n\tthrow new Error(\n\t\t`The backup request timed out and ${key} has not appeared after ` +\n\t\t\t`${Math.round(pollTimeout / 60_000)} minutes.\\n\\n` +\n\t\t\t`PocketBase may still be working on it \u2014 check \\`vela logs\\` and ` +\n\t\t\t`\\`vela backup list\\` before trying again.`\n\t);\n}\n\n/**\n * Fold any app-owned write-ahead log back into the database file it belongs to.\n *\n * PocketBase checkpoints the databases it owns before archiving `pb_data` \u2014 in\n * an archive its `-wal` files are empty. A database the app opened for itself\n * gets no such treatment: its `-wal` is copied as it was found, and a checkpoint\n * landing between the moments the archiver reads the two files leaves the pair\n * describing different instants.\n *\n * Every SQLite file in the directory is offered a checkpoint rather than a list\n * of the ones known to be app-owned: PocketBase's own are already flushed, so\n * the redundant work is one no-op each, and a guessed list is a list that goes\n * stale the first time a build adds a database to `pb_data`.\n *\n * Two things are deliberate. It runs as the app user, because a checkpoint run\n * as root recreates `-wal` and `-shm` owned by root and the app can no longer\n * write to its own database afterwards. And every step is best-effort: a\n * database busy enough to refuse is a database whose backup is slightly less\n * consistent, which is not worth failing the backup over.\n *\n * Remote only. Locally PocketBase and the app share a directory that no deploy\n * moves, `sqlite3` is not guaranteed to be installed, and a backup of a\n * development database is a convenience rather than a promise.\n */\nexport async function checkpointAppDatabases(session: SshSession, instance: string): Promise<void> {\n\tawait session.script(\n\t\t`command -v sqlite3 >/dev/null 2>&1 || exit 0\n\t\tfor db in \"$1\"/*.db \"$1\"/*.sqlite; do\n\t\t\t[ -f \"$db-wal\" ] || continue\n\t\t\trunuser -u \"$2\" -- sqlite3 \"$db\" \\\n\t\t\t\t'PRAGMA busy_timeout=5000; PRAGMA wal_checkpoint(TRUNCATE);' >/dev/null 2>&1 || true\n\t\tdone`,\n\t\t{ args: [remotePaths.pbData(instance), VELA_USER], check: false }\n\t);\n}\n\nexport function formatBytes(bytes: number): string {\n\tconst units = ['B', 'KB', 'MB', 'GB', 'TB'];\n\tlet value = bytes;\n\tlet unit = 0;\n\twhile (value >= 1024 && unit < units.length - 1) {\n\t\tvalue /= 1024;\n\t\tunit += 1;\n\t}\n\treturn `${value < 10 && unit > 0 ? value.toFixed(1) : Math.round(value)} ${units[unit]}`;\n}\n\nexport interface BackupSchedule {\n\t/** Empty when no automatic backup is scheduled. */\n\tcron: string;\n\t/** How many cron-generated archives PocketBase keeps. */\n\tmaxKeep: number;\n}\n\nexport async function readSchedule(pb: PocketBase): Promise<BackupSchedule> {\n\tconst settings = (await pb.settings.getAll()) as {\n\t\tbackups?: { cron?: string; cronMaxKeep?: number };\n\t};\n\treturn {\n\t\tcron: settings.backups?.cron ?? '',\n\t\tmaxKeep: settings.backups?.cronMaxKeep ?? 0\n\t};\n}\n\n/**\n * Set or clear the automatic backup schedule.\n *\n * PocketBase runs the cron itself, in the same process that serves the app, so\n * there is nothing to install on the server. `cronMaxKeep` is required and must\n * be at least 1 whenever a schedule is set, and it prunes only the archives the\n * cron made \u2014 anything from `vela backup create` is left alone.\n *\n * Only these two keys are sent: settings are merged, so an S3 backups bucket\n * configured alongside them survives untouched.\n */\nexport async function writeSchedule(pb: PocketBase, cron: string, maxKeep: number): Promise<void> {\n\tawait pb.settings.update({ backups: { cron, cronMaxKeep: cron ? maxKeep : 0 } });\n}\n", "import { Command } from 'commander';\nimport * as p from '@clack/prompts';\nimport pc from 'picocolors';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand } from '../../lib/run.ts';\nimport { addTargetOptions } from '../../lib/server-command.ts';\nimport { withBackupTarget } from '../../lib/backup-target.ts';\nimport { formatBytes, listBackups } from '../../lib/backups.ts';\n\nexport const backupList = addTargetOptions(\n\tnew Command('list').description('list the backups on a target').configureHelp(helpConfig),\n\t'production'\n).action((raw: unknown) =>\n\trunCommand(\n\t\t() =>\n\t\t\twithBackupTarget(raw, 'backup list', async (ctx) => {\n\t\t\t\tconst backups = await listBackups(ctx.pb);\n\t\t\t\tif (backups.length === 0) {\n\t\t\t\t\tp.log.info(\n\t\t\t\t\t\t`${pc.cyan(ctx.targetName)} has no backups yet.\\n\\n` +\n\t\t\t\t\t\t\t`Take one with ${pc.cyan('vela backup create')}.`\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconst width = Math.max(...backups.map((b) => b.key.length));\n\t\t\t\tp.log.message(\n\t\t\t\t\tbackups\n\t\t\t\t\t\t.map(\n\t\t\t\t\t\t\t(b) =>\n\t\t\t\t\t\t\t\t`${b.key.padEnd(width)} ${pc.dim(formatBytes(b.size).padStart(8))} ${pc.dim(b.modified)}`\n\t\t\t\t\t\t)\n\t\t\t\t\t\t.join('\\n')\n\t\t\t\t);\n\t\t\t}),\n\t\t'Failed to list backups.'\n\t)\n);\n", "import fs from 'node:fs';\nimport path from 'node:path';\nimport { Command } from 'commander';\nimport * as p from '@clack/prompts';\nimport pc from 'picocolors';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand } from '../../lib/run.ts';\nimport { reportResult } from '../../lib/result-report.ts';\nimport { addTargetOptions } from '../../lib/server-command.ts';\nimport { withBackupTarget } from '../../lib/backup-target.ts';\nimport { formatBytes, listBackups, readStorageSettings } from '../../lib/backups.ts';\nimport { remotePaths } from '../../lib/remote.ts';\nimport { DEFAULT_BACKUP_DIR } from './create.ts';\n\nexport const backupDownload = addTargetOptions(\n\tnew Command('download')\n\t\t.description('save a backup off the server')\n\t\t.argument('<key>', 'archive to download, as shown by `vela backup list`')\n\t\t.option('-o, --output <dir>', 'where to save the archive', DEFAULT_BACKUP_DIR)\n\t\t.configureHelp(helpConfig),\n\t'production'\n).action((key: string, raw: unknown) =>\n\trunCommand(() => {\n\t\tconst options = raw as { output: string };\n\t\treturn withBackupTarget(raw, 'backup download', async (ctx) => {\n\t\t\tconst found = (await listBackups(ctx.pb)).find((b) => b.key === key);\n\t\t\tif (!found) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`${ctx.targetName} has no backup called ${pc.cyan(key)}.\\n\\n` +\n\t\t\t\t\t\t`Run ${pc.cyan('vela backup list')} to see what it does have.`\n\t\t\t\t);\n\t\t\t}\n\n\t\t\t// With a backups bucket configured the archive was never written to the\n\t\t\t// server's disk, so there is nothing here to rsync.\n\t\t\tconst storage = await readStorageSettings(ctx.pb);\n\t\t\tif (storage.backupsS3Enabled) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`${key} is in the bucket configured for backups, not on the server.\\n\\n` +\n\t\t\t\t\t\t`Fetch it from the bucket directly \u2014 vela does not hold its credentials.`\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconst dir = path.resolve(ctx.workspaceRootDir, options.output);\n\t\t\tfs.mkdirSync(dir, { recursive: true });\n\t\t\tconst destination = path.join(dir, key);\n\n\t\t\tif (!ctx.session) {\n\t\t\t\tfs.copyFileSync(path.join(ctx.workspaceRootDir, 'data', 'backups', key), destination);\n\t\t\t} else {\n\t\t\t\tconst spinner = p.spinner();\n\t\t\t\tspinner.start(`Downloading ${key} (${formatBytes(found.size)})`);\n\t\t\t\ttry {\n\t\t\t\t\tawait ctx.session.download(remotePaths.backup(ctx.instance, key), destination);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tspinner.stop(`Could not download ${key}.`);\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t\tspinner.stop(`Downloaded ${key}`);\n\t\t\t}\n\n\t\t\treportResult({\n\t\t\t\tsummary: `Saved ${key} from ${ctx.targetName}.`,\n\t\t\t\tfilesCreated: [path.relative(ctx.workspaceRootDir, destination)]\n\t\t\t});\n\t\t});\n\t}, 'Failed to download the backup.')\n);\n", "import process from 'node:process';\nimport { Command } from 'commander';\nimport * as p from '@clack/prompts';\nimport pc from 'picocolors';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand } from '../../lib/run.ts';\nimport { reportResult } from '../../lib/result-report.ts';\nimport { addTargetOptions } from '../../lib/server-command.ts';\nimport { withBackupTarget } from '../../lib/backup-target.ts';\nimport { formatBytes, listBackups } from '../../lib/backups.ts';\n\nexport const backupDelete = addTargetOptions(\n\tnew Command('delete')\n\t\t.description('remove a backup from a target')\n\t\t.argument('<key>', 'archive to delete, as shown by `vela backup list`')\n\t\t.option('-y, --yes', 'skip the confirmation')\n\t\t.configureHelp(helpConfig),\n\t'production'\n).action((key: string, raw: unknown) =>\n\trunCommand(() => {\n\t\tconst options = raw as { yes?: boolean };\n\t\treturn withBackupTarget(raw, 'backup delete', async (ctx) => {\n\t\t\tconst found = (await listBackups(ctx.pb)).find((b) => b.key === key);\n\t\t\tif (!found) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`${ctx.targetName} has no backup called ${pc.cyan(key)}.\\n\\n` +\n\t\t\t\t\t\t`Run ${pc.cyan('vela backup list')} to see what it does have.`\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tif (!options.yes) {\n\t\t\t\tconst confirmed = await p.confirm({\n\t\t\t\t\tmessage: `Delete ${key} (${formatBytes(found.size)}) from ${ctx.targetName}?`,\n\t\t\t\t\tinitialValue: false\n\t\t\t\t});\n\t\t\t\tif (p.isCancel(confirmed) || !confirmed) {\n\t\t\t\t\tp.cancel('Operation cancelled.');\n\t\t\t\t\tprocess.exit(0);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tawait ctx.pb.backups.delete(key);\n\t\t\treportResult({ summary: `Deleted ${key} from ${ctx.targetName}.` });\n\t\t});\n\t}, 'Failed to delete the backup.')\n);\n", "import { Command } from 'commander';\nimport * as p from '@clack/prompts';\nimport pc from 'picocolors';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand } from '../../lib/run.ts';\nimport { reportResult } from '../../lib/result-report.ts';\nimport { addTargetOptions } from '../../lib/server-command.ts';\nimport { withBackupTarget } from '../../lib/backup-target.ts';\nimport { readSchedule, readStorageSettings, writeSchedule } from '../../lib/backups.ts';\n\nconst DEFAULT_KEEP = 7;\n\nexport const backupSchedule = addTargetOptions(\n\tnew Command('schedule')\n\t\t.description('back up automatically on a schedule')\n\t\t.argument('[cron]', 'when to run, as a cron expression \u2014 shows the current one when omitted')\n\t\t.option('--keep <n>', 'how many scheduled archives to keep', String(DEFAULT_KEEP))\n\t\t.option('--off', 'stop backing up automatically')\n\t\t.configureHelp(helpConfig),\n\t'production'\n).action((cron: string | undefined, raw: unknown) =>\n\trunCommand(() => {\n\t\tconst options = raw as { keep: string; off?: boolean };\n\t\treturn withBackupTarget(raw, 'backup schedule', async (ctx) => {\n\t\t\tif (options.off) {\n\t\t\t\tawait writeSchedule(ctx.pb, '', 0);\n\t\t\t\treportResult({ summary: `${ctx.targetName} no longer backs up automatically.` });\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (!cron) {\n\t\t\t\tconst current = await readSchedule(ctx.pb);\n\t\t\t\tp.log.info(\n\t\t\t\t\tcurrent.cron\n\t\t\t\t\t\t? `${ctx.targetName} backs up on ${pc.cyan(current.cron)}, keeping ${current.maxKeep}.`\n\t\t\t\t\t\t: `${ctx.targetName} has no backup schedule.\\n\\n` +\n\t\t\t\t\t\t\t\t`Set one with ${pc.cyan('vela backup schedule \"0 3 * * *\"')}.`\n\t\t\t\t);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst keep = Number.parseInt(options.keep, 10);\n\t\t\tif (!Number.isInteger(keep) || keep < 1) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`${pc.cyan(options.keep)} is not a number of backups to keep \u2014 pass at least 1.`\n\t\t\t\t);\n\t\t\t}\n\n\t\t\t// PocketBase validates the expression itself, and its message names the\n\t\t\t// part that is wrong, which is more use than anything guessed here.\n\t\t\tawait writeSchedule(ctx.pb, cron, keep);\n\n\t\t\tconst storage = await readStorageSettings(ctx.pb);\n\t\t\treportResult({\n\t\t\t\tsummary: `${ctx.targetName} now backs up on ${cron}, keeping ${keep}.`,\n\t\t\t\tnextSteps: [\n\t\t\t\t\t...(storage.backupsS3Enabled\n\t\t\t\t\t\t? ['Archives go to the bucket configured for backups.']\n\t\t\t\t\t\t: [\n\t\t\t\t\t\t\t\t'Archives are written to the server, on the same disk as the data they protect.',\n\t\t\t\t\t\t\t\t'Run `vela enable s3 --backups` to send them somewhere else.'\n\t\t\t\t\t\t\t]),\n\t\t\t\t\t...(storage.s3Enabled\n\t\t\t\t\t\t? ['Uploads live in S3, so these archives hold the database only.']\n\t\t\t\t\t\t: []),\n\t\t\t\t\t'`--keep` prunes only scheduled archives; ones from `vela backup create` are left alone.'\n\t\t\t\t]\n\t\t\t});\n\t\t});\n\t}, 'Failed to set the backup schedule.')\n);\n", "import fs from 'node:fs';\nimport path from 'node:path';\nimport process from 'node:process';\nimport { Command } from 'commander';\nimport * as p from '@clack/prompts';\nimport pc from 'picocolors';\nimport { helpConfig } from '../lib/help.ts';\nimport { runCommand } from '../lib/run.ts';\nimport { addTargetOptions, withTarget, type ServerContext } from '../lib/server-command.ts';\nimport { withRemotePocketbase } from '../lib/remote-pocketbase.ts';\nimport { readInstanceStates, remotePaths, runServerScript } from '../lib/remote.ts';\nimport { formatBytes, isBackupKey, listBackups, type BackupFile } from '../lib/backups.ts';\nimport { isProd } from '../lib/instance.ts';\n\ninterface RestoreResult {\n\tpreviousDataDir: string;\n\tstorageCarriedOver: boolean;\n\tmigrated: boolean;\n}\n\nexport const restore = addTargetOptions(\n\tnew Command('restore')\n\t\t.description('replace a deployment\u2019s database and uploads from a backup')\n\t\t.argument('[source]', 'a backup key on the target, or a path to a local archive')\n\t\t.configureHelp(helpConfig),\n\t'production'\n)\n\t.option('-y, --yes', 'skip the confirmation prompt')\n\t.option('--no-migrate', 'do not run migrations against the restored database')\n\t.option('--keep-previous <n>', 'how many replaced databases to keep', '1')\n\t.action((source: string | undefined, raw: unknown) =>\n\t\trunCommand(async () => {\n\t\t\tconst options = raw as { yes?: boolean; migrate: boolean; keepPrevious: string };\n\t\t\tawait withTarget(\n\t\t\t\traw,\n\t\t\t\t{\n\t\t\t\t\tremote: async (ctx) => {\n\t\t\t\t\t\tconst [state] = await readInstanceStates(ctx.session, ctx.instance);\n\t\t\t\t\t\tif (state && state.backend === false) {\n\t\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t\t`${ctx.targetName} was deployed without a database, so there is nothing to restore.`\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst local = source && fs.existsSync(source) ? source : undefined;\n\t\t\t\t\t\tconst key = local ? undefined : await resolveKey(ctx, source);\n\n\t\t\t\t\t\tif (!options.yes) {\n\t\t\t\t\t\t\tawait confirm(ctx.appName, ctx.targetName, ctx.envTag, local ?? key!);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst archive = local\n\t\t\t\t\t\t\t? await stage(ctx, local)\n\t\t\t\t\t\t\t: remotePaths.backup(ctx.instance, key!);\n\n\t\t\t\t\t\tconst result = await runServerScript<RestoreResult>(ctx.session, 'restore.sh', {\n\t\t\t\t\t\t\targs: [\n\t\t\t\t\t\t\t\tctx.instance,\n\t\t\t\t\t\t\t\t'--archive',\n\t\t\t\t\t\t\t\tarchive,\n\t\t\t\t\t\t\t\t'--keep-previous',\n\t\t\t\t\t\t\t\toptions.keepPrevious,\n\t\t\t\t\t\t\t\t...(options.migrate ? [] : ['--no-migrate']),\n\t\t\t\t\t\t\t\t// A copy this machine pushed up is scratch; one already in the\n\t\t\t\t\t\t\t\t// instance's own backups directory is not ours to delete.\n\t\t\t\t\t\t\t\t...(local ? ['--cleanup-archive'] : [])\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\tstream: true\n\t\t\t\t\t\t});\n\n\t\t\t\t\t\tp.log.success(\n\t\t\t\t\t\t\t`Restored ${pc.cyan(`${ctx.appName} (${ctx.targetName})`)} from ${pc.cyan(\n\t\t\t\t\t\t\t\tlocal ? path.basename(local) : key!\n\t\t\t\t\t\t\t)}.`\n\t\t\t\t\t\t);\n\n\t\t\t\t\t\tif (result?.storageCarriedOver) {\n\t\t\t\t\t\t\tp.log.info(\n\t\t\t\t\t\t\t\t'The archive held no uploads, so the files already on the server were kept.'\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (result?.previousDataDir) {\n\t\t\t\t\t\t\tp.log.info(\n\t\t\t\t\t\t\t\t`The database this replaced is at ${pc.cyan(result.previousDataDir)}.\\n\\n` +\n\t\t\t\t\t\t\t\t\t`It is the only way back. Remove it once you are satisfied with the restore.`\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tlabel: 'restore',\n\t\t\t\t\tlocalHint:\n\t\t\t\t\t\t'Restoring the local database is not supported yet \u2014 recreate it with `vela migrate up` and `vela seeds load`.'\n\t\t\t\t}\n\t\t\t);\n\t\t}, 'Failed to restore the backup.')\n\t);\n\n/** Work out which archive on the target to restore, asking when not told. */\nasync function resolveKey(ctx: ServerContext, source: string | undefined): Promise<string> {\n\tif (source && !isBackupKey(source)) {\n\t\tthrow new Error(\n\t\t\t`${pc.cyan(source)} is neither a file on this machine nor a backup key.\\n\\n` +\n\t\t\t\t`Run ${pc.cyan('vela backup list')} to see what ${ctx.targetName} has.`\n\t\t);\n\t}\n\n\tconst backups = await withRemotePocketbase(ctx.session, ctx.instance, listBackups);\n\tif (source) {\n\t\tif (!backups.some((b) => b.key === source)) {\n\t\t\tthrow new Error(\n\t\t\t\t`${ctx.targetName} has no backup called ${pc.cyan(source)}.\\n\\n` +\n\t\t\t\t\t`Run ${pc.cyan('vela backup list')} to see what it does have.`\n\t\t\t);\n\t\t}\n\t\treturn source;\n\t}\n\n\tif (backups.length === 0) {\n\t\tthrow new Error(\n\t\t\t`${ctx.targetName} has no backups to restore from.\\n\\n` +\n\t\t\t\t`Take one with ${pc.cyan('vela backup create')}, or pass the path to an archive on this machine.`\n\t\t);\n\t}\n\n\tconst chosen = await p.select({\n\t\tmessage: `Which backup should ${ctx.targetName} be restored from?`,\n\t\toptions: backups.map((b: BackupFile) => ({\n\t\t\tvalue: b.key,\n\t\t\tlabel: b.key,\n\t\t\thint: `${formatBytes(b.size)}, ${b.modified}`\n\t\t}))\n\t});\n\tif (p.isCancel(chosen)) {\n\t\tp.cancel('Operation cancelled.');\n\t\tprocess.exit(0);\n\t}\n\treturn chosen;\n}\n\n/**\n * Put a local archive somewhere the server can unpack it.\n *\n * Deliberately not `pb_data/backups`: that directory is moved aside during the\n * restore, so an archive placed there would disappear halfway through reading it.\n */\nasync function stage(ctx: ServerContext, file: string): Promise<string> {\n\tconst dir = remotePaths.restoreStage(ctx.instance);\n\tconst remote = `${dir}/${path.basename(file)}`;\n\n\tconst spinner = p.spinner();\n\tspinner.start(`Uploading ${path.basename(file)}`);\n\ttry {\n\t\tawait ctx.session.script(`mkdir -p \"$1\"`, { args: [dir] });\n\t\tawait ctx.session.upload([file], dir);\n\t} catch (error) {\n\t\tspinner.stop(`Could not upload ${path.basename(file)}.`);\n\t\tthrow error;\n\t}\n\tspinner.stop(`Uploaded ${path.basename(file)}`);\n\treturn remote;\n}\n\nasync function confirm(\n\tappName: string,\n\ttargetName: string,\n\tenvTag: string,\n\tfrom: string\n): Promise<void> {\n\tconst what = `${pc.cyan(`${appName} (${targetName})`)} from ${pc.cyan(path.basename(from))}`;\n\n\t// A restore overwrites a live database. On production that deserves the same\n\t// deliberate typing that destroying it does.\n\tif (isProd(envTag)) {\n\t\tconst answer = await p.text({\n\t\t\tmessage: `This replaces the database and uploads of ${what}. Type the app name to confirm`,\n\t\t\tvalidate: (value) => (value === appName ? undefined : `Type ${appName} to confirm`)\n\t\t});\n\t\tif (p.isCancel(answer)) {\n\t\t\tp.cancel('Operation cancelled.');\n\t\t\tprocess.exit(0);\n\t\t}\n\t\treturn;\n\t}\n\n\tconst ok = await p.confirm({\n\t\tmessage: `Replace the database and uploads of ${what}?`,\n\t\tinitialValue: false\n\t});\n\tif (p.isCancel(ok) || !ok) {\n\t\tp.cancel('Operation cancelled.');\n\t\tprocess.exit(0);\n\t}\n}\n", "import { Command } from 'commander';\nimport * as p from '@clack/prompts';\nimport pc from 'picocolors';\nimport { helpConfig } from '../lib/help.ts';\nimport { runCommand } from '../lib/run.ts';\nimport { getWorkspace } from './../lib/workspace.ts';\nimport { loadDeployConfig, readAppIdentity, readBindings } from '../lib/deploy-config.ts';\nimport { instanceId } from '../lib/instance.ts';\nimport { addSshOptions, sshOptionsFrom, SSH_OPTION_SCHEMA } from '../lib/ssh-options.ts';\nimport { parseOptions } from '../lib/options.ts';\nimport { withSsh } from '../lib/ssh.ts';\nimport { readInstanceStates } from '../lib/remote.ts';\nimport { getPocketbaseMetadata } from '../lib/pocketbase.ts';\nimport * as v from 'valibot';\n\nconst OptionsSchema = v.object({\n\t...SSH_OPTION_SCHEMA,\n\tjson: v.optional(v.boolean()),\n\toffline: v.optional(v.boolean())\n});\n\ninterface Row {\n\ttarget: string;\n\tkind: 'local' | 'remote';\n\tserver: string;\n\tdomain: string;\n\trelease: string;\n\treachable: boolean;\n}\n\nexport const targets = addSshOptions(\n\tnew Command('targets')\n\t\t.description('list the targets this project can deploy to')\n\t\t.configureHelp(helpConfig)\n)\n\t.option('--json', 'print raw JSON')\n\t.option('--offline', 'skip connecting to servers')\n\t.action((raw: unknown) =>\n\t\trunCommand(async () => {\n\t\t\tconst options = parseOptions(OptionsSchema, raw);\n\t\t\tconst { workspaceRootDir } = await getWorkspace();\n\t\t\tconst config = await loadDeployConfig(workspaceRootDir);\n\t\t\t// Listing must never mint an app id \u2014 that is a side effect nobody asks\n\t\t\t// for by running `vela targets`.\n\t\t\tconst app = readAppIdentity(workspaceRootDir, config);\n\t\t\tconst bindings = readBindings(workspaceRootDir);\n\n\t\t\tconst metadata = getPocketbaseMetadata(workspaceRootDir);\n\t\t\tconst rows: Row[] = [\n\t\t\t\t{\n\t\t\t\t\ttarget: 'local',\n\t\t\t\t\tkind: 'local',\n\t\t\t\t\tserver: '\u2014',\n\t\t\t\t\tdomain: metadata ? `http://${metadata.viteHost}:${metadata.vitePort}` : '\u2014',\n\t\t\t\t\trelease: '\u2014',\n\t\t\t\t\treachable: true\n\t\t\t\t}\n\t\t\t];\n\n\t\t\t// One connection per machine, not per target: a server usually hosts\n\t\t\t// several of this project's targets, and asking it once is enough.\n\t\t\tconst byServer = new Map<string, string[]>();\n\t\t\tfor (const [envTag, binding] of Object.entries(bindings)) {\n\t\t\t\tbyServer.set(binding.server, [...(byServer.get(binding.server) ?? []), envTag]);\n\t\t\t}\n\n\t\t\tfor (const [server, envTags] of byServer) {\n\t\t\t\tlet states: Awaited<ReturnType<typeof readInstanceStates>> = [];\n\t\t\t\tlet reachable = false;\n\n\t\t\t\tif (!options.offline && app) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait withSsh(server, sshOptionsFrom(options), async (session) => {\n\t\t\t\t\t\t\tawait session.detectElevation();\n\t\t\t\t\t\t\tstates = await readInstanceStates(session);\n\t\t\t\t\t\t});\n\t\t\t\t\t\treachable = true;\n\t\t\t\t\t} catch {\n\t\t\t\t\t\t// One unreachable box must not empty the whole table.\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tfor (const envTag of envTags) {\n\t\t\t\t\tconst binding = bindings[envTag]!;\n\t\t\t\t\tconst instance = app ? instanceId(app.appId, envTag) : '';\n\t\t\t\t\tconst state = states.find((candidate) => candidate.instance === instance);\n\t\t\t\t\trows.push({\n\t\t\t\t\t\ttarget: envTag,\n\t\t\t\t\t\tkind: 'remote',\n\t\t\t\t\t\tserver,\n\t\t\t\t\t\tdomain: state?.domain || binding.domain || '\u2014',\n\t\t\t\t\t\trelease: state?.activeRelease ?? (reachable ? 'not deployed' : '\u2014'),\n\t\t\t\t\t\treachable\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (options.json) {\n\t\t\t\tconsole.log(JSON.stringify(rows, null, 2));\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\treport(rows, options.offline === true);\n\t\t}, 'Failed to list targets.')\n\t);\n\nfunction report(rows: Row[], offline: boolean): void {\n\t// The header is part of the column, or a short value leaves it hanging over\n\t// the rows beneath it.\n\tconst width = (heading: string, pick: (row: Row) => string) =>\n\t\tMath.max(heading.length, ...rows.map((row) => pick(row).length));\n\tconst target = width('TARGET', (row) => row.target);\n\tconst server = width('SERVER', (row) => row.server);\n\tconst domain = width('DOMAIN', (row) => row.domain);\n\n\tconst header = `${'TARGET'.padEnd(target)} ${'SERVER'.padEnd(server)} ${'DOMAIN'.padEnd(domain)} RELEASE`;\n\tconst lines = rows.map(\n\t\t(row) =>\n\t\t\t`${row.kind === 'local' ? pc.dim(row.target.padEnd(target)) : pc.cyan(row.target.padEnd(target))} ` +\n\t\t\t`${row.server.padEnd(server)} ${row.domain.padEnd(domain)} ${row.release}`\n\t);\n\n\tp.log.info(`${pc.dim(header)}\\n${lines.join('\\n')}`);\n\n\tconst unreachable = rows.filter((row) => row.kind === 'remote' && !row.reachable);\n\tif (!offline && unreachable.length > 0) {\n\t\tp.log.warn(\n\t\t\t`Could not reach ${unreachable.map((row) => row.server).join(', ')}.\\n` +\n\t\t\t\t`Release and domain are shown from what this project recorded.`\n\t\t);\n\t}\n}\n", "import path from 'node:path';\nimport process from 'node:process';\nimport { Command } from 'commander';\nimport PocketBase from 'pocketbase';\nimport pc from 'picocolors';\nimport { x } from 'tinyexec';\nimport { detect } from 'package-manager-detector';\nimport { resolveCommand } from 'package-manager-detector/commands';\nimport fs from 'node:fs';\nimport { helpConfig } from '../lib/help.ts';\nimport { authWithRetries, findFreePort, launchPocketbase } from '../lib/pocketbase.ts';\nimport { DATA_DIR } from '../lib/constants.ts';\nimport { loadVite } from '../lib/vite.ts';\nimport type { Plugin } from 'vite';\n\nexport const testServer = new Command('test:server')\n\t.description('run server tests')\n\t.allowUnknownOption(true)\n\t.allowExcessArguments(true)\n\t.configureHelp(helpConfig)\n\t.action(async (_opts, cmd) => {\n\t\tconst cwd = process.cwd();\n\t\tconst email = `test-${Math.random().toString(36).slice(2)}@example.com`;\n\t\tconst password = 'password';\n\n\t\tconst testDataDir = path.join(cwd, 'test-data');\n\t\tfs.rmSync(testDataDir, { recursive: true, force: true });\n\n\t\tconst { stop, url } = await launchPocketbase(cwd, {\n\t\t\tdir: testDataDir,\n\t\t\tmigrationsDir: path.join(cwd, 'migrations'),\n\t\t\t// The app's PocketBase hooks (slug generation, personal teams, \u2026) are part\n\t\t\t// of its behaviour; the suite runs against the same server dev and build\n\t\t\t// start, so it loads them from the same place.\n\t\t\thooksDir: path.join(cwd, DATA_DIR, 'hooks'),\n\t\t\temail,\n\t\t\tpassword\n\t\t});\n\n\t\tprocess.env.POCKETBASE_URL = url;\n\t\tprocess.env.POCKETBASE_SUPERUSER_EMAIL = email;\n\t\tprocess.env.POCKETBASE_SUPERUSER_PASSWORD = password;\n\t\t// The app's data directory is PocketBase's, here as everywhere else. It\n\t\t// points at the throwaway one so that a database or an uploaded file the\n\t\t// suite creates is removed with it, rather than accumulating in the\n\t\t// directory the developer actually works against.\n\t\tprocess.env.VELA_DATA_DIR = testDataDir;\n\t\tprocess.env.TEST = 'true';\n\n\t\tconsole.log(`${pc.greenBright('\u2713')} Created test database`);\n\n\t\tconst { createServer } = await loadVite(cwd);\n\t\tconst vite = await createServer({\n\t\t\tmode: 'test',\n\t\t\tplugins: [stubPagesPlugin()],\n\t\t\toptimizeDeps: { noDiscovery: true }\n\t\t});\n\t\tconst vitePort = await findFreePort();\n\t\tawait vite.listen(vitePort);\n\t\tprocess.env.VITE_TEST_URL = `http://localhost:${vitePort}`;\n\n\t\tconsole.log(`${pc.greenBright('\u2713')} Started Vite: http://localhost:${vitePort}`);\n\t\tconsole.log(`${pc.greenBright('\u2713')} Started PocketBase: ${url}`);\n\n\t\tconst cleanup = async () => {\n\t\t\tstop();\n\t\t\tawait vite.close();\n\t\t\tfs.rmSync(testDataDir, { recursive: true, force: true });\n\t\t};\n\n\t\tconst pb = new PocketBase(url);\n\t\ttry {\n\t\t\tawait authWithRetries(pb, email, password);\n\t\t} catch (e) {\n\t\t\tawait cleanup();\n\t\t\tconsole.error(`${pc.redBright('\u2717')} Auth failed: ${(e as Error).message}`);\n\t\t\tprocess.exit(1);\n\t\t}\n\n\t\tconst extraArgs: string[] = (cmd.parent?.args ?? []).slice(1);\n\t\tlet filter = extraArgs.find((arg: string) => !arg.startsWith('-'));\n\t\tconst passthrough = filter ? extraArgs.filter((a: string) => a !== filter) : extraArgs;\n\t\tif (!filter) filter = 'server';\n\n\t\ttry {\n\t\t\tconst pm = (await detect({ cwd }))?.name ?? 'npm';\n\t\t\tconst resolved = resolveCommand(pm, 'execute', [\n\t\t\t\t'vitest',\n\t\t\t\t'run',\n\t\t\t\tfilter,\n\t\t\t\t'--reporter=dot',\n\t\t\t\t...passthrough\n\t\t\t])!;\n\t\t\tconst resolvedArgs = resolved.args.slice();\n\t\t\tif (pm === 'npm') resolvedArgs.unshift('--yes');\n\t\t\tawait x(resolved.command, resolvedArgs, {\n\t\t\t\tnodeOptions: { cwd, stdio: 'inherit', env: { ...process.env, CI: '1' } },\n\t\t\t\tthrowOnError: true\n\t\t\t});\n\t\t} catch {\n\t\t\t// vitest exit codes propagate up via exitCode\n\t\t} finally {\n\t\t\tawait cleanup();\n\t\t}\n\t});\n\nfunction stubPagesPlugin(): Plugin {\n\tconst stub = `<script>export const render = () => '';</script>`;\n\treturn {\n\t\tname: 'stub-pages',\n\t\tresolveId(id: string) {\n\t\t\tif (id.endsWith('+page.svelte')) return id;\n\t\t\treturn undefined;\n\t\t},\n\t\tload(id: string) {\n\t\t\tif (\n\t\t\t\tid.endsWith('+page.svelte') ||\n\t\t\t\tid.endsWith('+layout.svelte') ||\n\t\t\t\tid.endsWith('+error.svelte')\n\t\t\t) {\n\t\t\t\treturn stub;\n\t\t\t}\n\t\t\treturn undefined;\n\t\t}\n\t};\n}\n", "import fs from 'node:fs';\nimport path from 'node:path';\nimport process from 'node:process';\nimport { Command } from 'commander';\nimport { helpConfig } from '../lib/help.ts';\nimport { getWorkspace } from '../lib/workspace.ts';\n\ninterface Route {\n\tid: string;\n\turlPattern: string;\n\tmethods: string[];\n}\n\nconst HTTP_METHODS = new Set([\n\t'GET',\n\t'POST',\n\t'PUT',\n\t'PATCH',\n\t'DELETE',\n\t'OPTIONS',\n\t'HEAD',\n\t'fallback'\n]);\n\nexport const routes = new Command('routes')\n\t.description('list routes')\n\t.configureHelp(helpConfig)\n\t.action(async () => {\n\t\tconst { workspaceRootDir, routesDir } = await getWorkspace();\n\t\tconst routesRoot = path.join(workspaceRootDir, routesDir);\n\t\tconst found = walk(routesRoot, routesRoot).filter((r) => r.methods.length > 0);\n\t\tfound.sort((a, b) => a.urlPattern.localeCompare(b.urlPattern));\n\t\tprintTable(found);\n\t});\n\nfunction walk(root: string, dir: string): Route[] {\n\tconst entries = fs.readdirSync(dir, { withFileTypes: true });\n\tconst routes: Route[] = [];\n\n\tconst hasLeaf = entries.some((e) => e.isFile() && isRouteFile(e.name));\n\tif (hasLeaf) {\n\t\tconst id = '/' + path.relative(root, dir).split(path.sep).filter(Boolean).join('/');\n\t\tconst urlPattern = id.replace(/\\([^)]+\\)\\/?/g, '').replace(/\\/$/, '') || '/';\n\t\tconst methods = new Set<string>();\n\t\tfor (const entry of entries) {\n\t\t\tif (!entry.isFile()) continue;\n\t\t\tif (entry.name.endsWith('+page.svelte')) methods.add('GET');\n\t\t\tif (\n\t\t\t\tentry.name.endsWith('+server.ts') ||\n\t\t\t\tentry.name.endsWith('+server.js') ||\n\t\t\t\tentry.name.endsWith('+page.server.ts') ||\n\t\t\t\tentry.name.endsWith('+page.server.js')\n\t\t\t) {\n\t\t\t\textractMethods(path.join(dir, entry.name)).forEach((m) => methods.add(m));\n\t\t\t}\n\t\t}\n\t\troutes.push({ id: id || '/', urlPattern, methods: [...methods] });\n\t}\n\n\tfor (const entry of entries) {\n\t\tif (entry.isDirectory()) routes.push(...walk(root, path.join(dir, entry.name)));\n\t}\n\treturn routes;\n}\n\nfunction isRouteFile(name: string): boolean {\n\treturn (\n\t\tname.startsWith('+page.') || name.startsWith('+server.') || name.startsWith('+layout.server.')\n\t);\n}\n\nfunction extractMethods(file: string): string[] {\n\ttry {\n\t\tconst content = fs.readFileSync(file, 'utf8');\n\t\tconst methods: string[] = [];\n\t\tconst exportRegex = /export\\s+(?:const|async\\s+function|function)\\s+(\\w+)/g;\n\t\tlet match: RegExpExecArray | null;\n\t\twhile ((match = exportRegex.exec(content)) !== null) {\n\t\t\tconst name = match[1]!;\n\t\t\tif (HTTP_METHODS.has(name)) methods.push(name);\n\t\t\tif (name === 'actions') methods.push('POST');\n\t\t}\n\t\treturn methods;\n\t} catch {\n\t\treturn [];\n\t}\n}\n\nfunction printTable(routes: Route[]): void {\n\tif (routes.length === 0) {\n\t\tconsole.log('No routes found.');\n\t\treturn;\n\t}\n\tconst urlWidth = Math.max(...routes.map((r) => r.urlPattern.length), 3) + 2;\n\tconst methodsWidth = 30;\n\tconst idWidth = Math.max(...routes.map((r) => r.id.length), 2) + 2;\n\n\tconst line = (a: string, b: string, c: string) =>\n\t\t'\u250C' + '\u2500'.repeat(urlWidth) + a + '\u2500'.repeat(methodsWidth) + b + '\u2500'.repeat(idWidth) + c;\n\tconsole.log(line('\u252C', '\u252C', '\u2510'));\n\tconsole.log(\n\t\t'\u2502 ' +\n\t\t\t'URL'.padEnd(urlWidth - 2) +\n\t\t\t' \u2502 ' +\n\t\t\t'Methods'.padEnd(methodsWidth - 2) +\n\t\t\t' \u2502 ' +\n\t\t\t'ID'.padEnd(idWidth - 2) +\n\t\t\t' \u2502'\n\t);\n\tconsole.log(\n\t\t'\u251C' + '\u2500'.repeat(urlWidth) + '\u253C' + '\u2500'.repeat(methodsWidth) + '\u253C' + '\u2500'.repeat(idWidth) + '\u2524'\n\t);\n\tfor (const r of routes) {\n\t\tconsole.log(\n\t\t\t'\u2502 ' +\n\t\t\t\tr.urlPattern.padEnd(urlWidth - 2) +\n\t\t\t\t' \u2502 ' +\n\t\t\t\tr.methods.join(', ').padEnd(methodsWidth - 2) +\n\t\t\t\t' \u2502 ' +\n\t\t\t\tr.id.padEnd(idWidth - 2) +\n\t\t\t\t' \u2502'\n\t\t);\n\t}\n\tconsole.log(\n\t\t'\u2514' + '\u2500'.repeat(urlWidth) + '\u2534' + '\u2500'.repeat(methodsWidth) + '\u2534' + '\u2500'.repeat(idWidth) + '\u2518'\n\t);\n}\n", "import process from 'node:process';\nimport { Command } from 'commander';\nimport { x } from 'tinyexec';\nimport { detect } from 'package-manager-detector';\nimport { resolveCommand } from 'package-manager-detector/commands';\nimport { helpConfig } from '../lib/help.ts';\n\nasync function runWuchale(extraArgs: string[]): Promise<void> {\n\tconst cwd = process.cwd();\n\tconst pm = (await detect({ cwd }))?.name ?? 'npm';\n\tconst resolved = resolveCommand(pm, 'execute', ['wuchale', ...extraArgs])!;\n\tconst args = resolved.args.slice();\n\tif (pm === 'npm') args.unshift('--yes');\n\tawait x(resolved.command, args, {\n\t\tnodeOptions: { cwd, stdio: 'inherit' },\n\t\tthrowOnError: true\n\t});\n}\n\nconst extract = new Command('extract')\n\t.description('extract translatable strings')\n\t.configureHelp(helpConfig)\n\t.action(() => runWuchale([]));\n\nconst watch = new Command('watch')\n\t.description('watch and extract translatable strings')\n\t.configureHelp(helpConfig)\n\t.action(() => runWuchale(['--watch']));\n\nconst status = new Command('status')\n\t.description('show i18n status')\n\t.configureHelp(helpConfig)\n\t.action(() => runWuchale(['status']));\n\nconst clean = new Command('clean')\n\t.description('clean unused translatable strings')\n\t.configureHelp(helpConfig)\n\t.action(() => runWuchale(['--clean']));\n\nexport const i18n = new Command('i18n')\n\t.description('i18n utilities')\n\t.configureHelp(helpConfig)\n\t.addCommand(extract, { isDefault: true })\n\t.addCommand(watch)\n\t.addCommand(status)\n\t.addCommand(clean);\n", "import { stubCommand } from '../lib/stub.ts';\n\nexport const oauth = stubCommand('oauth', 'configure OAuth providers');\n", "import { stubCommand } from '../lib/stub.ts';\n\nexport const schemas = stubCommand('schemas', 'manage database schemas');\n", "import { Command } from 'commander';\nimport { helpConfig } from '../lib/help.ts';\nimport { editor } from './cms/editor.ts';\n\nexport const cms = new Command('cms')\n\t.description('manage the CMS')\n\t.configureHelp(helpConfig)\n\t.addCommand(editor);\n", "import { Command } from 'commander';\nimport { helpConfig } from '../../lib/help.ts';\nimport { editorAdd } from './editor/add.ts';\nimport { editorPassword } from './editor/password.ts';\nimport { editorList } from './editor/list.ts';\n\n/**\n * The admin bar signs in against the CMS's own `cms_editors` table, which\n * starts empty and has no UI to fill it. These commands are how an editor\n * gets an account.\n */\nexport const editor = new Command('editor')\n\t.description('manage who can sign in to the admin bar')\n\t.configureHelp(helpConfig)\n\t.addCommand(editorAdd)\n\t.addCommand(editorPassword)\n\t.addCommand(editorList);\n", "import { randomBytes } from 'node:crypto';\nimport { Command } from 'commander';\nimport * as p from '@clack/prompts';\nimport pc from 'picocolors';\nimport { helpConfig } from '../../../lib/help.ts';\nimport { runCommand } from '../../../lib/run.ts';\nimport { DEFAULT_PROJECT, withCmsBackend } from '../../../lib/cms-backend.ts';\n\nexport const editorAdd = new Command('add')\n\t.description('create an editor who can sign in to the admin bar')\n\t.argument('<email>', 'email the editor signs in with')\n\t.option('--password <password>', 'password to set \u2014 generated and shown once when omitted')\n\t.option('--project <id>', 'project the editor may edit', DEFAULT_PROJECT)\n\t.configureHelp(helpConfig)\n\t.action((email: string, options: { password?: string; project: string }) =>\n\t\trunCommand(async () => {\n\t\t\tconst generated = options.password === undefined;\n\t\t\t// 96 bits, URL-safe, and never written anywhere but this terminal.\n\t\t\tconst password = options.password ?? randomBytes(12).toString('base64url');\n\n\t\t\tconst editor = await withCmsBackend((cms) =>\n\t\t\t\tcms.editors.create({ email, password, projects: [options.project] })\n\t\t\t);\n\n\t\t\tconst lines = [`Added ${pc.cyan(editor.email)} as an editor of ${pc.cyan(options.project)}.`];\n\t\t\tif (generated) {\n\t\t\t\tlines.push('', `Password: ${pc.bold(password)}`, '', 'It is shown once; copy it now.');\n\t\t\t}\n\t\t\tp.log.success(lines.join('\\n'));\n\t\t\tp.log.info(\n\t\t\t\t`Run ${pc.cyan('vela dev')}, open any page with ${pc.cyan('?edit')} on the URL (or press ${pc.cyan('Ctrl+E')}), and sign in.`\n\t\t\t);\n\t\t}, 'Failed to add the editor.')\n\t);\n", "import { createRequire } from 'node:module';\nimport path from 'node:path';\nimport process from 'node:process';\nimport { pathToFileURL } from 'node:url';\nimport pc from 'picocolors';\nimport { findWorkspaceRoot, localDataDir } from './workspace.ts';\n\n/**\n * The slice of `@velastack/cms/backend` the CLI drives.\n *\n * Declared here rather than imported because the package is the project's\n * dependency, not the CLI's: `vela enable cms` installs it into the app, and\n * `vela cms editor \u2026` has to open the same database that app serves, through\n * the same version of the package. Resolving from the project also means a\n * global `vela` and a project-pinned one behave identically.\n */\nexport interface CmsEditor {\n\tid: string;\n\temail: string;\n\tname: string;\n}\n\nexport interface CmsEditorStore {\n\tcreate(input: {\n\t\temail: string;\n\t\tpassword: string;\n\t\tname?: string;\n\t\tprojects?: string[];\n\t}): Promise<CmsEditor>;\n\tsetPassword(idOrEmail: string, password: string): Promise<void>;\n\tlist(): CmsEditor[];\n\tprojectsFor(idOrEmail: string): string[];\n}\n\nexport interface CmsBackend {\n\teditors: CmsEditorStore;\n\tclose(): void;\n}\n\ninterface CmsBackendModule {\n\tcreateCmsBackend(options: { dbPath: string; uploadDir: string }): CmsBackend;\n}\n\n/**\n * The project id a single-tenant mount resolves every request to. It is the\n * backend's own default, so an editor granted this id can sign in to the app\n * `vela enable cms` produced without any further configuration.\n */\nexport const DEFAULT_PROJECT = 'default';\n\n/** Where the app keeps the CMS database, as `dataPath('cms.sqlite')` resolves it. */\nexport function cmsDatabasePath(root: string): string {\n\treturn path.join(localDataDir(root), 'cms.sqlite');\n}\n\nasync function loadBackendModule(root: string): Promise<CmsBackendModule> {\n\tlet entry: string;\n\ttry {\n\t\tentry = createRequire(path.join(root, 'package.json')).resolve('@velastack/cms/backend');\n\t} catch {\n\t\tthrow new Error(\n\t\t\t`@velastack/cms is not installed in this project.\\n\\n` +\n\t\t\t\t`Run ${pc.cyan('vela enable cms')} first.`\n\t\t);\n\t}\n\treturn (await import(pathToFileURL(entry).href)) as CmsBackendModule;\n}\n\n/**\n * Open the project's CMS backend, run `fn` against it, and close it.\n *\n * Opens the database at the same path the app uses \u2014 `<data dir>/cms.sqlite`,\n * resolved from the workspace root rather than the working directory so the\n * command can be run from a subdirectory \u2014 and so writes to the editors the\n * running app signs in against.\n */\nexport async function withCmsBackend<T>(\n\tfn: (backend: CmsBackend) => Promise<T>,\n\tcwd: string = process.cwd()\n): Promise<T> {\n\tconst root = findWorkspaceRoot(cwd);\n\tif (!root) {\n\t\tthrow new Error('Could not find workspace root (no package.json found)');\n\t}\n\n\tconst { createCmsBackend } = await loadBackendModule(root);\n\tconst dataDir = localDataDir(root);\n\t// A missing driver throws a message naming better-sqlite3 and how to\n\t// install it, which is exactly what should be shown.\n\tconst backend = createCmsBackend({\n\t\tdbPath: path.join(dataDir, 'cms.sqlite'),\n\t\tuploadDir: path.join(dataDir, 'uploads')\n\t});\n\n\ttry {\n\t\treturn await fn(backend);\n\t} finally {\n\t\tbackend.close();\n\t}\n}\n", "import { Command } from 'commander';\nimport * as p from '@clack/prompts';\nimport pc from 'picocolors';\nimport { helpConfig } from '../../../lib/help.ts';\nimport { runCommand } from '../../../lib/run.ts';\nimport { withCmsBackend } from '../../../lib/cms-backend.ts';\n\nexport const editorPassword = new Command('password')\n\t.description(\"set an editor's password\")\n\t.argument('<email>', 'email of the editor')\n\t.argument('<password>', 'new password')\n\t.configureHelp(helpConfig)\n\t.action((email: string, password: string) =>\n\t\trunCommand(async () => {\n\t\t\tawait withCmsBackend((cms) => cms.editors.setPassword(email, password));\n\t\t\t// The backend ends every session for the editor on a password change.\n\t\t\tp.log.success(\n\t\t\t\t`Updated the password for ${pc.cyan(email)}. Existing sessions were signed out.`\n\t\t\t);\n\t\t}, 'Failed to set the password.')\n\t);\n", "import { Command } from 'commander';\nimport * as p from '@clack/prompts';\nimport pc from 'picocolors';\nimport { helpConfig } from '../../../lib/help.ts';\nimport { runCommand } from '../../../lib/run.ts';\nimport { withCmsBackend } from '../../../lib/cms-backend.ts';\n\nexport const editorList = new Command('list')\n\t.description('list editors and the projects they may edit')\n\t.configureHelp(helpConfig)\n\t.action(() =>\n\t\trunCommand(async () => {\n\t\t\tconst rows = await withCmsBackend(async (cms) =>\n\t\t\t\tcms.editors.list().map((editor) => ({\n\t\t\t\t\temail: editor.email,\n\t\t\t\t\tprojects: cms.editors.projectsFor(editor.id)\n\t\t\t\t}))\n\t\t\t);\n\n\t\t\tif (rows.length === 0) {\n\t\t\t\tp.log.info(`No editors yet. Add one with ${pc.cyan('vela cms editor add <email>')}.`);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst width = Math.max(...rows.map((row) => row.email.length));\n\t\t\tp.log.info(\n\t\t\t\t`Editors\\n\\n` +\n\t\t\t\t\trows\n\t\t\t\t\t\t.map(\n\t\t\t\t\t\t\t(row) =>\n\t\t\t\t\t\t\t\t` ${row.email.padEnd(width)} ${pc.dim(row.projects.join(', ') || 'no projects')}`\n\t\t\t\t\t\t)\n\t\t\t\t\t\t.join('\\n')\n\t\t\t);\n\t\t}, 'Failed to list editors.')\n\t);\n"],
5
- "mappings": ";;;AAAA,OAAOA,eAAa;AACpB,SAAS,iBAAAC,sBAAqB;;;ACD9B;AAAA,EACC,MAAQ;AAAA,EACR,SAAW;AAAA,EACX,MAAQ;AAAA,EACR,aAAe;AAAA,EACf,SAAW;AAAA,EACX,YAAc;AAAA,IACb,MAAQ;AAAA,IACR,KAAO;AAAA,EACR;AAAA,EACA,UAAY;AAAA,EACZ,SAAW;AAAA,IACV,MAAQ;AAAA,EACT;AAAA,EACA,KAAO;AAAA,IACN,MAAQ;AAAA,IACR,WAAa;AAAA,EACd;AAAA,EACA,OAAS;AAAA,IACR;AAAA,IACA;AAAA,EACD;AAAA,EACA,SAAW;AAAA,IACV,OAAS;AAAA,IACT,KAAO;AAAA,IACP,OAAS;AAAA,IACT,MAAQ;AAAA,IACR,WAAW;AAAA,IACX,eAAe;AAAA,IACf,QAAU;AAAA,IACV,MAAQ;AAAA,IACR,SAAW;AAAA,EACZ;AAAA,EACA,cAAgB;AAAA,IACf,kBAAkB;AAAA,IAClB,mBAAmB;AAAA,IACnB,uBAAuB;AAAA,IACvB,iCAAiC;AAAA,IACjC,wBAAwB;AAAA,IACxB,WAAa;AAAA,IACb,eAAe;AAAA,IACf,QAAU;AAAA,IACV,QAAU;AAAA,IACV,gBAAgB;AAAA,IAChB,qBAAqB;AAAA,IACrB,gBAAgB;AAAA,IAChB,4BAA4B;AAAA,I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AAEA,WAAW,WAAW;AAAA,EACrB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACAI;AAAA,EACA;AAAA,EACA;AAAA,EACAC;AACD,GAAG;AACF,UAAQ,WAAW,OAAO;AAC3B;;;AJlLA,IAAM,OAAO,cAAcC,UAAQ,KAAK,MAAM,CAAC,CAAC;AAEhD,IAAM,oBAAoB,mBAAmB;AAAA,EAC5C;AAAA,EACA,UAAUC,eAAc,YAAY,GAAG;AAAA,EACvC,aAAa,gBAAI;AAClB,CAAC;AAED,IAAI,sBAAsB,MAAM;AAC/B,EAAAD,UAAQ,KAAK,iBAAiB;AAC/B;AAEA,QAAQ,MAAM,MAAM,EAAE,MAAM,OAAO,CAAC;",
6
- "names": ["process", "fileURLToPath", "argv", "process", "argv", "env", "process", "p", "Command", "dotenv", "pc", "pc", "pc", "fs", "path", "process", "fs", "path", "process", "path", "fs", "fs", "path", "process", "v", "Command", "p", "pc", "resolveCommand", "schema", "fs", "path", "fs", "path", "process", "p", "pm", "fs", "path", "process", "detect", "resolve", "email", "password", "path", "fs", "detect", "process", "require", "fs", "path", "fs", "path", "fs", "path", "init", "path", "fs", "fs", "path", "p", "report", "label", "fs", "path", "path", "fs", "Command", "email", "password", "process", "path", "fs", "pc", "resolveCommand", "fs", "path", "process", "v", "Command", "p", "detect", "resolveCommand", "optionsSchema", "Command", "path", "process", "detect", "resolveCommand", "onCancel", "fs", "email", "password", "Command", "Command", "p", "path", "p", "path", "slug", "argv", "report", "log", "collections", "fs", "path", "p", "pc", "fs", "path", "fs", "path", "p", "spinner", "p", "p", "argv", "pc", "path", "fs", "Command", "argv", "stage", "slug", "Command", "p", "Command", "argv", "stage", "Command", "Command", "Command", "p", "Command", "argv", "stage", "slug", "Command", "Command", "Command", "Command", "Command", "Command", "Command", "Command", "Command", "Command", "Command", "Command", "Command", "Command", "Command", "Command", "process", "Command", "p", "Command", "process", "v", "Command", "Command", "process", "Command", "p", "pc", "process", "v", "p", "pc", "fs", "path", "path", "fs", "slug", "env", "v", "fs", "os", "path", "crypto", "process", "spawn", "resolve", "path", "path", "fs", "env", "fs", "text", "label", "base", "pc", "process", "pc", "fs", "p", "pc", "fs", "env", "email", "password", "pc", "PocketBase", "env", "email", "password", "PocketBase", "label", "pc", "email", "password", "fs", "path", "s3", "path", "fs", "Command", "pc", "text", "process", "password", "confirm", "process", "Command", "p", "Command", "v", "process", "process", "Command", "p", "pc", "Command", "pc", "process", "Command", "Command", "Command", "Command", "Command", "Command", "Command", "process", "p", "process", "auth", "Command", "Command", "api", "Command", "Command", "apiKeys", "Command", "Command", "backend", "Command", "Command", "contentNegotiation", "Command", "Command", "i18n", "Command", "Command", "teams", "Command", "Command", "payments", "Command", "Command", "p", "pc", "s3", "Command", "label", "pc", "Command", "smtp", "Command", "Command", "auth", "api", "apiKeys", "backend", "contentNegotiation", "i18n", "teams", "payments", "s3", "smtp", "Command", "Command", "process", "p", "slug", "report", "process", "form", "Command", "Command", "schema", "Command", "Command", "resource", "Command", "Command", "scaffold", "Command", "process", "Command", "p", "pc", "Command", "confirm", "pc", "process", "Command", "form", "schema", "resource", "scaffold", "Command", "Command", "exec", "detect", "resolveCommand", "Command", "detect", "resolveCommand", "exec", "fs", "path", "Command", "path", "fs", "Command", "Command", "Command", "fs", "path", "Command", "p", "process", "p", "email", "email", "subscriptions", "path", "fs", "Command", "fs", "path", "Command", "p", "compute", "v", "sectionHeader", "sectionDefinitions", "intro", "sectionLinks", "sectionChanges", "sectionContact", "path", "fs", "Command", "Command", "Command", "fs", "path", "Command", "path", "fs", "Command", "path", "Command", "collections", "collections", "label", "path", "Command", "Command", "Command", "fs", "path", "Command", "InvalidArgumentError", "p", "InvalidArgumentError", "list", "path", "fs", "collections", "schema", "generate", "Command", "Command", "InvalidArgumentError", "p", "parseCount", "InvalidArgumentError", "parseSeed", "Command", "Command", "generate", "Command", "fs", "path", "Command", "path", "fs", "load", "Command", "seeds", "fs", "path", "Command", "padZeros", "Command", "path", "fs", "collections", "fs", "path", "Command", "seeds", "fs", "path", "clear", "Command", "Command", "load", "clear", "Command", "p", "makeFetchCookie", "os", "Command", "p", "Command", "email", "password", "label", "os", "Command", "email", "password", "makeFetchCookie", "Command", "p", "Command", "Command", "p", "Command", "Command", "Command", "path", "process", "x", "process", "x", "path", "Command", "Command", "InvalidArgumentError", "InvalidArgumentError", "Command", "fs", "path", "process", "Command", "create", "Command", "process", "path", "fs", "fs", "path", "process", "Command", "Command", "process", "listMigrationFiles", "path", "fs", "Command", "Command", "Command", "create", "fs", "path", "process", "Command", "InvalidArgumentError", "pc", "PocketBase", "path", "process", "createRequire", "pathToFileURL", "pc", "InvalidArgumentError", "Command", "process", "path", "backend", "fs", "PocketBase", "pc", "fs", "path", "process", "Command", "p", "pc", "x", "detect", "resolveCommand", "env", "process", "process", "path", "Command", "process", "detect", "resolveCommand", "x", "fs", "pc", "path", "process", "Command", "x", "detect", "resolveCommand", "Command", "process", "path", "detect", "resolveCommand", "x", "path", "Command", "Command", "path", "Command", "p", "pc", "v", "OptionsSchema", "Command", "pc", "path", "fs", "Command", "Option", "p", "pc", "v", "fs", "path", "process", "PocketBase", "path", "fs", "email", "process", "password", "PocketBase", "fs", "path", "detect", "resolveCommand", "env", "result", "detect", "resolveCommand", "add", "path", "fs", "OptionsSchema", "Command", "Option", "backend", "pc", "email", "password", "fs", "path", "path", "process", "Command", "p", "createProject", "Command", "teams", "createProject", "process", "defaultProjectName", "v", "path", "Command", "Command", "p", "pc", "Command", "env", "pc", "process", "Command", "p", "pc", "Command", "pc", "env", "process", "Command", "p", "pc", "Command", "pc", "env", "fs", "path", "process", "Command", "p", "pc", "Command", "pc", "path", "process", "fs", "Command", "Command", "p", "pc", "Command", "report", "pc", "label", "Command", "p", "pc", "Command", "pc", "Command", "Command", "Command", "process", "Command", "p", "pc", "Command", "email", "password", "promptPassword", "pc", "base", "process", "Command", "Command", "fs", "path", "Command", "p", "pc", "slug", "list", "resolve", "Command", "pc", "spinner", "path", "fs", "Command", "p", "pc", "Command", "pc", "fs", "path", "Command", "p", "pc", "Command", "pc", "path", "fs", "spinner", "process", "Command", "p", "pc", "Command", "pc", "process", "Command", "p", "pc", "Command", "pc", "Command", "fs", "path", "process", "Command", "p", "pc", "Command", "fs", "confirm", "pc", "path", "process", "spinner", "Command", "p", "pc", "v", "OptionsSchema", "Command", "report", "pc", "path", "process", "Command", "PocketBase", "pc", "x", "detect", "resolveCommand", "fs", "Command", "process", "email", "password", "path", "fs", "pc", "PocketBase", "detect", "resolveCommand", "x", "fs", "path", "Command", "Command", "path", "fs", "routes", "process", "Command", "x", "detect", "resolveCommand", "process", "detect", "resolveCommand", "x", "Command", "status", "i18n", "Command", "Command", "Command", "p", "pc", "createRequire", "path", "process", "pathToFileURL", "pc", "createRequire", "path", "pc", "pathToFileURL", "process", "backend", "Command", "email", "password", "editor", "cms", "pc", "Command", "p", "pc", "Command", "email", "password", "cms", "pc", "Command", "p", "pc", "Command", "cms", "editor", "pc", "Command", "cms", "Command", "Command", "process", "dotenv", "path", "pc", "i18n", "cms", "process", "fileURLToPath"]
3
+ "sources": ["../src/bin.ts", "../src/lib/argv.ts", "../src/program.ts", "../package.json", "../src/lib/help.ts", "../src/lib/stub.ts", "../src/lib/run.ts", "../src/lib/errors.ts", "../src/lib/workspace.ts", "../src/lib/constants.ts", "../src/lib/package-json.ts", "../src/commands/bless.ts", "../src/lib/options.ts", "../src/lib/templates.ts", "../src/lib/package-manager.ts", "../src/lib/pocketbase.ts", "../src/lib/env.ts", "../src/lib/config-merge.ts", "../src/lib/config-target.ts", "../src/lib/scaffold-detect.ts", "../src/lib/result-report.ts", "../src/lib/template-files.ts", "../src/commands/create.ts", "../src/commands/generate.ts", "../src/commands/generate/form.ts", "../src/lib/pattern-runner.ts", "../src/lib/ai-flow.ts", "../src/lib/config.ts", "../src/lib/project-config.ts", "../src/lib/ai-client.ts", "../src/lib/ai-loop.ts", "../src/lib/ai-existing-models.ts", "../src/lib/ai-to-argv.ts", "../src/lib/ai-grid.ts", "../src/commands/generate/schema.ts", "../src/commands/generate/resource.ts", "../src/commands/generate/scaffold.ts", "../src/commands/generate/migration.ts", "../src/commands/enable.ts", "../src/commands/enable/auth.ts", "../src/commands/enable/api.ts", "../src/commands/enable/api-keys.ts", "../src/commands/enable/backend.ts", "../src/commands/enable/i18n.ts", "../src/commands/enable/teams.ts", "../src/commands/enable/payments.ts", "../src/commands/enable/subscriptions.ts", "../src/commands/enable/s3.ts", "../src/lib/server-command.ts", "../src/lib/deploy-config.ts", "../src/lib/instance.ts", "../src/lib/ssh-options.ts", "../src/lib/ssh.ts", "../src/lib/remote.ts", "../src/lib/remote-env.ts", "../src/lib/target.ts", "../src/lib/backup-target.ts", "../src/lib/local-env.ts", "../src/lib/remote-pocketbase.ts", "../src/lib/s3-settings.ts", "../src/commands/enable/smtp.ts", "../src/commands/enable/cms.ts", "../src/commands/enable/blog.ts", "../src/commands/enable/content-negotiation.ts", "../src/commands/disable.ts", "../src/commands/disable/auth.ts", "../src/commands/disable/_shared.ts", "../src/commands/disable/api.ts", "../src/commands/disable/api-keys.ts", "../src/commands/disable/backend.ts", "../src/commands/disable/content-negotiation.ts", "../src/commands/disable/i18n.ts", "../src/commands/disable/teams.ts", "../src/commands/disable/payments.ts", "../src/commands/disable/s3.ts", "../src/commands/disable/smtp.ts", "../src/commands/destroy.ts", "../src/commands/destroy/form.ts", "../src/commands/destroy/_shared.ts", "../src/commands/destroy/schema.ts", "../src/commands/destroy/resource.ts", "../src/commands/destroy/scaffold.ts", "../src/commands/destroy/deployment.ts", "../src/commands/ui.ts", "../src/commands/ui/add.ts", "../src/commands/ui/base.ts", "../src/commands/legal.ts", "../src/commands/legal/terms.ts", "../src/commands/legal/shared.ts", "../src/commands/legal/privacy.ts", "../src/commands/fixtures.ts", "../src/commands/fixtures/load.ts", "../src/lib/data.ts", "../src/lib/collections.ts", "../src/commands/fixtures/clear.ts", "../src/commands/fixtures/reset.ts", "../src/commands/fixtures/generate.ts", "../src/commands/fixtures/regen.ts", "../src/commands/seeds.ts", "../src/commands/seeds/load.ts", "../src/commands/seeds/save.ts", "../src/commands/seeds/clear.ts", "../src/commands/signup.ts", "../src/commands/login.ts", "../src/commands/logout.ts", "../src/commands/whoami.ts", "../src/commands/migrate.ts", "../src/commands/migrate/up.ts", "../src/lib/migrate.ts", "../src/commands/migrate/down.ts", "../src/commands/migrate/create.ts", "../src/commands/migrate/collections.ts", "../src/commands/migrate/history-sync.ts", "../src/commands/dev.ts", "../src/lib/vite.ts", "../src/commands/build.ts", "../src/lib/build-env.ts", "../src/lib/origin.ts", "../src/commands/preview.ts", "../src/commands/sync.ts", "../src/commands/provision.ts", "../src/commands/deploy.ts", "../src/lib/pocketbase-settings.ts", "../src/lib/artifact.ts", "../src/commands/link.ts", "../src/lib/velastack-api.ts", "../src/commands/env.ts", "../src/commands/env/list.ts", "../src/commands/env/set.ts", "../src/commands/env/unset.ts", "../src/commands/env/import.ts", "../src/commands/status.ts", "../src/commands/rollback.ts", "../src/commands/logs.ts", "../src/commands/admin.ts", "../src/commands/admin/create.ts", "../src/commands/backup.ts", "../src/commands/backup/create.ts", "../src/lib/backups.ts", "../src/commands/backup/list.ts", "../src/commands/backup/download.ts", "../src/commands/backup/delete.ts", "../src/commands/backup/schedule.ts", "../src/commands/restore.ts", "../src/commands/targets.ts", "../src/commands/test.ts", "../src/commands/routes.ts", "../src/commands/i18n.ts", "../src/commands/oauth.ts", "../src/commands/schemas.ts", "../src/commands/cms.ts", "../src/commands/cms/editor.ts", "../src/commands/cms/editor/add.ts", "../src/lib/cms-backend.ts", "../src/commands/cms/editor/password.ts", "../src/commands/cms/editor/list.ts"],
4
+ "sourcesContent": ["import process from 'node:process';\nimport { normalizeArgv } from './lib/argv.ts';\nimport { program } from './program.ts';\n\nprogram.parse(normalizeArgv(process.argv.slice(2)), { from: 'user' });\n", "/**\n * Drop one `--` separator from the arguments.\n *\n * `npm run dev -- --open` is the idiom for forwarding flags through npm, and npm\n * strips the separator before the script sees it \u2014 so a template script running\n * `vela dev` receives a plain `--open`. Typed straight at the CLI the separator\n * survives, and commander reads everything after it as a positional argument, so\n * `vela dev -- --open` fails with \"too many arguments\" instead of opening a\n * browser.\n *\n * No vela command takes an argument that could be mistaken for a flag, so the\n * separator carries no meaning here. Removing it makes both spellings agree.\n */\nexport function normalizeArgv(argv: string[]): string[] {\n\tconst separator = argv.indexOf('--');\n\tif (separator === -1) return argv;\n\treturn [...argv.slice(0, separator), ...argv.slice(separator + 1)];\n}\n", "import process from 'node:process';\nimport * as p from '@clack/prompts';\nimport { Command } from 'commander';\nimport nodePath from 'node:path';\nimport dotenv from 'dotenv';\nimport pc from 'picocolors';\nimport pkg from '../package.json' with { type: 'json' };\nimport { helpConfig } from './lib/help.ts';\nimport { isStub } from './lib/stub.ts';\nimport { findWorkspaceRoot, hasBackend } from './lib/workspace.ts';\nimport { bless } from './commands/bless.ts';\nimport { create } from './commands/create.ts';\nimport { generate } from './commands/generate.ts';\nimport { enable } from './commands/enable.ts';\nimport { disable } from './commands/disable.ts';\nimport { destroy } from './commands/destroy.ts';\nimport { ui } from './commands/ui.ts';\nimport { legal } from './commands/legal.ts';\nimport { fixtures } from './commands/fixtures.ts';\nimport { seeds } from './commands/seeds.ts';\nimport { signup } from './commands/signup.ts';\nimport { login } from './commands/login.ts';\nimport { logout } from './commands/logout.ts';\nimport { whoami } from './commands/whoami.ts';\nimport { migrate } from './commands/migrate.ts';\nimport { dev } from './commands/dev.ts';\nimport { build } from './commands/build.ts';\nimport { preview } from './commands/preview.ts';\nimport { sync } from './commands/sync.ts';\nimport { provision } from './commands/provision.ts';\nimport { deploy } from './commands/deploy.ts';\nimport { link } from './commands/link.ts';\nimport { env } from './commands/env.ts';\nimport { status } from './commands/status.ts';\nimport { rollback } from './commands/rollback.ts';\nimport { logs } from './commands/logs.ts';\nimport { admin } from './commands/admin.ts';\nimport { backup } from './commands/backup.ts';\nimport { restore } from './commands/restore.ts';\nimport { targets } from './commands/targets.ts';\nimport { testServer } from './commands/test.ts';\nimport { routes } from './commands/routes.ts';\nimport { i18n } from './commands/i18n.ts';\nimport { oauth } from './commands/oauth.ts';\nimport { schemas } from './commands/schemas.ts';\nimport { cms } from './commands/cms.ts';\n\n/**\n * Commands that never touch the database, whether or not the project has one.\n */\nconst NO_BACKEND_COMMMANDS = new Set([\n\t'bless',\n\t'create',\n\t'signup',\n\t'login',\n\t'logout',\n\t'whoami',\n\t'legal',\n\t'ui',\n\t'routes',\n\t'i18n',\n\t'generate schema',\n\t'generate form',\n\t// The CMS keeps its own SQLite database and editors; PocketBase is never involved.\n\t'enable cms',\n\t'cms',\n\t// Server commands talk to a VPS over SSH, never to the local database.\n\t'provision',\n\t'env',\n\t'status',\n\t'rollback',\n\t'logs',\n\t'admin',\n\t'targets',\n\t'link',\n\t// Acts on whichever target `-t` names; the local path reads the project's\n\t// own credentials rather than requiring them in this process.\n\t'backup',\n\t'restore'\n]);\n\n/**\n * Commands that drive the frontend build and so work with or without a backend.\n * In a backend project they still start PocketBase, which is why they are not in\n * NO_BACKEND_COMMMANDS.\n */\nconst BACKEND_OPTIONAL_COMMANDS = new Set(['dev', 'build', 'preview', 'deploy']);\n\n/**\n * Commands that create their own superuser for a throwaway database, so the\n * credentials in `.env` are never read.\n */\nconst SELF_CREDENTIALED_COMMANDS = new Set(['test:server']);\n\nexport const program = new Command()\n\t.name(pkg.name)\n\t.description(pkg.description)\n\t.version(pkg.version, '-v, --version')\n\t.configureHelp(helpConfig);\n\nprogram.hook('preAction', (_thisCommand, actionCommand) => {\n\tif (isStub(actionCommand)) return;\n\n\t// Resolved from the workspace root rather than the cwd: dotenv's default\n\t// would miss `.env` for anything run from a subdirectory, which `-t local`\n\t// makes visible the moment a command reads or writes it.\n\tconst envRoot = findWorkspaceRoot() ?? process.cwd();\n\tdotenv.config({ path: nodePath.join(envRoot, '.env'), quiet: true });\n\n\tconst path = getCommandPath(actionCommand);\n\tif (NO_BACKEND_COMMMANDS.has(path)) return;\n\tconst top = path.split(' ', 1)[0];\n\tif (NO_BACKEND_COMMMANDS.has(top)) return;\n\n\t// A static project has no PocketBase, so there are no credentials to ask for.\n\t// Frontend commands carry on; anything that needs the database says so plainly\n\t// rather than sending the user off to look for a .env that would not help.\n\tif (!hasBackend()) {\n\t\tif (BACKEND_OPTIONAL_COMMANDS.has(top)) return;\n\n\t\tp.log.error(\n\t\t\t`${pc.cyan(`vela ${path}`)} needs a backend, and this project does not have one.\\n\\n` +\n\t\t\t\t`Static projects have no database to talk to.\\n\\n` +\n\t\t\t\t`To add a backend to this project, run ${pc.cyan('vela bless')}.`\n\t\t);\n\t\tp.log.message();\n\t\tp.cancel('Operation failed.');\n\t\tprocess.exit(1);\n\t}\n\n\tif (SELF_CREDENTIALED_COMMANDS.has(path)) return;\n\n\tif (!process.env.POCKETBASE_SUPERUSER_EMAIL || !process.env.POCKETBASE_SUPERUSER_PASSWORD) {\n\t\tp.log.error(\n\t\t\t`PocketBase superuser credentials are required.\\n\\n` +\n\t\t\t\t`Set ${pc.cyan('POCKETBASE_SUPERUSER_EMAIL')} and ${pc.cyan('POCKETBASE_SUPERUSER_PASSWORD')} in your .env file.\\n\\n` +\n\t\t\t\t`To set up a new project, run ${pc.cyan('vela create')}.\\n` +\n\t\t\t\t`To set up an existing project, run ${pc.cyan('vela bless')}.`\n\t\t);\n\t\tp.log.message();\n\t\tp.cancel('Operation failed.');\n\t\tprocess.exit(1);\n\t}\n});\n\nfunction getCommandPath(cmd: Command): string {\n\tconst names: string[] = [];\n\tlet current: Command | null = cmd;\n\twhile (current && current.parent) {\n\t\tnames.unshift(current.name());\n\t\tcurrent = current.parent;\n\t}\n\treturn names.join(' ');\n}\n\nfor (const command of [\n\tbless,\n\tcreate,\n\tgenerate,\n\tenable,\n\tdisable,\n\tdestroy,\n\tui,\n\tlegal,\n\tfixtures,\n\tseeds,\n\tsignup,\n\tlogin,\n\tlogout,\n\twhoami,\n\tmigrate,\n\tdev,\n\tbuild,\n\tpreview,\n\tsync,\n\tprovision,\n\tdeploy,\n\trollback,\n\tstatus,\n\tlogs,\n\tenv,\n\tadmin,\n\tbackup,\n\trestore,\n\ttargets,\n\tlink,\n\ttestServer,\n\troutes,\n\ti18n,\n\toauth,\n\tschemas,\n\tcms\n]) {\n\tprogram.addCommand(command);\n}\n", "{\n\t\"name\": \"vela\",\n\t\"version\": \"0.10.13\",\n\t\"type\": \"module\",\n\t\"description\": \"A CLI for creating and updating SvelteKit projects\",\n\t\"license\": \"MIT\",\n\t\"repository\": {\n\t\t\"type\": \"git\",\n\t\t\"url\": \"git+https://github.com/velastack/vela.git\"\n\t},\n\t\"homepage\": \"https://velastack.dev\",\n\t\"engines\": {\n\t\t\"node\": \">=20\"\n\t},\n\t\"bin\": {\n\t\t\"vela\": \"./dist/bin.js\",\n\t\t\"velastack\": \"./dist/bin.js\"\n\t},\n\t\"files\": [\n\t\t\"dist\",\n\t\t\"templates\"\n\t],\n\t\"scripts\": {\n\t\t\"build\": \"node --experimental-strip-types scripts/build.ts\",\n\t\t\"dev\": \"node --experimental-strip-types scripts/build.ts --watch\",\n\t\t\"clean\": \"rm -rf dist\",\n\t\t\"lint\": \"npm run lint:ts && npm run lint:format\",\n\t\t\"lint:ts\": \"tsc --noEmit\",\n\t\t\"lint:format\": \"prettier --check .\",\n\t\t\"format\": \"prettier --write .\",\n\t\t\"test\": \"vitest run\",\n\t\t\"prepare\": \"npm run build\"\n\t},\n\t\"dependencies\": {\n\t\t\"@clack/prompts\": \"^1.7.0\",\n\t\t\"@faker-js/faker\": \"^10.6.0\",\n\t\t\"@velastack/patterns\": \"^0.1.9\",\n\t\t\"@velastack/pocketbase-codegen\": \"^0.1.0\",\n\t\t\"annotate-json-schema\": \"^0.1.0\",\n\t\t\"commander\": \"^13.1.0\",\n\t\t\"cross-spawn\": \"^7.0.6\",\n\t\t\"dedent\": \"^1.7.2\",\n\t\t\"dotenv\": \"^17.4.2\",\n\t\t\"fetch-cookie\": \"^3.2.0\",\n\t\t\"json-schema-faker\": \"^0.6.3\",\n\t\t\"magic-string\": \"^0.30.21\",\n\t\t\"package-manager-detector\": \"^1.8.0\",\n\t\t\"picocolors\": \"^1.1.1\",\n\t\t\"pocketbase\": \"^0.28.0\",\n\t\t\"pocketbase-server\": \"^0.39.11\",\n\t\t\"stripe\": \"^19.3.0\",\n\t\t\"svelte\": \"^5.56.10\",\n\t\t\"tinyexec\": \"^1.3.0\",\n\t\t\"ts-morph\": \"^28.0.0\",\n\t\t\"valibot\": \"^1.4.2\"\n\t},\n\t\"devDependencies\": {\n\t\t\"@types/cross-spawn\": \"^6.0.6\",\n\t\t\"@types/node\": \"^22.0.0\",\n\t\t\"esbuild\": \"^0.28.2\",\n\t\t\"prettier\": \"^3.9.6\",\n\t\t\"typescript\": \"^5.6.0\",\n\t\t\"vite\": \"^8.2.2\",\n\t\t\"vitest\": \"^4.1.11\"\n\t},\n\t\"peerDependencies\": {\n\t\t\"@sveltejs/kit\": \"^2.57.1\",\n\t\t\"vite\": \"^8.0.8\"\n\t},\n\t\"peerDependenciesMeta\": {\n\t\t\"@sveltejs/kit\": {\n\t\t\t\"optional\": true\n\t\t},\n\t\t\"vite\": {\n\t\t\t\"optional\": true\n\t\t}\n\t},\n\t\"keywords\": [\n\t\t\"svelte\",\n\t\t\"sveltekit\",\n\t\t\"velastack\",\n\t\t\"pocketbase\",\n\t\t\"cli\",\n\t\t\"starter\",\n\t\t\"template\"\n\t]\n}\n", "import pc from 'picocolors';\nimport type { Argument, HelpConfiguration, Option } from 'commander';\n\nconst NO_PREFIX = '--no-';\nlet currentOptions: readonly Option[] = [];\n\nfunction getLongFlag(flags: string) {\n\treturn flags\n\t\t.split(',')\n\t\t.map((f) => f.trim())\n\t\t.find((f) => f.startsWith('--'));\n}\n\nfunction formatDescription(arg: Option | Argument): string {\n\tlet output = arg.description;\n\tif (arg.defaultValue !== undefined && String(arg.defaultValue)) {\n\t\toutput += pc.dim(` (default: ${JSON.stringify(arg.defaultValue)})`);\n\t}\n\tif (arg.argChoices !== undefined && String(arg.argChoices)) {\n\t\toutput += pc.dim(` (choices: ${arg.argChoices.join(', ')})`);\n\t}\n\treturn output;\n}\n\nexport const helpConfig: HelpConfiguration = {\n\targumentDescription: formatDescription,\n\toptionDescription: formatDescription,\n\tvisibleOptions(cmd) {\n\t\tcurrentOptions = cmd.options;\n\n\t\tconst visible = cmd.options.filter((o) => !o.hidden);\n\t\tconst show: Option[] = [];\n\t\tfor (const option of visible) {\n\t\t\tconst flag = getLongFlag(option.flags);\n\t\t\tif (flag?.startsWith(NO_PREFIX)) {\n\t\t\t\tconst stripped = flag.slice(NO_PREFIX.length);\n\t\t\t\tconst isNoVariant = visible.some((o) => getLongFlag(o.flags)?.startsWith(`--${stripped}`));\n\t\t\t\tif (isNoVariant) continue;\n\t\t\t}\n\t\t\tshow.push(option);\n\t\t}\n\t\treturn show;\n\t},\n\tsubcommandTerm: (cmd) => {\n\t\treturn cmd.name() + ' ' + cmd.usage().replace(/\\[options\\]\\s?/, '');\n\t},\n\toptionTerm(option) {\n\t\tconst longFlag = getLongFlag(option.flags);\n\t\tconst flag = longFlag?.split(' ').at(0);\n\t\tif (!flag || !longFlag) return option.flags;\n\n\t\tconst noVariant = `--no-${flag.slice(2)}`;\n\t\tconst hasVariant = currentOptions.some((o) => getLongFlag(o.flags) === noVariant);\n\t\tif (hasVariant) {\n\t\t\treturn `--[no-]${longFlag.slice(2)}`;\n\t\t}\n\n\t\treturn option.flags;\n\t},\n\tstyleTitle: (str) => pc.underline(str),\n\tstyleCommandText: (str) => pc.redBright(str),\n\tstyleDescriptionText: (str) => pc.gray(str),\n\tstyleOptionText: (str) => pc.white(str),\n\tstyleArgumentText: (str) => pc.white(str),\n\tstyleSubcommandText: (str) => pc.redBright(str)\n};\n", "import { Command } from 'commander';\nimport { helpConfig } from './help.ts';\nimport { notImplemented } from './run.ts';\n\nexport const STUB = Symbol('stub');\n\ninterface StubCommand extends Command {\n\t[STUB]?: true;\n}\n\nexport function isStub(cmd: Command): boolean {\n\treturn (cmd as StubCommand)[STUB] === true;\n}\n\nexport function stubCommand(name: string, description: string, fullName?: string): Command {\n\tconst cmd: StubCommand = new Command(name)\n\t\t.description(description)\n\t\t.configureHelp(helpConfig)\n\t\t.action(() => notImplemented(fullName ?? name));\n\tcmd[STUB] = true;\n\treturn cmd;\n}\n", "import * as p from '@clack/prompts';\nimport pc from 'picocolors';\nimport { UnsupportedError } from './errors.ts';\n\ntype MaybePromise = () => Promise<void> | void;\n\nexport async function runCommand(action: MaybePromise, failureMessage?: string): Promise<void> {\n\ttry {\n\t\tawait action();\n\t} catch (e) {\n\t\tif (e instanceof UnsupportedError) {\n\t\t\tconst padding = Math.max(...e.reasons.map((r) => r.id.length), 0);\n\t\t\tconst message = e.reasons\n\t\t\t\t.map((r) => ` ${r.id.padEnd(padding)} ${pc.redBright(r.reason)}`)\n\t\t\t\t.join('\\n');\n\t\t\tp.log.error(`${e.name}\\n\\n${message}`);\n\t\t\tp.log.message();\n\t\t} else if (e instanceof Error) {\n\t\t\tconst prefix = failureMessage ? `${failureMessage} ` : '';\n\t\t\tp.log.error(`${prefix}${e.message}`);\n\t\t\tp.log.message();\n\t\t}\n\t\tp.cancel('Operation failed.');\n\t\tprocess.exitCode = 1;\n\t}\n}\n\nexport function notImplemented(name: string) {\n\treturn runCommand(async () => {\n\t\tp.log.warn(`\\`${name}\\` is not yet implemented \u2014 see ${pc.cyan('https://docs.velastack.dev')}`);\n\t});\n}\n", "type Reason = { id: string; reason: string };\n\nexport class UnsupportedError extends Error {\n\toverride name = 'Unsupported Environment';\n\treasons: Reason[];\n\tconstructor(reasons: Reason[]) {\n\t\tsuper();\n\t\tthis.reasons = reasons;\n\t}\n}\n", "import fs from 'node:fs';\nimport path from 'node:path';\nimport process from 'node:process';\nimport { APP_DIR, PUBLIC_DIR, DATA_DIR } from './constants.ts';\nimport { readPackageJson } from './package-json.ts';\n\nexport interface Features {\n\tauth: boolean;\n\tapi: boolean;\n\tapiKeys: boolean;\n\tbackend: boolean;\n\ti18n: boolean;\n\tteams: boolean;\n\tpayments: boolean;\n\tblog: boolean;\n\tcontentNegotiation: boolean;\n\tcms: boolean;\n}\n\nexport interface Workspace {\n\tworkspaceRootDir: string;\n\troutesDir: string;\n\tpublicRoutesDir: string;\n\tappRoutesDir?: string;\n\tisAppMode: boolean;\n\tisPaymentsMode: boolean;\n\tfeatures: Features;\n}\n\n/**\n * Nearest ancestor holding a package.json, or null when there is none.\n */\nexport function findWorkspaceRoot(from: string = process.cwd()): string | null {\n\tlet currentDir = from;\n\n\twhile (currentDir !== path.parse(currentDir).root) {\n\t\tif (fs.existsSync(path.join(currentDir, 'package.json'))) return currentDir;\n\t\tcurrentDir = path.dirname(currentDir);\n\t}\n\n\treturn null;\n}\n\n/**\n * Whether the project has a PocketBase backend at all.\n *\n * The `data` directory is the marker: `vela create` writes it for backend\n * templates and `vela bless` adds it to an existing project, while the static\n * template has none. Commands that would start or talk to PocketBase have to\n * check this first \u2014 a static project has no database, and therefore no\n * credentials to ask for.\n *\n * Kept in step with `Features.backend`, which is derived from the same marker.\n */\nexport function hasBackend(from: string = process.cwd()): boolean {\n\tconst root = findWorkspaceRoot(from);\n\treturn root !== null && fs.existsSync(path.join(root, DATA_DIR));\n}\n\n/**\n * Where this project keeps the state that is not source.\n *\n * The same directory on a server is `shared/pb_data`, which is the whole reason\n * `vela` puts it in the environment as `VELA_DATA_DIR` instead of letting an app\n * work it out from its own working directory. That one is the project root here\n * and a release directory there, so an app that derives the path lands its\n * database inside a release \u2014 where the next deploy leaves it behind and the\n * pruner eventually deletes it.\n */\nexport function localDataDir(from: string = process.cwd()): string {\n\treturn path.join(findWorkspaceRoot(from) ?? from, DATA_DIR);\n}\n\nexport async function getWorkspace(): Promise<Workspace> {\n\tconst workspaceRootDir = findWorkspaceRoot();\n\n\tif (!workspaceRootDir) {\n\t\tthrow new Error('Could not find workspace root (no package.json found)');\n\t}\n\n\tconst routesDir = path.join('src', 'routes');\n\tconst fullRoutesPath = path.join(workspaceRootDir, routesDir);\n\n\tif (!fs.existsSync(fullRoutesPath)) {\n\t\tthrow new Error('Could not find src/routes directory');\n\t}\n\n\tlet publicRoutesDir = path.join(routesDir, PUBLIC_DIR);\n\tif (!fs.existsSync(path.join(workspaceRootDir, publicRoutesDir))) {\n\t\tpublicRoutesDir = routesDir;\n\t}\n\n\tlet appRoutesDir: string | undefined;\n\tconst appRoutesPath = path.join(fullRoutesPath, APP_DIR);\n\tconst isAppMode = fs.existsSync(appRoutesPath);\n\tif (isAppMode) appRoutesDir = path.join(routesDir, APP_DIR);\n\n\tconst isPaymentsMode = fs.existsSync(\n\t\tpath.join(workspaceRootDir, routesDir, 'webhooks', 'stripe')\n\t);\n\n\tconst features = detectFeatures(workspaceRootDir, { isAppMode, isPaymentsMode });\n\n\treturn {\n\t\tworkspaceRootDir,\n\t\troutesDir,\n\t\tpublicRoutesDir,\n\t\tappRoutesDir,\n\t\tisAppMode,\n\t\tisPaymentsMode,\n\t\tfeatures\n\t};\n}\n\nfunction detectFeatures(\n\troot: string,\n\t{ isAppMode, isPaymentsMode }: { isAppMode: boolean; isPaymentsMode: boolean }\n): Features {\n\tconst has = (rel: string) => fs.existsSync(path.join(root, rel));\n\tconst pkg = readPackageJson(path.join(root, 'package.json'));\n\tconst hasDep = (name: string) => Boolean(pkg.dependencies?.[name] || pkg.devDependencies?.[name]);\n\n\treturn {\n\t\tauth: isAppMode,\n\t\tapi: has('src/routes/api'),\n\t\tapiKeys: has('src/routes/api/api-keys') || has('src/routes/(app)/api-keys'),\n\t\tbackend: has(DATA_DIR),\n\t\ti18n: has('wuchale.config.js') || hasDep('wuchale'),\n\t\tteams: has('src/routes/(app)/teams') || has('src/lib/teams'),\n\t\tpayments: isPaymentsMode,\n\t\tblog: hasDep('mdsvex'),\n\t\tcontentNegotiation: hasDep('sveltekit-negotiate'),\n\t\tcms: hasDep('@velastack/cms')\n\t};\n}\n", "export const DATA_DIR = 'data';\nexport const MIGRATIONS_DIR = 'migrations';\nexport const PUBLIC_DIR = '(public)';\nexport const APP_DIR = '(app)';\nexport const LEGAL_DIR = '(legal)';\nexport const API_URL = 'https://velastack.dev';\nexport const FIXTURE_PREFIX = 'vela';\n", "import fs from 'node:fs';\n\nexport type DepKind = 'dependencies' | 'devDependencies';\nconst DEP_KINDS: DepKind[] = ['dependencies', 'devDependencies'];\n\nexport interface MergeChange {\n\tkind: DepKind | 'scripts';\n\tname: string;\n\ttemplateValue: string;\n\tuserValue?: string;\n}\n\nexport interface MergeResult {\n\tmerged: Record<string, unknown>;\n\tadded: MergeChange[];\n\tconflicts: MergeChange[];\n\treplaced: MergeChange[];\n}\n\ntype PkgJson = Record<string, unknown> & {\n\tdependencies?: Record<string, string>;\n\tdevDependencies?: Record<string, string>;\n\tscripts?: Record<string, string>;\n};\n\nexport function mergePackageJson(user: PkgJson, template: PkgJson): MergeResult {\n\tconst merged: PkgJson = structuredClone(user);\n\tconst added: MergeChange[] = [];\n\tconst conflicts: MergeChange[] = [];\n\tconst replaced: MergeChange[] = [];\n\n\tfor (const kind of DEP_KINDS) {\n\t\tconst templateDeps = template[kind];\n\t\tif (!templateDeps) continue;\n\n\t\tconst userDeps = (merged[kind] ??= {}) as Record<string, string>;\n\t\tconst otherKind: DepKind = kind === 'dependencies' ? 'devDependencies' : 'dependencies';\n\t\tconst userOther = (user[otherKind] ?? {}) as Record<string, string>;\n\n\t\tfor (const [name, templateValue] of Object.entries(templateDeps)) {\n\t\t\tif (name in userDeps) {\n\t\t\t\tif (userDeps[name] !== templateValue) {\n\t\t\t\t\tconflicts.push({ kind, name, templateValue, userValue: userDeps[name] });\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (name in userOther) {\n\t\t\t\t// already pinned in the other bucket \u2014 leave it there, don't duplicate.\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tuserDeps[name] = templateValue;\n\t\t\tadded.push({ kind, name, templateValue });\n\t\t}\n\t}\n\n\tconst templateScripts = template.scripts;\n\tif (templateScripts) {\n\t\tconst userScripts = (merged.scripts ??= {}) as Record<string, string>;\n\t\tfor (const [name, templateValue] of Object.entries(templateScripts)) {\n\t\t\tconst existing = userScripts[name];\n\t\t\tif (existing === undefined) {\n\t\t\t\tuserScripts[name] = templateValue;\n\t\t\t\tadded.push({ kind: 'scripts', name, templateValue });\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (existing === templateValue) continue;\n\t\t\tuserScripts[name] = templateValue;\n\t\t\treplaced.push({ kind: 'scripts', name, templateValue, userValue: existing });\n\t\t}\n\t}\n\n\tfor (const kind of DEP_KINDS) {\n\t\tconst deps = merged[kind];\n\t\tif (deps) merged[kind] = sortKeys(deps);\n\t}\n\n\treturn { merged, added, conflicts, replaced };\n}\n\nexport function readPackageJson(path: string): PkgJson {\n\treturn JSON.parse(fs.readFileSync(path, 'utf8')) as PkgJson;\n}\n\n/**\n * Placeholders a template file carries so it stays valid on disk while still\n * being parameterized. `~TODO~` becomes the npm-safe package name and\n * `~APP_NAME~` the name the user actually typed; the CLI writes its own version\n * into `~VELA_VERSION~` so a generated project pins the exact CLI that produced\n * it, rather than whatever was hardcoded when the template was last edited.\n *\n * `~APP_NAME~` is escaped for a single-quoted JS string, which is the only place\n * a template uses it.\n */\nconst PACKAGE_NAME_PLACEHOLDER = /~TODO~/g;\nconst APP_NAME_PLACEHOLDER = /~APP_NAME~/g;\nconst CLI_VERSION_PLACEHOLDER = /~VELA_VERSION~/g;\n\nexport interface TemplateValues {\n\tappName: string;\n\tcliVersion: string;\n}\n\n/** Substitute template placeholders in a raw template source string. */\nexport function fillTemplatePlaceholders(raw: string, values: TemplateValues): string {\n\tconst packageName = toValidPackageName(values.appName);\n\tconst appName = escapeSingleQuoted(values.appName);\n\t// Function replacements: `$&` and friends in an app name are literal text.\n\treturn raw\n\t\t.replace(PACKAGE_NAME_PLACEHOLDER, () => packageName)\n\t\t.replace(APP_NAME_PLACEHOLDER, () => appName)\n\t\t.replace(CLI_VERSION_PLACEHOLDER, () => values.cliVersion);\n}\n\nfunction escapeSingleQuoted(value: string): string {\n\treturn value.replace(/\\\\/g, '\\\\\\\\').replace(/'/g, \"\\\\'\");\n}\n\nexport function readTemplatePackageJson(path: string, values: TemplateValues): PkgJson {\n\tconst raw = fillTemplatePlaceholders(fs.readFileSync(path, 'utf8'), values);\n\treturn JSON.parse(raw) as PkgJson;\n}\n\nexport function writePackageJson(path: string, pkg: Record<string, unknown>): void {\n\tfs.writeFileSync(path, JSON.stringify(pkg, null, '\\t') + '\\n');\n}\n\nexport function toValidPackageName(name: string): string {\n\treturn name\n\t\t.trim()\n\t\t.toLowerCase()\n\t\t.replace(/\\s+/g, '-')\n\t\t.replace(/^[._]/, '')\n\t\t.replace(/[^a-z0-9~.-]+/g, '-');\n}\n\nfunction sortKeys<T extends Record<string, string>>(obj: T): T {\n\tconst sorted: Record<string, string> = {};\n\tfor (const key of Object.keys(obj).sort()) sorted[key] = obj[key]!;\n\treturn sorted as T;\n}\n", "import fs from 'node:fs';\nimport path from 'node:path';\nimport process from 'node:process';\nimport * as v from 'valibot';\nimport { Command } from 'commander';\nimport * as p from '@clack/prompts';\nimport pc from 'picocolors';\nimport { resolveCommand } from 'package-manager-detector';\nimport { helpConfig } from '../lib/help.ts';\nimport { runCommand } from '../lib/run.ts';\nimport { parseOptions } from '../lib/options.ts';\nimport { DEFAULT_TEMPLATE, findProjectTemplate, projectTemplateNames } from '../lib/templates.ts';\nimport {\n\tAGENT_NAMES,\n\taddPnpmBuildDependencies,\n\tgetUserAgent,\n\tinstallDependencies,\n\tinstallOption,\n\tpackageManagerPrompt\n} from '../lib/package-manager.ts';\nimport pkg from '../../package.json' with { type: 'json' };\nimport { createSuperuser } from '../lib/pocketbase.ts';\nimport { writeEnvFile } from '../lib/env.ts';\nimport {\n\tmergePackageJson,\n\treadPackageJson,\n\treadTemplatePackageJson,\n\twritePackageJson\n} from '../lib/package-json.ts';\nimport {\n\tmergeGitignore,\n\tmergeSvelteConfig,\n\tmergeTsconfig,\n\tmergeViteConfig\n} from '../lib/config-merge.ts';\nimport { isVanillaRoutes } from '../lib/scaffold-detect.ts';\nimport { getWorkspace } from '../lib/workspace.ts';\nimport { reportResult } from '../lib/result-report.ts';\nimport { templateName } from '../lib/template-files.ts';\n\n/**\n * Only backend templates: blessing is what adds PocketBase to a project, so a\n * frontend-only template has nothing to bless a project with. Read per run so\n * the list can't drift from the templates directory.\n */\nfunction optionsSchema() {\n\tconst templates = projectTemplateNames({ backend: true });\n\treturn v.strictObject({\n\t\tinstall: v.union([v.boolean(), v.picklist(AGENT_NAMES)], 'must be a package manager'),\n\t\ttemplate: v.optional(v.picklist(templates, `must be one of: ${templates.join(', ')}`)),\n\t\temail: v.optional(v.pipe(v.string(), v.email('must be a valid email address'))),\n\t\tpassword: v.optional(v.pipe(v.string(), v.minLength(8, 'must be at least 8 characters long'))),\n\t\tskipRoutes: v.optional(v.boolean()),\n\t\tforceRoutes: v.optional(v.boolean())\n\t});\n}\ntype Options = v.InferOutput<ReturnType<typeof optionsSchema>>;\n\ninterface VelaFile {\n\t/** Path in the blessed project. */\n\tpath: string;\n\t/** What vela's copy carries, shown when the project already has its own. */\n\tadds: string;\n}\n\n/**\n * Files vela owns outright. A real project may already have some of them, so each\n * one records what would be missed by keeping the existing version.\n */\nconst VELA_ONLY_FILES: VelaFile[] = [\n\t{\n\t\tpath: 'src/hooks.server.ts',\n\t\tadds: 'the handlePocketbase hook \u2014 the backend is not wired up without it'\n\t},\n\t{ path: 'src/app.css', adds: \"vela's Tailwind imports and theme tokens\" },\n\t{ path: 'src/lib/index.ts', adds: 'a $lib placeholder comment' },\n\t{ path: 'src/lib/utils.ts', adds: 'the cn helper and the component type utilities' },\n\t{ path: 'components.json', adds: 'the shadcn-svelte config that `vela ui add` reads' },\n\t{ path: '.npmrc', adds: 'engine-strict=true' },\n\t{ path: '.ignore', adds: 'search ignores for generated files' }\n];\nconst VELA_ONLY_DIRS = ['src/lib/components', 'data', 'test', 'static'];\n\nexport const bless = new Command('bless')\n\t.description('upgrade a vanilla SvelteKit project into a VelaStack project')\n\t.argument('[path]', 'path to the existing SvelteKit project')\n\t.option('--template <type>', 'template to scaffold from', 'minimal')\n\t.option('--email <email>', 'email of the admin user')\n\t.option('--password <password>', 'password of the admin user')\n\t.option('--no-install', 'skip installing dependencies')\n\t.addOption(installOption)\n\t.option('--skip-routes', 'preserve src/routes even if it looks untouched')\n\t.option('--force-routes', 'replace src/routes with the vela template without detection')\n\t.configureHelp(helpConfig)\n\t.action((projectPath: string | undefined, rawOpts) => {\n\t\treturn runCommand(async () => {\n\t\t\tconst options = parseOptions(optionsSchema(), rawOpts);\n\t\t\tif (options.skipRoutes && options.forceRoutes) {\n\t\t\t\tthrow new Error('--skip-routes and --force-routes are mutually exclusive');\n\t\t\t}\n\t\t\tawait blessProject(projectPath, options);\n\t\t}, 'Failed to bless project.');\n\t});\n\nasync function blessProject(cwdArg: string | undefined, options: Options) {\n\tconst projectPath = cwdArg ? resolveProjectPath(cwdArg) : (await getWorkspace()).workspaceRootDir;\n\n\tassertNotAlreadyBlessed(projectPath);\n\n\tconst templateDir = findProjectTemplate(options.template ?? DEFAULT_TEMPLATE).dir;\n\n\tconst { email, password } = await p.group(\n\t\t{\n\t\t\temail: () => {\n\t\t\t\tif (options.email) return Promise.resolve(options.email);\n\t\t\t\treturn p.text({\n\t\t\t\t\tmessage: 'Enter an email for the admin user',\n\t\t\t\t\tdefaultValue: 'admin@example.com',\n\t\t\t\t\tvalidate: (value) =>\n\t\t\t\t\t\t!value ? 'Email is required' : !value.includes('@') ? 'Invalid email' : undefined\n\t\t\t\t});\n\t\t\t},\n\t\t\tpassword: () => {\n\t\t\t\tif (options.password) return Promise.resolve(options.password);\n\t\t\t\treturn p.password({\n\t\t\t\t\tmessage: 'Enter a password for the admin user (at least 8 characters)',\n\t\t\t\t\tvalidate: (value) =>\n\t\t\t\t\t\t!value\n\t\t\t\t\t\t\t? 'Password is required'\n\t\t\t\t\t\t\t: value.length < 8\n\t\t\t\t\t\t\t\t? 'Password must be at least 8 characters long'\n\t\t\t\t\t\t\t\t: undefined\n\t\t\t\t});\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tonCancel: () => {\n\t\t\t\tp.cancel('Operation cancelled.');\n\t\t\t\tprocess.exit(0);\n\t\t\t}\n\t\t}\n\t);\n\n\tmergeDependencies(projectPath, templateDir);\n\tcopyVelaOnlyFiles(templateDir, projectPath);\n\tmergeConfigFiles(projectPath);\n\tmergeAppDts(templateDir, projectPath);\n\tmaybeReplaceRoutes(projectPath, templateDir, options);\n\n\tp.log.success('Vela files in place');\n\n\tlet packageManager: ReturnType<typeof getUserAgent> | undefined;\n\tif (options.install !== false) {\n\t\tconst pm =\n\t\t\ttypeof options.install === 'string'\n\t\t\t\t? options.install\n\t\t\t\t: await packageManagerPrompt(projectPath);\n\n\t\tif (pm) {\n\t\t\taddPnpmBuildDependencies(projectPath, pm, ['esbuild', 'pocketbase-server']);\n\t\t\tawait installDependencies(pm, projectPath);\n\t\t\tpackageManager = pm;\n\t\t}\n\t}\n\n\tp.log.step('Initializing PocketBase...');\n\tawait createSuperuser(projectPath, email, password);\n\n\twriteEnvFile(\n\t\tprojectPath,\n\t\t{\n\t\t\tPOCKETBASE_SUPERUSER_EMAIL: email,\n\t\t\tPOCKETBASE_SUPERUSER_PASSWORD: password\n\t\t},\n\t\t['PocketBase superuser credentials \u2014 used by `vela` commands']\n\t);\n\n\tp.log.success('PocketBase initialized');\n\n\tprintNextSteps(projectPath, packageManager);\n}\n\nfunction resolveProjectPath(cwdArg: string): string {\n\tconst projectPath = path.resolve(cwdArg);\n\tif (!fs.existsSync(projectPath)) {\n\t\tthrow new Error(`Path does not exist: ${projectPath}`);\n\t}\n\tif (!fs.existsSync(path.join(projectPath, 'package.json'))) {\n\t\tthrow new Error(`No package.json found at ${projectPath}`);\n\t}\n\tif (!fs.existsSync(path.join(projectPath, 'src', 'routes'))) {\n\t\tthrow new Error(`No src/routes directory found at ${projectPath}`);\n\t}\n\treturn projectPath;\n}\n\nfunction assertNotAlreadyBlessed(projectPath: string) {\n\tconst hooksPath = path.join(projectPath, 'src', 'hooks.server.ts');\n\tif (!fs.existsSync(hooksPath)) return;\n\tconst content = fs.readFileSync(hooksPath, 'utf8');\n\tif (content.includes('@velastack/pocketbase')) {\n\t\tthrow new Error(\n\t\t\t'This project already looks blessed (src/hooks.server.ts imports @velastack/pocketbase). Run `vela sync` instead.'\n\t\t);\n\t}\n}\n\nfunction mergeDependencies(projectPath: string, templateDir: string) {\n\tconst userPkgPath = path.join(projectPath, 'package.json');\n\tconst templatePkgPath = path.join(templateDir, 'package.template.json');\n\n\tconst userPkg = readPackageJson(userPkgPath);\n\tconst appName = typeof userPkg.name === 'string' ? userPkg.name : 'sveltekit';\n\tconst templatePkg = readTemplatePackageJson(templatePkgPath, {\n\t\tappName,\n\t\tcliVersion: pkg.version\n\t});\n\n\tconst { merged, added, conflicts, replaced } = mergePackageJson(userPkg, templatePkg);\n\twritePackageJson(userPkgPath, merged);\n\n\tif (added.length > 0) {\n\t\tp.log.info(\n\t\t\t`Added ${added.length} entries to package.json (${summarize(added.map((c) => c.name))}).`\n\t\t);\n\t}\n\tif (replaced.length > 0) {\n\t\tconst lines = replaced.map(\n\t\t\t(c) =>\n\t\t\t\t` script ${pc.bold(c.name)}: ${pc.gray(c.userValue ?? '')} \u2192 ${pc.cyan(c.templateValue)}`\n\t\t);\n\t\tp.log.info(`Updated ${replaced.length} script(s):\\n${lines.join('\\n')}`);\n\t}\n\tif (conflicts.length > 0) {\n\t\tconst lines = conflicts.map(\n\t\t\t(c) =>\n\t\t\t\t` dep ${pc.bold(c.name)}: kept ${pc.cyan(c.userValue ?? '')} (template wants ${pc.gray(c.templateValue)})`\n\t\t);\n\t\tp.log.warn(`Kept ${conflicts.length} dependency version(s) on conflict:\\n${lines.join('\\n')}`);\n\t}\n}\n\nfunction copyVelaOnlyFiles(templateDir: string, projectPath: string) {\n\tconst kept: VelaFile[] = [];\n\n\tfor (const file of VELA_ONLY_FILES) {\n\t\tconst src = path.join(templateDir, templateName(file.path));\n\t\tconst dest = path.join(projectPath, file.path);\n\t\tif (!fs.existsSync(src)) continue;\n\t\tif (fs.existsSync(dest)) {\n\t\t\tkept.push(file);\n\t\t\tcontinue;\n\t\t}\n\t\tfs.mkdirSync(path.dirname(dest), { recursive: true });\n\t\tfs.copyFileSync(src, dest);\n\t}\n\n\treportKeptFiles(kept);\n\n\tfor (const rel of VELA_ONLY_DIRS) {\n\t\tconst src = path.join(templateDir, rel);\n\t\tconst dest = path.join(projectPath, rel);\n\t\tif (!fs.existsSync(src)) continue;\n\t\tcopyDirShallow(src, dest);\n\t}\n}\n\n/**\n * Keeping a file the project already had is the expected outcome of blessing a\n * real project \u2014 but vela's version carries things the generators rely on, so\n * name what was skipped instead of leaving the difference invisible.\n */\nfunction reportKeptFiles(kept: VelaFile[]) {\n\tif (kept.length === 0) return;\n\tconst padding = Math.max(...kept.map((f) => f.path.length));\n\tconst lines = kept.map((f) => ` ${pc.bold(f.path.padEnd(padding))} ${pc.gray(f.adds)}`);\n\tp.log.info(\n\t\t`Kept ${kept.length} file(s) you already had. Merge by hand to pick up what vela adds:\\n${lines.join('\\n')}`\n\t);\n}\n\nfunction copyDirShallow(src: string, dest: string) {\n\tfs.mkdirSync(dest, { recursive: true });\n\tfor (const entry of fs.readdirSync(src, { withFileTypes: true })) {\n\t\tif (entry.name === '.DS_Store') continue;\n\t\tconst srcChild = path.join(src, entry.name);\n\t\tconst destChild = path.join(dest, entry.name);\n\t\tif (entry.isDirectory()) {\n\t\t\tcopyDirShallow(srcChild, destChild);\n\t\t} else if (entry.isFile() && !fs.existsSync(destChild)) {\n\t\t\tfs.copyFileSync(srcChild, destChild);\n\t\t}\n\t}\n}\n\nfunction mergeConfigFiles(projectPath: string) {\n\tconst runes = mergeSvelteConfig(projectPath);\n\tconst outcomes = [\n\t\t[runes.file ?? 'svelte.config', runes],\n\t\t['vite.config.ts', mergeViteConfig(path.join(projectPath, 'vite.config.ts'))],\n\t\t['tsconfig.json', mergeTsconfig(path.join(projectPath, 'tsconfig.json'))],\n\t\t['.gitignore', mergeGitignore(path.join(projectPath, '.gitignore'))]\n\t] as const;\n\n\tfor (const [name, outcome] of outcomes) {\n\t\tif (outcome.applied) {\n\t\t\tp.log.info(`${name}: ${outcome.reason}`);\n\t\t\tcontinue;\n\t\t}\n\t\tif (outcome.snippet) {\n\t\t\tp.log.warn(\n\t\t\t\t`${name}: ${outcome.reason}\\n${pc.gray('Add this manually:')}\\n${pc.cyan(outcome.snippet)}`\n\t\t\t);\n\t\t}\n\t}\n}\n\nfunction mergeAppDts(templateDir: string, projectPath: string) {\n\tconst dest = path.join(projectPath, 'src', 'app.d.ts');\n\tconst templateFile = path.join(templateDir, 'src', 'app.d.ts');\n\tif (!fs.existsSync(dest)) {\n\t\tif (!fs.existsSync(templateFile)) return;\n\t\tfs.copyFileSync(templateFile, dest);\n\t\treturn;\n\t}\n\tconst current = fs.readFileSync(dest, 'utf8');\n\tif (current.includes('namespace Superforms')) return;\n\tconst block = `\\tnamespace Superforms {\\n\\t\\ttype Message = {\\n\\t\\t\\ttype: 'error' | 'success';\\n\\t\\t\\ttext: string;\\n\\t\\t};\\n\\t}\\n`;\n\tconst match = current.match(/declare global\\s*\\{\\s*\\n/);\n\tif (!match || match.index === undefined) {\n\t\tp.log.warn(\n\t\t\t`src/app.d.ts: non-standard shape \u2014 add this namespace manually:\\n${pc.cyan(block)}`\n\t\t);\n\t\treturn;\n\t}\n\tconst insertAt = match.index + match[0].length;\n\tconst updated = current.slice(0, insertAt) + block + current.slice(insertAt);\n\tfs.writeFileSync(dest, updated);\n}\n\nfunction maybeReplaceRoutes(projectPath: string, templateDir: string, options: Options) {\n\tif (options.skipRoutes) {\n\t\tp.log.info('Skipping src/routes (--skip-routes).');\n\t\treturn;\n\t}\n\n\tif (!options.forceRoutes && !isVanillaRoutes(projectPath)) {\n\t\tp.log.info('Leaving src/routes alone (looks customized).');\n\t\treturn;\n\t}\n\n\tconst target = path.join(projectPath, 'src', 'routes');\n\tfs.rmSync(target, { recursive: true, force: true });\n\tconst src = path.join(templateDir, 'src', 'routes');\n\tfs.cpSync(src, target, {\n\t\trecursive: true,\n\t\tfilter: (s) => path.basename(s) !== '.DS_Store'\n\t});\n\tp.log.success('Replaced src/routes with the vela template.');\n}\n\nfunction summarize(names: string[]): string {\n\tif (names.length <= 4) return names.join(', ');\n\treturn `${names.slice(0, 3).join(', ')}, and ${names.length - 3} more`;\n}\n\nfunction printNextSteps(projectPath: string, packageManager: ReturnType<typeof getUserAgent>) {\n\tconst relative = path.relative(process.cwd(), projectPath);\n\tconst pm = packageManager ?? getUserAgent() ?? 'npm';\n\n\tconst nextSteps: string[] = [];\n\tif (relative !== '') {\n\t\tconst hasSpaces = relative.includes(' ');\n\t\tnextSteps.push(`\\`cd ${hasSpaces ? `\"${relative}\"` : relative}\\``);\n\t}\n\tconst runDev = resolveCommand(pm, 'run', ['dev', '--open']);\n\tif (runDev) {\n\t\tnextSteps.push(\n\t\t\t`\\`${runDev.command} ${runDev.args.join(' ')}\\` to start the dev server (Ctrl-C to stop)`\n\t\t);\n\t}\n\tnextSteps.push(\n\t\t'Run `vela enable auth` to layer on sign-in flows, or `vela generate scaffold <model>` to scaffold a CRUD page.'\n\t);\n\tnextSteps.push('Stuck? Visit https://docs.velastack.dev');\n\n\treportResult({\n\t\tsummary: `Blessed project at ${projectPath}.`,\n\t\tnextSteps\n\t});\n}\n", "import * as v from 'valibot';\n\n/**\n * Validate commander's raw options against a schema, reporting failures as a\n * plain `Error`.\n *\n * `v.parse` throws a `ValiError`, and commander invokes actions outside any\n * handler of ours, so calling it directly puts a valibot stack trace in front of\n * a user who merely mistyped a flag. Called inside `runCommand`, this instead\n * surfaces every bad flag through the CLI's normal error reporting.\n */\nexport function parseOptions<S extends v.GenericSchema>(schema: S, raw: unknown): v.InferOutput<S> {\n\tconst result = v.safeParse(schema, raw);\n\tif (result.success) return result.output;\n\tconst seen = new Set<string>();\n\tconst lines = result.issues.map(describeIssue).filter((line) => {\n\t\tif (seen.has(line)) return false;\n\t\tseen.add(line);\n\t\treturn true;\n\t});\n\tthrow new Error(lines.join('\\n'));\n}\n\nfunction describeIssue(issue: v.BaseIssue<unknown>): string {\n\tconst key = optionKey(issue);\n\treturn key ? `--${toFlag(key)}: ${issue.message}` : issue.message;\n}\n\n/** The option a nested issue belongs to \u2014 the first string key on its path. */\nfunction optionKey(issue: v.BaseIssue<unknown>): string | undefined {\n\tfor (const item of issue.path ?? []) {\n\t\tif (typeof item.key === 'string') return item.key;\n\t}\n\treturn undefined;\n}\n\n/** `skipRoutes` is what valibot sees; `--skip-routes` is what the user typed. */\nfunction toFlag(key: string): string {\n\treturn key.replace(/[A-Z]/g, (char) => `-${char.toLowerCase()}`);\n}\n", "import fs from 'node:fs';\nimport path from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\n/** Marks a directory under `templates/` as something `vela create` can scaffold. */\nexport const TEMPLATE_MANIFEST = 'template.json';\n\nexport const DEFAULT_TEMPLATE = 'minimal';\n\nexport interface ProjectTemplate {\n\t/** Directory name under `templates/`, and the value `--template` takes. */\n\tname: string;\n\tdescription: string;\n\t/**\n\t * Whether the template scaffolds a PocketBase backend. A template without one\n\t * is a frontend-only project: no superuser, no `.env`, no `vela dev`/`sync`.\n\t */\n\tbackend: boolean;\n\tdir: string;\n}\n\nlet cached: ProjectTemplate[] | undefined;\n\n/**\n * The packaged `templates/` directory, found by walking up from this module so\n * it resolves the same whether the CLI runs from `src/` or from `dist/`.\n *\n * A bare `templates` name is too common to match on alone, so a candidate only\n * counts once it holds at least one template manifest.\n */\nexport function templatesDir(): string {\n\tlet dir = path.dirname(fileURLToPath(import.meta.url));\n\tconst { root } = path.parse(dir);\n\twhile (dir !== root) {\n\t\tconst candidate = path.join(dir, 'templates');\n\t\tif (holdsManifest(candidate)) return candidate;\n\t\tdir = path.dirname(dir);\n\t}\n\tthrow new Error('Could not locate the templates directory');\n}\n\nfunction holdsManifest(dir: string): boolean {\n\tif (!fs.existsSync(dir)) return false;\n\treturn fs\n\t\t.readdirSync(dir, { withFileTypes: true })\n\t\t.some(\n\t\t\t(entry) => entry.isDirectory() && fs.existsSync(path.join(dir, entry.name, TEMPLATE_MANIFEST))\n\t\t);\n}\n\n/**\n * Every scaffoldable template, read from disk rather than hardcoded so adding a\n * template directory is all it takes to make `--template` accept it.\n */\nexport function listProjectTemplates(): ProjectTemplate[] {\n\tif (cached) return cached;\n\tconst root = templatesDir();\n\tcached = fs\n\t\t.readdirSync(root, { withFileTypes: true })\n\t\t.filter((entry) => entry.isDirectory())\n\t\t.map((entry) => readManifest(root, entry.name))\n\t\t.filter((template): template is ProjectTemplate => template !== undefined)\n\t\t.sort((a, b) => a.name.localeCompare(b.name));\n\treturn cached;\n}\n\n/** Template names accepted by `--template`, in the order they should be listed. */\nexport function projectTemplateNames(options: { backend?: boolean } = {}): string[] {\n\tconst templates = listProjectTemplates();\n\tconst matching =\n\t\toptions.backend === undefined\n\t\t\t? templates\n\t\t\t: templates.filter((template) => template.backend === options.backend);\n\treturn matching.map((template) => template.name);\n}\n\nexport function findProjectTemplate(name: string): ProjectTemplate {\n\tconst template = listProjectTemplates().find((candidate) => candidate.name === name);\n\tif (!template) throw new Error(`Template not found: ${name}`);\n\treturn template;\n}\n\nfunction readManifest(root: string, name: string): ProjectTemplate | undefined {\n\tconst manifestPath = path.join(root, name, TEMPLATE_MANIFEST);\n\tif (!fs.existsSync(manifestPath)) return undefined;\n\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));\n\t} catch (e) {\n\t\tthrow new Error(\n\t\t\t`Template ${name} has an unreadable ${TEMPLATE_MANIFEST}: ${(e as Error).message}`\n\t\t);\n\t}\n\n\tconst manifest = parsed as { description?: unknown; backend?: unknown };\n\tif (typeof manifest.description !== 'string' || typeof manifest.backend !== 'boolean') {\n\t\tthrow new Error(\n\t\t\t`Template ${name} has an invalid ${TEMPLATE_MANIFEST} (needs description and backend)`\n\t\t);\n\t}\n\n\treturn {\n\t\tname,\n\t\tdescription: manifest.description,\n\t\tbackend: manifest.backend,\n\t\tdir: path.join(root, name)\n\t};\n}\n", "import fs from 'node:fs';\nimport path from 'node:path';\nimport process from 'node:process';\nimport { exec } from 'tinyexec';\nimport { Option } from 'commander';\nimport * as p from '@clack/prompts';\nimport {\n\tAGENTS,\n\tCOMMANDS,\n\tconstructCommand,\n\tdetect,\n\ttype AgentName\n} from 'package-manager-detector';\n\nexport const AGENT_NAMES = AGENTS.filter((agent): agent is AgentName => !agent.includes('@'));\n\nexport const installOption = new Option(\n\t'--install <package-manager>',\n\t'installs dependencies with a specified package manager'\n).choices(AGENT_NAMES);\n\nexport function getUserAgent(): AgentName | undefined {\n\tconst userAgent = process.env.npm_config_user_agent;\n\tif (!userAgent) return undefined;\n\tconst pmSpec = userAgent.split(' ')[0]!;\n\tconst separatorPos = pmSpec.lastIndexOf('/');\n\tconst name = pmSpec.substring(0, separatorPos) as AgentName;\n\treturn AGENTS.includes(name) ? name : undefined;\n}\n\nexport async function packageManagerPrompt(cwd: string): Promise<AgentName | undefined> {\n\tconst detected = await detect({ cwd });\n\tconst agent = detected?.name ?? getUserAgent();\n\n\tif (!process.stdout.isTTY) return agent;\n\n\tconst options: Array<{ value: AgentName | undefined; label: AgentName | 'None' }> = [\n\t\t{ label: 'None', value: undefined },\n\t\t...AGENT_NAMES.map((pm) => ({ value: pm, label: pm }))\n\t];\n\n\tconst pm = await p.select({\n\t\tmessage: 'Which package manager do you want to install dependencies with?',\n\t\toptions,\n\t\tinitialValue: agent\n\t});\n\tif (p.isCancel(pm)) {\n\t\tp.cancel('Operation cancelled.');\n\t\tprocess.exit(1);\n\t}\n\treturn pm;\n}\n\nexport async function installDependencies(agent: AgentName, cwd: string): Promise<void> {\n\tconst task = p.taskLog({\n\t\ttitle: `Installing dependencies with ${agent}...`,\n\t\tlimit: Math.ceil(process.stdout.rows / 2),\n\t\tspacing: 0,\n\t\tretainLog: true\n\t});\n\n\ttry {\n\t\tconst { command, args } = constructCommand(COMMANDS[agent].install, [])!;\n\t\tconst proc = exec(command, args, {\n\t\t\tnodeOptions: { cwd, stdio: 'pipe' },\n\t\t\tthrowOnError: true\n\t\t});\n\n\t\tproc.process?.stdout?.on('data', (data) => task.message(data.toString(), { raw: true }));\n\t\tproc.process?.stderr?.on('data', (data) => task.message(data.toString(), { raw: true }));\n\n\t\tawait proc;\n\t\ttask.success('Successfully installed dependencies');\n\t} catch {\n\t\ttask.error('Failed to install dependencies');\n\t\tp.cancel('Operation failed.');\n\t\tprocess.exit(2);\n\t}\n}\n\nexport function addPnpmBuildDependencies(\n\tcwd: string,\n\tpackageManager: AgentName | null | undefined,\n\tallowedPackages: string[]\n) {\n\tif (!packageManager || packageManager !== 'pnpm') return;\n\n\tconst pkgPath = path.join(cwd, 'package.json');\n\tif (!fs.existsSync(pkgPath)) return;\n\n\tconst pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'));\n\tpkg.pnpm ??= {};\n\tpkg.pnpm.onlyBuiltDependencies ??= [];\n\tfor (const name of allowedPackages) {\n\t\tif (!pkg.pnpm.onlyBuiltDependencies.includes(name)) {\n\t\t\tpkg.pnpm.onlyBuiltDependencies.push(name);\n\t\t}\n\t}\n\tfs.writeFileSync(pkgPath, JSON.stringify(pkg, null, '\\t') + '\\n');\n}\n", "import fs from 'node:fs';\nimport net from 'node:net';\nimport path from 'node:path';\nimport process from 'node:process';\nimport { createRequire } from 'node:module';\nimport { spawn, type ChildProcess } from 'node:child_process';\nimport PocketBase from 'pocketbase';\nimport { detect } from 'package-manager-detector';\nimport { resolveCommand } from 'package-manager-detector/commands';\nimport { x } from 'tinyexec';\nimport { DATA_DIR, MIGRATIONS_DIR } from './constants.ts';\n\nexport function findFreePort(host = 'localhost'): Promise<number> {\n\treturn new Promise((resolve, reject) => {\n\t\tconst server = net.createServer();\n\t\tserver.unref();\n\t\tserver.once('error', reject);\n\t\tserver.listen(0, host, () => {\n\t\t\tconst addr = server.address() as net.AddressInfo | null;\n\t\t\tserver.close((err) => {\n\t\t\t\tif (err) reject(err);\n\t\t\t\telse if (!addr) reject(new Error('Failed to obtain a free port'));\n\t\t\t\telse resolve(addr.port);\n\t\t\t});\n\t\t});\n\t});\n}\n\nfunction waitForReadyOrExit(proc: ChildProcess, url: string, maxAttempts = 40): Promise<void> {\n\treturn new Promise((resolve, reject) => {\n\t\tlet settled = false;\n\t\tconst onExit = (code: number | null, signal: NodeJS.Signals | null) => {\n\t\t\tif (settled) return;\n\t\t\tsettled = true;\n\t\t\treject(\n\t\t\t\tnew Error(`PocketBase exited before becoming healthy (code=${code}, signal=${signal})`)\n\t\t\t);\n\t\t};\n\t\tproc.once('exit', onExit);\n\n\t\tlet attempts = 0;\n\t\tconst check = async () => {\n\t\t\tif (settled) return;\n\t\t\tattempts++;\n\t\t\ttry {\n\t\t\t\tconst r = await fetch(`${url}/api/health`);\n\t\t\t\tif (r.status === 200) {\n\t\t\t\t\tif (settled) return;\n\t\t\t\t\tsettled = true;\n\t\t\t\t\tproc.removeListener('exit', onExit);\n\t\t\t\t\tresolve();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t} catch {\n\t\t\t\t/* retry */\n\t\t\t}\n\t\t\tif (attempts >= maxAttempts) {\n\t\t\t\tif (settled) return;\n\t\t\t\tsettled = true;\n\t\t\t\tproc.removeListener('exit', onExit);\n\t\t\t\treject(new Error(`Timed out waiting for health at ${url}`));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tsetTimeout(check, 250);\n\t\t};\n\t\tcheck();\n\t});\n}\n\nexport interface StartPocketbaseServeOptions {\n\tdataDir: string;\n\tmigrationsDir: string;\n\thooksDir?: string;\n\tdev?: boolean;\n\tstdio?: 'inherit' | 'pipe' | 'ignore';\n\thost?: string;\n\tmaxAttempts?: number;\n}\n\nexport async function startPocketbaseServe(opts: StartPocketbaseServeOptions): Promise<{\n\tproc: ChildProcess;\n\tport: number;\n\turl: string;\n}> {\n\tconst { getBinaryPath } = await import('pocketbase-server');\n\tconst binaryPath = getBinaryPath();\n\tconst host = opts.host ?? 'localhost';\n\tconst stdio = opts.stdio ?? 'inherit';\n\tconst maxAttempts = opts.maxAttempts ?? 5;\n\n\tlet lastErr: unknown;\n\tfor (let attempt = 1; attempt <= maxAttempts; attempt++) {\n\t\tconst port = await findFreePort(host);\n\t\tconst args = [\n\t\t\t'serve',\n\t\t\t'--dir',\n\t\t\topts.dataDir,\n\t\t\t'--migrationsDir',\n\t\t\topts.migrationsDir,\n\t\t\t...(opts.hooksDir ? ['--hooksDir', opts.hooksDir] : []),\n\t\t\t...(opts.dev ? ['--dev'] : []),\n\t\t\t'--http',\n\t\t\t`${host}:${port}`\n\t\t];\n\t\tconst proc = spawn(binaryPath, args, { stdio });\n\n\t\ttry {\n\t\t\tawait waitForReadyOrExit(proc, `http://${host}:${port}`);\n\t\t\treturn { proc, port, url: `http://${host}:${port}` };\n\t\t} catch (err) {\n\t\t\tlastErr = err;\n\t\t\tif (proc.exitCode === null && proc.signalCode === null) {\n\t\t\t\tawait new Promise<void>((resolve) => {\n\t\t\t\t\tproc.once('exit', () => resolve());\n\t\t\t\t\tproc.kill();\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}\n\tthrow lastErr instanceof Error ? lastErr : new Error('Failed to start PocketBase');\n}\n\nexport async function authWithRetries(\n\tpb: PocketBase,\n\temail: string,\n\tpassword: string,\n\tattempts = 3\n) {\n\tfor (let attempt = 1; attempt <= attempts; attempt++) {\n\t\ttry {\n\t\t\tawait pb.collection('_superusers').authWithPassword(email, password);\n\t\t\treturn;\n\t\t} catch (e) {\n\t\t\tif (attempt === attempts) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t'Failed to authenticate with PocketBase. Check your superuser credentials.'\n\t\t\t\t);\n\t\t\t}\n\t\t\tawait new Promise((r) => setTimeout(r, 100));\n\t\t}\n\t}\n}\n\nexport function getPocketbaseMetadata(\n\tcwd: string\n): { pocketbaseUrl: string; vitePort: number; viteHost: string } | null {\n\tconst metadataPath = path.join(cwd, 'node_modules', '.vite', '_pocketbase_metadata.json');\n\tif (fs.existsSync(metadataPath)) {\n\t\treturn JSON.parse(fs.readFileSync(metadataPath, 'utf8'));\n\t}\n\treturn null;\n}\n\nasync function execPackageBin(cwd: string, args: string[], stdio: 'inherit' | 'pipe' = 'pipe') {\n\tconst packageManager = (await detect({ cwd }))?.name ?? 'npm';\n\tconst resolved = resolveCommand(packageManager, 'execute', args);\n\tif (!resolved) throw new Error(`Could not resolve command for ${packageManager}`);\n\tconst { command, args: resolvedArgs } = resolved;\n\tif (packageManager === 'npm') resolvedArgs.unshift('--yes');\n\treturn x(command, resolvedArgs, { nodeOptions: { cwd, stdio }, throwOnError: true });\n}\n\nexport async function withPocketbase(\n\tcwd: string,\n\tfn: (pb: PocketBase) => Promise<void>,\n\tcreds?: { email: string; password: string }\n) {\n\tconst dir = path.join(cwd, DATA_DIR);\n\tconst migrationsDir = path.join(cwd, MIGRATIONS_DIR);\n\tconst host = 'localhost';\n\tconst email = creds?.email ?? process.env.POCKETBASE_SUPERUSER_EMAIL!;\n\tconst password = creds?.password ?? process.env.POCKETBASE_SUPERUSER_PASSWORD!;\n\n\tif (!fs.existsSync(dir)) {\n\t\tthrow new Error('PocketBase data directory does not exist');\n\t}\n\n\tconst metadata = getPocketbaseMetadata(cwd);\n\tif (metadata?.pocketbaseUrl) {\n\t\tconst pb = new PocketBase(metadata.pocketbaseUrl);\n\t\tawait authWithRetries(pb, email, password);\n\t\tawait fn(pb);\n\t\treturn;\n\t}\n\n\tconst { proc, url } = await startPocketbaseServe({\n\t\tdataDir: dir,\n\t\tmigrationsDir,\n\t\thost,\n\t\tstdio: 'ignore'\n\t});\n\n\ttry {\n\t\tconst pb = new PocketBase(url);\n\t\tawait authWithRetries(pb, email, password);\n\t\tawait fn(pb);\n\t} finally {\n\t\tproc.kill();\n\t}\n}\n\nexport async function createSuperuser(cwd: string, email: string, password: string): Promise<void> {\n\tconst dir = path.join(cwd, DATA_DIR);\n\tconst migrationsDir = path.join(cwd, MIGRATIONS_DIR);\n\tfs.mkdirSync(dir, { recursive: true });\n\tfs.mkdirSync(migrationsDir, { recursive: true });\n\n\tawait execPackageBin(\n\t\tcwd,\n\t\t[\n\t\t\t'pocketbase-server',\n\t\t\t'--dir',\n\t\t\tdir,\n\t\t\t'--migrationsDir',\n\t\t\tmigrationsDir,\n\t\t\t'superuser',\n\t\t\t'create',\n\t\t\temail,\n\t\t\tpassword\n\t\t],\n\t\t'pipe'\n\t);\n}\n\nexport async function launchPocketbase(\n\tcwd: string,\n\t{\n\t\tdir,\n\t\tmigrationsDir,\n\t\thooksDir,\n\t\temail,\n\t\tpassword\n\t}: { dir: string; migrationsDir: string; hooksDir?: string; email: string; password: string }\n) {\n\tconst host = 'localhost';\n\tfs.mkdirSync(dir, { recursive: true });\n\tfs.mkdirSync(migrationsDir, { recursive: true });\n\n\tawait execPackageBin(\n\t\tcwd,\n\t\t[\n\t\t\t'pocketbase-server',\n\t\t\t'--dir',\n\t\t\tdir,\n\t\t\t'--migrationsDir',\n\t\t\tmigrationsDir,\n\t\t\t'superuser',\n\t\t\t'create',\n\t\t\temail,\n\t\t\tpassword\n\t\t],\n\t\t'pipe'\n\t);\n\n\tawait execPackageBin(\n\t\tcwd,\n\t\t['pocketbase-server', '--dir', dir, '--migrationsDir', migrationsDir, 'migrate', 'up'],\n\t\t'inherit'\n\t);\n\n\tconst { proc, url } = await startPocketbaseServe({\n\t\tdataDir: dir,\n\t\tmigrationsDir,\n\t\thooksDir,\n\t\thost,\n\t\tstdio: 'pipe'\n\t});\n\n\treturn {\n\t\tstop: () => proc.kill(),\n\t\turl\n\t};\n}\n\n/**\n * The PocketBase version this CLI develops against.\n *\n * Servers install the same build, so a deployed app and a developer's machine\n * never differ on the database engine.\n */\nexport function pocketbaseVersion(): string {\n\tconst require = createRequire(import.meta.url);\n\tconst pkg = require('pocketbase-server/package.json') as { version: string };\n\treturn pkg.version;\n}\n\n/**\n * Make sure the configured superuser exists in the local database.\n *\n * A vela app authenticates as its superuser while rendering, so a build needs\n * one to exist. On a developer's machine it always does; on a fresh checkout \u2014\n * CI, a new clone, a wiped `data/` \u2014 the database is empty and the build fails\n * at prerendering with \"invalid login credentials\". `upsert` is idempotent, so\n * this is a no-op everywhere else.\n */\nexport async function ensureSuperuser(cwd: string): Promise<void> {\n\tconst email = process.env.POCKETBASE_SUPERUSER_EMAIL;\n\tconst password = process.env.POCKETBASE_SUPERUSER_PASSWORD;\n\tif (!email || !password) return;\n\n\tconst dir = path.join(cwd, DATA_DIR);\n\tif (!fs.existsSync(dir)) return;\n\n\tconst { getBinaryPath } = await import('pocketbase-server');\n\tawait x(\n\t\tgetBinaryPath(),\n\t\t[\n\t\t\t'--dir',\n\t\t\tdir,\n\t\t\t'--migrationsDir',\n\t\t\tpath.join(cwd, MIGRATIONS_DIR),\n\t\t\t'superuser',\n\t\t\t'upsert',\n\t\t\temail,\n\t\t\tpassword\n\t\t],\n\t\t{ nodeOptions: { cwd, stdio: 'ignore' } }\n\t);\n}\n", "import fs from 'node:fs';\nimport path from 'node:path';\n\nexport function addEnvVar(content: string, key: string, value: string): string {\n\tif (content.includes(`${key}=`)) return content;\n\treturn appendLine(content, `${key}=${value}`);\n}\n\nexport function addEnvComment(content: string, comment: string): string {\n\tconst commented = `# ${comment}`;\n\tif (content.includes(commented)) return content;\n\treturn appendLine(content, commented);\n}\n\nfunction appendLine(existing: string, line: string): string {\n\tconst withNewline = !existing.length || existing.endsWith('\\n') ? existing : existing + '\\n';\n\treturn withNewline + line + '\\n';\n}\n\nexport function writeEnvFile(\n\tcwd: string,\n\tvars: Record<string, string>,\n\tcomments: string[] = []\n): void {\n\tconst envPath = path.join(cwd, '.env');\n\tlet content = fs.existsSync(envPath) ? fs.readFileSync(envPath, 'utf8') : '';\n\tfor (const comment of comments) content = addEnvComment(content, comment);\n\tfor (const [key, value] of Object.entries(vars)) content = addEnvVar(content, key, value);\n\tfs.writeFileSync(envPath, content);\n}\n\n/**\n * Set a value in a `.env` file, in place.\n *\n * `addEnvVar` above is append-only and silently does nothing when the key is\n * already present, which is right for scaffolding and wrong for `vela env set`.\n * This rewrites the existing line where there is one and appends otherwise, so\n * the comments, ordering and spacing a person put in the file survive being\n * edited by the CLI.\n */\nexport function upsertEnvVar(content: string, key: string, value: string): string {\n\tconst line = `${key}=${quoteEnvValue(value)}`;\n\tconst pattern = keyPattern(key);\n\n\tlet replaced = false;\n\tconst lines = content.split('\\n').map((existing) => {\n\t\tif (replaced || !pattern.test(existing)) return existing;\n\t\treplaced = true;\n\t\t// `export KEY=` is valid dotenv, and dropping the prefix would change how\n\t\t// the file behaves when it is sourced by a shell.\n\t\treturn existing.trimStart().startsWith('export ') ? `export ${line}` : line;\n\t});\n\n\treturn replaced ? lines.join('\\n') : appendLine(content, line);\n}\n\n/** Remove a key from a `.env` file, leaving the rest of it alone. */\nexport function removeEnvVar(content: string, key: string): string {\n\tconst pattern = keyPattern(key);\n\tconst lines = content.split('\\n');\n\tconst kept = lines.filter((line) => !pattern.test(line));\n\tif (kept.length === lines.length) return content;\n\treturn kept.join('\\n');\n}\n\nexport function hasEnvVar(content: string, key: string): boolean {\n\tconst pattern = keyPattern(key);\n\treturn content.split('\\n').some((line) => pattern.test(line));\n}\n\nfunction keyPattern(key: string): RegExp {\n\treturn new RegExp(`^\\\\s*(?:export\\\\s+)?${escapeRegExp(key)}\\\\s*=`);\n}\n\nfunction escapeRegExp(value: string): string {\n\treturn value.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n\n/**\n * Quote only what dotenv would otherwise misread.\n *\n * Deliberately not the systemd quoting `vela env` uses for the server: this file\n * is read by dotenv and by people, and quoting every value would churn lines\n * that did not need to change.\n */\nfunction quoteEnvValue(value: string): string {\n\tif (/^[A-Za-z0-9_./:@+-]*$/.test(value)) return value;\n\tconst escaped = value.replaceAll('\\\\', '\\\\\\\\').replaceAll('\"', '\\\\\"').replaceAll('\\n', '\\\\n');\n\treturn `\"${escaped}\"`;\n}\n", "import fs from 'node:fs';\nimport path from 'node:path';\nimport type { ObjectLiteralExpression } from 'ts-morph';\nimport {\n\tcreateSveltekitArg,\n\tgetOrCreateObjectLiteralProperty,\n\tinspectViteSveltekit,\n\tprobeFirstExisting,\n\tSVELTE_CONFIG_CANDIDATES,\n\ttype ViteSveltekit\n} from './config-target.ts';\n\nexport interface MergeOutcome {\n\tapplied: boolean;\n\treason: string;\n\tsnippet?: string;\n\t/** Basename of the config file the merge targeted, for reporting. */\n\tfile?: string;\n}\n\nconst RUNES_VALUE = `({ filename }) => (filename.split(/[/\\\\\\\\]/).includes('node_modules') ? undefined : true)`;\n\nconst RUNES_SNIPPET = `\\tcompilerOptions: {\n\\t\\trunes: ${RUNES_VALUE}\n\\t},\\n`;\n\nconst TAILWIND_IMPORT = `import tailwindcss from '@tailwindcss/vite';`;\n\n/**\n * Ensure the Svelte `runes` compiler option is set. Defaults to the inline\n * `sveltekit()` arg in vite.config (the new SvelteKit approach), falling back to\n * `svelte.config.*` when that's where the project keeps its config. Resolution\n * mirrors SvelteKit's own precedence.\n */\nexport function mergeSvelteConfig(projectRoot: string): MergeOutcome {\n\tconst vite = inspectViteSveltekit(projectRoot);\n\n\t// Rule 1: vite.config has an inline sveltekit() arg \u2192 inject runes there.\n\tif (vite?.inlineArg) {\n\t\treturn mergeRunesIntoViteArg(vite, vite.inlineArg);\n\t}\n\n\t// Rule 2: a svelte.config.* file exists \u2192 use the legacy in-place injector.\n\tconst sveltePath = probeFirstExisting(projectRoot, SVELTE_CONFIG_CANDIDATES);\n\tif (sveltePath) {\n\t\treturn mergeRunesIntoSvelteConfig(sveltePath);\n\t}\n\n\t// Rule 3: bare sveltekit() \u2192 create an arg and inject runes into it.\n\tif (vite?.sveltekitCall && !vite.nonObjectArg) {\n\t\tconst arg = createSveltekitArg(vite);\n\t\tif (arg) return mergeRunesIntoViteArg(vite, arg);\n\t}\n\n\treturn {\n\t\tapplied: false,\n\t\treason: 'no svelte.config or vite.config sveltekit() found',\n\t\tsnippet: RUNES_SNIPPET\n\t};\n}\n\nfunction mergeRunesIntoViteArg(vite: ViteSveltekit, arg: ObjectLiteralExpression): MergeOutcome {\n\tconst file = path.basename(vite.filePath);\n\tconst compilerOptions = getOrCreateObjectLiteralProperty(arg, 'compilerOptions', '{}');\n\tif (!compilerOptions) {\n\t\treturn {\n\t\t\tapplied: false,\n\t\t\treason: 'could not access sveltekit() compilerOptions',\n\t\t\tsnippet: RUNES_SNIPPET,\n\t\t\tfile\n\t\t};\n\t}\n\tif (compilerOptions.getProperty('runes')) {\n\t\treturn { applied: false, reason: 'runes already configured', file };\n\t}\n\tcompilerOptions.addPropertyAssignment({ name: 'runes', initializer: RUNES_VALUE });\n\tvite.sourceFile.formatText();\n\tvite.sourceFile.saveSync();\n\treturn { applied: true, reason: 'added runes compilerOption', file };\n}\n\nfunction mergeRunesIntoSvelteConfig(filePath: string): MergeOutcome {\n\tconst file = path.basename(filePath);\n\tconst original = fs.readFileSync(filePath, 'utf8');\n\tif (/runes\\s*:/m.test(original)) {\n\t\treturn { applied: false, reason: 'runes already configured', file };\n\t}\n\tif (/compilerOptions\\s*:/m.test(original)) {\n\t\treturn {\n\t\t\tapplied: false,\n\t\t\treason: 'compilerOptions already present \u2014 add `runes` manually',\n\t\t\tsnippet: `runes: ${RUNES_VALUE}`,\n\t\t\tfile\n\t\t};\n\t}\n\n\tconst anchor = original.match(/^(const\\s+config\\s*=\\s*\\{)\\s*\\n/m);\n\tif (!anchor || anchor.index === undefined) {\n\t\treturn {\n\t\t\tapplied: false,\n\t\t\treason: `${file} has a non-standard shape`,\n\t\t\tsnippet: RUNES_SNIPPET,\n\t\t\tfile\n\t\t};\n\t}\n\n\tconst insertAt = anchor.index + anchor[0].length;\n\tconst updated = original.slice(0, insertAt) + RUNES_SNIPPET + original.slice(insertAt);\n\tfs.writeFileSync(filePath, updated);\n\treturn { applied: true, reason: 'added runes compilerOption', file };\n}\n\nexport function mergeViteConfig(filePath: string): MergeOutcome {\n\tif (!fs.existsSync(filePath)) {\n\t\treturn {\n\t\t\tapplied: false,\n\t\t\treason: 'vite.config.ts not found',\n\t\t\tsnippet: `${TAILWIND_IMPORT}\\n// then add tailwindcss() to the plugins array`\n\t\t};\n\t}\n\n\tconst original = fs.readFileSync(filePath, 'utf8');\n\tif (original.includes('@tailwindcss/vite')) {\n\t\treturn { applied: false, reason: 'tailwindcss plugin already present' };\n\t}\n\n\tconst pluginsMatch = original.match(/plugins\\s*:\\s*\\[/);\n\tif (!pluginsMatch || pluginsMatch.index === undefined) {\n\t\treturn {\n\t\t\tapplied: false,\n\t\t\treason: 'vite.config.ts has a non-standard shape \u2014 no plugins array found',\n\t\t\tsnippet: `import tailwindcss from '@tailwindcss/vite';\\n// plugins: [tailwindcss(), sveltekit()]`\n\t\t};\n\t}\n\n\tconst withImport = addImport(original, TAILWIND_IMPORT);\n\n\tconst newPluginsMatch = withImport.match(/plugins\\s*:\\s*\\[/)!;\n\tconst insertAt = newPluginsMatch.index! + newPluginsMatch[0].length;\n\tconst trailing = withImport.slice(insertAt);\n\tconst prefix = /^\\s*\\]/.test(trailing) ? 'tailwindcss()' : 'tailwindcss(), ';\n\tconst updated = withImport.slice(0, insertAt) + prefix + withImport.slice(insertAt);\n\n\tfs.writeFileSync(filePath, updated);\n\treturn { applied: true, reason: 'added @tailwindcss/vite plugin' };\n}\n\nexport function mergeTsconfig(filePath: string): MergeOutcome {\n\tif (!fs.existsSync(filePath)) {\n\t\treturn { applied: false, reason: 'tsconfig.json not found' };\n\t}\n\tconst original = fs.readFileSync(filePath, 'utf8');\n\tif (/rewriteRelativeImportExtensions/.test(original)) {\n\t\treturn { applied: false, reason: 'rewriteRelativeImportExtensions already set' };\n\t}\n\n\tconst match = original.match(/\"compilerOptions\"\\s*:\\s*\\{/);\n\tif (!match || match.index === undefined) {\n\t\treturn {\n\t\t\tapplied: false,\n\t\t\treason: 'tsconfig.json has no compilerOptions block',\n\t\t\tsnippet: `\"compilerOptions\": { \"rewriteRelativeImportExtensions\": true }`\n\t\t};\n\t}\n\n\tconst insertAt = match.index + match[0].length;\n\tconst indent = detectIndent(original, insertAt);\n\tconst updated =\n\t\toriginal.slice(0, insertAt) +\n\t\t`\\n${indent}\"rewriteRelativeImportExtensions\": true,` +\n\t\toriginal.slice(insertAt);\n\tfs.writeFileSync(filePath, updated);\n\treturn { applied: true, reason: 'added rewriteRelativeImportExtensions' };\n}\n\nconst GITIGNORE_ENTRIES = [\n\t'.env',\n\t'.env.*',\n\t'!.env.example',\n\t'!.env.test',\n\t'vite.config.js.timestamp-*',\n\t'vite.config.ts.timestamp-*'\n];\n\nexport function mergeGitignore(filePath: string): MergeOutcome {\n\tconst existing = fs.existsSync(filePath) ? fs.readFileSync(filePath, 'utf8') : '';\n\tconst lines = existing.split('\\n').map((l) => l.trim());\n\tconst missing = GITIGNORE_ENTRIES.filter((entry) => !lines.includes(entry));\n\tif (missing.length === 0) {\n\t\treturn { applied: false, reason: '.gitignore already has vela entries' };\n\t}\n\n\tconst needsNewline = existing.length > 0 && !existing.endsWith('\\n');\n\tconst appended = `${existing}${needsNewline ? '\\n' : ''}${missing.join('\\n')}\\n`;\n\tfs.writeFileSync(filePath, appended);\n\treturn { applied: true, reason: `added ${missing.length} gitignore entries` };\n}\n\nfunction addImport(source: string, importLine: string): string {\n\tif (source.includes(importLine)) return source;\n\tconst importRegex = /^import\\s[^\\n]+;?\\s*$/gm;\n\tlet lastImportEnd = 0;\n\tlet match: RegExpExecArray | null;\n\twhile ((match = importRegex.exec(source)) !== null) {\n\t\tlastImportEnd = match.index + match[0].length;\n\t}\n\tif (lastImportEnd === 0) {\n\t\treturn `${importLine}\\n${source}`;\n\t}\n\treturn source.slice(0, lastImportEnd) + `\\n${importLine}` + source.slice(lastImportEnd);\n}\n\nfunction detectIndent(source: string, atOffset: number): string {\n\tconst rest = source.slice(atOffset);\n\tconst nextLine = rest.match(/\\n([ \\t]+)\"/);\n\treturn nextLine ? nextLine[1]! : '\\t';\n}\n", "import fs from 'node:fs';\nimport path from 'node:path';\nimport {\n\tProject,\n\tQuoteKind,\n\tSyntaxKind,\n\ttype CallExpression,\n\ttype ObjectLiteralExpression,\n\ttype SourceFile\n} from 'ts-morph';\n\nexport const VITE_CONFIG_CANDIDATES = [\n\t'vite.config.ts',\n\t'vite.config.js',\n\t'vite.config.mjs',\n\t'vite.config.cjs'\n];\n\nexport const SVELTE_CONFIG_CANDIDATES = [\n\t'svelte.config.ts',\n\t'svelte.config.js',\n\t'svelte.config.mjs',\n\t'svelte.config.cjs'\n];\n\n/** First candidate that exists under `root`, or null. */\nexport function probeFirstExisting(root: string, candidates: string[]): string | null {\n\tfor (const rel of candidates) {\n\t\tconst abs = path.join(root, rel);\n\t\tif (fs.existsSync(abs)) return abs;\n\t}\n\treturn null;\n}\n\nexport interface ViteSveltekit {\n\tfilePath: string;\n\tsourceFile: SourceFile;\n\tsveltekitCall: CallExpression | null;\n\t/** Inline object argument of `sveltekit(...)`, if it's an object literal. */\n\tinlineArg: ObjectLiteralExpression | null;\n\t/** True when `sveltekit(...)` has a non-object argument we mustn't touch. */\n\tnonObjectArg: boolean;\n}\n\n/**\n * Load the project's `vite.config.*` (if any) and locate the `sveltekit()` call\n * plus its inline argument. Returns null when there is no vite config file.\n */\nexport function inspectViteSveltekit(root: string): ViteSveltekit | null {\n\tconst filePath = probeFirstExisting(root, VITE_CONFIG_CANDIDATES);\n\tif (!filePath) return null;\n\n\tconst project = new Project({\n\t\tcompilerOptions: { allowJs: true },\n\t\tmanipulationSettings: { quoteKind: QuoteKind.Single }\n\t});\n\tconst sourceFile = project.addSourceFileAtPath(filePath);\n\tconst sveltekitCall =\n\t\tsourceFile\n\t\t\t.getDescendantsOfKind(SyntaxKind.CallExpression)\n\t\t\t.find((ce) => ce.getExpression().getText() === 'sveltekit') ?? null;\n\n\tlet inlineArg: ObjectLiteralExpression | null = null;\n\tlet nonObjectArg = false;\n\tconst arg = sveltekitCall?.getArguments()[0];\n\tif (arg) {\n\t\tif (arg.getKind() === SyntaxKind.ObjectLiteralExpression) {\n\t\t\tinlineArg = arg as ObjectLiteralExpression;\n\t\t} else {\n\t\t\tnonObjectArg = true;\n\t\t}\n\t}\n\n\treturn { filePath, sourceFile, sveltekitCall, inlineArg, nonObjectArg };\n}\n\n/** Add an empty `{}` argument to a bare `sveltekit()` call and return it. */\nexport function createSveltekitArg(vite: ViteSveltekit): ObjectLiteralExpression | null {\n\tif (!vite.sveltekitCall || vite.nonObjectArg) return null;\n\treturn vite.sveltekitCall.addArgument('{}').asKind(SyntaxKind.ObjectLiteralExpression) ?? null;\n}\n\n/**\n * Get the object-literal value of property `name`, creating it as an empty\n * object when missing. Returns null if it can't be coerced to an object literal.\n */\nexport function getOrCreateObjectLiteralProperty(\n\tobj: ObjectLiteralExpression,\n\tname: string,\n\tinitializer: string\n): ObjectLiteralExpression | null {\n\tconst prop = obj.getProperty(name);\n\tif (!prop) {\n\t\tobj.addPropertyAssignment({ name, initializer });\n\t\tconst added = obj.getProperty(name);\n\t\tif (!added || added.getKind() !== SyntaxKind.PropertyAssignment) return null;\n\t\tconst init = (added as import('ts-morph').PropertyAssignment).getInitializer();\n\t\treturn init && init.getKind() === SyntaxKind.ObjectLiteralExpression\n\t\t\t? (init as ObjectLiteralExpression)\n\t\t\t: null;\n\t}\n\n\tif (prop.getKind() !== SyntaxKind.PropertyAssignment) return null;\n\tconst init = (prop as import('ts-morph').PropertyAssignment).getInitializer();\n\tif (!init) return null;\n\tif (init.getKind() !== SyntaxKind.ObjectLiteralExpression) {\n\t\t(prop as import('ts-morph').PropertyAssignment).setInitializer(initializer);\n\t\tconst init2 = (prop as import('ts-morph').PropertyAssignment).getInitializer();\n\t\treturn init2 && init2.getKind() === SyntaxKind.ObjectLiteralExpression\n\t\t\t? (init2 as ObjectLiteralExpression)\n\t\t\t: null;\n\t}\n\n\treturn init as ObjectLiteralExpression;\n}\n", "import fs from 'node:fs';\nimport path from 'node:path';\n\nconst VANILLA_MARKER = 'Welcome to SvelteKit';\nconst PAGE_REL = path.join('src', 'routes', '+page.svelte');\n\nexport function isVanillaRoutes(cwd: string): boolean {\n\tconst pagePath = path.join(cwd, PAGE_REL);\n\tif (!fs.existsSync(pagePath)) return false;\n\treturn fs.readFileSync(pagePath, 'utf8').includes(VANILLA_MARKER);\n}\n", "import * as p from '@clack/prompts';\n\n/**\n * A file a pattern could not change, and what the user should do about it.\n *\n * Modifiers do best-effort surgery on files the project owns, so they meet\n * shapes they don't recognise \u2014 a renamed export, a different wrapper, a config\n * that isn't an object literal. When that happens they refuse to touch the file\n * and hand back a paste-ready snippet instead. That snippet is the whole point\n * of the failure path, so it gets printed, not counted.\n */\nexport interface ReportFailure {\n\tpath: string;\n\tstatus: 'failed' | 'not-found';\n\tmessage?: string;\n}\n\nexport interface ResultReport {\n\tsummary: string;\n\tfilesCreated?: string[];\n\tfilesModified?: string[];\n\tfilesDeleted?: string[];\n\tcomponentsAdded?: string[];\n\tpackagesInstalled?: string[];\n\tcollectionsAdded?: string[];\n\trecordsLoaded?: string[];\n\trecordsCleared?: string[];\n\tsections?: Array<{ label: string; items: string[] }>;\n\tfailures?: ReportFailure[];\n\tnextSteps?: string[];\n}\n\nexport function reportResult(report: ResultReport): void {\n\tconst sections: Array<[string, string[] | undefined]> = [\n\t\t['Files created', report.filesCreated],\n\t\t['Files modified', report.filesModified],\n\t\t['Files deleted', report.filesDeleted],\n\t\t['UI components added', report.componentsAdded],\n\t\t['Packages installed', report.packagesInstalled],\n\t\t['Collections added', report.collectionsAdded],\n\t\t['Records loaded', report.recordsLoaded],\n\t\t['Records cleared', report.recordsCleared]\n\t];\n\tfor (const extra of report.sections ?? []) {\n\t\tsections.push([extra.label, extra.items]);\n\t}\n\n\tconst body: string[] = [];\n\tfor (const [label, items] of sections) {\n\t\tif (!items || items.length === 0) continue;\n\t\tif (body.length > 0) body.push('');\n\t\tbody.push(`${label}:`);\n\t\tfor (const item of items) body.push(`- ${item}`);\n\t}\n\n\tconst failures = report.failures ?? [];\n\n\t// Anything changed is still a success; the failures are reported separately\n\t// rather than folded into the summary, so a partial application reads as\n\t// exactly that.\n\tif (body.length > 0) {\n\t\tp.log.success(`${report.summary}\\n\\n${body.join('\\n')}`);\n\t} else if (failures.length === 0) {\n\t\tp.log.success(report.summary);\n\t}\n\n\tfor (const failure of failures) {\n\t\tconst headline =\n\t\t\tfailure.status === 'not-found'\n\t\t\t\t? `Could not find ${failure.path}`\n\t\t\t\t: `Could not update ${failure.path}`;\n\t\tp.log.warn(failure.message ? `${headline}\\n\\n${failure.message}` : headline);\n\t}\n\n\tif (report.nextSteps && report.nextSteps.length > 0) {\n\t\tp.note(report.nextSteps.map((s) => `- ${s}`).join('\\n'), 'Next steps', {\n\t\t\tformat: (line) => line\n\t\t});\n\t}\n}\n", "import fs from 'node:fs';\nimport path from 'node:path';\nimport { fillTemplatePlaceholders, type TemplateValues } from './package-json.ts';\n\n/**\n * npm never publishes files named `.gitignore` or `.npmrc` inside a package, so\n * templates store them under a publish-safe name and the real name is restored\n * when a template is copied into a project.\n *\n * Keyed by the name the file must have in the generated project.\n */\nconst PUBLISH_SAFE_NAMES: Record<string, string> = {\n\t'.gitignore': '_gitignore',\n\t'.npmrc': '_npmrc'\n};\n\n/** Template-relative path for a file that must land at `projectRelPath`. */\nexport function templateName(projectRelPath: string): string {\n\tconst safe = PUBLISH_SAFE_NAMES[path.basename(projectRelPath)];\n\tif (!safe) return projectRelPath;\n\tconst dir = path.dirname(projectRelPath);\n\treturn dir === '.' ? safe : path.join(dir, safe);\n}\n\n/** Restore publish-safe names to their real ones after copying a template tree. */\nexport function restoreTemplateNames(target: string): void {\n\tfor (const [real, safe] of Object.entries(PUBLISH_SAFE_NAMES)) {\n\t\tconst from = path.join(target, safe);\n\t\tif (!fs.existsSync(from)) continue;\n\t\tfs.renameSync(from, path.join(target, real));\n\t}\n}\n\n/**\n * A template ships parameterized files under a `.template.` infix \u2014 the reason\n * being that `package.template.json` has to stay valid JSON (and installable\n * TypeScript) while it still holds `~TODO~` placeholders.\n */\nconst TEMPLATE_SOURCE = /\\.template\\.([^.]+)$/;\n\n/**\n * Fill placeholders in every `*.template.*` file a copied template left behind,\n * write each to its real name, and remove the source.\n *\n * Returns the project-relative paths written, so a caller can assert the files a\n * template must produce.\n */\nexport function applyTemplateFiles(target: string, values: TemplateValues): string[] {\n\tconst written: string[] = [];\n\tfor (const source of findTemplateSources(target)) {\n\t\tconst raw = fs.readFileSync(source, 'utf8');\n\t\tconst dest = source.replace(TEMPLATE_SOURCE, '.$1');\n\t\tfs.writeFileSync(dest, fillTemplatePlaceholders(raw, values));\n\t\tfs.unlinkSync(source);\n\t\twritten.push(path.relative(target, dest));\n\t}\n\treturn written.sort();\n}\n\nfunction findTemplateSources(dir: string): string[] {\n\tconst found: string[] = [];\n\tfor (const entry of fs.readdirSync(dir, { withFileTypes: true })) {\n\t\tconst full = path.join(dir, entry.name);\n\t\tif (entry.isDirectory()) {\n\t\t\tif (entry.name === 'node_modules' || entry.name === '.git') continue;\n\t\t\tfound.push(...findTemplateSources(full));\n\t\t} else if (entry.isFile() && TEMPLATE_SOURCE.test(entry.name)) {\n\t\t\tfound.push(full);\n\t\t}\n\t}\n\treturn found;\n}\n", "import fs from 'node:fs';\nimport path from 'node:path';\nimport process from 'node:process';\nimport * as v from 'valibot';\nimport { Command } from 'commander';\nimport * as p from '@clack/prompts';\nimport { detect, resolveCommand } from 'package-manager-detector';\nimport { helpConfig } from '../lib/help.ts';\nimport { runCommand } from '../lib/run.ts';\nimport { parseOptions } from '../lib/options.ts';\nimport {\n\tDEFAULT_TEMPLATE,\n\tTEMPLATE_MANIFEST,\n\tfindProjectTemplate,\n\tprojectTemplateNames,\n\ttype ProjectTemplate\n} from '../lib/templates.ts';\nimport {\n\tAGENT_NAMES,\n\tgetUserAgent,\n\tinstallOption,\n\tinstallDependencies,\n\tpackageManagerPrompt,\n\taddPnpmBuildDependencies\n} from '../lib/package-manager.ts';\nimport { createSuperuser, withPocketbase } from '../lib/pocketbase.ts';\nimport { writeEnvFile } from '../lib/env.ts';\nimport pkg from '../../package.json' with { type: 'json' };\nimport { applyTemplateFiles, restoreTemplateNames } from '../lib/template-files.ts';\nimport { reportResult } from '../lib/result-report.ts';\n\n/**\n * Built per run rather than at module load: the accepted templates come from the\n * templates directory, so adding one can't leave `--template` behind, and the\n * directory is only read once a command that needs it actually runs.\n */\nfunction optionsSchema() {\n\tconst templates = projectTemplateNames();\n\treturn v.strictObject({\n\t\tinstall: v.union([v.boolean(), v.picklist(AGENT_NAMES)], 'must be a package manager'),\n\t\ttemplate: v.optional(v.picklist(templates, `must be one of: ${templates.join(', ')}`)),\n\t\tname: v.optional(v.pipe(v.string(), v.trim(), v.minLength(1, 'must not be empty'))),\n\t\temail: v.optional(v.pipe(v.string(), v.email('must be a valid email address'))),\n\t\tpassword: v.optional(v.pipe(v.string(), v.minLength(8, 'must be at least 8 characters long')))\n\t});\n}\ntype Options = v.InferOutput<ReturnType<typeof optionsSchema>>;\n\nexport const create = new Command('create')\n\t.description('scaffold a new velastack project')\n\t.argument('[path]', 'where the project will be created')\n\t.option('--template <type>', 'template to scaffold', 'minimal')\n\t.option('--no-install', 'skip installing dependencies')\n\t.option('--name <name>', 'app name (used for emails, etc)')\n\t.option('--email <email>', 'email of the admin user')\n\t.option('--password <password>', 'password of the admin user')\n\t.addOption(installOption)\n\t.configureHelp(helpConfig)\n\t.action((projectPath: string | undefined, rawOpts) => {\n\t\treturn runCommand(async () => {\n\t\t\tconst options = parseOptions(optionsSchema(), rawOpts);\n\t\t\tconst { directory, packageManager, name, template } = await createProject(\n\t\t\t\tprojectPath,\n\t\t\t\toptions\n\t\t\t);\n\n\t\t\tconst relative = path.relative(process.cwd(), directory);\n\t\t\tconst pm =\n\t\t\t\tpackageManager ?? (await detect({ cwd: directory }))?.name ?? getUserAgent() ?? 'npm';\n\n\t\t\tconst nextSteps: string[] = [];\n\t\t\tif (relative !== '') {\n\t\t\t\tconst hasSpaces = relative.includes(' ');\n\t\t\t\tnextSteps.push(`\\`cd ${hasSpaces ? `\"${relative}\"` : relative}\\``);\n\t\t\t}\n\t\t\tif (!packageManager) {\n\t\t\t\tconst resolved = resolveCommand(pm, 'install', []);\n\t\t\t\tif (resolved) {\n\t\t\t\t\tnextSteps.push(\n\t\t\t\t\t\t`\\`${resolved.command} ${resolved.args.join(' ')}\\` to install dependencies`\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst runDev = resolveCommand(pm, 'run', ['dev', '--open']);\n\t\t\tif (runDev) {\n\t\t\t\tnextSteps.push(\n\t\t\t\t\t`\\`${runDev.command} ${runDev.args.join(' ')}\\` to start the dev server (Ctrl-C to stop)`\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (template.backend) {\n\t\t\t\tnextSteps.push('Run `vela generate scaffold <model>` to generate your first CRUD pages.');\n\t\t\t} else {\n\t\t\t\tnextSteps.push(\n\t\t\t\t\t'Set your deployed URL in `src/lib/site.ts` before building for production.'\n\t\t\t\t);\n\t\t\t\tnextSteps.push('Run `vela ui add <component>` to add UI components.');\n\t\t\t}\n\t\t\tnextSteps.push('Stuck? Visit https://docs.velastack.dev');\n\n\t\t\treportResult({\n\t\t\t\tsummary: `Created ${name} at ${directory}.`,\n\t\t\t\tnextSteps\n\t\t\t});\n\t\t}, 'Failed to create project.');\n\t});\n\nasync function createProject(cwdArg: string | undefined, options: Options) {\n\tconst onCancel = () => {\n\t\tp.cancel('Operation cancelled.');\n\t\tprocess.exit(0);\n\t};\n\n\tconst template = findProjectTemplate(options.template ?? DEFAULT_TEMPLATE);\n\tif (!template.backend && (options.email || options.password)) {\n\t\tthrow new Error(\n\t\t\t`--email and --password don't apply to the ${template.name} template \u2014 it has no backend.`\n\t\t);\n\t}\n\n\tlet directory: string;\n\tif (cwdArg) {\n\t\tdirectory = path.resolve(cwdArg);\n\t} else {\n\t\tconst answer = await p.text({\n\t\t\tmessage: 'Where would you like your project to be created?',\n\t\t\tplaceholder: ' (hit Enter to use current directory)',\n\t\t\tdefaultValue: './'\n\t\t});\n\t\tif (p.isCancel(answer)) onCancel();\n\t\tdirectory = path.resolve(answer as string);\n\t}\n\n\tif (\n\t\tfs.existsSync(directory) &&\n\t\tfs.readdirSync(directory).filter((f) => !f.startsWith('.git')).length > 0\n\t) {\n\t\tconst force = await p.confirm({\n\t\t\tmessage: 'Directory not empty. Continue?',\n\t\t\tinitialValue: false\n\t\t});\n\t\tif (p.isCancel(force) || !force) onCancel();\n\t}\n\n\tconst dirName = path.basename(directory);\n\n\tconst { name } = await p.group(\n\t\t{\n\t\t\tname: () => {\n\t\t\t\tif (options.name) return Promise.resolve(options.name);\n\t\t\t\treturn p.text({\n\t\t\t\t\tmessage: 'App name (used for emails, etc)',\n\t\t\t\t\tinitialValue: dirName || 'SvelteKit',\n\t\t\t\t\tvalidate: (value) => (value?.trim() ? undefined : 'App name is required')\n\t\t\t\t});\n\t\t\t}\n\t\t},\n\t\t{ onCancel }\n\t);\n\n\tconst credentials = template.backend ? await promptCredentials(options, onCancel) : undefined;\n\n\tconst projectPath = directory;\n\n\tcopyTemplate(template, projectPath);\n\tapplyTemplateFiles(projectPath, { appName: name, cliVersion: pkg.version });\n\tif (!fs.existsSync(path.join(projectPath, 'package.json'))) {\n\t\tthrow new Error(`Template ${template.name} is missing package.template.json`);\n\t}\n\n\tp.log.success('Project created');\n\n\tlet packageManager: ReturnType<typeof getUserAgent> | undefined;\n\tif (options.install !== false) {\n\t\tconst pm =\n\t\t\ttypeof options.install === 'string'\n\t\t\t\t? options.install\n\t\t\t\t: await packageManagerPrompt(projectPath);\n\n\t\tif (pm) {\n\t\t\tconst builds = template.backend ? ['esbuild', 'pocketbase-server'] : ['esbuild'];\n\t\t\taddPnpmBuildDependencies(projectPath, pm, builds);\n\t\t\tawait installDependencies(pm, projectPath);\n\t\t\tpackageManager = pm;\n\t\t}\n\t}\n\n\tif (credentials) {\n\t\tconst { email, password } = credentials;\n\n\t\tp.log.step('Initializing PocketBase...');\n\t\tawait createSuperuser(projectPath, email, password);\n\n\t\tawait withPocketbase(\n\t\t\tprojectPath,\n\t\t\tasync (pb) => {\n\t\t\t\tawait pb.settings.update({\n\t\t\t\t\tmeta: { appName: name, appURL: 'http://localhost:5173' }\n\t\t\t\t});\n\t\t\t},\n\t\t\t{ email, password }\n\t\t);\n\n\t\twriteEnvFile(\n\t\t\tprojectPath,\n\t\t\t{\n\t\t\t\tPOCKETBASE_SUPERUSER_EMAIL: email,\n\t\t\t\tPOCKETBASE_SUPERUSER_PASSWORD: password\n\t\t\t},\n\t\t\t['PocketBase superuser credentials \u2014 used by `vela` commands']\n\t\t);\n\n\t\tp.log.success('PocketBase initialized');\n\t}\n\n\treturn { directory: projectPath, packageManager, name, template };\n}\n\nfunction promptCredentials(options: Options, onCancel: () => void) {\n\treturn p.group(\n\t\t{\n\t\t\temail: () => {\n\t\t\t\tif (options.email) return Promise.resolve(options.email);\n\t\t\t\treturn p.text({\n\t\t\t\t\tmessage: 'Enter an email for the admin user',\n\t\t\t\t\tinitialValue: 'admin@example.com',\n\t\t\t\t\tvalidate: (value) =>\n\t\t\t\t\t\t!value ? 'Email is required' : !value.includes('@') ? 'Invalid email' : undefined\n\t\t\t\t});\n\t\t\t},\n\t\t\tpassword: () => {\n\t\t\t\tif (options.password) return Promise.resolve(options.password);\n\t\t\t\treturn p.password({\n\t\t\t\t\tmessage: 'Enter a password for the admin user (at least 8 characters)',\n\t\t\t\t\tvalidate: (value) =>\n\t\t\t\t\t\t!value\n\t\t\t\t\t\t\t? 'Password is required'\n\t\t\t\t\t\t\t: value.length < 8\n\t\t\t\t\t\t\t\t? 'Password must be at least 8 characters long'\n\t\t\t\t\t\t\t\t: undefined\n\t\t\t\t});\n\t\t\t}\n\t\t},\n\t\t{ onCancel }\n\t);\n}\n\nfunction copyTemplate(template: ProjectTemplate, target: string): void {\n\tfs.mkdirSync(target, { recursive: true });\n\tfs.cpSync(template.dir, target, {\n\t\trecursive: true,\n\t\t// The manifest describes the template to the CLI; it isn't part of the project.\n\t\tfilter: (src) =>\n\t\t\tpath.basename(src) !== '.DS_Store' && path.relative(template.dir, src) !== TEMPLATE_MANIFEST\n\t});\n\trestoreTemplateNames(target);\n}\n", "import { Command } from 'commander';\nimport { helpConfig } from '../lib/help.ts';\nimport { form } from './generate/form.ts';\nimport { schema } from './generate/schema.ts';\nimport { resource } from './generate/resource.ts';\nimport { scaffold } from './generate/scaffold.ts';\nimport { migration } from './generate/migration.ts';\n\nexport const generate = new Command('generate')\n\t.description('generate scaffolding for database models and forms')\n\t.configureHelp(helpConfig)\n\t.addCommand(form)\n\t.addCommand(schema)\n\t.addCommand(resource)\n\t.addCommand(scaffold)\n\t.addCommand(migration);\n", "import { Command } from 'commander';\nimport * as p from '@clack/prompts';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand } from '../../lib/run.ts';\nimport { runPattern } from '../../lib/pattern-runner.ts';\nimport {\n\trunSchemaStage,\n\trunLayoutStage,\n\tspecToArgv,\n\twriteLayoutSidecar\n} from '../../lib/ai-flow.ts';\n\nexport const form = new Command('form')\n\t.description('generate a form from a model')\n\t.argument('[model]', 'model name (e.g. \"contact\")')\n\t.argument('[fields...]', 'field definitions (e.g. \"name:text\", \"email:email\")')\n\t.option('--remote', 'generate a form backed by a remote PocketBase collection')\n\t.option(\n\t\t'--route <route>',\n\t\t'place the form at a custom route (e.g. \"(app)/[team_id]/projects/new\"). Defaults to the model name under (app)/(public).'\n\t)\n\t.option(\n\t\t'--ai <description>',\n\t\t'design the form with AI from a natural-language description (two stages: schema \u2192 layout)'\n\t)\n\t.allowUnknownOption(true)\n\t.configureHelp(helpConfig)\n\t.action(\n\t\t(\n\t\t\tmodel: string | undefined,\n\t\t\tfields: string[],\n\t\t\toptions: { remote?: boolean; route?: string; ai?: string }\n\t\t) =>\n\t\t\trunCommand(async () => {\n\t\t\t\tlet argv: string[];\n\t\t\t\tlet modelName: string;\n\t\t\t\tlet sidecarPath: string | null = null;\n\n\t\t\t\tif (options.ai) {\n\t\t\t\t\tif (model) {\n\t\t\t\t\t\tthrow new Error('Pass either a model name or --ai, not both.');\n\t\t\t\t\t}\n\t\t\t\t\tconst stage = await runSchemaStage({ prompt: options.ai, useCase: 'form' });\n\t\t\t\t\tif (!stage) {\n\t\t\t\t\t\tp.cancel('Aborted before any files were written.');\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tconst layout = await runLayoutStage(stage.workspaceRootDir, stage.model);\n\t\t\t\t\tif (!layout) {\n\t\t\t\t\t\tp.cancel('Aborted before any files were written.');\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\targv = specToArgv(stage.model);\n\t\t\t\t\tmodelName = stage.model.name;\n\t\t\t\t\tsidecarPath = writeLayoutSidecar(stage.workspaceRootDir, modelName, layout);\n\t\t\t\t} else {\n\t\t\t\t\tif (!model) {\n\t\t\t\t\t\tthrow new Error('Missing required argument: model. Pass a model name or use --ai.');\n\t\t\t\t\t}\n\t\t\t\t\targv = [model, ...fields];\n\t\t\t\t\tmodelName = model;\n\t\t\t\t}\n\n\t\t\t\tconst slug = options.remote ? 'generate-form-remote' : 'generate-form';\n\t\t\t\tconst nextSteps: string[] = [\n\t\t\t\t\t'Edit the form fields and validation in the generated +page.svelte.',\n\t\t\t\t\t'Run `vela dev` to preview the form in the browser.'\n\t\t\t\t];\n\t\t\t\tif (sidecarPath) {\n\t\t\t\t\tnextSteps.unshift(\n\t\t\t\t\t\t`Apply the AI-designed form layout from ${sidecarPath} to the generated +page.svelte.`\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tawait runPattern(\n\t\t\t\t\tslug,\n\t\t\t\t\targv,\n\t\t\t\t\t{ route: options.route },\n\t\t\t\t\t{\n\t\t\t\t\t\tsummary: `Created ${modelName} form.`,\n\t\t\t\t\t\tnextSteps,\n\t\t\t\t\t\ttask: {\n\t\t\t\t\t\t\ttitle: 'Generating form',\n\t\t\t\t\t\t\tsuccess: 'Generated form',\n\t\t\t\t\t\t\terror: 'Failed to generate form'\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t);\n\t\t\t}, 'Failed to generate form.')\n\t);\n", "import path from 'node:path';\nimport * as p from '@clack/prompts';\nimport { bySlug, type Slug } from '@velastack/patterns';\nimport { withPocketbase } from './pocketbase.ts';\nimport { getWorkspace } from './workspace.ts';\nimport { reportResult, type ReportFailure } from './result-report.ts';\n\nexport interface PatternReport {\n\tsummary?: string;\n\tnextSteps?: string[];\n\ttask: {\n\t\ttitle: string;\n\t\tsuccess: string;\n\t\terror: string;\n\t};\n}\n\nfunction toRelative(root: string, filePath: string): string {\n\treturn path.isAbsolute(filePath) ? path.relative(root, filePath) : filePath;\n}\n\n/**\n * What a pattern hands back for one file.\n *\n * A modifier that refuses to touch a file it doesn't recognise reports\n * `failed` / `not-found` plus a remediation snippet. Those entries are new\n * here: `writeResult` used to drop them, so a partial application was reported\n * as a clean success and the snippet was never seen. Partitioning on `status`\n * is what keeps a failure out of the \"created\"/\"modified\" lists.\n */\ninterface ResultFile {\n\tpath: string;\n\tstatus?: 'success' | 'failed' | 'not-found';\n\tmessage?: string;\n}\n\nconst isSuccess = (f: ResultFile) => (f.status ?? 'success') === 'success';\n\nexport async function runPattern(\n\tslug: Slug,\n\targv: string[],\n\tinput: Record<string, unknown>,\n\treport: PatternReport\n): Promise<void> {\n\tconst pattern = bySlug[slug];\n\tif (!pattern) {\n\t\tthrow new Error(`Unknown pattern: ${slug}`);\n\t}\n\n\tconst { workspaceRootDir, features } = await getWorkspace();\n\n\tconst log = p.taskLog({ title: report.task.title });\n\n\tlet result;\n\ttry {\n\t\tresult = await pattern.generate({\n\t\t\targv,\n\t\t\tenv: 'runtime',\n\t\t\troot: workspaceRootDir,\n\t\t\tfeatures,\n\t\t\tinput,\n\t\t\t// Patterns no longer read the schema themselves: @velastack/pocketbase-codegen\n\t\t\t// takes an injected client, and only the CLI knows how to reach (or spawn)\n\t\t\t// a PocketBase for this workspace.\n\t\t\tgetCollections: async () => {\n\t\t\t\tconst { getCollections } = await import('@velastack/pocketbase-codegen');\n\t\t\t\tlet collections: Awaited<ReturnType<typeof getCollections>> = [];\n\t\t\t\tawait withPocketbase(workspaceRootDir, async (pb) => {\n\t\t\t\t\tcollections = await getCollections(pb);\n\t\t\t\t});\n\t\t\t\treturn collections;\n\t\t\t},\n\t\t\tlogger: { info: (message: string) => log.message(message) }\n\t\t});\n\t\tlog.success(report.task.success);\n\t} catch (e) {\n\t\tlog.error(report.task.error);\n\t\tthrow e;\n\t}\n\n\tconst rel = (f: string) => toRelative(workspaceRootDir, f);\n\n\tconst files: ResultFile[] = [...result.creates, ...result.modifies, ...result.deletes];\n\tconst failures: ReportFailure[] = files\n\t\t.filter((f) => !isSuccess(f))\n\t\t.map((f) => ({\n\t\t\tpath: rel(f.path),\n\t\t\tstatus: f.status === 'not-found' ? 'not-found' : 'failed',\n\t\t\tmessage: f.message\n\t\t}));\n\n\tconst created = result.creates.filter(isSuccess);\n\tconst modified = result.modifies.filter(isSuccess);\n\tconst deleted = result.deletes.filter(isSuccess);\n\n\tconst totalChanges =\n\t\tcreated.length +\n\t\tmodified.length +\n\t\tdeleted.length +\n\t\tresult.components.length +\n\t\tresult.packages.length +\n\t\tresult.collections.length;\n\n\t// A run that only produced failures still has something to say.\n\tif (totalChanges === 0 && failures.length === 0) {\n\t\tp.log.info(`${pattern.title ?? slug} produced no changes.`);\n\t\treturn;\n\t}\n\n\treportResult({\n\t\tsummary: report.summary ?? `Applied ${pattern.title ?? slug}.`,\n\t\tfilesCreated: created.map((f: { path: string }) => rel(f.path)),\n\t\tfilesModified: modified.map((f: { path: string }) => rel(f.path)),\n\t\tfilesDeleted: deleted.map((f: { path: string }) => rel(f.path)),\n\t\tcomponentsAdded: result.components,\n\t\tpackagesInstalled: result.packages,\n\t\tcollectionsAdded: result.collections.map((c: { name: string }) => c.name),\n\t\tfailures,\n\t\t// Next steps assume the pattern applied; when part of it didn't, the\n\t\t// remediation snippets above are the actual next step.\n\t\tnextSteps: failures.length > 0 ? undefined : report.nextSteps\n\t});\n}\n", "import fs from 'node:fs';\nimport path from 'node:path';\nimport * as p from '@clack/prompts';\nimport pc from 'picocolors';\nimport { aiSchema, aiForm, type CollectionSpec, type FormLayout } from './ai-client.ts';\nimport { aiLoop } from './ai-loop.ts';\nimport { loadExistingModels } from './ai-existing-models.ts';\nimport { collectionSpecToArgv } from './ai-to-argv.ts';\nimport { renderGrid } from './ai-grid.ts';\nimport { getWorkspace } from './workspace.ts';\n\nexport type AiUseCase = 'scaffold' | 'form' | 'schema';\n\nconst USE_CASE_HINT: Record<AiUseCase, string> = {\n\tscaffold:\n\t\t'Use case: scaffold \u2014 designing a new persisted PocketBase collection. Lean toward forward-thinking field choices.',\n\tform: 'Use case: form \u2014 designing fields for a Svelte form with no DB persistence. Focus on user-input fields; relations only to existing collections.',\n\tschema: 'Use case: schema \u2014 designing a standalone zod schema. Same considerations as form.'\n};\n\nfunction renderModel(spec: CollectionSpec): void {\n\tconst lines: string[] = [];\n\tlines.push(`${pc.bold(spec.name)} (${spec.type})`);\n\tconst nameWidth = Math.max(...spec.fields.map((f) => f.name.length), 4);\n\tconst typeWidth = Math.max(...spec.fields.map((f) => f.type.length), 4);\n\tfor (const f of spec.fields) {\n\t\tconst required = f.required ? pc.yellow('!') : ' ';\n\t\tconst extra: string[] = [];\n\t\tif (f.values && f.values.length > 0) extra.push(`values=[${f.values.join(',')}]`);\n\t\tif (f.collectionName) extra.push(`\u2192 ${f.collectionName}`);\n\t\tconst tail = extra.length > 0 ? ' ' + pc.dim(extra.join(' ')) : '';\n\t\tlines.push(` ${f.name.padEnd(nameWidth)} ${f.type.padEnd(typeWidth)} ${required}${tail}`);\n\t}\n\tp.log.message(lines.join('\\n'));\n}\n\nfunction renderLayout(layout: FormLayout): void {\n\tp.log.message(renderGrid(layout));\n}\n\nexport interface RunSchemaStageOptions {\n\tprompt: string;\n\tuseCase: AiUseCase;\n}\n\nexport interface RunSchemaStageResult {\n\tmodel: CollectionSpec;\n\tworkspaceRootDir: string;\n}\n\nexport async function runSchemaStage(\n\topts: RunSchemaStageOptions\n): Promise<RunSchemaStageResult | null> {\n\tconst { workspaceRootDir } = await getWorkspace();\n\tconst existingModels = await loadExistingModels(workspaceRootDir);\n\n\tconst initialPrompt = `${USE_CASE_HINT[opts.useCase]}\\n\\nDescribe and design a model for: ${opts.prompt}`;\n\n\tconst model = await aiLoop<CollectionSpec>({\n\t\tinitialPrompt,\n\t\tstageLabel: 'Designing schema',\n\t\trefinePlaceholder: 'e.g. \"make role required and add a hire_date field\"',\n\t\tcall: ({ prompt, history }) =>\n\t\t\taiSchema(workspaceRootDir, {\n\t\t\t\tprompt,\n\t\t\t\thistory,\n\t\t\t\tcontext: { existingModels }\n\t\t\t}),\n\t\trenderPreview: renderModel\n\t});\n\n\tif (!model) return null;\n\treturn { model, workspaceRootDir };\n}\n\nexport async function runLayoutStage(\n\tworkspaceRootDir: string,\n\tmodel: CollectionSpec\n): Promise<FormLayout | null> {\n\treturn aiLoop<FormLayout>({\n\t\tinitialPrompt: '',\n\t\tstageLabel: 'Designing layout',\n\t\trefinePlaceholder: 'e.g. \"single column on mobile\" or \"group address fields\"',\n\t\tcall: ({ prompt, history }) =>\n\t\t\taiForm(workspaceRootDir, {\n\t\t\t\tprompt: prompt || undefined,\n\t\t\t\thistory,\n\t\t\t\tcontext: { model }\n\t\t\t}),\n\t\trenderPreview: renderLayout\n\t});\n}\n\nexport function specToArgv(spec: CollectionSpec): string[] {\n\treturn collectionSpecToArgv(spec);\n}\n\n/**\n * Persist the chosen layout as a sidecar file at\n * `data/ai-form-layouts/<model>.json`. Returns the relative path.\n */\nexport function writeLayoutSidecar(\n\tworkspaceRootDir: string,\n\tmodelName: string,\n\tlayout: FormLayout\n): string {\n\tconst dir = path.join(workspaceRootDir, 'data', 'ai-form-layouts');\n\tfs.mkdirSync(dir, { recursive: true });\n\tconst file = path.join(dir, `${modelName}.json`);\n\tfs.writeFileSync(file, JSON.stringify(layout, null, 2) + '\\n');\n\treturn path.relative(workspaceRootDir, file);\n}\n", "import fs from 'node:fs';\nimport os from 'node:os';\nimport path from 'node:path';\n\nexport interface VelaConfig {\n\tapiKey?: string;\n}\n\nconst CONFIG_DIR = path.join(os.homedir(), '.vela');\nconst CONFIG_PATH = path.join(CONFIG_DIR, 'config.json');\n\nexport function readConfig(): VelaConfig | null {\n\tif (!fs.existsSync(CONFIG_PATH)) return null;\n\ttry {\n\t\treturn JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf8')) as VelaConfig;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nexport function writeConfig(config: VelaConfig): void {\n\tfs.mkdirSync(CONFIG_DIR, { recursive: true });\n\tfs.writeFileSync(CONFIG_PATH, JSON.stringify(config, null, 2));\n}\n\nexport function clearConfig(): void {\n\tif (fs.existsSync(CONFIG_PATH)) fs.unlinkSync(CONFIG_PATH);\n}\n\nexport function requireApiKey(): string {\n\tconst config = readConfig();\n\tif (!config?.apiKey) {\n\t\tthrow new Error('Not logged in. Run `vela login` to login.');\n\t}\n\treturn config.apiKey;\n}\n", "import fs from 'node:fs';\nimport path from 'node:path';\n\nexport interface ProjectConfig {\n\tprojectId: string;\n\tteamId: string;\n\tprojectName: string;\n}\n\nexport function projectConfigPath(workspaceRootDir: string): string {\n\treturn path.join(workspaceRootDir, '.vela', 'project.json');\n}\n\nexport function readProjectConfig(workspaceRootDir: string): ProjectConfig | null {\n\tconst file = projectConfigPath(workspaceRootDir);\n\tif (!fs.existsSync(file)) return null;\n\ttry {\n\t\tconst parsed = JSON.parse(fs.readFileSync(file, 'utf8')) as Partial<ProjectConfig>;\n\t\tif (\n\t\t\ttypeof parsed.projectId !== 'string' ||\n\t\t\ttypeof parsed.teamId !== 'string' ||\n\t\t\ttypeof parsed.projectName !== 'string'\n\t\t) {\n\t\t\treturn null;\n\t\t}\n\t\treturn {\n\t\t\tprojectId: parsed.projectId,\n\t\t\tteamId: parsed.teamId,\n\t\t\tprojectName: parsed.projectName\n\t\t};\n\t} catch {\n\t\treturn null;\n\t}\n}\n\n/**\n * Record the velastack.dev link, keeping everything else in the file.\n *\n * `.vela/project.json` is written by two modules: this one for the link, and\n * `deploy-config.ts` for the app id and target bindings. Replacing the file\n * wholesale here would drop the app id \u2014 which server paths, systemd units and\n * databases all hang off \u2014 and strand the deployment on the server.\n */\nexport function writeProjectConfig(workspaceRootDir: string, config: ProjectConfig): void {\n\tconst file = projectConfigPath(workspaceRootDir);\n\tfs.mkdirSync(path.dirname(file), { recursive: true });\n\n\tlet existing: Record<string, unknown> = {};\n\tif (fs.existsSync(file)) {\n\t\ttry {\n\t\t\texisting = JSON.parse(fs.readFileSync(file, 'utf8')) as Record<string, unknown>;\n\t\t} catch {\n\t\t\t// A corrupt file is replaced rather than merged into.\n\t\t}\n\t}\n\n\tfs.writeFileSync(file, JSON.stringify({ ...existing, ...config }, null, 2) + '\\n');\n}\n", "import { API_URL } from './constants.ts';\nimport { requireApiKey } from './config.ts';\nimport { readProjectConfig } from './project-config.ts';\n\nexport interface AiTurn {\n\trole: 'user' | 'assistant';\n\tcontent: string;\n}\n\nexport interface CollectionFieldSpec {\n\tname: string;\n\ttype: string;\n\trequired?: boolean;\n\tvalues?: string[];\n\tcollectionName?: string;\n\tmaxSelect?: number;\n\tmin?: number;\n\tmax?: number;\n}\n\nexport interface CollectionSpec {\n\tname: string;\n\ttype: string;\n\tfields: CollectionFieldSpec[];\n}\n\nexport interface FormLayoutCol {\n\tspan: 1 | 2 | 3 | 4 | 6 | 12;\n\tfield: string;\n}\n\nexport interface FormLayoutRow {\n\tcols: FormLayoutCol[];\n}\n\nexport interface FormLayout {\n\trows: FormLayoutRow[];\n}\n\nexport interface AiResult<T> {\n\tresult: T;\n\tturn: AiTurn[];\n}\n\ninterface AiSchemaRequest {\n\tprompt: string;\n\thistory?: AiTurn[];\n\tcontext?: { existingModels?: CollectionSpec[] };\n}\n\ninterface AiFormRequest {\n\tprompt?: string;\n\thistory?: AiTurn[];\n\tcontext: { model: CollectionSpec };\n}\n\nasync function aiPost<T>(\n\tworkspaceRootDir: string,\n\tendpoint: 'schema' | 'form',\n\tbody: AiSchemaRequest | AiFormRequest\n): Promise<AiResult<T>> {\n\tconst apiKey = requireApiKey();\n\tconst project = readProjectConfig(workspaceRootDir);\n\tif (!project) {\n\t\tthrow new Error(\n\t\t\t\"This isn't a velastack project (no .vela/project.json). Run `vela create` first.\"\n\t\t);\n\t}\n\n\tconst res = await fetch(`${API_URL}/v1/projects/${project.projectId}/ai/${endpoint}`, {\n\t\tmethod: 'POST',\n\t\theaders: {\n\t\t\t'Content-Type': 'application/json',\n\t\t\tAuthorization: `Bearer ${apiKey}`\n\t\t},\n\t\tbody: JSON.stringify(body)\n\t});\n\n\tif (res.status === 401 || res.status === 403) {\n\t\tthrow new Error('API key invalid \u2014 run `vela login`');\n\t}\n\tif (res.status === 502) {\n\t\tconst msg = await res.text().catch(() => '');\n\t\tthrow new Error(`AI request failed: ${msg || 'upstream error'}`);\n\t}\n\tif (!res.ok) {\n\t\tconst msg = await res.text().catch(() => '');\n\t\tthrow new Error(`Velastack API error (${res.status}): ${msg || res.statusText}`);\n\t}\n\treturn (await res.json()) as AiResult<T>;\n}\n\nexport const aiSchema = (workspaceRootDir: string, body: AiSchemaRequest) =>\n\taiPost<CollectionSpec>(workspaceRootDir, 'schema', body);\n\nexport const aiForm = (workspaceRootDir: string, body: AiFormRequest) =>\n\taiPost<FormLayout>(workspaceRootDir, 'form', body);\n", "import * as p from '@clack/prompts';\nimport type { AiTurn } from './ai-client.ts';\n\nexport interface AiLoopCallContext {\n\tprompt: string;\n\thistory: AiTurn[];\n}\n\nexport interface AiLoopCallResult<T> {\n\tresult: T;\n\tturn: AiTurn[];\n}\n\nexport interface AiLoopOptions<T> {\n\tinitialPrompt: string;\n\tstageLabel: string;\n\trefinePlaceholder: string;\n\tcall: (ctx: AiLoopCallContext) => Promise<AiLoopCallResult<T>>;\n\trenderPreview: (result: T) => void;\n}\n\n/**\n * Run a preview-and-refine loop. Calls `call` with the current prompt + history,\n * renders the preview, then asks the user to refine (non-empty input) or apply\n * (empty input). Cancel exits the loop with `null`.\n */\nexport async function aiLoop<T>(opts: AiLoopOptions<T>): Promise<T | null> {\n\tlet prompt = opts.initialPrompt;\n\tlet history: AiTurn[] = [];\n\tlet attempt = 0;\n\n\twhile (true) {\n\t\tattempt++;\n\t\tconst spinner = p.spinner();\n\t\tspinner.start(`${opts.stageLabel} (${attempt > 1 ? 'iteration ' + attempt : 'first pass'})\u2026`);\n\t\tlet result: T;\n\t\tlet turn: AiTurn[];\n\t\ttry {\n\t\t\tconst out = await opts.call({ prompt, history });\n\t\t\tresult = out.result;\n\t\t\tturn = out.turn;\n\t\t\tspinner.stop(`${opts.stageLabel} ready.`);\n\t\t} catch (e) {\n\t\t\tspinner.stop(`${opts.stageLabel} failed.`);\n\t\t\tthrow e;\n\t\t}\n\n\t\topts.renderPreview(result);\n\n\t\tconst next = await p.text({\n\t\t\tmessage: 'Refine the result, or press Enter to apply.',\n\t\t\tplaceholder: opts.refinePlaceholder,\n\t\t\tdefaultValue: ''\n\t\t});\n\n\t\tif (p.isCancel(next)) return null;\n\t\tconst trimmed = (typeof next === 'string' ? next : '').trim();\n\t\tif (trimmed === '') return result;\n\n\t\thistory = turn;\n\t\tprompt = trimmed;\n\t}\n}\n", "import * as p from '@clack/prompts';\nimport { withPocketbase } from './pocketbase.ts';\nimport type { CollectionFieldSpec, CollectionSpec } from './ai-client.ts';\n\ninterface PbField {\n\tname: string;\n\ttype: string;\n\tsystem?: boolean;\n\trequired?: boolean;\n\tvalues?: string[];\n\tcollectionId?: string;\n\tmaxSelect?: number;\n\tmin?: number;\n\tmax?: number;\n}\n\ninterface PbCollection {\n\tid: string;\n\tname: string;\n\ttype: string;\n\tsystem?: boolean;\n\tfields: PbField[];\n}\n\n/**\n * Load existing user-defined collections from the project's PocketBase.\n * Returns [] (with a warning) if PocketBase is unreachable.\n */\nexport async function loadExistingModels(workspaceRootDir: string): Promise<CollectionSpec[]> {\n\tlet result: CollectionSpec[] = [];\n\ttry {\n\t\tawait withPocketbase(workspaceRootDir, async (pb) => {\n\t\t\tconst all = (await pb.collections.getFullList()) as unknown as PbCollection[];\n\t\t\tconst userCollections = all.filter((c) => !c.system);\n\t\t\tconst byId = new Map(userCollections.map((c) => [c.id, c.name]));\n\t\t\tresult = userCollections.map((c) => ({\n\t\t\t\tname: c.name,\n\t\t\t\ttype: c.type,\n\t\t\t\tfields: c.fields\n\t\t\t\t\t.filter((f) => !f.system)\n\t\t\t\t\t.map<CollectionFieldSpec>((f) => ({\n\t\t\t\t\t\tname: f.name,\n\t\t\t\t\t\ttype: f.type,\n\t\t\t\t\t\trequired: f.required,\n\t\t\t\t\t\tvalues: f.values,\n\t\t\t\t\t\tcollectionName: f.collectionId ? byId.get(f.collectionId) : undefined,\n\t\t\t\t\t\tmaxSelect: f.maxSelect,\n\t\t\t\t\t\tmin: f.min,\n\t\t\t\t\t\tmax: f.max\n\t\t\t\t\t}))\n\t\t\t}));\n\t\t});\n\t} catch (e) {\n\t\tconst msg = e instanceof Error ? e.message : String(e);\n\t\tp.log.warn(\n\t\t\t`Could not load existing schema from PocketBase (${msg}). The AI agent will design without that context.`\n\t\t);\n\t\treturn [];\n\t}\n\treturn result;\n}\n", "import * as p from '@clack/prompts';\nimport type { CollectionFieldSpec, CollectionSpec } from './ai-client.ts';\n\nconst PRIMITIVE_TYPES = new Set(['text', 'number', 'bool', 'email', 'date', 'url', 'file']);\n\nfunction singularize(name: string): string {\n\tif (name.endsWith('ies') && name.length > 3) return `${name.slice(0, -3)}y`;\n\tif (name.endsWith('s') && !name.endsWith('ss')) return name.slice(0, -1);\n\treturn name;\n}\n\nfunction typeArg(field: CollectionFieldSpec): string | null {\n\tif (field.type === 'select' && field.values && field.values.length > 0) {\n\t\treturn `select(${field.values.join(',')})`;\n\t}\n\tif (field.type === 'relation') {\n\t\tif (!field.collectionName) return null;\n\t\treturn singularize(field.collectionName);\n\t}\n\tif (PRIMITIVE_TYPES.has(field.type)) return field.type;\n\treturn null;\n}\n\n/**\n * Convert a CollectionSpec to argv for the patterns package.\n * Drops + warns on fields that can't be expressed cleanly.\n */\nexport function collectionSpecToArgv(spec: CollectionSpec): string[] {\n\tconst argv: string[] = [spec.name];\n\tfor (const field of spec.fields) {\n\t\tconst type = typeArg(field);\n\t\tif (type === null) {\n\t\t\tp.log.warn(\n\t\t\t\t`Skipping field \"${field.name}\" (type \"${field.type}\" cannot be represented as a pattern argument)`\n\t\t\t);\n\t\t\tcontinue;\n\t\t}\n\t\tconst required = field.required ? '!' : '';\n\t\targv.push(`${field.name}:${type}${required}`);\n\t}\n\treturn argv;\n}\n", "import type { FormLayout } from './ai-client.ts';\n\nconst TOTAL_COLS = 12;\nconst MIN_TERM_WIDTH = 60;\n\nfunction pad(s: string, width: number): string {\n\tif (s.length >= width) return s.slice(0, width);\n\treturn s + ' '.repeat(width - s.length);\n}\n\nfunction colWidths(layout: FormLayout, terminalWidth: number): number[][] {\n\tconst innerWidth = Math.max(MIN_TERM_WIDTH, terminalWidth) - 2;\n\treturn layout.rows.map((row) => {\n\t\tconst cellWidths: number[] = [];\n\t\tlet used = 0;\n\t\tfor (let i = 0; i < row.cols.length; i++) {\n\t\t\tconst col = row.cols[i]!;\n\t\t\tconst isLast = i === row.cols.length - 1;\n\t\t\tconst target = Math.round((innerWidth * col.span) / TOTAL_COLS);\n\t\t\tconst w = isLast ? innerWidth - used : Math.max(target, col.field.length + 2);\n\t\t\tcellWidths.push(w);\n\t\t\tused += w;\n\t\t}\n\t\treturn cellWidths;\n\t});\n}\n\n/**\n * Render a FormLayout as an ASCII grid. Falls back to a list view when\n * the terminal is narrower than MIN_TERM_WIDTH.\n */\nexport function renderGrid(\n\tlayout: FormLayout,\n\tterminalWidth = process.stdout.columns ?? 80\n): string {\n\tif (terminalWidth < MIN_TERM_WIDTH) {\n\t\treturn layout.rows\n\t\t\t.map((row, i) => `row ${i + 1}: ${row.cols.map((c) => `${c.field}(${c.span})`).join(' | ')}`)\n\t\t\t.join('\\n');\n\t}\n\n\tconst widths = colWidths(layout, terminalWidth);\n\tconst lines: string[] = [];\n\n\tfor (let r = 0; r < layout.rows.length; r++) {\n\t\tconst row = layout.rows[r]!;\n\t\tconst w = widths[r]!;\n\n\t\tconst top = r === 0 ? '\u250C' + w.map((width) => '\u2500'.repeat(width)).join('\u252C') + '\u2510' : '';\n\t\tif (top) lines.push(top);\n\n\t\tconst content = '\u2502' + row.cols.map((c, i) => ' ' + pad(c.field, w[i]! - 1)).join('\u2502') + '\u2502';\n\t\tlines.push(content);\n\n\t\tconst isLast = r === layout.rows.length - 1;\n\t\tif (isLast) {\n\t\t\tlines.push('\u2514' + w.map((width) => '\u2500'.repeat(width)).join('\u2534') + '\u2518');\n\t\t} else {\n\t\t\tconst nextW = widths[r + 1]!;\n\t\t\tlines.push(buildSeparator(w, nextW));\n\t\t}\n\t}\n\n\treturn lines.join('\\n');\n}\n\nfunction buildSeparator(curr: number[], next: number[]): string {\n\tconst currBoundaries = new Set<number>();\n\tlet pos = 0;\n\tfor (let i = 0; i < curr.length - 1; i++) {\n\t\tpos += curr[i]!;\n\t\tcurrBoundaries.add(pos);\n\t}\n\n\tconst nextBoundaries = new Set<number>();\n\tpos = 0;\n\tfor (let i = 0; i < next.length - 1; i++) {\n\t\tpos += next[i]!;\n\t\tnextBoundaries.add(pos);\n\t}\n\n\tconst total = curr.reduce((a, b) => a + b, 0);\n\tlet line = '\u251C';\n\tfor (let i = 0; i < total; i++) {\n\t\tconst inCurr = currBoundaries.has(i);\n\t\tconst inNext = nextBoundaries.has(i);\n\t\tif (inCurr && inNext) line += '\u253C';\n\t\telse if (inCurr) line += '\u2534';\n\t\telse if (inNext) line += '\u252C';\n\t\telse line += '\u2500';\n\t}\n\tline += '\u2524';\n\treturn line;\n}\n", "import { Command } from 'commander';\nimport * as p from '@clack/prompts';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand } from '../../lib/run.ts';\nimport { runPattern } from '../../lib/pattern-runner.ts';\nimport { runSchemaStage, specToArgv } from '../../lib/ai-flow.ts';\n\nexport const schema = new Command('schema')\n\t.description('generate a schema from a model')\n\t.argument('[model]', 'model name')\n\t.argument('[fields...]', 'field definitions')\n\t.option('--ai <description>', 'design the schema with AI from a natural-language description')\n\t.allowUnknownOption(true)\n\t.configureHelp(helpConfig)\n\t.action((model: string | undefined, fields: string[], options: { ai?: string }) =>\n\t\trunCommand(async () => {\n\t\t\tlet argv: string[];\n\t\t\tlet modelName: string;\n\n\t\t\tif (options.ai) {\n\t\t\t\tif (model) {\n\t\t\t\t\tthrow new Error('Pass either a model name or --ai, not both.');\n\t\t\t\t}\n\t\t\t\tconst stage = await runSchemaStage({ prompt: options.ai, useCase: 'schema' });\n\t\t\t\tif (!stage) {\n\t\t\t\t\tp.cancel('Aborted before any files were written.');\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\targv = specToArgv(stage.model);\n\t\t\t\tmodelName = stage.model.name;\n\t\t\t} else {\n\t\t\t\tif (!model) {\n\t\t\t\t\tthrow new Error('Missing required argument: model. Pass a model name or use --ai.');\n\t\t\t\t}\n\t\t\t\targv = [model, ...fields];\n\t\t\t\tmodelName = model;\n\t\t\t}\n\n\t\t\tawait runPattern(\n\t\t\t\t'generate-schema',\n\t\t\t\targv,\n\t\t\t\t{},\n\t\t\t\t{\n\t\t\t\t\tsummary: `Created ${modelName} schema.`,\n\t\t\t\t\tnextSteps: [\n\t\t\t\t\t\t`Edit field types and validation in src/lib/schemas/${modelName}.ts.`,\n\t\t\t\t\t\t`Run \\`vela generate form ${modelName}\\` to add a form for this schema.`\n\t\t\t\t\t],\n\t\t\t\t\ttask: {\n\t\t\t\t\t\ttitle: 'Generating schema',\n\t\t\t\t\t\tsuccess: 'Generated schema',\n\t\t\t\t\t\terror: 'Failed to generate schema'\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t);\n\t\t}, 'Failed to generate schema.')\n\t);\n", "import { Command } from 'commander';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand } from '../../lib/run.ts';\nimport { runPattern } from '../../lib/pattern-runner.ts';\n\nexport const resource = new Command('resource')\n\t.description('generate a resource (model + CRUD pages)')\n\t.argument('<model>', 'model name')\n\t.argument('[fields...]', 'field definitions')\n\t.allowUnknownOption(true)\n\t.configureHelp(helpConfig)\n\t.action((model: string, fields: string[]) =>\n\t\trunCommand(\n\t\t\t() =>\n\t\t\t\trunPattern(\n\t\t\t\t\t'generate-resource',\n\t\t\t\t\t[model, ...fields],\n\t\t\t\t\t{},\n\t\t\t\t\t{\n\t\t\t\t\t\tsummary: `Created ${model} resource.`,\n\t\t\t\t\t\tnextSteps: [\n\t\t\t\t\t\t\t`Run \\`vela fixtures generate\\` to create some ${model} records for development.`,\n\t\t\t\t\t\t\t`Run \\`vela dev\\` and visit /${model} to see the CRUD pages.`,\n\t\t\t\t\t\t\t`Customize the UI in src/routes/${model}/+page.svelte.`\n\t\t\t\t\t\t],\n\t\t\t\t\t\ttask: {\n\t\t\t\t\t\t\ttitle: 'Generating resource',\n\t\t\t\t\t\t\tsuccess: 'Generated resource',\n\t\t\t\t\t\t\terror: 'Failed to generate resource'\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t),\n\t\t\t'Failed to generate resource.'\n\t\t)\n\t);\n", "import { Command } from 'commander';\nimport * as p from '@clack/prompts';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand } from '../../lib/run.ts';\nimport { runPattern } from '../../lib/pattern-runner.ts';\nimport {\n\trunSchemaStage,\n\trunLayoutStage,\n\tspecToArgv,\n\twriteLayoutSidecar\n} from '../../lib/ai-flow.ts';\n\nexport const scaffold = new Command('scaffold')\n\t.description('generate a full CRUD scaffold (model, forms, list, detail)')\n\t.argument('[model]', 'model name')\n\t.argument('[fields...]', 'field definitions')\n\t.option('--remote', 'generate a scaffold backed by a remote PocketBase collection')\n\t.option(\n\t\t'--route <route>',\n\t\t'place the scaffold at a custom route (e.g. \"(app)/[team_id]/projects\"). Defaults to the pluralized model name under (app)/(public).'\n\t)\n\t.option(\n\t\t'--ai <description>',\n\t\t'design the scaffold with AI from a natural-language description (two stages: schema \u2192 layout)'\n\t)\n\t.allowUnknownOption(true)\n\t.configureHelp(helpConfig)\n\t.action(\n\t\t(\n\t\t\tmodel: string | undefined,\n\t\t\tfields: string[],\n\t\t\toptions: { remote?: boolean; route?: string; ai?: string }\n\t\t) =>\n\t\t\trunCommand(async () => {\n\t\t\t\tlet argv: string[];\n\t\t\t\tlet modelName: string;\n\t\t\t\tlet sidecarPath: string | null = null;\n\n\t\t\t\tif (options.ai) {\n\t\t\t\t\tif (model) {\n\t\t\t\t\t\tthrow new Error('Pass either a model name or --ai, not both.');\n\t\t\t\t\t}\n\t\t\t\t\tconst stage = await runSchemaStage({ prompt: options.ai, useCase: 'scaffold' });\n\t\t\t\t\tif (!stage) {\n\t\t\t\t\t\tp.cancel('Aborted before any files were written.');\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tconst layout = await runLayoutStage(stage.workspaceRootDir, stage.model);\n\t\t\t\t\tif (!layout) {\n\t\t\t\t\t\tp.cancel('Aborted before any files were written.');\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\targv = specToArgv(stage.model);\n\t\t\t\t\tmodelName = stage.model.name;\n\t\t\t\t\tsidecarPath = writeLayoutSidecar(stage.workspaceRootDir, modelName, layout);\n\t\t\t\t} else {\n\t\t\t\t\tif (!model) {\n\t\t\t\t\t\tthrow new Error('Missing required argument: model. Pass a model name or use --ai.');\n\t\t\t\t\t}\n\t\t\t\t\targv = [model, ...fields];\n\t\t\t\t\tmodelName = model;\n\t\t\t\t}\n\n\t\t\t\tconst slug = options.remote ? 'generate-scaffold-remote' : 'generate-scaffold';\n\t\t\t\tconst nextSteps: string[] = [\n\t\t\t\t\t`Run \\`vela fixtures generate\\` to create 10 ${modelName} records for development.`,\n\t\t\t\t\t'Run `vela dev` and visit the generated route to use the scaffold.',\n\t\t\t\t\t'Tweak list columns and detail layout in the generated +page.svelte files.'\n\t\t\t\t];\n\t\t\t\tif (sidecarPath) {\n\t\t\t\t\tnextSteps.unshift(\n\t\t\t\t\t\t`Apply the AI-designed form layout from ${sidecarPath} to the generated new/edit +page.svelte files.`\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tawait runPattern(\n\t\t\t\t\tslug,\n\t\t\t\t\targv,\n\t\t\t\t\t{ route: options.route },\n\t\t\t\t\t{\n\t\t\t\t\t\tsummary: `Created ${modelName} scaffold.`,\n\t\t\t\t\t\tnextSteps,\n\t\t\t\t\t\ttask: {\n\t\t\t\t\t\t\ttitle: 'Generating scaffold',\n\t\t\t\t\t\t\tsuccess: 'Generated scaffold',\n\t\t\t\t\t\t\terror: 'Failed to generate scaffold'\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t);\n\t\t\t}, 'Failed to generate scaffold.')\n\t);\n", "import { Command } from 'commander';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand } from '../../lib/run.ts';\nimport { runPattern } from '../../lib/pattern-runner.ts';\n\nexport const migration = new Command('migration')\n\t.description('generate a migration for an existing collection')\n\t.argument('<collection>', 'collection name')\n\t.argument('<op>', 'operation (add, remove, rename, references)')\n\t.argument('[args...]', 'operation arguments (e.g. \"birthday:date\")')\n\t.allowUnknownOption(true)\n\t.configureHelp(helpConfig)\n\t.action((collection: string, op: string, args: string[]) =>\n\t\trunCommand(\n\t\t\t() =>\n\t\t\t\trunPattern(\n\t\t\t\t\t'generate-migration',\n\t\t\t\t\t[collection, op, ...args],\n\t\t\t\t\t{},\n\t\t\t\t\t{\n\t\t\t\t\t\tsummary: `Created ${op} migration for ${collection}.`,\n\t\t\t\t\t\tnextSteps: [\n\t\t\t\t\t\t\t'Review the generated migration file in migrations/.',\n\t\t\t\t\t\t\t'Run `vela migrate up` to apply the migration.'\n\t\t\t\t\t\t],\n\t\t\t\t\t\ttask: {\n\t\t\t\t\t\t\ttitle: 'Generating migration',\n\t\t\t\t\t\t\tsuccess: 'Generated migration',\n\t\t\t\t\t\t\terror: 'Failed to generate migration'\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t),\n\t\t\t'Failed to generate migration.'\n\t\t)\n\t);\n", "import { Command } from 'commander';\nimport { helpConfig } from '../lib/help.ts';\nimport { auth } from './enable/auth.ts';\nimport { api } from './enable/api.ts';\nimport { apiKeys } from './enable/api-keys.ts';\nimport { backend } from './enable/backend.ts';\nimport { i18n } from './enable/i18n.ts';\nimport { teams } from './enable/teams.ts';\nimport { payments } from './enable/payments.ts';\nimport { subscriptions } from './enable/subscriptions.ts';\nimport { s3 } from './enable/s3.ts';\nimport { smtp } from './enable/smtp.ts';\nimport { cms } from './enable/cms.ts';\nimport { blog } from './enable/blog.ts';\nimport { contentNegotiation } from './enable/content-negotiation.ts';\n\nexport const enable = new Command('enable')\n\t.description('enable features')\n\t.configureHelp(helpConfig)\n\t.addCommand(auth)\n\t.addCommand(api)\n\t.addCommand(apiKeys)\n\t.addCommand(backend)\n\t.addCommand(contentNegotiation)\n\t.addCommand(i18n)\n\t.addCommand(teams)\n\t.addCommand(payments)\n\t.addCommand(subscriptions)\n\t.addCommand(s3)\n\t.addCommand(smtp)\n\t.addCommand(cms)\n\t.addCommand(blog);\n", "import { Command } from 'commander';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand } from '../../lib/run.ts';\nimport { runPattern } from '../../lib/pattern-runner.ts';\n\nexport const auth = new Command('auth')\n\t.description('enable authentication (email/password + OAuth scaffold)')\n\t.allowUnknownOption(true)\n\t.configureHelp(helpConfig)\n\t.action((_opts, cmd) =>\n\t\trunCommand(\n\t\t\t() =>\n\t\t\t\trunPattern(\n\t\t\t\t\t'enable-auth',\n\t\t\t\t\tcmd.args,\n\t\t\t\t\t{},\n\t\t\t\t\t{\n\t\t\t\t\t\tsummary: 'Enabled authentication.',\n\t\t\t\t\t\tnextSteps: [\n\t\t\t\t\t\t\t'Run `vela dev` and visit /login to try the new sign-in flow.',\n\t\t\t\t\t\t\t'Customize sign-in copy and providers in src/routes/(public)/(auth)/.',\n\t\t\t\t\t\t\t'Add OAuth providers via `vela oauth` (coming soon) or in the PocketBase admin UI.'\n\t\t\t\t\t\t],\n\t\t\t\t\t\ttask: {\n\t\t\t\t\t\t\ttitle: 'Enabling auth',\n\t\t\t\t\t\t\tsuccess: 'Enabled auth',\n\t\t\t\t\t\t\terror: 'Failed to enable auth'\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t),\n\t\t\t'Failed to enable auth.'\n\t\t)\n\t);\n", "import { Command } from 'commander';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand } from '../../lib/run.ts';\nimport { runPattern } from '../../lib/pattern-runner.ts';\n\nexport const api = new Command('api')\n\t.description('enable the PocketBase REST API')\n\t.allowUnknownOption(true)\n\t.configureHelp(helpConfig)\n\t.action((_opts, cmd) =>\n\t\trunCommand(\n\t\t\t() =>\n\t\t\t\trunPattern(\n\t\t\t\t\t'enable-api',\n\t\t\t\t\tcmd.args,\n\t\t\t\t\t{},\n\t\t\t\t\t{\n\t\t\t\t\t\tsummary: 'Enabled the PocketBase REST API.',\n\t\t\t\t\t\tnextSteps: [\n\t\t\t\t\t\t\t'Run `vela dev` to try the API at /api/collections/*.',\n\t\t\t\t\t\t\t'Adjust collection-level rules in the PocketBase admin UI or via migrations.',\n\t\t\t\t\t\t\t'Run `vela enable api-keys` if you want to issue machine-to-machine tokens.'\n\t\t\t\t\t\t],\n\t\t\t\t\t\ttask: {\n\t\t\t\t\t\t\ttitle: 'Enabling api',\n\t\t\t\t\t\t\tsuccess: 'Enabled api',\n\t\t\t\t\t\t\terror: 'Failed to enable api'\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t),\n\t\t\t'Failed to enable API.'\n\t\t)\n\t);\n", "import { Command } from 'commander';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand } from '../../lib/run.ts';\nimport { runPattern } from '../../lib/pattern-runner.ts';\n\nexport const apiKeys = new Command('api-keys')\n\t.description('enable API key management')\n\t.allowUnknownOption(true)\n\t.configureHelp(helpConfig)\n\t.action((_opts, cmd) =>\n\t\trunCommand(\n\t\t\t() =>\n\t\t\t\trunPattern(\n\t\t\t\t\t'enable-api-keys',\n\t\t\t\t\tcmd.args,\n\t\t\t\t\t{},\n\t\t\t\t\t{\n\t\t\t\t\t\tsummary: 'Enabled API key management.',\n\t\t\t\t\t\tnextSteps: [\n\t\t\t\t\t\t\t'Run `vela dev` and visit /account/api-keys to issue your first key.',\n\t\t\t\t\t\t\t'Customize the API key UI in src/routes/(app)/account/api-keys/.',\n\t\t\t\t\t\t\t'Protect API routes by reading `locals.apiKey` in your +server.ts handlers.'\n\t\t\t\t\t\t],\n\t\t\t\t\t\ttask: {\n\t\t\t\t\t\t\ttitle: 'Enabling api keys',\n\t\t\t\t\t\t\tsuccess: 'Enabled api keys',\n\t\t\t\t\t\t\terror: 'Failed to enable api keys'\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t),\n\t\t\t'Failed to enable API keys.'\n\t\t)\n\t);\n", "import { Command } from 'commander';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand } from '../../lib/run.ts';\nimport { runPattern } from '../../lib/pattern-runner.ts';\n\nexport const backend = new Command('backend')\n\t.description('enable the PocketBase backend')\n\t.allowUnknownOption(true)\n\t.configureHelp(helpConfig)\n\t.action((_opts, cmd) =>\n\t\trunCommand(\n\t\t\t() =>\n\t\t\t\trunPattern(\n\t\t\t\t\t'enable-backend',\n\t\t\t\t\tcmd.args,\n\t\t\t\t\t{},\n\t\t\t\t\t{\n\t\t\t\t\t\tsummary: 'Enabled the PocketBase backend.',\n\t\t\t\t\t\tnextSteps: [\n\t\t\t\t\t\t\t'Set POCKETBASE_URL, POCKETBASE_SUPERUSER_EMAIL, and POCKETBASE_SUPERUSER_PASSWORD in your environment.',\n\t\t\t\t\t\t\t'Run `vela dev` to start with PocketBase wired up.',\n\t\t\t\t\t\t\t'Run `vela enable auth` to add user authentication on top of the backend.'\n\t\t\t\t\t\t],\n\t\t\t\t\t\ttask: {\n\t\t\t\t\t\t\ttitle: 'Enabling backend',\n\t\t\t\t\t\t\tsuccess: 'Enabled backend',\n\t\t\t\t\t\t\terror: 'Failed to enable backend'\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t),\n\t\t\t'Failed to enable backend.'\n\t\t)\n\t);\n", "import { Command } from 'commander';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand } from '../../lib/run.ts';\nimport { runPattern } from '../../lib/pattern-runner.ts';\n\nexport const i18n = new Command('i18n')\n\t.description('enable internationalization')\n\t.allowUnknownOption(true)\n\t.configureHelp(helpConfig)\n\t.action((_opts, cmd) =>\n\t\trunCommand(\n\t\t\t() =>\n\t\t\t\trunPattern(\n\t\t\t\t\t'enable-i18n',\n\t\t\t\t\tcmd.args,\n\t\t\t\t\t{},\n\t\t\t\t\t{\n\t\t\t\t\t\tsummary: 'Enabled internationalization.',\n\t\t\t\t\t\tnextSteps: [\n\t\t\t\t\t\t\t'Add or adjust locales in wuchale.config.js.',\n\t\t\t\t\t\t\t'Run `vela i18n extract` to pull translatable strings from your components.',\n\t\t\t\t\t\t\t'Edit the generated .po files under locales/ to add translations.'\n\t\t\t\t\t\t],\n\t\t\t\t\t\ttask: {\n\t\t\t\t\t\t\ttitle: 'Enabling i18n',\n\t\t\t\t\t\t\tsuccess: 'Enabled i18n',\n\t\t\t\t\t\t\terror: 'Failed to enable i18n'\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t),\n\t\t\t'Failed to enable i18n.'\n\t\t)\n\t);\n", "import { Command } from 'commander';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand } from '../../lib/run.ts';\nimport { runPattern } from '../../lib/pattern-runner.ts';\n\nexport const teams = new Command('teams')\n\t.description('enable team / multi-tenant support')\n\t.allowUnknownOption(true)\n\t.configureHelp(helpConfig)\n\t.action((_opts, cmd) =>\n\t\trunCommand(\n\t\t\t() =>\n\t\t\t\trunPattern(\n\t\t\t\t\t'enable-teams',\n\t\t\t\t\tcmd.args,\n\t\t\t\t\t{},\n\t\t\t\t\t{\n\t\t\t\t\t\tsummary: 'Enabled teams.',\n\t\t\t\t\t\tnextSteps: [\n\t\t\t\t\t\t\t'Run `vela dev` and visit /account/teams to create a team and invite members.',\n\t\t\t\t\t\t\t'Scope your queries by `team_id` when reading or writing tenant data.',\n\t\t\t\t\t\t\t'Customize the team settings pages in src/routes/(app)/account/teams/.'\n\t\t\t\t\t\t],\n\t\t\t\t\t\ttask: {\n\t\t\t\t\t\t\ttitle: 'Enabling teams',\n\t\t\t\t\t\t\tsuccess: 'Enabled teams',\n\t\t\t\t\t\t\terror: 'Failed to enable teams'\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t),\n\t\t\t'Failed to enable teams.'\n\t\t)\n\t);\n", "import process from 'node:process';\nimport { Command } from 'commander';\nimport * as p from '@clack/prompts';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand } from '../../lib/run.ts';\nimport { runPattern } from '../../lib/pattern-runner.ts';\n\ntype Provider = 'stripe';\n\nconst PROVIDERS: Array<{ value: Provider; label: string }> = [{ value: 'stripe', label: 'Stripe' }];\n\nexport const payments = new Command('payments')\n\t.description('enable payments')\n\t.option('--provider <provider>', 'payment provider', 'stripe')\n\t.allowUnknownOption(true)\n\t.configureHelp(helpConfig)\n\t.action((opts, cmd) =>\n\t\trunCommand(async () => {\n\t\t\tconst provider = await resolveProvider(opts.provider, cmd.getOptionValueSource('provider'));\n\n\t\t\tconst input = {\n\t\t\t\tprovider,\n\t\t\t\tstripeSecretKey: await ensureKey('STRIPE_SECRET_KEY', 'Stripe secret key (sk_...)'),\n\t\t\t\tstripePublishableKey: await ensureKey(\n\t\t\t\t\t'PUBLIC_STRIPE_PUBLISHABLE_KEY',\n\t\t\t\t\t'Stripe publishable key (pk_...)'\n\t\t\t\t),\n\t\t\t\tstripeWebhookSecret: await ensureWebhookSecret(),\n\t\t\t\tstripePriceId: await ensurePriceId()\n\t\t\t};\n\t\t\tawait runPattern('enable-payments', cmd.args, input, {\n\t\t\t\tsummary: 'Enabled Stripe payments.',\n\t\t\t\tnextSteps: [\n\t\t\t\t\t'Forward Stripe webhooks locally with `stripe listen --forward-to localhost:5173/webhooks/stripe`.',\n\t\t\t\t\t'Run `vela dev` and visit /payment to run through the checkout flow.',\n\t\t\t\t\t'Add products and prices in the Stripe dashboard.'\n\t\t\t\t],\n\t\t\t\ttask: {\n\t\t\t\t\ttitle: 'Enabling payments',\n\t\t\t\t\tsuccess: 'Enabled payments',\n\t\t\t\t\terror: 'Failed to enable payments'\n\t\t\t\t}\n\t\t\t});\n\t\t}, 'Failed to enable payments.')\n\t);\n\nasync function resolveProvider(value: string, source: string | undefined): Promise<Provider> {\n\tif (source && source !== 'default') {\n\t\tif (!PROVIDERS.some((o) => o.value === value)) {\n\t\t\tthrow new Error(`Unknown payment provider: ${value}`);\n\t\t}\n\t\treturn value as Provider;\n\t}\n\n\tconst selected = await p.select<Provider>({\n\t\tmessage: 'Which payment provider?',\n\t\toptions: PROVIDERS,\n\t\tinitialValue: 'stripe'\n\t});\n\tif (p.isCancel(selected)) {\n\t\tp.cancel('Operation cancelled.');\n\t\tprocess.exit(0);\n\t}\n\treturn selected;\n}\n\nasync function ensureWebhookSecret(): Promise<string> {\n\tconst existing = process.env.STRIPE_WEBHOOK_SECRET;\n\tif (existing) return existing;\n\n\tp.note(\n\t\t[\n\t\t\t'Download the Stripe CLI (https://stripe.com/docs/stripe-cli), then run:',\n\t\t\t' stripe listen --forward-to localhost:5173/webhooks/stripe',\n\t\t\t'Copy the whsec_... value it prints and paste it below.'\n\t\t].join('\\n'),\n\t\t'Stripe webhook signing secret',\n\t\t{ format: (line) => line }\n\t);\n\n\treturn promptPassword('Stripe webhook signing secret (whsec_...)');\n}\n\nasync function ensurePriceId(): Promise<string> {\n\tp.note(\n\t\t[\n\t\t\t'Stripe checkout requires a product and price_id.',\n\t\t\t'If you have a demo product price_id, enter it below, or leave blank to create a demo one for you.'\n\t\t].join('\\n'),\n\t\t'Stripe demo product',\n\t\t{ format: (line) => line }\n\t);\n\n\tconst value = await p.text({\n\t\tmessage: 'Stripe price_id (price_...)',\n\t\tplaceholder: 'leave blank to create a demo product'\n\t});\n\tif (p.isCancel(value)) {\n\t\tp.cancel('Operation cancelled.');\n\t\tprocess.exit(0);\n\t}\n\treturn (value ?? '').trim();\n}\n\nasync function ensureKey(envVar: string, message: string): Promise<string> {\n\tconst existing = process.env[envVar];\n\tif (existing) return existing;\n\treturn promptPassword(message);\n}\n\nasync function promptPassword(message: string): Promise<string> {\n\tconst value = await p.password({\n\t\tmessage,\n\t\tvalidate: (v) => (v && v.length ? undefined : 'Required')\n\t});\n\tif (p.isCancel(value)) {\n\t\tp.cancel('Operation cancelled.');\n\t\tprocess.exit(0);\n\t}\n\treturn value;\n}\n", "import { Command } from 'commander';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand } from '../../lib/run.ts';\nimport { runPattern } from '../../lib/pattern-runner.ts';\n\nexport const subscriptions = new Command('subscriptions')\n\t.description('enable Stripe subscriptions (requires auth and payments)')\n\t.allowUnknownOption(true)\n\t.configureHelp(helpConfig)\n\t.action((_opts, cmd) =>\n\t\trunCommand(\n\t\t\t() =>\n\t\t\t\trunPattern(\n\t\t\t\t\t'enable-subscriptions',\n\t\t\t\t\tcmd.args,\n\t\t\t\t\t{},\n\t\t\t\t\t{\n\t\t\t\t\t\tsummary: 'Enabled subscriptions.',\n\t\t\t\t\t\tnextSteps: [\n\t\t\t\t\t\t\t'Create a recurring price in the Stripe dashboard and add its price_id where users can select a plan.',\n\t\t\t\t\t\t\t'Forward webhooks locally with `stripe listen --forward-to localhost:5173/webhooks/stripe`.',\n\t\t\t\t\t\t\t'Run `vela dev` and visit /billing to subscribe, cancel, or resume a plan.'\n\t\t\t\t\t\t],\n\t\t\t\t\t\ttask: {\n\t\t\t\t\t\t\ttitle: 'Enabling subscriptions',\n\t\t\t\t\t\t\tsuccess: 'Enabled subscriptions',\n\t\t\t\t\t\t\terror: 'Failed to enable subscriptions'\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t),\n\t\t\t'Failed to enable subscriptions.'\n\t\t)\n\t);\n", "import process from 'node:process';\nimport { Command } from 'commander';\nimport * as p from '@clack/prompts';\nimport pc from 'picocolors';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand } from '../../lib/run.ts';\nimport { reportResult } from '../../lib/result-report.ts';\nimport { addTargetOptions } from '../../lib/server-command.ts';\nimport { withBackupTarget, type BackupContext } from '../../lib/backup-target.ts';\nimport {\n\tapplyS3,\n\tdefaultForcePathStyle,\n\thasLocalUploads,\n\treadS3,\n\ttype S3Config,\n\ttype S3Filesystem\n} from '../../lib/s3-settings.ts';\nimport { remotePaths } from '../../lib/remote.ts';\n\ninterface Options {\n\tbackups?: boolean;\n\tforce?: boolean;\n\tendpoint?: string;\n\tbucket?: string;\n\tregion?: string;\n\taccessKey?: string;\n\tsecret?: string;\n\tforcePathStyle?: boolean;\n}\n\nexport const s3 = addTargetOptions(\n\tnew Command('s3')\n\t\t.description('enable S3 file storage')\n\t\t.option('--backups', 'configure where backups are kept, not where uploads go')\n\t\t.option('--endpoint <url>', 'S3 endpoint URL')\n\t\t.option('--bucket <name>', 'S3 bucket name')\n\t\t.option('--region <region>', 'S3 region')\n\t\t.option('--access-key <key>', 'S3 access key')\n\t\t.option('--secret <secret>', 'S3 secret key \u2014 prefer VELA_S3_SECRET')\n\t\t.option('--force-path-style', 'address the bucket in the path (MinIO, Ceph)')\n\t\t.option('--no-force-path-style', 'address the bucket as a subdomain (AWS, R2)')\n\t\t.option('--force', 'enable it even though uploads already exist on disk')\n\t\t.configureHelp(helpConfig),\n\t'local'\n).action((raw: unknown) =>\n\trunCommand(() => {\n\t\tconst options = raw as Options;\n\t\tconst filesystem: S3Filesystem = options.backups ? 'backups' : 'storage';\n\n\t\treturn withBackupTarget(raw, 'enable s3', async (ctx) => {\n\t\t\tif (filesystem === 'storage') await guardExistingUploads(ctx, options);\n\n\t\t\tconst existing = await readS3(ctx.pb, filesystem);\n\t\t\tconst config = await promptConfig(options, existing);\n\n\t\t\tawait applyS3(ctx.pb, config, filesystem);\n\n\t\t\t// The old code swallowed this. A wrong path style is exactly what the\n\t\t\t// test reports, so throwing the message away threw away the diagnosis.\n\t\t\tlet failure = '';\n\t\t\ttry {\n\t\t\t\tawait ctx.pb.settings.testS3(filesystem);\n\t\t\t} catch (error) {\n\t\t\t\tfailure = error instanceof Error ? error.message : String(error);\n\t\t\t}\n\n\t\t\tif (failure) {\n\t\t\t\tp.log.warn(\n\t\t\t\t\t`The connection test failed \u2014 the settings are saved but may be wrong.\\n\\n` +\n\t\t\t\t\t\t`${pc.dim(failure)}\\n\\n` +\n\t\t\t\t\t\t`If the bucket is not on AWS or R2, try ${pc.cyan('--force-path-style')}.`\n\t\t\t\t);\n\t\t\t}\n\n\t\t\treportResult({\n\t\t\t\tsummary: failure\n\t\t\t\t\t? `Enabled S3 ${label(filesystem)} on ${ctx.targetName}.`\n\t\t\t\t\t: `Enabled S3 ${label(filesystem)} on ${ctx.targetName} (connection verified).`,\n\t\t\t\tnextSteps:\n\t\t\t\t\tfilesystem === 'backups'\n\t\t\t\t\t\t? [\n\t\t\t\t\t\t\t\t'`vela backup create` now writes archives to the bucket instead of the server.',\n\t\t\t\t\t\t\t\t'Run `vela disable s3 --backups` to keep them on the server again.'\n\t\t\t\t\t\t\t]\n\t\t\t\t\t\t: [\n\t\t\t\t\t\t\t\t'New uploads go to the bucket. Files already on disk are not moved.',\n\t\t\t\t\t\t\t\t'`vela backup create` no longer captures uploads \u2014 PocketBase leaves them out whenever S3 is on. Bucket versioning is what protects them now.',\n\t\t\t\t\t\t\t\t'Run `vela enable s3 --backups` to get backup archives off the server too.',\n\t\t\t\t\t\t\t\t'Run `vela disable s3` to go back to local storage.'\n\t\t\t\t\t\t\t]\n\t\t\t});\n\t\t});\n\t}, 'Failed to enable S3.')\n);\n\nfunction label(filesystem: S3Filesystem): string {\n\treturn filesystem === 'backups' ? 'backup storage' : 'file storage';\n}\n\n/**\n * Refuse to strand files that are already on disk.\n *\n * PocketBase does not migrate anything when the filesystem changes \u2014 it simply\n * starts reading somewhere else \u2014 so every existing upload 404s from the moment\n * this is switched on. The keys are identical on both sides, which makes the fix\n * a plain sync, and that is worth saying rather than leaving to be discovered.\n */\nasync function guardExistingUploads(ctx: BackupContext, options: Options): Promise<void> {\n\tif (options.force) return;\n\tif (!(await hasLocalUploads(ctx.session, ctx.instance, ctx.workspaceRootDir))) return;\n\n\tconst from = ctx.session ? `${remotePaths.storage(ctx.instance)}/` : 'data/storage/';\n\tthrow new Error(\n\t\t`${ctx.targetName} already has uploaded files on disk.\\n\\n` +\n\t\t\t`Turning on S3 changes where PocketBase reads from; it does not move anything,\\n` +\n\t\t\t`so every one of those files would stop resolving.\\n\\n` +\n\t\t\t`The layout is the same on both sides, so copying them across is a plain sync:\\n\\n` +\n\t\t\t` ${pc.cyan(`rclone copy ${from} <remote>:<bucket>/`)}\\n\\n` +\n\t\t\t`Do that first, then re-run with ${pc.cyan('--force')}.`\n\t);\n}\n\nasync function promptConfig(\n\toptions: Options,\n\texisting: { endpoint: string; bucket: string; region: string; accessKey: string }\n): Promise<S3Config> {\n\tconst endpoint =\n\t\toptions.endpoint ??\n\t\t(await text('S3 endpoint URL', existing.endpoint || 'https://s3.amazonaws.com'));\n\tconst bucket = options.bucket ?? (await text('S3 bucket name', existing.bucket));\n\tconst region = options.region ?? (await text('S3 region', existing.region || 'us-east-1'));\n\tconst accessKey = options.accessKey ?? (await text('S3 access key', existing.accessKey));\n\n\t// An access key on the command line is bad enough; a secret there lands in\n\t// shell history and in `ps` for every user on the machine.\n\tconst secret = options.secret ?? process.env.VELA_S3_SECRET ?? (await password('S3 secret key'));\n\n\tconst forcePathStyle =\n\t\toptions.forcePathStyle ??\n\t\t(await confirm(\n\t\t\t'Address the bucket in the path? (MinIO, Ceph and most self-hosted gateways need this)',\n\t\t\tdefaultForcePathStyle(endpoint)\n\t\t));\n\n\treturn { endpoint, bucket, region, accessKey, secret, forcePathStyle };\n}\n\nasync function text(message: string, initialValue = ''): Promise<string> {\n\tconst value = await p.text({\n\t\tmessage,\n\t\tinitialValue,\n\t\tvalidate: (input) => (input?.trim() ? undefined : `${message} is required`)\n\t});\n\tif (p.isCancel(value)) {\n\t\tp.cancel('Operation cancelled.');\n\t\tprocess.exit(0);\n\t}\n\treturn value.trim();\n}\n\nasync function password(message: string): Promise<string> {\n\tconst value = await p.password({\n\t\tmessage,\n\t\tvalidate: (input) => (input ? undefined : `${message} is required`)\n\t});\n\tif (p.isCancel(value)) {\n\t\tp.cancel('Operation cancelled.');\n\t\tprocess.exit(0);\n\t}\n\treturn value;\n}\n\nasync function confirm(message: string, initialValue: boolean): Promise<boolean> {\n\tconst value = await p.confirm({ message, initialValue });\n\tif (p.isCancel(value)) {\n\t\tp.cancel('Operation cancelled.');\n\t\tprocess.exit(0);\n\t}\n\treturn value;\n}\n", "import process from 'node:process';\nimport { Command } from 'commander';\nimport * as v from 'valibot';\nimport * as p from '@clack/prompts';\nimport pc from 'picocolors';\nimport { getWorkspace } from './workspace.ts';\nimport {\n\tloadDeployConfig,\n\treadBinding,\n\tresolveAppIdentity,\n\twriteBinding,\n\ttype TargetBinding,\n\ttype VelaAppConfig\n} from './deploy-config.ts';\nimport { instanceId } from './instance.ts';\nimport { addSshOptions, SSH_OPTION_SCHEMA, sshOptionsFrom } from './ssh-options.ts';\nimport { parseOptions } from './options.ts';\nimport { withSsh, type SshSession } from './ssh.ts';\nimport { requireProvisioned, syncServerScripts } from './remote.ts';\nimport { restartInstance, touchesSuperuser } from './remote-env.ts';\nimport {\n\tdescribeTarget,\n\tparseTarget,\n\ttype RemoteTarget,\n\ttype Target,\n\ttype TargetFallback\n} from './target.ts';\n\nexport const SERVER_OPTIONS_SCHEMA = {\n\t...SSH_OPTION_SCHEMA,\n\ttarget: v.optional(v.string()),\n\tserver: v.optional(v.string())\n};\n\nconst OptionsSchema = v.object(SERVER_OPTIONS_SCHEMA);\n\n/**\n * The one selector.\n *\n * `fallback` is registered as commander's default so `--help` states what the\n * command means with no `-t`, rather than leaving it to prose.\n */\nexport function addTargetOptions(command: Command, fallback: TargetFallback): Command {\n\treturn addSshOptions(command)\n\t\t.option('-t, --target <target>', 'which copy of the app to act on', fallback)\n\t\t.option('--server <ssh>', 'server this target runs on \u2014 recorded on first use');\n}\n\ninterface BaseContext {\n\tworkspaceRootDir: string;\n\tappName: string;\n\tappId: string;\n\tconfig: VelaAppConfig;\n}\n\nexport interface LocalContext extends BaseContext {\n\tkind: 'local';\n\t/** Always the workspace root's, never the cwd's. */\n\tenvFile: string;\n}\n\nexport interface ServerContext extends BaseContext {\n\tkind: 'remote';\n\tsession: SshSession;\n\tinstance: string;\n\tenvTag: string;\n\t/** The target as the user named it, for output. */\n\ttargetName: string;\n\t/** SSH destination behind that target. */\n\tserver: string;\n\tbinding: TargetBinding;\n}\n\nexport interface TargetHandlers {\n\tlocal?: (ctx: LocalContext) => Promise<void>;\n\tremote?: (ctx: ServerContext) => Promise<void>;\n}\n\nexport interface TargetRunOptions {\n\t/** `--project`, forwarded to identity resolution. */\n\tproject?: string;\n\t/** Ask for a domain when binding. Only `deploy` acts on one. */\n\taskDomain?: boolean;\n\t/** Command name for errors, e.g. `env set`. */\n\tlabel?: string;\n\t/** What to point at instead when there is no local mode. */\n\tlocalHint?: string;\n}\n\n/**\n * Run a command against whichever copy of the app `-t` names.\n *\n * A command declares what it supports by which handlers it passes, so the\n * declaration *is* the branch: a remote-only command writes one handler and gets\n * a good error for `-t local` for free, and `ctx.session` exists only inside the\n * remote handler, so a local path cannot reach SSH even by accident.\n */\nexport async function withTarget(\n\traw: unknown,\n\thandlers: TargetHandlers,\n\trun: TargetRunOptions = {}\n): Promise<void> {\n\tconst options = parseOptions(OptionsSchema, raw);\n\tconst target = parseTarget(options.target, 'production');\n\tconst label = run.label ? `vela ${run.label}` : 'this command';\n\n\tif (target.kind === 'preview') {\n\t\tthrow new Error(\n\t\t\t`Preview targets are not supported yet.\\n\\n` +\n\t\t\t\t`\\`${describeTarget(target)}\\` parses, but nothing deploys it: previews need wildcard\\n` +\n\t\t\t\t`DNS and certificates that \\`vela provision\\` does not set up yet.`\n\t\t);\n\t}\n\n\tconst { workspaceRootDir } = await getWorkspace();\n\tconst config = await loadDeployConfig(workspaceRootDir);\n\t// Minting the app id here rather than demanding a prior deploy is what lets\n\t// `vela env import` run before the first `vela deploy`, which is the order\n\t// that gets an app its secrets before it ever serves a request.\n\tconst app = resolveAppIdentity(workspaceRootDir, {\n\t\t...config,\n\t\tproject: run.project ?? config.project\n\t});\n\tconst base = {\n\t\tworkspaceRootDir,\n\t\tappName: app.name,\n\t\tappId: app.appId,\n\t\tconfig\n\t};\n\n\tif (target.kind === 'local') {\n\t\tif (!handlers.local) {\n\t\t\tthrow new Error(\n\t\t\t\t`${label} has no local target.` + (run.localHint ? `\\n\\n${run.localHint}` : '')\n\t\t\t);\n\t\t}\n\t\tawait handlers.local({\n\t\t\t...base,\n\t\t\tkind: 'local',\n\t\t\tenvFile: envFilePath(workspaceRootDir)\n\t\t});\n\t\treturn;\n\t}\n\n\tif (!handlers.remote) {\n\t\tthrow new Error(`${label} only acts on ${pc.cyan('local')}.`);\n\t}\n\n\tconst binding = await ensureBinding(workspaceRootDir, target, {\n\t\tserver: options.server,\n\t\taskDomain: run.askDomain\n\t});\n\n\tawait withSsh(binding.server, sshOptionsFrom(options), async (session) => {\n\t\tawait session.detectElevation();\n\t\tawait requireProvisioned(session);\n\t\t// Keep the server's copy of the scripts in step with this CLI, so a\n\t\t// command never runs against a script from an older version.\n\t\tawait syncServerScripts(session);\n\t\tawait handlers.remote!({\n\t\t\t...base,\n\t\t\tkind: 'remote',\n\t\t\tsession,\n\t\t\tinstance: instanceId(app.appId, target.envTag),\n\t\t\tenvTag: target.envTag,\n\t\t\ttargetName: target.name,\n\t\t\tserver: binding.server,\n\t\t\tbinding\n\t\t});\n\t});\n}\n\nexport interface BindingRequest {\n\tserver?: string;\n\tdomain?: string;\n\taskDomain?: boolean;\n}\n\n/**\n * Work out which server a target runs on, binding it on first use.\n *\n * A target is a name; the machine behind it is recorded once and then never\n * retyped. `--server` is the non-interactive way in, which is what CI passes; a\n * terminal is asked instead, so `vela create` straight into `vela deploy` works\n * with nothing to look up.\n */\nexport async function ensureBinding(\n\tworkspaceRootDir: string,\n\ttarget: RemoteTarget,\n\trequest: BindingRequest = {}\n): Promise<TargetBinding> {\n\tconst existing = readBinding(workspaceRootDir, target.envTag);\n\tconst moving = Boolean(request.server && existing && existing.server !== request.server);\n\n\tlet server = request.server ?? existing?.server;\n\tif (!server) {\n\t\tserver = await promptServer(target);\n\t}\n\n\tlet domain = request.domain ?? existing?.domain;\n\tif (!domain && request.askDomain && !request.server) {\n\t\tdomain = await promptDomain(target);\n\t}\n\n\tconst binding: TargetBinding = domain ? { server, domain } : { server };\n\tif (!existing || existing.server !== server || existing.domain !== domain) {\n\t\twriteBinding(workspaceRootDir, target.envTag, binding);\n\t}\n\n\tif (moving) {\n\t\tp.log.warn(\n\t\t\t`${pc.cyan(target.name)} now points at ${pc.cyan(server)}.\\n\\n` +\n\t\t\t\t`Whatever is running on ${existing!.server} is left there, and this project can no\\n` +\n\t\t\t\t`longer reach it. Remove it there first if that was not intended.`\n\t\t);\n\t}\n\n\treturn binding;\n}\n\nasync function promptServer(target: RemoteTarget): Promise<string> {\n\tif (!process.stdout.isTTY || process.env.CI) {\n\t\tthrow new Error(\n\t\t\t`${target.name} is not bound to a server yet, and there is no terminal to ask on.\\n\\n` +\n\t\t\t\t`Pass ${pc.cyan('--server user@host')}, or run the command once from your own machine\\n` +\n\t\t\t\t`and commit ${pc.cyan('.vela/project.json')}.`\n\t\t);\n\t}\n\n\tp.log.info(`${pc.cyan(target.name)} is not bound to a server yet.`);\n\tconst value = await p.text({\n\t\tmessage: `Which server should ${target.name} run on?`,\n\t\tplaceholder: 'root@203.0.113.10',\n\t\tvalidate: (input) => (input?.trim() ? undefined : 'An ssh_config alias, or user@host')\n\t});\n\tif (p.isCancel(value)) {\n\t\tp.cancel('Operation cancelled.');\n\t\tprocess.exit(0);\n\t}\n\treturn value.trim();\n}\n\nasync function promptDomain(target: RemoteTarget): Promise<string | undefined> {\n\tif (!process.stdout.isTTY || process.env.CI) return undefined;\n\n\tconst value = await p.text({\n\t\tmessage: `Which hostname should ${target.name} be served on?`,\n\t\tplaceholder: 'example.com \u2014 leave blank to decide later'\n\t});\n\tif (p.isCancel(value)) {\n\t\tp.cancel('Operation cancelled.');\n\t\tprocess.exit(0);\n\t}\n\treturn value.trim() || undefined;\n}\n\n/** Restart after a change, reporting the two outcomes separately. */\nexport async function applyRestart(ctx: ServerContext): Promise<void> {\n\tconst outcome = await restartInstance(ctx.session, ctx.instance);\n\tif (!outcome.deployed) return;\n\tif (outcome.restarted) {\n\t\tp.log.success('App restarted');\n\t\treturn;\n\t}\n\tp.log.error(\n\t\t`App restart failed.\\n\\n` +\n\t\t\t`The new value is stored and will be used the next time the app starts.\\n` +\n\t\t\t`${pc.dim(outcome.error ?? '')}`\n\t);\n}\n\n/**\n * Restart after an env change, unless it touched the PocketBase superuser.\n *\n * Those two values are only half of the credential \u2014 the other half is a record\n * in the instance's database, which `vela deploy` reconciles. Restarting here\n * would pick up a password the database does not know yet and fail every\n * request, so the change is stored and the restart deferred.\n */\nexport async function applyEnvRestart(ctx: ServerContext, changed: string[]): Promise<void> {\n\tif (touchesSuperuser(changed)) {\n\t\tp.log.warn(\n\t\t\t`PocketBase superuser credentials changed.\\n\\n` +\n\t\t\t\t`The database still holds the old ones, so the app has not been restarted.\\n` +\n\t\t\t\t`Run ${pc.cyan('vela deploy')} to push them into the database and restart.`\n\t\t);\n\t\treturn;\n\t}\n\tawait applyRestart(ctx);\n}\n\n/**\n * Open a session against a server without naming an instance \u2014 `vela status\n * --all` is a question about the machine, not about one app.\n */\nexport async function withServerSession(\n\traw: unknown,\n\tfn: (session: SshSession) => Promise<void>\n): Promise<void> {\n\tconst options = parseOptions(OptionsSchema, raw);\n\n\tlet server = options.server;\n\tif (!server) {\n\t\tconst { workspaceRootDir } = await getWorkspace();\n\t\tconst target = parseTarget(options.target, 'production');\n\t\tif (target.kind !== 'remote') {\n\t\t\tthrow new Error(`${describeTarget(target)} does not run on a server.`);\n\t\t}\n\t\tserver = (await ensureBinding(workspaceRootDir, target, { server: options.server })).server;\n\t}\n\n\tawait withSsh(server, sshOptionsFrom(options), async (session) => {\n\t\tawait session.detectElevation();\n\t\tawait requireProvisioned(session);\n\t\tawait syncServerScripts(session);\n\t\tawait fn(session);\n\t});\n}\n\nfunction envFilePath(workspaceRootDir: string): string {\n\treturn `${workspaceRootDir}/.env`;\n}\n", "import fs from 'node:fs';\nimport path from 'node:path';\nimport crypto from 'node:crypto';\nimport { pathToFileURL } from 'node:url';\nimport { readPackageJson } from './package-json.ts';\n\n/**\n * Per-project deploy settings, read from `velastack.config.{ts,js,mjs,json}` at\n * the workspace root. Every field is optional \u2014 a project with no config file at\n * all can still be deployed, it just has to pass `--domain` the first time.\n */\nexport interface VelaDeployConfig {\n\t/** Public hostname Caddy should serve this app on. */\n\tdomain?: string;\n\t/** Path the deploy health check hits on the app's own port. */\n\thealthCheckPath?: string;\n\t/** Build command run locally before packing the artifact. */\n\tbuildCommand?: string;\n\t/** Directory the adapter writes to. */\n\toutputDir?: string;\n\t/** Extra files or directories to include in the release artifact. */\n\tinclude?: string[];\n\t/** How many old releases to keep on the server. */\n\tkeepReleases?: number;\n\t/** PocketBase version to run. Defaults to the one this CLI develops against. */\n\tpocketbaseVersion?: string;\n\t/**\n\t * Render the build against the deployed instance's database rather than a\n\t * throwaway local one. Needed when pages are prerendered from data, which\n\t * would otherwise bake in the defaults of an empty database.\n\t */\n\tbuildAgainstRemote?: boolean;\n}\n\nexport interface VelaAppConfig {\n\tproject?: string;\n\tdeploy?: VelaDeployConfig;\n}\n\nconst CONFIG_BASENAMES = [\n\t'velastack.config.ts',\n\t'velastack.config.js',\n\t'velastack.config.mjs',\n\t'velastack.config.json'\n];\n\nexport function findConfigFile(workspaceRootDir: string): string | null {\n\tfor (const name of CONFIG_BASENAMES) {\n\t\tconst file = path.join(workspaceRootDir, name);\n\t\tif (fs.existsSync(file)) return file;\n\t}\n\treturn null;\n}\n\nexport async function loadDeployConfig(workspaceRootDir: string): Promise<VelaAppConfig> {\n\tconst file = findConfigFile(workspaceRootDir);\n\tif (!file) return {};\n\n\tif (file.endsWith('.json')) {\n\t\treturn JSON.parse(fs.readFileSync(file, 'utf8')) as VelaAppConfig;\n\t}\n\n\tconst url = file.endsWith('.ts') ? await transpileToTemp(file) : pathToFileURL(file).href;\n\ttry {\n\t\tconst mod = (await import(url)) as { default?: VelaAppConfig };\n\t\tconst config = mod.default;\n\t\tif (!config || typeof config !== 'object') {\n\t\t\tthrow new Error(`${path.basename(file)} must export a config object as its default export.`);\n\t\t}\n\t\treturn config;\n\t} finally {\n\t\tif (url !== pathToFileURL(file).href) fs.rmSync(new URL(url), { force: true });\n\t}\n}\n\n/**\n * Type annotations are stripped with the TypeScript compiler that ships with\n * ts-morph \u2014 already a dependency \u2014 rather than relying on the host Node having\n * type stripping enabled. The temp file sits beside the original so relative\n * imports still resolve.\n */\nasync function transpileToTemp(file: string): Promise<string> {\n\tconst { ts } = await import('ts-morph');\n\tconst source = fs.readFileSync(file, 'utf8');\n\tconst { outputText } = ts.transpileModule(source, {\n\t\tcompilerOptions: { module: ts.ModuleKind.ESNext, target: ts.ScriptTarget.ES2022 }\n\t});\n\tconst temp = path.join(\n\t\tpath.dirname(file),\n\t\t`.velastack.config.${crypto.randomBytes(4).toString('hex')}.mjs`\n\t);\n\tfs.writeFileSync(temp, outputText);\n\treturn pathToFileURL(temp).href;\n}\n\n/** Identity of a deployable app, stable for the lifetime of the project. */\nexport interface AppIdentity {\n\t/** Immutable id used for server paths and unit names. */\n\tappId: string;\n\t/** Human-readable name, used in output and for the `by-name` symlink. */\n\tname: string;\n}\n\ninterface ProjectFile {\n\tprojectId?: string;\n\tteamId?: string;\n\tprojectName?: string;\n\tappId?: string;\n\ttargets?: Record<string, TargetBinding>;\n\t/**\n\t * The shape before targets were named. Still read, never written: a project\n\t * deployed with an older CLI keeps working, and is rewritten into `targets`\n\t * the next time it deploys.\n\t */\n\tdeployments?: Record<string, LegacyDeployment>;\n}\n\nfunction projectFilePath(workspaceRootDir: string): string {\n\treturn path.join(workspaceRootDir, '.vela', 'project.json');\n}\n\nfunction readProjectFile(workspaceRootDir: string): ProjectFile {\n\tconst file = projectFilePath(workspaceRootDir);\n\tif (!fs.existsSync(file)) return {};\n\ttry {\n\t\treturn JSON.parse(fs.readFileSync(file, 'utf8')) as ProjectFile;\n\t} catch {\n\t\treturn {};\n\t}\n}\n\nfunction writeProjectFile(workspaceRootDir: string, data: ProjectFile): void {\n\tconst file = projectFilePath(workspaceRootDir);\n\tfs.mkdirSync(path.dirname(file), { recursive: true });\n\tfs.writeFileSync(file, JSON.stringify(data, null, 2) + '\\n');\n}\n\n/**\n * Resolve \u2014 and on first use, mint \u2014 the app's immutable id.\n *\n * A project already linked to velastack.dev reuses its project id. Everything\n * else gets a locally generated one, so deploying to your own VPS never\n * requires an account. Either way the id is written to `.vela/project.json` and\n * never recomputed: server paths and env files hang off it, so it has to\n * survive renames.\n */\nexport function resolveAppIdentity(\n\tworkspaceRootDir: string,\n\tconfig: VelaAppConfig = {}\n): AppIdentity {\n\tconst project = readProjectFile(workspaceRootDir);\n\tconst name = config.project ?? project.projectName ?? defaultProjectName(workspaceRootDir);\n\n\tif (project.appId) return { appId: project.appId, name };\n\n\tconst appId = project.projectId ?? `${slug(name)}-${crypto.randomBytes(4).toString('hex')}`;\n\twriteProjectFile(workspaceRootDir, {\n\t\t...project,\n\t\tappId,\n\t\tprojectName: project.projectName ?? name\n\t});\n\treturn { appId, name };\n}\n\n/** Read the app id without minting one \u2014 for commands that must not create state. */\nexport function readAppIdentity(\n\tworkspaceRootDir: string,\n\tconfig: VelaAppConfig = {}\n): AppIdentity | null {\n\tconst project = readProjectFile(workspaceRootDir);\n\tconst appId = project.appId ?? project.projectId;\n\tif (!appId) return null;\n\treturn {\n\t\tappId,\n\t\tname: config.project ?? project.projectName ?? defaultProjectName(workspaceRootDir)\n\t};\n}\n\nexport function defaultProjectName(workspaceRootDir: string): string {\n\ttry {\n\t\tconst pkg = readPackageJson(path.join(workspaceRootDir, 'package.json'));\n\t\tif (typeof pkg.name === 'string' && pkg.name.trim()) return pkg.name.trim();\n\t} catch {\n\t\t// fall through to the directory name\n\t}\n\treturn path.basename(workspaceRootDir);\n}\n\nfunction slug(value: string): string {\n\treturn (\n\t\tvalue\n\t\t\t.toLowerCase()\n\t\t\t.replace(/^@/, '')\n\t\t\t.replace(/[^a-z0-9]+/g, '-')\n\t\t\t.replace(/^-+|-+$/g, '')\n\t\t\t.slice(0, 32) || 'app'\n\t);\n}\n\nexport interface TargetBinding {\n\t/** SSH destination, exactly as `ssh` would take it. */\n\tserver: string;\n\t/** Hostname(s) Caddy serves this target on. */\n\tdomain?: string;\n}\n\ninterface LegacyDeployment {\n\ttarget: string;\n\tdomain?: string;\n}\n\n/**\n * Where a target runs.\n *\n * This is ordinary project metadata \u2014 a hostname, never a credential \u2014 and\n * belongs in version control beside the app id. Binding a target to a server\n * once is what lets every other command take `-t staging` and nothing else.\n */\nexport function readBinding(workspaceRootDir: string, envTag: string): TargetBinding | null {\n\tconst project = readProjectFile(workspaceRootDir);\n\tconst bound = project.targets?.[envTag];\n\tif (bound?.server) return bound;\n\n\tconst legacy = project.deployments?.[envTag];\n\tif (legacy?.target) return { server: legacy.target, domain: legacy.domain };\n\n\treturn null;\n}\n\n/** Every bound target, newest shape taking precedence over the old one. */\nexport function readBindings(workspaceRootDir: string): Record<string, TargetBinding> {\n\tconst project = readProjectFile(workspaceRootDir);\n\tconst bindings: Record<string, TargetBinding> = {};\n\n\tfor (const [envTag, legacy] of Object.entries(project.deployments ?? {})) {\n\t\tif (legacy?.target) bindings[envTag] = { server: legacy.target, domain: legacy.domain };\n\t}\n\tfor (const [envTag, bound] of Object.entries(project.targets ?? {})) {\n\t\tif (bound?.server) bindings[envTag] = bound;\n\t}\n\n\treturn bindings;\n}\n\nexport function writeBinding(\n\tworkspaceRootDir: string,\n\tenvTag: string,\n\tbinding: TargetBinding\n): void {\n\tconst project = readProjectFile(workspaceRootDir);\n\twriteProjectFile(workspaceRootDir, {\n\t\t...project,\n\t\ttargets: { ...project.targets, [envTag]: binding }\n\t});\n}\n", "/**\n * Instance identity.\n *\n * A deployed app is identified on the server by a single stable token that is\n * safe in a path, a systemd unit name, and a filename:\n *\n * prod -> `<appId>`\n * staging -> `<appId>--staging`\n * preview/feature-x -> `<appId>--preview--feature-x`\n *\n * Production deliberately has no suffix, so the common case reads as\n * `/var/lib/vela/apps/<appId>` \u2014 the layout `plans/vela-env-plan.md` describes.\n */\n\nexport const PROD_ENV = 'prod';\n\nconst MAX_SEGMENT = 48;\n\n/** Normalize a user-supplied environment tag to its canonical form. */\nexport function normalizeEnvTag(tag: string | undefined): string {\n\tconst raw = (tag ?? PROD_ENV).trim();\n\tif (!raw) return PROD_ENV;\n\tconst normalized = raw\n\t\t.toLowerCase()\n\t\t.replace(/\\//g, '--')\n\t\t.replace(/[^a-z0-9-]+/g, '-')\n\t\t.replace(/-{3,}/g, '--')\n\t\t.replace(/^-+|-+$/g, '');\n\tif (!normalized) throw new Error(`Invalid environment tag: ${tag}`);\n\t// `local` is the copy on this machine and has no instance on any server.\n\t// Closed here rather than in the target parser so that no future caller can\n\t// route around it and create `<appId>--local`.\n\tif (normalized === 'local') {\n\t\tthrow new Error('`local` is not a deployable environment \u2014 it is the copy on this machine.');\n\t}\n\treturn normalized === 'production' ? PROD_ENV : normalized;\n}\n\n/** Turn a git branch name into an environment tag: `feature/auth` -> `preview--feature-auth`. */\nexport function branchToEnvTag(branch: string): string {\n\tconst slug = branch\n\t\t.toLowerCase()\n\t\t.replace(/[^a-z0-9]+/g, '-')\n\t\t.replace(/^-+|-+$/g, '')\n\t\t.slice(0, MAX_SEGMENT);\n\treturn `preview--${slug}`;\n}\n\nexport function instanceId(appId: string, envTag: string = PROD_ENV): string {\n\tconst env = normalizeEnvTag(envTag);\n\treturn env === PROD_ENV ? appId : `${appId}--${env}`;\n}\n\nexport function isProd(envTag: string): boolean {\n\treturn normalizeEnvTag(envTag) === PROD_ENV;\n}\n\n/** A release id sorts lexicographically by time, which is how `latest` is found. */\nexport function releaseId(date = new Date()): string {\n\treturn date\n\t\t.toISOString()\n\t\t.replace(/[-:]/g, '')\n\t\t.replace(/\\.\\d+Z$/, 'Z');\n}\n", "import { Command } from 'commander';\nimport * as v from 'valibot';\nimport type { SshOptions } from './ssh.ts';\n\n/** Flags every server-facing command shares. */\nexport const SSH_OPTION_SCHEMA = {\n\tidentity: v.optional(v.string()),\n\tsshPort: v.optional(v.string()),\n\tacceptHostKeys: v.optional(v.boolean())\n};\n\nexport function addSshOptions(command: Command): Command {\n\treturn command\n\t\t.option('-i, --identity <file>', 'SSH private key to authenticate with')\n\t\t.option('--ssh-port <port>', 'SSH port')\n\t\t.option('--accept-host-keys', 'trust an unknown host key on first connect (CI)');\n}\n\nexport function sshOptionsFrom(options: {\n\tidentity?: string;\n\tsshPort?: string;\n\tacceptHostKeys?: boolean;\n}): SshOptions {\n\treturn {\n\t\tidentityFile: options.identity,\n\t\tport: options.sshPort ? Number(options.sshPort) : undefined,\n\t\tacceptNewHostKeys: options.acceptHostKeys\n\t};\n}\n", "import fs from 'node:fs';\nimport os from 'node:os';\nimport path from 'node:path';\nimport crypto from 'node:crypto';\nimport process from 'node:process';\nimport { spawn, type StdioOptions } from 'node:child_process';\n\nexport interface SshOptions {\n\t/** Extra identity file, for CI where there is no ~/.ssh/config entry. */\n\tidentityFile?: string;\n\tport?: number;\n\t/** Skip host key prompts. CI sets this after seeding known_hosts itself. */\n\tacceptNewHostKeys?: boolean;\n}\n\n/**\n * Whether remote work has to be wrapped in `sudo`. Set once per session after\n * looking at the remote uid, so a `root` alias never pays for sudo and a\n * non-root alias fails early and clearly if it cannot escalate.\n */\nexport type Elevation = 'none' | 'sudo';\n\nexport interface RunOptions {\n\t/** Stream stdout/stderr to the terminal instead of capturing it. */\n\tstream?: boolean;\n\t/** Throw when the remote command exits non-zero. Defaults to true. */\n\tcheck?: boolean;\n\t/** Positional arguments passed to the script as `$1`, `$2`, ... */\n\targs?: string[];\n}\n\nexport interface RunResult {\n\tstdout: string;\n\tstderr: string;\n\texitCode: number;\n}\n\nexport class RemoteCommandError extends Error {\n\texitCode: number;\n\tstdout: string;\n\tstderr: string;\n\n\tconstructor(message: string, result: RunResult) {\n\t\tsuper(message);\n\t\tthis.name = 'RemoteCommandError';\n\t\tthis.exitCode = result.exitCode;\n\t\tthis.stdout = result.stdout;\n\t\tthis.stderr = result.stderr;\n\t}\n}\n\n/**\n * A connection to one server, multiplexed over a single OpenSSH ControlMaster\n * socket. Everything the CLI does remotely goes through `script()`, which pipes\n * a bash program over stdin \u2014 nothing user-supplied ever reaches a remote shell\n * as a concatenated string, and secrets never appear in the remote process list.\n */\nexport class SshSession {\n\treadonly target: string;\n\televation: Elevation = 'none';\n\tprivate readonly options: SshOptions;\n\tprivate controlPath: string | null = null;\n\n\tconstructor(target: string, options: SshOptions = {}) {\n\t\tthis.target = target;\n\t\tthis.options = options;\n\t}\n\n\tprivate sshArgs(): string[] {\n\t\tconst args: string[] = [];\n\t\tif (this.controlPath) args.push('-o', `ControlPath=${this.controlPath}`);\n\t\tif (this.options.identityFile) {\n\t\t\targs.push('-i', this.options.identityFile, '-o', 'IdentitiesOnly=yes');\n\t\t}\n\t\tif (this.options.port) args.push('-p', String(this.options.port));\n\t\tif (this.options.acceptNewHostKeys) args.push('-o', 'StrictHostKeyChecking=accept-new');\n\t\targs.push('-o', 'BatchMode=yes');\n\t\treturn args;\n\t}\n\n\t/** The `ssh` invocation rsync should use, as a single shell word list. */\n\trsyncShell(): string {\n\t\tconst parts = ['ssh', ...this.sshArgs()];\n\t\treturn parts.map(shellQuote).join(' ');\n\t}\n\n\tasync open(): Promise<void> {\n\t\tif (this.controlPath) return;\n\t\tconst dir = path.join(os.tmpdir(), 'vela-ssh');\n\t\tfs.mkdirSync(dir, { recursive: true, mode: 0o700 });\n\t\t// Socket paths live under a 104-char limit on macOS, so keep it short.\n\t\tconst socket = path.join(dir, `${crypto.randomBytes(6).toString('hex')}.sock`);\n\t\tthis.controlPath = socket;\n\n\t\tconst args = [\n\t\t\t...this.sshArgs(),\n\t\t\t'-o',\n\t\t\t'ControlMaster=yes',\n\t\t\t'-o',\n\t\t\t'ControlPersist=60',\n\t\t\t'-N',\n\t\t\t'-f',\n\t\t\tthis.target\n\t\t];\n\t\tconst result = await spawnCapture('ssh', args);\n\t\tif (result.exitCode !== 0) {\n\t\t\tthis.controlPath = null;\n\t\t\tthrow new Error(\n\t\t\t\t`Could not connect to ${this.target} over SSH.\\n\\n${result.stderr.trim() || result.stdout.trim()}`\n\t\t\t);\n\t\t}\n\t}\n\n\tasync close(): Promise<void> {\n\t\tif (!this.controlPath) return;\n\t\tconst socket = this.controlPath;\n\t\tthis.controlPath = null;\n\t\tawait spawnCapture('ssh', ['-o', `ControlPath=${socket}`, '-O', 'exit', this.target]);\n\t}\n\n\t/**\n\t * Run a bash program on the server. The program is piped over stdin, so it can\n\t * safely embed anything \u2014 quoting, newlines, base64 blobs \u2014 and `args` arrive\n\t * as ordinary positional parameters.\n\t */\n\tasync script(source: string, opts: RunOptions = {}): Promise<RunResult> {\n\t\tconst shell = this.elevation === 'sudo' ? 'sudo -n bash -s' : 'bash -s';\n\t\t// ssh joins its remaining argv with spaces and hands the result to a\n\t\t// remote shell, which silently drops empty arguments and splits ones\n\t\t// containing spaces. Quoting here means the remote `$@` is exactly what\n\t\t// was passed in.\n\t\tconst remote = [shell, '--', ...(opts.args ?? []).map(shellQuote)].join(' ');\n\t\tconst args = [...this.sshArgs(), this.target, remote];\n\t\tconst result = await spawnCapture('ssh', args, {\n\t\t\tstdin: `set -euo pipefail\\n${source}`,\n\t\t\tstream: opts.stream\n\t\t});\n\t\tif (opts.check !== false && result.exitCode !== 0) {\n\t\t\tthrow new RemoteCommandError(remoteFailure(this.target, result), result);\n\t\t}\n\t\treturn result;\n\t}\n\n\t/** Attach the terminal to a remote command \u2014 used by `vela logs -f`. */\n\tasync interactive(command: string[]): Promise<number> {\n\t\tconst args = [...this.sshArgs(), '-t', this.target, command.map(shellQuote).join(' ')];\n\t\treturn await new Promise((resolve) => {\n\t\t\tconst child = spawn('ssh', args, { stdio: 'inherit' });\n\t\t\tchild.on('close', (code) => resolve(code ?? 1));\n\t\t});\n\t}\n\n\t/**\n\t * Write a file on the server atomically, with an explicit mode.\n\t *\n\t * The payload rides inside the piped script as base64, so it never lands in\n\t * argv (visible in `ps`) or in a shell history, and binary-unsafe characters\n\t * are not an issue.\n\t */\n\tasync writeFile(remotePath: string, content: string, mode = '0644'): Promise<void> {\n\t\tconst payload = Buffer.from(content, 'utf8').toString('base64');\n\t\tawait this.script(\n\t\t\t`dest=\"$1\"; mode=\"$2\"\nmkdir -p \"$(dirname \"$dest\")\"\ntmp=$(mktemp \"$(dirname \"$dest\")/.vela.XXXXXX\")\nprintf %s ${payload} | base64 -d > \"$tmp\"\nchmod \"$mode\" \"$tmp\"\nmv -f \"$tmp\" \"$dest\"`,\n\t\t\t{ args: [remotePath, mode] }\n\t\t);\n\t}\n\n\t/**\n\t * Tunnel a local port to a port on the server, through the connection that is\n\t * already open. Used to point a local build at the target's database.\n\t */\n\tasync forwardLocalPort(localPort: number, remoteHost: string, remotePort: number): Promise<void> {\n\t\tif (!this.controlPath) throw new Error('Cannot forward a port without an open session.');\n\t\tconst spec = `${localPort}:${remoteHost}:${remotePort}`;\n\t\tconst result = await spawnCapture('ssh', [\n\t\t\t...this.sshArgs(),\n\t\t\t'-O',\n\t\t\t'forward',\n\t\t\t'-L',\n\t\t\tspec,\n\t\t\tthis.target\n\t\t]);\n\t\tif (result.exitCode !== 0) {\n\t\t\tthrow new Error(\n\t\t\t\t`Could not forward port ${spec} to ${this.target}.\\n\\n${result.stderr.trim()}`\n\t\t\t);\n\t\t}\n\t}\n\n\tasync cancelForward(localPort: number, remoteHost: string, remotePort: number): Promise<void> {\n\t\tif (!this.controlPath) return;\n\t\tawait spawnCapture('ssh', [\n\t\t\t...this.sshArgs(),\n\t\t\t'-O',\n\t\t\t'cancel',\n\t\t\t'-L',\n\t\t\t`${localPort}:${remoteHost}:${remotePort}`,\n\t\t\tthis.target\n\t\t]);\n\t}\n\n\tasync readFile(remotePath: string): Promise<string | null> {\n\t\tconst result = await this.script(`cat \"$1\" 2>/dev/null || exit 44`, {\n\t\t\targs: [remotePath],\n\t\t\tcheck: false\n\t\t});\n\t\tif (result.exitCode === 44) return null;\n\t\tif (result.exitCode !== 0)\n\t\t\tthrow new RemoteCommandError(remoteFailure(this.target, result), result);\n\t\treturn result.stdout;\n\t}\n\n\t/** rsync a local directory (contents) into a remote directory. */\n\tasync uploadDir(localDir: string, remoteDir: string, extraArgs: string[] = []): Promise<void> {\n\t\tconst src = localDir.endsWith('/') ? localDir : `${localDir}/`;\n\t\tconst args = [\n\t\t\t'-az',\n\t\t\t'--delete',\n\t\t\t'-e',\n\t\t\tthis.rsyncShell(),\n\t\t\t...this.rsyncPath(),\n\t\t\t...extraArgs,\n\t\t\tsrc,\n\t\t\t`${this.target}:${remoteDir}`\n\t\t];\n\t\tconst result = await spawnCapture('rsync', args);\n\t\tif (result.exitCode !== 0) {\n\t\t\tthrow new Error(`rsync to ${this.target}:${remoteDir} failed.\\n\\n${result.stderr.trim()}`);\n\t\t}\n\t}\n\n\tprivate rsyncPath(): string[] {\n\t\treturn this.elevation === 'sudo' ? ['--rsync-path=sudo -n rsync'] : [];\n\t}\n\n\t/**\n\t * rsync one remote path down to a local one.\n\t *\n\t * No `-z`: the only thing this moves is a backup archive, which is already\n\t * compressed, and asking gzip to compress a zip costs CPU on both ends for\n\t * nothing. `--partial` keeps what arrived when a large transfer is\n\t * interrupted, so retrying resumes rather than starting over.\n\t *\n\t * The remote path reaches rsync through a login shell, so it is quoted here\n\t * even though the paths this is called with are vela's own.\n\t */\n\tasync download(remotePath: string, localPath: string, extraArgs: string[] = []): Promise<void> {\n\t\tconst args = [\n\t\t\t'-a',\n\t\t\t'--partial',\n\t\t\t'-e',\n\t\t\tthis.rsyncShell(),\n\t\t\t...this.rsyncPath(),\n\t\t\t...extraArgs,\n\t\t\t`${this.target}:${shellQuote(remotePath)}`,\n\t\t\tlocalPath\n\t\t];\n\t\tconst result = await spawnCapture('rsync', args);\n\t\tif (result.exitCode !== 0) {\n\t\t\tthrow new Error(`rsync from ${this.target}:${remotePath} failed.\\n\\n${result.stderr.trim()}`);\n\t\t}\n\t}\n\n\t/** rsync one or more local paths to a remote directory. */\n\tasync upload(localPaths: string[], remoteDir: string, extraArgs: string[] = []): Promise<void> {\n\t\tconst args = [\n\t\t\t'-az',\n\t\t\t'-e',\n\t\t\tthis.rsyncShell(),\n\t\t\t...this.rsyncPath(),\n\t\t\t...extraArgs,\n\t\t\t...localPaths,\n\t\t\t`${this.target}:${remoteDir}`\n\t\t];\n\t\tconst result = await spawnCapture('rsync', args);\n\t\tif (result.exitCode !== 0) {\n\t\t\tthrow new Error(`rsync to ${this.target}:${remoteDir} failed.\\n\\n${result.stderr.trim()}`);\n\t\t}\n\t}\n\n\t/**\n\t * Decide once whether remote commands need `sudo`, and fail with something\n\t * actionable if they do but cannot get it.\n\t */\n\tasync detectElevation(): Promise<Elevation> {\n\t\tconst uid = await this.script('id -u', { check: false });\n\t\tif (uid.stdout.trim() === '0') {\n\t\t\tthis.elevation = 'none';\n\t\t\treturn this.elevation;\n\t\t}\n\t\tconst sudo = await this.script('sudo -n true', { check: false });\n\t\tif (sudo.exitCode !== 0) {\n\t\t\tthrow new Error(\n\t\t\t\t`${this.target} connects as a non-root user without passwordless sudo.\\n\\n` +\n\t\t\t\t\t`Use an SSH target that logs in as root, or give the user NOPASSWD sudo.`\n\t\t\t);\n\t\t}\n\t\tthis.elevation = 'sudo';\n\t\treturn this.elevation;\n\t}\n}\n\nfunction remoteFailure(target: string, result: RunResult): string {\n\tconst detail = (result.stderr.trim() || result.stdout.trim()).split('\\n').slice(-12).join('\\n');\n\treturn `Remote command failed on ${target} (exit ${result.exitCode}).\\n\\n${detail}`;\n}\n\nexport async function withSsh<T>(\n\ttarget: string,\n\toptions: SshOptions,\n\tfn: (session: SshSession) => Promise<T>\n): Promise<T> {\n\tconst session = new SshSession(target, options);\n\tawait session.open();\n\ttry {\n\t\treturn await fn(session);\n\t} finally {\n\t\tawait session.close();\n\t}\n}\n\nexport function shellQuote(value: string): string {\n\tif (/^[A-Za-z0-9_@%+=:,./-]+$/.test(value)) return value;\n\treturn `'${value.replaceAll(\"'\", `'\\\\''`)}'`;\n}\n\nexport interface SpawnOptions {\n\tstdin?: string;\n\t/**\n\t * Show the child's stderr as it arrives. stdout stays captured either way:\n\t * the server scripts put progress on stderr and their machine-readable\n\t * result on stdout, so the user sees one and the CLI parses the other.\n\t */\n\tstream?: boolean;\n\t/** Also echo stdout \u2014 for local builds, where stdout is the interesting half. */\n\tstreamStdout?: boolean;\n\tcwd?: string;\n\t/** Extra environment for the child, merged over the current process env. */\n\tenv?: Record<string, string | undefined>;\n}\n\nexport function spawnCapture(\n\tcommand: string,\n\targs: string[],\n\topts: SpawnOptions = {}\n): Promise<RunResult> {\n\treturn new Promise((resolve, reject) => {\n\t\tconst stdio: StdioOptions = [opts.stdin === undefined ? 'ignore' : 'pipe', 'pipe', 'pipe'];\n\t\tconst child = spawn(command, args, {\n\t\t\tstdio,\n\t\t\tcwd: opts.cwd,\n\t\t\tenv: opts.env ? { ...process.env, ...opts.env } : undefined\n\t\t});\n\t\tlet stdout = '';\n\t\tlet stderr = '';\n\t\tchild.stdout?.on('data', (chunk) => {\n\t\t\tstdout += chunk;\n\t\t\tif (opts.streamStdout) process.stdout.write(chunk);\n\t\t});\n\t\tchild.stderr?.on('data', (chunk) => {\n\t\t\tstderr += chunk;\n\t\t\tif (opts.stream) process.stderr.write(chunk);\n\t\t});\n\t\tchild.on('error', reject);\n\t\tchild.on('close', (code) => resolve({ stdout, stderr, exitCode: code ?? 1 }));\n\t\tif (opts.stdin !== undefined) {\n\t\t\tchild.stdin!.end(opts.stdin);\n\t\t}\n\t});\n}\n", "import path from 'node:path';\nimport { templatesDir } from './templates.ts';\nimport { SshSession, type RunResult } from './ssh.ts';\n\nexport const VELA_ROOT = '/var/lib/vela';\nexport const VELA_ETC = '/etc/vela';\n/** The unprivileged account every app's files and processes belong to. */\nexport const VELA_USER = 'vela';\nexport const SCRIPTS_DIR = `${VELA_ROOT}/scripts`;\nexport const PROVISIONED_MARKER = `${VELA_ETC}/provisioned`;\n\nexport interface ServerInfo {\n\tcliVersion: string;\n\tpocketbaseVersion: string;\n\tprovisionedAt: string;\n\tlayoutVersion: number;\n}\n\nexport interface InstanceState {\n\tappId: string;\n\tname: string;\n\tenv: string;\n\tinstance: string;\n\tactiveRelease?: string;\n\tpreviousRelease?: string;\n\tdomain?: string;\n\thealthCheckPath?: string;\n\tpocketbaseVersion?: string;\n\tgitSha?: string;\n\twebPort?: number;\n\tpbPort?: number;\n\tbackend?: boolean;\n\tdeployedAt?: string;\n\trolledBackAt?: string;\n\trestoredAt?: string;\n\t/** Backup key or uploaded filename the last restore came from. */\n\trestoredFrom?: string;\n\t/** The pb_data the last restore set aside, kept as the only undo. */\n\tpreviousDataDir?: string;\n\tcurrent?: string;\n\treleases?: string[];\n\tservices?: { web: string; pocketbase: string };\n}\n\n/** The `templates/server` tree that gets uploaded to `/var/lib/vela/scripts`. */\nexport function serverTemplatesDir(): string {\n\treturn path.join(templatesDir(), 'server');\n}\n\n/**\n * Put this CLI's copy of the server scripts on the box.\n *\n * Uploaded on every provision *and* every deploy, so the scripts a server runs\n * always match the CLI driving it \u2014 upgrading the CLI is all it takes to pick\n * up a fixed deploy script.\n */\nexport async function syncServerScripts(session: SshSession): Promise<void> {\n\tawait session.script(`mkdir -p \"$1\" && chmod 0755 \"$1\"`, { args: [SCRIPTS_DIR] });\n\tawait session.uploadDir(serverTemplatesDir(), SCRIPTS_DIR, ['--chmod=D755,F755']);\n\t// rsync preserves the developer's uid otherwise, which leaves root-run\n\t// scripts owned by a uid that means nothing on the server.\n\tawait session.script(`chown -R root:root \"$1\"`, { args: [SCRIPTS_DIR] });\n}\n\nexport interface ScriptOptions {\n\targs?: string[];\n\tstream?: boolean;\n}\n\n/**\n * Run one of the uploaded server scripts and return whatever it emitted as its\n * `VELA_RESULT` line. Progress goes to stderr, so it can stream to the user\n * while the structured result still comes back cleanly.\n */\nexport async function runServerScript<T = Record<string, unknown>>(\n\tsession: SshSession,\n\tname: string,\n\topts: ScriptOptions = {}\n): Promise<T | null> {\n\t// `bash -s -- a b c` leaves $0 as \"bash\", so the script path is the first\n\t// positional and has to be shifted off before exec.\n\tconst result = await session.script(`script=\"$1\"; shift; exec \"$script\" \"$@\"`, {\n\t\targs: [`${SCRIPTS_DIR}/${name}`, ...(opts.args ?? [])],\n\t\tstream: opts.stream\n\t});\n\treturn parseResult<T>(result);\n}\n\nexport function parseResult<T>(result: RunResult): T | null {\n\tconst line = result.stdout\n\t\t.split('\\n')\n\t\t.reverse()\n\t\t.find((l) => l.startsWith('VELA_RESULT '));\n\tif (!line) return null;\n\ttry {\n\t\treturn JSON.parse(line.slice('VELA_RESULT '.length)) as T;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nexport async function readServerInfo(session: SshSession): Promise<ServerInfo | null> {\n\tconst raw = await session.readFile(PROVISIONED_MARKER);\n\tif (!raw) return null;\n\ttry {\n\t\treturn JSON.parse(raw) as ServerInfo;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nexport async function requireProvisioned(session: SshSession): Promise<ServerInfo> {\n\tconst info = await readServerInfo(session);\n\tif (!info) {\n\t\tthrow new Error(\n\t\t\t`${session.target} has not been provisioned for vela yet.\\n\\n` +\n\t\t\t\t`Run \\`vela provision ${session.target}\\` first.`\n\t\t);\n\t}\n\treturn info;\n}\n\nexport async function readInstanceStates(\n\tsession: SshSession,\n\tinstance?: string\n): Promise<InstanceState[]> {\n\tconst result = await runServerScript<InstanceState[]>(session, 'status.sh', {\n\t\targs: instance ? [instance] : []\n\t});\n\treturn Array.isArray(result) ? result : [];\n}\n\n/** Paths on the server, kept in one place so the scripts and CLI agree. */\nexport const remotePaths = {\n\tapp: (instance: string) => `${VELA_ROOT}/apps/${instance}`,\n\treleases: (instance: string) => `${VELA_ROOT}/apps/${instance}/releases`,\n\trelease: (instance: string, release: string) =>\n\t\t`${VELA_ROOT}/apps/${instance}/releases/${release}`,\n\tshared: (instance: string) => `${VELA_ROOT}/apps/${instance}/shared`,\n\tpbData: (instance: string) => `${VELA_ROOT}/apps/${instance}/shared/pb_data`,\n\tstorage: (instance: string) => `${VELA_ROOT}/apps/${instance}/shared/pb_data/storage`,\n\tbackups: (instance: string) => `${VELA_ROOT}/apps/${instance}/shared/pb_data/backups`,\n\tbackup: (instance: string, key: string) =>\n\t\t`${VELA_ROOT}/apps/${instance}/shared/pb_data/backups/${key}`,\n\t/** Where an archive uploaded from this machine waits, outside pb_data. */\n\trestoreStage: (instance: string) => `${VELA_ROOT}/apps/${instance}/shared/.restore`,\n\tenv: (instance: string) => `${VELA_ETC}/apps/${instance}/env`,\n\truntimeEnv: (instance: string) => `${VELA_ETC}/apps/${instance}/runtime.env`,\n\tcaddy: (instance: string) => `${VELA_ETC}/caddy/${instance}.caddy`,\n\twebUnit: (instance: string) => `vela-web@${instance}.service`,\n\tpbUnit: (instance: string) => `vela-pb@${instance}.service`\n};\n", "import fs from 'node:fs';\nimport dotenv from 'dotenv';\nimport { remotePaths } from './remote.ts';\nimport type { SshSession } from './ssh.ts';\n\nexport type EnvRecord = Record<string, string>;\n\nconst KEY_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/;\n\nexport function isValidKey(key: string): boolean {\n\treturn KEY_PATTERN.test(key);\n}\n\n/**\n * Parse a vela-managed env file.\n *\n * The file is read by systemd, not by dotenv, so quoting follows systemd's\n * `EnvironmentFile` rules: values are double-quoted and `\\\\`, `\\\"` and `\\n` are\n * the escapes. vela writes every value that way, and this reads it back.\n */\nexport function parseEnv(content: string): EnvRecord {\n\tconst result: EnvRecord = {};\n\tfor (const line of content.split('\\n')) {\n\t\tconst trimmed = line.trim();\n\t\tif (!trimmed || trimmed.startsWith('#')) continue;\n\t\tconst eq = trimmed.indexOf('=');\n\t\tif (eq < 1) continue;\n\t\tconst key = trimmed.slice(0, eq).trim();\n\t\tif (!isValidKey(key)) continue;\n\t\tresult[key] = unquote(trimmed.slice(eq + 1).trim());\n\t}\n\treturn result;\n}\n\nfunction unquote(raw: string): string {\n\tif (!raw.startsWith('\"')) return raw;\n\tconst body = raw.endsWith('\"') && raw.length > 1 ? raw.slice(1, -1) : raw.slice(1);\n\tlet out = '';\n\tfor (let i = 0; i < body.length; i++) {\n\t\tif (body[i] !== '\\\\' || i === body.length - 1) {\n\t\t\tout += body[i];\n\t\t\tcontinue;\n\t\t}\n\t\tconst next = body[++i];\n\t\tif (next === 'n') out += '\\n';\n\t\telse if (next === 't') out += '\\t';\n\t\telse out += next;\n\t}\n\treturn out;\n}\n\n/** Canonical, deterministic serialization: sorted keys, always quoted. */\nexport function serializeEnv(env: EnvRecord): string {\n\tconst keys = Object.keys(env).sort();\n\tconst lines = [\n\t\t'# Managed by `vela env`. Values are read by systemd at service start.',\n\t\t...keys.map((key) => `${key}=${quote(env[key]!)}`)\n\t];\n\treturn lines.join('\\n') + '\\n';\n}\n\nfunction quote(value: string): string {\n\tconst escaped = value\n\t\t.replaceAll('\\\\', '\\\\\\\\')\n\t\t.replaceAll('\"', '\\\\\"')\n\t\t.replaceAll('\\n', '\\\\n')\n\t\t.replaceAll('\\t', '\\\\t');\n\treturn `\"${escaped}\"`;\n}\n\n/** Read a local dotenv file, using dotenv's parser for whatever the user wrote. */\nexport function readLocalEnvFile(file: string): EnvRecord {\n\tconst parsed = dotenv.parse(fs.readFileSync(file));\n\tconst result: EnvRecord = {};\n\tfor (const [key, value] of Object.entries(parsed)) {\n\t\tif (isValidKey(key)) result[key] = value;\n\t}\n\treturn result;\n}\n\nexport async function readRemoteEnv(session: SshSession, instance: string): Promise<EnvRecord> {\n\tconst content = await session.readFile(remotePaths.env(instance));\n\treturn content ? parseEnv(content) : {};\n}\n\n/**\n * Replace the instance's env file. The contents travel inside the piped script\n * as base64, so no secret is ever an argument to a remote command.\n */\nexport async function writeRemoteEnv(\n\tsession: SshSession,\n\tinstance: string,\n\tenv: EnvRecord\n): Promise<void> {\n\tconst file = remotePaths.env(instance);\n\tawait session.writeFile(file, serializeEnv(env), '0600');\n\tawait session.script(`chown root:root \"$1\" && chmod 0600 \"$1\"`, { args: [file] });\n}\n\n/**\n * Credentials the app authenticates to its own PocketBase with.\n *\n * Not ordinary variables: the value here has to match a record in the\n * instance's database, and only a deploy can put it there. Changing one and\n * restarting on the spot would leave the app unable to authenticate, so the\n * env commands write the value and leave the restart to `vela deploy`.\n */\nexport const SUPERUSER_KEYS = [\n\t'POCKETBASE_SUPERUSER_EMAIL',\n\t'POCKETBASE_SUPERUSER_PASSWORD'\n] as const;\n\nexport function touchesSuperuser(keys: Iterable<string>): boolean {\n\tfor (const key of keys) {\n\t\tif ((SUPERUSER_KEYS as readonly string[]).includes(key)) return true;\n\t}\n\treturn false;\n}\n\nexport interface RestartOutcome {\n\tdeployed: boolean;\n\trestarted: boolean;\n\terror?: string;\n}\n\n/**\n * Restart an instance so new values take effect. An env change that lands but\n * fails to restart is reported as exactly that \u2014 the value is stored either way,\n * so it is never rolled back over a restart failure.\n */\nexport async function restartInstance(\n\tsession: SshSession,\n\tinstance: string\n): Promise<RestartOutcome> {\n\t// Only units this instance actually enabled \u2014 a frontend-only app has no\n\t// PocketBase service, and restarting a unit that was never deployed fails.\n\tconst result = await session.script(\n\t\t`instance=\"$1\"\nenabled=()\nfor unit in \"vela-pb@$instance.service\" \"vela-web@$instance.service\"; do\n\tif systemctl is-enabled \"$unit\" >/dev/null 2>&1; then enabled+=(\"$unit\"); fi\ndone\nif [ \\${#enabled[@]} -eq 0 ]; then echo NOT_DEPLOYED; exit 0; fi\nsystemctl restart \"\\${enabled[@]}\"`,\n\t\t{ args: [instance], check: false }\n\t);\n\n\tif (result.stdout.includes('NOT_DEPLOYED')) return { deployed: false, restarted: false };\n\tif (result.exitCode !== 0) {\n\t\treturn { deployed: true, restarted: false, error: result.stderr.trim() };\n\t}\n\treturn { deployed: true, restarted: true };\n}\n", "import { branchToEnvTag, normalizeEnvTag, PROD_ENV } from './instance.ts';\n\n/**\n * Which copy of the app a command acts on.\n *\n * A target never names a machine. `local` is the project on this computer;\n * everything else is an environment deployed somewhere, and the server behind it\n * is a binding recorded in `.vela/project.json` rather than something retyped on\n * every command.\n */\nexport interface LocalTarget {\n\tkind: 'local';\n}\n\nexport interface RemoteTarget {\n\tkind: 'remote';\n\t/** Canonical name, as typed and as shown back. */\n\tname: string;\n\t/** Server-side instance suffix. Derived, never stored. */\n\tenvTag: string;\n}\n\n/** Parsed so the grammar is settled, refused until previews are built. */\nexport interface PreviewTarget {\n\tkind: 'preview';\n\tbranch?: string;\n\tenvTag: string;\n}\n\nexport type Target = LocalTarget | RemoteTarget | PreviewTarget;\n\nexport const LOCAL_TARGET = 'local';\nexport const PRODUCTION_TARGET = 'production';\n\n/** What a command means when no `-t` is given. */\nexport type TargetFallback = 'local' | 'production';\n\nexport class TargetError extends Error {}\n\n/**\n * Values that are obviously a server rather than a target.\n *\n * `-t` used to mean the SSH host, so `vela env list -t root@1.2.3.4` parsed\n * happily before this change and would otherwise go on parsing \u2014 resolving to a\n * target named after a machine instead of failing. An ssh_config alias with no\n * dots (`myserver`) is indistinguishable from a custom target name and is not\n * caught here; the dotted, `@`-bearing and numeric forms cover what people\n * actually typed.\n */\nconst SERVER_SHAPED = /@|^\\d{1,3}(?:\\.\\d{1,3}){3}$|\\.[a-z]{2,}$/i;\n\nconst PREVIEW = 'preview';\n\nconst TARGET_NAME = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;\n\n/**\n * Read a `-t/--target` value.\n *\n * `preview:<branch>` is split before any normalization: `normalizeEnvTag` turns a\n * colon into a single dash, so `preview:feature/maps` would become\n * `preview-feature-maps` while `branchToEnvTag('feature/maps')` gives\n * `preview--feature-maps`. Two spellings of one branch pointing at two different\n * instances is the kind of thing that is only discovered on a server.\n */\nexport function parseTarget(raw: string | undefined, fallback: TargetFallback): Target {\n\tconst value = raw?.trim();\n\tif (!value) {\n\t\treturn fallback === 'local' ? { kind: 'local' } : production();\n\t}\n\n\tif (SERVER_SHAPED.test(value)) {\n\t\tthrow new TargetError(\n\t\t\t`${value} looks like a server, and ${bold('-t')} now selects a target rather than a machine.\\n\\n` +\n\t\t\t\t`Targets are ${bold('local')}, ${bold('production')}, or a name you choose such as ${bold('staging')}.\\n` +\n\t\t\t\t`To point a target at a server, pass ${bold('--server')} on \\`vela deploy\\`.`\n\t\t);\n\t}\n\n\tconst lower = value.toLowerCase();\n\tif (lower === LOCAL_TARGET) return { kind: 'local' };\n\n\tif (lower === PREVIEW || lower.startsWith(`${PREVIEW}:`)) {\n\t\tconst branch = lower.slice(PREVIEW.length + 1) || undefined;\n\t\treturn {\n\t\t\tkind: 'preview',\n\t\t\tbranch,\n\t\t\t// Held for when previews are built, so the grammar and the instance\n\t\t\t// naming cannot drift apart in the meantime.\n\t\t\tenvTag: branch ? branchToEnvTag(branch) : PREVIEW\n\t\t};\n\t}\n\n\tif (value.includes(':')) {\n\t\tthrow new TargetError(\n\t\t\t`${value} is not a target. Only ${bold('preview')} takes a \\`:branch\\` suffix.`\n\t\t);\n\t}\n\n\t// Validated, never scrubbed. `normalizeEnvTag` would quietly turn `pre view!`\n\t// into `pre-view`, and a selector that silently addresses a different \u2014 and\n\t// therefore empty \u2014 instance reports success for a typo.\n\tif (!TARGET_NAME.test(lower)) {\n\t\tthrow new TargetError(\n\t\t\t`${value} is not a target name.\\n\\n` +\n\t\t\t\t`Use lowercase letters, digits and single dashes, such as ${bold('staging')}.`\n\t\t);\n\t}\n\n\treturn { kind: 'remote', name: lower, envTag: normalizeEnvTag(lower) };\n}\n\nfunction production(): Target {\n\treturn { kind: 'remote', name: PRODUCTION_TARGET, envTag: PROD_ENV };\n}\n\n/** How a target reads back in output and errors. */\nexport function describeTarget(target: Target): string {\n\tswitch (target.kind) {\n\t\tcase 'local':\n\t\t\treturn LOCAL_TARGET;\n\t\tcase 'preview':\n\t\t\treturn target.branch ? `${PREVIEW}:${target.branch}` : PREVIEW;\n\t\tcase 'remote':\n\t\t\treturn target.name;\n\t}\n}\n\nfunction bold(text: string): string {\n\treturn `\\`${text}\\``;\n}\n", "import pc from 'picocolors';\nimport type PocketBase from 'pocketbase';\nimport { hasBackend } from './workspace.ts';\nimport { readLocalEnv } from './local-env.ts';\nimport { withPocketbase } from './pocketbase.ts';\nimport { withRemotePocketbase } from './remote-pocketbase.ts';\nimport { readInstanceStates } from './remote.ts';\nimport { withTarget } from './server-command.ts';\nimport type { SshSession } from './ssh.ts';\n\nexport interface BackupContext {\n\tpb: PocketBase;\n\t/** The deployed instance's session, or null for the local database. */\n\tsession: SshSession | null;\n\t/** Instance id on a server, app name locally. Names the archive either way. */\n\tinstance: string;\n\t/** How to refer to this copy of the app in output. */\n\ttargetName: string;\n\tworkspaceRootDir: string;\n}\n\n/**\n * Open whichever database `-t` names, for a command that acts on its backups.\n *\n * The two paths differ only in how PocketBase is reached \u2014 a subprocess against\n * `data/` here, a forwarded port there \u2014 so every backup subcommand is written\n * once against the handle this yields.\n */\nexport async function withBackupTarget(\n\traw: unknown,\n\tlabel: string,\n\tfn: (ctx: BackupContext) => Promise<void>\n): Promise<void> {\n\tawait withTarget(\n\t\traw,\n\t\t{\n\t\t\tlocal: async (ctx) => {\n\t\t\t\tif (!hasBackend(ctx.workspaceRootDir)) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`This project has no database, so there is nothing to back up.\\n\\n` +\n\t\t\t\t\t\t\t`Run ${pc.cyan('vela bless')} to add a backend.`\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\t// Read here rather than relying on the process environment: `backup`\n\t\t\t\t// is a NO_BACKEND command precisely so that acting on a server does\n\t\t\t\t// not require local credentials, which means nothing has loaded them.\n\t\t\t\tconst creds = readLocalEnv(ctx.envFile);\n\t\t\t\tconst email = creds.POCKETBASE_SUPERUSER_EMAIL;\n\t\t\t\tconst password = creds.POCKETBASE_SUPERUSER_PASSWORD;\n\t\t\t\tif (!email || !password) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`The local database has no superuser credentials to sign in with.\\n\\n` +\n\t\t\t\t\t\t\t`Set ${pc.cyan('POCKETBASE_SUPERUSER_EMAIL')} and ` +\n\t\t\t\t\t\t\t`${pc.cyan('POCKETBASE_SUPERUSER_PASSWORD')} in ${pc.cyan('.env')}.`\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tawait withPocketbase(\n\t\t\t\t\tctx.workspaceRootDir,\n\t\t\t\t\t(pb) =>\n\t\t\t\t\t\tfn({\n\t\t\t\t\t\t\tpb,\n\t\t\t\t\t\t\tsession: null,\n\t\t\t\t\t\t\tinstance: ctx.appName,\n\t\t\t\t\t\t\ttargetName: 'local',\n\t\t\t\t\t\t\tworkspaceRootDir: ctx.workspaceRootDir\n\t\t\t\t\t\t}),\n\t\t\t\t\t{ email, password }\n\t\t\t\t);\n\t\t\t},\n\t\t\tremote: async (ctx) => {\n\t\t\t\tconst [state] = await readInstanceStates(ctx.session, ctx.instance);\n\t\t\t\tif (state && state.backend === false) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`${ctx.targetName} was deployed without a database, so it has nothing to back up.`\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tawait withRemotePocketbase(ctx.session, ctx.instance, (pb) =>\n\t\t\t\t\tfn({\n\t\t\t\t\t\tpb,\n\t\t\t\t\t\tsession: ctx.session,\n\t\t\t\t\t\tinstance: ctx.instance,\n\t\t\t\t\t\ttargetName: ctx.targetName,\n\t\t\t\t\t\tworkspaceRootDir: ctx.workspaceRootDir\n\t\t\t\t\t})\n\t\t\t\t);\n\t\t\t}\n\t\t},\n\t\t{ label }\n\t);\n}\n", "import fs from 'node:fs';\nimport * as p from '@clack/prompts';\nimport pc from 'picocolors';\nimport { removeEnvVar, upsertEnvVar } from './env.ts';\nimport { readLocalEnvFile, touchesSuperuser, type EnvRecord } from './remote-env.ts';\nimport { ensureSuperuser, getPocketbaseMetadata } from './pocketbase.ts';\nimport type { LocalContext } from './server-command.ts';\n\n/** The project's `.env`, or an empty record when it has none yet. */\nexport function readLocalEnv(envFile: string): EnvRecord {\n\tif (!fs.existsSync(envFile)) return {};\n\treturn readLocalEnvFile(envFile);\n}\n\nexport function editLocalEnv(envFile: string, edit: (content: string) => string): void {\n\tconst before = fs.existsSync(envFile) ? fs.readFileSync(envFile, 'utf8') : '';\n\tconst after = edit(before);\n\tif (after !== before) fs.writeFileSync(envFile, after);\n}\n\nexport function setLocalEnv(envFile: string, key: string, value: string): void {\n\teditLocalEnv(envFile, (content) => upsertEnvVar(content, key, value));\n}\n\nexport function unsetLocalEnv(envFile: string, key: string): void {\n\teditLocalEnv(envFile, (content) => removeEnvVar(content, key));\n}\n\n/**\n * The local counterpart of `applyEnvRestart`.\n *\n * Remotely, superuser credentials in the environment have to match a record in\n * the instance's database and only a deploy reconciles them. The same hazard\n * exists here, except the fix is local and immediate: `ensureSuperuser` upserts\n * the account so `.env` and `data/` cannot disagree.\n */\nexport async function applyLocalEnvChange(ctx: LocalContext, changed: string[]): Promise<void> {\n\tif (touchesSuperuser(changed)) {\n\t\tconst env = readLocalEnv(ctx.envFile);\n\t\tconst email = env.POCKETBASE_SUPERUSER_EMAIL;\n\t\tconst password = env.POCKETBASE_SUPERUSER_PASSWORD;\n\n\t\tif (email && password) {\n\t\t\t// `ensureSuperuser` reads them from the environment of this process,\n\t\t\t// which was loaded before the file was edited.\n\t\t\tprocess.env.POCKETBASE_SUPERUSER_EMAIL = email;\n\t\t\tprocess.env.POCKETBASE_SUPERUSER_PASSWORD = password;\n\t\t\tawait ensureSuperuser(ctx.workspaceRootDir);\n\t\t\tp.log.success('Local superuser updated to match');\n\t\t} else {\n\t\t\tp.log.warn(\n\t\t\t\t`The local database still has the old superuser.\\n` +\n\t\t\t\t\t`Set both ${pc.cyan('POCKETBASE_SUPERUSER_EMAIL')} and ${pc.cyan('POCKETBASE_SUPERUSER_PASSWORD')} to reconcile it.`\n\t\t\t);\n\t\t}\n\t}\n\n\tif (getPocketbaseMetadata(ctx.workspaceRootDir)) {\n\t\tp.log.info(`Restart ${pc.cyan('vela dev')} to pick this up.`);\n\t}\n}\n", "import PocketBase from 'pocketbase';\nimport { findFreePort, authWithRetries } from './pocketbase.ts';\nimport { readInstanceStates } from './remote.ts';\nimport { readRemoteEnv } from './remote-env.ts';\nimport type { SshSession } from './ssh.ts';\n\nexport interface RemoteDatabase {\n\t/** Loopback URL on this machine, forwarded to the instance's PocketBase. */\n\turl: string;\n\temail: string;\n\tpassword: string;\n\tclose: () => Promise<void>;\n}\n\n/**\n * Forward a port to the PocketBase of a deployed instance and hand back the\n * credentials to talk to it.\n *\n * PocketBase listens on the server's loopback only, so the SSH connection that\n * is already open is the way in. The superuser credentials come off the server\n * itself: they are the app's own, and nothing about them has to be known here.\n */\nexport async function openRemoteDatabase(\n\tsession: SshSession,\n\tinstance: string\n): Promise<RemoteDatabase> {\n\tconst [state] = await readInstanceStates(session, instance);\n\tconst pbPort = state?.pbPort;\n\tif (!pbPort) {\n\t\tthrow new Error(\n\t\t\t`${instance} has no deployed database yet.\\n\\n` +\n\t\t\t\t`Run \\`vela deploy\\` first \u2014 the database is created by the first deploy.`\n\t\t);\n\t}\n\n\tconst env = await readRemoteEnv(session, instance);\n\tconst email = env.POCKETBASE_SUPERUSER_EMAIL;\n\tconst password = env.POCKETBASE_SUPERUSER_PASSWORD;\n\tif (!email || !password) {\n\t\tthrow new Error(\n\t\t\t`${instance} has no PocketBase superuser credentials in its environment.\\n\\n` +\n\t\t\t\t`A deploy creates them. Deploy again to repair this instance.`\n\t\t);\n\t}\n\n\tconst localPort = await findFreePort('127.0.0.1');\n\tawait session.forwardLocalPort(localPort, '127.0.0.1', pbPort);\n\n\treturn {\n\t\turl: `http://127.0.0.1:${localPort}`,\n\t\temail,\n\t\tpassword,\n\t\tclose: () => session.cancelForward(localPort, '127.0.0.1', pbPort)\n\t};\n}\n\n/** Run one piece of work against a deployed instance's database, authenticated. */\nexport async function withRemotePocketbase<T>(\n\tsession: SshSession,\n\tinstance: string,\n\tfn: (pb: PocketBase) => Promise<T>\n): Promise<T> {\n\tconst db = await openRemoteDatabase(session, instance);\n\ttry {\n\t\tconst pb = new PocketBase(db.url);\n\t\tawait authWithRetries(pb, db.email, db.password);\n\t\treturn await fn(pb);\n\t} finally {\n\t\tawait db.close();\n\t}\n}\n", "import fs from 'node:fs';\nimport path from 'node:path';\nimport type PocketBase from 'pocketbase';\nimport { DATA_DIR } from './constants.ts';\nimport { remotePaths } from './remote.ts';\nimport type { SshSession } from './ssh.ts';\n\nexport interface S3Config {\n\tendpoint: string;\n\tbucket: string;\n\tregion: string;\n\taccessKey: string;\n\tsecret: string;\n\tforcePathStyle: boolean;\n}\n\n/** Which of PocketBase's two independent S3 configurations to write. */\nexport type S3Filesystem = 'storage' | 'backups';\n\n/**\n * Providers that address buckets as a subdomain.\n *\n * Everything else \u2014 MinIO, Ceph, Garage, most self-hosted gateways \u2014 needs the\n * bucket in the path instead, and gets an opaque connection failure when it does\n * not. Guessing from the endpoint is right far more often than defaulting to\n * either answer outright.\n */\nconst VIRTUAL_HOSTED = [/\\.amazonaws\\.com$/i, /\\.r2\\.cloudflarestorage\\.com$/i];\n\nexport function defaultForcePathStyle(endpoint: string): boolean {\n\tlet host: string;\n\ttry {\n\t\thost = new URL(endpoint).hostname;\n\t} catch {\n\t\treturn false;\n\t}\n\treturn !VIRTUAL_HOSTED.some((pattern) => pattern.test(host));\n}\n\nexport async function applyS3(\n\tpb: PocketBase,\n\tconfig: S3Config,\n\tfilesystem: S3Filesystem\n): Promise<void> {\n\tconst s3 = { enabled: true, ...config };\n\tawait pb.settings.update(filesystem === 'backups' ? { backups: { s3 } } : { s3 });\n}\n\nexport async function disableS3(pb: PocketBase, filesystem: S3Filesystem): Promise<void> {\n\t// Only `enabled` is sent: PocketBase merges settings, so the credentials stay\n\t// on record and turning it back on does not mean retyping them.\n\tconst s3 = { enabled: false };\n\tawait pb.settings.update(filesystem === 'backups' ? { backups: { s3 } } : { s3 });\n}\n\nexport interface StoredS3 {\n\tenabled: boolean;\n\tendpoint: string;\n\tbucket: string;\n\tregion: string;\n\taccessKey: string;\n\tforcePathStyle: boolean;\n}\n\n/**\n * Read back what is already configured, to pre-fill the prompts.\n *\n * The secret is never included \u2014 PocketBase strips it from the settings it\n * serves \u2014 so it is the one value that always has to be typed again.\n */\nexport async function readS3(pb: PocketBase, filesystem: S3Filesystem): Promise<StoredS3> {\n\tconst settings = (await pb.settings.getAll()) as {\n\t\ts3?: Partial<StoredS3>;\n\t\tbackups?: { s3?: Partial<StoredS3> };\n\t};\n\tconst s3 = (filesystem === 'backups' ? settings.backups?.s3 : settings.s3) ?? {};\n\treturn {\n\t\tenabled: s3.enabled === true,\n\t\tendpoint: s3.endpoint ?? '',\n\t\tbucket: s3.bucket ?? '',\n\t\tregion: s3.region ?? '',\n\t\taccessKey: s3.accessKey ?? '',\n\t\tforcePathStyle: s3.forcePathStyle === true\n\t};\n}\n\n/**\n * Whether any upload is already sitting on local disk.\n *\n * Turning S3 on switches which filesystem PocketBase reads from; it moves\n * nothing. Every file already on disk stops resolving the moment it is enabled,\n * so this is the difference between a clean switch and a wall of broken images.\n *\n * The answer only has to be yes or no, so both paths stop at the first file\n * rather than counting a tree that may hold millions.\n */\nexport async function hasLocalUploads(\n\tsession: SshSession | null,\n\tinstance: string,\n\tworkspaceRootDir: string\n): Promise<boolean> {\n\tif (session) {\n\t\tconst result = await session.script(`[ -d \"$1\" ] || exit 0; find \"$1\" -type f -print -quit`, {\n\t\t\targs: [remotePaths.storage(instance)]\n\t\t});\n\t\treturn result.stdout.trim().length > 0;\n\t}\n\treturn hasFile(path.join(workspaceRootDir, DATA_DIR, 'storage'));\n}\n\nfunction hasFile(dir: string): boolean {\n\tlet entries: fs.Dirent[];\n\ttry {\n\t\tentries = fs.readdirSync(dir, { withFileTypes: true });\n\t} catch {\n\t\treturn false;\n\t}\n\tfor (const entry of entries) {\n\t\tif (entry.isFile()) return true;\n\t\tif (entry.isDirectory() && hasFile(path.join(dir, entry.name))) return true;\n\t}\n\treturn false;\n}\n", "import process from 'node:process';\nimport { Command } from 'commander';\nimport * as p from '@clack/prompts';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand } from '../../lib/run.ts';\nimport { withPocketbase } from '../../lib/pocketbase.ts';\nimport { getWorkspace } from '../../lib/workspace.ts';\nimport { reportResult } from '../../lib/result-report.ts';\n\nexport const smtp = new Command('smtp')\n\t.description('configure SMTP for transactional email')\n\t.configureHelp(helpConfig)\n\t.action(() =>\n\t\trunCommand(async () => {\n\t\t\tconst { workspaceRootDir } = await getWorkspace();\n\n\t\t\tconst config = await p.group(\n\t\t\t\t{\n\t\t\t\t\thost: () =>\n\t\t\t\t\t\tp.text({\n\t\t\t\t\t\t\tmessage: 'SMTP host',\n\t\t\t\t\t\t\tplaceholder: 'smtp.example.com',\n\t\t\t\t\t\t\tvalidate: (v) => (v ? undefined : 'Host is required')\n\t\t\t\t\t\t}),\n\t\t\t\t\tport: () =>\n\t\t\t\t\t\tp.text({\n\t\t\t\t\t\t\tmessage: 'SMTP port',\n\t\t\t\t\t\t\tinitialValue: '587',\n\t\t\t\t\t\t\tvalidate: (v) => {\n\t\t\t\t\t\t\t\tif (!v) return 'Port is required';\n\t\t\t\t\t\t\t\tconst n = Number(v);\n\t\t\t\t\t\t\t\tif (!Number.isInteger(n) || n <= 0 || n > 65535) return 'Invalid port';\n\t\t\t\t\t\t\t\treturn undefined;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}),\n\t\t\t\t\tusername: () => p.text({ message: 'SMTP username' }),\n\t\t\t\t\tpassword: () => p.password({ message: 'SMTP password' })\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tonCancel: () => {\n\t\t\t\t\t\tp.cancel('Operation cancelled.');\n\t\t\t\t\t\tprocess.exit(0);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t);\n\n\t\t\tawait withPocketbase(workspaceRootDir, async (pb) => {\n\t\t\t\tawait pb.settings.update({\n\t\t\t\t\tsmtp: {\n\t\t\t\t\t\tenabled: true,\n\t\t\t\t\t\thost: config.host,\n\t\t\t\t\t\tport: parseInt(config.port, 10),\n\t\t\t\t\t\tusername: config.username ?? '',\n\t\t\t\t\t\tpassword: config.password ?? ''\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t});\n\n\t\t\treportResult({\n\t\t\t\tsummary: 'Enabled SMTP for transactional email.',\n\t\t\t\tnextSteps: [\n\t\t\t\t\t'PocketBase will now send auth/verification email via your SMTP server.',\n\t\t\t\t\t'Send a test email from the PocketBase admin UI (Settings \u2192 Mail settings).',\n\t\t\t\t\t'Run `vela disable smtp` to revert to the built-in fallback sender.'\n\t\t\t\t]\n\t\t\t});\n\t\t}, 'Failed to enable SMTP.')\n\t);\n", "import process from 'node:process';\nimport { Command } from 'commander';\nimport * as p from '@clack/prompts';\nimport pc from 'picocolors';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand } from '../../lib/run.ts';\nimport { runPattern } from '../../lib/pattern-runner.ts';\nimport { hasBackend } from '../../lib/workspace.ts';\n\nexport const cms = new Command('cms')\n\t.description('enable an inline-editing CMS with an admin bar')\n\t.allowUnknownOption(true)\n\t.configureHelp(helpConfig)\n\t.action((_opts, cmd) =>\n\t\trunCommand(async () => {\n\t\t\t// The command is exempt from the PocketBase guard \u2014 the CMS keeps its own\n\t\t\t// database \u2014 but the backend it installs runs inside the app's server,\n\t\t\t// which a static project does not have.\n\t\t\tif (!hasBackend()) {\n\t\t\t\tp.log.error(\n\t\t\t\t\t`${pc.cyan('vela enable cms')} needs a server to host the CMS backend, and this project is static.\\n\\n` +\n\t\t\t\t\t\t`Run ${pc.cyan('vela bless')} to add a backend first.`\n\t\t\t\t);\n\t\t\t\tp.log.message();\n\t\t\t\tp.cancel('Operation failed.');\n\t\t\t\tprocess.exitCode = 1;\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tawait runPattern(\n\t\t\t\t'enable-cms',\n\t\t\t\tcmd.args,\n\t\t\t\t{},\n\t\t\t\t{\n\t\t\t\t\tsummary: 'Enabled CMS.',\n\t\t\t\t\tnextSteps: [\n\t\t\t\t\t\t'Run `vela cms editor add you@example.com` to create the first editor login.',\n\t\t\t\t\t\t'Run `vela dev`, open any page with `?edit` on the URL, and sign in from the admin bar.',\n\t\t\t\t\t\t'Wrap page copy in `<CmsText>` and images in `<CmsImage>` to make them editable.'\n\t\t\t\t\t],\n\t\t\t\t\ttask: {\n\t\t\t\t\t\ttitle: 'Enabling CMS',\n\t\t\t\t\t\tsuccess: 'Enabled CMS',\n\t\t\t\t\t\terror: 'Failed to enable CMS'\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t);\n\t\t}, 'Failed to enable CMS.')\n\t);\n", "import { Command } from 'commander';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand } from '../../lib/run.ts';\nimport { runPattern } from '../../lib/pattern-runner.ts';\n\nexport const blog = new Command('blog')\n\t.description('enable an mdsvex blog with posts, tags, and RSS')\n\t.allowUnknownOption(true)\n\t.configureHelp(helpConfig)\n\t.action((_opts, cmd) =>\n\t\trunCommand(\n\t\t\t() =>\n\t\t\t\trunPattern(\n\t\t\t\t\t'enable-blog',\n\t\t\t\t\tcmd.args,\n\t\t\t\t\t{},\n\t\t\t\t\t{\n\t\t\t\t\t\tsummary: 'Enabled blog.',\n\t\t\t\t\t\tnextSteps: [\n\t\t\t\t\t\t\t'Run `vela dev` and visit /blog to see the example posts.',\n\t\t\t\t\t\t\t'Add new posts as .svx files in src/lib/content/blog/.',\n\t\t\t\t\t\t\t'Customize the post layout in src/routes/(public)/blog/[slug]/+page.svelte.'\n\t\t\t\t\t\t],\n\t\t\t\t\t\ttask: {\n\t\t\t\t\t\t\ttitle: 'Enabling blog',\n\t\t\t\t\t\t\tsuccess: 'Enabled blog',\n\t\t\t\t\t\t\terror: 'Failed to enable blog'\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t),\n\t\t\t'Failed to enable blog.'\n\t\t)\n\t);\n", "import { Command } from 'commander';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand } from '../../lib/run.ts';\nimport { runPattern } from '../../lib/pattern-runner.ts';\n\nexport const contentNegotiation = new Command('content-negotiation')\n\t.description('enable content negotiation (sveltekit-negotiate)')\n\t.allowUnknownOption(true)\n\t.configureHelp(helpConfig)\n\t.action((_opts, cmd) =>\n\t\trunCommand(\n\t\t\t() =>\n\t\t\t\trunPattern(\n\t\t\t\t\t'enable-content-negotiation',\n\t\t\t\t\tcmd.args,\n\t\t\t\t\t{},\n\t\t\t\t\t{\n\t\t\t\t\t\tsummary: 'Enabled content negotiation.',\n\t\t\t\t\t\tnextSteps: [\n\t\t\t\t\t\t\t'Create `+page.json.ts` / `+page.xml.ts` siblings alongside your routes to serve JSON/XML representations.',\n\t\t\t\t\t\t\t'Visit a page with `Accept: application/json` to verify content negotiation is wired up.'\n\t\t\t\t\t\t],\n\t\t\t\t\t\ttask: {\n\t\t\t\t\t\t\ttitle: 'Enabling content negotiation',\n\t\t\t\t\t\t\tsuccess: 'Enabled content negotiation',\n\t\t\t\t\t\t\terror: 'Failed to enable content negotiation'\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t),\n\t\t\t'Failed to enable content negotiation.'\n\t\t)\n\t);\n", "import { Command } from 'commander';\nimport { helpConfig } from '../lib/help.ts';\nimport { auth } from './disable/auth.ts';\nimport { api } from './disable/api.ts';\nimport { apiKeys } from './disable/api-keys.ts';\nimport { backend } from './disable/backend.ts';\nimport { contentNegotiation } from './disable/content-negotiation.ts';\nimport { i18n } from './disable/i18n.ts';\nimport { teams } from './disable/teams.ts';\nimport { payments } from './disable/payments.ts';\nimport { s3 } from './disable/s3.ts';\nimport { smtp } from './disable/smtp.ts';\n\nexport const disable = new Command('disable')\n\t.description('disable features')\n\t.configureHelp(helpConfig)\n\t.addCommand(auth)\n\t.addCommand(api)\n\t.addCommand(apiKeys)\n\t.addCommand(backend)\n\t.addCommand(contentNegotiation)\n\t.addCommand(i18n)\n\t.addCommand(teams)\n\t.addCommand(payments)\n\t.addCommand(s3)\n\t.addCommand(smtp);\n", "import { Command } from 'commander';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand, runDisable } from './_shared.ts';\n\nexport const auth = new Command('auth')\n\t.description('disable authentication')\n\t.option('-y, --yes', 'skip confirmation prompt')\n\t.allowUnknownOption(true)\n\t.configureHelp(helpConfig)\n\t.action((opts, cmd) =>\n\t\trunCommand(\n\t\t\t() =>\n\t\t\t\trunDisable(\n\t\t\t\t\t{\n\t\t\t\t\t\tslug: 'disable-auth',\n\t\t\t\t\t\tconfirmMessage:\n\t\t\t\t\t\t\t'Disable auth? Removes auth routes, drops oauth_accounts, and reverts layout/hooks edits. The users collection and existing accounts are preserved.',\n\t\t\t\t\t\treport: {\n\t\t\t\t\t\t\tsummary: 'Disabled authentication.',\n\t\t\t\t\t\t\tnextSteps: [\n\t\t\t\t\t\t\t\t'Users collection and accounts are kept. Drop them manually in the PocketBase admin if you no longer need them.'\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\ttask: {\n\t\t\t\t\t\t\t\ttitle: 'Disabling auth',\n\t\t\t\t\t\t\t\tsuccess: 'Disabled auth',\n\t\t\t\t\t\t\t\terror: 'Failed to disable auth'\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\topts,\n\t\t\t\t\tcmd.args\n\t\t\t\t),\n\t\t\t'Failed to disable auth.'\n\t\t)\n\t);\n", "import process from 'node:process';\nimport * as p from '@clack/prompts';\nimport type { Slug } from '@velastack/patterns';\nimport { runCommand } from '../../lib/run.ts';\nimport { runPattern, type PatternReport } from '../../lib/pattern-runner.ts';\n\nexport interface DisableOptions {\n\tslug: Slug;\n\tconfirmMessage: string;\n\treport: PatternReport;\n}\n\nexport async function runDisable(\n\topts: DisableOptions,\n\tflags: { yes?: boolean },\n\tcmdArgs: string[]\n): Promise<void> {\n\tif (!flags.yes) {\n\t\tconst ok = await p.confirm({\n\t\t\tmessage: opts.confirmMessage,\n\t\t\tinitialValue: false\n\t\t});\n\t\tif (p.isCancel(ok) || !ok) {\n\t\t\tp.cancel('Operation cancelled.');\n\t\t\tprocess.exit(0);\n\t\t}\n\t}\n\tawait runPattern(opts.slug, cmdArgs, { destructive: true }, opts.report);\n}\n\nexport { runCommand };\n", "import { Command } from 'commander';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand, runDisable } from './_shared.ts';\n\nexport const api = new Command('api')\n\t.description('disable the REST API')\n\t.option('-y, --yes', 'skip confirmation prompt')\n\t.allowUnknownOption(true)\n\t.configureHelp(helpConfig)\n\t.action((opts, cmd) =>\n\t\trunCommand(\n\t\t\t() =>\n\t\t\t\trunDisable(\n\t\t\t\t\t{\n\t\t\t\t\t\tslug: 'disable-api',\n\t\t\t\t\t\tconfirmMessage: 'Disable the REST API? Removes the PocketBase API handler.',\n\t\t\t\t\t\treport: {\n\t\t\t\t\t\t\tsummary: 'Disabled the REST API.',\n\t\t\t\t\t\t\ttask: {\n\t\t\t\t\t\t\t\ttitle: 'Disabling API',\n\t\t\t\t\t\t\t\tsuccess: 'Disabled API',\n\t\t\t\t\t\t\t\terror: 'Failed to disable API'\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\topts,\n\t\t\t\t\tcmd.args\n\t\t\t\t),\n\t\t\t'Failed to disable API.'\n\t\t)\n\t);\n", "import { Command } from 'commander';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand, runDisable } from './_shared.ts';\n\nexport const apiKeys = new Command('api-keys')\n\t.description('disable API key management')\n\t.option('-y, --yes', 'skip confirmation prompt')\n\t.allowUnknownOption(true)\n\t.configureHelp(helpConfig)\n\t.action((opts, cmd) =>\n\t\trunCommand(\n\t\t\t() =>\n\t\t\t\trunDisable(\n\t\t\t\t\t{\n\t\t\t\t\t\tslug: 'disable-api-keys',\n\t\t\t\t\t\tconfirmMessage:\n\t\t\t\t\t\t\t'Disable API key management? Drops the api_keys collection, reverts hooks.server and nav-user, and removes generated API key routes.',\n\t\t\t\t\t\treport: {\n\t\t\t\t\t\t\tsummary: 'Disabled API key management.',\n\t\t\t\t\t\t\ttask: {\n\t\t\t\t\t\t\t\ttitle: 'Disabling API keys',\n\t\t\t\t\t\t\t\tsuccess: 'Disabled API keys',\n\t\t\t\t\t\t\t\terror: 'Failed to disable API keys'\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\topts,\n\t\t\t\t\tcmd.args\n\t\t\t\t),\n\t\t\t'Failed to disable API keys.'\n\t\t)\n\t);\n", "import { Command } from 'commander';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand, runDisable } from './_shared.ts';\n\nexport const backend = new Command('backend')\n\t.description('disable the PocketBase backend')\n\t.option('-y, --yes', 'skip confirmation prompt')\n\t.allowUnknownOption(true)\n\t.configureHelp(helpConfig)\n\t.action((opts, cmd) =>\n\t\trunCommand(\n\t\t\t() =>\n\t\t\t\trunDisable(\n\t\t\t\t\t{\n\t\t\t\t\t\tslug: 'disable-backend',\n\t\t\t\t\t\tconfirmMessage:\n\t\t\t\t\t\t\t'Disable the PocketBase backend? Removes hooks.server.ts, the data/ scaffold, and reverts the SvelteKit adapter. The @velastack/pocketbase and pocketbase-sveltekit packages stay installed.',\n\t\t\t\t\t\treport: {\n\t\t\t\t\t\t\tsummary: 'Disabled the PocketBase backend.',\n\t\t\t\t\t\t\ttask: {\n\t\t\t\t\t\t\t\ttitle: 'Disabling backend',\n\t\t\t\t\t\t\t\tsuccess: 'Disabled backend',\n\t\t\t\t\t\t\t\terror: 'Failed to disable backend'\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\topts,\n\t\t\t\t\tcmd.args\n\t\t\t\t),\n\t\t\t'Failed to disable backend.'\n\t\t)\n\t);\n", "import { Command } from 'commander';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand, runDisable } from './_shared.ts';\n\nexport const contentNegotiation = new Command('content-negotiation')\n\t.description('disable content negotiation')\n\t.option('-y, --yes', 'skip confirmation prompt')\n\t.allowUnknownOption(true)\n\t.configureHelp(helpConfig)\n\t.action((opts, cmd) =>\n\t\trunCommand(\n\t\t\t() =>\n\t\t\t\trunDisable(\n\t\t\t\t\t{\n\t\t\t\t\t\tslug: 'disable-content-negotiation',\n\t\t\t\t\t\tconfirmMessage:\n\t\t\t\t\t\t\t'Disable content negotiation? Unwraps hooks.server handle, reverts reroute, and removes <Negotiate /> from the root layout.',\n\t\t\t\t\t\treport: {\n\t\t\t\t\t\t\tsummary: 'Disabled content negotiation.',\n\t\t\t\t\t\t\ttask: {\n\t\t\t\t\t\t\t\ttitle: 'Disabling content negotiation',\n\t\t\t\t\t\t\t\tsuccess: 'Disabled content negotiation',\n\t\t\t\t\t\t\t\terror: 'Failed to disable content negotiation'\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\topts,\n\t\t\t\t\tcmd.args\n\t\t\t\t),\n\t\t\t'Failed to disable content negotiation.'\n\t\t)\n\t);\n", "import { Command } from 'commander';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand, runDisable } from './_shared.ts';\n\nexport const i18n = new Command('i18n')\n\t.description('disable internationalization')\n\t.option('-y, --yes', 'skip confirmation prompt')\n\t.allowUnknownOption(true)\n\t.configureHelp(helpConfig)\n\t.action((opts, cmd) =>\n\t\trunCommand(\n\t\t\t() =>\n\t\t\t\trunDisable(\n\t\t\t\t\t{\n\t\t\t\t\t\tslug: 'disable-i18n',\n\t\t\t\t\t\tconfirmMessage:\n\t\t\t\t\t\t\t'Disable i18n? Removes i18n scaffolding files and the Wuchale .gitignore block. Manual reverts are still required in vite.config, svelte.config, hooks.server, app.html, and +layout.ts.',\n\t\t\t\t\t\treport: {\n\t\t\t\t\t\t\tsummary: 'Disabled i18n scaffolding.',\n\t\t\t\t\t\t\tnextSteps: [\n\t\t\t\t\t\t\t\t'Manually revert the Wuchale wiring in vite.config, svelte.config, hooks.server, app.html, and +layout.ts.'\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\ttask: {\n\t\t\t\t\t\t\t\ttitle: 'Disabling i18n',\n\t\t\t\t\t\t\t\tsuccess: 'Disabled i18n',\n\t\t\t\t\t\t\t\terror: 'Failed to disable i18n'\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\topts,\n\t\t\t\t\tcmd.args\n\t\t\t\t),\n\t\t\t'Failed to disable i18n.'\n\t\t)\n\t);\n", "import { Command } from 'commander';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand, runDisable } from './_shared.ts';\n\nexport const teams = new Command('teams')\n\t.description('disable teams')\n\t.option('-y, --yes', 'skip confirmation prompt')\n\t.allowUnknownOption(true)\n\t.configureHelp(helpConfig)\n\t.action((opts, cmd) =>\n\t\trunCommand(\n\t\t\t() =>\n\t\t\t\trunDisable(\n\t\t\t\t\t{\n\t\t\t\t\t\tslug: 'disable-teams',\n\t\t\t\t\t\tconfirmMessage:\n\t\t\t\t\t\t\t'Disable teams? Drops teams, team_memberships, team_invites, and team_invite_links collections and removes team routes. app-sidebar and +layout.server.ts must be reverted manually.',\n\t\t\t\t\t\treport: {\n\t\t\t\t\t\t\tsummary: 'Disabled teams.',\n\t\t\t\t\t\t\tnextSteps: [\n\t\t\t\t\t\t\t\t'Manually revert the Teams nav item in app-sidebar and any team context loading in +layout.server.ts.'\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\ttask: {\n\t\t\t\t\t\t\t\ttitle: 'Disabling teams',\n\t\t\t\t\t\t\t\tsuccess: 'Disabled teams',\n\t\t\t\t\t\t\t\terror: 'Failed to disable teams'\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\topts,\n\t\t\t\t\tcmd.args\n\t\t\t\t),\n\t\t\t'Failed to disable teams.'\n\t\t)\n\t);\n", "import { Command } from 'commander';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand, runDisable } from './_shared.ts';\n\nexport const payments = new Command('payments')\n\t.description('disable payments')\n\t.option('-y, --yes', 'skip confirmation prompt')\n\t.allowUnknownOption(true)\n\t.configureHelp(helpConfig)\n\t.action((opts, cmd) =>\n\t\trunCommand(\n\t\t\t() =>\n\t\t\t\trunDisable(\n\t\t\t\t\t{\n\t\t\t\t\t\tslug: 'disable-payments',\n\t\t\t\t\t\tconfirmMessage:\n\t\t\t\t\t\t\t'Disable payments? Drops Stripe collections, strips Stripe env credentials, reverts nav/signup edits, and removes generated payment files. Stripe dashboard products/prices and the stripe packages are untouched.',\n\t\t\t\t\t\treport: {\n\t\t\t\t\t\t\tsummary: 'Disabled payments.',\n\t\t\t\t\t\t\tnextSteps: [\n\t\t\t\t\t\t\t\t'Products and prices in the Stripe dashboard are not deleted \u2014 archive them there if you no longer need them.',\n\t\t\t\t\t\t\t\t'The stripe and @stripe/stripe-js packages remain installed. Uninstall them manually if desired.'\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\ttask: {\n\t\t\t\t\t\t\t\ttitle: 'Disabling payments',\n\t\t\t\t\t\t\t\tsuccess: 'Disabled payments',\n\t\t\t\t\t\t\t\terror: 'Failed to disable payments'\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\topts,\n\t\t\t\t\tcmd.args\n\t\t\t\t),\n\t\t\t'Failed to disable payments.'\n\t\t)\n\t);\n", "import { Command } from 'commander';\nimport * as p from '@clack/prompts';\nimport pc from 'picocolors';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand } from '../../lib/run.ts';\nimport { reportResult } from '../../lib/result-report.ts';\nimport { addTargetOptions } from '../../lib/server-command.ts';\nimport { withBackupTarget } from '../../lib/backup-target.ts';\nimport { disableS3, readS3, type S3Filesystem } from '../../lib/s3-settings.ts';\n\nexport const s3 = addTargetOptions(\n\tnew Command('s3')\n\t\t.description('disable S3 file storage')\n\t\t.option('--backups', 'keep backups on the server again, rather than uploads')\n\t\t.configureHelp(helpConfig),\n\t'local'\n).action((raw: unknown) =>\n\trunCommand(() => {\n\t\tconst options = raw as { backups?: boolean };\n\t\tconst filesystem: S3Filesystem = options.backups ? 'backups' : 'storage';\n\n\t\treturn withBackupTarget(raw, 'disable s3', async (ctx) => {\n\t\t\tconst existing = await readS3(ctx.pb, filesystem);\n\t\t\tif (!existing.enabled) {\n\t\t\t\tp.log.info(`S3 ${label(filesystem)} is already off for ${ctx.targetName}.`);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tawait disableS3(ctx.pb, filesystem);\n\n\t\t\treportResult({\n\t\t\t\tsummary: `Disabled S3 ${label(filesystem)} on ${ctx.targetName}.`,\n\t\t\t\tnextSteps:\n\t\t\t\t\tfilesystem === 'backups'\n\t\t\t\t\t\t? ['New backups are written to the server again.']\n\t\t\t\t\t\t: [\n\t\t\t\t\t\t\t\t`Anything uploaded while S3 was on is still in ${pc.cyan(existing.bucket || 'the bucket')} and will now 404.`,\n\t\t\t\t\t\t\t\t'Copy it back first if you need it: `rclone copy <remote>:<bucket>/ <storage dir>/`.',\n\t\t\t\t\t\t\t\t'The credentials are kept, so `vela enable s3` does not mean retyping them.'\n\t\t\t\t\t\t\t]\n\t\t\t});\n\t\t});\n\t}, 'Failed to disable S3.')\n);\n\nfunction label(filesystem: S3Filesystem): string {\n\treturn filesystem === 'backups' ? 'backup storage' : 'file storage';\n}\n", "import { Command } from 'commander';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand } from '../../lib/run.ts';\nimport { withPocketbase } from '../../lib/pocketbase.ts';\nimport { getWorkspace } from '../../lib/workspace.ts';\nimport { reportResult } from '../../lib/result-report.ts';\n\nexport const smtp = new Command('smtp')\n\t.description('disable SMTP configuration')\n\t.configureHelp(helpConfig)\n\t.action(() =>\n\t\trunCommand(async () => {\n\t\t\tconst { workspaceRootDir } = await getWorkspace();\n\n\t\t\tawait withPocketbase(workspaceRootDir, async (pb) => {\n\t\t\t\tawait pb.settings.update({ smtp: { enabled: false } });\n\t\t\t});\n\n\t\t\treportResult({\n\t\t\t\tsummary: 'Disabled SMTP.',\n\t\t\t\tnextSteps: [\n\t\t\t\t\t'PocketBase will fall back to the built-in sender for transactional email.',\n\t\t\t\t\t'Run `vela enable smtp` to reconfigure.'\n\t\t\t\t]\n\t\t\t});\n\t\t}, 'Failed to disable SMTP.')\n\t);\n", "import { Command } from 'commander';\nimport { helpConfig } from '../lib/help.ts';\nimport { form } from './destroy/form.ts';\nimport { schema } from './destroy/schema.ts';\nimport { resource } from './destroy/resource.ts';\nimport { scaffold } from './destroy/scaffold.ts';\nimport { deployment } from './destroy/deployment.ts';\n\nexport const destroy = new Command('destroy')\n\t.description('destroy scaffolding, or a deployment')\n\t.configureHelp(helpConfig)\n\t.addCommand(form)\n\t.addCommand(schema)\n\t.addCommand(resource)\n\t.addCommand(scaffold)\n\t.addCommand(deployment);\n", "import { Command } from 'commander';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand, runDestroy } from './_shared.ts';\n\nexport const form = new Command('form')\n\t.description('destroy a form generated by `vela generate form`')\n\t.argument('<model>', 'model name used when the form was generated (e.g., contact, login)')\n\t.option('-y, --yes', 'skip confirmation prompt')\n\t.option(\n\t\t'--route <route>',\n\t\t'custom route the form was generated at (must match the --route used at generation)'\n\t)\n\t.allowUnknownOption(true)\n\t.configureHelp(helpConfig)\n\t.action((model: string, opts: { yes?: boolean; route?: string }) =>\n\t\trunCommand(\n\t\t\t() =>\n\t\t\t\trunDestroy(\n\t\t\t\t\t'destroy-form',\n\t\t\t\t\tmodel,\n\t\t\t\t\t`Destroy form \"${model}\"? Removes the route directory and the schema file.`,\n\t\t\t\t\t{\n\t\t\t\t\t\tsummary: `Destroyed form \"${model}\".`,\n\t\t\t\t\t\ttask: {\n\t\t\t\t\t\t\ttitle: `Destroying form \"${model}\"`,\n\t\t\t\t\t\t\tsuccess: `Destroyed form \"${model}\"`,\n\t\t\t\t\t\t\terror: `Failed to destroy form \"${model}\"`\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\topts\n\t\t\t\t),\n\t\t\t'Failed to destroy form.'\n\t\t)\n\t);\n", "import process from 'node:process';\nimport * as p from '@clack/prompts';\nimport type { Slug } from '@velastack/patterns';\nimport { runCommand } from '../../lib/run.ts';\nimport { runPattern, type PatternReport } from '../../lib/pattern-runner.ts';\n\nexport async function runDestroy(\n\tslug: Slug,\n\tmodel: string,\n\tconfirmMessage: string,\n\treport: PatternReport,\n\tflags: { yes?: boolean; route?: string }\n): Promise<void> {\n\tif (!flags.yes) {\n\t\tconst ok = await p.confirm({ message: confirmMessage, initialValue: false });\n\t\tif (p.isCancel(ok) || !ok) {\n\t\t\tp.cancel('Operation cancelled.');\n\t\t\tprocess.exit(0);\n\t\t}\n\t}\n\tawait runPattern(slug, [model], { destructive: true, route: flags.route }, report);\n}\n\nexport { runCommand };\n", "import { Command } from 'commander';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand, runDestroy } from './_shared.ts';\n\nexport const schema = new Command('schema')\n\t.description('destroy a zod schema generated by `vela generate schema`')\n\t.argument('<model>', 'schema model name (e.g., contact, login)')\n\t.option('-y, --yes', 'skip confirmation prompt')\n\t.allowUnknownOption(true)\n\t.configureHelp(helpConfig)\n\t.action((model: string, opts) =>\n\t\trunCommand(\n\t\t\t() =>\n\t\t\t\trunDestroy(\n\t\t\t\t\t'destroy-schema',\n\t\t\t\t\tmodel,\n\t\t\t\t\t`Destroy schema \"${model}\"? Removes the zod schema file.`,\n\t\t\t\t\t{\n\t\t\t\t\t\tsummary: `Destroyed schema \"${model}\".`,\n\t\t\t\t\t\ttask: {\n\t\t\t\t\t\t\ttitle: `Destroying schema \"${model}\"`,\n\t\t\t\t\t\t\tsuccess: `Destroyed schema \"${model}\"`,\n\t\t\t\t\t\t\terror: `Failed to destroy schema \"${model}\"`\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\topts\n\t\t\t\t),\n\t\t\t'Failed to destroy schema.'\n\t\t)\n\t);\n", "import { Command } from 'commander';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand, runDestroy } from './_shared.ts';\n\nexport const resource = new Command('resource')\n\t.description('destroy a resource generated by `vela generate resource`')\n\t.argument('<model>', 'model path used when the resource was generated (e.g., contacts, articles)')\n\t.option('-y, --yes', 'skip confirmation prompt')\n\t.allowUnknownOption(true)\n\t.configureHelp(helpConfig)\n\t.action((model: string, opts) =>\n\t\trunCommand(\n\t\t\t() =>\n\t\t\t\trunDestroy(\n\t\t\t\t\t'destroy-resource',\n\t\t\t\t\tmodel,\n\t\t\t\t\t`Destroy resource \"${model}\"? Drops the collection and removes the schema file.`,\n\t\t\t\t\t{\n\t\t\t\t\t\tsummary: `Destroyed resource \"${model}\".`,\n\t\t\t\t\t\ttask: {\n\t\t\t\t\t\t\ttitle: `Destroying resource \"${model}\"`,\n\t\t\t\t\t\t\tsuccess: `Destroyed resource \"${model}\"`,\n\t\t\t\t\t\t\terror: `Failed to destroy resource \"${model}\"`\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\topts\n\t\t\t\t),\n\t\t\t'Failed to destroy resource.'\n\t\t)\n\t);\n", "import { Command } from 'commander';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand, runDestroy } from './_shared.ts';\n\nexport const scaffold = new Command('scaffold')\n\t.description('destroy a scaffold generated by `vela generate scaffold`')\n\t.argument('<model>', 'model name used when the scaffold was generated (e.g., contact, todo)')\n\t.option('-y, --yes', 'skip confirmation prompt')\n\t.option(\n\t\t'--route <route>',\n\t\t'custom route the scaffold was generated at (must match the --route used at generation)'\n\t)\n\t.allowUnknownOption(true)\n\t.configureHelp(helpConfig)\n\t.action((model: string, opts: { yes?: boolean; route?: string }) =>\n\t\trunCommand(\n\t\t\t() =>\n\t\t\t\trunDestroy(\n\t\t\t\t\t'destroy-scaffold',\n\t\t\t\t\tmodel,\n\t\t\t\t\t`Destroy scaffold \"${model}\"? Removes the route directory, schema file, and drops the collection. Shadcn components are retained.`,\n\t\t\t\t\t{\n\t\t\t\t\t\tsummary: `Destroyed scaffold \"${model}\".`,\n\t\t\t\t\t\tnextSteps: [\n\t\t\t\t\t\t\t'Shadcn components added during scaffolding are preserved \u2014 remove them manually if nothing else uses them.'\n\t\t\t\t\t\t],\n\t\t\t\t\t\ttask: {\n\t\t\t\t\t\t\ttitle: `Destroying scaffold \"${model}\"`,\n\t\t\t\t\t\t\tsuccess: `Destroyed scaffold \"${model}\"`,\n\t\t\t\t\t\t\terror: `Failed to destroy scaffold \"${model}\"`\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\topts\n\t\t\t\t),\n\t\t\t'Failed to destroy scaffold.'\n\t\t)\n\t);\n", "import process from 'node:process';\nimport { Command } from 'commander';\nimport * as p from '@clack/prompts';\nimport pc from 'picocolors';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand } from '../../lib/run.ts';\nimport { addTargetOptions, withTarget } from '../../lib/server-command.ts';\nimport { runServerScript } from '../../lib/remote.ts';\nimport { isProd } from '../../lib/instance.ts';\n\nexport const deployment = addTargetOptions(\n\tnew Command('deployment')\n\t\t.description('remove a deployed environment from its server')\n\t\t.configureHelp(helpConfig),\n\t'production'\n)\n\t.option('--purge', 'also delete the database and uploaded files')\n\t.option('-y, --yes', 'skip the confirmation prompt')\n\t.action((raw: unknown) =>\n\t\trunCommand(async () => {\n\t\t\tconst options = raw as { purge?: boolean; yes?: boolean };\n\t\t\tawait withTarget(\n\t\t\t\traw,\n\t\t\t\t{\n\t\t\t\t\tremote: async (ctx) => {\n\t\t\t\t\t\t// Production is the one you cannot get back by redeploying, so it\n\t\t\t\t\t\t// always asks, and `--purge` on it asks for the name in full.\n\t\t\t\t\t\tif (!options.yes) {\n\t\t\t\t\t\t\tawait confirm(ctx.appName, ctx.targetName, ctx.envTag, options.purge === true);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst result = await runServerScript<{ purged: boolean }>(ctx.session, 'destroy.sh', {\n\t\t\t\t\t\t\targs: [ctx.instance, ...(options.purge ? ['--purge'] : [])],\n\t\t\t\t\t\t\tstream: true\n\t\t\t\t\t\t});\n\n\t\t\t\t\t\tp.log.success(\n\t\t\t\t\t\t\t`Removed ${pc.cyan(`${ctx.appName} (${ctx.targetName})`)} from ${ctx.server}.` +\n\t\t\t\t\t\t\t\t(result?.purged\n\t\t\t\t\t\t\t\t\t? ''\n\t\t\t\t\t\t\t\t\t: `\\n\\nThe database and uploads are still in the instance's shared directory. Pass ${pc.cyan('--purge')} to delete them.`)\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tlabel: 'destroy deployment',\n\t\t\t\t\tlocalHint: 'There is nothing deployed locally to remove.'\n\t\t\t\t}\n\t\t\t);\n\t\t}, 'Failed to remove the deployment.')\n\t);\n\nasync function confirm(\n\tappName: string,\n\ttargetName: string,\n\tenvTag: string,\n\tpurge: boolean\n): Promise<void> {\n\tif (isProd(envTag) || purge) {\n\t\tconst answer = await p.text({\n\t\t\tmessage: `This removes ${pc.cyan(`${appName} (${targetName})`)}${purge ? ' and its database' : ''}. Type the app name to confirm`,\n\t\t\tvalidate: (value) => (value === appName ? undefined : `Type ${appName} to confirm`)\n\t\t});\n\t\tif (p.isCancel(answer)) {\n\t\t\tp.cancel('Operation cancelled.');\n\t\t\tprocess.exit(0);\n\t\t}\n\t\treturn;\n\t}\n\n\tconst ok = await p.confirm({\n\t\tmessage: `Remove ${appName} (${targetName})?`,\n\t\tinitialValue: false\n\t});\n\tif (p.isCancel(ok) || !ok) {\n\t\tp.cancel('Operation cancelled.');\n\t\tprocess.exit(0);\n\t}\n}\n", "import { Command } from 'commander';\nimport { helpConfig } from '../lib/help.ts';\nimport { add } from './ui/add.ts';\nimport { base } from './ui/base.ts';\n\nexport const ui = new Command('ui')\n\t.description('generate ui components')\n\t.configureHelp(helpConfig)\n\t.addCommand(add)\n\t.addCommand(base);\n", "import { Command } from 'commander';\nimport { exec, NonZeroExitError } from 'tinyexec';\nimport { detect, resolveCommand } from 'package-manager-detector';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand } from '../../lib/run.ts';\nimport { getWorkspace } from '../../lib/workspace.ts';\nimport { reportResult } from '../../lib/result-report.ts';\n\nexport const add = new Command('add')\n\t.description('add ui components')\n\t.argument('<components...>', 'the components to add')\n\t.configureHelp(helpConfig)\n\t.action((components: string[]) =>\n\t\trunCommand(async () => {\n\t\t\tconst { workspaceRootDir } = await getWorkspace();\n\t\t\tconst packageManager = (await detect({ cwd: workspaceRootDir }))?.name ?? 'npm';\n\t\t\tconst resolved = resolveCommand(packageManager, 'execute', [\n\t\t\t\t'shadcn-svelte',\n\t\t\t\t'add',\n\t\t\t\t...components\n\t\t\t]);\n\t\t\tif (!resolved) {\n\t\t\t\tthrow new Error(`Unable to resolve execute command for ${packageManager}`);\n\t\t\t}\n\n\t\t\tconst args = [...resolved.args];\n\t\t\tif (packageManager === 'npm') args.unshift('--yes');\n\n\t\t\ttry {\n\t\t\t\tawait exec(resolved.command, args, {\n\t\t\t\t\tnodeOptions: { cwd: workspaceRootDir, stdio: 'inherit' },\n\t\t\t\t\tthrowOnError: true\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\tconst typed = error as NonZeroExitError;\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Failed to execute '${resolved.command} ${args.join(' ')}': ${typed.message}`,\n\t\t\t\t\t{ cause: typed.output }\n\t\t\t\t);\n\t\t\t}\n\n\t\t\treportResult({\n\t\t\t\tsummary: `Added ${components.length} UI component(s).`,\n\t\t\t\tcomponentsAdded: components,\n\t\t\t\tnextSteps: [\n\t\t\t\t\t`Import a component with: import { Button } from '$lib/components/ui/button';`,\n\t\t\t\t\t'Tweak styling in src/lib/components/ui/<component>/*.svelte.',\n\t\t\t\t\t'Run `vela ui base <color>` to change the palette (slate, gray, zinc, stone, neutral).'\n\t\t\t\t]\n\t\t\t});\n\t\t}, 'Failed to add UI components.')\n\t);\n", "import fs from 'node:fs';\nimport path from 'node:path';\nimport { Command, InvalidArgumentError } from 'commander';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand } from '../../lib/run.ts';\nimport { getWorkspace } from '../../lib/workspace.ts';\nimport { reportResult } from '../../lib/result-report.ts';\nimport { templatesDir } from '../../lib/templates.ts';\n\nconst VALID_COLORS = ['slate', 'gray', 'zinc', 'stone', 'neutral'] as const;\ntype BaseColor = (typeof VALID_COLORS)[number];\n\nfunction findThemeFile(color: BaseColor): string {\n\tconst candidate = path.join(templatesDir(), 'ui', 'css', `${color}.css`);\n\tif (!fs.existsSync(candidate)) {\n\t\tthrow new Error(`Theme file not found for color: ${color}`);\n\t}\n\treturn candidate;\n}\n\nfunction extractSelectors(css: string): { root: string; dark: string } {\n\tconst rootMatch = css.match(/:root\\s*{[^}]*}/);\n\tconst darkMatch = css.match(/\\.dark\\s*{[^}]*}/);\n\tif (!rootMatch || !darkMatch) {\n\t\tthrow new Error('Invalid theme file: missing :root or .dark selector');\n\t}\n\treturn { root: rootMatch[0], dark: darkMatch[0] };\n}\n\nfunction applyTheme(appCss: string, selectors: { root: string; dark: string }): string {\n\tlet out = appCss;\n\tout = out.match(/:root\\s*{[^}]*}/)\n\t\t? out.replace(/:root\\s*{[^}]*}/, selectors.root)\n\t\t: `${selectors.root}\\n\\n${out}`;\n\tout = out.match(/\\.dark\\s*{[^}]*}/)\n\t\t? out.replace(/\\.dark\\s*{[^}]*}/, selectors.dark)\n\t\t: `${out}\\n\\n${selectors.dark}`;\n\treturn out;\n}\n\nexport const base = new Command('base')\n\t.description('change the base color')\n\t.argument('<color>', 'base color to use', (value) => {\n\t\tif (!(VALID_COLORS as readonly string[]).includes(value)) {\n\t\t\tthrow new InvalidArgumentError(`Valid colors are: ${VALID_COLORS.join(', ')}`);\n\t\t}\n\t\treturn value as BaseColor;\n\t})\n\t.configureHelp(helpConfig)\n\t.action((color: BaseColor) =>\n\t\trunCommand(async () => {\n\t\t\tconst { workspaceRootDir } = await getWorkspace();\n\t\t\tconst appCssPath = path.join(workspaceRootDir, 'src', 'app.css');\n\t\t\tif (!fs.existsSync(appCssPath)) {\n\t\t\t\tthrow new Error(`Could not find ${path.relative(workspaceRootDir, appCssPath)}`);\n\t\t\t}\n\n\t\t\tconst themeContent = fs.readFileSync(findThemeFile(color), 'utf8');\n\t\t\tconst selectors = extractSelectors(themeContent);\n\t\t\tconst appCss = fs.readFileSync(appCssPath, 'utf8');\n\t\t\tfs.writeFileSync(appCssPath, applyTheme(appCss, selectors));\n\n\t\t\treportResult({\n\t\t\t\tsummary: `Set base color to ${color}.`,\n\t\t\t\tfilesModified: [path.relative(workspaceRootDir, appCssPath)],\n\t\t\t\tnextSteps: [\n\t\t\t\t\t'Run your dev server to preview the new palette.',\n\t\t\t\t\t'Tweak individual CSS variables in src/app.css if you want to customize the theme further.'\n\t\t\t\t]\n\t\t\t});\n\t\t}, 'Failed to change base color.')\n\t);\n", "import { Command } from 'commander';\nimport { helpConfig } from '../lib/help.ts';\nimport { terms } from './legal/terms.ts';\nimport { privacy } from './legal/privacy.ts';\n\nexport const legal = new Command('legal')\n\t.description('generate placeholder legal documents')\n\t.configureHelp(helpConfig)\n\t.addCommand(terms)\n\t.addCommand(privacy);\n", "import fs from 'node:fs';\nimport path from 'node:path';\nimport { Command } from 'commander';\nimport * as p from '@clack/prompts';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand } from '../../lib/run.ts';\nimport { getWorkspace } from '../../lib/workspace.ts';\nimport { LEGAL_DIR } from '../../lib/constants.ts';\nimport { reportResult } from '../../lib/result-report.ts';\nimport {\n\tarbitrationBlock,\n\tcontactMethods,\n\tdmcaBlock,\n\tescapeHtml,\n\tlist,\n\tonCancel,\n\tpageMetaTagsLoader,\n\tsharedFields,\n\ttitledSection,\n\ttype LegalCoreAnswers\n} from './shared.ts';\n\ntype TermsAnswers = {\n\tcore: LegalCoreAnswers;\n\taccounts: 'yes' | 'no';\n\tuserContent: 'yes' | 'no';\n\tinfringementEmail?: string;\n\tcanBuyGoods: 'yes' | 'no';\n\tsubscriptions: 'yes' | 'no';\n\tfreeTrial?: 'yes' | 'no';\n\texclusiveContent: 'yes' | 'no';\n\tfeedbackReuse: 'yes' | 'no';\n\tpromotions: 'yes' | 'no';\n\tmobileApp: Array<'apple' | 'google'>;\n\tcontact: { methods: string[]; details: Record<string, unknown> };\n};\n\ntype Computed = {\n\tcompanyName: string;\n\tcompanyLong: string;\n\twebsiteName: string;\n\twebsiteUrl: string;\n\tgoverningLocation: string;\n\teffectiveDate: string;\n};\n\nconst compute = (a: TermsAnswers): Computed => {\n\tconst effectiveDate = new Date(Date.now()).toLocaleDateString('en-US', {\n\t\tyear: 'numeric',\n\t\tmonth: 'long',\n\t\tday: 'numeric'\n\t});\n\tconst websiteName = a.core?.websiteName ?? 'our website';\n\tconst websiteUrl = a.core?.websiteUrl ?? '';\n\tconst companyName =\n\t\ta.core?.entityType === 'business'\n\t\t\t? (a.core?.businessName ?? websiteName)\n\t\t\t: (a.core?.websiteName ?? 'the website owner');\n\tconst companyLong =\n\t\ta.core?.entityType === 'business'\n\t\t\t? `${escapeHtml(a.core?.businessName ?? websiteName)}${\n\t\t\t\t\ta.core?.businessAddress ? `, ${escapeHtml(a.core?.businessAddress)}` : ''\n\t\t\t\t}`\n\t\t\t: 'the website owner';\n\tconst governingLocation = `${escapeHtml(a.core?.state ?? '')}${a.core?.state ? ', ' : ''}${escapeHtml(\n\t\ta.core?.country ?? ''\n\t)}`;\n\n\treturn {\n\t\tcompanyName,\n\t\tcompanyLong,\n\t\twebsiteName,\n\t\twebsiteUrl,\n\t\tgoverningLocation,\n\t\teffectiveDate\n\t};\n};\n\nconst sectionHeader = (c: Computed) =>\n\t`<section class=\"space-y-3\"><h1 class=\"text-3xl font-semibold\">Terms &amp; Conditions</h1><p class=\"text-base leading-7\">Last updated: ${escapeHtml(\n\t\tc.effectiveDate\n\t)}</p><p class=\"text-base leading-7\">These Terms &amp; Conditions (\"Terms\") govern your access to and use of ${escapeHtml(\n\t\tc.websiteName\n\t)} (${escapeHtml(c.websiteUrl)}) and any related software, mobile applications, content, products, and services (collectively, the \"Service\"). The Service is provided by ${\n\t\tc.companyLong\n\t} (\"Company\", \"we\", \"us\", or \"our\").</p><p class=\"text-base leading-7\">By accessing or using the Service, you agree to be bound by these Terms and our Privacy Policy. If you do not agree to these Terms, you must not access or use the Service. Your continued use of the Service after we post or send a notice about changes to these Terms means you accept and agree to the changes.</p></section>`;\n\nconst sectionEligibility = () =>\n\ttitledSection(\n\t\t'Eligibility and Age',\n\t\t'<p>You must be at least 13 years of age to use the Service (or 16 years of age if you are a resident of the European Economic Area, the United Kingdom, or another jurisdiction whose laws require a higher minimum age). By using the Service, you represent and warrant that you meet the minimum age requirement, that you have the legal capacity to enter into a binding agreement, and that you are not prohibited from receiving the Service under the laws of any applicable jurisdiction.</p><p>If you are using the Service on behalf of a company, organization, or other legal entity, you represent that you are authorized to bind that entity to these Terms, in which case \"you\" and \"your\" refer to that entity.</p>'\n\t);\n\nconst sectionDefinitions = (c: Computed) =>\n\ttitledSection(\n\t\t'Definitions',\n\t\t`<p>The following definitions apply throughout these Terms:</p><ul><li><strong>Service</strong> means ${escapeHtml(\n\t\t\tc.websiteName\n\t\t)}, our website at <a href=\"${escapeHtml(\n\t\t\tc.websiteUrl\n\t\t)}\" rel=\"external nofollow noopener\" target=\"_blank\">${escapeHtml(\n\t\t\tc.websiteUrl\n\t\t)}</a>, and any related applications, software, content, and online services we provide.</li><li><strong>Content</strong> means any information, text, graphics, images, music, audio, video, code, or other material that is made available through the Service, whether by us, our licensors, our users, or third parties.</li><li><strong>User Content</strong> means any Content that you or other users submit, upload, post, transmit, or otherwise make available through the Service.</li><li><strong>You</strong> and <strong>your</strong> refer to the individual or entity that accesses or uses the Service.</li></ul>`\n\t);\n\nconst sectionLicense = () =>\n\ttitledSection(\n\t\t'License to Use the Service',\n\t\t'<p>Subject to your compliance with these Terms, we grant you a limited, revocable, non-exclusive, non-transferable, non-sublicensable license to access and use the Service for your personal or internal business use. This license does not include any right to: (a) sell, resell, or commercially exploit the Service or its Content; (b) modify, adapt, translate, reverse engineer, decompile, or disassemble any portion of the Service; (c) use the Service or its Content in any manner that infringes our or any third party\u2019s rights; or (d) use any data mining, robots, or similar data gathering or extraction methods. We reserve all rights not expressly granted to you.</p>'\n\t);\n\nconst sectionAccounts = () =>\n\ttitledSection(\n\t\t'Accounts',\n\t\t'<p>To access certain features of the Service, you may be required to create an account. You agree to provide accurate, complete, and current information at all times and to update your information to keep it accurate, complete, and current. You are responsible for safeguarding your password and for any activities or actions taken under your account, whether or not you have authorized those activities. You agree not to disclose your password to any third party and to notify us immediately upon becoming aware of any breach of security or unauthorized use of your account. We may, in our sole discretion, refuse to grant you an account or suspend or terminate your account at any time.</p>'\n\t);\n\nconst sectionUserContent = () =>\n\ttitledSection(\n\t\t'User Content',\n\t\t`<p><strong>Your content remains your content.</strong> You retain all rights you have in the User Content you submit, upload, post, transmit, or otherwise make available through the Service. You are solely responsible for your User Content and the consequences of making it available through the Service.</p><p><strong>License to us.</strong> By submitting User Content through the Service, you grant us a worldwide, non-exclusive, royalty-free, fully paid-up, perpetual, irrevocable, sublicensable, and transferable license to use, host, store, cache, reproduce, publish, publicly display, publicly perform, distribute, modify, adapt, translate, and create derivative works of your User Content, solely in connection with operating, providing, promoting, and improving the Service, and to enable our service providers to do the same on our behalf. The license you grant survives termination of these Terms with respect to User Content that has been shared, distributed, or otherwise relied upon by us or third parties before termination.</p><p><strong>Your representations and warranties.</strong> You represent and warrant that: (a) you own or have all necessary rights, licenses, consents, releases, and permissions in your User Content; (b) your User Content does not and will not infringe, misappropriate, or violate any third party\u2019s intellectual property, privacy, publicity, contractual, or other rights, or any applicable law; and (c) your User Content is not unlawful, defamatory, obscene, threatening, harassing, abusive, or otherwise objectionable.</p><p><strong>Right to remove.</strong> We reserve the right, but are not obligated, to review, screen, or remove any User Content at any time, with or without notice, for any reason, including any User Content that we determine, in our sole discretion, violates these Terms or is otherwise objectionable. We are not responsible for any User Content posted by users.</p>`\n\t);\n\nconst sectionDmca = (c: Computed, infringementEmail: string) =>\n\ttitledSection('DMCA Notice and Counter-Notice', dmcaBlock(c.companyName, infringementEmail));\n\nconst sectionExclusiveIp = (c: Computed) =>\n\ttitledSection(\n\t\t'Intellectual Property of the Company',\n\t\t`<p>The Service and its original content (excluding User Content), features, functionality, software, source code, designs, text, graphics, images, logos, trademarks, service marks, trade dress, and trade names are and will remain the exclusive property of ${escapeHtml(\n\t\t\tc.companyName\n\t\t)} and its licensors, and are protected by copyright, trademark, and other intellectual property laws. Nothing in these Terms grants you any right or license to use any of our trademarks, service marks, logos, trade names, or trade dress without our prior written permission. All goodwill arising from the use of our trademarks inures to our exclusive benefit.</p>`\n\t);\n\nconst sectionFeedback = () =>\n\ttitledSection(\n\t\t'Feedback',\n\t\t'<p>If you provide us with any suggestions, ideas, comments, improvements, recommendations, or other feedback regarding the Service (\"Feedback\"), you grant us a worldwide, perpetual, irrevocable, royalty-free, fully paid-up, sublicensable, and transferable license to use, copy, modify, distribute, and otherwise commercially exploit the Feedback for any purpose, without restriction or compensation to you. You waive any moral rights or similar rights in the Feedback to the maximum extent permitted by applicable law.</p>'\n\t);\n\nconst sectionPurchases = () =>\n\ttitledSection(\n\t\t'Purchases and Payments',\n\t\t'<p>We may offer goods, items, or services for purchase through the Service. By placing an order, you represent and warrant that you are legally capable of entering into a binding contract and that the information you provide is accurate, current, and complete.</p><p><strong>Pricing and availability.</strong> Prices, features, and availability are subject to change without notice. We reserve the right to refuse or cancel any order at any time for any reason, including suspected fraud, errors in product or pricing information, or unavailability.</p><p><strong>Taxes.</strong> Unless otherwise stated, prices are exclusive of any applicable taxes, duties, or similar governmental assessments. You are responsible for any such taxes associated with your purchase.</p><p><strong>Payment authorization.</strong> By submitting payment information, you authorize us (or our payment processor) to charge the applicable amount to your selected payment method. You agree to keep your payment information current and accurate.</p><p><strong>Refunds.</strong> Refunds, if available, are described at the point of purchase or in our refund policy. Except where required by law, all sales are final.</p>'\n\t);\n\nconst sectionSubscriptions = (a: TermsAnswers) => {\n\tconst bullets: string[] = [];\n\tif (a.freeTrial === 'yes') {\n\t\tbullets.push(\n\t\t\t'<strong>Free trial.</strong> We may offer a free trial for certain subscription plans. If you do not cancel before the end of the free trial, you will be automatically charged for the applicable plan at the then-current rate. We will provide notice before charging your payment method where required by law.'\n\t\t);\n\t}\n\tbullets.push(\n\t\t'<strong>Recurring billing.</strong> Subscriptions are billed in advance on a recurring and periodic basis (such as weekly, monthly, or annually), depending on the plan you select. Each billing period begins on the date your subscription is established or renewed.',\n\t\t'<strong>Automatic renewal.</strong> Your subscription will automatically renew at the end of each billing period at the then-current rate, unless you cancel before the end of the current billing period. By starting a subscription, you authorize us to automatically charge your payment method for each renewal until you cancel. This authorization will continue until you cancel.',\n\t\t'<strong>Cancellation.</strong> You may cancel your subscription at any time by following the cancellation instructions in your account settings or by contacting us using the methods listed in the \"Contact Us\" section. Cancellation will take effect at the end of the current billing period; you will continue to have access to the subscription through the end of that period and will not receive a refund for the current period unless required by law.',\n\t\t'<strong>Price changes.</strong> We may change subscription fees and the features included in any subscription plan at any time. Where required by law, we will provide reasonable advance notice of any fee changes. If you do not agree to the changes, you may cancel your subscription before the change takes effect.',\n\t\t'<strong>Failed payments.</strong> If we are unable to charge your payment method for any reason, we may suspend or terminate your access to the subscription until payment is successfully processed.'\n\t);\n\tconst autoRenewalNotice = `<p><strong>Auto-renewal disclosure (California, New York, and other states).</strong> In accordance with the California Automatic Renewal Law (Cal. Bus. &amp; Prof. Code &sect; 17600 et seq.), New York General Business Law &sect; 527-a, and similar laws, you acknowledge that your subscription will continue until cancelled, that we will charge the payment method you provided on a recurring basis at the frequency described at the time of purchase, that your subscription will automatically renew unless you cancel, and that you may cancel at any time using the cancellation methods described above.</p>`;\n\treturn titledSection(\n\t\t'Subscriptions and Automatic Renewal',\n\t\t`<p>Some parts of the Service may be billed on a subscription basis.</p>${list(bullets)}${autoRenewalNotice}`\n\t);\n};\n\nconst sectionPromotions = () =>\n\ttitledSection(\n\t\t'Promotions',\n\t\t'<p>Any promotions, contests, sweepstakes, or similar offerings (\"Promotions\") made available through the Service may be governed by rules separate from these Terms. If you participate in any Promotion, please review the applicable rules as well as our Privacy Policy. If the rules for a Promotion conflict with these Terms, the Promotion rules will apply.</p>'\n\t);\n\nconst sectionProhibited = () =>\n\ttitledSection(\n\t\t'Prohibited Uses',\n\t\t`<p>You agree not to use the Service:</p>${list([\n\t\t\t'In any way that violates any applicable national, state, local, or international law or regulation (including, without limitation, any laws regarding the export of data or software to and from the United States or other countries).',\n\t\t\t'For the purpose of exploiting, harming, or attempting to exploit or harm minors in any way by exposing them to inappropriate content, asking for personally identifiable information, or otherwise.',\n\t\t\t'To transmit, or procure the sending of, any advertising or promotional material, including any \"junk mail,\" \"chain letter,\" \"spam,\" or any other similar solicitation, without our prior written consent.',\n\t\t\t'To impersonate or attempt to impersonate the Company, a Company employee, another user, or any other person or entity.',\n\t\t\t'To engage in any other conduct that restricts or inhibits anyone\u2019s use or enjoyment of the Service, or which, as determined by us, may harm the Company or users of the Service or expose them to liability.',\n\t\t\t'To use the Service in any manner that could disable, overburden, damage, or impair the Service or interfere with any other party\u2019s use of the Service.',\n\t\t\t'To use any robot, spider, or other automatic device, process, or means to access the Service for any purpose, including monitoring or copying any of the material on the Service.',\n\t\t\t'To introduce any viruses, Trojan horses, worms, logic bombs, or other material that is malicious or technologically harmful.',\n\t\t\t'To attempt to gain unauthorized access to, interfere with, damage, or disrupt any parts of the Service, the server on which the Service is stored, or any server, computer, or database connected to the Service.',\n\t\t\t'To attack the Service via a denial-of-service attack or a distributed denial-of-service attack.',\n\t\t\t'To otherwise attempt to interfere with the proper working of the Service.'\n\t\t])}`\n\t);\n\nconst sectionTermination = () =>\n\ttitledSection(\n\t\t'Termination',\n\t\t'<p>We may terminate or suspend your account and access to the Service immediately, without prior notice or liability, for any reason, including without limitation if you breach these Terms. Upon termination, your right to use the Service will cease immediately. If you wish to terminate your account, you may simply discontinue using the Service or follow the account-deletion process in your account settings.</p><p>All provisions of these Terms which by their nature should survive termination shall survive, including, without limitation, ownership provisions, warranty disclaimers, indemnity, limitations of liability, and dispute-resolution provisions.</p>'\n\t);\n\nconst sectionDisclaimer = (c: Computed) =>\n\ttitledSection(\n\t\t'Disclaimer of Warranties',\n\t\t`<p>YOUR USE OF THE SERVICE IS AT YOUR SOLE RISK. THE SERVICE IS PROVIDED ON AN \"AS IS\" AND \"AS AVAILABLE\" BASIS, WITH ALL FAULTS. TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, ${escapeHtml(\n\t\t\tc.companyName\n\t\t).toUpperCase()} EXPRESSLY DISCLAIMS ALL WARRANTIES OF ANY KIND, WHETHER EXPRESS, IMPLIED, STATUTORY, OR OTHERWISE, INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE, NON-INFRINGEMENT, AND ANY WARRANTIES ARISING OUT OF COURSE OF DEALING OR USAGE OF TRADE.</p><p>WITHOUT LIMITING THE FOREGOING, ${escapeHtml(\n\t\t\tc.companyName\n\t\t).toUpperCase()} MAKES NO WARRANTY THAT (A) THE SERVICE WILL MEET YOUR REQUIREMENTS, (B) THE SERVICE WILL BE UNINTERRUPTED, TIMELY, SECURE, OR ERROR-FREE, (C) THE RESULTS OBTAINED FROM THE USE OF THE SERVICE WILL BE ACCURATE OR RELIABLE, OR (D) THE QUALITY OF ANY PRODUCTS, SERVICES, INFORMATION, OR OTHER MATERIAL OBTAINED THROUGH THE SERVICE WILL MEET YOUR EXPECTATIONS.</p><p>SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION OF CERTAIN WARRANTIES, SO SOME OF THE ABOVE EXCLUSIONS MAY NOT APPLY TO YOU. IN SUCH JURISDICTIONS, OUR LIABILITY IS LIMITED TO THE GREATEST EXTENT PERMITTED BY LAW.</p>`\n\t);\n\nconst sectionLimitation = (c: Computed) =>\n\ttitledSection(\n\t\t'Limitation of Liability',\n\t\t`<p>TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, IN NO EVENT SHALL ${escapeHtml(\n\t\t\tc.companyName\n\t\t).toUpperCase()}, ITS DIRECTORS, EMPLOYEES, AGENTS, AFFILIATES, PARTNERS, SUPPLIERS, OR LICENSORS BE LIABLE FOR ANY INDIRECT, INCIDENTAL, SPECIAL, CONSEQUENTIAL, EXEMPLARY, OR PUNITIVE DAMAGES, INCLUDING WITHOUT LIMITATION LOSS OF PROFITS, REVENUE, DATA, USE, GOODWILL, OR OTHER INTANGIBLE LOSSES, ARISING OUT OF OR RELATING TO YOUR ACCESS TO OR USE OF, OR INABILITY TO ACCESS OR USE, THE SERVICE; ANY CONDUCT OR CONTENT OF ANY THIRD PARTY ON THE SERVICE; ANY CONTENT OBTAINED FROM THE SERVICE; OR UNAUTHORIZED ACCESS, USE, OR ALTERATION OF YOUR TRANSMISSIONS OR CONTENT, WHETHER BASED ON WARRANTY, CONTRACT, TORT (INCLUDING NEGLIGENCE), OR ANY OTHER LEGAL THEORY, AND WHETHER OR NOT WE HAVE BEEN INFORMED OF THE POSSIBILITY OF SUCH DAMAGE.</p><p>TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, OUR TOTAL CUMULATIVE LIABILITY TO YOU FOR ALL CLAIMS ARISING OUT OF OR RELATING TO THESE TERMS OR THE SERVICE WILL NOT EXCEED THE GREATER OF (A) ONE HUNDRED U.S. DOLLARS ($100) OR (B) THE AMOUNTS YOU PAID US IN THE TWELVE (12) MONTHS PRECEDING THE EVENT GIVING RISE TO THE CLAIM.</p><p>THE LIMITATIONS IN THIS SECTION DO NOT APPLY TO LIABILITY THAT CANNOT BE EXCLUDED OR LIMITED UNDER APPLICABLE LAW, INCLUDING LIABILITY FOR GROSS NEGLIGENCE, WILLFUL MISCONDUCT, OR FRAUD. SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION OR LIMITATION OF CERTAIN DAMAGES, SO THE ABOVE LIMITATIONS MAY NOT APPLY TO YOU.</p>`\n\t);\n\nconst sectionIndemnification = (c: Computed) =>\n\ttitledSection(\n\t\t'Indemnification',\n\t\t`<p>You agree to defend, indemnify, and hold harmless ${escapeHtml(\n\t\t\tc.companyName\n\t\t)}, its affiliates, licensors, and service providers, and its and their respective officers, directors, employees, contractors, agents, licensors, suppliers, successors, and assigns, from and against any claims, liabilities, damages, judgments, awards, losses, costs, expenses, or fees (including reasonable attorneys\u2019 fees) arising out of or relating to (a) your violation of these Terms, (b) your use or misuse of the Service, (c) your User Content, including any claim that your User Content infringes or violates the rights of a third party, or (d) your violation of any applicable law or the rights of any third party.</p>`\n\t);\n\nconst sectionForceMajeure = () =>\n\ttitledSection(\n\t\t'Force Majeure',\n\t\t'<p>We will not be liable for any failure or delay in performance under these Terms to the extent caused by circumstances beyond our reasonable control, including without limitation acts of God, natural disasters, war, terrorism, riots, civil unrest, governmental actions, labor disputes, epidemics or pandemics, fires, floods, power or telecommunications failures, internet or third-party service failures, or any other event of force majeure.</p>'\n\t);\n\nconst sectionGoverningLaw = (c: Computed) =>\n\ttitledSection(\n\t\t'Governing Law',\n\t\t`<p>These Terms shall be governed by and construed in accordance with the laws of ${\n\t\t\tc.governingLocation\n\t\t}, without regard to its conflict-of-laws provisions. The United Nations Convention on Contracts for the International Sale of Goods does not apply to these Terms. Subject to the \"Dispute Resolution\" section below, you agree to submit to the personal and exclusive jurisdiction of the courts located in ${\n\t\t\tc.governingLocation\n\t\t} for the resolution of any disputes not subject to arbitration.</p>`\n\t);\n\nconst sectionArbitration = (c: Computed) =>\n\ttitledSection(\n\t\t'Dispute Resolution; Binding Arbitration; Class-Action Waiver',\n\t\tarbitrationBlock(c.companyName, c.governingLocation)\n\t);\n\nconst sectionExport = (c: Computed) =>\n\ttitledSection(\n\t\t'Export Controls and Sanctions',\n\t\t`<p>The Service may be subject to U.S. and other export-control and economic-sanctions laws and regulations. You may not access, use, export, re-export, or transfer the Service in violation of those laws. You represent and warrant that you are not located in, under the control of, or a national or resident of any country or person subject to U.S. or other applicable economic sanctions or embargoes, and that you are not on any U.S. government list of restricted or prohibited parties. You agree to comply with all applicable export, re-export, and sanctions laws in your use of the Service. ${escapeHtml(\n\t\t\tc.companyName\n\t\t)} reserves the right to restrict access to the Service from any jurisdiction at any time.</p>`\n\t);\n\nconst sectionAppleRider = (c: Computed) =>\n\ttitledSection(\n\t\t'Additional Terms for Apple App Store',\n\t\t`<p>If you accessed or downloaded the Service from the Apple App Store, the following additional terms apply. You acknowledge that these Terms are concluded between you and ${escapeHtml(\n\t\t\tc.companyName\n\t\t)}, and not with Apple Inc. (\"Apple\"), and that ${escapeHtml(\n\t\t\tc.companyName\n\t\t)}, not Apple, is solely responsible for the Service and its content.</p><ul><li><strong>Scope of license.</strong> The license granted to you for the Service is limited to a non-transferable license to use the Service on any Apple-branded products that you own or control, as permitted by the Usage Rules in the Apple Media Services Terms and Conditions.</li><li><strong>Maintenance and support.</strong> ${escapeHtml(\n\t\t\tc.companyName\n\t\t)} is solely responsible for providing any maintenance and support services, as specified in these Terms or as required under applicable law. Apple has no obligation whatsoever to furnish any maintenance and support services with respect to the Service.</li><li><strong>Warranty.</strong> ${escapeHtml(\n\t\t\tc.companyName\n\t\t)} is solely responsible for any product warranties, whether express or implied by law, to the extent not effectively disclaimed. In the event of any failure of the Service to conform to any applicable warranty, you may notify Apple, and Apple will refund the purchase price for the Service to you (if any). To the maximum extent permitted by applicable law, Apple will have no other warranty obligation whatsoever with respect to the Service.</li><li><strong>Product claims.</strong> ${escapeHtml(\n\t\t\tc.companyName\n\t\t)}, not Apple, is responsible for addressing any claims by you or any third party relating to the Service, including: (i) product liability claims; (ii) any claim that the Service fails to conform to any applicable legal or regulatory requirement; and (iii) claims arising under consumer protection, privacy, or similar legislation.</li><li><strong>Intellectual property rights.</strong> In the event of any third-party claim that the Service or your possession and use of the Service infringes that third party\u2019s intellectual property rights, ${escapeHtml(\n\t\t\tc.companyName\n\t\t)}, not Apple, will be solely responsible for the investigation, defense, settlement, and discharge of any such claim, to the extent required by these Terms.</li><li><strong>Legal compliance.</strong> You represent and warrant that you are not located in a country that is subject to a U.S. Government embargo or that has been designated by the U.S. Government as a \"terrorist supporting\" country, and that you are not listed on any U.S. Government list of prohibited or restricted parties.</li><li><strong>Third-party beneficiary.</strong> You and ${escapeHtml(\n\t\t\tc.companyName\n\t\t)} acknowledge and agree that Apple, and Apple\u2019s subsidiaries, are third-party beneficiaries of these Terms, and that, upon your acceptance of these Terms, Apple will have the right (and will be deemed to have accepted the right) to enforce these Terms against you as a third-party beneficiary thereof.</li><li><strong>Contact.</strong> Any questions, complaints, or claims with respect to the Service should be directed to ${escapeHtml(\n\t\t\tc.companyName\n\t\t)} using the methods in the \"Contact Us\" section.</li></ul>`\n\t);\n\nconst sectionGoogleRider = (c: Computed) =>\n\ttitledSection(\n\t\t'Additional Terms for Google Play',\n\t\t`<p>If you accessed or downloaded the Service from Google Play, you acknowledge and agree that:</p><ul><li>${escapeHtml(\n\t\t\tc.companyName\n\t\t)}, not Google LLC (\"Google\"), is solely responsible for the Service and its content.</li><li>Google has no obligation or liability to you with respect to the Service or these Terms.</li><li>Your use of the Service must comply with the then-current Google Play Terms of Service.</li><li>Google is a third-party beneficiary of these Terms only to the extent necessary to enforce its rights under the Google Play Terms of Service.</li></ul>`\n\t);\n\nconst sectionSeverability = () =>\n\ttitledSection(\n\t\t'Severability and Waiver',\n\t\t'<p><strong>Severability.</strong> If any provision of these Terms is held by a court or other tribunal of competent jurisdiction to be invalid, illegal, or unenforceable for any reason, that provision will be modified to the minimum extent necessary to make it enforceable, or, if it cannot be modified, severed from these Terms. The remaining provisions will continue in full force and effect.</p><p><strong>Waiver.</strong> No waiver by us of any term or condition set forth in these Terms shall be deemed a further or continuing waiver of such term or condition or a waiver of any other term or condition. Our failure to assert a right or provision under these Terms shall not constitute a waiver of such right or provision.</p>'\n\t);\n\nconst sectionEntireAgreement = () =>\n\ttitledSection(\n\t\t'Entire Agreement',\n\t\t'<p>These Terms, together with our Privacy Policy and any other policies referenced herein, constitute the entire agreement between you and us regarding the Service and supersede all prior and contemporaneous agreements, proposals, or representations, whether written or oral, regarding the Service.</p>'\n\t);\n\nconst sectionAssignment = (c: Computed) =>\n\ttitledSection(\n\t\t'Assignment',\n\t\t`<p>You may not assign or transfer these Terms, by operation of law or otherwise, without our prior written consent. Any attempt by you to assign or transfer these Terms without such consent will be null and void. ${escapeHtml(\n\t\t\tc.companyName\n\t\t)} may freely assign or transfer these Terms without restriction. Subject to the foregoing, these Terms will bind and inure to the benefit of the parties, their successors, and permitted assigns.</p>`\n\t);\n\nconst sectionNotices = () =>\n\ttitledSection(\n\t\t'Notices',\n\t\t'<p>Any notices or other communications provided by us under these Terms will be given by posting to the Service or by email to the address associated with your account. Notices to us must be sent using the methods listed in the \"Contact Us\" section. A notice is deemed given on the date received or, if delivery is not accomplished by reason of some fault of the addressee, when tendered.</p>'\n\t);\n\nconst sectionLinks = () =>\n\ttitledSection(\n\t\t'Links to Other Websites',\n\t\t'<p>The Service may contain links to third-party websites or services that are not owned or controlled by us. We have no control over, and assume no responsibility for, the content, privacy policies, or practices of any third-party websites or services. You acknowledge and agree that we are not responsible or liable, directly or indirectly, for any damage or loss caused or alleged to be caused by or in connection with the use of or reliance on any such content, goods, or services available on or through any such websites or services.</p>'\n\t);\n\nconst sectionChanges = () =>\n\ttitledSection(\n\t\t'Changes to These Terms',\n\t\t'<p>We may update these Terms from time to time. We will notify you of any changes by posting the new Terms on this page and updating the \"Last updated\" date at the top. Where required by law, we will provide additional notice (such as by email) and give you the opportunity to review the changes before they take effect. Your continued use of the Service after the updated Terms become effective constitutes your acceptance of the changes. If you do not agree to the new Terms, you must stop using the Service.</p>'\n\t);\n\nconst sectionContact = (a: TermsAnswers) => {\n\tconst items: string[] = [];\n\tif (a.contact?.methods?.includes('email') && a.contact.details.email) {\n\t\titems.push(\n\t\t\t`By email: <a href=\"mailto:${escapeHtml(a.contact.details.email)}\">${escapeHtml(\n\t\t\t\ta.contact.details.email\n\t\t\t)}</a>`\n\t\t);\n\t}\n\tif (a.contact?.methods?.includes('page') && a.contact.details.page) {\n\t\titems.push(\n\t\t\t`By visiting this page on our website: <a href=\"${escapeHtml(\n\t\t\t\ta.contact.details.page\n\t\t\t)}\" rel=\"external nofollow noopener\" target=\"_blank\">${escapeHtml(a.contact.details.page)}</a>`\n\t\t);\n\t}\n\tif (a.contact?.methods?.includes('phone') && a.contact.details.phone) {\n\t\titems.push(`By phone number: ${escapeHtml(a.contact.details.phone)}`);\n\t}\n\tif (a.contact?.methods?.includes('mail') && a.contact.details.address) {\n\t\titems.push(`By mail: ${escapeHtml(a.contact.details.address)}`);\n\t}\n\treturn `<section class=\"space-y-3\"><h2 class=\"text-xl font-semibold\">Contact Us</h2><p class=\"text-base leading-7\">If you have any questions about these Terms, you can contact us:</p>${list(items)}</section>`;\n};\n\nexport const generateTermsHtml = (answers: TermsAnswers) => {\n\tconst c = compute(answers);\n\tconst sections: string[] = [];\n\n\tsections.push(sectionHeader(c));\n\tsections.push(sectionEligibility());\n\tsections.push(sectionDefinitions(c));\n\tsections.push(sectionLicense());\n\tif (answers.accounts === 'yes') sections.push(sectionAccounts());\n\tif (answers.userContent === 'yes') sections.push(sectionUserContent());\n\tif (answers.userContent === 'yes' && answers.infringementEmail) {\n\t\tsections.push(sectionDmca(c, answers.infringementEmail));\n\t}\n\tif (answers.exclusiveContent === 'yes') sections.push(sectionExclusiveIp(c));\n\tif (answers.feedbackReuse === 'yes') sections.push(sectionFeedback());\n\tif (answers.canBuyGoods === 'yes') sections.push(sectionPurchases());\n\tif (answers.subscriptions === 'yes') sections.push(sectionSubscriptions(answers));\n\tif (answers.promotions === 'yes') sections.push(sectionPromotions());\n\tsections.push(sectionProhibited());\n\tsections.push(sectionTermination());\n\tsections.push(sectionDisclaimer(c));\n\tsections.push(sectionLimitation(c));\n\tsections.push(sectionIndemnification(c));\n\tsections.push(sectionForceMajeure());\n\tsections.push(sectionGoverningLaw(c));\n\tsections.push(sectionArbitration(c));\n\tsections.push(sectionExport(c));\n\tif (answers.mobileApp.includes('apple')) sections.push(sectionAppleRider(c));\n\tif (answers.mobileApp.includes('google')) sections.push(sectionGoogleRider(c));\n\tsections.push(sectionSeverability());\n\tsections.push(sectionEntireAgreement());\n\tsections.push(sectionAssignment(c));\n\tsections.push(sectionNotices());\n\tsections.push(sectionLinks());\n\tsections.push(sectionChanges());\n\tsections.push(sectionContact(answers));\n\n\treturn `<section data-role=\"content\">${sections.filter(Boolean).join('')}</section>`;\n};\n\nasync function termsAction(): Promise<void> {\n\tconst { workspaceRootDir, publicRoutesDir } = await getWorkspace();\n\n\tconst core = await p.group(\n\t\t{\n\t\t\twebsiteUrl: sharedFields.websiteUrl,\n\t\t\twebsiteName: sharedFields.websiteName,\n\t\t\tentityType: sharedFields.entityType,\n\t\t\tbusinessName: sharedFields.businessName,\n\t\t\tbusinessAddress: sharedFields.businessAddress,\n\t\t\tcountry: sharedFields.country,\n\t\t\tstate: sharedFields.state\n\t\t},\n\t\t{ onCancel }\n\t);\n\n\tconst accounts = await p.select({\n\t\tmessage: 'Can users create accounts?',\n\t\toptions: [\n\t\t\t{ value: 'yes', label: 'Yes, users can create accounts' },\n\t\t\t{ value: 'no', label: 'No' }\n\t\t]\n\t});\n\tif (p.isCancel(accounts)) onCancel();\n\n\tconst userContent = await p.select({\n\t\tmessage: 'Can users create and/or upload content (ie. text, images)?',\n\t\toptions: [\n\t\t\t{ value: 'yes', label: 'Yes, users can create and/or upload content' },\n\t\t\t{ value: 'no', label: 'No' }\n\t\t]\n\t});\n\tif (p.isCancel(userContent)) onCancel();\n\n\tlet infringementEmail: string | undefined;\n\tif (userContent === 'yes') {\n\t\tconst email = await p.text({\n\t\t\tmessage: \"What's the email address where you will receive infringements notices?\",\n\t\t\tplaceholder: 'dmca@website.com',\n\t\t\tvalidate: (value: string | undefined) => {\n\t\t\t\tif (!value) {\n\t\t\t\t\treturn 'Please enter an email address';\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\tif (p.isCancel(email)) onCancel();\n\t\tinfringementEmail = email as string;\n\t}\n\n\tconst canBuyGoods = await p.select({\n\t\tmessage: 'Can users buy goods (products, items)?',\n\t\toptions: [\n\t\t\t{\n\t\t\t\tvalue: 'yes',\n\t\t\t\tlabel: 'Yes, users can buy goods, items or services (one-time payments only)'\n\t\t\t},\n\t\t\t{ value: 'no', label: 'No' }\n\t\t]\n\t});\n\tif (p.isCancel(canBuyGoods)) onCancel();\n\n\tconst subscriptions = await p.select({\n\t\tmessage: 'Do you offer subscription plans?',\n\t\toptions: [\n\t\t\t{ value: 'yes', label: 'Yes, we offer subscription plans' },\n\t\t\t{ value: 'no', label: 'No' }\n\t\t]\n\t});\n\tif (p.isCancel(subscriptions)) onCancel();\n\n\tlet freeTrial: 'yes' | 'no' | undefined;\n\tif (subscriptions === 'yes') {\n\t\tconst ft = await p.select({\n\t\t\tmessage: 'Do you offer a free trial?',\n\t\t\toptions: [\n\t\t\t\t{ value: 'yes', label: 'Yes' },\n\t\t\t\t{ value: 'no', label: 'No' }\n\t\t\t]\n\t\t});\n\t\tif (p.isCancel(ft)) onCancel();\n\t\tfreeTrial = ft as 'yes' | 'no';\n\t}\n\n\tconst exclusiveContent = await p.select({\n\t\tmessage:\n\t\t\t'Do you want to make it clear that your own content & trademarks are your exclusive property?',\n\t\toptions: [\n\t\t\t{\n\t\t\t\tvalue: 'yes',\n\t\t\t\tlabel: 'Yes, our content (logo, visual design, trademarks etc.) is our exclusive property'\n\t\t\t},\n\t\t\t{ value: 'no', label: 'No' }\n\t\t]\n\t});\n\tif (p.isCancel(exclusiveContent)) onCancel();\n\n\tconst feedbackReuse = await p.select({\n\t\tmessage:\n\t\t\t'If users provide you feedback & suggestions, do you want to use this feedback without compensation or credits given?',\n\t\toptions: [\n\t\t\t{ value: 'yes', label: 'Yes, we may implement any feedback or suggestions we receive' },\n\t\t\t{ value: 'no', label: 'No' }\n\t\t]\n\t});\n\tif (p.isCancel(feedbackReuse)) onCancel();\n\n\tconst promotions = await p.select({\n\t\tmessage: 'Do you plan to offer promotions, contests, sweepstakes?',\n\t\toptions: [\n\t\t\t{ value: 'yes', label: 'Yes, we may offer promotions, contests, sweepstakes' },\n\t\t\t{ value: 'no', label: 'No' }\n\t\t]\n\t});\n\tif (p.isCancel(promotions)) onCancel();\n\n\tconst mobileAppRaw = await p.multiselect({\n\t\tmessage: 'Is the Service distributed through any mobile app stores? Check all that apply',\n\t\toptions: [\n\t\t\t{ value: 'apple', label: 'Apple App Store' },\n\t\t\t{ value: 'google', label: 'Google Play' }\n\t\t],\n\t\trequired: false\n\t});\n\tif (p.isCancel(mobileAppRaw)) onCancel();\n\tconst mobileApp = (mobileAppRaw ?? []) as Array<'apple' | 'google'>;\n\n\tconst contact = await contactMethods('terms');\n\n\tconst html = generateTermsHtml({\n\t\tcore,\n\t\taccounts: accounts as 'yes' | 'no',\n\t\tuserContent: userContent as 'yes' | 'no',\n\t\tinfringementEmail,\n\t\tcanBuyGoods: canBuyGoods as 'yes' | 'no',\n\t\tsubscriptions: subscriptions as 'yes' | 'no',\n\t\tfreeTrial,\n\t\texclusiveContent: exclusiveContent as 'yes' | 'no',\n\t\tfeedbackReuse: feedbackReuse as 'yes' | 'no',\n\t\tpromotions: promotions as 'yes' | 'no',\n\t\tmobileApp,\n\t\tcontact\n\t});\n\n\tconst termsPage = path.join(\n\t\tworkspaceRootDir,\n\t\tpublicRoutesDir,\n\t\tLEGAL_DIR,\n\t\t'terms',\n\t\t'+page.svelte'\n\t);\n\tconst termsPageTs = path.join(workspaceRootDir, publicRoutesDir, LEGAL_DIR, 'terms', '+page.ts');\n\tfs.mkdirSync(path.dirname(termsPage), { recursive: true });\n\tfs.writeFileSync(termsPage, html);\n\tfs.writeFileSync(\n\t\ttermsPageTs,\n\t\tpageMetaTagsLoader('Terms of Service', `Terms of Service for ${core.websiteName}`)\n\t);\n\n\tconst relativeTermsPage = path.relative(workspaceRootDir, termsPage);\n\tconst relativeTermsPageTs = path.relative(workspaceRootDir, termsPageTs);\n\treportResult({\n\t\tsummary: 'Generated placeholder terms and conditions.',\n\t\tfilesCreated: [relativeTermsPage, relativeTermsPageTs],\n\t\tnextSteps: [\n\t\t\t`Review the generated copy in ${relativeTermsPage} and replace placeholder sections with details for your business.`,\n\t\t\t'Have the final document reviewed by a lawyer before publishing \u2014 this is a starter template, not legal advice.',\n\t\t\t'Link to /terms from your footer and sign-up flow.'\n\t\t]\n\t});\n}\n\nexport const terms = new Command('terms')\n\t.description('generate placeholder terms and conditions')\n\t.configureHelp(helpConfig)\n\t.action(() => runCommand(termsAction, 'Failed to generate terms and conditions.'));\n", "import process from 'node:process';\nimport * as p from '@clack/prompts';\n\nexport const sharedFields = {\n\twebsiteUrl: () =>\n\t\tp.text({\n\t\t\tmessage: 'What is your website URL?',\n\t\t\tplaceholder: 'http://www.mysite.com',\n\t\t\tvalidate: (value: string | undefined) => {\n\t\t\t\tif (!value || !value.startsWith('http')) {\n\t\t\t\t\treturn 'Please enter a valid URL starting with http or https';\n\t\t\t\t}\n\t\t\t}\n\t\t}),\n\twebsiteName: () =>\n\t\tp.text({\n\t\t\tmessage: 'What is your website name?',\n\t\t\tplaceholder: 'My Site',\n\t\t\tvalidate: (value: string | undefined) => {\n\t\t\t\tif (!value) {\n\t\t\t\t\treturn 'Please enter a website name';\n\t\t\t\t}\n\t\t\t}\n\t\t}),\n\tentityType: () =>\n\t\tp.select({\n\t\t\tmessage: 'Entity type',\n\t\t\toptions: [\n\t\t\t\t{\n\t\t\t\t\tvalue: 'business',\n\t\t\t\t\tlabel: \"I'm a Business\",\n\t\t\t\t\thint: 'e.g. Corporation, Limited Liability Company, Non-profit, Partnership, Sole Proprietor'\n\t\t\t\t},\n\t\t\t\t{ value: 'individual', label: \"I'm an Individual\" }\n\t\t\t]\n\t\t}),\n\tbusinessName: ({ results }: { results: { entityType?: 'business' | 'individual' } }) =>\n\t\tresults?.entityType === 'business'\n\t\t\t? p.text({\n\t\t\t\t\tmessage: 'What is the name of the business?',\n\t\t\t\t\tplaceholder: 'My Company LLC',\n\t\t\t\t\tvalidate: (value: string | undefined) => {\n\t\t\t\t\t\tif (!value) {\n\t\t\t\t\t\t\treturn 'Please enter a business name';\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t: undefined,\n\tbusinessAddress: ({ results }: { results: { entityType?: 'business' | 'individual' } }) =>\n\t\tresults?.entityType === 'business'\n\t\t\t? p.text({\n\t\t\t\t\tmessage: 'What is the address of the business?',\n\t\t\t\t\tplaceholder: '1 Cupertino, CA 95014',\n\t\t\t\t\tvalidate: (value: string | undefined) => {\n\t\t\t\t\t\tif (!value) {\n\t\t\t\t\t\t\treturn 'Please enter a business address';\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t: undefined,\n\tcountry: () =>\n\t\tp.text({\n\t\t\tmessage: 'Enter the country',\n\t\t\tvalidate: (value: string | undefined) => {\n\t\t\t\tif (!value) {\n\t\t\t\t\treturn 'Please enter a country';\n\t\t\t\t}\n\t\t\t}\n\t\t}),\n\tstate: () =>\n\t\tp.text({\n\t\t\tmessage: 'Enter the state',\n\t\t\tvalidate: (value: string | undefined) => {\n\t\t\t\tif (!value) {\n\t\t\t\t\treturn 'Please enter a state';\n\t\t\t\t}\n\t\t\t}\n\t\t})\n};\n\nexport const onCancel = () => {\n\tp.cancel('Operation cancelled.');\n\tprocess.exit(0);\n};\n\nexport async function contactMethods(type: 'terms' | 'privacy'): Promise<{\n\tmethods: Array<'email' | 'page' | 'phone' | 'mail'>;\n\tdetails: Record<string, string>;\n}> {\n\tconst selection = await p.multiselect({\n\t\tmessage: `How can users contact you for any questions regarding your ${type === 'privacy' ? 'Privacy Policy' : 'Terms & Conditions'}? Check all that apply`,\n\t\toptions: [\n\t\t\t{ value: 'email', label: 'By email' },\n\t\t\t{ value: 'page', label: 'By visiting a page on our website' },\n\t\t\t{ value: 'phone', label: 'By phone number' },\n\t\t\t{ value: 'mail', label: 'By sending post mail' }\n\t\t]\n\t});\n\n\tif (p.isCancel(selection)) onCancel();\n\n\tconst contact = selection as Array<'email' | 'page' | 'phone' | 'mail'>;\n\tconst details: Record<string, string> = {};\n\n\tif (contact.includes('email')) {\n\t\tconst email = await p.text({\n\t\t\tmessage: \"What's the email?\",\n\t\t\tplaceholder: 'office@mycompany.com',\n\t\t\tvalidate: (value: string | undefined) => {\n\t\t\t\tif (!value) {\n\t\t\t\t\treturn 'Please enter an email address';\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\tif (p.isCancel(email)) onCancel();\n\t\tdetails.email = email as string;\n\t}\n\tif (contact.includes('page')) {\n\t\tconst page = await p.text({\n\t\t\tmessage: \"What's the link?\",\n\t\t\tplaceholder: 'http://www.mycompany.com/contact',\n\t\t\tvalidate: (value: string | undefined) => {\n\t\t\t\tif (!value) {\n\t\t\t\t\treturn 'Please enter a link';\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\tif (p.isCancel(page)) onCancel();\n\t\tdetails.page = page as string;\n\t}\n\tif (contact.includes('phone')) {\n\t\tconst phone = await p.text({\n\t\t\tmessage: \"What's the phone number?\",\n\t\t\tplaceholder: '408.996.1010',\n\t\t\tvalidate: (value: string | undefined) => {\n\t\t\t\tif (!value) {\n\t\t\t\t\treturn 'Please enter a phone number';\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\tif (p.isCancel(phone)) onCancel();\n\t\tdetails.phone = phone as string;\n\t}\n\tif (contact.includes('mail')) {\n\t\tconst address = await p.text({\n\t\t\tmessage: \"What's the address?\",\n\t\t\tplaceholder: '767 Fifth Avenue New York, NY 10153, United States',\n\t\t\tvalidate: (value: string | undefined) => {\n\t\t\t\tif (!value) {\n\t\t\t\t\treturn 'Please enter an address';\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\tif (p.isCancel(address)) onCancel();\n\t\tdetails.address = address as string;\n\t}\n\n\treturn { methods: contact, details };\n}\n\nexport const escapeHtml = (value: unknown) =>\n\tString(value ?? '')\n\t\t.replaceAll('&', '&amp;')\n\t\t.replaceAll('<', '&lt;')\n\t\t.replaceAll('>', '&gt;')\n\t\t.replaceAll('\"', '&quot;')\n\t\t.replaceAll(\"'\", '&#39;');\n\nexport type LegalCoreAnswers = {\n\twebsiteUrl: string;\n\twebsiteName: string;\n\tentityType: 'business' | 'individual';\n\tbusinessName?: string;\n\tbusinessAddress?: string;\n\tcountry: string;\n\tstate: string;\n};\n\nexport const applyTypography = (html: string) =>\n\thtml\n\t\t.replaceAll('<p>', '<p class=\"text-base leading-7\">')\n\t\t.replaceAll('<ul>', '<ul class=\"list-disc pl-6 space-y-1 text-base leading-7\">')\n\t\t.replaceAll('<h3>', '<h3 class=\"text-lg font-semibold\">')\n\t\t.replaceAll('<h4>', '<h4 class=\"font-semibold\">');\n\nexport const list = (items: string[]) =>\n\titems.length\n\t\t? `<ul class=\"list-disc pl-6 space-y-1 text-base leading-7\">${items\n\t\t\t\t.map((i) => `<li>${i}</li>`)\n\t\t\t\t.join('')}</ul>`\n\t\t: '';\n\nexport const titledSection = (title: string, body: string) =>\n\tbody\n\t\t? `<section class=\"space-y-3\"><h2 class=\"text-xl font-semibold\">${escapeHtml(\n\t\t\t\ttitle\n\t\t\t)}</h2>${applyTypography(body)}</section>`\n\t\t: '';\n\nexport const subSection = (title: string, body: string) =>\n\tbody\n\t\t? `<div class=\"space-y-2\"><h3 class=\"text-lg font-semibold\">${escapeHtml(\n\t\t\t\ttitle\n\t\t\t)}</h3>${applyTypography(body)}</div>`\n\t\t: '';\n\nconst jsString = (s: string) =>\n\t`'${s.replace(/\\\\/g, '\\\\\\\\').replace(/'/g, \"\\\\'\").replace(/\\n/g, '\\\\n')}'`;\n\nexport const pageMetaTagsLoader = (title: string, description: string) =>\n\t`import { definePageMetaTags } from 'svelte-meta-tags';\n\nexport const load = async ({ parent }) => {\n\\tawait parent();\n\n\\tconst { pageMetaTags } = definePageMetaTags({\n\\t\\ttitle: ${jsString(title)},\n\\t\\tdescription: ${jsString(description)}\n\\t});\n\n\\treturn { pageMetaTags };\n};\n`;\n\nexport const ccpaCategoriesTable = (collected: {\n\tidentifiers: boolean;\n\tcustomerRecords: boolean;\n\tcommercialInfo: boolean;\n\tinternetActivity: boolean;\n\tgeolocation: boolean;\n\tsensitive: boolean;\n}) => {\n\tconst rows: Array<[string, string, boolean]> = [\n\t\t[\n\t\t\t'A. Identifiers',\n\t\t\t'A real name, alias, postal address, unique personal identifier, online identifier, IP address, email address, account name, or similar identifiers.',\n\t\t\tcollected.identifiers\n\t\t],\n\t\t[\n\t\t\t'B. Personal information categories listed in the California Customer Records statute (Cal. Civ. Code \u00A7 1798.80(e))',\n\t\t\t'A name, signature, address, telephone number, education, employment, employment history, financial information, or similar information. Some personal information included in this category may overlap with other categories.',\n\t\t\tcollected.customerRecords\n\t\t],\n\t\t[\n\t\t\t'C. Protected classification characteristics under California or federal law',\n\t\t\t'Age, race, color, ancestry, national origin, citizenship, religion, marital status, sex (including gender identity, gender expression), sexual orientation, veteran or military status, genetic information, or disability.',\n\t\t\tfalse\n\t\t],\n\t\t[\n\t\t\t'D. Commercial information',\n\t\t\t'Records and history of products or services purchased or considered.',\n\t\t\tcollected.commercialInfo\n\t\t],\n\t\t[\n\t\t\t'E. Biometric information',\n\t\t\t'Genetic, physiological, behavioral, and biological characteristics.',\n\t\t\tfalse\n\t\t],\n\t\t[\n\t\t\t'F. Internet or other similar network activity',\n\t\t\t'Browsing history, search history, interaction with our Service, advertisements, or other websites.',\n\t\t\tcollected.internetActivity\n\t\t],\n\t\t['G. Geolocation data', 'Approximate physical location.', collected.geolocation],\n\t\t[\n\t\t\t'H. Sensory data',\n\t\t\t'Audio, electronic, visual, thermal, olfactory, or similar information.',\n\t\t\tfalse\n\t\t],\n\t\t[\n\t\t\t'I. Professional or employment-related information',\n\t\t\t'Current or past job history or performance evaluations.',\n\t\t\tfalse\n\t\t],\n\t\t[\n\t\t\t'J. Non-public education information',\n\t\t\t'Education records directly related to a student maintained by an educational institution or party acting on its behalf, such as grades, transcripts, class lists, schedules, identification codes, financial information, or disciplinary records.',\n\t\t\tfalse\n\t\t],\n\t\t[\n\t\t\t'K. Inferences drawn from other personal information',\n\t\t\t'Profile reflecting a person\u2019s preferences, characteristics, predispositions, behavior, attitudes, intelligence, abilities, and aptitudes.',\n\t\t\tcollected.internetActivity\n\t\t]\n\t];\n\tconst items = rows.map(\n\t\t([cat, desc, yes]) =>\n\t\t\t`<li><p class=\"text-base leading-7\"><strong>${escapeHtml(cat)}</strong> &mdash; ${escapeHtml(\n\t\t\t\tdesc\n\t\t\t)} <em>Collected: ${yes ? 'Yes' : 'No'}.</em></p></li>`\n\t);\n\tlet body = `<p class=\"text-base leading-7\">In the past twelve (12) months, we may have collected the following categories of personal information:</p><ul class=\"list-disc pl-6 space-y-1 text-base leading-7\">${items.join('')}</ul>`;\n\tif (collected.sensitive) {\n\t\tbody += `<p class=\"text-base leading-7\"><strong>Sensitive Personal Information.</strong> We may collect a limited subset of sensitive personal information (such as account log-in credentials in combination with required security or access codes) as defined by the California Privacy Rights Act (\"CPRA\"). We do not use or disclose sensitive personal information for purposes other than those permitted under Cal. Civ. Code \u00A7 1798.121.</p>`;\n\t}\n\treturn body;\n};\n\nexport const legalBasesBlock = () =>\n\t`<p class=\"text-base leading-7\">If you are a resident of the European Economic Area (\"EEA\"), the United Kingdom, or Switzerland, our legal basis for collecting and using the personal information described in this Privacy Policy depends on the personal information we collect and the specific context in which we collect it. We may process your personal information because:</p><ul class=\"list-disc pl-6 space-y-1 text-base leading-7\"><li><p class=\"text-base leading-7\"><strong>Performance of a contract:</strong> processing is necessary to perform a contract with you or to take steps at your request before entering into a contract (Article 6(1)(b) GDPR).</p></li><li><p class=\"text-base leading-7\"><strong>Legitimate interests:</strong> processing is necessary for our legitimate interests or those of a third party, provided your interests and fundamental rights do not override those interests (Article 6(1)(f) GDPR). Our legitimate interests include securing the Service, preventing fraud, improving the Service, and direct marketing where permitted.</p></li><li><p class=\"text-base leading-7\"><strong>Compliance with legal obligation:</strong> processing is necessary for compliance with a legal obligation to which we are subject (Article 6(1)(c) GDPR).</p></li><li><p class=\"text-base leading-7\"><strong>Consent:</strong> we have your consent to do so for a specific purpose (Article 6(1)(a) GDPR). You may withdraw consent at any time by contacting us.</p></li><li><p class=\"text-base leading-7\"><strong>Vital interests:</strong> processing is necessary to protect your vital interests or those of another natural person (Article 6(1)(d) GDPR).</p></li><li><p class=\"text-base leading-7\"><strong>Public interest:</strong> processing is necessary for the performance of a task carried out in the public interest (Article 6(1)(e) GDPR).</p></li></ul>`;\n\nexport const internationalTransfersBlock = () =>\n\t`<p class=\"text-base leading-7\">Your information, including personal data, may be processed at our operating offices and in any other places where the parties involved in the processing are located. This means that this information may be transferred to \u2014 and maintained on \u2014 computers located outside of your state, province, country, or other governmental jurisdiction where the data protection laws may differ from those of your jurisdiction.</p><p class=\"text-base leading-7\">If we transfer personal information from the European Economic Area, the United Kingdom, or Switzerland to a country that has not been determined by the European Commission or the relevant authority to provide an adequate level of protection, we rely on appropriate safeguards. These safeguards include the European Commission\u2019s Standard Contractual Clauses (and the UK International Data Transfer Addendum, where applicable), supplementary technical and organizational measures, and, where appropriate, your explicit consent.</p><p class=\"text-base leading-7\">Your submission of personal information represents your agreement to that transfer. We will take all steps reasonably necessary to ensure that your data is treated securely and in accordance with this Privacy Policy and applicable law.</p>`;\n\nexport const usStateRightsBlock = (companyName: string) =>\n\t`<p class=\"text-base leading-7\">Residents of certain U.S. states (including California, Virginia, Colorado, Connecticut, Utah, Texas, Oregon, and others with comprehensive consumer privacy laws) have specific rights regarding their personal information. Subject to the requirements and exceptions of the applicable law, you may have the right to:</p><ul class=\"list-disc pl-6 space-y-1 text-base leading-7\"><li><p class=\"text-base leading-7\"><strong>Right to know / access:</strong> request that we disclose the categories and specific pieces of personal information we have collected about you, the categories of sources, the business or commercial purpose for collection, and the categories of third parties with whom we share your information.</p></li><li><p class=\"text-base leading-7\"><strong>Right to delete:</strong> request that we delete personal information we have collected from you, subject to certain exceptions.</p></li><li><p class=\"text-base leading-7\"><strong>Right to correct:</strong> request that we correct inaccurate personal information we maintain about you.</p></li><li><p class=\"text-base leading-7\"><strong>Right to opt out of sale or sharing:</strong> opt out of the sale of your personal information or sharing of your personal information for cross-context behavioral advertising.</p></li><li><p class=\"text-base leading-7\"><strong>Right to limit the use of sensitive personal information:</strong> direct us to limit our use and disclosure of sensitive personal information to those uses necessary to perform the services or provide the goods reasonably expected by an average consumer who requests them.</p></li><li><p class=\"text-base leading-7\"><strong>Right to non-discrimination:</strong> not be subjected to discriminatory treatment for exercising your privacy rights.</p></li><li><p class=\"text-base leading-7\"><strong>Right to appeal:</strong> if we deny your request, you may appeal our decision by contacting us. If your appeal is denied, you may contact your state attorney general.</p></li></ul><p class=\"text-base leading-7\"><strong>How to exercise your rights.</strong> You may submit a verifiable consumer request by contacting us using the methods listed in the \"Contact Us\" section. We will need to verify your identity before responding to your request. You may use an authorized agent to submit a request on your behalf, provided you give the agent written permission and verify your identity directly with us.</p><p class=\"text-base leading-7\"><strong>\"Do Not Sell or Share My Personal Information\" and Global Privacy Control.</strong> You may opt out of the \"sale\" or \"sharing\" of your personal information at any time. We honor opt-out preference signals, including the Global Privacy Control (\"GPC\"), as a valid request to opt out of sale and sharing for the browser or device on which the signal is detected.</p><p class=\"text-base leading-7\"><strong>California \"Shine the Light\" (Cal. Civ. Code &sect; 1798.83).</strong> California residents may request information about our disclosures of personal information to third parties for their direct marketing purposes once per calendar year. To make such a request, please contact us using the information in the \"Contact Us\" section.</p><p class=\"text-base leading-7\"><strong>CalOPPA disclosures.</strong> ${escapeHtml(\n\t\tcompanyName\n\t)} does not track its users over time and across third-party websites or services. We respond to Do Not Track (\"DNT\") signals as described above. We will notify users of material changes to this Privacy Policy by posting an updated policy on this page.</p>`;\n\nexport const gdprRightsBlock = (\n\tcompanyName: string,\n\tfacebookFanPage: { name: string; url: string } | null\n) => {\n\tlet body = `<p class=\"text-base leading-7\">If you are a resident of the European Economic Area (\"EEA\"), the United Kingdom, or Switzerland, you have the following rights under the General Data Protection Regulation (\"GDPR\") and the UK GDPR:</p><ul class=\"list-disc pl-6 space-y-1 text-base leading-7\"><li><p class=\"text-base leading-7\"><strong>Right of access:</strong> request a copy of the personal data we hold about you and information about how we process it.</p></li><li><p class=\"text-base leading-7\"><strong>Right to rectification:</strong> request that we correct inaccurate or complete incomplete personal data.</p></li><li><p class=\"text-base leading-7\"><strong>Right to erasure (\"right to be forgotten\"):</strong> request that we delete your personal data, where there is no compelling reason for us to continue processing it.</p></li><li><p class=\"text-base leading-7\"><strong>Right to restrict processing:</strong> request that we restrict the processing of your personal data in certain circumstances.</p></li><li><p class=\"text-base leading-7\"><strong>Right to data portability:</strong> receive the personal data you provided to us in a structured, commonly used, machine-readable format and have it transmitted to another controller.</p></li><li><p class=\"text-base leading-7\"><strong>Right to object:</strong> object to our processing of your personal data based on legitimate interests, including for direct marketing.</p></li><li><p class=\"text-base leading-7\"><strong>Right to withdraw consent:</strong> where processing is based on consent, withdraw that consent at any time without affecting the lawfulness of prior processing.</p></li><li><p class=\"text-base leading-7\"><strong>Right not to be subject to automated decision-making:</strong> not to be subject to a decision based solely on automated processing, including profiling, that produces legal effects concerning you or similarly significantly affects you.</p></li><li><p class=\"text-base leading-7\"><strong>Right to lodge a complaint:</strong> lodge a complaint with the supervisory authority in your country of residence, place of work, or place of the alleged infringement.</p></li></ul><p class=\"text-base leading-7\">To exercise any of these rights, please contact us using the methods listed in the \"Contact Us\" section. We will respond within one month, subject to any extensions permitted by law.</p>`;\n\tif (facebookFanPage) {\n\t\tconst name = escapeHtml(facebookFanPage.name);\n\t\tconst url = escapeHtml(facebookFanPage.url);\n\t\tbody += `<p class=\"text-base leading-7\"><strong>Facebook Fan Page \u2014 Joint Controller.</strong> ${escapeHtml(\n\t\t\tcompanyName\n\t\t)} operates the Facebook Fan Page${name ? ` \"${name}\"` : ''}${\n\t\t\turl ? ` at <a href=\"${url}\" rel=\"external nofollow noopener\" target=\"_blank\">${url}</a>` : ''\n\t\t}. As a result of the decision of the Court of Justice of the European Union in Case C-210/16, ${escapeHtml(\n\t\t\tcompanyName\n\t\t)} and Meta Platforms Ireland Limited are joint controllers in respect of personal data collected through the Page Insights service. The agreement between the parties governing this joint controllership is available on Meta\u2019s website. You may exercise your rights under the GDPR with either party.</p>`;\n\t}\n\treturn body;\n};\n\nexport const arbitrationBlock = (companyName: string, governingLocation: string) =>\n\t`<p class=\"text-base leading-7\"><strong>Informal resolution first.</strong> Before filing a claim against ${escapeHtml(\n\t\tcompanyName\n\t)}, you agree to try to resolve the dispute informally by contacting us. We will attempt to resolve the dispute by contacting you via email. If a dispute is not resolved within thirty (30) days of submission, you or ${escapeHtml(\n\t\tcompanyName\n\t)} may bring a formal proceeding.</p><p class=\"text-base leading-7\"><strong>Binding arbitration.</strong> Except for claims that may be properly brought in a small claims court of competent jurisdiction, all controversies, disputes, or claims arising out of or relating to these Terms or the Service shall be resolved by final and binding arbitration administered by the American Arbitration Association (\"AAA\") under its applicable rules then in effect (or, for users outside the United States, by an equivalent recognized arbitration body). The arbitration shall take place in ${escapeHtml(\n\t\tgoverningLocation\n\t)} or, at your election, by telephone or written submissions. The arbitrator\u2019s decision shall be final and binding, and judgment on the award may be entered in any court of competent jurisdiction.</p><p class=\"text-base leading-7\"><strong>Class-action waiver.</strong> You and ${escapeHtml(\n\t\tcompanyName\n\t)} agree that each may bring claims against the other only in your or its individual capacity and not as a plaintiff or class member in any purported class or representative proceeding. Unless both parties agree otherwise in writing, the arbitrator may not consolidate more than one person\u2019s claims and may not otherwise preside over any form of a representative or class proceeding.</p><p class=\"text-base leading-7\"><strong>Jury trial waiver.</strong> By agreeing to these Terms and to arbitration, you and ${escapeHtml(\n\t\tcompanyName\n\t)} are each waiving the right to a trial by jury or to participate in a class action.</p><p class=\"text-base leading-7\"><strong>30-day right to opt out.</strong> You may opt out of these arbitration and class-action waiver provisions by sending written notice of your decision to opt out to the contact address listed in the \"Contact Us\" section, postmarked within thirty (30) days of first accepting these Terms. Your notice must include your name, address, the email associated with your account, and a clear statement that you wish to opt out of arbitration. Opting out will not affect the other terms of this agreement.</p><p class=\"text-base leading-7\"><strong>Severability of class waiver.</strong> If the class-action waiver is found unenforceable in a particular case, then that proceeding shall be severed from any arbitration and brought in a court of competent jurisdiction; the remainder of these arbitration provisions shall continue to apply.</p>`;\n\nexport const dmcaBlock = (companyName: string, infringementEmail: string) =>\n\t`<p class=\"text-base leading-7\">${escapeHtml(\n\t\tcompanyName\n\t)} respects the intellectual property rights of others and expects users of the Service to do the same. We respond to clear notices of alleged copyright infringement that comply with the U.S. Digital Millennium Copyright Act (\"DMCA\"), 17 U.S.C. &sect; 512.</p><p class=\"text-base leading-7\"><strong>Submitting a notice of infringement.</strong> If you believe that material on the Service infringes your copyright, please send a written notice to our designated agent at <a href=\"mailto:${escapeHtml(\n\t\tinfringementEmail\n\t)}\">${escapeHtml(\n\t\tinfringementEmail\n\t)}</a>. To be effective under 17 U.S.C. &sect; 512(c)(3)(A), your notice must include substantially the following:</p><ul class=\"list-disc pl-6 space-y-1 text-base leading-7\"><li><p class=\"text-base leading-7\">A physical or electronic signature of a person authorized to act on behalf of the owner of an exclusive right that is allegedly infringed.</p></li><li><p class=\"text-base leading-7\">Identification of the copyrighted work claimed to have been infringed, or, if multiple copyrighted works are covered by a single notification, a representative list of such works.</p></li><li><p class=\"text-base leading-7\">Identification of the material that is claimed to be infringing or to be the subject of infringing activity, with information reasonably sufficient to permit us to locate the material (such as a URL).</p></li><li><p class=\"text-base leading-7\">Information reasonably sufficient to permit us to contact you, such as an address, telephone number, and an email address.</p></li><li><p class=\"text-base leading-7\">A statement that you have a good-faith belief that use of the material in the manner complained of is not authorized by the copyright owner, its agent, or the law.</p></li><li><p class=\"text-base leading-7\">A statement that the information in the notification is accurate, and under penalty of perjury, that you are authorized to act on behalf of the owner of an exclusive right that is allegedly infringed.</p></li></ul><p class=\"text-base leading-7\"><strong>Counter-notice.</strong> If you believe that your content was removed or disabled by mistake or misidentification, you may submit a written counter-notice to the same address. Under 17 U.S.C. &sect; 512(g)(3), the counter-notice must include your physical or electronic signature, identification of the material removed and its prior location, a statement under penalty of perjury that you have a good-faith belief that the material was removed or disabled as a result of mistake or misidentification, your name, address, telephone number, and a statement that you consent to the jurisdiction of the federal district court for your judicial district (or, if outside the United States, of any judicial district in which we may be found) and that you will accept service of process from the person who provided the original notification or an agent of such person.</p><p class=\"text-base leading-7\"><strong>Repeat infringers.</strong> It is our policy, in appropriate circumstances and at our sole discretion, to disable or terminate the accounts of users who are repeat infringers. Submitting false or misleading notices or counter-notices may result in liability for damages under 17 U.S.C. &sect; 512(f).</p>`;\n", "import fs from 'node:fs';\nimport path from 'node:path';\nimport { Command } from 'commander';\nimport * as p from '@clack/prompts';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand } from '../../lib/run.ts';\nimport { getWorkspace } from '../../lib/workspace.ts';\nimport { LEGAL_DIR } from '../../lib/constants.ts';\nimport { reportResult } from '../../lib/result-report.ts';\nimport {\n\tapplyTypography,\n\tccpaCategoriesTable,\n\tcontactMethods,\n\tescapeHtml,\n\tgdprRightsBlock,\n\tinternationalTransfersBlock,\n\tlegalBasesBlock,\n\tlist,\n\tonCancel,\n\tpageMetaTagsLoader,\n\tsharedFields,\n\tsubSection,\n\ttitledSection,\n\tusStateRightsBlock,\n\ttype LegalCoreAnswers\n} from './shared.ts';\n\nconst mapLabels = {\n\tpersonalInfo: {\n\t\temail: 'Email address',\n\t\tname: 'First name and last name',\n\t\tphone: 'Phone number',\n\t\taddress: 'Address, State, Province, ZIP/Postal code, City',\n\t\tsocial:\n\t\t\t'Social Media Profile information (e.g. from Connect with Facebook, Sign In With Twitter)',\n\t\tother: 'Other information you choose to provide'\n\t},\n\ttracking: {\n\t\tga: 'Google Analytics',\n\t\tfirebase: 'Firebase',\n\t\tmatomo: 'Matomo (formerly Piwik)',\n\t\tclicky: 'Clicky',\n\t\tstatcounter: 'Statcounter',\n\t\tflurry: 'Flurry Analytics',\n\t\tmixpanel: 'Mixpanel',\n\t\tunity: 'Unity Analytics'\n\t},\n\temailPlatforms: {\n\t\tmailchimp: 'Mailchimp',\n\t\t'constant-contact': 'Constant Contact',\n\t\taweber: 'AWeber',\n\t\tgetresponse: 'GetResponse'\n\t},\n\tads: {\n\t\tadsense: 'Google Ads (AdSense)',\n\t\tadmob: 'AdMob by Google',\n\t\tbing: 'Bing Ads',\n\t\tflurry: 'Flurry',\n\t\tinmobi: 'InMobi',\n\t\tmopub: 'MoPub',\n\t\tstartapp: 'StartApp',\n\t\tadcolony: 'AdColony',\n\t\tapplovin: 'AppLovin',\n\t\tvungle: 'Vungle',\n\t\tadbutler: 'AdButler',\n\t\t'unity-ads': 'Unity Ads'\n\t},\n\tpayments: {\n\t\t'apple-iap': 'Apple Store In-App Payments',\n\t\t'google-iap': 'Google Play In-App Payments',\n\t\tpaypal: 'PayPal',\n\t\tbraintree: 'Braintree',\n\t\tstripe: 'Stripe',\n\t\tfastspring: 'FastSpring',\n\t\tshopify: 'Shopify',\n\t\tsquare: 'Square',\n\t\t'2checkout': '2Checkout',\n\t\twepay: 'WePay',\n\t\tworldpay: 'WorldPay',\n\t\t'authorize-net': 'Authorize.net',\n\t\t'sage-pay': 'Sage Pay',\n\t\tgocardless: 'Go Cardless',\n\t\telavon: 'Elavon',\n\t\tverifone: 'Verifone',\n\t\tmoneris: 'Moneris',\n\t\twechat: 'WeChat',\n\t\talipay: 'Alipay',\n\t\tbank: 'Bank Transfer'\n\t},\n\tremarketing: {\n\t\t'google-ads': 'Google Ads (AdWords)',\n\t\ttwitter: 'Twitter',\n\t\tfacebook: 'Facebook',\n\t\tbing: 'Bing Ads',\n\t\tpinterest: 'Pinterest',\n\t\tadroll: 'AdRoll',\n\t\t'perfect-audience': 'Perfect Audience',\n\t\tappnexus: 'AppNexus'\n\t},\n\tproviders: {\n\t\trecaptcha: 'Invisible reCAPTCHA',\n\t\t'google-places': 'Google Places',\n\t\tmouseflow: 'Mouseflow',\n\t\tfreshdesk: 'FreshDesk'\n\t}\n} as const;\n\ntype PrivacyAnswers = {\n\tcore: LegalCoreAnswers;\n\tpersonalInfo: Array<'phone' | 'address' | 'email' | 'name' | 'social' | 'other'>;\n\tcontact: { methods: string[]; details: Record<string, unknown> };\n\ttracking: 'yes' | 'no';\n\ttrackingTools?: Array<keyof typeof mapLabels.tracking | string>;\n\tsendEmails: 'yes' | 'no';\n\temailPlatforms?: Array<keyof typeof mapLabels.emailPlatforms | string>;\n\tshowAds: 'yes' | 'no';\n\tadsPlatforms?: Array<keyof typeof mapLabels.ads | string>;\n\tcanPay: 'yes' | 'no';\n\tpaymentProcessors?: Array<keyof typeof mapLabels.payments | string>;\n\tremarketing: 'yes' | 'no';\n\tremarketingPlatforms?: Array<keyof typeof mapLabels.remarketing | string>;\n\tproviders?: Array<keyof typeof mapLabels.providers | string>;\n\tusStates: 'yes' | 'no';\n\tgdpr: 'yes' | 'no';\n\tfacebookFanPage?: 'yes' | 'no';\n\tfacebookDetails?: { name: string; url: string };\n\tkids: 'yes' | 'no';\n\tretention?: string;\n};\n\ntype Computed = {\n\tcompanyName: string;\n\tcompanyAddress: string;\n\twebsiteName: string;\n\twebsiteUrl: string;\n\tcountryText: string;\n\teffectiveDate: string;\n\tpiLabels: string[];\n\thasSocial: boolean;\n\ttrackingTools: string[];\n\temailPlatforms: string[];\n\tadsPlatforms: string[];\n\tpaymentProcessors: string[];\n\tremarketingPlatforms: string[];\n\tproviders: string[];\n\tretentionText: string;\n};\n\nconst compute = (a: PrivacyAnswers): Computed => {\n\tconst effectiveDate = new Date(Date.now()).toLocaleDateString('en-US', {\n\t\tyear: 'numeric',\n\t\tmonth: 'long',\n\t\tday: 'numeric'\n\t});\n\n\tconst piSelections = (a.personalInfo as string[] | undefined) ?? [];\n\tconst piLabels = piSelections.map(\n\t\t(v) => mapLabels.personalInfo[v as keyof typeof mapLabels.personalInfo] ?? v\n\t);\n\n\tconst lookup = <T extends Record<string, string>>(map: T, vs?: string[]) =>\n\t\t(vs ?? []).map((v) => map[v as keyof T] ?? v);\n\n\tconst companyName =\n\t\ta.core?.entityType === 'business'\n\t\t\t? (a.core?.businessName ?? a.core?.websiteName)\n\t\t\t: (a.core?.websiteName ?? 'Our Company');\n\tconst companyAddress = a.core?.entityType === 'business' ? (a.core?.businessAddress ?? '') : '';\n\tconst websiteName = a.core?.websiteName ?? 'our website';\n\tconst websiteUrl = a.core?.websiteUrl ?? '';\n\tconst countryText = `${a.core?.state ?? ''}${a.core?.state ? ', ' : ''}${a.core?.country ?? ''}`;\n\n\treturn {\n\t\tcompanyName,\n\t\tcompanyAddress,\n\t\twebsiteName,\n\t\twebsiteUrl,\n\t\tcountryText,\n\t\teffectiveDate,\n\t\tpiLabels,\n\t\thasSocial: piSelections.includes('social'),\n\t\ttrackingTools: lookup(mapLabels.tracking, a.trackingTools as string[] | undefined),\n\t\temailPlatforms: lookup(mapLabels.emailPlatforms, a.emailPlatforms as string[] | undefined),\n\t\tadsPlatforms: lookup(mapLabels.ads, a.adsPlatforms as string[] | undefined),\n\t\tpaymentProcessors: lookup(mapLabels.payments, a.paymentProcessors as string[] | undefined),\n\t\tremarketingPlatforms: lookup(\n\t\t\tmapLabels.remarketing,\n\t\t\ta.remarketingPlatforms as string[] | undefined\n\t\t),\n\t\tproviders: lookup(mapLabels.providers, a.providers as string[] | undefined),\n\t\tretentionText:\n\t\t\ta.retention && a.retention.trim().length > 0\n\t\t\t\t? a.retention.trim()\n\t\t\t\t: 'as long as is necessary to provide the Service and fulfil the purposes outlined in this Privacy Policy, and to comply with our legal obligations, resolve disputes, and enforce our agreements'\n\t};\n};\n\nconst sectionHeader = (c: Computed) =>\n\t`<section class=\"space-y-3\"><h1 class=\"text-3xl font-semibold\">Privacy Policy</h1><p class=\"text-base leading-7\">Last updated: ${escapeHtml(\n\t\tc.effectiveDate\n\t)}</p><p class=\"text-base leading-7\">This Privacy Policy describes the policies and procedures of ${escapeHtml(\n\t\tc.companyName\n\t)} (\"we\", \"us\", or \"our\") regarding the collection, use, and disclosure of your information when you use ${escapeHtml(\n\t\tc.websiteName\n\t)} (the \"Service\"), and tells you about your privacy rights and how applicable law protects you.</p><p class=\"text-base leading-7\">We use your personal data to provide and improve the Service. By using the Service, you agree to the collection and use of information in accordance with this Privacy Policy. If you do not agree with this Privacy Policy, please do not use the Service.</p></section>`;\n\nconst sectionDefinitions = (c: Computed) => {\n\tconst items: string[] = [];\n\tconst def = (term: string, body: string) =>\n\t\titems.push(`<li><p class=\"text-base leading-7\"><strong>${term}</strong> ${body}</p></li>`);\n\n\tdef(\n\t\t'Account',\n\t\t'means a unique account created for you to access our Service or parts of our Service.'\n\t);\n\tdef(\n\t\t'Affiliate',\n\t\t'means an entity that controls, is controlled by, or is under common control with a party, where \"control\" means ownership of 50% or more of the shares, equity interest, or other securities entitled to vote for election of directors or other managing authority.'\n\t);\n\tdef(\n\t\t'Business',\n\t\t`(referred to as either \"the Company\", \"We\", \"Us\", or \"Our\" in this Agreement) refers to ${escapeHtml(\n\t\t\tc.companyName\n\t\t)}${c.companyAddress ? `, ${escapeHtml(c.companyAddress)}` : ''}.`\n\t);\n\tdef(\n\t\t'Consumer',\n\t\t'for the purposes of U.S. state privacy laws, means a natural person who is a resident of a U.S. state with a comprehensive consumer privacy law.'\n\t);\n\tdef(\n\t\t'Cookies',\n\t\t'are small files that are placed on your computer, mobile device, or any other device by a website, containing details of your browsing history on that website among many other uses.'\n\t);\n\tdef('Country', `refers to: ${escapeHtml(c.countryText)}.`);\n\tdef(\n\t\t'Device',\n\t\t'means any device that can access the Service, such as a computer, a cellphone, or a digital tablet.'\n\t);\n\tdef(\n\t\t'Personal Data',\n\t\t'or Personal Information is any information that relates to an identified or identifiable individual, including any information that identifies, relates to, describes, or is reasonably capable of being associated with you.'\n\t);\n\tdef(\n\t\t'Sale',\n\t\t\"for the purposes of California, Colorado, Connecticut, Utah, and Virginia consumer privacy laws, means selling, renting, releasing, disclosing, disseminating, making available, transferring, or otherwise communicating orally, in writing, or by electronic means, a Consumer's Personal Information by the Business to a third party for valuable consideration.\"\n\t);\n\tdef(\n\t\t'Share',\n\t\t'for the purposes of the California Privacy Rights Act (\"CPRA\"), means sharing, renting, releasing, disclosing, disseminating, making available, transferring, or otherwise communicating orally, in writing, or by electronic or other means, a Consumer\\'s Personal Information by the Business to a third party for cross-context behavioral advertising, whether or not for monetary or other valuable consideration.'\n\t);\n\tdef(\n\t\t'Sensitive Personal Information',\n\t\t'has the meaning given in applicable U.S. state privacy laws (including the CPRA) and may include, where collected, government-issued identifiers, account log-in credentials, precise geolocation, racial or ethnic origin, religious beliefs, contents of communications, genetic data, biometric data, health information, and information concerning sex life or sexual orientation.'\n\t);\n\tdef(\n\t\t'Service',\n\t\t`refers to ${escapeHtml(c.websiteName)}, accessible from <a href=\"${escapeHtml(\n\t\t\tc.websiteUrl\n\t\t)}\" rel=\"external nofollow noopener\" target=\"_blank\">${escapeHtml(c.websiteUrl)}</a>.`\n\t);\n\tdef(\n\t\t'Service Provider',\n\t\t'means any natural or legal person who processes the data on behalf of the Company, including third-party companies or individuals employed by the Company to facilitate the Service.'\n\t);\n\tdef(\n\t\t'Third-party Social Media Service',\n\t\t'refers to any website or any social network website through which a user can log in or create an account to use the Service.'\n\t);\n\tdef(\n\t\t'Usage Data',\n\t\t'refers to data collected automatically, either generated by the use of the Service or from the Service infrastructure itself (for example, the duration of a page visit).'\n\t);\n\tdef(\n\t\t'You',\n\t\t'means the individual accessing or using the Service, or the company or other legal entity on behalf of which such individual is accessing or using the Service, as applicable.'\n\t);\n\n\tconst interpretation =\n\t\t'<p class=\"text-base leading-7\">The words of which the initial letter is capitalized have meanings defined under the following conditions. The following definitions shall have the same meaning regardless of whether they appear in singular or in plural.</p>';\n\tconst definitions = `<p class=\"text-base leading-7\">For the purposes of this Privacy Policy:</p><ul class=\"list-disc pl-6 space-y-1 text-base leading-7\">${items.join('')}</ul>`;\n\treturn `<section class=\"space-y-3\"><h2 class=\"text-xl font-semibold\">Interpretation and Definitions</h2><h3 class=\"text-lg font-semibold\">Interpretation</h3>${interpretation}<h3 class=\"text-lg font-semibold\">Definitions</h3>${definitions}</section>`;\n};\n\nconst sectionCategoriesCollected = (a: PrivacyAnswers, c: Computed) => {\n\tconst pi = (a.personalInfo as string[] | undefined) ?? [];\n\tconst internetActivity = a.tracking === 'yes' || (a.providers ?? []).length > 0;\n\tconst body = ccpaCategoriesTable({\n\t\tidentifiers: true,\n\t\tcustomerRecords: pi.includes('name') || pi.includes('address') || pi.includes('phone'),\n\t\tcommercialInfo: a.canPay === 'yes',\n\t\tinternetActivity,\n\t\tgeolocation: pi.includes('address'),\n\t\tsensitive: false\n\t});\n\n\tconst personal = `<h4 class=\"font-semibold\">Personal Data</h4><p class=\"text-base leading-7\">While using our Service, we may ask you to provide us with certain personally identifiable information that can be used to contact or identify you. Personally identifiable information may include, but is not limited to:</p>${list(\n\t\t(c.piLabels.length\n\t\t\t? c.piLabels\n\t\t\t: [\n\t\t\t\t\t'Email address',\n\t\t\t\t\t'First name and last name',\n\t\t\t\t\t'Phone number',\n\t\t\t\t\t'Address, State, Province, ZIP/Postal code, City',\n\t\t\t\t\t'Usage Data'\n\t\t\t\t]\n\t\t).map(escapeHtml)\n\t)}`;\n\n\tconst usage = `<h4 class=\"font-semibold\">Usage Data</h4><p class=\"text-base leading-7\">Usage Data is collected automatically when using the Service. It may include information such as your device\u2019s Internet Protocol address (e.g. IP address), browser type and version, the pages of our Service that you visit, the time and date of your visit, the time spent on those pages, unique device identifiers, and other diagnostic data.</p><p class=\"text-base leading-7\">When you access the Service by or through a mobile device, we may collect certain information automatically, including, but not limited to, the type of mobile device you use, your mobile device\u2019s unique ID, the IP address of your mobile device, your mobile operating system, the type of mobile Internet browser you use, unique device identifiers, and other diagnostic data.</p>`;\n\n\tlet social = '';\n\tif (c.hasSocial) {\n\t\tsocial = `<h4 class=\"font-semibold\">Information from Third-Party Social Media Services</h4><p class=\"text-base leading-7\">The Company allows you to create an account and log in to use the Service through Third-party Social Media Services such as Google, Facebook, Instagram, X (formerly Twitter), or LinkedIn. If you decide to register through or otherwise grant us access to a Third-party Social Media Service, we may collect personal data associated with your account, such as your name, email address, activities, or contact list.</p><p class=\"text-base leading-7\">You may also have the option of sharing additional information with the Company through your Third-party Social Media Service\u2019s account. If you choose to provide such information and Personal Data, during registration or otherwise, you are giving the Company permission to use, share, and store it in a manner consistent with this Privacy Policy.</p>`;\n\t}\n\n\treturn `<section class=\"space-y-3\"><h2 class=\"text-xl font-semibold\">Personal Information We Collect</h2>${applyTypography(\n\t\tbody\n\t)}${applyTypography(personal)}${applyTypography(usage)}${applyTypography(social)}</section>`;\n};\n\nconst sectionSources = () =>\n\ttitledSection(\n\t\t'Sources of Personal Information',\n\t\t`<p>We collect personal information from the following categories of sources:</p><ul><li><strong>Directly from you</strong> when you provide information to us, for example by creating an account, completing a form, contacting us, or making a purchase.</li><li><strong>Automatically</strong> as you navigate through the Service, including through cookies, log files, and similar tracking technologies.</li><li><strong>From third parties</strong>, such as analytics providers, advertising networks, payment processors, and Third-party Social Media Services that you use to log in.</li><li><strong>From publicly available sources</strong>, such as public records, public profile information, and public databases.</li><li><strong>From service providers and business partners</strong> that help us operate or improve the Service.</li></ul>`\n\t);\n\nconst sectionUse = (a: PrivacyAnswers, c: Computed) => {\n\tconst useBullets: string[] = [\n\t\t'<strong>To provide and maintain our Service,</strong> including to monitor the usage of our Service and to detect, prevent, and address technical issues.',\n\t\t'<strong>To manage your Account:</strong> to manage your registration as a user of the Service. The Personal Data you provide can give you access to different functionalities of the Service available to you as a registered user.'\n\t];\n\tif (a.canPay === 'yes') {\n\t\tuseBullets.push(\n\t\t\t'<strong>For the performance of a contract:</strong> the development, compliance, and undertaking of the purchase contract for products, items, or services you have purchased or of any other contract with us through the Service.'\n\t\t);\n\t}\n\tuseBullets.push(\n\t\t'<strong>To contact you:</strong> to contact you by email, telephone calls, SMS, or other equivalent forms of electronic communication, such as a mobile application\u2019s push notifications, regarding updates or informative communications related to the functionalities, products, or contracted services, including the security updates, when necessary or reasonable for their implementation.'\n\t);\n\tif (a.sendEmails === 'yes') {\n\t\tuseBullets.push(\n\t\t\t'<strong>To provide you</strong> with news, special offers, and general information about goods, services, and events that we offer, unless you have opted not to receive such information.'\n\t\t);\n\t}\n\tuseBullets.push(\n\t\t'<strong>To manage your requests:</strong> to attend to and manage your requests to us.',\n\t\t'<strong>For business transfers:</strong> we may use your information to evaluate or conduct a merger, divestiture, restructuring, reorganization, dissolution, or other sale or transfer of some or all of our assets, whether as a going concern or as part of bankruptcy, liquidation, or similar proceedings, in which Personal Data held by us about our Service users is among the assets transferred.',\n\t\t'<strong>For analytics and improvement:</strong> for data analysis, identifying usage trends, determining the effectiveness of our promotional campaigns, and improving our Service, products, services, marketing, and your experience.',\n\t\t'<strong>For security and fraud prevention:</strong> to protect the rights, property, or safety of the Company, our users, or others, including detecting, preventing, and responding to fraud, abuse, security risks, and technical issues.',\n\t\t'<strong>To comply with legal obligations:</strong> to comply with applicable laws, lawful requests, court orders, and legal processes.'\n\t);\n\n\tlet body = `<p class=\"text-base leading-7\">The Company may use Personal Data for the following purposes:</p>${list(useBullets)}`;\n\tif (a.showAds === 'yes') {\n\t\tbody += `<p class=\"text-base leading-7\">We may display advertising on the Service${\n\t\t\tc.adsPlatforms.length ? ' using the following platforms:' : '.'\n\t\t}</p>${c.adsPlatforms.length ? list(c.adsPlatforms.map(escapeHtml)) : ''}`;\n\t}\n\tif (a.canPay === 'yes' && c.paymentProcessors.length) {\n\t\tbody += `<p class=\"text-base leading-7\">If you make purchases, we may process payments via the following providers, who handle your payment information in accordance with their own privacy policies:</p>${list(\n\t\t\tc.paymentProcessors.map(escapeHtml)\n\t\t)}`;\n\t}\n\n\treturn titledSection('How We Use Your Personal Information', body);\n};\n\nconst sectionLegalBases = () =>\n\ttitledSection('Legal Bases for Processing (EEA, UK, Switzerland)', legalBasesBlock());\n\nconst sectionShare = (a: PrivacyAnswers, c: Computed) => {\n\tlet body =\n\t\t'<p>We may share your personal information in the following situations and with the following categories of recipients:</p><ul>';\n\tbody +=\n\t\t'<li><strong>With Service Providers:</strong> to monitor and analyze the use of our Service, host the Service, process payments, send emails, provide customer support, and contact you. These providers have access to your Personal Information only to perform these tasks on our behalf and are obligated not to disclose or use it for any other purpose.</li>';\n\tbody +=\n\t\t'<li><strong>For business transfers:</strong> we may share or transfer your Personal Information in connection with, or during negotiations of, any merger, sale of Company assets, financing, or acquisition of all or a portion of our business to another company.</li>';\n\tbody +=\n\t\t'<li><strong>With Affiliates:</strong> we may share your information with our affiliates, in which case we will require those affiliates to honor this Privacy Policy.</li>';\n\tbody +=\n\t\t'<li><strong>With business partners:</strong> we may share your information with our business partners to offer you certain products, services, or promotions.</li>';\n\tbody +=\n\t\t'<li><strong>With other users:</strong> when you share personal information or otherwise interact in public areas with other users, such information may be viewed by all users and may be publicly distributed outside.</li>';\n\tbody +=\n\t\t'<li><strong>For legal reasons:</strong> we may disclose your information where we believe in good faith that it is necessary to comply with a legal obligation, to protect our rights or property, to prevent fraud or harm, or to enforce our terms.</li>';\n\tbody += '<li><strong>With your consent:</strong> for any other purpose with your consent.</li>';\n\tbody += '</ul>';\n\tif (c.providers.length) {\n\t\tbody += `<p>We currently use the following service providers:</p>${list(c.providers.map(escapeHtml))}`;\n\t}\n\tvoid a;\n\treturn titledSection('How We Share or Disclose Personal Information', body);\n};\n\nconst sectionSaleSharing = (a: PrivacyAnswers, c: Computed) => {\n\tconst sells = a.showAds === 'yes' || a.remarketing === 'yes';\n\tconst intro = sells\n\t\t? `<p>For purposes of certain U.S. state privacy laws (including the California Consumer Privacy Act, as amended by the California Privacy Rights Act, and the Virginia, Colorado, Connecticut, Utah, Texas, and Oregon consumer privacy laws), our use of cookies, pixels, and similar advertising and analytics technologies \u2014 including for cross-context behavioral advertising and targeted advertising \u2014 may be considered a \"sale\" or \"share\" of personal information. The categories of personal information involved typically include online identifiers, IP addresses, internet or other electronic network activity information, and inferences derived from this information.</p>`\n\t\t: '<p>We do not \"sell\" your personal information for monetary consideration. We do not \"share\" your personal information for cross-context behavioral advertising as those terms are defined under the California Privacy Rights Act (\"CPRA\") or comparable U.S. state privacy laws. We do not knowingly sell or share personal information of consumers under 16 years of age.</p>';\n\n\tlet recipients = '';\n\tif (sells) {\n\t\tconst partners = [...c.adsPlatforms, ...c.remarketingPlatforms];\n\t\tconst list_ = partners.length\n\t\t\t? `<p>The categories of third parties to which we may disclose personal information for these purposes include advertising networks, analytics providers, and marketing partners, including:</p>${list(\n\t\t\t\t\tpartners.map(escapeHtml)\n\t\t\t\t)}`\n\t\t\t: '<p>The categories of third parties to which we may disclose personal information for these purposes include advertising networks, analytics providers, social media platforms, and marketing partners.</p>';\n\t\trecipients = list_;\n\t}\n\n\tconst optOut = `<p><strong>Your right to opt out.</strong> You have the right to opt out of the sale or sharing of your personal information at any time. To exercise this right, you may use the controls described in the \"Tracking Technologies and Cookies\" section, change the privacy settings in your browser or mobile device, contact us using the methods listed in the \"Contact Us\" section, or send an opt-out preference signal \u2014 we honor the Global Privacy Control (\"GPC\") signal as a request to opt out of sale and sharing for the browser or device on which the signal is detected.</p>`;\n\n\treturn titledSection(\n\t\t'Sale or Sharing of Personal Information; Targeted Advertising',\n\t\t`${intro}${recipients}${optOut}`\n\t);\n};\n\nconst sectionCookies = (a: PrivacyAnswers, c: Computed) => {\n\tlet body = `<p>We use Cookies and similar tracking technologies (such as web beacons, pixels, tags, scripts, and software development kits) to track the activity on our Service and hold certain information.</p><p>Cookies can be \"Persistent\" or \"Session\" Cookies. Persistent Cookies remain on your personal computer or mobile device when you go offline, while Session Cookies are deleted as soon as you close your web browser.</p><h4>Categories of Cookies We Use</h4><ul><li><strong>Strictly Necessary Cookies.</strong> These are required for the operation of the Service and to provide functionalities you request, such as logging in or accessing secure areas. The Service cannot function properly without them.</li><li><strong>Performance / Analytics Cookies.</strong> These cookies allow us to count visits and traffic sources so we can measure and improve the performance of the Service.</li><li><strong>Functional Cookies.</strong> These cookies enable enhanced functionality and personalization, such as remembering your preferences.</li><li><strong>Targeting / Advertising Cookies.</strong> These cookies may be set through our Service by our advertising partners to build a profile of your interests and show you relevant advertisements on other sites.</li><li><strong>Cookies Policy / Notice Acceptance Cookies.</strong> These cookies identify whether users have accepted the use of cookies on the Service.</li></ul>`;\n\tif (a.tracking === 'yes' && c.trackingTools.length) {\n\t\tbody += `<p>We currently use the following analytics and tracking tools:</p>${list(c.trackingTools.map(escapeHtml))}`;\n\t}\n\tbody += `<h4>Your Choices About Cookies</h4><p>You can instruct your browser to refuse all Cookies or to indicate when a Cookie is being sent. If you do not accept Cookies, you may not be able to use some parts of our Service. You can also manage your cookie preferences through any cookie banner or preference center we provide.</p><h4>Do Not Track and Global Privacy Control</h4><p>Some browsers transmit \"Do Not Track\" (\"DNT\") or Global Privacy Control (\"GPC\") signals. There is currently no industry standard for responding to DNT signals, but we honor GPC signals as an opt-out of the sale or sharing of personal information for the browser or device on which the signal is detected, as required by applicable law.</p>`;\n\treturn titledSection('Tracking Technologies and Cookies', body);\n};\n\nconst sectionEmail = (a: PrivacyAnswers, c: Computed) =>\n\ta.sendEmails === 'yes'\n\t\t? titledSection(\n\t\t\t\t'Email Communications',\n\t\t\t\tc.emailPlatforms.length\n\t\t\t\t\t? `<p>We may send transactional, account-related, and (where you have opted in) marketing emails using the following platforms, who process email information on our behalf as service providers:</p>${list(\n\t\t\t\t\t\t\tc.emailPlatforms.map(escapeHtml)\n\t\t\t\t\t\t)}<p>You may unsubscribe from marketing emails at any time using the unsubscribe link included in those emails. Even if you unsubscribe from marketing emails, we may still send you transactional or account-related emails (for example, to confirm a purchase or notify you of changes to the Service).</p>`\n\t\t\t\t\t: '<p>We may send you transactional, account-related, and (where you have opted in) marketing emails. You may unsubscribe from marketing emails at any time using the unsubscribe link included in those emails.</p>'\n\t\t\t)\n\t\t: '';\n\nconst sectionRemarketing = (a: PrivacyAnswers, c: Computed) =>\n\ta.remarketing === 'yes'\n\t\t? titledSection(\n\t\t\t\t'Remarketing and Targeted Advertising',\n\t\t\t\tc.remarketingPlatforms.length\n\t\t\t\t\t? `<p>We use remarketing services to advertise to visitors of our Service on third-party websites and applications after they have visited the Service. These services may use cookies and similar technologies to deliver advertisements based on your past visits. The remarketing services we use include:</p>${list(\n\t\t\t\t\t\t\tc.remarketingPlatforms.map(escapeHtml)\n\t\t\t\t\t\t)}<p>You may opt out of personalized advertising by visiting the Network Advertising Initiative opt-out page (<a href=\"https://www.networkadvertising.org/choices/\" rel=\"external nofollow noopener\" target=\"_blank\">https://www.networkadvertising.org/choices/</a>), the Digital Advertising Alliance opt-out page (<a href=\"https://www.aboutads.info/choices/\" rel=\"external nofollow noopener\" target=\"_blank\">https://www.aboutads.info/choices/</a>), or the European Interactive Digital Advertising Alliance (<a href=\"https://www.youronlinechoices.eu\" rel=\"external nofollow noopener\" target=\"_blank\">https://www.youronlinechoices.eu</a>).</p>`\n\t\t\t\t\t: '<p>We use remarketing services to advertise to visitors of our Service on third-party websites and applications after they have visited the Service.</p>'\n\t\t\t)\n\t\t: '';\n\nconst sectionRetention = (c: Computed) =>\n\ttitledSection(\n\t\t'Retention of Your Personal Information',\n\t\t`<p>The Company will retain your Personal Information ${escapeHtml(\n\t\t\tc.retentionText\n\t\t)}. We will retain and use your Personal Information to the extent necessary to comply with our legal obligations (for example, if we are required to retain your data to comply with applicable laws), resolve disputes, and enforce our agreements and policies.</p><p>The Company will also retain Usage Data for internal analysis purposes. Usage Data is generally retained for a shorter period of time, except when this data is used to strengthen the security or to improve the functionality of our Service, or we are legally obligated to retain this data for longer periods.</p><p>When we no longer have a legitimate business need to process your Personal Information, we will either delete or anonymize it or, if this is not possible (for example, because your Personal Information has been stored in backup archives), we will securely store your Personal Information and isolate it from any further processing until deletion is possible.</p>`\n\t);\n\nconst sectionTransfers = () =>\n\ttitledSection('International Data Transfers', internationalTransfersBlock());\n\nconst sectionSecurity = () =>\n\ttitledSection(\n\t\t'Data Security',\n\t\t'<p>The security of your Personal Information is important to us, and we use commercially reasonable administrative, technical, and organizational measures designed to protect Personal Information against unauthorized access, alteration, disclosure, or destruction. However, no method of transmission over the Internet or method of electronic storage is 100% secure. While we strive to use commercially acceptable means to protect your Personal Information, we cannot guarantee its absolute security.</p>'\n\t);\n\nconst sectionAutomated = () =>\n\ttitledSection(\n\t\t'Automated Decision-Making',\n\t\t'<p>We do not use your Personal Information to make decisions based solely on automated processing \u2014 including profiling \u2014 that produce legal effects concerning you or similarly significantly affect you, except as may be necessary for entering into or performing a contract with you, where authorized by applicable law, or where you have given your explicit consent. If we ever do, we will provide meaningful information about the logic involved and the significance and envisaged consequences of such processing, and you may request human review of any such decision.</p>'\n\t);\n\nconst sectionRights = (a: PrivacyAnswers, c: Computed) => {\n\tconst intro =\n\t\t'<p>This section describes your privacy rights under applicable laws and how to exercise them. Even if a particular section does not apply to you, you may always contact us using the methods in the \"Contact Us\" section to ask about your privacy choices.</p>';\n\tlet body = intro;\n\tif (a.usStates === 'yes') {\n\t\tbody += subSection('U.S. State Privacy Rights', usStateRightsBlock(c.companyName));\n\t}\n\tif (a.gdpr === 'yes') {\n\t\tconst fan =\n\t\t\ta.facebookFanPage === 'yes' && a.facebookDetails\n\t\t\t\t? { name: a.facebookDetails.name ?? '', url: a.facebookDetails.url ?? '' }\n\t\t\t\t: null;\n\t\tbody += subSection(\n\t\t\t'EEA, UK, and Swiss Privacy Rights (GDPR)',\n\t\t\tgdprRightsBlock(c.companyName, fan)\n\t\t);\n\t}\n\tbody += subSection(\n\t\t'Right to Delete',\n\t\t'<p>You have the right to delete or request that we assist in deleting Personal Information that we have collected about you. Our Service may give you the ability to delete certain information from within the Service. You may also contact us to request access to, correct, or delete any personal information that you have provided to us. We may need to retain certain information when we have a legal obligation or lawful basis to do so.</p>'\n\t);\n\treturn titledSection('Your Privacy Rights', body);\n};\n\nconst sectionChildren = (a: PrivacyAnswers) => {\n\tlet body =\n\t\t'<p>Our Service is not directed to children under the age of 13 (or such higher age threshold as required by applicable law, including 16 for residents of certain jurisdictions). We do not knowingly collect Personal Information from children under 13. If you are a parent or guardian and you become aware that your child has provided us with Personal Information without your consent, please contact us so that we can take appropriate action. If we become aware that we have collected Personal Information from a child under 13 without verification of parental consent, we will take steps to remove that information from our servers.</p><p>For users in the European Economic Area, the United Kingdom, or other jurisdictions where consent from a parent or legal guardian is required for the processing of personal data of minors, we will not knowingly collect or process such data without the appropriate consent.</p>';\n\tif (a.kids === 'yes') {\n\t\tbody +=\n\t\t\t'<p><strong>Verifiable parental consent.</strong> Where we knowingly collect Personal Information from a child under 13, we will obtain verifiable parental consent before collection in accordance with the Children\u2019s Online Privacy Protection Act (\"COPPA\"). Parents may review the Personal Information collected from their child, request that we delete such information, and refuse to permit further collection or use of the child\u2019s Personal Information by contacting us using the methods in the \"Contact Us\" section.</p>';\n\t}\n\treturn titledSection('Children\u2019s Privacy', body);\n};\n\nconst sectionLinks = () =>\n\ttitledSection(\n\t\t'Links to Other Websites',\n\t\t'<p>Our Service may contain links to other websites that are not operated by us. If you click on a third-party link, you will be directed to that third party\u2019s site. We strongly advise you to review the privacy policy of every site you visit. We have no control over and assume no responsibility for the content, privacy policies, or practices of any third-party sites or services.</p>'\n\t);\n\nconst sectionChanges = () =>\n\ttitledSection(\n\t\t'Changes to This Privacy Policy',\n\t\t'<p>We may update this Privacy Policy from time to time. We will notify you of any material changes by posting the new Privacy Policy on this page and updating the \"Last updated\" date at the top of this Privacy Policy. Where required by law, we will provide a more prominent notice or seek your consent. You are advised to review this Privacy Policy periodically for any changes. Changes to this Privacy Policy are effective when they are posted on this page.</p>'\n\t);\n\nconst sectionContact = (a: PrivacyAnswers) => {\n\tconst items: string[] = [];\n\tif (a.contact?.methods?.includes('email') && a.contact.details.email) {\n\t\titems.push(\n\t\t\t`By email: <a href=\"mailto:${escapeHtml(a.contact.details.email)}\">${escapeHtml(\n\t\t\t\ta.contact.details.email\n\t\t\t)}</a>`\n\t\t);\n\t}\n\tif (a.contact?.methods?.includes('page') && a.contact.details.page) {\n\t\titems.push(\n\t\t\t`By visiting this page on our website: <a href=\"${escapeHtml(\n\t\t\t\ta.contact.details.page\n\t\t\t)}\" rel=\"external nofollow noopener\" target=\"_blank\">${escapeHtml(a.contact.details.page)}</a>`\n\t\t);\n\t}\n\tif (a.contact?.methods?.includes('phone') && a.contact.details.phone) {\n\t\titems.push(`By phone number: ${escapeHtml(a.contact.details.phone)}`);\n\t}\n\tif (a.contact?.methods?.includes('mail') && a.contact.details.address) {\n\t\titems.push(`By mail: ${escapeHtml(a.contact.details.address)}`);\n\t}\n\treturn `<section class=\"space-y-3\"><h2 class=\"text-xl font-semibold\">Contact Us</h2><p class=\"text-base leading-7\">If you have any questions about this Privacy Policy, you can contact us:</p>${list(items)}</section>`;\n};\n\nexport const generatePrivacyHtml = (answers: PrivacyAnswers) => {\n\tconst c = compute(answers);\n\n\tconst sections: string[] = [\n\t\tsectionHeader(c),\n\t\tsectionDefinitions(c),\n\t\tsectionCategoriesCollected(answers, c),\n\t\tsectionSources(),\n\t\tsectionUse(answers, c),\n\t\tsectionLegalBases(),\n\t\tsectionShare(answers, c),\n\t\tsectionSaleSharing(answers, c),\n\t\tsectionCookies(answers, c),\n\t\tsectionEmail(answers, c),\n\t\tsectionRemarketing(answers, c),\n\t\tsectionRetention(c),\n\t\tsectionTransfers(),\n\t\tsectionSecurity(),\n\t\tsectionAutomated(),\n\t\tsectionRights(answers, c),\n\t\tsectionChildren(answers),\n\t\tsectionLinks(),\n\t\tsectionChanges(),\n\t\tsectionContact(answers)\n\t].filter(Boolean);\n\n\treturn `<section data-role=\"content\">${sections.join('')}</section>`;\n};\n\nasync function promptWithCustom(\n\tmessage: string,\n\toptions: Array<{ value: string; label: string }>,\n\tcustomMessage: string\n): Promise<string[]> {\n\tconst selection = await p.multiselect({ message, options });\n\tif (p.isCancel(selection)) onCancel();\n\tconst values = selection as string[];\n\tif (values.includes('custom')) {\n\t\tconst custom = await p.text({ message: customMessage });\n\t\tif (p.isCancel(custom)) onCancel();\n\t\tconst idx = values.indexOf('custom');\n\t\tif (idx !== -1) values.splice(idx, 1);\n\t\tif (custom) values.push(String(custom));\n\t}\n\treturn values;\n}\n\nasync function privacyAction(): Promise<void> {\n\tconst { workspaceRootDir, publicRoutesDir } = await getWorkspace();\n\n\tconst core = await p.group(\n\t\t{\n\t\t\twebsiteUrl: sharedFields.websiteUrl,\n\t\t\twebsiteName: sharedFields.websiteName,\n\t\t\tentityType: sharedFields.entityType,\n\t\t\tbusinessName: sharedFields.businessName,\n\t\t\tbusinessAddress: sharedFields.businessAddress,\n\t\t\tcountry: sharedFields.country,\n\t\t\tstate: sharedFields.state\n\t\t},\n\t\t{ onCancel }\n\t);\n\n\tconst personalInfo = await p.multiselect({\n\t\tmessage: 'What kind of personal information do you collect from users? Check all that apply',\n\t\toptions: [\n\t\t\t{ value: 'email', label: 'Email address' },\n\t\t\t{ value: 'name', label: 'First name and last name' },\n\t\t\t{ value: 'phone', label: 'Phone number' },\n\t\t\t{ value: 'address', label: 'Address, State, Province, ZIP/Postal code, City' },\n\t\t\t{\n\t\t\t\tvalue: 'social',\n\t\t\t\tlabel:\n\t\t\t\t\t'Social Media Profile information (ie. from Connect with Facebook, Sign In With Twitter)'\n\t\t\t},\n\t\t\t{ value: 'other', label: 'Others' }\n\t\t],\n\t\trequired: false\n\t});\n\tif (p.isCancel(personalInfo)) onCancel();\n\n\tconst contact = await contactMethods('privacy');\n\n\tconst tracking = await p.select({\n\t\tmessage: 'Do you use tracking and/or analytics tools, such as Google Analytics?',\n\t\toptions: [\n\t\t\t{ value: 'yes', label: 'Yes, we use Google Analytics or other related tools' },\n\t\t\t{ value: 'no', label: 'No' }\n\t\t]\n\t});\n\tif (p.isCancel(tracking)) onCancel();\n\n\tlet trackingTools: string[] | undefined;\n\tif (tracking === 'yes') {\n\t\ttrackingTools = await promptWithCustom(\n\t\t\t'Select the tools you use for tracking and/or analytics',\n\t\t\t[\n\t\t\t\t{ value: 'ga', label: 'Google Analytics' },\n\t\t\t\t{ value: 'firebase', label: 'Firebase' },\n\t\t\t\t{ value: 'matomo', label: 'Matomo (formely Piwik)' },\n\t\t\t\t{ value: 'clicky', label: 'Clicky' },\n\t\t\t\t{ value: 'statcounter', label: 'Statcounter' },\n\t\t\t\t{ value: 'flurry', label: 'Flurry Analytics' },\n\t\t\t\t{ value: 'mixpanel', label: 'Mixpanel' },\n\t\t\t\t{ value: 'unity', label: 'Unity Analytics' },\n\t\t\t\t{ value: 'custom', label: 'Add your own' }\n\t\t\t],\n\t\t\t'Enter your custom tracking/analytics tool name'\n\t\t);\n\t}\n\n\tconst sendEmails = await p.select({\n\t\tmessage: 'Do you send emails to users?',\n\t\toptions: [\n\t\t\t{\n\t\t\t\tvalue: 'yes',\n\t\t\t\tlabel: 'Yes, we send emails to users or users can opt-in to receive emails from us'\n\t\t\t},\n\t\t\t{ value: 'no', label: 'No' }\n\t\t]\n\t});\n\tif (p.isCancel(sendEmails)) onCancel();\n\n\tlet emailPlatforms: string[] | undefined;\n\tif (sendEmails === 'yes') {\n\t\temailPlatforms = await promptWithCustom(\n\t\t\t'Select the platforms you use to send emails',\n\t\t\t[\n\t\t\t\t{ value: 'mailchimp', label: 'Mailchimp' },\n\t\t\t\t{ value: 'constant-contact', label: 'Constant Contact' },\n\t\t\t\t{ value: 'aweber', label: 'AWeber' },\n\t\t\t\t{ value: 'getresponse', label: 'GetResponse' },\n\t\t\t\t{ value: 'custom', label: 'Add your own' }\n\t\t\t],\n\t\t\t'Enter your custom email platform'\n\t\t);\n\t}\n\n\tconst showAds = await p.select({\n\t\tmessage: 'Do you show ads?',\n\t\toptions: [\n\t\t\t{ value: 'yes', label: 'Yes, we show ads' },\n\t\t\t{ value: 'no', label: 'No' }\n\t\t]\n\t});\n\tif (p.isCancel(showAds)) onCancel();\n\n\tlet adsPlatforms: string[] | undefined;\n\tif (showAds === 'yes') {\n\t\tadsPlatforms = await promptWithCustom(\n\t\t\t'Select the platforms you use to show ads',\n\t\t\t[\n\t\t\t\t{ value: 'adsense', label: 'Google Ads (AdSense)' },\n\t\t\t\t{ value: 'admob', label: 'AdMob by Google' },\n\t\t\t\t{ value: 'bing', label: 'Bing Ads' },\n\t\t\t\t{ value: 'flurry', label: 'Flurry' },\n\t\t\t\t{ value: 'inmobi', label: 'InMobi' },\n\t\t\t\t{ value: 'mopub', label: 'MoPub' },\n\t\t\t\t{ value: 'startapp', label: 'StartApp' },\n\t\t\t\t{ value: 'adcolony', label: 'AdColony' },\n\t\t\t\t{ value: 'applovin', label: 'AppLovin' },\n\t\t\t\t{ value: 'vungle', label: 'Vungle' },\n\t\t\t\t{ value: 'adbutler', label: 'AdButler' },\n\t\t\t\t{ value: 'unity-ads', label: 'Unity Ads' },\n\t\t\t\t{ value: 'custom', label: 'Add your own' }\n\t\t\t],\n\t\t\t'Enter your custom ads platform'\n\t\t);\n\t}\n\n\tconst canPay = await p.select({\n\t\tmessage: 'Can users pay for products or services?',\n\t\toptions: [\n\t\t\t{ value: 'yes', label: 'Yes, users can pay for our products/services' },\n\t\t\t{\n\t\t\t\tvalue: 'no',\n\t\t\t\tlabel: 'No, we do not sell anything or allow users to pay for products/services'\n\t\t\t}\n\t\t]\n\t});\n\tif (p.isCancel(canPay)) onCancel();\n\n\tlet paymentProcessors: string[] | undefined;\n\tif (canPay === 'yes') {\n\t\tpaymentProcessors = await promptWithCustom(\n\t\t\t'Select the payment processors/methods',\n\t\t\t[\n\t\t\t\t{ value: 'apple-iap', label: 'Apple Store In-App Payments' },\n\t\t\t\t{ value: 'google-iap', label: 'Google Play In-App Payments' },\n\t\t\t\t{ value: 'paypal', label: 'PayPal' },\n\t\t\t\t{ value: 'braintree', label: 'Braintree' },\n\t\t\t\t{ value: 'stripe', label: 'Stripe' },\n\t\t\t\t{ value: 'fastspring', label: 'FastSpring' },\n\t\t\t\t{ value: 'shopify', label: 'Shopify' },\n\t\t\t\t{ value: 'square', label: 'Square' },\n\t\t\t\t{ value: '2checkout', label: '2Checkout' },\n\t\t\t\t{ value: 'wepay', label: 'WePay' },\n\t\t\t\t{ value: 'worldpay', label: 'WorldPay' },\n\t\t\t\t{ value: 'authorize-net', label: 'Authorize.net' },\n\t\t\t\t{ value: 'sage-pay', label: 'Sage Pay' },\n\t\t\t\t{ value: 'gocardless', label: 'Go Cardless' },\n\t\t\t\t{ value: 'elavon', label: 'Elavon' },\n\t\t\t\t{ value: 'verifone', label: 'Verifone' },\n\t\t\t\t{ value: 'moneris', label: 'Moneris' },\n\t\t\t\t{ value: 'wechat', label: 'WeChat' },\n\t\t\t\t{ value: 'alipay', label: 'Alipay' },\n\t\t\t\t{ value: 'bank', label: 'Bank Transfer' },\n\t\t\t\t{ value: 'custom', label: 'Add your own' }\n\t\t\t],\n\t\t\t'Enter your custom payment processor/method'\n\t\t);\n\t}\n\n\tconst remarketing = await p.select({\n\t\tmessage: 'Do you use remarketing services for marketing & advertising purposes?',\n\t\toptions: [\n\t\t\t{ value: 'yes', label: 'Yes, we use remarketing services to advertise our business' },\n\t\t\t{ value: 'no', label: 'No' }\n\t\t]\n\t});\n\tif (p.isCancel(remarketing)) onCancel();\n\n\tlet remarketingPlatforms: string[] | undefined;\n\tif (remarketing === 'yes') {\n\t\tremarketingPlatforms = await promptWithCustom(\n\t\t\t'Select the platforms you use for remarketing purposes',\n\t\t\t[\n\t\t\t\t{ value: 'google-ads', label: 'Google Ads (AdWords)' },\n\t\t\t\t{ value: 'twitter', label: 'Twitter' },\n\t\t\t\t{ value: 'facebook', label: 'Facebook' },\n\t\t\t\t{ value: 'bing', label: 'Bing Ads' },\n\t\t\t\t{ value: 'pinterest', label: 'Pinterest' },\n\t\t\t\t{ value: 'adroll', label: 'AdRoll' },\n\t\t\t\t{ value: 'perfect-audience', label: 'Perfect Audience' },\n\t\t\t\t{ value: 'appnexus', label: 'AppNexus' },\n\t\t\t\t{ value: 'custom', label: 'Add your own' }\n\t\t\t],\n\t\t\t'Enter your custom remarketing platform'\n\t\t);\n\t}\n\n\tconst providersRaw = await p.multiselect({\n\t\tmessage: 'Select if you use any of the following providers',\n\t\toptions: [\n\t\t\t{ value: 'recaptcha', label: 'Invisible reCAPTCHA' },\n\t\t\t{ value: 'google-places', label: 'Google Places' },\n\t\t\t{ value: 'mouseflow', label: 'Mouseflow' },\n\t\t\t{ value: 'freshdesk', label: 'FreshDesk' },\n\t\t\t{ value: 'custom', label: 'Add your own' }\n\t\t],\n\t\trequired: false\n\t});\n\tif (p.isCancel(providersRaw)) onCancel();\n\n\tconst providers = providersRaw as string[];\n\tif (providers.includes('custom')) {\n\t\tconst custom = await p.text({ message: 'Enter your custom provider' });\n\t\tif (p.isCancel(custom)) onCancel();\n\t\tconst idx = providers.indexOf('custom');\n\t\tif (idx !== -1) providers.splice(idx, 1);\n\t\tif (custom) providers.push(String(custom));\n\t}\n\n\tconst usStates = await p.select({\n\t\tmessage:\n\t\t\t'Include U.S. state privacy rights (CCPA/CPRA, VCDPA, CPA, CTDPA, UCPA, TX, OR, etc.)?',\n\t\toptions: [\n\t\t\t{\n\t\t\t\tvalue: 'yes',\n\t\t\t\tlabel: 'Yes. Include comprehensive U.S. state privacy rights and disclosures'\n\t\t\t},\n\t\t\t{ value: 'no', label: 'No' }\n\t\t],\n\t\tinitialValue: 'yes'\n\t});\n\tif (p.isCancel(usStates)) onCancel();\n\n\tconst gdpr = await p.select({\n\t\tmessage: 'Do you want your Privacy Policy to include GDPR / UK GDPR wording?',\n\t\toptions: [\n\t\t\t{ value: 'yes', label: 'Yes. Include GDPR rights for EEA, UK, and Swiss residents' },\n\t\t\t{ value: 'no', label: 'No' }\n\t\t]\n\t});\n\tif (p.isCancel(gdpr)) onCancel();\n\n\tlet facebookFanPage: 'yes' | 'no' = 'no';\n\tconst facebookDetails: { name: string; url: string } = { name: '', url: '' };\n\tif (gdpr === 'yes') {\n\t\tconst fan = await p.select({\n\t\t\tmessage: 'Do you have a Facebook Fan Page?',\n\t\t\toptions: [\n\t\t\t\t{ value: 'yes', label: 'Yes, we have a Facebook Fan Page' },\n\t\t\t\t{ value: 'no', label: 'No' }\n\t\t\t]\n\t\t});\n\t\tif (p.isCancel(fan)) onCancel();\n\t\tfacebookFanPage = fan as 'yes' | 'no';\n\t\tif (facebookFanPage === 'yes') {\n\t\t\tconst name = await p.text({\n\t\t\t\tmessage: 'What is the name of the Facebook Fan Page?',\n\t\t\t\tplaceholder: 'My Facebook Page'\n\t\t\t});\n\t\t\tif (p.isCancel(name)) onCancel();\n\t\t\tfacebookDetails.name = name as string;\n\t\t\tconst url = await p.text({\n\t\t\t\tmessage: 'What is the URL of the Facebook Fan Page?',\n\t\t\t\tplaceholder: 'https://facebook.com/my-facebook-page'\n\t\t\t});\n\t\t\tif (p.isCancel(url)) onCancel();\n\t\t\tfacebookDetails.url = url as string;\n\t\t}\n\t}\n\n\tconst kids = await p.select({\n\t\tmessage: 'Do you collect information from kids under the age of 13?',\n\t\toptions: [\n\t\t\t{ value: 'yes', label: 'Yes. We collect information from children under the age of 13' },\n\t\t\t{ value: 'no', label: 'No' }\n\t\t]\n\t});\n\tif (p.isCancel(kids)) onCancel();\n\n\tconst retention = await p.text({\n\t\tmessage: 'How long do you retain personal information? (leave blank for default wording)',\n\t\tplaceholder: 'e.g. 12 months after account closure'\n\t});\n\tif (p.isCancel(retention)) onCancel();\n\n\tconst html = generatePrivacyHtml({\n\t\tcore,\n\t\tpersonalInfo: (personalInfo ?? []) as Array<\n\t\t\t'phone' | 'address' | 'email' | 'name' | 'social' | 'other'\n\t\t>,\n\t\tcontact,\n\t\ttracking: tracking as 'yes' | 'no',\n\t\ttrackingTools: tracking === 'yes' ? trackingTools : [],\n\t\tsendEmails: sendEmails as 'yes' | 'no',\n\t\temailPlatforms: sendEmails === 'yes' ? emailPlatforms : [],\n\t\tshowAds: showAds as 'yes' | 'no',\n\t\tadsPlatforms: showAds === 'yes' ? adsPlatforms : [],\n\t\tcanPay: canPay as 'yes' | 'no',\n\t\tpaymentProcessors: canPay === 'yes' ? paymentProcessors : [],\n\t\tremarketing: remarketing as 'yes' | 'no',\n\t\tremarketingPlatforms: remarketing === 'yes' ? remarketingPlatforms : [],\n\t\tproviders,\n\t\tusStates: usStates as 'yes' | 'no',\n\t\tgdpr: gdpr as 'yes' | 'no',\n\t\tfacebookFanPage,\n\t\tfacebookDetails,\n\t\tkids: kids as 'yes' | 'no',\n\t\tretention: retention as string | undefined\n\t});\n\n\tconst privacyPage = path.join(\n\t\tworkspaceRootDir,\n\t\tpublicRoutesDir,\n\t\tLEGAL_DIR,\n\t\t'privacy',\n\t\t'+page.svelte'\n\t);\n\tconst privacyPageTs = path.join(\n\t\tworkspaceRootDir,\n\t\tpublicRoutesDir,\n\t\tLEGAL_DIR,\n\t\t'privacy',\n\t\t'+page.ts'\n\t);\n\tfs.mkdirSync(path.dirname(privacyPage), { recursive: true });\n\tfs.writeFileSync(privacyPage, html);\n\tfs.writeFileSync(\n\t\tprivacyPageTs,\n\t\tpageMetaTagsLoader('Privacy Policy', `Privacy Policy for ${core.websiteName}`)\n\t);\n\n\tconst relativePrivacyPage = path.relative(workspaceRootDir, privacyPage);\n\tconst relativePrivacyPageTs = path.relative(workspaceRootDir, privacyPageTs);\n\treportResult({\n\t\tsummary: 'Generated placeholder privacy policy.',\n\t\tfilesCreated: [relativePrivacyPage, relativePrivacyPageTs],\n\t\tnextSteps: [\n\t\t\t`Review the generated copy in ${relativePrivacyPage} and fill in company-specific details (data processors, retention, contact info).`,\n\t\t\t'Have the final document reviewed by a lawyer before publishing \u2014 this is a starter template, not legal advice.',\n\t\t\t'Link to /privacy from your footer and sign-up flow.'\n\t\t]\n\t});\n}\n\nexport const privacy = new Command('privacy')\n\t.description('generate placeholder privacy policy')\n\t.configureHelp(helpConfig)\n\t.action(() => runCommand(privacyAction, 'Failed to generate privacy policy.'));\n", "import { Command } from 'commander';\nimport { helpConfig } from '../lib/help.ts';\nimport { load } from './fixtures/load.ts';\nimport { clear } from './fixtures/clear.ts';\nimport { reset } from './fixtures/reset.ts';\nimport { generate } from './fixtures/generate.ts';\nimport { regen } from './fixtures/regen.ts';\n\nexport const fixtures = new Command('fixtures')\n\t.description('manage fixture data')\n\t.configureHelp(helpConfig)\n\t.addCommand(generate)\n\t.addCommand(load)\n\t.addCommand(clear)\n\t.addCommand(reset)\n\t.addCommand(regen);\n", "import { Command } from 'commander';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand } from '../../lib/run.ts';\nimport { withPocketbase } from '../../lib/pocketbase.ts';\nimport { getWorkspace } from '../../lib/workspace.ts';\nimport { reportResult } from '../../lib/result-report.ts';\nimport { loadFixtures } from '../../lib/data.ts';\n\nexport const load = new Command('load')\n\t.description('load fixtures into the database')\n\t.configureHelp(helpConfig)\n\t.action(() =>\n\t\trunCommand(async () => {\n\t\t\tconst { workspaceRootDir } = await getWorkspace();\n\t\t\tlet loaded: string[] = [];\n\t\t\tawait withPocketbase(workspaceRootDir, async (pb) => {\n\t\t\t\tloaded = await loadFixtures(pb, workspaceRootDir);\n\t\t\t});\n\n\t\t\tif (loaded.length === 0) {\n\t\t\t\treportResult({\n\t\t\t\t\tsummary: 'No fixture files found in data/fixtures.',\n\t\t\t\t\tnextSteps: ['Run `vela fixtures generate` to create fixture files first.']\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\treportResult({\n\t\t\t\tsummary: `Loaded ${loaded.length} fixture file(s) into the database.`,\n\t\t\t\trecordsLoaded: loaded,\n\t\t\t\tnextSteps: [\n\t\t\t\t\t'Run `vela dev` to see the fixture data in the app.',\n\t\t\t\t\t'Run `vela fixtures clear` to remove the loaded fixture records.'\n\t\t\t\t]\n\t\t\t});\n\t\t}, 'Failed to load fixtures.')\n\t);\n", "import fs from 'node:fs';\nimport path from 'node:path';\nimport PocketBase, { ClientResponseError } from 'pocketbase';\nimport { DATA_DIR, FIXTURE_PREFIX } from './constants.ts';\nimport { dependencyOrder } from './collections.ts';\n\n/**\n * Seeds are the data an app needs to function \u2014 plans, roles, an initial\n * admin \u2014 and ship with it. Fixtures are mock data for development and tests.\n * Both are JSON files under `data/<kind>`, one per collection, loaded through\n * the PocketBase API so the app's hooks see them like any other write.\n */\nexport type DataKind = 'seeds' | 'fixtures';\n\nexport interface DataFile {\n\tcollectionName: string;\n\tfilePath: string;\n}\n\nexport function dataDir(cwd: string, kind: DataKind): string {\n\treturn path.join(cwd, DATA_DIR, kind);\n}\n\n/**\n * The JSON files under `data/<kind>` in load order. A leading numeric prefix\n * (`01-plans.json`) orders the files without being part of the collection name.\n */\nexport function getDataFiles(cwd: string, kind: DataKind): DataFile[] {\n\tconst dir = dataDir(cwd, kind);\n\tif (!fs.existsSync(dir)) return [];\n\treturn fs\n\t\t.readdirSync(dir)\n\t\t.filter((file) => file.endsWith('.json'))\n\t\t.sort((a, b) => a.localeCompare(b))\n\t\t.map((file) => ({\n\t\t\tcollectionName: file.replace(/\\.json$/i, '').replace(/^\\d+[-_]?/, ''),\n\t\t\tfilePath: path.join(dir, file)\n\t\t}));\n}\n\nexport function getSeedFiles(cwd: string): DataFile[] {\n\treturn getDataFiles(cwd, 'seeds');\n}\n\nexport function getFixtureFiles(cwd: string): DataFile[] {\n\treturn getDataFiles(cwd, 'fixtures');\n}\n\nexport function readRecords(filePath: string): Array<Record<string, unknown>> {\n\treturn JSON.parse(fs.readFileSync(filePath, 'utf8'));\n}\n\n/**\n * Seed record ids by collection name. Fixtures load after seeds, so a fixture\n * may relate to a seeded record \u2014 generation draws relation targets from here.\n */\nexport function readSeedIds(cwd: string): Map<string, string[]> {\n\tconst ids = new Map<string, string[]>();\n\tfor (const { collectionName, filePath } of getSeedFiles(cwd)) {\n\t\tconst list = ids.get(collectionName) ?? [];\n\t\tfor (const record of readRecords(filePath)) {\n\t\t\tif (typeof record.id === 'string' && record.id) list.push(record.id);\n\t\t}\n\t\tids.set(collectionName, list);\n\t}\n\treturn ids;\n}\n\n/** Fixture ids carry a known prefix, which is how they are found again. */\nexport function fixtureFilter(collectionName: string): string {\n\treturn `id ~ \"${FIXTURE_PREFIX}${collectionName.slice(0, 6)}%\"`;\n}\n\n/** A record in a seed or fixture file that PocketBase refused. */\nexport class DataLoadError extends Error {\n\treadonly kind: DataKind;\n\treadonly file: string;\n\n\tconstructor(kind: DataKind, file: string, index: number, cause: unknown) {\n\t\tsuper(`${file}, record ${index + 1}: ${describeError(cause)}`);\n\t\tthis.name = 'DataLoadError';\n\t\tthis.kind = kind;\n\t\tthis.file = file;\n\t}\n}\n\nfunction describeError(e: unknown): string {\n\tif (e instanceof ClientResponseError) {\n\t\tconst data: unknown = e.response?.data;\n\t\tconst details =\n\t\t\tdata && typeof data === 'object'\n\t\t\t\t? Object.entries(data as Record<string, { message?: string } | undefined>).map(\n\t\t\t\t\t\t([field, detail]) => `${field}: ${detail?.message ?? JSON.stringify(detail)}`\n\t\t\t\t\t)\n\t\t\t\t: [];\n\t\treturn [e.message, ...details].join(' ');\n\t}\n\treturn e instanceof Error ? e.message : String(e);\n}\n\nfunction label(cwd: string, filePath: string, count: number): string {\n\treturn `${path.relative(cwd, filePath)} (${count} records)`;\n}\n\nasync function createRecords(\n\tpb: PocketBase,\n\tkind: DataKind,\n\tcwd: string,\n\t{ collectionName, filePath }: DataFile\n): Promise<number> {\n\tconst records = readRecords(filePath);\n\tfor (const [index, record] of records.entries()) {\n\t\ttry {\n\t\t\tawait pb.collection(collectionName).create(record);\n\t\t} catch (e) {\n\t\t\tthrow new DataLoadError(kind, path.relative(cwd, filePath), index, e);\n\t\t}\n\t}\n\treturn records.length;\n}\n\n/** Load every seed file, or the given ones, returning a label per file. */\nexport async function loadSeeds(\n\tpb: PocketBase,\n\tcwd: string,\n\tseedFiles: DataFile[] = getSeedFiles(cwd)\n): Promise<string[]> {\n\tconst loaded: string[] = [];\n\tfor (const file of seedFiles) {\n\t\tconst count = await createRecords(pb, 'seeds', cwd, file);\n\t\tloaded.push(label(cwd, file.filePath, count));\n\t}\n\treturn loaded;\n}\n\nexport async function clearSeeds(\n\tpb: PocketBase,\n\tcwd: string,\n\tseedFiles: DataFile[] = getSeedFiles(cwd)\n): Promise<string[]> {\n\tconst cleared: string[] = [];\n\tfor (const { collectionName, filePath } of seedFiles) {\n\t\tconst seeds = readRecords(filePath) as Array<{ id: string }>;\n\t\tfor (const { id } of seeds) {\n\t\t\tawait pb.collection(collectionName).delete(id);\n\t\t}\n\t\tcleared.push(label(cwd, filePath, seeds.length));\n\t}\n\treturn cleared;\n}\n\n/** Load every fixture file, refusing a collection that already holds fixtures. */\nexport async function loadFixtures(pb: PocketBase, cwd: string): Promise<string[]> {\n\tconst loaded: string[] = [];\n\tfor (const file of getFixtureFiles(cwd)) {\n\t\tconst existing = await pb.collection(file.collectionName).getFullList({\n\t\t\tfilter: fixtureFilter(file.collectionName),\n\t\t\tfields: 'id'\n\t\t});\n\t\tif (existing.length > 0) {\n\t\t\tthrow new Error(\n\t\t\t\t`${file.collectionName} collection already has fixture records. ` +\n\t\t\t\t\t'Run `vela fixtures reset` to clear and reload, or `vela fixtures clear` first.'\n\t\t\t);\n\t\t}\n\t\tconst count = await createRecords(pb, 'fixtures', cwd, file);\n\t\tloaded.push(label(cwd, file.filePath, count));\n\t}\n\treturn loaded;\n}\n\n/** Remove fixture records from every collection, dependents first. */\nexport async function clearFixtures(pb: PocketBase, cwd: string): Promise<string[]> {\n\tconst fixturePathByName = new Map(\n\t\tgetFixtureFiles(cwd).map((f) => [f.collectionName, f.filePath])\n\t);\n\n\tconst cleared: string[] = [];\n\tconst fullList = await pb.collections.getFullList();\n\tconst collections = fullList.map((c) => ({\n\t\tid: c.id,\n\t\tname: c.name,\n\t\tfields: c.fields.map((f) => ({\n\t\t\ttype: f.type,\n\t\t\tcollectionId: (f as { collectionId?: string }).collectionId\n\t\t}))\n\t}));\n\n\tconst { names } = dependencyOrder(collections);\n\tconst reversed = [...names].reverse();\n\n\tfor (const collectionName of reversed) {\n\t\tconst records = await pb.collection(collectionName).getFullList({\n\t\t\tfilter: fixtureFilter(collectionName),\n\t\t\tfields: 'id'\n\t\t});\n\n\t\tif (records.length === 0) continue;\n\n\t\tfor (const { id } of records) {\n\t\t\tawait pb.collection(collectionName).delete(id);\n\t\t}\n\t\tconst fixturePath = fixturePathByName.get(collectionName);\n\t\tcleared.push(\n\t\t\tfixturePath\n\t\t\t\t? label(cwd, fixturePath, records.length)\n\t\t\t\t: `${collectionName} (${records.length} records)`\n\t\t);\n\t}\n\n\treturn cleared;\n}\n\nexport async function hasLoadedFixtures(pb: PocketBase): Promise<boolean> {\n\tconst fullList = await pb.collections.getFullList();\n\tfor (const collection of fullList) {\n\t\tif (collection.name.startsWith('_')) continue;\n\t\tconst page = await pb.collection(collection.name).getList(1, 1, {\n\t\t\tfilter: fixtureFilter(collection.name),\n\t\t\tfields: 'id'\n\t\t});\n\t\tif (page.totalItems > 0) return true;\n\t}\n\treturn false;\n}\n", "export interface CollectionLike {\n\tid: string;\n\tname: string;\n\tfields: Array<{ type: string; collectionId?: string }>;\n}\n\nexport function dependencyOrder(\n\tcollections: CollectionLike[],\n\tstartingCollectionId?: string\n): { ids: string[]; names: string[] } {\n\tconst order: string[] = [];\n\tconst visited: Record<string, boolean> = {};\n\tconst queue: string[] = [];\n\n\tconst eligible = collections.filter((c) => !c.name.startsWith('_'));\n\n\tif (startingCollectionId) {\n\t\tqueue.push(startingCollectionId);\n\t} else {\n\t\tfor (const collection of eligible) {\n\t\t\tif (!visited[collection.id]) {\n\t\t\t\tvisited[collection.id] = true;\n\t\t\t\tqueue.push(collection.id);\n\t\t\t}\n\t\t}\n\t}\n\n\twhile (queue.length > 0) {\n\t\tconst collectionId = queue.shift();\n\t\tif (!collectionId) continue;\n\t\torder.push(collectionId);\n\n\t\tconst source = collections.find((c) => c.id === collectionId);\n\t\tfor (const field of source?.fields ?? []) {\n\t\t\tif (field.type === 'relation' && field.collectionId && !visited[field.collectionId]) {\n\t\t\t\tvisited[field.collectionId] = true;\n\t\t\t\tqueue.push(field.collectionId);\n\t\t\t}\n\t\t}\n\t}\n\n\tconst nameById = Object.fromEntries(collections.map((c) => [c.id, c.name]));\n\treturn { ids: order, names: order.map((id) => nameById[id]!) };\n}\n", "import { Command } from 'commander';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand } from '../../lib/run.ts';\nimport { withPocketbase } from '../../lib/pocketbase.ts';\nimport { getWorkspace } from '../../lib/workspace.ts';\nimport { reportResult } from '../../lib/result-report.ts';\nimport { clearFixtures } from '../../lib/data.ts';\n\nexport const clear = new Command('clear')\n\t.description('clear loaded fixtures')\n\t.configureHelp(helpConfig)\n\t.action(() =>\n\t\trunCommand(async () => {\n\t\t\tconst { workspaceRootDir } = await getWorkspace();\n\t\t\tlet cleared: string[] = [];\n\t\t\tawait withPocketbase(workspaceRootDir, async (pb) => {\n\t\t\t\tcleared = await clearFixtures(pb, workspaceRootDir);\n\t\t\t});\n\n\t\t\tif (cleared.length === 0) {\n\t\t\t\treportResult({\n\t\t\t\t\tsummary: 'No fixtures to clear.',\n\t\t\t\t\tnextSteps: [\n\t\t\t\t\t\t'Run `vela fixtures generate` to create fixture files.',\n\t\t\t\t\t\t'Run `vela fixtures load` to load them into the database.'\n\t\t\t\t\t]\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\treportResult({\n\t\t\t\tsummary: `Cleared ${cleared.length} fixture collection(s) from the database.`,\n\t\t\t\trecordsCleared: cleared,\n\t\t\t\tnextSteps: [\n\t\t\t\t\t'Run `vela fixtures load` to reload the existing fixture files.',\n\t\t\t\t\t'Run `vela fixtures generate --force` to regenerate fixture files from scratch.'\n\t\t\t\t]\n\t\t\t});\n\t\t}, 'Failed to clear fixtures.')\n\t);\n", "import { Command } from 'commander';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand } from '../../lib/run.ts';\nimport { withPocketbase } from '../../lib/pocketbase.ts';\nimport { getWorkspace } from '../../lib/workspace.ts';\nimport { reportResult } from '../../lib/result-report.ts';\nimport { clearFixtures, loadFixtures } from '../../lib/data.ts';\n\nexport const reset = new Command('reset')\n\t.description('clear and reload fixtures')\n\t.configureHelp(helpConfig)\n\t.action(() =>\n\t\trunCommand(async () => {\n\t\t\tconst { workspaceRootDir } = await getWorkspace();\n\t\t\tlet cleared: string[] = [];\n\t\t\tlet loaded: string[] = [];\n\t\t\tawait withPocketbase(workspaceRootDir, async (pb) => {\n\t\t\t\tcleared = await clearFixtures(pb, workspaceRootDir);\n\t\t\t\tloaded = await loadFixtures(pb, workspaceRootDir);\n\t\t\t});\n\n\t\t\tif (loaded.length === 0) {\n\t\t\t\treportResult({\n\t\t\t\t\tsummary: 'No fixture files found in data/fixtures.',\n\t\t\t\t\trecordsCleared: cleared,\n\t\t\t\t\tnextSteps: ['Run `vela fixtures generate` to create fixture files first.']\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\treportResult({\n\t\t\t\tsummary: `Reset fixtures (${loaded.length} collection(s) reloaded).`,\n\t\t\t\trecordsCleared: cleared,\n\t\t\t\trecordsLoaded: loaded,\n\t\t\t\tnextSteps: [\n\t\t\t\t\t'Run `vela dev` to see the freshly reloaded fixture data.',\n\t\t\t\t\t'Run `vela fixtures regen` if you also want to regenerate the fixture files.'\n\t\t\t\t]\n\t\t\t});\n\t\t}, 'Failed to reset fixtures.')\n\t);\n", "import fs from 'node:fs';\nimport path from 'node:path';\nimport { Command, InvalidArgumentError } from 'commander';\nimport * as p from '@clack/prompts';\nimport type PocketBase from 'pocketbase';\nimport { annotate } from 'annotate-json-schema';\nimport { createGenerator, type JsonSchema } from 'json-schema-faker';\nimport { faker } from '@faker-js/faker';\nimport { collectionToJsonSchema } from '@velastack/pocketbase-codegen';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand } from '../../lib/run.ts';\nimport { withPocketbase } from '../../lib/pocketbase.ts';\nimport { getWorkspace } from '../../lib/workspace.ts';\nimport { dependencyOrder } from '../../lib/collections.ts';\nimport { DATA_DIR, FIXTURE_PREFIX } from '../../lib/constants.ts';\nimport { reportResult } from '../../lib/result-report.ts';\nimport {\n\tclearFixtures,\n\tdataDir,\n\tgetFixtureFiles,\n\thasLoadedFixtures,\n\treadSeedIds\n} from '../../lib/data.ts';\n\nconst SKIP_TYPES = new Set(['autodate', 'file', 'relation']);\nconst AUTH_OVERRIDE_FIELDS = ['email', 'password', 'passwordConfirm', 'tokenKey'];\n\nfunction padZeros(num: number, length: number) {\n\treturn num.toString().padStart(length, '0');\n}\n\nfunction parseCount(value: string): number {\n\tconst n = parseInt(value, 10);\n\tif (!Number.isFinite(n) || n <= 0 || n > 999) {\n\t\tthrow new InvalidArgumentError('count must be between 1 and 999');\n\t}\n\treturn n;\n}\n\nfunction parseSeed(value: string): number {\n\tconst n = parseInt(value, 10);\n\tif (!Number.isFinite(n)) {\n\t\tthrow new InvalidArgumentError('seed must be an integer');\n\t}\n\treturn n;\n}\n\ntype CollectionSummary = Parameters<typeof collectionToJsonSchema>[0];\ntype FieldSummary = CollectionSummary['fields'][number];\n\nasync function loadCollections(pb: PocketBase): Promise<CollectionSummary[]> {\n\tconst list = await pb.collections.getFullList();\n\treturn list.map((c) => ({\n\t\tid: c.id,\n\t\tname: c.name,\n\t\ttype: c.type as CollectionSummary['type'],\n\t\tfields: c.fields as FieldSummary[]\n\t}));\n}\n\nexport interface GenerateFixturesOptions {\n\tcount: number;\n\tseed?: number;\n}\n\nexport interface GenerateFixturesResult {\n\twrittenFiles: string[];\n\twarnings: string[];\n}\n\nexport async function generateFixtureFiles(\n\tpb: PocketBase,\n\tworkspaceRootDir: string,\n\topts: GenerateFixturesOptions\n): Promise<GenerateFixturesResult> {\n\tconst fixturesDir = dataDir(workspaceRootDir, 'fixtures');\n\tfs.mkdirSync(fixturesDir, { recursive: true });\n\tfor (const file of fs.readdirSync(fixturesDir)) {\n\t\tif (file.endsWith('.json')) fs.unlinkSync(path.join(fixturesDir, file));\n\t}\n\n\tif (opts.seed !== undefined) faker.seed(opts.seed);\n\tconst generator = createGenerator({\n\t\textensions: { faker },\n\t\talwaysFakeOptionals: true,\n\t\t...(opts.seed !== undefined ? { seed: opts.seed } : {})\n\t});\n\n\tconst collections = await loadCollections(pb);\n\tconst eligible = collections.filter((c) => !c.name.startsWith('_') && c.type !== 'view');\n\tconst { ids } = dependencyOrder(eligible);\n\n\t// Fixtures load after seeds, so a relation may point at a seeded record \u2014\n\t// the seeded plans and roles are exactly what fixture rows should refer to.\n\tconst seedIds = readSeedIds(workspaceRootDir);\n\tconst recordIds = new Map<string, string[]>();\n\tfor (const collection of eligible) {\n\t\trecordIds.set(collection.id, [...(seedIds.get(collection.name) ?? [])]);\n\t}\n\n\tconst writtenFiles: string[] = [];\n\tconst warnings: string[] = [];\n\tlet fileIndex = 1;\n\tfor (const collectionId of ids) {\n\t\tconst collection = eligible.find((c) => c.id === collectionId);\n\t\tif (!collection) continue;\n\n\t\tfor (const f of collection.fields) {\n\t\t\tif (f.type !== 'relation' || !f.required) continue;\n\t\t\tconst pool = f.collectionId ? recordIds.get(f.collectionId) : undefined;\n\t\t\tif (!pool || pool.length === 0) {\n\t\t\t\tconst target = collections.find((c) => c.id === f.collectionId);\n\t\t\t\tconst targetLabel = target?.name ?? f.collectionId ?? '<unknown>';\n\t\t\t\twarnings.push(\n\t\t\t\t\t`${collection.name}.${f.name} requires a ${targetLabel} record, but there are none in seeds or generated fixtures yet`\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\tconst schema = collectionToJsonSchema(collection);\n\t\tconst properties = schema.properties as Record<string, unknown>;\n\t\tdelete properties.id;\n\t\tfor (const f of collection.fields) {\n\t\t\tif (SKIP_TYPES.has(f.type)) delete properties[f.name];\n\t\t}\n\t\tif (collection.type === 'auth') {\n\t\t\tfor (const name of AUTH_OVERRIDE_FIELDS) delete properties[name];\n\t\t}\n\t\tschema.required = schema.required.filter((name) => name in properties);\n\n\t\tconst annotated = annotate(schema as JsonSchema, collection.name);\n\n\t\tconst items: Record<string, unknown>[] = [];\n\t\tfor (let idx = 0; idx < opts.count; idx++) {\n\t\t\tconst record = (await generator.generate(annotated)) as Record<string, unknown>;\n\n\t\t\tconst shortName = collection.name.slice(0, 6);\n\t\t\tconst remaining = 15 - shortName.length - FIXTURE_PREFIX.length;\n\t\t\tconst id = `${FIXTURE_PREFIX}${shortName}${padZeros(idx + 1, remaining)}`;\n\t\t\trecord.id = id;\n\t\t\trecordIds.get(collection.id)!.push(id);\n\n\t\t\tfor (const f of collection.fields) {\n\t\t\t\tif (f.type !== 'relation') continue;\n\t\t\t\tconst parentIds = f.collectionId ? (recordIds.get(f.collectionId) ?? []) : [];\n\t\t\t\tif (parentIds.length === 0) continue;\n\t\t\t\tconst multi = f.maxSelect !== undefined && f.maxSelect > 1;\n\t\t\t\trecord[f.name] = multi\n\t\t\t\t\t? [faker.helpers.arrayElement(parentIds)]\n\t\t\t\t\t: faker.helpers.arrayElement(parentIds);\n\t\t\t}\n\n\t\t\tif (collection.type === 'auth') {\n\t\t\t\trecord.email = `${faker.string.uuid()}@example.com`;\n\t\t\t\trecord.password = 'password';\n\t\t\t\trecord.passwordConfirm = 'password';\n\t\t\t}\n\n\t\t\titems.push(record);\n\t\t}\n\n\t\tconst filename = `${padZeros(fileIndex, 2)}-${collection.name}.json`;\n\t\tfs.writeFileSync(path.join(fixturesDir, filename), JSON.stringify(items, null, 2));\n\t\twrittenFiles.push(`${path.join(DATA_DIR, 'fixtures', filename)} (${items.length} records)`);\n\t\tfileIndex++;\n\t}\n\n\treturn { writtenFiles, warnings };\n}\n\nexport const generate = new Command('generate')\n\t.description('generate fixture data')\n\t.option('-c, --count <count>', 'number of records per collection', parseCount, 10)\n\t.option('-s, --seed <seed>', 'seed for deterministic output', parseSeed)\n\t.option('-f, --force', 'overwrite existing fixture files and clear loaded fixtures')\n\t.configureHelp(helpConfig)\n\t.action((opts: { count: number; seed?: number; force?: boolean }) =>\n\t\trunCommand(async () => {\n\t\t\tconst { workspaceRootDir } = await getWorkspace();\n\t\t\tconst existing = getFixtureFiles(workspaceRootDir);\n\n\t\t\tif (existing.length > 0 && !opts.force) {\n\t\t\t\tawait withPocketbase(workspaceRootDir, async (pb) => {\n\t\t\t\t\tconst loaded = await hasLoadedFixtures(pb);\n\t\t\t\t\tif (loaded) {\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t'Existing fixture files found and fixtures are loaded in the database. ' +\n\t\t\t\t\t\t\t\t'Run `vela fixtures reset` to clear + reload, or `vela fixtures clear` then `vela fixtures generate --force`.'\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t'Existing fixture files found in data/fixtures. Pass --force to overwrite.'\n\t\t\t\t\t);\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tlet result: GenerateFixturesResult = { writtenFiles: [], warnings: [] };\n\t\t\tlet cleared: string[] = [];\n\t\t\tawait withPocketbase(workspaceRootDir, async (pb) => {\n\t\t\t\tif (opts.force) {\n\t\t\t\t\tcleared = await clearFixtures(pb, workspaceRootDir);\n\t\t\t\t}\n\t\t\t\tresult = await generateFixtureFiles(pb, workspaceRootDir, {\n\t\t\t\t\tcount: opts.count,\n\t\t\t\t\tseed: opts.seed\n\t\t\t\t});\n\t\t\t});\n\n\t\t\tfor (const warning of result.warnings) p.log.warn(warning);\n\n\t\t\tif (result.writtenFiles.length === 0) {\n\t\t\t\treportResult({\n\t\t\t\t\tsummary: 'No eligible collections found to generate fixtures for.',\n\t\t\t\t\tnextSteps: [\n\t\t\t\t\t\t'Create collections with `vela generate scaffold <model>` or in the PocketBase admin UI.',\n\t\t\t\t\t\t'Run `vela fixtures generate` again once you have at least one collection.'\n\t\t\t\t\t]\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\treportResult({\n\t\t\t\tsummary: `Generated fixture files for ${result.writtenFiles.length} collection(s).`,\n\t\t\t\tfilesCreated: result.writtenFiles,\n\t\t\t\trecordsCleared: cleared,\n\t\t\t\tnextSteps: [\n\t\t\t\t\t'Run `vela fixtures load` to load the generated fixtures into the database.',\n\t\t\t\t\t'Edit the JSON files under data/fixtures/ to customize the generated data.'\n\t\t\t\t]\n\t\t\t});\n\t\t}, 'Failed to generate fixtures.')\n\t);\n", "import { Command, InvalidArgumentError } from 'commander';\nimport * as p from '@clack/prompts';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand } from '../../lib/run.ts';\nimport { withPocketbase } from '../../lib/pocketbase.ts';\nimport { getWorkspace } from '../../lib/workspace.ts';\nimport { reportResult } from '../../lib/result-report.ts';\nimport { clearFixtures, loadFixtures } from '../../lib/data.ts';\nimport { generateFixtureFiles, type GenerateFixturesResult } from './generate.ts';\n\nfunction parseCount(value: string): number {\n\tconst n = parseInt(value, 10);\n\tif (!Number.isFinite(n) || n <= 0 || n > 999) {\n\t\tthrow new InvalidArgumentError('count must be between 1 and 999');\n\t}\n\treturn n;\n}\n\nfunction parseSeed(value: string): number {\n\tconst n = parseInt(value, 10);\n\tif (!Number.isFinite(n)) {\n\t\tthrow new InvalidArgumentError('seed must be an integer');\n\t}\n\treturn n;\n}\n\nexport const regen = new Command('regen')\n\t.description('clear the database, regenerate fixture files, and reload them')\n\t.option('-c, --count <count>', 'number of records per collection', parseCount, 10)\n\t.option('-s, --seed <seed>', 'seed for deterministic output', parseSeed)\n\t.configureHelp(helpConfig)\n\t.action((opts: { count: number; seed?: number }) =>\n\t\trunCommand(async () => {\n\t\t\tconst { workspaceRootDir } = await getWorkspace();\n\t\t\tlet cleared: string[] = [];\n\t\t\tlet result: GenerateFixturesResult = { writtenFiles: [], warnings: [] };\n\t\t\tlet loaded: string[] = [];\n\t\t\tawait withPocketbase(workspaceRootDir, async (pb) => {\n\t\t\t\tcleared = await clearFixtures(pb, workspaceRootDir);\n\t\t\t\tresult = await generateFixtureFiles(pb, workspaceRootDir, {\n\t\t\t\t\tcount: opts.count,\n\t\t\t\t\tseed: opts.seed\n\t\t\t\t});\n\t\t\t\tloaded = await loadFixtures(pb, workspaceRootDir);\n\t\t\t});\n\n\t\t\tfor (const warning of result.warnings) p.log.warn(warning);\n\n\t\t\treportResult({\n\t\t\t\tsummary: `Regenerated fixtures (${loaded.length} collection(s) reloaded).`,\n\t\t\t\tfilesCreated: result.writtenFiles,\n\t\t\t\trecordsCleared: cleared,\n\t\t\t\trecordsLoaded: loaded,\n\t\t\t\tnextSteps: [\n\t\t\t\t\t'Run `vela dev` to see the new fixture data in the app.',\n\t\t\t\t\t'Edit data/fixtures/*.json or tweak `-c/--count` and re-run to adjust the dataset.'\n\t\t\t\t]\n\t\t\t});\n\t\t}, 'Failed to regenerate fixtures.')\n\t);\n", "import { Command } from 'commander';\nimport { helpConfig } from '../lib/help.ts';\nimport { load } from './seeds/load.ts';\nimport { save } from './seeds/save.ts';\nimport { clear } from './seeds/clear.ts';\n\nexport const seeds = new Command('seeds')\n\t.description('manage seed data')\n\t.configureHelp(helpConfig)\n\t.addCommand(load)\n\t.addCommand(save)\n\t.addCommand(clear);\n", "import { Command } from 'commander';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand } from '../../lib/run.ts';\nimport { withPocketbase } from '../../lib/pocketbase.ts';\nimport { getWorkspace } from '../../lib/workspace.ts';\nimport { reportResult } from '../../lib/result-report.ts';\nimport { getSeedFiles, loadSeeds } from '../../lib/data.ts';\n\nexport const load = new Command('load')\n\t.description('load seeds into the database')\n\t.option('-f, --force', 'load even if target collections already have records')\n\t.configureHelp(helpConfig)\n\t.action((opts: { force?: boolean }) =>\n\t\trunCommand(async () => {\n\t\t\tconst { workspaceRootDir } = await getWorkspace();\n\t\t\tconst seedFiles = getSeedFiles(workspaceRootDir);\n\n\t\t\tif (seedFiles.length === 0) {\n\t\t\t\treportResult({\n\t\t\t\t\tsummary: 'No seed files found in data/seeds.',\n\t\t\t\t\tnextSteps: ['Run `vela seeds save` to snapshot the current database contents as seeds.']\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tlet loaded: string[] = [];\n\n\t\t\tawait withPocketbase(workspaceRootDir, async (pb) => {\n\t\t\t\tif (!opts.force) {\n\t\t\t\t\tfor (const { collectionName } of seedFiles) {\n\t\t\t\t\t\tconst page = await pb.collection(collectionName).getList(1, 1, { fields: 'id' });\n\t\t\t\t\t\tif (page.totalItems > 0) {\n\t\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t\t`${collectionName} collection already has records. Pass --force to load anyway.`\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tloaded = await loadSeeds(pb, workspaceRootDir, seedFiles);\n\t\t\t});\n\n\t\t\treportResult({\n\t\t\t\tsummary: `Loaded ${loaded.length} seed file(s) into the database.`,\n\t\t\t\trecordsLoaded: loaded,\n\t\t\t\tnextSteps: [\n\t\t\t\t\t'Run `vela dev` to see the seeded data in the app.',\n\t\t\t\t\t'Run `vela seeds clear` to remove the seeded records.'\n\t\t\t\t]\n\t\t\t});\n\t\t}, 'Failed to load seeds.')\n\t);\n", "import fs from 'node:fs';\nimport path from 'node:path';\nimport { Command } from 'commander';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand } from '../../lib/run.ts';\nimport { withPocketbase } from '../../lib/pocketbase.ts';\nimport { getWorkspace } from '../../lib/workspace.ts';\nimport { dependencyOrder } from '../../lib/collections.ts';\nimport { reportResult } from '../../lib/result-report.ts';\nimport { DATA_DIR } from '../../lib/constants.ts';\nimport { dataDir, getSeedFiles } from '../../lib/data.ts';\n\nconst padZeros = (num: number, length: number) => num.toString().padStart(length, '0');\n\nfunction filterSystemFields(\n\trecord: Record<string, unknown>,\n\tsystemFieldNames: Set<string>\n): Record<string, unknown> {\n\tconst out: Record<string, unknown> = {};\n\tfor (const [key, value] of Object.entries(record)) {\n\t\tif (systemFieldNames.has(key)) continue;\n\t\tif (key === 'collectionId' || key === 'collectionName' || key === 'expand') continue;\n\t\tout[key] = value;\n\t}\n\treturn out;\n}\n\nexport const save = new Command('save')\n\t.description('save the current data as seeds')\n\t.option('-f, --force', 'overwrite existing seed files')\n\t.configureHelp(helpConfig)\n\t.action((opts: { force?: boolean }) =>\n\t\trunCommand(async () => {\n\t\t\tconst { workspaceRootDir } = await getWorkspace();\n\t\t\tconst seedsPath = dataDir(workspaceRootDir, 'seeds');\n\n\t\t\tconst existing = getSeedFiles(workspaceRootDir);\n\t\t\tif (existing.length > 0 && !opts.force) {\n\t\t\t\tthrow new Error('Existing seed files found in data/seeds. Pass --force to overwrite.');\n\t\t\t}\n\n\t\t\tfs.mkdirSync(seedsPath, { recursive: true });\n\t\t\tif (opts.force) {\n\t\t\t\tfor (const file of fs.readdirSync(seedsPath)) {\n\t\t\t\t\tif (file.endsWith('.json')) fs.unlinkSync(path.join(seedsPath, file));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst saved: string[] = [];\n\n\t\t\tawait withPocketbase(workspaceRootDir, async (pb) => {\n\t\t\t\tconst fullList = await pb.collections.getFullList();\n\t\t\t\tconst collections = fullList.map((c) => ({\n\t\t\t\t\tid: c.id,\n\t\t\t\t\tname: c.name,\n\t\t\t\t\tfields: c.fields.map((f) => ({\n\t\t\t\t\t\tname: f.name,\n\t\t\t\t\t\ttype: f.type,\n\t\t\t\t\t\tsystem: f.system,\n\t\t\t\t\t\tcollectionId: (f as { collectionId?: string }).collectionId\n\t\t\t\t\t}))\n\t\t\t\t}));\n\n\t\t\t\tconst { names } = dependencyOrder(collections);\n\n\t\t\t\tlet count = 1;\n\t\t\t\tfor (const collectionName of names) {\n\t\t\t\t\tconst collection = collections.find((c) => c.name === collectionName);\n\t\t\t\t\tif (!collection) continue;\n\t\t\t\t\tconst systemFieldNames = new Set(\n\t\t\t\t\t\tcollection.fields.filter((f) => f.system && f.name !== 'id').map((f) => f.name)\n\t\t\t\t\t);\n\n\t\t\t\t\tconst records = await pb.collection(collectionName).getFullList();\n\t\t\t\t\tif (records.length === 0) continue;\n\n\t\t\t\t\tconst filtered = records.map((r) =>\n\t\t\t\t\t\tfilterSystemFields(r as Record<string, unknown>, systemFieldNames)\n\t\t\t\t\t);\n\n\t\t\t\t\tconst relativeSeedPath = path.join(\n\t\t\t\t\t\tDATA_DIR,\n\t\t\t\t\t\t'seeds',\n\t\t\t\t\t\t`${padZeros(count, 2)}-${collectionName}.json`\n\t\t\t\t\t);\n\t\t\t\t\tconst seedPath = path.join(workspaceRootDir, relativeSeedPath);\n\t\t\t\t\tfs.writeFileSync(seedPath, JSON.stringify(filtered, null, 2));\n\t\t\t\t\tsaved.push(`${relativeSeedPath} (${filtered.length} records)`);\n\t\t\t\t\tcount++;\n\t\t\t\t}\n\t\t\t});\n\n\t\t\tif (saved.length === 0) {\n\t\t\t\treportResult({\n\t\t\t\t\tsummary: 'No records to save.',\n\t\t\t\t\tnextSteps: [\n\t\t\t\t\t\t'Create some records first (via the app, `vela fixtures load`, or the PocketBase admin UI), then rerun `vela seeds save`.'\n\t\t\t\t\t]\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\treportResult({\n\t\t\t\tsummary: `Saved ${saved.length} collection(s) as seeds.`,\n\t\t\t\tfilesCreated: saved,\n\t\t\t\tnextSteps: [\n\t\t\t\t\t'Commit the new files under data/seeds/ so teammates get the same starting data.',\n\t\t\t\t\t'Run `vela seeds load` on a fresh database to restore this snapshot.'\n\t\t\t\t]\n\t\t\t});\n\t\t}, 'Failed to save seeds.')\n\t);\n", "import { Command } from 'commander';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand } from '../../lib/run.ts';\nimport { withPocketbase } from '../../lib/pocketbase.ts';\nimport { getWorkspace } from '../../lib/workspace.ts';\nimport { reportResult } from '../../lib/result-report.ts';\nimport { clearSeeds, getSeedFiles } from '../../lib/data.ts';\n\nexport const clear = new Command('clear')\n\t.description('clear seeded records')\n\t.configureHelp(helpConfig)\n\t.action(() =>\n\t\trunCommand(async () => {\n\t\t\tconst { workspaceRootDir } = await getWorkspace();\n\t\t\tconst seedFiles = getSeedFiles(workspaceRootDir);\n\n\t\t\tif (seedFiles.length === 0) {\n\t\t\t\treportResult({\n\t\t\t\t\tsummary: 'No seed files found in data/seeds.',\n\t\t\t\t\tnextSteps: ['Run `vela seeds save` to create seed files from the current database.']\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tlet cleared: string[] = [];\n\t\t\tawait withPocketbase(workspaceRootDir, async (pb) => {\n\t\t\t\tcleared = await clearSeeds(pb, workspaceRootDir, seedFiles);\n\t\t\t});\n\n\t\t\tif (cleared.length === 0) {\n\t\t\t\treportResult({\n\t\t\t\t\tsummary: 'No seeded records found to clear.',\n\t\t\t\t\tnextSteps: ['Run `vela seeds load` to load seed records into the database.']\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\treportResult({\n\t\t\t\tsummary: `Cleared ${cleared.length} seed file(s) worth of records.`,\n\t\t\t\trecordsCleared: cleared,\n\t\t\t\tnextSteps: ['Run `vela seeds load` to reload seeds from the files in data/seeds.']\n\t\t\t});\n\t\t}, 'Failed to clear seeds.')\n\t);\n", "import { Command } from 'commander';\nimport * as p from '@clack/prompts';\nimport makeFetchCookie from 'fetch-cookie';\nimport { helpConfig } from '../lib/help.ts';\nimport { API_URL } from '../lib/constants.ts';\nimport { writeConfig } from '../lib/config.ts';\nimport { runCommand } from '../lib/run.ts';\nimport { issueApiKey } from './login.ts';\n\nexport const signup = new Command('signup')\n\t.description('signup to velastack.dev')\n\t.configureHelp(helpConfig)\n\t.action(() =>\n\t\trunCommand(async () => {\n\t\t\tconst { email, password, passwordConfirm } = await p.group({\n\t\t\t\temail: () => p.text({ message: 'Email' }),\n\t\t\t\tpassword: () => p.password({ message: 'Password' }),\n\t\t\t\tpasswordConfirm: () => p.password({ message: 'Confirm password' })\n\t\t\t});\n\n\t\t\tif (password !== passwordConfirm) {\n\t\t\t\tthrow new Error('Passwords do not match.');\n\t\t\t}\n\n\t\t\tconst fetchCookie = makeFetchCookie(fetch);\n\t\t\tconst res = await fetchCookie(`${API_URL}/signup`, {\n\t\t\t\tmethod: 'POST',\n\t\t\t\theaders: {\n\t\t\t\t\t'Content-Type': 'application/x-www-form-urlencoded',\n\t\t\t\t\tOrigin: API_URL\n\t\t\t\t},\n\t\t\t\tbody: new URLSearchParams({\n\t\t\t\t\ttype: 'password',\n\t\t\t\t\temail: email as string,\n\t\t\t\t\tpassword: password as string,\n\t\t\t\t\tpasswordConfirm: passwordConfirm as string\n\t\t\t\t}).toString()\n\t\t\t});\n\n\t\t\tif (!res.headers.get('Set-Cookie')) {\n\t\t\t\tthrow new Error('Failed to signup. Try again or contact support.');\n\t\t\t}\n\n\t\t\tconst apiKey = await issueApiKey(fetchCookie);\n\t\t\twriteConfig({ apiKey });\n\t\t\tp.log.success('Signed up to velastack.dev');\n\t\t\tp.log.info('Check your email for a confirmation link.');\n\t\t}, 'Failed to signup.')\n\t);\n", "import os from 'node:os';\nimport { Command } from 'commander';\nimport * as p from '@clack/prompts';\nimport makeFetchCookie, { type FetchCookieImpl } from 'fetch-cookie';\nimport { helpConfig } from '../lib/help.ts';\nimport { API_URL } from '../lib/constants.ts';\nimport { writeConfig } from '../lib/config.ts';\nimport { runCommand } from '../lib/run.ts';\n\nexport type FetchCookie = FetchCookieImpl<string | URL | Request, RequestInit, Response>;\n\nexport const login = new Command('login')\n\t.description('login to velastack.dev')\n\t.configureHelp(helpConfig)\n\t.action(() =>\n\t\trunCommand(async () => {\n\t\t\tconst { email, password } = await p.group({\n\t\t\t\temail: () => p.text({ message: 'Email' }),\n\t\t\t\tpassword: () => p.password({ message: 'Password' })\n\t\t\t});\n\n\t\t\tconst fetchCookie = makeFetchCookie(fetch);\n\t\t\tconst loginRes = await fetchCookie(`${API_URL}/login`, {\n\t\t\t\tmethod: 'POST',\n\t\t\t\theaders: {\n\t\t\t\t\t'Content-Type': 'application/x-www-form-urlencoded',\n\t\t\t\t\tOrigin: API_URL\n\t\t\t\t},\n\t\t\t\tbody: new URLSearchParams({\n\t\t\t\t\ttype: 'password',\n\t\t\t\t\temail: email as string,\n\t\t\t\t\tpassword: password as string\n\t\t\t\t}).toString()\n\t\t\t});\n\n\t\t\tif (!loginRes.headers.get('Set-Cookie')) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t'Run `vela signup` to create an account or reset at https://velastack.dev/reset'\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconst apiKey = await issueApiKey(fetchCookie);\n\t\t\twriteConfig({ apiKey });\n\t\t\tp.log.success('Logged in to velastack.dev');\n\t\t}, 'Failed to login.')\n\t);\n\nexport async function issueApiKey(fetchCookie: FetchCookie): Promise<string> {\n\tconst label = `CLI - ${os.hostname()}`;\n\n\tawait fetchCookie(`${API_URL}/api-keys/new`, {\n\t\tmethod: 'POST',\n\t\theaders: {\n\t\t\t'Content-Type': 'application/x-www-form-urlencoded',\n\t\t\tOrigin: API_URL\n\t\t},\n\t\tbody: new URLSearchParams({ label }).toString()\n\t});\n\n\tconst cookie = await fetchCookie.cookieJar.getCookieString(API_URL);\n\tconst apiKey = extractApiKey(cookie);\n\tif (!apiKey) {\n\t\tthrow new Error('Failed to create API key. Try again or contact support.');\n\t}\n\n\tconst [id] = apiKey.split('.');\n\tconst res = await fetchCookie(`${API_URL}/api/collections/api_keys/records`, {\n\t\theaders: { Authorization: `Bearer ${apiKey}` }\n\t});\n\tconst data = (await res.json()) as { items: Array<{ id: string; label: string }> };\n\tfor (const item of data.items) {\n\t\tif (item.label === label && item.id !== id) {\n\t\t\tawait fetchCookie(`${API_URL}/api/collections/api_keys/records/${item.id}`, {\n\t\t\t\tmethod: 'DELETE',\n\t\t\t\theaders: { Authorization: `Bearer ${apiKey}` }\n\t\t\t});\n\t\t}\n\t}\n\n\treturn apiKey;\n}\n\nfunction extractApiKey(cookie: string): string | null {\n\tconst flashCookie = cookie.split(';').find((c) => c.trim().startsWith('flash='));\n\tif (!flashCookie) return null;\n\tconst decoded = decodeURIComponent(flashCookie.split('=')[1]!);\n\treturn (JSON.parse(decoded) as { apiKey: string }).apiKey;\n}\n", "import { Command } from 'commander';\nimport * as p from '@clack/prompts';\nimport { helpConfig } from '../lib/help.ts';\nimport { clearConfig, readConfig } from '../lib/config.ts';\nimport { runCommand } from '../lib/run.ts';\n\nexport const logout = new Command('logout')\n\t.alias('signout')\n\t.description('logout from velastack.dev')\n\t.configureHelp(helpConfig)\n\t.action(() =>\n\t\trunCommand(() => {\n\t\t\tif (!readConfig()) {\n\t\t\t\tp.log.info('Not logged in');\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tclearConfig();\n\t\t\tp.log.success('Logged out of velastack.dev');\n\t\t})\n\t);\n", "import { Command } from 'commander';\nimport * as p from '@clack/prompts';\nimport { helpConfig } from '../lib/help.ts';\nimport { API_URL } from '../lib/constants.ts';\nimport { readConfig } from '../lib/config.ts';\nimport { runCommand } from '../lib/run.ts';\n\nexport const whoami = new Command('whoami')\n\t.description('show the current user')\n\t.configureHelp(helpConfig)\n\t.action(() =>\n\t\trunCommand(async () => {\n\t\t\tconst apiKey = readConfig()?.apiKey;\n\t\t\tif (!apiKey) {\n\t\t\t\tp.log.info('Not logged in. Run `vela login` to login.');\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst res = await fetch(`${API_URL}/api/collections/users/records`, {\n\t\t\t\theaders: { Authorization: `Bearer ${apiKey}` }\n\t\t\t});\n\t\t\tconst data = (await res.json()) as { items: Array<{ email: string }> };\n\t\t\tif (!data.items.length) throw new Error('No user found. Run `vela login` to login.');\n\t\t\tp.log.success(`Logged in as ${data.items[0]!.email}`);\n\t\t})\n\t);\n", "import { Command } from 'commander';\nimport { helpConfig } from '../lib/help.ts';\nimport { runCommand } from '../lib/run.ts';\nimport { up, runMigrateUp } from './migrate/up.ts';\nimport { down } from './migrate/down.ts';\nimport { create } from './migrate/create.ts';\nimport { collections } from './migrate/collections.ts';\nimport { historySync } from './migrate/history-sync.ts';\n\nexport const migrate = new Command('migrate')\n\t.description('manage database migrations')\n\t.configureHelp(helpConfig)\n\t.action(() => runCommand(runMigrateUp, 'Failed to run migrations.'))\n\t.addCommand(up)\n\t.addCommand(down)\n\t.addCommand(create)\n\t.addCommand(collections)\n\t.addCommand(historySync);\n", "import { Command } from 'commander';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand } from '../../lib/run.ts';\nimport { runPocketbaseMigrate } from '../../lib/migrate.ts';\nimport { reportResult } from '../../lib/result-report.ts';\n\nexport async function runMigrateUp(): Promise<void> {\n\tawait runPocketbaseMigrate(['up']);\n\treportResult({\n\t\tsummary: 'Ran pending migrations.',\n\t\tnextSteps: [\n\t\t\t'Run `vela sync` to refresh generated TypeScript types from the updated schema.',\n\t\t\t'Run `vela dev` to pick up the new schema in the running app.',\n\t\t\t'Run `vela migrate down` if you need to revert the last migration.'\n\t\t]\n\t});\n}\n\nexport const up = new Command('up')\n\t.description('apply all pending migrations')\n\t.configureHelp(helpConfig)\n\t.action(() => runCommand(runMigrateUp, 'Failed to run migrations.'));\n", "import path from 'node:path';\nimport process from 'node:process';\nimport { x } from 'tinyexec';\nimport { DATA_DIR, MIGRATIONS_DIR } from './constants.ts';\n\nexport async function runPocketbaseMigrate(args: string[]): Promise<void> {\n\tconst cwd = process.cwd();\n\tconst { getBinaryPath } = await import('pocketbase-server');\n\tconst binaryPath = getBinaryPath();\n\n\tawait x(\n\t\tbinaryPath,\n\t\t[\n\t\t\t'--dir',\n\t\t\tpath.join(cwd, DATA_DIR),\n\t\t\t'--migrationsDir',\n\t\t\tpath.join(cwd, MIGRATIONS_DIR),\n\t\t\t'migrate',\n\t\t\t...args\n\t\t],\n\t\t{\n\t\t\tnodeOptions: { cwd, stdio: 'inherit' },\n\t\t\tthrowOnError: true\n\t\t}\n\t);\n}\n", "import { Command, InvalidArgumentError } from 'commander';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand } from '../../lib/run.ts';\nimport { runPocketbaseMigrate } from '../../lib/migrate.ts';\nimport { reportResult } from '../../lib/result-report.ts';\n\nexport function parseSteps(value: string): number {\n\tconst n = parseInt(value, 10);\n\tif (!Number.isFinite(n) || n <= 0) {\n\t\tthrow new InvalidArgumentError('number must be a positive integer');\n\t}\n\treturn n;\n}\n\nexport const down = new Command('down')\n\t.alias('rollback')\n\t.description('revert the last N applied migrations')\n\t.argument('[number]', 'how many migrations to revert', parseSteps, 1)\n\t.configureHelp(helpConfig)\n\t.action((n: number) =>\n\t\trunCommand(async () => {\n\t\t\tawait runPocketbaseMigrate(['down', String(n)]);\n\t\t\treportResult({\n\t\t\t\tsummary: `Reverted the last ${n} migration(s).`,\n\t\t\t\tnextSteps: [\n\t\t\t\t\t'Run `vela sync` to regenerate TypeScript types after the rollback.',\n\t\t\t\t\t'Run `vela migrate up` to reapply reverted migrations when ready.'\n\t\t\t\t]\n\t\t\t});\n\t\t}, 'Failed to revert migrations.')\n\t);\n", "import fs from 'node:fs';\nimport path from 'node:path';\nimport process from 'node:process';\nimport { Command } from 'commander';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand } from '../../lib/run.ts';\nimport { runPocketbaseMigrate } from '../../lib/migrate.ts';\nimport { MIGRATIONS_DIR } from '../../lib/constants.ts';\nimport { reportResult } from '../../lib/result-report.ts';\n\nexport const create = new Command('create')\n\t.alias('new')\n\t.description('create a new blank migration')\n\t.argument('<name>', 'migration name (snake_case)')\n\t.configureHelp(helpConfig)\n\t.action((name: string) =>\n\t\trunCommand(async () => {\n\t\t\tconst cwd = process.cwd();\n\t\t\tconst before = listMigrationFiles(cwd);\n\t\t\tawait runPocketbaseMigrate(['create', name]);\n\t\t\tconst after = listMigrationFiles(cwd);\n\t\t\tconst added = [...after].filter((f) => !before.has(f));\n\n\t\t\treportResult({\n\t\t\t\tsummary: `Created blank migration ${name}.`,\n\t\t\t\tfilesCreated: added.map((f: string) => path.join(MIGRATIONS_DIR, f)),\n\t\t\t\tnextSteps: [\n\t\t\t\t\t`Open the new file in ${MIGRATIONS_DIR}/ and fill in the up/down handlers.`,\n\t\t\t\t\t'Run `vela migrate up` to apply the migration once the handlers are written.'\n\t\t\t\t]\n\t\t\t});\n\t\t}, 'Failed to create migration.')\n\t);\n\nfunction listMigrationFiles(cwd: string): Set<string> {\n\tconst dir = path.join(cwd, MIGRATIONS_DIR);\n\tif (!fs.existsSync(dir)) return new Set();\n\treturn new Set(fs.readdirSync(dir).filter((f) => /\\.[jt]s$/.test(f)));\n}\n", "import fs from 'node:fs';\nimport path from 'node:path';\nimport process from 'node:process';\nimport { Command } from 'commander';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand } from '../../lib/run.ts';\nimport { runPocketbaseMigrate } from '../../lib/migrate.ts';\nimport { MIGRATIONS_DIR } from '../../lib/constants.ts';\nimport { reportResult } from '../../lib/result-report.ts';\n\nexport const collections = new Command('collections')\n\t.alias('snapshot')\n\t.description('snapshot local collections into a new migration')\n\t.configureHelp(helpConfig)\n\t.action(() =>\n\t\trunCommand(async () => {\n\t\t\tconst cwd = process.cwd();\n\t\t\tconst before = listMigrationFiles(cwd);\n\t\t\tawait runPocketbaseMigrate(['collections']);\n\t\t\tconst after = listMigrationFiles(cwd);\n\t\t\tconst added = [...after].filter((f) => !before.has(f));\n\n\t\t\tif (added.length === 0) {\n\t\t\t\treportResult({\n\t\t\t\t\tsummary: 'No schema changes to snapshot \u2014 migrations are already up to date.'\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\treportResult({\n\t\t\t\tsummary: 'Snapshotted local collections into a new migration.',\n\t\t\t\tfilesCreated: added.map((f: string) => path.join(MIGRATIONS_DIR, f)),\n\t\t\t\tnextSteps: [\n\t\t\t\t\t`Review the generated snapshot in ${MIGRATIONS_DIR}/.`,\n\t\t\t\t\t'Commit the snapshot so teammates pick up the new schema.',\n\t\t\t\t\t'Run `vela migrate up` on other environments to apply the schema.'\n\t\t\t\t]\n\t\t\t});\n\t\t}, 'Failed to snapshot collections.')\n\t);\n\nfunction listMigrationFiles(cwd: string): Set<string> {\n\tconst dir = path.join(cwd, MIGRATIONS_DIR);\n\tif (!fs.existsSync(dir)) return new Set();\n\treturn new Set(fs.readdirSync(dir).filter((f) => /\\.[jt]s$/.test(f)));\n}\n", "import { Command } from 'commander';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand } from '../../lib/run.ts';\nimport { runPocketbaseMigrate } from '../../lib/migrate.ts';\nimport { reportResult } from '../../lib/result-report.ts';\n\nexport const historySync = new Command('history-sync')\n\t.description('drop _migrations rows whose files no longer exist')\n\t.configureHelp(helpConfig)\n\t.action(() =>\n\t\trunCommand(async () => {\n\t\t\tawait runPocketbaseMigrate(['history-sync']);\n\t\t\treportResult({\n\t\t\t\tsummary: 'Synced migration history with files on disk.',\n\t\t\t\tnextSteps: ['Run `vela migrate up` if any pending migrations surfaced after the sync.']\n\t\t\t});\n\t\t}, 'Failed to sync migration history.')\n\t);\n", "import fs from 'node:fs';\nimport path from 'node:path';\nimport process from 'node:process';\nimport { performance } from 'node:perf_hooks';\nimport type { ChildProcess } from 'node:child_process';\nimport type { AddressInfo } from 'node:net';\nimport { Command, InvalidArgumentError } from 'commander';\nimport type { InlineConfig } from 'vite';\nimport pc from 'picocolors';\nimport PocketBase from 'pocketbase';\nimport { helpConfig } from '../lib/help.ts';\nimport { DATA_DIR, MIGRATIONS_DIR } from '../lib/constants.ts';\nimport { startPocketbaseServe } from '../lib/pocketbase.ts';\nimport { hasBackend, localDataDir } from '../lib/workspace.ts';\nimport { loadVite } from '../lib/vite.ts';\n\n/**\n * Vite dev-server flags worth forwarding, spelled exactly as vite's own CLI\n * spells them so anything learned there carries over. `--open` is the one\n * `vela create` tells users to run.\n */\ninterface DevOptions {\n\topen?: boolean | string;\n\thost?: boolean | string;\n\tport?: number;\n\tcors?: boolean;\n\tstrictPort?: boolean;\n\tforce?: boolean;\n}\n\n/** Everything except `--force`, which vite routes outside `server`. */\ntype ServerFlags = Omit<DevOptions, 'force'>;\n\nfunction parsePort(value: string): number {\n\tconst port = Number(value);\n\tif (!Number.isInteger(port) || port < 1 || port > 65535) {\n\t\tthrow new InvalidArgumentError('must be a whole number between 1 and 65535.');\n\t}\n\treturn port;\n}\n\nexport const dev = new Command('dev')\n\t.description('start the development server')\n\t.option('--open [path]', 'open the app in a browser once the server is ready')\n\t.option('--host [host]', 'expose the server on the network')\n\t.option('--port <port>', 'port to listen on', parsePort)\n\t.option('--strictPort', 'exit if the port is already in use instead of taking the next one')\n\t.option('--cors', 'enable CORS')\n\t.option('--force', 're-bundle dependencies, ignoring the optimizer cache')\n\t.configureHelp(helpConfig)\n\t.action(async (options: DevOptions) => {\n\t\tconst cwd = process.cwd();\n\n\t\t// Every other context reads the data directory out of the environment, so\n\t\t// the one this machine uses has to be there too \u2014 otherwise the fallback\n\t\t// is the only code path local development ever exercises.\n\t\tprocess.env.VELA_DATA_DIR ??= localDataDir(cwd);\n\t\tconst startTime = performance.now();\n\n\t\tconst { createServer, version } = await loadVite(cwd);\n\n\t\tconst viteMetadataDir = path.join(cwd, 'node_modules', '.vite');\n\t\tconst viteMetadataFile = path.join(viteMetadataDir, '_pocketbase_metadata.json');\n\n\t\tlet pbProc: ChildProcess | undefined;\n\t\t// A static project has no PocketBase to start, and nothing to sync types from.\n\t\tconst backend = hasBackend(cwd);\n\t\tconst needsStart = backend && !process.env.POCKETBASE_URL;\n\n\t\tconst cleanup = () => {\n\t\t\tif (pbProc?.pid) pbProc.kill();\n\t\t\tif (fs.existsSync(viteMetadataFile)) fs.rmSync(viteMetadataFile);\n\t\t};\n\n\t\tif (needsStart) {\n\t\t\tconst dataDir = path.join(cwd, DATA_DIR);\n\t\t\tconst started = await startPocketbaseServe({\n\t\t\t\tdataDir,\n\t\t\t\tmigrationsDir: MIGRATIONS_DIR,\n\t\t\t\thooksDir: path.join(dataDir, 'hooks'),\n\t\t\t\tdev: true,\n\t\t\t\tstdio: 'pipe'\n\t\t\t});\n\t\t\tpbProc = started.proc;\n\t\t\tprocess.env.POCKETBASE_URL = started.url;\n\n\t\t\tpbProc.stdout?.pipe(process.stdout);\n\t\t\tpbProc.stderr?.pipe(process.stderr);\n\t\t\tpbProc.on('error', (err) => console.error('PocketBase error:', err));\n\t\t\tpbProc.on('exit', (code) => console.log(`PocketBase exited with code ${code}`));\n\n\t\t\tprocess.on('exit', cleanup);\n\t\t\tprocess.on('SIGINT', () => {\n\t\t\t\tcleanup();\n\t\t\t\tprocess.exit(0);\n\t\t\t});\n\t\t}\n\n\t\t// Only forward what was actually passed: an explicit `undefined` here would\n\t\t// still be merged over whatever vite.config.ts sets.\n\t\tconst serverOptions: ServerFlags = {};\n\t\tif (options.open !== undefined) serverOptions.open = options.open;\n\t\tif (options.host !== undefined) serverOptions.host = options.host;\n\t\tif (options.port !== undefined) serverOptions.port = options.port;\n\t\tif (options.cors !== undefined) serverOptions.cors = options.cors;\n\t\tif (options.strictPort !== undefined) serverOptions.strictPort = options.strictPort;\n\n\t\t// `--force` is not a server option: vite's CLI strips it from the server\n\t\t// config and passes it as `forceOptimizeDeps`. Typed as vite's own\n\t\t// `InlineConfig` so a renamed or dropped option fails `lint:ts` here\n\t\t// rather than being silently ignored at runtime.\n\t\tconst inlineConfig: InlineConfig = {\n\t\t\tserver: serverOptions\n\t\t};\n\t\tif (options.force !== undefined) inlineConfig.forceOptimizeDeps = options.force;\n\n\t\tconst server = await createServer(inlineConfig);\n\n\t\tserver.httpServer?.on('listening', async () => {\n\t\t\tif (!backend) return;\n\n\t\t\tconst { address, port: vitePort } = server.httpServer!.address() as AddressInfo;\n\t\t\tconst viteHost = address === '::1' ? 'localhost' : address;\n\t\t\tawait fs.promises.mkdir(viteMetadataDir, { recursive: true });\n\t\t\tawait fs.promises.writeFile(\n\t\t\t\tviteMetadataFile,\n\t\t\t\tJSON.stringify({\n\t\t\t\t\tpocketbaseUrl: process.env.POCKETBASE_URL,\n\t\t\t\t\tvitePort,\n\t\t\t\t\tviteHost\n\t\t\t\t})\n\t\t\t);\n\n\t\t\tconst pb = new PocketBase(process.env.POCKETBASE_URL!);\n\t\t\tawait pb\n\t\t\t\t.collection('_superusers')\n\t\t\t\t.authWithPassword(\n\t\t\t\t\tprocess.env.POCKETBASE_SUPERUSER_EMAIL!,\n\t\t\t\t\tprocess.env.POCKETBASE_SUPERUSER_PASSWORD!\n\t\t\t\t);\n\t\t\tawait pb.settings.update({ meta: { appURL: `http://${viteHost}:${vitePort}` } });\n\n\t\t\tawait startWatchingTypes(cwd, pb);\n\t\t});\n\n\t\tawait server.listen();\n\n\t\tconst hasExistingLogs = process.stdout.bytesWritten > 0 || process.stderr.bytesWritten > 0;\n\t\tconst startupDurationString = pc.dim(\n\t\t\t`ready in ${pc.reset(pc.bold(Math.ceil(performance.now() - startTime)))} ms`\n\t\t);\n\t\tserver.config.logger.info(\n\t\t\t`\\n ${pc.green(`${pc.bold('VITE')} v${version}`)} ${startupDurationString}\\n`,\n\t\t\t{ clear: !hasExistingLogs }\n\t\t);\n\t\tserver.printUrls();\n\t\tserver.bindCLIShortcuts({ print: true });\n\t});\n\nasync function startWatchingTypes(cwd: string, pb: PocketBase): Promise<void> {\n\tconst { processTypes } = await import('@velastack/pocketbase-codegen');\n\n\tconst typesDir = path.resolve(cwd, '.svelte-kit', 'types');\n\tconst pocketbaseDir = path.join(typesDir, 'pocketbase');\n\tconst pocketbaseTypes = path.join(pocketbaseDir, '$types.d.ts');\n\n\tconst regenerate = () => processTypes(pb, typesDir).catch(() => {});\n\n\t// Never let a first-run failure escape: this runs inside an async\n\t// `listening` listener, where a rejection takes the process down, and it\n\t// would also leave the session with no watcher at all. Both SvelteKit and\n\t// handlePocketbase rely on that watcher to rebuild $types.d.ts after they\n\t// delete it, so losing it silently disables type sync for the session.\n\tawait regenerate();\n\n\t// Re-arm on failure: the watch is bound to the directory's inode, so\n\t// `rm -rf .svelte-kit` would otherwise kill it permanently.\n\tvoid (async () => {\n\t\tfor (;;) {\n\t\t\ttry {\n\t\t\t\tawait fs.promises.mkdir(pocketbaseDir, { recursive: true });\n\t\t\t\tfor await (const event of fs.promises.watch(pocketbaseDir)) {\n\t\t\t\t\tif (\n\t\t\t\t\t\tevent.eventType === 'rename' &&\n\t\t\t\t\t\tevent.filename === '$types.d.ts' &&\n\t\t\t\t\t\t!fs.existsSync(pocketbaseTypes)\n\t\t\t\t\t) {\n\t\t\t\t\t\tsetTimeout(regenerate, 100);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} catch {\n\t\t\t\t// directory vanished or the watch broke \u2014 rebuild and re-watch\n\t\t\t\tawait new Promise((r) => setTimeout(r, 200));\n\t\t\t}\n\t\t}\n\t})();\n}\n", "import path from 'node:path';\nimport process from 'node:process';\nimport { createRequire } from 'node:module';\nimport { pathToFileURL } from 'node:url';\nimport pc from 'picocolors';\n\n/**\n * The vite major the inline server configs in `vela dev` and `vela test:server`\n * are written against.\n */\nexport const REQUIRED_VITE_MAJOR = 8;\n\n/**\n * Returns an error message when `version` is too old for those inline configs,\n * or null when it is usable.\n *\n * An unparseable version returns null. A prerelease or fork string is not\n * evidence of a problem, and refusing to start over one we simply failed to\n * read would be worse than letting vite speak for itself.\n */\nexport function viteVersionError(version: string): string | null {\n\tconst major = Number.parseInt(version, 10);\n\tif (!Number.isFinite(major) || major >= REQUIRED_VITE_MAJOR) return null;\n\n\treturn [\n\t\t`This project has vite ${version}, but vela needs vite ${REQUIRED_VITE_MAJOR} or newer.`,\n\t\t'',\n\t\t' npm install -D vite@^8 @sveltejs/vite-plugin-svelte@^7',\n\t\t'',\n\t\t'Both move together: @sveltejs/vite-plugin-svelte 7 requires vite 8, and',\n\t\t'version 6 is the last that supports vite 7.'\n\t].join('\\n');\n}\n\n/**\n * Resolves the `vite` entry point as seen from `cwd`, or null when the project\n * has none.\n */\nfunction resolveProjectVite(cwd: string): string | null {\n\ttry {\n\t\treturn createRequire(path.join(cwd, 'package.json')).resolve('vite');\n\t} catch {\n\t\treturn null;\n\t}\n}\n\n/**\n * Loads the vite the *project* will actually be built with, and checks we can\n * drive it.\n *\n * Resolving from `cwd` rather than importing `vite` bare matters: a bare import\n * resolves relative to this file, which is the project's own `node_modules` for\n * a normal install but the CLI's for a global install, an `npx` run, or a linked\n * dev checkout. Since `createServer` reads the project's `vite.config.ts` either\n * way, a bare import can pair the project's config with a different vite than\n * the project declares.\n *\n * Falls back to a bare import when the project has no vite of its own, which\n * keeps `--help`-shaped and scratch invocations working.\n */\nexport async function loadVite(cwd: string = process.cwd()): Promise<typeof import('vite')> {\n\tconst entry = resolveProjectVite(cwd);\n\tconst vite: typeof import('vite') = entry\n\t\t? await import(pathToFileURL(entry).href)\n\t\t: await import('vite');\n\n\tconst error = viteVersionError(vite.version);\n\tif (error) {\n\t\tconsole.error(`${pc.redBright('\u2717')} ${error}`);\n\t\tprocess.exit(1);\n\t}\n\treturn vite;\n}\n", "import fs from 'node:fs';\nimport path from 'node:path';\nimport process from 'node:process';\nimport type { ChildProcess } from 'node:child_process';\nimport { Command } from 'commander';\nimport * as p from '@clack/prompts';\nimport pc from 'picocolors';\nimport { x } from 'tinyexec';\nimport { detect } from 'package-manager-detector';\nimport { resolveCommand } from 'package-manager-detector/commands';\nimport { helpConfig } from '../lib/help.ts';\nimport { DATA_DIR, MIGRATIONS_DIR } from '../lib/constants.ts';\nimport { ensureSuperuser, startPocketbaseServe } from '../lib/pocketbase.ts';\nimport { findWorkspaceRoot, hasBackend } from '../lib/workspace.ts';\nimport { applyBuildEnv } from '../lib/build-env.ts';\nimport { loadDeployConfig } from '../lib/deploy-config.ts';\nimport { parseTarget, PRODUCTION_TARGET } from '../lib/target.ts';\nimport { resolveOrigin } from '../lib/origin.ts';\n\n/** Where SvelteKit leaves the pages it rendered at build time. */\nconst PRERENDERED_DIR = path.join('.svelte-kit', 'output', 'prerendered');\n\nexport const build = new Command('build')\n\t.description('build the app')\n\t.configureHelp(helpConfig)\n\t.option('-t, --target <target>', 'which copy of the app to build for', PRODUCTION_TARGET)\n\t.action(async (options: { target?: string }) => {\n\t\tconst cwd = process.cwd();\n\n\t\tapplyBuildEnv(cwd);\n\n\t\t// Prerendering has no request to take an origin from, so the domain the\n\t\t// app is served on has to arrive as configuration or not at all.\n\t\tconst origin = await originForBuild(cwd, options.target);\n\t\tif (origin) process.env.VELA_ORIGIN = origin;\n\n\t\tlet pbProc: ChildProcess | undefined;\n\t\t// A static project has no PocketBase to start, and no `data` dir to start it from.\n\t\tconst needsStart = hasBackend(cwd) && !process.env.POCKETBASE_URL;\n\n\t\tconst cleanup = () => {\n\t\t\tif (pbProc?.pid) pbProc.kill();\n\t\t};\n\n\t\tif (needsStart) {\n\t\t\tawait ensureSuperuser(cwd);\n\t\t\tconst dataDir = path.join(cwd, DATA_DIR);\n\t\t\tconst started = await startPocketbaseServe({\n\t\t\t\tdataDir,\n\t\t\t\tmigrationsDir: MIGRATIONS_DIR,\n\t\t\t\thooksDir: path.join(dataDir, 'hooks'),\n\t\t\t\tdev: true\n\t\t\t});\n\t\t\tpbProc = started.proc;\n\t\t\tprocess.env.POCKETBASE_URL = started.url;\n\n\t\t\tprocess.on('exit', cleanup);\n\t\t\tprocess.on('SIGINT', () => {\n\t\t\t\tcleanup();\n\t\t\t\tprocess.exit(0);\n\t\t\t});\n\t\t}\n\n\t\ttry {\n\t\t\tconst pm = (await detect({ cwd }))?.name ?? 'npm';\n\t\t\tconst resolved = resolveCommand(pm, 'execute', ['vite', 'build'])!;\n\t\t\tconst args = resolved.args.slice();\n\t\t\tif (pm === 'npm') args.unshift('--yes');\n\t\t\tawait x(resolved.command, args, {\n\t\t\t\tnodeOptions: { cwd, stdio: 'inherit' },\n\t\t\t\tthrowOnError: true\n\t\t\t});\n\t\t} finally {\n\t\t\tcleanup();\n\t\t}\n\n\t\tif (!origin) warnIfPrerendered(cwd);\n\t});\n\n/**\n * The origin to render this build's absolute URLs against, if one is knowable.\n *\n * Resolution needs the workspace root rather than the cwd, and neither is worth\n * failing a build over: a project outside a workspace, or one whose target has\n * no domain yet, simply builds the way it always has.\n */\nasync function originForBuild(cwd: string, target: string | undefined): Promise<string | null> {\n\tconst workspaceRootDir = findWorkspaceRoot(cwd);\n\tif (!workspaceRootDir) return null;\n\n\ttry {\n\t\tconst parsed = parseTarget(target, PRODUCTION_TARGET);\n\t\t// `local` is this machine, where `url.origin` is already the dev server's.\n\t\tif (parsed.kind !== 'remote') return null;\n\n\t\tconst config = await loadDeployConfig(workspaceRootDir);\n\t\treturn resolveOrigin(workspaceRootDir, parsed.envTag, config);\n\t} catch {\n\t\treturn null;\n\t}\n}\n\n/**\n * Say so when pages were rendered against SvelteKit's placeholder host.\n *\n * Checked against the output rather than guessed from the routes beforehand,\n * because whether anything prerenders is a property of the build. Silence here\n * is what shipped `<link rel=\"canonical\" href=\"http://sveltekit-prerender/\">` to\n * production.\n */\nfunction warnIfPrerendered(cwd: string): void {\n\tconst dir = path.join(cwd, PRERENDERED_DIR);\n\tif (!fs.existsSync(dir) || fs.readdirSync(dir).length === 0) return;\n\n\tp.log.warn(\n\t\t`Prerendered pages were built with no domain configured, so their canonical\\n` +\n\t\t\t`links point at SvelteKit's placeholder host rather than at this site.\\n\\n` +\n\t\t\t`Set one with ${pc.cyan('vela deploy --domain example.com')}, or pass ${pc.cyan('VELA_ORIGIN')}.`\n\t);\n}\n", "import { localDataDir } from './workspace.ts';\n\n/**\n * The environment a build needs beyond whatever the shell already provides.\n *\n * Gathered in one named place rather than set inline at the top of the command,\n * because that is how `VITE_BUILD` was lost: a refactor changed the action's\n * signature and took the assignment with it, and nothing failed until a\n * prerendered page 500'd on a deploy days later.\n */\nexport function applyBuildEnv(cwd: string, env: NodeJS.ProcessEnv = process.env): void {\n\t// `@velastack/pocketbase` reads this to point its admin client straight at\n\t// PocketBase for the duration of the build. Without it the client keeps its\n\t// default relative base, so a prerendered page calls back into the app's own\n\t// admin proxy \u2014 which reads `url.search`, something SvelteKit forbids on a\n\t// prerendered page. The build then fails as an opaque `[500] GET /`.\n\tenv.VITE_BUILD = 'true';\n\n\t// Every other context reads the data directory out of the environment, so the\n\t// one this machine uses has to be there too \u2014 otherwise the fallback is the\n\t// only code path local development ever exercises. An explicit value wins.\n\tenv.VELA_DATA_DIR ??= localDataDir(cwd);\n}\n", "import process from 'node:process';\nimport { readBinding, type VelaAppConfig } from './deploy-config.ts';\n\n/**\n * The public origin a build renders absolute URLs against.\n *\n * Prerendering happens with no request to take an origin from, so SvelteKit\n * substitutes `http://sveltekit-prerender` and every canonical link, `og:url`\n * and `hreflang` baked into a prerendered page points at a host that does not\n * exist. The domain the app is actually served on is already known here \u2014 it is\n * the one Caddy is configured with \u2014 so the build is told about it and\n * `kit.prerender.origin` takes over.\n *\n * Null rather than a guess: an origin invented from a default would be wrong in\n * a way that is invisible until someone reads the shipped HTML, which is exactly\n * the failure this exists to end.\n */\nexport function resolveOrigin(\n\tworkspaceRootDir: string,\n\tenvTag: string,\n\tconfig: VelaAppConfig = {}\n): string | null {\n\treturn normalizeOrigin(\n\t\tprocess.env.VELA_ORIGIN ??\n\t\t\treadBinding(workspaceRootDir, envTag)?.domain ??\n\t\t\tconfig.deploy?.domain\n\t);\n}\n\n/**\n * Turn a configured domain into an origin, or null if it cannot be one.\n *\n * `--domain` takes the comma-separated list Caddy serves, and the first host is\n * the canonical one \u2014 the same choice `velastack/action` makes when it reports a\n * deployment's URL. A bare hostname gets `https://`, because that is what Caddy\n * terminates; anything already carrying a scheme is left alone, so a local\n * `http://127.0.0.1:4100` survives.\n */\nexport function normalizeOrigin(value: string | null | undefined): string | null {\n\tconst first = value?.split(',')[0]?.trim();\n\tif (!first) return null;\n\n\tconst withScheme = /^[a-z][a-z0-9+.-]*:\\/\\//i.test(first) ? first : `https://${first}`;\n\n\ttry {\n\t\tconst url = new URL(withScheme);\n\t\t// `origin` is scheme + host + non-default port and nothing else, which\n\t\t// drops any path, query or trailing slash a hand-written domain carried.\n\t\treturn url.origin;\n\t} catch {\n\t\treturn null;\n\t}\n}\n", "import path from 'node:path';\nimport process from 'node:process';\nimport type { ChildProcess } from 'node:child_process';\nimport { Command } from 'commander';\nimport { x } from 'tinyexec';\nimport { detect } from 'package-manager-detector';\nimport { resolveCommand } from 'package-manager-detector/commands';\nimport { helpConfig } from '../lib/help.ts';\nimport { DATA_DIR, MIGRATIONS_DIR } from '../lib/constants.ts';\nimport { startPocketbaseServe } from '../lib/pocketbase.ts';\nimport { hasBackend, localDataDir } from '../lib/workspace.ts';\n\nexport const preview = new Command('preview')\n\t.description('preview the built app')\n\t.configureHelp(helpConfig)\n\t.action(async () => {\n\t\tconst cwd = process.cwd();\n\n\t\t// Every other context reads the data directory out of the environment, so\n\t\t// the one this machine uses has to be there too \u2014 otherwise the fallback\n\t\t// is the only code path local development ever exercises.\n\t\tprocess.env.VELA_DATA_DIR ??= localDataDir(cwd);\n\n\t\tlet pbProc: ChildProcess | undefined;\n\t\t// A static project has no PocketBase to start, and no `data` dir to start it from.\n\t\tconst needsStart = hasBackend(cwd) && !process.env.POCKETBASE_URL;\n\n\t\tconst cleanup = () => {\n\t\t\tif (pbProc?.pid) pbProc.kill();\n\t\t};\n\n\t\tif (needsStart) {\n\t\t\tconst dataDir = path.join(cwd, DATA_DIR);\n\t\t\tconst started = await startPocketbaseServe({\n\t\t\t\tdataDir,\n\t\t\t\tmigrationsDir: MIGRATIONS_DIR,\n\t\t\t\thooksDir: path.join(dataDir, 'hooks'),\n\t\t\t\tdev: true\n\t\t\t});\n\t\t\tpbProc = started.proc;\n\t\t\tprocess.env.POCKETBASE_URL = started.url;\n\n\t\t\tprocess.on('exit', cleanup);\n\t\t\tprocess.on('SIGINT', () => {\n\t\t\t\tcleanup();\n\t\t\t\tprocess.exit(0);\n\t\t\t});\n\t\t}\n\n\t\ttry {\n\t\t\tconst pm = (await detect({ cwd }))?.name ?? 'npm';\n\t\t\tconst resolved = resolveCommand(pm, 'execute', ['vite', 'preview'])!;\n\t\t\tconst args = resolved.args.slice();\n\t\t\tif (pm === 'npm') args.unshift('--yes');\n\t\t\tawait x(resolved.command, args, {\n\t\t\t\tnodeOptions: { cwd, stdio: 'inherit' },\n\t\t\t\tthrowOnError: true\n\t\t\t});\n\t\t} finally {\n\t\t\tcleanup();\n\t\t}\n\t});\n", "import path from 'node:path';\nimport { Command } from 'commander';\nimport { helpConfig } from '../lib/help.ts';\nimport { runCommand } from '../lib/run.ts';\nimport { getWorkspace } from '../lib/workspace.ts';\nimport { withPocketbase } from '../lib/pocketbase.ts';\n\nexport const sync = new Command('sync')\n\t.description('sync types from the database')\n\t.configureHelp(helpConfig)\n\t.action(() =>\n\t\trunCommand(async () => {\n\t\t\tconst { workspaceRootDir } = await getWorkspace();\n\t\t\tconst typesDir = path.join(workspaceRootDir, '.svelte-kit', 'types');\n\n\t\t\tconst { processTypes } = await import('@velastack/pocketbase-codegen');\n\n\t\t\tawait withPocketbase(workspaceRootDir, async (pb) => {\n\t\t\t\tawait processTypes(pb, typesDir);\n\t\t\t});\n\n\t\t\tconsole.log('types synced');\n\t\t}, 'Failed to sync types.')\n\t);\n", "import { Command } from 'commander';\nimport * as p from '@clack/prompts';\nimport pc from 'picocolors';\nimport * as v from 'valibot';\nimport pkg from '../../package.json' with { type: 'json' };\nimport { helpConfig } from '../lib/help.ts';\nimport { runCommand } from '../lib/run.ts';\nimport { parseOptions } from '../lib/options.ts';\nimport { withSsh } from '../lib/ssh.ts';\nimport { pocketbaseVersion } from '../lib/pocketbase.ts';\nimport { readServerInfo, runServerScript, syncServerScripts } from '../lib/remote.ts';\nimport { sshOptionsFrom, SSH_OPTION_SCHEMA, addSshOptions } from '../lib/ssh-options.ts';\n\nconst OptionsSchema = v.object({\n\t...SSH_OPTION_SCHEMA,\n\tpbVersion: v.optional(v.string()),\n\tnodeMajor: v.optional(v.string())\n});\n\nexport const provision = addSshOptions(\n\tnew Command('provision')\n\t\t.description('prepare a server to host vela apps')\n\t\t.argument('<target>', 'SSH target \u2014 an alias from ~/.ssh/config, or user@host')\n\t\t.configureHelp(helpConfig)\n)\n\t.option('--pb-version <version>', 'PocketBase version to install')\n\t.option('--node-major <version>', 'Node.js major version to install', '22')\n\t.action((target: string, raw: unknown) =>\n\t\trunCommand(async () => {\n\t\t\tconst options = parseOptions(OptionsSchema, raw);\n\t\t\tconst pbVersion = options.pbVersion ?? pocketbaseVersion();\n\n\t\t\tp.intro(pc.bgCyan(pc.black(' vela provision ')));\n\t\t\tp.log.info(`Target ${pc.cyan(target)}`);\n\n\t\t\tawait withSsh(target, sshOptionsFrom(options), async (session) => {\n\t\t\t\tawait session.detectElevation();\n\n\t\t\t\tconst existing = await readServerInfo(session);\n\t\t\t\tif (existing) {\n\t\t\t\t\tp.log.info(\n\t\t\t\t\t\t`Already provisioned by vela ${existing.cliVersion} on ${existing.provisionedAt}. Bringing it up to date.`\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tp.log.step('Uploading server scripts');\n\t\t\t\tawait syncServerScripts(session);\n\n\t\t\t\tp.log.step('Running provision');\n\t\t\t\tconst result = await runServerScript<{\n\t\t\t\t\tnode: string;\n\t\t\t\t\tcaddy: string;\n\t\t\t\t\tpocketbase: string;\n\t\t\t\t}>(session, 'provision.sh', {\n\t\t\t\t\targs: [\n\t\t\t\t\t\t'--pb-version',\n\t\t\t\t\t\tpbVersion,\n\t\t\t\t\t\t'--node-major',\n\t\t\t\t\t\toptions.nodeMajor ?? '22',\n\t\t\t\t\t\t'--cli-version',\n\t\t\t\t\t\tpkg.version\n\t\t\t\t\t],\n\t\t\t\t\tstream: true\n\t\t\t\t});\n\n\t\t\t\tp.log.success(\n\t\t\t\t\t`${target} is ready.\\n\\n` +\n\t\t\t\t\t\t` Node ${result?.node ?? 'installed'}\\n` +\n\t\t\t\t\t\t` Caddy ${result?.caddy ?? 'installed'}\\n` +\n\t\t\t\t\t\t` PocketBase ${result?.pocketbase ?? pbVersion}`\n\t\t\t\t);\n\t\t\t});\n\n\t\t\tp.outro(`Deploy with ${pc.cyan(`vela deploy --server ${target}`)}`);\n\t\t}, 'Failed to provision.')\n\t);\n", "import path from 'node:path';\nimport fs from 'node:fs';\nimport { Command, Option } from 'commander';\nimport * as p from '@clack/prompts';\nimport pc from 'picocolors';\nimport * as v from 'valibot';\nimport { helpConfig } from '../lib/help.ts';\nimport { runCommand } from '../lib/run.ts';\nimport { parseOptions } from '../lib/options.ts';\nimport { getWorkspace, hasBackend } from '../lib/workspace.ts';\nimport { withSsh, type SshSession } from '../lib/ssh.ts';\nimport { addSshOptions, SSH_OPTION_SCHEMA, sshOptionsFrom } from '../lib/ssh-options.ts';\nimport { writeBinding } from '../lib/deploy-config.ts';\nimport { addTargetOptions, withTarget } from '../lib/server-command.ts';\nimport { instanceId, normalizeEnvTag, releaseId } from '../lib/instance.ts';\nimport { ensureSuperuser, findFreePort, pocketbaseVersion } from '../lib/pocketbase.ts';\nimport { readLocalMeta, readRemoteAppURL, seedRemoteMeta } from '../lib/pocketbase-settings.ts';\nimport { normalizeOrigin } from '../lib/origin.ts';\nimport { restartInstance } from '../lib/remote-env.ts';\nimport {\n\treadInstanceStates,\n\tremotePaths,\n\ttype InstanceState,\n\trequireProvisioned,\n\trunServerScript,\n\tsyncServerScripts\n} from '../lib/remote.ts';\nimport { collectArtifact, gitSha, runBuild } from '../lib/artifact.ts';\nimport { readRemoteEnv } from '../lib/remote-env.ts';\n\nconst OptionsSchema = v.object({\n\t...SSH_OPTION_SCHEMA,\n\tenv: v.optional(v.string()),\n\tproject: v.optional(v.string()),\n\tremoteDb: v.optional(v.boolean()),\n\tdomain: v.optional(v.string()),\n\thealthPath: v.optional(v.string()),\n\tkeep: v.optional(v.string()),\n\tpbVersion: v.optional(v.string()),\n\tbuild: v.optional(v.boolean())\n});\n\nexport const deploy = addTargetOptions(\n\tnew Command('deploy').description('deploy the app').configureHelp(helpConfig),\n\t'production'\n)\n\t.option('--project <name>', 'override the project name')\n\t.option('--domain <hosts>', 'hostname(s) to serve on, comma separated')\n\t.option('--health-path <path>', 'path the health check requests')\n\t.option('--keep <count>', 'how many old releases to keep on the server')\n\t.option('--pb-version <version>', 'PocketBase version to run')\n\t.option('--no-build', 'deploy the existing build output without rebuilding')\n\t// Both spellings, with no default, so \"neither flag given\" stays\n\t// distinguishable from an explicit choice: commander would otherwise make\n\t// `--no-remote-db` alone default the value to true.\n\t.addOption(\n\t\tnew Option(\n\t\t\t'--remote-db',\n\t\t\t'render the build against the database on the server, over an SSH tunnel \u2014 on by default once the target has been deployed to'\n\t\t).default(undefined)\n\t)\n\t.addOption(\n\t\tnew Option('--no-remote-db', 'render the build against a throwaway local database').default(\n\t\t\tundefined\n\t\t)\n\t)\n\t.action((raw: unknown) =>\n\t\trunCommand(async () => {\n\t\t\tconst options = parseOptions(OptionsSchema, raw);\n\t\t\tconst backend = hasBackend();\n\t\t\tconst release = releaseId();\n\n\t\t\tp.intro(pc.bgCyan(pc.black(' vela deploy ')));\n\n\t\t\tawait withTarget(\n\t\t\t\traw,\n\t\t\t\t{\n\t\t\t\t\tremote: async (ctx) => {\n\t\t\t\t\t\tconst { session, instance, workspaceRootDir, config } = ctx;\n\t\t\t\t\t\tp.log.info(\n\t\t\t\t\t\t\t`${pc.cyan(ctx.appName)} ${pc.dim('\u2192')} ${pc.cyan(ctx.targetName)} ${pc.dim(`(${ctx.server})`)}`\n\t\t\t\t\t\t);\n\n\t\t\t\t\t\tconst [existing] = await readInstanceStates(session, instance);\n\t\t\t\t\t\t// The binding outranks the config file: one `deploy.domain` cannot\n\t\t\t\t\t\t// serve production and staging at once.\n\t\t\t\t\t\tconst domain =\n\t\t\t\t\t\t\toptions.domain ??\n\t\t\t\t\t\t\tctx.binding.domain ??\n\t\t\t\t\t\t\tconfig.deploy?.domain ??\n\t\t\t\t\t\t\texisting?.domain ??\n\t\t\t\t\t\t\t'';\n\t\t\t\t\t\t// Rendering against the database being deployed to is the default\n\t\t\t\t\t\t// once there is one to render against. Left off, a build quietly\n\t\t\t\t\t\t// used a throwaway local database instead, which is how prerendered\n\t\t\t\t\t\t// pages shipped with a developer's own data baked into them.\n\t\t\t\t\t\tconst askedForRemoteDb = options.remoteDb ?? config.deploy?.buildAgainstRemote;\n\t\t\t\t\t\tconst remoteDb = askedForRemoteDb ?? Boolean(existing?.pbPort);\n\n\t\t\t\t\t\tif (options.build !== false) {\n\t\t\t\t\t\t\t// Prerendering has no request to take an origin from, and the\n\t\t\t\t\t\t\t// binding is not written until further down, so a first deploy\n\t\t\t\t\t\t\t// learns its domain from here or not at all.\n\t\t\t\t\t\t\tconst origin = normalizeOrigin(process.env.VELA_ORIGIN ?? domain);\n\t\t\t\t\t\t\tlet buildEnv: Record<string, string | undefined> = origin\n\t\t\t\t\t\t\t\t? { VELA_ORIGIN: origin }\n\t\t\t\t\t\t\t\t: {};\n\t\t\t\t\t\t\tlet tunnel: Tunnel | null = null;\n\n\t\t\t\t\t\t\tif (backend && remoteDb) {\n\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\ttunnel = await openDatabaseTunnel(session, instance, existing);\n\t\t\t\t\t\t\t\t} catch (err) {\n\t\t\t\t\t\t\t\t\t// Asked for explicitly, the failure is the answer. Merely\n\t\t\t\t\t\t\t\t\t// defaulted on, it is only a reason to build the older way.\n\t\t\t\t\t\t\t\t\tif (askedForRemoteDb) throw err;\n\t\t\t\t\t\t\t\t\tp.log.warn(\n\t\t\t\t\t\t\t\t\t\t`Could not build against the ${pc.cyan(ctx.targetName)} database, ` +\n\t\t\t\t\t\t\t\t\t\t\t`using a local one instead.\\n${pc.dim(String(err))}`\n\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif (tunnel) {\n\t\t\t\t\t\t\t\tbuildEnv = { ...buildEnv, ...tunnel.env };\n\t\t\t\t\t\t\t\tp.log.info(\n\t\t\t\t\t\t\t\t\t`Building against the ${pc.cyan(ctx.targetName)} database on ${ctx.server} ${pc.dim(`(port ${tunnel.pbPort})`)}`\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t} else if (backend) {\n\t\t\t\t\t\t\t\t// The build renders pages against a local database, and on a fresh\n\t\t\t\t\t\t\t\t// checkout that database has no superuser yet. Done here as well as\n\t\t\t\t\t\t\t\t// in `vela build` so a project pinning an older CLI builds in CI.\n\t\t\t\t\t\t\t\tawait ensureSuperuser(workspaceRootDir);\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tp.log.step('Building');\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\tawait runBuild(workspaceRootDir, config.deploy?.buildCommand, buildEnv);\n\t\t\t\t\t\t\t} finally {\n\t\t\t\t\t\t\t\tif (tunnel) await tunnel.close();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst entries = collectArtifact(workspaceRootDir, config.deploy ?? {});\n\t\t\t\t\t\tconst sha = await gitSha(workspaceRootDir);\n\n\t\t\t\t\t\tp.log.step(`Uploading release ${pc.dim(release)}`);\n\t\t\t\t\t\tawait uploadRelease(session, instance, release, entries);\n\n\t\t\t\t\t\tp.log.step('Activating');\n\t\t\t\t\t\tconst result = await runServerScript<{\n\t\t\t\t\t\t\turl: string;\n\t\t\t\t\t\t\twebPort: number;\n\t\t\t\t\t\t\tpbPort: number;\n\t\t\t\t\t\t\tsuperuserCreated: boolean;\n\t\t\t\t\t\t}>(session, 'apply.sh', {\n\t\t\t\t\t\t\targs: [\n\t\t\t\t\t\t\t\tinstance,\n\t\t\t\t\t\t\t\trelease,\n\t\t\t\t\t\t\t\t'--name',\n\t\t\t\t\t\t\t\tctx.appName,\n\t\t\t\t\t\t\t\t'--app-id',\n\t\t\t\t\t\t\t\tctx.appId,\n\t\t\t\t\t\t\t\t'--env',\n\t\t\t\t\t\t\t\tctx.envTag,\n\t\t\t\t\t\t\t\t'--domain',\n\t\t\t\t\t\t\t\tdomain,\n\t\t\t\t\t\t\t\t'--health-path',\n\t\t\t\t\t\t\t\toptions.healthPath ?? config.deploy?.healthCheckPath ?? '/',\n\t\t\t\t\t\t\t\t'--keep',\n\t\t\t\t\t\t\t\toptions.keep ?? String(config.deploy?.keepReleases ?? 5),\n\t\t\t\t\t\t\t\t'--backend',\n\t\t\t\t\t\t\t\tbackend ? '1' : '0',\n\t\t\t\t\t\t\t\t'--pb-version',\n\t\t\t\t\t\t\t\toptions.pbVersion ?? config.deploy?.pocketbaseVersion ?? pocketbaseVersion(),\n\t\t\t\t\t\t\t\t'--git-sha',\n\t\t\t\t\t\t\t\tsha\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\tstream: true\n\t\t\t\t\t\t});\n\n\t\t\t\t\t\twriteBinding(workspaceRootDir, ctx.envTag, {\n\t\t\t\t\t\t\tserver: ctx.server,\n\t\t\t\t\t\t\tdomain: domain || undefined\n\t\t\t\t\t\t});\n\t\t\t\t\t\tif (!existing) await reportEmptyEnvironment(session, instance, workspaceRootDir);\n\n\t\t\t\t\t\tconst url = result?.url ?? '';\n\t\t\t\t\t\tp.log.success(\n\t\t\t\t\t\t\t`Deployed ${pc.cyan(ctx.appName)} ${pc.dim(release)}\\n\\n` +\n\t\t\t\t\t\t\t\t` URL ${url}\\n` +\n\t\t\t\t\t\t\t\t` Port ${result?.webPort ?? '?'}${backend ? ` (PocketBase ${result?.pbPort ?? '?'})` : ''}`\n\t\t\t\t\t\t);\n\n\t\t\t\t\t\t// Created by the server on the first deploy of a backend instance, and\n\t\t\t\t\t\t// never printed: the app reads it from the environment, and a human who\n\t\t\t\t\t\t// wants the admin UI sets their own with `vela env set`.\n\t\t\t\t\t\tif (result?.superuserCreated) {\n\t\t\t\t\t\t\tawait copyLocalBranding(\n\t\t\t\t\t\t\t\tsession,\n\t\t\t\t\t\t\t\tinstance,\n\t\t\t\t\t\t\t\tworkspaceRootDir,\n\t\t\t\t\t\t\t\tdomain ? (result?.url ?? '') : ''\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tp.log.info(\n\t\t\t\t\t\t\t\t`Created the PocketBase superuser this app authenticates as.\\n\\n` +\n\t\t\t\t\t\t\t\t\t`Its credentials are stored in the environment on the server. To use\\n` +\n\t\t\t\t\t\t\t\t\t`your own instead, ${pc.cyan('vela env set POCKETBASE_SUPERUSER_PASSWORD')}\\n` +\n\t\t\t\t\t\t\t\t\t`and deploy again.`\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t} else if (backend && domain) {\n\t\t\t\t\t\t\tawait reportAppURLDrift(session, instance, domain);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (!domain) {\n\t\t\t\t\t\t\tp.log.warn(\n\t\t\t\t\t\t\t\t`No domain configured, so nothing is proxied to this app yet.\\n` +\n\t\t\t\t\t\t\t\t\t`Redeploy with ${pc.cyan('--domain example.com')} once DNS points at ${ctx.server}.`\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t{ project: options.project, askDomain: true, label: 'deploy' }\n\t\t\t);\n\n\t\t\tp.outro(`${pc.cyan('vela status')} to see what is running`);\n\t\t}, 'Failed to deploy.')\n\t);\n\n/**\n * Point out an `appURL` that no longer matches the domain being deployed to.\n *\n * `appURL` is seeded once and belongs to the deployed admin panel from then on,\n * which is deliberate \u2014 it is how an app serves one canonical domain while being\n * deployed to another. That also makes it the one setting that can quietly go\n * stale after a domain change, taking password-reset emails and every other link\n * PocketBase renders with it. Reported rather than corrected, so the override\n * keeps working.\n */\nasync function reportAppURLDrift(\n\tsession: SshSession,\n\tinstance: string,\n\tdomain: string\n): Promise<void> {\n\tconst expected = normalizeOrigin(domain);\n\tif (!expected) return;\n\n\tconst current = await readRemoteAppURL(session, instance);\n\tif (!current || normalizeOrigin(current) === expected) return;\n\n\tp.log.warn(\n\t\t`This app's PocketBase ${pc.cyan('appURL')} is ${pc.dim(current)}, but it is served on ${pc.dim(expected)}.\\n\\n` +\n\t\t\t`Emails and anything else PocketBase links to will use the former. Update it in\\n` +\n\t\t\t`the admin panel if that is not deliberate.`\n\t);\n}\n\n/**\n * Give a database this deploy created the branding the project already has.\n *\n * A fresh PocketBase answers with its own defaults, which is how a new\n * deployment ends up calling itself \"Acme\" on every page that reads\n * `locals.meta`. Best-effort by design: the deploy has already succeeded, so\n * nothing here is worth failing it over.\n */\nasync function copyLocalBranding(\n\tsession: SshSession,\n\tinstance: string,\n\tworkspaceRootDir: string,\n\tappURL: string\n): Promise<void> {\n\tconst local = await readLocalMeta(workspaceRootDir);\n\tif (!local) return;\n\n\ttry {\n\t\tconst copied = await seedRemoteMeta(session, instance, local, appURL);\n\t\tif (copied.length === 0) return;\n\n\t\t// The app caches `meta` in process, and it read the defaults on the way up\n\t\t// a moment ago. Without this the site serves PocketBase's \"Acme\" until\n\t\t// something else happens to restart it.\n\t\tconst outcome = await restartInstance(session, instance);\n\t\tif (outcome.deployed && !outcome.restarted) {\n\t\t\tp.log.warn(\n\t\t\t\t`Copied ${copied.join(', ')}, but the app did not restart to pick them up.\\n` +\n\t\t\t\t\t`${pc.dim(outcome.error ?? '')}`\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tp.log.success(`Copied ${copied.join(', ')} from this project's database`);\n\t} catch (err) {\n\t\tp.log.warn(\n\t\t\t`Could not copy this project's PocketBase settings across.\\n` +\n\t\t\t\t`Set them in the admin panel instead. ${pc.dim(String(err))}`\n\t\t);\n\t}\n}\n\ninterface Tunnel {\n\tenv: Record<string, string>;\n\tpbPort: number;\n\tclose: () => Promise<void>;\n}\n\n/**\n * Point the build at the target's PocketBase through the SSH connection that is\n * already open.\n *\n * Pages that prerender from data are rendered at build time, so whatever\n * database the build can see is what gets baked into the static HTML. On a CI\n * runner that is an empty throwaway database, which silently produces pages\n * full of defaults. Building against the instance being deployed to is what a\n * developer's own machine approximates, and what makes CI output match.\n *\n * The superuser credentials come off the server itself, so nothing new has to be\n * stored in CI. The build should only ever read; a load function that writes\n * would write to the live database.\n */\nasync function openDatabaseTunnel(\n\tsession: SshSession,\n\tinstance: string,\n\tstate: InstanceState | undefined\n): Promise<Tunnel> {\n\tconst pbPort = state?.pbPort;\n\tif (!pbPort) {\n\t\tthrow new Error(\n\t\t\t`--remote-db needs an existing deployment to build against, and ${instance} has not been deployed yet.\\n\\n` +\n\t\t\t\t`Deploy once without it, then turn it on.`\n\t\t);\n\t}\n\n\tconst remoteEnv = await readRemoteEnv(session, instance);\n\tconst email = remoteEnv.POCKETBASE_SUPERUSER_EMAIL;\n\tconst password = remoteEnv.POCKETBASE_SUPERUSER_PASSWORD;\n\tif (!email || !password) {\n\t\t// Failing here beats failing thirty seconds later, inside the build, as an\n\t\t// \"invalid login credentials\" stack trace from the app's own hooks.\n\t\tthrow new Error(\n\t\t\t`--remote-db renders the build as the superuser of ${instance}, and that environment has no credentials for one.\\n\\n` +\n\t\t\t\t`Set them with \\`vela env set POCKETBASE_SUPERUSER_EMAIL\\` and \\`vela env set POCKETBASE_SUPERUSER_PASSWORD\\`.`\n\t\t);\n\t}\n\n\tconst localPort = await findFreePort('127.0.0.1');\n\tawait session.forwardLocalPort(localPort, '127.0.0.1', pbPort);\n\n\t// Having credentials is not the same as having ones the database accepts, and\n\t// the difference is invisible until the build is already running: the app\n\t// renders every page as an unauthenticated 500, and the deploy dies as\n\t// `[500] GET /` with nothing naming the cause.\n\t//\n\t// The two drift whenever the superuser password is changed in the admin panel,\n\t// because `$ETC/env` is what a deploy reconciles the database against, and\n\t// that reconciliation happens in `apply.sh` \u2014 after this build. So the first\n\t// deploy after such a change cannot repair itself; it fails here instead, and\n\t// this is where it has to be explained.\n\tif (!(await superuserAuthenticates(localPort, email, password))) {\n\t\tawait session.cancelForward(localPort, '127.0.0.1', pbPort);\n\t\tthrow new Error(\n\t\t\t`${instance} does not accept the superuser credentials in its own environment.\\n\\n` +\n\t\t\t\t`They are what \\`--remote-db\\` renders the build as. The usual cause is a password\\n` +\n\t\t\t\t`changed in the PocketBase admin panel, which leaves the database and\\n` +\n\t\t\t\t`${pc.cyan(`/etc/vela/apps/${instance}/env`)} disagreeing.\\n\\n` +\n\t\t\t\t`Point the environment at the password the database has:\\n` +\n\t\t\t\t` ${pc.cyan('vela env set POCKETBASE_SUPERUSER_PASSWORD')}\\n\\n` +\n\t\t\t\t`or build against a throwaway local database instead:\\n` +\n\t\t\t\t` ${pc.cyan('vela deploy --no-remote-db')}`\n\t\t);\n\t}\n\n\treturn {\n\t\tpbPort,\n\t\tenv: {\n\t\t\tPOCKETBASE_URL: `http://127.0.0.1:${localPort}`,\n\t\t\tPOCKETBASE_SUPERUSER_EMAIL: email,\n\t\t\tPOCKETBASE_SUPERUSER_PASSWORD: password\n\t\t},\n\t\tclose: () => session.cancelForward(localPort, '127.0.0.1', pbPort)\n\t};\n}\n\n/**\n * Whether the instance's own superuser credentials sign in to its database.\n *\n * A plain request rather than a PocketBase client: this runs before the build,\n * and all it needs to know is whether the password is the one on record.\n */\nasync function superuserAuthenticates(\n\tport: number,\n\tidentity: string,\n\tpassword: string\n): Promise<boolean> {\n\ttry {\n\t\tconst response = await fetch(\n\t\t\t`http://127.0.0.1:${port}/api/collections/_superusers/auth-with-password`,\n\t\t\t{\n\t\t\t\tmethod: 'POST',\n\t\t\t\theaders: { 'content-type': 'application/json' },\n\t\t\t\tbody: JSON.stringify({ identity, password })\n\t\t\t}\n\t\t);\n\t\treturn response.ok;\n\t} catch {\n\t\t// Unreachable is not the same as unauthorized, and the tunnel has its own\n\t\t// failure modes. Let the build proceed and report whatever it finds.\n\t\treturn true;\n\t}\n}\n\nasync function uploadRelease(\n\tsession: SshSession,\n\tinstance: string,\n\trelease: string,\n\tentries: { localPath: string; remoteDir: string }[]\n): Promise<void> {\n\tconst dir = remotePaths.release(instance, release);\n\tawait session.script(`mkdir -p \"$1\"`, { args: [dir] });\n\n\tconst byTarget = new Map<string, string[]>();\n\tfor (const entry of entries) {\n\t\tconst target = entry.remoteDir ? `${dir}/${entry.remoteDir}` : dir;\n\t\t// A trailing slash makes rsync copy a directory's contents rather than the\n\t\t// directory itself, which is what a renamed target (data/hooks -> hooks)\n\t\t// needs.\n\t\tconst source =\n\t\t\tentry.remoteDir && isDirectory(entry.localPath) ? `${entry.localPath}/` : entry.localPath;\n\t\tbyTarget.set(target, [...(byTarget.get(target) ?? []), source]);\n\t}\n\n\tfor (const [target, sources] of byTarget) {\n\t\tif (target !== dir) await session.script(`mkdir -p \"$1\"`, { args: [target] });\n\t\tawait session.upload(sources, target);\n\t}\n}\n\nfunction isDirectory(target: string): boolean {\n\ttry {\n\t\treturn fs.statSync(target).isDirectory();\n\t} catch {\n\t\treturn false;\n\t}\n}\n\n/**\n * A brand new instance starts with an empty production environment. Say so once,\n * rather than quietly shipping an app that cannot reach anything \u2014 but never\n * upload the local `.env`, which is a development file.\n */\nasync function reportEmptyEnvironment(\n\tsession: SshSession,\n\tinstance: string,\n\tworkspaceRootDir: string\n): Promise<void> {\n\tconst remote = await readRemoteEnv(session, instance);\n\tif (Object.keys(remote).length > 0) return;\n\tif (!fs.existsSync(path.join(workspaceRootDir, '.env'))) return;\n\n\tp.log.warn(\n\t\t`This app has no production environment variables yet.\\n\\n` +\n\t\t\t`Local ${pc.cyan('.env')} values are not uploaded by a deploy. Set them with\\n` +\n\t\t\t`${pc.cyan('vela env set KEY')}, or copy a file across with ${pc.cyan('vela env import .env.production')}.`\n\t);\n}\n", "import fs from 'node:fs';\nimport path from 'node:path';\nimport process from 'node:process';\nimport PocketBase from 'pocketbase';\nimport { DATA_DIR, MIGRATIONS_DIR } from './constants.ts';\nimport { authWithRetries, startPocketbaseServe } from './pocketbase.ts';\nimport { withRemotePocketbase } from './remote-pocketbase.ts';\nimport type { SshSession } from './ssh.ts';\n\n/**\n * Branding a new deployment inherits from the project's own database.\n *\n * Deliberately not everything under `meta`: `appURL` is per-deployment, and the\n * rest of PocketBase's settings \u2014 smtp, s3, backups \u2014 is either credentials or\n * an endpoint belonging to whichever machine it was configured on. Copying\n * those would push a developer's mail account into production silently.\n */\nconst COPIED_KEYS = ['appName', 'senderName', 'senderAddress'] as const;\n\ntype Meta = Record<string, unknown>;\n\n/**\n * Read the project's own PocketBase settings.\n *\n * The database is a file, so this starts a server against it just long enough\n * to ask. Returns null whenever that is not possible \u2014 no backend, no database\n * yet, no superuser to authenticate as \u2014 because none of those are reasons to\n * fail a deploy that has already succeeded.\n */\nexport async function readLocalMeta(cwd: string): Promise<Meta | null> {\n\tconst dataDir = path.join(cwd, DATA_DIR);\n\tif (!fs.existsSync(dataDir)) return null;\n\n\tconst email = process.env.POCKETBASE_SUPERUSER_EMAIL;\n\tconst password = process.env.POCKETBASE_SUPERUSER_PASSWORD;\n\tif (!email || !password) return null;\n\n\tlet proc: { kill: () => void } | undefined;\n\ttry {\n\t\tconst started = await startPocketbaseServe({\n\t\t\tdataDir,\n\t\t\tmigrationsDir: MIGRATIONS_DIR,\n\t\t\thooksDir: path.join(dataDir, 'hooks')\n\t\t});\n\t\tproc = started.proc;\n\n\t\tconst pb = new PocketBase(started.url);\n\t\tawait authWithRetries(pb, email, password);\n\t\tconst settings = (await pb.settings.getAll()) as { meta?: Meta };\n\t\treturn settings.meta ?? null;\n\t} catch {\n\t\treturn null;\n\t} finally {\n\t\tproc?.kill();\n\t}\n}\n\n/**\n * Read the `appURL` a deployment is currently telling itself it has.\n *\n * Only ever used to report a mismatch, so a database that cannot be reached is\n * not worth a word: the deploy has already succeeded either way.\n */\nexport async function readRemoteAppURL(\n\tsession: SshSession,\n\tinstance: string\n): Promise<string | null> {\n\ttry {\n\t\tlet appURL: string | null = null;\n\t\tawait withRemotePocketbase(session, instance, async (pb) => {\n\t\t\tconst settings = (await pb.settings.getAll()) as { meta?: Meta };\n\t\t\tconst value = settings.meta?.appURL;\n\t\t\tappURL = typeof value === 'string' && value.trim() ? value : null;\n\t\t});\n\t\treturn appURL;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\n/**\n * Give a freshly created deployment the project's branding.\n *\n * Only ever called for a database this deploy created: re-running it would\n * overwrite whatever had since been set in the deployed admin panel, and the\n * deployed value is the one that should win from then on.\n */\nexport async function seedRemoteMeta(\n\tsession: SshSession,\n\tinstance: string,\n\tlocal: Meta,\n\tappURL: string\n): Promise<string[]> {\n\tconst patch: Meta = {};\n\tfor (const key of COPIED_KEYS) {\n\t\tconst value = local[key];\n\t\tif (typeof value === 'string' && value.trim()) patch[key] = value;\n\t}\n\tif (appURL) patch.appURL = appURL;\n\tif (Object.keys(patch).length === 0) return [];\n\n\tawait withRemotePocketbase(session, instance, async (pb) => {\n\t\tconst settings = (await pb.settings.getAll()) as { meta?: Meta };\n\t\t// Merged rather than replaced: `meta` carries fields this does not set,\n\t\t// and PocketBase would take a bare object as the whole of it.\n\t\tawait pb.settings.update({ meta: { ...(settings.meta ?? {}), ...patch } });\n\t});\n\n\treturn Object.keys(patch);\n}\n", "import fs from 'node:fs';\nimport path from 'node:path';\nimport { detect } from 'package-manager-detector';\nimport { resolveCommand } from 'package-manager-detector/commands';\nimport { spawnCapture } from './ssh.ts';\nimport { DATA_DIR, MIGRATIONS_DIR } from './constants.ts';\nimport type { VelaDeployConfig } from './deploy-config.ts';\n\nexport const DEFAULT_OUTPUT_DIR = 'build';\n\n/** One entry in the release: a local path, and where it lands in the release. */\nexport interface ArtifactEntry {\n\tlocalPath: string;\n\t/** Remote subdirectory, or '' for the release root. */\n\tremoteDir: string;\n}\n\nexport class BuildError extends Error {}\n\n/**\n * Run the project's build. Defaults to the package manager's `build` script,\n * which in a vela project is `vela build` \u2014 the same command used locally, so\n * what ships is what was tested.\n */\nexport async function runBuild(\n\tcwd: string,\n\tbuildCommand?: string,\n\tenv?: Record<string, string | undefined>\n): Promise<void> {\n\tif (buildCommand) {\n\t\tconst result = await spawnCapture('bash', ['-lc', buildCommand], {\n\t\t\tcwd,\n\t\t\tstream: true,\n\t\t\tstreamStdout: true,\n\t\t\tenv\n\t\t});\n\t\tif (result.exitCode !== 0)\n\t\t\tthrow new BuildError(`\\`${buildCommand}\\` exited ${result.exitCode}.`);\n\t\treturn;\n\t}\n\n\tconst pm = (await detect({ cwd }))?.name ?? 'npm';\n\tconst resolved = resolveCommand(pm, 'run', ['build']);\n\tif (!resolved) throw new BuildError(`Could not work out how to run a build with ${pm}.`);\n\tconst result = await spawnCapture(resolved.command, resolved.args, {\n\t\tcwd,\n\t\tstream: true,\n\t\tstreamStdout: true,\n\t\tenv\n\t});\n\tif (result.exitCode !== 0) {\n\t\tthrow new BuildError(\n\t\t\t`\\`${resolved.command} ${resolved.args.join(' ')}\\` exited ${result.exitCode}.`\n\t\t);\n\t}\n}\n\n/**\n * Work out what goes into a release.\n *\n * The adapter output plus what PocketBase needs at runtime \u2014 nothing else. No\n * source, no dev dependencies, and deliberately no `.env`: production\n * environment lives on the server and is managed only by `vela env`.\n */\nexport function collectArtifact(cwd: string, config: VelaDeployConfig = {}): ArtifactEntry[] {\n\tconst outputDir = config.outputDir ?? DEFAULT_OUTPUT_DIR;\n\tconst entries: ArtifactEntry[] = [];\n\tconst add = (rel: string, remoteDir = '') => {\n\t\tconst localPath = path.join(cwd, rel);\n\t\tif (fs.existsSync(localPath)) entries.push({ localPath, remoteDir });\n\t};\n\n\tconst buildPath = path.join(cwd, outputDir);\n\tif (!fs.existsSync(path.join(buildPath, 'index.js'))) {\n\t\tthrow new BuildError(\n\t\t\t`No ${outputDir}/index.js after the build.\\n\\n` +\n\t\t\t\t`Deploying to a server needs @sveltejs/adapter-node. Install it and set it as\\n` +\n\t\t\t\t`the adapter in your Vite or Svelte config, then build again.`\n\t\t);\n\t}\n\tentries.push({ localPath: buildPath, remoteDir: '' });\n\n\tadd('package.json');\n\tadd('package-lock.json');\n\tadd('.npmrc');\n\tadd(MIGRATIONS_DIR);\n\t// PocketBase hooks live under `data/` locally but next to the release on the\n\t// server, where `data/` is the instance's private database directory.\n\tconst hooks = path.join(cwd, DATA_DIR, 'hooks');\n\tif (fs.existsSync(hooks)) entries.push({ localPath: hooks, remoteDir: 'hooks' });\n\n\tfor (const extra of config.include ?? []) add(extra);\n\n\treturn entries;\n}\n\nexport function hasLockfile(cwd: string): boolean {\n\treturn fs.existsSync(path.join(cwd, 'package-lock.json'));\n}\n\n/** Best-effort git metadata, recorded on the release for traceability. */\nexport async function gitSha(cwd: string): Promise<string> {\n\tconst result = await spawnCapture('git', ['rev-parse', 'HEAD'], { cwd });\n\treturn result.exitCode === 0 ? result.stdout.trim() : '';\n}\n", "import path from 'node:path';\nimport process from 'node:process';\nimport { Command } from 'commander';\nimport * as p from '@clack/prompts';\nimport { helpConfig } from '../lib/help.ts';\nimport { runCommand } from '../lib/run.ts';\nimport { requireApiKey } from '../lib/config.ts';\nimport { getWorkspace } from '../lib/workspace.ts';\nimport { readPackageJson } from '../lib/package-json.ts';\nimport { readProjectConfig, writeProjectConfig } from '../lib/project-config.ts';\nimport {\n\tcreateProject,\n\tgetCurrentUser,\n\tlistProjects,\n\tlistTeams,\n\ttype ProjectRecord,\n\ttype Team\n} from '../lib/velastack-api.ts';\n\nconst CREATE_NEW = '__new__';\n\nexport const link = new Command('link')\n\t.description('link this project to a velastack.dev project')\n\t.configureHelp(helpConfig)\n\t.action(() => runCommand(linkProject, 'Failed to link the project.'));\n\nasync function linkProject() {\n\tconst { workspaceRootDir } = await getWorkspace();\n\n\tconst existing = readProjectConfig(workspaceRootDir);\n\tif (existing) {\n\t\tp.log.success(`Linked to ${existing.projectName}.`);\n\t\treturn;\n\t}\n\n\tconst apiKey = requireApiKey();\n\tconst [user, teams, projects] = await Promise.all([\n\t\tgetCurrentUser(apiKey),\n\t\tlistTeams(apiKey),\n\t\tlistProjects(apiKey)\n\t]);\n\n\tlet projectId: string;\n\tlet teamId: string;\n\tlet projectName: string;\n\n\tconst picked = projects.length > 0 ? await pickExistingProject(projects) : CREATE_NEW;\n\tif (picked !== CREATE_NEW) {\n\t\tconst project = projects.find((pr) => pr.id === picked)!;\n\t\tprojectId = project.id;\n\t\tteamId = project.team;\n\t\tprojectName = project.name;\n\t} else {\n\t\tconst team = await pickTeam(teams);\n\t\tconst name = await promptProjectName(workspaceRootDir);\n\t\tconst created = await createProject(apiKey, { name, teamId: team.id, userId: user.id });\n\t\tprojectId = created.id;\n\t\tteamId = team.id;\n\t\tprojectName = created.name;\n\t}\n\n\twriteProjectConfig(workspaceRootDir, { projectId, teamId, projectName });\n\tp.log.success(`Linked to ${projectName}.`);\n}\n\nasync function pickExistingProject(projects: ProjectRecord[]): Promise<string> {\n\tconst choice = await p.select({\n\t\tmessage: 'Select a project',\n\t\toptions: [\n\t\t\t...projects.map((pr) => ({\n\t\t\t\tvalue: pr.id,\n\t\t\t\tlabel: `${pr.name} (${pr.expand?.team?.name ?? 'unknown team'})`\n\t\t\t})),\n\t\t\t{ value: CREATE_NEW, label: 'Create a new project' }\n\t\t]\n\t});\n\tif (p.isCancel(choice)) {\n\t\tp.cancel('Operation cancelled.');\n\t\tprocess.exit(0);\n\t}\n\treturn choice;\n}\n\nasync function pickTeam(teams: Team[]): Promise<Team> {\n\tif (teams.length === 1) return teams[0]!;\n\tconst choice = await p.select({\n\t\tmessage: 'Select a team',\n\t\toptions: teams.map((team) => ({\n\t\t\tvalue: team.id,\n\t\t\tlabel: team.is_personal ? `${team.name} (personal)` : team.name\n\t\t}))\n\t});\n\tif (p.isCancel(choice)) {\n\t\tp.cancel('Operation cancelled.');\n\t\tprocess.exit(0);\n\t}\n\treturn teams.find((team) => team.id === choice)!;\n}\n\nasync function promptProjectName(workspaceRootDir: string): Promise<string> {\n\tconst defaultValue = defaultProjectName(workspaceRootDir);\n\tconst value = await p.text({\n\t\tmessage: 'Project name',\n\t\tdefaultValue,\n\t\tinitialValue: defaultValue,\n\t\tplaceholder: defaultValue,\n\t\tvalidate: (v) => (!v?.trim() ? 'Required' : undefined)\n\t});\n\tif (p.isCancel(value)) {\n\t\tp.cancel('Operation cancelled.');\n\t\tprocess.exit(0);\n\t}\n\treturn value.trim();\n}\n\nfunction defaultProjectName(workspaceRootDir: string): string {\n\ttry {\n\t\tconst pkg = readPackageJson(path.join(workspaceRootDir, 'package.json'));\n\t\tconst name = pkg.name;\n\t\tif (typeof name === 'string' && name.trim()) return name.trim();\n\t} catch {\n\t\t// fall through\n\t}\n\treturn path.basename(workspaceRootDir);\n}\n", "import { API_URL } from './constants.ts';\n\nexport interface User {\n\tid: string;\n\temail: string;\n}\n\nexport interface Team {\n\tid: string;\n\tname: string;\n\tis_personal: boolean;\n\towner: string;\n}\n\nexport interface ProjectRecord {\n\tid: string;\n\tname: string;\n\tteam: string;\n\tuser?: string;\n\texpand?: { team?: Team };\n}\n\ninterface PaginatedResponse<T> {\n\titems: T[];\n\tpage: number;\n\tperPage: number;\n\ttotalItems: number;\n\ttotalPages: number;\n}\n\nasync function apiFetch<T>(apiKey: string, pathAndQuery: string, init?: RequestInit): Promise<T> {\n\tconst headers = new Headers(init?.headers);\n\theaders.set('Authorization', `Bearer ${apiKey}`);\n\tif (init?.body && !headers.has('Content-Type')) {\n\t\theaders.set('Content-Type', 'application/json');\n\t}\n\n\tconst res = await fetch(`${API_URL}${pathAndQuery}`, { ...init, headers });\n\tif (res.status === 401 || res.status === 403) {\n\t\tthrow new Error('API key invalid \u2014 run `vela login`');\n\t}\n\tif (!res.ok) {\n\t\tconst body = await res.text().catch(() => '');\n\t\tthrow new Error(`Velastack API error (${res.status}): ${body || res.statusText}`);\n\t}\n\treturn (await res.json()) as T;\n}\n\nexport async function getCurrentUser(apiKey: string): Promise<User> {\n\tconst data = await apiFetch<PaginatedResponse<User>>(\n\t\tapiKey,\n\t\t'/api/collections/users/records?perPage=1'\n\t);\n\tconst user = data.items[0];\n\tif (!user) throw new Error('No user found. Run `vela login` to login.');\n\treturn user;\n}\n\nexport async function listTeams(apiKey: string): Promise<Team[]> {\n\tconst data = await apiFetch<PaginatedResponse<Team>>(\n\t\tapiKey,\n\t\t'/api/collections/teams/records?perPage=200'\n\t);\n\treturn data.items;\n}\n\nexport async function listProjects(apiKey: string): Promise<ProjectRecord[]> {\n\tconst data = await apiFetch<PaginatedResponse<ProjectRecord>>(\n\t\tapiKey,\n\t\t'/api/collections/projects/records?perPage=200&expand=team'\n\t);\n\treturn data.items;\n}\n\nexport async function createProject(\n\tapiKey: string,\n\targs: { name: string; teamId: string; userId: string }\n): Promise<ProjectRecord> {\n\treturn apiFetch<ProjectRecord>(apiKey, '/api/collections/projects/records', {\n\t\tmethod: 'POST',\n\t\tbody: JSON.stringify({ name: args.name, team: args.teamId, user: args.userId })\n\t});\n}\n", "import { Command } from 'commander';\nimport { helpConfig } from '../lib/help.ts';\nimport { envList } from './env/list.ts';\nimport { envSet } from './env/set.ts';\nimport { envUnset } from './env/unset.ts';\nimport { envImport } from './env/import.ts';\n\nexport const env = new Command('env')\n\t.description('manage environment variables, locally or on a target')\n\t.configureHelp(helpConfig)\n\t.addCommand(envList)\n\t.addCommand(envSet)\n\t.addCommand(envUnset)\n\t.addCommand(envImport);\n", "import { Command } from 'commander';\nimport * as p from '@clack/prompts';\nimport pc from 'picocolors';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand } from '../../lib/run.ts';\nimport { addTargetOptions, withTarget } from '../../lib/server-command.ts';\nimport { readRemoteEnv } from '../../lib/remote-env.ts';\nimport { readLocalEnv } from '../../lib/local-env.ts';\n\nexport const envList = addTargetOptions(\n\tnew Command('list').description('list environment variable names').configureHelp(helpConfig),\n\t'local'\n).action((raw: unknown) =>\n\trunCommand(\n\t\t() =>\n\t\t\twithTarget(\n\t\t\t\traw,\n\t\t\t\t{\n\t\t\t\t\tlocal: async (ctx) => {\n\t\t\t\t\t\treport(Object.keys(readLocalEnv(ctx.envFile)), `${ctx.appName}, local (.env)`);\n\t\t\t\t\t},\n\t\t\t\t\tremote: async (ctx) => {\n\t\t\t\t\t\tconst env = await readRemoteEnv(ctx.session, ctx.instance);\n\t\t\t\t\t\treport(Object.keys(env), `${ctx.appName}, ${ctx.targetName}`);\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t{ label: 'env list' }\n\t\t\t),\n\t\t'Failed to read the environment.'\n\t)\n);\n\n// Names only, never values \u2014 the same rule on both sides, so that piping the\n// output of one into a screenshot or an issue is safe wherever it came from.\nfunction report(keys: string[], where: string): void {\n\tif (keys.length === 0) {\n\t\tp.log.info(`No environment variables configured ${pc.dim(`(${where})`)}.`);\n\t\treturn;\n\t}\n\tp.log.info(\n\t\t`Environment ${pc.dim(`(${where})`)}\\n\\n` +\n\t\t\tkeys\n\t\t\t\t.sort()\n\t\t\t\t.map((key) => ` ${key}`)\n\t\t\t\t.join('\\n')\n\t);\n}\n", "import process from 'node:process';\nimport { Command } from 'commander';\nimport * as p from '@clack/prompts';\nimport pc from 'picocolors';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand } from '../../lib/run.ts';\nimport { addTargetOptions, applyEnvRestart, withTarget } from '../../lib/server-command.ts';\nimport { isValidKey, readRemoteEnv, writeRemoteEnv } from '../../lib/remote-env.ts';\nimport { applyLocalEnvChange, setLocalEnv } from '../../lib/local-env.ts';\n\nexport const envSet = addTargetOptions(\n\tnew Command('set')\n\t\t.description('set an environment variable')\n\t\t.argument('<key>', 'variable name')\n\t\t.argument('[value]', 'value \u2014 prompted for, without echo, when omitted')\n\t\t.configureHelp(helpConfig),\n\t'local'\n).action((key: string, value: string | undefined, raw: unknown) =>\n\trunCommand(\n\t\t() =>\n\t\t\twithTarget(\n\t\t\t\traw,\n\t\t\t\t{\n\t\t\t\t\tlocal: async (ctx) => {\n\t\t\t\t\t\tconst resolved = await resolveValue(key, value);\n\t\t\t\t\t\tsetLocalEnv(ctx.envFile, key, resolved);\n\t\t\t\t\t\tp.log.success(`${key} updated ${pc.dim('(local)')}`);\n\t\t\t\t\t\tawait applyLocalEnvChange(ctx, [key]);\n\t\t\t\t\t},\n\t\t\t\t\tremote: async (ctx) => {\n\t\t\t\t\t\tconst resolved = await resolveValue(key, value);\n\t\t\t\t\t\tconst env = await readRemoteEnv(ctx.session, ctx.instance);\n\t\t\t\t\t\tawait writeRemoteEnv(ctx.session, ctx.instance, { ...env, [key]: resolved });\n\t\t\t\t\t\tp.log.success(`${key} updated ${pc.dim(`(${ctx.targetName})`)}`);\n\t\t\t\t\t\tawait applyEnvRestart(ctx, [key]);\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t{ label: 'env set' }\n\t\t\t),\n\t\t'Failed to set the variable.'\n\t)\n);\n\nasync function resolveValue(key: string, value: string | undefined): Promise<string> {\n\tif (!isValidKey(key)) throw new Error(`${key} is not a valid environment variable name.`);\n\treturn value ?? (await promptValue(key));\n}\n\nasync function promptValue(key: string): Promise<string> {\n\tconst value = await p.password({\n\t\tmessage: `Value for ${pc.cyan(key)}`,\n\t\tvalidate: (input) => (!input?.length ? 'Required' : undefined)\n\t});\n\tif (p.isCancel(value)) {\n\t\tp.cancel('Operation cancelled.');\n\t\tprocess.exit(0);\n\t}\n\treturn value;\n}\n", "import { Command } from 'commander';\nimport * as p from '@clack/prompts';\nimport pc from 'picocolors';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand } from '../../lib/run.ts';\nimport { addTargetOptions, applyEnvRestart, withTarget } from '../../lib/server-command.ts';\nimport { readRemoteEnv, writeRemoteEnv } from '../../lib/remote-env.ts';\nimport { applyLocalEnvChange, readLocalEnv, unsetLocalEnv } from '../../lib/local-env.ts';\n\nexport const envUnset = addTargetOptions(\n\tnew Command('unset')\n\t\t.description('remove an environment variable')\n\t\t.argument('<key>', 'variable name')\n\t\t.configureHelp(helpConfig),\n\t'local'\n).action((key: string, raw: unknown) =>\n\trunCommand(\n\t\t() =>\n\t\t\twithTarget(\n\t\t\t\traw,\n\t\t\t\t{\n\t\t\t\t\tlocal: async (ctx) => {\n\t\t\t\t\t\tif (!(key in readLocalEnv(ctx.envFile))) {\n\t\t\t\t\t\t\tp.log.info(`${key} is not set \u2014 nothing to remove.`);\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tunsetLocalEnv(ctx.envFile, key);\n\t\t\t\t\t\tp.log.success(`${key} removed ${pc.dim('(local)')}`);\n\t\t\t\t\t\tawait applyLocalEnvChange(ctx, [key]);\n\t\t\t\t\t},\n\t\t\t\t\tremote: async (ctx) => {\n\t\t\t\t\t\tconst env = await readRemoteEnv(ctx.session, ctx.instance);\n\t\t\t\t\t\tif (!(key in env)) {\n\t\t\t\t\t\t\tp.log.info(`${key} is not set \u2014 nothing to remove.`);\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tdelete env[key];\n\t\t\t\t\t\tawait writeRemoteEnv(ctx.session, ctx.instance, env);\n\t\t\t\t\t\tp.log.success(`${key} removed ${pc.dim(`(${ctx.targetName})`)}`);\n\t\t\t\t\t\tawait applyEnvRestart(ctx, [key]);\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t{ label: 'env unset' }\n\t\t\t),\n\t\t'Failed to remove the variable.'\n\t)\n);\n", "import fs from 'node:fs';\nimport path from 'node:path';\nimport process from 'node:process';\nimport { Command } from 'commander';\nimport * as p from '@clack/prompts';\nimport pc from 'picocolors';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand } from '../../lib/run.ts';\nimport { addTargetOptions, applyEnvRestart, withTarget } from '../../lib/server-command.ts';\nimport { readLocalEnvFile, readRemoteEnv, writeRemoteEnv } from '../../lib/remote-env.ts';\nimport { applyLocalEnvChange, editLocalEnv } from '../../lib/local-env.ts';\nimport { upsertEnvVar } from '../../lib/env.ts';\n\nexport const envImport = addTargetOptions(\n\tnew Command('import')\n\t\t.description('merge a dotenv file into the environment')\n\t\t.argument('<file>', 'dotenv file to read')\n\t\t.configureHelp(helpConfig),\n\t'local'\n).action((file: string, raw: unknown) =>\n\trunCommand(\n\t\t() =>\n\t\t\twithTarget(\n\t\t\t\traw,\n\t\t\t\t{\n\t\t\t\t\tlocal: async (ctx) => {\n\t\t\t\t\t\tconst source = resolve(file);\n\t\t\t\t\t\tif (source === ctx.envFile) {\n\t\t\t\t\t\t\tthrow new Error(`${file} is the file you would be importing into.`);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst incoming = read(source, file);\n\t\t\t\t\t\tconst keys = Object.keys(incoming);\n\t\t\t\t\t\tif (keys.length === 0) return;\n\n\t\t\t\t\t\tp.log.step(`Importing ${keys.length} variable(s) from ${pc.cyan(file)}`);\n\t\t\t\t\t\teditLocalEnv(ctx.envFile, (content) =>\n\t\t\t\t\t\t\tkeys.reduce((acc, key) => upsertEnvVar(acc, key, incoming[key]!), content)\n\t\t\t\t\t\t);\n\t\t\t\t\t\tp.log.success(`${keys.length} variable(s) updated ${pc.dim('(local)')}`);\n\t\t\t\t\t\tawait applyLocalEnvChange(ctx, keys);\n\t\t\t\t\t},\n\t\t\t\t\tremote: async (ctx) => {\n\t\t\t\t\t\tconst incoming = read(resolve(file), file);\n\t\t\t\t\t\tconst keys = Object.keys(incoming);\n\t\t\t\t\t\tif (keys.length === 0) return;\n\n\t\t\t\t\t\tp.log.step(`Importing ${keys.length} variable(s) from ${pc.cyan(file)}`);\n\t\t\t\t\t\t// Merge: values on the server that the file does not mention stay put.\n\t\t\t\t\t\tconst existing = await readRemoteEnv(ctx.session, ctx.instance);\n\t\t\t\t\t\tawait writeRemoteEnv(ctx.session, ctx.instance, { ...existing, ...incoming });\n\n\t\t\t\t\t\tp.log.success(`${keys.length} variable(s) updated ${pc.dim(`(${ctx.targetName})`)}`);\n\t\t\t\t\t\tawait applyEnvRestart(ctx, keys);\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t{ label: 'env import' }\n\t\t\t),\n\t\t'Failed to import the environment.'\n\t)\n);\n\nfunction resolve(file: string): string {\n\treturn path.resolve(process.cwd(), file);\n}\n\nfunction read(resolved: string, shown: string): Record<string, string> {\n\tif (!fs.existsSync(resolved)) throw new Error(`${shown} does not exist.`);\n\tconst incoming = readLocalEnvFile(resolved);\n\tif (Object.keys(incoming).length === 0) p.log.info(`${shown} has no variables to import.`);\n\treturn incoming;\n}\n", "import { Command } from 'commander';\nimport * as p from '@clack/prompts';\nimport pc from 'picocolors';\nimport { helpConfig } from '../lib/help.ts';\nimport { runCommand } from '../lib/run.ts';\nimport { addTargetOptions, withServerSession, withTarget } from '../lib/server-command.ts';\nimport { readInstanceStates, type InstanceState } from '../lib/remote.ts';\n\nexport const status = addTargetOptions(\n\tnew Command('status').description('show what is deployed').configureHelp(helpConfig),\n\t'production'\n)\n\t.option('--all', 'show every app on the server, not just this project')\n\t.option('--json', 'print raw JSON')\n\t.action((raw: unknown) =>\n\t\trunCommand(async () => {\n\t\t\tconst options = raw as { all?: boolean; json?: boolean };\n\n\t\t\t// `--all` is a question about the machine, so it needs a server but not\n\t\t\t// an instance \u2014 and `--server` alone answers it outside a project.\n\t\t\tif (options.all) {\n\t\t\t\tawait withServerSession(raw, async (session) => {\n\t\t\t\t\treport(await readInstanceStates(session), options.json);\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tawait withTarget(\n\t\t\t\traw,\n\t\t\t\t{\n\t\t\t\t\tremote: async (ctx) => {\n\t\t\t\t\t\treport(await readInstanceStates(ctx.session, ctx.instance), options.json);\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tlabel: 'status',\n\t\t\t\t\tlocalHint: 'Nothing is deployed locally \u2014 `vela dev` reports what it is running.'\n\t\t\t\t}\n\t\t\t);\n\t\t}, 'Failed to read status.')\n\t);\n\nfunction report(states: InstanceState[], json?: boolean): void {\n\tif (json) {\n\t\tconsole.log(JSON.stringify(states, null, 2));\n\t\treturn;\n\t}\n\tif (states.length === 0) {\n\t\tp.log.info('Nothing is deployed here yet.');\n\t\treturn;\n\t}\n\tfor (const state of states) {\n\t\tp.log.info(describe(state));\n\t}\n}\n\nfunction describe(state: InstanceState): string {\n\tconst health = (value?: string) =>\n\t\tvalue === 'active' ? pc.green(value) : pc.red(value || 'inactive');\n\tconst rows: [string, string][] = [\n\t\t['Instance', state.instance],\n\t\t['Environment', state.env],\n\t\t['Release', state.activeRelease ?? '\u2014'],\n\t\t['Previous', state.previousRelease || '\u2014'],\n\t\t['Domain', state.domain || '\u2014'],\n\t\t['Ports', `web ${state.webPort ?? '?'}${state.backend ? `, pb ${state.pbPort ?? '?'}` : ''}`],\n\t\t['App', health(state.services?.web)],\n\t\t...(state.backend\n\t\t\t? ([['PocketBase', health(state.services?.pocketbase)]] as [string, string][])\n\t\t\t: []),\n\t\t['Deployed', state.deployedAt ?? '\u2014'],\n\t\t...(state.rolledBackAt ? ([['Rolled back', state.rolledBackAt]] as [string, string][]) : []),\n\t\t...(state.gitSha ? ([['Commit', state.gitSha.slice(0, 12)]] as [string, string][]) : [])\n\t];\n\tconst width = Math.max(...rows.map(([label]) => label.length));\n\treturn (\n\t\tpc.cyan(state.name) +\n\t\t'\\n\\n' +\n\t\trows.map(([label, value]) => ` ${label.padEnd(width)} ${value}`).join('\\n')\n\t);\n}\n", "import { Command } from 'commander';\nimport * as p from '@clack/prompts';\nimport pc from 'picocolors';\nimport { helpConfig } from '../lib/help.ts';\nimport { runCommand } from '../lib/run.ts';\nimport { addTargetOptions, withTarget } from '../lib/server-command.ts';\nimport { runServerScript } from '../lib/remote.ts';\n\nexport const rollback = addTargetOptions(\n\tnew Command('rollback').description('put the previous release back').configureHelp(helpConfig),\n\t'production'\n)\n\t.option('--to <release>', 'roll back to a specific release instead of the previous one')\n\t.action((raw: unknown) =>\n\t\trunCommand(async () => {\n\t\t\tconst options = raw as { to?: string };\n\t\t\tawait withTarget(\n\t\t\t\traw,\n\t\t\t\t{\n\t\t\t\t\tremote: async (ctx) => {\n\t\t\t\t\t\tp.log.step(\n\t\t\t\t\t\t\t`Rolling back ${pc.cyan(ctx.appName)} ${pc.dim(`(${ctx.targetName})`)} on ${ctx.server}`\n\t\t\t\t\t\t);\n\n\t\t\t\t\t\tconst result = await runServerScript<{ release: string; from: string }>(\n\t\t\t\t\t\t\tctx.session,\n\t\t\t\t\t\t\t'rollback.sh',\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\targs: [ctx.instance, ...(options.to ? ['--to', options.to] : [])],\n\t\t\t\t\t\t\t\tstream: true\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t);\n\n\t\t\t\t\t\tp.log.success(\n\t\t\t\t\t\t\t`Rolled back to ${pc.cyan(result?.release ?? 'the previous release')}` +\n\t\t\t\t\t\t\t\t(result?.from ? ` ${pc.dim(`(was ${result.from})`)}` : '')\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tlabel: 'rollback',\n\t\t\t\t\tlocalHint: 'Nothing is released locally \u2014 `vela dev` always runs the working tree.'\n\t\t\t\t}\n\t\t\t);\n\t\t}, 'Failed to roll back.')\n\t);\n", "import { Command } from 'commander';\nimport { helpConfig } from '../lib/help.ts';\nimport { runCommand } from '../lib/run.ts';\nimport { addTargetOptions, withTarget } from '../lib/server-command.ts';\nimport { remotePaths } from '../lib/remote.ts';\n\nexport const logs = addTargetOptions(\n\tnew Command('logs').description('tail the logs of a deployed app').configureHelp(helpConfig),\n\t'production'\n)\n\t.option('-f, --follow', 'keep streaming new output')\n\t.option('-n, --lines <count>', 'how many lines of history to show', '100')\n\t.option('--pocketbase', 'show the PocketBase service instead of the app')\n\t.action((raw: unknown) =>\n\t\trunCommand(async () => {\n\t\t\tconst options = raw as { follow?: boolean; lines?: string; pocketbase?: boolean };\n\t\t\tawait withTarget(\n\t\t\t\traw,\n\t\t\t\t{\n\t\t\t\t\tremote: async (ctx) => {\n\t\t\t\t\t\tconst unit = options.pocketbase\n\t\t\t\t\t\t\t? remotePaths.pbUnit(ctx.instance)\n\t\t\t\t\t\t\t: remotePaths.webUnit(ctx.instance);\n\t\t\t\t\t\tconst command = [\n\t\t\t\t\t\t\t'journalctl',\n\t\t\t\t\t\t\t'-u',\n\t\t\t\t\t\t\tunit,\n\t\t\t\t\t\t\t'-n',\n\t\t\t\t\t\t\toptions.lines ?? '100',\n\t\t\t\t\t\t\t'--no-pager',\n\t\t\t\t\t\t\t...(options.follow ? ['-f'] : [])\n\t\t\t\t\t\t];\n\t\t\t\t\t\tconst code = await ctx.session.interactive(command);\n\t\t\t\t\t\tif (code !== 0 && !options.follow) {\n\t\t\t\t\t\t\tthrow new Error(`journalctl exited ${code}.`);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tlabel: 'logs',\n\t\t\t\t\tlocalHint:\n\t\t\t\t\t\t'There are no logs for the copy on this machine \u2014 `vela dev` prints them as it runs.'\n\t\t\t\t}\n\t\t\t);\n\t\t}, 'Failed to read logs.')\n\t);\n", "import { Command } from 'commander';\nimport { helpConfig } from '../lib/help.ts';\nimport { adminCreate } from './admin/create.ts';\n\nexport const admin = new Command('admin')\n\t.description('manage admin panel logins')\n\t.configureHelp(helpConfig)\n\t.addCommand(adminCreate);\n", "import process from 'node:process';\nimport type PocketBase from 'pocketbase';\nimport { Command } from 'commander';\nimport * as p from '@clack/prompts';\nimport pc from 'picocolors';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand } from '../../lib/run.ts';\nimport { addTargetOptions, withTarget } from '../../lib/server-command.ts';\nimport { withRemotePocketbase } from '../../lib/remote-pocketbase.ts';\nimport { readInstanceStates } from '../../lib/remote.ts';\nimport { getPocketbaseMetadata, withPocketbase } from '../../lib/pocketbase.ts';\nimport { readLocalEnv } from '../../lib/local-env.ts';\n\n/** PocketBase's own minimum for a superuser password. */\nconst MIN_PASSWORD = 10;\n\nexport const adminCreate = addTargetOptions(\n\tnew Command('create')\n\t\t.description('create a login for the admin panel')\n\t\t.argument('[email]', 'email to sign in with \u2014 prompted for when omitted')\n\t\t.configureHelp(helpConfig),\n\t'local'\n).action((email: string | undefined, raw: unknown) =>\n\trunCommand(\n\t\t() =>\n\t\t\twithTarget(\n\t\t\t\traw,\n\t\t\t\t{\n\t\t\t\t\tlocal: async (ctx) => {\n\t\t\t\t\t\tconst creds = readLocalEnv(ctx.envFile);\n\t\t\t\t\t\tconst address = email ?? (await promptEmail());\n\t\t\t\t\t\tconst password = await promptPassword();\n\n\t\t\t\t\t\tlet signIn = '';\n\t\t\t\t\t\tawait withPocketbase(\n\t\t\t\t\t\t\tctx.workspaceRootDir,\n\t\t\t\t\t\t\tasync (pb) => {\n\t\t\t\t\t\t\t\tawait upsertSuperuser(pb, address, password);\n\t\t\t\t\t\t\t\t// `vela dev` writes the real URL into PocketBase settings on every\n\t\t\t\t\t\t\t\t// boot, and it survives dev exiting \u2014 a better source than the\n\t\t\t\t\t\t\t\t// metadata file, which is deleted when dev stops.\n\t\t\t\t\t\t\t\tconst settings = (await pb.settings.getAll()) as {\n\t\t\t\t\t\t\t\t\tmeta?: { appURL?: string };\n\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t\tsignIn = settings.meta?.appURL ?? '';\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\temail: creds.POCKETBASE_SUPERUSER_EMAIL,\n\t\t\t\t\t\t\t\tpassword: creds.POCKETBASE_SUPERUSER_PASSWORD\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t);\n\n\t\t\t\t\t\tif (!signIn) {\n\t\t\t\t\t\t\tconst metadata = getPocketbaseMetadata(ctx.workspaceRootDir);\n\t\t\t\t\t\t\tif (metadata) signIn = `http://${metadata.viteHost}:${metadata.vitePort}`;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tp.log.info(\n\t\t\t\t\t\t\tsignIn\n\t\t\t\t\t\t\t\t? `Sign in at ${pc.cyan(`${signIn}/admin`)}`\n\t\t\t\t\t\t\t\t: `Sign in at ${pc.cyan('/admin')} once ${pc.cyan('vela dev')} is running.`\n\t\t\t\t\t\t);\n\t\t\t\t\t},\n\t\t\t\t\tremote: async (ctx) => {\n\t\t\t\t\t\tconst address = email ?? (await promptEmail());\n\t\t\t\t\t\tconst password = await promptPassword();\n\t\t\t\t\t\tconst [state] = await readInstanceStates(ctx.session, ctx.instance);\n\n\t\t\t\t\t\tawait withRemotePocketbase(ctx.session, ctx.instance, (pb) =>\n\t\t\t\t\t\t\tupsertSuperuser(pb, address, password)\n\t\t\t\t\t\t);\n\n\t\t\t\t\t\t// The panel is served by the app itself, at the adapter's `/admin`,\n\t\t\t\t\t\t// so it is reachable wherever the app is \u2014 PocketBase itself never\n\t\t\t\t\t\t// leaves the server's loopback.\n\t\t\t\t\t\tconst base = state?.domain ? `https://${state.domain.split(',')[0]!.trim()}` : '';\n\t\t\t\t\t\tp.log.info(\n\t\t\t\t\t\t\tbase\n\t\t\t\t\t\t\t\t? `Sign in at ${pc.cyan(`${base}/admin`)}`\n\t\t\t\t\t\t\t\t: `Sign in at ${pc.cyan('/admin')} once a domain is configured for this target.`\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t{ label: 'admin create' }\n\t\t\t),\n\t\t'Failed to create the admin login.'\n\t)\n);\n\n/**\n * Create the login, or reset its password when the email already signs in.\n *\n * Shared by both targets so a local account and a deployed one are made the same\n * way, against whichever PocketBase the caller opened.\n */\nasync function upsertSuperuser(pb: PocketBase, email: string, password: string): Promise<void> {\n\tconst existing = await findSuperuser(pb, email);\n\tif (existing) {\n\t\tconst confirmed = await p.confirm({\n\t\t\tmessage: `${email} already has an account, update its password?`,\n\t\t\tinitialValue: false\n\t\t});\n\t\tif (p.isCancel(confirmed) || !confirmed) {\n\t\t\tp.cancel('Operation cancelled.');\n\t\t\tprocess.exit(0);\n\t\t}\n\t\tawait pb.collection('_superusers').update(existing, { password, passwordConfirm: password });\n\t\tp.log.success(`Password updated for ${pc.cyan(email)}, you can sign in now`);\n\t\treturn;\n\t}\n\n\tawait pb.collection('_superusers').create({ email, password, passwordConfirm: password });\n\tp.log.success(`${pc.cyan(email)} can now sign in`);\n}\n\n/**\n * The account this creates is the human's, and deliberately separate from the\n * superuser the app authenticates as: that one is generated on the server, kept\n * in the instance environment and never printed. Two accounts, so a person can\n * be given or denied access without touching what the app runs on.\n */\nasync function findSuperuser(pb: PocketBase, email: string): Promise<string | null> {\n\ttry {\n\t\tconst record = await pb\n\t\t\t.collection('_superusers')\n\t\t\t.getFirstListItem(pb.filter('email = {:email}', { email }));\n\t\treturn record.id;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nasync function promptEmail(): Promise<string> {\n\tconst value = await p.text({\n\t\tmessage: 'Email to sign in with',\n\t\tvalidate: (input) => (input?.includes('@') ? undefined : 'An email address is required')\n\t});\n\tif (p.isCancel(value)) {\n\t\tp.cancel('Operation cancelled.');\n\t\tprocess.exit(0);\n\t}\n\treturn value.trim();\n}\n\nasync function promptPassword(): Promise<string> {\n\tconst value = await p.password({\n\t\tmessage: 'Password',\n\t\tvalidate: (input) =>\n\t\t\t(input?.length ?? 0) >= MIN_PASSWORD\n\t\t\t\t? undefined\n\t\t\t\t: `At least ${MIN_PASSWORD} characters is required`\n\t});\n\tif (p.isCancel(value)) {\n\t\tp.cancel('Operation cancelled.');\n\t\tprocess.exit(0);\n\t}\n\n\tconst again = await p.password({\n\t\tmessage: 'Password again',\n\t\tvalidate: (input) => (input === value ? undefined : 'The two do not match')\n\t});\n\tif (p.isCancel(again)) {\n\t\tp.cancel('Operation cancelled.');\n\t\tprocess.exit(0);\n\t}\n\treturn value;\n}\n", "import { Command } from 'commander';\nimport { helpConfig } from '../lib/help.ts';\nimport { backupCreate } from './backup/create.ts';\nimport { backupList } from './backup/list.ts';\nimport { backupDownload } from './backup/download.ts';\nimport { backupDelete } from './backup/delete.ts';\nimport { backupSchedule } from './backup/schedule.ts';\n\nexport const backup = new Command('backup')\n\t.description('back up the database and uploads, locally or on a target')\n\t.configureHelp(helpConfig)\n\t.addCommand(backupCreate)\n\t.addCommand(backupList)\n\t.addCommand(backupDownload)\n\t.addCommand(backupDelete)\n\t.addCommand(backupSchedule);\n", "import fs from 'node:fs';\nimport path from 'node:path';\nimport { Command } from 'commander';\nimport * as p from '@clack/prompts';\nimport pc from 'picocolors';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand } from '../../lib/run.ts';\nimport { reportResult } from '../../lib/result-report.ts';\nimport { addTargetOptions } from '../../lib/server-command.ts';\nimport { withBackupTarget, type BackupContext } from '../../lib/backup-target.ts';\nimport {\n\tbackupName,\n\tcheckpointAppDatabases,\n\tcreateBackup,\n\tformatBytes,\n\tisBackupKey,\n\tlistBackups,\n\treadStorageSettings\n} from '../../lib/backups.ts';\nimport { remotePaths } from '../../lib/remote.ts';\n\nexport const DEFAULT_BACKUP_DIR = 'backups';\n\nexport const backupCreate = addTargetOptions(\n\tnew Command('create')\n\t\t.description('take a backup of the database and uploads')\n\t\t.argument('[name]', 'name for the archive \u2014 generated when omitted')\n\t\t.option('-o, --output <dir>', 'where to save the archive', DEFAULT_BACKUP_DIR)\n\t\t.option('--no-download', 'leave the archive on the server')\n\t\t.configureHelp(helpConfig),\n\t'production'\n).action((name: string | undefined, raw: unknown) =>\n\trunCommand(() => {\n\t\tconst options = raw as { output: string; download: boolean };\n\t\treturn withBackupTarget(raw, 'backup create', async (ctx) => {\n\t\t\tconst key = name ?? backupName(ctx.instance);\n\t\t\tif (!isBackupKey(key)) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`${pc.cyan(key)} is not a name PocketBase will accept.\\n\\n` +\n\t\t\t\t\t\t`Backup names are lowercase letters, digits, ${pc.cyan('-')} and ${pc.cyan('_')}, ` +\n\t\t\t\t\t\t`ending in ${pc.cyan('.zip')}.`\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconst storage = await readStorageSettings(ctx.pb);\n\t\t\tif (storage.s3Enabled) {\n\t\t\t\tp.log.warn(\n\t\t\t\t\t`Uploads are stored in S3, so this archive holds the database only.\\n\\n` +\n\t\t\t\t\t\t`PocketBase leaves ${pc.cyan('storage/')} out of a backup whenever S3 is on.\\n` +\n\t\t\t\t\t\t`Your bucket's own versioning is what protects the uploaded files.`\n\t\t\t\t);\n\t\t\t}\n\n\t\t\t// PocketBase flushes the write-ahead logs of its own databases before it\n\t\t\t// archives the directory. Anything the app keeps alongside them has to be\n\t\t\t// asked separately, or the archive holds a database and a log that\n\t\t\t// describe different moments.\n\t\t\tif (ctx.session) await checkpointAppDatabases(ctx.session, ctx.instance);\n\n\t\t\tconst spinner = p.spinner();\n\t\t\tspinner.start(`Backing up ${ctx.targetName}`);\n\t\t\ttry {\n\t\t\t\tawait createBackup(ctx.pb, key);\n\t\t\t} catch (error) {\n\t\t\t\tspinner.stop(`Backup of ${ctx.targetName} failed.`);\n\t\t\t\tthrow error;\n\t\t\t}\n\n\t\t\tconst size = (await listBackups(ctx.pb)).find((b) => b.key === key)?.size ?? 0;\n\t\t\tspinner.stop(`Backed up ${ctx.targetName} \u2014 ${key} (${formatBytes(size)})`);\n\n\t\t\tif (storage.backupsS3Enabled) {\n\t\t\t\treportResult({\n\t\t\t\t\tsummary: `Backed up ${ctx.targetName} to your backups bucket.`,\n\t\t\t\t\tnextSteps: [\n\t\t\t\t\t\t`The archive is ${key} in the bucket configured for backups, not on the server.`,\n\t\t\t\t\t\t'Run `vela backup list` to see what is stored there.'\n\t\t\t\t\t]\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (!options.download) {\n\t\t\t\treportResult({\n\t\t\t\t\tsummary: `Backed up ${ctx.targetName}.`,\n\t\t\t\t\tnextSteps: [\n\t\t\t\t\t\t`${key} is on the server, in the directory it is a backup of.`,\n\t\t\t\t\t\t'Run `vela backup download ' + key + '` to keep a copy off the box.'\n\t\t\t\t\t]\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst saved = await download(ctx, key, options.output);\n\t\t\treportResult({\n\t\t\t\tsummary: `Backed up ${ctx.targetName} \u2014 ${formatBytes(size)}.`,\n\t\t\t\tfilesCreated: [saved],\n\t\t\t\tnextSteps: [`Restore it with \\`vela restore ${key}\\`.`]\n\t\t\t});\n\t\t});\n\t}, 'Failed to create the backup.')\n);\n\n/**\n * Bring the archive off the machine it protects.\n *\n * PocketBase writes it into `pb_data/backups`, inside the very directory being\n * backed up, so a backup that is never downloaded survives exactly the failures\n * that do not matter.\n */\nasync function download(ctx: BackupContext, key: string, outputDir: string): Promise<string> {\n\tconst dir = path.resolve(ctx.workspaceRootDir, outputDir);\n\tfs.mkdirSync(dir, { recursive: true });\n\tconst destination = path.join(dir, key);\n\n\tif (!ctx.session) {\n\t\tfs.copyFileSync(path.join(ctx.workspaceRootDir, 'data', 'backups', key), destination);\n\t\treturn path.relative(ctx.workspaceRootDir, destination);\n\t}\n\n\tconst spinner = p.spinner();\n\tspinner.start(`Downloading ${key}`);\n\ttry {\n\t\tawait ctx.session.download(remotePaths.backup(ctx.instance, key), destination);\n\t} catch (error) {\n\t\tspinner.stop(`Could not download ${key}.`);\n\t\tthrow error;\n\t}\n\tspinner.stop(`Downloaded ${key}`);\n\treturn path.relative(ctx.workspaceRootDir, destination);\n}\n", "import type PocketBase from 'pocketbase';\nimport { remotePaths, VELA_USER } from './remote.ts';\nimport type { SshSession } from './ssh.ts';\n\n/**\n * What PocketBase will accept as a backup name.\n *\n * `apis/backup_create.go` matches this exactly and rejects anything else, which\n * rules out the `20260901T134501Z` stamp releases use \u2014 no uppercase.\n */\nconst BACKUP_KEY = /^[a-z0-9_-]+\\.zip$/;\n\n/** PocketBase caps the name at 150; the stamp and affixes take 24 of them. */\nconst MAX_SLUG = 100;\n\nexport interface BackupFile {\n\tkey: string;\n\tsize: number;\n\tmodified: string;\n}\n\nexport interface StorageSettings {\n\t/** Uploads are in a bucket, so a backup archive will not contain them. */\n\ts3Enabled: boolean;\n\t/** Backup archives go to a bucket rather than to `pb_data/backups`. */\n\tbackupsS3Enabled: boolean;\n}\n\nexport function isBackupKey(value: string): boolean {\n\treturn BACKUP_KEY.test(value);\n}\n\n/**\n * Name a backup after the instance it came from.\n *\n * Deterministic on purpose: `createBackup` needs to be able to look the archive\n * up again after a request times out, and it has nothing else to look it up by.\n */\nexport function backupName(instance: string, now: Date = new Date()): string {\n\tconst slug = instance\n\t\t.toLowerCase()\n\t\t.replace(/[^a-z0-9_-]+/g, '-')\n\t\t.replace(/^-+|-+$/g, '')\n\t\t.slice(0, MAX_SLUG);\n\tconst stamp = now.toISOString().replace(/[-:T]/g, '').slice(0, 14);\n\treturn `vela_${slug || 'app'}_${stamp}.zip`;\n}\n\nexport async function readStorageSettings(pb: PocketBase): Promise<StorageSettings> {\n\tconst settings = (await pb.settings.getAll()) as {\n\t\ts3?: { enabled?: boolean };\n\t\tbackups?: { s3?: { enabled?: boolean } };\n\t};\n\treturn {\n\t\ts3Enabled: settings.s3?.enabled === true,\n\t\tbackupsS3Enabled: settings.backups?.s3?.enabled === true\n\t};\n}\n\nexport async function listBackups(pb: PocketBase): Promise<BackupFile[]> {\n\tconst list = await pb.backups.getFullList();\n\treturn [...list].sort((a, b) => b.modified.localeCompare(a.modified));\n}\n\n/**\n * True when a request died because the client gave up waiting, not because the\n * server said no.\n *\n * `POST /api/backups` archives the whole data directory before it answers, and\n * Node's fetch stops waiting for headers after five minutes. On a large\n * instance that fires while PocketBase carries on and finishes successfully, so\n * it has to be told apart from a real failure.\n */\nfunction isClientTimeout(error: unknown): boolean {\n\tfor (let e: unknown = error, depth = 0; e && depth < 5; depth++) {\n\t\tconst cause = e as { code?: string; name?: string; originalError?: unknown; cause?: unknown };\n\t\tif (cause.code === 'UND_ERR_HEADERS_TIMEOUT' || cause.name === 'HeadersTimeoutError')\n\t\t\treturn true;\n\t\te = cause.originalError ?? cause.cause;\n\t}\n\treturn false;\n}\n\nconst POLL_INTERVAL = 5_000;\n\n/**\n * Take a backup, tolerating a request that outlives the client's patience.\n *\n * The name is chosen here rather than by PocketBase so that a timed-out request\n * can be resolved by asking whether the archive turned up \u2014 the alternative is\n * reporting a failure for a backup that actually exists.\n */\nexport async function createBackup(\n\tpb: PocketBase,\n\tkey: string,\n\t{ pollTimeout = 30 * 60_000 }: { pollTimeout?: number } = {}\n): Promise<void> {\n\ttry {\n\t\tawait pb.backups.create(key);\n\t\treturn;\n\t} catch (error) {\n\t\tif (!isClientTimeout(error)) throw error;\n\t}\n\n\tconst deadline = Date.now() + pollTimeout;\n\twhile (Date.now() < deadline) {\n\t\tawait new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL));\n\t\tconst found = await listBackups(pb).catch(() => [] as BackupFile[]);\n\t\tif (found.some((b) => b.key === key)) return;\n\t}\n\n\tthrow new Error(\n\t\t`The backup request timed out and ${key} has not appeared after ` +\n\t\t\t`${Math.round(pollTimeout / 60_000)} minutes.\\n\\n` +\n\t\t\t`PocketBase may still be working on it \u2014 check \\`vela logs\\` and ` +\n\t\t\t`\\`vela backup list\\` before trying again.`\n\t);\n}\n\n/**\n * Fold any app-owned write-ahead log back into the database file it belongs to.\n *\n * PocketBase checkpoints the databases it owns before archiving `pb_data` \u2014 in\n * an archive its `-wal` files are empty. A database the app opened for itself\n * gets no such treatment: its `-wal` is copied as it was found, and a checkpoint\n * landing between the moments the archiver reads the two files leaves the pair\n * describing different instants.\n *\n * Every SQLite file in the directory is offered a checkpoint rather than a list\n * of the ones known to be app-owned: PocketBase's own are already flushed, so\n * the redundant work is one no-op each, and a guessed list is a list that goes\n * stale the first time a build adds a database to `pb_data`.\n *\n * Two things are deliberate. It runs as the app user, because a checkpoint run\n * as root recreates `-wal` and `-shm` owned by root and the app can no longer\n * write to its own database afterwards. And every step is best-effort: a\n * database busy enough to refuse is a database whose backup is slightly less\n * consistent, which is not worth failing the backup over.\n *\n * Remote only. Locally PocketBase and the app share a directory that no deploy\n * moves, `sqlite3` is not guaranteed to be installed, and a backup of a\n * development database is a convenience rather than a promise.\n */\nexport async function checkpointAppDatabases(session: SshSession, instance: string): Promise<void> {\n\tawait session.script(\n\t\t`command -v sqlite3 >/dev/null 2>&1 || exit 0\n\t\tfor db in \"$1\"/*.db \"$1\"/*.sqlite; do\n\t\t\t[ -f \"$db-wal\" ] || continue\n\t\t\trunuser -u \"$2\" -- sqlite3 \"$db\" \\\n\t\t\t\t'PRAGMA busy_timeout=5000; PRAGMA wal_checkpoint(TRUNCATE);' >/dev/null 2>&1 || true\n\t\tdone`,\n\t\t{ args: [remotePaths.pbData(instance), VELA_USER], check: false }\n\t);\n}\n\nexport function formatBytes(bytes: number): string {\n\tconst units = ['B', 'KB', 'MB', 'GB', 'TB'];\n\tlet value = bytes;\n\tlet unit = 0;\n\twhile (value >= 1024 && unit < units.length - 1) {\n\t\tvalue /= 1024;\n\t\tunit += 1;\n\t}\n\treturn `${value < 10 && unit > 0 ? value.toFixed(1) : Math.round(value)} ${units[unit]}`;\n}\n\nexport interface BackupSchedule {\n\t/** Empty when no automatic backup is scheduled. */\n\tcron: string;\n\t/** How many cron-generated archives PocketBase keeps. */\n\tmaxKeep: number;\n}\n\nexport async function readSchedule(pb: PocketBase): Promise<BackupSchedule> {\n\tconst settings = (await pb.settings.getAll()) as {\n\t\tbackups?: { cron?: string; cronMaxKeep?: number };\n\t};\n\treturn {\n\t\tcron: settings.backups?.cron ?? '',\n\t\tmaxKeep: settings.backups?.cronMaxKeep ?? 0\n\t};\n}\n\n/**\n * Set or clear the automatic backup schedule.\n *\n * PocketBase runs the cron itself, in the same process that serves the app, so\n * there is nothing to install on the server. `cronMaxKeep` is required and must\n * be at least 1 whenever a schedule is set, and it prunes only the archives the\n * cron made \u2014 anything from `vela backup create` is left alone.\n *\n * Only these two keys are sent: settings are merged, so an S3 backups bucket\n * configured alongside them survives untouched.\n */\nexport async function writeSchedule(pb: PocketBase, cron: string, maxKeep: number): Promise<void> {\n\tawait pb.settings.update({ backups: { cron, cronMaxKeep: cron ? maxKeep : 0 } });\n}\n", "import { Command } from 'commander';\nimport * as p from '@clack/prompts';\nimport pc from 'picocolors';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand } from '../../lib/run.ts';\nimport { addTargetOptions } from '../../lib/server-command.ts';\nimport { withBackupTarget } from '../../lib/backup-target.ts';\nimport { formatBytes, listBackups } from '../../lib/backups.ts';\n\nexport const backupList = addTargetOptions(\n\tnew Command('list').description('list the backups on a target').configureHelp(helpConfig),\n\t'production'\n).action((raw: unknown) =>\n\trunCommand(\n\t\t() =>\n\t\t\twithBackupTarget(raw, 'backup list', async (ctx) => {\n\t\t\t\tconst backups = await listBackups(ctx.pb);\n\t\t\t\tif (backups.length === 0) {\n\t\t\t\t\tp.log.info(\n\t\t\t\t\t\t`${pc.cyan(ctx.targetName)} has no backups yet.\\n\\n` +\n\t\t\t\t\t\t\t`Take one with ${pc.cyan('vela backup create')}.`\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconst width = Math.max(...backups.map((b) => b.key.length));\n\t\t\t\tp.log.message(\n\t\t\t\t\tbackups\n\t\t\t\t\t\t.map(\n\t\t\t\t\t\t\t(b) =>\n\t\t\t\t\t\t\t\t`${b.key.padEnd(width)} ${pc.dim(formatBytes(b.size).padStart(8))} ${pc.dim(b.modified)}`\n\t\t\t\t\t\t)\n\t\t\t\t\t\t.join('\\n')\n\t\t\t\t);\n\t\t\t}),\n\t\t'Failed to list backups.'\n\t)\n);\n", "import fs from 'node:fs';\nimport path from 'node:path';\nimport { Command } from 'commander';\nimport * as p from '@clack/prompts';\nimport pc from 'picocolors';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand } from '../../lib/run.ts';\nimport { reportResult } from '../../lib/result-report.ts';\nimport { addTargetOptions } from '../../lib/server-command.ts';\nimport { withBackupTarget } from '../../lib/backup-target.ts';\nimport { formatBytes, listBackups, readStorageSettings } from '../../lib/backups.ts';\nimport { remotePaths } from '../../lib/remote.ts';\nimport { DEFAULT_BACKUP_DIR } from './create.ts';\n\nexport const backupDownload = addTargetOptions(\n\tnew Command('download')\n\t\t.description('save a backup off the server')\n\t\t.argument('<key>', 'archive to download, as shown by `vela backup list`')\n\t\t.option('-o, --output <dir>', 'where to save the archive', DEFAULT_BACKUP_DIR)\n\t\t.configureHelp(helpConfig),\n\t'production'\n).action((key: string, raw: unknown) =>\n\trunCommand(() => {\n\t\tconst options = raw as { output: string };\n\t\treturn withBackupTarget(raw, 'backup download', async (ctx) => {\n\t\t\tconst found = (await listBackups(ctx.pb)).find((b) => b.key === key);\n\t\t\tif (!found) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`${ctx.targetName} has no backup called ${pc.cyan(key)}.\\n\\n` +\n\t\t\t\t\t\t`Run ${pc.cyan('vela backup list')} to see what it does have.`\n\t\t\t\t);\n\t\t\t}\n\n\t\t\t// With a backups bucket configured the archive was never written to the\n\t\t\t// server's disk, so there is nothing here to rsync.\n\t\t\tconst storage = await readStorageSettings(ctx.pb);\n\t\t\tif (storage.backupsS3Enabled) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`${key} is in the bucket configured for backups, not on the server.\\n\\n` +\n\t\t\t\t\t\t`Fetch it from the bucket directly \u2014 vela does not hold its credentials.`\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconst dir = path.resolve(ctx.workspaceRootDir, options.output);\n\t\t\tfs.mkdirSync(dir, { recursive: true });\n\t\t\tconst destination = path.join(dir, key);\n\n\t\t\tif (!ctx.session) {\n\t\t\t\tfs.copyFileSync(path.join(ctx.workspaceRootDir, 'data', 'backups', key), destination);\n\t\t\t} else {\n\t\t\t\tconst spinner = p.spinner();\n\t\t\t\tspinner.start(`Downloading ${key} (${formatBytes(found.size)})`);\n\t\t\t\ttry {\n\t\t\t\t\tawait ctx.session.download(remotePaths.backup(ctx.instance, key), destination);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tspinner.stop(`Could not download ${key}.`);\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t\tspinner.stop(`Downloaded ${key}`);\n\t\t\t}\n\n\t\t\treportResult({\n\t\t\t\tsummary: `Saved ${key} from ${ctx.targetName}.`,\n\t\t\t\tfilesCreated: [path.relative(ctx.workspaceRootDir, destination)]\n\t\t\t});\n\t\t});\n\t}, 'Failed to download the backup.')\n);\n", "import process from 'node:process';\nimport { Command } from 'commander';\nimport * as p from '@clack/prompts';\nimport pc from 'picocolors';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand } from '../../lib/run.ts';\nimport { reportResult } from '../../lib/result-report.ts';\nimport { addTargetOptions } from '../../lib/server-command.ts';\nimport { withBackupTarget } from '../../lib/backup-target.ts';\nimport { formatBytes, listBackups } from '../../lib/backups.ts';\n\nexport const backupDelete = addTargetOptions(\n\tnew Command('delete')\n\t\t.description('remove a backup from a target')\n\t\t.argument('<key>', 'archive to delete, as shown by `vela backup list`')\n\t\t.option('-y, --yes', 'skip the confirmation')\n\t\t.configureHelp(helpConfig),\n\t'production'\n).action((key: string, raw: unknown) =>\n\trunCommand(() => {\n\t\tconst options = raw as { yes?: boolean };\n\t\treturn withBackupTarget(raw, 'backup delete', async (ctx) => {\n\t\t\tconst found = (await listBackups(ctx.pb)).find((b) => b.key === key);\n\t\t\tif (!found) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`${ctx.targetName} has no backup called ${pc.cyan(key)}.\\n\\n` +\n\t\t\t\t\t\t`Run ${pc.cyan('vela backup list')} to see what it does have.`\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tif (!options.yes) {\n\t\t\t\tconst confirmed = await p.confirm({\n\t\t\t\t\tmessage: `Delete ${key} (${formatBytes(found.size)}) from ${ctx.targetName}?`,\n\t\t\t\t\tinitialValue: false\n\t\t\t\t});\n\t\t\t\tif (p.isCancel(confirmed) || !confirmed) {\n\t\t\t\t\tp.cancel('Operation cancelled.');\n\t\t\t\t\tprocess.exit(0);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tawait ctx.pb.backups.delete(key);\n\t\t\treportResult({ summary: `Deleted ${key} from ${ctx.targetName}.` });\n\t\t});\n\t}, 'Failed to delete the backup.')\n);\n", "import { Command } from 'commander';\nimport * as p from '@clack/prompts';\nimport pc from 'picocolors';\nimport { helpConfig } from '../../lib/help.ts';\nimport { runCommand } from '../../lib/run.ts';\nimport { reportResult } from '../../lib/result-report.ts';\nimport { addTargetOptions } from '../../lib/server-command.ts';\nimport { withBackupTarget } from '../../lib/backup-target.ts';\nimport { readSchedule, readStorageSettings, writeSchedule } from '../../lib/backups.ts';\n\nconst DEFAULT_KEEP = 7;\n\nexport const backupSchedule = addTargetOptions(\n\tnew Command('schedule')\n\t\t.description('back up automatically on a schedule')\n\t\t.argument('[cron]', 'when to run, as a cron expression \u2014 shows the current one when omitted')\n\t\t.option('--keep <n>', 'how many scheduled archives to keep', String(DEFAULT_KEEP))\n\t\t.option('--off', 'stop backing up automatically')\n\t\t.configureHelp(helpConfig),\n\t'production'\n).action((cron: string | undefined, raw: unknown) =>\n\trunCommand(() => {\n\t\tconst options = raw as { keep: string; off?: boolean };\n\t\treturn withBackupTarget(raw, 'backup schedule', async (ctx) => {\n\t\t\tif (options.off) {\n\t\t\t\tawait writeSchedule(ctx.pb, '', 0);\n\t\t\t\treportResult({ summary: `${ctx.targetName} no longer backs up automatically.` });\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (!cron) {\n\t\t\t\tconst current = await readSchedule(ctx.pb);\n\t\t\t\tp.log.info(\n\t\t\t\t\tcurrent.cron\n\t\t\t\t\t\t? `${ctx.targetName} backs up on ${pc.cyan(current.cron)}, keeping ${current.maxKeep}.`\n\t\t\t\t\t\t: `${ctx.targetName} has no backup schedule.\\n\\n` +\n\t\t\t\t\t\t\t\t`Set one with ${pc.cyan('vela backup schedule \"0 3 * * *\"')}.`\n\t\t\t\t);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst keep = Number.parseInt(options.keep, 10);\n\t\t\tif (!Number.isInteger(keep) || keep < 1) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`${pc.cyan(options.keep)} is not a number of backups to keep \u2014 pass at least 1.`\n\t\t\t\t);\n\t\t\t}\n\n\t\t\t// PocketBase validates the expression itself, and its message names the\n\t\t\t// part that is wrong, which is more use than anything guessed here.\n\t\t\tawait writeSchedule(ctx.pb, cron, keep);\n\n\t\t\tconst storage = await readStorageSettings(ctx.pb);\n\t\t\treportResult({\n\t\t\t\tsummary: `${ctx.targetName} now backs up on ${cron}, keeping ${keep}.`,\n\t\t\t\tnextSteps: [\n\t\t\t\t\t...(storage.backupsS3Enabled\n\t\t\t\t\t\t? ['Archives go to the bucket configured for backups.']\n\t\t\t\t\t\t: [\n\t\t\t\t\t\t\t\t'Archives are written to the server, on the same disk as the data they protect.',\n\t\t\t\t\t\t\t\t'Run `vela enable s3 --backups` to send them somewhere else.'\n\t\t\t\t\t\t\t]),\n\t\t\t\t\t...(storage.s3Enabled\n\t\t\t\t\t\t? ['Uploads live in S3, so these archives hold the database only.']\n\t\t\t\t\t\t: []),\n\t\t\t\t\t'`--keep` prunes only scheduled archives; ones from `vela backup create` are left alone.'\n\t\t\t\t]\n\t\t\t});\n\t\t});\n\t}, 'Failed to set the backup schedule.')\n);\n", "import fs from 'node:fs';\nimport path from 'node:path';\nimport process from 'node:process';\nimport { Command } from 'commander';\nimport * as p from '@clack/prompts';\nimport pc from 'picocolors';\nimport { helpConfig } from '../lib/help.ts';\nimport { runCommand } from '../lib/run.ts';\nimport { addTargetOptions, withTarget, type ServerContext } from '../lib/server-command.ts';\nimport { withRemotePocketbase } from '../lib/remote-pocketbase.ts';\nimport { readInstanceStates, remotePaths, runServerScript } from '../lib/remote.ts';\nimport { formatBytes, isBackupKey, listBackups, type BackupFile } from '../lib/backups.ts';\nimport { isProd } from '../lib/instance.ts';\n\ninterface RestoreResult {\n\tpreviousDataDir: string;\n\tstorageCarriedOver: boolean;\n\tmigrated: boolean;\n}\n\nexport const restore = addTargetOptions(\n\tnew Command('restore')\n\t\t.description('replace a deployment\u2019s database and uploads from a backup')\n\t\t.argument('[source]', 'a backup key on the target, or a path to a local archive')\n\t\t.configureHelp(helpConfig),\n\t'production'\n)\n\t.option('-y, --yes', 'skip the confirmation prompt')\n\t.option('--no-migrate', 'do not run migrations against the restored database')\n\t.option('--keep-previous <n>', 'how many replaced databases to keep', '1')\n\t.action((source: string | undefined, raw: unknown) =>\n\t\trunCommand(async () => {\n\t\t\tconst options = raw as { yes?: boolean; migrate: boolean; keepPrevious: string };\n\t\t\tawait withTarget(\n\t\t\t\traw,\n\t\t\t\t{\n\t\t\t\t\tremote: async (ctx) => {\n\t\t\t\t\t\tconst [state] = await readInstanceStates(ctx.session, ctx.instance);\n\t\t\t\t\t\tif (state && state.backend === false) {\n\t\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t\t`${ctx.targetName} was deployed without a database, so there is nothing to restore.`\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst local = source && fs.existsSync(source) ? source : undefined;\n\t\t\t\t\t\tconst key = local ? undefined : await resolveKey(ctx, source);\n\n\t\t\t\t\t\tif (!options.yes) {\n\t\t\t\t\t\t\tawait confirm(ctx.appName, ctx.targetName, ctx.envTag, local ?? key!);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst archive = local\n\t\t\t\t\t\t\t? await stage(ctx, local)\n\t\t\t\t\t\t\t: remotePaths.backup(ctx.instance, key!);\n\n\t\t\t\t\t\tconst result = await runServerScript<RestoreResult>(ctx.session, 'restore.sh', {\n\t\t\t\t\t\t\targs: [\n\t\t\t\t\t\t\t\tctx.instance,\n\t\t\t\t\t\t\t\t'--archive',\n\t\t\t\t\t\t\t\tarchive,\n\t\t\t\t\t\t\t\t'--keep-previous',\n\t\t\t\t\t\t\t\toptions.keepPrevious,\n\t\t\t\t\t\t\t\t...(options.migrate ? [] : ['--no-migrate']),\n\t\t\t\t\t\t\t\t// A copy this machine pushed up is scratch; one already in the\n\t\t\t\t\t\t\t\t// instance's own backups directory is not ours to delete.\n\t\t\t\t\t\t\t\t...(local ? ['--cleanup-archive'] : [])\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\tstream: true\n\t\t\t\t\t\t});\n\n\t\t\t\t\t\tp.log.success(\n\t\t\t\t\t\t\t`Restored ${pc.cyan(`${ctx.appName} (${ctx.targetName})`)} from ${pc.cyan(\n\t\t\t\t\t\t\t\tlocal ? path.basename(local) : key!\n\t\t\t\t\t\t\t)}.`\n\t\t\t\t\t\t);\n\n\t\t\t\t\t\tif (result?.storageCarriedOver) {\n\t\t\t\t\t\t\tp.log.info(\n\t\t\t\t\t\t\t\t'The archive held no uploads, so the files already on the server were kept.'\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (result?.previousDataDir) {\n\t\t\t\t\t\t\tp.log.info(\n\t\t\t\t\t\t\t\t`The database this replaced is at ${pc.cyan(result.previousDataDir)}.\\n\\n` +\n\t\t\t\t\t\t\t\t\t`It is the only way back. Remove it once you are satisfied with the restore.`\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tlabel: 'restore',\n\t\t\t\t\tlocalHint:\n\t\t\t\t\t\t'Restoring the local database is not supported yet \u2014 recreate it with `vela migrate up` and `vela seeds load`.'\n\t\t\t\t}\n\t\t\t);\n\t\t}, 'Failed to restore the backup.')\n\t);\n\n/** Work out which archive on the target to restore, asking when not told. */\nasync function resolveKey(ctx: ServerContext, source: string | undefined): Promise<string> {\n\tif (source && !isBackupKey(source)) {\n\t\tthrow new Error(\n\t\t\t`${pc.cyan(source)} is neither a file on this machine nor a backup key.\\n\\n` +\n\t\t\t\t`Run ${pc.cyan('vela backup list')} to see what ${ctx.targetName} has.`\n\t\t);\n\t}\n\n\tconst backups = await withRemotePocketbase(ctx.session, ctx.instance, listBackups);\n\tif (source) {\n\t\tif (!backups.some((b) => b.key === source)) {\n\t\t\tthrow new Error(\n\t\t\t\t`${ctx.targetName} has no backup called ${pc.cyan(source)}.\\n\\n` +\n\t\t\t\t\t`Run ${pc.cyan('vela backup list')} to see what it does have.`\n\t\t\t);\n\t\t}\n\t\treturn source;\n\t}\n\n\tif (backups.length === 0) {\n\t\tthrow new Error(\n\t\t\t`${ctx.targetName} has no backups to restore from.\\n\\n` +\n\t\t\t\t`Take one with ${pc.cyan('vela backup create')}, or pass the path to an archive on this machine.`\n\t\t);\n\t}\n\n\tconst chosen = await p.select({\n\t\tmessage: `Which backup should ${ctx.targetName} be restored from?`,\n\t\toptions: backups.map((b: BackupFile) => ({\n\t\t\tvalue: b.key,\n\t\t\tlabel: b.key,\n\t\t\thint: `${formatBytes(b.size)}, ${b.modified}`\n\t\t}))\n\t});\n\tif (p.isCancel(chosen)) {\n\t\tp.cancel('Operation cancelled.');\n\t\tprocess.exit(0);\n\t}\n\treturn chosen;\n}\n\n/**\n * Put a local archive somewhere the server can unpack it.\n *\n * Deliberately not `pb_data/backups`: that directory is moved aside during the\n * restore, so an archive placed there would disappear halfway through reading it.\n */\nasync function stage(ctx: ServerContext, file: string): Promise<string> {\n\tconst dir = remotePaths.restoreStage(ctx.instance);\n\tconst remote = `${dir}/${path.basename(file)}`;\n\n\tconst spinner = p.spinner();\n\tspinner.start(`Uploading ${path.basename(file)}`);\n\ttry {\n\t\tawait ctx.session.script(`mkdir -p \"$1\"`, { args: [dir] });\n\t\tawait ctx.session.upload([file], dir);\n\t} catch (error) {\n\t\tspinner.stop(`Could not upload ${path.basename(file)}.`);\n\t\tthrow error;\n\t}\n\tspinner.stop(`Uploaded ${path.basename(file)}`);\n\treturn remote;\n}\n\nasync function confirm(\n\tappName: string,\n\ttargetName: string,\n\tenvTag: string,\n\tfrom: string\n): Promise<void> {\n\tconst what = `${pc.cyan(`${appName} (${targetName})`)} from ${pc.cyan(path.basename(from))}`;\n\n\t// A restore overwrites a live database. On production that deserves the same\n\t// deliberate typing that destroying it does.\n\tif (isProd(envTag)) {\n\t\tconst answer = await p.text({\n\t\t\tmessage: `This replaces the database and uploads of ${what}. Type the app name to confirm`,\n\t\t\tvalidate: (value) => (value === appName ? undefined : `Type ${appName} to confirm`)\n\t\t});\n\t\tif (p.isCancel(answer)) {\n\t\t\tp.cancel('Operation cancelled.');\n\t\t\tprocess.exit(0);\n\t\t}\n\t\treturn;\n\t}\n\n\tconst ok = await p.confirm({\n\t\tmessage: `Replace the database and uploads of ${what}?`,\n\t\tinitialValue: false\n\t});\n\tif (p.isCancel(ok) || !ok) {\n\t\tp.cancel('Operation cancelled.');\n\t\tprocess.exit(0);\n\t}\n}\n", "import { Command } from 'commander';\nimport * as p from '@clack/prompts';\nimport pc from 'picocolors';\nimport { helpConfig } from '../lib/help.ts';\nimport { runCommand } from '../lib/run.ts';\nimport { getWorkspace } from './../lib/workspace.ts';\nimport { loadDeployConfig, readAppIdentity, readBindings } from '../lib/deploy-config.ts';\nimport { instanceId } from '../lib/instance.ts';\nimport { addSshOptions, sshOptionsFrom, SSH_OPTION_SCHEMA } from '../lib/ssh-options.ts';\nimport { parseOptions } from '../lib/options.ts';\nimport { withSsh } from '../lib/ssh.ts';\nimport { readInstanceStates } from '../lib/remote.ts';\nimport { getPocketbaseMetadata } from '../lib/pocketbase.ts';\nimport * as v from 'valibot';\n\nconst OptionsSchema = v.object({\n\t...SSH_OPTION_SCHEMA,\n\tjson: v.optional(v.boolean()),\n\toffline: v.optional(v.boolean())\n});\n\ninterface Row {\n\ttarget: string;\n\tkind: 'local' | 'remote';\n\tserver: string;\n\tdomain: string;\n\trelease: string;\n\treachable: boolean;\n}\n\nexport const targets = addSshOptions(\n\tnew Command('targets')\n\t\t.description('list the targets this project can deploy to')\n\t\t.configureHelp(helpConfig)\n)\n\t.option('--json', 'print raw JSON')\n\t.option('--offline', 'skip connecting to servers')\n\t.action((raw: unknown) =>\n\t\trunCommand(async () => {\n\t\t\tconst options = parseOptions(OptionsSchema, raw);\n\t\t\tconst { workspaceRootDir } = await getWorkspace();\n\t\t\tconst config = await loadDeployConfig(workspaceRootDir);\n\t\t\t// Listing must never mint an app id \u2014 that is a side effect nobody asks\n\t\t\t// for by running `vela targets`.\n\t\t\tconst app = readAppIdentity(workspaceRootDir, config);\n\t\t\tconst bindings = readBindings(workspaceRootDir);\n\n\t\t\tconst metadata = getPocketbaseMetadata(workspaceRootDir);\n\t\t\tconst rows: Row[] = [\n\t\t\t\t{\n\t\t\t\t\ttarget: 'local',\n\t\t\t\t\tkind: 'local',\n\t\t\t\t\tserver: '\u2014',\n\t\t\t\t\tdomain: metadata ? `http://${metadata.viteHost}:${metadata.vitePort}` : '\u2014',\n\t\t\t\t\trelease: '\u2014',\n\t\t\t\t\treachable: true\n\t\t\t\t}\n\t\t\t];\n\n\t\t\t// One connection per machine, not per target: a server usually hosts\n\t\t\t// several of this project's targets, and asking it once is enough.\n\t\t\tconst byServer = new Map<string, string[]>();\n\t\t\tfor (const [envTag, binding] of Object.entries(bindings)) {\n\t\t\t\tbyServer.set(binding.server, [...(byServer.get(binding.server) ?? []), envTag]);\n\t\t\t}\n\n\t\t\tfor (const [server, envTags] of byServer) {\n\t\t\t\tlet states: Awaited<ReturnType<typeof readInstanceStates>> = [];\n\t\t\t\tlet reachable = false;\n\n\t\t\t\tif (!options.offline && app) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait withSsh(server, sshOptionsFrom(options), async (session) => {\n\t\t\t\t\t\t\tawait session.detectElevation();\n\t\t\t\t\t\t\tstates = await readInstanceStates(session);\n\t\t\t\t\t\t});\n\t\t\t\t\t\treachable = true;\n\t\t\t\t\t} catch {\n\t\t\t\t\t\t// One unreachable box must not empty the whole table.\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tfor (const envTag of envTags) {\n\t\t\t\t\tconst binding = bindings[envTag]!;\n\t\t\t\t\tconst instance = app ? instanceId(app.appId, envTag) : '';\n\t\t\t\t\tconst state = states.find((candidate) => candidate.instance === instance);\n\t\t\t\t\trows.push({\n\t\t\t\t\t\ttarget: envTag,\n\t\t\t\t\t\tkind: 'remote',\n\t\t\t\t\t\tserver,\n\t\t\t\t\t\tdomain: state?.domain || binding.domain || '\u2014',\n\t\t\t\t\t\trelease: state?.activeRelease ?? (reachable ? 'not deployed' : '\u2014'),\n\t\t\t\t\t\treachable\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (options.json) {\n\t\t\t\tconsole.log(JSON.stringify(rows, null, 2));\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\treport(rows, options.offline === true);\n\t\t}, 'Failed to list targets.')\n\t);\n\nfunction report(rows: Row[], offline: boolean): void {\n\t// The header is part of the column, or a short value leaves it hanging over\n\t// the rows beneath it.\n\tconst width = (heading: string, pick: (row: Row) => string) =>\n\t\tMath.max(heading.length, ...rows.map((row) => pick(row).length));\n\tconst target = width('TARGET', (row) => row.target);\n\tconst server = width('SERVER', (row) => row.server);\n\tconst domain = width('DOMAIN', (row) => row.domain);\n\n\tconst header = `${'TARGET'.padEnd(target)} ${'SERVER'.padEnd(server)} ${'DOMAIN'.padEnd(domain)} RELEASE`;\n\tconst lines = rows.map(\n\t\t(row) =>\n\t\t\t`${row.kind === 'local' ? pc.dim(row.target.padEnd(target)) : pc.cyan(row.target.padEnd(target))} ` +\n\t\t\t`${row.server.padEnd(server)} ${row.domain.padEnd(domain)} ${row.release}`\n\t);\n\n\tp.log.info(`${pc.dim(header)}\\n${lines.join('\\n')}`);\n\n\tconst unreachable = rows.filter((row) => row.kind === 'remote' && !row.reachable);\n\tif (!offline && unreachable.length > 0) {\n\t\tp.log.warn(\n\t\t\t`Could not reach ${unreachable.map((row) => row.server).join(', ')}.\\n` +\n\t\t\t\t`Release and domain are shown from what this project recorded.`\n\t\t);\n\t}\n}\n", "import path from 'node:path';\nimport process from 'node:process';\nimport { Command } from 'commander';\nimport PocketBase from 'pocketbase';\nimport pc from 'picocolors';\nimport { x } from 'tinyexec';\nimport { detect } from 'package-manager-detector';\nimport { resolveCommand } from 'package-manager-detector/commands';\nimport fs from 'node:fs';\nimport { helpConfig } from '../lib/help.ts';\nimport { authWithRetries, findFreePort, launchPocketbase } from '../lib/pocketbase.ts';\nimport { DATA_DIR, MIGRATIONS_DIR } from '../lib/constants.ts';\nimport { DataLoadError, loadFixtures, loadSeeds } from '../lib/data.ts';\nimport { loadVite } from '../lib/vite.ts';\nimport type { Plugin, ViteDevServer } from 'vite';\n\nexport const testServer = new Command('test:server')\n\t.description('run server tests')\n\t.allowUnknownOption(true)\n\t.allowExcessArguments(true)\n\t.configureHelp(helpConfig)\n\t.action(async (_opts, cmd) => {\n\t\tconst cwd = process.cwd();\n\t\tconst email = `test-${Math.random().toString(36).slice(2)}@example.com`;\n\t\tconst password = 'password';\n\n\t\tconst testDataDir = path.join(cwd, 'test-data');\n\t\tfs.rmSync(testDataDir, { recursive: true, force: true });\n\n\t\tconst { stop, url } = await launchPocketbase(cwd, {\n\t\t\tdir: testDataDir,\n\t\t\tmigrationsDir: path.join(cwd, MIGRATIONS_DIR),\n\t\t\t// The app's PocketBase hooks (slug generation, personal teams, \u2026) are part\n\t\t\t// of its behaviour; the suite runs against the same server dev and build\n\t\t\t// start, so it loads them from the same place.\n\t\t\thooksDir: path.join(cwd, DATA_DIR, 'hooks'),\n\t\t\temail,\n\t\t\tpassword\n\t\t});\n\n\t\tprocess.env.POCKETBASE_URL = url;\n\t\tprocess.env.POCKETBASE_SUPERUSER_EMAIL = email;\n\t\tprocess.env.POCKETBASE_SUPERUSER_PASSWORD = password;\n\t\t// The app's data directory is PocketBase's, here as everywhere else. It\n\t\t// points at the throwaway one so that a database or an uploaded file the\n\t\t// suite creates is removed with it, rather than accumulating in the\n\t\t// directory the developer actually works against.\n\t\tprocess.env.VELA_DATA_DIR = testDataDir;\n\t\tprocess.env.TEST = 'true';\n\n\t\tconsole.log(`${pc.greenBright('\u2713')} Created test database`);\n\n\t\tlet vite: ViteDevServer | undefined;\n\t\tlet cleanedUp = false;\n\t\t// Synchronous so it can run from an exit or signal handler; Vite's close\n\t\t// is async and is only awaited on the normal path.\n\t\tconst cleanupSync = () => {\n\t\t\tif (cleanedUp) return;\n\t\t\tcleanedUp = true;\n\t\t\tstop();\n\t\t\tfs.rmSync(testDataDir, { recursive: true, force: true });\n\t\t};\n\t\tconst cleanup = async () => {\n\t\t\tif (cleanedUp) return;\n\t\t\tawait vite?.close().catch(() => {});\n\t\t\tcleanupSync();\n\t\t};\n\t\tconst fail = async (message: string): Promise<never> => {\n\t\t\tconsole.error(`${pc.redBright('\u2717')} ${message}`);\n\t\t\tawait cleanup();\n\t\t\tprocess.exit(1);\n\t\t};\n\t\tprocess.on('exit', cleanupSync);\n\t\tprocess.on('SIGINT', () => {\n\t\t\tcleanupSync();\n\t\t\tprocess.exit(130);\n\t\t});\n\n\t\tconst pb = new PocketBase(url);\n\t\ttry {\n\t\t\tawait authWithRetries(pb, email, password);\n\t\t} catch (e) {\n\t\t\tawait fail(`Auth failed: ${(e as Error).message}`);\n\t\t}\n\n\t\t// Seeds are the data the app needs to function and fixtures are its test\n\t\t// data, so the test database carries both. They go in through the running\n\t\t// server so the app's hooks apply to them as they would to any write.\n\t\ttry {\n\t\t\tconst seeds = await loadSeeds(pb, cwd);\n\t\t\tif (seeds.length > 0) {\n\t\t\t\tconsole.log(`${pc.greenBright('\u2713')} Loaded ${seeds.length} seed file(s)`);\n\t\t\t}\n\t\t\tconst fixtures = await loadFixtures(pb, cwd);\n\t\t\tif (fixtures.length > 0) {\n\t\t\t\tconsole.log(`${pc.greenBright('\u2713')} Loaded ${fixtures.length} fixture file(s)`);\n\t\t\t}\n\t\t} catch (e) {\n\t\t\tawait fail(describeLoadFailure(e));\n\t\t}\n\n\t\tconst { createServer } = await loadVite(cwd);\n\t\tvite = await createServer({\n\t\t\tmode: 'test',\n\t\t\tplugins: [stubPagesPlugin()],\n\t\t\toptimizeDeps: { noDiscovery: true }\n\t\t});\n\t\tconst vitePort = await findFreePort();\n\t\tawait vite.listen(vitePort);\n\t\tprocess.env.VITE_TEST_URL = `http://localhost:${vitePort}`;\n\n\t\tconsole.log(`${pc.greenBright('\u2713')} Started Vite: http://localhost:${vitePort}`);\n\t\tconsole.log(`${pc.greenBright('\u2713')} Started PocketBase: ${url}`);\n\n\t\tconst extraArgs: string[] = (cmd.parent?.args ?? []).slice(1);\n\t\tlet filter = extraArgs.find((arg: string) => !arg.startsWith('-'));\n\t\tconst passthrough = filter ? extraArgs.filter((a: string) => a !== filter) : extraArgs;\n\t\tif (!filter) filter = 'server';\n\n\t\ttry {\n\t\t\tconst pm = (await detect({ cwd }))?.name ?? 'npm';\n\t\t\tconst resolved = resolveCommand(pm, 'execute', [\n\t\t\t\t'vitest',\n\t\t\t\t'run',\n\t\t\t\tfilter,\n\t\t\t\t'--reporter=dot',\n\t\t\t\t...passthrough\n\t\t\t])!;\n\t\t\tconst resolvedArgs = resolved.args.slice();\n\t\t\tif (pm === 'npm') resolvedArgs.unshift('--yes');\n\t\t\tconst result = await x(resolved.command, resolvedArgs, {\n\t\t\t\tnodeOptions: { cwd, stdio: 'inherit', env: { ...process.env, CI: '1' } }\n\t\t\t});\n\t\t\t// A failing suite is this command failing: CI reads the exit code.\n\t\t\tprocess.exitCode = result.exitCode ?? 1;\n\t\t} catch (e) {\n\t\t\tconsole.error(`${pc.redBright('\u2717')} ${(e as Error).message}`);\n\t\t\tprocess.exitCode = 1;\n\t\t} finally {\n\t\t\tawait cleanup();\n\t\t}\n\t});\n\nfunction describeLoadFailure(e: unknown): string {\n\tif (e instanceof DataLoadError) {\n\t\tconst hint =\n\t\t\te.kind === 'fixtures'\n\t\t\t\t? 'Run `vela fixtures regen` to regenerate fixtures from the current schema.'\n\t\t\t\t: `Check ${e.file} against the current schema.`;\n\t\treturn `Failed to load ${e.message}\\n ${hint}`;\n\t}\n\treturn `Failed to load test data: ${(e as Error).message}`;\n}\n\nfunction stubPagesPlugin(): Plugin {\n\tconst stub = `<script>export const render = () => '';</script>`;\n\treturn {\n\t\tname: 'stub-pages',\n\t\tresolveId(id: string) {\n\t\t\tif (id.endsWith('+page.svelte')) return id;\n\t\t\treturn undefined;\n\t\t},\n\t\tload(id: string) {\n\t\t\tif (\n\t\t\t\tid.endsWith('+page.svelte') ||\n\t\t\t\tid.endsWith('+layout.svelte') ||\n\t\t\t\tid.endsWith('+error.svelte')\n\t\t\t) {\n\t\t\t\treturn stub;\n\t\t\t}\n\t\t\treturn undefined;\n\t\t}\n\t};\n}\n", "import fs from 'node:fs';\nimport path from 'node:path';\nimport process from 'node:process';\nimport { Command } from 'commander';\nimport { helpConfig } from '../lib/help.ts';\nimport { getWorkspace } from '../lib/workspace.ts';\n\ninterface Route {\n\tid: string;\n\turlPattern: string;\n\tmethods: string[];\n}\n\nconst HTTP_METHODS = new Set([\n\t'GET',\n\t'POST',\n\t'PUT',\n\t'PATCH',\n\t'DELETE',\n\t'OPTIONS',\n\t'HEAD',\n\t'fallback'\n]);\n\nexport const routes = new Command('routes')\n\t.description('list routes')\n\t.configureHelp(helpConfig)\n\t.action(async () => {\n\t\tconst { workspaceRootDir, routesDir } = await getWorkspace();\n\t\tconst routesRoot = path.join(workspaceRootDir, routesDir);\n\t\tconst found = walk(routesRoot, routesRoot).filter((r) => r.methods.length > 0);\n\t\tfound.sort((a, b) => a.urlPattern.localeCompare(b.urlPattern));\n\t\tprintTable(found);\n\t});\n\nfunction walk(root: string, dir: string): Route[] {\n\tconst entries = fs.readdirSync(dir, { withFileTypes: true });\n\tconst routes: Route[] = [];\n\n\tconst hasLeaf = entries.some((e) => e.isFile() && isRouteFile(e.name));\n\tif (hasLeaf) {\n\t\tconst id = '/' + path.relative(root, dir).split(path.sep).filter(Boolean).join('/');\n\t\tconst urlPattern = id.replace(/\\([^)]+\\)\\/?/g, '').replace(/\\/$/, '') || '/';\n\t\tconst methods = new Set<string>();\n\t\tfor (const entry of entries) {\n\t\t\tif (!entry.isFile()) continue;\n\t\t\tif (entry.name.endsWith('+page.svelte')) methods.add('GET');\n\t\t\tif (\n\t\t\t\tentry.name.endsWith('+server.ts') ||\n\t\t\t\tentry.name.endsWith('+server.js') ||\n\t\t\t\tentry.name.endsWith('+page.server.ts') ||\n\t\t\t\tentry.name.endsWith('+page.server.js')\n\t\t\t) {\n\t\t\t\textractMethods(path.join(dir, entry.name)).forEach((m) => methods.add(m));\n\t\t\t}\n\t\t}\n\t\troutes.push({ id: id || '/', urlPattern, methods: [...methods] });\n\t}\n\n\tfor (const entry of entries) {\n\t\tif (entry.isDirectory()) routes.push(...walk(root, path.join(dir, entry.name)));\n\t}\n\treturn routes;\n}\n\nfunction isRouteFile(name: string): boolean {\n\treturn (\n\t\tname.startsWith('+page.') || name.startsWith('+server.') || name.startsWith('+layout.server.')\n\t);\n}\n\nfunction extractMethods(file: string): string[] {\n\ttry {\n\t\tconst content = fs.readFileSync(file, 'utf8');\n\t\tconst methods: string[] = [];\n\t\tconst exportRegex = /export\\s+(?:const|async\\s+function|function)\\s+(\\w+)/g;\n\t\tlet match: RegExpExecArray | null;\n\t\twhile ((match = exportRegex.exec(content)) !== null) {\n\t\t\tconst name = match[1]!;\n\t\t\tif (HTTP_METHODS.has(name)) methods.push(name);\n\t\t\tif (name === 'actions') methods.push('POST');\n\t\t}\n\t\treturn methods;\n\t} catch {\n\t\treturn [];\n\t}\n}\n\nfunction printTable(routes: Route[]): void {\n\tif (routes.length === 0) {\n\t\tconsole.log('No routes found.');\n\t\treturn;\n\t}\n\tconst urlWidth = Math.max(...routes.map((r) => r.urlPattern.length), 3) + 2;\n\tconst methodsWidth = 30;\n\tconst idWidth = Math.max(...routes.map((r) => r.id.length), 2) + 2;\n\n\tconst line = (a: string, b: string, c: string) =>\n\t\t'\u250C' + '\u2500'.repeat(urlWidth) + a + '\u2500'.repeat(methodsWidth) + b + '\u2500'.repeat(idWidth) + c;\n\tconsole.log(line('\u252C', '\u252C', '\u2510'));\n\tconsole.log(\n\t\t'\u2502 ' +\n\t\t\t'URL'.padEnd(urlWidth - 2) +\n\t\t\t' \u2502 ' +\n\t\t\t'Methods'.padEnd(methodsWidth - 2) +\n\t\t\t' \u2502 ' +\n\t\t\t'ID'.padEnd(idWidth - 2) +\n\t\t\t' \u2502'\n\t);\n\tconsole.log(\n\t\t'\u251C' + '\u2500'.repeat(urlWidth) + '\u253C' + '\u2500'.repeat(methodsWidth) + '\u253C' + '\u2500'.repeat(idWidth) + '\u2524'\n\t);\n\tfor (const r of routes) {\n\t\tconsole.log(\n\t\t\t'\u2502 ' +\n\t\t\t\tr.urlPattern.padEnd(urlWidth - 2) +\n\t\t\t\t' \u2502 ' +\n\t\t\t\tr.methods.join(', ').padEnd(methodsWidth - 2) +\n\t\t\t\t' \u2502 ' +\n\t\t\t\tr.id.padEnd(idWidth - 2) +\n\t\t\t\t' \u2502'\n\t\t);\n\t}\n\tconsole.log(\n\t\t'\u2514' + '\u2500'.repeat(urlWidth) + '\u2534' + '\u2500'.repeat(methodsWidth) + '\u2534' + '\u2500'.repeat(idWidth) + '\u2518'\n\t);\n}\n", "import process from 'node:process';\nimport { Command } from 'commander';\nimport { x } from 'tinyexec';\nimport { detect } from 'package-manager-detector';\nimport { resolveCommand } from 'package-manager-detector/commands';\nimport { helpConfig } from '../lib/help.ts';\n\nasync function runWuchale(extraArgs: string[]): Promise<void> {\n\tconst cwd = process.cwd();\n\tconst pm = (await detect({ cwd }))?.name ?? 'npm';\n\tconst resolved = resolveCommand(pm, 'execute', ['wuchale', ...extraArgs])!;\n\tconst args = resolved.args.slice();\n\tif (pm === 'npm') args.unshift('--yes');\n\tawait x(resolved.command, args, {\n\t\tnodeOptions: { cwd, stdio: 'inherit' },\n\t\tthrowOnError: true\n\t});\n}\n\nconst extract = new Command('extract')\n\t.description('extract translatable strings')\n\t.configureHelp(helpConfig)\n\t.action(() => runWuchale([]));\n\nconst watch = new Command('watch')\n\t.description('watch and extract translatable strings')\n\t.configureHelp(helpConfig)\n\t.action(() => runWuchale(['--watch']));\n\nconst status = new Command('status')\n\t.description('show i18n status')\n\t.configureHelp(helpConfig)\n\t.action(() => runWuchale(['status']));\n\nconst clean = new Command('clean')\n\t.description('clean unused translatable strings')\n\t.configureHelp(helpConfig)\n\t.action(() => runWuchale(['--clean']));\n\nexport const i18n = new Command('i18n')\n\t.description('i18n utilities')\n\t.configureHelp(helpConfig)\n\t.addCommand(extract, { isDefault: true })\n\t.addCommand(watch)\n\t.addCommand(status)\n\t.addCommand(clean);\n", "import { stubCommand } from '../lib/stub.ts';\n\nexport const oauth = stubCommand('oauth', 'configure OAuth providers');\n", "import { stubCommand } from '../lib/stub.ts';\n\nexport const schemas = stubCommand('schemas', 'manage database schemas');\n", "import { Command } from 'commander';\nimport { helpConfig } from '../lib/help.ts';\nimport { editor } from './cms/editor.ts';\n\nexport const cms = new Command('cms')\n\t.description('manage the CMS')\n\t.configureHelp(helpConfig)\n\t.addCommand(editor);\n", "import { Command } from 'commander';\nimport { helpConfig } from '../../lib/help.ts';\nimport { editorAdd } from './editor/add.ts';\nimport { editorPassword } from './editor/password.ts';\nimport { editorList } from './editor/list.ts';\n\n/**\n * The admin bar signs in against the CMS's own `cms_editors` table, which\n * starts empty and has no UI to fill it. These commands are how an editor\n * gets an account.\n */\nexport const editor = new Command('editor')\n\t.description('manage who can sign in to the admin bar')\n\t.configureHelp(helpConfig)\n\t.addCommand(editorAdd)\n\t.addCommand(editorPassword)\n\t.addCommand(editorList);\n", "import { randomBytes } from 'node:crypto';\nimport { Command } from 'commander';\nimport * as p from '@clack/prompts';\nimport pc from 'picocolors';\nimport { helpConfig } from '../../../lib/help.ts';\nimport { runCommand } from '../../../lib/run.ts';\nimport { DEFAULT_PROJECT, withCmsBackend } from '../../../lib/cms-backend.ts';\n\nexport const editorAdd = new Command('add')\n\t.description('create an editor who can sign in to the admin bar')\n\t.argument('<email>', 'email the editor signs in with')\n\t.option('--password <password>', 'password to set \u2014 generated and shown once when omitted')\n\t.option('--project <id>', 'project the editor may edit', DEFAULT_PROJECT)\n\t.configureHelp(helpConfig)\n\t.action((email: string, options: { password?: string; project: string }) =>\n\t\trunCommand(async () => {\n\t\t\tconst generated = options.password === undefined;\n\t\t\t// 96 bits, URL-safe, and never written anywhere but this terminal.\n\t\t\tconst password = options.password ?? randomBytes(12).toString('base64url');\n\n\t\t\tconst editor = await withCmsBackend((cms) =>\n\t\t\t\tcms.editors.create({ email, password, projects: [options.project] })\n\t\t\t);\n\n\t\t\tconst lines = [`Added ${pc.cyan(editor.email)} as an editor of ${pc.cyan(options.project)}.`];\n\t\t\tif (generated) {\n\t\t\t\tlines.push('', `Password: ${pc.bold(password)}`, '', 'It is shown once; copy it now.');\n\t\t\t}\n\t\t\tp.log.success(lines.join('\\n'));\n\t\t\tp.log.info(\n\t\t\t\t`Run ${pc.cyan('vela dev')}, open any page with ${pc.cyan('?edit')} on the URL (or press ${pc.cyan('Ctrl+E')}), and sign in.`\n\t\t\t);\n\t\t}, 'Failed to add the editor.')\n\t);\n", "import { createRequire } from 'node:module';\nimport path from 'node:path';\nimport process from 'node:process';\nimport { pathToFileURL } from 'node:url';\nimport pc from 'picocolors';\nimport { findWorkspaceRoot, localDataDir } from './workspace.ts';\n\n/**\n * The slice of `@velastack/cms/backend` the CLI drives.\n *\n * Declared here rather than imported because the package is the project's\n * dependency, not the CLI's: `vela enable cms` installs it into the app, and\n * `vela cms editor \u2026` has to open the same database that app serves, through\n * the same version of the package. Resolving from the project also means a\n * global `vela` and a project-pinned one behave identically.\n */\nexport interface CmsEditor {\n\tid: string;\n\temail: string;\n\tname: string;\n}\n\nexport interface CmsEditorStore {\n\tcreate(input: {\n\t\temail: string;\n\t\tpassword: string;\n\t\tname?: string;\n\t\tprojects?: string[];\n\t}): Promise<CmsEditor>;\n\tsetPassword(idOrEmail: string, password: string): Promise<void>;\n\tlist(): CmsEditor[];\n\tprojectsFor(idOrEmail: string): string[];\n}\n\nexport interface CmsBackend {\n\teditors: CmsEditorStore;\n\tclose(): void;\n}\n\ninterface CmsBackendModule {\n\tcreateCmsBackend(options: { dbPath: string; uploadDir: string }): CmsBackend;\n}\n\n/**\n * The project id a single-tenant mount resolves every request to. It is the\n * backend's own default, so an editor granted this id can sign in to the app\n * `vela enable cms` produced without any further configuration.\n */\nexport const DEFAULT_PROJECT = 'default';\n\n/** Where the app keeps the CMS database, as `dataPath('cms.sqlite')` resolves it. */\nexport function cmsDatabasePath(root: string): string {\n\treturn path.join(localDataDir(root), 'cms.sqlite');\n}\n\nasync function loadBackendModule(root: string): Promise<CmsBackendModule> {\n\tlet entry: string;\n\ttry {\n\t\tentry = createRequire(path.join(root, 'package.json')).resolve('@velastack/cms/backend');\n\t} catch {\n\t\tthrow new Error(\n\t\t\t`@velastack/cms is not installed in this project.\\n\\n` +\n\t\t\t\t`Run ${pc.cyan('vela enable cms')} first.`\n\t\t);\n\t}\n\treturn (await import(pathToFileURL(entry).href)) as CmsBackendModule;\n}\n\n/**\n * Open the project's CMS backend, run `fn` against it, and close it.\n *\n * Opens the database at the same path the app uses \u2014 `<data dir>/cms.sqlite`,\n * resolved from the workspace root rather than the working directory so the\n * command can be run from a subdirectory \u2014 and so writes to the editors the\n * running app signs in against.\n */\nexport async function withCmsBackend<T>(\n\tfn: (backend: CmsBackend) => Promise<T>,\n\tcwd: string = process.cwd()\n): Promise<T> {\n\tconst root = findWorkspaceRoot(cwd);\n\tif (!root) {\n\t\tthrow new Error('Could not find workspace root (no package.json found)');\n\t}\n\n\tconst { createCmsBackend } = await loadBackendModule(root);\n\tconst dataDir = localDataDir(root);\n\t// A missing driver throws a message naming better-sqlite3 and how to\n\t// install it, which is exactly what should be shown.\n\tconst backend = createCmsBackend({\n\t\tdbPath: path.join(dataDir, 'cms.sqlite'),\n\t\tuploadDir: path.join(dataDir, 'uploads')\n\t});\n\n\ttry {\n\t\treturn await fn(backend);\n\t} finally {\n\t\tbackend.close();\n\t}\n}\n", "import { Command } from 'commander';\nimport * as p from '@clack/prompts';\nimport pc from 'picocolors';\nimport { helpConfig } from '../../../lib/help.ts';\nimport { runCommand } from '../../../lib/run.ts';\nimport { withCmsBackend } from '../../../lib/cms-backend.ts';\n\nexport const editorPassword = new Command('password')\n\t.description(\"set an editor's password\")\n\t.argument('<email>', 'email of the editor')\n\t.argument('<password>', 'new password')\n\t.configureHelp(helpConfig)\n\t.action((email: string, password: string) =>\n\t\trunCommand(async () => {\n\t\t\tawait withCmsBackend((cms) => cms.editors.setPassword(email, password));\n\t\t\t// The backend ends every session for the editor on a password change.\n\t\t\tp.log.success(\n\t\t\t\t`Updated the password for ${pc.cyan(email)}. Existing sessions were signed out.`\n\t\t\t);\n\t\t}, 'Failed to set the password.')\n\t);\n", "import { Command } from 'commander';\nimport * as p from '@clack/prompts';\nimport pc from 'picocolors';\nimport { helpConfig } from '../../../lib/help.ts';\nimport { runCommand } from '../../../lib/run.ts';\nimport { withCmsBackend } from '../../../lib/cms-backend.ts';\n\nexport const editorList = new Command('list')\n\t.description('list editors and the projects they may edit')\n\t.configureHelp(helpConfig)\n\t.action(() =>\n\t\trunCommand(async () => {\n\t\t\tconst rows = await withCmsBackend(async (cms) =>\n\t\t\t\tcms.editors.list().map((editor) => ({\n\t\t\t\t\temail: editor.email,\n\t\t\t\t\tprojects: cms.editors.projectsFor(editor.id)\n\t\t\t\t}))\n\t\t\t);\n\n\t\t\tif (rows.length === 0) {\n\t\t\t\tp.log.info(`No editors yet. Add one with ${pc.cyan('vela cms editor add <email>')}.`);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst width = Math.max(...rows.map((row) => row.email.length));\n\t\t\tp.log.info(\n\t\t\t\t`Editors\\n\\n` +\n\t\t\t\t\trows\n\t\t\t\t\t\t.map(\n\t\t\t\t\t\t\t(row) =>\n\t\t\t\t\t\t\t\t` ${row.email.padEnd(width)} ${pc.dim(row.projects.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AAAA,EACA;AAAA,EACAI;AAAA,EACA;AAAA,EACA;AAAA,EACAC;AACD,GAAG;AACF,UAAQ,WAAW,OAAO;AAC3B;;;AF9LA,QAAQ,MAAM,cAAcC,UAAQ,KAAK,MAAM,CAAC,CAAC,GAAG,EAAE,MAAM,OAAO,CAAC;",
6
+ "names": ["process", "process", "p", "Command", "dotenv", "pc", "pc", "pc", "fs", "process", "path", "process", "fs", "fs", "path", "process", "v", "Command", "p", "pc", "resolveCommand", "schema", "fs", "path", "fs", "path", "process", "p", "pm", "fs", "path", "process", "detect", "resolve", "email", "password", "path", "fs", "detect", "process", "require", "fs", "path", "fs", "path", "fs", "path", "init", "path", "fs", "fs", "path", "p", "report", "label", "fs", "path", "path", "fs", "Command", "email", "password", "process", "path", "fs", "pc", "resolveCommand", "fs", "path", "process", "v", "Command", "p", "detect", "resolveCommand", "optionsSchema", "Command", "path", "process", "detect", "resolveCommand", "onCancel", "fs", "email", "password", "Command", "Command", "p", "path", "p", "path", "slug", "report", "log", "collections", "fs", "path", "p", "pc", "fs", "path", "fs", "path", "p", "spinner", "p", "p", "pc", "path", "fs", "Command", "stage", "slug", "Command", "p", "Command", "stage", "Command", "Command", "Command", "p", "Command", "stage", "slug", "Command", "Command", "Command", "Command", "Command", "Command", "Command", "Command", "Command", "Command", "Command", "Command", "Command", "Command", "Command", "Command", "process", "Command", "p", "Command", "process", "v", "Command", "Command", "process", "Command", "p", "pc", "process", "v", "p", "pc", "fs", "path", "path", "fs", "slug", "env", "v", "fs", "os", "path", "crypto", "process", "spawn", "resolve", "path", "path", "fs", "env", "fs", "text", "label", "base", "pc", "process", "pc", "fs", "p", "pc", "fs", "env", "email", "password", "pc", "PocketBase", "env", "email", "password", "PocketBase", "label", "pc", "email", "password", "fs", "path", "s3", "path", "fs", "Command", "pc", "text", "process", "password", "confirm", "process", "Command", "p", "Command", "v", "process", "process", "Command", "p", "pc", "Command", "pc", "process", "Command", "Command", "Command", "Command", "Command", "Command", "Command", "process", "p", "process", "auth", "Command", "Command", "api", "Command", "Command", "apiKeys", "Command", "Command", "backend", "Command", "Command", "contentNegotiation", "Command", "Command", "i18n", "Command", "Command", "teams", "Command", "Command", "payments", "Command", "Command", "p", "pc", "s3", "Command", "label", "pc", "Command", "smtp", "Command", "Command", "auth", "api", "apiKeys", "backend", "contentNegotiation", "i18n", "teams", "payments", "s3", "smtp", "Command", "Command", "process", "p", "slug", "report", "process", "form", "Command", "Command", "schema", "Command", "Command", "resource", "Command", "Command", "scaffold", "Command", "process", "Command", "p", "pc", "Command", "confirm", "pc", "process", "Command", "form", "schema", "resource", "scaffold", "Command", "Command", "exec", "detect", "resolveCommand", "Command", "detect", "resolveCommand", "exec", "fs", "path", "Command", "path", "fs", "Command", "Command", "Command", "fs", "path", "Command", "p", "process", "p", "email", "email", "subscriptions", "path", "fs", "Command", "fs", "path", "Command", "p", "compute", "v", "sectionHeader", "sectionDefinitions", "intro", "sectionLinks", "sectionChanges", "sectionContact", "path", "fs", "Command", "Command", "Command", "Command", "fs", "path", "collections", "path", "fs", "list", "label", "seeds", "collections", "Command", "Command", "Command", "Command", "Command", "fs", "path", "Command", "InvalidArgumentError", "p", "InvalidArgumentError", "list", "fs", "path", "collections", "schema", "generate", "Command", "Command", "InvalidArgumentError", "p", "parseCount", "InvalidArgumentError", "parseSeed", "Command", "Command", "generate", "Command", "Command", "load", "Command", "fs", "path", "Command", "padZeros", "Command", "fs", "path", "collections", "Command", "clear", "Command", "Command", "load", "clear", "Command", "p", "makeFetchCookie", "os", "Command", "p", "Command", "email", "password", "label", "os", "Command", "email", "password", "makeFetchCookie", "Command", "p", "Command", "Command", "p", "Command", "Command", "Command", "path", "process", "x", "process", "x", "path", "Command", "Command", "InvalidArgumentError", "InvalidArgumentError", "Command", "fs", "path", "process", "Command", "create", "Command", "process", "path", "fs", "fs", "path", "process", "Command", "Command", "process", "listMigrationFiles", "path", "fs", "Command", "Command", "Command", "create", "fs", "path", "process", "Command", "InvalidArgumentError", "pc", "PocketBase", "path", "process", "createRequire", "pathToFileURL", "pc", "InvalidArgumentError", "Command", "process", "path", "backend", "fs", "dataDir", "PocketBase", "pc", "fs", "path", "process", "Command", "p", "pc", "x", "detect", "resolveCommand", "env", "process", "process", "path", "Command", "process", "dataDir", "detect", "resolveCommand", "x", "fs", "pc", "path", "process", "Command", "x", "detect", "resolveCommand", "Command", "process", "dataDir", "path", "detect", "resolveCommand", "x", "path", "Command", "Command", "path", "Command", "p", "pc", "v", "OptionsSchema", "Command", "pc", "path", "fs", "Command", "Option", "p", "pc", "v", "fs", "path", "process", "PocketBase", "dataDir", "path", "fs", "email", "process", "password", "PocketBase", "fs", "path", "detect", "resolveCommand", "env", "result", "detect", "resolveCommand", "add", "path", "fs", "OptionsSchema", "Command", "Option", "backend", "pc", "email", "password", "fs", "path", "path", "process", "Command", "p", "createProject", "Command", "teams", "createProject", "process", "defaultProjectName", "v", "path", "Command", "Command", "p", "pc", "Command", "env", "pc", "process", "Command", "p", "pc", "Command", "pc", "env", "process", "Command", "p", "pc", "Command", "pc", "env", "fs", "path", "process", "Command", "p", "pc", "Command", "pc", "path", "process", "fs", "Command", "Command", "p", "pc", "Command", "report", "pc", "label", "Command", "p", "pc", "Command", "pc", "Command", "Command", "Command", "process", "Command", "p", "pc", "Command", "email", "password", "promptPassword", "pc", "base", "process", "Command", "Command", "fs", "path", "Command", "p", "pc", "slug", "list", "resolve", "Command", "pc", "spinner", "path", "fs", "Command", "p", "pc", "Command", "pc", "fs", "path", "Command", "p", "pc", "Command", "pc", "path", "fs", "spinner", "process", "Command", "p", "pc", "Command", "pc", "process", "Command", "p", "pc", "Command", "pc", "Command", "fs", "path", "process", "Command", "p", "pc", "Command", "fs", "confirm", "pc", "path", "process", "spinner", "Command", "p", "pc", "v", "OptionsSchema", "Command", "report", "pc", "path", "process", "Command", "PocketBase", "pc", "x", "detect", "resolveCommand", "fs", "Command", "process", "email", "password", "path", "fs", "pc", "PocketBase", "seeds", "fixtures", "detect", "resolveCommand", "x", "fs", "path", "Command", "Command", "path", "fs", "routes", "process", "Command", "x", "detect", "resolveCommand", "process", "detect", "resolveCommand", "x", "Command", "status", "i18n", "Command", "Command", "Command", "p", "pc", "createRequire", "path", "process", "pathToFileURL", "pc", "createRequire", "path", "pc", "pathToFileURL", "process", "dataDir", "backend", "Command", "email", "password", "editor", "cms", "pc", "Command", "p", "pc", "Command", "email", "password", "cms", "pc", "Command", "p", "pc", "Command", "cms", "editor", "pc", "Command", "cms", "Command", "Command", "process", "dotenv", "path", "pc", "i18n", "cms", "process"]
7
7
  }