@velastack/patterns 0.0.44 → 0.0.46
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunks/{collections-DeT38X6O.js → collections-BwO27pJg.js} +2 -2
- package/dist/chunks/{collections-DeT38X6O.js.map → collections-BwO27pJg.js.map} +1 -1
- package/dist/chunks/{env-KcKcG4Mg.js → env-Bk-LRVos.js} +1 -1
- package/dist/chunks/{env-KcKcG4Mg.js.map → env-Bk-LRVos.js.map} +1 -1
- package/dist/chunks/env.runtime-D46GCIKe.js +31 -0
- package/dist/chunks/env.runtime-D46GCIKe.js.map +1 -0
- package/dist/chunks/{generate.runtime-AgF-_CuZ.js → generate.runtime-Bbf2YWaA.js} +1 -1
- package/dist/chunks/{generate.runtime-AgF-_CuZ.js.map → generate.runtime-Bbf2YWaA.js.map} +1 -1
- package/dist/chunks/{generate.runtime-BhJKZmLN.js → generate.runtime-BkvtIjgh.js} +2 -2
- package/dist/chunks/{generate.runtime-BhJKZmLN.js.map → generate.runtime-BkvtIjgh.js.map} +1 -1
- package/dist/chunks/{generate.runtime-VhD6Bmgq.js → generate.runtime-BnkNmF1g.js} +1 -1
- package/dist/chunks/{generate.runtime-VhD6Bmgq.js.map → generate.runtime-BnkNmF1g.js.map} +1 -1
- package/dist/chunks/{generate.runtime-RfPLo7XV.js → generate.runtime-Bpx69a8t.js} +4 -4
- package/dist/chunks/{generate.runtime-RfPLo7XV.js.map → generate.runtime-Bpx69a8t.js.map} +1 -1
- package/dist/chunks/{generate.runtime-WWvlaFF2.js → generate.runtime-CEtVUz4k.js} +3 -3
- package/dist/chunks/{generate.runtime-WWvlaFF2.js.map → generate.runtime-CEtVUz4k.js.map} +1 -1
- package/dist/chunks/{generate.runtime-C0kTnsI4.js → generate.runtime-CUgleG0U.js} +1 -1
- package/dist/chunks/{generate.runtime-C0kTnsI4.js.map → generate.runtime-CUgleG0U.js.map} +1 -1
- package/dist/chunks/{generate.runtime-DL1Ik7b6.js → generate.runtime-Cb2vYF1l.js} +1 -1
- package/dist/chunks/{generate.runtime-DL1Ik7b6.js.map → generate.runtime-Cb2vYF1l.js.map} +1 -1
- package/dist/chunks/{generate.runtime-DBAtF_T_.js → generate.runtime-CrAHzaEW.js} +2 -2
- package/dist/chunks/{generate.runtime-DBAtF_T_.js.map → generate.runtime-CrAHzaEW.js.map} +1 -1
- package/dist/chunks/{generate.runtime-Cp5n_QqA.js → generate.runtime-Cudp67b-.js} +1 -1
- package/dist/chunks/{generate.runtime-Cp5n_QqA.js.map → generate.runtime-Cudp67b-.js.map} +1 -1
- package/dist/chunks/{generate.runtime-DprX2Upp.js → generate.runtime-D1uQBjeg.js} +3 -3
- package/dist/chunks/{generate.runtime-DprX2Upp.js.map → generate.runtime-D1uQBjeg.js.map} +1 -1
- package/dist/chunks/{generate.runtime-Cjr2Xa3e.js → generate.runtime-D1wqmaXU.js} +2 -2
- package/dist/chunks/{generate.runtime-Cjr2Xa3e.js.map → generate.runtime-D1wqmaXU.js.map} +1 -1
- package/dist/chunks/generate.runtime-D6oE0Mmf.js +28 -0
- package/dist/chunks/generate.runtime-D6oE0Mmf.js.map +1 -0
- package/dist/chunks/{generate.runtime-Dqa95On4.js → generate.runtime-DFDFxHih.js} +2 -2
- package/dist/chunks/{generate.runtime-Dqa95On4.js.map → generate.runtime-DFDFxHih.js.map} +1 -1
- package/dist/chunks/generate.runtime-DFG2C9gc.js +28 -0
- package/dist/chunks/generate.runtime-DFG2C9gc.js.map +1 -0
- package/dist/chunks/{generate.runtime-Cf_EwiYf.js → generate.runtime-DPzrDUU7.js} +2 -2
- package/dist/chunks/{generate.runtime-Cf_EwiYf.js.map → generate.runtime-DPzrDUU7.js.map} +1 -1
- package/dist/chunks/{generate.runtime-8Ciy0dLy.js → generate.runtime-DQLmiRz6.js} +4 -4
- package/dist/chunks/{generate.runtime-8Ciy0dLy.js.map → generate.runtime-DQLmiRz6.js.map} +1 -1
- package/dist/chunks/{generate.runtime-kovRoEUU.js → generate.runtime-DjwRKg8K.js} +1 -1
- package/dist/chunks/{generate.runtime-kovRoEUU.js.map → generate.runtime-DjwRKg8K.js.map} +1 -1
- package/dist/chunks/{generate.runtime-4F-eepmc.js → generate.runtime-DnymXcvu.js} +2 -2
- package/dist/chunks/{generate.runtime-4F-eepmc.js.map → generate.runtime-DnymXcvu.js.map} +1 -1
- package/dist/chunks/{generate.runtime-BM00PfQB.js → generate.runtime-M6LNL7Tq.js} +2 -2
- package/dist/chunks/{generate.runtime-BM00PfQB.js.map → generate.runtime-M6LNL7Tq.js.map} +1 -1
- package/dist/chunks/{generate.runtime-JZeLiMFO.js → generate2.runtime-yP14iPwX.js} +3 -3
- package/dist/chunks/generate2.runtime-yP14iPwX.js.map +1 -0
- package/dist/chunks/{modify-svelte-config-remote-DenOsWro.js → modify-svelte-config-remote-C3g7Oi6_.js} +1 -1
- package/dist/chunks/{modify-svelte-config-remote-DenOsWro.js.map → modify-svelte-config-remote-C3g7Oi6_.js.map} +1 -1
- package/dist/chunks/{modify-utils-FsEBGzju.js → modify-utils-CZ9Auvp9.js} +1 -1
- package/dist/chunks/{modify-utils-FsEBGzju.js.map → modify-utils-CZ9Auvp9.js.map} +1 -1
- package/dist/chunks/{pocketbase-DYaSZ9lS.js → pocketbase-D7GjPuNu.js} +1 -1
- package/dist/chunks/{pocketbase-DYaSZ9lS.js.map → pocketbase-D7GjPuNu.js.map} +1 -1
- package/dist/chunks/{shared-B_6tQpQF.js → shared-C4wJ9sb0.js} +2 -2
- package/dist/chunks/{shared-B_6tQpQF.js.map → shared-C4wJ9sb0.js.map} +1 -1
- package/dist/chunks/test-setup-C3gvjtTY.js +140 -0
- package/dist/chunks/test-setup-C3gvjtTY.js.map +1 -0
- package/dist/chunks/{write-result-B5eX8Cjw.js → write-result-BmL8uLNd.js} +2 -2
- package/dist/chunks/{write-result-B5eX8Cjw.js.map → write-result-BmL8uLNd.js.map} +1 -1
- package/dist/index.d.ts +224 -39
- package/dist/index.js +792 -587
- package/dist/index.js.map +1 -1
- package/package.json +3 -3
- package/dist/chunks/env.runtime-N65jqPxq.js +0 -32
- package/dist/chunks/env.runtime-N65jqPxq.js.map +0 -1
- package/dist/chunks/generate.runtime-JZeLiMFO.js.map +0 -1
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { t as e } from "./errors-Co77I4oK.js";
|
|
2
2
|
import { i as t } from "./util-BNtpm1tP.js";
|
|
3
3
|
import { n, t as r } from "./logger-BpgCb-ZG.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-D7GjPuNu.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-BwO27pJg.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"collections-DeT38X6O.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;AACT,KACE,EAAM,UAAU,MAAM,MAAM,SA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AAU,EAAQ;AAqBjC,QAnBA,MAAM,EAAe,EAAQ,MAAM,OAAO,MAAO;AAC/C,OAAK,IAAM,KAAQ,GAAO;AACxB,KAAO,KAAK,wBAAwB,EAAK,KAAK,GAAG;GACjD,IAAM,EAAE,eAAY,MAAM,EAAyB,GAAI,EAAK,MAAM,EAAO;AACzE,OAAI,CAAC,EAAS;AACd,SAAM,GAAgB;GAEtB,IAAM,IAAgB,EAAiB,EAAK,MAAM,WAAW,EAAQ;AAChE,QAEL,EAAW,KAAK;IACd,MAAM;IACN,UAAU,EAAiB,EAAc;IACzC,SAAS,EAAa,GAAe,OAAO;IAC5C,QAAQ;IACT,CAAC;;GAEJ,EAEK;;AAGT,eAAsB,EACpB,GACA,GACiB;AACjB,KAAI,EAAY,WAAW,EACzB,QAAO,EAAE;CAGX,IAAM,IAAqB,EAAE,EACvB,IAAS,EAAU,EAAQ;AA+BjC,QA7BA,MAAM,EAAe,EAAQ,MAAM,OAAO,MAAO;AAC/C,OAAK,IAAM,KAAc,GAAa;AACpC,KAAO,KAAK,wBAAwB,EAAW,KAAK,GAAG;GACvD,IAAM,EAAE,eAAY,MAAM,EACxB,GACA,GACA,EACD;AACD,OAAI,CAAC,EAAS;AACd,SAAM,GAAgB;GAEtB,IAAM,IAAgB,EACpB,EAAW,MACX,WACA,EACD;AACI,QAIL,EAAW,KAAK;IACd,MAAM;IACN,UAAU,EAAiB,EAAc;IACzC,SAAS,EAAa,GAAe,OAAO;IAC5C,QAAQ;IACT,CAAC;;GAEJ,EAEK"}
|
|
1
|
+
{"version":3,"file":"collections-BwO27pJg.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;AACT,KACE,EAAM,UAAU,MAAM,MAAM,SAAS,oCAErC,QAAO;CAGT,IAAM,IAAU,EAAM,SAAS,aAAa,IAAI;AAChD,QACE,EAAQ,SAAS,iBAAiB,IAAI,EAAQ,SAAS,iBAAiB;;AAiB5E,eAAsB,EACpB,GACA,GACA,IAAiB,GACgB;CACjC,IAAM,IAAQ,EAA0B;AACxC,KAAI;AAEF,SAAO;GAAE,YADU,MAAM,EAAG,YAAY,OAAO,EAAK;GAC/B,SAAS;GAAM;UAC7B,GAAO;AACd,MACE,CAAC,EAA+B,EAAyC,CAEzE,OAAM;AAIR,SAFA,EAAO,KAAK,eAAe,EAAK,4BAA4B,EAErD;GAAE,YADU,MAAM,EAAG,YAAY,OAAO,EAAK;GAC/B,SAAS;GAAO;;;AAIzC,SAAS,EACP,GACyB;CACzB,IAAM,IAAmC,EAAE;AAM3C,QALI,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;;AAOT,eAAsB,EACpB,GAMA,GACA,GACA,IAAiB,GACA;CACjB,IAAM,IAAqB,EAAE;AAE7B,MAAK,IAAM,KAAS,GAAS;EAC3B,IAAM,IAAU,EAAM,eAAe,QAAQ,MAAM,KAAK,EAClD,IAAM,MAAM,EAAG,YAAY,iBAAiB,SAAS,EAAQ,GAAG;AAKtE,MAJA,EAAO,KAAK,iCAAiC,EAAM,eAAe,GAAG,EACrE,MAAM,EAAG,YAAY,OAAO,EAAI,IAAI,EAAqB,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esContent":["import fs from \"node:fs\";\nimport type { ModifyOutcome } from \"../core/types\";\n\nexport interface EnvEdit {\n type: \"comment\" | \"var\";\n /** For \"comment\": the text after `# `. For \"var\": the KEY. */\n key: string;\n /** Only for \"var\" entries. */\n value?: string;\n}\n\nfunction appendEnvContent(existing: string, content: string): string {\n const withNewLine =\n !existing.length || existing.endsWith(\"\\n\") ? existing : existing + \"\\n\";\n return withNewLine + content + \"\\n\";\n}\n\nexport function applyEnvEdits(source: string, edits: EnvEdit[]): string {\n let next = source;\n for (const edit of edits) {\n if (edit.type === \"comment\") {\n const commented = `# ${edit.key}`;\n if (!next.includes(commented)) {\n next = appendEnvContent(next, commented);\n }\n continue;\n }\n if (!next.includes(`${edit.key}=`)) {\n next = appendEnvContent(next, `${edit.key}=${edit.value ?? \"\"}`);\n }\n }\n return next;\n}\n\nexport function modifyEnv(envPath: string, edits: EnvEdit[]): ModifyOutcome {\n const existing = fs.existsSync(envPath)\n ? fs.readFileSync(envPath, \"utf8\")\n : \"\";\n const next = applyEnvEdits(existing, edits);\n if (next === existing) {\n return { status: \"success\", changed: false };\n }\n fs.writeFileSync(envPath, next, \"utf8\");\n return { status: \"success\", changed: true };\n}\n\n/**\n * Remove lines matching the given edits from env source. Var edits remove the\n * exact `KEY=...` line (anchored, so `FOO` does not match `FOO_BAR`). Comment\n * edits remove the `# key` line only when it has become orphaned — i.e. the\n * next non-blank line is another comment, another orphaned block, or EOF.\n */\nexport function removeEnvEdits(source: string, edits: EnvEdit[]): string {\n const lines = source.split(\"\\n\");\n const keep: boolean[] = lines.map(() => true);\n\n for (const edit of edits) {\n if (edit.type !== \"var\") continue;\n for (let i = 0; i < lines.length; i++) {\n if (!keep[i]) continue;\n const line = lines[i];\n if (\n line === `${edit.key}=${edit.value ?? \"\"}` ||\n line.startsWith(`${edit.key}=`)\n ) {\n keep[i] = false;\n }\n }\n }\n\n for (const edit of edits) {\n if (edit.type !== \"comment\") continue;\n const target = `# ${edit.key}`;\n for (let i = 0; i < lines.length; i++) {\n if (!keep[i] || lines[i] !== target) continue;\n let j = i + 1;\n while (j < lines.length && (!keep[j] || lines[j].trim() === \"\")) j++;\n const nextIsComment = j >= lines.length || lines[j].startsWith(\"#\");\n if (nextIsComment) {\n keep[i] = false;\n }\n }\n }\n\n const result: string[] = [];\n let lastWasBlank = false;\n for (let i = 0; i < lines.length; i++) {\n if (!keep[i]) continue;\n const isBlank = lines[i].trim() === \"\";\n if (isBlank && lastWasBlank) continue;\n result.push(lines[i]);\n lastWasBlank = isBlank;\n }\n\n while (result.length > 0 && result[result.length - 1].trim() === \"\") {\n result.pop();\n }\n\n return result.length === 0 ? \"\" : result.join(\"\\n\") + \"\\n\";\n}\n\nexport function modifyEnvRemove(\n envPath: string,\n edits: EnvEdit[],\n): ModifyOutcome {\n const existing = fs.existsSync(envPath)\n ? fs.readFileSync(envPath, \"utf8\")\n : \"\";\n const next = removeEnvEdits(existing, edits);\n if (next === existing) {\n return { status: \"success\", changed: false };\n }\n fs.writeFileSync(envPath, next, \"utf8\");\n return { status: \"success\", changed: true };\n}\n"],"mappings":";;AAWA,SAAS,EAAiB,GAAkB,GAAyB;AAGnE,SADE,CAAC,EAAS,UAAU,EAAS,SAAS,KAAK,GAAG,IAAW,IAAW,QACjD,IAAU;;AAGjC,SAAgB,EAAc,GAAgB,GAA0B;CACtE,IAAI,IAAO;AACX,MAAK,IAAM,KAAQ,GAAO;AACxB,MAAI,EAAK,SAAS,WAAW;GAC3B,IAAM,IAAY,KAAK,EAAK;AAC5B,GAAK,EAAK,SAAS,EAAU,KAC3B,IAAO,EAAiB,GAAM,EAAU;AAE1C;;AAEF,EAAK,EAAK,SAAS,GAAG,EAAK,IAAI,GAAG,KAChC,IAAO,EAAiB,GAAM,GAAG,EAAK,IAAI,GAAG,EAAK,SAAS,KAAK;;AAGpE,QAAO;;AAGT,SAAgB,EAAU,GAAiB,GAAiC;CAC1E,IAAM,IAAW,EAAG,WAAW,EAAQ,GACnC,EAAG,aAAa,GAAS,O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,QAAO,EAAO,WAAW,IAAI,KAAK,EAAO,KAAK,KAAK,GAAG;;AAGxD,SAAgB,EACd,GACA,GACe;CACf,IAAM,IAAW,EAAG,WAAW,EAAQ,GACnC,EAAG,aAAa,GAAS,OAAO,GAChC,IACE,IAAO,EAAe,GAAU,EAAM;AAK5C,QAJI,MAAS,IACJ;EAAE,QAAQ;EAAW,SAAS;EAAO,IAE9C,EAAG,cAAc,GAAS,GAAM,OAAO,EAChC;EAAE,QAAQ;EAAW,SAAS;EAAM"}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { getCollections as e } from "@velastack/pocketbase/internal";
|
|
2
|
+
import t from "node:fs";
|
|
3
|
+
import n from "node:path";
|
|
4
|
+
import r from "node:process";
|
|
5
|
+
//#region src/parse/env.runtime.ts
|
|
6
|
+
function i(e) {
|
|
7
|
+
return t.existsSync(n.join(e, "package.json")) && t.existsSync(n.join(e, "src", "routes"));
|
|
8
|
+
}
|
|
9
|
+
function a(e = r.cwd()) {
|
|
10
|
+
let t = n.resolve(e);
|
|
11
|
+
for (;;) {
|
|
12
|
+
if (i(t)) return t;
|
|
13
|
+
let e = n.dirname(t);
|
|
14
|
+
if (e === t) break;
|
|
15
|
+
t = e;
|
|
16
|
+
}
|
|
17
|
+
throw Error(`Could not resolve project root from "${e}". Expected package.json and src/routes.`);
|
|
18
|
+
}
|
|
19
|
+
async function o() {
|
|
20
|
+
let t = a();
|
|
21
|
+
return e({
|
|
22
|
+
pocketbaseUrl: "",
|
|
23
|
+
superuserEmail: r.env.POCKETBASE_SUPERUSER_EMAIL,
|
|
24
|
+
superuserPassword: r.env.POCKETBASE_SUPERUSER_PASSWORD,
|
|
25
|
+
root: t
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
//#endregion
|
|
29
|
+
export { o as getCollections };
|
|
30
|
+
|
|
31
|
+
//# sourceMappingURL=env.runtime-D46GCIKe.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"env.runtime-D46GCIKe.js","names":[],"sources":["../../src/parse/env.runtime.ts"],"sourcesContent":["import { getCollections as getCollectionsFromPB } from \"@velastack/pocketbase/internal\";\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport process from \"node:process\";\nimport type { Collection } from \"./types\";\n\nfunction hasProjectMarkers(dir: string): boolean {\n return (\n fs.existsSync(path.join(dir, \"package.json\")) &&\n fs.existsSync(path.join(dir, \"src\", \"routes\"))\n );\n}\n\nexport function resolveProjectRoot(startDir = process.cwd()): string {\n let current = path.resolve(startDir);\n\n while (true) {\n if (hasProjectMarkers(current)) {\n return current;\n }\n\n const parent = path.dirname(current);\n if (parent === current) {\n break;\n }\n current = parent;\n }\n\n throw new Error(\n `Could not resolve project root from \"${startDir}\". Expected package.json and src/routes.`,\n );\n}\n\nexport async function getCollections(): Promise<Collection[]> {\n const root = resolveProjectRoot();\n\n return getCollectionsFromPB({\n pocketbaseUrl: \"\",\n superuserEmail: process.env.POCKETBASE_SUPERUSER_EMAIL!,\n superuserPassword: process.env.POCKETBASE_SUPERUSER_PASSWORD!,\n root,\n }) as Promise<Collection[]>;\n}\n"],"mappings":";;;;;AAMA,SAAS,EAAkB,GAAsB;AAC/C,QACE,EAAG,WAAW,EAAK,KAAK,GAAK,eAAe,CAAC,IAC7C,EAAG,WAAW,EAAK,KAAK,GAAK,OAAO,SAAS,CAAC;;AAIlD,SAAgB,EAAmB,IAAW,EAAQ,KAAK,EAAU;CACnE,IAAI,IAAU,EAAK,QAAQ,EAAS;AAEpC,UAAa;AACX,MAAI,EAAkB,EAAQ,CAC5B,QAAO;EAGT,IAAM,IAAS,EAAK,QAAQ,EAAQ;AACpC,MAAI,MAAW,EACb;AAEF,MAAU;;AAGZ,OAAU,MACR,wCAAwC,EAAS,0CAClD;;AAGH,eAAsB,IAAwC;CAC5D,IAAM,IAAO,GAAoB;AAEjC,QAAO,EAAqB;EAC1B,eAAe;EACf,gBAAgB,EAAQ,IAAI;EAC5B,mBAAmB,EAAQ,IAAI;EAC/B;EACD,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"generate.runtime-
|
|
1
|
+
{"version":3,"file":"generate.runtime-Bbf2YWaA.js","names":[],"sources":["../../src/patterns/disable/i18n/modifies/gitignore.ts","../../src/patterns/disable/i18n/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nexport function unmodifyGitignore(gitignorePath: string): ModifyOutcome {\n if (!fs.existsSync(gitignorePath)) {\n return { status: \"success\", changed: false };\n }\n\n const original = fs.readFileSync(gitignorePath, \"utf8\");\n if (!original.includes(\"src/locales/.wuchale\")) {\n return { status: \"success\", changed: false };\n }\n\n const lines = original.split(\"\\n\");\n const out: string[] = [];\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i];\n if (line === \"# Wuchale\") {\n let j = i + 1;\n let hasWuchale = false;\n while (j < lines.length && lines[j].trim() !== \"\") {\n if (lines[j] === \"src/locales/.wuchale\") {\n hasWuchale = true;\n }\n j++;\n }\n if (hasWuchale) {\n i = j;\n continue;\n }\n }\n if (line === \"src/locales/.wuchale\") continue;\n out.push(line);\n }\n\n let updated = out.join(\"\\n\");\n updated = updated.replace(/\\n{3,}/g, \"\\n\\n\");\n\n if (updated === original) {\n return { status: \"success\", changed: false };\n }\n\n fs.writeFileSync(gitignorePath, updated);\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 { unmodifyGitignore } from \"./modifies/gitignore\";\n\nconst MANUAL_REMEDIATION = [\n \"vite.config, svelte.config, hooks.server, app.html, and +layout.ts must be reverted manually.\",\n \"The i18n integration touches these files in ways that are not safely reversible by tooling.\",\n \"See the enable-i18n modifies for the blocks to remove.\",\n].join(\" \");\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 .gitignore\");\n const gitignorePath = path.join(options.root, \".gitignore\");\n pushResult(\n modifyOutcomeToFile(gitignorePath, unmodifyGitignore(gitignorePath)),\n );\n\n logger.info(MANUAL_REMEDIATION);\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":";;;;;AAGA,SAAgB,EAAkB,GAAsC;AACtE,KAAI,CAAC,EAAG,WAAW,EAAc,CAC/B,QAAO;EAAE,QAAQ;EAAW,SAAS;EAAO;CAG9C,IAAM,IAAW,EAAG,aAAa,GAAe,OAAO;AACvD,KAAI,CAAC,EAAS,SAAS,uBAAuB,CAC5C,QAAO;EAAE,QAAQ;EAAW,SAAS;EAAO;CAG9C,IAAM,IAAQ,EAAS,MAAM,KAAK,EAC5B,IAAgB,EAAE;AACxB,MAAK,IAAI,IAAI,GAAG,IAAI,EAAM,QAAQ,KAAK;EACrC,IAAM,IAAO,EAAM;AACnB,MAAI,MAAS,aAAa;GACxB,IAAI,IAAI,IAAI,GACR,IAAa;AACjB,UAAO,IAAI,EAAM,UAAU,EAAM,GAAG,MAAM,KAAK,IAI7C,CAHI,EAAM,OAAO,2BACf,IAAa,KAEf;AAEF,OAAI,GAAY;AACd,QAAI;AACJ;;;AAGA,QAAS,0BACb,EAAI,KAAK,EAAK;;CAGhB,IAAI,IAAU,EAAI,KAAK,KAAK;AAQ5B,QAPA,IAAU,EAAQ,QAAQ,WAAW,OAAO,EAExC,MAAY,IACP;EAAE,QAAQ;EAAW,SAAS;EAAO,IAG9C,EAAG,cAAc,GAAe,EAAQ,EACjC;EAAE,QAAQ;EAAW,SAAS;EAAM;;;;ACrC7C,IAAM,IAAqB;CACzB;CACA;CACA;CACD,CAAC,KAAK,IAAI;AAEX,eAAsB,EAAS,GAAkB;CAC/C,IAAM,IAAS,EAAU,EAAQ,EAC3B,IAAmB,EAAE,EACrB,KAAc,MAAsB;AACxC,EAAI,KAAM,EAAS,KAAK,EAAK;;AAG/B,GAAO,KAAK,uBAAuB;CACnC,IAAM,IAAgB,EAAK,KAAK,EAAQ,MAAM,aAAa;AAO3D,QANA,EACE,EAAoB,GAAe,EAAkB,EAAc,CAAC,CACrE,EAED,EAAO,KAAK,EAAmB,EAExB;EACL,SAAS,EAAE;EACX;EACA,SAAS,EAAE;EACX,YAAY,EAAE;EACd,UAAU,EAAE;EACZ,aAAa,EAAE;EACf,mBAAmB,EAAE;EACrB,iBAAiB,EAAE;EACpB"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { n as e } from "./logger-BpgCb-ZG.js";
|
|
2
|
-
import { t } from "./shared-
|
|
2
|
+
import { t } from "./shared-C4wJ9sb0.js";
|
|
3
3
|
import { modifyOutcomeToFile as n } from "./modify-file-DE7tPADZ.js";
|
|
4
4
|
import { i as r, o as i } from "./ts-morph-helpers-bR0-x04t.js";
|
|
5
5
|
import a from "node:fs";
|
|
@@ -57,4 +57,4 @@ async function l(r) {
|
|
|
57
57
|
//#endregion
|
|
58
58
|
export { l as generate };
|
|
59
59
|
|
|
60
|
-
//# sourceMappingURL=generate.runtime-
|
|
60
|
+
//# sourceMappingURL=generate.runtime-BkvtIjgh.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"generate.runtime-
|
|
1
|
+
{"version":3,"file":"generate.runtime-BkvtIjgh.js","names":[],"sources":["../../src/patterns/disable/teams/modifies/modify-nav-user.ts","../../src/patterns/disable/teams/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(\"/teams\")) {\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 \"Teams\",\n \"@lucide/svelte/icons/users\",\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 fs from \"node:fs\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { unmodifyNavUser } from \"./modifies/modify-nav-user\";\nimport { planDropsForCollections } from \"../../destroy/shared\";\n\nconst MANUAL_REMEDIATION = [\n \"app-sidebar, +layout.server.ts (teams loader), and app-layout.svelte (AppSidebar team props) must be reverted manually.\",\n \"These edits are substantial and are not safely reversed by tooling.\",\n].join(\" \");\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 nav-user.svelte\");\n const navUserCandidates = [\n path.join(options.root, \"src\", \"lib\", \"components\", \"nav-user.svelte\"),\n ];\n const navUserPath =\n navUserCandidates.find((p) => fs.existsSync(p)) ?? navUserCandidates[0];\n pushResult(modifyOutcomeToFile(navUserPath, unmodifyNavUser(navUserPath)));\n\n logger.info(MANUAL_REMEDIATION);\n\n const collectionDrops = await planDropsForCollections(\n [\"team_invite_links\", \"team_invites\", \"team_memberships\", \"teams\"],\n options,\n );\n\n return {\n creates: [],\n modifies,\n deletes: [],\n components: [],\n packages: [],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EACd,UAAU,EAAE;EACZ,aAAa,EAAE;EACf,mBAAmB,EAAE;EACrB,iBAbsB,MAAM,EAC5B;GAAC;GAAqB;GAAgB;GAAoB;GAAQ,EAClE,EACD;EAWA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"generate.runtime-VhD6Bmgq.js","names":[],"sources":["../../src/patterns/disable/content-negotiation/modifies/hooks.server.ts","../../src/patterns/disable/content-negotiation/modifies/hooks.ts","../../src/patterns/disable/content-negotiation/modifies/root-layout.svelte.ts","../../src/patterns/disable/content-negotiation/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport { Project, QuoteKind, SyntaxKind, type SourceFile } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nfunction removeNegotiateImport(sourceFile: SourceFile): boolean {\n const decl = sourceFile\n .getImportDeclarations()\n .find((d) => d.getModuleSpecifierValue() === \"$lib/negotiate\");\n if (!decl) return false;\n\n const named = decl.getNamedImports().find((ni) => {\n return (\n ni.getName() === \"handle\" &&\n ni.getAliasNode()?.getText() === \"handleNegotiate\"\n );\n });\n\n if (!named) return false;\n\n if (decl.getNamedImports().length === 1 && !decl.getDefaultImport()) {\n decl.remove();\n } else {\n named.remove();\n }\n return true;\n}\n\nfunction removeSequenceImportIfUnused(sourceFile: SourceFile): void {\n const decl = sourceFile\n .getImportDeclarations()\n .find((d) => d.getModuleSpecifierValue() === \"@sveltejs/kit/hooks\");\n if (!decl) return;\n\n const stillReferenced = sourceFile\n .getDescendantsOfKind(SyntaxKind.Identifier)\n .some((id) => {\n if (id.getText() !== \"sequence\") return false;\n const parent = id.getParent();\n const kind = parent?.getKind();\n return (\n kind !== SyntaxKind.ImportSpecifier && kind !== SyntaxKind.ImportClause\n );\n });\n\n if (stillReferenced) return;\n\n const named = decl\n .getNamedImports()\n .find((ni) => ni.getName() === \"sequence\");\n if (!named) return;\n\n if (decl.getNamedImports().length === 1 && !decl.getDefaultImport()) {\n decl.remove();\n } else {\n named.remove();\n }\n}\n\nexport function unmodifyHooksServerNegotiate(\n hooksServerPath: string,\n): ModifyOutcome {\n if (!fs.existsSync(hooksServerPath)) {\n return { status: \"success\", changed: false };\n }\n\n const original = fs.readFileSync(hooksServerPath, \"utf8\");\n if (!original.includes(\"handleNegotiate\")) {\n return { status: \"success\", changed: false };\n }\n\n const project = new Project({\n compilerOptions: { allowJs: true },\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n const sourceFile = project.addSourceFileAtPath(hooksServerPath);\n\n const handleDecl = sourceFile.getVariableDeclaration(\"handle\");\n if (!handleDecl) {\n removeNegotiateImport(sourceFile);\n removeSequenceImportIfUnused(sourceFile);\n sourceFile.formatText();\n sourceFile.saveSync();\n return {\n status: \"success\",\n changed: sourceFile.getFullText() !== original,\n };\n }\n\n const init = handleDecl.getInitializer();\n if (init?.getKind() === SyntaxKind.CallExpression) {\n const call = init.asKindOrThrow(SyntaxKind.CallExpression);\n if (call.getExpression().getText() === \"sequence\") {\n const args = call.getArguments();\n const idx = args.findIndex((arg) => arg.getText() === \"handleNegotiate\");\n if (idx >= 0) {\n if (args.length === 2) {\n const keepText = args[idx === 0 ? 1 : 0].getText();\n handleDecl.setInitializer(keepText);\n } else {\n call.removeArgument(idx);\n }\n }\n }\n }\n\n removeNegotiateImport(sourceFile);\n removeSequenceImportIfUnused(sourceFile);\n sourceFile.formatText();\n sourceFile.saveSync();\n\n return {\n status: \"success\",\n changed: sourceFile.getFullText() !== original,\n };\n}\n","import fs from \"node:fs\";\nimport { Project, QuoteKind, SyntaxKind, type SourceFile } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nfunction removeNegotiateImport(sourceFile: SourceFile): boolean {\n const decl = sourceFile\n .getImportDeclarations()\n .find((d) => d.getModuleSpecifierValue() === \"$lib/negotiate\");\n if (!decl) return false;\n\n const named = decl.getNamedImports().find((ni) => {\n return (\n ni.getName() === \"reroute\" &&\n ni.getAliasNode()?.getText() === \"negotiateReroute\"\n );\n });\n if (!named) return false;\n\n if (decl.getNamedImports().length === 1 && !decl.getDefaultImport()) {\n decl.remove();\n } else {\n named.remove();\n }\n return true;\n}\n\nfunction isMeaningfullyEmpty(sourceFile: SourceFile): boolean {\n return sourceFile\n .getStatements()\n .every((s) => s.getKind() === SyntaxKind.EmptyStatement);\n}\n\nexport function unmodifyHooksNegotiate(hooksPath: string): ModifyOutcome {\n if (!fs.existsSync(hooksPath)) {\n return { status: \"success\", changed: false };\n }\n\n const original = fs.readFileSync(hooksPath, \"utf8\");\n if (!original.includes(\"negotiateReroute\")) {\n return { status: \"success\", changed: false };\n }\n\n const project = new Project({\n compilerOptions: { allowJs: true },\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n const sourceFile = project.addSourceFileAtPath(hooksPath);\n\n const rerouteDecl = sourceFile.getVariableDeclaration(\"reroute\");\n const init = rerouteDecl?.getInitializer();\n const initText = init?.getText() ?? \"\";\n\n const hasI18nHelper = sourceFile\n .getVariableDeclarations()\n .some((d) => d.getName() === \"rerouteDeLocalize\");\n\n if (\n rerouteDecl &&\n hasI18nHelper &&\n initText.includes(\"rerouteDeLocalize\") &&\n initText.includes(\"negotiateReroute\")\n ) {\n rerouteDecl.setInitializer(\"({ url }) => rerouteDeLocalize(url.pathname)\");\n } else if (rerouteDecl && initText.includes(\"negotiateReroute\")) {\n const stmt = rerouteDecl.getFirstAncestorByKind(\n SyntaxKind.VariableStatement,\n );\n stmt?.remove();\n }\n\n removeNegotiateImport(sourceFile);\n\n if (isMeaningfullyEmpty(sourceFile)) {\n fs.rmSync(hooksPath, { force: true });\n return { status: \"success\", changed: true };\n }\n\n sourceFile.formatText();\n sourceFile.saveSync();\n return {\n status: \"success\",\n changed: sourceFile.getFullText() !== original,\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 unmodifyRootLayoutNegotiate(layoutPath: string): ModifyOutcome {\n if (!fs.existsSync(layoutPath)) {\n return { status: \"success\", changed: false };\n }\n\n const file = SvelteFile.fromPath(layoutPath);\n const hasElement = file.hasElement(\"Negotiate\");\n\n file.modifyScript((source) => {\n const { source: out } = withInMemoryScript(source, (sf) => {\n removeImportByModuleSpecifier(sf, \"$lib/negotiate\");\n });\n return out;\n });\n\n if (hasElement) {\n file.removeElement(\"Negotiate\");\n }\n\n file.writeTo(layoutPath);\n return { status: \"success\", changed: file.hasChanged() };\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 { unmodifyHooksServerNegotiate } from \"./modifies/hooks.server\";\nimport { unmodifyHooksNegotiate } from \"./modifies/hooks\";\nimport { unmodifyRootLayoutNegotiate } from \"./modifies/root-layout.svelte\";\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(\n hooksServerPath,\n unmodifyHooksServerNegotiate(hooksServerPath),\n ),\n );\n\n logger.info(\"Reverting hooks.ts\");\n const hooksPath = path.join(options.root, \"src\", \"hooks.ts\");\n pushResult(modifyOutcomeToFile(hooksPath, unmodifyHooksNegotiate(hooksPath)));\n\n logger.info(\"Reverting src/routes/+layout.svelte\");\n const rootLayoutPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"+layout.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(\n rootLayoutPath,\n unmodifyRootLayoutNegotiate(rootLayoutPath),\n ),\n );\n\n return {\n creates: [],\n modifies,\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n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,EAEE,KACF,EAAK,cAAc,YAAY,EAGjC,EAAK,QAAQ,EAAW,EACjB;EAAE,QAAQ;EAAW,SAAS,EAAK,YAAY;EAAE;;;;ACpB1D,eAAsB,EAAS,GAAkB;CAC/C,IAAM,IAAS,EAAU,EAAQ,EAC3B,IAAmB,EAAE,EACrB,KAAc,MAAsB;AACxC,EAAI,KAAM,EAAS,KAAK,EAAK;;AAG/B,GAAO,KAAK,4BAA4B;CACxC,IAAM,IAAkB,EAAK,KAAK,EAAQ,MAAM,OAAO,kBAAkB;AAQzE,CAPA,EACE,EACE,GACA,EAA6B,EAAgB,CAC9C,CACF,EAED,EAAO,KAAK,qBAAqB;CACjC,IAAM,IAAY,EAAK,KAAK,EAAQ,MAAM,OAAO,WAAW;AAG5D,CAFA,EAAW,EAAoB,GAAW,EAAuB,EAAU,CAAC,CAAC,EAE7E,EAAO,KAAK,sCAAsC;CAClD,IAAM,IAAiB,EAAK,KAC1B,EAAQ,MACR,OACA,UACA,iBACD;AAQD,QAPA,EACE,EACE,GACA,EAA4B,EAAe,CAC5C,CACF,EAEM;EACL,SAAS,EAAE;EACX;EACA,SAAS,EAAE;EACX,YAAY,EAAE;EACd,UAAU,EAAE;EACZ,aAAa,EAAE;EACf,mBAAmB,EAAE;EACrB,iBAAiB,EAAE;EACpB"}
|
|
1
|
+
{"version":3,"file":"generate.runtime-BnkNmF1g.js","names":[],"sources":["../../src/patterns/disable/content-negotiation/modifies/hooks.server.ts","../../src/patterns/disable/content-negotiation/modifies/hooks.ts","../../src/patterns/disable/content-negotiation/modifies/root-layout.svelte.ts","../../src/patterns/disable/content-negotiation/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport { Project, QuoteKind, SyntaxKind, type SourceFile } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nfunction removeNegotiateImport(sourceFile: SourceFile): boolean {\n const decl = sourceFile\n .getImportDeclarations()\n .find((d) => d.getModuleSpecifierValue() === \"$lib/negotiate\");\n if (!decl) return false;\n\n const named = decl.getNamedImports().find((ni) => {\n return (\n ni.getName() === \"handle\" &&\n ni.getAliasNode()?.getText() === \"handleNegotiate\"\n );\n });\n\n if (!named) return false;\n\n if (decl.getNamedImports().length === 1 && !decl.getDefaultImport()) {\n decl.remove();\n } else {\n named.remove();\n }\n return true;\n}\n\nfunction removeSequenceImportIfUnused(sourceFile: SourceFile): void {\n const decl = sourceFile\n .getImportDeclarations()\n .find((d) => d.getModuleSpecifierValue() === \"@sveltejs/kit/hooks\");\n if (!decl) return;\n\n const stillReferenced = sourceFile\n .getDescendantsOfKind(SyntaxKind.Identifier)\n .some((id) => {\n if (id.getText() !== \"sequence\") return false;\n const parent = id.getParent();\n const kind = parent?.getKind();\n return (\n kind !== SyntaxKind.ImportSpecifier && kind !== SyntaxKind.ImportClause\n );\n });\n\n if (stillReferenced) return;\n\n const named = decl\n .getNamedImports()\n .find((ni) => ni.getName() === \"sequence\");\n if (!named) return;\n\n if (decl.getNamedImports().length === 1 && !decl.getDefaultImport()) {\n decl.remove();\n } else {\n named.remove();\n }\n}\n\nexport function unmodifyHooksServerNegotiate(\n hooksServerPath: string,\n): ModifyOutcome {\n if (!fs.existsSync(hooksServerPath)) {\n return { status: \"success\", changed: false };\n }\n\n const original = fs.readFileSync(hooksServerPath, \"utf8\");\n if (!original.includes(\"handleNegotiate\")) {\n return { status: \"success\", changed: false };\n }\n\n const project = new Project({\n compilerOptions: { allowJs: true },\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n const sourceFile = project.addSourceFileAtPath(hooksServerPath);\n\n const handleDecl = sourceFile.getVariableDeclaration(\"handle\");\n if (!handleDecl) {\n removeNegotiateImport(sourceFile);\n removeSequenceImportIfUnused(sourceFile);\n sourceFile.formatText();\n sourceFile.saveSync();\n return {\n status: \"success\",\n changed: sourceFile.getFullText() !== original,\n };\n }\n\n const init = handleDecl.getInitializer();\n if (init?.getKind() === SyntaxKind.CallExpression) {\n const call = init.asKindOrThrow(SyntaxKind.CallExpression);\n if (call.getExpression().getText() === \"sequence\") {\n const args = call.getArguments();\n const idx = args.findIndex((arg) => arg.getText() === \"handleNegotiate\");\n if (idx >= 0) {\n if (args.length === 2) {\n const keepText = args[idx === 0 ? 1 : 0].getText();\n handleDecl.setInitializer(keepText);\n } else {\n call.removeArgument(idx);\n }\n }\n }\n }\n\n removeNegotiateImport(sourceFile);\n removeSequenceImportIfUnused(sourceFile);\n sourceFile.formatText();\n sourceFile.saveSync();\n\n return {\n status: \"success\",\n changed: sourceFile.getFullText() !== original,\n };\n}\n","import fs from \"node:fs\";\nimport { Project, QuoteKind, SyntaxKind, type SourceFile } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nfunction removeNegotiateImport(sourceFile: SourceFile): boolean {\n const decl = sourceFile\n .getImportDeclarations()\n .find((d) => d.getModuleSpecifierValue() === \"$lib/negotiate\");\n if (!decl) return false;\n\n const named = decl.getNamedImports().find((ni) => {\n return (\n ni.getName() === \"reroute\" &&\n ni.getAliasNode()?.getText() === \"negotiateReroute\"\n );\n });\n if (!named) return false;\n\n if (decl.getNamedImports().length === 1 && !decl.getDefaultImport()) {\n decl.remove();\n } else {\n named.remove();\n }\n return true;\n}\n\nfunction isMeaningfullyEmpty(sourceFile: SourceFile): boolean {\n return sourceFile\n .getStatements()\n .every((s) => s.getKind() === SyntaxKind.EmptyStatement);\n}\n\nexport function unmodifyHooksNegotiate(hooksPath: string): ModifyOutcome {\n if (!fs.existsSync(hooksPath)) {\n return { status: \"success\", changed: false };\n }\n\n const original = fs.readFileSync(hooksPath, \"utf8\");\n if (!original.includes(\"negotiateReroute\")) {\n return { status: \"success\", changed: false };\n }\n\n const project = new Project({\n compilerOptions: { allowJs: true },\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n const sourceFile = project.addSourceFileAtPath(hooksPath);\n\n const rerouteDecl = sourceFile.getVariableDeclaration(\"reroute\");\n const init = rerouteDecl?.getInitializer();\n const initText = init?.getText() ?? \"\";\n\n const hasI18nHelper = sourceFile\n .getVariableDeclarations()\n .some((d) => d.getName() === \"rerouteDeLocalize\");\n\n if (\n rerouteDecl &&\n hasI18nHelper &&\n initText.includes(\"rerouteDeLocalize\") &&\n initText.includes(\"negotiateReroute\")\n ) {\n rerouteDecl.setInitializer(\"({ url }) => rerouteDeLocalize(url.pathname)\");\n } else if (rerouteDecl && initText.includes(\"negotiateReroute\")) {\n const stmt = rerouteDecl.getFirstAncestorByKind(\n SyntaxKind.VariableStatement,\n );\n stmt?.remove();\n }\n\n removeNegotiateImport(sourceFile);\n\n if (isMeaningfullyEmpty(sourceFile)) {\n fs.rmSync(hooksPath, { force: true });\n return { status: \"success\", changed: true };\n }\n\n sourceFile.formatText();\n sourceFile.saveSync();\n return {\n status: \"success\",\n changed: sourceFile.getFullText() !== original,\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 unmodifyRootLayoutNegotiate(layoutPath: string): ModifyOutcome {\n if (!fs.existsSync(layoutPath)) {\n return { status: \"success\", changed: false };\n }\n\n const file = SvelteFile.fromPath(layoutPath);\n const hasElement = file.hasElement(\"Negotiate\");\n\n file.modifyScript((source) => {\n const { source: out } = withInMemoryScript(source, (sf) => {\n removeImportByModuleSpecifier(sf, \"$lib/negotiate\");\n });\n return out;\n });\n\n if (hasElement) {\n file.removeElement(\"Negotiate\");\n }\n\n file.writeTo(layoutPath);\n return { status: \"success\", changed: file.hasChanged() };\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 { unmodifyHooksServerNegotiate } from \"./modifies/hooks.server\";\nimport { unmodifyHooksNegotiate } from \"./modifies/hooks\";\nimport { unmodifyRootLayoutNegotiate } from \"./modifies/root-layout.svelte\";\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(\n hooksServerPath,\n unmodifyHooksServerNegotiate(hooksServerPath),\n ),\n );\n\n logger.info(\"Reverting hooks.ts\");\n const hooksPath = path.join(options.root, \"src\", \"hooks.ts\");\n pushResult(modifyOutcomeToFile(hooksPath, unmodifyHooksNegotiate(hooksPath)));\n\n logger.info(\"Reverting src/routes/+layout.svelte\");\n const rootLayoutPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"+layout.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(\n rootLayoutPath,\n unmodifyRootLayoutNegotiate(rootLayoutPath),\n ),\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,SAAS,EAAsB,GAAiC;CAC9D,IAAM,IAAO,EACV,uBAAuB,CACvB,MAAM,MAAM,EAAE,yBAAyB,KAAK,iBAAiB;AAChE,KAAI,CAAC,EAAM,QAAO;CAElB,IAAM,IAAQ,EAAK,iBAAiB,CAAC,MAAM,MAEvC,EAAG,SAAS,KAAK,YACjB,EAAG,cAAc,EAAE,SAAS,KAAK,kBAEnC;AASF,QAPK,KAED,EAAK,iBAAiB,CAAC,WAAW,KAAK,CAAC,EAAK,kBAAkB,GACjE,EAAK,QAAQ,GAEb,EAAM,QAAQ,EAET,MAPY;;AAUrB,SAAS,EAA6B,GAA8B;CAClE,IAAM,IAAO,EACV,uBAAuB,CACvB,MAAM,MAAM,EAAE,yBAAyB,KAAK,sBAAsB;AAcrE,KAbI,CAAC,KAEmB,EACrB,qBAAqB,EAAW,WAAW,CAC3C,MAAM,MAAO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KAC1B,EAAQ,MACR,OACA,UACA,iBACD;AAQD,QAPA,EACE,EACE,GACA,EAA4B,EAAe,CAC5C,CACF,EAEM;EACL,SAAS,EAAE;EACX;EACA,SAAS,EAAE;EACX,YAAY,EAAE;EACd,UAAU,EAAE;EACZ,aAAa,EAAE;EACf,mBAAmB,EAAE;EACrB,iBAAiB,EAAE;EACpB"}
|
|
@@ -4,9 +4,9 @@ import { n } from "./logger-BpgCb-ZG.js";
|
|
|
4
4
|
import { t as r } from "./pocketbase-Dm2SF3vM.js";
|
|
5
5
|
import { modifyOutcomeToFile as i } from "./modify-file-DE7tPADZ.js";
|
|
6
6
|
import { a, n as o, o as s } from "./ts-morph-helpers-bR0-x04t.js";
|
|
7
|
-
import { t as c } from "./modify-utils-
|
|
8
|
-
import { getMigrationFile as l, migrationDelay as u, withPocketbase as d } from "./pocketbase-
|
|
9
|
-
import { applyCollectionRulePatches as f, createCollectionIdempotent as p } from "./collections-
|
|
7
|
+
import { t as c } from "./modify-utils-CZ9Auvp9.js";
|
|
8
|
+
import { getMigrationFile as l, migrationDelay as u, withPocketbase as d } from "./pocketbase-D7GjPuNu.js";
|
|
9
|
+
import { applyCollectionRulePatches as f, createCollectionIdempotent as p } from "./collections-BwO27pJg.js";
|
|
10
10
|
import m from "node:fs";
|
|
11
11
|
import h from "node:path";
|
|
12
12
|
import { Project as g, SyntaxKind as _ } from "ts-morph";
|
|
@@ -286,4 +286,4 @@ async function O(e) {
|
|
|
286
286
|
//#endregion
|
|
287
287
|
export { O as generate };
|
|
288
288
|
|
|
289
|
-
//# sourceMappingURL=generate.runtime-
|
|
289
|
+
//# sourceMappingURL=generate.runtime-Bpx69a8t.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"generate.runtime-RfPLo7XV.js","names":[],"sources":["../../src/patterns/enable/notifications/modifies/modify-app-layout.ts","../../src/patterns/enable/notifications/modifies/+layout.server.ts","../../src/patterns/enable/notifications/generate.runtime.ts"],"sourcesContent":["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 BELL_SNIPPET = `\n\t\t<div class=\"ml-auto px-4\">\n\t\t\t<NotificationsBell />\n\t\t</div>\n\t`;\n\nconst IMPORT_SNIPPET = dedent`\n import NotificationsBell from '$lib/components/notifications-bell.svelte';\n`;\n\nconst FAILURE_HINT = [\n \"Add the notifications bell inside the (app) layout's <header>.\",\n \"\",\n \"Imports to add to the <script> tag:\",\n \"\",\n IMPORT_SNIPPET,\n \"\",\n \"Markup to add inside <header>:\",\n BELL_SNIPPET,\n].join(\"\\n\");\n\nconst NOT_FOUND_HINT = [\n \"Create src/routes/(app)/+layout.svelte with a <header> that includes the bell.\",\n \"\",\n \"Imports for the <script> tag:\",\n \"\",\n IMPORT_SNIPPET,\n \"\",\n \"Markup inside <header>:\",\n BELL_SNIPPET,\n].join(\"\\n\");\n\nexport function modifyAppLayout(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(\"header\")) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n if (file.hasElement(\"NotificationsBell\")) {\n return { status: \"success\", changed: false };\n }\n\n file.modifyScript((source) => {\n const { source: out } = withInMemoryScript(source, (sf) => {\n ensureImports(sf, [\n {\n defaultImport: \"NotificationsBell\",\n moduleSpecifier: \"$lib/components/notifications-bell.svelte\",\n },\n ]);\n });\n return out;\n });\n\n file.insertBeforeClosingTag(\"header\", BELL_SNIPPET);\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 FETCH_STATEMENT = dedent`\n const notificationsList = await locals.pb\n .collection(\"notifications\")\n .getList(1, 5, {\n filter: \\`user = \"\\${locals.pb.authStore.record!.id}\" && read = false\\`,\n sort: \"-created\",\n });\n`;\n\nconst NOTIFICATIONS_STATEMENT =\n \"const notifications = { count: notificationsList.totalItems, items: notificationsList.items };\";\n\nconst DEPENDS_STATEMENT = 'depends(\"app:notifications\");';\n\nexport function modifyLayoutServer(layoutServerPath: string): ModifyOutcome {\n if (!fs.existsSync(layoutServerPath)) {\n const snippet = dedent`\n export const load = async ({ locals, depends }) => {\n ${FETCH_STATEMENT}\n ${NOTIFICATIONS_STATEMENT}\n ${DEPENDS_STATEMENT}\n return { notifications };\n };\n `;\n fs.writeFileSync(layoutServerPath, snippet);\n return { status: \"success\", changed: true };\n }\n\n const originalSource = fs.readFileSync(layoutServerPath, \"utf8\");\n const project = new Project();\n const sourceFile = project.addSourceFileAtPath(layoutServerPath);\n\n const addProperty = (\n obj: import(\"ts-morph\").ObjectLiteralExpression,\n name: string,\n initializer: string,\n ) => {\n if (obj.getProperty(name)) return;\n if (name === initializer) {\n obj.addShorthandPropertyAssignment({ name });\n } else {\n obj.addPropertyAssignment({ name, initializer });\n }\n };\n\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 if (vs?.hasExportKeyword()) {\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) loadFn = innerFnExpr;\n }\n }\n }\n }\n }\n\n if (!loadArrow && !loadFn) {\n const maybeFn = sourceFile.getFunction(\"load\");\n if (maybeFn && maybeFn.isExported()) loadFn = maybeFn;\n }\n\n if (!loadArrow && !loadFn) {\n sourceFile.addFunction({\n isExported: true,\n isAsync: true,\n name: \"load\",\n parameters: [{ name: \"{ locals, depends }\" }],\n statements: [\n FETCH_STATEMENT,\n NOTIFICATIONS_STATEMENT,\n DEPENDS_STATEMENT,\n \"return { notifications };\",\n ],\n });\n sourceFile.formatText();\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n }\n\n const fnLike = (loadArrow ?? loadFn!) as\n | import(\"ts-morph\").ArrowFunction\n | import(\"ts-morph\").FunctionDeclaration\n | import(\"ts-morph\").FunctionExpression;\n\n // Ensure first param destructures { locals, depends }\n const params = fnLike.getParameters();\n if (params.length === 0) {\n fnLike.insertParameter(0, { name: \"{ locals, depends }\" });\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 elementNames = obp.getElements().map((el) => el.getName());\n const hasDepends = elementNames.includes(\"depends\");\n const hasLocals = elementNames.includes(\"locals\");\n\n if (!hasDepends || !hasLocals) {\n const existingParts = obp\n .getElements()\n .map((el) => el.getText())\n .filter(Boolean);\n const parts: string[] = hasLocals ? [] : [\"locals\"];\n parts.push(...existingParts);\n if (!hasDepends) parts.push(\"depends\");\n first.set({\n name: `{ ${parts.join(\", \")} }`,\n type: original.type,\n initializer: (original as { initializer?: string }).initializer,\n });\n }\n } else {\n const currentName = first.getName();\n if (currentName !== \"locals\") {\n first.set({\n name: `{ locals, depends, ...${currentName} }`,\n type: original.type,\n initializer: (original as { initializer?: string }).initializer,\n });\n } else {\n first.set({\n name: `{ locals, depends }`,\n type: original.type,\n initializer: (original as { initializer?: string }).initializer,\n });\n }\n }\n }\n\n if (loadArrow && !loadArrow.isAsync()) loadArrow.setIsAsync(true);\n else if (loadFn && !loadFn.isAsync()) loadFn.setIsAsync(true);\n\n const body = fnLike.getBody();\n if (body && body.getKind() === SyntaxKind.Block) {\n const blockBody = body as import(\"ts-morph\").Block;\n const statements = blockBody.getStatements();\n\n const declaresVar = (name: string) =>\n statements.some((stmt) => {\n if (stmt.getKind() !== SyntaxKind.VariableStatement) return false;\n return (stmt as import(\"ts-morph\").VariableStatement)\n .getDeclarations()\n .some((d) => d.getName() === name);\n });\n\n const hasDependsCall = statements.some(\n (stmt) =>\n stmt.getKind() === SyntaxKind.ExpressionStatement &&\n stmt.getDescendantsOfKind(SyntaxKind.CallExpression).some((ce) => {\n if (ce.getExpression().getText() !== \"depends\") return false;\n const args = ce.getArguments();\n const argText = args[0]?.getText() ?? \"\";\n return (\n args.length === 1 &&\n (argText === \"'app:notifications'\" ||\n argText === '\"app:notifications\"')\n );\n }),\n );\n\n const hasNotificationsList = declaresVar(\"notificationsList\");\n const hasNotifications = declaresVar(\"notifications\");\n\n const returnIdx = statements.findIndex(\n (s) => s.getKind() === SyntaxKind.ReturnStatement,\n );\n let insertAt = returnIdx >= 0 ? returnIdx : statements.length;\n\n if (!hasNotificationsList) {\n blockBody.insertStatements(insertAt, FETCH_STATEMENT);\n insertAt++;\n }\n if (!hasNotifications) {\n blockBody.insertStatements(insertAt, NOTIFICATIONS_STATEMENT);\n insertAt++;\n }\n if (!hasDependsCall) {\n blockBody.insertStatements(insertAt, DEPENDS_STATEMENT);\n }\n }\n\n const augmentReturnObject = (\n obj: import(\"ts-morph\").ObjectLiteralExpression,\n ) => {\n addProperty(obj, \"notifications\", \"notifications\");\n };\n\n const augmentReturns = (target: import(\"ts-morph\").Node) => {\n const returns = target.getDescendantsOfKind(SyntaxKind.ReturnStatement);\n returns.forEach((ret) => {\n const expr = ret.getExpression();\n if (!expr) return;\n if (expr.getKind() === SyntaxKind.ObjectLiteralExpression) {\n augmentReturnObject(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 augmentReturnObject(\n inner as import(\"ts-morph\").ObjectLiteralExpression,\n );\n }\n }\n });\n };\n\n if (loadArrow) {\n const arrowBody = loadArrow.getBody();\n if (arrowBody.getKind() === SyntaxKind.Block) {\n augmentReturns(arrowBody);\n } else {\n const bodyExpr = arrowBody 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 augmentReturnObject(\n inner as import(\"ts-morph\").ObjectLiteralExpression,\n );\n }\n } else if (bodyExpr.getKind() === SyntaxKind.ObjectLiteralExpression) {\n augmentReturnObject(\n bodyExpr as import(\"ts-morph\").ObjectLiteralExpression,\n );\n }\n }\n } else if (loadFn) {\n const fnBody = loadFn.getBody();\n if (fnBody) augmentReturns(fnBody);\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 path from \"node:path\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport { languageFromPath } from \"../../../core/util\";\nimport {\n applyCollectionRulePatches,\n createCollectionIdempotent,\n} from \"../../../runtime/collections\";\nimport {\n getMigrationFile,\n migrationDelay,\n withPocketbase,\n} from \"../../../runtime/pocketbase\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { modifyUtils } from \"../../../runtime/modify-utils\";\nimport { modifyAppLayout } from \"./modifies/modify-app-layout\";\nimport { modifyLayoutServer } from \"./modifies/+layout.server\";\nimport { NOTIFICATION_RULE_PATCHES } from \"./runtime/pocketbase\";\n\nasync function pushMigrationCreates(\n creates: File[],\n collectionName: string,\n options: Options,\n created = true,\n) {\n if (!created) return;\n await migrationDelay();\n const migrationFile = getMigrationFile(collectionName, \"created\", options);\n if (!migrationFile) return;\n creates.push({\n path: migrationFile,\n language: languageFromPath(migrationFile),\n content: fs.readFileSync(migrationFile, \"utf8\"),\n status: \"success\",\n });\n}\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const creates: File[] = [];\n\n await withPocketbase(options.root, async (pb) => {\n const userCollection = await pb.collections.getOne(\"users\");\n const create = (spec: Parameters<typeof createCollectionIdempotent>[1]) =>\n createCollectionIdempotent(pb, spec, logger);\n\n logger.info(\"Creating notifications collection\");\n const result = await create({\n name: \"notifications\",\n type: \"base\",\n fields: [\n {\n name: \"id\",\n type: \"text\",\n primaryKey: true,\n autogeneratePattern: \"[a-z0-9]{15}\",\n max: 15,\n min: 15,\n pattern: \"^[a-z0-9]+$\",\n required: true,\n },\n {\n name: \"user\",\n type: \"relation\",\n cascadeDelete: true,\n collectionId: userCollection.id,\n maxSelect: 1,\n minSelect: 0,\n required: true,\n },\n {\n name: \"title\",\n type: \"text\",\n required: true,\n },\n {\n name: \"body\",\n type: \"text\",\n },\n {\n name: \"read\",\n type: \"bool\",\n },\n {\n name: \"created\",\n type: \"autodate\",\n onCreate: true,\n onUpdate: false,\n },\n {\n name: \"updated\",\n type: \"autodate\",\n onCreate: true,\n onUpdate: true,\n },\n ],\n indexes: [\n \"CREATE INDEX `idx_notifications_user_read_created` ON `notifications` (`user`, `read`, `created` DESC)\",\n ],\n });\n await pushMigrationCreates(\n creates,\n \"notifications\",\n options,\n result.created,\n );\n\n logger.info(\"Applying notifications rule patches\");\n const ruleMigrations = await applyCollectionRulePatches(\n pb,\n NOTIFICATION_RULE_PATCHES,\n options,\n logger,\n );\n creates.push(...ruleMigrations);\n });\n\n const modifies: File[] = [];\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n logger.info(\"Modifying (app) +layout.svelte\");\n const appLayoutPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(app)\",\n \"+layout.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(appLayoutPath, modifyAppLayout(appLayoutPath)),\n );\n\n logger.info(\"Modifying (app) +layout.server.ts\");\n const appLayoutServerPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(app)\",\n \"+layout.server.ts\",\n );\n pushResult(\n modifyOutcomeToFile(\n appLayoutServerPath,\n modifyLayoutServer(appLayoutServerPath),\n ),\n );\n\n logger.info(\"Modifying utils.ts\");\n const utilsPath = path.join(options.root, \"src\", \"lib\", \"utils.ts\");\n pushResult(modifyOutcomeToFile(utilsPath, modifyUtils(utilsPath)));\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":";;;;;;;;;;;;;AASA,IAAM,IAAe,2EAMf,IAAiB,CAAM;;GAIvB,IAAe;CACnB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD,CAAC,KAAK,KAAK,EAEN,IAAiB;CACrB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD,CAAC,KAAK,KAAK;AAEZ,SAAgB,EAAgB,GAAmC;AACjE,KAAI,CAAC,EAAG,WAAW,EAAW,CAC5B,QAAO;EAAE,QAAQ;EAAa,SAAS;EAAgB;CAGzD,IAAM,IAAO,EAAW,SAAS,EAAW;AAsB5C,QArBK,EAAK,WAAW,SAAS,GAG1B,EAAK,WAAW,oBAAoB,GAC/B;EAAE,QAAQ;EAAW,SAAS;EAAO,IAG9C,EAAK,cAAc,MAAW;EAC5B,IAAM,EAAE,QAAQ,MAAQ,EAAmB,IAAS,MAAO;AACzD,KAAc,GAAI,CAChB;IACE,eAAe;IACf,iBAAiB;IAClB,CACF,CAAC;IACF;AACF,SAAO;GACP,EAEF,EAAK,uBAAuB,UAAU,EAAa,EACnD,EAAK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AM;KACN,UAAU;KACX;IACD;KACE,MAAM;KACN,MAAM;KACP;IACD;KACE,MAAM;KACN,MAAM;KACP;IACD;KACE,MAAM;KACN,MAAM;KACN,UAAU;KACV,UAAU;KACX;IACD;KACE,MAAM;KACN,MAAM;KACN,UAAU;KACV,UAAU;KACX;IACF;GACD,SAAS,CACP,yGACD;GACF,CAAC,EAKO,QACR,EAED,EAAO,KAAK,sCAAsC;EAClD,IAAM,IAAiB,MAAM,EAC3B,GACA,GACA,GACA,EACD;AACD,IAAQ,KAAK,GAAG,EAAe;GAC/B;CAEF,IAAM,IAAmB,EAAE,EACrB,KAAc,MAAsB;AACxC,EAAI,KAAM,EAAS,KAAK,EAAK;;AAG/B,GAAO,KAAK,iCAAiC;CAC7C,IAAM,IAAgB,EAAK,KACzB,EAAQ,MACR,OACA,UACA,SACA,iBACD;AAKD,CAJA,EACE,EAAoB,GAAe,EAAgB,EAAc,CAAC,CACnE,EAED,EAAO,KAAK,oCAAoC;CAChD,IAAM,IAAsB,EAAK,KAC/B,EAAQ,MACR,OACA,UACA,SACA,oBACD;AAQD,CAPA,EACE,EACE,GACA,EAAmB,EAAoB,CACxC,CACF,EAED,EAAO,KAAK,qBAAqB;CACjC,IAAM,IAAY,EAAK,KAAK,EAAQ,MAAM,OAAO,OAAO,WAAW;AAGnE,QAFA,EAAW,EAAoB,GAAW,EAAY,EAAU,CAAC,CAAC,EAE3D;EACL;EACA;EACA,SAAS,EAAE;EACX,YAAY,EAAE;EACd,UAAU,EAAE;EACZ,aAAa,EAAE;EACf,mBAAmB,EAAE;EACrB,iBAAiB,EAAE;EACpB"}
|
|
1
|
+
{"version":3,"file":"generate.runtime-Bpx69a8t.js","names":[],"sources":["../../src/patterns/enable/notifications/modifies/modify-app-layout.ts","../../src/patterns/enable/notifications/modifies/+layout.server.ts","../../src/patterns/enable/notifications/generate.runtime.ts"],"sourcesContent":["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 BELL_SNIPPET = `\n\t\t<div class=\"ml-auto px-4\">\n\t\t\t<NotificationsBell />\n\t\t</div>\n\t`;\n\nconst IMPORT_SNIPPET = dedent`\n import NotificationsBell from '$lib/components/notifications-bell.svelte';\n`;\n\nconst FAILURE_HINT = [\n \"Add the notifications bell inside the (app) layout's <header>.\",\n \"\",\n \"Imports to add to the <script> tag:\",\n \"\",\n IMPORT_SNIPPET,\n \"\",\n \"Markup to add inside <header>:\",\n BELL_SNIPPET,\n].join(\"\\n\");\n\nconst NOT_FOUND_HINT = [\n \"Create src/routes/(app)/+layout.svelte with a <header> that includes the bell.\",\n \"\",\n \"Imports for the <script> tag:\",\n \"\",\n IMPORT_SNIPPET,\n \"\",\n \"Markup inside <header>:\",\n BELL_SNIPPET,\n].join(\"\\n\");\n\nexport function modifyAppLayout(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(\"header\")) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n if (file.hasElement(\"NotificationsBell\")) {\n return { status: \"success\", changed: false };\n }\n\n file.modifyScript((source) => {\n const { source: out } = withInMemoryScript(source, (sf) => {\n ensureImports(sf, [\n {\n defaultImport: \"NotificationsBell\",\n moduleSpecifier: \"$lib/components/notifications-bell.svelte\",\n },\n ]);\n });\n return out;\n });\n\n file.insertBeforeClosingTag(\"header\", BELL_SNIPPET);\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 FETCH_STATEMENT = dedent`\n const notificationsList = await locals.pb\n .collection(\"notifications\")\n .getList(1, 5, {\n filter: \\`user = \"\\${locals.pb.authStore.record!.id}\" && read = false\\`,\n sort: \"-created\",\n });\n`;\n\nconst NOTIFICATIONS_STATEMENT =\n \"const notifications = { count: notificationsList.totalItems, items: notificationsList.items };\";\n\nconst DEPENDS_STATEMENT = 'depends(\"app:notifications\");';\n\nexport function modifyLayoutServer(layoutServerPath: string): ModifyOutcome {\n if (!fs.existsSync(layoutServerPath)) {\n const snippet = dedent`\n export const load = async ({ locals, depends }) => {\n ${FETCH_STATEMENT}\n ${NOTIFICATIONS_STATEMENT}\n ${DEPENDS_STATEMENT}\n return { notifications };\n };\n `;\n fs.writeFileSync(layoutServerPath, snippet);\n return { status: \"success\", changed: true };\n }\n\n const originalSource = fs.readFileSync(layoutServerPath, \"utf8\");\n const project = new Project();\n const sourceFile = project.addSourceFileAtPath(layoutServerPath);\n\n const addProperty = (\n obj: import(\"ts-morph\").ObjectLiteralExpression,\n name: string,\n initializer: string,\n ) => {\n if (obj.getProperty(name)) return;\n if (name === initializer) {\n obj.addShorthandPropertyAssignment({ name });\n } else {\n obj.addPropertyAssignment({ name, initializer });\n }\n };\n\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 if (vs?.hasExportKeyword()) {\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) loadFn = innerFnExpr;\n }\n }\n }\n }\n }\n\n if (!loadArrow && !loadFn) {\n const maybeFn = sourceFile.getFunction(\"load\");\n if (maybeFn && maybeFn.isExported()) loadFn = maybeFn;\n }\n\n if (!loadArrow && !loadFn) {\n sourceFile.addFunction({\n isExported: true,\n isAsync: true,\n name: \"load\",\n parameters: [{ name: \"{ locals, depends }\" }],\n statements: [\n FETCH_STATEMENT,\n NOTIFICATIONS_STATEMENT,\n DEPENDS_STATEMENT,\n \"return { notifications };\",\n ],\n });\n sourceFile.formatText();\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n }\n\n const fnLike = (loadArrow ?? loadFn!) as\n | import(\"ts-morph\").ArrowFunction\n | import(\"ts-morph\").FunctionDeclaration\n | import(\"ts-morph\").FunctionExpression;\n\n // Ensure first param destructures { locals, depends }\n const params = fnLike.getParameters();\n if (params.length === 0) {\n fnLike.insertParameter(0, { name: \"{ locals, depends }\" });\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 elementNames = obp.getElements().map((el) => el.getName());\n const hasDepends = elementNames.includes(\"depends\");\n const hasLocals = elementNames.includes(\"locals\");\n\n if (!hasDepends || !hasLocals) {\n const existingParts = obp\n .getElements()\n .map((el) => el.getText())\n .filter(Boolean);\n const parts: string[] = hasLocals ? [] : [\"locals\"];\n parts.push(...existingParts);\n if (!hasDepends) parts.push(\"depends\");\n first.set({\n name: `{ ${parts.join(\", \")} }`,\n type: original.type,\n initializer: (original as { initializer?: string }).initializer,\n });\n }\n } else {\n const currentName = first.getName();\n if (currentName !== \"locals\") {\n first.set({\n name: `{ locals, depends, ...${currentName} }`,\n type: original.type,\n initializer: (original as { initializer?: string }).initializer,\n });\n } else {\n first.set({\n name: `{ locals, depends }`,\n type: original.type,\n initializer: (original as { initializer?: string }).initializer,\n });\n }\n }\n }\n\n if (loadArrow && !loadArrow.isAsync()) loadArrow.setIsAsync(true);\n else if (loadFn && !loadFn.isAsync()) loadFn.setIsAsync(true);\n\n const body = fnLike.getBody();\n if (body && body.getKind() === SyntaxKind.Block) {\n const blockBody = body as import(\"ts-morph\").Block;\n const statements = blockBody.getStatements();\n\n const declaresVar = (name: string) =>\n statements.some((stmt) => {\n if (stmt.getKind() !== SyntaxKind.VariableStatement) return false;\n return (stmt as import(\"ts-morph\").VariableStatement)\n .getDeclarations()\n .some((d) => d.getName() === name);\n });\n\n const hasDependsCall = statements.some(\n (stmt) =>\n stmt.getKind() === SyntaxKind.ExpressionStatement &&\n stmt.getDescendantsOfKind(SyntaxKind.CallExpression).some((ce) => {\n if (ce.getExpression().getText() !== \"depends\") return false;\n const args = ce.getArguments();\n const argText = args[0]?.getText() ?? \"\";\n return (\n args.length === 1 &&\n (argText === \"'app:notifications'\" ||\n argText === '\"app:notifications\"')\n );\n }),\n );\n\n const hasNotificationsList = declaresVar(\"notificationsList\");\n const hasNotifications = declaresVar(\"notifications\");\n\n const returnIdx = statements.findIndex(\n (s) => s.getKind() === SyntaxKind.ReturnStatement,\n );\n let insertAt = returnIdx >= 0 ? returnIdx : statements.length;\n\n if (!hasNotificationsList) {\n blockBody.insertStatements(insertAt, FETCH_STATEMENT);\n insertAt++;\n }\n if (!hasNotifications) {\n blockBody.insertStatements(insertAt, NOTIFICATIONS_STATEMENT);\n insertAt++;\n }\n if (!hasDependsCall) {\n blockBody.insertStatements(insertAt, DEPENDS_STATEMENT);\n }\n }\n\n const augmentReturnObject = (\n obj: import(\"ts-morph\").ObjectLiteralExpression,\n ) => {\n addProperty(obj, \"notifications\", \"notifications\");\n };\n\n const augmentReturns = (target: import(\"ts-morph\").Node) => {\n const returns = target.getDescendantsOfKind(SyntaxKind.ReturnStatement);\n returns.forEach((ret) => {\n const expr = ret.getExpression();\n if (!expr) return;\n if (expr.getKind() === SyntaxKind.ObjectLiteralExpression) {\n augmentReturnObject(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 augmentReturnObject(\n inner as import(\"ts-morph\").ObjectLiteralExpression,\n );\n }\n }\n });\n };\n\n if (loadArrow) {\n const arrowBody = loadArrow.getBody();\n if (arrowBody.getKind() === SyntaxKind.Block) {\n augmentReturns(arrowBody);\n } else {\n const bodyExpr = arrowBody 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 augmentReturnObject(\n inner as import(\"ts-morph\").ObjectLiteralExpression,\n );\n }\n } else if (bodyExpr.getKind() === SyntaxKind.ObjectLiteralExpression) {\n augmentReturnObject(\n bodyExpr as import(\"ts-morph\").ObjectLiteralExpression,\n );\n }\n }\n } else if (loadFn) {\n const fnBody = loadFn.getBody();\n if (fnBody) augmentReturns(fnBody);\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 path from \"node:path\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport { languageFromPath } from \"../../../core/util\";\nimport {\n applyCollectionRulePatches,\n createCollectionIdempotent,\n} from \"../../../runtime/collections\";\nimport {\n getMigrationFile,\n migrationDelay,\n withPocketbase,\n} from \"../../../runtime/pocketbase\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { modifyUtils } from \"../../../runtime/modify-utils\";\nimport { modifyAppLayout } from \"./modifies/modify-app-layout\";\nimport { modifyLayoutServer } from \"./modifies/+layout.server\";\nimport { NOTIFICATION_RULE_PATCHES } from \"./runtime/pocketbase\";\n\nasync function pushMigrationCreates(\n creates: File[],\n collectionName: string,\n options: Options,\n created = true,\n) {\n if (!created) return;\n await migrationDelay();\n const migrationFile = getMigrationFile(collectionName, \"created\", options);\n if (!migrationFile) return;\n creates.push({\n path: migrationFile,\n language: languageFromPath(migrationFile),\n content: fs.readFileSync(migrationFile, \"utf8\"),\n status: \"success\",\n });\n}\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const creates: File[] = [];\n\n await withPocketbase(options.root, async (pb) => {\n const userCollection = await pb.collections.getOne(\"users\");\n const create = (spec: Parameters<typeof createCollectionIdempotent>[1]) =>\n createCollectionIdempotent(pb, spec, logger);\n\n logger.info(\"Creating notifications collection\");\n const result = await create({\n name: \"notifications\",\n type: \"base\",\n fields: [\n {\n name: \"id\",\n type: \"text\",\n primaryKey: true,\n autogeneratePattern: \"[a-z0-9]{15}\",\n max: 15,\n min: 15,\n pattern: \"^[a-z0-9]+$\",\n required: true,\n },\n {\n name: \"user\",\n type: \"relation\",\n cascadeDelete: true,\n collectionId: userCollection.id,\n maxSelect: 1,\n minSelect: 0,\n required: true,\n },\n {\n name: \"title\",\n type: \"text\",\n required: true,\n },\n {\n name: \"body\",\n type: \"text\",\n },\n {\n name: \"read\",\n type: \"bool\",\n },\n {\n name: \"created\",\n type: \"autodate\",\n onCreate: true,\n onUpdate: false,\n },\n {\n name: \"updated\",\n type: \"autodate\",\n onCreate: true,\n onUpdate: true,\n },\n ],\n indexes: [\n \"CREATE INDEX `idx_notifications_user_read_created` ON `notifications` (`user`, `read`, `created` DESC)\",\n ],\n });\n await pushMigrationCreates(\n creates,\n \"notifications\",\n options,\n result.created,\n );\n\n logger.info(\"Applying notifications rule patches\");\n const ruleMigrations = await applyCollectionRulePatches(\n pb,\n NOTIFICATION_RULE_PATCHES,\n options,\n logger,\n );\n creates.push(...ruleMigrations);\n });\n\n const modifies: File[] = [];\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n logger.info(\"Modifying (app) +layout.svelte\");\n const appLayoutPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(app)\",\n \"+layout.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(appLayoutPath, modifyAppLayout(appLayoutPath)),\n );\n\n logger.info(\"Modifying (app) +layout.server.ts\");\n const appLayoutServerPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(app)\",\n \"+layout.server.ts\",\n );\n pushResult(\n modifyOutcomeToFile(\n appLayoutServerPath,\n modifyLayoutServer(appLayoutServerPath),\n ),\n );\n\n logger.info(\"Modifying utils.ts\");\n const utilsPath = path.join(options.root, \"src\", \"lib\", \"utils.ts\");\n pushResult(modifyOutcomeToFile(utilsPath, modifyUtils(utilsPath)));\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":";;;;;;;;;;;;;AASA,IAAM,IAAe,2EAMf,IAAiB,CAAM;;GAIvB,IAAe;CACnB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD,CAAC,KAAK,KAAK,EAEN,IAAiB;CACrB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD,CAAC,KAAK,KAAK;AAEZ,SAAgB,EAAgB,GAAmC;AACjE,KAAI,CAAC,EAAG,WAAW,EAAW,CAC5B,QAAO;EAAE,QAAQ;EAAa,SAAS;EAAgB;CAGzD,IAAM,IAAO,EAAW,SAAS,EAAW;AAsB5C,QArBK,EAAK,WAAW,SAAS,GAG1B,EAAK,WAAW,oBAAoB,GAC/B;EAAE,QAAQ;EAAW,SAAS;EAAO,IAG9C,EAAK,cAAc,MAAW;EAC5B,IAAM,EAAE,QAAQ,MAAQ,EAAmB,IAAS,MAAO;AACzD,KAAc,GAAI,CAChB;IACE,eAAe;IACf,iBAAiB;IAClB,CACF,CAAC;IACF;AACF,SAAO;GACP,EAEF,EAAK,uBAAuB,UAAU,EAAa,EACnD,EAAK,QAAQ,EAAW,EACjB;EAAE,QAAQ;EAAW,SAAS,EAAK,YAAY;EAAE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AM;KACN,MAAM;KACP;IACD;KACE,MAAM;KACN,MAAM;KACN,UAAU;KACV,UAAU;KACX;IACD;KACE,MAAM;KACN,MAAM;KACN,UAAU;KACV,UAAU;KACX;IACF;GACD,SAAS,CACP,yGACD;GACF,CAAC,EAKO,QACR,EAED,EAAO,KAAK,sCAAsC;EAClD,IAAM,IAAiB,MAAM,EAC3B,GACA,GACA,GACA,EACD;AACD,IAAQ,KAAK,GAAG,EAAe;GAC/B;CAEF,IAAM,IAAmB,EAAE,EACrB,KAAc,MAAsB;AACxC,EAAI,KAAM,EAAS,KAAK,EAAK;;AAG/B,GAAO,KAAK,iCAAiC;CAC7C,IAAM,IAAgB,EAAK,KACzB,EAAQ,MACR,OACA,UACA,SACA,iBACD;AAKD,CAJA,EACE,EAAoB,GAAe,EAAgB,EAAc,CAAC,CACnE,EAED,EAAO,KAAK,oCAAoC;CAChD,IAAM,IAAsB,EAAK,KAC/B,EAAQ,MACR,OACA,UACA,SACA,oBACD;AAQD,CAPA,EACE,EACE,GACA,EAAmB,EAAoB,CACxC,CACF,EAED,EAAO,KAAK,qBAAqB;CACjC,IAAM,IAAY,EAAK,KAAK,EAAQ,MAAM,OAAO,OAAO,WAAW;AAGnE,QAFA,EAAW,EAAoB,GAAW,EAAY,EAAU,CAAC,CAAC,EAE3D;EACL;EACA;EACA,SAAS,EAAE;EACX,YAAY,EAAE;EACd,UAAU,EAAE;EACZ,aAAa,EAAE;EACf,mBAAmB,EAAE;EACrB,iBAAiB,EAAE;EACpB"}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { n as e } from "./logger-BpgCb-ZG.js";
|
|
2
|
-
import { t } from "./shared-
|
|
2
|
+
import { t } from "./shared-C4wJ9sb0.js";
|
|
3
3
|
import { modifyOutcomeToFile as n } from "./modify-file-DE7tPADZ.js";
|
|
4
4
|
import { i as r, o as i } from "./ts-morph-helpers-bR0-x04t.js";
|
|
5
|
-
import { n as a } from "./env-
|
|
5
|
+
import { n as a } from "./env-Bk-LRVos.js";
|
|
6
6
|
import o from "node:fs";
|
|
7
7
|
import s from "node:path";
|
|
8
8
|
import { Project as c, QuoteKind as l, SyntaxKind as u } from "ts-morph";
|
|
@@ -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-CEtVUz4k.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"generate.runtime-
|
|
1
|
+
{"version":3,"file":"generate.runtime-CEtVUz4k.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 \"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;AAClE,KAAI,CAAC,EAAG,WAAW,EAAY,CAC7B,QAAO;EAAE,QAAQ;EAAW,SAAS;EAAO;CAG9C,IAAM,IAAS,EAAG,aAAa,GAAa,OAAO;AACnD,KAAI,CAAC,EAAO,SAAS,WAAW,CAC9B,QAAO;EAAE,QAAQ;EAAW,SAAS;EAAO;CAG9C,IAAM,IAAO,IAAI,EAAW,EAAO,EAC/B,IAAa,IAEX,KAAa,MAAgD;AAC7D,OACJ,GAAK,MAAQ;GACX,IAAM,IAAS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CAC/C,IAAM,IAAY,EAAQ,SAAS,MAC7B,IAAS,EAAU,EAAQ,EAC3B,IAAmB,EAAE,EACrB,KAAc,MAAsB;AACxC,EAAI,KAAM,EAAS,KAAK,EAAK;;AAG/B,GAAO,KAAK,yCAAyC;CACrD,IAAM,IAAsB;EAC1B;GAAE,MAAM;GAAW,KAAK;GAAsB;EAC9C;GAAE,MAAM;GAAO,KAAK;GAAqB;EACzC;GAAE,MAAM;GAAO,KAAK;GAAiC;EACrD;GAAE,MAAM;GAAO,KAAK;GAAyB;EAC7C;GAAE,MAAM;GAAO,KAAK;GAAuB;EAC5C,EACK,IAAU,EAAK,KAAK,EAAQ,MAAM,OAAO;AAG/C,KAFA,EAAW,EAAoB,GAAS,EAAgB,GAAS,EAAS,CAAC,CAAC,EAExE,GAAW;AACb,IAAO,KAAK,4BAA4B;EACxC,IAAM,IAAc,EAAK,KACvB,EAAQ,MACR,OACA,OACA,cACA,kBACD;AAGD,EAFA,EAAW,EAAoB,GAAa,EAAgB,EAAY,CAAC,CAAC,EAE1E,EAAO,KAAK,mCAAmC;EAC/C,IAAM,IAAiB,EAAK,KAC1B,EAAQ,MACR,OACA,UACA,YACA,UACA,kBACD;AACD,IACE,EAAoB,GAAgB,EAAmB,EAAe,CAAC,CACxE;;AAeH,QAAO;EACL,SAAS,EAAE;EACX;EACA,SAAS,EAAE;EACX,YAAY,EAAE;EACd,UAAU,EAAE;EACZ,aAAa,EAAE;EACf,mBAAmB,EAAE;EACrB,iBAbsB,MAAM,EAC5B,IARsB;GACtB;GACA;GACA;GACA;GACA;GACD,GAE+B,CAAC,iBAAiB,kBAAkB,EAClE,EACD;EAWA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"generate.runtime-
|
|
1
|
+
{"version":3,"file":"generate.runtime-CUgleG0U.js","names":[],"sources":["../../src/patterns/enable/api/modifies/hooks.server.ts","../../src/patterns/enable/api/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\nconst FAILURE_HINT = dedent`\n Configure handlePocketbase() with the api option in hooks.server.ts:\n\n handlePocketbase({\n api: { enabled: true },\n });\n`;\n\nconst NOT_FOUND_HINT = dedent`\n Create src/hooks.server.ts with handlePocketbase:\n\n import { handlePocketbase } from 'velastack/handle';\n\n export const handle = handlePocketbase({\n api: { enabled: true },\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 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(`{ api: { enabled: true } }`);\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, `{ api: { enabled: true } }`);\n sourceFile.formatText();\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n }\n\n const optionsObj = firstArg.asKindOrThrow(SyntaxKind.ObjectLiteralExpression);\n const apiProp = optionsObj.getProperty(\"api\");\n\n if (!apiProp) {\n optionsObj.addPropertyAssignment({\n name: \"api\",\n initializer: `{ enabled: true }`,\n });\n sourceFile.formatText();\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n }\n\n if (apiProp.getKind() === SyntaxKind.PropertyAssignment) {\n const apiInit = (\n apiProp as import(\"ts-morph\").PropertyAssignment\n ).getInitializer();\n if (apiInit && apiInit.getKind() === SyntaxKind.ObjectLiteralExpression) {\n const apiObj = apiInit as import(\"ts-morph\").ObjectLiteralExpression;\n const enabledProp = apiObj.getProperty(\"enabled\");\n if (!enabledProp) {\n apiObj.addPropertyAssignment({ name: \"enabled\", initializer: \"true\" });\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 type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { modifyHooksServer } from \"./modifies/hooks.server\";\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const modifies: File[] = [];\n\n logger.info(\"Modifying hooks.server.ts\");\n const hooksServerPath = path.join(options.root, \"src\", \"hooks.server.ts\");\n const file = modifyOutcomeToFile(\n hooksServerPath,\n modifyHooksServer(hooksServerPath),\n );\n if (file) modifies.push(file);\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,IAAM,IAAe,CAAM;;;;;;GAQrB,IAAiB,CAAM;;;;;;;;;AAU7B,SAAgB,EAAkB,GAAwC;AACxE,KAAI,CAAC,EAAG,WAAW,EAAgB,CACjC,QAAO;EAAE,QAAQ;EAAa,SAAS;EAAgB;CAGzD,IAAM,IAAiB,EAAG,aAAa,GAAiB,OAAO,EAEzD,IADU,IAAI,GAAS,CACF,oBAAoB,EAAgB,EAEzD,IAAW,EACd,qBAAqB,EAAW,eAAe,CAC/C,MAAM,MAAO,EAAG,eAAe,CAAC,SAAS,KAAK,mBAAmB;AAEpE,KAAI,CAAC,EACH,QAAO;EAAE,QAAQ;EAAU,SAAS;EAAc;CAGpD,IAAM,IAAO,EAAS,cAAc;AACpC,KAAI,EAAK,WAAW,EAIlB,QAHA,EAAS,YAAY,6BAA6B,EAClD,EAAW,YAAY,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