@velastack/patterns 0.14.1 → 0.14.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (115) hide show
  1. package/dist/chunks/{collections-DMdTP6H_.js → collections-B_-NTtLW.js} +2 -2
  2. package/dist/chunks/{collections-DMdTP6H_.js.map → collections-B_-NTtLW.js.map} +1 -1
  3. package/dist/chunks/{constants-Bo85Ke0C.js → constants-CTp-0HKk.js} +18 -28
  4. package/dist/chunks/{constants-Bo85Ke0C.js.map → constants-CTp-0HKk.js.map} +1 -1
  5. package/dist/chunks/{currency.server-CNc9ASqB.js → currency.server-DOX4Rzyb.js} +2 -2
  6. package/dist/chunks/{currency.server-CNc9ASqB.js.map → currency.server-DOX4Rzyb.js.map} +1 -1
  7. package/dist/chunks/{env-vars-ZzWTCtYk.js → env-vars-BbS_mWyP.js} +3 -3
  8. package/dist/chunks/{env-vars-ZzWTCtYk.js.map → env-vars-BbS_mWyP.js.map} +1 -1
  9. package/dist/chunks/{generate-DiKYcuxK.js → generate-4iujJNAW.js} +3 -3
  10. package/dist/chunks/{generate-DiKYcuxK.js.map → generate-4iujJNAW.js.map} +1 -1
  11. package/dist/chunks/{generate-CpWYpXme.js → generate-B4uDCW5D.js} +2 -2
  12. package/dist/chunks/{generate-CpWYpXme.js.map → generate-B4uDCW5D.js.map} +1 -1
  13. package/dist/chunks/{generate-vSMSfoEL.js → generate-BJY8AtAp.js} +2 -2
  14. package/dist/chunks/{generate-vSMSfoEL.js.map → generate-BJY8AtAp.js.map} +1 -1
  15. package/dist/chunks/{generate-DPR1uuZM.js → generate-Bwkx_usZ.js} +2 -2
  16. package/dist/chunks/{generate-DPR1uuZM.js.map → generate-Bwkx_usZ.js.map} +1 -1
  17. package/dist/chunks/{generate-JcPcxodU.js → generate-JkvSNTy-.js} +2 -2
  18. package/dist/chunks/{generate-JcPcxodU.js.map → generate-JkvSNTy-.js.map} +1 -1
  19. package/dist/chunks/{generate.runtime-DMhsz52A.js → generate.runtime-27KTIg_o.js} +3 -3
  20. package/dist/chunks/{generate.runtime-DMhsz52A.js.map → generate.runtime-27KTIg_o.js.map} +1 -1
  21. package/dist/chunks/{generate.runtime-Czu9sahf.js → generate.runtime-B7XOa9_A.js} +3 -3
  22. package/dist/chunks/{generate.runtime-Czu9sahf.js.map → generate.runtime-B7XOa9_A.js.map} +1 -1
  23. package/dist/chunks/{generate.runtime-CTAAJJr6.js → generate.runtime-B8-ORwxT.js} +6 -6
  24. package/dist/chunks/{generate.runtime-CTAAJJr6.js.map → generate.runtime-B8-ORwxT.js.map} +1 -1
  25. package/dist/chunks/{generate.runtime-CZaJ7Uud.js → generate.runtime-BFX_8erf.js} +6 -6
  26. package/dist/chunks/{generate.runtime-CZaJ7Uud.js.map → generate.runtime-BFX_8erf.js.map} +1 -1
  27. package/dist/chunks/{generate.runtime-BbyC1DMB.js → generate.runtime-BROXlbeJ.js} +3 -3
  28. package/dist/chunks/{generate.runtime-BbyC1DMB.js.map → generate.runtime-BROXlbeJ.js.map} +1 -1
  29. package/dist/chunks/{generate.runtime-BBjaUxGz.js → generate.runtime-BU-4sjyu.js} +4 -4
  30. package/dist/chunks/{generate.runtime-BBjaUxGz.js.map → generate.runtime-BU-4sjyu.js.map} +1 -1
  31. package/dist/chunks/{generate.runtime-Dw6umCTf.js → generate.runtime-BXNBWGYr.js} +2 -2
  32. package/dist/chunks/{generate.runtime-Dw6umCTf.js.map → generate.runtime-BXNBWGYr.js.map} +1 -1
  33. package/dist/chunks/{generate.runtime-DD3OVUB5.js → generate.runtime-BlEy2fFF.js} +3 -3
  34. package/dist/chunks/{generate.runtime-DD3OVUB5.js.map → generate.runtime-BlEy2fFF.js.map} +1 -1
  35. package/dist/chunks/{generate.runtime-Jzkg3tWq.js → generate.runtime-CBVcsole.js} +2 -2
  36. package/dist/chunks/{generate.runtime-Jzkg3tWq.js.map → generate.runtime-CBVcsole.js.map} +1 -1
  37. package/dist/chunks/{generate.runtime-Bna36DjV.js → generate.runtime-CCaCaXNu.js} +2 -2
  38. package/dist/chunks/{generate.runtime-Bna36DjV.js.map → generate.runtime-CCaCaXNu.js.map} +1 -1
  39. package/dist/chunks/{generate.runtime-CkqBNJmH.js → generate.runtime-Cm75waRD.js} +2 -2
  40. package/dist/chunks/{generate.runtime-CkqBNJmH.js.map → generate.runtime-Cm75waRD.js.map} +1 -1
  41. package/dist/chunks/{generate.runtime-D7SysNQ9.js → generate.runtime-CuvdtjKc.js} +2 -2
  42. package/dist/chunks/{generate.runtime-D7SysNQ9.js.map → generate.runtime-CuvdtjKc.js.map} +1 -1
  43. package/dist/chunks/{generate.runtime-VXM0eG6V.js → generate.runtime-D0lI3Gt8.js} +4 -4
  44. package/dist/chunks/{generate.runtime-VXM0eG6V.js.map → generate.runtime-D0lI3Gt8.js.map} +1 -1
  45. package/dist/chunks/{generate.runtime-TPgoAXWD.js → generate.runtime-D6l6uLiY.js} +2 -2
  46. package/dist/chunks/{generate.runtime-TPgoAXWD.js.map → generate.runtime-D6l6uLiY.js.map} +1 -1
  47. package/dist/chunks/{generate.runtime-CsfHtEy3.js → generate.runtime-D77ueFKY.js} +5 -5
  48. package/dist/chunks/{generate.runtime-CsfHtEy3.js.map → generate.runtime-D77ueFKY.js.map} +1 -1
  49. package/dist/chunks/{generate.runtime-BufPbKvb.js → generate.runtime-D9OC1RXu.js} +2 -2
  50. package/dist/chunks/{generate.runtime-BufPbKvb.js.map → generate.runtime-D9OC1RXu.js.map} +1 -1
  51. package/dist/chunks/{generate.runtime-CU1Gec33.js → generate.runtime-DLoYscQO.js} +3 -3
  52. package/dist/chunks/{generate.runtime-CU1Gec33.js.map → generate.runtime-DLoYscQO.js.map} +1 -1
  53. package/dist/chunks/{generate.runtime-D50A0Jkc.js → generate.runtime-DhSH1o8H.js} +3 -3
  54. package/dist/chunks/{generate.runtime-D50A0Jkc.js.map → generate.runtime-DhSH1o8H.js.map} +1 -1
  55. package/dist/chunks/{generate.runtime-BSKontB4.js → generate.runtime-DiEiFoxR.js} +3 -3
  56. package/dist/chunks/{generate.runtime-BSKontB4.js.map → generate.runtime-DiEiFoxR.js.map} +1 -1
  57. package/dist/chunks/{generate.runtime-DHFjipkv.js → generate.runtime-Dm7IEo2h.js} +3 -3
  58. package/dist/chunks/{generate.runtime-DHFjipkv.js.map → generate.runtime-Dm7IEo2h.js.map} +1 -1
  59. package/dist/chunks/{generate.runtime-B-FbahJY.js → generate.runtime-Dn0_y2iV.js} +4 -4
  60. package/dist/chunks/{generate.runtime-B-FbahJY.js.map → generate.runtime-Dn0_y2iV.js.map} +1 -1
  61. package/dist/chunks/{generate.runtime-vr8Tp4dr.js → generate.runtime-DuAYqKxl.js} +2 -2
  62. package/dist/chunks/{generate.runtime-vr8Tp4dr.js.map → generate.runtime-DuAYqKxl.js.map} +1 -1
  63. package/dist/chunks/{generate.runtime-C8vGwunw.js → generate.runtime-Duw_JI_b.js} +2 -2
  64. package/dist/chunks/{generate.runtime-C8vGwunw.js.map → generate.runtime-Duw_JI_b.js.map} +1 -1
  65. package/dist/chunks/{generate.runtime-B2TQboJB.js → generate.runtime-DxyQqNpu.js} +4 -4
  66. package/dist/chunks/{generate.runtime-B2TQboJB.js.map → generate.runtime-DxyQqNpu.js.map} +1 -1
  67. package/dist/chunks/{generate.runtime-CDQ3bnRi.js → generate.runtime-PDnSxiek.js} +6 -6
  68. package/dist/chunks/{generate.runtime-CDQ3bnRi.js.map → generate.runtime-PDnSxiek.js.map} +1 -1
  69. package/dist/chunks/{generate.runtime-DL16fW78.js → generate.runtime-RTGpwxcS.js} +5 -5
  70. package/dist/chunks/{generate.runtime-DL16fW78.js.map → generate.runtime-RTGpwxcS.js.map} +1 -1
  71. package/dist/chunks/{generate.runtime-CSusmHj9.js → generate.runtime-TQmspB4Z.js} +4 -4
  72. package/dist/chunks/{generate.runtime-CSusmHj9.js.map → generate.runtime-TQmspB4Z.js.map} +1 -1
  73. package/dist/chunks/{generate.runtime-opwafU4k.js → generate.runtime-UtkANHk1.js} +3 -3
  74. package/dist/chunks/{generate.runtime-opwafU4k.js.map → generate.runtime-UtkANHk1.js.map} +1 -1
  75. package/dist/chunks/{generate.runtime-BL78nWra.js → generate.runtime-VMTLHWLk.js} +7 -7
  76. package/dist/chunks/{generate.runtime-BL78nWra.js.map → generate.runtime-VMTLHWLk.js.map} +1 -1
  77. package/dist/chunks/{generate.runtime-pjRWIwSm.js → generate.runtime-XT_JQlTk.js} +2 -2
  78. package/dist/chunks/{generate.runtime-pjRWIwSm.js.map → generate.runtime-XT_JQlTk.js.map} +1 -1
  79. package/dist/chunks/{generate.runtime-BB2GGj4d.js → generate.runtime-XpYi9SlM.js} +2 -2
  80. package/dist/chunks/{generate.runtime-BB2GGj4d.js.map → generate.runtime-XpYi9SlM.js.map} +1 -1
  81. package/dist/chunks/{generate.runtime-DStnhncj.js → generate.runtime-ZgLxGWuy.js} +3 -3
  82. package/dist/chunks/{generate.runtime-DStnhncj.js.map → generate.runtime-ZgLxGWuy.js.map} +1 -1
  83. package/dist/chunks/{generate.runtime-D50lIHIY.js → generate.runtime-bsuqrKOm.js} +2 -2
  84. package/dist/chunks/{generate.runtime-D50lIHIY.js.map → generate.runtime-bsuqrKOm.js.map} +1 -1
  85. package/dist/chunks/{generate.runtime-CPWxn8rh.js → generate.runtime-nXjFqHyb.js} +4 -4
  86. package/dist/chunks/{generate.runtime-CPWxn8rh.js.map → generate.runtime-nXjFqHyb.js.map} +1 -1
  87. package/dist/chunks/{generate.runtime-BPnFkMKl.js → generate.runtime-sjFAWbZc.js} +6 -6
  88. package/dist/chunks/{generate.runtime-BPnFkMKl.js.map → generate.runtime-sjFAWbZc.js.map} +1 -1
  89. package/dist/chunks/{generate.runtime-7QPUM9c3.js → generate.runtime-wiWdXXPi.js} +4 -4
  90. package/dist/chunks/{generate.runtime-7QPUM9c3.js.map → generate.runtime-wiWdXXPi.js.map} +1 -1
  91. package/dist/chunks/{i18n-D8hsUX_P.js → i18n-mnzzcYhz.js} +2 -2
  92. package/dist/chunks/{i18n-D8hsUX_P.js.map → i18n-mnzzcYhz.js.map} +1 -1
  93. package/dist/chunks/{modify-file-CoFH_Y5n.js → modify-file-CgJIza72.js} +2 -2
  94. package/dist/chunks/{modify-file-CoFH_Y5n.js.map → modify-file-CgJIza72.js.map} +1 -1
  95. package/dist/chunks/{pocketbase-BTLraFEp.js → pocketbase-S8lUt0nI.js} +2 -2
  96. package/dist/chunks/{pocketbase-BTLraFEp.js.map → pocketbase-S8lUt0nI.js.map} +1 -1
  97. package/dist/chunks/{providers-cp9IJLRl.js → providers-CDUFaOeQ.js} +2 -2
  98. package/dist/chunks/{providers-cp9IJLRl.js.map → providers-CDUFaOeQ.js.map} +1 -1
  99. package/dist/chunks/{shared-Be8NptJO.js → shared-BjTRQ5QH.js} +2 -2
  100. package/dist/chunks/{shared-Be8NptJO.js.map → shared-BjTRQ5QH.js.map} +1 -1
  101. package/dist/chunks/{site-BHCX2hbj.js → site-C8Wcg6LT.js} +2 -2
  102. package/dist/chunks/{site-BHCX2hbj.js.map → site-C8Wcg6LT.js.map} +1 -1
  103. package/dist/chunks/{table-core-JdtTKQKA.js → table-core-RvMjoXpT.js} +2 -2
  104. package/dist/chunks/{table-core-JdtTKQKA.js.map → table-core-RvMjoXpT.js.map} +1 -1
  105. package/dist/chunks/{test-setup-SleehT05.js → test-setup-CpjhQSl-.js} +3 -3
  106. package/dist/chunks/{test-setup-SleehT05.js.map → test-setup-CpjhQSl-.js.map} +1 -1
  107. package/dist/chunks/{ui-smOXuMsQ.js → ui-CE-8llQS.js} +3 -3
  108. package/dist/chunks/{ui-smOXuMsQ.js.map → ui-CE-8llQS.js.map} +1 -1
  109. package/dist/chunks/{whatsapp-qMxxv6e0.js → whatsapp-DT10x76l.js} +2 -2
  110. package/dist/chunks/{whatsapp-qMxxv6e0.js.map → whatsapp-DT10x76l.js.map} +1 -1
  111. package/dist/chunks/{write-result-DPM26sZ_.js → write-result-BguSfKV-.js} +4 -4
  112. package/dist/chunks/{write-result-DPM26sZ_.js.map → write-result-BguSfKV-.js.map} +1 -1
  113. package/dist/index.js +97 -97
  114. package/dist/index.js.map +1 -1
  115. package/package.json +3 -3
@@ -1 +1 @@
1
- {"version":3,"file":"generate.runtime-CZaJ7Uud.js","names":["getLogger","revertOutcomeToFile","modifyOutcomeToFile","toDeleteEntry","ensureSiteFile","dedent","removeHandle","pruneUnusedImports","removeStatementWithComments","ensureBlankLineAfterImports","formatLikeSource","libModule","isLibSpecifier","unmodifyTestSetup","unmodifySvelteConfig","unmodifyGitignore","BACKEND_ENV_VARS","WORKFLOWS_ENV_VARS","fs","path","HANDLE_HINT","INIT_HINT","BACKEND_MODULES","isStartWorkerCall","node","Node","onlyStartsWorker","fn","body","statements","workerInit","sf","decl","target","unmodifyHooksServerBackend","hooksServerPath","original","sourceFile","Project","QuoteKind","init","FAILURE_HINT","unmodifyLayoutServerMeta","layoutServerPath","updated","withoutParam","m","serverTestFiles","dir","found","entry","full","generate","logger","options","creates","modifies","deletes","revert","svelteConfigFile","hooksServerRevert","hasWorkflows","envVars","unmodifyEnvVarsFiles","spec","gitignorePath","gitignoreFile","layoutServerFile","siteFile","testFile","testSetupPath","testSetupFile"],"sources":["../../src/patterns/disable/backend/modifies/hooks.server.ts","../../src/patterns/disable/backend/modifies/layout-server.ts","../../src/patterns/disable/backend/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport {\n Node,\n Project,\n QuoteKind,\n type SourceFile,\n type Statement,\n} from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport { removeHandle } from \"../../../../runtime/compose-handle\";\nimport {\n ensureBlankLineAfterImports,\n pruneUnusedImports,\n removeStatementWithComments,\n formatLikeSource,\n type ModuleMatch,\n} from \"../../../../runtime/ts-morph-helpers\";\nimport { libModule } from \"../../../../runtime/lib-specifier\";\n\nconst HANDLE_HINT = dedent`\n Take handlePocketbase(...) out of the exported handle in src/hooks.server.ts,\n and its imports from '@velastack/pocketbase' and '$app/env/private'.\n`;\n\nconst INIT_HINT = dedent`\n The workflows are removed with the backend. Take the startWorker() call out\n of the init hook in src/hooks.server.ts, and its import:\n\n import { startWorker } from '#lib/server/workflows.js';\n`;\n\n/**\n * Modules only the backend's handle and init import from. An import nothing\n * references any more is dropped; a variable other code still reads stays.\n * `$env/dynamic/private` is the `env` object hooks written before SvelteKit 3\n * read the PocketBase variables from.\n */\nconst BACKEND_MODULES: ModuleMatch[] = [\n \"@velastack/pocketbase\",\n \"$app/env/private\",\n \"$env/dynamic/private\",\n libModule(\"server/workflows\"),\n \"@sveltejs/kit\",\n \"@sveltejs/kit/hooks\",\n];\n\n/** `startWorker()`, `await startWorker()` or `return startWorker()`. */\nfunction isStartWorkerCall(node: Node | undefined): boolean {\n if (!node) return false;\n if (Node.isAwaitExpression(node))\n return isStartWorkerCall(node.getExpression());\n if (Node.isExpressionStatement(node) || Node.isReturnStatement(node)) {\n return isStartWorkerCall(node.getExpression());\n }\n return (\n Node.isCallExpression(node) &&\n node.getExpression().getText() === \"startWorker\" &&\n node.getArguments().length === 0\n );\n}\n\n/** A function whose whole body starts the worker. */\nfunction onlyStartsWorker(fn: Node | undefined): boolean {\n if (\n !Node.isArrowFunction(fn) &&\n !Node.isFunctionExpression(fn) &&\n !Node.isFunctionDeclaration(fn)\n ) {\n return false;\n }\n const body = fn.getBody();\n if (!body) return false;\n if (!Node.isBlock(body)) return isStartWorkerCall(body);\n const statements = body.getStatements();\n return statements.length === 1 && isStartWorkerCall(statements[0]);\n}\n\n/**\n * The `init` export when all it does is start the workflow worker, the way\n * the minimal template and enable-workflows write it. `\"custom\"` when an init\n * starts the worker among other things; null when there is nothing to do.\n */\nfunction workerInit(sf: SourceFile): Statement | \"custom\" | null {\n const fn = sf.getFunction(\"init\");\n const decl = sf.getVariableDeclaration(\"init\");\n const target = fn ?? decl?.getVariableStatement();\n if (!target || !target.getText().includes(\"startWorker\")) return null;\n const onlyWorker = fn\n ? onlyStartsWorker(fn)\n : decl?.getVariableStatement()?.getDeclarations().length === 1 &&\n onlyStartsWorker(decl.getInitializer());\n return onlyWorker ? target : \"custom\";\n}\n\n/**\n * Undo what the backend put in `hooks.server.ts`: the PocketBase handle, and\n * the `init` that starts the workflow worker, which is deleted along with the\n * backend. Whatever else the file holds (i18n, content negotiation) stays; a\n * file with nothing else comes out empty, for the caller to delete.\n */\nexport function unmodifyHooksServerBackend(\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 (\n !original.includes(\"handlePocketbase\") &&\n !original.includes(\"startWorker\")\n ) {\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 // Checked before anything changes, so a failure leaves the file as it was.\n if (workerInit(sourceFile) === \"custom\") {\n return { status: \"failed\", message: INIT_HINT };\n }\n\n const removed = removeHandle(sourceFile, \"handlePocketbase\");\n if (removed.status === \"unsupported\") {\n return { status: \"failed\", message: HANDLE_HINT };\n }\n // Looked up again: edits to the file forget the nodes found before them.\n const init = workerInit(sourceFile);\n if (init && init !== \"custom\") removeStatementWithComments(sourceFile, init);\n\n pruneUnusedImports(sourceFile, BACKEND_MODULES);\n formatLikeSource(sourceFile);\n ensureBlankLineAfterImports(sourceFile);\n sourceFile.saveSync();\n return {\n status: \"success\",\n changed: sourceFile.getFullText() !== original,\n };\n}\n","import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport { isLibSpecifier } from \"../../../../runtime/lib-specifier\";\n\nconst FAILURE_HINT = dedent`\n src/routes/+layout.server.ts still reads locals.meta, which only the\n PocketBase hook provides. Read the values from a static module instead:\n\n import { site } from '#lib/site.js';\n\n // locals.meta.appName -> site.name\n // locals.meta.appURL -> site.url\n // meta: locals.meta -> meta: { appName: site.name, appURL: site.url }\n`;\n\n/**\n * Point an older root layout's meta at `#lib/site.js` instead of `locals.meta`.\n * Templates from before `src/lib/site.ts` read the app name and URL off the\n * PocketBase hook; without the backend nothing sets them, and `App.Locals` no\n * longer declares them. Current templates read `#lib/site.js` already, so this\n * leaves them alone.\n */\nexport function unmodifyLayoutServerMeta(\n layoutServerPath: string,\n): ModifyOutcome {\n if (!fs.existsSync(layoutServerPath)) {\n return { status: \"success\", changed: false };\n }\n\n const original = fs.readFileSync(layoutServerPath, \"utf8\");\n if (!original.includes(\"locals.meta\")) {\n return { status: \"success\", changed: false };\n }\n\n let updated = original\n .replace(/\\blocals\\.meta\\.appName\\b/g, \"site.name\")\n .replace(/\\blocals\\.meta\\.appURL\\b/g, \"site.url\")\n .replace(\n /\\bmeta:\\s*locals\\.meta\\b/g,\n \"meta: { appName: site.name, appURL: site.url }\",\n );\n\n if (updated.includes(\"locals.meta\")) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n // `locals` usually only carried meta; drop it from the destructuring when\n // nothing else reads it.\n const withoutParam = updated\n .replace(/\\(\\{\\s*locals\\s*,\\s*/g, \"({ \")\n .replace(/,\\s*locals\\s*\\}/g, \" }\");\n if (!/\\blocals\\b/.test(withoutParam)) {\n updated = withoutParam;\n }\n\n const importsSite = [...updated.matchAll(/from\\s+['\"]([^'\"]+)['\"]/g)].some(\n (m) => isLibSpecifier(m[1], \"site\"),\n );\n if (!importsSite) {\n updated = \"import { site } from '#lib/site.js';\\n\" + updated;\n }\n\n fs.writeFileSync(layoutServerPath, updated, \"utf8\");\n return { status: \"success\", changed: true };\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 {\n modifyOutcomeToFile,\n revertOutcomeToFile,\n} from \"../../../runtime/modify-file\";\nimport { toDeleteEntry } from \"../../destroy/shared\";\nimport { ensureSiteFile } from \"../../../runtime/site\";\nimport { unmodifyHooksServerBackend } from \"./modifies/hooks.server\";\nimport { unmodifyLayoutServerMeta } from \"./modifies/layout-server\";\nimport { unmodifySvelteConfig } from \"../../enable/backend/modifies/svelte-config\";\nimport { unmodifyGitignore } from \"../../enable/backend/modifies/gitignore\";\nimport { unmodifyTestSetup } from \"../../enable/backend/modifies/test-setup\";\nimport { BACKEND_ENV_VARS } from \"../../enable/backend/env-vars\";\nimport { WORKFLOWS_ENV_VARS } from \"../../enable/workflows/env-vars\";\nimport { unmodifyEnvVarsFiles } from \"../../../runtime/env-vars\";\n\n/** Every server test under a directory; they need the PocketBase test context. */\nfunction serverTestFiles(dir: string): string[] {\n if (!fs.existsSync(dir)) return [];\n const found: string[] = [];\n for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {\n const full = path.join(dir, entry.name);\n if (entry.isDirectory()) found.push(...serverTestFiles(full));\n else if (entry.name === \"server.test.ts\") found.push(full);\n }\n return found;\n}\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const creates: File[] = [];\n const modifies: File[] = [];\n const deletes: File[] = [];\n\n logger.info(\"Reverting adapter config\");\n const revert = unmodifySvelteConfig(options.root);\n const svelteConfigFile = modifyOutcomeToFile(revert.filePath, revert.outcome);\n if (svelteConfigFile) modifies.push(svelteConfigFile);\n\n // Only the backend's handle and worker come out; handles other patterns\n // composed in stay. The file goes when nothing else was in it.\n logger.info(\"Reverting hooks.server.ts\");\n const hooksServerPath = path.join(options.root, \"src\", \"hooks.server.ts\");\n const hooksServerRevert = revertOutcomeToFile(\n hooksServerPath,\n unmodifyHooksServerBackend(hooksServerPath),\n );\n if (hooksServerRevert.modify) modifies.push(hooksServerRevert.modify);\n if (hooksServerRevert.delete) deletes.push(hooksServerRevert.delete);\n\n // The file goes when these were all it declared. The workflow runtime\n // (deleted with the backend) is the only reader of its switches, so they\n // go too, but only from a project that has it: `TEST` is a common name.\n const hasWorkflows = fs.existsSync(\n path.join(options.root, \"src\", \"lib\", \"server\", \"workflows.ts\"),\n );\n logger.info(\n hasWorkflows\n ? \"Removing the PocketBase and workflow variables from src/env.ts\"\n : \"Removing the PocketBase variables from src/env.ts\",\n );\n const envVars = unmodifyEnvVarsFiles(\n options.root,\n (hasWorkflows ? WORKFLOWS_ENV_VARS : BACKEND_ENV_VARS).map(\n (spec) => spec.name,\n ),\n );\n if (envVars.modify) modifies.push(envVars.modify);\n if (envVars.delete) deletes.push(envVars.delete);\n\n logger.info(\"Reverting .gitignore\");\n const gitignorePath = path.join(options.root, \".gitignore\");\n const gitignoreFile = modifyOutcomeToFile(\n gitignorePath,\n unmodifyGitignore(gitignorePath),\n );\n if (gitignoreFile) modifies.push(gitignoreFile);\n\n logger.info(\"Reverting src/routes/+layout.server.ts\");\n const layoutServerPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"+layout.server.ts\",\n );\n const layoutServerFile = modifyOutcomeToFile(\n layoutServerPath,\n unmodifyLayoutServerMeta(layoutServerPath),\n );\n if (layoutServerFile) modifies.push(layoutServerFile);\n\n // The converted layout reads `src/lib/site.ts`. Every template ships it; a\n // project from before that gets one here, named as PocketBase knew it.\n if (layoutServerFile?.status === \"success\") {\n const siteFile = await ensureSiteFile(options);\n if (siteFile) creates.push(siteFile);\n }\n\n // Server tests run against the PocketBase-backed test context that the\n // backend's test/setup.ts provides; without it they neither type-check nor\n // run.\n for (const testFile of serverTestFiles(path.join(options.root, \"src\"))) {\n logger.info(`Removing ${path.relative(options.root, testFile)}`);\n deletes.push(toDeleteEntry(testFile));\n }\n\n logger.info(\"Reverting test/setup.ts\");\n const testSetupPath = path.join(options.root, \"test\", \"setup.ts\");\n const testSetupFile = modifyOutcomeToFile(\n testSetupPath,\n unmodifyTestSetup(testSetupPath),\n );\n if (testSetupFile) modifies.push(testSetupFile);\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":";;;;;;;;;;;;;;;;AAoBA,IAAMoB,IAAc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ACA;EACA;EACA,YAAY,CAAC;EACb,UAAU,CAAC;EACX,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAiB,CAAC;CACpB;AACF"}
1
+ {"version":3,"file":"generate.runtime-BFX_8erf.js","names":["getLogger","revertOutcomeToFile","modifyOutcomeToFile","toDeleteEntry","ensureSiteFile","dedent","removeHandle","pruneUnusedImports","removeStatementWithComments","ensureBlankLineAfterImports","formatLikeSource","libModule","isLibSpecifier","unmodifyTestSetup","unmodifySvelteConfig","unmodifyGitignore","BACKEND_ENV_VARS","WORKFLOWS_ENV_VARS","fs","path","HANDLE_HINT","INIT_HINT","BACKEND_MODULES","isStartWorkerCall","node","Node","onlyStartsWorker","fn","body","statements","workerInit","sf","decl","target","unmodifyHooksServerBackend","hooksServerPath","original","sourceFile","Project","QuoteKind","init","FAILURE_HINT","unmodifyLayoutServerMeta","layoutServerPath","updated","withoutParam","m","serverTestFiles","dir","found","entry","full","generate","logger","options","creates","modifies","deletes","revert","svelteConfigFile","hooksServerRevert","hasWorkflows","envVars","unmodifyEnvVarsFiles","spec","gitignorePath","gitignoreFile","layoutServerFile","siteFile","testFile","testSetupPath","testSetupFile"],"sources":["../../src/patterns/disable/backend/modifies/hooks.server.ts","../../src/patterns/disable/backend/modifies/layout-server.ts","../../src/patterns/disable/backend/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport {\n Node,\n Project,\n QuoteKind,\n type SourceFile,\n type Statement,\n} from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport { removeHandle } from \"../../../../runtime/compose-handle\";\nimport {\n ensureBlankLineAfterImports,\n pruneUnusedImports,\n removeStatementWithComments,\n formatLikeSource,\n type ModuleMatch,\n} from \"../../../../runtime/ts-morph-helpers\";\nimport { libModule } from \"../../../../runtime/lib-specifier\";\n\nconst HANDLE_HINT = dedent`\n Take handlePocketbase(...) out of the exported handle in src/hooks.server.ts,\n and its imports from '@velastack/pocketbase' and '$app/env/private'.\n`;\n\nconst INIT_HINT = dedent`\n The workflows are removed with the backend. Take the startWorker() call out\n of the init hook in src/hooks.server.ts, and its import:\n\n import { startWorker } from '#lib/server/workflows.js';\n`;\n\n/**\n * Modules only the backend's handle and init import from. An import nothing\n * references any more is dropped; a variable other code still reads stays.\n * `$env/dynamic/private` is the `env` object hooks written before SvelteKit 3\n * read the PocketBase variables from.\n */\nconst BACKEND_MODULES: ModuleMatch[] = [\n \"@velastack/pocketbase\",\n \"$app/env/private\",\n \"$env/dynamic/private\",\n libModule(\"server/workflows\"),\n \"@sveltejs/kit\",\n \"@sveltejs/kit/hooks\",\n];\n\n/** `startWorker()`, `await startWorker()` or `return startWorker()`. */\nfunction isStartWorkerCall(node: Node | undefined): boolean {\n if (!node) return false;\n if (Node.isAwaitExpression(node))\n return isStartWorkerCall(node.getExpression());\n if (Node.isExpressionStatement(node) || Node.isReturnStatement(node)) {\n return isStartWorkerCall(node.getExpression());\n }\n return (\n Node.isCallExpression(node) &&\n node.getExpression().getText() === \"startWorker\" &&\n node.getArguments().length === 0\n );\n}\n\n/** A function whose whole body starts the worker. */\nfunction onlyStartsWorker(fn: Node | undefined): boolean {\n if (\n !Node.isArrowFunction(fn) &&\n !Node.isFunctionExpression(fn) &&\n !Node.isFunctionDeclaration(fn)\n ) {\n return false;\n }\n const body = fn.getBody();\n if (!body) return false;\n if (!Node.isBlock(body)) return isStartWorkerCall(body);\n const statements = body.getStatements();\n return statements.length === 1 && isStartWorkerCall(statements[0]);\n}\n\n/**\n * The `init` export when all it does is start the workflow worker, the way\n * the minimal template and enable-workflows write it. `\"custom\"` when an init\n * starts the worker among other things; null when there is nothing to do.\n */\nfunction workerInit(sf: SourceFile): Statement | \"custom\" | null {\n const fn = sf.getFunction(\"init\");\n const decl = sf.getVariableDeclaration(\"init\");\n const target = fn ?? decl?.getVariableStatement();\n if (!target || !target.getText().includes(\"startWorker\")) return null;\n const onlyWorker = fn\n ? onlyStartsWorker(fn)\n : decl?.getVariableStatement()?.getDeclarations().length === 1 &&\n onlyStartsWorker(decl.getInitializer());\n return onlyWorker ? target : \"custom\";\n}\n\n/**\n * Undo what the backend put in `hooks.server.ts`: the PocketBase handle, and\n * the `init` that starts the workflow worker, which is deleted along with the\n * backend. Whatever else the file holds (i18n, content negotiation) stays; a\n * file with nothing else comes out empty, for the caller to delete.\n */\nexport function unmodifyHooksServerBackend(\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 (\n !original.includes(\"handlePocketbase\") &&\n !original.includes(\"startWorker\")\n ) {\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 // Checked before anything changes, so a failure leaves the file as it was.\n if (workerInit(sourceFile) === \"custom\") {\n return { status: \"failed\", message: INIT_HINT };\n }\n\n const removed = removeHandle(sourceFile, \"handlePocketbase\");\n if (removed.status === \"unsupported\") {\n return { status: \"failed\", message: HANDLE_HINT };\n }\n // Looked up again: edits to the file forget the nodes found before them.\n const init = workerInit(sourceFile);\n if (init && init !== \"custom\") removeStatementWithComments(sourceFile, init);\n\n pruneUnusedImports(sourceFile, BACKEND_MODULES);\n formatLikeSource(sourceFile);\n ensureBlankLineAfterImports(sourceFile);\n sourceFile.saveSync();\n return {\n status: \"success\",\n changed: sourceFile.getFullText() !== original,\n };\n}\n","import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport { isLibSpecifier } from \"../../../../runtime/lib-specifier\";\n\nconst FAILURE_HINT = dedent`\n src/routes/+layout.server.ts still reads locals.meta, which only the\n PocketBase hook provides. Read the values from a static module instead:\n\n import { site } from '#lib/site.js';\n\n // locals.meta.appName -> site.name\n // locals.meta.appURL -> site.url\n // meta: locals.meta -> meta: { appName: site.name, appURL: site.url }\n`;\n\n/**\n * Point an older root layout's meta at `#lib/site.js` instead of `locals.meta`.\n * Templates from before `src/lib/site.ts` read the app name and URL off the\n * PocketBase hook; without the backend nothing sets them, and `App.Locals` no\n * longer declares them. Current templates read `#lib/site.js` already, so this\n * leaves them alone.\n */\nexport function unmodifyLayoutServerMeta(\n layoutServerPath: string,\n): ModifyOutcome {\n if (!fs.existsSync(layoutServerPath)) {\n return { status: \"success\", changed: false };\n }\n\n const original = fs.readFileSync(layoutServerPath, \"utf8\");\n if (!original.includes(\"locals.meta\")) {\n return { status: \"success\", changed: false };\n }\n\n let updated = original\n .replace(/\\blocals\\.meta\\.appName\\b/g, \"site.name\")\n .replace(/\\blocals\\.meta\\.appURL\\b/g, \"site.url\")\n .replace(\n /\\bmeta:\\s*locals\\.meta\\b/g,\n \"meta: { appName: site.name, appURL: site.url }\",\n );\n\n if (updated.includes(\"locals.meta\")) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n // `locals` usually only carried meta; drop it from the destructuring when\n // nothing else reads it.\n const withoutParam = updated\n .replace(/\\(\\{\\s*locals\\s*,\\s*/g, \"({ \")\n .replace(/,\\s*locals\\s*\\}/g, \" }\");\n if (!/\\blocals\\b/.test(withoutParam)) {\n updated = withoutParam;\n }\n\n const importsSite = [...updated.matchAll(/from\\s+['\"]([^'\"]+)['\"]/g)].some(\n (m) => isLibSpecifier(m[1], \"site\"),\n );\n if (!importsSite) {\n updated = \"import { site } from '#lib/site.js';\\n\" + updated;\n }\n\n fs.writeFileSync(layoutServerPath, updated, \"utf8\");\n return { status: \"success\", changed: true };\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 {\n modifyOutcomeToFile,\n revertOutcomeToFile,\n} from \"../../../runtime/modify-file\";\nimport { toDeleteEntry } from \"../../destroy/shared\";\nimport { ensureSiteFile } from \"../../../runtime/site\";\nimport { unmodifyHooksServerBackend } from \"./modifies/hooks.server\";\nimport { unmodifyLayoutServerMeta } from \"./modifies/layout-server\";\nimport { unmodifySvelteConfig } from \"../../enable/backend/modifies/svelte-config\";\nimport { unmodifyGitignore } from \"../../enable/backend/modifies/gitignore\";\nimport { unmodifyTestSetup } from \"../../enable/backend/modifies/test-setup\";\nimport { BACKEND_ENV_VARS } from \"../../enable/backend/env-vars\";\nimport { WORKFLOWS_ENV_VARS } from \"../../enable/workflows/env-vars\";\nimport { unmodifyEnvVarsFiles } from \"../../../runtime/env-vars\";\n\n/** Every server test under a directory; they need the PocketBase test context. */\nfunction serverTestFiles(dir: string): string[] {\n if (!fs.existsSync(dir)) return [];\n const found: string[] = [];\n for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {\n const full = path.join(dir, entry.name);\n if (entry.isDirectory()) found.push(...serverTestFiles(full));\n else if (entry.name === \"server.test.ts\") found.push(full);\n }\n return found;\n}\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const creates: File[] = [];\n const modifies: File[] = [];\n const deletes: File[] = [];\n\n logger.info(\"Reverting adapter config\");\n const revert = unmodifySvelteConfig(options.root);\n const svelteConfigFile = modifyOutcomeToFile(revert.filePath, revert.outcome);\n if (svelteConfigFile) modifies.push(svelteConfigFile);\n\n // Only the backend's handle and worker come out; handles other patterns\n // composed in stay. The file goes when nothing else was in it.\n logger.info(\"Reverting hooks.server.ts\");\n const hooksServerPath = path.join(options.root, \"src\", \"hooks.server.ts\");\n const hooksServerRevert = revertOutcomeToFile(\n hooksServerPath,\n unmodifyHooksServerBackend(hooksServerPath),\n );\n if (hooksServerRevert.modify) modifies.push(hooksServerRevert.modify);\n if (hooksServerRevert.delete) deletes.push(hooksServerRevert.delete);\n\n // The file goes when these were all it declared. The workflow runtime\n // (deleted with the backend) is the only reader of its switches, so they\n // go too, but only from a project that has it: `TEST` is a common name.\n const hasWorkflows = fs.existsSync(\n path.join(options.root, \"src\", \"lib\", \"server\", \"workflows.ts\"),\n );\n logger.info(\n hasWorkflows\n ? \"Removing the PocketBase and workflow variables from src/env.ts\"\n : \"Removing the PocketBase variables from src/env.ts\",\n );\n const envVars = unmodifyEnvVarsFiles(\n options.root,\n (hasWorkflows ? WORKFLOWS_ENV_VARS : BACKEND_ENV_VARS).map(\n (spec) => spec.name,\n ),\n );\n if (envVars.modify) modifies.push(envVars.modify);\n if (envVars.delete) deletes.push(envVars.delete);\n\n logger.info(\"Reverting .gitignore\");\n const gitignorePath = path.join(options.root, \".gitignore\");\n const gitignoreFile = modifyOutcomeToFile(\n gitignorePath,\n unmodifyGitignore(gitignorePath),\n );\n if (gitignoreFile) modifies.push(gitignoreFile);\n\n logger.info(\"Reverting src/routes/+layout.server.ts\");\n const layoutServerPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"+layout.server.ts\",\n );\n const layoutServerFile = modifyOutcomeToFile(\n layoutServerPath,\n unmodifyLayoutServerMeta(layoutServerPath),\n );\n if (layoutServerFile) modifies.push(layoutServerFile);\n\n // The converted layout reads `src/lib/site.ts`. Every template ships it; a\n // project from before that gets one here, named as PocketBase knew it.\n if (layoutServerFile?.status === \"success\") {\n const siteFile = await ensureSiteFile(options);\n if (siteFile) creates.push(siteFile);\n }\n\n // Server tests run against the PocketBase-backed test context that the\n // backend's test/setup.ts provides; without it they neither type-check nor\n // run.\n for (const testFile of serverTestFiles(path.join(options.root, \"src\"))) {\n logger.info(`Removing ${path.relative(options.root, testFile)}`);\n deletes.push(toDeleteEntry(testFile));\n }\n\n logger.info(\"Reverting test/setup.ts\");\n const testSetupPath = path.join(options.root, \"test\", \"setup.ts\");\n const testSetupFile = modifyOutcomeToFile(\n testSetupPath,\n unmodifyTestSetup(testSetupPath),\n );\n if (testSetupFile) modifies.push(testSetupFile);\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":";;;;;;;;;;;;;;;;AAoBA,IAAMoB,IAAc,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A;EACA;EACA,YAAY,CAAC;EACb,UAAU,CAAC;EACX,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAiB,CAAC;CACpB;AACF"}
@@ -1,10 +1,10 @@
1
1
  import { n as e } from "./logger-t1HxmpG2.js";
2
- import { r as t } from "./modify-file-CoFH_Y5n.js";
2
+ import { r as t } from "./modify-file-CgJIza72.js";
3
3
  import { t as n } from "./svelte-file-DfplF3BU.js";
4
4
  import { _ as r, f as i, n as a, o, u as s } from "./ts-morph-helpers-B4KZXP44.js";
5
5
  import { t as c } from "./unmodify-load-CdWXJ_Ac.js";
6
6
  import { r as l } from "./lib-specifier-C3M0WTev.js";
7
- import { t as u } from "./shared-Be8NptJO.js";
7
+ import { t as u } from "./shared-BjTRQ5QH.js";
8
8
  import d from "node:fs";
9
9
  import f from "node:path";
10
10
  import { SyntaxKind as p } from "ts-morph";
@@ -139,4 +139,4 @@ async function w(n) {
139
139
  }
140
140
  export { w as generate };
141
141
 
142
- //# sourceMappingURL=generate.runtime-BbyC1DMB.js.map
142
+ //# sourceMappingURL=generate.runtime-BROXlbeJ.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"generate.runtime-BbyC1DMB.js","names":["getLogger","modifyOutcomeToFile","SvelteFile","withInMemoryScript","removeNavItemFromScript","ensureBlankLineAfterImports","removeImportByModuleSpecifier","removeFromLoad","libModule","planDropsForCollections","fs","path","unmodifyNavUser","navUserPath","source","file","wasRemoved","tryRemove","run","result","src","fn","unmodifyLayoutServer","layoutServerPath","unmodifyAppLayoutSvelte","layoutPath","ORIGINAL_HEADER","LEGACY_NAME","TEAM_IMPORTS","TEAM_PROPS","markupOf","revertAppSidebarScript","out","decl","sf","init","nameNode","SyntaxKind","typeNode","member","literal","before","name","remaining","p","pattern","elements","kept","el","moduleSpecifier","markup","formatLikeSource","unmodifyAppSidebar","appSidebarPath","generate","logger","options","modifies","pushResult","navUserCandidates","appLayoutPath"],"sources":["../../src/patterns/disable/teams/modifies/modify-nav-user.ts","../../src/patterns/disable/teams/modifies/+layout.server.ts","../../src/patterns/disable/teams/modifies/modify-app-layout.ts","../../src/patterns/disable/teams/modifies/modify-app-sidebar.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 type { ModifyOutcome } from \"../../../../core/types\";\nimport { removeFromLoad } from \"../../../../runtime/unmodify-load\";\n\n/** Take the team loader back out of the (app) layout's load. */\nexport function unmodifyLayoutServer(layoutServerPath: string): ModifyOutcome {\n return removeFromLoad(layoutServerPath, {\n variables: [\"team\", \"teams\"],\n dependsKeys: [\"app:team\"],\n returnProps: [\"team\", \"teams\"],\n });\n}\n","import fs from \"node:fs\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\n/** Drop the team props enable-teams passed to <AppSidebar>. */\nexport function unmodifyAppLayoutSvelte(layoutPath: string): ModifyOutcome {\n if (!fs.existsSync(layoutPath)) {\n return { status: \"success\", changed: false };\n }\n\n const file = SvelteFile.fromPath(layoutPath);\n if (!file.hasElement(\"AppSidebar\")) {\n return { status: \"success\", changed: false };\n }\n\n file.removeAttribute(\"AppSidebar\", \"team\");\n file.removeAttribute(\"AppSidebar\", \"teams\");\n if (!file.hasChanged()) {\n return { status: \"success\", changed: false };\n }\n\n file.writeTo(layoutPath);\n return { status: \"success\", changed: true };\n}\n","import fs from \"node:fs\";\nimport { SyntaxKind } from \"ts-morph\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport {\n ensureBlankLineAfterImports,\n removeImportByModuleSpecifier,\n withInMemoryScript,\n formatLikeSource,\n type ModuleMatch,\n} from \"../../../../runtime/ts-morph-helpers\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport { libModule } from \"../../../../runtime/lib-specifier\";\n\n/** The header enable-auth ships, which the team switcher replaced. */\nconst ORIGINAL_HEADER = `<Sidebar.Header>\n\t\t<Sidebar.Menu>\n\t\t\t<Sidebar.MenuItem>\n\t\t\t\t<Sidebar.MenuButton size=\"lg\">\n\t\t\t\t\t{#snippet child({ props })}\n\t\t\t\t\t\t<a href=\"/dashboard\" {...props}>\n\t\t\t\t\t\t\t<div\n\t\t\t\t\t\t\t\tclass=\"bg-sidebar-accent text-sidebar-primary-foreground flex aspect-square size-8 items-center justify-center rounded-lg\"\n\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t<img src={favicon} alt=\"logo\" class=\"size-6\" />\n\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t<div class=\"grid flex-1 text-left text-sm leading-tight\">\n\t\t\t\t\t\t\t\t<span class=\"truncate font-medium\">{site.name}</span>\n\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t</a>\n\t\t\t\t\t{/snippet}\n\t\t\t\t</Sidebar.MenuButton>\n\t\t\t</Sidebar.MenuItem>\n\t\t</Sidebar.Menu>\n\t</Sidebar.Header>`;\n\n/**\n * A sidebar from before `#lib/site.js` names the app with a `meta` prop; the\n * header goes back to whichever the team switcher's fallback used.\n */\nconst LEGACY_NAME = \"{meta.appName}\";\n\n/** Imports enable-teams added, dropped once the markup no longer uses them. */\nconst TEAM_IMPORTS: [name: string, module: ModuleMatch][] = [\n [\"TeamSwitcher\", libModule(\"components/team-switcher.svelte\")],\n [\"ChevronsUpDownIcon\", \"@lucide/svelte/icons/chevrons-up-down\"],\n [\"Avatar\", libModule(\"components/ui/avatar\")],\n];\n\nconst TEAM_PROPS = [\"team\", \"teams\"];\n\nfunction markupOf(source: string): string {\n return source.replace(/<script[\\s\\S]*?<\\/script>/g, \"\");\n}\n\nfunction revertAppSidebarScript(source: string, markup: string): string {\n const { source: out } = withInMemoryScript(source, (sf) => {\n for (const decl of sf.getVariableDeclarations()) {\n const init = decl.getInitializer();\n if (!init || init.getText() !== \"$props()\") continue;\n\n const nameNode = decl.getNameNode();\n if (nameNode.getKind() !== SyntaxKind.ObjectBindingPattern) continue;\n\n // Type first: rewriting the binding pattern shifts what follows.\n const typeNode = decl.getTypeNode();\n if (typeNode?.getKind() === SyntaxKind.IntersectionType) {\n for (const member of typeNode\n .asKindOrThrow(SyntaxKind.IntersectionType)\n .getTypeNodes()) {\n if (member.getKind() !== SyntaxKind.TypeLiteral) continue;\n const literal = member.asKindOrThrow(SyntaxKind.TypeLiteral);\n const before = literal.getProperties().length;\n for (const name of TEAM_PROPS) {\n literal.getProperty(name)?.remove();\n }\n if (literal.getProperties().length !== before) {\n // Collapse to one line, as enable-auth writes it; prettier keeps\n // whichever shape it finds.\n const remaining = literal\n .getProperties()\n .map((p) => p.getText().replace(/[;,]\\s*$/, \"\"));\n literal.replaceWithText(`{ ${remaining.join(\"; \")} }`);\n }\n }\n }\n\n const pattern = nameNode.asKindOrThrow(SyntaxKind.ObjectBindingPattern);\n const elements = pattern.getElements();\n const kept = elements\n .filter((el) => !TEAM_PROPS.includes(el.getName()))\n .map((el) => el.getText());\n if (kept.length !== elements.length) {\n pattern.replaceWithText(`{ ${kept.join(\", \")} }`);\n }\n }\n\n for (const [name, moduleSpecifier] of TEAM_IMPORTS) {\n if (!new RegExp(`\\\\b${name}\\\\b`).test(markup)) {\n removeImportByModuleSpecifier(sf, moduleSpecifier);\n }\n }\n formatLikeSource(sf);\n ensureBlankLineAfterImports(sf);\n });\n return out;\n}\n\n/** Put the plain app-name header back in place of the team switcher. */\nexport function unmodifyAppSidebar(appSidebarPath: string): ModifyOutcome {\n if (!fs.existsSync(appSidebarPath)) {\n return { status: \"success\", changed: false };\n }\n\n const file = SvelteFile.fromPath(appSidebarPath);\n if (!file.hasElement(\"TeamSwitcher\")) {\n return { status: \"success\", changed: false };\n }\n\n file.replaceElement(\n \"Sidebar.Header\",\n file.toString().includes(LEGACY_NAME)\n ? ORIGINAL_HEADER.replace(\"{site.name}\", LEGACY_NAME)\n : ORIGINAL_HEADER,\n );\n const markup = markupOf(file.toString());\n file.modifyScript((source) => revertAppSidebarScript(source, markup));\n file.writeTo(appSidebarPath);\n return { status: \"success\", changed: file.hasChanged() };\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 { unmodifyLayoutServer } from \"./modifies/+layout.server\";\nimport { unmodifyAppLayoutSvelte } from \"./modifies/modify-app-layout\";\nimport { unmodifyAppSidebar } from \"./modifies/modify-app-sidebar\";\nimport { planDropsForCollections } from \"../../destroy/shared\";\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const modifies: File[] = [];\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n logger.info(\"Reverting 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(\"Reverting (app) +layout.server.ts\");\n const layoutServerPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(app)\",\n \"+layout.server.ts\",\n );\n pushResult(\n modifyOutcomeToFile(\n layoutServerPath,\n unmodifyLayoutServer(layoutServerPath),\n ),\n );\n\n logger.info(\"Reverting (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, unmodifyAppLayoutSvelte(appLayoutPath)),\n );\n\n logger.info(\"Reverting app-sidebar.svelte\");\n const appSidebarPath = path.join(\n options.root,\n \"src\",\n \"lib\",\n \"components\",\n \"app-sidebar.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(appSidebarPath, unmodifyAppSidebar(appSidebarPath)),\n );\n\n const collectionDrops = await planDropsForCollections(\n // team_users is a view over teams, so it has to go first or PocketBase\n // refuses to drop teams (\"existing reference in team_users\").\n [\n \"team_users\",\n \"team_invite_links\",\n \"team_invites\",\n \"team_memberships\",\n \"teams\",\n ],\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,SAAgBY,EAAgB,GAAoC;CAClE,IAAI,CAACF,EAAG,WAAWG,CAAW,GAC5B,OAAO;EAAE,QAAQ;EAAW,SAAS;CAAM;CAG7C,IAAMC,IAASJ,EAAG,aAAaG,GAAa,MAAM;CAClD,IAAI,CAACC,EAAO,SAAS,QAAQ,GAC3B,OAAO;EAAE,QAAQ;EAAW,SAAS;CAAM;CAG7C,IAAMC,IAAO,IAAIb,EAAWY,CAAM,GAC9BE,IAAa,IAEXC,KAAa,MAAgD;EACjE,AAAID,KACJE,GAAK,MAAQ;GACX,IAAMC,IAASf,EACb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C,CACF,GAEAgC,EAAO,KAAK,gCAAgC;CAC5C,IAAMK,IAAgBjD,EAAK,KACzB6C,EAAQ,MACR,OACA,UACA,SACA,gBACF;CAKA,AAJAE,EACEzD,EAAoB2D,GAAepC,EAAwBoC,CAAa,CAAC,CAC3E,GAEAL,EAAO,KAAK,8BAA8B;CAC1C,IAAMF,IAAiB1C,EAAK,KAC1B6C,EAAQ,MACR,OACA,OACA,cACA,oBACF;CAkBA,OAjBAE,EACEzD,EAAoBoD,GAAgBD,EAAmBC,CAAc,CAAC,CACxE,GAeO;EACL,SAAS,CAAC;EACV;EACA,SAAS,CAAC;EACV,YAAY,CAAC;EACb,UAAU,CAAC;EACX,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAA,MArB4B5C,EAG5B;GACE;GACA;GACA;GACA;GACA;EACF,GACA+C,CACF;CAWA;AACF"}
1
+ {"version":3,"file":"generate.runtime-BROXlbeJ.js","names":["getLogger","modifyOutcomeToFile","SvelteFile","withInMemoryScript","removeNavItemFromScript","ensureBlankLineAfterImports","removeImportByModuleSpecifier","removeFromLoad","libModule","planDropsForCollections","fs","path","unmodifyNavUser","navUserPath","source","file","wasRemoved","tryRemove","run","result","src","fn","unmodifyLayoutServer","layoutServerPath","unmodifyAppLayoutSvelte","layoutPath","ORIGINAL_HEADER","LEGACY_NAME","TEAM_IMPORTS","TEAM_PROPS","markupOf","revertAppSidebarScript","out","decl","sf","init","nameNode","SyntaxKind","typeNode","member","literal","before","name","remaining","p","pattern","elements","kept","el","moduleSpecifier","markup","formatLikeSource","unmodifyAppSidebar","appSidebarPath","generate","logger","options","modifies","pushResult","navUserCandidates","appLayoutPath"],"sources":["../../src/patterns/disable/teams/modifies/modify-nav-user.ts","../../src/patterns/disable/teams/modifies/+layout.server.ts","../../src/patterns/disable/teams/modifies/modify-app-layout.ts","../../src/patterns/disable/teams/modifies/modify-app-sidebar.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 type { ModifyOutcome } from \"../../../../core/types\";\nimport { removeFromLoad } from \"../../../../runtime/unmodify-load\";\n\n/** Take the team loader back out of the (app) layout's load. */\nexport function unmodifyLayoutServer(layoutServerPath: string): ModifyOutcome {\n return removeFromLoad(layoutServerPath, {\n variables: [\"team\", \"teams\"],\n dependsKeys: [\"app:team\"],\n returnProps: [\"team\", \"teams\"],\n });\n}\n","import fs from \"node:fs\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\n/** Drop the team props enable-teams passed to <AppSidebar>. */\nexport function unmodifyAppLayoutSvelte(layoutPath: string): ModifyOutcome {\n if (!fs.existsSync(layoutPath)) {\n return { status: \"success\", changed: false };\n }\n\n const file = SvelteFile.fromPath(layoutPath);\n if (!file.hasElement(\"AppSidebar\")) {\n return { status: \"success\", changed: false };\n }\n\n file.removeAttribute(\"AppSidebar\", \"team\");\n file.removeAttribute(\"AppSidebar\", \"teams\");\n if (!file.hasChanged()) {\n return { status: \"success\", changed: false };\n }\n\n file.writeTo(layoutPath);\n return { status: \"success\", changed: true };\n}\n","import fs from \"node:fs\";\nimport { SyntaxKind } from \"ts-morph\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport {\n ensureBlankLineAfterImports,\n removeImportByModuleSpecifier,\n withInMemoryScript,\n formatLikeSource,\n type ModuleMatch,\n} from \"../../../../runtime/ts-morph-helpers\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport { libModule } from \"../../../../runtime/lib-specifier\";\n\n/** The header enable-auth ships, which the team switcher replaced. */\nconst ORIGINAL_HEADER = `<Sidebar.Header>\n\t\t<Sidebar.Menu>\n\t\t\t<Sidebar.MenuItem>\n\t\t\t\t<Sidebar.MenuButton size=\"lg\">\n\t\t\t\t\t{#snippet child({ props })}\n\t\t\t\t\t\t<a href=\"/dashboard\" {...props}>\n\t\t\t\t\t\t\t<div\n\t\t\t\t\t\t\t\tclass=\"bg-sidebar-accent text-sidebar-primary-foreground flex aspect-square size-8 items-center justify-center rounded-lg\"\n\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t<img src={favicon} alt=\"logo\" class=\"size-6\" />\n\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t<div class=\"grid flex-1 text-left text-sm leading-tight\">\n\t\t\t\t\t\t\t\t<span class=\"truncate font-medium\">{site.name}</span>\n\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t</a>\n\t\t\t\t\t{/snippet}\n\t\t\t\t</Sidebar.MenuButton>\n\t\t\t</Sidebar.MenuItem>\n\t\t</Sidebar.Menu>\n\t</Sidebar.Header>`;\n\n/**\n * A sidebar from before `#lib/site.js` names the app with a `meta` prop; the\n * header goes back to whichever the team switcher's fallback used.\n */\nconst LEGACY_NAME = \"{meta.appName}\";\n\n/** Imports enable-teams added, dropped once the markup no longer uses them. */\nconst TEAM_IMPORTS: [name: string, module: ModuleMatch][] = [\n [\"TeamSwitcher\", libModule(\"components/team-switcher.svelte\")],\n [\"ChevronsUpDownIcon\", \"@lucide/svelte/icons/chevrons-up-down\"],\n [\"Avatar\", libModule(\"components/ui/avatar\")],\n];\n\nconst TEAM_PROPS = [\"team\", \"teams\"];\n\nfunction markupOf(source: string): string {\n return source.replace(/<script[\\s\\S]*?<\\/script>/g, \"\");\n}\n\nfunction revertAppSidebarScript(source: string, markup: string): string {\n const { source: out } = withInMemoryScript(source, (sf) => {\n for (const decl of sf.getVariableDeclarations()) {\n const init = decl.getInitializer();\n if (!init || init.getText() !== \"$props()\") continue;\n\n const nameNode = decl.getNameNode();\n if (nameNode.getKind() !== SyntaxKind.ObjectBindingPattern) continue;\n\n // Type first: rewriting the binding pattern shifts what follows.\n const typeNode = decl.getTypeNode();\n if (typeNode?.getKind() === SyntaxKind.IntersectionType) {\n for (const member of typeNode\n .asKindOrThrow(SyntaxKind.IntersectionType)\n .getTypeNodes()) {\n if (member.getKind() !== SyntaxKind.TypeLiteral) continue;\n const literal = member.asKindOrThrow(SyntaxKind.TypeLiteral);\n const before = literal.getProperties().length;\n for (const name of TEAM_PROPS) {\n literal.getProperty(name)?.remove();\n }\n if (literal.getProperties().length !== before) {\n // Collapse to one line, as enable-auth writes it; prettier keeps\n // whichever shape it finds.\n const remaining = literal\n .getProperties()\n .map((p) => p.getText().replace(/[;,]\\s*$/, \"\"));\n literal.replaceWithText(`{ ${remaining.join(\"; \")} }`);\n }\n }\n }\n\n const pattern = nameNode.asKindOrThrow(SyntaxKind.ObjectBindingPattern);\n const elements = pattern.getElements();\n const kept = elements\n .filter((el) => !TEAM_PROPS.includes(el.getName()))\n .map((el) => el.getText());\n if (kept.length !== elements.length) {\n pattern.replaceWithText(`{ ${kept.join(\", \")} }`);\n }\n }\n\n for (const [name, moduleSpecifier] of TEAM_IMPORTS) {\n if (!new RegExp(`\\\\b${name}\\\\b`).test(markup)) {\n removeImportByModuleSpecifier(sf, moduleSpecifier);\n }\n }\n formatLikeSource(sf);\n ensureBlankLineAfterImports(sf);\n });\n return out;\n}\n\n/** Put the plain app-name header back in place of the team switcher. */\nexport function unmodifyAppSidebar(appSidebarPath: string): ModifyOutcome {\n if (!fs.existsSync(appSidebarPath)) {\n return { status: \"success\", changed: false };\n }\n\n const file = SvelteFile.fromPath(appSidebarPath);\n if (!file.hasElement(\"TeamSwitcher\")) {\n return { status: \"success\", changed: false };\n }\n\n file.replaceElement(\n \"Sidebar.Header\",\n file.toString().includes(LEGACY_NAME)\n ? ORIGINAL_HEADER.replace(\"{site.name}\", LEGACY_NAME)\n : ORIGINAL_HEADER,\n );\n const markup = markupOf(file.toString());\n file.modifyScript((source) => revertAppSidebarScript(source, markup));\n file.writeTo(appSidebarPath);\n return { status: \"success\", changed: file.hasChanged() };\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 { unmodifyLayoutServer } from \"./modifies/+layout.server\";\nimport { unmodifyAppLayoutSvelte } from \"./modifies/modify-app-layout\";\nimport { unmodifyAppSidebar } from \"./modifies/modify-app-sidebar\";\nimport { planDropsForCollections } from \"../../destroy/shared\";\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const modifies: File[] = [];\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n logger.info(\"Reverting 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(\"Reverting (app) +layout.server.ts\");\n const layoutServerPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(app)\",\n \"+layout.server.ts\",\n );\n pushResult(\n modifyOutcomeToFile(\n layoutServerPath,\n unmodifyLayoutServer(layoutServerPath),\n ),\n );\n\n logger.info(\"Reverting (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, unmodifyAppLayoutSvelte(appLayoutPath)),\n );\n\n logger.info(\"Reverting app-sidebar.svelte\");\n const appSidebarPath = path.join(\n options.root,\n \"src\",\n \"lib\",\n \"components\",\n \"app-sidebar.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(appSidebarPath, unmodifyAppSidebar(appSidebarPath)),\n );\n\n const collectionDrops = await planDropsForCollections(\n // team_users is a view over teams, so it has to go first or PocketBase\n // refuses to drop teams (\"existing reference in team_users\").\n [\n \"team_users\",\n \"team_invite_links\",\n \"team_invites\",\n \"team_memberships\",\n \"teams\",\n ],\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,SAAgBY,EAAgB,GAAoC;CAClE,IAAI,CAACF,EAAG,WAAWG,CAAW,GAC5B,OAAO;EAAE,QAAQ;EAAW,SAAS;CAAM;CAG7C,IAAMC,IAASJ,EAAG,aAAaG,GAAa,MAAM;CAClD,IAAI,CAACC,EAAO,SAAS,QAAQ,GAC3B,OAAO;EAAE,QAAQ;EAAW,SAAS;CAAM;CAG7C,IAAMC,IAAO,IAAIb,EAAWY,CAAM,GAC9BE,IAAa,IAEXC,KAAa,MAAgD;EACjE,AAAID,KACJE,GAAK,MAAQ;GACX,IAAMC,IAASf,EACbgB,GACA,SACA,4BACF;GAEA,OADID,EAAO,eAAY,IAAa,KAC7BA,EAAO;EAChB,CAAC;CACH;CAUA,OARAF,GAAW,MAAOF,EAAK,mBAAmBM,CAAE,CAAC,GACxCL,KAAYC,GAAW,MAAOF,EA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AC,CAC3E,GAEAL,EAAO,KAAK,8BAA8B;CAC1C,IAAMF,IAAiB1C,EAAK,KAC1B6C,EAAQ,MACR,OACA,OACA,cACA,oBACF;CAkBA,OAjBAE,EACEzD,EAAoBoD,GAAgBD,EAAmBC,CAAc,CAAC,CACxE,GAeO;EACL,SAAS,CAAC;EACV;EACA,SAAS,CAAC;EACV,YAAY,CAAC;EACb,UAAU,CAAC;EACX,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAA,MArB4B5C,EAG5B;GACE;GACA;GACA;GACA;GACA;EACF,GACA+C,CACF;CAWA;AACF"}
@@ -1,7 +1,7 @@
1
1
  import { n as e } from "./logger-t1HxmpG2.js";
2
- import { i as t, n, t as r } from "./pocketbase-BTLraFEp.js";
3
- import { r as i } from "./modify-file-CoFH_Y5n.js";
4
- import { n as a } from "./site-BHCX2hbj.js";
2
+ import { i as t, n, t as r } from "./pocketbase-S8lUt0nI.js";
3
+ import { r as i } from "./modify-file-CgJIza72.js";
4
+ import { n as a } from "./site-C8Wcg6LT.js";
5
5
  import { modifySvelteConfigRemote as o } from "./modify-svelte-config-remote-wE5K2bU_.js";
6
6
  import { t as s } from "./dedent-CCUOcPFW.js";
7
7
  import { _ as c, a as l, o as u, r as d } from "./ts-morph-helpers-B4KZXP44.js";
@@ -325,4 +325,4 @@ async function O(s) {
325
325
  }
326
326
  export { O as generate };
327
327
 
328
- //# sourceMappingURL=generate.runtime-BBjaUxGz.js.map
328
+ //# sourceMappingURL=generate.runtime-BU-4sjyu.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"generate.runtime-BBjaUxGz.js","names":["FAILURE_HINT","NOT_FOUND_HINT","getLogger","withPocketbase","getMigrationFile","modifyOutcomeToFile","ensureSiteFile","dedent","withInMemoryScript","ensurePropsBinding","formatLikeSource","ensureImports","SvelteFile","fs","path","modifyLayoutServer","layoutPath","snippet","originalSource","sourceFile","Project","addUserProp","obj","loadArrow","loadFn","varDecl","SyntaxKind","directArrow","init","innerArrow","innerFnExpr","maybeFn","fnLike","params","first","original","nameNode","obp","el","parts","tail","currentName","body","expr","ret","inner","bodyExpr","AUTH_MENU_NAVBAR_ITEM","IMPORT_SNIPPET","FAILURE_HINT$1","NOT_FOUND_HINT$1","modifyRootLayoutSvelte","file","out","source","sf","FAILURE_HINT","NOT_FOUND_HINT","modifyHooksServer","hooksServerPath","callExpr","ce","args","firstArg","optionsObj","authProp","authInit","authObj","prProp","prInit","arr","COOKIE_LOGIN","modifyTestSetup","setupPath","helper","generate","options","logger","creates","pb","input","migrationDelay","userCollection","verificationTemplate","resetPasswordTemplate","confirmEmailChangeTemplate","migrationFile","modifies","pushResult","layoutServerFile","layoutCandidates","layoutFile","p","hooksServerFile","testSetupFile","remote","modifySvelteConfigRemote","siteFile"],"sources":["../../src/patterns/enable/auth-remote/modifies/+layout.server.ts","../../src/patterns/enable/auth-remote/modifies/root-layout.svelte.ts","../../src/patterns/enable/auth-remote/modifies/hooks.server.ts","../../src/patterns/enable/auth-remote/modifies/test-setup.ts","../../src/patterns/enable/auth-remote/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { Project, SyntaxKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport { formatLikeSource } from \"../../../../runtime/ts-morph-helpers\";\n\nexport function modifyLayoutServer(layoutPath: string): ModifyOutcome {\n if (!fs.existsSync(layoutPath)) {\n const snippet = dedent`\n\t\t\texport const load = async ({ locals }) => {\n\t\t\t\treturn { user: locals.pb.authStore.record };\n\t\t\t};\n\t\t`;\n\n fs.writeFileSync(layoutPath, snippet);\n return { status: \"success\", changed: true };\n }\n\n const originalSource = fs.readFileSync(layoutPath, \"utf8\");\n const project = new Project();\n const sourceFile = project.addSourceFileAtPath(layoutPath);\n\n // helper to add user property to an object literal if missing\n const addUserProp = (obj: import(\"ts-morph\").ObjectLiteralExpression) => {\n const hasUser = !!obj.getProperty(\"user\");\n if (!hasUser) {\n obj.addPropertyAssignment({\n name: \"user\",\n initializer: \"locals.pb.authStore.record\",\n });\n }\n };\n\n // find existing exported load (function or const with arrow)\n let loadArrow: import(\"ts-morph\").ArrowFunction | undefined;\n let loadFn:\n | import(\"ts-morph\").FunctionDeclaration\n | import(\"ts-morph\").FunctionExpression\n | undefined;\n\n const varDecl = sourceFile.getVariableDeclaration(\"load\");\n if (varDecl) {\n const vs = varDecl.getFirstAncestorByKind(SyntaxKind.VariableStatement);\n const isExported = !!vs?.hasExportKeyword();\n if (isExported) {\n const directArrow = varDecl.getInitializerIfKind(\n SyntaxKind.ArrowFunction,\n );\n if (directArrow) {\n loadArrow = directArrow;\n } else {\n const init = varDecl.getInitializer();\n if (init) {\n const innerArrow = init.getFirstDescendantByKind(\n SyntaxKind.ArrowFunction,\n );\n if (innerArrow) {\n loadArrow = innerArrow;\n } else {\n const innerFnExpr = init.getFirstDescendantByKind(\n SyntaxKind.FunctionExpression,\n );\n if (innerFnExpr) {\n loadFn = innerFnExpr;\n }\n }\n }\n }\n }\n }\n\n if (!loadArrow) {\n const maybeFn = sourceFile.getFunction(\"load\");\n if (maybeFn && maybeFn.isExported()) {\n loadFn = maybeFn;\n }\n }\n\n // if no load found, create one\n if (!loadArrow && !loadFn) {\n sourceFile.addFunction({\n isExported: true,\n isAsync: true,\n name: \"load\",\n parameters: [{ name: \"{ locals }\" }],\n statements: `return { user: locals.pb.authStore.record };`,\n });\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n }\n\n // normalize function-like to a single handle\n const fnLike:\n | import(\"ts-morph\").ArrowFunction\n | import(\"ts-morph\").FunctionDeclaration\n | import(\"ts-morph\").FunctionExpression = (loadArrow ?? loadFn!) as any;\n\n // ensure first parameter destructures locals, preserving existing information\n const params = fnLike.getParameters();\n if (params.length === 0) {\n fnLike.insertParameter(0, { name: \"{ locals }\" });\n } else {\n const first = params[0];\n const original = first.getStructure();\n const nameNode = first.getNameNode();\n if (nameNode.getKind() === SyntaxKind.ObjectBindingPattern) {\n const obp = nameNode as import(\"ts-morph\").ObjectBindingPattern;\n const hasLocals = obp\n .getElements()\n .some((el) => el.getName() === \"locals\");\n if (!hasLocals) {\n const parts = obp\n .getElements()\n .map((el) => el.getText())\n .filter(Boolean);\n const tail = parts.length > 0 ? \", \" + parts.join(\", \") : \"\";\n first.set({\n name: `{ locals${tail} }`,\n type: original.type,\n initializer: (original as any).initializer,\n });\n }\n } else {\n const currentName = first.getName();\n if (currentName !== \"locals\") {\n first.set({\n name: `{ locals, ...${currentName} }`,\n type: original.type,\n initializer: (original as any).initializer,\n });\n }\n }\n }\n\n // add user to returned object literals without altering other properties\n if (loadArrow) {\n const body = loadArrow.getBody();\n if (body.getKind() === SyntaxKind.Block) {\n const returns = body.getDescendantsOfKind(SyntaxKind.ReturnStatement);\n returns.forEach((ret) => {\n const expr = ret.getExpression();\n if (!expr) return;\n if (expr.getKind() === SyntaxKind.ObjectLiteralExpression) {\n addUserProp(expr as import(\"ts-morph\").ObjectLiteralExpression);\n } else if (expr.getKind() === SyntaxKind.ParenthesizedExpression) {\n const inner = (\n expr as import(\"ts-morph\").ParenthesizedExpression\n ).getExpression();\n if (inner.getKind() === SyntaxKind.ObjectLiteralExpression) {\n addUserProp(inner as import(\"ts-morph\").ObjectLiteralExpression);\n }\n }\n });\n } else {\n // concise body\n const bodyExpr = body as import(\"ts-morph\").Expression;\n if (bodyExpr.getKind() === SyntaxKind.ParenthesizedExpression) {\n const inner = (\n bodyExpr as import(\"ts-morph\").ParenthesizedExpression\n ).getExpression();\n if (inner.getKind() === SyntaxKind.ObjectLiteralExpression) {\n addUserProp(inner as import(\"ts-morph\").ObjectLiteralExpression);\n }\n } else if (bodyExpr.getKind() === SyntaxKind.ObjectLiteralExpression) {\n addUserProp(bodyExpr as import(\"ts-morph\").ObjectLiteralExpression);\n }\n }\n } else if (loadFn) {\n const body = loadFn.getBody();\n if (body) {\n const returns = body.getDescendantsOfKind(SyntaxKind.ReturnStatement);\n returns.forEach((ret) => {\n const expr = ret.getExpression();\n if (!expr) return;\n if (expr.getKind() === SyntaxKind.ObjectLiteralExpression) {\n addUserProp(expr as import(\"ts-morph\").ObjectLiteralExpression);\n } else if (expr.getKind() === SyntaxKind.ParenthesizedExpression) {\n const inner = (\n expr as import(\"ts-morph\").ParenthesizedExpression\n ).getExpression();\n if (inner.getKind() === SyntaxKind.ObjectLiteralExpression) {\n addUserProp(inner as import(\"ts-morph\").ObjectLiteralExpression);\n }\n }\n });\n }\n }\n\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return {\n status: \"success\",\n changed: sourceFile.getFullText() !== originalSource,\n };\n}\n","import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport {\n ensureImports,\n ensurePropsBinding,\n withInMemoryScript,\n} from \"../../../../runtime/ts-morph-helpers\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst AUTH_MENU_NAVBAR_ITEM = `\n\t\t<Navbar.Item\n\t\t\tclass=\"flex flex-col md:flex-row items-center space-y-2 md:space-y-0 md:space-x-4\"\n\t\t>\n\t\t\t<AuthMenu.Root>\n\t\t\t\t{#snippet user()}\n\t\t\t\t\t<AuthMenu.Trigger>\n\t\t\t\t\t\t<UserAvatar user={data.user} />\n\t\t\t\t\t</AuthMenu.Trigger>\n\n\t\t\t\t\t<AuthMenu.Content align=\"end\">\n\t\t\t\t\t\t<AuthMenu.Item href=\"/dashboard\">Dashboard</AuthMenu.Item>\n\t\t\t\t\t\t<AuthMenu.Group>\n\t\t\t\t\t\t\t<AuthMenu.Item href=\"/settings\">Settings</AuthMenu.Item>\n\t\t\t\t\t\t\t<AuthMenu.Item>\n\t\t\t\t\t\t\t\t<form action=\"/logout\" method=\"post\">\n\t\t\t\t\t\t\t\t\t<button type=\"submit\" class=\"contents\">Logout</button>\n\t\t\t\t\t\t\t\t</form>\n\t\t\t\t\t\t\t</AuthMenu.Item>\n\t\t\t\t\t\t</AuthMenu.Group>\n\t\t\t\t\t</AuthMenu.Content>\n\t\t\t\t{/snippet}\n\n\t\t\t\t{#snippet guest()}\n\t\t\t\t\t<Button\n\t\t\t\t\t\tclass=\"w-full justify-start md:justify-center md:w-auto\"\n\t\t\t\t\t\tvariant=\"ghost\"\n\t\t\t\t\t\thref=\"/login\">Login</Button\n\t\t\t\t\t>\n\t\t\t\t\t<Button\n\t\t\t\t\t\tclass=\"w-full justify-start md:justify-center md:w-auto\"\n\t\t\t\t\t\tvariant=\"outline\"\n\t\t\t\t\t\thref=\"/signup\">Sign up</Button\n\t\t\t\t\t>\n\t\t\t\t{/snippet}\n\t\t\t</AuthMenu.Root>\n\t\t</Navbar.Item>\n\t`;\n\nconst IMPORT_SNIPPET = dedent`\n import * as AuthMenu from '#lib/components/ui/auth-menu/index.js';\n import UserAvatar from '#lib/components/user-avatar.svelte';\n`;\n\nconst FAILURE_HINT = [\n \"Add the auth menu inside your <Navbar.List> in the root layout.\",\n \"\",\n \"Imports to add to the <script> tag:\",\n \"\",\n IMPORT_SNIPPET,\n \"\",\n \"Markup to add inside <Navbar.List>:\",\n AUTH_MENU_NAVBAR_ITEM,\n].join(\"\\n\");\n\nconst NOT_FOUND_HINT = [\n \"Create a root layout that includes an auth menu inside <Navbar.List>.\",\n \"\",\n \"Imports for the <script> tag:\",\n \"\",\n IMPORT_SNIPPET,\n \"\",\n \"Markup inside <Navbar.List>:\",\n AUTH_MENU_NAVBAR_ITEM,\n].join(\"\\n\");\n\nexport function modifyRootLayoutSvelte(layoutPath: string): ModifyOutcome {\n if (!fs.existsSync(layoutPath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const file = SvelteFile.fromPath(layoutPath);\n if (!file.hasElement(\"Navbar.List\")) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n if (file.hasElement(\"AuthMenu.Root\")) {\n return { status: \"success\", changed: false };\n }\n\n file.modifyScript((source) => {\n const { source: out } = withInMemoryScript(source, (sf) => {\n ensureImports(sf, [\n {\n namespaceImport: \"AuthMenu\",\n moduleSpecifier: \"#lib/components/ui/auth-menu/index.js\",\n },\n {\n defaultImport: \"UserAvatar\",\n moduleSpecifier: \"#lib/components/user-avatar.svelte\",\n },\n ]);\n // The menu reads `data.user`; the template's layout takes no props.\n ensurePropsBinding(sf, \"data\");\n });\n return out;\n });\n\n file.insertBeforeClosingTag(\"Navbar.List\", AUTH_MENU_NAVBAR_ITEM);\n file.writeTo(layoutPath);\n return { status: \"success\", changed: file.hasChanged() };\n}\n","import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { Project, SyntaxKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport { formatLikeSource } from \"../../../../runtime/ts-morph-helpers\";\n\nconst FAILURE_HINT = dedent`\n Configure handlePocketbase() with the auth option in hooks.server.ts:\n\n handlePocketbase({\n auth: { protectedRoutes: ['/(app)'] },\n });\n`;\n\nconst NOT_FOUND_HINT = dedent`\n Create src/hooks.server.ts with handlePocketbase:\n\n import { handlePocketbase } from '@velastack/pocketbase';\n\n export const handle = handlePocketbase({\n auth: { protectedRoutes: ['/(app)'] },\n });\n`;\n\nexport function modifyHooksServer(hooksServerPath: string): ModifyOutcome {\n if (!fs.existsSync(hooksServerPath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const originalSource = fs.readFileSync(hooksServerPath, \"utf8\");\n const project = new Project();\n const sourceFile = project.addSourceFileAtPath(hooksServerPath);\n\n // Find the handlePocketbase(...) call\n const callExpr = sourceFile\n .getDescendantsOfKind(SyntaxKind.CallExpression)\n .find((ce) => ce.getExpression().getText() === \"handlePocketbase\");\n\n if (!callExpr) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n const args = callExpr.getArguments();\n if (args.length === 0) {\n callExpr.addArgument(`{ auth: { protectedRoutes: ['/(app)'] } }`);\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n }\n\n const firstArg = args[0];\n if (firstArg.getKind() !== SyntaxKind.ObjectLiteralExpression) {\n callExpr.insertArgument(0, `{ auth: { protectedRoutes: ['/(app)'] } }`);\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n }\n\n const optionsObj = firstArg.asKindOrThrow(SyntaxKind.ObjectLiteralExpression);\n\n // Ensure auth property exists\n const authProp = optionsObj.getProperty(\"auth\");\n if (!authProp) {\n optionsObj.addPropertyAssignment({\n name: \"auth\",\n initializer: `{ protectedRoutes: ['/(app)'] }`,\n });\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n }\n\n // If auth exists, ensure protectedRoutes includes '/(app)'\n if (authProp.getKind() === SyntaxKind.PropertyAssignment) {\n const authInit = (\n authProp as import(\"ts-morph\").PropertyAssignment\n ).getInitializer();\n if (authInit && authInit.getKind() === SyntaxKind.ObjectLiteralExpression) {\n const authObj = authInit as import(\"ts-morph\").ObjectLiteralExpression;\n const prProp = authObj.getProperty(\"protectedRoutes\");\n if (!prProp) {\n authObj.addPropertyAssignment({\n name: \"protectedRoutes\",\n initializer: `['/(app)']`,\n });\n } else if (prProp.getKind() === SyntaxKind.PropertyAssignment) {\n const prInit = (\n prProp as import(\"ts-morph\").PropertyAssignment\n ).getInitializer();\n if (prInit && prInit.getKind() === SyntaxKind.ArrayLiteralExpression) {\n const arr = prInit as import(\"ts-morph\").ArrayLiteralExpression;\n const hasApp = arr\n .getElements()\n .some((el) => el.getText().replace(/['\"`]/g, \"\") === \"/(app)\");\n if (!hasApp) {\n arr.addElement(`'/(app)'`);\n }\n } else {\n (prProp as import(\"ts-morph\").PropertyAssignment).setInitializer(\n `['/(app)']`,\n );\n }\n }\n }\n }\n\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return {\n status: \"success\",\n changed: sourceFile.getFullText() !== originalSource,\n };\n}\n","import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { Project } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst COOKIE_LOGIN = dedent`\n // Login is a remote function, so there is no form action to post to: carry\n // the session the way the browser does, in the \\`pb_auth\\` cookie.\n async function authenticateUser(agent: Agent, user: { email?: string }) {\n // Logs in with the password, so it needs the email (made optional by\n // enable-whatsapp, for accounts that sign in with a phone number).\n if (!user.email) {\n throw new Error('authenticateUser needs a user with an email');\n }\n const client = new PocketBase(process.env.POCKETBASE_URL!);\n await client.collection(\"users\").authWithPassword(user.email, testUserPassword);\n agent.set(\"Cookie\", client.authStore.exportToCookie().split(\";\")[0]);\n }\n`;\n\n/**\n * The template's server-test helper logs in by posting the `/login` form\n * action, which this pattern replaces with a remote function. A project\n * without the helper (or with its own) has nothing to fix.\n */\nexport function modifyTestSetup(setupPath: string): ModifyOutcome {\n if (!fs.existsSync(setupPath)) {\n return { status: \"success\", changed: false };\n }\n\n const project = new Project();\n const sourceFile = project.addSourceFileAtPath(setupPath);\n const helper = sourceFile.getFunction(\"authenticateUser\");\n\n if (!helper || !/\\.post\\(\\s*[\"'`]\\/login[\"'`]\\s*\\)/.test(helper.getText())) {\n return { status: \"success\", changed: false };\n }\n\n helper.replaceWithText(COOKIE_LOGIN);\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n}\n","import path from \"node:path\";\nimport fs from \"node:fs\";\nimport { Options, Result, File } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport {\n getMigrationFile,\n migrationDelay,\n withPocketbase,\n} from \"../../../runtime/pocketbase\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { ensureSiteFile } from \"../../../runtime/site\";\nimport { modifySvelteConfigRemote } from \"../../../runtime/modify-svelte-config-remote\";\n\nimport { modifyLayoutServer } from \"./modifies/+layout.server\";\nimport { modifyRootLayoutSvelte } from \"./modifies/root-layout.svelte\";\nimport { modifyHooksServer } from \"./modifies/hooks.server\";\nimport { modifyTestSetup } from \"./modifies/test-setup\";\n\nexport async function generate(options: Options) {\n const { input } = options;\n const logger = getLogger(options);\n\n const creates: File[] = [];\n\n // Update PocketBase\n await withPocketbase(options.root, async (pb) => {\n logger.info(\"Updating PocketBase mail settings\");\n await pb.settings.update({\n meta: {\n senderName: input.senderName,\n senderAddress: input.senderAddress,\n },\n });\n await migrationDelay();\n\n const userCollection = await pb.collections.getOne(\"users\");\n\n if (!userCollection) {\n throw new Error(\"Users collection not found\");\n }\n\n const verificationTemplate =\n userCollection.verificationTemplate.body.replace(\n \"{APP_URL}/_/#/auth/confirm-verification/{TOKEN}\",\n \"{APP_URL}/confirm-verification/{TOKEN}\",\n );\n const resetPasswordTemplate =\n userCollection.resetPasswordTemplate.body.replace(\n \"{APP_URL}/_/#/auth/confirm-reset/{TOKEN}\",\n \"{APP_URL}/confirm-reset/{TOKEN}\",\n );\n const confirmEmailChangeTemplate =\n userCollection.confirmEmailChangeTemplate.body.replace(\n \"{APP_URL}/_/#/auth/confirm-email-change/{TOKEN}\",\n \"{APP_URL}/confirm-email-change/{TOKEN}\",\n );\n\n logger.info(\"Locking down users collection rules and email templates\");\n // Update user auth rules to lock down access to the user's own account\n await pb.collections.update(\"users\", {\n listRule: \"@request.auth.id = id\",\n viewRule: \"@request.auth.id = id\",\n createRule: \"@request.auth.id = id\",\n updateRule: \"@request.auth.id = id\",\n deleteRule: \"@request.auth.id = id\",\n\n // Update email templates to VelaStack auth urls\n verificationTemplate: {\n body: verificationTemplate,\n },\n resetPasswordTemplate: {\n body: resetPasswordTemplate,\n },\n confirmEmailChangeTemplate: {\n body: confirmEmailChangeTemplate,\n },\n });\n await migrationDelay();\n\n const migrationFile = getMigrationFile(\"users\", \"updated\", options);\n if (migrationFile) {\n creates.push({\n path: migrationFile,\n language: \"ts\",\n content: fs.readFileSync(migrationFile, \"utf8\"),\n status: \"success\",\n });\n }\n });\n\n // Modify files\n const modifies: File[] = [];\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n logger.info(\"Modifying +layout.server.ts\");\n const layoutServerFile = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"+layout.server.ts\",\n );\n pushResult(\n modifyOutcomeToFile(layoutServerFile, modifyLayoutServer(layoutServerFile)),\n );\n\n logger.info(\"Modifying root layout\");\n // TODO: make this more robust by searching for Navbar.Root > Navbar.List\n // src/routes/(public)/root-layout.svelte is what vela creates by default\n const layoutCandidates = [\n path.join(options.root, \"src\", \"routes\", \"(public)\", \"root-layout.svelte\"),\n path.join(options.root, \"src\", \"routes\", \"root-layout.svelte\"),\n path.join(options.root, \"src\", \"routes\", \"(public)\", \"+layout.svelte\"),\n path.join(options.root, \"src\", \"routes\", \"+layout.svelte\"),\n ];\n const layoutFile =\n layoutCandidates.find((p) => fs.existsSync(p)) ?? layoutCandidates[0];\n pushResult(\n modifyOutcomeToFile(layoutFile, modifyRootLayoutSvelte(layoutFile)),\n );\n\n logger.info(\"Modifying hooks.server.ts\");\n const hooksServerFile = path.join(options.root, \"src\", \"hooks.server.ts\");\n pushResult(\n modifyOutcomeToFile(hooksServerFile, modifyHooksServer(hooksServerFile)),\n );\n\n logger.info(\"Modifying test/setup.ts\");\n const testSetupFile = path.join(options.root, \"test\", \"setup.ts\");\n pushResult(\n modifyOutcomeToFile(testSetupFile, modifyTestSetup(testSetupFile)),\n );\n\n logger.info(\"Modifying config for remote functions\");\n const remote = modifySvelteConfigRemote(options.root);\n pushResult(modifyOutcomeToFile(remote.filePath, remote.outcome));\n\n // The auth pages and the app sidebar show `site.name`.\n const siteFile = await ensureSiteFile(options);\n\n return {\n creates: siteFile ? [...creates, siteFile] : creates,\n modifies,\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n } satisfies Result;\n}\n"],"mappings":";;;;;;;;;;;;AAMA,SAAgBe,EAAmB,GAAmC;CACpE,IAAI,CAACF,EAAG,WAAWG,CAAU,GAAG;EAC9B,IAAMC,IAAU,CAAM;;;;;EAOtB,OADAJ,EAAG,cAAcG,GAAYC,CAAO,GAC7B;GAAE,QAAQ;GAAW,SAAS;EAAK;CA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ger","withPocketbase","getMigrationFile","modifyOutcomeToFile","ensureSiteFile","dedent","withInMemoryScript","ensurePropsBinding","formatLikeSource","ensureImports","SvelteFile","fs","path","modifyLayoutServer","layoutPath","snippet","originalSource","sourceFile","Project","addUserProp","obj","loadArrow","loadFn","varDecl","SyntaxKind","directArrow","init","innerArrow","innerFnExpr","maybeFn","fnLike","params","first","original","nameNode","obp","el","parts","tail","currentName","body","expr","ret","inner","bodyExpr","AUTH_MENU_NAVBAR_ITEM","IMPORT_SNIPPET","FAILURE_HINT$1","NOT_FOUND_HINT$1","modifyRootLayoutSvelte","file","out","source","sf","FAILURE_HINT","NOT_FOUND_HINT","modifyHooksServer","hooksServerPath","callExpr","ce","args","firstArg","optionsObj","authProp","authInit","authObj","prProp","prInit","arr","COOKIE_LOGIN","modifyTestSetup","setupPath","helper","generate","options","logger","creates","pb","input","migrationDelay","userCollection","verificationTemplate","resetPasswordTemplate","confirmEmailChangeTemplate","migrationFile","modifies","pushResult","layoutServerFile","layoutCandidates","layoutFile","p","hooksServerFile","testSetupFile","remote","modifySvelteConfigRemote","siteFile"],"sources":["../../src/patterns/enable/auth-remote/modifies/+layout.server.ts","../../src/patterns/enable/auth-remote/modifies/root-layout.svelte.ts","../../src/patterns/enable/auth-remote/modifies/hooks.server.ts","../../src/patterns/enable/auth-remote/modifies/test-setup.ts","../../src/patterns/enable/auth-remote/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { Project, SyntaxKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport { formatLikeSource } from \"../../../../runtime/ts-morph-helpers\";\n\nexport function modifyLayoutServer(layoutPath: string): ModifyOutcome {\n if (!fs.existsSync(layoutPath)) {\n const snippet = dedent`\n\t\t\texport const load = async ({ locals }) => {\n\t\t\t\treturn { user: locals.pb.authStore.record };\n\t\t\t};\n\t\t`;\n\n fs.writeFileSync(layoutPath, snippet);\n return { status: \"success\", changed: true };\n }\n\n const originalSource = fs.readFileSync(layoutPath, \"utf8\");\n const project = new Project();\n const sourceFile = project.addSourceFileAtPath(layoutPath);\n\n // helper to add user property to an object literal if missing\n const addUserProp = (obj: import(\"ts-morph\").ObjectLiteralExpression) => {\n const hasUser = !!obj.getProperty(\"user\");\n if (!hasUser) {\n obj.addPropertyAssignment({\n name: \"user\",\n initializer: \"locals.pb.authStore.record\",\n });\n }\n };\n\n // find existing exported load (function or const with arrow)\n let loadArrow: import(\"ts-morph\").ArrowFunction | undefined;\n let loadFn:\n | import(\"ts-morph\").FunctionDeclaration\n | import(\"ts-morph\").FunctionExpression\n | undefined;\n\n const varDecl = sourceFile.getVariableDeclaration(\"load\");\n if (varDecl) {\n const vs = varDecl.getFirstAncestorByKind(SyntaxKind.VariableStatement);\n const isExported = !!vs?.hasExportKeyword();\n if (isExported) {\n const directArrow = varDecl.getInitializerIfKind(\n SyntaxKind.ArrowFunction,\n );\n if (directArrow) {\n loadArrow = directArrow;\n } else {\n const init = varDecl.getInitializer();\n if (init) {\n const innerArrow = init.getFirstDescendantByKind(\n SyntaxKind.ArrowFunction,\n );\n if (innerArrow) {\n loadArrow = innerArrow;\n } else {\n const innerFnExpr = init.getFirstDescendantByKind(\n SyntaxKind.FunctionExpression,\n );\n if (innerFnExpr) {\n loadFn = innerFnExpr;\n }\n }\n }\n }\n }\n }\n\n if (!loadArrow) {\n const maybeFn = sourceFile.getFunction(\"load\");\n if (maybeFn && maybeFn.isExported()) {\n loadFn = maybeFn;\n }\n }\n\n // if no load found, create one\n if (!loadArrow && !loadFn) {\n sourceFile.addFunction({\n isExported: true,\n isAsync: true,\n name: \"load\",\n parameters: [{ name: \"{ locals }\" }],\n statements: `return { user: locals.pb.authStore.record };`,\n });\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n }\n\n // normalize function-like to a single handle\n const fnLike:\n | import(\"ts-morph\").ArrowFunction\n | import(\"ts-morph\").FunctionDeclaration\n | import(\"ts-morph\").FunctionExpression = (loadArrow ?? loadFn!) as any;\n\n // ensure first parameter destructures locals, preserving existing information\n const params = fnLike.getParameters();\n if (params.length === 0) {\n fnLike.insertParameter(0, { name: \"{ locals }\" });\n } else {\n const first = params[0];\n const original = first.getStructure();\n const nameNode = first.getNameNode();\n if (nameNode.getKind() === SyntaxKind.ObjectBindingPattern) {\n const obp = nameNode as import(\"ts-morph\").ObjectBindingPattern;\n const hasLocals = obp\n .getElements()\n .some((el) => el.getName() === \"locals\");\n if (!hasLocals) {\n const parts = obp\n .getElements()\n .map((el) => el.getText())\n .filter(Boolean);\n const tail = parts.length > 0 ? \", \" + parts.join(\", \") : \"\";\n first.set({\n name: `{ locals${tail} }`,\n type: original.type,\n initializer: (original as any).initializer,\n });\n }\n } else {\n const currentName = first.getName();\n if (currentName !== \"locals\") {\n first.set({\n name: `{ locals, ...${currentName} }`,\n type: original.type,\n initializer: (original as any).initializer,\n });\n }\n }\n }\n\n // add user to returned object literals without altering other properties\n if (loadArrow) {\n const body = loadArrow.getBody();\n if (body.getKind() === SyntaxKind.Block) {\n const returns = body.getDescendantsOfKind(SyntaxKind.ReturnStatement);\n returns.forEach((ret) => {\n const expr = ret.getExpression();\n if (!expr) return;\n if (expr.getKind() === SyntaxKind.ObjectLiteralExpression) {\n addUserProp(expr as import(\"ts-morph\").ObjectLiteralExpression);\n } else if (expr.getKind() === SyntaxKind.ParenthesizedExpression) {\n const inner = (\n expr as import(\"ts-morph\").ParenthesizedExpression\n ).getExpression();\n if (inner.getKind() === SyntaxKind.ObjectLiteralExpression) {\n addUserProp(inner as import(\"ts-morph\").ObjectLiteralExpression);\n }\n }\n });\n } else {\n // concise body\n const bodyExpr = body as import(\"ts-morph\").Expression;\n if (bodyExpr.getKind() === SyntaxKind.ParenthesizedExpression) {\n const inner = (\n bodyExpr as import(\"ts-morph\").ParenthesizedExpression\n ).getExpression();\n if (inner.getKind() === SyntaxKind.ObjectLiteralExpression) {\n addUserProp(inner as import(\"ts-morph\").ObjectLiteralExpression);\n }\n } else if (bodyExpr.getKind() === SyntaxKind.ObjectLiteralExpression) {\n addUserProp(bodyExpr as import(\"ts-morph\").ObjectLiteralExpression);\n }\n }\n } else if (loadFn) {\n const body = loadFn.getBody();\n if (body) {\n const returns = body.getDescendantsOfKind(SyntaxKind.ReturnStatement);\n returns.forEach((ret) => {\n const expr = ret.getExpression();\n if (!expr) return;\n if (expr.getKind() === SyntaxKind.ObjectLiteralExpression) {\n addUserProp(expr as import(\"ts-morph\").ObjectLiteralExpression);\n } else if (expr.getKind() === SyntaxKind.ParenthesizedExpression) {\n const inner = (\n expr as import(\"ts-morph\").ParenthesizedExpression\n ).getExpression();\n if (inner.getKind() === SyntaxKind.ObjectLiteralExpression) {\n addUserProp(inner as import(\"ts-morph\").ObjectLiteralExpression);\n }\n }\n });\n }\n }\n\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return {\n status: \"success\",\n changed: sourceFile.getFullText() !== originalSource,\n };\n}\n","import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport {\n ensureImports,\n ensurePropsBinding,\n withInMemoryScript,\n} from \"../../../../runtime/ts-morph-helpers\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst AUTH_MENU_NAVBAR_ITEM = `\n\t\t<Navbar.Item\n\t\t\tclass=\"flex flex-col md:flex-row items-center space-y-2 md:space-y-0 md:space-x-4\"\n\t\t>\n\t\t\t<AuthMenu.Root>\n\t\t\t\t{#snippet user()}\n\t\t\t\t\t<AuthMenu.Trigger>\n\t\t\t\t\t\t<UserAvatar user={data.user} />\n\t\t\t\t\t</AuthMenu.Trigger>\n\n\t\t\t\t\t<AuthMenu.Content align=\"end\">\n\t\t\t\t\t\t<AuthMenu.Item href=\"/dashboard\">Dashboard</AuthMenu.Item>\n\t\t\t\t\t\t<AuthMenu.Group>\n\t\t\t\t\t\t\t<AuthMenu.Item href=\"/settings\">Settings</AuthMenu.Item>\n\t\t\t\t\t\t\t<AuthMenu.Item>\n\t\t\t\t\t\t\t\t<form action=\"/logout\" method=\"post\">\n\t\t\t\t\t\t\t\t\t<button type=\"submit\" class=\"contents\">Logout</button>\n\t\t\t\t\t\t\t\t</form>\n\t\t\t\t\t\t\t</AuthMenu.Item>\n\t\t\t\t\t\t</AuthMenu.Group>\n\t\t\t\t\t</AuthMenu.Content>\n\t\t\t\t{/snippet}\n\n\t\t\t\t{#snippet guest()}\n\t\t\t\t\t<Button\n\t\t\t\t\t\tclass=\"w-full justify-start md:justify-center md:w-auto\"\n\t\t\t\t\t\tvariant=\"ghost\"\n\t\t\t\t\t\thref=\"/login\">Login</Button\n\t\t\t\t\t>\n\t\t\t\t\t<Button\n\t\t\t\t\t\tclass=\"w-full justify-start md:justify-center md:w-auto\"\n\t\t\t\t\t\tvariant=\"outline\"\n\t\t\t\t\t\thref=\"/signup\">Sign up</Button\n\t\t\t\t\t>\n\t\t\t\t{/snippet}\n\t\t\t</AuthMenu.Root>\n\t\t</Navbar.Item>\n\t`;\n\nconst IMPORT_SNIPPET = dedent`\n import * as AuthMenu from '#lib/components/ui/auth-menu/index.js';\n import UserAvatar from '#lib/components/user-avatar.svelte';\n`;\n\nconst FAILURE_HINT = [\n \"Add the auth menu inside your <Navbar.List> in the root layout.\",\n \"\",\n \"Imports to add to the <script> tag:\",\n \"\",\n IMPORT_SNIPPET,\n \"\",\n \"Markup to add inside <Navbar.List>:\",\n AUTH_MENU_NAVBAR_ITEM,\n].join(\"\\n\");\n\nconst NOT_FOUND_HINT = [\n \"Create a root layout that includes an auth menu inside <Navbar.List>.\",\n \"\",\n \"Imports for the <script> tag:\",\n \"\",\n IMPORT_SNIPPET,\n \"\",\n \"Markup inside <Navbar.List>:\",\n AUTH_MENU_NAVBAR_ITEM,\n].join(\"\\n\");\n\nexport function modifyRootLayoutSvelte(layoutPath: string): ModifyOutcome {\n if (!fs.existsSync(layoutPath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const file = SvelteFile.fromPath(layoutPath);\n if (!file.hasElement(\"Navbar.List\")) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n if (file.hasElement(\"AuthMenu.Root\")) {\n return { status: \"success\", changed: false };\n }\n\n file.modifyScript((source) => {\n const { source: out } = withInMemoryScript(source, (sf) => {\n ensureImports(sf, [\n {\n namespaceImport: \"AuthMenu\",\n moduleSpecifier: \"#lib/components/ui/auth-menu/index.js\",\n },\n {\n defaultImport: \"UserAvatar\",\n moduleSpecifier: \"#lib/components/user-avatar.svelte\",\n },\n ]);\n // The menu reads `data.user`; the template's layout takes no props.\n ensurePropsBinding(sf, \"data\");\n });\n return out;\n });\n\n file.insertBeforeClosingTag(\"Navbar.List\", AUTH_MENU_NAVBAR_ITEM);\n file.writeTo(layoutPath);\n return { status: \"success\", changed: file.hasChanged() };\n}\n","import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { Project, SyntaxKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport { formatLikeSource } from \"../../../../runtime/ts-morph-helpers\";\n\nconst FAILURE_HINT = dedent`\n Configure handlePocketbase() with the auth option in hooks.server.ts:\n\n handlePocketbase({\n auth: { protectedRoutes: ['/(app)'] },\n });\n`;\n\nconst NOT_FOUND_HINT = dedent`\n Create src/hooks.server.ts with handlePocketbase:\n\n import { handlePocketbase } from '@velastack/pocketbase';\n\n export const handle = handlePocketbase({\n auth: { protectedRoutes: ['/(app)'] },\n });\n`;\n\nexport function modifyHooksServer(hooksServerPath: string): ModifyOutcome {\n if (!fs.existsSync(hooksServerPath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const originalSource = fs.readFileSync(hooksServerPath, \"utf8\");\n const project = new Project();\n const sourceFile = project.addSourceFileAtPath(hooksServerPath);\n\n // Find the handlePocketbase(...) call\n const callExpr = sourceFile\n .getDescendantsOfKind(SyntaxKind.CallExpression)\n .find((ce) => ce.getExpression().getText() === \"handlePocketbase\");\n\n if (!callExpr) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n const args = callExpr.getArguments();\n if (args.length === 0) {\n callExpr.addArgument(`{ auth: { protectedRoutes: ['/(app)'] } }`);\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n }\n\n const firstArg = args[0];\n if (firstArg.getKind() !== SyntaxKind.ObjectLiteralExpression) {\n callExpr.insertArgument(0, `{ auth: { protectedRoutes: ['/(app)'] } }`);\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n }\n\n const optionsObj = firstArg.asKindOrThrow(SyntaxKind.ObjectLiteralExpression);\n\n // Ensure auth property exists\n const authProp = optionsObj.getProperty(\"auth\");\n if (!authProp) {\n optionsObj.addPropertyAssignment({\n name: \"auth\",\n initializer: `{ protectedRoutes: ['/(app)'] }`,\n });\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n }\n\n // If auth exists, ensure protectedRoutes includes '/(app)'\n if (authProp.getKind() === SyntaxKind.PropertyAssignment) {\n const authInit = (\n authProp as import(\"ts-morph\").PropertyAssignment\n ).getInitializer();\n if (authInit && authInit.getKind() === SyntaxKind.ObjectLiteralExpression) {\n const authObj = authInit as import(\"ts-morph\").ObjectLiteralExpression;\n const prProp = authObj.getProperty(\"protectedRoutes\");\n if (!prProp) {\n authObj.addPropertyAssignment({\n name: \"protectedRoutes\",\n initializer: `['/(app)']`,\n });\n } else if (prProp.getKind() === SyntaxKind.PropertyAssignment) {\n const prInit = (\n prProp as import(\"ts-morph\").PropertyAssignment\n ).getInitializer();\n if (prInit && prInit.getKind() === SyntaxKind.ArrayLiteralExpression) {\n const arr = prInit as import(\"ts-morph\").ArrayLiteralExpression;\n const hasApp = arr\n .getElements()\n .some((el) => el.getText().replace(/['\"`]/g, \"\") === \"/(app)\");\n if (!hasApp) {\n arr.addElement(`'/(app)'`);\n }\n } else {\n (prProp as import(\"ts-morph\").PropertyAssignment).setInitializer(\n `['/(app)']`,\n );\n }\n }\n }\n }\n\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return {\n status: \"success\",\n changed: sourceFile.getFullText() !== originalSource,\n };\n}\n","import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { Project } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst COOKIE_LOGIN = dedent`\n // Login is a remote function, so there is no form action to post to: carry\n // the session the way the browser does, in the \\`pb_auth\\` cookie.\n async function authenticateUser(agent: Agent, user: { email?: string }) {\n // Logs in with the password, so it needs the email (made optional by\n // enable-whatsapp, for accounts that sign in with a phone number).\n if (!user.email) {\n throw new Error('authenticateUser needs a user with an email');\n }\n const client = new PocketBase(process.env.POCKETBASE_URL!);\n await client.collection(\"users\").authWithPassword(user.email, testUserPassword);\n agent.set(\"Cookie\", client.authStore.exportToCookie().split(\";\")[0]);\n }\n`;\n\n/**\n * The template's server-test helper logs in by posting the `/login` form\n * action, which this pattern replaces with a remote function. A project\n * without the helper (or with its own) has nothing to fix.\n */\nexport function modifyTestSetup(setupPath: string): ModifyOutcome {\n if (!fs.existsSync(setupPath)) {\n return { status: \"success\", changed: false };\n }\n\n const project = new Project();\n const sourceFile = project.addSourceFileAtPath(setupPath);\n const helper = sourceFile.getFunction(\"authenticateUser\");\n\n if (!helper || !/\\.post\\(\\s*[\"'`]\\/login[\"'`]\\s*\\)/.test(helper.getText())) {\n return { status: \"success\", changed: false };\n }\n\n helper.replaceWithText(COOKIE_LOGIN);\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n}\n","import path from \"node:path\";\nimport fs from \"node:fs\";\nimport { Options, Result, File } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport {\n getMigrationFile,\n migrationDelay,\n withPocketbase,\n} from \"../../../runtime/pocketbase\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { ensureSiteFile } from \"../../../runtime/site\";\nimport { modifySvelteConfigRemote } from \"../../../runtime/modify-svelte-config-remote\";\n\nimport { modifyLayoutServer } from \"./modifies/+layout.server\";\nimport { modifyRootLayoutSvelte } from \"./modifies/root-layout.svelte\";\nimport { modifyHooksServer } from \"./modifies/hooks.server\";\nimport { modifyTestSetup } from \"./modifies/test-setup\";\n\nexport async function generate(options: Options) {\n const { input } = options;\n const logger = getLogger(options);\n\n const creates: File[] = [];\n\n // Update PocketBase\n await withPocketbase(options.root, async (pb) => {\n logger.info(\"Updating PocketBase mail settings\");\n await pb.settings.update({\n meta: {\n senderName: input.senderName,\n senderAddress: input.senderAddress,\n },\n });\n await migrationDelay();\n\n const userCollection = await pb.collections.getOne(\"users\");\n\n if (!userCollection) {\n throw new Error(\"Users collection not found\");\n }\n\n const verificationTemplate =\n userCollection.verificationTemplate.body.replace(\n \"{APP_URL}/_/#/auth/confirm-verification/{TOKEN}\",\n \"{APP_URL}/confirm-verification/{TOKEN}\",\n );\n const resetPasswordTemplate =\n userCollection.resetPasswordTemplate.body.replace(\n \"{APP_URL}/_/#/auth/confirm-reset/{TOKEN}\",\n \"{APP_URL}/confirm-reset/{TOKEN}\",\n );\n const confirmEmailChangeTemplate =\n userCollection.confirmEmailChangeTemplate.body.replace(\n \"{APP_URL}/_/#/auth/confirm-email-change/{TOKEN}\",\n \"{APP_URL}/confirm-email-change/{TOKEN}\",\n );\n\n logger.info(\"Locking down users collection rules and email templates\");\n // Update user auth rules to lock down access to the user's own account\n await pb.collections.update(\"users\", {\n listRule: \"@request.auth.id = id\",\n viewRule: \"@request.auth.id = id\",\n createRule: \"@request.auth.id = id\",\n updateRule: \"@request.auth.id = id\",\n deleteRule: \"@request.auth.id = id\",\n\n // Update email templates to VelaStack auth urls\n verificationTemplate: {\n body: verificationTemplate,\n },\n resetPasswordTemplate: {\n body: resetPasswordTemplate,\n },\n confirmEmailChangeTemplate: {\n body: confirmEmailChangeTemplate,\n },\n });\n await migrationDelay();\n\n const migrationFile = getMigrationFile(\"users\", \"updated\", options);\n if (migrationFile) {\n creates.push({\n path: migrationFile,\n language: \"ts\",\n content: fs.readFileSync(migrationFile, \"utf8\"),\n status: \"success\",\n });\n }\n });\n\n // Modify files\n const modifies: File[] = [];\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n logger.info(\"Modifying +layout.server.ts\");\n const layoutServerFile = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"+layout.server.ts\",\n );\n pushResult(\n modifyOutcomeToFile(layoutServerFile, modifyLayoutServer(layoutServerFile)),\n );\n\n logger.info(\"Modifying root layout\");\n // TODO: make this more robust by searching for Navbar.Root > Navbar.List\n // src/routes/(public)/root-layout.svelte is what vela creates by default\n const layoutCandidates = [\n path.join(options.root, \"src\", \"routes\", \"(public)\", \"root-layout.svelte\"),\n path.join(options.root, \"src\", \"routes\", \"root-layout.svelte\"),\n path.join(options.root, \"src\", \"routes\", \"(public)\", \"+layout.svelte\"),\n path.join(options.root, \"src\", \"routes\", \"+layout.svelte\"),\n ];\n const layoutFile =\n layoutCandidates.find((p) => fs.existsSync(p)) ?? layoutCandidates[0];\n pushResult(\n modifyOutcomeToFile(layoutFile, modifyRootLayoutSvelte(layoutFile)),\n );\n\n logger.info(\"Modifying hooks.server.ts\");\n const hooksServerFile = path.join(options.root, \"src\", \"hooks.server.ts\");\n pushResult(\n modifyOutcomeToFile(hooksServerFile, modifyHooksServer(hooksServerFile)),\n );\n\n logger.info(\"Modifying test/setup.ts\");\n const testSetupFile = path.join(options.root, \"test\", \"setup.ts\");\n pushResult(\n modifyOutcomeToFile(testSetupFile, modifyTestSetup(testSetupFile)),\n );\n\n logger.info(\"Modifying config for remote functions\");\n const remote = modifySvelteConfigRemote(options.root);\n pushResult(modifyOutcomeToFile(remote.filePath, remote.outcome));\n\n // The auth pages and the app sidebar show `site.name`.\n const siteFile = await ensureSiteFile(options);\n\n return {\n creates: siteFile ? [...creates, siteFile] : creates,\n modifies,\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n } satisfies Result;\n}\n"],"mappings":";;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7C;EACA,SAAS,CAAC;EACV,YAAY,CAAC;EACb,UAAU,CAAC;EACX,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAiB,CAAC;CACpB;AACF"}
@@ -1,5 +1,5 @@
1
1
  import { n as e } from "./logger-t1HxmpG2.js";
2
- import { a as t, r as n } from "./modify-file-CoFH_Y5n.js";
2
+ import { a as t, r as n } from "./modify-file-CgJIza72.js";
3
3
  import { a as r, o as i, s as a, t as o } from "./config-target-DJbVHwHl.js";
4
4
  import { i as s, l as c, n as l, o as u, s as d, t as f } from "./app-d-ts-h33RrYIv.js";
5
5
  import { _ as p, c as m, d as h, g, h as _, m as v, n as y, o as b, s as x, u as S } from "./ts-morph-helpers-B4KZXP44.js";
@@ -426,4 +426,4 @@ async function ge(i) {
426
426
  }
427
427
  export { ge as generate };
428
428
 
429
- //# sourceMappingURL=generate.runtime-Dw6umCTf.js.map
429
+ //# sourceMappingURL=generate.runtime-BXNBWGYr.js.map