@velastack/patterns 0.15.0 → 0.15.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunks/_page-BFUn0CG1.js +5 -0
- package/dist/chunks/{_page-6d3DCr0p.js.map → _page-BFUn0CG1.js.map} +1 -1
- package/dist/chunks/auth-pages-D8n8gfCL.js +311 -0
- package/dist/chunks/auth-pages-D8n8gfCL.js.map +1 -0
- package/dist/chunks/{collections-FKsKGtaH.js → collections-Daxlnbm0.js} +2 -2
- package/dist/chunks/{collections-FKsKGtaH.js.map → collections-Daxlnbm0.js.map} +1 -1
- package/dist/chunks/{constants-BHuzzsKu.js → constants-E1I-__KI.js} +20 -20
- package/dist/chunks/{constants-BHuzzsKu.js.map → constants-E1I-__KI.js.map} +1 -1
- package/dist/chunks/{currency.server-DRuEFc6D.js → currency.server-BkzwY17R.js} +2 -2
- package/dist/chunks/{currency.server-DRuEFc6D.js.map → currency.server-BkzwY17R.js.map} +1 -1
- package/dist/chunks/{env-vars-BcHu8247.js → env-vars-C3TSZc4f.js} +3 -3
- package/dist/chunks/{env-vars-BcHu8247.js.map → env-vars-C3TSZc4f.js.map} +1 -1
- package/dist/chunks/{generate-CXAKf1Hh.js → generate-CAYM7OUF.js} +2 -2
- package/dist/chunks/{generate-CXAKf1Hh.js.map → generate-CAYM7OUF.js.map} +1 -1
- package/dist/chunks/{generate-rcDj36TD.js → generate-CL7wG0ZC.js} +3 -3
- package/dist/chunks/{generate-rcDj36TD.js.map → generate-CL7wG0ZC.js.map} +1 -1
- package/dist/chunks/{generate-CkfJrlEg.js → generate-CbchamhA.js} +3 -3
- package/dist/chunks/{generate-CkfJrlEg.js.map → generate-CbchamhA.js.map} +1 -1
- package/dist/chunks/{generate-9O0VdZOl.js → generate-DI58vuk1.js} +2 -2
- package/dist/chunks/{generate-9O0VdZOl.js.map → generate-DI58vuk1.js.map} +1 -1
- package/dist/chunks/{generate-a3U8uDzW.js → generate-DR2wkVPY.js} +2 -2
- package/dist/chunks/{generate-a3U8uDzW.js.map → generate-DR2wkVPY.js.map} +1 -1
- package/dist/chunks/{generate.runtime-BmdO8oKV.js → generate.runtime-B11mOr45.js} +3 -3
- package/dist/chunks/{generate.runtime-BmdO8oKV.js.map → generate.runtime-B11mOr45.js.map} +1 -1
- package/dist/chunks/{generate.runtime-BDVPJJbh.js → generate.runtime-B1Y2JrGW.js} +5 -5
- package/dist/chunks/{generate.runtime-BDVPJJbh.js.map → generate.runtime-B1Y2JrGW.js.map} +1 -1
- package/dist/chunks/{generate.runtime-Cxa24AOd.js → generate.runtime-B7VubPTW.js} +3 -3
- package/dist/chunks/{generate.runtime-Cxa24AOd.js.map → generate.runtime-B7VubPTW.js.map} +1 -1
- package/dist/chunks/{generate.runtime-DsW0Q5S5.js → generate.runtime-BCv4F1Wm.js} +5 -5
- package/dist/chunks/{generate.runtime-DsW0Q5S5.js.map → generate.runtime-BCv4F1Wm.js.map} +1 -1
- package/dist/chunks/{generate.runtime-COo85dGX.js → generate.runtime-BEWp57Y7.js} +2 -2
- package/dist/chunks/{generate.runtime-COo85dGX.js.map → generate.runtime-BEWp57Y7.js.map} +1 -1
- package/dist/chunks/{generate.runtime-BKsrh3ZN.js → generate.runtime-BH6hHygm.js} +3 -3
- package/dist/chunks/{generate.runtime-BKsrh3ZN.js.map → generate.runtime-BH6hHygm.js.map} +1 -1
- package/dist/chunks/{generate.runtime-D7EETq9M.js → generate.runtime-BL6DpWFI.js} +3 -3
- package/dist/chunks/{generate.runtime-D7EETq9M.js.map → generate.runtime-BL6DpWFI.js.map} +1 -1
- package/dist/chunks/{generate.runtime-Dp3x08St.js → generate.runtime-BRV9hIl5.js} +2 -2
- package/dist/chunks/{generate.runtime-Dp3x08St.js.map → generate.runtime-BRV9hIl5.js.map} +1 -1
- package/dist/chunks/{generate.runtime-CGbSe_nd.js → generate.runtime-BRcP6sFt.js} +2 -2
- package/dist/chunks/{generate.runtime-CGbSe_nd.js.map → generate.runtime-BRcP6sFt.js.map} +1 -1
- package/dist/chunks/{generate.runtime-DcBEbV-k.js → generate.runtime-Bhs7ttZS.js} +2 -2
- package/dist/chunks/{generate.runtime-DcBEbV-k.js.map → generate.runtime-Bhs7ttZS.js.map} +1 -1
- package/dist/chunks/{generate.runtime-BGLekCHZ.js → generate.runtime-BjrtdoYE.js} +2 -2
- package/dist/chunks/{generate.runtime-BGLekCHZ.js.map → generate.runtime-BjrtdoYE.js.map} +1 -1
- package/dist/chunks/{generate.runtime-CtV9Gn9T.js → generate.runtime-Bo_s7gYB.js} +2 -2
- package/dist/chunks/{generate.runtime-CtV9Gn9T.js.map → generate.runtime-Bo_s7gYB.js.map} +1 -1
- package/dist/chunks/{generate.runtime-CnGVlvxN.js → generate.runtime-Bs77Oc8P.js} +3 -3
- package/dist/chunks/{generate.runtime-CnGVlvxN.js.map → generate.runtime-Bs77Oc8P.js.map} +1 -1
- package/dist/chunks/{generate.runtime-B5SP9iyN.js → generate.runtime-C3IswX7B.js} +2 -2
- package/dist/chunks/{generate.runtime-B5SP9iyN.js.map → generate.runtime-C3IswX7B.js.map} +1 -1
- package/dist/chunks/{generate.runtime-DtcKbzOm.js → generate.runtime-C90_2L-8.js} +3 -3
- package/dist/chunks/{generate.runtime-DtcKbzOm.js.map → generate.runtime-C90_2L-8.js.map} +1 -1
- package/dist/chunks/{generate.runtime-As1It8o7.js → generate.runtime-CDY0Ot_t.js} +6 -6
- package/dist/chunks/{generate.runtime-As1It8o7.js.map → generate.runtime-CDY0Ot_t.js.map} +1 -1
- package/dist/chunks/{generate.runtime-CI_rUVZo.js → generate.runtime-CZMVPVjS.js} +6 -6
- package/dist/chunks/{generate.runtime-CI_rUVZo.js.map → generate.runtime-CZMVPVjS.js.map} +1 -1
- package/dist/chunks/{generate.runtime-BYhWm9JA.js → generate.runtime-C_hrLPD4.js} +3 -3
- package/dist/chunks/{generate.runtime-BYhWm9JA.js.map → generate.runtime-C_hrLPD4.js.map} +1 -1
- package/dist/chunks/{generate.runtime-BKA41qV0.js → generate.runtime-CdZ3GzPS.js} +6 -6
- package/dist/chunks/{generate.runtime-BKA41qV0.js.map → generate.runtime-CdZ3GzPS.js.map} +1 -1
- package/dist/chunks/{generate.runtime-Cqbsn5Ov.js → generate.runtime-ChSVP7cD.js} +6 -6
- package/dist/chunks/{generate.runtime-Cqbsn5Ov.js.map → generate.runtime-ChSVP7cD.js.map} +1 -1
- package/dist/chunks/{generate.runtime-BL7O2fy8.js → generate.runtime-Cs73i6Zf.js} +2 -2
- package/dist/chunks/{generate.runtime-BL7O2fy8.js.map → generate.runtime-Cs73i6Zf.js.map} +1 -1
- package/dist/chunks/{generate.runtime-C7NexMXs.js → generate.runtime-D7KYlnvb.js} +3 -3
- package/dist/chunks/{generate.runtime-C7NexMXs.js.map → generate.runtime-D7KYlnvb.js.map} +1 -1
- package/dist/chunks/{generate.runtime-CTQvLaU0.js → generate.runtime-DG9LRwbt.js} +3 -3
- package/dist/chunks/{generate.runtime-CTQvLaU0.js.map → generate.runtime-DG9LRwbt.js.map} +1 -1
- package/dist/chunks/{generate.runtime-DiAnQ9MW.js → generate.runtime-DKL7VAAd.js} +6 -6
- package/dist/chunks/{generate.runtime-DiAnQ9MW.js.map → generate.runtime-DKL7VAAd.js.map} +1 -1
- package/dist/chunks/{generate.runtime-DaJ4gLPv.js → generate.runtime-DP63Wwea.js} +4 -4
- package/dist/chunks/{generate.runtime-DaJ4gLPv.js.map → generate.runtime-DP63Wwea.js.map} +1 -1
- package/dist/chunks/{generate.runtime-CFSBH8yG.js → generate.runtime-DRPxOLnB.js} +4 -4
- package/dist/chunks/{generate.runtime-CFSBH8yG.js.map → generate.runtime-DRPxOLnB.js.map} +1 -1
- package/dist/chunks/{generate.runtime-SZInujfP.js → generate.runtime-DW9bqOtC.js} +2 -2
- package/dist/chunks/{generate.runtime-SZInujfP.js.map → generate.runtime-DW9bqOtC.js.map} +1 -1
- package/dist/chunks/{generate.runtime-Cc5Aw1zc.js → generate.runtime-DdY44Ulv.js} +6 -6
- package/dist/chunks/{generate.runtime-Cc5Aw1zc.js.map → generate.runtime-DdY44Ulv.js.map} +1 -1
- package/dist/chunks/{generate.runtime-BOtYaNA5.js → generate.runtime-DjEj-n6m.js} +7 -7
- package/dist/chunks/{generate.runtime-BOtYaNA5.js.map → generate.runtime-DjEj-n6m.js.map} +1 -1
- package/dist/chunks/{generate.runtime-ICaKVEuW.js → generate.runtime-DlAJQ5Js.js} +4 -4
- package/dist/chunks/{generate.runtime-ICaKVEuW.js.map → generate.runtime-DlAJQ5Js.js.map} +1 -1
- package/dist/chunks/{generate.runtime-4gS2ZHpj.js → generate.runtime-JftBoKYS.js} +5 -5
- package/dist/chunks/{generate.runtime-4gS2ZHpj.js.map → generate.runtime-JftBoKYS.js.map} +1 -1
- package/dist/chunks/{generate.runtime-B8t8HtB6.js → generate.runtime-_426A1Ij.js} +3 -3
- package/dist/chunks/{generate.runtime-B8t8HtB6.js.map → generate.runtime-_426A1Ij.js.map} +1 -1
- package/dist/chunks/{generate.runtime-CyteiEzT.js → generate.runtime-fs6GEMx-.js} +5 -5
- package/dist/chunks/{generate.runtime-CyteiEzT.js.map → generate.runtime-fs6GEMx-.js.map} +1 -1
- package/dist/chunks/{generate.runtime-B9U3kzHD.js → generate.runtime-jIlQ2GMh.js} +2 -2
- package/dist/chunks/{generate.runtime-B9U3kzHD.js.map → generate.runtime-jIlQ2GMh.js.map} +1 -1
- package/dist/chunks/{generate.runtime-BY5VmBG4.js → generate.runtime-v3KCv1B6.js} +2 -2
- package/dist/chunks/{generate.runtime-BY5VmBG4.js.map → generate.runtime-v3KCv1B6.js.map} +1 -1
- package/dist/chunks/{generate.runtime-CG3udLj8.js → generate.runtime-xrxAElb3.js} +3 -3
- package/dist/chunks/{generate.runtime-CG3udLj8.js.map → generate.runtime-xrxAElb3.js.map} +1 -1
- package/dist/chunks/{gitignore-CPardo4E.js → gitignore-CBiWFRif.js} +3 -3
- package/dist/chunks/{gitignore-CPardo4E.js.map → gitignore-CBiWFRif.js.map} +1 -1
- package/dist/chunks/{i18n-C8OfN_nr.js → i18n-Ho8H91Ze.js} +3 -3
- package/dist/chunks/{i18n-C8OfN_nr.js.map → i18n-Ho8H91Ze.js.map} +1 -1
- package/dist/chunks/{modify-file-DvIwtj4o.js → modify-file-BOEKlIDw.js} +2 -2
- package/dist/chunks/{modify-file-DvIwtj4o.js.map → modify-file-BOEKlIDw.js.map} +1 -1
- package/dist/chunks/{pocketbase-Ir-TPv7H.js → pocketbase-B2ksFrvH.js} +2 -2
- package/dist/chunks/{pocketbase-Ir-TPv7H.js.map → pocketbase-B2ksFrvH.js.map} +1 -1
- package/dist/chunks/{providers-B386TYCN.js → providers-BEjDonyG.js} +2 -2
- package/dist/chunks/{providers-B386TYCN.js.map → providers-BEjDonyG.js.map} +1 -1
- package/dist/chunks/{route-BJBV1DtX.js → route-9ZVJZkYu.js} +23 -19
- package/dist/chunks/route-9ZVJZkYu.js.map +1 -0
- package/dist/chunks/{schema-DSNYWlel.js → schema-DnMqw2Hn.js} +3 -3
- package/dist/chunks/{schema-DSNYWlel.js.map → schema-DnMqw2Hn.js.map} +1 -1
- package/dist/chunks/{shared-CZHopdly.js → shared-CSwGWMcN.js} +2 -2
- package/dist/chunks/{shared-CZHopdly.js.map → shared-CSwGWMcN.js.map} +1 -1
- package/dist/chunks/{shared-BofFBVmT.js → shared-Cdwm_-Nl.js} +40 -40
- package/dist/chunks/{shared-BofFBVmT.js.map → shared-Cdwm_-Nl.js.map} +1 -1
- package/dist/chunks/{site-B9-emR6D.js → site-B5zrFba9.js} +2 -2
- package/dist/chunks/{site-B9-emR6D.js.map → site-B5zrFba9.js.map} +1 -1
- package/dist/chunks/{table-core-CHsfbi-n.js → table-core-ux1xEJxN.js} +2 -2
- package/dist/chunks/{table-core-CHsfbi-n.js.map → table-core-ux1xEJxN.js.map} +1 -1
- package/dist/chunks/{translations-CiJnl574.js → translations-B5hX0Qq-.js} +5 -2
- package/dist/chunks/{translations-CiJnl574.js.map → translations-B5hX0Qq-.js.map} +1 -1
- package/dist/chunks/{ui-BUhkIHse.js → ui-CpjUq_lm.js} +3 -3
- package/dist/chunks/{ui-BUhkIHse.js.map → ui-CpjUq_lm.js.map} +1 -1
- package/dist/chunks/{whatsapp-DFZUsKWe.js → whatsapp-DOSZ_zwn.js} +2 -2
- package/dist/chunks/{whatsapp-DFZUsKWe.js.map → whatsapp-DOSZ_zwn.js.map} +1 -1
- package/dist/chunks/{write-result-Bkdkp7u2.js → write-result-DlB-id5k.js} +50 -26
- package/dist/chunks/write-result-DlB-id5k.js.map +1 -0
- package/dist/index.js +1864 -1842
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
- package/dist/chunks/_page-6d3DCr0p.js +0 -5
- package/dist/chunks/auth-pages-DHzh31mw.js +0 -285
- package/dist/chunks/auth-pages-DHzh31mw.js.map +0 -1
- package/dist/chunks/route-BJBV1DtX.js.map +0 -1
- package/dist/chunks/write-result-Bkdkp7u2.js.map +0 -1
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { n as e } from "./logger-t1HxmpG2.js";
|
|
2
2
|
import { a as t } from "./util-mXrQ89nG.js";
|
|
3
|
-
import { r as n } from "./modify-file-
|
|
3
|
+
import { r as n } from "./modify-file-BOEKlIDw.js";
|
|
4
4
|
import { t as r } from "./dedent-CCUOcPFW.js";
|
|
5
5
|
import { _ as i, o as a, r as o, u as s } from "./ts-morph-helpers-B4KZXP44.js";
|
|
6
6
|
import { t as c } from "./modify-nav-user-D42kWyU6.js";
|
|
@@ -157,4 +157,4 @@ async function E(r) {
|
|
|
157
157
|
}
|
|
158
158
|
export { w as SUCCESS_PAGE, E as generate, C as t };
|
|
159
159
|
|
|
160
|
-
//# sourceMappingURL=generate.runtime-
|
|
160
|
+
//# sourceMappingURL=generate.runtime-jIlQ2GMh.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"generate.runtime-B9U3kzHD.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"],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AAmB,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
|
+
{"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,EA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BAAmBrD,CAAa,GACjC,CAAC,gBAAgBC,CAAa,CAChC,GAAY;EACV,IAAMiD,IAAOpC,EAAK,KAAKiC,EAAQ,MAAMJ,GAAcS,CAAI;EACvD,AAAIvC,EAAG,WAAWqC,CAAI,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,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,kBAAkB;CAEnE,IAAI,CAACF,GACH,OAAO;EAAE,QAAQ;EAAU,SAASP;CAAa;CAGnD,IAAMU,IAAOH,EAAS,aAAa;CACnC,IAAIG,EAAK,WAAW,GAIlB,OAHAH,EAAS,YAAY,4BAA4B,GACjDV,EAAiBQ,CAAU,GAC3BA,EAAW,SAAS,GACb;EAAE,QAAQ;EAAW,SAAS;CAAK;CAG5C,IAAMM,IAAWD,EAAK;CACtB,IAAIC,EAAS,QAAQ,MAAMH,EAAW,yBAIpC,OAHAD,EAAS,eAAe,GAAG,4BAA4B,GACvDV,EAAiBQ,CAAU,GAC3BA,EAAW,SAAS,GACb;EAAE,QAAQ;EAAW,SAAS;CAAK;CAG5C,IAAMO,IAAaD,EAAS,cAAcH,EAAW,uBAAuB,GACtEK,IAAUD,EAAW,YAAY,KAAK;CAE5C,IAAI,CAACC,GAOH,OANAD,EAAW,sBAAsB;EAC/B,MAAM;EACN,aAAa;CACf,CAAC,GACDf,EAAiBQ,CAAU,GAC3BA,EAAW,SAAS,GACb;EAAE,QAAQ;EAAW,SAAS;CAAK;CAG5C,IAAIQ,EAAQ,QAAQ,MAAML,EAAW,oBAAoB;EACvD,IAAMM,IACJD,EACA,eAAe;EACjB,IAAIC,KAAWA,EAAQ,QAAQ,MAAMN,EAAW,yBAAyB;GACvE,IAAMO,IAASD;GAEf,AADoBC,EAAO,YAAY,SAClC,KACHA,EAAO,sBAAsB;IAAE,MAAM;IAAW,aAAa;GAAO,CAAC;EAEzE;CACF;CAIA,OAFAlB,EAAiBQ,CAAU,GAC3BA,EAAW,SAAS,GACb;EACL,QAAQ;EACR,SAASA,EAAW,YAAY,MAAMD;CACxC;AACF;;ACnFA,eAAsBY,EAAS,GAAkB;CAC/C,IAAMC,IAASvB,EAAUwB,CAAO,GAC1BC,IAAmB,CAAC;CAE1B,EAAO,KAAK,2BAA2B;CACvC,IAAMhB,IAAkBJ,EAAK,KAAKmB,EAAQ,MAAM,OAAO,iBAAiB,GAClEE,IAAOzB,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 packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n } satisfies Result;\n}\n"],"mappings":";;;;;;;;;;AAMA,IAAMO,IAAe,CAAM;;;GAKrBC,IAAe,CAAM;;;;;;;;;GAWrBC,IAAiB,CAAM;;;;;;;;AAS7B,SAASC,EACP,GACA,GACA,GACA,IAAW,IACX;CACA,IAAMC,IAAWC,EACd,sBAAsB,CAAC,CACvB,MAAM,MAAMC,EAAE,wBAAwB,MAAMC,CAAe;CAC9D,AAAKH,IAQDA,EAAS,gBAAgB,CAAC,CAAC,MAAM,MAAOI,EAAG,QAAQ,MAAMC,CAAI,KAGjEL,EAAS,eACPM,KAAY,CAACN,EAAS,WAAW,IAAI;EAAE;EAAM,YAAY;CAAK,IAAIK,CACpE,IAZEJ,EAAW,qBAAqB;EAC9B,YAAYK;EACZ,cAAc,CAACD,CAAI;EACnB;CACF,CAAC;AASL;AAEA,SAASE,EAAc,GAAiC;CAGtD,OAFIN,EAAW,uBAAuB,MAAM,KACxCA,EAAW,YAAY,MAAM,IAAU,KACpCA,EACJ,sBAAsB,CAAC,CACvB,MAAM,MAAMC,EA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;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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AAM,GACxC;EAAE,QAAQ;EAAW,SAAS;CAAK;AAC5C"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { n as e } from "./logger-t1HxmpG2.js";
|
|
2
|
-
import { r as t } from "./modify-file-
|
|
3
|
-
import { i as n, n as r, r as i, t as a } from "./translations-
|
|
2
|
+
import { r as t } from "./modify-file-BOEKlIDw.js";
|
|
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";
|
|
6
6
|
import l from "node:path";
|
|
@@ -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
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pocketbase-Ir-TPv7H.js","names":["__exportAll","MIGRATIONS_DIR","DATA_DIR","POCKETBASE_BIN_ENV","path","PocketBase","spawn","net","BAD_PORTS","osAssignedPort","server","reject","host","resolve","port","freePort","waitForPort","attempts","tryConnect","socket","maxAttempts","describeFetchError","error","cause","waitForHealth","lastFailure","tryHealth","response","url","pocketbase_exports","withPocketbase","MIGRATION_DELAY_MS","migrationDelay","getMigrationFile","ending","action","collectionName","migrationFile","readdirSync","options","file","getPocketbaseMetadata","metadataPath","cwd","existsSync","readFileSync","authWithRetries","authSuccess","attempt","pb","email","password","pocketbaseCommand","bin","env","serverArgs","packageManager","detect","resolveCommand","args","dir","migrationsDir","metadata","fn","detached","serverProcess","command","exited","signal","code","stopProcessTree","child"],"sources":["../../src/runtime/net.ts","../../src/runtime/pocketbase.ts"],"sourcesContent":["import net from \"node:net\";\n\n/**\n * Ports the Fetch spec tells clients to refuse outright\n * (https://fetch.spec.whatwg.org/#port-blocking). Node's `fetch` enforces the\n * list, so a server bound to one of them is unreachable from `waitForHealth`\n * and the PocketBase SDK alike: the request fails with cause \"bad port\"\n * before a connection is even attempted. 10080 sat inside the 10000–19999\n * range ports used to be drawn from, and cost a CI run a 30-second health\n * timeout whenever the draw landed on it.\n */\nexport const BAD_PORTS: ReadonlySet<number> = new Set([\n 1, 7, 9, 11, 13, 15, 17, 19, 20, 21, 22, 23, 25, 37, 42, 43, 53, 69, 77, 79,\n 87, 95, 101, 102, 103, 104, 109, 110, 111, 113, 115, 117, 119, 123, 135, 137,\n 139, 143, 161, 179, 389, 427, 465, 512, 513, 514, 515, 526, 530, 531, 532,\n 540, 548, 554, 556, 563, 587, 601, 636, 989, 990, 993, 995, 1719, 1720, 1723,\n 2049, 3659, 4045, 4190, 5060, 5061, 6000, 6566, 6665, 6666, 6667, 6668, 6669,\n 6679, 6697, 10080,\n]);\n\nfunction osAssignedPort(host: string): Promise<number> {\n return new Promise((resolve, reject) => {\n const server = net.createServer();\n server.unref();\n server.once(\"error\", reject);\n server.listen(0, host, () => {\n const { port } = server.address() as net.AddressInfo;\n server.close(() => resolve(port));\n });\n });\n}\n\n/**\n * A port nothing is listening on right now, taken from the OS's ephemeral\n * range so it neither collides with whatever else the machine runs nor hits\n * `BAD_PORTS`. The port is released again before this resolves, so the\n * caller's server has to bind it promptly.\n */\nexport async function freePort(host: string): Promise<number> {\n for (;;) {\n const port = await osAssignedPort(host);\n if (!BAD_PORTS.has(port)) return port;\n }\n}\n\n// Wait for the port to be available. A cold `npx pocketbase-server` on a CI\n// runner can take well over the five seconds the old default allowed.\nexport function waitForPort(\n port: number,\n host: string,\n maxAttempts = 60,\n): Promise<void> {\n return new Promise((resolve, reject) => {\n let attempts = 0;\n\n const tryConnect = () => {\n attempts++;\n\n const socket = new net.Socket();\n\n const onError = () => {\n socket.destroy();\n\n if (attempts === maxAttempts) {\n reject(\n new Error(`Timed out waiting for port ${port} to be available`),\n );\n return;\n }\n\n setTimeout(tryConnect, 500);\n };\n\n socket.once(\"error\", onError);\n\n socket.connect(port, host, () => {\n socket.destroy();\n resolve();\n });\n };\n\n tryConnect();\n });\n}\n\n/**\n * `fetch` wraps the interesting part in `cause`: an errno error for a\n * connection that was refused, or a bare string such as \"bad port\" for a\n * request undici declined to make.\n */\nfunction describeFetchError(error: unknown): string {\n if (!(error instanceof Error)) return String(error);\n const { cause } = error as Error & { cause?: unknown };\n if (cause instanceof Error) {\n const code = (cause as NodeJS.ErrnoException).code;\n return code || cause.message || error.message;\n }\n if (cause !== undefined) return String(cause);\n return error.message;\n}\n\n// Wait for the health check to be successful\nexport function waitForHealth(url: string, maxAttempts = 60): Promise<void> {\n return new Promise((resolve, reject) => {\n let attempts = 0;\n let lastFailure = \"no attempt made\";\n\n const tryHealth = async () => {\n attempts++;\n\n try {\n const response = await fetch(`${url}/api/health`);\n if (response.status === 200) {\n resolve();\n return;\n }\n lastFailure = `HTTP ${response.status}`;\n } catch (error) {\n lastFailure = describeFetchError(error);\n }\n\n if (attempts === maxAttempts) {\n reject(\n new Error(\n `Timed out waiting for health check at ${url}/api/health (last attempt: ${lastFailure})`,\n ),\n );\n return;\n }\n\n setTimeout(tryHealth, 500);\n };\n\n tryHealth();\n });\n}\n","import { existsSync, readdirSync, readFileSync } from \"node:fs\";\nimport path from \"node:path\";\nimport PocketBase from \"pocketbase\";\nimport { detect } from \"package-manager-detector\";\nimport { resolveCommand } from \"package-manager-detector/commands\";\nimport spawn from \"cross-spawn\";\nimport { freePort, waitForPort, waitForHealth } from \"./net\";\nimport type { Options } from \"../core/types\";\nimport {\n DATA_DIR,\n MIGRATIONS_DIR,\n POCKETBASE_BIN_ENV,\n} from \"../core/constants\";\n\n/**\n * PocketBase names migration files with a 1-second-resolution Unix timestamp\n * (e.g. `1776099881_created_users.js`). Two schema operations issued in the\n * same wall-clock second produce files that sort alphabetically by their\n * action/collection suffix — which reverses the intended order whenever a\n * later migration depends on an earlier one. Wait out the full second between\n * migration-producing calls so the timestamps stay distinct.\n */\nconst MIGRATION_DELAY_MS = 1100;\n\nexport function migrationDelay(): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, MIGRATION_DELAY_MS));\n}\n\nexport function getMigrationFile(\n collectionName: string,\n action: \"created\" | \"deleted\" | \"updated\",\n options: Options,\n): string | undefined {\n const ending = `${action}_${collectionName}.js`;\n\n // find last file with ending in migrations dir\n const migrationFiles = readdirSync(\n path.join(options.root, MIGRATIONS_DIR),\n ).filter((file) => file.endsWith(ending));\n\n const migrationFile = migrationFiles.sort().pop();\n\n if (!migrationFile) {\n return undefined;\n }\n\n return path.join(options.root, MIGRATIONS_DIR, migrationFile);\n}\n\nexport function getPocketbaseMetadata(cwd: string): {\n pocketbaseUrl: string;\n vitePort: number;\n} | null {\n const metadataPath = path.join(\n cwd,\n \"node_modules\",\n \".vite\",\n \"_pocketbase_metadata.json\",\n );\n if (existsSync(metadataPath)) {\n return JSON.parse(readFileSync(metadataPath, \"utf8\"));\n }\n return null;\n}\n\nexport async function authWithRetries(\n pb: PocketBase,\n email: string,\n password: string,\n) {\n // Retry authentication up to 3 times with 100ms backoff\n let authSuccess = false;\n for (let attempt = 1; attempt <= 3; attempt++) {\n try {\n await pb.collection(\"_superusers\").authWithPassword(email, password);\n authSuccess = true;\n break;\n } catch {\n if (attempt < 3) {\n await new Promise((resolve) => setTimeout(resolve, 100));\n }\n }\n }\n\n if (!authSuccess) {\n throw new Error(\n \"Failed to authenticate with PocketBase. Check your superuser credentials.\",\n );\n }\n}\n\n/**\n * The command that runs PocketBase with the given arguments (`serve --dir\n * ...`).\n *\n * With `VELA_POCKETBASE_BIN` (`POCKETBASE_BIN_ENV`) set, that binary itself:\n * the caller has resolved it, and nothing about the project's package manager\n * is consulted. `pocketbase-server`'s own bin only forwards its arguments to\n * the binary, so they are the same either way. The value has to be an\n * absolute path to a file that exists; anything else is an error rather than\n * a quiet fall back to the package manager, since whoever set it meant it.\n * Unset or empty, the server is started as before, through the project's\n * package manager (`npx --yes pocketbase-server ...`, `pnpm dlx ...`), which\n * the integration harness and direct callers of this library rely on.\n */\nexport async function pocketbaseCommand(\n cwd: string,\n serverArgs: string[],\n env: Record<string, string | undefined> = process.env,\n): Promise<{ command: string; args: string[] }> {\n const bin = env[POCKETBASE_BIN_ENV];\n if (bin) {\n if (!path.isAbsolute(bin)) {\n throw new Error(\n `${POCKETBASE_BIN_ENV} must be an absolute path to the PocketBase binary; it is \"${bin}\".`,\n );\n }\n if (!existsSync(bin)) {\n throw new Error(\n `${POCKETBASE_BIN_ENV} points at ${bin}, which does not exist.`,\n );\n }\n return { command: bin, args: [...serverArgs] };\n }\n\n const packageManager = (await detect({ cwd }))?.name ?? \"npm\";\n const { command, args } = resolveCommand(packageManager, \"execute\", [\n \"pocketbase-server\",\n ...serverArgs,\n ])!;\n\n // adding --yes as the first parameter helps avoiding the \"Need to install the following packages:\" message\n if (packageManager === \"npm\") args.unshift(\"--yes\");\n\n return { command, args };\n}\n\nexport async function withPocketbase(\n cwd: string,\n fn: (pb: PocketBase) => Promise<void>,\n) {\n const dir = path.join(cwd, DATA_DIR);\n const migrationsDir = path.join(cwd, MIGRATIONS_DIR);\n const host = \"localhost\";\n\n if (!existsSync(dir)) {\n throw new Error(\"PocketBase data directory does not exist\");\n }\n\n // First check if the server is already running by reading node_modules/.vite/_pocketbase_metadata.json\n const metadata = getPocketbaseMetadata(cwd);\n if (metadata) {\n if (metadata.pocketbaseUrl) {\n const pb = new PocketBase(metadata.pocketbaseUrl);\n await authWithRetries(\n pb,\n process.env.POCKETBASE_SUPERUSER_EMAIL!,\n process.env.POCKETBASE_SUPERUSER_PASSWORD!,\n );\n await fn(pb);\n return;\n }\n }\n\n const port = await freePort(host);\n const { command, args } = await pocketbaseCommand(cwd, [\n \"serve\",\n \"--dir\",\n dir,\n \"--migrationsDir\",\n migrationsDir,\n \"--http\",\n `${host}:${port}`,\n ]);\n\n // Start the PocketBase server process. A package manager wrapper (`npx`)\n // spawns the real binary as a grandchild; put the tree in its own process\n // group so it can be killed as a whole, otherwise `pocketbase serve` outlives\n // us and keeps the data directory open.\n const detached = process.platform !== \"win32\";\n const serverProcess = spawn(command, args, {\n cwd,\n stdio: \"ignore\",\n detached,\n });\n\n // A wrapper that dies before the server listens (missing binary, bad\n // arguments) would otherwise only surface as a port timeout a minute later.\n const exited = new Promise<never>((_, reject) => {\n serverProcess.once(\"exit\", (code, signal) => {\n reject(\n new Error(\n `PocketBase (${command}) exited before listening on ${host}:${port} (${signal ?? `code ${code}`})`,\n ),\n );\n });\n serverProcess.once(\"error\", reject);\n });\n\n try {\n // Wait for the server to be ready\n await Promise.race([\n (async () => {\n await waitForPort(port, host);\n await waitForHealth(`http://${host}:${port}`);\n })(),\n exited,\n ]);\n\n const pb = new PocketBase(`http://${host}:${port}`);\n await authWithRetries(\n pb,\n process.env.POCKETBASE_SUPERUSER_EMAIL!,\n process.env.POCKETBASE_SUPERUSER_PASSWORD!,\n );\n await fn(pb);\n } finally {\n // Ensure we always clean up the process tree\n stopProcessTree(serverProcess, detached);\n }\n}\n\nfunction stopProcessTree(\n child: ReturnType<typeof spawn>,\n detached: boolean,\n): void {\n if (detached && child.pid) {\n try {\n process.kill(-child.pid, \"SIGTERM\");\n return;\n } catch {\n // Group already gone or unsupported; fall through to the plain kill.\n }\n }\n child.kill();\n}\n"],"mappings":";;;;;;;;;;AAWA,IAAaQ,oBAAiC,IAAI,IAAI;CACpD;CAAG;CAAG;CAAG;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CACzE;CAAI;CAAI;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CACzE;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CACtE;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAM;CAAM;CACxE;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;CACxE;CAAM;CAAM;AACd,CAAC;AAED,SAASC,EAAe,GAA+B;CACrD,OAAO,IAAI,SAAS,GAAS,MAAW;EACtC,IAAMC,IAASH,EAAI,aAAa;EAGhC,AAFAG,EAAO,MAAM,GACbA,EAAO,KAAK,SAASC,CAAM,GAC3BD,EAAO,OAAO,GAAGE,SAAY;GAC3B,IAAM,EAAE,YAASF,EAAO,QAAQ;GAChC,EAAO,YAAYG,EAAQC,CAAI,CAAC;EAClC,CAAC;CACH,CAAC;AACH;AAQA,eAAsBC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M;CACpC,CAAC;CAED,IAAI;EAEF,MAAM,QAAQ,KAAK,EAChB,YAAY;GAEX,AADA,MAAMK,EAAYF,GAAMF,CAAI,GAC5B,MAAMY,EAAc,UAAUZ,EAAK,GAAGE,GAAM;EAC9C,EAAA,CAAG,GACHqD,CACF,CAAC;EAED,IAAMlB,IAAK,IAAI5C,EAAW,UAAUO,EAAK,GAAGE,GAAM;EAMlD,AALA,MAAMgC,EACJG,GACA,QAAQ,IAAI,4BACZ,QAAQ,IAAI,6BACd,GACA,MAAMc,EAAGd,CAAE;CACb,UAAU;EAER,EAAgBgB,GAAeD,CAAQ;CACzC;AACF;AAEA,SAASM,EACP,GACA,GACM;CACN,IAAIN,KAAYO,EAAM,KACpB,IAAI;EACF,QAAQ,KAAK,CAACA,EAAM,KAAK,SAAS;EAClC;CACF,QAAQ,CAER;CAEF,EAAM,KAAK;AACb"}
|
|
1
|
+
{"version":3,"file":"pocketbase-B2ksFrvH.js","names":["__exportAll","MIGRATIONS_DIR","DATA_DIR","POCKETBASE_BIN_ENV","path","PocketBase","spawn","net","BAD_PORTS","osAssignedPort","server","reject","host","resolve","port","freePort","waitForPort","attempts","tryConnect","socket","maxAttempts","describeFetchError","error","cause","waitForHealth","lastFailure","tryHealth","response","url","pocketbase_exports","withPocketbase","MIGRATION_DELAY_MS","migrationDelay","getMigrationFile","ending","action","collectionName","migrationFile","readdirSync","options","file","getPocketbaseMetadata","metadataPath","cwd","existsSync","readFileSync","authWithRetries","authSuccess","attempt","pb","email","password","pocketbaseCommand","bin","env","serverArgs","packageManager","detect","resolveCommand","args","dir","migrationsDir","metadata","fn","detached","serverProcess","command","exited","signal","code","stopProcessTree","child"],"sources":["../../src/runtime/net.ts","../../src/runtime/pocketbase.ts"],"sourcesContent":["import net from \"node:net\";\n\n/**\n * Ports the Fetch spec tells clients to refuse outright\n * (https://fetch.spec.whatwg.org/#port-blocking). Node's `fetch` enforces the\n * list, so a server bound to one of them is unreachable from `waitForHealth`\n * and the PocketBase SDK alike: the request fails with cause \"bad port\"\n * before a connection is even attempted. 10080 sat inside the 10000–19999\n * range ports used to be drawn from, and cost a CI run a 30-second health\n * timeout whenever the draw landed on it.\n */\nexport const BAD_PORTS: ReadonlySet<number> = new Set([\n 1, 7, 9, 11, 13, 15, 17, 19, 20, 21, 22, 23, 25, 37, 42, 43, 53, 69, 77, 79,\n 87, 95, 101, 102, 103, 104, 109, 110, 111, 113, 115, 117, 119, 123, 135, 137,\n 139, 143, 161, 179, 389, 427, 465, 512, 513, 514, 515, 526, 530, 531, 532,\n 540, 548, 554, 556, 563, 587, 601, 636, 989, 990, 993, 995, 1719, 1720, 1723,\n 2049, 3659, 4045, 4190, 5060, 5061, 6000, 6566, 6665, 6666, 6667, 6668, 6669,\n 6679, 6697, 10080,\n]);\n\nfunction osAssignedPort(host: string): Promise<number> {\n return new Promise((resolve, reject) => {\n const server = net.createServer();\n server.unref();\n server.once(\"error\", reject);\n server.listen(0, host, () => {\n const { port } = server.address() as net.AddressInfo;\n server.close(() => resolve(port));\n });\n });\n}\n\n/**\n * A port nothing is listening on right now, taken from the OS's ephemeral\n * range so it neither collides with whatever else the machine runs nor hits\n * `BAD_PORTS`. The port is released again before this resolves, so the\n * caller's server has to bind it promptly.\n */\nexport async function freePort(host: string): Promise<number> {\n for (;;) {\n const port = await osAssignedPort(host);\n if (!BAD_PORTS.has(port)) return port;\n }\n}\n\n// Wait for the port to be available. A cold `npx pocketbase-server` on a CI\n// runner can take well over the five seconds the old default allowed.\nexport function waitForPort(\n port: number,\n host: string,\n maxAttempts = 60,\n): Promise<void> {\n return new Promise((resolve, reject) => {\n let attempts = 0;\n\n const tryConnect = () => {\n attempts++;\n\n const socket = new net.Socket();\n\n const onError = () => {\n socket.destroy();\n\n if (attempts === maxAttempts) {\n reject(\n new Error(`Timed out waiting for port ${port} to be available`),\n );\n return;\n }\n\n setTimeout(tryConnect, 500);\n };\n\n socket.once(\"error\", onError);\n\n socket.connect(port, host, () => {\n socket.destroy();\n resolve();\n });\n };\n\n tryConnect();\n });\n}\n\n/**\n * `fetch` wraps the interesting part in `cause`: an errno error for a\n * connection that was refused, or a bare string such as \"bad port\" for a\n * request undici declined to make.\n */\nfunction describeFetchError(error: unknown): string {\n if (!(error instanceof Error)) return String(error);\n const { cause } = error as Error & { cause?: unknown };\n if (cause instanceof Error) {\n const code = (cause as NodeJS.ErrnoException).code;\n return code || cause.message || error.message;\n }\n if (cause !== undefined) return String(cause);\n return error.message;\n}\n\n// Wait for the health check to be successful\nexport function waitForHealth(url: string, maxAttempts = 60): Promise<void> {\n return new Promise((resolve, reject) => {\n let attempts = 0;\n let lastFailure = \"no attempt made\";\n\n const tryHealth = async () => {\n attempts++;\n\n try {\n const response = await fetch(`${url}/api/health`);\n if (response.status === 200) {\n resolve();\n return;\n }\n lastFailure = `HTTP ${response.status}`;\n } catch (error) {\n lastFailure = describeFetchError(error);\n }\n\n if (attempts === maxAttempts) {\n reject(\n new Error(\n `Timed out waiting for health check at ${url}/api/health (last attempt: ${lastFailure})`,\n ),\n );\n return;\n }\n\n setTimeout(tryHealth, 500);\n };\n\n tryHealth();\n });\n}\n","import { existsSync, readdirSync, readFileSync } from \"node:fs\";\nimport path from \"node:path\";\nimport PocketBase from \"pocketbase\";\nimport { detect } from \"package-manager-detector\";\nimport { resolveCommand } from \"package-manager-detector/commands\";\nimport spawn from \"cross-spawn\";\nimport { freePort, waitForPort, waitForHealth } from \"./net\";\nimport type { Options } from \"../core/types\";\nimport {\n DATA_DIR,\n MIGRATIONS_DIR,\n POCKETBASE_BIN_ENV,\n} from \"../core/constants\";\n\n/**\n * PocketBase names migration files with a 1-second-resolution Unix timestamp\n * (e.g. `1776099881_created_users.js`). Two schema operations issued in the\n * same wall-clock second produce files that sort alphabetically by their\n * action/collection suffix — which reverses the intended order whenever a\n * later migration depends on an earlier one. Wait out the full second between\n * migration-producing calls so the timestamps stay distinct.\n */\nconst MIGRATION_DELAY_MS = 1100;\n\nexport function migrationDelay(): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, MIGRATION_DELAY_MS));\n}\n\nexport function getMigrationFile(\n collectionName: string,\n action: \"created\" | \"deleted\" | \"updated\",\n options: Options,\n): string | undefined {\n const ending = `${action}_${collectionName}.js`;\n\n // find last file with ending in migrations dir\n const migrationFiles = readdirSync(\n path.join(options.root, MIGRATIONS_DIR),\n ).filter((file) => file.endsWith(ending));\n\n const migrationFile = migrationFiles.sort().pop();\n\n if (!migrationFile) {\n return undefined;\n }\n\n return path.join(options.root, MIGRATIONS_DIR, migrationFile);\n}\n\nexport function getPocketbaseMetadata(cwd: string): {\n pocketbaseUrl: string;\n vitePort: number;\n} | null {\n const metadataPath = path.join(\n cwd,\n \"node_modules\",\n \".vite\",\n \"_pocketbase_metadata.json\",\n );\n if (existsSync(metadataPath)) {\n return JSON.parse(readFileSync(metadataPath, \"utf8\"));\n }\n return null;\n}\n\nexport async function authWithRetries(\n pb: PocketBase,\n email: string,\n password: string,\n) {\n // Retry authentication up to 3 times with 100ms backoff\n let authSuccess = false;\n for (let attempt = 1; attempt <= 3; attempt++) {\n try {\n await pb.collection(\"_superusers\").authWithPassword(email, password);\n authSuccess = true;\n break;\n } catch {\n if (attempt < 3) {\n await new Promise((resolve) => setTimeout(resolve, 100));\n }\n }\n }\n\n if (!authSuccess) {\n throw new Error(\n \"Failed to authenticate with PocketBase. Check your superuser credentials.\",\n );\n }\n}\n\n/**\n * The command that runs PocketBase with the given arguments (`serve --dir\n * ...`).\n *\n * With `VELA_POCKETBASE_BIN` (`POCKETBASE_BIN_ENV`) set, that binary itself:\n * the caller has resolved it, and nothing about the project's package manager\n * is consulted. `pocketbase-server`'s own bin only forwards its arguments to\n * the binary, so they are the same either way. The value has to be an\n * absolute path to a file that exists; anything else is an error rather than\n * a quiet fall back to the package manager, since whoever set it meant it.\n * Unset or empty, the server is started as before, through the project's\n * package manager (`npx --yes pocketbase-server ...`, `pnpm dlx ...`), which\n * the integration harness and direct callers of this library rely on.\n */\nexport async function pocketbaseCommand(\n cwd: string,\n serverArgs: string[],\n env: Record<string, string | undefined> = process.env,\n): Promise<{ command: string; args: string[] }> {\n const bin = env[POCKETBASE_BIN_ENV];\n if (bin) {\n if (!path.isAbsolute(bin)) {\n throw new Error(\n `${POCKETBASE_BIN_ENV} must be an absolute path to the PocketBase binary; it is \"${bin}\".`,\n );\n }\n if (!existsSync(bin)) {\n throw new Error(\n `${POCKETBASE_BIN_ENV} points at ${bin}, which does not exist.`,\n );\n }\n return { command: bin, args: [...serverArgs] };\n }\n\n const packageManager = (await detect({ cwd }))?.name ?? \"npm\";\n const { command, args } = resolveCommand(packageManager, \"execute\", [\n \"pocketbase-server\",\n ...serverArgs,\n ])!;\n\n // adding --yes as the first parameter helps avoiding the \"Need to install the following packages:\" message\n if (packageManager === \"npm\") args.unshift(\"--yes\");\n\n return { command, args };\n}\n\nexport async function withPocketbase(\n cwd: string,\n fn: (pb: PocketBase) => Promise<void>,\n) {\n const dir = path.join(cwd, DATA_DIR);\n const migrationsDir = path.join(cwd, MIGRATIONS_DIR);\n const host = \"localhost\";\n\n if (!existsSync(dir)) {\n throw new Error(\"PocketBase data directory does not exist\");\n }\n\n // First check if the server is already running by reading node_modules/.vite/_pocketbase_metadata.json\n const metadata = getPocketbaseMetadata(cwd);\n if (metadata) {\n if (metadata.pocketbaseUrl) {\n const pb = new PocketBase(metadata.pocketbaseUrl);\n await authWithRetries(\n pb,\n process.env.POCKETBASE_SUPERUSER_EMAIL!,\n process.env.POCKETBASE_SUPERUSER_PASSWORD!,\n );\n await fn(pb);\n return;\n }\n }\n\n const port = await freePort(host);\n const { command, args } = await pocketbaseCommand(cwd, [\n \"serve\",\n \"--dir\",\n dir,\n \"--migrationsDir\",\n migrationsDir,\n \"--http\",\n `${host}:${port}`,\n ]);\n\n // Start the PocketBase server process. A package manager wrapper (`npx`)\n // spawns the real binary as a grandchild; put the tree in its own process\n // group so it can be killed as a whole, otherwise `pocketbase serve` outlives\n // us and keeps the data directory open.\n const detached = process.platform !== \"win32\";\n const serverProcess = spawn(command, args, {\n cwd,\n stdio: \"ignore\",\n detached,\n });\n\n // A wrapper that dies before the server listens (missing binary, bad\n // arguments) would otherwise only surface as a port timeout a minute later.\n const exited = new Promise<never>((_, reject) => {\n serverProcess.once(\"exit\", (code, signal) => {\n reject(\n new Error(\n `PocketBase (${command}) exited before listening on ${host}:${port} (${signal ?? `code ${code}`})`,\n ),\n );\n });\n serverProcess.once(\"error\", reject);\n });\n\n try {\n // Wait for the server to be ready\n await Promise.race([\n (async () => {\n await waitForPort(port, host);\n await waitForHealth(`http://${host}:${port}`);\n })(),\n exited,\n ]);\n\n const pb = new PocketBase(`http://${host}:${port}`);\n await authWithRetries(\n pb,\n process.env.POCKETBASE_SUPERUSER_EMAIL!,\n process.env.POCKETBASE_SUPERUSER_PASSWORD!,\n );\n await fn(pb);\n } finally {\n // Ensure we always clean up the process tree\n stopProcessTree(serverProcess, detached);\n }\n}\n\nfunction stopProcessTree(\n child: ReturnType<typeof spawn>,\n detached: boolean,\n): void {\n if (detached && child.pid) {\n try {\n process.kill(-child.pid, \"SIGTERM\");\n return;\n } catch {\n // Group already gone or unsupported; fall through to the plain kill.\n }\n }\n child.kill();\n}\n"],"mappings":";;;;;;;;;;AAWA,IAAaQ,oBAAiC,IAAI,IAAI;CACpD;CAAG;CAAG;CAAG;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CACzE;CAAI;CAAI;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CACzE;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CACtE;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAM;CAAM;CACxE;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;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,GAAGjD,EAAK,GAAGE;CACb,CAAC,GAMKkD,IAAW,QAAQ,aAAa,SAChCC,IAAgB3D,EAAM4D,GAASP,GAAM;EACzC;EACA,OAAO;EACP;CACF,CAAC,GAIKQ,IAAS,IAAI,SAAgB,GAAG,MAAW;EAQ/C,AAPAF,EAAc,KAAK,SAAS,GAAM,MAAW;GAC3C,EACE,gBAAI,MACF,eAAeC,EAAQ,+BAA+BtD,EAAK,GAAGE,EAAK,IAAIsD,KAAU,QAAQC,IAAO,EAClG,CACF;EACF,CAAC,GACDJ,EAAc,KAAK,SAAStD,CAAM;CACpC,CAAC;CAED,IAAI;EAEF,MAAM,QAAQ,KAAK,EAChB,YAAY;GAEX,AADA,MAAMK,EAAYF,GAAMF,CAAI,GAC5B,MAAMY,EAAc,UAAUZ,EAAK,GAAGE,GAAM;EAC9C,EAAA,CAAG,GACHqD,CACF,CAAC;EAED,IAAMlB,IAAK,IAAI5C,EAAW,UAAUO,EAAK,GAAGE,GAAM;EAMlD,AALA,MAAMgC,EACJG,GACA,QAAQ,IAAI,4BACZ,QAAQ,IAAI,6BACd,GACA,MAAMc,EAAGd,CAAE;CACb,UAAU;EAER,EAAgBgB,GAAeD,CAAQ;CACzC;AACF;AAEA,SAASM,EACP,GACA,GACM;CACN,IAAIN,KAAYO,EAAM,KACpB,IAAI;EACF,QAAQ,KAAK,CAACA,EAAM,KAAK,SAAS;EAClC;CACF,QAAQ,CAER;CAEF,EAAM,KAAK;AACb"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { n as e, s as t } from "./providers-DrK_hjSr.js";
|
|
2
|
-
import { readEnvVarNames as n } from "./env-vars-
|
|
2
|
+
import { readEnvVarNames as n } from "./env-vars-C3TSZc4f.js";
|
|
3
3
|
import r from "node:fs";
|
|
4
4
|
import i from "node:path";
|
|
5
5
|
// src/runtime/providers.ts
|
|
@@ -34,4 +34,4 @@ function s(e) {
|
|
|
34
34
|
}
|
|
35
35
|
export { a as detectProviders };
|
|
36
36
|
|
|
37
|
-
//# sourceMappingURL=providers-
|
|
37
|
+
//# sourceMappingURL=providers-BEjDonyG.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"providers-
|
|
1
|
+
{"version":3,"file":"providers-BEjDonyG.js","names":["capabilityName","providerMarkers","fs","path","detectProviders","detected","present","markerProbe","root","pattern","patterns","ids","provider","capability","envNames","dependencies","marker","readEnvVarNames","readDependencies","file","pkg"],"sources":["../../src/runtime/providers.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport path from \"node:path\";\nimport { capabilityName, providerMarkers } from \"../core/providers\";\nimport type { DetectedProviders, Pattern, ProviderMarker } from \"../core/types\";\nimport { readEnvVarNames } from \"./env-vars\";\n\ntype DetectablePattern = Pick<\n Pattern,\n \"slug\" | \"providers\" | \"inheritsProvider\"\n>;\n\n/**\n * The provider in use for each capability, read from what the providers left\n * in the project. Nothing records the choice, so this is the only way to know\n * it. A pattern that inherits its provider is skipped: its files say nothing\n * the capability it is built on doesn't already.\n *\n * The registry is passed in rather than imported, so this module and the\n * package entry don't import each other.\n */\nexport function detectProviders(\n root: string,\n patterns: readonly DetectablePattern[],\n): DetectedProviders {\n const detected: DetectedProviders = { providers: {}, ambiguous: [] };\n const present = markerProbe(root);\n\n for (const pattern of patterns) {\n if (!pattern.providers?.length || pattern.inheritsProvider) continue;\n const ids = pattern.providers\n .filter((provider) => providerMarkers(provider).some(present))\n .map((provider) => provider.id);\n\n const capability = capabilityName(pattern.slug);\n if (ids.length === 1) detected.providers[capability] = ids[0];\n if (ids.length > 1) detected.ambiguous.push({ capability, ids });\n }\n\n return detected;\n}\n\n/** Checks one marker against the project; `src/env.ts` and `package.json` are read once. */\nfunction markerProbe(root: string): (marker: ProviderMarker) => boolean {\n let envNames: Set<string> | undefined;\n let dependencies: Set<string> | undefined;\n\n return (marker) => {\n if (\"env\" in marker) {\n envNames ??= readEnvVarNames(root);\n return envNames.has(marker.env);\n }\n if (\"path\" in marker) {\n return fs.existsSync(path.join(root, marker.path));\n }\n dependencies ??= readDependencies(root);\n return dependencies.has(marker.dependency);\n };\n}\n\nfunction readDependencies(root: string): Set<string> {\n const file = path.join(root, \"package.json\");\n if (!fs.existsSync(file)) return new Set();\n try {\n const pkg = JSON.parse(fs.readFileSync(file, \"utf8\")) as {\n dependencies?: Record<string, string>;\n devDependencies?: Record<string, string>;\n };\n return new Set([\n ...Object.keys(pkg.dependencies ?? {}),\n ...Object.keys(pkg.devDependencies ?? {}),\n ]);\n } catch {\n return new Set();\n }\n}\n"],"mappings":";;;;;AAoBA,SAAgBI,EACd,GACA,GACmB;CACnB,IAAMC,IAA8B;EAAE,WAAW,CAAC;EAAG,WAAW,CAAC;CAAE,GAC7DC,IAAUC,EAAYC,CAAI;CAEhC,KAAK,IAAMC,KAAWC,GAAU;EAC9B,IAAI,CAACD,EAAQ,WAAW,UAAUA,EAAQ,kBAAkB;EAC5D,IAAME,IAAMF,EAAQ,UACjB,QAAQ,MAAaR,EAAgBW,CAAQ,CAAC,CAAC,KAAKN,CAAO,CAAC,CAAC,CAC7D,KAAK,MAAaM,EAAS,EAAE,GAE1BC,IAAab,EAAeS,EAAQ,IAAI;EAE9C,AADIE,EAAI,WAAW,MAAG,EAAS,UAAUE,KAAcF,EAAI,KACvDA,EAAI,SAAS,KAAGN,EAAS,UAAU,KAAK;GAAE;GAAY;EAAI,CAAC;CACjE;CAEA,OAAOA;AACT;AAGA,SAASE,EAAY,GAAmD;CACtE,IAAIO,GACAC;CAEJ,QAAQ,MACF,SAASC,KACX,MAAaC,EAAgBT,CAAI,GAC1BM,EAAS,IAAIE,EAAO,GAAG,KAE5B,UAAUA,IACLd,EAAG,WAAWC,EAAK,KAAKK,GAAMQ,EAAO,IAAI,CAAC,KAEnD,MAAiBE,EAAiBV,CAAI,GAC/BO,EAAa,IAAIC,EAAO,UAAU;AAE7C;AAEA,SAASE,EAAiB,GAA2B;CACnD,IAAMC,IAAOhB,EAAK,KAAKK,GAAM,cAAc;CAC3C,IAAI,CAACN,EAAG,WAAWiB,CAAI,GAAG,uBAAO,IAAI,IAAI;CACzC,IAAI;EACF,IAAMC,IAAM,KAAK,MAAMlB,EAAG,aAAaiB,GAAM,MAAM,CAAC;EAIpD,uBAAO,IAAI,IAAI,CACb,GAAG,OAAO,KAAKC,EAAI,gBAAgB,CAAC,CAAC,GACrC,GAAG,OAAO,KAAKA,EAAI,mBAAmB,CAAC,CAAC,CAC1C,CAAC;CACH,QAAQ;EACN,uBAAO,IAAI,IAAI;CACjB;AACF"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import "./constants-
|
|
1
|
+
import "./constants-E1I-__KI.js";
|
|
2
2
|
import { t as e } from "./errors-DdSUZI8f.js";
|
|
3
3
|
// node_modules/change-case/dist/index.js
|
|
4
4
|
var t = /([\p{Ll}\d])(\p{Lu})/gu, n = /(\p{Lu})([\p{Lu}][\p{Ll}])/gu, r = /(\d)\p{Ll}|(\p{L})\d/u, i = /[^\p{L}\d]+/giu, a = "$1\0$2", o = "";
|
|
@@ -92,25 +92,29 @@ function C({ features: e, routeGroups: t }) {
|
|
|
92
92
|
};
|
|
93
93
|
return e.auth ? n.app ?? n.public : n.public;
|
|
94
94
|
}
|
|
95
|
-
function w(e, t) {
|
|
95
|
+
function w(e, { features: t, routeGroups: n }) {
|
|
96
|
+
let r = (n ?? { app: "(app)" }).app;
|
|
97
|
+
return !!(t.auth && r && e.fileBase.split("/").includes(r));
|
|
98
|
+
}
|
|
99
|
+
function T(e, t) {
|
|
96
100
|
return [
|
|
97
101
|
b,
|
|
98
102
|
e,
|
|
99
103
|
t
|
|
100
104
|
].filter(Boolean).join("/");
|
|
101
105
|
}
|
|
102
|
-
function
|
|
106
|
+
function E(e, t) {
|
|
103
107
|
return p(t === "scaffold" ? e.pluralDisplayName : e.displayName);
|
|
104
108
|
}
|
|
105
|
-
function
|
|
109
|
+
function D(e) {
|
|
106
110
|
return `/${(e.startsWith(`${b}/`) ? e.slice(11) : e).split("/").filter((e) => !(e.startsWith("(") && e.endsWith(")"))).join("/")}`;
|
|
107
111
|
}
|
|
108
|
-
function
|
|
112
|
+
function O(e) {
|
|
109
113
|
let t = [];
|
|
110
114
|
for (let n of e.matchAll(x)) t.push(n[1]);
|
|
111
115
|
return t;
|
|
112
116
|
}
|
|
113
|
-
function
|
|
117
|
+
function k(t) {
|
|
114
118
|
if (t.startsWith("/")) throw new e(`Route must not start with "/". Got: "${t}"`);
|
|
115
119
|
if (t.startsWith(`${b}/`) || t === b) throw new e(`Route must not start with "${b}/" — paths are rooted there automatically. Got: "${t}"`);
|
|
116
120
|
let n = t.split("/");
|
|
@@ -121,27 +125,27 @@ function O(t) {
|
|
|
121
125
|
if (!S.test(r)) throw new e(`Route segment "${r}" contains invalid characters. Allowed: letters, digits, underscore, dash, brackets, parentheses.`);
|
|
122
126
|
}
|
|
123
127
|
}
|
|
124
|
-
function
|
|
128
|
+
function A(e) {
|
|
125
129
|
return e.split("/").some((e) => e.startsWith("(") && e.endsWith(")"));
|
|
126
130
|
}
|
|
127
|
-
function
|
|
131
|
+
function j(e, t, n, r) {
|
|
128
132
|
if (e === void 0 || e === "") {
|
|
129
|
-
let e =
|
|
133
|
+
let e = E(t, r), i = T(C(n), e);
|
|
130
134
|
return {
|
|
131
135
|
fileBase: i,
|
|
132
|
-
urlBase:
|
|
133
|
-
dynamicParams:
|
|
136
|
+
urlBase: D(i),
|
|
137
|
+
dynamicParams: O(i)
|
|
134
138
|
};
|
|
135
139
|
}
|
|
136
|
-
|
|
137
|
-
let i =
|
|
140
|
+
k(e);
|
|
141
|
+
let i = T(A(e) ? null : C(n), e);
|
|
138
142
|
return {
|
|
139
143
|
fileBase: i,
|
|
140
|
-
urlBase:
|
|
141
|
-
dynamicParams:
|
|
144
|
+
urlBase: D(i),
|
|
145
|
+
dynamicParams: O(i)
|
|
142
146
|
};
|
|
143
147
|
}
|
|
144
|
-
function
|
|
148
|
+
function M(e) {
|
|
145
149
|
return {
|
|
146
150
|
list: e.fileBase,
|
|
147
151
|
new: `${e.fileBase}/new`,
|
|
@@ -149,7 +153,7 @@ function j(e) {
|
|
|
149
153
|
edit: `${e.fileBase}/[id]/edit`
|
|
150
154
|
};
|
|
151
155
|
}
|
|
152
|
-
function
|
|
156
|
+
function N(e) {
|
|
153
157
|
return {
|
|
154
158
|
list: e.urlBase,
|
|
155
159
|
new: `${e.urlBase}/new`,
|
|
@@ -157,6 +161,6 @@ function M(e) {
|
|
|
157
161
|
edit: `${e.urlBase}/[id]/edit`
|
|
158
162
|
};
|
|
159
163
|
}
|
|
160
|
-
export {
|
|
164
|
+
export { N as a, p as c, M as i, d as l, w as n, u as o, j as r, f as s, C as t, m as u };
|
|
161
165
|
|
|
162
|
-
//# sourceMappingURL=route-
|
|
166
|
+
//# sourceMappingURL=route-9ZVJZkYu.js.map
|