@velastack/patterns 0.4.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/dist/chunks/_layout-kkgN0IF7.js.map +1 -1
  2. package/dist/chunks/collections-Dz2fvKnz.js.map +1 -1
  3. package/dist/chunks/compose-handle-D_Rz3Fzo.js.map +1 -1
  4. package/dist/chunks/config-target-Dx3w6WSk.js.map +1 -1
  5. package/dist/chunks/constants-BjyMU5s8.js.map +1 -1
  6. package/dist/chunks/dedent-Gq6Krl4n.js.map +1 -1
  7. package/dist/chunks/dispatch-CXOXPLFk.js.map +1 -1
  8. package/dist/chunks/env-BPfk1VAw.js.map +1 -1
  9. package/dist/chunks/env-vars-C1NUX-bf.js.map +1 -1
  10. package/dist/chunks/env-vars-Cr4lbMD_.js.map +1 -1
  11. package/dist/chunks/env-vars-De0Xs0L2.js.map +1 -1
  12. package/dist/chunks/env-vars-file-B_6esJW3.js.map +1 -1
  13. package/dist/chunks/env-vars-mnRA0hOe.js.map +1 -1
  14. package/dist/chunks/env.preview-uMRKT5Pc.js.map +1 -1
  15. package/dist/chunks/errors-DR3gF_7a.js.map +1 -1
  16. package/dist/chunks/format-result-DZ8De8KY.js.map +1 -1
  17. package/dist/chunks/generate-BW3l5Fxw.js.map +1 -1
  18. package/dist/chunks/generate-DeaBlnK6.js.map +1 -1
  19. package/dist/chunks/generate-DetW_gbr.js.map +1 -1
  20. package/dist/chunks/generate-Gcc8iRkZ.js.map +1 -1
  21. package/dist/chunks/generate-WMJo3QGZ.js.map +1 -1
  22. package/dist/chunks/generate.runtime-1-91UmM8.js.map +1 -1
  23. package/dist/chunks/generate.runtime-6FXJM8hT.js.map +1 -1
  24. package/dist/chunks/generate.runtime-B1jVAnDI.js.map +1 -1
  25. package/dist/chunks/generate.runtime-BA3tDKnn.js.map +1 -1
  26. package/dist/chunks/generate.runtime-BO778G0r.js.map +1 -1
  27. package/dist/chunks/generate.runtime-B_UVGa3q.js.map +1 -1
  28. package/dist/chunks/{generate.runtime-CA7Ofjlx.js → generate.runtime-BgTz41Zg.js} +2 -2
  29. package/dist/chunks/generate.runtime-BgTz41Zg.js.map +1 -0
  30. package/dist/chunks/generate.runtime-C6bSvGMb.js.map +1 -1
  31. package/dist/chunks/generate.runtime-C8zJRNYG.js.map +1 -1
  32. package/dist/chunks/generate.runtime-CCr1lvo4.js.map +1 -1
  33. package/dist/chunks/generate.runtime-CYagyR5c.js.map +1 -1
  34. package/dist/chunks/generate.runtime-Ce_rwzNa.js.map +1 -1
  35. package/dist/chunks/generate.runtime-CexC1Oky.js.map +1 -1
  36. package/dist/chunks/generate.runtime-CnPraLKv.js.map +1 -1
  37. package/dist/chunks/generate.runtime-CslAvllQ.js.map +1 -1
  38. package/dist/chunks/generate.runtime-CuNhY5hn.js.map +1 -1
  39. package/dist/chunks/generate.runtime-DD51OSuL.js.map +1 -1
  40. package/dist/chunks/generate.runtime-DHBRyMAq.js.map +1 -1
  41. package/dist/chunks/{generate.runtime-BXkZob1O.js → generate.runtime-DM4o_QYY.js} +2 -2
  42. package/dist/chunks/{generate.runtime-BXkZob1O.js.map → generate.runtime-DM4o_QYY.js.map} +1 -1
  43. package/dist/chunks/generate.runtime-DV3WmZtb.js.map +1 -1
  44. package/dist/chunks/generate.runtime-D_sQOeQa.js.map +1 -1
  45. package/dist/chunks/generate.runtime-DqD3PW-W.js.map +1 -1
  46. package/dist/chunks/generate.runtime-Dtgw9IQO.js.map +1 -1
  47. package/dist/chunks/generate.runtime-IlBCcXvv.js.map +1 -1
  48. package/dist/chunks/generate.runtime-cwvAoKoH.js.map +1 -1
  49. package/dist/chunks/generate.runtime-kvxmTlQb.js.map +1 -1
  50. package/dist/chunks/generate.runtime-pVLzzpUM.js.map +1 -1
  51. package/dist/chunks/generate.runtime-zJpEufTc.js.map +1 -1
  52. package/dist/chunks/lib-specifier-Cngo1zF_.js.map +1 -1
  53. package/dist/chunks/logger-CQONztPm.js.map +1 -1
  54. package/dist/chunks/modify-file-BlDeeurK.js.map +1 -1
  55. package/dist/chunks/modify-svelte-config-remote-p0TfVzxm.js.map +1 -1
  56. package/dist/chunks/modify-utils-Cw-on_cL.js.map +1 -1
  57. package/dist/chunks/nav-user-BRIHOOpG.js.map +1 -1
  58. package/dist/chunks/package-imports-Bbw3iMPg.js.map +1 -1
  59. package/dist/chunks/pocketbase-C5GS-Dh5.js.map +1 -1
  60. package/dist/chunks/pocketbase-DpudAAmd.js.map +1 -1
  61. package/dist/chunks/pocketbase-Dry6ry17.js.map +1 -1
  62. package/dist/chunks/providers-BHR6-XZ7.js.map +1 -1
  63. package/dist/chunks/shared-CZC4d7Uj.js.map +1 -1
  64. package/dist/chunks/site-BwCA18Sv.js.map +1 -1
  65. package/dist/chunks/svelte-file-B3RfgVdt.js.map +1 -1
  66. package/dist/chunks/table-core-AjBpYi-y.js.map +1 -1
  67. package/dist/chunks/{taggedTemplateLiteral-Dx0fjWiw.js → taggedTemplateLiteral-CswN2AAa.js} +1 -1
  68. package/dist/chunks/test-setup-DEmWd9Ul.js.map +1 -1
  69. package/dist/chunks/ts-morph-helpers-CDW4lhox.js.map +1 -1
  70. package/dist/chunks/ui-DD4NltyN.js.map +1 -1
  71. package/dist/chunks/ui-X698F10c.js.map +1 -1
  72. package/dist/chunks/unmodify-load-CyGzC1Hu.js.map +1 -1
  73. package/dist/chunks/util-BLYliuUK.js.map +1 -1
  74. package/dist/chunks/write-result-B68lvI57.js.map +1 -1
  75. package/dist/index.js +6 -6
  76. package/dist/index.js.map +1 -1
  77. package/package.json +1 -1
  78. package/dist/chunks/generate.runtime-CA7Ofjlx.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"generate.runtime-CexC1Oky.js","names":[],"sources":["../../src/patterns/enable/subscriptions/modifies/modify-webhook-server.ts","../../src/patterns/enable/subscriptions/modifies/modify-by-template.ts","../../src/patterns/enable/subscriptions/modifies/modify-app-layout-server.ts","../../src/patterns/enable/subscriptions/modifies/modify-app-layout-svelte.ts","../../src/patterns/enable/subscriptions/modifies/modify-app-sidebar.ts","../../src/patterns/enable/subscriptions/modifies/modify-nav-user.ts","../../src/patterns/enable/subscriptions/modifies/modify-billing-page-server.ts","../../src/patterns/enable/subscriptions/modifies/modify-billing-page-svelte.ts","../../src/patterns/enable/subscriptions/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport { SyntaxKind } from \"ts-morph\";\nimport dedent from \"dedent\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport {\n ensureImports,\n withInMemoryScript,\n formatLikeSource,\n} from \"../../../../runtime/ts-morph-helpers\";\n\nconst FAILURE_HINT = dedent`\n Wire the subscription event handlers into src/routes/webhooks/stripe/handlers/dispatch.ts:\n\n Add imports:\n import { handleSubscriptionCreated } from \"./subscription/created\";\n import { handleSubscriptionUpdated } from \"./subscription/updated\";\n import { handleSubscriptionDeleted } from \"./subscription/deleted\";\n\n Add switch cases inside the event.type switch:\n case \"customer.subscription.created\":\n await handleSubscriptionCreated(event.data.object, locals);\n break;\n case \"customer.subscription.updated\":\n await handleSubscriptionUpdated(event.data.object, locals);\n break;\n case \"customer.subscription.deleted\":\n await handleSubscriptionDeleted(event.data.object, locals);\n break;\n`;\n\nconst NOT_FOUND_HINT =\n \"Enable payments first — src/routes/webhooks/stripe/handlers/dispatch.ts is created by enable-payments.\";\n\nconst SUBSCRIPTION_CASES_SNIPPET = dedent`\n case \"customer.subscription.created\":\n await handleSubscriptionCreated(event.data.object, locals);\n break;\n\n case \"customer.subscription.updated\":\n await handleSubscriptionUpdated(event.data.object, locals);\n break;\n\n case \"customer.subscription.deleted\":\n await handleSubscriptionDeleted(event.data.object, locals);\n break;\n`;\n\nexport function modifyWebhookServer(filePath: string): ModifyOutcome {\n if (!fs.existsSync(filePath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const original = fs.readFileSync(filePath, \"utf8\");\n if (original.includes(\"handleSubscriptionCreated\")) {\n return { status: \"success\", changed: false };\n }\n\n let addedCases = false;\n const { source } = withInMemoryScript(original, (sf) => {\n ensureImports(sf, [\n {\n namedImports: [\"handleSubscriptionCreated\"],\n moduleSpecifier: \"./subscription/created\",\n },\n {\n namedImports: [\"handleSubscriptionUpdated\"],\n moduleSpecifier: \"./subscription/updated\",\n },\n {\n namedImports: [\"handleSubscriptionDeleted\"],\n moduleSpecifier: \"./subscription/deleted\",\n },\n ]);\n\n const switchStmt = sf\n .getDescendantsOfKind(SyntaxKind.SwitchStatement)\n .find((stmt) => stmt.getExpression().getText().includes(\"event.type\"));\n if (!switchStmt) return;\n\n const caseBlock = switchStmt.getCaseBlock();\n const clauses = caseBlock.getClauses();\n const defaultClause = clauses.find(\n (c) => c.getKind() === SyntaxKind.DefaultClause,\n );\n\n // Prepend subscription cases in front of the default clause, or append\n // before the closing brace of the case block if there's no default.\n const prefix = `${SUBSCRIPTION_CASES_SNIPPET}\\n\\n`;\n if (defaultClause) {\n defaultClause.replaceWithText(prefix + defaultClause.getText());\n } else if (clauses.length > 0) {\n const last = clauses[clauses.length - 1];\n last.replaceWithText(\n last.getText() + `\\n\\n${SUBSCRIPTION_CASES_SNIPPET}`,\n );\n } else {\n return;\n }\n\n formatLikeSource(sf);\n addedCases = true;\n });\n\n if (!addedCases) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n fs.writeFileSync(filePath, source, \"utf8\");\n return { status: \"success\", changed: true };\n}\n","import fs from \"node:fs\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\n/**\n * Overwrites a file with the given template content, guarded by an idempotency\n * marker: if the current file already contains the marker, the modify is a\n * no-op. Used for complex rewrites where surgical AST changes aren't worth it\n * (e.g. pages that are largely replaced).\n *\n * Strips leading `// [!code highlight:N]` and `<!-- [!code highlight:N] -->`\n * lines so the same content can be shared with preview-modifies, which uses\n * those comments for documentation highlighting.\n */\nexport function modifyByTemplate(\n filePath: string,\n template: string,\n idempotencyMarker: string,\n notFoundHint: string,\n): ModifyOutcome {\n if (!fs.existsSync(filePath)) {\n return { status: \"not-found\", message: notFoundHint };\n }\n const current = fs.readFileSync(filePath, \"utf8\");\n if (current.includes(idempotencyMarker)) {\n return { status: \"success\", changed: false };\n }\n const stripped = template\n .replace(/^[ \\t]*\\/\\/[ \\t]*\\[!code highlight:\\d+\\][ \\t]*\\r?\\n/gm, \"\")\n .replace(\n /^[ \\t]*<!--[ \\t]*\\[!code highlight:\\d+\\][ \\t]*-->[ \\t]*\\r?\\n/gm,\n \"\",\n );\n if (current === stripped) {\n return { status: \"success\", changed: false };\n }\n fs.writeFileSync(filePath, stripped, \"utf8\");\n return { status: \"success\", changed: true };\n}\n","import { modifyByTemplate } from \"./modify-by-template\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst NOT_FOUND_HINT = [\n \"Create src/routes/(app)/+layout.server.ts before enabling subscriptions.\",\n \"Enable auth first — the (app) layout is provided by the velastack-auth baseline.\",\n].join(\"\\n\");\n\nexport function modifyAppLayoutServer(\n filePath: string,\n template: string,\n): ModifyOutcome {\n return modifyByTemplate(\n filePath,\n template,\n \"loadActiveSubscription\",\n NOT_FOUND_HINT,\n );\n}\n","import fs from \"node:fs\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst FAILURE_HINT = [\n \"Pass the subscription prop to <AppSidebar> in src/routes/(app)/+layout.svelte:\",\n \"\",\n \"<AppSidebar user={data.user} subscription={data.subscription} />\",\n].join(\"\\n\");\n\nconst NOT_FOUND_HINT = [\n \"Create src/routes/(app)/+layout.svelte with an <AppSidebar /> that receives the subscription prop.\",\n].join(\"\\n\");\n\nexport function modifyAppLayoutSvelte(filePath: string): ModifyOutcome {\n if (!fs.existsSync(filePath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const file = SvelteFile.fromPath(filePath);\n if (!file.hasElement(\"AppSidebar\")) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n if (file.hasAttribute(\"AppSidebar\", \"subscription\")) {\n return { status: \"success\", changed: false };\n }\n\n const appended = file.appendToAttributes(\n \"AppSidebar\",\n \" subscription={data.subscription}\",\n );\n if (!appended) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n file.writeTo(filePath);\n return { status: \"success\", changed: file.hasChanged() };\n}\n","import fs from \"node:fs\";\nimport { SyntaxKind } from \"ts-morph\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport {\n withInMemoryScript,\n formatLikeSource,\n} from \"../../../../runtime/ts-morph-helpers\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst SUBSCRIPTION_TYPE = \"{ id: string; productName: string | null } | null\";\n\nconst FAILURE_HINT = [\n \"Update src/lib/components/app-sidebar.svelte to forward a subscription prop:\",\n \"\",\n \"1. Add `subscription = null` to the destructured $props() call.\",\n `2. Add \\`subscription?: ${SUBSCRIPTION_TYPE}\\` to the props type.`,\n \"3. Pass `{subscription}` to <NavUser>.\",\n].join(\"\\n\");\n\nconst NOT_FOUND_HINT = [\n \"Create src/lib/components/app-sidebar.svelte before enabling subscriptions.\",\n].join(\"\\n\");\n\nfunction updateScript(source: string): {\n source: string;\n wasAdded: boolean;\n} {\n let wasAdded = false;\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 const pattern = nameNode.asKindOrThrow(SyntaxKind.ObjectBindingPattern);\n const elements = pattern.getElements();\n if (elements.some((e) => e.getName() === \"subscription\")) {\n // Already has subscription prop — no-op.\n return;\n }\n\n // Insert subscription?: ... into the props type literal if present.\n const typeNode = decl.getTypeNode();\n if (typeNode?.getKind() === SyntaxKind.IntersectionType) {\n const intersection = typeNode.asKindOrThrow(\n SyntaxKind.IntersectionType,\n );\n for (const member of intersection.getTypeNodes()) {\n if (member.getKind() !== SyntaxKind.TypeLiteral) continue;\n const lit = member.asKindOrThrow(SyntaxKind.TypeLiteral);\n const propTexts = lit\n .getProperties()\n .map((p) => p.getText().replace(/[;,]\\s*$/, \"\"));\n if (propTexts.some((t) => /^\\s*subscription\\??\\s*:/.test(t))) {\n continue;\n }\n propTexts.push(`subscription?: ${SUBSCRIPTION_TYPE}`);\n lit.replaceWithText(`{ ${propTexts.join(\"; \")}; }`);\n break;\n }\n }\n\n // Insert `subscription = null` before the first rest/default-only element.\n const elementTexts = elements.map((e) => e.getText());\n let insertIdx = elements.findIndex(\n (e) => e.getDotDotDotToken() || e.getInitializer(),\n );\n if (insertIdx === -1) insertIdx = elementTexts.length;\n elementTexts.splice(insertIdx, 0, \"subscription = null\");\n pattern.replaceWithText(`{ ${elementTexts.join(\", \")} }`);\n wasAdded = true;\n }\n formatLikeSource(sf);\n });\n return { source: out, wasAdded };\n}\n\nexport function modifyAppSidebar(filePath: string): ModifyOutcome {\n if (!fs.existsSync(filePath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const original = fs.readFileSync(filePath, \"utf8\");\n if (\n original.includes(\"subscription?: {\") ||\n original.includes(\"subscription={subscription}\") ||\n original.includes(\"{subscription}\")\n ) {\n return { status: \"success\", changed: false };\n }\n\n const file = new SvelteFile(original);\n if (!file.hasElement(\"NavUser\")) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n const scriptChanged = file.modifyScript((src) => updateScript(src).source);\n\n const templateChanged = !file.hasAttribute(\"NavUser\", \"subscription\")\n ? file.appendToAttributes(\"NavUser\", \" {subscription}\")\n : false;\n\n if (!scriptChanged && !templateChanged) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n file.writeTo(filePath);\n return { status: \"success\", changed: file.hasChanged() };\n}\n","import { modifyByTemplate } from \"./modify-by-template\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst NOT_FOUND_HINT = [\n \"src/lib/components/nav-user.svelte is missing.\",\n \"Enable auth and payments first; subscriptions layers a plan label on top of the existing nav-user.\",\n].join(\"\\n\");\n\nexport function modifyNavUser(\n filePath: string,\n template: string,\n): ModifyOutcome {\n // `planLabel` is unique to subscriptions — safe idempotency marker.\n return modifyByTemplate(filePath, template, \"planLabel\", NOT_FOUND_HINT);\n}\n","import { modifyByTemplate } from \"./modify-by-template\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst NOT_FOUND_HINT = [\n \"src/routes/(app)/billing/+page.server.ts is missing.\",\n \"Enable payments first — subscriptions extends the billing page with plan management.\",\n].join(\"\\n\");\n\nexport function modifyBillingPageServer(\n filePath: string,\n template: string,\n): ModifyOutcome {\n return modifyByTemplate(filePath, template, \"selectPlan\", NOT_FOUND_HINT);\n}\n","import { modifyByTemplate } from \"./modify-by-template\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst NOT_FOUND_HINT = [\n \"src/routes/(app)/billing/+page.svelte is missing.\",\n \"Enable payments first — subscriptions extends the billing page with plan management.\",\n].join(\"\\n\");\n\nexport function modifyBillingPageSvelte(\n filePath: string,\n template: string,\n): ModifyOutcome {\n return modifyByTemplate(filePath, template, \"availablePlans\", NOT_FOUND_HINT);\n}\n","import path from \"node:path\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { modifyWebhookServer } from \"./modifies/modify-webhook-server\";\nimport { modifyAppLayoutServer } from \"./modifies/modify-app-layout-server\";\nimport { modifyAppLayoutSvelte } from \"./modifies/modify-app-layout-svelte\";\nimport { modifyAppSidebar } from \"./modifies/modify-app-sidebar\";\nimport { modifyNavUser } from \"./modifies/modify-nav-user\";\nimport { modifyBillingPageServer } from \"./modifies/modify-billing-page-server\";\nimport { modifyBillingPageSvelte } from \"./modifies/modify-billing-page-svelte\";\n\n// Share the final-state files between preview (rendered as-is) and runtime\n// (used as overwrite templates for modifies that amount to full rewrites).\nconst previewRaw = import.meta.glob<string>(\"./preview-modifies/**\", {\n query: \"?raw\",\n import: \"default\",\n eager: true,\n});\n\nfunction template(relativePath: string): string {\n const key = `./preview-modifies/${relativePath}`;\n const content = previewRaw[key];\n if (content === undefined) {\n throw new Error(\n `Missing template for ${relativePath} in subscriptions preview-modifies`,\n );\n }\n return content;\n}\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(\"Modifying webhooks/stripe/handlers/dispatch.ts\");\n const webhookServerPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"webhooks\",\n \"stripe\",\n \"handlers\",\n \"dispatch.ts\",\n );\n pushResult(\n modifyOutcomeToFile(\n webhookServerPath,\n modifyWebhookServer(webhookServerPath),\n ),\n );\n\n logger.info(\"Modifying (app)/+layout.server.ts\");\n const appLayoutServerPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(app)\",\n \"+layout.server.ts\",\n );\n pushResult(\n modifyOutcomeToFile(\n appLayoutServerPath,\n modifyAppLayoutServer(\n appLayoutServerPath,\n template(\"src/routes/(app)/+layout.server.ts\"),\n ),\n ),\n );\n\n logger.info(\"Modifying (app)/+layout.svelte\");\n const appLayoutSveltePath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(app)\",\n \"+layout.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(\n appLayoutSveltePath,\n modifyAppLayoutSvelte(appLayoutSveltePath),\n ),\n );\n\n logger.info(\"Modifying 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, modifyAppSidebar(appSidebarPath)),\n );\n\n logger.info(\"Modifying nav-user.svelte\");\n const navUserPath = path.join(\n options.root,\n \"src\",\n \"lib\",\n \"components\",\n \"nav-user.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(\n navUserPath,\n modifyNavUser(\n navUserPath,\n template(\"src/lib/components/nav-user.svelte\"),\n ),\n ),\n );\n\n logger.info(\"Modifying billing/+page.server.ts\");\n const billingPageServerPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(app)\",\n \"billing\",\n \"+page.server.ts\",\n );\n pushResult(\n modifyOutcomeToFile(\n billingPageServerPath,\n modifyBillingPageServer(\n billingPageServerPath,\n template(\"src/routes/(app)/billing/+page.server.ts\"),\n ),\n ),\n );\n\n logger.info(\"Modifying billing/+page.svelte\");\n const billingPageSveltePath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(app)\",\n \"billing\",\n \"+page.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(\n billingPageSveltePath,\n modifyBillingPageSvelte(\n billingPageSveltePath,\n template(\"src/routes/(app)/billing/+page.svelte\"),\n ),\n ),\n );\n\n return {\n creates: [],\n modifies,\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n } satisfies Result;\n}\n"],"mappings":";;;;;;;;;;AAUA,IAAM,IAAe,CAAM;;;;;;;;;;;;;;;;;;GAoBrB,IACJ,0GAEI,IAA6B,CAAM;;;;;;;;;;;;;AAczC,SAAgB,EAAoB,GAAiC;CACnE,IAAI,CAAC,EAAG,WAAW,CAAQ,GACzB,OAAO;EAAE,QAAQ;EAAa,SAAS;CAAe;CAGxD,IAAM,IAAW,EAAG,aAAa,GAAU,MAAM;CACjD,IAAI,EAAS,SAAS,2BAA2B,GAC/C,OAAO;EAAE,QAAQ;EAAW,SAAS;CAAM;CAG7C,IAAI,IAAa,IACX,EAAE,cAAW,EAAmB,IAAW,MAAO;EACtD,EAAc,GAAI;GAChB;IACE,cAAc,CAAC,2BAA2B;IAC1C,iBAAiB;GACnB;GACA;IACE,cAAc,CAAC,2BAA2B;IAC1C,iBAAiB;GACnB;GACA;IACE,cAAc,CAAC,2BAA2B;IAC1C,iBAAiB;GACnB;EACF,CAAC;EAED,IAAM,IAAa,EAChB,qBAAqB,EA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IAAM,IAAsB,EAAK,KAC/B,EAAQ,MACR,OACA,UACA,SACA,mBACF;CAWA,AAVA,EACE,EACE,GACA,EACE,GACA,EAAS,oCAAoC,CAC/C,CACF,CACF,GAEA,EAAO,KAAK,gCAAgC;CAC5C,IAAM,IAAsB,EAAK,KAC/B,EAAQ,MACR,OACA,UACA,SACA,gBACF;CAQA,AAPA,EACE,EACE,GACA,EAAsB,CAAmB,CAC3C,CACF,GAEA,EAAO,KAAK,8BAA8B;CAC1C,IAAM,IAAiB,EAAK,KAC1B,EAAQ,MACR,OACA,OACA,cACA,oBACF;CAKA,AAJA,EACE,EAAoB,GAAgB,EAAiB,CAAc,CAAC,CACtE,GAEA,EAAO,KAAK,2BAA2B;CACvC,IAAM,IAAc,EAAK,KACvB,EAAQ,MACR,OACA,OACA,cACA,iBACF;CAWA,AAVA,EACE,EACE,GACA,EACE,GACA,EAAS,oCAAoC,CAC/C,CACF,CACF,GAEA,EAAO,KAAK,mCAAmC;CAC/C,IAAM,IAAwB,EAAK,KACjC,EAAQ,MACR,OACA,UACA,SACA,WACA,iBACF;CAWA,AAVA,EACE,EACE,GACA,EACE,GACA,EAAS,0CAA0C,CACrD,CACF,CACF,GAEA,EAAO,KAAK,gCAAgC;CAC5C,IAAM,IAAwB,EAAK,KACjC,EAAQ,MACR,OACA,UACA,SACA,WACA,cACF;CAWA,OAVA,EACE,EACE,GACA,EACE,GACA,EAAS,uCAAuC,CAClD,CACF,CACF,GAEO;EACL,SAAS,CAAC;EACV;EACA,SAAS,CAAC;EACV,YAAY,CAAC;EACb,UAAU,CAAC;EACX,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAiB,CAAC;CACpB;AACF"}
1
+ {"version":3,"file":"generate.runtime-CexC1Oky.js","names":["FAILURE_HINT","NOT_FOUND_HINT","NOT_FOUND_HINT","FAILURE_HINT","NOT_FOUND_HINT","NOT_FOUND_HINT","NOT_FOUND_HINT","NOT_FOUND_HINT","__import_glob__0_0_","__import_glob__0_1_","__import_glob__0_2_","__import_glob__0_3_","__import_glob__0_4_","__import_glob__0_5_","__import_glob__0_6_","dedent","getLogger","_layout_server_default","_layout_default","_page_default","nav_user_default","_page_server_default","dispatch_default","withInMemoryScript","formatLikeSource","ensureImports","SvelteFile","fs","path","FAILURE_HINT$2","NOT_FOUND_HINT$6","SUBSCRIPTION_CASES_SNIPPET","modifyWebhookServer","filePath","original","addedCases","sf","switchStmt","SyntaxKind","stmt","clauses","defaultClause","c","prefix","last","source","modifyByTemplate","notFoundHint","current","idempotencyMarker","stripped","template","NOT_FOUND_HINT$5","modifyAppLayoutServer","FAILURE_HINT$1","NOT_FOUND_HINT$4","modifyAppLayoutSvelte","file","SUBSCRIPTION_TYPE","FAILURE_HINT","NOT_FOUND_HINT$3","updateScript","wasAdded","out","decl","init","nameNode","pattern","elements","typeNode","intersection","member","lit","propTexts","p","t","elementTexts","insertIdx","modifyAppSidebar","scriptChanged","src","templateChanged","NOT_FOUND_HINT$2","modifyNavUser","NOT_FOUND_HINT$1","modifyBillingPageServer","NOT_FOUND_HINT","modifyBillingPageSvelte","previewRaw","app_sidebar_default","content","relativePath","generate","logger","options","modifies","pushResult","webhookServerPath","modifyOutcomeToFile","appLayoutServerPath","appLayoutSveltePath","appSidebarPath","navUserPath","billingPageServerPath","billingPageSveltePath"],"sources":["../../src/patterns/enable/subscriptions/modifies/modify-webhook-server.ts","../../src/patterns/enable/subscriptions/modifies/modify-by-template.ts","../../src/patterns/enable/subscriptions/modifies/modify-app-layout-server.ts","../../src/patterns/enable/subscriptions/modifies/modify-app-layout-svelte.ts","../../src/patterns/enable/subscriptions/modifies/modify-app-sidebar.ts","../../src/patterns/enable/subscriptions/modifies/modify-nav-user.ts","../../src/patterns/enable/subscriptions/modifies/modify-billing-page-server.ts","../../src/patterns/enable/subscriptions/modifies/modify-billing-page-svelte.ts","../../src/patterns/enable/subscriptions/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport { SyntaxKind } from \"ts-morph\";\nimport dedent from \"dedent\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport {\n ensureImports,\n withInMemoryScript,\n formatLikeSource,\n} from \"../../../../runtime/ts-morph-helpers\";\n\nconst FAILURE_HINT = dedent`\n Wire the subscription event handlers into src/routes/webhooks/stripe/handlers/dispatch.ts:\n\n Add imports:\n import { handleSubscriptionCreated } from \"./subscription/created\";\n import { handleSubscriptionUpdated } from \"./subscription/updated\";\n import { handleSubscriptionDeleted } from \"./subscription/deleted\";\n\n Add switch cases inside the event.type switch:\n case \"customer.subscription.created\":\n await handleSubscriptionCreated(event.data.object, locals);\n break;\n case \"customer.subscription.updated\":\n await handleSubscriptionUpdated(event.data.object, locals);\n break;\n case \"customer.subscription.deleted\":\n await handleSubscriptionDeleted(event.data.object, locals);\n break;\n`;\n\nconst NOT_FOUND_HINT =\n \"Enable payments first — src/routes/webhooks/stripe/handlers/dispatch.ts is created by enable-payments.\";\n\nconst SUBSCRIPTION_CASES_SNIPPET = dedent`\n case \"customer.subscription.created\":\n await handleSubscriptionCreated(event.data.object, locals);\n break;\n\n case \"customer.subscription.updated\":\n await handleSubscriptionUpdated(event.data.object, locals);\n break;\n\n case \"customer.subscription.deleted\":\n await handleSubscriptionDeleted(event.data.object, locals);\n break;\n`;\n\nexport function modifyWebhookServer(filePath: string): ModifyOutcome {\n if (!fs.existsSync(filePath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const original = fs.readFileSync(filePath, \"utf8\");\n if (original.includes(\"handleSubscriptionCreated\")) {\n return { status: \"success\", changed: false };\n }\n\n let addedCases = false;\n const { source } = withInMemoryScript(original, (sf) => {\n ensureImports(sf, [\n {\n namedImports: [\"handleSubscriptionCreated\"],\n moduleSpecifier: \"./subscription/created\",\n },\n {\n namedImports: [\"handleSubscriptionUpdated\"],\n moduleSpecifier: \"./subscription/updated\",\n },\n {\n namedImports: [\"handleSubscriptionDeleted\"],\n moduleSpecifier: \"./subscription/deleted\",\n },\n ]);\n\n const switchStmt = sf\n .getDescendantsOfKind(SyntaxKind.SwitchStatement)\n .find((stmt) => stmt.getExpression().getText().includes(\"event.type\"));\n if (!switchStmt) return;\n\n const caseBlock = switchStmt.getCaseBlock();\n const clauses = caseBlock.getClauses();\n const defaultClause = clauses.find(\n (c) => c.getKind() === SyntaxKind.DefaultClause,\n );\n\n // Prepend subscription cases in front of the default clause, or append\n // before the closing brace of the case block if there's no default.\n const prefix = `${SUBSCRIPTION_CASES_SNIPPET}\\n\\n`;\n if (defaultClause) {\n defaultClause.replaceWithText(prefix + defaultClause.getText());\n } else if (clauses.length > 0) {\n const last = clauses[clauses.length - 1];\n last.replaceWithText(\n last.getText() + `\\n\\n${SUBSCRIPTION_CASES_SNIPPET}`,\n );\n } else {\n return;\n }\n\n formatLikeSource(sf);\n addedCases = true;\n });\n\n if (!addedCases) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n fs.writeFileSync(filePath, source, \"utf8\");\n return { status: \"success\", changed: true };\n}\n","import fs from \"node:fs\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\n/**\n * Overwrites a file with the given template content, guarded by an idempotency\n * marker: if the current file already contains the marker, the modify is a\n * no-op. Used for complex rewrites where surgical AST changes aren't worth it\n * (e.g. pages that are largely replaced).\n *\n * Strips leading `// [!code highlight:N]` and `<!-- [!code highlight:N] -->`\n * lines so the same content can be shared with preview-modifies, which uses\n * those comments for documentation highlighting.\n */\nexport function modifyByTemplate(\n filePath: string,\n template: string,\n idempotencyMarker: string,\n notFoundHint: string,\n): ModifyOutcome {\n if (!fs.existsSync(filePath)) {\n return { status: \"not-found\", message: notFoundHint };\n }\n const current = fs.readFileSync(filePath, \"utf8\");\n if (current.includes(idempotencyMarker)) {\n return { status: \"success\", changed: false };\n }\n const stripped = template\n .replace(/^[ \\t]*\\/\\/[ \\t]*\\[!code highlight:\\d+\\][ \\t]*\\r?\\n/gm, \"\")\n .replace(\n /^[ \\t]*<!--[ \\t]*\\[!code highlight:\\d+\\][ \\t]*-->[ \\t]*\\r?\\n/gm,\n \"\",\n );\n if (current === stripped) {\n return { status: \"success\", changed: false };\n }\n fs.writeFileSync(filePath, stripped, \"utf8\");\n return { status: \"success\", changed: true };\n}\n","import { modifyByTemplate } from \"./modify-by-template\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst NOT_FOUND_HINT = [\n \"Create src/routes/(app)/+layout.server.ts before enabling subscriptions.\",\n \"Enable auth first — the (app) layout is provided by the velastack-auth baseline.\",\n].join(\"\\n\");\n\nexport function modifyAppLayoutServer(\n filePath: string,\n template: string,\n): ModifyOutcome {\n return modifyByTemplate(\n filePath,\n template,\n \"loadActiveSubscription\",\n NOT_FOUND_HINT,\n );\n}\n","import fs from \"node:fs\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst FAILURE_HINT = [\n \"Pass the subscription prop to <AppSidebar> in src/routes/(app)/+layout.svelte:\",\n \"\",\n \"<AppSidebar user={data.user} subscription={data.subscription} />\",\n].join(\"\\n\");\n\nconst NOT_FOUND_HINT = [\n \"Create src/routes/(app)/+layout.svelte with an <AppSidebar /> that receives the subscription prop.\",\n].join(\"\\n\");\n\nexport function modifyAppLayoutSvelte(filePath: string): ModifyOutcome {\n if (!fs.existsSync(filePath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const file = SvelteFile.fromPath(filePath);\n if (!file.hasElement(\"AppSidebar\")) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n if (file.hasAttribute(\"AppSidebar\", \"subscription\")) {\n return { status: \"success\", changed: false };\n }\n\n const appended = file.appendToAttributes(\n \"AppSidebar\",\n \" subscription={data.subscription}\",\n );\n if (!appended) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n file.writeTo(filePath);\n return { status: \"success\", changed: file.hasChanged() };\n}\n","import fs from \"node:fs\";\nimport { SyntaxKind } from \"ts-morph\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport {\n withInMemoryScript,\n formatLikeSource,\n} from \"../../../../runtime/ts-morph-helpers\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst SUBSCRIPTION_TYPE = \"{ id: string; productName: string | null } | null\";\n\nconst FAILURE_HINT = [\n \"Update src/lib/components/app-sidebar.svelte to forward a subscription prop:\",\n \"\",\n \"1. Add `subscription = null` to the destructured $props() call.\",\n `2. Add \\`subscription?: ${SUBSCRIPTION_TYPE}\\` to the props type.`,\n \"3. Pass `{subscription}` to <NavUser>.\",\n].join(\"\\n\");\n\nconst NOT_FOUND_HINT = [\n \"Create src/lib/components/app-sidebar.svelte before enabling subscriptions.\",\n].join(\"\\n\");\n\nfunction updateScript(source: string): {\n source: string;\n wasAdded: boolean;\n} {\n let wasAdded = false;\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 const pattern = nameNode.asKindOrThrow(SyntaxKind.ObjectBindingPattern);\n const elements = pattern.getElements();\n if (elements.some((e) => e.getName() === \"subscription\")) {\n // Already has subscription prop — no-op.\n return;\n }\n\n // Insert subscription?: ... into the props type literal if present.\n const typeNode = decl.getTypeNode();\n if (typeNode?.getKind() === SyntaxKind.IntersectionType) {\n const intersection = typeNode.asKindOrThrow(\n SyntaxKind.IntersectionType,\n );\n for (const member of intersection.getTypeNodes()) {\n if (member.getKind() !== SyntaxKind.TypeLiteral) continue;\n const lit = member.asKindOrThrow(SyntaxKind.TypeLiteral);\n const propTexts = lit\n .getProperties()\n .map((p) => p.getText().replace(/[;,]\\s*$/, \"\"));\n if (propTexts.some((t) => /^\\s*subscription\\??\\s*:/.test(t))) {\n continue;\n }\n propTexts.push(`subscription?: ${SUBSCRIPTION_TYPE}`);\n lit.replaceWithText(`{ ${propTexts.join(\"; \")}; }`);\n break;\n }\n }\n\n // Insert `subscription = null` before the first rest/default-only element.\n const elementTexts = elements.map((e) => e.getText());\n let insertIdx = elements.findIndex(\n (e) => e.getDotDotDotToken() || e.getInitializer(),\n );\n if (insertIdx === -1) insertIdx = elementTexts.length;\n elementTexts.splice(insertIdx, 0, \"subscription = null\");\n pattern.replaceWithText(`{ ${elementTexts.join(\", \")} }`);\n wasAdded = true;\n }\n formatLikeSource(sf);\n });\n return { source: out, wasAdded };\n}\n\nexport function modifyAppSidebar(filePath: string): ModifyOutcome {\n if (!fs.existsSync(filePath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const original = fs.readFileSync(filePath, \"utf8\");\n if (\n original.includes(\"subscription?: {\") ||\n original.includes(\"subscription={subscription}\") ||\n original.includes(\"{subscription}\")\n ) {\n return { status: \"success\", changed: false };\n }\n\n const file = new SvelteFile(original);\n if (!file.hasElement(\"NavUser\")) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n const scriptChanged = file.modifyScript((src) => updateScript(src).source);\n\n const templateChanged = !file.hasAttribute(\"NavUser\", \"subscription\")\n ? file.appendToAttributes(\"NavUser\", \" {subscription}\")\n : false;\n\n if (!scriptChanged && !templateChanged) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n file.writeTo(filePath);\n return { status: \"success\", changed: file.hasChanged() };\n}\n","import { modifyByTemplate } from \"./modify-by-template\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst NOT_FOUND_HINT = [\n \"src/lib/components/nav-user.svelte is missing.\",\n \"Enable auth and payments first; subscriptions layers a plan label on top of the existing nav-user.\",\n].join(\"\\n\");\n\nexport function modifyNavUser(\n filePath: string,\n template: string,\n): ModifyOutcome {\n // `planLabel` is unique to subscriptions — safe idempotency marker.\n return modifyByTemplate(filePath, template, \"planLabel\", NOT_FOUND_HINT);\n}\n","import { modifyByTemplate } from \"./modify-by-template\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst NOT_FOUND_HINT = [\n \"src/routes/(app)/billing/+page.server.ts is missing.\",\n \"Enable payments first — subscriptions extends the billing page with plan management.\",\n].join(\"\\n\");\n\nexport function modifyBillingPageServer(\n filePath: string,\n template: string,\n): ModifyOutcome {\n return modifyByTemplate(filePath, template, \"selectPlan\", NOT_FOUND_HINT);\n}\n","import { modifyByTemplate } from \"./modify-by-template\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst NOT_FOUND_HINT = [\n \"src/routes/(app)/billing/+page.svelte is missing.\",\n \"Enable payments first — subscriptions extends the billing page with plan management.\",\n].join(\"\\n\");\n\nexport function modifyBillingPageSvelte(\n filePath: string,\n template: string,\n): ModifyOutcome {\n return modifyByTemplate(filePath, template, \"availablePlans\", NOT_FOUND_HINT);\n}\n","import path from \"node:path\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { modifyWebhookServer } from \"./modifies/modify-webhook-server\";\nimport { modifyAppLayoutServer } from \"./modifies/modify-app-layout-server\";\nimport { modifyAppLayoutSvelte } from \"./modifies/modify-app-layout-svelte\";\nimport { modifyAppSidebar } from \"./modifies/modify-app-sidebar\";\nimport { modifyNavUser } from \"./modifies/modify-nav-user\";\nimport { modifyBillingPageServer } from \"./modifies/modify-billing-page-server\";\nimport { modifyBillingPageSvelte } from \"./modifies/modify-billing-page-svelte\";\n\n// Share the final-state files between preview (rendered as-is) and runtime\n// (used as overwrite templates for modifies that amount to full rewrites).\nconst previewRaw = import.meta.glob<string>(\"./preview-modifies/**\", {\n query: \"?raw\",\n import: \"default\",\n eager: true,\n});\n\nfunction template(relativePath: string): string {\n const key = `./preview-modifies/${relativePath}`;\n const content = previewRaw[key];\n if (content === undefined) {\n throw new Error(\n `Missing template for ${relativePath} in subscriptions preview-modifies`,\n );\n }\n return content;\n}\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(\"Modifying webhooks/stripe/handlers/dispatch.ts\");\n const webhookServerPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"webhooks\",\n \"stripe\",\n \"handlers\",\n \"dispatch.ts\",\n );\n pushResult(\n modifyOutcomeToFile(\n webhookServerPath,\n modifyWebhookServer(webhookServerPath),\n ),\n );\n\n logger.info(\"Modifying (app)/+layout.server.ts\");\n const appLayoutServerPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(app)\",\n \"+layout.server.ts\",\n );\n pushResult(\n modifyOutcomeToFile(\n appLayoutServerPath,\n modifyAppLayoutServer(\n appLayoutServerPath,\n template(\"src/routes/(app)/+layout.server.ts\"),\n ),\n ),\n );\n\n logger.info(\"Modifying (app)/+layout.svelte\");\n const appLayoutSveltePath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(app)\",\n \"+layout.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(\n appLayoutSveltePath,\n modifyAppLayoutSvelte(appLayoutSveltePath),\n ),\n );\n\n logger.info(\"Modifying 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, modifyAppSidebar(appSidebarPath)),\n );\n\n logger.info(\"Modifying nav-user.svelte\");\n const navUserPath = path.join(\n options.root,\n \"src\",\n \"lib\",\n \"components\",\n \"nav-user.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(\n navUserPath,\n modifyNavUser(\n navUserPath,\n template(\"src/lib/components/nav-user.svelte\"),\n ),\n ),\n );\n\n logger.info(\"Modifying billing/+page.server.ts\");\n const billingPageServerPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(app)\",\n \"billing\",\n \"+page.server.ts\",\n );\n pushResult(\n modifyOutcomeToFile(\n billingPageServerPath,\n modifyBillingPageServer(\n billingPageServerPath,\n template(\"src/routes/(app)/billing/+page.server.ts\"),\n ),\n ),\n );\n\n logger.info(\"Modifying billing/+page.svelte\");\n const billingPageSveltePath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(app)\",\n \"billing\",\n \"+page.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(\n billingPageSveltePath,\n modifyBillingPageSvelte(\n billingPageSveltePath,\n template(\"src/routes/(app)/billing/+page.svelte\"),\n ),\n ),\n );\n\n return {\n creates: [],\n modifies,\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n } satisfies Result;\n}\n"],"mappings":";;;;;;;;;;AAUA,IAAMA,IAAe,CAAM;;;;;;;;;;;;;;;;;;GAoBrBC,IACJ,0GAEI8B,IAA6B,CAAM;;;;;;;;;;;;;AAczC,SAAgBC,EAAoB,GAAiC;CACnE,IAAI,CAACL,EAAG,WAAWM,CAAQ,GACzB,OAAO;EAAE,QAAQ;EAAa,SAAShC;CAAe;CAGxD,IAAMiC,IAAWP,EAAG,aAAaM,GAAU,MAAM;CACjD,IAAIC,EAAS,SAAS,2BAA2B,GAC/C,OAAO;EAAE,QAAQ;EAAW,SAAS;CAAM;CAG7C,IAAIC,IAAa,IACX,EAAE,cAAWZ,EAAmBW,IAAW,MAAO;EACtD,EAAcE,GAAI;GAChB;IACE,cAAc,CAAC,2BAA2B;IAC1C,iBAAiB;GACnB;GACA;IACE,cAAc,CAAC,2BAA2B;IAC1C,iBAAiB;GACnB;GACA;IACE,cAAc,CAAC,2BAA2B;IAC1C,iBAAiB;GACnB;EACF,CAAC;EAED,IAAMC,IAAaD,EAChB,qBAAqBE,EAAW,eAAe,CAAC,CAChD,MAAM,MAASC,EAAK,cAAc,CAAC,CAAC,QAAQ,CAAC,CAAC,SAAS,YAAY,CAAC;EACvE,IAAI,CAACF,GAAY;EAGjB,IAAMG,IADYH,EAAW,aACb,CAAA,CAAU,WAAW,GAC/BI,IAAgBD,EAAQ,MAC3B,MAAME,EAAE,QAAQ,MAAMJ,EAAW,aACpC,GAIMK,IAAS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,"file":"generate.runtime-CnPraLKv.js","names":[],"sources":["../../src/patterns/enable/workflows/modifies/hooks.server.ts","../../src/patterns/enable/workflows/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { Project, QuoteKind, type SourceFile } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport { formatLikeSource } from \"../../../../runtime/ts-morph-helpers\";\n\nconst INIT_SNIPPET = dedent`\n // Runs once when the server starts: executes the workflows in src/lib/workflows.\n export const init: ServerInit = () => startWorker();\n`;\n\nconst FAILURE_HINT = dedent`\n src/hooks.server.ts already exports an init hook. Start the workflow worker from it:\n\n import { startWorker } from '#lib/server/workflows.js';\n\n export const init: ServerInit = async () => {\n await startWorker();\n // ...the rest of your init\n };\n`;\n\nconst NOT_FOUND_HINT = dedent`\n Create src/hooks.server.ts and start the workflow worker from its init hook:\n\n import type { ServerInit } from '@sveltejs/kit/hooks';\n import { startWorker } from '#lib/server/workflows.js';\n\n export const init: ServerInit = () => startWorker();\n`;\n\nfunction ensureNamedImport(\n sourceFile: SourceFile,\n moduleSpecifier: string,\n name: string,\n typeOnly = false,\n) {\n const existing = sourceFile\n .getImportDeclarations()\n .find((d) => d.getModuleSpecifierValue() === moduleSpecifier);\n if (!existing) {\n sourceFile.addImportDeclaration({\n isTypeOnly: typeOnly,\n namedImports: [name],\n moduleSpecifier,\n });\n return;\n }\n if (existing.getNamedImports().some((ni) => ni.getName() === name)) return;\n // A declaration that is already `import type` covers the new name; a value\n // import takes the name as an inline `type` specifier.\n existing.addNamedImport(\n typeOnly && !existing.isTypeOnly() ? { name, isTypeOnly: true } : name,\n );\n}\n\nfunction hasInitExport(sourceFile: SourceFile): boolean {\n if (sourceFile.getVariableDeclaration(\"init\")) return true;\n if (sourceFile.getFunction(\"init\")) return true;\n return sourceFile\n .getExportDeclarations()\n .some((d) => d.getNamedExports().some((e) => e.getName() === \"init\"));\n}\n\n/**\n * Adds the `init` hook that starts the workflow worker. Projects created from\n * the base template already have it; this is the upgrade path for older ones.\n */\nexport function modifyHooksServerWorkflows(\n hooksServerPath: string,\n): ModifyOutcome {\n if (!fs.existsSync(hooksServerPath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const original = fs.readFileSync(hooksServerPath, \"utf8\");\n if (original.includes(\"startWorker\")) {\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 if (hasInitExport(sourceFile)) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n ensureNamedImport(sourceFile, \"@sveltejs/kit/hooks\", \"ServerInit\", true);\n ensureNamedImport(sourceFile, \"#lib/server/workflows.js\", \"startWorker\");\n\n // After everything else, so the hook reads as the last thing the server does on start.\n sourceFile.addStatements(`\\n${INIT_SNIPPET}`);\n\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n}\n","import path from \"node:path\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { modifyHooksServerWorkflows } from \"./modifies/hooks.server\";\nimport { modifyEnvVarsFiles } from \"../../../runtime/env-vars\";\nimport { WORKFLOWS_ENV_VARS } from \"./env-vars\";\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const creates: File[] = [];\n const modifies: File[] = [];\n\n logger.info(\"Modifying hooks.server.ts\");\n const hooksServerPath = path.join(options.root, \"src\", \"hooks.server.ts\");\n const hooksFile = modifyOutcomeToFile(\n hooksServerPath,\n modifyHooksServerWorkflows(hooksServerPath),\n );\n if (hooksFile) modifies.push(hooksFile);\n\n // SvelteKit 3 exposes only declared variables; the template declares these\n // already, an older project gets whichever it is missing.\n logger.info(\"Declaring the workflow variables in src/env.ts\");\n const envVars = modifyEnvVarsFiles(options.root, WORKFLOWS_ENV_VARS);\n if (envVars.create) creates.push(envVars.create);\n if (envVars.modify) modifies.push(envVars.modify);\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":";;;;;;;;;;AAMA,IAAM,IAAe,CAAM;;;GAKrB,IAAe,CAAM;;;;;;;;;GAWrB,IAAiB,CAAM;;;;;;;;AAS7B,SAAS,EACP,GACA,GACA,GACA,IAAW,IACX;CACA,IAAM,IAAW,EACd,sBAAsB,CAAC,CACvB,MAAM,MAAM,EAAE,wBAAwB,MAAM,CAAe;CAC9D,IAAI,CAAC,GAAU;EACb,EAAW,qBAAqB;GAC9B,YAAY;GACZ,cAAc,CAAC,CAAI;GACnB;EACF,CAAC;EACD;CACF;CACI,EAAS,gBAAgB,CAAC,CAAC,MAAM,MAAO,EAAG,QAAQ,MAAM,CAAI,KAGjE,EAAS,eACP,KAAY,CAAC,EAAS,WAAW,IAAI;EAAE;EAAM,YAAY;CAAK,IAAI,CACpE;AACF;AAEA,SAAS,EAAc,GAAiC;CAGtD,OAFI,EAAW,uBAAuB,MAAM,KACxC,EAAW,YAAY,MAAM,IAAU,KACpC,EACJ,sBAAsB,CAAC,CACvB,MAAM,MAAM,EAAE,gBAAgB,CAAC,CAAC,MAAM,MAAM,EAAE,QAAQ,MAAM,MAAM,CAAC;AACxE;AAMA,SAAgB,EACd,GACe;CACf,IAAI,CAAC,EAAG,WAAW,CAAe,GAChC,OAAO;EAAE,QAAQ;EAAa,SAAS;CAAe;CAIxD,IADiB,EAAG,aAAa,GAAiB,MAC9C,CAAA,CAAS,SAAS,aAAa,GACjC,OAAO;EAAE,QAAQ;EAAW,SAAS;CAAM;CAO7C,IAAM,IAAa,IAJC,EAAQ;EAC1B,iBAAiB,EAAE,SAAS,GAAK;EACjC,sBAAsB,EAAE,WAAW,EAAU,OAAO;CACtD,CACmB,CAAA,CAAQ,oBAAoB,CAAe;CAc9D,OAZI,EAAc,CAAU,IACnB;EAAE,QAAQ;EAAU,SAAS;CAAa,KAGnD,EAAkB,GAAY,uBAAuB,cAAc,EAAI,GACvE,EAAkB,GAAY,4BAA4B,aAAa,GAGvE,EAAW,cAAc,KAAK,GAAc,GAE5C,EAAiB,CAAU,GAC3B,EAAW,SAAS,GACb;EAAE,QAAQ;EAAW,SAAS;CAAK;AAC5C;;;AC3FA,eAAsB,EAAS,GAAkB;CAC/C,IAAM,IAAS,EAAU,CAAO,GAC1B,IAAkB,CAAC,GACnB,IAAmB,CAAC;CAE1B,EAAO,KAAK,2BAA2B;CACvC,IAAM,IAAkB,EAAK,KAAK,EAAQ,MAAM,OAAO,iBAAiB,GAClE,IAAY,EAChB,GACA,EAA2B,CAAe,CAC5C;CAKA,AAJI,KAAW,EAAS,KAAK,CAAS,GAItC,EAAO,KAAK,gDAAgD;CAC5D,IAAM,IAAU,EAAmB,EAAQ,MAAM,CAAkB;CAInE,OAHI,EAAQ,UAAQ,EAAQ,KAAK,EAAQ,MAAM,GAC3C,EAAQ,UAAQ,EAAS,KAAK,EAAQ,MAAM,GAEzC;EACL;EACA;EACA,SAAS,CAAC;EACV,YAAY,CAAC;EACb,UAAU,CAAC;EACX,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAiB,CAAC;CACpB;AACF"}
1
+ {"version":3,"file":"generate.runtime-CnPraLKv.js","names":["dedent","getLogger","WORKFLOWS_ENV_VARS","formatLikeSource","fs","path","INIT_SNIPPET","FAILURE_HINT","NOT_FOUND_HINT","ensureNamedImport","existing","sourceFile","d","moduleSpecifier","typeOnly","name","ni","hasInitExport","modifyHooksServerWorkflows","hooksServerPath","Project","QuoteKind","generate","logger","options","creates","modifies","hooksFile","modifyOutcomeToFile","envVars","modifyEnvVarsFiles"],"sources":["../../src/patterns/enable/workflows/modifies/hooks.server.ts","../../src/patterns/enable/workflows/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { Project, QuoteKind, type SourceFile } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport { formatLikeSource } from \"../../../../runtime/ts-morph-helpers\";\n\nconst INIT_SNIPPET = dedent`\n // Runs once when the server starts: executes the workflows in src/lib/workflows.\n export const init: ServerInit = () => startWorker();\n`;\n\nconst FAILURE_HINT = dedent`\n src/hooks.server.ts already exports an init hook. Start the workflow worker from it:\n\n import { startWorker } from '#lib/server/workflows.js';\n\n export const init: ServerInit = async () => {\n await startWorker();\n // ...the rest of your init\n };\n`;\n\nconst NOT_FOUND_HINT = dedent`\n Create src/hooks.server.ts and start the workflow worker from its init hook:\n\n import type { ServerInit } from '@sveltejs/kit/hooks';\n import { startWorker } from '#lib/server/workflows.js';\n\n export const init: ServerInit = () => startWorker();\n`;\n\nfunction ensureNamedImport(\n sourceFile: SourceFile,\n moduleSpecifier: string,\n name: string,\n typeOnly = false,\n) {\n const existing = sourceFile\n .getImportDeclarations()\n .find((d) => d.getModuleSpecifierValue() === moduleSpecifier);\n if (!existing) {\n sourceFile.addImportDeclaration({\n isTypeOnly: typeOnly,\n namedImports: [name],\n moduleSpecifier,\n });\n return;\n }\n if (existing.getNamedImports().some((ni) => ni.getName() === name)) return;\n // A declaration that is already `import type` covers the new name; a value\n // import takes the name as an inline `type` specifier.\n existing.addNamedImport(\n typeOnly && !existing.isTypeOnly() ? { name, isTypeOnly: true } : name,\n );\n}\n\nfunction hasInitExport(sourceFile: SourceFile): boolean {\n if (sourceFile.getVariableDeclaration(\"init\")) return true;\n if (sourceFile.getFunction(\"init\")) return true;\n return sourceFile\n .getExportDeclarations()\n .some((d) => d.getNamedExports().some((e) => e.getName() === \"init\"));\n}\n\n/**\n * Adds the `init` hook that starts the workflow worker. Projects created from\n * the base template already have it; this is the upgrade path for older ones.\n */\nexport function modifyHooksServerWorkflows(\n hooksServerPath: string,\n): ModifyOutcome {\n if (!fs.existsSync(hooksServerPath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const original = fs.readFileSync(hooksServerPath, \"utf8\");\n if (original.includes(\"startWorker\")) {\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 if (hasInitExport(sourceFile)) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n ensureNamedImport(sourceFile, \"@sveltejs/kit/hooks\", \"ServerInit\", true);\n ensureNamedImport(sourceFile, \"#lib/server/workflows.js\", \"startWorker\");\n\n // After everything else, so the hook reads as the last thing the server does on start.\n sourceFile.addStatements(`\\n${INIT_SNIPPET}`);\n\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n}\n","import path from \"node:path\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { modifyHooksServerWorkflows } from \"./modifies/hooks.server\";\nimport { modifyEnvVarsFiles } from \"../../../runtime/env-vars\";\nimport { WORKFLOWS_ENV_VARS } from \"./env-vars\";\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const creates: File[] = [];\n const modifies: File[] = [];\n\n logger.info(\"Modifying hooks.server.ts\");\n const hooksServerPath = path.join(options.root, \"src\", \"hooks.server.ts\");\n const hooksFile = modifyOutcomeToFile(\n hooksServerPath,\n modifyHooksServerWorkflows(hooksServerPath),\n );\n if (hooksFile) modifies.push(hooksFile);\n\n // SvelteKit 3 exposes only declared variables; the template declares these\n // already, an older project gets whichever it is missing.\n logger.info(\"Declaring the workflow variables in src/env.ts\");\n const envVars = modifyEnvVarsFiles(options.root, WORKFLOWS_ENV_VARS);\n if (envVars.create) creates.push(envVars.create);\n if (envVars.modify) modifies.push(envVars.modify);\n\n return {\n creates,\n modifies,\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n } satisfies Result;\n}\n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B,aAAa,GAGvEA,EAAW,cAAc,KAAKL,GAAc,GAE5CH,EAAiBQ,CAAU,GAC3BA,EAAW,SAAS,GACb;EAAE,QAAQ;EAAW,SAAS;CAAK;AAC5C;;;AC3FA,eAAsBW,EAAS,GAAkB;CAC/C,IAAMC,IAAStB,EAAUuB,CAAO,GAC1BC,IAAkB,CAAC,GACnBC,IAAmB,CAAC;CAE1B,EAAO,KAAK,2BAA2B;CACvC,IAAMP,IAAkBd,EAAK,KAAKmB,EAAQ,MAAM,OAAO,iBAAiB,GAClEG,IAAYC,EAChBT,GACAD,EAA2BC,CAAe,CAC5C;CAKA,AAJIQ,KAAWD,EAAS,KAAKC,CAAS,GAItCJ,EAAO,KAAK,gDAAgD;CAC5D,IAAMM,IAAUC,EAAmBN,EAAQ,MAAMtB,CAAkB;CAInE,OAHI2B,EAAQ,UAAQJ,EAAQ,KAAKI,EAAQ,MAAM,GAC3CA,EAAQ,UAAQH,EAAS,KAAKG,EAAQ,MAAM,GAEzC;EACL;EACA;EACA,SAAS,CAAC;EACV,YAAY,CAAC;EACb,UAAU,CAAC;EACX,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAiB,CAAC;CACpB;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"generate.runtime-CslAvllQ.js","names":[],"sources":["../../src/patterns/disable/auth/modifies/+layout.server.ts","../../src/patterns/disable/auth/modifies/root-layout.svelte.ts","../../src/patterns/disable/auth/modifies/hooks.server.ts","../../src/patterns/disable/auth/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport { Project, SyntaxKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport {\n removeUnusedBindingElement,\n formatLikeSource,\n} from \"../../../../runtime/ts-morph-helpers\";\n\nexport function unmodifyLayoutServer(layoutPath: string): ModifyOutcome {\n if (!fs.existsSync(layoutPath)) {\n return { status: \"success\", changed: false };\n }\n\n const originalSource = fs.readFileSync(layoutPath, \"utf8\");\n if (!originalSource.includes(\"locals.pb.authStore.record\")) {\n return { status: \"success\", changed: false };\n }\n\n const project = new Project();\n const sourceFile = project.addSourceFileAtPath(layoutPath);\n\n const literals = sourceFile.getDescendantsOfKind(\n SyntaxKind.ObjectLiteralExpression,\n );\n for (const obj of literals) {\n const userProp = obj.getProperty(\"user\");\n if (!userProp || userProp.getKind() !== SyntaxKind.PropertyAssignment) {\n continue;\n }\n const value = (userProp as import(\"ts-morph\").PropertyAssignment)\n .getInitializer()\n ?.getText();\n if (value === \"locals.pb.authStore.record\") {\n userProp.remove();\n }\n }\n // `user` was often the layout's only use of `locals`, which enable-auth\n // destructured for it.\n removeUnusedBindingElement(sourceFile, \"locals\");\n\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n\n return {\n status: \"success\",\n changed: sourceFile.getFullText() !== originalSource,\n };\n}\n","import fs from \"node:fs\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport {\n ensureBlankLineAfterImports,\n removeImportByModuleSpecifier,\n removePropsBindingIfUnused,\n withInMemoryScript,\n} from \"../../../../runtime/ts-morph-helpers\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport { libModule } from \"../../../../runtime/lib-specifier\";\n\nexport function unmodifyRootLayoutSvelte(layoutPath: string): ModifyOutcome {\n if (!fs.existsSync(layoutPath)) {\n return { status: \"success\", changed: false };\n }\n\n const source = fs.readFileSync(layoutPath, \"utf8\");\n const file = new SvelteFile(source);\n if (!file.hasElement(\"AuthMenu.Root\")) {\n return { status: \"success\", changed: false };\n }\n\n file.removeElement(\"AuthMenu.Root\");\n const markup = file.toString().replace(/<script[\\s\\S]*?<\\/script>/g, \"\");\n\n file.modifyScript((content) => {\n const { source: out } = withInMemoryScript(content, (sf) => {\n removeImportByModuleSpecifier(sf, libModule(\"components/ui/auth-menu\"));\n removeImportByModuleSpecifier(sf, libModule(\"components/ui/avatar\"));\n // enable-auth added `data` for the menu's `data.user`.\n removePropsBindingIfUnused(sf, \"data\", markup);\n ensureBlankLineAfterImports(sf);\n });\n return out;\n });\n\n file.writeTo(layoutPath);\n return { status: \"success\", changed: file.hasChanged() };\n}\n","import fs from \"node:fs\";\nimport { Project, SyntaxKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport { formatLikeSource } from \"../../../../runtime/ts-morph-helpers\";\n\nexport function unmodifyHooksServer(hooksServerPath: string): ModifyOutcome {\n if (!fs.existsSync(hooksServerPath)) {\n return { status: \"success\", changed: false };\n }\n\n const originalSource = fs.readFileSync(hooksServerPath, \"utf8\");\n const project = new Project();\n const sourceFile = project.addSourceFileAtPath(hooksServerPath);\n\n const callExpr = sourceFile\n .getDescendantsOfKind(SyntaxKind.CallExpression)\n .find((ce) => ce.getExpression().getText() === \"handlePocketbase\");\n if (!callExpr) return { status: \"success\", changed: false };\n\n const [firstArg] = callExpr.getArguments();\n if (!firstArg || firstArg.getKind() !== SyntaxKind.ObjectLiteralExpression) {\n return { status: \"success\", changed: false };\n }\n\n const optionsObj = firstArg.asKindOrThrow(SyntaxKind.ObjectLiteralExpression);\n const authProp = optionsObj.getProperty(\"auth\");\n if (!authProp) {\n return { status: \"success\", changed: false };\n }\n\n authProp.remove();\n\n if (optionsObj.getProperties().length === 0) {\n callExpr.removeArgument(0);\n }\n\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n\n return {\n status: \"success\",\n changed: sourceFile.getFullText() !== originalSource,\n };\n}\n","import path from \"node:path\";\nimport fs from \"node:fs\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { unmodifyLayoutServer } from \"./modifies/+layout.server\";\nimport { unmodifyRootLayoutSvelte } from \"./modifies/root-layout.svelte\";\nimport { unmodifyHooksServer } from \"./modifies/hooks.server\";\nimport { planDropsForCollections } from \"../../destroy/shared\";\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const modifies: File[] = [];\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n logger.info(\"Reverting +layout.server.ts\");\n const layoutServerFile = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"+layout.server.ts\",\n );\n pushResult(\n modifyOutcomeToFile(\n layoutServerFile,\n unmodifyLayoutServer(layoutServerFile),\n ),\n );\n\n logger.info(\"Reverting root layout\");\n const layoutCandidates = [\n path.join(options.root, \"src\", \"routes\", \"(public)\", \"root-layout.svelte\"),\n path.join(options.root, \"src\", \"routes\", \"root-layout.svelte\"),\n path.join(options.root, \"src\", \"routes\", \"(public)\", \"+layout.svelte\"),\n path.join(options.root, \"src\", \"routes\", \"+layout.svelte\"),\n ];\n const layoutFile =\n layoutCandidates.find((p) => fs.existsSync(p)) ?? layoutCandidates[0];\n pushResult(\n modifyOutcomeToFile(layoutFile, unmodifyRootLayoutSvelte(layoutFile)),\n );\n\n logger.info(\"Reverting hooks.server.ts\");\n const hooksServerFile = path.join(options.root, \"src\", \"hooks.server.ts\");\n pushResult(\n modifyOutcomeToFile(hooksServerFile, unmodifyHooksServer(hooksServerFile)),\n );\n\n const collectionDrops = await planDropsForCollections(\n [\"oauth_accounts\"],\n options,\n );\n\n return {\n creates: [],\n modifies,\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops,\n } satisfies Result;\n}\n"],"mappings":";;;;;;;;;;AAQA,SAAgB,EAAqB,GAAmC;CACtE,IAAI,CAAC,EAAG,WAAW,CAAU,GAC3B,OAAO;EAAE,QAAQ;EAAW,SAAS;CAAM;CAG7C,IAAM,IAAiB,EAAG,aAAa,GAAY,MAAM;CACzD,IAAI,CAAC,EAAe,SAAS,4BAA4B,GACvD,OAAO;EAAE,QAAQ;EAAW,SAAS;CAAM;CAI7C,IAAM,IAAa,IADC,EACD,CAAA,CAAQ,oBAAoB,CAAU,GAEnD,IAAW,EAAW,qBAC1B,EAAW,uBACb;CACA,KAAK,IAAM,KAAO,GAAU;EAC1B,IAAM,IAAW,EAAI,YAAY,MAAM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IAAM,IAAkB,EAAK,KAAK,EAAQ,MAAM,OAAO,iBAAiB;CAUxE,OATA,EACE,EAAoB,GAAiB,EAAoB,CAAe,CAAC,CAC3E,GAOO;EACL,SAAS,CAAC;EACV;EACA,SAAS,CAAC;EACV,YAAY,CAAC;EACb,UAAU,CAAC;EACX,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAA,MAb4B,EAC5B,CAAC,gBAAgB,GACjB,CACF;CAWA;AACF"}
1
+ {"version":3,"file":"generate.runtime-CslAvllQ.js","names":["libModule","getLogger","planDropsForCollections","withInMemoryScript","removeUnusedBindingElement","ensureBlankLineAfterImports","removePropsBindingIfUnused","removeImportByModuleSpecifier","SvelteFile","fs","path","unmodifyLayoutServer","layoutPath","originalSource","sourceFile","Project","literals","SyntaxKind","obj","userProp","formatLikeSource","unmodifyRootLayoutSvelte","source","file","markup","out","content","sf","unmodifyHooksServer","hooksServerPath","callExpr","ce","firstArg","optionsObj","authProp","generate","logger","options","modifies","pushResult","layoutServerFile","modifyOutcomeToFile","layoutCandidates","layoutFile","p","hooksServerFile"],"sources":["../../src/patterns/disable/auth/modifies/+layout.server.ts","../../src/patterns/disable/auth/modifies/root-layout.svelte.ts","../../src/patterns/disable/auth/modifies/hooks.server.ts","../../src/patterns/disable/auth/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport { Project, SyntaxKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport {\n removeUnusedBindingElement,\n formatLikeSource,\n} from \"../../../../runtime/ts-morph-helpers\";\n\nexport function unmodifyLayoutServer(layoutPath: string): ModifyOutcome {\n if (!fs.existsSync(layoutPath)) {\n return { status: \"success\", changed: false };\n }\n\n const originalSource = fs.readFileSync(layoutPath, \"utf8\");\n if (!originalSource.includes(\"locals.pb.authStore.record\")) {\n return { status: \"success\", changed: false };\n }\n\n const project = new Project();\n const sourceFile = project.addSourceFileAtPath(layoutPath);\n\n const literals = sourceFile.getDescendantsOfKind(\n SyntaxKind.ObjectLiteralExpression,\n );\n for (const obj of literals) {\n const userProp = obj.getProperty(\"user\");\n if (!userProp || userProp.getKind() !== SyntaxKind.PropertyAssignment) {\n continue;\n }\n const value = (userProp as import(\"ts-morph\").PropertyAssignment)\n .getInitializer()\n ?.getText();\n if (value === \"locals.pb.authStore.record\") {\n userProp.remove();\n }\n }\n // `user` was often the layout's only use of `locals`, which enable-auth\n // destructured for it.\n removeUnusedBindingElement(sourceFile, \"locals\");\n\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n\n return {\n status: \"success\",\n changed: sourceFile.getFullText() !== originalSource,\n };\n}\n","import fs from \"node:fs\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport {\n ensureBlankLineAfterImports,\n removeImportByModuleSpecifier,\n removePropsBindingIfUnused,\n withInMemoryScript,\n} from \"../../../../runtime/ts-morph-helpers\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport { libModule } from \"../../../../runtime/lib-specifier\";\n\nexport function unmodifyRootLayoutSvelte(layoutPath: string): ModifyOutcome {\n if (!fs.existsSync(layoutPath)) {\n return { status: \"success\", changed: false };\n }\n\n const source = fs.readFileSync(layoutPath, \"utf8\");\n const file = new SvelteFile(source);\n if (!file.hasElement(\"AuthMenu.Root\")) {\n return { status: \"success\", changed: false };\n }\n\n file.removeElement(\"AuthMenu.Root\");\n const markup = file.toString().replace(/<script[\\s\\S]*?<\\/script>/g, \"\");\n\n file.modifyScript((content) => {\n const { source: out } = withInMemoryScript(content, (sf) => {\n removeImportByModuleSpecifier(sf, libModule(\"components/ui/auth-menu\"));\n removeImportByModuleSpecifier(sf, libModule(\"components/ui/avatar\"));\n // enable-auth added `data` for the menu's `data.user`.\n removePropsBindingIfUnused(sf, \"data\", markup);\n ensureBlankLineAfterImports(sf);\n });\n return out;\n });\n\n file.writeTo(layoutPath);\n return { status: \"success\", changed: file.hasChanged() };\n}\n","import fs from \"node:fs\";\nimport { Project, SyntaxKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport { formatLikeSource } from \"../../../../runtime/ts-morph-helpers\";\n\nexport function unmodifyHooksServer(hooksServerPath: string): ModifyOutcome {\n if (!fs.existsSync(hooksServerPath)) {\n return { status: \"success\", changed: false };\n }\n\n const originalSource = fs.readFileSync(hooksServerPath, \"utf8\");\n const project = new Project();\n const sourceFile = project.addSourceFileAtPath(hooksServerPath);\n\n const callExpr = sourceFile\n .getDescendantsOfKind(SyntaxKind.CallExpression)\n .find((ce) => ce.getExpression().getText() === \"handlePocketbase\");\n if (!callExpr) return { status: \"success\", changed: false };\n\n const [firstArg] = callExpr.getArguments();\n if (!firstArg || firstArg.getKind() !== SyntaxKind.ObjectLiteralExpression) {\n return { status: \"success\", changed: false };\n }\n\n const optionsObj = firstArg.asKindOrThrow(SyntaxKind.ObjectLiteralExpression);\n const authProp = optionsObj.getProperty(\"auth\");\n if (!authProp) {\n return { status: \"success\", changed: false };\n }\n\n authProp.remove();\n\n if (optionsObj.getProperties().length === 0) {\n callExpr.removeArgument(0);\n }\n\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n\n return {\n status: \"success\",\n changed: sourceFile.getFullText() !== originalSource,\n };\n}\n","import path from \"node:path\";\nimport fs from \"node:fs\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { unmodifyLayoutServer } from \"./modifies/+layout.server\";\nimport { unmodifyRootLayoutSvelte } from \"./modifies/root-layout.svelte\";\nimport { unmodifyHooksServer } from \"./modifies/hooks.server\";\nimport { planDropsForCollections } from \"../../destroy/shared\";\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const modifies: File[] = [];\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n logger.info(\"Reverting +layout.server.ts\");\n const layoutServerFile = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"+layout.server.ts\",\n );\n pushResult(\n modifyOutcomeToFile(\n layoutServerFile,\n unmodifyLayoutServer(layoutServerFile),\n ),\n );\n\n logger.info(\"Reverting root layout\");\n const layoutCandidates = [\n path.join(options.root, \"src\", \"routes\", \"(public)\", \"root-layout.svelte\"),\n path.join(options.root, \"src\", \"routes\", \"root-layout.svelte\"),\n path.join(options.root, \"src\", \"routes\", \"(public)\", \"+layout.svelte\"),\n path.join(options.root, \"src\", \"routes\", \"+layout.svelte\"),\n ];\n const layoutFile =\n layoutCandidates.find((p) => fs.existsSync(p)) ?? layoutCandidates[0];\n pushResult(\n modifyOutcomeToFile(layoutFile, unmodifyRootLayoutSvelte(layoutFile)),\n );\n\n logger.info(\"Reverting hooks.server.ts\");\n const hooksServerFile = path.join(options.root, \"src\", \"hooks.server.ts\");\n pushResult(\n modifyOutcomeToFile(hooksServerFile, unmodifyHooksServer(hooksServerFile)),\n );\n\n const collectionDrops = await planDropsForCollections(\n [\"oauth_accounts\"],\n options,\n );\n\n return {\n creates: [],\n modifies,\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops,\n } satisfies Result;\n}\n"],"mappings":";;;;;;;;;;AAQA,SAAgBW,EAAqB,GAAmC;CACtE,IAAI,CAACF,EAAG,WAAWG,CAAU,GAC3B,OAAO;EAAE,QAAQ;EAAW,SAAS;CAAM;CAG7C,IAAMC,IAAiBJ,EAAG,aAAaG,GAAY,MAAM;CACzD,IAAI,CAACC,EAAe,SAAS,4BAA4B,GACvD,OAAO;EAAE,QAAQ;EAAW,SAAS;CAAM;CAI7C,IAAMC,IAAa,IADCC,EACD,CAAA,CAAQ,oBAAoBH,CAAU,GAEnDI,IAAWF,EAAW,qBAC1BG,EAAW,uBACb;CACA,KAAK,IAAMC,KAAOF,GAAU;EAC1B,IAAMG,IAAWD,EAAI,YAAY,MAAM;EACvC,AAAKC,KAAYA,EAAS,QAAQ,MAAMF,EAAW,sBAGpCE,EACZ,eAAe,CAAC,EACf,QAAQ,MACE,gCACZA,EAAS,OAA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B,CAAU,CAAC,CACtE,GAEAP,EAAO,KAAK,2BAA2B;CACvC,IAAMS,IAAkBnC,EAAK,KAAK2B,EAAQ,MAAM,OAAO,iBAAiB;CAUxE,OATAE,EACEE,EAAoBI,GAAiBjB,EAAoBiB,CAAe,CAAC,CAC3E,GAOO;EACL,SAAS,CAAC;EACV;EACA,SAAS,CAAC;EACV,YAAY,CAAC;EACb,UAAU,CAAC;EACX,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAA,MAb4B3C,EAC5B,CAAC,gBAAgB,GACjBmC,CACF;CAWA;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"generate.runtime-CuNhY5hn.js","names":[],"sources":["../../src/patterns/enable/auth-remote/modifies/+layout.server.ts","../../src/patterns/enable/auth-remote/modifies/root-layout.svelte.ts","../../src/patterns/enable/auth-remote/modifies/hooks.server.ts","../../src/patterns/enable/auth-remote/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<Avatar.Root>\n\t\t\t\t\t\t\t{#if data.user?.avatar}\n\t\t\t\t\t\t\t\t<Avatar.Image\n\t\t\t\t\t\t\t\t\tsrc=\"/api/files/users/{data.user?.id}/{data.user?.avatar}\"\n\t\t\t\t\t\t\t\t\talt={data.user?.email}\n\t\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t\t{/if}\n\t\t\t\t\t\t\t<Avatar.Fallback>\n\t\t\t\t\t\t\t\t{data.user?.email?.charAt(0).toUpperCase()}\n\t\t\t\t\t\t\t</Avatar.Fallback>\n\t\t\t\t\t\t</Avatar.Root>\n\t\t\t\t\t</AuthMenu.Trigger>\n\n\t\t\t\t\t<AuthMenu.Content align=\"end\">\n\t\t\t\t\t\t<AuthMenu.Item href=\"/dashboard\">Dashboard</AuthMenu.Item>\n\t\t\t\t\t\t<AuthMenu.Group>\n\t\t\t\t\t\t\t<AuthMenu.Item href=\"/settings\">Settings</AuthMenu.Item>\n\t\t\t\t\t\t\t<AuthMenu.Item>\n\t\t\t\t\t\t\t\t<form action=\"/logout\" method=\"post\">\n\t\t\t\t\t\t\t\t\t<button type=\"submit\" class=\"contents\">Logout</button>\n\t\t\t\t\t\t\t\t</form>\n\t\t\t\t\t\t\t</AuthMenu.Item>\n\t\t\t\t\t\t</AuthMenu.Group>\n\t\t\t\t\t</AuthMenu.Content>\n\t\t\t\t{/snippet}\n\n\t\t\t\t{#snippet guest()}\n\t\t\t\t\t<Button\n\t\t\t\t\t\tclass=\"w-full justify-start md:justify-center md:w-auto\"\n\t\t\t\t\t\tvariant=\"ghost\"\n\t\t\t\t\t\thref=\"/login\">Login</Button\n\t\t\t\t\t>\n\t\t\t\t\t<Button\n\t\t\t\t\t\tclass=\"w-full justify-start md:justify-center md:w-auto\"\n\t\t\t\t\t\tvariant=\"outline\"\n\t\t\t\t\t\thref=\"/signup\">Sign up</Button\n\t\t\t\t\t>\n\t\t\t\t{/snippet}\n\t\t\t</AuthMenu.Root>\n\t\t</Navbar.Item>\n\t`;\n\nconst IMPORT_SNIPPET = dedent`\n import * as AuthMenu from '#lib/components/ui/auth-menu/index.js';\n import * as Avatar from '#lib/components/ui/avatar/index.js';\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 namespaceImport: \"Avatar\",\n moduleSpecifier: \"#lib/components/ui/avatar/index.js\",\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 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 let creates: File[] = [];\n\n // Update PocketBase\n await withPocketbase(options.root, async (pb) => {\n logger.info(\"Updating PocketBase mail settings\");\n await pb.settings.update({\n meta: {\n senderName: input.senderName,\n senderAddress: input.senderAddress,\n },\n });\n await migrationDelay();\n\n const userCollection = await pb.collections.getOne(\"users\");\n\n if (!userCollection) {\n throw new Error(\"Users collection not found\");\n }\n\n const verificationTemplate =\n userCollection.verificationTemplate.body.replace(\n \"{APP_URL}/_/#/auth/confirm-verification/{TOKEN}\",\n \"{APP_URL}/confirm-verification/{TOKEN}\",\n );\n const resetPasswordTemplate =\n userCollection.resetPasswordTemplate.body.replace(\n \"{APP_URL}/_/#/auth/confirm-reset/{TOKEN}\",\n \"{APP_URL}/confirm-reset/{TOKEN}\",\n );\n const confirmEmailChangeTemplate =\n userCollection.confirmEmailChangeTemplate.body.replace(\n \"{APP_URL}/_/#/auth/confirm-email-change/{TOKEN}\",\n \"{APP_URL}/confirm-email-change/{TOKEN}\",\n );\n\n logger.info(\"Locking down users collection rules and email templates\");\n // Update user auth rules to lock down access to the user's own account\n await pb.collections.update(\"users\", {\n listRule: \"@request.auth.id = id\",\n viewRule: \"@request.auth.id = id\",\n createRule: \"@request.auth.id = id\",\n updateRule: \"@request.auth.id = id\",\n deleteRule: \"@request.auth.id = id\",\n\n // Update email templates to VelaStack auth urls\n verificationTemplate: {\n body: verificationTemplate,\n },\n resetPasswordTemplate: {\n body: resetPasswordTemplate,\n },\n confirmEmailChangeTemplate: {\n body: confirmEmailChangeTemplate,\n },\n });\n await migrationDelay();\n\n const migrationFile = getMigrationFile(\"users\", \"updated\", options);\n if (migrationFile) {\n creates.push({\n path: migrationFile,\n language: \"ts\",\n content: fs.readFileSync(migrationFile, \"utf8\"),\n status: \"success\",\n });\n }\n });\n\n // Modify files\n const modifies: File[] = [];\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n logger.info(\"Modifying +layout.server.ts\");\n const layoutServerFile = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"+layout.server.ts\",\n );\n pushResult(\n modifyOutcomeToFile(layoutServerFile, modifyLayoutServer(layoutServerFile)),\n );\n\n logger.info(\"Modifying root layout\");\n // TODO: make this more robust by searching for Navbar.Root > Navbar.List\n // src/routes/(public)/root-layout.svelte is what vela creates by default\n const layoutCandidates = [\n path.join(options.root, \"src\", \"routes\", \"(public)\", \"root-layout.svelte\"),\n path.join(options.root, \"src\", \"routes\", \"root-layout.svelte\"),\n path.join(options.root, \"src\", \"routes\", \"(public)\", \"+layout.svelte\"),\n path.join(options.root, \"src\", \"routes\", \"+layout.svelte\"),\n ];\n const layoutFile =\n layoutCandidates.find((p) => fs.existsSync(p)) ?? layoutCandidates[0];\n pushResult(\n modifyOutcomeToFile(layoutFile, modifyRootLayoutSvelte(layoutFile)),\n );\n\n logger.info(\"Modifying hooks.server.ts\");\n const hooksServerFile = path.join(options.root, \"src\", \"hooks.server.ts\");\n pushResult(\n modifyOutcomeToFile(hooksServerFile, modifyHooksServer(hooksServerFile)),\n );\n\n logger.info(\"Modifying 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 ? [siteFile] : [],\n modifies,\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n } satisfies Result;\n}\n"],"mappings":";;;;;;;;;;;;AA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UAAU,gBAAgB;CAC3D,GACM,IACJ,EAAiB,MAAM,MAAM,EAAG,WAAW,CAAC,CAAC,KAAK,EAAiB;CAKrE,AAJA,EACE,EAAoB,GAAY,EAAuB,CAAU,CAAC,CACpE,GAEA,EAAO,KAAK,2BAA2B;CACvC,IAAM,IAAkB,EAAK,KAAK,EAAQ,MAAM,OAAO,iBAAiB;CAKxE,AAJA,EACE,EAAoB,GAAiB,EAAkB,CAAe,CAAC,CACzE,GAEA,EAAO,KAAK,yBAAyB;CACrC,IAAM,IAAgB,EAAK,KAAK,EAAQ,MAAM,QAAQ,UAAU;CAKhE,AAJA,EACE,EAAoB,GAAe,EAAgB,CAAa,CAAC,CACnE,GAEA,EAAO,KAAK,uCAAuC;CACnD,IAAM,IAAS,EAAyB,EAAQ,IAAI;CACpD,EAAW,EAAoB,EAAO,UAAU,EAAO,OAAO,CAAC;CAG/D,IAAM,IAAW,MAAM,EAAe,CAAO;CAE7C,OAAO;EACL,SAAS,IAAW,CAAC,CAAQ,IAAI,CAAC;EAClC;EACA,SAAS,CAAC;EACV,YAAY,CAAC;EACb,UAAU,CAAC;EACX,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAiB,CAAC;CACpB;AACF"}
1
+ {"version":3,"file":"generate.runtime-CuNhY5hn.js","names":["FAILURE_HINT","NOT_FOUND_HINT","dedent","getLogger","withInMemoryScript","ensurePropsBinding","formatLikeSource","ensureImports","SvelteFile","withPocketbase","migrationDelay","getMigrationFile","ensureSiteFile","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","userCollection","verificationTemplate","resetPasswordTemplate","confirmEmailChangeTemplate","migrationFile","modifies","pushResult","layoutServerFile","modifyOutcomeToFile","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<Avatar.Root>\n\t\t\t\t\t\t\t{#if data.user?.avatar}\n\t\t\t\t\t\t\t\t<Avatar.Image\n\t\t\t\t\t\t\t\t\tsrc=\"/api/files/users/{data.user?.id}/{data.user?.avatar}\"\n\t\t\t\t\t\t\t\t\talt={data.user?.email}\n\t\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t\t{/if}\n\t\t\t\t\t\t\t<Avatar.Fallback>\n\t\t\t\t\t\t\t\t{data.user?.email?.charAt(0).toUpperCase()}\n\t\t\t\t\t\t\t</Avatar.Fallback>\n\t\t\t\t\t\t</Avatar.Root>\n\t\t\t\t\t</AuthMenu.Trigger>\n\n\t\t\t\t\t<AuthMenu.Content align=\"end\">\n\t\t\t\t\t\t<AuthMenu.Item href=\"/dashboard\">Dashboard</AuthMenu.Item>\n\t\t\t\t\t\t<AuthMenu.Group>\n\t\t\t\t\t\t\t<AuthMenu.Item href=\"/settings\">Settings</AuthMenu.Item>\n\t\t\t\t\t\t\t<AuthMenu.Item>\n\t\t\t\t\t\t\t\t<form action=\"/logout\" method=\"post\">\n\t\t\t\t\t\t\t\t\t<button type=\"submit\" class=\"contents\">Logout</button>\n\t\t\t\t\t\t\t\t</form>\n\t\t\t\t\t\t\t</AuthMenu.Item>\n\t\t\t\t\t\t</AuthMenu.Group>\n\t\t\t\t\t</AuthMenu.Content>\n\t\t\t\t{/snippet}\n\n\t\t\t\t{#snippet guest()}\n\t\t\t\t\t<Button\n\t\t\t\t\t\tclass=\"w-full justify-start md:justify-center md:w-auto\"\n\t\t\t\t\t\tvariant=\"ghost\"\n\t\t\t\t\t\thref=\"/login\">Login</Button\n\t\t\t\t\t>\n\t\t\t\t\t<Button\n\t\t\t\t\t\tclass=\"w-full justify-start md:justify-center md:w-auto\"\n\t\t\t\t\t\tvariant=\"outline\"\n\t\t\t\t\t\thref=\"/signup\">Sign up</Button\n\t\t\t\t\t>\n\t\t\t\t{/snippet}\n\t\t\t</AuthMenu.Root>\n\t\t</Navbar.Item>\n\t`;\n\nconst IMPORT_SNIPPET = dedent`\n import * as AuthMenu from '#lib/components/ui/auth-menu/index.js';\n import * as Avatar from '#lib/components/ui/avatar/index.js';\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 namespaceImport: \"Avatar\",\n moduleSpecifier: \"#lib/components/ui/avatar/index.js\",\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 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 let creates: File[] = [];\n\n // Update PocketBase\n await withPocketbase(options.root, async (pb) => {\n logger.info(\"Updating PocketBase mail settings\");\n await pb.settings.update({\n meta: {\n senderName: input.senderName,\n senderAddress: input.senderAddress,\n },\n });\n await migrationDelay();\n\n const userCollection = await pb.collections.getOne(\"users\");\n\n if (!userCollection) {\n throw new Error(\"Users collection not found\");\n }\n\n const verificationTemplate =\n userCollection.verificationTemplate.body.replace(\n \"{APP_URL}/_/#/auth/confirm-verification/{TOKEN}\",\n \"{APP_URL}/confirm-verification/{TOKEN}\",\n );\n const resetPasswordTemplate =\n userCollection.resetPasswordTemplate.body.replace(\n \"{APP_URL}/_/#/auth/confirm-reset/{TOKEN}\",\n \"{APP_URL}/confirm-reset/{TOKEN}\",\n );\n const confirmEmailChangeTemplate =\n userCollection.confirmEmailChangeTemplate.body.replace(\n \"{APP_URL}/_/#/auth/confirm-email-change/{TOKEN}\",\n \"{APP_URL}/confirm-email-change/{TOKEN}\",\n );\n\n logger.info(\"Locking down users collection rules and email templates\");\n // Update user auth rules to lock down access to the user's own account\n await pb.collections.update(\"users\", {\n listRule: \"@request.auth.id = id\",\n viewRule: \"@request.auth.id = id\",\n createRule: \"@request.auth.id = id\",\n updateRule: \"@request.auth.id = id\",\n deleteRule: \"@request.auth.id = id\",\n\n // Update email templates to VelaStack auth urls\n verificationTemplate: {\n body: verificationTemplate,\n },\n resetPasswordTemplate: {\n body: resetPasswordTemplate,\n },\n confirmEmailChangeTemplate: {\n body: confirmEmailChangeTemplate,\n },\n });\n await migrationDelay();\n\n const migrationFile = getMigrationFile(\"users\", \"updated\", options);\n if (migrationFile) {\n creates.push({\n path: migrationFile,\n language: \"ts\",\n content: fs.readFileSync(migrationFile, \"utf8\"),\n status: \"success\",\n });\n }\n });\n\n // Modify files\n const modifies: File[] = [];\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n logger.info(\"Modifying +layout.server.ts\");\n const layoutServerFile = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"+layout.server.ts\",\n );\n pushResult(\n modifyOutcomeToFile(layoutServerFile, modifyLayoutServer(layoutServerFile)),\n );\n\n logger.info(\"Modifying root layout\");\n // TODO: make this more robust by searching for Navbar.Root > Navbar.List\n // src/routes/(public)/root-layout.svelte is what vela creates by default\n const layoutCandidates = [\n path.join(options.root, \"src\", \"routes\", \"(public)\", \"root-layout.svelte\"),\n path.join(options.root, \"src\", \"routes\", \"root-layout.svelte\"),\n path.join(options.root, \"src\", \"routes\", \"(public)\", \"+layout.svelte\"),\n path.join(options.root, \"src\", \"routes\", \"+layout.svelte\"),\n ];\n const layoutFile =\n layoutCandidates.find((p) => fs.existsSync(p)) ?? layoutCandidates[0];\n pushResult(\n modifyOutcomeToFile(layoutFile, modifyRootLayoutSvelte(layoutFile)),\n );\n\n logger.info(\"Modifying hooks.server.ts\");\n const hooksServerFile = path.join(options.root, \"src\", \"hooks.server.ts\");\n pushResult(\n modifyOutcomeToFile(hooksServerFile, modifyHooksServer(hooksServerFile)),\n );\n\n logger.info(\"Modifying 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 ? [siteFile] : [],\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,CA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names":[],"sources":["../../src/patterns/enable/content-negotiation/modifies/hooks.server.ts","../../src/patterns/enable/content-negotiation/modifies/hooks.ts","../../src/patterns/enable/content-negotiation/modifies/root-layout.svelte.ts","../../src/patterns/enable/content-negotiation/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport path from \"node:path\";\nimport dedent from \"dedent\";\nimport { Project, QuoteKind, type SourceFile } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport { addHandle } from \"../../../../runtime/compose-handle\";\nimport { formatLikeSource } from \"../../../../runtime/ts-morph-helpers\";\n\nconst FAILURE_HINT = dedent`\n Wrap your exported handle with the negotiation handler:\n\n import { sequence } from '@sveltejs/kit/hooks';\n import { handle as handleNegotiate } from '#lib/negotiate.js';\n\n export const handle = sequence(handleNegotiate, /* your existing handle */);\n`;\n\nconst HOOKS_SERVER_SNIPPET = dedent`\n import { handle as handleNegotiate } from '#lib/negotiate.js';\n\n export const handle = handleNegotiate;\n`;\n\nfunction ensureNegotiateHandleImport(sourceFile: SourceFile) {\n const existing = sourceFile\n .getImportDeclarations()\n .find((d) => d.getModuleSpecifierValue() === \"#lib/negotiate.js\");\n if (existing) {\n const has = existing.getNamedImports().some((ni) => {\n return (\n ni.getName() === \"handle\" &&\n ni.getAliasNode()?.getText() === \"handleNegotiate\"\n );\n });\n if (!has)\n existing.addNamedImport({ name: \"handle\", alias: \"handleNegotiate\" });\n return;\n }\n sourceFile.addImportDeclaration({\n namedImports: [{ name: \"handle\", alias: \"handleNegotiate\" }],\n moduleSpecifier: \"#lib/negotiate.js\",\n });\n}\n\nexport function modifyHooksServerNegotiate(\n hooksServerPath: string,\n): ModifyOutcome {\n if (!fs.existsSync(hooksServerPath)) {\n // SvelteKit loads the first `hooks.server.*` it finds, and `.js` sorts\n // first, so a new `.ts` beside it would never run.\n if (fs.existsSync(hooksServerPath.replace(/\\.ts$/, \".js\"))) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n fs.mkdirSync(path.dirname(hooksServerPath), { recursive: true });\n fs.writeFileSync(hooksServerPath, HOOKS_SERVER_SNIPPET + \"\\n\");\n return { status: \"success\", changed: true };\n }\n\n const original = fs.readFileSync(hooksServerPath, \"utf8\");\n if (original.includes(\"handleNegotiate\")) {\n return { status: \"success\", changed: false };\n }\n\n const project = new Project({\n compilerOptions: { allowJs: true },\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n const sourceFile = project.addSourceFileAtPath(hooksServerPath);\n\n const composed = addHandle(sourceFile, { expression: \"handleNegotiate\" });\n if (composed.status === \"unsupported\") {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n ensureNegotiateHandleImport(sourceFile);\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return {\n status: \"success\",\n changed: sourceFile.getFullText() !== original,\n };\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport dedent from \"dedent\";\nimport { Project, QuoteKind, SyntaxKind, type SourceFile } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport { formatLikeSource } from \"../../../../runtime/ts-morph-helpers\";\n\nconst NEGOTIATE_ONLY_SNIPPET = dedent`\n import { reroute as negotiateReroute } from '#lib/negotiate.js';\n\n export const reroute = ({ url }) => negotiateReroute(url.pathname);\n`;\n\nconst FAILURE_HINT = dedent`\n Compose your existing reroute in src/hooks.ts with the negotiation reroute:\n\n import { reroute as negotiateReroute } from '#lib/negotiate.js';\n\n export const reroute = ({ url }) => existingReroute(negotiateReroute(url.pathname));\n`;\n\nfunction ensureNegotiateImport(sourceFile: SourceFile) {\n const existing = sourceFile\n .getImportDeclarations()\n .find((d) => d.getModuleSpecifierValue() === \"#lib/negotiate.js\");\n if (existing) {\n const has = existing.getNamedImports().some((ni) => {\n return (\n ni.getName() === \"reroute\" &&\n ni.getAliasNode()?.getText() === \"negotiateReroute\"\n );\n });\n if (!has) {\n existing.addNamedImport({ name: \"reroute\", alias: \"negotiateReroute\" });\n }\n return;\n }\n sourceFile.addImportDeclaration({\n namedImports: [{ name: \"reroute\", alias: \"negotiateReroute\" }],\n moduleSpecifier: \"#lib/negotiate.js\",\n });\n}\n\nexport function modifyHooksNegotiate(hooksPath: string): ModifyOutcome {\n if (!fs.existsSync(hooksPath)) {\n fs.mkdirSync(path.dirname(hooksPath), { recursive: true });\n fs.writeFileSync(hooksPath, NEGOTIATE_ONLY_SNIPPET + \"\\n\");\n return { status: \"success\", changed: true };\n }\n\n const original = fs.readFileSync(hooksPath, \"utf8\");\n if (original.includes(\"negotiateReroute\")) {\n return { status: \"success\", changed: false };\n }\n\n const project = new Project({\n compilerOptions: { allowJs: true },\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n const sourceFile = project.addSourceFileAtPath(hooksPath);\n\n const rerouteDecl = sourceFile.getVariableDeclaration(\"reroute\");\n\n if (!rerouteDecl) {\n ensureNegotiateImport(sourceFile);\n sourceFile.addStatements(\n `\\nexport const reroute = ({ url }) => negotiateReroute(url.pathname);\\n`,\n );\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n }\n\n const rerouteStmt = rerouteDecl.getFirstAncestorByKind(\n SyntaxKind.VariableStatement,\n );\n if (!rerouteStmt?.hasExportKeyword()) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n const init = rerouteDecl.getInitializer();\n if (!init) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n const hasI18nHelper = sourceFile\n .getVariableDeclarations()\n .some((d) => d.getName() === \"rerouteDeLocalize\");\n const initText = init.getText();\n\n if (hasI18nHelper && initText.includes(\"rerouteDeLocalize\")) {\n ensureNegotiateImport(sourceFile);\n rerouteDecl.setInitializer(\n \"({ url }) => rerouteDeLocalize(negotiateReroute(url.pathname))\",\n );\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n }\n\n return { status: \"failed\", message: FAILURE_HINT };\n}\n","import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport {\n ensureImports,\n withInMemoryScript,\n} from \"../../../../runtime/ts-morph-helpers\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst IMPORT_SNIPPET = dedent`\n import { Negotiate } from '#lib/negotiate.js';\n`;\n\nconst MARKUP_SNIPPET = \"\\n<Negotiate />\\n\";\n\nconst NOT_FOUND_HINT = [\n \"Create the root +layout.svelte and mount <Negotiate /> inside it.\",\n \"\",\n \"Import for the <script> tag:\",\n \"\",\n IMPORT_SNIPPET,\n \"\",\n \"Markup to add at the top level of the layout:\",\n MARKUP_SNIPPET.trim(),\n].join(\"\\n\");\n\nexport function modifyRootLayoutNegotiate(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(\"Negotiate\")) {\n return { status: \"success\", changed: false };\n }\n\n file.modifyScript((source) => {\n const { source: out } = withInMemoryScript(source, (sf) => {\n ensureImports(sf, [\n {\n namedImports: [\"Negotiate\"],\n moduleSpecifier: \"#lib/negotiate.js\",\n },\n ]);\n });\n return out;\n });\n\n file.appendMarkup(MARKUP_SNIPPET);\n file.writeTo(layoutPath);\n return { status: \"success\", changed: file.hasChanged() };\n}\n","import path from \"node:path\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { modifyHooksServerNegotiate } from \"./modifies/hooks.server\";\nimport { modifyHooksNegotiate } from \"./modifies/hooks\";\nimport { modifyRootLayoutNegotiate } from \"./modifies/root-layout.svelte\";\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const modifies: File[] = [];\n\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n logger.info(\"Modifying hooks.server.ts\");\n const hooksServerPath = path.join(options.root, \"src\", \"hooks.server.ts\");\n pushResult(\n modifyOutcomeToFile(\n hooksServerPath,\n modifyHooksServerNegotiate(hooksServerPath),\n ),\n );\n\n logger.info(\"Modifying hooks.ts\");\n const hooksPath = path.join(options.root, \"src\", \"hooks.ts\");\n pushResult(modifyOutcomeToFile(hooksPath, modifyHooksNegotiate(hooksPath)));\n\n logger.info(\"Modifying src/routes/+layout.svelte\");\n const rootLayoutPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"+layout.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(\n rootLayoutPath,\n modifyRootLayoutNegotiate(rootLayoutPath),\n ),\n );\n\n return {\n creates: [],\n modifies,\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n } satisfies Result;\n}\n"],"mappings":";;;;;;;;;;AAQA,IAAM,IAAe,CAAM;;;;;;;GASrB,IAAuB,CAAM;;;;;AAMnC,SAAS,EAA4B,GAAwB;CAC3D,IAAM,IAAW,EACd,sBAAsB,CAAC,CACvB,MAAM,MAAM,EAAE,wBAAwB,MAAM,mBAAmB;CAClE,IAAI,GAAU;EAOZ,AANY,EAAS,gBAAgB,CAAC,CAAC,MAAM,MAEzC,EAAG,QAAQ,MAAM,YACjB,EAAG,aAAa,CAAC,EAAE,QAAQ,MAAM,iBAGhC,KACH,EAAS,eAAe;GAAE,MAAM;GAAU,OAAO;EAAkB,CAAC;EACtE;CACF;CACA,EAAW,qBAAqB;EAC9B,cAAc,CAAC;GAAE,MAAM;GAAU,OAAO;EAAkB,CAAC;EAC3D,iBAAiB;CACnB,CAAC;AACH;AAEA,SAAgB,EACd,GACe;CACf,IAAI,CAAC,EAAG,WAAW,CAAe,GAQhC,OALI,EAAG,WAAW,EAAgB,QAAQ,SAAS,KAAK,CAAC,IAChD;EAAE,QAAQ;EAAU,SAAS;CAAa,KAEnD,EAAG,UAAU,EAAK,QAAQ,CAAe,GAAG,EAAE,WAAW,GAAK,CAAC,GAC/D,EAAG,cAAc,GAAiB,IAAuB,IAAI,GACtD;EAAE,QAAQ;EAAW,S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;EAAE,QAAQ;EAAW,SAAS;CAAM,KAG7C,EAAK,cAAc,MAAW;EAC5B,IAAM,EAAE,QAAQ,MAAQ,EAAmB,IAAS,MAAO;GACzD,EAAc,GAAI,CAChB;IACE,cAAc,CAAC,WAAW;IAC1B,iBAAiB;GACnB,CACF,CAAC;EACH,CAAC;EACD,OAAO;CACT,CAAC,GAED,EAAK,aAAa,CAAc,GAChC,EAAK,QAAQ,CAAU,GAChB;EAAE,QAAQ;EAAW,SAAS,EAAK,WAAW;CAAE;AACzD;;;AC3CA,eAAsB,EAAS,GAAkB;CAC/C,IAAM,IAAS,EAAU,CAAO,GAC1B,IAAmB,CAAC,GAEpB,KAAc,MAAsB;EACxC,AAAI,KAAM,EAAS,KAAK,CAAI;CAC9B;CAEA,EAAO,KAAK,2BAA2B;CACvC,IAAM,IAAkB,EAAK,KAAK,EAAQ,MAAM,OAAO,iBAAiB;CAQxE,AAPA,EACE,EACE,GACA,EAA2B,CAAe,CAC5C,CACF,GAEA,EAAO,KAAK,oBAAoB;CAChC,IAAM,IAAY,EAAK,KAAK,EAAQ,MAAM,OAAO,UAAU;CAG3D,AAFA,EAAW,EAAoB,GAAW,EAAqB,CAAS,CAAC,CAAC,GAE1E,EAAO,KAAK,qCAAqC;CACjD,IAAM,IAAiB,EAAK,KAC1B,EAAQ,MACR,OACA,UACA,gBACF;CAQA,OAPA,EACE,EACE,GACA,EAA0B,CAAc,CAC1C,CACF,GAEO;EACL,SAAS,CAAC;EACV;EACA,SAAS,CAAC;EACV,YAAY,CAAC;EACb,UAAU,CAAC;EACX,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAiB,CAAC;CACpB;AACF"}
1
+ {"version":3,"file":"generate.runtime-DD51OSuL.js","names":["FAILURE_HINT","dedent","getLogger","withInMemoryScript","formatLikeSource","ensureImports","SvelteFile","addHandle","fs","path","FAILURE_HINT$1","HOOKS_SERVER_SNIPPET","ensureNegotiateHandleImport","existing","sourceFile","d","ni","modifyHooksServerNegotiate","hooksServerPath","original","Project","QuoteKind","NEGOTIATE_ONLY_SNIPPET","FAILURE_HINT","ensureNegotiateImport","modifyHooksNegotiate","hooksPath","rerouteDecl","SyntaxKind","init","hasI18nHelper","initText","IMPORT_SNIPPET","MARKUP_SNIPPET","NOT_FOUND_HINT","modifyRootLayoutNegotiate","layoutPath","file","out","source","sf","generate","logger","options","modifies","pushResult","modifyOutcomeToFile","rootLayoutPath"],"sources":["../../src/patterns/enable/content-negotiation/modifies/hooks.server.ts","../../src/patterns/enable/content-negotiation/modifies/hooks.ts","../../src/patterns/enable/content-negotiation/modifies/root-layout.svelte.ts","../../src/patterns/enable/content-negotiation/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport path from \"node:path\";\nimport dedent from \"dedent\";\nimport { Project, QuoteKind, type SourceFile } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport { addHandle } from \"../../../../runtime/compose-handle\";\nimport { formatLikeSource } from \"../../../../runtime/ts-morph-helpers\";\n\nconst FAILURE_HINT = dedent`\n Wrap your exported handle with the negotiation handler:\n\n import { sequence } from '@sveltejs/kit/hooks';\n import { handle as handleNegotiate } from '#lib/negotiate.js';\n\n export const handle = sequence(handleNegotiate, /* your existing handle */);\n`;\n\nconst HOOKS_SERVER_SNIPPET = dedent`\n import { handle as handleNegotiate } from '#lib/negotiate.js';\n\n export const handle = handleNegotiate;\n`;\n\nfunction ensureNegotiateHandleImport(sourceFile: SourceFile) {\n const existing = sourceFile\n .getImportDeclarations()\n .find((d) => d.getModuleSpecifierValue() === \"#lib/negotiate.js\");\n if (existing) {\n const has = existing.getNamedImports().some((ni) => {\n return (\n ni.getName() === \"handle\" &&\n ni.getAliasNode()?.getText() === \"handleNegotiate\"\n );\n });\n if (!has)\n existing.addNamedImport({ name: \"handle\", alias: \"handleNegotiate\" });\n return;\n }\n sourceFile.addImportDeclaration({\n namedImports: [{ name: \"handle\", alias: \"handleNegotiate\" }],\n moduleSpecifier: \"#lib/negotiate.js\",\n });\n}\n\nexport function modifyHooksServerNegotiate(\n hooksServerPath: string,\n): ModifyOutcome {\n if (!fs.existsSync(hooksServerPath)) {\n // SvelteKit loads the first `hooks.server.*` it finds, and `.js` sorts\n // first, so a new `.ts` beside it would never run.\n if (fs.existsSync(hooksServerPath.replace(/\\.ts$/, \".js\"))) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n fs.mkdirSync(path.dirname(hooksServerPath), { recursive: true });\n fs.writeFileSync(hooksServerPath, HOOKS_SERVER_SNIPPET + \"\\n\");\n return { status: \"success\", changed: true };\n }\n\n const original = fs.readFileSync(hooksServerPath, \"utf8\");\n if (original.includes(\"handleNegotiate\")) {\n return { status: \"success\", changed: false };\n }\n\n const project = new Project({\n compilerOptions: { allowJs: true },\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n const sourceFile = project.addSourceFileAtPath(hooksServerPath);\n\n const composed = addHandle(sourceFile, { expression: \"handleNegotiate\" });\n if (composed.status === \"unsupported\") {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n ensureNegotiateHandleImport(sourceFile);\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return {\n status: \"success\",\n changed: sourceFile.getFullText() !== original,\n };\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport dedent from \"dedent\";\nimport { Project, QuoteKind, SyntaxKind, type SourceFile } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport { formatLikeSource } from \"../../../../runtime/ts-morph-helpers\";\n\nconst NEGOTIATE_ONLY_SNIPPET = dedent`\n import { reroute as negotiateReroute } from '#lib/negotiate.js';\n\n export const reroute = ({ url }) => negotiateReroute(url.pathname);\n`;\n\nconst FAILURE_HINT = dedent`\n Compose your existing reroute in src/hooks.ts with the negotiation reroute:\n\n import { reroute as negotiateReroute } from '#lib/negotiate.js';\n\n export const reroute = ({ url }) => existingReroute(negotiateReroute(url.pathname));\n`;\n\nfunction ensureNegotiateImport(sourceFile: SourceFile) {\n const existing = sourceFile\n .getImportDeclarations()\n .find((d) => d.getModuleSpecifierValue() === \"#lib/negotiate.js\");\n if (existing) {\n const has = existing.getNamedImports().some((ni) => {\n return (\n ni.getName() === \"reroute\" &&\n ni.getAliasNode()?.getText() === \"negotiateReroute\"\n );\n });\n if (!has) {\n existing.addNamedImport({ name: \"reroute\", alias: \"negotiateReroute\" });\n }\n return;\n }\n sourceFile.addImportDeclaration({\n namedImports: [{ name: \"reroute\", alias: \"negotiateReroute\" }],\n moduleSpecifier: \"#lib/negotiate.js\",\n });\n}\n\nexport function modifyHooksNegotiate(hooksPath: string): ModifyOutcome {\n if (!fs.existsSync(hooksPath)) {\n fs.mkdirSync(path.dirname(hooksPath), { recursive: true });\n fs.writeFileSync(hooksPath, NEGOTIATE_ONLY_SNIPPET + \"\\n\");\n return { status: \"success\", changed: true };\n }\n\n const original = fs.readFileSync(hooksPath, \"utf8\");\n if (original.includes(\"negotiateReroute\")) {\n return { status: \"success\", changed: false };\n }\n\n const project = new Project({\n compilerOptions: { allowJs: true },\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n const sourceFile = project.addSourceFileAtPath(hooksPath);\n\n const rerouteDecl = sourceFile.getVariableDeclaration(\"reroute\");\n\n if (!rerouteDecl) {\n ensureNegotiateImport(sourceFile);\n sourceFile.addStatements(\n `\\nexport const reroute = ({ url }) => negotiateReroute(url.pathname);\\n`,\n );\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n }\n\n const rerouteStmt = rerouteDecl.getFirstAncestorByKind(\n SyntaxKind.VariableStatement,\n );\n if (!rerouteStmt?.hasExportKeyword()) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n const init = rerouteDecl.getInitializer();\n if (!init) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n const hasI18nHelper = sourceFile\n .getVariableDeclarations()\n .some((d) => d.getName() === \"rerouteDeLocalize\");\n const initText = init.getText();\n\n if (hasI18nHelper && initText.includes(\"rerouteDeLocalize\")) {\n ensureNegotiateImport(sourceFile);\n rerouteDecl.setInitializer(\n \"({ url }) => rerouteDeLocalize(negotiateReroute(url.pathname))\",\n );\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n }\n\n return { status: \"failed\", message: FAILURE_HINT };\n}\n","import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport {\n ensureImports,\n withInMemoryScript,\n} from \"../../../../runtime/ts-morph-helpers\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst IMPORT_SNIPPET = dedent`\n import { Negotiate } from '#lib/negotiate.js';\n`;\n\nconst MARKUP_SNIPPET = \"\\n<Negotiate />\\n\";\n\nconst NOT_FOUND_HINT = [\n \"Create the root +layout.svelte and mount <Negotiate /> inside it.\",\n \"\",\n \"Import for the <script> tag:\",\n \"\",\n IMPORT_SNIPPET,\n \"\",\n \"Markup to add at the top level of the layout:\",\n MARKUP_SNIPPET.trim(),\n].join(\"\\n\");\n\nexport function modifyRootLayoutNegotiate(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(\"Negotiate\")) {\n return { status: \"success\", changed: false };\n }\n\n file.modifyScript((source) => {\n const { source: out } = withInMemoryScript(source, (sf) => {\n ensureImports(sf, [\n {\n namedImports: [\"Negotiate\"],\n moduleSpecifier: \"#lib/negotiate.js\",\n },\n ]);\n });\n return out;\n });\n\n file.appendMarkup(MARKUP_SNIPPET);\n file.writeTo(layoutPath);\n return { status: \"success\", changed: file.hasChanged() };\n}\n","import path from \"node:path\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { modifyHooksServerNegotiate } from \"./modifies/hooks.server\";\nimport { modifyHooksNegotiate } from \"./modifies/hooks\";\nimport { modifyRootLayoutNegotiate } from \"./modifies/root-layout.svelte\";\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const modifies: File[] = [];\n\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n logger.info(\"Modifying hooks.server.ts\");\n const hooksServerPath = path.join(options.root, \"src\", \"hooks.server.ts\");\n pushResult(\n modifyOutcomeToFile(\n hooksServerPath,\n modifyHooksServerNegotiate(hooksServerPath),\n ),\n );\n\n logger.info(\"Modifying hooks.ts\");\n const hooksPath = path.join(options.root, \"src\", \"hooks.ts\");\n pushResult(modifyOutcomeToFile(hooksPath, modifyHooksNegotiate(hooksPath)));\n\n logger.info(\"Modifying src/routes/+layout.svelte\");\n const rootLayoutPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"+layout.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(\n rootLayoutPath,\n modifyRootLayoutNegotiate(rootLayoutPath),\n ),\n );\n\n return {\n creates: [],\n modifies,\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n } satisfies Result;\n}\n"],"mappings":";;;;;;;;;;AAQA,IAAMA,IAAe,CAAM;;;;;;;GASrBW,IAAuB,CAAM;;;;;AAMnC,SAASC,EAA4B,GAAwB;CAC3D,IAAMC,IAAWC,EACd,sBAAsB,CAAC,CACvB,MAAM,MAAMC,EAAE,wBAAwB,MAAM,mBAAmB;CAClE,IAAIF,GAAU;EAOZ,AANYA,EAAS,gBAAgB,CAAC,CAAC,MAAM,MAEzCG,EAAG,QAAQ,MAAM,YACjBA,EAAG,aAAa,CAAC,EAAE,QAAQ,MAAM,iBAGhC,KACHH,EAAS,eAAe;GAAE,MAAM;GAAU,OAAO;EAAkB,CAAC;EACtE;CACF;CACA,EAAW,qBAAqB;EAC9B,cAAc,CAAC;GAAE,MAAM;GAAU,OAAO;EAAkB,CAAC;EAC3D,iBAAiB;CACnB,CAAC;AACH;AAEA,SAAgBI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jD,IAAMK,IAAiBtC,EAAK,KAC1BkC,EAAQ,MACR,OACA,UACA,gBACF;CAQA,OAPAE,EACEC,EACEC,GACAZ,EAA0BY,CAAc,CAC1C,CACF,GAEO;EACL,SAAS,CAAC;EACV;EACA,SAAS,CAAC;EACV,YAAY,CAAC;EACb,UAAU,CAAC;EACX,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAiB,CAAC;CACpB;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"generate.runtime-DHBRyMAq.js","names":[],"sources":["../../src/patterns/disable/analytics/modifies/layout.svelte.ts","../../src/patterns/disable/analytics/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport {\n ensureBlankLineAfterImports,\n removeImportByModuleSpecifier,\n withInMemoryScript,\n} from \"../../../../runtime/ts-morph-helpers\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport { libModule } from \"../../../../runtime/lib-specifier\";\n\nconst MODULE = \"components/analytics/analytics.svelte\";\n\n/**\n * Takes `<Analytics />` and its import back out of the root layout. The\n * element goes with its whole line, since enable-analytics put it on one of\n * its own. A layout without it, or no layout at all, is left alone.\n */\nexport function unmodifyLayoutSvelte(layoutPath: string): ModifyOutcome {\n if (!fs.existsSync(layoutPath)) {\n return { status: \"success\", changed: false };\n }\n\n const original = fs.readFileSync(layoutPath, \"utf8\");\n if (!original.includes(MODULE) && !original.includes(\"<Analytics\")) {\n return { status: \"success\", changed: false };\n }\n\n const file = SvelteFile.fromPath(layoutPath);\n file.modifyScript((source) => {\n const { source: out } = withInMemoryScript(source, (sf) => {\n removeImportByModuleSpecifier(sf, libModule(MODULE));\n ensureBlankLineAfterImports(sf);\n });\n return out;\n });\n\n const updated = file\n .toString()\n .replace(/[ \\t]*<Analytics\\s*\\/>[ \\t]*\\r?\\n?/g, \"\");\n\n if (updated === original) {\n return { status: \"success\", changed: false };\n }\n fs.writeFileSync(layoutPath, updated, \"utf8\");\n return { status: \"success\", changed: true };\n}\n","import path from \"node:path\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport { modifyEnvRemove } from \"../../../runtime/env\";\nimport {\n envRevertOutcomeToFile,\n modifyOutcomeToFile,\n} from \"../../../runtime/modify-file\";\nimport { allEnvEdits, allEnvNames } from \"./generate\";\nimport { unmodifyEnvVarsFiles } from \"../../../runtime/env-vars\";\nimport { unmodifyLayoutSvelte } from \"./modifies/layout.svelte\";\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const modifies: File[] = [];\n const deletes: File[] = [];\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n logger.info(\"Reverting src/routes/+layout.svelte\");\n const layoutPath = path.join(options.root, \"src\", \"routes\", \"+layout.svelte\");\n pushResult(modifyOutcomeToFile(layoutPath, unmodifyLayoutSvelte(layoutPath)));\n\n // Which provider was chosen is not recorded, so every one's variables go;\n // the file goes too when these were all it declared.\n logger.info(\"Removing analytics variables from src/env.ts\");\n const envVars = unmodifyEnvVarsFiles(options.root, allEnvNames());\n pushResult(envVars.modify);\n if (envVars.delete) deletes.push(envVars.delete);\n\n logger.info(\"Removing analytics variables from .env\");\n const envPath = path.join(options.root, \".env\");\n const env = envRevertOutcomeToFile(\n envPath,\n modifyEnvRemove(envPath, allEnvEdits()),\n );\n pushResult(env.modify);\n if (env.delete) deletes.push(env.delete);\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":";;;;;;;;;;;AAUA,IAAM,IAAS;AAOf,SAAgB,EAAqB,GAAmC;CACtE,IAAI,CAAC,EAAG,WAAW,CAAU,GAC3B,OAAO;EAAE,QAAQ;EAAW,SAAS;CAAM;CAG7C,IAAM,IAAW,EAAG,aAAa,GAAY,MAAM;CACnD,IAAI,CAAC,EAAS,SAAS,CAAM,KAAK,CAAC,EAAS,SAAS,Y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AAC;EACpB,iBAAiB,CAAC;CACpB;AACF"}
1
+ {"version":3,"file":"generate.runtime-DHBRyMAq.js","names":["libModule","getLogger","allEnvEdits","modifyEnvRemove","withInMemoryScript","ensureBlankLineAfterImports","removeImportByModuleSpecifier","SvelteFile","fs","path","MODULE","unmodifyLayoutSvelte","layoutPath","original","file","out","source","sf","updated","generate","logger","options","modifies","deletes","pushResult","modifyOutcomeToFile","envVars","unmodifyEnvVarsFiles","allEnvNames","envPath","env","envRevertOutcomeToFile"],"sources":["../../src/patterns/disable/analytics/modifies/layout.svelte.ts","../../src/patterns/disable/analytics/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport {\n ensureBlankLineAfterImports,\n removeImportByModuleSpecifier,\n withInMemoryScript,\n} from \"../../../../runtime/ts-morph-helpers\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport { libModule } from \"../../../../runtime/lib-specifier\";\n\nconst MODULE = \"components/analytics/analytics.svelte\";\n\n/**\n * Takes `<Analytics />` and its import back out of the root layout. The\n * element goes with its whole line, since enable-analytics put it on one of\n * its own. A layout without it, or no layout at all, is left alone.\n */\nexport function unmodifyLayoutSvelte(layoutPath: string): ModifyOutcome {\n if (!fs.existsSync(layoutPath)) {\n return { status: \"success\", changed: false };\n }\n\n const original = fs.readFileSync(layoutPath, \"utf8\");\n if (!original.includes(MODULE) && !original.includes(\"<Analytics\")) {\n return { status: \"success\", changed: false };\n }\n\n const file = SvelteFile.fromPath(layoutPath);\n file.modifyScript((source) => {\n const { source: out } = withInMemoryScript(source, (sf) => {\n removeImportByModuleSpecifier(sf, libModule(MODULE));\n ensureBlankLineAfterImports(sf);\n });\n return out;\n });\n\n const updated = file\n .toString()\n .replace(/[ \\t]*<Analytics\\s*\\/>[ \\t]*\\r?\\n?/g, \"\");\n\n if (updated === original) {\n return { status: \"success\", changed: false };\n }\n fs.writeFileSync(layoutPath, updated, \"utf8\");\n return { status: \"success\", changed: true };\n}\n","import path from \"node:path\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport { modifyEnvRemove } from \"../../../runtime/env\";\nimport {\n envRevertOutcomeToFile,\n modifyOutcomeToFile,\n} from \"../../../runtime/modify-file\";\nimport { allEnvEdits, allEnvNames } from \"./generate\";\nimport { unmodifyEnvVarsFiles } from \"../../../runtime/env-vars\";\nimport { unmodifyLayoutSvelte } from \"./modifies/layout.svelte\";\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const modifies: File[] = [];\n const deletes: File[] = [];\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n logger.info(\"Reverting src/routes/+layout.svelte\");\n const layoutPath = path.join(options.root, \"src\", \"routes\", \"+layout.svelte\");\n pushResult(modifyOutcomeToFile(layoutPath, unmodifyLayoutSvelte(layoutPath)));\n\n // Which provider was chosen is not recorded, so every one's variables go;\n // the file goes too when these were all it declared.\n logger.info(\"Removing analytics variables from src/env.ts\");\n const envVars = unmodifyEnvVarsFiles(options.root, allEnvNames());\n pushResult(envVars.modify);\n if (envVars.delete) deletes.push(envVars.delete);\n\n logger.info(\"Removing analytics variables from .env\");\n const envPath = path.join(options.root, \".env\");\n const env = envRevertOutcomeToFile(\n envPath,\n modifyEnvRemove(envPath, allEnvEdits()),\n );\n pushResult(env.modify);\n if (env.delete) deletes.push(env.delete);\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":";;;;;;;;;;;AAUA,IAAMU,IAAS;AAOf,SAAgBC,EAAqB,GAAmC;CACtE,IAAI,CAACH,EAAG,WAAWI,CAAU,GAC3B,OAAO;EAAE,QAAQ;EAAW,SAAS;CAAM;CAG7C,IAAMC,IAAWL,EAAG,aAAaI,GAAY,MAAM;CACnD,IAAI,CAACC,EAAS,SAASH,CAAM,KAAK,CAACG,EAAS,SAAS,YAAY,G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;EACV;EACA;EACA,YAAY,CAAC;EACb,UAAU,CAAC;EACX,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAiB,CAAC;CACpB;AACF"}
@@ -1,5 +1,5 @@
1
1
  import { t as e } from "./dedent-Gq6Krl4n.js";
2
- import { t } from "./taggedTemplateLiteral-Dx0fjWiw.js";
2
+ import { t } from "./taggedTemplateLiteral-CswN2AAa.js";
3
3
  import { n } from "./logger-CQONztPm.js";
4
4
  import { r } from "./ts-morph-helpers-CDW4lhox.js";
5
5
  import { modifyOutcomeToFile as i } from "./modify-file-BlDeeurK.js";
@@ -173,4 +173,4 @@ async function T(e) {
173
173
  //#endregion
174
174
  export { T as generate };
175
175
 
176
- //# sourceMappingURL=generate.runtime-BXkZob1O.js.map
176
+ //# sourceMappingURL=generate.runtime-DM4o_QYY.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"generate.runtime-BXkZob1O.js","names":[],"sources":["../../src/patterns/enable/blog/modifies/vite-config.ts","../../src/patterns/enable/blog/modifies/root-layout-svelte.ts","../../src/patterns/enable/blog/modifies/public-root-layout-svelte.ts","../../src/patterns/enable/blog/generate.runtime.ts"],"sourcesContent":["import dedent from \"dedent\";\nimport {\n SyntaxKind,\n type ArrayLiteralExpression,\n type ObjectLiteralExpression,\n} from \"ts-morph\";\nimport {\n modifyConfig,\n type ConfigModifyResult,\n} from \"../../../../runtime/config-target\";\nimport { ensureImports } from \"../../../../runtime/ts-morph-helpers\";\n\nconst FAILURE_HINT = dedent`\n Enable mdsvex in your config (the sveltekit() arg in vite.config):\n\n import { mdsvex } from 'mdsvex';\n\n // ...\n extensions: ['.svelte', '.svx'],\n preprocess: [mdsvex()],\n`;\n\nconst NOT_FOUND_HINT = dedent`\n Enable mdsvex by passing config to the sveltekit() plugin in vite.config.ts:\n\n import { sveltekit } from '@sveltejs/kit/vite';\n import { mdsvex } from 'mdsvex';\n import { defineConfig } from 'vite';\n\n export default defineConfig({\n plugins: [\n sveltekit({\n extensions: ['.svelte', '.svx'],\n preprocess: [mdsvex()],\n }),\n ],\n });\n`;\n\nfunction ensureExtensionsSvx(obj: ObjectLiteralExpression): boolean {\n const existing = obj.getProperty(\"extensions\");\n if (!existing) {\n obj.addPropertyAssignment({\n name: \"extensions\",\n initializer: \"['.svelte', '.svx']\",\n });\n return true;\n }\n if (existing.getKind() !== SyntaxKind.PropertyAssignment) return false;\n const init = (\n existing as import(\"ts-morph\").PropertyAssignment\n ).getInitializer();\n if (!init || init.getKind() !== SyntaxKind.ArrayLiteralExpression) {\n (existing as import(\"ts-morph\").PropertyAssignment).setInitializer(\n \"['.svelte', '.svx']\",\n );\n return true;\n }\n const arr = init as ArrayLiteralExpression;\n const hasSvx = arr\n .getElements()\n .some((el) => el.getText().replace(/['\"`]/g, \"\") === \".svx\");\n if (hasSvx) return false;\n arr.addElement(\"'.svx'\");\n return true;\n}\n\nfunction ensurePreprocessMdsvex(obj: ObjectLiteralExpression): boolean {\n const existing = obj.getProperty(\"preprocess\");\n if (!existing) {\n obj.addPropertyAssignment({\n name: \"preprocess\",\n initializer: \"[mdsvex()]\",\n });\n return true;\n }\n if (existing.getKind() !== SyntaxKind.PropertyAssignment) return false;\n const init = (\n existing as import(\"ts-morph\").PropertyAssignment\n ).getInitializer();\n if (!init) {\n (existing as import(\"ts-morph\").PropertyAssignment).setInitializer(\n \"[mdsvex()]\",\n );\n return true;\n }\n if (init.getKind() === SyntaxKind.ArrayLiteralExpression) {\n const arr = init as ArrayLiteralExpression;\n const hasMdsvex = arr\n .getElements()\n .some((el) => /\\bmdsvex\\s*\\(/.test(el.getText()));\n if (hasMdsvex) return false;\n arr.addElement(\"mdsvex()\");\n return true;\n }\n const text = init.getText();\n if (/\\bmdsvex\\s*\\(/.test(text)) return false;\n (existing as import(\"ts-morph\").PropertyAssignment).setInitializer(\n `[${text}, mdsvex()]`,\n );\n return true;\n}\n\n/**\n * Enable mdsvex: ensure `extensions` includes `.svx`, `preprocess` includes\n * `mdsvex()`, and the `mdsvex` import is present, at the top level of the\n * inline sveltekit() arg in vite.config.\n */\nexport function modifyViteConfigMdsvex(root: string): ConfigModifyResult {\n return modifyConfig(\n root,\n { notFound: NOT_FOUND_HINT, failed: FAILURE_HINT },\n (target) => {\n ensureExtensionsSvx(target.configObject);\n ensurePreprocessMdsvex(target.configObject);\n ensureImports(target.sourceFile, [\n { namedImports: [\"mdsvex\"], moduleSpecifier: \"mdsvex\" },\n ]);\n return true;\n },\n );\n}\n","import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst PRISM_IMPORT = `import '../css/prism-vsc-dark-plus.css';`;\n\nconst NOT_FOUND_HINT = dedent`\n Create src/routes/+layout.svelte and import the Prism theme for\n code block highlighting in blog posts:\n\n <script lang=\"ts\">\n import '../app.css';\n ${PRISM_IMPORT}\n </script>\n`;\n\nconst FAILURE_HINT = dedent`\n Import the Prism theme in your root +layout.svelte for blog code\n block highlighting:\n\n ${PRISM_IMPORT}\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 const script = file.getScript();\n if (!script) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n if (script.content.includes(\"prism-vsc-dark-plus.css\")) {\n return { status: \"success\", changed: false };\n }\n\n file.modifyScript((source) => {\n const appCssMatch = source.match(\n /^(\\s*)import\\s+['\"][^'\"]*app\\.css['\"];?\\s*$/m,\n );\n if (appCssMatch) {\n const indent = appCssMatch[1] ?? \"\";\n const insertion = `\\n${indent}${PRISM_IMPORT}`;\n const end = (appCssMatch.index ?? 0) + appCssMatch[0].length;\n return source.slice(0, end) + insertion + source.slice(end);\n }\n return source.replace(/^/, `\\n\\t${PRISM_IMPORT}\\n`);\n });\n\n file.writeTo(layoutPath);\n return { status: \"success\", changed: file.hasChanged() };\n}\n","import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst BLOG_NAVBAR_ITEM = `\n\t\t<Navbar.Item>\n\t\t\t<Button class=\"w-full justify-start md:justify-center md:w-auto\" href=\"/blog\" variant=\"ghost\">\n\t\t\t\tBlog\n\t\t\t</Button>\n\t\t</Navbar.Item>\n\t`;\n\nconst FAILURE_HINT = dedent`\n Add a Blog link inside <Navbar.List> in the public root layout:\n\n <Navbar.Item>\n <Button class=\"w-full justify-start md:justify-center md:w-auto\" href=\"/blog\" variant=\"ghost\">\n Blog\n </Button>\n </Navbar.Item>\n`;\n\nconst NOT_FOUND_HINT = dedent`\n Create a public root layout with a Blog link in its Navbar.List:\n\n <Navbar.Item>\n <Button class=\"w-full justify-start md:justify-center md:w-auto\" href=\"/blog\" variant=\"ghost\">\n Blog\n </Button>\n </Navbar.Item>\n`;\n\nexport function modifyPublicRootLayout(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\n const raw = fs.readFileSync(layoutPath, \"utf8\");\n if (/href=[\"']\\/blog[\"']/.test(raw)) {\n return { status: \"success\", changed: false };\n }\n\n file.insertBeforeClosingTag(\"Navbar.List\", BLOG_NAVBAR_ITEM);\n file.writeTo(layoutPath);\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 { ensureSiteFile } from \"../../../runtime/site\";\nimport { modifyViteConfigMdsvex } from \"./modifies/vite-config\";\nimport { modifyRootLayoutSvelte } from \"./modifies/root-layout-svelte\";\nimport { modifyPublicRootLayout } from \"./modifies/public-root-layout-svelte\";\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const modifies: File[] = [];\n\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n logger.info(\"Modifying vite.config for mdsvex\");\n const mdsvex = modifyViteConfigMdsvex(options.root);\n pushResult(modifyOutcomeToFile(mdsvex.filePath, mdsvex.outcome));\n\n logger.info(\"Modifying src/routes/+layout.svelte\");\n const rootLayoutPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"+layout.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(rootLayoutPath, modifyRootLayoutSvelte(rootLayoutPath)),\n );\n\n logger.info(\"Modifying public root layout\");\n const publicLayoutCandidates = [\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 ];\n const publicLayoutPath =\n publicLayoutCandidates.find((p) => fs.existsSync(p)) ??\n publicLayoutCandidates[0];\n pushResult(\n modifyOutcomeToFile(\n publicLayoutPath,\n modifyPublicRootLayout(publicLayoutPath),\n ),\n );\n\n // The RSS feed is titled and linked from `src/lib/site.ts`.\n const siteFile = await ensureSiteFile(options);\n\n return {\n creates: siteFile ? [siteFile] : [],\n modifies,\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n } satisfies Result;\n}\n"],"mappings":";;;;;;;;;;;;AAYA,IAAM,IAAe,CAAM;;;;;;;;GAUrB,IAAiB,CAAM;;;;;;;;;;;;;;;;AAiB7B,SAAS,EAAoB,GAAuC;CAClE,IAAM,IAAW,EAAI,YAAY,YAAY;CAC7C,IAAI,CAAC,GAKH,OAJA,EAAI,sBAAsB;EACxB,MAAM;EACN,aAAa;CACf,CAAC,GACM;CAET,IAAI,EAAS,QAAQ,MAAM,EAAW,oBAA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;AACzD;;;ACzCA,eAAsB,EAAS,GAAkB;CAC/C,IAAM,IAAS,EAAU,CAAO,GAC1B,IAAmB,CAAC,GAEpB,KAAc,MAAsB;EACxC,AAAI,KAAM,EAAS,KAAK,CAAI;CAC9B;CAEA,EAAO,KAAK,kCAAkC;CAC9C,IAAM,IAAS,EAAuB,EAAQ,IAAI;CAGlD,AAFA,EAAW,EAAoB,EAAO,UAAU,EAAO,OAAO,CAAC,GAE/D,EAAO,KAAK,qCAAqC;CACjD,IAAM,IAAiB,EAAK,KAC1B,EAAQ,MACR,OACA,UACA,gBACF;CAKA,AAJA,EACE,EAAoB,GAAgB,EAAuB,CAAc,CAAC,CAC5E,GAEA,EAAO,KAAK,8BAA8B;CAC1C,IAAM,IAAyB;EAC7B,EAAK,KAAK,EAAQ,MAAM,OAAO,UAAU,YAAY,oBAAoB;EACzE,EAAK,KAAK,EAAQ,MAAM,OAAO,UAAU,oBAAoB;EAC7D,EAAK,KAAK,EAAQ,MAAM,OAAO,UAAU,YAAY,gBAAgB;CACvE,GACM,IACJ,EAAuB,MAAM,MAAM,EAAG,WAAW,CAAC,CAAC,KACnD,EAAuB;CACzB,EACE,EACE,GACA,EAAuB,CAAgB,CACzC,CACF;CAGA,IAAM,IAAW,MAAM,EAAe,CAAO;CAE7C,OAAO;EACL,SAAS,IAAW,CAAC,CAAQ,IAAI,CAAC;EAClC;EACA,SAAS,CAAC;EACV,YAAY,CAAC;EACb,UAAU,CAAC;EACX,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAiB,CAAC;CACpB;AACF"}
1
+ {"version":3,"file":"generate.runtime-DM4o_QYY.js","names":["FAILURE_HINT","NOT_FOUND_HINT","NOT_FOUND_HINT","FAILURE_HINT","dedent","SvelteFile","ensureSiteFile","modifyConfig","fs","path","FAILURE_HINT$2","NOT_FOUND_HINT$2","ensureExtensionsSvx","existing","obj","SyntaxKind","init","arr","el","ensurePreprocessMdsvex","text","modifyViteConfigMdsvex","root","target","ensureImports","_templateObject","PRISM_IMPORT","NOT_FOUND_HINT$1","_taggedTemplateLiteral","FAILURE_HINT$1","modifyRootLayoutSvelte","layoutPath","file","script","appCssMatch","source","insertion","end","BLOG_NAVBAR_ITEM","FAILURE_HINT","NOT_FOUND_HINT","modifyPublicRootLayout","raw","generate","logger","getLogger","options","modifies","pushResult","mdsvex","modifyOutcomeToFile","rootLayoutPath","publicLayoutCandidates","publicLayoutPath","p","siteFile"],"sources":["../../src/patterns/enable/blog/modifies/vite-config.ts","../../src/patterns/enable/blog/modifies/root-layout-svelte.ts","../../src/patterns/enable/blog/modifies/public-root-layout-svelte.ts","../../src/patterns/enable/blog/generate.runtime.ts"],"sourcesContent":["import dedent from \"dedent\";\nimport {\n SyntaxKind,\n type ArrayLiteralExpression,\n type ObjectLiteralExpression,\n} from \"ts-morph\";\nimport {\n modifyConfig,\n type ConfigModifyResult,\n} from \"../../../../runtime/config-target\";\nimport { ensureImports } from \"../../../../runtime/ts-morph-helpers\";\n\nconst FAILURE_HINT = dedent`\n Enable mdsvex in your config (the sveltekit() arg in vite.config):\n\n import { mdsvex } from 'mdsvex';\n\n // ...\n extensions: ['.svelte', '.svx'],\n preprocess: [mdsvex()],\n`;\n\nconst NOT_FOUND_HINT = dedent`\n Enable mdsvex by passing config to the sveltekit() plugin in vite.config.ts:\n\n import { sveltekit } from '@sveltejs/kit/vite';\n import { mdsvex } from 'mdsvex';\n import { defineConfig } from 'vite';\n\n export default defineConfig({\n plugins: [\n sveltekit({\n extensions: ['.svelte', '.svx'],\n preprocess: [mdsvex()],\n }),\n ],\n });\n`;\n\nfunction ensureExtensionsSvx(obj: ObjectLiteralExpression): boolean {\n const existing = obj.getProperty(\"extensions\");\n if (!existing) {\n obj.addPropertyAssignment({\n name: \"extensions\",\n initializer: \"['.svelte', '.svx']\",\n });\n return true;\n }\n if (existing.getKind() !== SyntaxKind.PropertyAssignment) return false;\n const init = (\n existing as import(\"ts-morph\").PropertyAssignment\n ).getInitializer();\n if (!init || init.getKind() !== SyntaxKind.ArrayLiteralExpression) {\n (existing as import(\"ts-morph\").PropertyAssignment).setInitializer(\n \"['.svelte', '.svx']\",\n );\n return true;\n }\n const arr = init as ArrayLiteralExpression;\n const hasSvx = arr\n .getElements()\n .some((el) => el.getText().replace(/['\"`]/g, \"\") === \".svx\");\n if (hasSvx) return false;\n arr.addElement(\"'.svx'\");\n return true;\n}\n\nfunction ensurePreprocessMdsvex(obj: ObjectLiteralExpression): boolean {\n const existing = obj.getProperty(\"preprocess\");\n if (!existing) {\n obj.addPropertyAssignment({\n name: \"preprocess\",\n initializer: \"[mdsvex()]\",\n });\n return true;\n }\n if (existing.getKind() !== SyntaxKind.PropertyAssignment) return false;\n const init = (\n existing as import(\"ts-morph\").PropertyAssignment\n ).getInitializer();\n if (!init) {\n (existing as import(\"ts-morph\").PropertyAssignment).setInitializer(\n \"[mdsvex()]\",\n );\n return true;\n }\n if (init.getKind() === SyntaxKind.ArrayLiteralExpression) {\n const arr = init as ArrayLiteralExpression;\n const hasMdsvex = arr\n .getElements()\n .some((el) => /\\bmdsvex\\s*\\(/.test(el.getText()));\n if (hasMdsvex) return false;\n arr.addElement(\"mdsvex()\");\n return true;\n }\n const text = init.getText();\n if (/\\bmdsvex\\s*\\(/.test(text)) return false;\n (existing as import(\"ts-morph\").PropertyAssignment).setInitializer(\n `[${text}, mdsvex()]`,\n );\n return true;\n}\n\n/**\n * Enable mdsvex: ensure `extensions` includes `.svx`, `preprocess` includes\n * `mdsvex()`, and the `mdsvex` import is present, at the top level of the\n * inline sveltekit() arg in vite.config.\n */\nexport function modifyViteConfigMdsvex(root: string): ConfigModifyResult {\n return modifyConfig(\n root,\n { notFound: NOT_FOUND_HINT, failed: FAILURE_HINT },\n (target) => {\n ensureExtensionsSvx(target.configObject);\n ensurePreprocessMdsvex(target.configObject);\n ensureImports(target.sourceFile, [\n { namedImports: [\"mdsvex\"], moduleSpecifier: \"mdsvex\" },\n ]);\n return true;\n },\n );\n}\n","import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst PRISM_IMPORT = `import '../css/prism-vsc-dark-plus.css';`;\n\nconst NOT_FOUND_HINT = dedent`\n Create src/routes/+layout.svelte and import the Prism theme for\n code block highlighting in blog posts:\n\n <script lang=\"ts\">\n import '../app.css';\n ${PRISM_IMPORT}\n </script>\n`;\n\nconst FAILURE_HINT = dedent`\n Import the Prism theme in your root +layout.svelte for blog code\n block highlighting:\n\n ${PRISM_IMPORT}\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 const script = file.getScript();\n if (!script) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n if (script.content.includes(\"prism-vsc-dark-plus.css\")) {\n return { status: \"success\", changed: false };\n }\n\n file.modifyScript((source) => {\n const appCssMatch = source.match(\n /^(\\s*)import\\s+['\"][^'\"]*app\\.css['\"];?\\s*$/m,\n );\n if (appCssMatch) {\n const indent = appCssMatch[1] ?? \"\";\n const insertion = `\\n${indent}${PRISM_IMPORT}`;\n const end = (appCssMatch.index ?? 0) + appCssMatch[0].length;\n return source.slice(0, end) + insertion + source.slice(end);\n }\n return source.replace(/^/, `\\n\\t${PRISM_IMPORT}\\n`);\n });\n\n file.writeTo(layoutPath);\n return { status: \"success\", changed: file.hasChanged() };\n}\n","import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst BLOG_NAVBAR_ITEM = `\n\t\t<Navbar.Item>\n\t\t\t<Button class=\"w-full justify-start md:justify-center md:w-auto\" href=\"/blog\" variant=\"ghost\">\n\t\t\t\tBlog\n\t\t\t</Button>\n\t\t</Navbar.Item>\n\t`;\n\nconst FAILURE_HINT = dedent`\n Add a Blog link inside <Navbar.List> in the public root layout:\n\n <Navbar.Item>\n <Button class=\"w-full justify-start md:justify-center md:w-auto\" href=\"/blog\" variant=\"ghost\">\n Blog\n </Button>\n </Navbar.Item>\n`;\n\nconst NOT_FOUND_HINT = dedent`\n Create a public root layout with a Blog link in its Navbar.List:\n\n <Navbar.Item>\n <Button class=\"w-full justify-start md:justify-center md:w-auto\" href=\"/blog\" variant=\"ghost\">\n Blog\n </Button>\n </Navbar.Item>\n`;\n\nexport function modifyPublicRootLayout(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\n const raw = fs.readFileSync(layoutPath, \"utf8\");\n if (/href=[\"']\\/blog[\"']/.test(raw)) {\n return { status: \"success\", changed: false };\n }\n\n file.insertBeforeClosingTag(\"Navbar.List\", BLOG_NAVBAR_ITEM);\n file.writeTo(layoutPath);\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 { ensureSiteFile } from \"../../../runtime/site\";\nimport { modifyViteConfigMdsvex } from \"./modifies/vite-config\";\nimport { modifyRootLayoutSvelte } from \"./modifies/root-layout-svelte\";\nimport { modifyPublicRootLayout } from \"./modifies/public-root-layout-svelte\";\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const modifies: File[] = [];\n\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n logger.info(\"Modifying vite.config for mdsvex\");\n const mdsvex = modifyViteConfigMdsvex(options.root);\n pushResult(modifyOutcomeToFile(mdsvex.filePath, mdsvex.outcome));\n\n logger.info(\"Modifying src/routes/+layout.svelte\");\n const rootLayoutPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"+layout.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(rootLayoutPath, modifyRootLayoutSvelte(rootLayoutPath)),\n );\n\n logger.info(\"Modifying public root layout\");\n const publicLayoutCandidates = [\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 ];\n const publicLayoutPath =\n publicLayoutCandidates.find((p) => fs.existsSync(p)) ??\n publicLayoutCandidates[0];\n pushResult(\n modifyOutcomeToFile(\n publicLayoutPath,\n modifyPublicRootLayout(publicLayoutPath),\n ),\n );\n\n // The RSS feed is titled and linked from `src/lib/site.ts`.\n const siteFile = await ensureSiteFile(options);\n\n return {\n creates: siteFile ? [siteFile] : [],\n modifies,\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n } satisfies Result;\n}\n"],"mappings":";;;;;;;;;;;;AAYA,IAAMA,IAAe,CAAM;;;;;;;;GAUrBC,IAAiB,CAAM;;;;;;;;;;;;;;;;AAiB7B,SAASW,EAAoB,GAAuC;CAClE,IAAMC,IAAWC,EAAI,YAAY,YAAY;CAC7C,IAAI,CAACD,GAKH,OAJAC,EAAI,sBAAsB;EACxB,MAAM;EACN,aAAa;CACf,CAAC,GACM;CAET,IAAID,EAAS,QAAQ,MAAME,EAAW,oBAAoB,OAAO;CACjE,IAAMC,IACJH,EACA,eAAe;CACjB,IAAI,CAACG,KAAQA,EAAK,QAAQ,MAAMD,EAAW,wBAIzC,OAHAF,EAAoD,eAClD,qBACF,GACO;CAET,IAAMI,IAAMD;CAMZ,OAFA,CAHeC,EACZ,YAAY,CAAC,CACb,MAAM,MAAOC,EAAG,QAAQ,CAAC,CAAC,QAAQ,UAAU,EAAE,MAAM,MACnD,MACJD,EAAI,WAAW,QAAQ,GAChB;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