@velastack/patterns 0.11.0 → 0.13.0

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 (123) hide show
  1. package/README.md +21 -2
  2. package/dist/chunks/{collections-BYcVyY9O.js → collections-zEoRuILr.js} +2 -2
  3. package/dist/chunks/{collections-BYcVyY9O.js.map → collections-zEoRuILr.js.map} +1 -1
  4. package/dist/chunks/constants-CUv536Rj.js +87 -0
  5. package/dist/chunks/constants-CUv536Rj.js.map +1 -0
  6. package/dist/chunks/{currency.server-Dwz8LgvP.js → currency.server-DygAf6a1.js} +2 -2
  7. package/dist/chunks/{currency.server-Dwz8LgvP.js.map → currency.server-DygAf6a1.js.map} +1 -1
  8. package/dist/chunks/{env-vars-0hvKe55u.js → env-vars-XvAeH6u5.js} +3 -3
  9. package/dist/chunks/{env-vars-0hvKe55u.js.map → env-vars-XvAeH6u5.js.map} +1 -1
  10. package/dist/chunks/{generate-Df7t5Nbk.js → generate-BtWZCvuO.js} +3 -3
  11. package/dist/chunks/{generate-Df7t5Nbk.js.map → generate-BtWZCvuO.js.map} +1 -1
  12. package/dist/chunks/{generate-BOuNjssv.js → generate-Cbg-Z3sA.js} +2 -2
  13. package/dist/chunks/{generate-BOuNjssv.js.map → generate-Cbg-Z3sA.js.map} +1 -1
  14. package/dist/chunks/{generate-CNabcEBx.js → generate-Crdzw45a.js} +2 -2
  15. package/dist/chunks/{generate-CNabcEBx.js.map → generate-Crdzw45a.js.map} +1 -1
  16. package/dist/chunks/{generate-DoHn_xJZ.js → generate-DgZhFNjO.js} +22 -22
  17. package/dist/chunks/generate-DgZhFNjO.js.map +1 -0
  18. package/dist/chunks/{generate-l2JZTRKb.js → generate-DjuhSibA.js} +84 -84
  19. package/dist/chunks/generate-DjuhSibA.js.map +1 -0
  20. package/dist/chunks/{generate.runtime-DqLmhrsM.js → generate.runtime-2GD2E1NK.js} +6 -6
  21. package/dist/chunks/{generate.runtime-DqLmhrsM.js.map → generate.runtime-2GD2E1NK.js.map} +1 -1
  22. package/dist/chunks/{generate.runtime-T7JLE4Wc.js → generate.runtime-4TxcYKld.js} +3 -3
  23. package/dist/chunks/{generate.runtime-T7JLE4Wc.js.map → generate.runtime-4TxcYKld.js.map} +1 -1
  24. package/dist/chunks/{generate.runtime-BoYwV0nt.js → generate.runtime-7sU7RzIA.js} +2 -2
  25. package/dist/chunks/{generate.runtime-BoYwV0nt.js.map → generate.runtime-7sU7RzIA.js.map} +1 -1
  26. package/dist/chunks/{generate.runtime-q17D7QUT.js → generate.runtime-B-WOQsda.js} +3 -3
  27. package/dist/chunks/{generate.runtime-q17D7QUT.js.map → generate.runtime-B-WOQsda.js.map} +1 -1
  28. package/dist/chunks/{generate.runtime-DiqfbDfk.js → generate.runtime-B2DI0x05.js} +2 -2
  29. package/dist/chunks/{generate.runtime-DiqfbDfk.js.map → generate.runtime-B2DI0x05.js.map} +1 -1
  30. package/dist/chunks/{generate.runtime-Du84quuK.js → generate.runtime-B8y_l-6N.js} +5 -5
  31. package/dist/chunks/{generate.runtime-Du84quuK.js.map → generate.runtime-B8y_l-6N.js.map} +1 -1
  32. package/dist/chunks/{generate.runtime-BC6CBKh6.js → generate.runtime-BEvi6bml.js} +3 -3
  33. package/dist/chunks/{generate.runtime-BC6CBKh6.js.map → generate.runtime-BEvi6bml.js.map} +1 -1
  34. package/dist/chunks/{generate.runtime-DJ5uF6EN.js → generate.runtime-BO1KyRcJ.js} +2 -2
  35. package/dist/chunks/{generate.runtime-DJ5uF6EN.js.map → generate.runtime-BO1KyRcJ.js.map} +1 -1
  36. package/dist/chunks/{generate.runtime-BP31tAcD.js → generate.runtime-BPVZsAL0.js} +4 -4
  37. package/dist/chunks/{generate.runtime-BP31tAcD.js.map → generate.runtime-BPVZsAL0.js.map} +1 -1
  38. package/dist/chunks/{generate.runtime-CHUCMVa2.js → generate.runtime-BfM3dX_R.js} +2 -2
  39. package/dist/chunks/{generate.runtime-CHUCMVa2.js.map → generate.runtime-BfM3dX_R.js.map} +1 -1
  40. package/dist/chunks/{generate.runtime-DSs4gVRU.js → generate.runtime-BfQlxsWK.js} +7 -7
  41. package/dist/chunks/{generate.runtime-DSs4gVRU.js.map → generate.runtime-BfQlxsWK.js.map} +1 -1
  42. package/dist/chunks/{generate.runtime-zr6uIHCd.js → generate.runtime-BsjcGBme.js} +2 -2
  43. package/dist/chunks/{generate.runtime-zr6uIHCd.js.map → generate.runtime-BsjcGBme.js.map} +1 -1
  44. package/dist/chunks/{generate.runtime-D677SB4v.js → generate.runtime-ByC9kOl2.js} +2 -2
  45. package/dist/chunks/{generate.runtime-D677SB4v.js.map → generate.runtime-ByC9kOl2.js.map} +1 -1
  46. package/dist/chunks/{generate.runtime-bN61eWkc.js → generate.runtime-C2pIioyZ.js} +6 -6
  47. package/dist/chunks/{generate.runtime-bN61eWkc.js.map → generate.runtime-C2pIioyZ.js.map} +1 -1
  48. package/dist/chunks/{generate.runtime-BnqS_Zq8.js → generate.runtime-C4hyve9h.js} +3 -3
  49. package/dist/chunks/{generate.runtime-BnqS_Zq8.js.map → generate.runtime-C4hyve9h.js.map} +1 -1
  50. package/dist/chunks/{generate.runtime-BqCbJ-No.js → generate.runtime-C9yduilW.js} +3 -3
  51. package/dist/chunks/{generate.runtime-BqCbJ-No.js.map → generate.runtime-C9yduilW.js.map} +1 -1
  52. package/dist/chunks/{generate.runtime-CIvecd9c.js → generate.runtime-CEd3qCtW.js} +4 -4
  53. package/dist/chunks/{generate.runtime-CIvecd9c.js.map → generate.runtime-CEd3qCtW.js.map} +1 -1
  54. package/dist/chunks/{generate.runtime-C4LUUuq7.js → generate.runtime-CHaE6Mm9.js} +3 -3
  55. package/dist/chunks/{generate.runtime-C4LUUuq7.js.map → generate.runtime-CHaE6Mm9.js.map} +1 -1
  56. package/dist/chunks/{generate.runtime-nyJ6v56q.js → generate.runtime-CXGiQWDK.js} +4 -4
  57. package/dist/chunks/{generate.runtime-nyJ6v56q.js.map → generate.runtime-CXGiQWDK.js.map} +1 -1
  58. package/dist/chunks/{generate.runtime-Bvjj3zn0.js → generate.runtime-CvtSK0E1.js} +3 -3
  59. package/dist/chunks/{generate.runtime-Bvjj3zn0.js.map → generate.runtime-CvtSK0E1.js.map} +1 -1
  60. package/dist/chunks/{generate.runtime-DERcpgc-.js → generate.runtime-DGmpjkRe.js} +4 -4
  61. package/dist/chunks/{generate.runtime-DERcpgc-.js.map → generate.runtime-DGmpjkRe.js.map} +1 -1
  62. package/dist/chunks/{generate.runtime-e_BkDyP0.js → generate.runtime-DI73x08q.js} +2 -2
  63. package/dist/chunks/{generate.runtime-e_BkDyP0.js.map → generate.runtime-DI73x08q.js.map} +1 -1
  64. package/dist/chunks/{generate.runtime-B84ymwlD.js → generate.runtime-DIkM5xIB.js} +2 -2
  65. package/dist/chunks/{generate.runtime-B84ymwlD.js.map → generate.runtime-DIkM5xIB.js.map} +1 -1
  66. package/dist/chunks/{generate.runtime-DuDcKDUl.js → generate.runtime-DRZDjZqw.js} +2 -2
  67. package/dist/chunks/{generate.runtime-DuDcKDUl.js.map → generate.runtime-DRZDjZqw.js.map} +1 -1
  68. package/dist/chunks/{generate.runtime-ByPcr9vJ.js → generate.runtime-DVUj1LJK.js} +3 -3
  69. package/dist/chunks/{generate.runtime-ByPcr9vJ.js.map → generate.runtime-DVUj1LJK.js.map} +1 -1
  70. package/dist/chunks/{generate.runtime-Cv3unKap.js → generate.runtime-Deg1Tz9u.js} +3 -3
  71. package/dist/chunks/{generate.runtime-Cv3unKap.js.map → generate.runtime-Deg1Tz9u.js.map} +1 -1
  72. package/dist/chunks/generate.runtime-DqYYJXAz.js +24 -0
  73. package/dist/chunks/generate.runtime-DqYYJXAz.js.map +1 -0
  74. package/dist/chunks/{generate.runtime-oUJUQRdg.js → generate.runtime-Du8puIJQ.js} +6 -6
  75. package/dist/chunks/{generate.runtime-oUJUQRdg.js.map → generate.runtime-Du8puIJQ.js.map} +1 -1
  76. package/dist/chunks/{generate.runtime-WPq7bHRA.js → generate.runtime-DzCVGruq.js} +2 -2
  77. package/dist/chunks/{generate.runtime-WPq7bHRA.js.map → generate.runtime-DzCVGruq.js.map} +1 -1
  78. package/dist/chunks/generate.runtime-TKR-qAJM.js +50 -0
  79. package/dist/chunks/generate.runtime-TKR-qAJM.js.map +1 -0
  80. package/dist/chunks/{generate.runtime-C7tlPKH1.js → generate.runtime-USnFqTbU.js} +4 -4
  81. package/dist/chunks/{generate.runtime-C7tlPKH1.js.map → generate.runtime-USnFqTbU.js.map} +1 -1
  82. package/dist/chunks/{generate.runtime-rLlDp4R6.js → generate.runtime-UrLaWKvN.js} +4 -4
  83. package/dist/chunks/{generate.runtime-rLlDp4R6.js.map → generate.runtime-UrLaWKvN.js.map} +1 -1
  84. package/dist/chunks/{generate.runtime-Dfz53sSK.js → generate.runtime-bWGwyz2U.js} +3 -3
  85. package/dist/chunks/{generate.runtime-Dfz53sSK.js.map → generate.runtime-bWGwyz2U.js.map} +1 -1
  86. package/dist/chunks/{generate.runtime-gZ4wfYBP.js → generate.runtime-g6qaIY3k.js} +6 -6
  87. package/dist/chunks/{generate.runtime-gZ4wfYBP.js.map → generate.runtime-g6qaIY3k.js.map} +1 -1
  88. package/dist/chunks/{generate.runtime-Cj-5fzbQ.js → generate.runtime-s9ai7PxV.js} +4 -4
  89. package/dist/chunks/{generate.runtime-Cj-5fzbQ.js.map → generate.runtime-s9ai7PxV.js.map} +1 -1
  90. package/dist/chunks/{generate.runtime-CVWCUn52.js → generate.runtime-taYl9Tg5.js} +4 -4
  91. package/dist/chunks/{generate.runtime-CVWCUn52.js.map → generate.runtime-taYl9Tg5.js.map} +1 -1
  92. package/dist/chunks/layout.svelte-Cb12mxua.js +65 -0
  93. package/dist/chunks/layout.svelte-Cb12mxua.js.map +1 -0
  94. package/dist/chunks/{modify-file-B4uJzOEj.js → modify-file-D9U2LXEa.js} +2 -2
  95. package/dist/chunks/{modify-file-B4uJzOEj.js.map → modify-file-D9U2LXEa.js.map} +1 -1
  96. package/dist/chunks/{pocketbase-BtN-wL8f.js → pocketbase-BTR3gI8o.js} +2 -2
  97. package/dist/chunks/{pocketbase-BtN-wL8f.js.map → pocketbase-BTR3gI8o.js.map} +1 -1
  98. package/dist/chunks/{providers-DRwJnSzb.js → providers-CpRRQdMg.js} +2 -2
  99. package/dist/chunks/{providers-DRwJnSzb.js.map → providers-CpRRQdMg.js.map} +1 -1
  100. package/dist/chunks/{shared-BbxLil4g.js → shared-CAjLx_8Z.js} +2 -2
  101. package/dist/chunks/{shared-BbxLil4g.js.map → shared-CAjLx_8Z.js.map} +1 -1
  102. package/dist/chunks/{site-VrqOvuiU.js → site-D0IuWkAR.js} +2 -2
  103. package/dist/chunks/{site-VrqOvuiU.js.map → site-D0IuWkAR.js.map} +1 -1
  104. package/dist/chunks/table-core-BKBoEStB.js +127 -0
  105. package/dist/chunks/table-core-BKBoEStB.js.map +1 -0
  106. package/dist/chunks/{test-setup-BtV6Gk9I.js → test-setup-CbCXmPkE.js} +3 -3
  107. package/dist/chunks/{test-setup-BtV6Gk9I.js.map → test-setup-CbCXmPkE.js.map} +1 -1
  108. package/dist/chunks/{ui-gG8i_Mzk.js → ui-B3Db8cQg.js} +3 -3
  109. package/dist/chunks/{ui-gG8i_Mzk.js.map → ui-B3Db8cQg.js.map} +1 -1
  110. package/dist/chunks/{whatsapp-DbjOxHaZ.js → whatsapp-Pya8Zi07.js} +2 -2
  111. package/dist/chunks/{whatsapp-DbjOxHaZ.js.map → whatsapp-Pya8Zi07.js.map} +1 -1
  112. package/dist/chunks/{write-result-DcqMefuP.js → write-result-BWXq9RRn.js} +12 -12
  113. package/dist/chunks/{write-result-DcqMefuP.js.map → write-result-BWXq9RRn.js.map} +1 -1
  114. package/dist/index.d.ts +181 -17
  115. package/dist/index.js +2391 -2228
  116. package/dist/index.js.map +1 -1
  117. package/package.json +6 -3
  118. package/dist/chunks/constants-Bdx8mp7v.js +0 -6
  119. package/dist/chunks/constants-Bdx8mp7v.js.map +0 -1
  120. package/dist/chunks/generate-DoHn_xJZ.js.map +0 -1
  121. package/dist/chunks/generate-l2JZTRKb.js.map +0 -1
  122. package/dist/chunks/table-core-BHFT-uMX.js +0 -127
  123. package/dist/chunks/table-core-BHFT-uMX.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"generate.runtime-DJ5uF6EN.js","names":["FAILURE_HINT","NOT_FOUND_HINT","NOT_FOUND_HINT","FAILURE_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_","stripeCustomerHelper","InvalidArgumentError","stripe_customer_default","_layout_server_default","_layout_default","_page_default","nav_user_default","_page_server_default","app_sidebar_default","dispatch_default","withInMemoryScript","formatLikeSource","ensureImports","keepMissing","modifyOutcomeToFile","SvelteFile","modifyNavUser","fs","path","FAILURE_HINT$2","NOT_FOUND_HINT$5","SUBSCRIPTION_CASES_SNIPPET","modifyWebhookServer","filePath","original","addedCases","sf","switchStmt","SyntaxKind","stmt","clauses","defaultClause","c","prefix","last","source","LOAD_LINE","NOT_FOUND_HINT$4","failureHint","helper","helperFrom","clean","template","start","end","findLoad","varDecl","init","fn","modifyAppLayoutServer","Project","QuoteKind","load","body","block","binding","hasLocals","el","userIndex","s","d","statements","ret","returned","text","writer","FAILURE_HINT$1","NOT_FOUND_HINT$3","modifyAppLayoutSvelte","file","SUBSCRIPTION_TYPE","FAILURE_HINT","NOT_FOUND_HINT$2","updateScript","wasAdded","out","decl","nameNode","pattern","elements","typeNode","intersection","member","lit","propTexts","p","t","elementTexts","insertIdx","modifyAppSidebar","scriptChanged","src","templateChanged","modifyByTemplate","notFoundHint","current","idempotencyMarker","stripped","NOT_FOUND_HINT$1","modifyBillingPageServer","NOT_FOUND_HINT","modifyBillingPageSvelte","STRIPE_CUSTOMER_HELPER","BILLING_PAGE","assertPaymentsAppMode","root","previewRaw","content","relativePath","generate","logger","getLogger","options","modifies","pushResult","webhookServerPath","appLayoutServerPath","appLayoutSveltePath","appSidebarPath","navUserPath","billingPageServerPath","billingPageSveltePath"],"sources":["../../src/patterns/enable/subscriptions/modifies/modify-webhook-server.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-by-template.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 { Project, QuoteKind, SyntaxKind, type SourceFile } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport { formatLikeSource } from \"../../../../runtime/ts-morph-helpers\";\n\nconst LOAD_LINE =\n \"const subscription = await loadActiveSubscription(locals, user.id);\";\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\nconst failureHint = (helper: string) =>\n [\n \"Could not find the user and the returned object in the (app) layout load.\",\n \"Add the active subscription to it by hand:\",\n \"\",\n helper,\n \"\",\n \"// In load, once `user` is set:\",\n LOAD_LINE,\n \"// ...and return it with the rest:\",\n \"return { ..., subscription };\",\n ].join(\"\\n\");\n\n/**\n * The `loadActiveSubscription` helper, taken from the preview template so the\n * docs and what gets written stay the same.\n */\nfunction helperFrom(template: string): string {\n const clean = template.replace(\n /^[ \\t]*\\/\\/[ \\t]*\\[!code highlight:\\d+\\][ \\t]*\\r?\\n/gm,\n \"\",\n );\n const start = clean.indexOf(\"async function loadActiveSubscription\");\n const end = clean.indexOf(\"\\n}\\n\", start);\n if (start === -1 || end === -1) {\n throw new Error(\"No loadActiveSubscription in the layout template\");\n }\n return clean.slice(start, end + 2);\n}\n\nfunction findLoad(sf: SourceFile) {\n const varDecl = sf.getVariableDeclaration(\"load\");\n if (varDecl?.getVariableStatement()?.hasExportKeyword()) {\n const init = varDecl.getInitializer();\n const fn =\n varDecl.getInitializerIfKind(SyntaxKind.ArrowFunction) ??\n init?.getFirstDescendantByKind(SyntaxKind.ArrowFunction) ??\n init?.getFirstDescendantByKind(SyntaxKind.FunctionExpression);\n if (fn) return { fn, statement: varDecl.getVariableStatement()! };\n }\n const fn = sf.getFunction(\"load\");\n return fn?.isExported() ? { fn, statement: fn } : undefined;\n}\n\n/**\n * Adds the active subscription to the (app) layout's data: the\n * `loadActiveSubscription` helper, a call to it in `load`, and `subscription`\n * in what `load` returns. Edits the file rather than replacing it, so what\n * other patterns put in the load (teams' `team`/`teams`, say) stays.\n */\nexport function modifyAppLayoutServer(\n filePath: string,\n template: string,\n): ModifyOutcome {\n if (!fs.existsSync(filePath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n const original = fs.readFileSync(filePath, \"utf8\");\n if (original.includes(\"loadActiveSubscription\")) {\n return { status: \"success\", changed: false };\n }\n\n const helper = helperFrom(template);\n const project = new Project({\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n const sf = project.addSourceFileAtPath(filePath);\n const load = findLoad(sf);\n const body = load?.fn.getBody();\n if (!load || !body || body.getKind() !== SyntaxKind.Block) {\n return { status: \"failed\", message: failureHint(helper) };\n }\n const block = body.asKindOrThrow(SyntaxKind.Block);\n\n // The call needs `locals` and `user`, and goes before the return.\n const params = load.fn.getParameters();\n const binding = params[0]?.getNameNode();\n const hasLocals =\n binding?.getKind() === SyntaxKind.ObjectBindingPattern &&\n binding\n .asKindOrThrow(SyntaxKind.ObjectBindingPattern)\n .getElements()\n .some((el) => el.getName() === \"locals\");\n const userIndex = block.getStatements().findIndex(\n (s) =>\n s.getKind() === SyntaxKind.VariableStatement &&\n s\n .asKindOrThrow(SyntaxKind.VariableStatement)\n .getDeclarations()\n .some((d) => d.getName() === \"user\"),\n );\n const statements = block.getStatements();\n const ret = [...statements]\n .reverse()\n .find((s) => s.getKind() === SyntaxKind.ReturnStatement)\n ?.asKind(SyntaxKind.ReturnStatement);\n const returned = ret\n ?.getExpression()\n ?.asKind(SyntaxKind.ObjectLiteralExpression);\n if (!hasLocals || userIndex === -1 || !ret || !returned) {\n return { status: \"failed\", message: failureHint(helper) };\n }\n\n block.insertStatements(statements.indexOf(ret), LOAD_LINE);\n if (!returned.getProperty(\"subscription\")) {\n const text = returned.getText();\n if (text.includes(\"\\n\")) {\n returned.addShorthandPropertyAssignment({ name: \"subscription\" });\n } else {\n // Kept on one line, as written.\n returned.replaceWithText(text.replace(/\\s*\\}$/, \", subscription }\"));\n }\n }\n if (!load.fn.isAsync()) load.fn.setIsAsync(true);\n sf.insertStatements(sf.getStatements().indexOf(load.statement), (writer) =>\n writer.write(helper).blankLine(),\n );\n\n formatLikeSource(sf);\n sf.saveSync();\n return { status: \"success\", changed: sf.getFullText() !== original };\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 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 \"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 fs from \"node:fs\";\nimport path from \"node:path\";\nimport { InvalidArgumentError } from \"../../../core/errors\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport { keepMissing, 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\";\nimport stripeCustomerHelper from \"../payments/providers-app-mode/stripe/src/lib/server/stripe-customer.ts?raw\";\n\n// The billing page imports this payments helper, which apps that enabled\n// payments before it existed do not have yet.\nconst STRIPE_CUSTOMER_HELPER = \"src/lib/server/stripe-customer.ts\";\n\n// enable-payments writes the billing page (and the stripe_customers collection\n// subscriptions relate to) only when auth is already on.\nconst BILLING_PAGE = \"src/routes/(app)/billing/+page.server.ts\";\n\n/**\n * Refuses a project whose payments were enabled before auth. Every `requires`\n * flag passes there (auth and payments are both on), yet the billing page and\n * `stripe_customers` don't exist, so this runs before any collection is made.\n */\nexport function assertPaymentsAppMode(root: string): void {\n if (fs.existsSync(path.join(root, BILLING_PAGE))) return;\n throw new InvalidArgumentError(\n [\n \"Subscriptions need payments set up with auth on: they add plans to the billing page\",\n `(${BILLING_PAGE}) and link to the stripe_customers collection, which enable-payments`,\n \"creates only when auth is already enabled. This project enabled payments before auth.\",\n \"\",\n \"Re-enable payments now that auth is on: `vela disable payments`, then `vela enable payments`.\",\n \"disable-payments drops the catalog collections, which the sync workflow refills from Stripe.\",\n ].join(\"\\n\"),\n );\n}\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(modifyOutcomeToFile(navUserPath, modifyNavUser(navUserPath)));\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 const creates = keepMissing(\n [\n {\n path: STRIPE_CUSTOMER_HELPER,\n language: \"ts\",\n content: stripeCustomerHelper,\n status: \"success\",\n },\n ],\n options.root,\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,I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iBAAiB,CAAC;CACpB;AACF"}
1
+ {"version":3,"file":"generate.runtime-BO1KyRcJ.js","names":["FAILURE_HINT","NOT_FOUND_HINT","NOT_FOUND_HINT","FAILURE_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_","stripeCustomerHelper","InvalidArgumentError","stripe_customer_default","_layout_server_default","_layout_default","_page_default","nav_user_default","_page_server_default","app_sidebar_default","dispatch_default","withInMemoryScript","formatLikeSource","ensureImports","keepMissing","modifyOutcomeToFile","SvelteFile","modifyNavUser","fs","path","FAILURE_HINT$2","NOT_FOUND_HINT$5","SUBSCRIPTION_CASES_SNIPPET","modifyWebhookServer","filePath","original","addedCases","sf","switchStmt","SyntaxKind","stmt","clauses","defaultClause","c","prefix","last","source","LOAD_LINE","NOT_FOUND_HINT$4","failureHint","helper","helperFrom","clean","template","start","end","findLoad","varDecl","init","fn","modifyAppLayoutServer","Project","QuoteKind","load","body","block","binding","hasLocals","el","userIndex","s","d","statements","ret","returned","text","writer","FAILURE_HINT$1","NOT_FOUND_HINT$3","modifyAppLayoutSvelte","file","SUBSCRIPTION_TYPE","FAILURE_HINT","NOT_FOUND_HINT$2","updateScript","wasAdded","out","decl","nameNode","pattern","elements","typeNode","intersection","member","lit","propTexts","p","t","elementTexts","insertIdx","modifyAppSidebar","scriptChanged","src","templateChanged","modifyByTemplate","notFoundHint","current","idempotencyMarker","stripped","NOT_FOUND_HINT$1","modifyBillingPageServer","NOT_FOUND_HINT","modifyBillingPageSvelte","STRIPE_CUSTOMER_HELPER","BILLING_PAGE","assertPaymentsAppMode","root","previewRaw","content","relativePath","generate","logger","getLogger","options","modifies","pushResult","webhookServerPath","appLayoutServerPath","appLayoutSveltePath","appSidebarPath","navUserPath","billingPageServerPath","billingPageSveltePath"],"sources":["../../src/patterns/enable/subscriptions/modifies/modify-webhook-server.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-by-template.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 { Project, QuoteKind, SyntaxKind, type SourceFile } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport { formatLikeSource } from \"../../../../runtime/ts-morph-helpers\";\n\nconst LOAD_LINE =\n \"const subscription = await loadActiveSubscription(locals, user.id);\";\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\nconst failureHint = (helper: string) =>\n [\n \"Could not find the user and the returned object in the (app) layout load.\",\n \"Add the active subscription to it by hand:\",\n \"\",\n helper,\n \"\",\n \"// In load, once `user` is set:\",\n LOAD_LINE,\n \"// ...and return it with the rest:\",\n \"return { ..., subscription };\",\n ].join(\"\\n\");\n\n/**\n * The `loadActiveSubscription` helper, taken from the preview template so the\n * docs and what gets written stay the same.\n */\nfunction helperFrom(template: string): string {\n const clean = template.replace(\n /^[ \\t]*\\/\\/[ \\t]*\\[!code highlight:\\d+\\][ \\t]*\\r?\\n/gm,\n \"\",\n );\n const start = clean.indexOf(\"async function loadActiveSubscription\");\n const end = clean.indexOf(\"\\n}\\n\", start);\n if (start === -1 || end === -1) {\n throw new Error(\"No loadActiveSubscription in the layout template\");\n }\n return clean.slice(start, end + 2);\n}\n\nfunction findLoad(sf: SourceFile) {\n const varDecl = sf.getVariableDeclaration(\"load\");\n if (varDecl?.getVariableStatement()?.hasExportKeyword()) {\n const init = varDecl.getInitializer();\n const fn =\n varDecl.getInitializerIfKind(SyntaxKind.ArrowFunction) ??\n init?.getFirstDescendantByKind(SyntaxKind.ArrowFunction) ??\n init?.getFirstDescendantByKind(SyntaxKind.FunctionExpression);\n if (fn) return { fn, statement: varDecl.getVariableStatement()! };\n }\n const fn = sf.getFunction(\"load\");\n return fn?.isExported() ? { fn, statement: fn } : undefined;\n}\n\n/**\n * Adds the active subscription to the (app) layout's data: the\n * `loadActiveSubscription` helper, a call to it in `load`, and `subscription`\n * in what `load` returns. Edits the file rather than replacing it, so what\n * other patterns put in the load (teams' `team`/`teams`, say) stays.\n */\nexport function modifyAppLayoutServer(\n filePath: string,\n template: string,\n): ModifyOutcome {\n if (!fs.existsSync(filePath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n const original = fs.readFileSync(filePath, \"utf8\");\n if (original.includes(\"loadActiveSubscription\")) {\n return { status: \"success\", changed: false };\n }\n\n const helper = helperFrom(template);\n const project = new Project({\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n const sf = project.addSourceFileAtPath(filePath);\n const load = findLoad(sf);\n const body = load?.fn.getBody();\n if (!load || !body || body.getKind() !== SyntaxKind.Block) {\n return { status: \"failed\", message: failureHint(helper) };\n }\n const block = body.asKindOrThrow(SyntaxKind.Block);\n\n // The call needs `locals` and `user`, and goes before the return.\n const params = load.fn.getParameters();\n const binding = params[0]?.getNameNode();\n const hasLocals =\n binding?.getKind() === SyntaxKind.ObjectBindingPattern &&\n binding\n .asKindOrThrow(SyntaxKind.ObjectBindingPattern)\n .getElements()\n .some((el) => el.getName() === \"locals\");\n const userIndex = block.getStatements().findIndex(\n (s) =>\n s.getKind() === SyntaxKind.VariableStatement &&\n s\n .asKindOrThrow(SyntaxKind.VariableStatement)\n .getDeclarations()\n .some((d) => d.getName() === \"user\"),\n );\n const statements = block.getStatements();\n const ret = [...statements]\n .reverse()\n .find((s) => s.getKind() === SyntaxKind.ReturnStatement)\n ?.asKind(SyntaxKind.ReturnStatement);\n const returned = ret\n ?.getExpression()\n ?.asKind(SyntaxKind.ObjectLiteralExpression);\n if (!hasLocals || userIndex === -1 || !ret || !returned) {\n return { status: \"failed\", message: failureHint(helper) };\n }\n\n block.insertStatements(statements.indexOf(ret), LOAD_LINE);\n if (!returned.getProperty(\"subscription\")) {\n const text = returned.getText();\n if (text.includes(\"\\n\")) {\n returned.addShorthandPropertyAssignment({ name: \"subscription\" });\n } else {\n // Kept on one line, as written.\n returned.replaceWithText(text.replace(/\\s*\\}$/, \", subscription }\"));\n }\n }\n if (!load.fn.isAsync()) load.fn.setIsAsync(true);\n sf.insertStatements(sf.getStatements().indexOf(load.statement), (writer) =>\n writer.write(helper).blankLine(),\n );\n\n formatLikeSource(sf);\n sf.saveSync();\n return { status: \"success\", changed: sf.getFullText() !== original };\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 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 \"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 fs from \"node:fs\";\nimport path from \"node:path\";\nimport { InvalidArgumentError } from \"../../../core/errors\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport { keepMissing, 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\";\nimport stripeCustomerHelper from \"../payments/providers-app-mode/stripe/src/lib/server/stripe-customer.ts?raw\";\n\n// The billing page imports this payments helper, which apps that enabled\n// payments before it existed do not have yet.\nconst STRIPE_CUSTOMER_HELPER = \"src/lib/server/stripe-customer.ts\";\n\n// enable-payments writes the billing page (and the stripe_customers collection\n// subscriptions relate to) only when auth is already on.\nconst BILLING_PAGE = \"src/routes/(app)/billing/+page.server.ts\";\n\n/**\n * Refuses a project whose payments were enabled before auth. Every `requires`\n * flag passes there (auth and payments are both on), yet the billing page and\n * `stripe_customers` don't exist, so this runs before any collection is made.\n */\nexport function assertPaymentsAppMode(root: string): void {\n if (fs.existsSync(path.join(root, BILLING_PAGE))) return;\n throw new InvalidArgumentError(\n [\n \"Subscriptions need payments set up with auth on: they add plans to the billing page\",\n `(${BILLING_PAGE}) and link to the stripe_customers collection, which enable-payments`,\n \"creates only when auth is already enabled. This project enabled payments before auth.\",\n \"\",\n \"Re-enable payments now that auth is on: `vela disable payments`, then `vela enable payments`.\",\n \"disable-payments drops the catalog collections, which the sync workflow refills from Stripe.\",\n ].join(\"\\n\"),\n );\n}\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(modifyOutcomeToFile(navUserPath, modifyNavUser(navUserPath)));\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 const creates = keepMissing(\n [\n {\n path: STRIPE_CUSTOMER_HELPER,\n language: \"ts\",\n content: stripeCustomerHelper,\n status: \"success\",\n },\n ],\n options.root,\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,0GAEIkC,IAA6B,CAAM;;;;;;;;;;;;;AAczC,SAAgBC,EAAoB,GAAiC;CACnE,IA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,GACA1E,EAAS,oCAAoC,CAC/C,CACF,CACF,GAEAoE,EAAO,KAAK,gCAAgC;CAC5C,IAAMO,IAAsBnG,EAAK,KAC/B8F,EAAQ,MACR,OACA,UACA,SACA,gBACF;CAQA,AAPAE,EACEpG,EACEuG,GACAjD,EAAsBiD,CAAmB,CAC3C,CACF,GAEAP,EAAO,KAAK,8BAA8B;CAC1C,IAAMQ,IAAiBpG,EAAK,KAC1B8F,EAAQ,MACR,OACA,OACA,cACA,oBACF;CAKA,AAJAE,EACEpG,EAAoBwG,GAAgB7B,EAAiB6B,CAAc,CAAC,CACtE,GAEAR,EAAO,KAAK,2BAA2B;CACvC,IAAMS,IAAcrG,EAAK,KACvB8F,EAAQ,MACR,OACA,OACA,cACA,iBACF;CAGA,AAFAE,EAAWpG,EAAoByG,GAAavG,EAAcuG,CAAW,CAAC,CAAC,GAEvET,EAAO,KAAK,mCAAmC;CAC/C,IAAMU,IAAwBtG,EAAK,KACjC8F,EAAQ,MACR,OACA,UACA,SACA,WACA,iBACF;CAWA,AAVAE,EACEpG,EACE0G,GACArB,EACEqB,GACA9E,EAAS,0CAA0C,CACrD,CACF,CACF,GAEAoE,EAAO,KAAK,gCAAgC;CAC5C,IAAMW,IAAwBvG,EAAK,KACjC8F,EAAQ,MACR,OACA,UACA,SACA,WACA,cACF;CAuBA,OAtBAE,EACEpG,EACE2G,GACApB,EACEoB,GACA/E,EAAS,uCAAuC,CAClD,CACF,CACF,GAcO;EACL,SAbc7B,EACd,CACE;GACE,MAAMyF;GACN,UAAU;GACV,SAAStG;GACT,QAAQ;EACV,CACF,GACAgH,EAAQ,IAIR;EACA;EACA,SAAS,CAAC;EACV,YAAY,CAAC;EACb,UAAU,CAAC;EACX,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAiB,CAAC;CACpB;AACF"}
@@ -1,7 +1,7 @@
1
1
  import { n as e } from "./logger-CQONztPm.js";
2
- import { i as t, n, t as r } from "./pocketbase-BtN-wL8f.js";
3
- import { r as i } from "./modify-file-B4uJzOEj.js";
4
- import { a, i as o, o as s, r as c, t as l } from "./whatsapp-DbjOxHaZ.js";
2
+ import { i as t, n, t as r } from "./pocketbase-BTR3gI8o.js";
3
+ import { r as i } from "./modify-file-D9U2LXEa.js";
4
+ import { a, i as o, o as s, r as c, t as l } from "./whatsapp-Pya8Zi07.js";
5
5
  import { swapAuthPages as u } from "./auth-pages-jsyDV1GR.js";
6
6
  import d from "node:fs";
7
7
  import f from "node:path";
@@ -65,4 +65,4 @@ async function g(d) {
65
65
  //#endregion
66
66
  export { g as generate };
67
67
 
68
- //# sourceMappingURL=generate.runtime-BP31tAcD.js.map
68
+ //# sourceMappingURL=generate.runtime-BPVZsAL0.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"generate.runtime-BP31tAcD.js","names":["getLogger","withPocketbase","getMigrationFile","modifyOutcomeToFile","hasWhatsAppPlugin","writeWhatsAppConfigMigration","enableWhatsAppAuth","MIN_POCKETBASE_SERVER","fs","path","modifyTestSetup","setupPath","original","content","indent","head","tail","bodyIndent","value","fieldIndent","DOCS_URL","migrationCreate","file","generate","logger","options","creates","pb","setupWhatsAppFields","migrationDelay","configMigration","modifies","outcomes","swapAuthPages","filePath","outcome","testSetup","testSetupFile"],"sources":["../../src/patterns/enable/whatsapp/modifies/modify-test-setup.ts","../../src/patterns/enable/whatsapp/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\n/**\n * `email` turns optional on `users`, which the generated types follow, so a\n * test setup from before enable-backend handled that no longer type-checks:\n * its `authenticateUser` takes `{ email: string }` and it signs the test\n * user in with `context.user.email`. Brings those two spots up to the\n * current setup; anything else in the file is the project's own.\n */\nexport function modifyTestSetup(setupPath: string): ModifyOutcome {\n if (!fs.existsSync(setupPath)) {\n return { status: \"success\", changed: false };\n }\n\n const original = fs.readFileSync(setupPath, \"utf8\");\n let content = original;\n\n content = content.replace(\n /^([ \\t]*)(async function authenticateUser\\(agent: Agent, user: \\{ )email: string( \\}\\) \\{\\n)([ \\t]*)/m,\n (_, indent, head, tail, bodyIndent) =>\n `${indent}${head}email?: string${tail}` +\n `${bodyIndent}// Logs in with the password, so it needs the email (made optional by\\n` +\n `${bodyIndent}// enable-whatsapp, for accounts that sign in with a phone number).\\n` +\n `${bodyIndent}if (!user.email) {\\n` +\n `${bodyIndent}${bodyIndent.includes(\"\\t\") ? \"\\t\" : \" \"}throw new Error('authenticateUser needs a user with an email');\\n` +\n `${bodyIndent}}\\n` +\n bodyIndent,\n );\n\n // The user is made with a known email: sign in with that.\n content = content.replace(\n /^([ \\t]*)context\\.user = await context\\.admin\\.collection\\('users'\\)\\.create\\(\\{\\n([ \\t]*)email: (`test-\\$\\{Math\\.random\\(\\)\\.toString\\(36\\)\\.slice\\(2\\)\\}@example\\.com`),/m,\n (_, indent, fieldIndent, value) =>\n `${indent}const email = ${value};\\n` +\n `${indent}context.user = await context.admin.collection('users').create({\\n` +\n `${fieldIndent}email,`,\n );\n if (content.includes(\"const email = `test-\")) {\n content = content.replace(\n \".authWithPassword(context.user.email, testUserPassword)\",\n \".authWithPassword(email, testUserPassword)\",\n );\n }\n\n if (content === original) {\n return { status: \"success\", changed: false };\n }\n fs.writeFileSync(setupPath, content, \"utf8\");\n return { status: \"success\", changed: true };\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport {\n getMigrationFile,\n migrationDelay,\n withPocketbase,\n} from \"../../../runtime/pocketbase\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport {\n MIN_POCKETBASE_SERVER,\n enableWhatsAppAuth,\n hasWhatsAppPlugin,\n setupWhatsAppFields,\n writeWhatsAppConfigMigration,\n} from \"./runtime/whatsapp\";\nimport { swapAuthPages } from \"./modifies/auth-pages\";\nimport { modifyTestSetup } from \"./modifies/modify-test-setup\";\n\nexport const DOCS_URL = \"https://velastack.dev/docs/enable/whatsapp\";\n\nfunction migrationCreate(file: string): File {\n return {\n path: file,\n language: \"js\",\n content: fs.readFileSync(file, \"utf8\"),\n status: \"success\",\n };\n}\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const creates: File[] = [];\n\n await withPocketbase(options.root, async (pb) => {\n if (!(await hasWhatsAppPlugin(pb))) {\n throw new Error(\n `This PocketBase has no WhatsApp sign-in. It comes with pocketbase-server ${MIN_POCKETBASE_SERVER} and later: run \\`npm install -D pocketbase-server@^${MIN_POCKETBASE_SERVER}\\`, then \\`vela enable whatsapp\\` again.`,\n );\n }\n\n logger.info(\"Adding the phone fields to users and making email optional\");\n if (await setupWhatsAppFields(pb)) {\n await migrationDelay();\n const file = getMigrationFile(\"users\", \"updated\", options);\n if (file) creates.push(migrationCreate(file));\n }\n\n logger.info(\"Turning on WhatsApp sign-in for users\");\n await enableWhatsAppAuth(pb);\n await migrationDelay();\n const configMigration = writeWhatsAppConfigMigration(options, true);\n if (configMigration) creates.push(migrationCreate(configMigration));\n });\n\n logger.info(\"Adding WhatsApp to the login and signup pages\");\n const modifies: File[] = [];\n const outcomes = await swapAuthPages(\n options.root,\n \"enable\",\n (filePath) =>\n `${path.relative(options.root, filePath)} is not the page enable-auth wrote, so it was left as it is. Add the WhatsApp option to it by hand: ${DOCS_URL}`,\n );\n for (const [filePath, outcome] of outcomes) {\n const file = modifyOutcomeToFile(filePath, outcome);\n if (file) modifies.push(file);\n }\n\n logger.info(\"Updating test/setup.ts for an optional email\");\n const testSetup = path.join(options.root, \"test\", \"setup.ts\");\n const testSetupFile = modifyOutcomeToFile(\n testSetup,\n modifyTestSetup(testSetup),\n );\n if (testSetupFile) modifies.push(testSetupFile);\n\n return {\n creates,\n modifies,\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n } satisfies Result;\n}\n"],"mappings":";;;;;;;;AAUA,SAAgBU,EAAgB,GAAkC;CAChE,IAAI,CAACF,EAAG,WAAWG,CA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C;EAC9C;EAIA,AAFAE,EAAO,KAAK,uCAAuC,GACnD,MAAMlB,EAAmBqB,CAAE,GAC3B,MAAME,EAAe;EACrB,IAAMC,IAAkBzB,EAA6BoB,GAAS,EAAI;EAClE,AAAIK,KAAiBJ,EAAQ,KAAKL,EAAgBS,CAAe,CAAC;CACpE,CAAC,GAEDN,EAAO,KAAK,+CAA+C;CAC3D,IAAMO,IAAmB,CAAC,GACpBC,IAAW,MAAMC,EACrBR,EAAQ,MACR,WACC,MACC,GAAGhB,EAAK,SAASgB,EAAQ,MAAMS,CAAQ,EAAE,sGAAsGd,GACnJ;CACA,KAAK,IAAM,CAACc,GAAUC,MAAYH,GAAU;EAC1C,IAAMV,IAAOnB,EAAoB+B,GAAUC,CAAO;EAClD,AAAIb,KAAMS,EAAS,KAAKT,CAAI;CAC9B;CAEA,EAAO,KAAK,8CAA8C;CAC1D,IAAMc,IAAY3B,EAAK,KAAKgB,EAAQ,MAAM,QAAQ,UAAU,GACtDY,IAAgBlC,EACpBiC,GACA1B,EAAgB0B,CAAS,CAC3B;CAGA,OAFIC,KAAeN,EAAS,KAAKM,CAAa,GAEvC;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-BPVZsAL0.js","names":["getLogger","withPocketbase","getMigrationFile","modifyOutcomeToFile","hasWhatsAppPlugin","writeWhatsAppConfigMigration","enableWhatsAppAuth","MIN_POCKETBASE_SERVER","fs","path","modifyTestSetup","setupPath","original","content","indent","head","tail","bodyIndent","value","fieldIndent","DOCS_URL","migrationCreate","file","generate","logger","options","creates","pb","setupWhatsAppFields","migrationDelay","configMigration","modifies","outcomes","swapAuthPages","filePath","outcome","testSetup","testSetupFile"],"sources":["../../src/patterns/enable/whatsapp/modifies/modify-test-setup.ts","../../src/patterns/enable/whatsapp/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\n/**\n * `email` turns optional on `users`, which the generated types follow, so a\n * test setup from before enable-backend handled that no longer type-checks:\n * its `authenticateUser` takes `{ email: string }` and it signs the test\n * user in with `context.user.email`. Brings those two spots up to the\n * current setup; anything else in the file is the project's own.\n */\nexport function modifyTestSetup(setupPath: string): ModifyOutcome {\n if (!fs.existsSync(setupPath)) {\n return { status: \"success\", changed: false };\n }\n\n const original = fs.readFileSync(setupPath, \"utf8\");\n let content = original;\n\n content = content.replace(\n /^([ \\t]*)(async function authenticateUser\\(agent: Agent, user: \\{ )email: string( \\}\\) \\{\\n)([ \\t]*)/m,\n (_, indent, head, tail, bodyIndent) =>\n `${indent}${head}email?: string${tail}` +\n `${bodyIndent}// Logs in with the password, so it needs the email (made optional by\\n` +\n `${bodyIndent}// enable-whatsapp, for accounts that sign in with a phone number).\\n` +\n `${bodyIndent}if (!user.email) {\\n` +\n `${bodyIndent}${bodyIndent.includes(\"\\t\") ? \"\\t\" : \" \"}throw new Error('authenticateUser needs a user with an email');\\n` +\n `${bodyIndent}}\\n` +\n bodyIndent,\n );\n\n // The user is made with a known email: sign in with that.\n content = content.replace(\n /^([ \\t]*)context\\.user = await context\\.admin\\.collection\\('users'\\)\\.create\\(\\{\\n([ \\t]*)email: (`test-\\$\\{Math\\.random\\(\\)\\.toString\\(36\\)\\.slice\\(2\\)\\}@example\\.com`),/m,\n (_, indent, fieldIndent, value) =>\n `${indent}const email = ${value};\\n` +\n `${indent}context.user = await context.admin.collection('users').create({\\n` +\n `${fieldIndent}email,`,\n );\n if (content.includes(\"const email = `test-\")) {\n content = content.replace(\n \".authWithPassword(context.user.email, testUserPassword)\",\n \".authWithPassword(email, testUserPassword)\",\n );\n }\n\n if (content === original) {\n return { status: \"success\", changed: false };\n }\n fs.writeFileSync(setupPath, content, \"utf8\");\n return { status: \"success\", changed: true };\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport {\n getMigrationFile,\n migrationDelay,\n withPocketbase,\n} from \"../../../runtime/pocketbase\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport {\n MIN_POCKETBASE_SERVER,\n enableWhatsAppAuth,\n hasWhatsAppPlugin,\n setupWhatsAppFields,\n writeWhatsAppConfigMigration,\n} from \"./runtime/whatsapp\";\nimport { swapAuthPages } from \"./modifies/auth-pages\";\nimport { modifyTestSetup } from \"./modifies/modify-test-setup\";\n\nexport const DOCS_URL = \"https://velastack.dev/docs/enable/whatsapp\";\n\nfunction migrationCreate(file: string): File {\n return {\n path: file,\n language: \"js\",\n content: fs.readFileSync(file, \"utf8\"),\n status: \"success\",\n };\n}\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const creates: File[] = [];\n\n await withPocketbase(options.root, async (pb) => {\n if (!(await hasWhatsAppPlugin(pb))) {\n throw new Error(\n `This PocketBase has no WhatsApp sign-in. It comes with pocketbase-server ${MIN_POCKETBASE_SERVER} and later: run \\`npm install -D pocketbase-server@^${MIN_POCKETBASE_SERVER}\\`, then \\`vela enable whatsapp\\` again.`,\n );\n }\n\n logger.info(\"Adding the phone fields to users and making email optional\");\n if (await setupWhatsAppFields(pb)) {\n await migrationDelay();\n const file = getMigrationFile(\"users\", \"updated\", options);\n if (file) creates.push(migrationCreate(file));\n }\n\n logger.info(\"Turning on WhatsApp sign-in for users\");\n await enableWhatsAppAuth(pb);\n await migrationDelay();\n const configMigration = writeWhatsAppConfigMigration(options, true);\n if (configMigration) creates.push(migrationCreate(configMigration));\n });\n\n logger.info(\"Adding WhatsApp to the login and signup pages\");\n const modifies: File[] = [];\n const outcomes = await swapAuthPages(\n options.root,\n \"enable\",\n (filePath) =>\n `${path.relative(options.root, filePath)} is not the page enable-auth wrote, so it was left as it is. Add the WhatsApp option to it by hand: ${DOCS_URL}`,\n );\n for (const [filePath, outcome] of outcomes) {\n const file = modifyOutcomeToFile(filePath, outcome);\n if (file) modifies.push(file);\n }\n\n logger.info(\"Updating test/setup.ts for an optional email\");\n const testSetup = path.join(options.root, \"test\", \"setup.ts\");\n const testSetupFile = modifyOutcomeToFile(\n testSetup,\n modifyTestSetup(testSetup),\n );\n if (testSetupFile) modifies.push(testSetupFile);\n\n return {\n creates,\n modifies,\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n } satisfies Result;\n}\n"],"mappings":";;;;;;;;AAUA,SAAgBU,EAAgB,GAAkC;CAChE,IAAI,CAACF,EAAG,WAAWG,CAAS,GAC1B,OAAO;EAAE,QAAQ;EAAW,SAAS;CAAM;CAG7C,IAAMC,IAAWJ,EAAG,aAAaG,GAAW,MAAM,GAC9CE,IAAUD;CAiCd,OA/BA,IAAUC,EAAQ,QAChB,0GACC,GAAG,GAAQ,GAAM,GAAM,MACtB,GAAGC,IAASC,EAAK,gBAAgBC,IAC9BC,EAAW,yEACXA,EAAW,uEACXA,EAAW,sBACXA,IAAaA,EAAW,SAAS,GAAI,IAAI,MAAO,KAAK,mEACrDA,EAAW,OACdA,CACJ,GAGA,IAAUJ,EAAQ,QAChB,gLACC,GAAG,GAAQ,GAAa,MACvB,GAAGC,EAAO,gBAAgBI,EAAM,KAC7BJ,EAAO,mEACPK,EAAY,OACnB,GACIN,EAAQ,SAAS,sBAAsB,MACzC,IAAUA,EAAQ,QAChB,2DACA,4CACF,IAGEA,MAAYD,IACP;EAAE,QAAQ;EAAW,SAAS;CAAM,KAE7CJ,EAAG,cAAcG,GAAWE,GAAS,MAAM,GACpC;EAAE,QAAQ;EAAW,SAAS;CAAK;AAC5C;;;AC9BA,IAAaO,IAAW;AAExB,SAASC,EAAgB,GAAoB;CAC3C,OAAO;EACL,MAAMC;EACN,UAAU;EACV,SAASd,EAAG,aAAac,GAAM,MAAM;EACrC,QAAQ;CACV;AACF;AAEA,eAAsBC,EAAS,GAAkB;CAC/C,IAAMC,IAASxB,EAA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@
1
1
  import { r as e } from "./lib-specifier-Cngo1zF_.js";
2
2
  import { n as t } from "./logger-CQONztPm.js";
3
3
  import { _ as n, n as r, u as i } from "./ts-morph-helpers-CHI9wAil.js";
4
- import { r as a } from "./modify-file-B4uJzOEj.js";
4
+ import { r as a } from "./modify-file-D9U2LXEa.js";
5
5
  import { t as o } from "./svelte-file-Dv5-bl79.js";
6
6
  import s from "node:fs";
7
7
  import c from "node:path";
@@ -45,4 +45,4 @@ async function u(e) {
45
45
  //#endregion
46
46
  export { u as generate };
47
47
 
48
- //# sourceMappingURL=generate.runtime-CHUCMVa2.js.map
48
+ //# sourceMappingURL=generate.runtime-BfM3dX_R.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"generate.runtime-CHUCMVa2.js","names":["libModule","getLogger","withInMemoryScript","ensureBlankLineAfterImports","removeImportByModuleSpecifier","modifyOutcomeToFile","SvelteFile","fs","path","unmodifyRootLayoutSvelte","layoutPath","file","out","content","sf","generate","logger","options","modifies"],"sources":["../../src/patterns/disable/ecommerce/modifies/root-layout.svelte.ts","../../src/patterns/disable/ecommerce/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\n/** Takes out the navbar item enable-ecommerce added, and its import. */\nexport function unmodifyRootLayoutSvelte(layoutPath: string): ModifyOutcome {\n if (!fs.existsSync(layoutPath)) {\n return { status: \"success\", changed: false };\n }\n\n const file = SvelteFile.fromPath(layoutPath);\n if (!file.hasElement(\"CartButton\")) {\n return { status: \"success\", changed: false };\n }\n\n if (!file.removeElementContaining(\"Navbar.Item\", \"CartButton\")) {\n file.removeElement(\"CartButton\");\n }\n file.modifyScript((content) => {\n const { source: out } = withInMemoryScript(content, (sf) => {\n removeImportByModuleSpecifier(\n sf,\n libModule(\"components/cart/cart-button.svelte\"),\n );\n ensureBlankLineAfterImports(sf);\n });\n return out;\n });\n\n file.writeTo(layoutPath);\n return { status: \"success\", changed: file.hasChanged() };\n}\n","import path from \"node:path\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { unmodifyRootLayoutSvelte } from \"./modifies/root-layout.svelte\";\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const modifies: File[] = [];\n\n logger.info(\"Taking the cart out of the navbar\");\n const layoutPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(public)\",\n \"root-layout.svelte\",\n );\n const file = modifyOutcomeToFile(\n layoutPath,\n unmodifyRootLayoutSvelte(layoutPath),\n );\n if (file) modifies.push(file);\n\n return {\n creates: [],\n modifies,\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n } satisfies Result;\n}\n"],"mappings":";;;;;;;;AAWA,SAAgBS,EAAyB,GAAmC;CAC1E,IAAI,CAACF,EAAG,WAAWG,CAAU,GAC3B,OAAO;EAAE,QAAQ;EAAW,SAAS;CAAM;CAG7C,IAAMC,IAAOL,EAAW,SAASI,CAAU;CAoB3C,OAnBKC,EAAK,WAAW,YAAY,KAI5BA,EAAK,wBAAwB,eAAe,YAAY,KAC3DA,EAAK,cAAc,YAAY,GAEjCA,EAAK,cAAc,MAAY;EAC7B,IAAM,EAAE,QAAQC,MAAQV,EAAmBW,IAAU,MAAO;GAK1D,AAJAT,EACEU,GACAd,EAAU,oCAAoC,CAChD,GACAG,EAA4BW,CAAE;EAChC,CAAC;EACD,OAAOF;CACT,CAAC,GAEDD,EAAK,QAAQD,CAAU,GAChB;EAAE,QAAQ;EAAW,SAASC,EAAK,WAAW;CAAE,KAlB9C;EAAE,QAAQ;EAAW,SAAS;CAAM;AAmB/C;;;AC/BA,eAAsBI,EAAS,GAAkB;CAC/C,IAAMC,IAASf,EAAUgB,CAAO,GAC1BC,IAAmB,CAAC;CAE1B,EAAO,KAAK,mCAAmC;CAC/C,IAAMR,IAAaF,EAAK,KACtBS,EAAQ,MACR,OACA,UACA,YACA,oBACF,GACMN,IAAON,EACXK,GACAD,EAAyBC,CAAU,CACrC;CAGA,OAFIC,KAAMO,EAAS,KAAKP,CAAI,GAErB;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-BfM3dX_R.js","names":["libModule","getLogger","withInMemoryScript","ensureBlankLineAfterImports","removeImportByModuleSpecifier","modifyOutcomeToFile","SvelteFile","fs","path","unmodifyRootLayoutSvelte","layoutPath","file","out","content","sf","generate","logger","options","modifies"],"sources":["../../src/patterns/disable/ecommerce/modifies/root-layout.svelte.ts","../../src/patterns/disable/ecommerce/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\n/** Takes out the navbar item enable-ecommerce added, and its import. */\nexport function unmodifyRootLayoutSvelte(layoutPath: string): ModifyOutcome {\n if (!fs.existsSync(layoutPath)) {\n return { status: \"success\", changed: false };\n }\n\n const file = SvelteFile.fromPath(layoutPath);\n if (!file.hasElement(\"CartButton\")) {\n return { status: \"success\", changed: false };\n }\n\n if (!file.removeElementContaining(\"Navbar.Item\", \"CartButton\")) {\n file.removeElement(\"CartButton\");\n }\n file.modifyScript((content) => {\n const { source: out } = withInMemoryScript(content, (sf) => {\n removeImportByModuleSpecifier(\n sf,\n libModule(\"components/cart/cart-button.svelte\"),\n );\n ensureBlankLineAfterImports(sf);\n });\n return out;\n });\n\n file.writeTo(layoutPath);\n return { status: \"success\", changed: file.hasChanged() };\n}\n","import path from \"node:path\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { unmodifyRootLayoutSvelte } from \"./modifies/root-layout.svelte\";\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const modifies: File[] = [];\n\n logger.info(\"Taking the cart out of the navbar\");\n const layoutPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(public)\",\n \"root-layout.svelte\",\n );\n const file = modifyOutcomeToFile(\n layoutPath,\n unmodifyRootLayoutSvelte(layoutPath),\n );\n if (file) modifies.push(file);\n\n return {\n creates: [],\n modifies,\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n } satisfies Result;\n}\n"],"mappings":";;;;;;;;AAWA,SAAgBS,EAAyB,GAAmC;CAC1E,IAAI,CAACF,EAAG,WAAWG,CAAU,GAC3B,OAAO;EAAE,QAAQ;EAAW,SAAS;CAAM;CAG7C,IAAMC,IAAOL,EAAW,SAASI,CAAU;CAoB3C,OAnBKC,EAAK,WAAW,YAAY,KAI5BA,EAAK,wBAAwB,eAAe,YAAY,KAC3DA,EAAK,cAAc,YAAY,GAEjCA,EAAK,cAAc,MAAY;EAC7B,IAAM,EAAE,QAAQC,MAAQV,EAAmBW,IAAU,MAAO;GAK1D,AAJAT,EACEU,GACAd,EAAU,oCAAoC,CAChD,GACAG,EAA4BW,CAAE;EAChC,CAAC;EACD,OAAOF;CACT,CAAC,GAEDD,EAAK,QAAQD,CAAU,GAChB;EAAE,QAAQ;EAAW,SAASC,EAAK,WAAW;CAAE,KAlB9C;EAAE,QAAQ;EAAW,SAAS;CAAM;AAmB/C;;;AC/BA,eAAsBI,EAAS,GAAkB;CAC/C,IAAMC,IAASf,EAAUgB,CAAO,GAC1BC,IAAmB,CAAC;CAE1B,EAAO,KAAK,mCAAmC;CAC/C,IAAMR,IAAaF,EAAK,KACtBS,EAAQ,MACR,OACA,UACA,YACA,oBACF,GACMN,IAAON,EACXK,GACAD,EAAyBC,CAAU,CACrC;CAGA,OAFIC,KAAMO,EAAS,KAAKP,CAAI,GAErB;EACL,SAAS,CAAC;EACV;EACA,SAAS,CAAC;EACV,YAAY,CAAC;EACb,UAAU,CAAC;EACX,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAiB,CAAC;CACpB;AACF"}
@@ -4,18 +4,18 @@ import { a as i, c as a, l as o } from "./providers-CL9kQ4hp.js";
4
4
  import { t as s } from "./dedent-Gq6Krl4n.js";
5
5
  import { t as c } from "./taggedTemplateLiteral-KSUnuvOk.js";
6
6
  import { n as l } from "./logger-CQONztPm.js";
7
- import { a as u, n as d, r as f, t as p } from "./currency.server-Dwz8LgvP.js";
7
+ import { a as u, n as d, r as f, t as p } from "./currency.server-DygAf6a1.js";
8
8
  import { a as m, i as h, r as g } from "./collections-DZOuRpvS.js";
9
- import { i as _, n as v, t as y } from "./pocketbase-BtN-wL8f.js";
10
- import { a as b, i as x, r as S, s as C, t as w } from "./site-VrqOvuiU.js";
9
+ import { i as _, n as v, t as y } from "./pocketbase-BTR3gI8o.js";
10
+ import { a as b, i as x, r as S, s as C, t as w } from "./site-D0IuWkAR.js";
11
11
  import { t as T } from "./env-BugddEjd.js";
12
- import { r as E } from "./modify-file-B4uJzOEj.js";
13
- import { modifyEnvVarsFiles as D } from "./env-vars-0hvKe55u.js";
12
+ import { r as E } from "./modify-file-D9U2LXEa.js";
13
+ import { modifyEnvVarsFiles as D } from "./env-vars-XvAeH6u5.js";
14
14
  import { n as O } from "./modify-nav-user-iUpv2lm-.js";
15
15
  import { a as k, r as A, s as j, t as M } from "./root-layout.svelte-CUVbnlX-.js";
16
16
  import { n as N, t as P } from "./wuchale-config-c3Q4JVSF.js";
17
17
  import { t as F } from "./modify-user-signup-DLtopazD.js";
18
- import { i as I, r as L } from "./collections-BYcVyY9O.js";
18
+ import { i as I, r as L } from "./collections-zEoRuILr.js";
19
19
  import R from "node:fs";
20
20
  import z from "node:path";
21
21
  import B from "stripe";
@@ -499,4 +499,4 @@ async function $(e) {
499
499
  //#endregion
500
500
  export { $ as generate, Q as hasVitest };
501
501
 
502
- //# sourceMappingURL=generate.runtime-DSs4gVRU.js.map
502
+ //# sourceMappingURL=generate.runtime-BfQlxsWK.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"generate.runtime-DSs4gVRU.js","names":["__import_glob__0_0_","__import_glob__0_1_","InvalidArgumentError","languageFromPath","mergeResults","providerEnvVars","resolveProvider","suppliedProviderEnv","dedent","_taggedTemplateLiteral","getLogger","envEditsFor","currency_server_test_default","META","currency_server_default","buyPageSnippet","STRIPE_PRODUCTS","STRIPE_PRICES","withPocketbase","migrationDelay","getMigrationFile","normalizeCurrency","normalizeCurrencies","normalizeCountry","sitePath","ensureSiteBusiness","modifyEnv","modifyOutcomeToFile","modifyNavUser","modifyLayoutServerCurrency","modifyLayoutSvelteCurrency","modifyHooksServerCurrency","modifyRootLayoutCurrencySelect","modifyWuchaleJsFiles","TRANSLATED_LIB_FILES","modifyUserSignup","ensureCollectionFields","createCollectionIdempotent","fs","path","Stripe","setupShopify","logger","options","variantId","creates","syncUsersToStripeCustomers","stripe","stripeSecretKey","users","pb","existing","linkedUserIds","c","result","user","matching","label","customer","isExistingCustomer","error","paymentMethods","paymentMethod","defaultPaymentMethod","createTestProductAndPrice","products","product","prices","getProductAndPriceById","price","priceId","_templateObject","pushMigrationCreates","created","migrationFile","collectionName","action","paymentPageSnippet","setupStripe","stripePriceId","isAppMode","modifies","pushResult","file","create","spec","customersResult","stripeCustomersCollection","paymentMethodsResult","stripePaymentMethodsCollection","transactionsResult","syncResult","navUserPath","userSignupPath","setupWhatsApp","business","given","wuchaleConfig","edit","createsServerRaw","serverCreates","filesFromGlob","unitTests","a","b","hasVitest","pkg","root","generate","provider","envPath","envVars","modifyEnvVarsFiles","siteExisted","siteFile","currency","country","currencies","layoutPath","layoutServerPath","layoutServer","hooksServerPath","rootLayoutPath","env","setup"],"sources":["../../src/patterns/enable/payments/runtime/setup-shopify.ts","../../src/patterns/enable/payments/runtime/stripe.ts","../../src/patterns/enable/payments/runtime/setup-stripe.ts","../../src/patterns/enable/payments/runtime/setup-whatsapp.ts","../../src/patterns/enable/payments/generate.runtime.ts"],"sourcesContent":["import type { Options, Result } from \"../../../../core/types\";\nimport { getLogger } from \"../../../../core/logger\";\nimport { buyPageSnippet } from \"../shopify-page\";\n\n/**\n * Shopify keeps products, customers and checkout on its side, so past the env\n * there is only the demo page, and only when a variant to sell was given.\n */\nexport async function setupShopify(options: Options) {\n const logger = getLogger(options);\n const variantId =\n typeof options.input.demoId === \"string\" ? options.input.demoId.trim() : \"\";\n\n const creates = [];\n if (variantId) {\n logger.info(\"Creating payment +page.svelte\");\n creates.push({\n path: \"src/routes/(public)/payment/+page.svelte\",\n language: \"svelte\",\n content: buyPageSnippet(variantId),\n status: \"success\" as const,\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","import Stripe from \"stripe\";\nimport type PocketBase from \"pocketbase\";\nimport type { Logger } from \"../../../../core/logger\";\n\nexport interface StripeTestFixture {\n product: Stripe.Product;\n price: Stripe.Price;\n existing: boolean;\n}\n\nexport interface SyncUsersResult {\n total: number;\n linked: number;\n created: number;\n reused: number;\n skipped: number;\n}\n\nexport async function syncUsersToStripeCustomers(\n pb: PocketBase,\n stripeSecretKey: string,\n logger: Logger,\n): Promise<SyncUsersResult> {\n const stripe = new Stripe(stripeSecretKey);\n const users = await pb.collection(\"users\").getFullList<{\n id: string;\n email?: string;\n name?: string;\n phone?: string;\n }>();\n\n const existing = await pb\n .collection(\"stripe_customers\")\n .getFullList<{ id: string; user: string }>();\n const linkedUserIds = new Set(existing.map((c) => c.user));\n\n const result: SyncUsersResult = {\n total: users.length,\n linked: linkedUserIds.size,\n created: 0,\n reused: 0,\n skipped: 0,\n };\n\n for (const user of users) {\n if (linkedUserIds.has(user.id)) {\n result.skipped += 1;\n continue;\n }\n\n // A user made with a phone number may have no email to match on.\n const matching = user.email\n ? await stripe.customers.list({\n email: user.email,\n limit: 1,\n expand: [\"data.invoice_settings\"],\n })\n : { data: [] };\n const label = user.email || user.id;\n\n let customer: Stripe.Customer;\n let isExistingCustomer = false;\n\n if (matching.data.length > 0) {\n customer = matching.data[0];\n isExistingCustomer = true;\n result.reused += 1;\n logger.info(`Reusing Stripe customer ${customer.id} for ${label}`);\n } else {\n customer = await stripe.customers.create(\n user.email\n ? { email: user.email }\n : { name: user.name || undefined, phone: user.phone || undefined },\n );\n result.created += 1;\n logger.info(`Created Stripe customer ${customer.id} for ${label}`);\n }\n\n try {\n await pb.collection(\"stripe_customers\").create({\n id: customer.id,\n user: user.id,\n });\n } catch (error) {\n logger.info(\n `Failed to create stripe_customers row for ${label}: ${(error as Error).message}`,\n );\n continue;\n }\n\n if (!isExistingCustomer) {\n continue;\n }\n\n const paymentMethods = await stripe.customers.listPaymentMethods(\n customer.id,\n { type: \"card\", allow_redisplay: \"always\" },\n );\n\n for (const paymentMethod of paymentMethods.data) {\n if (paymentMethod.allow_redisplay === \"unspecified\") continue;\n try {\n await pb.collection(\"stripe_payment_methods\").create({\n id: paymentMethod.id,\n customer: customer.id,\n brand: paymentMethod.card?.brand,\n last4: paymentMethod.card?.last4,\n exp_month: paymentMethod.card?.exp_month,\n exp_year: paymentMethod.card?.exp_year,\n });\n } catch {}\n }\n\n const defaultPaymentMethod =\n customer.invoice_settings?.default_payment_method;\n if (defaultPaymentMethod) {\n try {\n await pb.collection(\"stripe_customers\").update(customer.id, {\n default_payment_method:\n typeof defaultPaymentMethod === \"string\"\n ? defaultPaymentMethod\n : defaultPaymentMethod.id,\n });\n } catch {}\n }\n }\n\n return result;\n}\n\nexport async function createTestProductAndPrice(\n stripeSecretKey: string,\n): Promise<StripeTestFixture> {\n const stripe = new Stripe(stripeSecretKey);\n\n const products = await stripe.products.search({\n query: `name:\"Test Product\" AND metadata[\"test\"]:\"true\"`,\n limit: 1,\n });\n\n if (products.data.length > 0) {\n const product = products.data[0];\n const prices = await stripe.prices.list({\n product: product.id,\n active: true,\n limit: 1,\n });\n if (prices.data.length > 0) {\n return { product, price: prices.data[0], existing: true };\n }\n }\n\n const product = await stripe.products.create({\n name: \"Test Product\",\n metadata: { test: \"true\" },\n });\n\n const price = await stripe.prices.create({\n product: product.id,\n unit_amount: 1000,\n currency: \"usd\",\n });\n\n return { product, price, existing: false };\n}\n\nexport async function getProductAndPriceById(\n stripeSecretKey: string,\n priceId: string,\n): Promise<StripeTestFixture> {\n const stripe = new Stripe(stripeSecretKey);\n const price = await stripe.prices.retrieve(priceId, { expand: [\"product\"] });\n const product =\n typeof price.product === \"string\"\n ? await stripe.products.retrieve(price.product)\n : (price.product as Stripe.Product);\n price.product = product.id;\n return { product, price, existing: true };\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport dedent from \"dedent\";\nimport type { File, Options, Result } from \"../../../../core/types\";\nimport { getLogger } from \"../../../../core/logger\";\nimport { suppliedProviderEnv } from \"../../../../core/providers\";\nimport { languageFromPath } from \"../../../../core/util\";\nimport {\n getMigrationFile,\n migrationDelay,\n withPocketbase,\n} from \"../../../../runtime/pocketbase\";\nimport {\n createCollectionIdempotent,\n ensureCollectionFields,\n} from \"../../../../runtime/collections\";\nimport { STRIPE_PRICES, STRIPE_PRODUCTS } from \"./collections\";\nimport { modifyOutcomeToFile } from \"../../../../runtime/modify-file\";\nimport { modifyNavUser } from \"../modifies/modify-nav-user\";\nimport { modifyUserSignup } from \"../modifies/modify-user-signup\";\nimport {\n createTestProductAndPrice,\n getProductAndPriceById,\n syncUsersToStripeCustomers,\n} from \"./stripe\";\n\nasync function pushMigrationCreates(\n creates: File[],\n collectionName: string,\n action: \"created\" | \"updated\",\n options: Options,\n created = true,\n) {\n if (!created) return;\n await migrationDelay();\n const migrationFile = getMigrationFile(collectionName, action, options);\n if (!migrationFile) return;\n creates.push({\n path: migrationFile,\n language: languageFromPath(migrationFile),\n content: fs.readFileSync(migrationFile, \"utf8\"),\n status: \"success\",\n });\n}\n\nfunction paymentPageSnippet(priceId: string): string {\n return dedent`\n <script lang=\"ts\">\n import PaymentButton from '#lib/components/payments/payment-button.svelte';\n </script>\n\n <section data-role=\"content\">\n <PaymentButton priceId=\"${priceId}\" />\n </section>\n `;\n}\n\n/**\n * Everything Stripe needs past its env: the catalog and customer collections,\n * the existing users as Stripe customers, a product/price for the demo page,\n * and, with auth, the billing nav item and the signup link to Stripe.\n */\nexport async function setupStripe(options: Options) {\n const stripeSecretKey = suppliedProviderEnv(options).STRIPE_SECRET_KEY ?? \"\";\n const stripePriceId =\n typeof options.input.demoId === \"string\" && options.input.demoId !== \"\"\n ? options.input.demoId\n : undefined;\n\n const isAppMode = options.features.auth;\n const logger = getLogger(options);\n const creates: File[] = [];\n const modifies: File[] = [];\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n await withPocketbase(options.root, async (pb) => {\n const create = (spec: Parameters<typeof createCollectionIdempotent>[1]) =>\n createCollectionIdempotent(pb, spec, logger);\n\n // The catalog: created, or, when a project enabled payments before a\n // field existed, brought up to the spec (the next sync fills the field).\n for (const spec of [STRIPE_PRODUCTS, STRIPE_PRICES]) {\n logger.info(`Creating ${spec.name} collection`);\n const result = await create(spec);\n await pushMigrationCreates(\n creates,\n spec.name,\n \"created\",\n options,\n result.created,\n );\n if (!result.created) {\n creates.push(\n ...(await ensureCollectionFields(pb, spec, options, logger)),\n );\n }\n }\n\n if (isAppMode) {\n logger.info(\"Creating stripe_customers collection\");\n const customersResult = await create({\n name: \"stripe_customers\",\n type: \"base\",\n fields: [\n {\n name: \"id\",\n pattern: \"^[a-zA-Z0-9_]+$\",\n primaryKey: true,\n required: true,\n system: true,\n type: \"text\",\n },\n {\n collectionId: \"_pb_users_auth_\",\n maxSelect: 1,\n minSelect: 0,\n name: \"user\",\n required: true,\n type: \"relation\",\n },\n {\n name: \"created\",\n onCreate: true,\n onUpdate: false,\n type: \"autodate\",\n },\n {\n name: \"updated\",\n onCreate: true,\n onUpdate: true,\n type: \"autodate\",\n },\n ],\n });\n const stripeCustomersCollection = customersResult.collection;\n await pushMigrationCreates(\n creates,\n \"stripe_customers\",\n \"created\",\n options,\n customersResult.created,\n );\n\n logger.info(\"Creating stripe_payment_methods collection\");\n const paymentMethodsResult = await create({\n name: \"stripe_payment_methods\",\n type: \"base\",\n fields: [\n {\n name: \"id\",\n pattern: \"^[a-zA-Z0-9_]+$\",\n primaryKey: true,\n required: true,\n system: true,\n type: \"text\",\n },\n { name: \"brand\", required: true, type: \"text\" },\n { name: \"last4\", required: true, type: \"text\" },\n { name: \"exp_month\", required: true, type: \"number\" },\n { name: \"exp_year\", required: true, type: \"number\" },\n {\n collectionId: stripeCustomersCollection.id,\n maxSelect: 1,\n minSelect: 0,\n name: \"customer\",\n required: true,\n type: \"relation\",\n cascadeDelete: true,\n },\n {\n name: \"created\",\n onCreate: true,\n onUpdate: false,\n type: \"autodate\",\n },\n {\n name: \"updated\",\n onCreate: true,\n onUpdate: true,\n type: \"autodate\",\n },\n ],\n });\n const stripePaymentMethodsCollection = paymentMethodsResult.collection;\n await pushMigrationCreates(\n creates,\n \"stripe_payment_methods\",\n \"created\",\n options,\n paymentMethodsResult.created,\n );\n\n logger.info(\"Linking default_payment_method on stripe_customers\");\n await pb.collections.update(\"stripe_customers\", {\n fields: [\n {\n name: \"id\",\n pattern: \"^[a-zA-Z0-9_]+$\",\n primaryKey: true,\n required: true,\n system: true,\n type: \"text\",\n },\n {\n collectionId: \"_pb_users_auth_\",\n maxSelect: 1,\n minSelect: 0,\n name: \"user\",\n required: true,\n type: \"relation\",\n },\n {\n collectionId: stripePaymentMethodsCollection.id,\n maxSelect: 1,\n minSelect: 0,\n name: \"default_payment_method\",\n required: false,\n type: \"relation\",\n },\n {\n name: \"created\",\n onCreate: true,\n onUpdate: false,\n type: \"autodate\",\n },\n {\n name: \"updated\",\n onCreate: true,\n onUpdate: true,\n type: \"autodate\",\n },\n ],\n });\n await pushMigrationCreates(\n creates,\n \"stripe_customers\",\n \"updated\",\n options,\n );\n\n logger.info(\"Creating transactions collection\");\n const transactionsResult = await create({\n name: \"transactions\",\n type: \"base\",\n fields: [\n {\n autogeneratePattern: \"[a-z0-9]{15}\",\n max: 15,\n min: 15,\n name: \"id\",\n pattern: \"^[a-z0-9]+$\",\n primaryKey: true,\n required: true,\n system: true,\n type: \"text\",\n },\n { name: \"stripe_payment_intent\", required: true, type: \"text\" },\n { name: \"amount\", required: true, type: \"number\" },\n { name: \"currency\", required: true, type: \"text\" },\n { name: \"last4\", required: true, type: \"text\" },\n { name: \"brand\", required: true, type: \"text\" },\n { name: \"created\", required: true, type: \"date\" },\n { name: \"stripe_charge\", required: true, type: \"text\" },\n { name: \"stripe_customer\", required: true, type: \"text\" },\n {\n collectionId: \"_pb_users_auth_\",\n maxSelect: 1,\n minSelect: 0,\n name: \"user\",\n required: true,\n type: \"relation\",\n },\n { name: \"receipt_url\", required: true, type: \"url\" },\n ],\n });\n await pushMigrationCreates(\n creates,\n \"transactions\",\n \"created\",\n options,\n transactionsResult.created,\n );\n\n logger.info(\"Syncing existing PocketBase users to Stripe customers\");\n const syncResult = await syncUsersToStripeCustomers(\n pb,\n stripeSecretKey,\n logger,\n );\n logger.info(\n `Synced ${syncResult.total} users (created ${syncResult.created}, reused ${syncResult.reused}, skipped ${syncResult.skipped})`,\n );\n }\n });\n\n if (stripePriceId) {\n logger.info(`Fetching Stripe product/price ${stripePriceId}`);\n } else {\n logger.info(\"Creating test Stripe product and price\");\n }\n const { product, price, existing } = stripePriceId\n ? await getProductAndPriceById(stripeSecretKey, stripePriceId)\n : await createTestProductAndPrice(stripeSecretKey);\n\n if (existing) {\n logger.info(\"Stripe product/price already exists, skipping creation\");\n }\n\n logger.info(\"Seeding Stripe product/price records\");\n await withPocketbase(options.root, async (pb) => {\n try {\n await pb.collection(\"stripe_products\").getOne(product.id);\n } catch (error) {\n await pb.collection(\"stripe_products\").create({\n id: product.id,\n name: product.name,\n active: product.active,\n default_price: product.default_price,\n });\n }\n\n try {\n await pb.collection(\"stripe_prices\").getOne(price.id);\n } catch (error) {\n await pb.collection(\"stripe_prices\").create({\n id: price.id,\n billing_scheme: price.billing_scheme,\n currency: price.currency,\n product: price.product,\n recurring: price.recurring,\n type: price.type,\n unit_amount: price.unit_amount,\n active: price.active,\n });\n }\n });\n\n logger.info(\"Creating payment +page.svelte\");\n creates.push({\n path: \"src/routes/(public)/payment/+page.svelte\",\n language: \"svelte\",\n content: paymentPageSnippet(price.id),\n status: \"success\",\n });\n\n if (isAppMode) {\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(modifyOutcomeToFile(navUserPath, modifyNavUser(navUserPath)));\n\n logger.info(\"Modifying signup +page.server.ts\");\n const userSignupPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(public)\",\n \"(auth)\",\n \"signup\",\n \"+page.server.ts\",\n );\n pushResult(\n modifyOutcomeToFile(userSignupPath, modifyUserSignup(userSignupPath)),\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","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { File, Options, Result } from \"../../../../core/types\";\nimport { InvalidArgumentError } from \"../../../../core/errors\";\nimport { getLogger } from \"../../../../core/logger\";\nimport { modifyOutcomeToFile } from \"../../../../runtime/modify-file\";\nimport type { SiteBusiness } from \"../../../../runtime/site\";\nimport {\n modifyWuchaleJsFiles,\n TRANSLATED_LIB_FILES,\n} from \"../../../../runtime/wuchale-config\";\n\n/**\n * WhatsApp keeps nothing past the env: orders go to the business's chat, and\n * the hosted form they are recorded to is created by the CLI. Every price is\n * in `site.currency`, so a project without one can't take orders: `business`\n * is what `src/lib/site.ts` declares after the shared step wrote it.\n */\nexport async function setupWhatsApp(options: Options, business: SiteBusiness) {\n if (!business.currency) {\n const given = options.input.currency;\n throw new InvalidArgumentError(\n given === undefined || given === \"\"\n ? \"Payments on WhatsApp need the business's currency, the one it prices in (an ISO 4217 code such as MXN or EUR). Pass --currency, or set `currency` in src/lib/site.ts.\"\n : `${String(given)} is not an ISO 4217 currency code, such as MXN or EUR.`,\n );\n }\n const modifies: File[] = [];\n\n // The order message is text a visitor sends, so with wuchale on it is\n // translated like the pages: the js adapter has to be told about the module.\n const wuchaleConfig = path.join(options.root, \"wuchale.config.js\");\n if (fs.existsSync(wuchaleConfig)) {\n getLogger(options).info(\"Adding src/lib/order.ts to wuchale's js adapter\");\n const edit = modifyOutcomeToFile(\n wuchaleConfig,\n modifyWuchaleJsFiles(wuchaleConfig, TRANSLATED_LIB_FILES),\n );\n if (edit) modifies.push(edit);\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","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport {\n providerEnvVars,\n resolveProvider,\n suppliedProviderEnv,\n} from \"../../../core/providers\";\nimport { filesFromGlob, mergeResults } from \"../../../core/util\";\nimport { modifyEnvVarsFiles } from \"../../../runtime/env-vars\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { modifyEnv } from \"../../../runtime/env\";\nimport {\n ensureSiteBusiness,\n normalizeCountry,\n normalizeCurrencies,\n normalizeCurrency,\n sitePath,\n} from \"../../../runtime/site\";\nimport { envEditsFor, META } from \"./generate\";\nimport { modifyHooksServerCurrency } from \"./modifies/hooks.server\";\nimport { modifyLayoutServerCurrency } from \"./modifies/layout.server\";\nimport { modifyLayoutSvelteCurrency } from \"./modifies/layout.svelte\";\nimport { modifyRootLayoutCurrencySelect } from \"./modifies/root-layout.svelte\";\nimport { setupShopify } from \"./runtime/setup-shopify\";\nimport { setupStripe } from \"./runtime/setup-stripe\";\nimport { setupWhatsApp } from \"./runtime/setup-whatsapp\";\n\nconst createsServerRaw = import.meta.glob<string>(\"./creates-server/**\", {\n query: \"?raw\",\n import: \"default\",\n eager: true,\n});\n\n/** The server half of the currency store, for a project with a server load. */\nexport function serverCreates(unitTests: boolean): File[] {\n return Object.values(filesFromGlob(createsServerRaw, \"./creates-server/\"))\n .filter((file) => unitTests || !file.path.endsWith(\".test.ts\"))\n .sort((a, b) => a.path.localeCompare(b.path));\n}\n\n/** Whether the project can run a unit test (`vitest` in package.json). */\nexport function hasVitest(root: string): boolean {\n try {\n const pkg = JSON.parse(\n fs.readFileSync(path.join(root, \"package.json\"), \"utf8\"),\n ) as {\n dependencies?: Record<string, string>;\n devDependencies?: Record<string, string>;\n };\n return Boolean(pkg.devDependencies?.vitest || pkg.dependencies?.vitest);\n } catch {\n return false;\n }\n}\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const provider = resolveProvider(META, options);\n const creates: File[] = [];\n const modifies: File[] = [];\n\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n logger.info(`Writing ${provider.label} credentials to .env`);\n const envPath = path.join(options.root, \".env\");\n pushResult(\n modifyOutcomeToFile(\n envPath,\n modifyEnv(envPath, envEditsFor(provider, suppliedProviderEnv(options))),\n ),\n );\n\n // SvelteKit 3 exposes only declared variables, and only `public: true`\n // ones through `$app/env/public`.\n logger.info(`Declaring ${provider.label} variables in src/env.ts`);\n const envVars = modifyEnvVarsFiles(options.root, providerEnvVars(provider));\n if (envVars.create) creates.push(envVars.create);\n pushResult(envVars.modify);\n\n // What the business declares in src/lib/site.ts: the currency it prices\n // in, the country it is in, and the other currencies it shows prices in.\n // Asked for by the CLI; a value already there is kept.\n const { currency, country, currencies } = options.input;\n const siteExisted = fs.existsSync(sitePath(options.root));\n const { file: siteFile, business } = await ensureSiteBusiness(options, {\n currency: normalizeCurrency(currency) ?? undefined,\n country: normalizeCountry(country) ?? undefined,\n currencies:\n normalizeCurrencies(\n currencies,\n normalizeCurrency(currency) ?? undefined,\n ) ?? undefined,\n });\n if (siteFile) (siteExisted ? modifies : creates).push(siteFile);\n\n logger.info(\"Adding the currency select to the navbar\");\n const layoutPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(public)\",\n \"root-layout.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(layoutPath, modifyRootLayoutCurrencySelect(layoutPath)),\n );\n\n // With a server, the visitor's currency is decided per request and the\n // first render already shows it. A static site (a universal root load) keeps\n // the store's browser-side start.\n const layoutServerPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"+layout.server.ts\",\n );\n if (fs.existsSync(layoutServerPath)) {\n logger.info(\"Resolving the visitor's currency on the server\");\n const layoutServer = modifyLayoutServerCurrency(layoutServerPath);\n pushResult(modifyOutcomeToFile(layoutServerPath, layoutServer));\n if (layoutServer.status === \"success\") {\n const hooksServerPath = path.join(options.root, \"src\", \"hooks.server.ts\");\n pushResult(\n modifyOutcomeToFile(\n hooksServerPath,\n modifyHooksServerCurrency(hooksServerPath),\n ),\n );\n const rootLayoutPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"+layout.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(\n rootLayoutPath,\n modifyLayoutSvelteCurrency(rootLayoutPath),\n ),\n );\n for (const file of serverCreates(hasVitest(options.root)))\n creates.push(file);\n }\n }\n\n const env: Result = {\n creates,\n modifies,\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n };\n\n const setup =\n provider.id === \"stripe\"\n ? await setupStripe(options)\n : provider.id === \"shopify\"\n ? await setupShopify(options)\n : await setupWhatsApp(options, business);\n\n return mergeResults([env, setup]) sat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C5BI,EAAQ,MACR,OACA,UACA,mBACF;CACA,IAAIL,EAAG,WAAWiF,CAAgB,GAAG;EACnC,EAAO,KAAK,gDAAgD;EAC5D,IAAMC,IAAe3F,EAA2B0F,CAAgB;EAEhE,IADArC,EAAWvD,EAAoB4F,GAAkBC,CAAY,CAAC,GAC1DA,EAAa,WAAW,WAAW;GACrC,IAAMC,IAAkBlF,EAAK,KAAKI,EAAQ,MAAM,OAAO,iBAAiB;GACxE,EACEhB,EACE8F,GACA1F,EAA0B0F,CAAe,CAC3C,CACF;GACA,IAAMC,IAAiBnF,EAAK,KAC1BI,EAAQ,MACR,OACA,UACA,gBACF;GACA,EACEhB,EACE+F,GACA5F,EAA2B4F,CAAc,CAC3C,CACF;GACA,KAAK,IAAMvC,KAAQiB,EAAcK,EAAU9D,EAAQ,IAAI,CAAC,GACtD,EAAQ,KAAKwC,CAAI;EACrB;CACF;CAEA,IAAMwC,IAAc;EAClB;EACA;EACA,SAAS,CAAC;EACV,YAAY,CAAC;EACb,UAAU,CAAC;EACX,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAiB,CAAC;CACpB,GAEMC,IACJf,EAAS,OAAO,WACZ,MAAM/B,EAAYnC,CAAO,IACzBkE,EAAS,OAAO,YACd,MAAMpE,EAAaE,CAAO,IAC1B,MAAMmD,EAAcnD,GAASoD,CAAQ;CAE7C,OAAO3F,EAAa,CAACuH,GAAKC,CAAK,CAAC;AAClC"}
1
+ {"version":3,"file":"generate.runtime-BfQlxsWK.js","names":["__import_glob__0_0_","__import_glob__0_1_","InvalidArgumentError","languageFromPath","mergeResults","providerEnvVars","resolveProvider","suppliedProviderEnv","dedent","_taggedTemplateLiteral","getLogger","envEditsFor","currency_server_test_default","META","currency_server_default","buyPageSnippet","STRIPE_PRODUCTS","STRIPE_PRICES","withPocketbase","migrationDelay","getMigrationFile","normalizeCurrency","normalizeCurrencies","normalizeCountry","sitePath","ensureSiteBusiness","modifyEnv","modifyOutcomeToFile","modifyNavUser","modifyLayoutServerCurrency","modifyLayoutSvelteCurrency","modifyHooksServerCurrency","modifyRootLayoutCurrencySelect","modifyWuchaleJsFiles","TRANSLATED_LIB_FILES","modifyUserSignup","ensureCollectionFields","createCollectionIdempotent","fs","path","Stripe","setupShopify","logger","options","variantId","creates","syncUsersToStripeCustomers","stripe","stripeSecretKey","users","pb","existing","linkedUserIds","c","result","user","matching","label","customer","isExistingCustomer","error","paymentMethods","paymentMethod","defaultPaymentMethod","createTestProductAndPrice","products","product","prices","getProductAndPriceById","price","priceId","_templateObject","pushMigrationCreates","created","migrationFile","collectionName","action","paymentPageSnippet","setupStripe","stripePriceId","isAppMode","modifies","pushResult","file","create","spec","customersResult","stripeCustomersCollection","paymentMethodsResult","stripePaymentMethodsCollection","transactionsResult","syncResult","navUserPath","userSignupPath","setupWhatsApp","business","given","wuchaleConfig","edit","createsServerRaw","serverCreates","filesFromGlob","unitTests","a","b","hasVitest","pkg","root","generate","provider","envPath","envVars","modifyEnvVarsFiles","siteExisted","siteFile","currency","country","currencies","layoutPath","layoutServerPath","layoutServer","hooksServerPath","rootLayoutPath","env","setup"],"sources":["../../src/patterns/enable/payments/runtime/setup-shopify.ts","../../src/patterns/enable/payments/runtime/stripe.ts","../../src/patterns/enable/payments/runtime/setup-stripe.ts","../../src/patterns/enable/payments/runtime/setup-whatsapp.ts","../../src/patterns/enable/payments/generate.runtime.ts"],"sourcesContent":["import type { Options, Result } from \"../../../../core/types\";\nimport { getLogger } from \"../../../../core/logger\";\nimport { buyPageSnippet } from \"../shopify-page\";\n\n/**\n * Shopify keeps products, customers and checkout on its side, so past the env\n * there is only the demo page, and only when a variant to sell was given.\n */\nexport async function setupShopify(options: Options) {\n const logger = getLogger(options);\n const variantId =\n typeof options.input.demoId === \"string\" ? options.input.demoId.trim() : \"\";\n\n const creates = [];\n if (variantId) {\n logger.info(\"Creating payment +page.svelte\");\n creates.push({\n path: \"src/routes/(public)/payment/+page.svelte\",\n language: \"svelte\",\n content: buyPageSnippet(variantId),\n status: \"success\" as const,\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","import Stripe from \"stripe\";\nimport type PocketBase from \"pocketbase\";\nimport type { Logger } from \"../../../../core/logger\";\n\nexport interface StripeTestFixture {\n product: Stripe.Product;\n price: Stripe.Price;\n existing: boolean;\n}\n\nexport interface SyncUsersResult {\n total: number;\n linked: number;\n created: number;\n reused: number;\n skipped: number;\n}\n\nexport async function syncUsersToStripeCustomers(\n pb: PocketBase,\n stripeSecretKey: string,\n logger: Logger,\n): Promise<SyncUsersResult> {\n const stripe = new Stripe(stripeSecretKey);\n const users = await pb.collection(\"users\").getFullList<{\n id: string;\n email?: string;\n name?: string;\n phone?: string;\n }>();\n\n const existing = await pb\n .collection(\"stripe_customers\")\n .getFullList<{ id: string; user: string }>();\n const linkedUserIds = new Set(existing.map((c) => c.user));\n\n const result: SyncUsersResult = {\n total: users.length,\n linked: linkedUserIds.size,\n created: 0,\n reused: 0,\n skipped: 0,\n };\n\n for (const user of users) {\n if (linkedUserIds.has(user.id)) {\n result.skipped += 1;\n continue;\n }\n\n // A user made with a phone number may have no email to match on.\n const matching = user.email\n ? await stripe.customers.list({\n email: user.email,\n limit: 1,\n expand: [\"data.invoice_settings\"],\n })\n : { data: [] };\n const label = user.email || user.id;\n\n let customer: Stripe.Customer;\n let isExistingCustomer = false;\n\n if (matching.data.length > 0) {\n customer = matching.data[0];\n isExistingCustomer = true;\n result.reused += 1;\n logger.info(`Reusing Stripe customer ${customer.id} for ${label}`);\n } else {\n customer = await stripe.customers.create(\n user.email\n ? { email: user.email }\n : { name: user.name || undefined, phone: user.phone || undefined },\n );\n result.created += 1;\n logger.info(`Created Stripe customer ${customer.id} for ${label}`);\n }\n\n try {\n await pb.collection(\"stripe_customers\").create({\n id: customer.id,\n user: user.id,\n });\n } catch (error) {\n logger.info(\n `Failed to create stripe_customers row for ${label}: ${(error as Error).message}`,\n );\n continue;\n }\n\n if (!isExistingCustomer) {\n continue;\n }\n\n const paymentMethods = await stripe.customers.listPaymentMethods(\n customer.id,\n { type: \"card\", allow_redisplay: \"always\" },\n );\n\n for (const paymentMethod of paymentMethods.data) {\n if (paymentMethod.allow_redisplay === \"unspecified\") continue;\n try {\n await pb.collection(\"stripe_payment_methods\").create({\n id: paymentMethod.id,\n customer: customer.id,\n brand: paymentMethod.card?.brand,\n last4: paymentMethod.card?.last4,\n exp_month: paymentMethod.card?.exp_month,\n exp_year: paymentMethod.card?.exp_year,\n });\n } catch {}\n }\n\n const defaultPaymentMethod =\n customer.invoice_settings?.default_payment_method;\n if (defaultPaymentMethod) {\n try {\n await pb.collection(\"stripe_customers\").update(customer.id, {\n default_payment_method:\n typeof defaultPaymentMethod === \"string\"\n ? defaultPaymentMethod\n : defaultPaymentMethod.id,\n });\n } catch {}\n }\n }\n\n return result;\n}\n\nexport async function createTestProductAndPrice(\n stripeSecretKey: string,\n): Promise<StripeTestFixture> {\n const stripe = new Stripe(stripeSecretKey);\n\n const products = await stripe.products.search({\n query: `name:\"Test Product\" AND metadata[\"test\"]:\"true\"`,\n limit: 1,\n });\n\n if (products.data.length > 0) {\n const product = products.data[0];\n const prices = await stripe.prices.list({\n product: product.id,\n active: true,\n limit: 1,\n });\n if (prices.data.length > 0) {\n return { product, price: prices.data[0], existing: true };\n }\n }\n\n const product = await stripe.products.create({\n name: \"Test Product\",\n metadata: { test: \"true\" },\n });\n\n const price = await stripe.prices.create({\n product: product.id,\n unit_amount: 1000,\n currency: \"usd\",\n });\n\n return { product, price, existing: false };\n}\n\nexport async function getProductAndPriceById(\n stripeSecretKey: string,\n priceId: string,\n): Promise<StripeTestFixture> {\n const stripe = new Stripe(stripeSecretKey);\n const price = await stripe.prices.retrieve(priceId, { expand: [\"product\"] });\n const product =\n typeof price.product === \"string\"\n ? await stripe.products.retrieve(price.product)\n : (price.product as Stripe.Product);\n price.product = product.id;\n return { product, price, existing: true };\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport dedent from \"dedent\";\nimport type { File, Options, Result } from \"../../../../core/types\";\nimport { getLogger } from \"../../../../core/logger\";\nimport { suppliedProviderEnv } from \"../../../../core/providers\";\nimport { languageFromPath } from \"../../../../core/util\";\nimport {\n getMigrationFile,\n migrationDelay,\n withPocketbase,\n} from \"../../../../runtime/pocketbase\";\nimport {\n createCollectionIdempotent,\n ensureCollectionFields,\n} from \"../../../../runtime/collections\";\nimport { STRIPE_PRICES, STRIPE_PRODUCTS } from \"./collections\";\nimport { modifyOutcomeToFile } from \"../../../../runtime/modify-file\";\nimport { modifyNavUser } from \"../modifies/modify-nav-user\";\nimport { modifyUserSignup } from \"../modifies/modify-user-signup\";\nimport {\n createTestProductAndPrice,\n getProductAndPriceById,\n syncUsersToStripeCustomers,\n} from \"./stripe\";\n\nasync function pushMigrationCreates(\n creates: File[],\n collectionName: string,\n action: \"created\" | \"updated\",\n options: Options,\n created = true,\n) {\n if (!created) return;\n await migrationDelay();\n const migrationFile = getMigrationFile(collectionName, action, options);\n if (!migrationFile) return;\n creates.push({\n path: migrationFile,\n language: languageFromPath(migrationFile),\n content: fs.readFileSync(migrationFile, \"utf8\"),\n status: \"success\",\n });\n}\n\nfunction paymentPageSnippet(priceId: string): string {\n return dedent`\n <script lang=\"ts\">\n import PaymentButton from '#lib/components/payments/payment-button.svelte';\n </script>\n\n <section data-role=\"content\">\n <PaymentButton priceId=\"${priceId}\" />\n </section>\n `;\n}\n\n/**\n * Everything Stripe needs past its env: the catalog and customer collections,\n * the existing users as Stripe customers, a product/price for the demo page,\n * and, with auth, the billing nav item and the signup link to Stripe.\n */\nexport async function setupStripe(options: Options) {\n const stripeSecretKey = suppliedProviderEnv(options).STRIPE_SECRET_KEY ?? \"\";\n const stripePriceId =\n typeof options.input.demoId === \"string\" && options.input.demoId !== \"\"\n ? options.input.demoId\n : undefined;\n\n const isAppMode = options.features.auth;\n const logger = getLogger(options);\n const creates: File[] = [];\n const modifies: File[] = [];\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n await withPocketbase(options.root, async (pb) => {\n const create = (spec: Parameters<typeof createCollectionIdempotent>[1]) =>\n createCollectionIdempotent(pb, spec, logger);\n\n // The catalog: created, or, when a project enabled payments before a\n // field existed, brought up to the spec (the next sync fills the field).\n for (const spec of [STRIPE_PRODUCTS, STRIPE_PRICES]) {\n logger.info(`Creating ${spec.name} collection`);\n const result = await create(spec);\n await pushMigrationCreates(\n creates,\n spec.name,\n \"created\",\n options,\n result.created,\n );\n if (!result.created) {\n creates.push(\n ...(await ensureCollectionFields(pb, spec, options, logger)),\n );\n }\n }\n\n if (isAppMode) {\n logger.info(\"Creating stripe_customers collection\");\n const customersResult = await create({\n name: \"stripe_customers\",\n type: \"base\",\n fields: [\n {\n name: \"id\",\n pattern: \"^[a-zA-Z0-9_]+$\",\n primaryKey: true,\n required: true,\n system: true,\n type: \"text\",\n },\n {\n collectionId: \"_pb_users_auth_\",\n maxSelect: 1,\n minSelect: 0,\n name: \"user\",\n required: true,\n type: \"relation\",\n },\n {\n name: \"created\",\n onCreate: true,\n onUpdate: false,\n type: \"autodate\",\n },\n {\n name: \"updated\",\n onCreate: true,\n onUpdate: true,\n type: \"autodate\",\n },\n ],\n });\n const stripeCustomersCollection = customersResult.collection;\n await pushMigrationCreates(\n creates,\n \"stripe_customers\",\n \"created\",\n options,\n customersResult.created,\n );\n\n logger.info(\"Creating stripe_payment_methods collection\");\n const paymentMethodsResult = await create({\n name: \"stripe_payment_methods\",\n type: \"base\",\n fields: [\n {\n name: \"id\",\n pattern: \"^[a-zA-Z0-9_]+$\",\n primaryKey: true,\n required: true,\n system: true,\n type: \"text\",\n },\n { name: \"brand\", required: true, type: \"text\" },\n { name: \"last4\", required: true, type: \"text\" },\n { name: \"exp_month\", required: true, type: \"number\" },\n { name: \"exp_year\", required: true, type: \"number\" },\n {\n collectionId: stripeCustomersCollection.id,\n maxSelect: 1,\n minSelect: 0,\n name: \"customer\",\n required: true,\n type: \"relation\",\n cascadeDelete: true,\n },\n {\n name: \"created\",\n onCreate: true,\n onUpdate: false,\n type: \"autodate\",\n },\n {\n name: \"updated\",\n onCreate: true,\n onUpdate: true,\n type: \"autodate\",\n },\n ],\n });\n const stripePaymentMethodsCollection = paymentMethodsResult.collection;\n await pushMigrationCreates(\n creates,\n \"stripe_payment_methods\",\n \"created\",\n options,\n paymentMethodsResult.created,\n );\n\n logger.info(\"Linking default_payment_method on stripe_customers\");\n await pb.collections.update(\"stripe_customers\", {\n fields: [\n {\n name: \"id\",\n pattern: \"^[a-zA-Z0-9_]+$\",\n primaryKey: true,\n required: true,\n system: true,\n type: \"text\",\n },\n {\n collectionId: \"_pb_users_auth_\",\n maxSelect: 1,\n minSelect: 0,\n name: \"user\",\n required: true,\n type: \"relation\",\n },\n {\n collectionId: stripePaymentMethodsCollection.id,\n maxSelect: 1,\n minSelect: 0,\n name: \"default_payment_method\",\n required: false,\n type: \"relation\",\n },\n {\n name: \"created\",\n onCreate: true,\n onUpdate: false,\n type: \"autodate\",\n },\n {\n name: \"updated\",\n onCreate: true,\n onUpdate: true,\n type: \"autodate\",\n },\n ],\n });\n await pushMigrationCreates(\n creates,\n \"stripe_customers\",\n \"updated\",\n options,\n );\n\n logger.info(\"Creating transactions collection\");\n const transactionsResult = await create({\n name: \"transactions\",\n type: \"base\",\n fields: [\n {\n autogeneratePattern: \"[a-z0-9]{15}\",\n max: 15,\n min: 15,\n name: \"id\",\n pattern: \"^[a-z0-9]+$\",\n primaryKey: true,\n required: true,\n system: true,\n type: \"text\",\n },\n { name: \"stripe_payment_intent\", required: true, type: \"text\" },\n { name: \"amount\", required: true, type: \"number\" },\n { name: \"currency\", required: true, type: \"text\" },\n { name: \"last4\", required: true, type: \"text\" },\n { name: \"brand\", required: true, type: \"text\" },\n { name: \"created\", required: true, type: \"date\" },\n { name: \"stripe_charge\", required: true, type: \"text\" },\n { name: \"stripe_customer\", required: true, type: \"text\" },\n {\n collectionId: \"_pb_users_auth_\",\n maxSelect: 1,\n minSelect: 0,\n name: \"user\",\n required: true,\n type: \"relation\",\n },\n { name: \"receipt_url\", required: true, type: \"url\" },\n ],\n });\n await pushMigrationCreates(\n creates,\n \"transactions\",\n \"created\",\n options,\n transactionsResult.created,\n );\n\n logger.info(\"Syncing existing PocketBase users to Stripe customers\");\n const syncResult = await syncUsersToStripeCustomers(\n pb,\n stripeSecretKey,\n logger,\n );\n logger.info(\n `Synced ${syncResult.total} users (created ${syncResult.created}, reused ${syncResult.reused}, skipped ${syncResult.skipped})`,\n );\n }\n });\n\n if (stripePriceId) {\n logger.info(`Fetching Stripe product/price ${stripePriceId}`);\n } else {\n logger.info(\"Creating test Stripe product and price\");\n }\n const { product, price, existing } = stripePriceId\n ? await getProductAndPriceById(stripeSecretKey, stripePriceId)\n : await createTestProductAndPrice(stripeSecretKey);\n\n if (existing) {\n logger.info(\"Stripe product/price already exists, skipping creation\");\n }\n\n logger.info(\"Seeding Stripe product/price records\");\n await withPocketbase(options.root, async (pb) => {\n try {\n await pb.collection(\"stripe_products\").getOne(product.id);\n } catch (error) {\n await pb.collection(\"stripe_products\").create({\n id: product.id,\n name: product.name,\n active: product.active,\n default_price: product.default_price,\n });\n }\n\n try {\n await pb.collection(\"stripe_prices\").getOne(price.id);\n } catch (error) {\n await pb.collection(\"stripe_prices\").create({\n id: price.id,\n billing_scheme: price.billing_scheme,\n currency: price.currency,\n product: price.product,\n recurring: price.recurring,\n type: price.type,\n unit_amount: price.unit_amount,\n active: price.active,\n });\n }\n });\n\n logger.info(\"Creating payment +page.svelte\");\n creates.push({\n path: \"src/routes/(public)/payment/+page.svelte\",\n language: \"svelte\",\n content: paymentPageSnippet(price.id),\n status: \"success\",\n });\n\n if (isAppMode) {\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(modifyOutcomeToFile(navUserPath, modifyNavUser(navUserPath)));\n\n logger.info(\"Modifying signup +page.server.ts\");\n const userSignupPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(public)\",\n \"(auth)\",\n \"signup\",\n \"+page.server.ts\",\n );\n pushResult(\n modifyOutcomeToFile(userSignupPath, modifyUserSignup(userSignupPath)),\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","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { File, Options, Result } from \"../../../../core/types\";\nimport { InvalidArgumentError } from \"../../../../core/errors\";\nimport { getLogger } from \"../../../../core/logger\";\nimport { modifyOutcomeToFile } from \"../../../../runtime/modify-file\";\nimport type { SiteBusiness } from \"../../../../runtime/site\";\nimport {\n modifyWuchaleJsFiles,\n TRANSLATED_LIB_FILES,\n} from \"../../../../runtime/wuchale-config\";\n\n/**\n * WhatsApp keeps nothing past the env: orders go to the business's chat, and\n * the hosted form they are recorded to is created by the CLI. Every price is\n * in `site.currency`, so a project without one can't take orders: `business`\n * is what `src/lib/site.ts` declares after the shared step wrote it.\n */\nexport async function setupWhatsApp(options: Options, business: SiteBusiness) {\n if (!business.currency) {\n const given = options.input.currency;\n throw new InvalidArgumentError(\n given === undefined || given === \"\"\n ? \"Payments on WhatsApp need the business's currency, the one it prices in (an ISO 4217 code such as MXN or EUR). Pass --currency, or set `currency` in src/lib/site.ts.\"\n : `${String(given)} is not an ISO 4217 currency code, such as MXN or EUR.`,\n );\n }\n const modifies: File[] = [];\n\n // The order message is text a visitor sends, so with wuchale on it is\n // translated like the pages: the js adapter has to be told about the module.\n const wuchaleConfig = path.join(options.root, \"wuchale.config.js\");\n if (fs.existsSync(wuchaleConfig)) {\n getLogger(options).info(\"Adding src/lib/order.ts to wuchale's js adapter\");\n const edit = modifyOutcomeToFile(\n wuchaleConfig,\n modifyWuchaleJsFiles(wuchaleConfig, TRANSLATED_LIB_FILES),\n );\n if (edit) modifies.push(edit);\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","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport {\n providerEnvVars,\n resolveProvider,\n suppliedProviderEnv,\n} from \"../../../core/providers\";\nimport { filesFromGlob, mergeResults } from \"../../../core/util\";\nimport { modifyEnvVarsFiles } from \"../../../runtime/env-vars\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { modifyEnv } from \"../../../runtime/env\";\nimport {\n ensureSiteBusiness,\n normalizeCountry,\n normalizeCurrencies,\n normalizeCurrency,\n sitePath,\n} from \"../../../runtime/site\";\nimport { envEditsFor, META } from \"./generate\";\nimport { modifyHooksServerCurrency } from \"./modifies/hooks.server\";\nimport { modifyLayoutServerCurrency } from \"./modifies/layout.server\";\nimport { modifyLayoutSvelteCurrency } from \"./modifies/layout.svelte\";\nimport { modifyRootLayoutCurrencySelect } from \"./modifies/root-layout.svelte\";\nimport { setupShopify } from \"./runtime/setup-shopify\";\nimport { setupStripe } from \"./runtime/setup-stripe\";\nimport { setupWhatsApp } from \"./runtime/setup-whatsapp\";\n\nconst createsServerRaw = import.meta.glob<string>(\"./creates-server/**\", {\n query: \"?raw\",\n import: \"default\",\n eager: true,\n});\n\n/** The server half of the currency store, for a project with a server load. */\nexport function serverCreates(unitTests: boolean): File[] {\n return Object.values(filesFromGlob(createsServerRaw, \"./creates-server/\"))\n .filter((file) => unitTests || !file.path.endsWith(\".test.ts\"))\n .sort((a, b) => a.path.localeCompare(b.path));\n}\n\n/** Whether the project can run a unit test (`vitest` in package.json). */\nexport function hasVitest(root: string): boolean {\n try {\n const pkg = JSON.parse(\n fs.readFileSync(path.join(root, \"package.json\"), \"utf8\"),\n ) as {\n dependencies?: Record<string, string>;\n devDependencies?: Record<string, string>;\n };\n return Boolean(pkg.devDependencies?.vitest || pkg.dependencies?.vitest);\n } catch {\n return false;\n }\n}\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const provider = resolveProvider(META, options);\n const creates: File[] = [];\n const modifies: File[] = [];\n\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n logger.info(`Writing ${provider.label} credentials to .env`);\n const envPath = path.join(options.root, \".env\");\n pushResult(\n modifyOutcomeToFile(\n envPath,\n modifyEnv(envPath, envEditsFor(provider, suppliedProviderEnv(options))),\n ),\n );\n\n // SvelteKit 3 exposes only declared variables, and only `public: true`\n // ones through `$app/env/public`.\n logger.info(`Declaring ${provider.label} variables in src/env.ts`);\n const envVars = modifyEnvVarsFiles(options.root, providerEnvVars(provider));\n if (envVars.create) creates.push(envVars.create);\n pushResult(envVars.modify);\n\n // What the business declares in src/lib/site.ts: the currency it prices\n // in, the country it is in, and the other currencies it shows prices in.\n // Asked for by the CLI; a value already there is kept.\n const { currency, country, currencies } = options.input;\n const siteExisted = fs.existsSync(sitePath(options.root));\n const { file: siteFile, business } = await ensureSiteBusiness(options, {\n currency: normalizeCurrency(currency) ?? undefined,\n country: normalizeCountry(country) ?? undefined,\n currencies:\n normalizeCurrencies(\n currencies,\n normalizeCurrency(currency) ?? undefined,\n ) ?? undefined,\n });\n if (siteFile) (siteExisted ? modifies : creates).push(siteFile);\n\n logger.info(\"Adding the currency select to the navbar\");\n const layoutPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(public)\",\n \"root-layout.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(layoutPath, modifyRootLayoutCurrencySelect(layoutPath)),\n );\n\n // With a server, the visitor's currency is decided per request and the\n // first render already shows it. A static site (a universal root load) keeps\n // the store's browser-side start.\n const layoutServerPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"+layout.server.ts\",\n );\n if (fs.existsSync(layoutServerPath)) {\n logger.info(\"Resolving the visitor's currency on the server\");\n const layoutServer = modifyLayoutServerCurrency(layoutServerPath);\n pushResult(modifyOutcomeToFile(layoutServerPath, layoutServer));\n if (layoutServer.status === \"success\") {\n const hooksServerPath = path.join(options.root, \"src\", \"hooks.server.ts\");\n pushResult(\n modifyOutcomeToFile(\n hooksServerPath,\n modifyHooksServerCurrency(hooksServerPath),\n ),\n );\n const rootLayoutPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"+layout.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(\n rootLayoutPath,\n modifyLayoutSvelteCurrency(rootLayoutPath),\n ),\n );\n for (const file of serverCreates(hasVitest(options.root)))\n creates.push(file);\n }\n }\n\n const env: Result = {\n creates,\n modifies,\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n };\n\n const setup =\n provider.id === \"stripe\"\n ? await setupStripe(options)\n : provider.id === \"shopify\"\n ? await setupShopify(options)\n : await setupWhatsApp(options, business);\n\n return mergeResults([env, setup]) satisfies Result;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAQA,eAAsByC,EAAa,GAAkB;CACnD,IAAMC,IAAShC,EAAUiC,CAAO,GAC1BC,IACJ,OAAOD,EAAQ,MAAM,UAAW,WAAWA,EAAQ,MAAM,OAAO,KAAK,IAAI,IAErEE,IAAU,CAAC;CAWjB,OAVID,MACFF,EAAO,KAAK,+BAA+B,GAC3CG,EAAQ,KAAK;EACX,MAAM;EACN,UAAU;EACV,SAAS9B,EAAe6B,CAAS;EACjC,QAAQ;CACV,CAAC,IAGI;EACL;EACA,UAAU,CAAC;EACX,SAAS,CAAC;EACV,YAAY,CAAC;EACb,UAAU,CAAC;EACX,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAiB,CAAC;CACpB;AACF;;;AChBA,eAAsBE,EACpB,GACA,GACA,GAC0B;CAC1B,IAAMC,IAAS,IAAIP,EAAOQ,CAAe,GACnCC,IAAQ,MAAMC,EAAG,WAAW,OAAO,CAAC,CAAC,YAKxC,GAEGC,IAAW,MAAMD,EACpB,W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,mBAAmB,CAAC;EACpB,iBAAiB,CAAC;CACpB,GAEMC,IACJf,EAAS,OAAO,WACZ,MAAM/B,EAAYnC,CAAO,IACzBkE,EAAS,OAAO,YACd,MAAMpE,EAAaE,CAAO,IAC1B,MAAMmD,EAAcnD,GAASoD,CAAQ;CAE7C,OAAO3F,EAAa,CAACuH,GAAKC,CAAK,CAAC;AAClC"}
@@ -1,6 +1,6 @@
1
1
  import { n as e } from "./logger-CQONztPm.js";
2
2
  import { o as t } from "./ts-morph-helpers-CHI9wAil.js";
3
- import { r as n } from "./modify-file-B4uJzOEj.js";
3
+ import { r as n } from "./modify-file-D9U2LXEa.js";
4
4
  import r from "node:fs";
5
5
  import i from "node:path";
6
6
  import { Project as a, SyntaxKind as o } from "ts-morph";
@@ -54,4 +54,4 @@ async function c(t) {
54
54
  //#endregion
55
55
  export { c as generate };
56
56
 
57
- //# sourceMappingURL=generate.runtime-zr6uIHCd.js.map
57
+ //# sourceMappingURL=generate.runtime-BsjcGBme.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"generate.runtime-zr6uIHCd.js","names":["getLogger","formatLikeSource","modifyOutcomeToFile","fs","path","unmodifyHooksServer","hooksServerPath","originalSource","sourceFile","Project","callExpr","SyntaxKind","ce","args","firstArg","optionsObj","apiProp","generate","logger","options","modifies","file"],"sources":["../../src/patterns/disable/api/modifies/hooks.server.ts","../../src/patterns/disable/api/generate.runtime.ts"],"sourcesContent":["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\n if (!callExpr) {\n return { status: \"success\", changed: false };\n }\n\n const args = callExpr.getArguments();\n if (args.length === 0) {\n return { status: \"success\", changed: false };\n }\n\n const firstArg = args[0];\n if (firstArg.getKind() !== SyntaxKind.ObjectLiteralExpression) {\n return { status: \"success\", changed: false };\n }\n\n const optionsObj = firstArg.asKindOrThrow(SyntaxKind.ObjectLiteralExpression);\n const apiProp = optionsObj.getProperty(\"api\");\n if (!apiProp) {\n return { status: \"success\", changed: false };\n }\n\n apiProp.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 type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { unmodifyHooksServer } from \"./modifies/hooks.server\";\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const modifies: File[] = [];\n\n logger.info(\"Reverting hooks.server.ts\");\n const hooksServerPath = path.join(options.root, \"src\", \"hooks.server.ts\");\n const file = modifyOutcomeToFile(\n hooksServerPath,\n unmodifyHooksServer(hooksServerPath),\n );\n if (file) modifies.push(file);\n\n return {\n creates: [],\n modifies,\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n } satisfies Result;\n}\n"],"mappings":";;;;;;;AAKA,SAAgBK,EAAoB,GAAwC;CAC1E,IAAI,CAACF,EAAG,WAAWG,CAAe,GAChC,OAAO;EAAE,QAAQ;EAAW,SAAS;CAAM;CAG7C,IAAMC,IAAiBJ,EAAG,aAAaG,GAAiB,MAAM,GAExDE,IAAa,IADCC,EACD,CAAA,CAAQ,oBAAoBH,CAAe,GAExDI,IAAWF,EACd,qBAAqBG,EAAW,cAAc,CAAC,CAC/C,MAAM,MAAOC,EAAG,cAAc,CAAC,CAAC,QAAQ,MAAM,kBAAkB;CAEnE,IAAI,CAACF,GACH,OAAO;EAAE,QAAQ;EAAW,SAAS;CAAM;CAG7C,IAAMG,IAAOH,EAAS,aAAa;CACnC,IAAIG,EAAK,WAAW,GAClB,OAAO;EAAE,QAAQ;EAAW,SAAS;CAAM;CAG7C,IAAMC,IAAWD,EAAK;CACtB,IAAIC,EAAS,QAAQ,MAAMH,EAAW,yBACpC,OAAO;EAAE,QAAQ;EAAW,SAAS;CAAM;CAG7C,IAAMI,IAAaD,EAAS,cAAcH,EAAW,uBAAuB,GACtEK,IAAUD,EAAW,YAAY,KAAK;CAc5C,OAbKC,KAILA,EAAQ,OAAO,GAEXD,EAAW,cAAc,CAAC,CAAC,WAAW,KACxCL,EAAS,eAAe,CAAC,GAG3BT,EAAiBO,CAAU,GAC3BA,EAAW,SAAS,GAEb;EACL,QAAQ;EACR,SAASA,EAAW,YAAY,MAAMD;CACxC,KAfS;EAAE,QAAQ;EAAW,SAAS;CAAM;AAgB/C;;;AC7CA,eAAsBU,EAAS,GAAkB;CAC/C,IAAMC,IAASlB,EAAUmB,CAAO,GAC1BC,IAAmB,CAAC;CAE1B,EAAO,KAAK,2BAA2B;CACvC,IAAMd,IAAkBF,EAAK,KAAKe,EAAQ,MAAM,OAAO,iBAAiB,GAClEE,IAAOnB,EACXI,GACAD,EAAoBC,CAAe,CACrC;CAGA,OAFIe,KAAMD,EAAS,KAAKC,CAAI,GAErB;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-BsjcGBme.js","names":["getLogger","formatLikeSource","modifyOutcomeToFile","fs","path","unmodifyHooksServer","hooksServerPath","originalSource","sourceFile","Project","callExpr","SyntaxKind","ce","args","firstArg","optionsObj","apiProp","generate","logger","options","modifies","file"],"sources":["../../src/patterns/disable/api/modifies/hooks.server.ts","../../src/patterns/disable/api/generate.runtime.ts"],"sourcesContent":["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\n if (!callExpr) {\n return { status: \"success\", changed: false };\n }\n\n const args = callExpr.getArguments();\n if (args.length === 0) {\n return { status: \"success\", changed: false };\n }\n\n const firstArg = args[0];\n if (firstArg.getKind() !== SyntaxKind.ObjectLiteralExpression) {\n return { status: \"success\", changed: false };\n }\n\n const optionsObj = firstArg.asKindOrThrow(SyntaxKind.ObjectLiteralExpression);\n const apiProp = optionsObj.getProperty(\"api\");\n if (!apiProp) {\n return { status: \"success\", changed: false };\n }\n\n apiProp.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 type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { unmodifyHooksServer } from \"./modifies/hooks.server\";\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const modifies: File[] = [];\n\n logger.info(\"Reverting hooks.server.ts\");\n const hooksServerPath = path.join(options.root, \"src\", \"hooks.server.ts\");\n const file = modifyOutcomeToFile(\n hooksServerPath,\n unmodifyHooksServer(hooksServerPath),\n );\n if (file) modifies.push(file);\n\n return {\n creates: [],\n modifies,\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n } satisfies Result;\n}\n"],"mappings":";;;;;;;AAKA,SAAgBK,EAAoB,GAAwC;CAC1E,IAAI,CAACF,EAAG,WAAWG,CAAe,GAChC,OAAO;EAAE,QAAQ;EAAW,SAAS;CAAM;CAG7C,IAAMC,IAAiBJ,EAAG,aAAaG,GAAiB,MAAM,GAExDE,IAAa,IADCC,EACD,CAAA,CAAQ,oBAAoBH,CAAe,GAExDI,IAAWF,EACd,qBAAqBG,EAAW,cAAc,CAAC,CAC/C,MAAM,MAAOC,EAAG,cAAc,CAAC,CAAC,QAAQ,MAAM,kBAAkB;CAEnE,IAAI,CAACF,GACH,OAAO;EAAE,QAAQ;EAAW,SAAS;CAAM;CAG7C,IAAMG,IAAOH,EAAS,aAAa;CACnC,IAAIG,EAAK,WAAW,GAClB,OAAO;EAAE,QAAQ;EAAW,SAAS;CAAM;CAG7C,IAAMC,IAAWD,EAAK;CACtB,IAAIC,EAAS,QAAQ,MAAMH,EAAW,yBACpC,OAAO;EAAE,QAAQ;EAAW,SAAS;CAAM;CAG7C,IAAMI,IAAaD,EAAS,cAAcH,EAAW,uBAAuB,GACtEK,IAAUD,EAAW,YAAY,KAAK;CAc5C,OAbKC,KAILA,EAAQ,OAAO,GAEXD,EAAW,cAAc,CAAC,CAAC,WAAW,KACxCL,EAAS,eAAe,CAAC,GAG3BT,EAAiBO,CAAU,GAC3BA,EAAW,SAAS,GAEb;EACL,QAAQ;EACR,SAASA,EAAW,YAAY,MAAMD;CACxC,KAfS;EAAE,QAAQ;EAAW,SAAS;CAAM;AAgB/C;;;AC7CA,eAAsBU,EAAS,GAAkB;CAC/C,IAAMC,IAASlB,EAAUmB,CAAO,GAC1BC,IAAmB,CAAC;CAE1B,EAAO,KAAK,2BAA2B;CACvC,IAAMd,IAAkBF,EAAK,KAAKe,EAAQ,MAAM,OAAO,iBAAiB,GAClEE,IAAOnB,EACXI,GACAD,EAAoBC,CAAe,CACrC;CAGA,OAFIe,KAAMD,EAAS,KAAKC,CAAI,GAErB;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,7 +1,7 @@
1
1
  import { t as e } from "./dedent-Gq6Krl4n.js";
2
2
  import { n as t } from "./logger-CQONztPm.js";
3
3
  import { _ as n, o as r, r as i } from "./ts-morph-helpers-CHI9wAil.js";
4
- import { r as a } from "./modify-file-B4uJzOEj.js";
4
+ import { r as a } from "./modify-file-D9U2LXEa.js";
5
5
  import { t as o } from "./svelte-file-Dv5-bl79.js";
6
6
  import { t as s } from "./compose-handle-BBlamPfx.js";
7
7
  import c from "node:fs";
@@ -181,4 +181,4 @@ async function T(e) {
181
181
  //#endregion
182
182
  export { T as generate };
183
183
 
184
- //# sourceMappingURL=generate.runtime-D677SB4v.js.map
184
+ //# sourceMappingURL=generate.runtime-ByC9kOl2.js.map