@velastack/patterns 0.1.10 → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +22 -0
- package/dist/chunks/{collections-C1SaNdMd.js → collections-wIKcIKzY.js} +3 -3
- package/dist/chunks/{collections-C1SaNdMd.js.map → collections-wIKcIKzY.js.map} +1 -1
- package/dist/chunks/constants-PBCzh8eY.js +6 -0
- package/dist/chunks/constants-PBCzh8eY.js.map +1 -0
- package/dist/chunks/errors-D6gyegUK.js +14 -0
- package/dist/chunks/errors-D6gyegUK.js.map +1 -0
- package/dist/chunks/format-result-BdAy5M8C.js +50 -0
- package/dist/chunks/format-result-BdAy5M8C.js.map +1 -0
- package/dist/chunks/{generate-3QOmCHGZ.js → generate-vRi-W3rL.js} +2 -2
- package/dist/chunks/{generate-3QOmCHGZ.js.map → generate-vRi-W3rL.js.map} +1 -1
- package/dist/chunks/{generate.runtime-eojYS75G.js → generate.runtime-4QI3es6J.js} +2 -2
- package/dist/chunks/{generate.runtime-eojYS75G.js.map → generate.runtime-4QI3es6J.js.map} +1 -1
- package/dist/chunks/{generate.runtime-CKW5vPzA.js → generate.runtime-BX0QcpGg.js} +2 -2
- package/dist/chunks/{generate.runtime-CKW5vPzA.js.map → generate.runtime-BX0QcpGg.js.map} +1 -1
- package/dist/chunks/{generate.runtime-DnFdGn1e.js → generate.runtime-BlK7yHff.js} +2 -2
- package/dist/chunks/{generate.runtime-DnFdGn1e.js.map → generate.runtime-BlK7yHff.js.map} +1 -1
- package/dist/chunks/{generate.runtime-C2DgLTi8.js → generate.runtime-BmW0th7X.js} +2 -2
- package/dist/chunks/{generate.runtime-C2DgLTi8.js.map → generate.runtime-BmW0th7X.js.map} +1 -1
- package/dist/chunks/{generate.runtime-B08p7DoC.js → generate.runtime-C4wcEIc9.js} +3 -3
- package/dist/chunks/{generate.runtime-B08p7DoC.js.map → generate.runtime-C4wcEIc9.js.map} +1 -1
- package/dist/chunks/{generate.runtime-CWA_i6Ch.js → generate.runtime-CAzHPuHk.js} +2 -2
- package/dist/chunks/{generate.runtime-CWA_i6Ch.js.map → generate.runtime-CAzHPuHk.js.map} +1 -1
- package/dist/chunks/{generate.runtime-CK1ApRFh.js → generate.runtime-CNrtLDCf.js} +2 -2
- package/dist/chunks/{generate.runtime-CK1ApRFh.js.map → generate.runtime-CNrtLDCf.js.map} +1 -1
- package/dist/chunks/{generate.runtime-D33zutDr.js → generate.runtime-CQ0Veyk4.js} +3 -3
- package/dist/chunks/{generate.runtime-D33zutDr.js.map → generate.runtime-CQ0Veyk4.js.map} +1 -1
- package/dist/chunks/{generate.runtime-YwrRBYSg.js → generate.runtime-CQWygx-F.js} +2 -2
- package/dist/chunks/{generate.runtime-YwrRBYSg.js.map → generate.runtime-CQWygx-F.js.map} +1 -1
- package/dist/chunks/{generate.runtime-BS0FFasX.js → generate.runtime-DOBfTVW3.js} +3 -3
- package/dist/chunks/{generate.runtime-BS0FFasX.js.map → generate.runtime-DOBfTVW3.js.map} +1 -1
- package/dist/chunks/{generate.runtime-B3IKmGyV.js → generate.runtime-DpgPAnEd.js} +2 -2
- package/dist/chunks/{generate.runtime-B3IKmGyV.js.map → generate.runtime-DpgPAnEd.js.map} +1 -1
- package/dist/chunks/{pocketbase-C4NoNrnW.js → pocketbase-fERkp8b8.js} +6 -6
- package/dist/chunks/{pocketbase-C4NoNrnW.js.map → pocketbase-fERkp8b8.js.map} +1 -1
- package/dist/chunks/{shared--GUUivGs.js → shared-BZlvCHX8.js} +2 -2
- package/dist/chunks/{shared--GUUivGs.js.map → shared-BZlvCHX8.js.map} +1 -1
- package/dist/chunks/ui-DZS2SAQg.js +173 -0
- package/dist/chunks/ui-DZS2SAQg.js.map +1 -0
- package/dist/chunks/write-result-Cb3r0sCO.js +445 -0
- package/dist/chunks/write-result-Cb3r0sCO.js.map +1 -0
- package/dist/index.d.ts +161 -2
- package/dist/index.js +2097 -2103
- package/dist/index.js.map +1 -1
- package/package.json +3 -1
- package/dist/chunks/constants-qmioN-7W.js +0 -6
- package/dist/chunks/constants-qmioN-7W.js.map +0 -1
- package/dist/chunks/errors-D3Zy3wCg.js +0 -10
- package/dist/chunks/errors-D3Zy3wCg.js.map +0 -1
- package/dist/chunks/write-result-Hq8bafvV.js +0 -296
- package/dist/chunks/write-result-Hq8bafvV.js.map +0 -1
package/README.md
CHANGED
|
@@ -66,6 +66,28 @@ the modifications work across a wide range of project setups.
|
|
|
66
66
|
|
|
67
67
|
The `preview-modifies` directory is the mock modify output used only for previews. It's bundled in the same way as the `creates` directory.
|
|
68
68
|
|
|
69
|
+
## UI components
|
|
70
|
+
|
|
71
|
+
`src/ui/components/<name>` holds the components Vela ships itself (`data-table`, `multiselect`, `geopoint`,
|
|
72
|
+
`auth-menu`, ...). They are bundled as raw strings the same way `creates` are and copied into a project's
|
|
73
|
+
`src/lib/components/ui` by `installComponents()` in `src/runtime/write-result.ts`. Everything else a pattern
|
|
74
|
+
lists in `components` is handed to `shadcn-svelte add`, which resolves it from the style-scoped registry
|
|
75
|
+
(`/registry/styles/<style>/`) named by the project's `components.json`.
|
|
76
|
+
|
|
77
|
+
- `customDependencies` must list every `$lib/components/ui/<x>` a shipped component imports, and
|
|
78
|
+
`customNpmPackages` every npm package no shadcn item installs for it.
|
|
79
|
+
- `installComponents()` is also exported from the package; `vela ui add` calls it. It is node-only and is
|
|
80
|
+
loaded on the first call, the same rule as `generate.runtime.ts`. Before spawning `shadcn-svelte add` it
|
|
81
|
+
checks bare item names against the style's registry index (`src/runtime/registry.ts`) and rejects
|
|
82
|
+
unknown ones with an `InvalidArgumentError`; when the registry cannot be read the check is skipped.
|
|
83
|
+
- `listComponents()`, `switchStyle()`, `applyBaseColor()` and `applyTheme()` (`src/runtime/ui.ts`) back
|
|
84
|
+
`vela ui list`, `vela ui style`, `vela ui base` and `vela ui theme`. Palette and font changes go through
|
|
85
|
+
`shadcn-svelte apply --preset <code> --only theme|font`; the preset code is produced by the project's own
|
|
86
|
+
`shadcn-svelte/preset` (`src/runtime/shadcn-preset.ts`), so the value lists never drift from what `apply`
|
|
87
|
+
accepts. The one vendored table is `STYLE_FONTS` (each style's designed font), guarded by a test against
|
|
88
|
+
the `shadcn-svelte` devDependency.
|
|
89
|
+
- `WriteResultRuntime.fetch` is the test seam for the registry, next to `executeCommand` for the spawns.
|
|
90
|
+
|
|
69
91
|
# Workflow for adding new patterns
|
|
70
92
|
|
|
71
93
|
- Develop the pattern in the `src/patterns` directory.
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { t as e } from "./errors-
|
|
1
|
+
import { t as e } from "./errors-D6gyegUK.js";
|
|
2
2
|
import { i as t } from "./util-Bk7aQQJR.js";
|
|
3
3
|
import { n, t as r } from "./logger-CQONztPm.js";
|
|
4
|
-
import { getMigrationFile as i, migrationDelay as a, withPocketbase as o } from "./pocketbase-
|
|
4
|
+
import { getMigrationFile as i, migrationDelay as a, withPocketbase as o } from "./pocketbase-fERkp8b8.js";
|
|
5
5
|
import { readFileSync as s } from "node:fs";
|
|
6
6
|
//#region src/runtime/collections.ts
|
|
7
7
|
function c(e) {
|
|
@@ -173,4 +173,4 @@ async function v(e, r) {
|
|
|
173
173
|
//#endregion
|
|
174
174
|
export { p as applyCollectionFieldsPatches, d as applyCollectionRulePatches, l as createCollectionIdempotent, v as createCollections, _ as dropCollections, g as planCollectionDrops };
|
|
175
175
|
|
|
176
|
-
//# sourceMappingURL=collections-
|
|
176
|
+
//# sourceMappingURL=collections-wIKcIKzY.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"collections-C1SaNdMd.js","names":[],"sources":["../../src/runtime/collections.ts"],"sourcesContent":["import { readFileSync } from \"node:fs\";\nimport type PocketBase from \"pocketbase\";\nimport type { CollectionModel } from \"pocketbase\";\nimport type {\n CollectionDropSpec,\n CollectionFieldSpec,\n CollectionFieldsPatch,\n CollectionRulesPatch,\n CollectionSpec,\n File,\n Options,\n} from \"../core/types\";\nimport { InvalidArgumentError } from \"../core/errors\";\nimport { getLogger, NOOP_LOGGER, type Logger } from \"../core/logger\";\nimport { languageFromPath } from \"../core/util\";\nimport { getMigrationFile, migrationDelay, withPocketbase } from \"./pocketbase\";\n\ninterface PocketBaseCollectionCreateError {\n response?: {\n data?: {\n name?: {\n code?: string;\n };\n };\n };\n message?: string;\n}\n\nfunction isCollectionAlreadyExistsError(\n error: PocketBaseCollectionCreateError,\n): boolean {\n if (\n error.response?.data?.name?.code === \"validation_collection_name_exists\"\n ) {\n return true;\n }\n\n const message = error.message?.toLowerCase() ?? \"\";\n return (\n message.includes(\"already exists\") || message.includes(\"must be unique\")\n );\n}\n\ntype CollectionCreateInput = Parameters<PocketBase[\"collections\"][\"create\"]>[0];\n\nexport interface CreateCollectionResult {\n collection: CollectionModel;\n created: boolean;\n}\n\n/**\n * Idempotent wrapper around `pb.collections.create`. If the collection already\n * exists, logs and returns the existing model with `created: false` so callers\n * can skip work tied to a fresh create (e.g. appending a newly-generated\n * migration file to the result).\n */\nexport async function createCollectionIdempotent(\n pb: PocketBase,\n spec: CollectionCreateInput,\n logger: Logger = NOOP_LOGGER,\n): Promise<CreateCollectionResult> {\n const name = (spec as { name: string }).name;\n try {\n const collection = await pb.collections.create(spec);\n return { collection, created: true };\n } catch (error) {\n if (\n !isCollectionAlreadyExistsError(error as PocketBaseCollectionCreateError)\n ) {\n throw error;\n }\n logger.info(`Collection \"${name}\" already exists, skipping`);\n const collection = await pb.collections.getOne(name);\n return { collection, created: false };\n }\n}\n\nfunction rulePayloadFromPatch(\n patch: CollectionRulesPatch,\n): Record<string, unknown> {\n const payload: Record<string, unknown> = {};\n if (patch.listRule !== undefined) payload.listRule = patch.listRule;\n if (patch.viewRule !== undefined) payload.viewRule = patch.viewRule;\n if (patch.createRule !== undefined) payload.createRule = patch.createRule;\n if (patch.updateRule !== undefined) payload.updateRule = patch.updateRule;\n if (patch.deleteRule !== undefined) payload.deleteRule = patch.deleteRule;\n return payload;\n}\n\n/**\n * Applies API rule updates in array order. Call after all referenced collections exist.\n * Collects migration files produced by each update when `options` is provided.\n */\nexport async function applyCollectionRulePatches(\n pb: {\n collections: {\n getFirstListItem: (filter: string) => Promise<{ id: string }>;\n update: (id: string, body: Record<string, unknown>) => Promise<unknown>;\n };\n },\n patches: CollectionRulesPatch[],\n options?: Options,\n logger: Logger = NOOP_LOGGER,\n): Promise<File[]> {\n const migrations: File[] = [];\n\n for (const patch of patches) {\n const escaped = patch.collectionName.replace(/'/g, \"''\");\n const col = await pb.collections.getFirstListItem(`name='${escaped}'`);\n logger.info(`Updating rules on collection \"${patch.collectionName}\"`);\n await pb.collections.update(col.id, rulePayloadFromPatch(patch));\n await migrationDelay();\n\n if (options) {\n const migrationFile = getMigrationFile(\n patch.collectionName,\n \"updated\",\n options,\n );\n if (migrationFile) {\n migrations.push({\n path: migrationFile,\n language: languageFromPath(migrationFile),\n content: readFileSync(migrationFile, \"utf8\"),\n status: \"success\",\n });\n }\n }\n }\n\n return migrations;\n}\n\nfunction applyFieldChanges(\n existing: CollectionFieldSpec[],\n patch: CollectionFieldsPatch,\n): CollectionFieldSpec[] {\n const fields = existing.map((field) => ({ ...field }));\n\n for (const change of patch.changes) {\n if (change.op === \"add\") {\n if (fields.some((f) => f.name === change.field.name)) {\n throw new InvalidArgumentError(\n `Field \"${change.field.name}\" already exists on collection \"${patch.collectionName}\"`,\n );\n }\n fields.push(change.field);\n continue;\n }\n if (change.op === \"remove\") {\n const index = fields.findIndex((f) => f.name === change.fieldName);\n if (index === -1) {\n throw new InvalidArgumentError(\n `Field \"${change.fieldName}\" does not exist on collection \"${patch.collectionName}\"`,\n );\n }\n fields.splice(index, 1);\n continue;\n }\n if (change.op === \"rename\") {\n const field = fields.find((f) => f.name === change.from);\n if (!field) {\n throw new InvalidArgumentError(\n `Field \"${change.from}\" does not exist on collection \"${patch.collectionName}\"`,\n );\n }\n if (fields.some((f) => f.name === change.to)) {\n throw new InvalidArgumentError(\n `Field \"${change.to}\" already exists on collection \"${patch.collectionName}\"`,\n );\n }\n field.name = change.to;\n continue;\n }\n }\n\n return fields;\n}\n\nexport async function applyCollectionFieldsPatches(\n pb: {\n collections: {\n getOne: (\n name: string,\n ) => Promise<{ id: string; fields: CollectionFieldSpec[] }>;\n update: (id: string, body: Record<string, unknown>) => Promise<unknown>;\n };\n },\n patches: CollectionFieldsPatch[],\n options: Options,\n logger: Logger = NOOP_LOGGER,\n): Promise<File[]> {\n const migrations: File[] = [];\n\n for (const patch of patches) {\n const collection = await pb.collections.getOne(patch.collectionName);\n const newFields = applyFieldChanges(collection.fields, patch);\n logger.info(`Updating fields on collection \"${patch.collectionName}\"`);\n await pb.collections.update(collection.id, { fields: newFields });\n await migrationDelay();\n\n const migrationFile = getMigrationFile(\n patch.collectionName,\n \"updated\",\n options,\n );\n if (!migrationFile) continue;\n\n migrations.push({\n path: migrationFile,\n language: languageFromPath(migrationFile),\n content: readFileSync(migrationFile, \"utf8\"),\n status: \"success\",\n });\n }\n\n return migrations;\n}\n\nexport interface DropCollectionResult {\n dropped: boolean;\n existed: boolean;\n}\n\n/**\n * Idempotent collection drop. Returns `{ existed: false, dropped: false }` if\n * the collection is already gone, matching the idempotency contract of\n * `createCollectionIdempotent`.\n */\nexport async function dropCollectionIdempotent(\n pb: PocketBase,\n name: string,\n logger: Logger = NOOP_LOGGER,\n): Promise<DropCollectionResult> {\n try {\n await pb.collections.getOne(name);\n } catch (error) {\n const status = (error as { status?: number }).status;\n if (status === 404) {\n logger.info(`Collection \"${name}\" does not exist, skipping drop`);\n return { dropped: false, existed: false };\n }\n throw error;\n }\n await pb.collections.delete(name);\n return { dropped: true, existed: true };\n}\n\nexport interface CollectionStats {\n exists: boolean;\n rowCount: number;\n}\n\nexport async function getCollectionStats(\n pb: PocketBase,\n name: string,\n): Promise<CollectionStats> {\n try {\n await pb.collections.getOne(name);\n } catch (error) {\n const status = (error as { status?: number }).status;\n if (status === 404) {\n return { exists: false, rowCount: 0 };\n }\n throw error;\n }\n\n try {\n const result = await pb\n .collection(name)\n .getList(1, 1, { skipTotal: false });\n return { exists: true, rowCount: result.totalItems };\n } catch {\n return { exists: true, rowCount: 0 };\n }\n}\n\n/**\n * Resolve the set of collections to drop, with current row counts. Missing\n * collections are included with `exists: false, rowCount: 0` so callers can\n * display the full reversal plan even when some collections were already gone.\n */\nexport async function planCollectionDrops(\n pb: PocketBase,\n names: string[],\n): Promise<CollectionDropSpec[]> {\n const plans: CollectionDropSpec[] = [];\n for (const name of names) {\n const stats = await getCollectionStats(pb, name);\n plans.push({ name, exists: stats.exists, rowCount: stats.rowCount });\n }\n return plans;\n}\n\n/**\n * Drop each of the given collections (skipping those that are already gone)\n * and collect the `_deleted_<name>.js` migration file PocketBase emits for\n * each successful drop. Symmetric to `createCollections`.\n */\nexport async function dropCollections(\n specs: CollectionDropSpec[],\n options: Options,\n): Promise<File[]> {\n if (specs.length === 0) {\n return [];\n }\n\n const migrations: File[] = [];\n const logger = getLogger(options);\n\n await withPocketbase(options.root, async (pb) => {\n for (const spec of specs) {\n logger.info(`Dropping collection \"${spec.name}\"`);\n const { dropped } = await dropCollectionIdempotent(pb, spec.name, logger);\n if (!dropped) continue;\n await migrationDelay();\n\n const migrationFile = getMigrationFile(spec.name, \"deleted\", options);\n if (!migrationFile) continue;\n\n migrations.push({\n path: migrationFile,\n language: languageFromPath(migrationFile),\n content: readFileSync(migrationFile, \"utf8\"),\n status: \"success\",\n });\n }\n });\n\n return migrations;\n}\n\nexport async function createCollections(\n collections: CollectionSpec[],\n options: Options,\n): Promise<File[]> {\n if (collections.length === 0) {\n return [];\n }\n\n const migrations: File[] = [];\n const logger = getLogger(options);\n\n await withPocketbase(options.root, async (pb) => {\n for (const collection of collections) {\n logger.info(`Creating collection \"${collection.name}\"`);\n const { created } = await createCollectionIdempotent(\n pb,\n collection,\n logger,\n );\n if (!created) continue;\n await migrationDelay();\n\n const migrationFile = getMigrationFile(\n collection.name,\n \"created\",\n options,\n );\n if (!migrationFile) {\n continue;\n }\n\n migrations.push({\n path: migrationFile,\n language: languageFromPath(migrationFile),\n content: readFileSync(migrationFile, \"utf8\"),\n status: \"success\",\n });\n }\n });\n\n return migrations;\n}\n"],"mappings":";;;;;;AA4BA,SAAS,EACP,GACS;CACT,IACE,EAAM,UAAU,MAAM,MAAM,SAAS,qCAErC,OAAO;CAGT,IAAM,IAAU,EAAM,SAAS,YAAY,KAAK;CAChD,OACE,EAAQ,SAAS,gBAAgB,KAAK,EAAQ,SAAS,gBAAgB;AAE3E;AAeA,eAAsB,EACpB,GACA,GACA,IAAiB,GACgB;CACjC,IAAM,IAAQ,EAA0B;CACxC,IAAI;EAEF,OAAO;GAAE,YAAA,MADgB,EAAG,YAAY,OAAO,CAAI;GAC9B,SAAS;EAAK;CACrC,SAAS,GAAO;EACd,IACE,CAAC,EAA+B,CAAwC,GAExE,MAAM;EAIR,OAFA,EAAO,KAAK,eAAe,EAAK,2BAA2B,GAEpD;GAAE,YAAA,MADgB,EAAG,YAAY,OAAO,CAAI;GAC9B,SAAS;EAAM;CACtC;AACF;AAEA,SAAS,EACP,GACyB;CACzB,IAAM,IAAmC,CAAC;CAM1C,OALI,EAAM,aAAa,KAAA,MAAW,EAAQ,WAAW,EAAM,WACvD,EAAM,aAAa,KAAA,MAAW,EAAQ,WAAW,EAAM,WACvD,EAAM,eAAe,KAAA,MAAW,EAAQ,aAAa,EAAM,aAC3D,EAAM,eAAe,KAAA,MAAW,EAAQ,aAAa,EAAM,aAC3D,EAAM,eAAe,KAAA,MAAW,EAAQ,aAAa,EAAM,aACxD;AACT;AAMA,eAAsB,EACpB,GAMA,GACA,GACA,IAAiB,GACA;CACjB,IAAM,IAAqB,CAAC;CAE5B,KAAK,IAAM,KAAS,GAAS;EAC3B,IAAM,IAAU,EAAM,eAAe,QAAQ,MAAM,IAAI,GACjD,IAAM,MAAM,EAAG,YAAY,iBAAiB,SAAS,EAAQ,EAAE;EAKrE,IAJA,EAAO,KAAK,iCAAiC,EAAM,eAAe,EAAE,GACpE,MAAM,EAAG,Y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ACT"}
|
|
1
|
+
{"version":3,"file":"collections-wIKcIKzY.js","names":[],"sources":["../../src/runtime/collections.ts"],"sourcesContent":["import { readFileSync } from \"node:fs\";\nimport type PocketBase from \"pocketbase\";\nimport type { CollectionModel } from \"pocketbase\";\nimport type {\n CollectionDropSpec,\n CollectionFieldSpec,\n CollectionFieldsPatch,\n CollectionRulesPatch,\n CollectionSpec,\n File,\n Options,\n} from \"../core/types\";\nimport { InvalidArgumentError } from \"../core/errors\";\nimport { getLogger, NOOP_LOGGER, type Logger } from \"../core/logger\";\nimport { languageFromPath } from \"../core/util\";\nimport { getMigrationFile, migrationDelay, withPocketbase } from \"./pocketbase\";\n\ninterface PocketBaseCollectionCreateError {\n response?: {\n data?: {\n name?: {\n code?: string;\n };\n };\n };\n message?: string;\n}\n\nfunction isCollectionAlreadyExistsError(\n error: PocketBaseCollectionCreateError,\n): boolean {\n if (\n error.response?.data?.name?.code === \"validation_collection_name_exists\"\n ) {\n return true;\n }\n\n const message = error.message?.toLowerCase() ?? \"\";\n return (\n message.includes(\"already exists\") || message.includes(\"must be unique\")\n );\n}\n\ntype CollectionCreateInput = Parameters<PocketBase[\"collections\"][\"create\"]>[0];\n\nexport interface CreateCollectionResult {\n collection: CollectionModel;\n created: boolean;\n}\n\n/**\n * Idempotent wrapper around `pb.collections.create`. If the collection already\n * exists, logs and returns the existing model with `created: false` so callers\n * can skip work tied to a fresh create (e.g. appending a newly-generated\n * migration file to the result).\n */\nexport async function createCollectionIdempotent(\n pb: PocketBase,\n spec: CollectionCreateInput,\n logger: Logger = NOOP_LOGGER,\n): Promise<CreateCollectionResult> {\n const name = (spec as { name: string }).name;\n try {\n const collection = await pb.collections.create(spec);\n return { collection, created: true };\n } catch (error) {\n if (\n !isCollectionAlreadyExistsError(error as PocketBaseCollectionCreateError)\n ) {\n throw error;\n }\n logger.info(`Collection \"${name}\" already exists, skipping`);\n const collection = await pb.collections.getOne(name);\n return { collection, created: false };\n }\n}\n\nfunction rulePayloadFromPatch(\n patch: CollectionRulesPatch,\n): Record<string, unknown> {\n const payload: Record<string, unknown> = {};\n if (patch.listRule !== undefined) payload.listRule = patch.listRule;\n if (patch.viewRule !== undefined) payload.viewRule = patch.viewRule;\n if (patch.createRule !== undefined) payload.createRule = patch.createRule;\n if (patch.updateRule !== undefined) payload.updateRule = patch.updateRule;\n if (patch.deleteRule !== undefined) payload.deleteRule = patch.deleteRule;\n return payload;\n}\n\n/**\n * Applies API rule updates in array order. Call after all referenced collections exist.\n * Collects migration files produced by each update when `options` is provided.\n */\nexport async function applyCollectionRulePatches(\n pb: {\n collections: {\n getFirstListItem: (filter: string) => Promise<{ id: string }>;\n update: (id: string, body: Record<string, unknown>) => Promise<unknown>;\n };\n },\n patches: CollectionRulesPatch[],\n options?: Options,\n logger: Logger = NOOP_LOGGER,\n): Promise<File[]> {\n const migrations: File[] = [];\n\n for (const patch of patches) {\n const escaped = patch.collectionName.replace(/'/g, \"''\");\n const col = await pb.collections.getFirstListItem(`name='${escaped}'`);\n logger.info(`Updating rules on collection \"${patch.collectionName}\"`);\n await pb.collections.update(col.id, rulePayloadFromPatch(patch));\n await migrationDelay();\n\n if (options) {\n const migrationFile = getMigrationFile(\n patch.collectionName,\n \"updated\",\n options,\n );\n if (migrationFile) {\n migrations.push({\n path: migrationFile,\n language: languageFromPath(migrationFile),\n content: readFileSync(migrationFile, \"utf8\"),\n status: \"success\",\n });\n }\n }\n }\n\n return migrations;\n}\n\nfunction applyFieldChanges(\n existing: CollectionFieldSpec[],\n patch: CollectionFieldsPatch,\n): CollectionFieldSpec[] {\n const fields = existing.map((field) => ({ ...field }));\n\n for (const change of patch.changes) {\n if (change.op === \"add\") {\n if (fields.some((f) => f.name === change.field.name)) {\n throw new InvalidArgumentError(\n `Field \"${change.field.name}\" already exists on collection \"${patch.collectionName}\"`,\n );\n }\n fields.push(change.field);\n continue;\n }\n if (change.op === \"remove\") {\n const index = fields.findIndex((f) => f.name === change.fieldName);\n if (index === -1) {\n throw new InvalidArgumentError(\n `Field \"${change.fieldName}\" does not exist on collection \"${patch.collectionName}\"`,\n );\n }\n fields.splice(index, 1);\n continue;\n }\n if (change.op === \"rename\") {\n const field = fields.find((f) => f.name === change.from);\n if (!field) {\n throw new InvalidArgumentError(\n `Field \"${change.from}\" does not exist on collection \"${patch.collectionName}\"`,\n );\n }\n if (fields.some((f) => f.name === change.to)) {\n throw new InvalidArgumentError(\n `Field \"${change.to}\" already exists on collection \"${patch.collectionName}\"`,\n );\n }\n field.name = change.to;\n continue;\n }\n }\n\n return fields;\n}\n\nexport async function applyCollectionFieldsPatches(\n pb: {\n collections: {\n getOne: (\n name: string,\n ) => Promise<{ id: string; fields: CollectionFieldSpec[] }>;\n update: (id: string, body: Record<string, unknown>) => Promise<unknown>;\n };\n },\n patches: CollectionFieldsPatch[],\n options: Options,\n logger: Logger = NOOP_LOGGER,\n): Promise<File[]> {\n const migrations: File[] = [];\n\n for (const patch of patches) {\n const collection = await pb.collections.getOne(patch.collectionName);\n const newFields = applyFieldChanges(collection.fields, patch);\n logger.info(`Updating fields on collection \"${patch.collectionName}\"`);\n await pb.collections.update(collection.id, { fields: newFields });\n await migrationDelay();\n\n const migrationFile = getMigrationFile(\n patch.collectionName,\n \"updated\",\n options,\n );\n if (!migrationFile) continue;\n\n migrations.push({\n path: migrationFile,\n language: languageFromPath(migrationFile),\n content: readFileSync(migrationFile, \"utf8\"),\n status: \"success\",\n });\n }\n\n return migrations;\n}\n\nexport interface DropCollectionResult {\n dropped: boolean;\n existed: boolean;\n}\n\n/**\n * Idempotent collection drop. Returns `{ existed: false, dropped: false }` if\n * the collection is already gone, matching the idempotency contract of\n * `createCollectionIdempotent`.\n */\nexport async function dropCollectionIdempotent(\n pb: PocketBase,\n name: string,\n logger: Logger = NOOP_LOGGER,\n): Promise<DropCollectionResult> {\n try {\n await pb.collections.getOne(name);\n } catch (error) {\n const status = (error as { status?: number }).status;\n if (status === 404) {\n logger.info(`Collection \"${name}\" does not exist, skipping drop`);\n return { dropped: false, existed: false };\n }\n throw error;\n }\n await pb.collections.delete(name);\n return { dropped: true, existed: true };\n}\n\nexport interface CollectionStats {\n exists: boolean;\n rowCount: number;\n}\n\nexport async function getCollectionStats(\n pb: PocketBase,\n name: string,\n): Promise<CollectionStats> {\n try {\n await pb.collections.getOne(name);\n } catch (error) {\n const status = (error as { status?: number }).status;\n if (status === 404) {\n return { exists: false, rowCount: 0 };\n }\n throw error;\n }\n\n try {\n const result = await pb\n .collection(name)\n .getList(1, 1, { skipTotal: false });\n return { exists: true, rowCount: result.totalItems };\n } catch {\n return { exists: true, rowCount: 0 };\n }\n}\n\n/**\n * Resolve the set of collections to drop, with current row counts. Missing\n * collections are included with `exists: false, rowCount: 0` so callers can\n * display the full reversal plan even when some collections were already gone.\n */\nexport async function planCollectionDrops(\n pb: PocketBase,\n names: string[],\n): Promise<CollectionDropSpec[]> {\n const plans: CollectionDropSpec[] = [];\n for (const name of names) {\n const stats = await getCollectionStats(pb, name);\n plans.push({ name, exists: stats.exists, rowCount: stats.rowCount });\n }\n return plans;\n}\n\n/**\n * Drop each of the given collections (skipping those that are already gone)\n * and collect the `_deleted_<name>.js` migration file PocketBase emits for\n * each successful drop. Symmetric to `createCollections`.\n */\nexport async function dropCollections(\n specs: CollectionDropSpec[],\n options: Options,\n): Promise<File[]> {\n if (specs.length === 0) {\n return [];\n }\n\n const migrations: File[] = [];\n const logger = getLogger(options);\n\n await withPocketbase(options.root, async (pb) => {\n for (const spec of specs) {\n logger.info(`Dropping collection \"${spec.name}\"`);\n const { dropped } = await dropCollectionIdempotent(pb, spec.name, logger);\n if (!dropped) continue;\n await migrationDelay();\n\n const migrationFile = getMigrationFile(spec.name, \"deleted\", options);\n if (!migrationFile) continue;\n\n migrations.push({\n path: migrationFile,\n language: languageFromPath(migrationFile),\n content: readFileSync(migrationFile, \"utf8\"),\n status: \"success\",\n });\n }\n });\n\n return migrations;\n}\n\nexport async function createCollections(\n collections: CollectionSpec[],\n options: Options,\n): Promise<File[]> {\n if (collections.length === 0) {\n return [];\n }\n\n const migrations: File[] = [];\n const logger = getLogger(options);\n\n await withPocketbase(options.root, async (pb) => {\n for (const collection of collections) {\n logger.info(`Creating collection \"${collection.name}\"`);\n const { created } = await createCollectionIdempotent(\n pb,\n collection,\n logger,\n );\n if (!created) continue;\n await migrationDelay();\n\n const migrationFile = getMigrationFile(\n collection.name,\n \"created\",\n options,\n );\n if (!migrationFile) {\n continue;\n }\n\n migrations.push({\n path: migrationFile,\n language: languageFromPath(migrationFile),\n content: readFileSync(migrationFile, \"utf8\"),\n status: \"success\",\n });\n }\n });\n\n return migrations;\n}\n"],"mappings":";;;;;;AA4BA,SAAS,EACP,GACS;CACT,IACE,EAAM,UAAU,MAAM,MAAM,SAAS,qCAErC,OAAO;CAGT,IAAM,IAAU,EAAM,SAAS,YAAY,KAAK;CAChD,OACE,EAAQ,SAAS,gBAAgB,KAAK,EAAQ,SAAS,gBAAgB;AAE3E;AAeA,eAAsB,EACpB,GACA,GACA,IAAiB,GACgB;CACjC,IAAM,IAAQ,EAA0B;CACxC,IAAI;EAEF,OAAO;GAAE,YAAA,MADgB,EAAG,YAAY,OAAO,CAAI;GAC9B,SAAS;EAAK;CACrC,SAAS,GAAO;EACd,IACE,CAAC,EAA+B,CAAwC,GAExE,MAAM;EAIR,OAFA,EAAO,KAAK,eAAe,EAAK,2BAA2B,GAEpD;GAAE,YAAA,MADgB,EAAG,YAAY,OAAO,CAAI;GAC9B,SAAS;EAAM;CACtC;AACF;AAEA,SAAS,EACP,GACyB;CACzB,IAAM,IAAmC,CAAC;CAM1C,OALI,EAAM,aAAa,KAAA,MAAW,EAAQ,WAAW,EAAM,WACvD,EAAM,aAAa,KAAA,MAAW,EAAQ,WAAW,EAAM,WACvD,EAAM,eAAe,KAAA,MAAW,EAAQ,aAAa,EAAM,aAC3D,EAAM,eAAe,KAAA,MAAW,EAAQ,aAAa,EAAM,aAC3D,EAAM,eAAe,KAAA,MAAW,EAAQ,aAAa,EAAM,aACxD;AACT;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AAK,EAAE;GACtD,IAAM,EAAE,eAAY,MAAM,EACxB,GACA,GACA,CACF;GACA,IAAI,CAAC,GAAS;GACd,MAAM,EAAe;GAErB,IAAM,IAAgB,EACpB,EAAW,MACX,WACA,CACF;GACK,KAIL,EAAW,KAAK;IACd,MAAM;IACN,UAAU,EAAiB,CAAa;IACxC,SAAS,EAAa,GAAe,MAAM;IAC3C,QAAQ;GACV,CAAC;EACH;CACF,CAAC,GAEM;AACT"}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
//#region src/core/constants.ts
|
|
2
|
+
var e = "data", t = "migrations", n = "(public)", r = "(app)", i = "@tanstack/table-core@^8.21.3", a = "formsnap@^2.0.1";
|
|
3
|
+
//#endregion
|
|
4
|
+
export { n as a, t as i, e as n, i as o, a as r, r as t };
|
|
5
|
+
|
|
6
|
+
//# sourceMappingURL=constants-PBCzh8eY.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"constants-PBCzh8eY.js","names":[],"sources":["../../src/core/constants.ts"],"sourcesContent":["export const DATA_DIR = \"data\";\nexport const MIGRATIONS_DIR = \"migrations\";\nexport const FIXTURE_PREFIX = \"vela\";\nexport const PUBLIC_DIR = \"(public)\";\nexport const APP_DIR = \"(app)\";\nexport const AUTHED_REDIRECT_PATH = \"/dashboard\";\nexport const API_URL = \"http://localhost:5173\";\n\n/**\n * The table helpers this repo ships (`data-table`, `column-header`,\n * `faceted-filter`, `pagination`) and the pages the scaffold generators emit\n * target TanStack Table v8; npm's `latest` tag now points at v9, whose types\n * are incompatible, so every install of it has to carry this range.\n */\nexport const TANSTACK_TABLE_CORE = \"@tanstack/table-core@^8.21.3\";\n\n/** `file-form` and `multiselect` build on formsnap's field context. */\nexport const FORMSNAP = \"formsnap@^2.0.1\";\n"],"mappings":";AAAA,IAAa,IAAW,QACX,IAAiB,cAEjB,IAAa,YACb,IAAU,SAUV,IAAsB,gCAGtB,IAAW"}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
//#region src/core/errors.ts
|
|
2
|
+
var e = class extends Error {
|
|
3
|
+
constructor(e) {
|
|
4
|
+
super(e), this.name = "InvalidArgumentError";
|
|
5
|
+
}
|
|
6
|
+
}, t = class extends Error {
|
|
7
|
+
constructor(e, t) {
|
|
8
|
+
super(`Could not read the shadcn-svelte registry at ${e}: ${t}`), this.name = "RegistryUnavailableError", this.url = e;
|
|
9
|
+
}
|
|
10
|
+
};
|
|
11
|
+
//#endregion
|
|
12
|
+
export { t as n, e as t };
|
|
13
|
+
|
|
14
|
+
//# sourceMappingURL=errors-D6gyegUK.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"errors-D6gyegUK.js","names":[],"sources":["../../src/core/errors.ts"],"sourcesContent":["export class InvalidArgumentError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"InvalidArgumentError\";\n }\n}\n\n/**\n * The shadcn-svelte registry could not be read (offline, a proxy, an outage).\n * Callers that only need the registry for a nicety, such as name checks or a\n * listing, catch this and degrade; callers that cannot proceed without it let\n * it surface as-is.\n */\nexport class RegistryUnavailableError extends Error {\n readonly url: string;\n\n constructor(url: string, reason: string) {\n super(`Could not read the shadcn-svelte registry at ${url}: ${reason}`);\n this.name = \"RegistryUnavailableError\";\n this.url = url;\n }\n}\n"],"mappings":";AAAA,IAAa,IAAb,cAA0C,MAAM;CAC9C,YAAY,GAAiB;EAE3B,AADA,MAAM,CAAO,GACb,KAAK,OAAO;CACd;AACF,GAQa,IAAb,cAA8C,MAAM;CAGlD,YAAY,GAAa,GAAgB;EAGvC,AAFA,MAAM,gDAAgD,EAAI,IAAI,GAAQ,GACtE,KAAK,OAAO,4BACZ,KAAK,MAAM;CACb;AACF"}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import e from "node:path";
|
|
2
|
+
import t from "prettier";
|
|
3
|
+
import n from "prettier-plugin-svelte";
|
|
4
|
+
//#region src/core/format-result.ts
|
|
5
|
+
function r(e) {
|
|
6
|
+
return e.language === "ts" || e.language === "js" || e.language === "svelte" || e.path.endsWith(".json");
|
|
7
|
+
}
|
|
8
|
+
async function i(n, r) {
|
|
9
|
+
if (r?.env !== "runtime" || !r.root) return {};
|
|
10
|
+
let i = e.isAbsolute(n.path) ? n.path : e.join(r.root, n.path), a = await t.resolveConfig(i, { editorconfig: !0 });
|
|
11
|
+
if (!a) return {};
|
|
12
|
+
let o = (a.plugins ?? []).filter((e) => e !== "prettier-plugin-svelte");
|
|
13
|
+
return {
|
|
14
|
+
...a,
|
|
15
|
+
plugins: o
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
async function a(e, r, a) {
|
|
19
|
+
try {
|
|
20
|
+
let o = await i({ path: r }, a);
|
|
21
|
+
return await t.format(e, {
|
|
22
|
+
...o,
|
|
23
|
+
filepath: r,
|
|
24
|
+
plugins: [...o.plugins ?? [], n]
|
|
25
|
+
});
|
|
26
|
+
} catch {
|
|
27
|
+
return e;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
async function o(e, t) {
|
|
31
|
+
return e.status !== "success" || !r(e) ? e : {
|
|
32
|
+
...e,
|
|
33
|
+
content: await a(e.content, e.path, t)
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
async function s(e, t) {
|
|
37
|
+
return Promise.all(e.map((e) => o(e, t)));
|
|
38
|
+
}
|
|
39
|
+
async function c(e, t) {
|
|
40
|
+
let [n, r] = await Promise.all([s(e.creates, t), s(e.modifies, t)]);
|
|
41
|
+
return {
|
|
42
|
+
...e,
|
|
43
|
+
creates: n,
|
|
44
|
+
modifies: r
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
//#endregion
|
|
48
|
+
export { a as n, c as t };
|
|
49
|
+
|
|
50
|
+
//# sourceMappingURL=format-result-BdAy5M8C.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"format-result-BdAy5M8C.js","names":[],"sources":["../../src/core/format-result.ts"],"sourcesContent":["import path from \"node:path\";\nimport prettier from \"prettier\";\nimport type { File, Options, Result } from \"./types\";\nimport sveltePlugin from \"prettier-plugin-svelte\";\n\n/** What the formatter needs to know about the run: where the project is, and whether it exists at all. */\nexport type FormatContext = Pick<Options, \"env\" | \"root\">;\n\nfunction canFormatFile(file: File): boolean {\n return (\n file.language === \"ts\" ||\n file.language === \"js\" ||\n file.language === \"svelte\" ||\n file.path.endsWith(\".json\")\n );\n}\n\n/**\n * The target project's own prettier settings (`.prettierrc`, `.editorconfig`,\n * `package.json#prettier`), so pattern output matches what `npm run lint`\n * expects there. Preview runs have no project and use prettier's defaults.\n *\n * The svelte plugin is always supplied as a module: a project's config names\n * it by string, which would resolve relative to this package instead.\n */\nasync function projectOptions(\n file: Pick<File, \"path\">,\n context?: FormatContext,\n): Promise<prettier.Options> {\n if (context?.env !== \"runtime\" || !context.root) return {};\n const target = path.isAbsolute(file.path)\n ? file.path\n : path.join(context.root, file.path);\n const resolved = await prettier.resolveConfig(target, { editorconfig: true });\n if (!resolved) return {};\n const plugins = (resolved.plugins ?? []).filter(\n (plugin) => plugin !== \"prettier-plugin-svelte\",\n );\n return { ...resolved, plugins };\n}\n\n/**\n * Formats one source text the way pattern output is formatted; the content\n * comes back unchanged when prettier cannot parse it. Also used for component\n * files that arrive on disk from `shadcn-svelte add` or the bundled\n * components, so `npm run lint` in the project stays clean after an install.\n */\nexport async function formatSource(\n content: string,\n filePath: string,\n context?: FormatContext,\n): Promise<string> {\n try {\n const options = await projectOptions({ path: filePath }, context);\n return await prettier.format(content, {\n ...options,\n filepath: filePath,\n plugins: [...(options.plugins ?? []), sveltePlugin],\n });\n } catch {\n return content;\n }\n}\n\nasync function formatFile(file: File, context?: FormatContext): Promise<File> {\n if (file.status !== \"success\" || !canFormatFile(file)) {\n return file;\n }\n return {\n ...file,\n content: await formatSource(file.content, file.path, context),\n };\n}\n\nasync function formatFiles(\n files: File[],\n context?: FormatContext,\n): Promise<File[]> {\n return Promise.all(files.map((file) => formatFile(file, context)));\n}\n\nexport async function formatResult(\n result: Result,\n context?: FormatContext,\n): Promise<Result> {\n const [creates, modifies] = await Promise.all([\n formatFiles(result.creates, context),\n formatFiles(result.modifies, context),\n ]);\n\n return {\n ...result,\n creates,\n modifies,\n };\n}\n"],"mappings":";;;;AAQA,SAAS,EAAc,GAAqB;CAC1C,OACE,EAAK,aAAa,QAClB,EAAK,aAAa,QAClB,EAAK,aAAa,YAClB,EAAK,KAAK,SAAS,OAAO;AAE9B;AAUA,eAAe,EACb,GACA,GAC2B;CAC3B,IAAI,GAAS,QAAQ,aAAa,CAAC,EAAQ,MAAM,OAAO,CAAC;CACzD,IAAM,IAAS,EAAK,WAAW,EAAK,IAAI,IACpC,EAAK,OACL,EAAK,KAAK,EAAQ,MAAM,EAAK,IAAI,GAC/B,IAAW,MAAM,EAAS,cAAc,GAAQ,EAAE,cAAc,GAAK,CAAC;CAC5E,IAAI,CAAC,GAAU,OAAO,CAAC;CACvB,IAAM,KAAW,EAAS,WAAW,CAAC,EAAA,CAAG,QACtC,MAAW,MAAW,wBACzB;CACA,OAAO;EAAE,GAAG;EAAU;CAAQ;AAChC;AAQA,eAAsB,EACpB,GACA,GACA,GACiB;CACjB,IAAI;EACF,IAAM,IAAU,MAAM,EAAe,EAAE,MAAM,EAAS,GAAG,CAAO;EAChE,OAAO,MAAM,EAAS,OAAO,GAAS;GACpC,GAAG;GACH,UAAU;GACV,SAAS,CAAC,GAAI,EAAQ,WAAW,CAAC,GAAI,CAAY;EACpD,CAAC;CACH,QAAQ;EACN,OAAO;CACT;AACF;AAEA,eAAe,EAAW,GAAY,GAAwC;CAI5E,OAHI,EAAK,WAAW,aAAa,CAAC,EAAc,CAAI,IAC3C,IAEF;EACL,GAAG;EACH,SAAS,MAAM,EAAa,EAAK,SAAS,EAAK,MAAM,CAAO;CAC9D;AACF;AAEA,eAAe,EACb,GACA,GACiB;CACjB,OAAO,QAAQ,IAAI,EAAM,KAAK,MAAS,EAAW,GAAM,CAAO,CAAC,CAAC;AACnE;AAEA,eAAsB,EACpB,GACA,GACiB;CACjB,IAAM,CAAC,GAAS,KAAY,MAAM,QAAQ,IAAI,CAC5C,EAAY,EAAO,SAAS,CAAO,GACnC,EAAY,EAAO,UAAU,CAAO,CACtC,CAAC;CAED,OAAO;EACL,GAAG;EACH;EACA;CACF;AACF"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { t as e } from "./errors-
|
|
1
|
+
import { t as e } from "./errors-D6gyegUK.js";
|
|
2
2
|
import { r as t } from "./util-Bk7aQQJR.js";
|
|
3
3
|
//#endregion
|
|
4
4
|
//#region src/patterns/enable/cms/generate.ts
|
|
@@ -87,4 +87,4 @@ async function l(e) {
|
|
|
87
87
|
//#endregion
|
|
88
88
|
export { s as n, l as t };
|
|
89
89
|
|
|
90
|
-
//# sourceMappingURL=generate-
|
|
90
|
+
//# sourceMappingURL=generate-vRi-W3rL.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"generate-
|
|
1
|
+
{"version":3,"file":"generate-vRi-W3rL.js","names":[],"sources":["../../src/patterns/enable/cms/generate.ts"],"sourcesContent":["import type { File, Options, Result } from \"../../../core/types\";\nimport { InvalidArgumentError } from \"../../../core/errors\";\nimport { filesFromGlob } from \"../../../core/util\";\n\n// The backend, for an app that hosts the CMS itself: the SQLite-backed HTTP\n// API and the two routes that mount it and serve uploads.\nconst backendRaw = import.meta.glob<string>(\"./creates-backend/**\", {\n query: \"?raw\",\n import: \"default\",\n eager: true,\n});\n\nconst BACKEND_PREFIX = \"./creates-backend/\";\n\n/** Where an app that hosts the backend itself mounts it. Also the admin bar's default. */\nexport const LOCAL_ENDPOINT = \"/api/cms\";\n\nexport const ENDPOINT_EXAMPLE =\n \"https://velastack.dev/v1/projects/<project>/cms\";\n\nexport interface CmsMode {\n /** What the read path and the admin bar talk to. */\n endpoint: string;\n /** Whether this app hosts the backend at `endpoint` itself. */\n local: boolean;\n}\n\n/** `--endpoint <url>` or `--endpoint=<url>`, for callers that hand flags through in argv. */\nfunction endpointFromArgv(argv: string[]): string | undefined {\n for (let i = 0; i < argv.length; i++) {\n const arg = argv[i];\n if (arg === \"--endpoint\") return argv[i + 1];\n if (arg.startsWith(\"--endpoint=\")) return arg.slice(\"--endpoint=\".length);\n }\n return undefined;\n}\n\n/**\n * Which of the two shapes to produce.\n *\n * An explicit `--endpoint` means a hosted CMS: the app only reads from it and\n * the admin bar signs in there, so no backend is installed. Without one, an\n * app with a server hosts the backend itself at `/api/cms`. A static site has\n * no server to host it, so there the endpoint is required.\n */\nexport function resolveMode(options: Options): CmsMode {\n const raw =\n typeof options.input.endpoint === \"string\"\n ? options.input.endpoint\n : endpointFromArgv(options.argv);\n const endpoint = raw?.trim().replace(/\\/+$/, \"\");\n\n if (endpoint) {\n if (!/^https?:\\/\\/\\S+$/.test(endpoint)) {\n throw new InvalidArgumentError(\n `--endpoint must be the absolute URL of a hosted CMS, like ${ENDPOINT_EXAMPLE}; got ${endpoint}`,\n );\n }\n return { endpoint, local: false };\n }\n\n if (!options.features.backend) {\n throw new InvalidArgumentError(\n \"This site has no server to host the CMS backend. \" +\n `Point it at a hosted CMS instead: vela enable cms --endpoint ${ENDPOINT_EXAMPLE}`,\n );\n }\n\n return { endpoint: LOCAL_ENDPOINT, local: true };\n}\n\n/** `$lib/cms.ts`: the read path, with the endpoint and locales bound. */\nfunction cmsLibSource(mode: CmsMode, i18n: boolean): string {\n const imports = [\n \"import { apiAdapter, createCms } from '@velastack/cms/server';\",\n ];\n if (i18n) imports.push(\"import { locales } from '$locales/data';\");\n\n const where = mode.local\n ? [\n \" * `/api/cms` is where `src/routes/api/cms/[...path]/+server.ts` mounts the\",\n \" * backend. It is also the admin bar's default, so the endpoint is named here\",\n \" * and nowhere else.\",\n ]\n : [\n \" * The CMS is hosted at this endpoint: the app reads published content from\",\n \" * it and the admin bar signs in there. The same URL is given to the `cms()`\",\n \" * plugin in vite.config.ts, which downloads media into the build.\",\n ];\n\n const which = i18n\n ? [\n \" * The locales are the site's own, from wuchale, so the CMS supports exactly\",\n \" * the languages the UI does; the first is the default that a missing\",\n \" * translation falls back to.\",\n ]\n : [\n \" * `locales` lists every locale the site supports; the first is the default\",\n \" * that a missing translation falls back to.\",\n ];\n\n return [\n ...imports,\n \"\",\n \"/**\",\n \" * The CMS read path, called from the root `+layout.server.ts`.\",\n \" *\",\n ...where,\n \" *\",\n ...which,\n \" */\",\n \"export const { load: loadCms, generateEntries } = createCms({\",\n `\\tadapter: apiAdapter({ endpoint: '${mode.endpoint}' }),`,\n `\\tlocales: ${i18n ? \"[...locales]\" : \"['en']\"}`,\n \"});\",\n \"\",\n ].join(\"\\n\");\n}\n\nexport async function generate(options: Options) {\n const mode = resolveMode(options);\n const creates: Record<string, File> = {};\n\n if (mode.local) {\n Object.assign(creates, filesFromGlob(backendRaw, BACKEND_PREFIX));\n }\n\n creates[\"src/lib/cms.ts\"] = {\n path: \"src/lib/cms.ts\",\n language: \"ts\",\n content: cmsLibSource(mode, options.features.i18n),\n status: \"success\",\n };\n\n const sortedCreates = Object.values(creates).sort((a, b) =>\n a.path.localeCompare(b.path),\n );\n\n // better-sqlite3 and marked are the package's optional peers, which npm\n // skips on install precisely because they are optional — so they have to be\n // named here. The backend needs the first; the root entry imports the\n // second statically, so <AdminBar /> cannot render without it.\n // 0.2.2 is the first release whose Vite plugin imports from the package\n // name rather than its own source tree; 0.2.1 breaks every consumer route.\n const packages = mode.local\n ? [\"@velastack/cms@^0.2.2\", \"better-sqlite3\", \"marked\"]\n : [\"@velastack/cms@^0.2.2\", \"marked\"];\n\n return {\n creates: sortedCreates,\n modifies: [],\n deletes: [],\n components: [],\n packages,\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n } satisfies Result;\n}\n"],"mappings":";;;;AAMA,IAAM,IAAa,uBAAA,OAAA;CAAA,2CAAA;CAAA,6DAAA;CAAA,8DAAA;AAIlB,CAAA,GAEK,IAAiB,sBAGV,IAAiB,YAEjB,IACX;AAUF,SAAS,EAAiB,GAAoC;C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UAAU;EACV,SAAS,EAAa,GAAM,EAAQ,SAAS,IAAI;EACjD,QAAQ;CACV,GAgBO;EACL,SAfoB,OAAO,OAAO,CAAO,CAAC,CAAC,MAAM,GAAG,MACpD,EAAE,KAAK,cAAc,EAAE,IAAI,CAclB;EACT,UAAU,CAAC;EACX,SAAS,CAAC;EACV,YAAY,CAAC;EACb,UATe,EAAK,QAClB;GAAC;GAAyB;GAAkB;EAAQ,IACpD,CAAC,yBAAyB,QAAQ;EAQpC,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAiB,CAAC;CACpB;AACF"}
|
|
@@ -2,7 +2,7 @@ import { t as e } from "./dedent-Gq6Krl4n.js";
|
|
|
2
2
|
import { n as t } from "./logger-CQONztPm.js";
|
|
3
3
|
import { modifyOutcomeToFile as n } from "./modify-file-PVKmDJHk.js";
|
|
4
4
|
import { a as r, n as i, o as a } from "./ts-morph-helpers-Bk82Z2n7.js";
|
|
5
|
-
import { getMigrationFile as o, migrationDelay as s, withPocketbase as c } from "./pocketbase-
|
|
5
|
+
import { getMigrationFile as o, migrationDelay as s, withPocketbase as c } from "./pocketbase-fERkp8b8.js";
|
|
6
6
|
import { modifySvelteConfigRemote as l } from "./modify-svelte-config-remote-D3eBzcZc.js";
|
|
7
7
|
import u from "node:path";
|
|
8
8
|
import d from "node:fs";
|
|
@@ -294,4 +294,4 @@ async function C(e) {
|
|
|
294
294
|
//#endregion
|
|
295
295
|
export { C as generate };
|
|
296
296
|
|
|
297
|
-
//# sourceMappingURL=generate.runtime-
|
|
297
|
+
//# sourceMappingURL=generate.runtime-4QI3es6J.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"generate.runtime-eojYS75G.js","names":[],"sources":["../../src/patterns/enable/auth-remote/modifies/+layout.server.ts","../../src/patterns/enable/auth-remote/modifies/root-layout.svelte.ts","../../src/patterns/enable/auth-remote/modifies/hooks.server.ts","../../src/patterns/enable/auth-remote/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { Project, SyntaxKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nexport function modifyLayoutServer(layoutPath: string): ModifyOutcome {\n if (!fs.existsSync(layoutPath)) {\n const snippet = dedent`\n\t\t\texport const load = async ({ locals }) => {\n\t\t\t\treturn { user: locals.pb.authStore.record };\n\t\t\t};\n\t\t`;\n\n fs.writeFileSync(layoutPath, snippet);\n return { status: \"success\", changed: true };\n }\n\n const originalSource = fs.readFileSync(layoutPath, \"utf8\");\n const project = new Project();\n const sourceFile = project.addSourceFileAtPath(layoutPath);\n\n // helper to add user property to an object literal if missing\n const addUserProp = (obj: import(\"ts-morph\").ObjectLiteralExpression) => {\n const hasUser = !!obj.getProperty(\"user\");\n if (!hasUser) {\n obj.addPropertyAssignment({\n name: \"user\",\n initializer: \"locals.pb.authStore.record\",\n });\n }\n };\n\n // find existing exported load (function or const with arrow)\n let loadArrow: import(\"ts-morph\").ArrowFunction | undefined;\n let loadFn:\n | import(\"ts-morph\").FunctionDeclaration\n | import(\"ts-morph\").FunctionExpression\n | undefined;\n\n const varDecl = sourceFile.getVariableDeclaration(\"load\");\n if (varDecl) {\n const vs = varDecl.getFirstAncestorByKind(SyntaxKind.VariableStatement);\n const isExported = !!vs?.hasExportKeyword();\n if (isExported) {\n const directArrow = varDecl.getInitializerIfKind(\n SyntaxKind.ArrowFunction,\n );\n if (directArrow) {\n loadArrow = directArrow;\n } else {\n const init = varDecl.getInitializer();\n if (init) {\n const innerArrow = init.getFirstDescendantByKind(\n SyntaxKind.ArrowFunction,\n );\n if (innerArrow) {\n loadArrow = innerArrow;\n } else {\n const innerFnExpr = init.getFirstDescendantByKind(\n SyntaxKind.FunctionExpression,\n );\n if (innerFnExpr) {\n loadFn = innerFnExpr;\n }\n }\n }\n }\n }\n }\n\n if (!loadArrow) {\n const maybeFn = sourceFile.getFunction(\"load\");\n if (maybeFn && maybeFn.isExported()) {\n loadFn = maybeFn;\n }\n }\n\n // if no load found, create one\n if (!loadArrow && !loadFn) {\n sourceFile.addFunction({\n isExported: true,\n isAsync: true,\n name: \"load\",\n parameters: [{ name: \"{ locals }\" }],\n statements: `return { user: locals.pb.authStore.record };`,\n });\n sourceFile.formatText();\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n }\n\n // normalize function-like to a single handle\n const fnLike:\n | import(\"ts-morph\").ArrowFunction\n | import(\"ts-morph\").FunctionDeclaration\n | import(\"ts-morph\").FunctionExpression = (loadArrow ?? loadFn!) as any;\n\n // ensure first parameter destructures locals, preserving existing information\n const params = fnLike.getParameters();\n if (params.length === 0) {\n fnLike.insertParameter(0, { name: \"{ locals }\" });\n } else {\n const first = params[0];\n const original = first.getStructure();\n const nameNode = first.getNameNode();\n if (nameNode.getKind() === SyntaxKind.ObjectBindingPattern) {\n const obp = nameNode as import(\"ts-morph\").ObjectBindingPattern;\n const hasLocals = obp\n .getElements()\n .some((el) => el.getName() === \"locals\");\n if (!hasLocals) {\n const parts = obp\n .getElements()\n .map((el) => el.getText())\n .filter(Boolean);\n const tail = parts.length > 0 ? \", \" + parts.join(\", \") : \"\";\n first.set({\n name: `{ locals${tail} }`,\n type: original.type,\n initializer: (original as any).initializer,\n });\n }\n } else {\n const currentName = first.getName();\n if (currentName !== \"locals\") {\n first.set({\n name: `{ locals, ...${currentName} }`,\n type: original.type,\n initializer: (original as any).initializer,\n });\n }\n }\n }\n\n // add user to returned object literals without altering other properties\n if (loadArrow) {\n const body = loadArrow.getBody();\n if (body.getKind() === SyntaxKind.Block) {\n const returns = body.getDescendantsOfKind(SyntaxKind.ReturnStatement);\n returns.forEach((ret) => {\n const expr = ret.getExpression();\n if (!expr) return;\n if (expr.getKind() === SyntaxKind.ObjectLiteralExpression) {\n addUserProp(expr as import(\"ts-morph\").ObjectLiteralExpression);\n } else if (expr.getKind() === SyntaxKind.ParenthesizedExpression) {\n const inner = (\n expr as import(\"ts-morph\").ParenthesizedExpression\n ).getExpression();\n if (inner.getKind() === SyntaxKind.ObjectLiteralExpression) {\n addUserProp(inner as import(\"ts-morph\").ObjectLiteralExpression);\n }\n }\n });\n } else {\n // concise body\n const bodyExpr = body as import(\"ts-morph\").Expression;\n if (bodyExpr.getKind() === SyntaxKind.ParenthesizedExpression) {\n const inner = (\n bodyExpr as import(\"ts-morph\").ParenthesizedExpression\n ).getExpression();\n if (inner.getKind() === SyntaxKind.ObjectLiteralExpression) {\n addUserProp(inner as import(\"ts-morph\").ObjectLiteralExpression);\n }\n } else if (bodyExpr.getKind() === SyntaxKind.ObjectLiteralExpression) {\n addUserProp(bodyExpr as import(\"ts-morph\").ObjectLiteralExpression);\n }\n }\n } else if (loadFn) {\n const body = loadFn.getBody();\n if (body) {\n const returns = body.getDescendantsOfKind(SyntaxKind.ReturnStatement);\n returns.forEach((ret) => {\n const expr = ret.getExpression();\n if (!expr) return;\n if (expr.getKind() === SyntaxKind.ObjectLiteralExpression) {\n addUserProp(expr as import(\"ts-morph\").ObjectLiteralExpression);\n } else if (expr.getKind() === SyntaxKind.ParenthesizedExpression) {\n const inner = (\n expr as import(\"ts-morph\").ParenthesizedExpression\n ).getExpression();\n if (inner.getKind() === SyntaxKind.ObjectLiteralExpression) {\n addUserProp(inner as import(\"ts-morph\").ObjectLiteralExpression);\n }\n }\n });\n }\n }\n\n sourceFile.formatText();\n sourceFile.saveSync();\n return {\n status: \"success\",\n changed: sourceFile.getFullText() !== originalSource,\n };\n}\n","import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport {\n ensureImports,\n withInMemoryScript,\n} from \"../../../../runtime/ts-morph-helpers\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst AUTH_MENU_NAVBAR_ITEM = `\n\t\t<Navbar.Item\n\t\t\tclass=\"flex flex-col md:flex-row items-center space-y-2 md:space-y-0 md:space-x-4\"\n\t\t>\n\t\t\t<AuthMenu.Root>\n\t\t\t\t{#snippet user()}\n\t\t\t\t\t<AuthMenu.Trigger>\n\t\t\t\t\t\t<Avatar.Root>\n\t\t\t\t\t\t\t{#if data.user?.avatar}\n\t\t\t\t\t\t\t\t<Avatar.Image\n\t\t\t\t\t\t\t\t\tsrc=\"/api/files/users/{data.user?.id}/{data.user?.avatar}\"\n\t\t\t\t\t\t\t\t\talt={data.user?.email}\n\t\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t\t{/if}\n\t\t\t\t\t\t\t<Avatar.Fallback>\n\t\t\t\t\t\t\t\t{data.user?.email?.charAt(0).toUpperCase()}\n\t\t\t\t\t\t\t</Avatar.Fallback>\n\t\t\t\t\t\t</Avatar.Root>\n\t\t\t\t\t</AuthMenu.Trigger>\n\n\t\t\t\t\t<AuthMenu.Content align=\"end\">\n\t\t\t\t\t\t<AuthMenu.Item href=\"/dashboard\">Dashboard</AuthMenu.Item>\n\t\t\t\t\t\t<AuthMenu.Group>\n\t\t\t\t\t\t\t<AuthMenu.Item href=\"/settings\">Settings</AuthMenu.Item>\n\t\t\t\t\t\t\t<AuthMenu.Item>\n\t\t\t\t\t\t\t\t<form action=\"/logout\" method=\"post\">\n\t\t\t\t\t\t\t\t\t<button type=\"submit\" class=\"contents\">Logout</button>\n\t\t\t\t\t\t\t\t</form>\n\t\t\t\t\t\t\t</AuthMenu.Item>\n\t\t\t\t\t\t</AuthMenu.Group>\n\t\t\t\t\t</AuthMenu.Content>\n\t\t\t\t{/snippet}\n\n\t\t\t\t{#snippet guest()}\n\t\t\t\t\t<Button\n\t\t\t\t\t\tclass=\"w-full justify-start md:justify-center md:w-auto\"\n\t\t\t\t\t\tvariant=\"ghost\"\n\t\t\t\t\t\thref=\"/login\">Login</Button\n\t\t\t\t\t>\n\t\t\t\t\t<Button\n\t\t\t\t\t\tclass=\"w-full justify-start md:justify-center md:w-auto\"\n\t\t\t\t\t\tvariant=\"outline\"\n\t\t\t\t\t\thref=\"/signup\">Sign up</Button\n\t\t\t\t\t>\n\t\t\t\t{/snippet}\n\t\t\t</AuthMenu.Root>\n\t\t</Navbar.Item>\n\t`;\n\nconst IMPORT_SNIPPET = dedent`\n import * as AuthMenu from '$lib/components/ui/auth-menu';\n import * as Avatar from '$lib/components/ui/avatar';\n`;\n\nconst FAILURE_HINT = [\n \"Add the auth menu inside your <Navbar.List> in the root layout.\",\n \"\",\n \"Imports to add to the <script> tag:\",\n \"\",\n IMPORT_SNIPPET,\n \"\",\n \"Markup to add inside <Navbar.List>:\",\n AUTH_MENU_NAVBAR_ITEM,\n].join(\"\\n\");\n\nconst NOT_FOUND_HINT = [\n \"Create a root layout that includes an auth menu inside <Navbar.List>.\",\n \"\",\n \"Imports for the <script> tag:\",\n \"\",\n IMPORT_SNIPPET,\n \"\",\n \"Markup inside <Navbar.List>:\",\n AUTH_MENU_NAVBAR_ITEM,\n].join(\"\\n\");\n\nexport function modifyRootLayoutSvelte(layoutPath: string): ModifyOutcome {\n if (!fs.existsSync(layoutPath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const file = SvelteFile.fromPath(layoutPath);\n if (!file.hasElement(\"Navbar.List\")) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n if (file.hasElement(\"AuthMenu.Root\")) {\n return { status: \"success\", changed: false };\n }\n\n file.modifyScript((source) => {\n const { source: out } = withInMemoryScript(source, (sf) => {\n ensureImports(sf, [\n {\n namespaceImport: \"AuthMenu\",\n moduleSpecifier: \"$lib/components/ui/auth-menu\",\n },\n {\n namespaceImport: \"Avatar\",\n moduleSpecifier: \"$lib/components/ui/avatar\",\n },\n ]);\n });\n return out;\n });\n\n file.insertBeforeClosingTag(\"Navbar.List\", AUTH_MENU_NAVBAR_ITEM);\n file.writeTo(layoutPath);\n return { status: \"success\", changed: file.hasChanged() };\n}\n","import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { Project, SyntaxKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst FAILURE_HINT = dedent`\n Configure handlePocketbase() with the auth option in hooks.server.ts:\n\n handlePocketbase({\n auth: { protectedRoutes: ['/(app)'] },\n });\n`;\n\nconst NOT_FOUND_HINT = dedent`\n Create src/hooks.server.ts with handlePocketbase:\n\n import { handlePocketbase } from '@velastack/pocketbase';\n\n export const handle = handlePocketbase({\n auth: { protectedRoutes: ['/(app)'] },\n });\n`;\n\nexport function modifyHooksServer(hooksServerPath: string): ModifyOutcome {\n if (!fs.existsSync(hooksServerPath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const originalSource = fs.readFileSync(hooksServerPath, \"utf8\");\n const project = new Project();\n const sourceFile = project.addSourceFileAtPath(hooksServerPath);\n\n // Find the handlePocketbase(...) call\n const callExpr = sourceFile\n .getDescendantsOfKind(SyntaxKind.CallExpression)\n .find((ce) => ce.getExpression().getText() === \"handlePocketbase\");\n\n if (!callExpr) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n const args = callExpr.getArguments();\n if (args.length === 0) {\n callExpr.addArgument(`{ auth: { protectedRoutes: ['/(app)'] } }`);\n sourceFile.formatText();\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n }\n\n const firstArg = args[0];\n if (firstArg.getKind() !== SyntaxKind.ObjectLiteralExpression) {\n callExpr.insertArgument(0, `{ auth: { protectedRoutes: ['/(app)'] } }`);\n sourceFile.formatText();\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n }\n\n const optionsObj = firstArg.asKindOrThrow(SyntaxKind.ObjectLiteralExpression);\n\n // Ensure auth property exists\n const authProp = optionsObj.getProperty(\"auth\");\n if (!authProp) {\n optionsObj.addPropertyAssignment({\n name: \"auth\",\n initializer: `{ protectedRoutes: ['/(app)'] }`,\n });\n sourceFile.formatText();\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n }\n\n // If auth exists, ensure protectedRoutes includes '/(app)'\n if (authProp.getKind() === SyntaxKind.PropertyAssignment) {\n const authInit = (\n authProp as import(\"ts-morph\").PropertyAssignment\n ).getInitializer();\n if (authInit && authInit.getKind() === SyntaxKind.ObjectLiteralExpression) {\n const authObj = authInit as import(\"ts-morph\").ObjectLiteralExpression;\n const prProp = authObj.getProperty(\"protectedRoutes\");\n if (!prProp) {\n authObj.addPropertyAssignment({\n name: \"protectedRoutes\",\n initializer: `['/(app)']`,\n });\n } else if (prProp.getKind() === SyntaxKind.PropertyAssignment) {\n const prInit = (\n prProp as import(\"ts-morph\").PropertyAssignment\n ).getInitializer();\n if (prInit && prInit.getKind() === SyntaxKind.ArrayLiteralExpression) {\n const arr = prInit as import(\"ts-morph\").ArrayLiteralExpression;\n const hasApp = arr\n .getElements()\n .some((el) => el.getText().replace(/['\"`]/g, \"\") === \"/(app)\");\n if (!hasApp) {\n arr.addElement(`'/(app)'`);\n }\n } else {\n (prProp as import(\"ts-morph\").PropertyAssignment).setInitializer(\n `['/(app)']`,\n );\n }\n }\n }\n }\n\n sourceFile.formatText();\n sourceFile.saveSync();\n return {\n status: \"success\",\n changed: sourceFile.getFullText() !== originalSource,\n };\n}\n","import path from \"node:path\";\nimport fs from \"node:fs\";\nimport { Options, Result, File } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport {\n getMigrationFile,\n migrationDelay,\n withPocketbase,\n} from \"../../../runtime/pocketbase\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { modifySvelteConfigRemote } from \"../../../runtime/modify-svelte-config-remote\";\n\nimport { modifyLayoutServer } from \"./modifies/+layout.server\";\nimport { modifyRootLayoutSvelte } from \"./modifies/root-layout.svelte\";\nimport { modifyHooksServer } from \"./modifies/hooks.server\";\n\nexport async function generate(options: Options) {\n const { input } = options;\n const logger = getLogger(options);\n\n let creates: File[] = [];\n\n // Update PocketBase\n await withPocketbase(options.root, async (pb) => {\n logger.info(\"Updating PocketBase mail settings\");\n await pb.settings.update({\n meta: {\n senderName: input.senderName,\n senderAddress: input.senderAddress,\n },\n });\n await migrationDelay();\n\n const userCollection = await pb.collections.getOne(\"users\");\n\n if (!userCollection) {\n throw new Error(\"Users collection not found\");\n }\n\n const verificationTemplate =\n userCollection.verificationTemplate.body.replace(\n \"{APP_URL}/_/#/auth/confirm-verification/{TOKEN}\",\n \"{APP_URL}/confirm-verification/{TOKEN}\",\n );\n const resetPasswordTemplate =\n userCollection.resetPasswordTemplate.body.replace(\n \"{APP_URL}/_/#/auth/confirm-reset/{TOKEN}\",\n \"{APP_URL}/confirm-reset/{TOKEN}\",\n );\n const confirmEmailChangeTemplate =\n userCollection.confirmEmailChangeTemplate.body.replace(\n \"{APP_URL}/_/#/auth/confirm-email-change/{TOKEN}\",\n \"{APP_URL}/confirm-email-change/{TOKEN}\",\n );\n\n logger.info(\"Locking down users collection rules and email templates\");\n // Update user auth rules to lock down access to the user's own account\n await pb.collections.update(\"users\", {\n listRule: \"@request.auth.id = id\",\n viewRule: \"@request.auth.id = id\",\n createRule: \"@request.auth.id = id\",\n updateRule: \"@request.auth.id = id\",\n deleteRule: \"@request.auth.id = id\",\n\n // Update email templates to VelaStack auth urls\n verificationTemplate: {\n body: verificationTemplate,\n },\n resetPasswordTemplate: {\n body: resetPasswordTemplate,\n },\n confirmEmailChangeTemplate: {\n body: confirmEmailChangeTemplate,\n },\n });\n await migrationDelay();\n\n const migrationFile = getMigrationFile(\"users\", \"updated\", options);\n if (migrationFile) {\n creates.push({\n path: migrationFile,\n language: \"ts\",\n content: fs.readFileSync(migrationFile, \"utf8\"),\n status: \"success\",\n });\n }\n });\n\n // Modify files\n const modifies: File[] = [];\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n logger.info(\"Modifying +layout.server.ts\");\n const layoutServerFile = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"+layout.server.ts\",\n );\n pushResult(\n modifyOutcomeToFile(layoutServerFile, modifyLayoutServer(layoutServerFile)),\n );\n\n logger.info(\"Modifying root layout\");\n // TODO: make this more robust by searching for Navbar.Root > Navbar.List\n // src/routes/(public)/root-layout.svelte is what vela creates by default\n const layoutCandidates = [\n path.join(options.root, \"src\", \"routes\", \"(public)\", \"root-layout.svelte\"),\n path.join(options.root, \"src\", \"routes\", \"root-layout.svelte\"),\n path.join(options.root, \"src\", \"routes\", \"(public)\", \"+layout.svelte\"),\n path.join(options.root, \"src\", \"routes\", \"+layout.svelte\"),\n ];\n const layoutFile =\n layoutCandidates.find((p) => fs.existsSync(p)) ?? layoutCandidates[0];\n pushResult(\n modifyOutcomeToFile(layoutFile, modifyRootLayoutSvelte(layoutFile)),\n );\n\n logger.info(\"Modifying hooks.server.ts\");\n const hooksServerFile = path.join(options.root, \"src\", \"hooks.server.ts\");\n pushResult(\n modifyOutcomeToFile(hooksServerFile, modifyHooksServer(hooksServerFile)),\n );\n\n logger.info(\"Modifying config for remote functions\");\n const remote = modifySvelteConfigRemote(options.root);\n pushResult(modifyOutcomeToFile(remote.filePath, remote.outcome));\n\n return {\n creates: [],\n modifies,\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n } satisfies Result;\n}\n"],"mappings":";;;;;;;;;;AAKA,SAAgB,EAAmB,GAAmC;CACpE,IAAI,CAAC,EAAG,WAAW,CAAU,GAAG;EAC9B,IAAM,IAAU,CAAM;;;;;EAOtB,OADA,EAAG,cAAc,GAAY,CAAO,GAC7B;GAAE,QAAQ;GAAW,SAAS;EAAK;CAC5C;CAEA,IAAM,IAAiB,EAAG,aAAa,GAAY,MAAM,GAEnD,IAAa,IADC,EACD,CAAA,CAAQ,oBAAoB,CAAU,GAGnD,KAAe,MAAoD;EAEvE,AADkB,EAAI,YAAY,MAAM,KAEtC,EAAI,sBAAsB;GACxB,MAAM;GACN,aAAa;EACf,CAAC;CAEL,GAGI,GACA,GAKE,IAAU,EAAW,uBAAuB,MAAM;CACxD,IAAI,KACS,EAAQ,uBAAuB,EAAW,iBAChC,CAAA,EAAI,iBAAiB,GAC1B;EACd,IAAM,IAAc,EAAQ,qBAC1B,EAAW,aACb;EACA,IAAI,GACF,IAAY;OACP;GACL,IAAM,IAAO,EAAQ,eAA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Y,oBAAoB;EACzE,EAAK,KAAK,EAAQ,MAAM,OAAO,UAAU,oBAAoB;EAC7D,EAAK,KAAK,EAAQ,MAAM,OAAO,UAAU,YAAY,gBAAgB;EACrE,EAAK,KAAK,EAAQ,MAAM,OAAO,UAAU,gBAAgB;CAC3D,GACM,IACJ,EAAiB,MAAM,MAAM,EAAG,WAAW,CAAC,CAAC,KAAK,EAAiB;CAKrE,AAJA,EACE,EAAoB,GAAY,EAAuB,CAAU,CAAC,CACpE,GAEA,EAAO,KAAK,2BAA2B;CACvC,IAAM,IAAkB,EAAK,KAAK,EAAQ,MAAM,OAAO,iBAAiB;CAKxE,AAJA,EACE,EAAoB,GAAiB,EAAkB,CAAe,CAAC,CACzE,GAEA,EAAO,KAAK,uCAAuC;CACnD,IAAM,IAAS,EAAyB,EAAQ,IAAI;CAGpD,OAFA,EAAW,EAAoB,EAAO,UAAU,EAAO,OAAO,CAAC,GAExD;EACL,SAAS,CAAC;EACV;EACA,SAAS,CAAC;EACV,YAAY,CAAC;EACb,UAAU,CAAC;EACX,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAiB,CAAC;CACpB;AACF"}
|
|
1
|
+
{"version":3,"file":"generate.runtime-4QI3es6J.js","names":[],"sources":["../../src/patterns/enable/auth-remote/modifies/+layout.server.ts","../../src/patterns/enable/auth-remote/modifies/root-layout.svelte.ts","../../src/patterns/enable/auth-remote/modifies/hooks.server.ts","../../src/patterns/enable/auth-remote/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { Project, SyntaxKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nexport function modifyLayoutServer(layoutPath: string): ModifyOutcome {\n if (!fs.existsSync(layoutPath)) {\n const snippet = dedent`\n\t\t\texport const load = async ({ locals }) => {\n\t\t\t\treturn { user: locals.pb.authStore.record };\n\t\t\t};\n\t\t`;\n\n fs.writeFileSync(layoutPath, snippet);\n return { status: \"success\", changed: true };\n }\n\n const originalSource = fs.readFileSync(layoutPath, \"utf8\");\n const project = new Project();\n const sourceFile = project.addSourceFileAtPath(layoutPath);\n\n // helper to add user property to an object literal if missing\n const addUserProp = (obj: import(\"ts-morph\").ObjectLiteralExpression) => {\n const hasUser = !!obj.getProperty(\"user\");\n if (!hasUser) {\n obj.addPropertyAssignment({\n name: \"user\",\n initializer: \"locals.pb.authStore.record\",\n });\n }\n };\n\n // find existing exported load (function or const with arrow)\n let loadArrow: import(\"ts-morph\").ArrowFunction | undefined;\n let loadFn:\n | import(\"ts-morph\").FunctionDeclaration\n | import(\"ts-morph\").FunctionExpression\n | undefined;\n\n const varDecl = sourceFile.getVariableDeclaration(\"load\");\n if (varDecl) {\n const vs = varDecl.getFirstAncestorByKind(SyntaxKind.VariableStatement);\n const isExported = !!vs?.hasExportKeyword();\n if (isExported) {\n const directArrow = varDecl.getInitializerIfKind(\n SyntaxKind.ArrowFunction,\n );\n if (directArrow) {\n loadArrow = directArrow;\n } else {\n const init = varDecl.getInitializer();\n if (init) {\n const innerArrow = init.getFirstDescendantByKind(\n SyntaxKind.ArrowFunction,\n );\n if (innerArrow) {\n loadArrow = innerArrow;\n } else {\n const innerFnExpr = init.getFirstDescendantByKind(\n SyntaxKind.FunctionExpression,\n );\n if (innerFnExpr) {\n loadFn = innerFnExpr;\n }\n }\n }\n }\n }\n }\n\n if (!loadArrow) {\n const maybeFn = sourceFile.getFunction(\"load\");\n if (maybeFn && maybeFn.isExported()) {\n loadFn = maybeFn;\n }\n }\n\n // if no load found, create one\n if (!loadArrow && !loadFn) {\n sourceFile.addFunction({\n isExported: true,\n isAsync: true,\n name: \"load\",\n parameters: [{ name: \"{ locals }\" }],\n statements: `return { user: locals.pb.authStore.record };`,\n });\n sourceFile.formatText();\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n }\n\n // normalize function-like to a single handle\n const fnLike:\n | import(\"ts-morph\").ArrowFunction\n | import(\"ts-morph\").FunctionDeclaration\n | import(\"ts-morph\").FunctionExpression = (loadArrow ?? loadFn!) as any;\n\n // ensure first parameter destructures locals, preserving existing information\n const params = fnLike.getParameters();\n if (params.length === 0) {\n fnLike.insertParameter(0, { name: \"{ locals }\" });\n } else {\n const first = params[0];\n const original = first.getStructure();\n const nameNode = first.getNameNode();\n if (nameNode.getKind() === SyntaxKind.ObjectBindingPattern) {\n const obp = nameNode as import(\"ts-morph\").ObjectBindingPattern;\n const hasLocals = obp\n .getElements()\n .some((el) => el.getName() === \"locals\");\n if (!hasLocals) {\n const parts = obp\n .getElements()\n .map((el) => el.getText())\n .filter(Boolean);\n const tail = parts.length > 0 ? \", \" + parts.join(\", \") : \"\";\n first.set({\n name: `{ locals${tail} }`,\n type: original.type,\n initializer: (original as any).initializer,\n });\n }\n } else {\n const currentName = first.getName();\n if (currentName !== \"locals\") {\n first.set({\n name: `{ locals, ...${currentName} }`,\n type: original.type,\n initializer: (original as any).initializer,\n });\n }\n }\n }\n\n // add user to returned object literals without altering other properties\n if (loadArrow) {\n const body = loadArrow.getBody();\n if (body.getKind() === SyntaxKind.Block) {\n const returns = body.getDescendantsOfKind(SyntaxKind.ReturnStatement);\n returns.forEach((ret) => {\n const expr = ret.getExpression();\n if (!expr) return;\n if (expr.getKind() === SyntaxKind.ObjectLiteralExpression) {\n addUserProp(expr as import(\"ts-morph\").ObjectLiteralExpression);\n } else if (expr.getKind() === SyntaxKind.ParenthesizedExpression) {\n const inner = (\n expr as import(\"ts-morph\").ParenthesizedExpression\n ).getExpression();\n if (inner.getKind() === SyntaxKind.ObjectLiteralExpression) {\n addUserProp(inner as import(\"ts-morph\").ObjectLiteralExpression);\n }\n }\n });\n } else {\n // concise body\n const bodyExpr = body as import(\"ts-morph\").Expression;\n if (bodyExpr.getKind() === SyntaxKind.ParenthesizedExpression) {\n const inner = (\n bodyExpr as import(\"ts-morph\").ParenthesizedExpression\n ).getExpression();\n if (inner.getKind() === SyntaxKind.ObjectLiteralExpression) {\n addUserProp(inner as import(\"ts-morph\").ObjectLiteralExpression);\n }\n } else if (bodyExpr.getKind() === SyntaxKind.ObjectLiteralExpression) {\n addUserProp(bodyExpr as import(\"ts-morph\").ObjectLiteralExpression);\n }\n }\n } else if (loadFn) {\n const body = loadFn.getBody();\n if (body) {\n const returns = body.getDescendantsOfKind(SyntaxKind.ReturnStatement);\n returns.forEach((ret) => {\n const expr = ret.getExpression();\n if (!expr) return;\n if (expr.getKind() === SyntaxKind.ObjectLiteralExpression) {\n addUserProp(expr as import(\"ts-morph\").ObjectLiteralExpression);\n } else if (expr.getKind() === SyntaxKind.ParenthesizedExpression) {\n const inner = (\n expr as import(\"ts-morph\").ParenthesizedExpression\n ).getExpression();\n if (inner.getKind() === SyntaxKind.ObjectLiteralExpression) {\n addUserProp(inner as import(\"ts-morph\").ObjectLiteralExpression);\n }\n }\n });\n }\n }\n\n sourceFile.formatText();\n sourceFile.saveSync();\n return {\n status: \"success\",\n changed: sourceFile.getFullText() !== originalSource,\n };\n}\n","import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport {\n ensureImports,\n withInMemoryScript,\n} from \"../../../../runtime/ts-morph-helpers\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst AUTH_MENU_NAVBAR_ITEM = `\n\t\t<Navbar.Item\n\t\t\tclass=\"flex flex-col md:flex-row items-center space-y-2 md:space-y-0 md:space-x-4\"\n\t\t>\n\t\t\t<AuthMenu.Root>\n\t\t\t\t{#snippet user()}\n\t\t\t\t\t<AuthMenu.Trigger>\n\t\t\t\t\t\t<Avatar.Root>\n\t\t\t\t\t\t\t{#if data.user?.avatar}\n\t\t\t\t\t\t\t\t<Avatar.Image\n\t\t\t\t\t\t\t\t\tsrc=\"/api/files/users/{data.user?.id}/{data.user?.avatar}\"\n\t\t\t\t\t\t\t\t\talt={data.user?.email}\n\t\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t\t{/if}\n\t\t\t\t\t\t\t<Avatar.Fallback>\n\t\t\t\t\t\t\t\t{data.user?.email?.charAt(0).toUpperCase()}\n\t\t\t\t\t\t\t</Avatar.Fallback>\n\t\t\t\t\t\t</Avatar.Root>\n\t\t\t\t\t</AuthMenu.Trigger>\n\n\t\t\t\t\t<AuthMenu.Content align=\"end\">\n\t\t\t\t\t\t<AuthMenu.Item href=\"/dashboard\">Dashboard</AuthMenu.Item>\n\t\t\t\t\t\t<AuthMenu.Group>\n\t\t\t\t\t\t\t<AuthMenu.Item href=\"/settings\">Settings</AuthMenu.Item>\n\t\t\t\t\t\t\t<AuthMenu.Item>\n\t\t\t\t\t\t\t\t<form action=\"/logout\" method=\"post\">\n\t\t\t\t\t\t\t\t\t<button type=\"submit\" class=\"contents\">Logout</button>\n\t\t\t\t\t\t\t\t</form>\n\t\t\t\t\t\t\t</AuthMenu.Item>\n\t\t\t\t\t\t</AuthMenu.Group>\n\t\t\t\t\t</AuthMenu.Content>\n\t\t\t\t{/snippet}\n\n\t\t\t\t{#snippet guest()}\n\t\t\t\t\t<Button\n\t\t\t\t\t\tclass=\"w-full justify-start md:justify-center md:w-auto\"\n\t\t\t\t\t\tvariant=\"ghost\"\n\t\t\t\t\t\thref=\"/login\">Login</Button\n\t\t\t\t\t>\n\t\t\t\t\t<Button\n\t\t\t\t\t\tclass=\"w-full justify-start md:justify-center md:w-auto\"\n\t\t\t\t\t\tvariant=\"outline\"\n\t\t\t\t\t\thref=\"/signup\">Sign up</Button\n\t\t\t\t\t>\n\t\t\t\t{/snippet}\n\t\t\t</AuthMenu.Root>\n\t\t</Navbar.Item>\n\t`;\n\nconst IMPORT_SNIPPET = dedent`\n import * as AuthMenu from '$lib/components/ui/auth-menu';\n import * as Avatar from '$lib/components/ui/avatar';\n`;\n\nconst FAILURE_HINT = [\n \"Add the auth menu inside your <Navbar.List> in the root layout.\",\n \"\",\n \"Imports to add to the <script> tag:\",\n \"\",\n IMPORT_SNIPPET,\n \"\",\n \"Markup to add inside <Navbar.List>:\",\n AUTH_MENU_NAVBAR_ITEM,\n].join(\"\\n\");\n\nconst NOT_FOUND_HINT = [\n \"Create a root layout that includes an auth menu inside <Navbar.List>.\",\n \"\",\n \"Imports for the <script> tag:\",\n \"\",\n IMPORT_SNIPPET,\n \"\",\n \"Markup inside <Navbar.List>:\",\n AUTH_MENU_NAVBAR_ITEM,\n].join(\"\\n\");\n\nexport function modifyRootLayoutSvelte(layoutPath: string): ModifyOutcome {\n if (!fs.existsSync(layoutPath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const file = SvelteFile.fromPath(layoutPath);\n if (!file.hasElement(\"Navbar.List\")) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n if (file.hasElement(\"AuthMenu.Root\")) {\n return { status: \"success\", changed: false };\n }\n\n file.modifyScript((source) => {\n const { source: out } = withInMemoryScript(source, (sf) => {\n ensureImports(sf, [\n {\n namespaceImport: \"AuthMenu\",\n moduleSpecifier: \"$lib/components/ui/auth-menu\",\n },\n {\n namespaceImport: \"Avatar\",\n moduleSpecifier: \"$lib/components/ui/avatar\",\n },\n ]);\n });\n return out;\n });\n\n file.insertBeforeClosingTag(\"Navbar.List\", AUTH_MENU_NAVBAR_ITEM);\n file.writeTo(layoutPath);\n return { status: \"success\", changed: file.hasChanged() };\n}\n","import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { Project, SyntaxKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst FAILURE_HINT = dedent`\n Configure handlePocketbase() with the auth option in hooks.server.ts:\n\n handlePocketbase({\n auth: { protectedRoutes: ['/(app)'] },\n });\n`;\n\nconst NOT_FOUND_HINT = dedent`\n Create src/hooks.server.ts with handlePocketbase:\n\n import { handlePocketbase } from '@velastack/pocketbase';\n\n export const handle = handlePocketbase({\n auth: { protectedRoutes: ['/(app)'] },\n });\n`;\n\nexport function modifyHooksServer(hooksServerPath: string): ModifyOutcome {\n if (!fs.existsSync(hooksServerPath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const originalSource = fs.readFileSync(hooksServerPath, \"utf8\");\n const project = new Project();\n const sourceFile = project.addSourceFileAtPath(hooksServerPath);\n\n // Find the handlePocketbase(...) call\n const callExpr = sourceFile\n .getDescendantsOfKind(SyntaxKind.CallExpression)\n .find((ce) => ce.getExpression().getText() === \"handlePocketbase\");\n\n if (!callExpr) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n const args = callExpr.getArguments();\n if (args.length === 0) {\n callExpr.addArgument(`{ auth: { protectedRoutes: ['/(app)'] } }`);\n sourceFile.formatText();\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n }\n\n const firstArg = args[0];\n if (firstArg.getKind() !== SyntaxKind.ObjectLiteralExpression) {\n callExpr.insertArgument(0, `{ auth: { protectedRoutes: ['/(app)'] } }`);\n sourceFile.formatText();\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n }\n\n const optionsObj = firstArg.asKindOrThrow(SyntaxKind.ObjectLiteralExpression);\n\n // Ensure auth property exists\n const authProp = optionsObj.getProperty(\"auth\");\n if (!authProp) {\n optionsObj.addPropertyAssignment({\n name: \"auth\",\n initializer: `{ protectedRoutes: ['/(app)'] }`,\n });\n sourceFile.formatText();\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n }\n\n // If auth exists, ensure protectedRoutes includes '/(app)'\n if (authProp.getKind() === SyntaxKind.PropertyAssignment) {\n const authInit = (\n authProp as import(\"ts-morph\").PropertyAssignment\n ).getInitializer();\n if (authInit && authInit.getKind() === SyntaxKind.ObjectLiteralExpression) {\n const authObj = authInit as import(\"ts-morph\").ObjectLiteralExpression;\n const prProp = authObj.getProperty(\"protectedRoutes\");\n if (!prProp) {\n authObj.addPropertyAssignment({\n name: \"protectedRoutes\",\n initializer: `['/(app)']`,\n });\n } else if (prProp.getKind() === SyntaxKind.PropertyAssignment) {\n const prInit = (\n prProp as import(\"ts-morph\").PropertyAssignment\n ).getInitializer();\n if (prInit && prInit.getKind() === SyntaxKind.ArrayLiteralExpression) {\n const arr = prInit as import(\"ts-morph\").ArrayLiteralExpression;\n const hasApp = arr\n .getElements()\n .some((el) => el.getText().replace(/['\"`]/g, \"\") === \"/(app)\");\n if (!hasApp) {\n arr.addElement(`'/(app)'`);\n }\n } else {\n (prProp as import(\"ts-morph\").PropertyAssignment).setInitializer(\n `['/(app)']`,\n );\n }\n }\n }\n }\n\n sourceFile.formatText();\n sourceFile.saveSync();\n return {\n status: \"success\",\n changed: sourceFile.getFullText() !== originalSource,\n };\n}\n","import path from \"node:path\";\nimport fs from \"node:fs\";\nimport { Options, Result, File } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport {\n getMigrationFile,\n migrationDelay,\n withPocketbase,\n} from \"../../../runtime/pocketbase\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { modifySvelteConfigRemote } from \"../../../runtime/modify-svelte-config-remote\";\n\nimport { modifyLayoutServer } from \"./modifies/+layout.server\";\nimport { modifyRootLayoutSvelte } from \"./modifies/root-layout.svelte\";\nimport { modifyHooksServer } from \"./modifies/hooks.server\";\n\nexport async function generate(options: Options) {\n const { input } = options;\n const logger = getLogger(options);\n\n let creates: File[] = [];\n\n // Update PocketBase\n await withPocketbase(options.root, async (pb) => {\n logger.info(\"Updating PocketBase mail settings\");\n await pb.settings.update({\n meta: {\n senderName: input.senderName,\n senderAddress: input.senderAddress,\n },\n });\n await migrationDelay();\n\n const userCollection = await pb.collections.getOne(\"users\");\n\n if (!userCollection) {\n throw new Error(\"Users collection not found\");\n }\n\n const verificationTemplate =\n userCollection.verificationTemplate.body.replace(\n \"{APP_URL}/_/#/auth/confirm-verification/{TOKEN}\",\n \"{APP_URL}/confirm-verification/{TOKEN}\",\n );\n const resetPasswordTemplate =\n userCollection.resetPasswordTemplate.body.replace(\n \"{APP_URL}/_/#/auth/confirm-reset/{TOKEN}\",\n \"{APP_URL}/confirm-reset/{TOKEN}\",\n );\n const confirmEmailChangeTemplate =\n userCollection.confirmEmailChangeTemplate.body.replace(\n \"{APP_URL}/_/#/auth/confirm-email-change/{TOKEN}\",\n \"{APP_URL}/confirm-email-change/{TOKEN}\",\n );\n\n logger.info(\"Locking down users collection rules and email templates\");\n // Update user auth rules to lock down access to the user's own account\n await pb.collections.update(\"users\", {\n listRule: \"@request.auth.id = id\",\n viewRule: \"@request.auth.id = id\",\n createRule: \"@request.auth.id = id\",\n updateRule: \"@request.auth.id = id\",\n deleteRule: \"@request.auth.id = id\",\n\n // Update email templates to VelaStack auth urls\n verificationTemplate: {\n body: verificationTemplate,\n },\n resetPasswordTemplate: {\n body: resetPasswordTemplate,\n },\n confirmEmailChangeTemplate: {\n body: confirmEmailChangeTemplate,\n },\n });\n await migrationDelay();\n\n const migrationFile = getMigrationFile(\"users\", \"updated\", options);\n if (migrationFile) {\n creates.push({\n path: migrationFile,\n language: \"ts\",\n content: fs.readFileSync(migrationFile, \"utf8\"),\n status: \"success\",\n });\n }\n });\n\n // Modify files\n const modifies: File[] = [];\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n logger.info(\"Modifying +layout.server.ts\");\n const layoutServerFile = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"+layout.server.ts\",\n );\n pushResult(\n modifyOutcomeToFile(layoutServerFile, modifyLayoutServer(layoutServerFile)),\n );\n\n logger.info(\"Modifying root layout\");\n // TODO: make this more robust by searching for Navbar.Root > Navbar.List\n // src/routes/(public)/root-layout.svelte is what vela creates by default\n const layoutCandidates = [\n path.join(options.root, \"src\", \"routes\", \"(public)\", \"root-layout.svelte\"),\n path.join(options.root, \"src\", \"routes\", \"root-layout.svelte\"),\n path.join(options.root, \"src\", \"routes\", \"(public)\", \"+layout.svelte\"),\n path.join(options.root, \"src\", \"routes\", \"+layout.svelte\"),\n ];\n const layoutFile =\n layoutCandidates.find((p) => fs.existsSync(p)) ?? layoutCandidates[0];\n pushResult(\n modifyOutcomeToFile(layoutFile, modifyRootLayoutSvelte(layoutFile)),\n );\n\n logger.info(\"Modifying hooks.server.ts\");\n const hooksServerFile = path.join(options.root, \"src\", \"hooks.server.ts\");\n pushResult(\n modifyOutcomeToFile(hooksServerFile, modifyHooksServer(hooksServerFile)),\n );\n\n logger.info(\"Modifying config for remote functions\");\n const remote = modifySvelteConfigRemote(options.root);\n pushResult(modifyOutcomeToFile(remote.filePath, remote.outcome));\n\n return {\n creates: [],\n modifies,\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n } satisfies Result;\n}\n"],"mappings":";;;;;;;;;;AAKA,SAAgB,EAAmB,GAAmC;CACpE,IAAI,CAAC,EAAG,WAAW,CAAU,GAAG;EAC9B,IAAM,IAAU,CAAM;;;;;EAOtB,OADA,EAAG,cAAc,GAAY,CAAO,GAC7B;GAAE,QAAQ;GAAW,SAAS;EAAK;CAC5C;CAEA,IAAM,IAAiB,EAAG,aAAa,GAAY,MAAM,GAEnD,IAAa,IADC,EACD,CAAA,CAAQ,oBAAoB,CAAU,GAGnD,KAAe,MAAoD;EAEvE,AADkB,EAAI,YAAY,MAAM,KAEtC,EAAI,sBAAsB;GACxB,MAAM;GACN,aAAa;EACf,CAAC;CAEL,GAGI,GACA,GAKE,IAAU,EAAW,uBAAuB,MAAM;CACxD,IAAI,KACS,EAAQ,uBAAuB,EAAW,iBAChC,CAAA,EAAI,iBAAiB,GAC1B;EACd,IAAM,IAAc,EAAQ,qBAC1B,EAAW,aACb;EACA,IAAI,GACF,IAAY;OACP;GACL,IAAM,IAAO,EAAQ,eAAe;GACpC,IAAI,GAAM;IACR,IAAM,IAAa,EAAK,yBACtB,EAAW,aACb;IACA,IAAI,GACF,IAAY;SACP;KACL,IAAM,IAAc,EAAK,yBACvB,EAAW,kBACb;KACA,AAAI,MACF,IAAS;IAEb;GACF;EACF;CACF;CAGF,IAAI,CAAC,GAAW;EACd,IAAM,IAAU,EAAW,YAAY,MAAM;EAC7C,AAAI,KAAW,EAAQ,WAAW,MAChC,IAAS;CAEb;CAGA,IAAI,CAAC,K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pE,GAEA,EAAO,KAAK,2BAA2B;CACvC,IAAM,IAAkB,EAAK,KAAK,EAAQ,MAAM,OAAO,iBAAiB;CAKxE,AAJA,EACE,EAAoB,GAAiB,EAAkB,CAAe,CAAC,CACzE,GAEA,EAAO,KAAK,uCAAuC;CACnD,IAAM,IAAS,EAAyB,EAAQ,IAAI;CAGpD,OAFA,EAAW,EAAoB,EAAO,UAAU,EAAO,OAAO,CAAC,GAExD;EACL,SAAS,CAAC;EACV;EACA,SAAS,CAAC;EACV,YAAY,CAAC;EACb,UAAU,CAAC;EACX,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAiB,CAAC;CACpB;AACF"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { n as e } from "./logger-CQONztPm.js";
|
|
2
|
-
import { t } from "./shared
|
|
2
|
+
import { t } from "./shared-BZlvCHX8.js";
|
|
3
3
|
import { modifyOutcomeToFile as n } from "./modify-file-PVKmDJHk.js";
|
|
4
4
|
import { a as r, o as i, r as a } from "./ts-morph-helpers-Bk82Z2n7.js";
|
|
5
5
|
import o from "node:path";
|
|
@@ -104,4 +104,4 @@ async function p(r) {
|
|
|
104
104
|
//#endregion
|
|
105
105
|
export { p as generate };
|
|
106
106
|
|
|
107
|
-
//# sourceMappingURL=generate.runtime-
|
|
107
|
+
//# sourceMappingURL=generate.runtime-BX0QcpGg.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"generate.runtime-
|
|
1
|
+
{"version":3,"file":"generate.runtime-BX0QcpGg.js","names":[],"sources":["../../src/patterns/disable/auth/modifies/+layout.server.ts","../../src/patterns/disable/auth/modifies/root-layout.svelte.ts","../../src/patterns/disable/auth/modifies/hooks.server.ts","../../src/patterns/disable/auth/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport { Project, SyntaxKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nexport function unmodifyLayoutServer(layoutPath: string): ModifyOutcome {\n if (!fs.existsSync(layoutPath)) {\n return { status: \"success\", changed: false };\n }\n\n const originalSource = fs.readFileSync(layoutPath, \"utf8\");\n if (!originalSource.includes(\"locals.pb.authStore.record\")) {\n return { status: \"success\", changed: false };\n }\n\n const project = new Project();\n const sourceFile = project.addSourceFileAtPath(layoutPath);\n\n const literals = sourceFile.getDescendantsOfKind(\n SyntaxKind.ObjectLiteralExpression,\n );\n for (const obj of literals) {\n const userProp = obj.getProperty(\"user\");\n if (!userProp || userProp.getKind() !== SyntaxKind.PropertyAssignment) {\n continue;\n }\n const value = (userProp as import(\"ts-morph\").PropertyAssignment)\n .getInitializer()\n ?.getText();\n if (value === \"locals.pb.authStore.record\") {\n userProp.remove();\n }\n }\n\n sourceFile.formatText();\n sourceFile.saveSync();\n\n return {\n status: \"success\",\n changed: sourceFile.getFullText() !== originalSource,\n };\n}\n","import fs from \"node:fs\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport {\n removeImportByModuleSpecifier,\n withInMemoryScript,\n} from \"../../../../runtime/ts-morph-helpers\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nexport function unmodifyRootLayoutSvelte(layoutPath: string): ModifyOutcome {\n if (!fs.existsSync(layoutPath)) {\n return { status: \"success\", changed: false };\n }\n\n const source = fs.readFileSync(layoutPath, \"utf8\");\n const file = new SvelteFile(source);\n if (!file.hasElement(\"AuthMenu.Root\")) {\n return { status: \"success\", changed: false };\n }\n\n file.removeElement(\"AuthMenu.Root\");\n\n file.modifyScript((content) => {\n const { source: out } = withInMemoryScript(content, (sf) => {\n removeImportByModuleSpecifier(sf, \"$lib/components/ui/auth-menu\");\n removeImportByModuleSpecifier(sf, \"$lib/components/ui/avatar\");\n });\n return out;\n });\n\n file.writeTo(layoutPath);\n return { status: \"success\", changed: file.hasChanged() };\n}\n","import fs from \"node:fs\";\nimport { Project, SyntaxKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nexport function unmodifyHooksServer(hooksServerPath: string): ModifyOutcome {\n if (!fs.existsSync(hooksServerPath)) {\n return { status: \"success\", changed: false };\n }\n\n const originalSource = fs.readFileSync(hooksServerPath, \"utf8\");\n const project = new Project();\n const sourceFile = project.addSourceFileAtPath(hooksServerPath);\n\n const callExpr = sourceFile\n .getDescendantsOfKind(SyntaxKind.CallExpression)\n .find((ce) => ce.getExpression().getText() === \"handlePocketbase\");\n if (!callExpr) return { status: \"success\", changed: false };\n\n const [firstArg] = callExpr.getArguments();\n if (!firstArg || firstArg.getKind() !== SyntaxKind.ObjectLiteralExpression) {\n return { status: \"success\", changed: false };\n }\n\n const optionsObj = firstArg.asKindOrThrow(SyntaxKind.ObjectLiteralExpression);\n const authProp = optionsObj.getProperty(\"auth\");\n if (!authProp) {\n return { status: \"success\", changed: false };\n }\n\n authProp.remove();\n\n if (optionsObj.getProperties().length === 0) {\n callExpr.removeArgument(0);\n }\n\n sourceFile.formatText();\n sourceFile.saveSync();\n\n return {\n status: \"success\",\n changed: sourceFile.getFullText() !== originalSource,\n };\n}\n","import path from \"node:path\";\nimport fs from \"node:fs\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { unmodifyLayoutServer } from \"./modifies/+layout.server\";\nimport { unmodifyRootLayoutSvelte } from \"./modifies/root-layout.svelte\";\nimport { unmodifyHooksServer } from \"./modifies/hooks.server\";\nimport { planDropsForCollections } from \"../../destroy/shared\";\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const modifies: File[] = [];\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n logger.info(\"Reverting +layout.server.ts\");\n const layoutServerFile = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"+layout.server.ts\",\n );\n pushResult(\n modifyOutcomeToFile(\n layoutServerFile,\n unmodifyLayoutServer(layoutServerFile),\n ),\n );\n\n logger.info(\"Reverting root layout\");\n const layoutCandidates = [\n path.join(options.root, \"src\", \"routes\", \"(public)\", \"root-layout.svelte\"),\n path.join(options.root, \"src\", \"routes\", \"root-layout.svelte\"),\n path.join(options.root, \"src\", \"routes\", \"(public)\", \"+layout.svelte\"),\n path.join(options.root, \"src\", \"routes\", \"+layout.svelte\"),\n ];\n const layoutFile =\n layoutCandidates.find((p) => fs.existsSync(p)) ?? layoutCandidates[0];\n pushResult(\n modifyOutcomeToFile(layoutFile, unmodifyRootLayoutSvelte(layoutFile)),\n );\n\n logger.info(\"Reverting hooks.server.ts\");\n const hooksServerFile = path.join(options.root, \"src\", \"hooks.server.ts\");\n pushResult(\n modifyOutcomeToFile(hooksServerFile, unmodifyHooksServer(hooksServerFile)),\n );\n\n const collectionDrops = await planDropsForCollections(\n [\"oauth_accounts\"],\n options,\n );\n\n return {\n creates: [],\n modifies,\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops,\n } satisfies Result;\n}\n"],"mappings":";;;;;;;;AAIA,SAAgB,EAAqB,GAAmC;CACtE,IAAI,CAAC,EAAG,WAAW,CAAU,GAC3B,OAAO;EAAE,QAAQ;EAAW,SAAS;CAAM;CAG7C,IAAM,IAAiB,EAAG,aAAa,GAAY,MAAM;CACzD,IAAI,CAAC,EAAe,SAAS,4BAA4B,GACvD,OAAO;EAAE,QAAQ;EAAW,SAAS;CAAM;CAI7C,IAAM,IAAa,IADC,EACD,CAAA,CAAQ,oBAAoB,CAAU,GAEnD,IAAW,EAAW,qBAC1B,EAAW,uBACb;CACA,KAAK,IAAM,KAAO,GAAU;EAC1B,IAAM,IAAW,EAAI,YAAY,MAAM;EACnC,CAAC,KAAY,EAAS,QAAQ,MAAM,EAAW,sBAGpC,EACZ,eAAe,CAAC,EACf,QAAQ,MACE,gCACZ,EAAS,OAAO;CAEpB;CAKA,OAHA,EAAW,WAAW,GACtB,EAAW,SAAS,GAEb;EACL,QAAQ;EACR,SAAS,EAAW,YAAY,MAAM;CACxC;AACF;;;AChCA,SAAgB,EAAyB,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
|
import { modifyOutcomeToFile as n } from "./modify-file-PVKmDJHk.js";
|
|
4
4
|
import { i as r, o as i } from "./ts-morph-helpers-Bk82Z2n7.js";
|
|
5
5
|
import { n as a } from "./env-BPfk1VAw.js";
|
|
@@ -113,4 +113,4 @@ async function p(r) {
|
|
|
113
113
|
//#endregion
|
|
114
114
|
export { p as generate };
|
|
115
115
|
|
|
116
|
-
//# sourceMappingURL=generate.runtime-
|
|
116
|
+
//# sourceMappingURL=generate.runtime-BlK7yHff.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"generate.runtime-
|
|
1
|
+
{"version":3,"file":"generate.runtime-BlK7yHff.js","names":[],"sources":["../../src/patterns/disable/payments/modifies/modify-nav-user.ts","../../src/patterns/disable/payments/modifies/modify-user-signup.ts","../../src/patterns/disable/payments/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport { removeNavItemFromScript } from \"../../../../runtime/ts-morph-helpers\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nexport function unmodifyNavUser(navUserPath: string): ModifyOutcome {\n if (!fs.existsSync(navUserPath)) {\n return { status: \"success\", changed: false };\n }\n\n const source = fs.readFileSync(navUserPath, \"utf8\");\n if (!source.includes(\"/billing\")) {\n return { status: \"success\", changed: false };\n }\n\n const file = new SvelteFile(source);\n let wasRemoved = false;\n\n const tryRemove = (run: (fn: (s: string) => string) => boolean) => {\n if (wasRemoved) return;\n run((src) => {\n const result = removeNavItemFromScript(\n src,\n \"Billing\",\n \"@lucide/svelte/icons/credit-card\",\n );\n if (result.wasRemoved) wasRemoved = true;\n return result.source;\n });\n };\n\n tryRemove((fn) => file.modifyModuleScript(fn));\n if (!wasRemoved) tryRemove((fn) => file.modifyScript(fn));\n\n if (!wasRemoved) {\n return { status: \"success\", changed: false };\n }\n\n fs.writeFileSync(navUserPath, file.toString(), \"utf8\");\n return { status: \"success\", changed: true };\n}\n","import fs from \"node:fs\";\nimport { Project, QuoteKind, SyntaxKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nexport function unmodifyUserSignup(userSignupPath: string): ModifyOutcome {\n if (!fs.existsSync(userSignupPath)) {\n return { status: \"success\", changed: false };\n }\n\n const originalSource = fs.readFileSync(userSignupPath, \"utf8\");\n if (!originalSource.includes(\"linkStripeCustomer\")) {\n return { status: \"success\", changed: false };\n }\n\n const project = new Project({\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n const sourceFile = project.addSourceFileAtPath(userSignupPath);\n\n const stripeImport = sourceFile\n .getImportDeclarations()\n .find((d) => d.getModuleSpecifierValue() === \"$lib/stripe\");\n if (stripeImport) stripeImport.remove();\n\n const linkFn = sourceFile.getVariableStatement((s) =>\n s.getDeclarations().some((d) => d.getName() === \"linkStripeCustomer\"),\n );\n if (linkFn) linkFn.remove();\n\n const callStatements = sourceFile\n .getDescendantsOfKind(SyntaxKind.CallExpression)\n .filter((ce) => ce.getExpression().getText() === \"linkStripeCustomer\");\n for (const call of callStatements) {\n const stmt = call.getFirstAncestorByKind(SyntaxKind.ExpressionStatement);\n if (stmt) stmt.remove();\n }\n\n sourceFile.formatText();\n sourceFile.saveSync();\n\n return {\n status: \"success\",\n changed: sourceFile.getFullText() !== originalSource,\n };\n}\n","import path from \"node:path\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { modifyEnvRemove, type EnvEdit } from \"../../../runtime/env\";\nimport { unmodifyNavUser } from \"./modifies/modify-nav-user\";\nimport { unmodifyUserSignup } from \"./modifies/modify-user-signup\";\nimport { planDropsForCollections } from \"../../destroy/shared\";\n\nexport async function generate(options: Options) {\n const isAppMode = options.features.auth;\n const logger = getLogger(options);\n const modifies: File[] = [];\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n logger.info(\"Stripping Stripe credentials from .env\");\n const envEdits: EnvEdit[] = [\n { type: \"comment\", key: \"Stripe credentials\" },\n { type: \"var\", key: \"STRIPE_SECRET_KEY\" },\n { type: \"var\", key: \"PUBLIC_STRIPE_PUBLISHABLE_KEY\" },\n { type: \"var\", key: \"STRIPE_WEBHOOK_SECRET\" },\n { type: \"var\", key: \"INTERNAL_JOB_SECRET\" },\n ];\n const envPath = path.join(options.root, \".env\");\n pushResult(modifyOutcomeToFile(envPath, modifyEnvRemove(envPath, envEdits)));\n\n if (isAppMode) {\n logger.info(\"Reverting nav-user.svelte\");\n const navUserPath = path.join(\n options.root,\n \"src\",\n \"lib\",\n \"components\",\n \"nav-user.svelte\",\n );\n pushResult(modifyOutcomeToFile(navUserPath, unmodifyNavUser(navUserPath)));\n\n logger.info(\"Reverting signup +page.server.ts\");\n const userSignupPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(public)\",\n \"(auth)\",\n \"signup\",\n \"+page.server.ts\",\n );\n pushResult(\n modifyOutcomeToFile(userSignupPath, unmodifyUserSignup(userSignupPath)),\n );\n }\n\n const collectionNames = [\n \"transactions\",\n \"stripe_customers\",\n \"stripe_payment_methods\",\n \"stripe_prices\",\n \"stripe_products\",\n ];\n const collectionDrops = await planDropsForCollections(\n isAppMode ? collectionNames : [\"stripe_prices\", \"stripe_products\"],\n options,\n );\n\n return {\n creates: [],\n modifies,\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops,\n } satisfies Result;\n}\n"],"mappings":";;;;;;;;;AAKA,SAAgB,EAAgB,GAAoC;CAClE,IAAI,CAAC,EAAG,WAAW,CAAW,GAC5B,OAAO;EAAE,QAAQ;EAAW,SAAS;CAAM;CAG7C,IAAM,IAAS,EAAG,aAAa,GAAa,MAAM;CAClD,IAAI,CAAC,EAAO,SAAS,UAAU,GAC7B,OAAO;EAAE,QAAQ;EAAW,SAAS;CAAM;CAG7C,IAAM,IAAO,IAAI,EAAW,CAAM,GAC9B,IAAa,IAEX,KAAa,MAAgD;EAC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
|
2
|
+
import { t } from "./shared-BZlvCHX8.js";
|
|
3
3
|
import { modifyOutcomeToFile as n } from "./modify-file-PVKmDJHk.js";
|
|
4
4
|
import { i as r, o as i } from "./ts-morph-helpers-Bk82Z2n7.js";
|
|
5
5
|
import a from "node:path";
|
|
@@ -90,4 +90,4 @@ async function d(r) {
|
|
|
90
90
|
//#endregion
|
|
91
91
|
export { d as generate };
|
|
92
92
|
|
|
93
|
-
//# sourceMappingURL=generate.runtime-
|
|
93
|
+
//# sourceMappingURL=generate.runtime-BmW0th7X.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"generate.runtime-
|
|
1
|
+
{"version":3,"file":"generate.runtime-BmW0th7X.js","names":[],"sources":["../../src/patterns/disable/api-keys/modifies/hooks.server.ts","../../src/patterns/disable/api-keys/modifies/nav-user.svelte.ts","../../src/patterns/disable/api-keys/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport { Project, SyntaxKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nexport function unmodifyHooksServer(hooksServerPath: string): ModifyOutcome {\n if (!fs.existsSync(hooksServerPath)) {\n return { status: \"success\", changed: false };\n }\n\n const originalSource = fs.readFileSync(hooksServerPath, \"utf8\");\n const project = new Project();\n const sourceFile = project.addSourceFileAtPath(hooksServerPath);\n\n const callExpr = sourceFile\n .getDescendantsOfKind(SyntaxKind.CallExpression)\n .find((ce) => ce.getExpression().getText() === \"handlePocketbase\");\n if (!callExpr) return { status: \"success\", changed: false };\n\n const [firstArg] = callExpr.getArguments();\n if (!firstArg || firstArg.getKind() !== SyntaxKind.ObjectLiteralExpression) {\n return { status: \"success\", changed: false };\n }\n\n const optionsObj = firstArg.asKindOrThrow(SyntaxKind.ObjectLiteralExpression);\n const apiProp = optionsObj.getProperty(\"api\");\n if (!apiProp || apiProp.getKind() !== SyntaxKind.PropertyAssignment) {\n return { status: \"success\", changed: false };\n }\n\n const apiInit = (\n apiProp as import(\"ts-morph\").PropertyAssignment\n ).getInitializer();\n if (!apiInit || apiInit.getKind() !== SyntaxKind.ObjectLiteralExpression) {\n return { status: \"success\", changed: false };\n }\n\n const apiObj = apiInit as import(\"ts-morph\").ObjectLiteralExpression;\n const apiKeysProp = apiObj.getProperty(\"apiKeys\");\n if (!apiKeysProp) {\n return { status: \"success\", changed: false };\n }\n\n apiKeysProp.remove();\n\n sourceFile.formatText();\n sourceFile.saveSync();\n\n return {\n status: \"success\",\n changed: sourceFile.getFullText() !== originalSource,\n };\n}\n","import fs from \"node:fs\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport { removeNavItemFromScript } from \"../../../../runtime/ts-morph-helpers\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nexport function unmodifyNavUser(navUserPath: string): ModifyOutcome {\n if (!fs.existsSync(navUserPath)) {\n return { status: \"success\", changed: false };\n }\n\n const source = fs.readFileSync(navUserPath, \"utf8\");\n if (!source.includes(\"/api-keys\")) {\n return { status: \"success\", changed: false };\n }\n\n const file = new SvelteFile(source);\n let wasRemoved = false;\n\n const tryRemove = (run: (fn: (s: string) => string) => boolean) => {\n if (wasRemoved) return;\n run((src) => {\n const result = removeNavItemFromScript(\n src,\n \"API Keys\",\n \"@lucide/svelte/icons/key-round\",\n );\n if (result.wasRemoved) wasRemoved = true;\n return result.source;\n });\n };\n\n tryRemove((fn) => file.modifyModuleScript(fn));\n if (!wasRemoved) tryRemove((fn) => file.modifyScript(fn));\n\n if (!wasRemoved) {\n return { status: \"success\", changed: false };\n }\n\n fs.writeFileSync(navUserPath, file.toString(), \"utf8\");\n return { status: \"success\", changed: true };\n}\n","import path from \"node:path\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { unmodifyHooksServer } from \"./modifies/hooks.server\";\nimport { unmodifyNavUser } from \"./modifies/nav-user.svelte\";\nimport { planDropsForCollections } from \"../../destroy/shared\";\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const modifies: File[] = [];\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n logger.info(\"Reverting hooks.server.ts\");\n const hooksServerPath = path.join(options.root, \"src\", \"hooks.server.ts\");\n pushResult(\n modifyOutcomeToFile(hooksServerPath, unmodifyHooksServer(hooksServerPath)),\n );\n\n logger.info(\"Reverting nav-user.svelte\");\n const navUserPath = path.join(\n options.root,\n \"src\",\n \"lib\",\n \"components\",\n \"nav-user.svelte\",\n );\n pushResult(modifyOutcomeToFile(navUserPath, unmodifyNavUser(navUserPath)));\n\n const collectionDrops = await planDropsForCollections([\"api_keys\"], options);\n\n return {\n creates: [],\n modifies,\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops,\n } satisfies Result;\n}\n"],"mappings":";;;;;;;;AAIA,SAAgB,EAAoB,GAAwC;CAC1E,IAAI,CAAC,EAAG,WAAW,CAAe,GAChC,OAAO;EAAE,QAAQ;EAAW,SAAS;CAAM;CAG7C,IAAM,IAAiB,EAAG,aAAa,GAAiB,MAAM,GAExD,IAAa,IADC,EACD,CAAA,CAAQ,oBAAoB,CAAe,GAExD,IAAW,EACd,qBAAqB,EAAW,cAAc,CAAC,CAC/C,MAAM,MAAO,EAAG,cAAc,CAAC,CAAC,QAAQ,MAAM,kBAAkB;CACnE,IAAI,CAAC,GAAU,OAAO;EAAE,QAAQ;EAAW,SAAS;CAAM;CAE1D,IAAM,CAAC,KAAY,EAAS,aAAa;CACzC,IAAI,CAAC,KAAY,EAAS,QAAQ,MAAM,EAAW,yBACjD,OAAO;EAAE,QAAQ;EAAW,SAAS;CAAM;CAI7C,IAAM,IADa,EAAS,cAAc,EAAW,uBACrC,CAAA,CAAW,YAAY,KAAK;CAC5C,IAAI,CAAC,KAAW,EAAQ,QAAQ,MAAM,EAAW,oBAC/C,OAAO;EAAE,QAAQ;EAAW,SAAS;CAAM;CAG7C,IAAM,IACJ,EACA,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