@velastack/patterns 0.15.1 → 0.15.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunks/_page-CFeYIl2d.js +5 -0
- package/dist/chunks/_page-CFeYIl2d.js.map +1 -0
- package/dist/chunks/_page-DkCd_o3E.js +5 -0
- package/dist/chunks/{_page-Cg7LjaOE.js.map → _page-DkCd_o3E.js.map} +1 -1
- package/dist/chunks/{auth-pages-DSBqKjO0.js → auth-pages-mZeR1WIj.js} +2 -2
- package/dist/chunks/{auth-pages-DSBqKjO0.js.map → auth-pages-mZeR1WIj.js.map} +1 -1
- package/dist/chunks/{collections-D2_2cxWD.js → collections-Daxlnbm0.js} +2 -2
- package/dist/chunks/{collections-D2_2cxWD.js.map → collections-Daxlnbm0.js.map} +1 -1
- package/dist/chunks/{constants-DbpctM1D.js → constants-E1I-__KI.js} +18 -18
- package/dist/chunks/{constants-DbpctM1D.js.map → constants-E1I-__KI.js.map} +1 -1
- package/dist/chunks/{currency.server-CFrwmYra.js → currency.server-CHzEhyTx.js} +74 -74
- package/dist/chunks/currency.server-CHzEhyTx.js.map +1 -0
- package/dist/chunks/dispatch-DSkRrJFe.js +5 -0
- package/dist/chunks/{dispatch-BxlKS_5v.js.map → dispatch-DSkRrJFe.js.map} +1 -1
- package/dist/chunks/{env-vars-Dm3Xy4rl.js → env-vars-C3TSZc4f.js} +3 -3
- package/dist/chunks/{env-vars-Dm3Xy4rl.js.map → env-vars-C3TSZc4f.js.map} +1 -1
- package/dist/chunks/{generate-BMWoD9E2.js → generate-CAYM7OUF.js} +2 -2
- package/dist/chunks/{generate-BMWoD9E2.js.map → generate-CAYM7OUF.js.map} +1 -1
- package/dist/chunks/{generate-DZ9kT3iC.js → generate-CL7wG0ZC.js} +3 -3
- package/dist/chunks/{generate-DZ9kT3iC.js.map → generate-CL7wG0ZC.js.map} +1 -1
- package/dist/chunks/{generate-BRTIGlqT.js → generate-CbchamhA.js} +3 -3
- package/dist/chunks/{generate-BRTIGlqT.js.map → generate-CbchamhA.js.map} +1 -1
- package/dist/chunks/{generate-BvQ6VwYH.js → generate-DR2wkVPY.js} +2 -2
- package/dist/chunks/{generate-BvQ6VwYH.js.map → generate-DR2wkVPY.js.map} +1 -1
- package/dist/chunks/{generate-Cs_fdfD7.js → generate-DZ2S8KDR.js} +3 -3
- package/dist/chunks/{generate-Cs_fdfD7.js.map → generate-DZ2S8KDR.js.map} +1 -1
- package/dist/chunks/{generate.runtime-Cd742Yqf.js → generate.runtime-373mTxeo.js} +113 -104
- package/dist/chunks/generate.runtime-373mTxeo.js.map +1 -0
- package/dist/chunks/{generate.runtime-1eTnPFmA.js → generate.runtime-B11mOr45.js} +2 -2
- package/dist/chunks/{generate.runtime-1eTnPFmA.js.map → generate.runtime-B11mOr45.js.map} +1 -1
- package/dist/chunks/{generate.runtime-CnNtG_x5.js → generate.runtime-B7VubPTW.js} +3 -3
- package/dist/chunks/{generate.runtime-CnNtG_x5.js.map → generate.runtime-B7VubPTW.js.map} +1 -1
- package/dist/chunks/{generate.runtime-BvHK8IN-.js → generate.runtime-BCv4F1Wm.js} +5 -5
- package/dist/chunks/{generate.runtime-BvHK8IN-.js.map → generate.runtime-BCv4F1Wm.js.map} +1 -1
- package/dist/chunks/{generate.runtime-D8G8cwCr.js → generate.runtime-BEWp57Y7.js} +2 -2
- package/dist/chunks/{generate.runtime-D8G8cwCr.js.map → generate.runtime-BEWp57Y7.js.map} +1 -1
- package/dist/chunks/{generate.runtime-CfCDLJ6Y.js → generate.runtime-BL6DpWFI.js} +3 -3
- package/dist/chunks/{generate.runtime-CfCDLJ6Y.js.map → generate.runtime-BL6DpWFI.js.map} +1 -1
- package/dist/chunks/{generate.runtime-BJwSyslL.js → generate.runtime-BRV9hIl5.js} +2 -2
- package/dist/chunks/{generate.runtime-BJwSyslL.js.map → generate.runtime-BRV9hIl5.js.map} +1 -1
- package/dist/chunks/{generate.runtime-B9nVU5iO.js → generate.runtime-BRcP6sFt.js} +2 -2
- package/dist/chunks/{generate.runtime-B9nVU5iO.js.map → generate.runtime-BRcP6sFt.js.map} +1 -1
- package/dist/chunks/{generate.runtime-BC1GJUXE.js → generate.runtime-Bhs7ttZS.js} +2 -2
- package/dist/chunks/{generate.runtime-BC1GJUXE.js.map → generate.runtime-Bhs7ttZS.js.map} +1 -1
- package/dist/chunks/{generate.runtime-B4mQEW54.js → generate.runtime-BjTZ2Ls-.js} +76 -76
- package/dist/chunks/generate.runtime-BjTZ2Ls-.js.map +1 -0
- package/dist/chunks/{generate.runtime-Bda2_WK7.js → generate.runtime-BjrtdoYE.js} +2 -2
- package/dist/chunks/{generate.runtime-Bda2_WK7.js.map → generate.runtime-BjrtdoYE.js.map} +1 -1
- package/dist/chunks/{generate.runtime-CjLath7N.js → generate.runtime-Bn17HK_S.js} +100 -98
- package/dist/chunks/generate.runtime-Bn17HK_S.js.map +1 -0
- package/dist/chunks/{generate.runtime-DBQvnQmR.js → generate.runtime-Bo_s7gYB.js} +2 -2
- package/dist/chunks/{generate.runtime-DBQvnQmR.js.map → generate.runtime-Bo_s7gYB.js.map} +1 -1
- package/dist/chunks/{generate.runtime-B-H2F-sH.js → generate.runtime-C90_2L-8.js} +3 -3
- package/dist/chunks/{generate.runtime-B-H2F-sH.js.map → generate.runtime-C90_2L-8.js.map} +1 -1
- package/dist/chunks/{generate.runtime-B4rG6gSK.js → generate.runtime-CDY0Ot_t.js} +6 -6
- package/dist/chunks/{generate.runtime-B4rG6gSK.js.map → generate.runtime-CDY0Ot_t.js.map} +1 -1
- package/dist/chunks/{generate.runtime-Doumu0TL.js → generate.runtime-CZMVPVjS.js} +6 -6
- package/dist/chunks/{generate.runtime-Doumu0TL.js.map → generate.runtime-CZMVPVjS.js.map} +1 -1
- package/dist/chunks/{generate.runtime-liAz2TOE.js → generate.runtime-C_hrLPD4.js} +3 -3
- package/dist/chunks/{generate.runtime-liAz2TOE.js.map → generate.runtime-C_hrLPD4.js.map} +1 -1
- package/dist/chunks/{generate.runtime-BkQPchHe.js → generate.runtime-ChSVP7cD.js} +6 -6
- package/dist/chunks/{generate.runtime-BkQPchHe.js.map → generate.runtime-ChSVP7cD.js.map} +1 -1
- package/dist/chunks/{generate.runtime-C1HlZnLC.js → generate.runtime-Cs73i6Zf.js} +2 -2
- package/dist/chunks/{generate.runtime-C1HlZnLC.js.map → generate.runtime-Cs73i6Zf.js.map} +1 -1
- package/dist/chunks/{generate.runtime-DFSsgOmB.js → generate.runtime-DG9LRwbt.js} +3 -3
- package/dist/chunks/{generate.runtime-DFSsgOmB.js.map → generate.runtime-DG9LRwbt.js.map} +1 -1
- package/dist/chunks/{generate.runtime-CZA46Ghe.js → generate.runtime-DIIeK2w9.js} +5 -5
- package/dist/chunks/{generate.runtime-CZA46Ghe.js.map → generate.runtime-DIIeK2w9.js.map} +1 -1
- package/dist/chunks/{generate.runtime-CIOi-XSm.js → generate.runtime-DKL7VAAd.js} +6 -6
- package/dist/chunks/{generate.runtime-CIOi-XSm.js.map → generate.runtime-DKL7VAAd.js.map} +1 -1
- package/dist/chunks/{generate.runtime-CQ_U4YTJ.js → generate.runtime-DP63Wwea.js} +4 -4
- package/dist/chunks/{generate.runtime-CQ_U4YTJ.js.map → generate.runtime-DP63Wwea.js.map} +1 -1
- package/dist/chunks/{generate.runtime-C62ChKGg.js → generate.runtime-DRPxOLnB.js} +4 -4
- package/dist/chunks/{generate.runtime-C62ChKGg.js.map → generate.runtime-DRPxOLnB.js.map} +1 -1
- package/dist/chunks/{generate.runtime-DE-vPcn4.js → generate.runtime-DVZUNxtv.js} +6 -6
- package/dist/chunks/{generate.runtime-DE-vPcn4.js.map → generate.runtime-DVZUNxtv.js.map} +1 -1
- package/dist/chunks/{generate.runtime-DQI69jkX.js → generate.runtime-DW9bqOtC.js} +2 -2
- package/dist/chunks/{generate.runtime-DQI69jkX.js.map → generate.runtime-DW9bqOtC.js.map} +1 -1
- package/dist/chunks/{generate.runtime-Dtum580c.js → generate.runtime-DXqBku2y.js} +6 -6
- package/dist/chunks/{generate.runtime-Dtum580c.js.map → generate.runtime-DXqBku2y.js.map} +1 -1
- package/dist/chunks/{generate.runtime-GmsldrGj.js → generate.runtime-DgKiFemb.js} +4 -4
- package/dist/chunks/{generate.runtime-GmsldrGj.js.map → generate.runtime-DgKiFemb.js.map} +1 -1
- package/dist/chunks/{generate.runtime-DQUZRJH8.js → generate.runtime-DmbDEjMA.js} +4 -4
- package/dist/chunks/{generate.runtime-DQUZRJH8.js.map → generate.runtime-DmbDEjMA.js.map} +1 -1
- package/dist/chunks/{generate.runtime-rxzMCECc.js → generate.runtime-VZIxJWlr.js} +72 -64
- package/dist/chunks/generate.runtime-VZIxJWlr.js.map +1 -0
- package/dist/chunks/{generate.runtime-DNjyaFml.js → generate.runtime-_426A1Ij.js} +3 -3
- package/dist/chunks/{generate.runtime-DNjyaFml.js.map → generate.runtime-_426A1Ij.js.map} +1 -1
- package/dist/chunks/{generate.runtime-DR8z6DyZ.js → generate.runtime-fs6GEMx-.js} +5 -5
- package/dist/chunks/{generate.runtime-DR8z6DyZ.js.map → generate.runtime-fs6GEMx-.js.map} +1 -1
- package/dist/chunks/{generate.runtime-Diix70x4.js → generate.runtime-jIlQ2GMh.js} +2 -2
- package/dist/chunks/{generate.runtime-Diix70x4.js.map → generate.runtime-jIlQ2GMh.js.map} +1 -1
- package/dist/chunks/{generate.runtime-ufoTIUXA.js → generate.runtime-sey-wxXB.js} +7 -7
- package/dist/chunks/{generate.runtime-ufoTIUXA.js.map → generate.runtime-sey-wxXB.js.map} +1 -1
- package/dist/chunks/{generate.runtime-BuQASx9Y.js → generate.runtime-v3KCv1B6.js} +2 -2
- package/dist/chunks/{generate.runtime-BuQASx9Y.js.map → generate.runtime-v3KCv1B6.js.map} +1 -1
- package/dist/chunks/{generate.runtime-lP4eoera.js → generate.runtime-xrxAElb3.js} +3 -3
- package/dist/chunks/{generate.runtime-lP4eoera.js.map → generate.runtime-xrxAElb3.js.map} +1 -1
- package/dist/chunks/{gitignore-2XpeEFmr.js → gitignore-CBiWFRif.js} +3 -3
- package/dist/chunks/{gitignore-2XpeEFmr.js.map → gitignore-CBiWFRif.js.map} +1 -1
- package/dist/chunks/{i18n-CxT1kz8Y.js → i18n-Ho8H91Ze.js} +2 -2
- package/dist/chunks/{i18n-CxT1kz8Y.js.map → i18n-Ho8H91Ze.js.map} +1 -1
- package/dist/chunks/{modify-file-BX9-aZD1.js → modify-file-BOEKlIDw.js} +2 -2
- package/dist/chunks/{modify-file-BX9-aZD1.js.map → modify-file-BOEKlIDw.js.map} +1 -1
- package/dist/chunks/{pocketbase-Dq9UdK_j.js → pocketbase-B2ksFrvH.js} +2 -2
- package/dist/chunks/{pocketbase-Dq9UdK_j.js.map → pocketbase-B2ksFrvH.js.map} +1 -1
- package/dist/chunks/{providers-2UgxXRJW.js → providers-BEjDonyG.js} +2 -2
- package/dist/chunks/{providers-2UgxXRJW.js.map → providers-BEjDonyG.js.map} +1 -1
- package/dist/chunks/{route-BDhlro0V.js → route-9ZVJZkYu.js} +23 -19
- package/dist/chunks/route-9ZVJZkYu.js.map +1 -0
- package/dist/chunks/{schema-2frI_BS2.js → schema-DnMqw2Hn.js} +3 -3
- package/dist/chunks/{schema-2frI_BS2.js.map → schema-DnMqw2Hn.js.map} +1 -1
- package/dist/chunks/{shared-BOFCKWJs.js → shared-CSwGWMcN.js} +2 -2
- package/dist/chunks/{shared-BOFCKWJs.js.map → shared-CSwGWMcN.js.map} +1 -1
- package/dist/chunks/{shared-DJ4KvhTb.js → shared-Cdwm_-Nl.js} +40 -40
- package/dist/chunks/{shared-DJ4KvhTb.js.map → shared-Cdwm_-Nl.js.map} +1 -1
- package/dist/chunks/{site-qASrdyUt.js → site-B5zrFba9.js} +2 -2
- package/dist/chunks/{site-qASrdyUt.js.map → site-B5zrFba9.js.map} +1 -1
- package/dist/chunks/{table-core-s2xjYgRD.js → table-core-ux1xEJxN.js} +2 -2
- package/dist/chunks/{table-core-s2xjYgRD.js.map → table-core-ux1xEJxN.js.map} +1 -1
- package/dist/chunks/{ui-DZuwcswv.js → ui-CpjUq_lm.js} +3 -3
- package/dist/chunks/{ui-DZuwcswv.js.map → ui-CpjUq_lm.js.map} +1 -1
- package/dist/chunks/{unmodify-load-CdWXJ_Ac.js → unmodify-load-DWixBz7y.js} +17 -4
- package/dist/chunks/unmodify-load-DWixBz7y.js.map +1 -0
- package/dist/chunks/{whatsapp-BytvTPlS.js → whatsapp-DOSZ_zwn.js} +2 -2
- package/dist/chunks/{whatsapp-BytvTPlS.js.map → whatsapp-DOSZ_zwn.js.map} +1 -1
- package/dist/chunks/{write-result-BhfLWAXf.js → write-result-DlB-id5k.js} +50 -26
- package/dist/chunks/write-result-DlB-id5k.js.map +1 -0
- package/dist/index.js +1997 -1965
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/dist/chunks/_page-Bt37d4uo.js +0 -5
- package/dist/chunks/_page-Bt37d4uo.js.map +0 -1
- package/dist/chunks/_page-Cg7LjaOE.js +0 -5
- package/dist/chunks/currency.server-CFrwmYra.js.map +0 -1
- package/dist/chunks/dispatch-BxlKS_5v.js +0 -5
- package/dist/chunks/generate.runtime-B4mQEW54.js.map +0 -1
- package/dist/chunks/generate.runtime-Cd742Yqf.js.map +0 -1
- package/dist/chunks/generate.runtime-CjLath7N.js.map +0 -1
- package/dist/chunks/generate.runtime-rxzMCECc.js.map +0 -1
- package/dist/chunks/route-BDhlro0V.js.map +0 -1
- package/dist/chunks/unmodify-load-CdWXJ_Ac.js.map +0 -1
- package/dist/chunks/write-result-BhfLWAXf.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"generate.runtime-Diix70x4.js","names":["successServer","successSvelte","getLogger","languageFromPath","modifyOutcomeToFile","dedent","withInMemoryScript","formatLikeSource","ensureImports","removeImportByModuleSpecifier","addItemToNavUser","_page_server_default","_page_default","fs","path","COMPLETED","ASYNC_PAYMENT","EVENTS","CASES_SNIPPET","FAILURE_HINT","NOT_FOUND_HINT","eventSwitch","sf","SyntaxKind","statement","modifyWebhookServer","filePath","original","added","clauses","defaultClause","Node","last","source","unmodifyWebhookServer","isOrders","clause","expression","ranges","i","first","start","end","SUCCESS_PAGE","NAV_USER","generate","logger","options","modifies","pushResult","file","dispatchPath","name","content","navUserPath","wasAdded","newNavUserSnippet"],"sources":["../../src/patterns/enable/orders/modifies/modify-webhook-server.ts","../../src/patterns/enable/orders/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { Node, SyntaxKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport {\n ensureImports,\n formatLikeSource,\n removeImportByModuleSpecifier,\n withInMemoryScript,\n} from \"../../../../runtime/ts-morph-helpers\";\n\nconst COMPLETED = \"./checkout/completed\";\nconst ASYNC_PAYMENT = \"./checkout/async-payment\";\n\n/** The Checkout Session events the order handlers take. */\nconst EVENTS = [\n \"checkout.session.completed\",\n \"checkout.session.async_payment_succeeded\",\n \"checkout.session.async_payment_failed\",\n];\n\nconst CASES_SNIPPET = dedent`\n case 'checkout.session.completed':\n await handleCheckoutSessionCompleted(event.data.object, locals);\n break;\n\n case 'checkout.session.async_payment_succeeded':\n case 'checkout.session.async_payment_failed':\n await handleCheckoutAsyncPayment(event.data.object, locals);\n break;\n`;\n\nconst FAILURE_HINT = dedent`\n Route the Checkout Session events to the order handlers in src/routes/webhooks/stripe/handlers/dispatch.ts:\n\n import { handleCheckoutSessionCompleted } from '${COMPLETED}';\n import { handleCheckoutAsyncPayment } from '${ASYNC_PAYMENT}';\n\n and, inside the \\`switch (event.type)\\`:\n\n ${CASES_SNIPPET.split(\"\\n\").join(\"\\n \")}\n`;\n\nconst NOT_FOUND_HINT =\n \"Enable payments first: src/routes/webhooks/stripe/handlers/dispatch.ts is created by enable-payments.\";\n\n/** The `switch (event.type)` the dispatcher routes on. */\nfunction eventSwitch(sf: import(\"ts-morph\").SourceFile) {\n return sf\n .getDescendantsOfKind(SyntaxKind.SwitchStatement)\n .find((statement) =>\n statement.getExpression().getText().includes(\"event.type\"),\n );\n}\n\n/** The order handlers join the dispatcher's switch, ahead of its default. */\nexport function modifyWebhookServer(filePath: string): 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(\"handleCheckoutSessionCompleted\")) {\n return { status: \"success\", changed: false };\n }\n\n let added = false;\n const { source } = withInMemoryScript(original, (sf) => {\n const statement = eventSwitch(sf);\n if (!statement) return;\n const clauses = statement.getCaseBlock().getClauses();\n const defaultClause = clauses.find(Node.isDefaultClause);\n if (defaultClause) {\n defaultClause.replaceWithText(\n `${CASES_SNIPPET}\\n\\n${defaultClause.getText()}`,\n );\n } else if (clauses.length > 0) {\n const last = clauses[clauses.length - 1];\n last.replaceWithText(`${last.getText()}\\n\\n${CASES_SNIPPET}`);\n } else {\n return;\n }\n ensureImports(sf, [\n {\n namedImports: [\"handleCheckoutSessionCompleted\"],\n moduleSpecifier: COMPLETED,\n },\n {\n namedImports: [\"handleCheckoutAsyncPayment\"],\n moduleSpecifier: ASYNC_PAYMENT,\n },\n ]);\n formatLikeSource(sf);\n added = true;\n });\n if (!added) return { status: \"failed\", message: FAILURE_HINT };\n fs.writeFileSync(filePath, source, \"utf8\");\n return { status: \"success\", changed: true };\n}\n\n/** Take the order cases and their imports back out of the dispatcher. */\nexport function unmodifyWebhookServer(filePath: string): ModifyOutcome {\n if (!fs.existsSync(filePath)) {\n return { status: \"success\", changed: false };\n }\n const original = fs.readFileSync(filePath, \"utf8\");\n if (!original.includes(\"handleCheckoutSessionCompleted\")) {\n return { status: \"success\", changed: false };\n }\n\n const { source } = withInMemoryScript(original, (sf) => {\n const statement = eventSwitch(sf);\n if (statement) {\n // Each run of order clauses goes with the whitespace before it, so the\n // blank line that separated its neighbours is the one that stays.\n const clauses = statement.getCaseBlock().getClauses();\n const isOrders = (clause: (typeof clauses)[number]) => {\n if (!Node.isCaseClause(clause)) return false;\n const expression = clause.getExpression();\n return (\n Node.isStringLiteral(expression) &&\n EVENTS.includes(expression.getLiteralText())\n );\n };\n // Positions first, bottom-up: removing text forgets the nodes after it.\n const ranges: [number, number][] = [];\n for (let i = clauses.length - 1; i >= 0; i--) {\n if (!isOrders(clauses[i])) continue;\n let first = i;\n while (first > 0 && isOrders(clauses[first - 1])) first--;\n const start =\n first > 0 ? clauses[first - 1].getEnd() : clauses[first].getStart();\n ranges.push([start, clauses[i].getEnd()]);\n i = first;\n }\n for (const [start, end] of ranges) sf.removeText(start, end);\n }\n removeImportByModuleSpecifier(sf, COMPLETED);\n removeImportByModuleSpecifier(sf, ASYNC_PAYMENT);\n formatLikeSource(sf);\n });\n fs.writeFileSync(filePath, source, \"utf8\");\n return { status: \"success\", changed: source !== original };\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport { languageFromPath } from \"../../../core/util\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { modifyWebhookServer } from \"./modifies/modify-webhook-server\";\nimport { addItemToNavUser } from \"../payments/modifies/modify-nav-user\";\nimport successServer from \"./preview-modifies/src/routes/(public)/checkout/success/+page.server.ts?raw\";\nimport successSvelte from \"./preview-modifies/src/routes/(public)/checkout/success/+page.svelte?raw\";\n\n/** The success page, which enable-ecommerce wrote and this pattern rewrites to show the order. */\nexport const SUCCESS_PAGE = \"src/routes/(public)/checkout/success\";\n\nconst NAV_USER = path.join(\"src\", \"lib\", \"components\", \"nav-user.svelte\");\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const modifies: File[] = [];\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n logger.info(\n \"Routing the Checkout Session events in webhooks/stripe/handlers/dispatch.ts\",\n );\n const dispatchPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"webhooks\",\n \"stripe\",\n \"handlers\",\n \"dispatch.ts\",\n );\n pushResult(\n modifyOutcomeToFile(dispatchPath, modifyWebhookServer(dispatchPath)),\n );\n\n // A rewrite rather than an edit: the page's load changes shape (the order\n // and its lines, then Stripe's summary as the fallback).\n logger.info(\"Showing the order on /checkout/success\");\n for (const [name, content] of [\n [\"+page.server.ts\", successServer],\n [\"+page.svelte\", successSvelte],\n ] as const) {\n const file = path.join(options.root, SUCCESS_PAGE, name);\n if (fs.existsSync(file) && fs.readFileSync(file, \"utf8\") === content)\n continue;\n modifies.push({\n path: file,\n language: languageFromPath(file),\n content,\n status: \"success\",\n });\n }\n\n if (options.features.auth) {\n logger.info(\"Adding Orders to the user menu\");\n const navUserPath = path.join(options.root, NAV_USER);\n if (fs.existsSync(navUserPath)) {\n const source = fs.readFileSync(navUserPath, \"utf8\");\n if (!source.includes(\"'/orders'\")) {\n const { newNavUserSnippet, wasAdded } = addItemToNavUser(\n source,\n \"Orders\",\n \"/orders\",\n \"PackageIcon\",\n \"@lucide/svelte/icons/package\",\n );\n if (wasAdded) {\n fs.writeFileSync(navUserPath, newNavUserSnippet, \"utf8\");\n modifies.push({\n path: navUserPath,\n language: languageFromPath(navUserPath),\n content: newNavUserSnippet,\n status: \"success\",\n });\n } else {\n modifies.push({\n path: navUserPath,\n language: languageFromPath(navUserPath),\n content: source,\n status: \"failed\",\n message:\n \"Add an Orders item to the navUser array in nav-user.svelte:\\n\\n\" +\n \"import PackageIcon from '@lucide/svelte/icons/package';\\n\" +\n \"{ title: 'Orders', url: '/orders', icon: PackageIcon }\",\n });\n }\n }\n }\n }\n\n return {\n creates: [],\n modifies,\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n } satisfies Result;\n}\n"],"mappings":";;;;;;;;;;;AAWA,IAAMe,IAAY,wBACZC,IAAgB,4BAGhBC,IAAS;CACb;CACA;CACA;AACF,GAEMC,IAAgB,CAAM;;;;;;;;;GAWtBC,IAAe,CAAM;;;oDAGyBJ,EA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BmD,CAAW;KACtC,SAASE;KACT,QAAQ;IACV,CAAC,KAEDR,EAAS,KAAK;KACZ,MAAMM;KACN,UAAUnD,EAAiBmD,CAAW;KACtC,SAASrB;KACT,QAAQ;KACR,SACE;IAGJ,CAAC;GAEL;EACF;CACF;CAEA,OAAO;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-jIlQ2GMh.js","names":["successServer","successSvelte","getLogger","languageFromPath","modifyOutcomeToFile","dedent","withInMemoryScript","formatLikeSource","ensureImports","removeImportByModuleSpecifier","addItemToNavUser","_page_server_default","_page_default","fs","path","COMPLETED","ASYNC_PAYMENT","EVENTS","CASES_SNIPPET","FAILURE_HINT","NOT_FOUND_HINT","eventSwitch","sf","SyntaxKind","statement","modifyWebhookServer","filePath","original","added","clauses","defaultClause","Node","last","source","unmodifyWebhookServer","isOrders","clause","expression","ranges","i","first","start","end","SUCCESS_PAGE","NAV_USER","generate","logger","options","modifies","pushResult","file","dispatchPath","name","content","navUserPath","wasAdded","newNavUserSnippet"],"sources":["../../src/patterns/enable/orders/modifies/modify-webhook-server.ts","../../src/patterns/enable/orders/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { Node, SyntaxKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport {\n ensureImports,\n formatLikeSource,\n removeImportByModuleSpecifier,\n withInMemoryScript,\n} from \"../../../../runtime/ts-morph-helpers\";\n\nconst COMPLETED = \"./checkout/completed\";\nconst ASYNC_PAYMENT = \"./checkout/async-payment\";\n\n/** The Checkout Session events the order handlers take. */\nconst EVENTS = [\n \"checkout.session.completed\",\n \"checkout.session.async_payment_succeeded\",\n \"checkout.session.async_payment_failed\",\n];\n\nconst CASES_SNIPPET = dedent`\n case 'checkout.session.completed':\n await handleCheckoutSessionCompleted(event.data.object, locals);\n break;\n\n case 'checkout.session.async_payment_succeeded':\n case 'checkout.session.async_payment_failed':\n await handleCheckoutAsyncPayment(event.data.object, locals);\n break;\n`;\n\nconst FAILURE_HINT = dedent`\n Route the Checkout Session events to the order handlers in src/routes/webhooks/stripe/handlers/dispatch.ts:\n\n import { handleCheckoutSessionCompleted } from '${COMPLETED}';\n import { handleCheckoutAsyncPayment } from '${ASYNC_PAYMENT}';\n\n and, inside the \\`switch (event.type)\\`:\n\n ${CASES_SNIPPET.split(\"\\n\").join(\"\\n \")}\n`;\n\nconst NOT_FOUND_HINT =\n \"Enable payments first: src/routes/webhooks/stripe/handlers/dispatch.ts is created by enable-payments.\";\n\n/** The `switch (event.type)` the dispatcher routes on. */\nfunction eventSwitch(sf: import(\"ts-morph\").SourceFile) {\n return sf\n .getDescendantsOfKind(SyntaxKind.SwitchStatement)\n .find((statement) =>\n statement.getExpression().getText().includes(\"event.type\"),\n );\n}\n\n/** The order handlers join the dispatcher's switch, ahead of its default. */\nexport function modifyWebhookServer(filePath: string): 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(\"handleCheckoutSessionCompleted\")) {\n return { status: \"success\", changed: false };\n }\n\n let added = false;\n const { source } = withInMemoryScript(original, (sf) => {\n const statement = eventSwitch(sf);\n if (!statement) return;\n const clauses = statement.getCaseBlock().getClauses();\n const defaultClause = clauses.find(Node.isDefaultClause);\n if (defaultClause) {\n defaultClause.replaceWithText(\n `${CASES_SNIPPET}\\n\\n${defaultClause.getText()}`,\n );\n } else if (clauses.length > 0) {\n const last = clauses[clauses.length - 1];\n last.replaceWithText(`${last.getText()}\\n\\n${CASES_SNIPPET}`);\n } else {\n return;\n }\n ensureImports(sf, [\n {\n namedImports: [\"handleCheckoutSessionCompleted\"],\n moduleSpecifier: COMPLETED,\n },\n {\n namedImports: [\"handleCheckoutAsyncPayment\"],\n moduleSpecifier: ASYNC_PAYMENT,\n },\n ]);\n formatLikeSource(sf);\n added = true;\n });\n if (!added) return { status: \"failed\", message: FAILURE_HINT };\n fs.writeFileSync(filePath, source, \"utf8\");\n return { status: \"success\", changed: true };\n}\n\n/** Take the order cases and their imports back out of the dispatcher. */\nexport function unmodifyWebhookServer(filePath: string): ModifyOutcome {\n if (!fs.existsSync(filePath)) {\n return { status: \"success\", changed: false };\n }\n const original = fs.readFileSync(filePath, \"utf8\");\n if (!original.includes(\"handleCheckoutSessionCompleted\")) {\n return { status: \"success\", changed: false };\n }\n\n const { source } = withInMemoryScript(original, (sf) => {\n const statement = eventSwitch(sf);\n if (statement) {\n // Each run of order clauses goes with the whitespace before it, so the\n // blank line that separated its neighbours is the one that stays.\n const clauses = statement.getCaseBlock().getClauses();\n const isOrders = (clause: (typeof clauses)[number]) => {\n if (!Node.isCaseClause(clause)) return false;\n const expression = clause.getExpression();\n return (\n Node.isStringLiteral(expression) &&\n EVENTS.includes(expression.getLiteralText())\n );\n };\n // Positions first, bottom-up: removing text forgets the nodes after it.\n const ranges: [number, number][] = [];\n for (let i = clauses.length - 1; i >= 0; i--) {\n if (!isOrders(clauses[i])) continue;\n let first = i;\n while (first > 0 && isOrders(clauses[first - 1])) first--;\n const start =\n first > 0 ? clauses[first - 1].getEnd() : clauses[first].getStart();\n ranges.push([start, clauses[i].getEnd()]);\n i = first;\n }\n for (const [start, end] of ranges) sf.removeText(start, end);\n }\n removeImportByModuleSpecifier(sf, COMPLETED);\n removeImportByModuleSpecifier(sf, ASYNC_PAYMENT);\n formatLikeSource(sf);\n });\n fs.writeFileSync(filePath, source, \"utf8\");\n return { status: \"success\", changed: source !== original };\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport { languageFromPath } from \"../../../core/util\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { modifyWebhookServer } from \"./modifies/modify-webhook-server\";\nimport { addItemToNavUser } from \"../payments/modifies/modify-nav-user\";\nimport successServer from \"./preview-modifies/src/routes/(public)/checkout/success/+page.server.ts?raw\";\nimport successSvelte from \"./preview-modifies/src/routes/(public)/checkout/success/+page.svelte?raw\";\n\n/** The success page, which enable-ecommerce wrote and this pattern rewrites to show the order. */\nexport const SUCCESS_PAGE = \"src/routes/(public)/checkout/success\";\n\nconst NAV_USER = path.join(\"src\", \"lib\", \"components\", \"nav-user.svelte\");\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const modifies: File[] = [];\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n logger.info(\n \"Routing the Checkout Session events in webhooks/stripe/handlers/dispatch.ts\",\n );\n const dispatchPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"webhooks\",\n \"stripe\",\n \"handlers\",\n \"dispatch.ts\",\n );\n pushResult(\n modifyOutcomeToFile(dispatchPath, modifyWebhookServer(dispatchPath)),\n );\n\n // A rewrite rather than an edit: the page's load changes shape (the order\n // and its lines, then Stripe's summary as the fallback).\n logger.info(\"Showing the order on /checkout/success\");\n for (const [name, content] of [\n [\"+page.server.ts\", successServer],\n [\"+page.svelte\", successSvelte],\n ] as const) {\n const file = path.join(options.root, SUCCESS_PAGE, name);\n if (fs.existsSync(file) && fs.readFileSync(file, \"utf8\") === content)\n continue;\n modifies.push({\n path: file,\n language: languageFromPath(file),\n content,\n status: \"success\",\n });\n }\n\n if (options.features.auth) {\n logger.info(\"Adding Orders to the user menu\");\n const navUserPath = path.join(options.root, NAV_USER);\n if (fs.existsSync(navUserPath)) {\n const source = fs.readFileSync(navUserPath, \"utf8\");\n if (!source.includes(\"'/orders'\")) {\n const { newNavUserSnippet, wasAdded } = addItemToNavUser(\n source,\n \"Orders\",\n \"/orders\",\n \"PackageIcon\",\n \"@lucide/svelte/icons/package\",\n );\n if (wasAdded) {\n fs.writeFileSync(navUserPath, newNavUserSnippet, \"utf8\");\n modifies.push({\n path: navUserPath,\n language: languageFromPath(navUserPath),\n content: newNavUserSnippet,\n status: \"success\",\n });\n } else {\n modifies.push({\n path: navUserPath,\n language: languageFromPath(navUserPath),\n content: source,\n status: \"failed\",\n message:\n \"Add an Orders item to the navUser array in nav-user.svelte:\\n\\n\" +\n \"import PackageIcon from '@lucide/svelte/icons/package';\\n\" +\n \"{ title: 'Orders', url: '/orders', icon: PackageIcon }\",\n });\n }\n }\n }\n }\n\n return {\n creates: [],\n modifies,\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n } satisfies Result;\n}\n"],"mappings":";;;;;;;;;;;AAWA,IAAMe,IAAY,wBACZC,IAAgB,4BAGhBC,IAAS;CACb;CACA;CACA;AACF,GAEMC,IAAgB,CAAM;;;;;;;;;GAWtBC,IAAe,CAAM;;;oDAGyBJ,EAAU;gDACdC,EAAc;;;;IAI1DE,EAAc,MAAM,IAAI,CAAC,CAAC,KAAK,MAAM,EAAE;GAGrCE,IACJ;AAGF,SAASC,EAAY,GAAmC;CACtD,OAAOC,EACJ,qBAAqBC,EAAW,eAAe,CAAC,CAChD,MAAM,MACLC,EAAU,cAAc,CAAC,CAAC,QAAQ,CAAC,CAAC,SAAS,YAAY,CAC3D;AACJ;AAGA,SAAgBC,EAAoB,GAAiC;CACnE,IAAI,CAACZ,EAAG,WAAWa,CAAQ,GACzB,OAAO;EAAE,QAAQ;EAAa,SAASN;CAAe;CAExD,IAAMO,IAAWd,EAAG,aAAaa,GAAU,MAAM;CACjD,IAAIC,EAAS,SAAS,gCAAgC,GACpD,OAAO;EAAE,QAAQ;EAAW,SAAS;CAAM;CAG7C,IAAIC,IAAQ,IACN,EAAE,cAAWtB,EAAmBqB,IAAW,MAAO;EACtD,IAAMH,IAAYH,EAAYC,CAAE;EAChC,IAAI,CAACE,GAAW;EAChB,IAAMK,IAAUL,EAAU,aAAa,CAAC,CAAC,WAAW,GAC9CM,IAA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,KAAKrC,EAAG,aAAaqC,GAAM,MAAM,MAAMG,KAE7DL,EAAS,KAAK;GACZ,MAAME;GACN,UAAU/C,EAAiB+C,CAAI;GAC/B;GACA,QAAQ;EACV,CAAC;CACH;CAEA,IAAIH,EAAQ,SAAS,MAAM;EACzB,EAAO,KAAK,gCAAgC;EAC5C,IAAMO,IAAcxC,EAAK,KAAKiC,EAAQ,MAAMH,CAAQ;EACpD,IAAI/B,EAAG,WAAWyC,CAAW,GAAG;GAC9B,IAAMrB,IAASpB,EAAG,aAAayC,GAAa,MAAM;GAClD,IAAI,CAACrB,EAAO,SAAS,WAAW,GAAG;IACjC,IAAM,EAAE,sBAAmB,gBAAavB,EACtCuB,GACA,UACA,WACA,eACA,8BACF;IACA,AAAIsB,KACF1C,EAAG,cAAcyC,GAAaE,GAAmB,MAAM,GACvDR,EAAS,KAAK;KACZ,MAAMM;KACN,UAAUnD,EAAiBmD,CAAW;KACtC,SAASE;KACT,QAAQ;IACV,CAAC,KAEDR,EAAS,KAAK;KACZ,MAAMM;KACN,UAAUnD,EAAiBmD,CAAW;KACtC,SAASrB;KACT,QAAQ;KACR,SACE;IAGJ,CAAC;GAEL;EACF;CACF;CAEA,OAAO;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,16 +1,16 @@
|
|
|
1
|
-
import { a as e, n as t, r as n, t as r } from "./currency.server-
|
|
1
|
+
import { a as e, n as t, r as n, t as r } from "./currency.server-CHzEhyTx.js";
|
|
2
2
|
import { n as i } from "./logger-t1HxmpG2.js";
|
|
3
3
|
import { a, c as o, l as s } from "./providers-DrK_hjSr.js";
|
|
4
4
|
import { o as c, r as l } from "./util-mXrQ89nG.js";
|
|
5
|
-
import { modifyEnvVarsFiles as u } from "./env-vars-
|
|
6
|
-
import { r as d } from "./modify-file-
|
|
5
|
+
import { modifyEnvVarsFiles as u } from "./env-vars-C3TSZc4f.js";
|
|
6
|
+
import { r as d } from "./modify-file-BOEKlIDw.js";
|
|
7
7
|
import { t as f } from "./env-AxyRWcC_.js";
|
|
8
|
-
import { a as p, i as m, r as h, s as g, t as _ } from "./site-
|
|
8
|
+
import { a as p, i as m, r as h, s as g, t as _ } from "./site-B5zrFba9.js";
|
|
9
9
|
import { a as v, r as y, s as b, t as x } from "./root-layout.svelte-DE0c_y-T.js";
|
|
10
10
|
import { a as S, i as C, r as w } from "./collections-CFW9ZqUE.js";
|
|
11
11
|
import { t as T } from "./dedent-CCUOcPFW.js";
|
|
12
|
-
import { i as E, n as D, t as O } from "./pocketbase-
|
|
13
|
-
import { a as k, i as A, r as j } from "./collections-
|
|
12
|
+
import { i as E, n as D, t as O } from "./pocketbase-B2ksFrvH.js";
|
|
13
|
+
import { a as k, i as A, r as j } from "./collections-Daxlnbm0.js";
|
|
14
14
|
import { n as M } from "./modify-nav-user-D42kWyU6.js";
|
|
15
15
|
import { t as N } from "./modify-user-signup-ENhadGKH.js";
|
|
16
16
|
import { t as P } from "./taggedTemplateLiteral-CLenToGE.js";
|
|
@@ -489,4 +489,4 @@ async function $(t) {
|
|
|
489
489
|
}
|
|
490
490
|
export { $ as generate, Q as hasVitest };
|
|
491
491
|
|
|
492
|
-
//# sourceMappingURL=generate.runtime-
|
|
492
|
+
//# sourceMappingURL=generate.runtime-sey-wxXB.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"generate.runtime-ufoTIUXA.js","names":["__import_glob__0_0_","__import_glob__0_1_","envEditsFor","currency_server_test_default","META","currency_server_default","getLogger","resolveProvider","suppliedProviderEnv","mergeResults","filesFromGlob","modifyOutcomeToFile","modifyEnv","normalizeCurrency","normalizeCurrencies","normalizeCountry","sitePath","ensureSiteBusiness","modifyLayoutServerCurrency","modifyLayoutSvelteCurrency","modifyHooksServerCurrency","modifyRootLayoutCurrencySelect","buyPageSnippet","STRIPE_PRODUCTS","STRIPE_PRICES","dedent","withPocketbase","migrationDelay","getMigrationFile","readMigration","ensureCollectionFields","createCollectionIdempotent","modifyNavUser","modifyUserSignup","_taggedTemplateLiteral","InvalidArgumentError","modifyWuchaleJsFiles","TRANSLATED_LIB_FILES","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","unitTests","a","b","hasVitest","pkg","root","generate","provider","envPath","envVars","modifyEnvVarsFiles","providerEnvVars","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 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 {\n getMigrationFile,\n migrationDelay,\n withPocketbase,\n} from \"../../../../runtime/pocketbase\";\nimport {\n createCollectionIdempotent,\n ensureCollectionFields,\n readMigration,\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(await readMigration(migrationFile, options));\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,IAASpC,EAAUqC,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,SAASvB,EAAesB,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,WAAW,kBAAkB,CAAC,CAC9B,YAA0C,GACvCE,IAAgB,IAAI,IAAID,EAAS,KAAK,MAAME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O,IAC1B,MAAMmD,EAAcnD,GAASoD,CAAQ;CAE7C,OAAOtF,EAAa,CAACkH,GAAKC,CAAK,CAAC;AAClC"}
|
|
1
|
+
{"version":3,"file":"generate.runtime-sey-wxXB.js","names":["__import_glob__0_0_","__import_glob__0_1_","envEditsFor","currency_server_test_default","META","currency_server_default","getLogger","resolveProvider","suppliedProviderEnv","mergeResults","filesFromGlob","modifyOutcomeToFile","modifyEnv","normalizeCurrency","normalizeCurrencies","normalizeCountry","sitePath","ensureSiteBusiness","modifyLayoutServerCurrency","modifyLayoutSvelteCurrency","modifyHooksServerCurrency","modifyRootLayoutCurrencySelect","buyPageSnippet","STRIPE_PRODUCTS","STRIPE_PRICES","dedent","withPocketbase","migrationDelay","getMigrationFile","readMigration","ensureCollectionFields","createCollectionIdempotent","modifyNavUser","modifyUserSignup","_taggedTemplateLiteral","InvalidArgumentError","modifyWuchaleJsFiles","TRANSLATED_LIB_FILES","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","unitTests","a","b","hasVitest","pkg","root","generate","provider","envPath","envVars","modifyEnvVarsFiles","providerEnvVars","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 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 {\n getMigrationFile,\n migrationDelay,\n withPocketbase,\n} from \"../../../../runtime/pocketbase\";\nimport {\n createCollectionIdempotent,\n ensureCollectionFields,\n readMigration,\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(await readMigration(migrationFile, options));\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,IAASpC,EAAUqC,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,SAASvB,EAAesB,CAAS;EACjC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ACA,gBACF;GACA,EACEhC,EACE+G,GACAvG,EAA2BuG,CAAc,CAC3C,CACF;GACA,KAAK,IAAMvC,KAAQiB,EAAcI,EAAU7D,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,IACJhB,EAAS,OAAO,WACZ,MAAM9B,EAAYnC,CAAO,IACzBiE,EAAS,OAAO,YACd,MAAMnE,EAAaE,CAAO,IAC1B,MAAMmD,EAAcnD,GAASoD,CAAQ;CAE7C,OAAOtF,EAAa,CAACkH,GAAKC,CAAK,CAAC;AAClC"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { n as e } from "./logger-t1HxmpG2.js";
|
|
2
|
-
import { r as t } from "./modify-file-
|
|
2
|
+
import { r as t } from "./modify-file-BOEKlIDw.js";
|
|
3
3
|
import { t as n } from "./dedent-CCUOcPFW.js";
|
|
4
4
|
import { o as r } from "./ts-morph-helpers-B4KZXP44.js";
|
|
5
5
|
import i from "node:fs";
|
|
@@ -82,4 +82,4 @@ async function d(n) {
|
|
|
82
82
|
}
|
|
83
83
|
export { d as generate };
|
|
84
84
|
|
|
85
|
-
//# sourceMappingURL=generate.runtime-
|
|
85
|
+
//# sourceMappingURL=generate.runtime-v3KCv1B6.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"generate.runtime-
|
|
1
|
+
{"version":3,"file":"generate.runtime-v3KCv1B6.js","names":["getLogger","modifyOutcomeToFile","dedent","formatLikeSource","fs","path","FAILURE_HINT","NOT_FOUND_HINT","modifyHooksServer","hooksServerPath","originalSource","sourceFile","Project","callExpr","SyntaxKind","ce","args","firstArg","optionsObj","apiProp","apiInit","apiObj","generate","logger","options","modifies","file"],"sources":["../../src/patterns/enable/api/modifies/hooks.server.ts","../../src/patterns/enable/api/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { Project, SyntaxKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport { formatLikeSource } from \"../../../../runtime/ts-morph-helpers\";\n\nconst FAILURE_HINT = dedent`\n Configure handlePocketbase() with the api option in hooks.server.ts:\n\n handlePocketbase({\n api: { enabled: true },\n });\n`;\n\nconst NOT_FOUND_HINT = dedent`\n Create src/hooks.server.ts with handlePocketbase:\n\n import { handlePocketbase } from 'velastack/handle';\n\n export const handle = handlePocketbase({\n api: { enabled: true },\n });\n`;\n\nexport function modifyHooksServer(hooksServerPath: string): ModifyOutcome {\n if (!fs.existsSync(hooksServerPath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const originalSource = fs.readFileSync(hooksServerPath, \"utf8\");\n const project = new Project();\n const sourceFile = project.addSourceFileAtPath(hooksServerPath);\n\n const callExpr = sourceFile\n .getDescendantsOfKind(SyntaxKind.CallExpression)\n .find((ce) => ce.getExpression().getText() === \"handlePocketbase\");\n\n if (!callExpr) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n const args = callExpr.getArguments();\n if (args.length === 0) {\n callExpr.addArgument(`{ api: { enabled: true } }`);\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n }\n\n const firstArg = args[0];\n if (firstArg.getKind() !== SyntaxKind.ObjectLiteralExpression) {\n callExpr.insertArgument(0, `{ api: { enabled: true } }`);\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n }\n\n const optionsObj = firstArg.asKindOrThrow(SyntaxKind.ObjectLiteralExpression);\n const apiProp = optionsObj.getProperty(\"api\");\n\n if (!apiProp) {\n optionsObj.addPropertyAssignment({\n name: \"api\",\n initializer: `{ enabled: true }`,\n });\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n }\n\n if (apiProp.getKind() === SyntaxKind.PropertyAssignment) {\n const apiInit = (\n apiProp as import(\"ts-morph\").PropertyAssignment\n ).getInitializer();\n if (apiInit && apiInit.getKind() === SyntaxKind.ObjectLiteralExpression) {\n const apiObj = apiInit as import(\"ts-morph\").ObjectLiteralExpression;\n const enabledProp = apiObj.getProperty(\"enabled\");\n if (!enabledProp) {\n apiObj.addPropertyAssignment({ name: \"enabled\", initializer: \"true\" });\n }\n }\n }\n\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return {\n status: \"success\",\n changed: sourceFile.getFullText() !== originalSource,\n };\n}\n","import path from \"node:path\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { modifyHooksServer } from \"./modifies/hooks.server\";\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const modifies: File[] = [];\n\n logger.info(\"Modifying hooks.server.ts\");\n const hooksServerPath = path.join(options.root, \"src\", \"hooks.server.ts\");\n const file = modifyOutcomeToFile(\n hooksServerPath,\n modifyHooksServer(hooksServerPath),\n );\n if (file) modifies.push(file);\n\n return {\n creates: [],\n modifies,\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n } satisfies Result;\n}\n"],"mappings":";;;;;;;;AAMA,IAAMM,IAAe,CAAM;;;;;;GAQrBC,IAAiB,CAAM;;;;;;;;;AAU7B,SAAgBC,EAAkB,GAAwC;CACxE,IAAI,CAACJ,EAAG,WAAWK,CAAe,GAChC,OAAO;EAAE,QAAQ;EAAa,SAASF;CAAe;CAGxD,IAAMG,IAAiBN,EAAG,aAAaK,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,k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,EACXQ,GACAD,EAAkBC,CAAe,CACnC;CAGA,OAFIiB,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,8 +1,8 @@
|
|
|
1
1
|
import { n as e } from "./logger-t1HxmpG2.js";
|
|
2
|
-
import { r as t } from "./modify-file-
|
|
2
|
+
import { r as t } from "./modify-file-BOEKlIDw.js";
|
|
3
3
|
import { t as n } from "./dedent-CCUOcPFW.js";
|
|
4
4
|
import { o as r } from "./ts-morph-helpers-B4KZXP44.js";
|
|
5
|
-
import { modifyEnvVarsFiles as i } from "./env-vars-
|
|
5
|
+
import { modifyEnvVarsFiles as i } from "./env-vars-C3TSZc4f.js";
|
|
6
6
|
import { t as a } from "./env-vars-T3_7JNSg.js";
|
|
7
7
|
import o from "node:fs";
|
|
8
8
|
import s from "node:path";
|
|
@@ -83,4 +83,4 @@ async function g(n) {
|
|
|
83
83
|
}
|
|
84
84
|
export { g as generate };
|
|
85
85
|
|
|
86
|
-
//# sourceMappingURL=generate.runtime-
|
|
86
|
+
//# sourceMappingURL=generate.runtime-xrxAElb3.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"generate.runtime-
|
|
1
|
+
{"version":3,"file":"generate.runtime-xrxAElb3.js","names":["getLogger","modifyOutcomeToFile","dedent","formatLikeSource","WORKFLOWS_ENV_VARS","fs","path","INIT_SNIPPET","FAILURE_HINT","NOT_FOUND_HINT","ensureNamedImport","existing","sourceFile","d","moduleSpecifier","ni","name","typeOnly","hasInitExport","modifyHooksServerWorkflows","hooksServerPath","Project","QuoteKind","generate","logger","options","creates","modifies","hooksFile","envVars","modifyEnvVarsFiles"],"sources":["../../src/patterns/enable/workflows/modifies/hooks.server.ts","../../src/patterns/enable/workflows/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { Project, QuoteKind, type SourceFile } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport { formatLikeSource } from \"../../../../runtime/ts-morph-helpers\";\n\nconst INIT_SNIPPET = dedent`\n // Runs once when the server starts: executes the workflows in src/lib/workflows.\n export const init: ServerInit = () => startWorker();\n`;\n\nconst FAILURE_HINT = dedent`\n src/hooks.server.ts already exports an init hook. Start the workflow worker from it:\n\n import { startWorker } from '#lib/server/workflows.js';\n\n export const init: ServerInit = async () => {\n await startWorker();\n // ...the rest of your init\n };\n`;\n\nconst NOT_FOUND_HINT = dedent`\n Create src/hooks.server.ts and start the workflow worker from its init hook:\n\n import type { ServerInit } from '@sveltejs/kit/hooks';\n import { startWorker } from '#lib/server/workflows.js';\n\n export const init: ServerInit = () => startWorker();\n`;\n\nfunction ensureNamedImport(\n sourceFile: SourceFile,\n moduleSpecifier: string,\n name: string,\n typeOnly = false,\n) {\n const existing = sourceFile\n .getImportDeclarations()\n .find((d) => d.getModuleSpecifierValue() === moduleSpecifier);\n if (!existing) {\n sourceFile.addImportDeclaration({\n isTypeOnly: typeOnly,\n namedImports: [name],\n moduleSpecifier,\n });\n return;\n }\n if (existing.getNamedImports().some((ni) => ni.getName() === name)) return;\n // A declaration that is already `import type` covers the new name; a value\n // import takes the name as an inline `type` specifier.\n existing.addNamedImport(\n typeOnly && !existing.isTypeOnly() ? { name, isTypeOnly: true } : name,\n );\n}\n\nfunction hasInitExport(sourceFile: SourceFile): boolean {\n if (sourceFile.getVariableDeclaration(\"init\")) return true;\n if (sourceFile.getFunction(\"init\")) return true;\n return sourceFile\n .getExportDeclarations()\n .some((d) => d.getNamedExports().some((e) => e.getName() === \"init\"));\n}\n\n/**\n * Adds the `init` hook that starts the workflow worker. Projects created from\n * the base template already have it; this is the upgrade path for older ones.\n */\nexport function modifyHooksServerWorkflows(\n hooksServerPath: string,\n): ModifyOutcome {\n if (!fs.existsSync(hooksServerPath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const original = fs.readFileSync(hooksServerPath, \"utf8\");\n if (original.includes(\"startWorker\")) {\n return { status: \"success\", changed: false };\n }\n\n const project = new Project({\n compilerOptions: { allowJs: true },\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n const sourceFile = project.addSourceFileAtPath(hooksServerPath);\n\n if (hasInitExport(sourceFile)) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n ensureNamedImport(sourceFile, \"@sveltejs/kit/hooks\", \"ServerInit\", true);\n ensureNamedImport(sourceFile, \"#lib/server/workflows.js\", \"startWorker\");\n\n // After everything else, so the hook reads as the last thing the server does on start.\n sourceFile.addStatements(`\\n${INIT_SNIPPET}`);\n\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n}\n","import path from \"node:path\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { modifyHooksServerWorkflows } from \"./modifies/hooks.server\";\nimport { modifyEnvVarsFiles } from \"../../../runtime/env-vars\";\nimport { WORKFLOWS_ENV_VARS } from \"./env-vars\";\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const creates: File[] = [];\n const modifies: File[] = [];\n\n logger.info(\"Modifying hooks.server.ts\");\n const hooksServerPath = path.join(options.root, \"src\", \"hooks.server.ts\");\n const hooksFile = modifyOutcomeToFile(\n hooksServerPath,\n modifyHooksServerWorkflows(hooksServerPath),\n );\n if (hooksFile) modifies.push(hooksFile);\n\n // SvelteKit 3 exposes only declared variables; the template declares these\n // already, an older project gets whichever it is missing.\n logger.info(\"Declaring the workflow variables in src/env.ts\");\n const envVars = modifyEnvVarsFiles(options.root, WORKFLOWS_ENV_VARS);\n if (envVars.create) creates.push(envVars.create);\n if (envVars.modify) modifies.push(envVars.modify);\n\n return {\n creates,\n modifies,\n deletes: [],\n components: [],\n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c,EAAI,GACvEF,EAAkBE,GAAY,4BAA4B,aAAa,GAGvEA,EAAW,cAAc,KAAKL,GAAc,GAE5CJ,EAAiBS,CAAU,GAC3BA,EAAW,SAAS,GACb;EAAE,QAAQ;EAAW,SAAS;CAAK;AAC5C;;AC3FA,eAAsBW,EAAS,GAAkB;CAC/C,IAAMC,IAASxB,EAAUyB,CAAO,GAC1BC,IAAkB,CAAC,GACnBC,IAAmB,CAAC;CAE1B,EAAO,KAAK,2BAA2B;CACvC,IAAMP,IAAkBd,EAAK,KAAKmB,EAAQ,MAAM,OAAO,iBAAiB,GAClEG,IAAY3B,EAChBmB,GACAD,EAA2BC,CAAe,CAC5C;CAKA,AAJIQ,KAAWD,EAAS,KAAKC,CAAS,GAItCJ,EAAO,KAAK,gDAAgD;CAC5D,IAAMK,IAAUC,EAAmBL,EAAQ,MAAMrB,CAAkB;CAInE,OAHIyB,EAAQ,UAAQH,EAAQ,KAAKG,EAAQ,MAAM,GAC3CA,EAAQ,UAAQF,EAAS,KAAKE,EAAQ,MAAM,GAEzC;EACL;EACA;EACA,SAAS,CAAC;EACV,YAAY,CAAC;EACb,UAAU,CAAC;EACX,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAiB,CAAC;CACpB;AACF"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { n as e, t } from "./constants-
|
|
1
|
+
import { n as e, t } from "./constants-E1I-__KI.js";
|
|
2
2
|
import { t as n } from "./dedent-CCUOcPFW.js";
|
|
3
3
|
import { o as r, s as i } from "./config-target-DJbVHwHl.js";
|
|
4
|
-
import { c as a } from "./write-result-
|
|
4
|
+
import { c as a } from "./write-result-DlB-id5k.js";
|
|
5
5
|
import o from "node:fs";
|
|
6
6
|
import { SyntaxKind as s } from "ts-morph";
|
|
7
7
|
// src/patterns/enable/backend/modifies/svelte-config.ts
|
|
@@ -136,4 +136,4 @@ function b(e) {
|
|
|
136
136
|
}
|
|
137
137
|
export { g as i, b as n, h as r, y as t };
|
|
138
138
|
|
|
139
|
-
//# sourceMappingURL=gitignore-
|
|
139
|
+
//# sourceMappingURL=gitignore-CBiWFRif.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"gitignore-
|
|
1
|
+
{"version":3,"file":"gitignore-CBiWFRif.js","names":["ADAPTER_NODE_SPEC","ADAPTER_STATIC_SPEC","NOT_FOUND_HINT","ADAPTER_STATIC$1","dedent","resolveConfigTarget","saveTarget","packageName","fs","ADAPTER_NODE","ADAPTER_NODE$1","ADAPTER_STATIC","ADAPTER_AUTO","FAILURE_HINT","NOT_FOUND_HINT$1","findAdapterImport","sourceFile","decl","adapterCalls","SyntaxKind","ce","modifySvelteConfig","res","root","adapterImport","target","call","args","i","unmodifySvelteConfig","POCKETBASE_BLOCK","NOT_FOUND_HINT","modifyGitignore","gitignorePath","original","next","unmodifyGitignore","cleaned"],"sources":["../../src/patterns/enable/backend/modifies/svelte-config.ts","../../src/patterns/enable/backend/modifies/gitignore.ts"],"sourcesContent":["import dedent from \"dedent\";\nimport { SyntaxKind } from \"ts-morph\";\nimport {\n resolveConfigTarget,\n saveTarget,\n type ConfigModifyResult,\n type ConfigTarget,\n} from \"../../../../runtime/config-target\";\nimport { packageName } from \"../../../../runtime/write-result\";\nimport {\n ADAPTER_NODE as ADAPTER_NODE_SPEC,\n ADAPTER_STATIC as ADAPTER_STATIC_SPEC,\n} from \"../../../../core/constants\";\n\n// Imports name the package, not the versioned spec the constants install.\nconst ADAPTER_NODE = packageName(ADAPTER_NODE_SPEC);\nconst ADAPTER_STATIC = packageName(ADAPTER_STATIC_SPEC);\nconst ADAPTER_AUTO = \"@sveltejs/adapter-auto\";\n\nconst FAILURE_HINT = dedent`\n Switch the SvelteKit adapter to ${ADAPTER_NODE}:\n\n import adapter from '${ADAPTER_NODE}';\n\n // ...\n adapter: adapter()\n`;\n\nconst NOT_FOUND_HINT = dedent`\n Configure ${ADAPTER_NODE} via the sveltekit() plugin in vite.config.ts.\n`;\n\n/**\n * The adapters this pattern moves between. adapter-auto is included because\n * that is what `sv create` ships, and a project that never chose is one the\n * backend is free to decide for.\n */\nfunction findAdapterImport(sourceFile: ConfigTarget[\"sourceFile\"]) {\n return sourceFile\n .getImportDeclarations()\n .find((decl) =>\n [ADAPTER_STATIC, ADAPTER_AUTO, ADAPTER_NODE].includes(\n decl.getModuleSpecifierValue(),\n ),\n );\n}\n\nfunction adapterCalls(sourceFile: ConfigTarget[\"sourceFile\"]) {\n return sourceFile\n .getDescendantsOfKind(SyntaxKind.CallExpression)\n .filter((ce) => ce.getExpression().getText() === \"adapter\");\n}\n\n/**\n * Switch the adapter to `@sveltejs/adapter-node` and drop its arguments in\n * vite.config, which holds the adapter import + `adapter()` call. A project with a\n * backend is served from a Node process, which is what `vela deploy` runs.\n * Operates on the import and call expression directly, so it never needs the\n * config object.\n */\nexport function modifySvelteConfig(root: string): ConfigModifyResult {\n const res = resolveConfigTarget(root, {\n notFound: NOT_FOUND_HINT,\n failed: FAILURE_HINT,\n });\n if (res.status !== \"resolved\") {\n return {\n filePath: res.filePath,\n outcome: { status: res.status, message: res.message },\n };\n }\n const { target } = res;\n const adapterImport = findAdapterImport(target.sourceFile);\n if (!adapterImport) {\n return {\n filePath: target.filePath,\n outcome: { status: \"failed\", message: FAILURE_HINT },\n };\n }\n\n if (adapterImport.getModuleSpecifierValue() !== ADAPTER_NODE) {\n adapterImport.setModuleSpecifier(ADAPTER_NODE);\n }\n\n for (const call of adapterCalls(target.sourceFile)) {\n const args = call.getArguments();\n for (let i = args.length - 1; i >= 0; i--) {\n call.removeArgument(i);\n }\n }\n\n return { filePath: target.filePath, outcome: saveTarget(target) };\n}\n\n/**\n * Reverse of {@link modifySvelteConfig}: switch back to\n * `@sveltejs/adapter-static` and restore the `{ fallback: '200.html' }` arg.\n * Lenient when there is no config or no adapter import: a no-op success. A\n * config that can't be edited (a leftover svelte.config) still fails.\n */\nexport function unmodifySvelteConfig(root: string): ConfigModifyResult {\n const res = resolveConfigTarget(root, {\n notFound: NOT_FOUND_HINT,\n failed: FAILURE_HINT,\n });\n if (res.status === \"not-found\") {\n // Nothing to revert.\n return {\n filePath: res.filePath,\n outcome: { status: \"success\", changed: false },\n };\n }\n if (res.status === \"failed\") {\n return {\n filePath: res.filePath,\n outcome: { status: \"failed\", message: res.message },\n };\n }\n const { target } = res;\n const adapterImport = findAdapterImport(target.sourceFile);\n if (!adapterImport) {\n return {\n filePath: target.filePath,\n outcome: { status: \"success\", changed: false },\n };\n }\n\n if (adapterImport.getModuleSpecifierValue() !== ADAPTER_STATIC) {\n adapterImport.setModuleSpecifier(ADAPTER_STATIC);\n }\n\n for (const call of adapterCalls(target.sourceFile)) {\n if (call.getArguments().length === 0) {\n call.addArgument(\"{ fallback: '200.html' }\");\n }\n }\n\n return { filePath: target.filePath, outcome: saveTarget(target) };\n}\n","import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst POCKETBASE_BLOCK = `# PocketBase\n/data/*\n!/data/fixtures\n!/data/seeds\n!/data/hooks\n`;\n\nconst NOT_FOUND_HINT = dedent`\n Create a .gitignore at the project root with the PocketBase block:\n\n # PocketBase\n /data/*\n !/data/fixtures\n !/data/seeds\n !/data/hooks\n`;\n\nexport function modifyGitignore(gitignorePath: string): ModifyOutcome {\n if (!fs.existsSync(gitignorePath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const original = fs.readFileSync(gitignorePath, \"utf8\");\n\n if (original.includes(\"# PocketBase\") && original.includes(\"/data/*\")) {\n return { status: \"success\", changed: false };\n }\n\n const separator = original.endsWith(\"\\n\") ? \"\\n\" : \"\\n\\n\";\n const next = original + separator + POCKETBASE_BLOCK;\n fs.writeFileSync(gitignorePath, next, \"utf8\");\n\n return { status: \"success\", changed: true };\n}\n\nexport function unmodifyGitignore(gitignorePath: string): ModifyOutcome {\n if (!fs.existsSync(gitignorePath)) {\n return { status: \"success\", changed: false };\n }\n\n const original = fs.readFileSync(gitignorePath, \"utf8\");\n\n if (!original.includes(\"# PocketBase\")) {\n return { status: \"success\", changed: false };\n }\n\n const withBlockRemoved = original.replace(\n /\\n*# PocketBase\\n\\/data\\/\\*\\n!\\/data\\/fixtures\\n!\\/data\\/seeds\\n!\\/data\\/hooks\\n?/,\n \"\\n\",\n );\n\n const cleaned = withBlockRemoved.replace(/\\n{3,}$/, \"\\n\");\n\n if (cleaned === original) {\n return { status: \"success\", changed: false };\n }\n\n fs.writeFileSync(gitignorePath, cleaned, \"utf8\");\n return { status: \"success\", changed: true };\n}\n"],"mappings":";;;;;;;AAeA,IAAMS,IAAeF,EAAYP,CAAiB,GAC5CW,IAAiBJ,EAAYN,CAAmB,GAChDW,IAAe,0BAEfC,IAAe,CAAM;oCACSJ,EAAa;;yBAExBA,EAAa;;;;GAMhCP,IAAiB,CAAM;cACfO,EAAa;;AAQ3B,SAASM,EAAkB,GAAwC;CACjE,OAAOC,EACJ,sBAAsB,CAAC,CACvB,MAAM,MACL;EAACL;EAAgBC;EAAcH;CAAY,CAAC,CAAC,SAC3CQ,EAAK,wBAAwB,CAC/B,CACF;AACJ;AAEA,SAASC,EAAa,GAAwC;CAC5D,OAAOF,EACJ,qBAAqBG,EAAW,cAAc,CAAC,CAC/C,QAAQ,MAAOC,EAAG,cAAc,CAAC,CAAC,QAAQ,MAAM,SAAS;AAC9D;AASA,SAAgBC,EAAmB,GAAkC;CACnE,IAAMC,IAAMjB,EAAoBkB,GAAM;EACpC,UAAUrB;EACV,QAAQW;CACV,CAAC;CACD,IAAIS,EAAI,WAAW,YACjB,OAAO;EACL,UAAUA,EAAI;EACd,SAAS;GAAE,QAAQA,EAAI;GAAQ,SAASA,EAAI;EAAQ;CACtD;CAEF,IAAM,EAAE,cAAWA,GACbE,IAAgBT,EAAkBU,EAAO,UAAU;CACzD,IAAI,CAACD,GACH,OAAO;EACL,UAAUC,EAAO;EACjB,SAAS;GAAE,QAAQ;GAAU,SAASZ;EAAa;CACrD;CAGF,AAAIW,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AAayB,GAAe,MAAM;CAEtD,IAAIC,EAAS,SAAS,cAAc,KAAKA,EAAS,SAAS,SAAS,GAClE,OAAO;EAAE,QAAQ;EAAW,SAAS;CAAM;CAI7C,IAAMC,IAAOD,KADKA,EAAS,SAAS,IAAI,IAAI,OAAO,UACfJ;CAGpC,OAFAtB,EAAG,cAAcyB,GAAeE,GAAM,MAAM,GAErC;EAAE,QAAQ;EAAW,SAAS;CAAK;AAC5C;AAEA,SAAgBC,EAAkB,GAAsC;CACtE,IAAI,CAAC5B,EAAG,WAAWyB,CAAa,GAC9B,OAAO;EAAE,QAAQ;EAAW,SAAS;CAAM;CAG7C,IAAMC,IAAW1B,EAAG,aAAayB,GAAe,MAAM;CAEtD,IAAI,CAACC,EAAS,SAAS,cAAc,GACnC,OAAO;EAAE,QAAQ;EAAW,SAAS;CAAM;CAQ7C,IAAMG,IALmBH,EAAS,QAChC,qFACA,IAGc,CAAA,CAAiB,QAAQ,WAAW,IAAI;CAOxD,OALIG,MAAYH,IACP;EAAE,QAAQ;EAAW,SAAS;CAAM,KAG7C1B,EAAG,cAAcyB,GAAeI,GAAS,MAAM,GACxC;EAAE,QAAQ;EAAW,SAAS;CAAK;AAC5C"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { n as e } from "./logger-t1HxmpG2.js";
|
|
2
|
-
import { r as t } from "./modify-file-
|
|
2
|
+
import { r as t } from "./modify-file-BOEKlIDw.js";
|
|
3
3
|
import { i as n, n as r, r as i, t as a } from "./translations-B5hX0Qq-.js";
|
|
4
4
|
import { n as o, r as s } from "./app-layout.svelte-CZ0hw-pi.js";
|
|
5
5
|
import c from "node:fs";
|
|
@@ -25,4 +25,4 @@ function u(u) {
|
|
|
25
25
|
}
|
|
26
26
|
export { u as localizeAuthPages };
|
|
27
27
|
|
|
28
|
-
//# sourceMappingURL=i18n-
|
|
28
|
+
//# sourceMappingURL=i18n-Ho8H91Ze.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"i18n-
|
|
1
|
+
{"version":3,"file":"i18n-Ho8H91Ze.js","names":["getLogger","modifyOutcomeToFile","translateCatalog","entriesInProject","hasSpanish","AUTH_TRANSLATIONS","APP_LAYOUT_PATH","modifyAppLayoutLanguageSelect","fs","path","localizeAuthPages","logger","options","creates","modifies","appLayoutFile","select","translated"],"sources":["../../src/patterns/enable/auth/i18n.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { File, Options } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport {\n entriesInProject,\n hasSpanish,\n translateCatalog,\n} from \"../../../runtime/wuchale-catalog\";\nimport {\n APP_LAYOUT_PATH,\n modifyAppLayoutLanguageSelect,\n} from \"../i18n/modifies/app-layout.svelte\";\nimport { AUTH_TRANSLATIONS } from \"./translations\";\n\n/**\n * What enable-i18n would have done to the auth pages had they been in the\n * project when it ran: the language select in the signed-in layout, and the\n * pages' Spanish in the catalog. For enable-auth and enable-auth-remote, in a\n * project that already has i18n; nothing happens in one that does not.\n *\n * Reads the pages from disk, so it runs after the pattern's creates are\n * written. Detected by the files enable-i18n wrote rather than\n * `features.i18n`, so a project that dropped Spanish keeps its catalog as it\n * is.\n */\nexport function localizeAuthPages(options: Options): {\n creates: File[];\n modifies: File[];\n} {\n const logger = getLogger(options);\n const creates: File[] = [];\n const modifies: File[] = [];\n if (!fs.existsSync(path.join(options.root, \"wuchale.config.js\"))) {\n return { creates, modifies };\n }\n\n logger.info(\"Adding the language select to the signed-in layout\");\n const appLayoutFile = path.join(options.root, APP_LAYOUT_PATH);\n const select = modifyOutcomeToFile(\n appLayoutFile,\n modifyAppLayoutLanguageSelect(appLayoutFile),\n );\n if (select) modifies.push(select);\n\n if (hasSpanish(options.root)) {\n logger.info(\"Translating the sign-in pages into Spanish\");\n const translated = translateCatalog(\n options.root,\n entriesInProject(options.root, AUTH_TRANSLATIONS),\n );\n if (translated.create) creates.push(translated.create);\n if (translated.modify) modifies.push(translated.modify);\n }\n\n return { creates, modifies };\n}\n"],"mappings":";;;;;;;AA2BA,SAAgBU,EAAkB,GAGhC;CACA,IAAMC,IAASX,EAAUY,CAAO,GAC1BC,IAAkB,CAAC,GACnBC,IAAmB,CAAC;CAC1B,IAAI,CAACN,EAAG,WAAWC,EAAK,KAAKG,EAAQ,MAAM,mBAAmB,CAAC,GAC7D,OAAO;EAAE;EAAS;CAAS;CAG7B,EAAO,KAAK,oDAAoD;CAChE,IAAMG,IAAgBN,EAAK,KAAKG,EAAQ,MAAMN,CAAe,GACvDU,IAASf,EACbc,GACAR,EAA8BQ,CAAa,CAC7C;CAGA,IAFIC,KAAQF,EAAS,KAAKE,CAAM,GAE5BZ,EAAWQ,EAAQ,IAAI,GAAG;EAC5B,EAAO,KAAK,4CAA4C;EACxD,IAAMK,IAAaf,EACjBU,EAAQ,MACRT,EAAiBS,EAAQ,MAAMP,CAAiB,CAClD;EAEA,AADIY,EAAW,UAAQJ,EAAQ,KAAKI,EAAW,MAAM,GACjDA,EAAW,UAAQH,EAAS,KAAKG,EAAW,MAAM;CACxD;CAEA,OAAO;EAAE;EAAS;CAAS;AAC7B"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { n as e } from "./rolldown-runtime-CwxnZyOB.js";
|
|
2
2
|
import { a as t } from "./util-mXrQ89nG.js";
|
|
3
|
-
import { n } from "./shared-
|
|
3
|
+
import { n } from "./shared-CSwGWMcN.js";
|
|
4
4
|
import { _ as r, s as i } from "./ts-morph-helpers-B4KZXP44.js";
|
|
5
5
|
import a from "node:fs";
|
|
6
6
|
import o from "node:path";
|
|
@@ -47,4 +47,4 @@ function d(e, t) {
|
|
|
47
47
|
}
|
|
48
48
|
export { l as a, s as i, d as n, c as r, u as t };
|
|
49
49
|
|
|
50
|
-
//# sourceMappingURL=modify-file-
|
|
50
|
+
//# sourceMappingURL=modify-file-BOEKlIDw.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"modify-file-
|
|
1
|
+
{"version":3,"file":"modify-file-BOEKlIDw.js","names":["__exportAll","languageFromPath","withInMemoryScript","isEffectivelyEmpty","fs","path","modify_file_exports","keepMissing","modifyOutcomeToFile","language","filePath","outcome","revertOutcomeToFile","toDeleteEntry","envRevertOutcomeToFile","envPath","creates","root","file"],"sources":["../../src/runtime/modify-file.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { File, ModifyOutcome } from \"../core/types\";\nimport { languageFromPath } from \"../core/util\";\nimport { toDeleteEntry } from \"../patterns/destroy/shared\";\nimport { isEffectivelyEmpty, withInMemoryScript } from \"./ts-morph-helpers\";\n\nexport function modifyOutcomeToFile(\n filePath: string,\n outcome: ModifyOutcome,\n): File | null {\n const language = languageFromPath(filePath);\n\n if (outcome.status === \"success\") {\n if (!outcome.changed) return null;\n return {\n path: filePath,\n language,\n content: fs.readFileSync(filePath, \"utf8\"),\n status: \"success\",\n };\n }\n\n const content =\n outcome.status === \"failed\" && fs.existsSync(filePath)\n ? fs.readFileSync(filePath, \"utf8\")\n : \"\";\n\n return {\n path: filePath,\n language,\n content,\n status: outcome.status,\n message: outcome.message,\n };\n}\n\n/**\n * `modifyOutcomeToFile` for a revert that may have taken out everything the\n * file held: a script left with no statements, only comments and whitespace,\n * is reported as a delete. For hooks files a pattern created, or that ended\n * up holding nothing but what patterns put there.\n */\nexport function revertOutcomeToFile(\n filePath: string,\n outcome: ModifyOutcome,\n): { modify: File | null; delete: File | null } {\n if (\n outcome.status === \"success\" &&\n outcome.changed &&\n fs.existsSync(filePath) &&\n withInMemoryScript(fs.readFileSync(filePath, \"utf8\"), isEffectivelyEmpty)\n .result\n ) {\n return { modify: null, delete: toDeleteEntry(filePath) };\n }\n return { modify: modifyOutcomeToFile(filePath, outcome), delete: null };\n}\n\n/**\n * `modifyOutcomeToFile` for a `.env` revert: a file the revert left empty is\n * reported as a delete. The enable pattern most likely created it, and an\n * empty `.env` holds nothing worth keeping.\n */\nexport function envRevertOutcomeToFile(\n envPath: string,\n outcome: ModifyOutcome,\n): { modify: File | null; delete: File | null } {\n if (\n outcome.status === \"success\" &&\n outcome.changed &&\n fs.existsSync(envPath) &&\n fs.readFileSync(envPath, \"utf8\").trim() === \"\"\n ) {\n return { modify: null, delete: toDeleteEntry(envPath) };\n }\n return { modify: modifyOutcomeToFile(envPath, outcome), delete: null };\n}\n\n/**\n * Drop any create that already exists on disk.\n *\n * `writeResult` overwrites an existing create whose content differs and\n * reports it as a modify, which would mean a re-run silently resetting a\n * developer's edits, or a create clobbering a file other patterns have\n * already written to. The file is theirs once it exists; a pattern that has\n * something to add to it does so with a modifier.\n */\nexport function keepMissing(creates: File[], root: string): File[] {\n return creates.filter((file) => !fs.existsSync(path.join(root, file.path)));\n}\n"],"mappings":";;;;;;;;;;;AAOA,SAAgBQ,EACd,GACA,GACa;CACb,IAAMC,IAAWR,EAAiBS,CAAQ;CAiB1C,OAfIC,EAAQ,WAAW,YAChBA,EAAQ,UACN;EACL,MAAMD;EACN;EACA,SAASN,EAAG,aAAaM,GAAU,MAAM;EACzC,QAAQ;CACV,IAN6B,OAcxB;EACL,MAAMA;EACN;EACA,SAPAC,EAAQ,WAAW,YAAYP,EAAG,WAAWM,CAAQ,IACjDN,EAAG,aAAaM,GAAU,MAAM,IAChC;EAMJ,QAAQC,EAAQ;EAChB,SAASA,EAAQ;CACnB;AACF;AAQA,SAAgBC,EACd,GACA,GAC8C;CAU9C,OARED,EAAQ,WAAW,aACnBA,EAAQ,WACRP,EAAG,WAAWM,CAAQ,KACtBR,EAAmBE,EAAG,aAAaM,GAAU,MAAM,GAAGP,CAAkB,CAAC,CACtE,SAEI;EAAE,QAAQ;EAAM,QAAQU,EAAcH,CAAQ;CAAE,IAElD;EAAE,QAAQF,EAAoBE,GAAUC,CAAO;EAAG,QAAQ;CAAK;AACxE;AAOA,SAAgBG,EACd,GACA,GAC8C;CAS9C,OAPEH,EAAQ,WAAW,aACnBA,EAAQ,WACRP,EAAG,WAAWW,CAAO,KACrBX,EAAG,aAAaW,GAAS,MAAM,CAAC,CAAC,KAAK,MAAM,KAErC;EAAE,QAAQ;EAAM,QAAQF,EAAcE,CAAO;CAAE,IAEjD;EAAE,QAAQP,EAAoBO,GAASJ,CAAO;EAAG,QAAQ;CAAK;AACvE;AAWA,SAAgBJ,EAAY,GAAiB,GAAsB;CACjE,OAAOS,EAAQ,QAAQ,MAAS,CAACZ,EAAG,WAAWC,EAAK,KAAKY,GAAMC,EAAK,IAAI,CAAC,CAAC;AAC5E"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { n as e } from "./rolldown-runtime-CwxnZyOB.js";
|
|
2
|
-
import { c as t, i as n, u as r } from "./constants-
|
|
2
|
+
import { c as t, i as n, u as r } from "./constants-E1I-__KI.js";
|
|
3
3
|
import { existsSync as i, readFileSync as a, readdirSync as o } from "node:fs";
|
|
4
4
|
import s from "node:path";
|
|
5
5
|
import c from "pocketbase";
|
|
@@ -229,4 +229,4 @@ function D(e, t) {
|
|
|
229
229
|
}
|
|
230
230
|
export { E as i, x as n, y as r, S as t };
|
|
231
231
|
|
|
232
|
-
//# sourceMappingURL=pocketbase-
|
|
232
|
+
//# sourceMappingURL=pocketbase-B2ksFrvH.js.map
|