@velastack/patterns 0.11.0 → 0.13.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +21 -2
- package/dist/chunks/{collections-BYcVyY9O.js → collections-zEoRuILr.js} +2 -2
- package/dist/chunks/{collections-BYcVyY9O.js.map → collections-zEoRuILr.js.map} +1 -1
- package/dist/chunks/constants-CUv536Rj.js +87 -0
- package/dist/chunks/constants-CUv536Rj.js.map +1 -0
- package/dist/chunks/{currency.server-Dwz8LgvP.js → currency.server-DygAf6a1.js} +2 -2
- package/dist/chunks/{currency.server-Dwz8LgvP.js.map → currency.server-DygAf6a1.js.map} +1 -1
- package/dist/chunks/{env-vars-0hvKe55u.js → env-vars-XvAeH6u5.js} +3 -3
- package/dist/chunks/{env-vars-0hvKe55u.js.map → env-vars-XvAeH6u5.js.map} +1 -1
- package/dist/chunks/{generate-Df7t5Nbk.js → generate-BtWZCvuO.js} +3 -3
- package/dist/chunks/{generate-Df7t5Nbk.js.map → generate-BtWZCvuO.js.map} +1 -1
- package/dist/chunks/{generate-BOuNjssv.js → generate-Cbg-Z3sA.js} +2 -2
- package/dist/chunks/{generate-BOuNjssv.js.map → generate-Cbg-Z3sA.js.map} +1 -1
- package/dist/chunks/{generate-CNabcEBx.js → generate-Crdzw45a.js} +2 -2
- package/dist/chunks/{generate-CNabcEBx.js.map → generate-Crdzw45a.js.map} +1 -1
- package/dist/chunks/{generate-DoHn_xJZ.js → generate-DgZhFNjO.js} +22 -22
- package/dist/chunks/generate-DgZhFNjO.js.map +1 -0
- package/dist/chunks/{generate-l2JZTRKb.js → generate-DjuhSibA.js} +84 -84
- package/dist/chunks/generate-DjuhSibA.js.map +1 -0
- package/dist/chunks/{generate.runtime-DqLmhrsM.js → generate.runtime-2GD2E1NK.js} +6 -6
- package/dist/chunks/{generate.runtime-DqLmhrsM.js.map → generate.runtime-2GD2E1NK.js.map} +1 -1
- package/dist/chunks/{generate.runtime-T7JLE4Wc.js → generate.runtime-4TxcYKld.js} +3 -3
- package/dist/chunks/{generate.runtime-T7JLE4Wc.js.map → generate.runtime-4TxcYKld.js.map} +1 -1
- package/dist/chunks/{generate.runtime-BoYwV0nt.js → generate.runtime-7sU7RzIA.js} +2 -2
- package/dist/chunks/{generate.runtime-BoYwV0nt.js.map → generate.runtime-7sU7RzIA.js.map} +1 -1
- package/dist/chunks/{generate.runtime-q17D7QUT.js → generate.runtime-B-WOQsda.js} +3 -3
- package/dist/chunks/{generate.runtime-q17D7QUT.js.map → generate.runtime-B-WOQsda.js.map} +1 -1
- package/dist/chunks/{generate.runtime-DiqfbDfk.js → generate.runtime-B2DI0x05.js} +2 -2
- package/dist/chunks/{generate.runtime-DiqfbDfk.js.map → generate.runtime-B2DI0x05.js.map} +1 -1
- package/dist/chunks/{generate.runtime-Du84quuK.js → generate.runtime-B8y_l-6N.js} +5 -5
- package/dist/chunks/{generate.runtime-Du84quuK.js.map → generate.runtime-B8y_l-6N.js.map} +1 -1
- package/dist/chunks/{generate.runtime-BC6CBKh6.js → generate.runtime-BEvi6bml.js} +3 -3
- package/dist/chunks/{generate.runtime-BC6CBKh6.js.map → generate.runtime-BEvi6bml.js.map} +1 -1
- package/dist/chunks/{generate.runtime-DJ5uF6EN.js → generate.runtime-BO1KyRcJ.js} +2 -2
- package/dist/chunks/{generate.runtime-DJ5uF6EN.js.map → generate.runtime-BO1KyRcJ.js.map} +1 -1
- package/dist/chunks/{generate.runtime-BP31tAcD.js → generate.runtime-BPVZsAL0.js} +4 -4
- package/dist/chunks/{generate.runtime-BP31tAcD.js.map → generate.runtime-BPVZsAL0.js.map} +1 -1
- package/dist/chunks/{generate.runtime-CHUCMVa2.js → generate.runtime-BfM3dX_R.js} +2 -2
- package/dist/chunks/{generate.runtime-CHUCMVa2.js.map → generate.runtime-BfM3dX_R.js.map} +1 -1
- package/dist/chunks/{generate.runtime-DSs4gVRU.js → generate.runtime-BfQlxsWK.js} +7 -7
- package/dist/chunks/{generate.runtime-DSs4gVRU.js.map → generate.runtime-BfQlxsWK.js.map} +1 -1
- package/dist/chunks/{generate.runtime-zr6uIHCd.js → generate.runtime-BsjcGBme.js} +2 -2
- package/dist/chunks/{generate.runtime-zr6uIHCd.js.map → generate.runtime-BsjcGBme.js.map} +1 -1
- package/dist/chunks/{generate.runtime-D677SB4v.js → generate.runtime-ByC9kOl2.js} +2 -2
- package/dist/chunks/{generate.runtime-D677SB4v.js.map → generate.runtime-ByC9kOl2.js.map} +1 -1
- package/dist/chunks/{generate.runtime-bN61eWkc.js → generate.runtime-C2pIioyZ.js} +6 -6
- package/dist/chunks/{generate.runtime-bN61eWkc.js.map → generate.runtime-C2pIioyZ.js.map} +1 -1
- package/dist/chunks/{generate.runtime-BnqS_Zq8.js → generate.runtime-C4hyve9h.js} +3 -3
- package/dist/chunks/{generate.runtime-BnqS_Zq8.js.map → generate.runtime-C4hyve9h.js.map} +1 -1
- package/dist/chunks/{generate.runtime-BqCbJ-No.js → generate.runtime-C9yduilW.js} +3 -3
- package/dist/chunks/{generate.runtime-BqCbJ-No.js.map → generate.runtime-C9yduilW.js.map} +1 -1
- package/dist/chunks/{generate.runtime-CIvecd9c.js → generate.runtime-CEd3qCtW.js} +4 -4
- package/dist/chunks/{generate.runtime-CIvecd9c.js.map → generate.runtime-CEd3qCtW.js.map} +1 -1
- package/dist/chunks/{generate.runtime-C4LUUuq7.js → generate.runtime-CHaE6Mm9.js} +3 -3
- package/dist/chunks/{generate.runtime-C4LUUuq7.js.map → generate.runtime-CHaE6Mm9.js.map} +1 -1
- package/dist/chunks/{generate.runtime-nyJ6v56q.js → generate.runtime-CXGiQWDK.js} +4 -4
- package/dist/chunks/{generate.runtime-nyJ6v56q.js.map → generate.runtime-CXGiQWDK.js.map} +1 -1
- package/dist/chunks/{generate.runtime-Bvjj3zn0.js → generate.runtime-CvtSK0E1.js} +3 -3
- package/dist/chunks/{generate.runtime-Bvjj3zn0.js.map → generate.runtime-CvtSK0E1.js.map} +1 -1
- package/dist/chunks/{generate.runtime-DERcpgc-.js → generate.runtime-DGmpjkRe.js} +4 -4
- package/dist/chunks/{generate.runtime-DERcpgc-.js.map → generate.runtime-DGmpjkRe.js.map} +1 -1
- package/dist/chunks/{generate.runtime-e_BkDyP0.js → generate.runtime-DI73x08q.js} +2 -2
- package/dist/chunks/{generate.runtime-e_BkDyP0.js.map → generate.runtime-DI73x08q.js.map} +1 -1
- package/dist/chunks/{generate.runtime-B84ymwlD.js → generate.runtime-DIkM5xIB.js} +2 -2
- package/dist/chunks/{generate.runtime-B84ymwlD.js.map → generate.runtime-DIkM5xIB.js.map} +1 -1
- package/dist/chunks/{generate.runtime-DuDcKDUl.js → generate.runtime-DRZDjZqw.js} +2 -2
- package/dist/chunks/{generate.runtime-DuDcKDUl.js.map → generate.runtime-DRZDjZqw.js.map} +1 -1
- package/dist/chunks/{generate.runtime-ByPcr9vJ.js → generate.runtime-DVUj1LJK.js} +3 -3
- package/dist/chunks/{generate.runtime-ByPcr9vJ.js.map → generate.runtime-DVUj1LJK.js.map} +1 -1
- package/dist/chunks/{generate.runtime-Cv3unKap.js → generate.runtime-Deg1Tz9u.js} +3 -3
- package/dist/chunks/{generate.runtime-Cv3unKap.js.map → generate.runtime-Deg1Tz9u.js.map} +1 -1
- package/dist/chunks/generate.runtime-DqYYJXAz.js +24 -0
- package/dist/chunks/generate.runtime-DqYYJXAz.js.map +1 -0
- package/dist/chunks/{generate.runtime-oUJUQRdg.js → generate.runtime-Du8puIJQ.js} +6 -6
- package/dist/chunks/{generate.runtime-oUJUQRdg.js.map → generate.runtime-Du8puIJQ.js.map} +1 -1
- package/dist/chunks/{generate.runtime-WPq7bHRA.js → generate.runtime-DzCVGruq.js} +2 -2
- package/dist/chunks/{generate.runtime-WPq7bHRA.js.map → generate.runtime-DzCVGruq.js.map} +1 -1
- package/dist/chunks/generate.runtime-TKR-qAJM.js +50 -0
- package/dist/chunks/generate.runtime-TKR-qAJM.js.map +1 -0
- package/dist/chunks/{generate.runtime-C7tlPKH1.js → generate.runtime-USnFqTbU.js} +4 -4
- package/dist/chunks/{generate.runtime-C7tlPKH1.js.map → generate.runtime-USnFqTbU.js.map} +1 -1
- package/dist/chunks/{generate.runtime-rLlDp4R6.js → generate.runtime-UrLaWKvN.js} +4 -4
- package/dist/chunks/{generate.runtime-rLlDp4R6.js.map → generate.runtime-UrLaWKvN.js.map} +1 -1
- package/dist/chunks/{generate.runtime-Dfz53sSK.js → generate.runtime-bWGwyz2U.js} +3 -3
- package/dist/chunks/{generate.runtime-Dfz53sSK.js.map → generate.runtime-bWGwyz2U.js.map} +1 -1
- package/dist/chunks/{generate.runtime-gZ4wfYBP.js → generate.runtime-g6qaIY3k.js} +6 -6
- package/dist/chunks/{generate.runtime-gZ4wfYBP.js.map → generate.runtime-g6qaIY3k.js.map} +1 -1
- package/dist/chunks/{generate.runtime-Cj-5fzbQ.js → generate.runtime-s9ai7PxV.js} +4 -4
- package/dist/chunks/{generate.runtime-Cj-5fzbQ.js.map → generate.runtime-s9ai7PxV.js.map} +1 -1
- package/dist/chunks/{generate.runtime-CVWCUn52.js → generate.runtime-taYl9Tg5.js} +4 -4
- package/dist/chunks/{generate.runtime-CVWCUn52.js.map → generate.runtime-taYl9Tg5.js.map} +1 -1
- package/dist/chunks/layout.svelte-Cb12mxua.js +65 -0
- package/dist/chunks/layout.svelte-Cb12mxua.js.map +1 -0
- package/dist/chunks/{modify-file-B4uJzOEj.js → modify-file-D9U2LXEa.js} +2 -2
- package/dist/chunks/{modify-file-B4uJzOEj.js.map → modify-file-D9U2LXEa.js.map} +1 -1
- package/dist/chunks/{pocketbase-BtN-wL8f.js → pocketbase-BTR3gI8o.js} +2 -2
- package/dist/chunks/{pocketbase-BtN-wL8f.js.map → pocketbase-BTR3gI8o.js.map} +1 -1
- package/dist/chunks/{providers-DRwJnSzb.js → providers-CpRRQdMg.js} +2 -2
- package/dist/chunks/{providers-DRwJnSzb.js.map → providers-CpRRQdMg.js.map} +1 -1
- package/dist/chunks/{shared-BbxLil4g.js → shared-CAjLx_8Z.js} +2 -2
- package/dist/chunks/{shared-BbxLil4g.js.map → shared-CAjLx_8Z.js.map} +1 -1
- package/dist/chunks/{site-VrqOvuiU.js → site-D0IuWkAR.js} +2 -2
- package/dist/chunks/{site-VrqOvuiU.js.map → site-D0IuWkAR.js.map} +1 -1
- package/dist/chunks/table-core-BKBoEStB.js +127 -0
- package/dist/chunks/table-core-BKBoEStB.js.map +1 -0
- package/dist/chunks/{test-setup-BtV6Gk9I.js → test-setup-CbCXmPkE.js} +3 -3
- package/dist/chunks/{test-setup-BtV6Gk9I.js.map → test-setup-CbCXmPkE.js.map} +1 -1
- package/dist/chunks/{ui-gG8i_Mzk.js → ui-B3Db8cQg.js} +3 -3
- package/dist/chunks/{ui-gG8i_Mzk.js.map → ui-B3Db8cQg.js.map} +1 -1
- package/dist/chunks/{whatsapp-DbjOxHaZ.js → whatsapp-Pya8Zi07.js} +2 -2
- package/dist/chunks/{whatsapp-DbjOxHaZ.js.map → whatsapp-Pya8Zi07.js.map} +1 -1
- package/dist/chunks/{write-result-DcqMefuP.js → write-result-BWXq9RRn.js} +12 -12
- package/dist/chunks/{write-result-DcqMefuP.js.map → write-result-BWXq9RRn.js.map} +1 -1
- package/dist/index.d.ts +181 -17
- package/dist/index.js +2391 -2228
- package/dist/index.js.map +1 -1
- package/package.json +6 -3
- package/dist/chunks/constants-Bdx8mp7v.js +0 -6
- package/dist/chunks/constants-Bdx8mp7v.js.map +0 -1
- package/dist/chunks/generate-DoHn_xJZ.js.map +0 -1
- package/dist/chunks/generate-l2JZTRKb.js.map +0 -1
- package/dist/chunks/table-core-BHFT-uMX.js +0 -127
- package/dist/chunks/table-core-BHFT-uMX.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"generate.runtime-Cj-5fzbQ.js","names":["FAILURE_HINT","NOT_FOUND_HINT","NOT_FOUND_HINT","dedent","getLogger","withPocketbase","migrationDelay","getMigrationFile","ensureSiteFile","withInMemoryScript","ensurePropsBinding","formatLikeSource","ensureImports","modifyOutcomeToFile","SvelteFile","fs","path","modifyLayoutServer","layoutPath","snippet","originalSource","sourceFile","Project","addUserProp","obj","loadArrow","loadFn","varDecl","SyntaxKind","directArrow","init","innerArrow","innerFnExpr","maybeFn","fnLike","params","first","original","nameNode","obp","el","parts","tail","currentName","body","expr","ret","inner","bodyExpr","AUTH_MENU_NAVBAR_ITEM","IMPORT_SNIPPET","FAILURE_HINT$1","NOT_FOUND_HINT$2","modifyRootLayoutSvelte","file","out","source","sf","FAILURE_HINT","NOT_FOUND_HINT$1","modifyHooksServer","hooksServerPath","callExpr","ce","args","firstArg","optionsObj","authProp","authInit","authObj","prProp","prInit","arr","VARIANTS","NOT_FOUND_HINT","modifySidebarMenuButton","filePath","to","variant","from","updated","generate","options","logger","creates","pb","input","userCollection","verificationTemplate","resetPasswordTemplate","confirmEmailChangeTemplate","migrationFile","modifies","pushResult","layoutServerFile","layoutCandidates","layoutFile","p","hooksServerFile","sidebarMenuButtonFile","siteFile"],"sources":["../../src/patterns/enable/auth/modifies/+layout.server.ts","../../src/patterns/enable/auth/modifies/root-layout.svelte.ts","../../src/patterns/enable/auth/modifies/hooks.server.ts","../../src/patterns/enable/auth/modifies/sidebar-menu-button.svelte.ts","../../src/patterns/enable/auth/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { Project, SyntaxKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport { formatLikeSource } from \"../../../../runtime/ts-morph-helpers\";\n\nexport function modifyLayoutServer(layoutPath: string): ModifyOutcome {\n if (!fs.existsSync(layoutPath)) {\n const snippet = dedent`\n\t\t\texport const load = async ({ locals }) => {\n\t\t\t\treturn { user: locals.pb.authStore.record };\n\t\t\t};\n\t\t`;\n\n fs.writeFileSync(layoutPath, snippet);\n return { status: \"success\", changed: true };\n }\n\n const originalSource = fs.readFileSync(layoutPath, \"utf8\");\n const project = new Project();\n const sourceFile = project.addSourceFileAtPath(layoutPath);\n\n // helper to add user property to an object literal if missing\n const addUserProp = (obj: import(\"ts-morph\").ObjectLiteralExpression) => {\n const hasUser = !!obj.getProperty(\"user\");\n if (!hasUser) {\n obj.addPropertyAssignment({\n name: \"user\",\n initializer: \"locals.pb.authStore.record\",\n });\n }\n };\n\n // find existing exported load (function or const with arrow)\n let loadArrow: import(\"ts-morph\").ArrowFunction | undefined;\n let loadFn:\n | import(\"ts-morph\").FunctionDeclaration\n | import(\"ts-morph\").FunctionExpression\n | undefined;\n\n const varDecl = sourceFile.getVariableDeclaration(\"load\");\n if (varDecl) {\n const vs = varDecl.getFirstAncestorByKind(SyntaxKind.VariableStatement);\n const isExported = !!vs?.hasExportKeyword();\n if (isExported) {\n const directArrow = varDecl.getInitializerIfKind(\n SyntaxKind.ArrowFunction,\n );\n if (directArrow) {\n loadArrow = directArrow;\n } else {\n const init = varDecl.getInitializer();\n if (init) {\n const innerArrow = init.getFirstDescendantByKind(\n SyntaxKind.ArrowFunction,\n );\n if (innerArrow) {\n loadArrow = innerArrow;\n } else {\n const innerFnExpr = init.getFirstDescendantByKind(\n SyntaxKind.FunctionExpression,\n );\n if (innerFnExpr) {\n loadFn = innerFnExpr;\n }\n }\n }\n }\n }\n }\n\n if (!loadArrow) {\n const maybeFn = sourceFile.getFunction(\"load\");\n if (maybeFn && maybeFn.isExported()) {\n loadFn = maybeFn;\n }\n }\n\n // if no load found, create one\n if (!loadArrow && !loadFn) {\n sourceFile.addFunction({\n isExported: true,\n isAsync: true,\n name: \"load\",\n parameters: [{ name: \"{ locals }\" }],\n statements: `return { user: locals.pb.authStore.record };`,\n });\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n }\n\n // normalize function-like to a single handle\n const fnLike:\n | import(\"ts-morph\").ArrowFunction\n | import(\"ts-morph\").FunctionDeclaration\n | import(\"ts-morph\").FunctionExpression = (loadArrow ?? loadFn!) as any;\n\n // ensure first parameter destructures locals, preserving existing information\n const params = fnLike.getParameters();\n if (params.length === 0) {\n fnLike.insertParameter(0, { name: \"{ locals }\" });\n } else {\n const first = params[0];\n const original = first.getStructure();\n const nameNode = first.getNameNode();\n if (nameNode.getKind() === SyntaxKind.ObjectBindingPattern) {\n const obp = nameNode as import(\"ts-morph\").ObjectBindingPattern;\n const hasLocals = obp\n .getElements()\n .some((el) => el.getName() === \"locals\");\n if (!hasLocals) {\n const parts = obp\n .getElements()\n .map((el) => el.getText())\n .filter(Boolean);\n const tail = parts.length > 0 ? \", \" + parts.join(\", \") : \"\";\n first.set({\n name: `{ locals${tail} }`,\n type: original.type,\n initializer: (original as any).initializer,\n });\n }\n } else {\n const currentName = first.getName();\n if (currentName !== \"locals\") {\n first.set({\n name: `{ locals, ...${currentName} }`,\n type: original.type,\n initializer: (original as any).initializer,\n });\n }\n }\n }\n\n // add user to returned object literals without altering other properties\n if (loadArrow) {\n const body = loadArrow.getBody();\n if (body.getKind() === SyntaxKind.Block) {\n const returns = body.getDescendantsOfKind(SyntaxKind.ReturnStatement);\n returns.forEach((ret) => {\n const expr = ret.getExpression();\n if (!expr) return;\n if (expr.getKind() === SyntaxKind.ObjectLiteralExpression) {\n addUserProp(expr as import(\"ts-morph\").ObjectLiteralExpression);\n } else if (expr.getKind() === SyntaxKind.ParenthesizedExpression) {\n const inner = (\n expr as import(\"ts-morph\").ParenthesizedExpression\n ).getExpression();\n if (inner.getKind() === SyntaxKind.ObjectLiteralExpression) {\n addUserProp(inner as import(\"ts-morph\").ObjectLiteralExpression);\n }\n }\n });\n } else {\n // concise body\n const bodyExpr = body as import(\"ts-morph\").Expression;\n if (bodyExpr.getKind() === SyntaxKind.ParenthesizedExpression) {\n const inner = (\n bodyExpr as import(\"ts-morph\").ParenthesizedExpression\n ).getExpression();\n if (inner.getKind() === SyntaxKind.ObjectLiteralExpression) {\n addUserProp(inner as import(\"ts-morph\").ObjectLiteralExpression);\n }\n } else if (bodyExpr.getKind() === SyntaxKind.ObjectLiteralExpression) {\n addUserProp(bodyExpr as import(\"ts-morph\").ObjectLiteralExpression);\n }\n }\n } else if (loadFn) {\n const body = loadFn.getBody();\n if (body) {\n const returns = body.getDescendantsOfKind(SyntaxKind.ReturnStatement);\n returns.forEach((ret) => {\n const expr = ret.getExpression();\n if (!expr) return;\n if (expr.getKind() === SyntaxKind.ObjectLiteralExpression) {\n addUserProp(expr as import(\"ts-morph\").ObjectLiteralExpression);\n } else if (expr.getKind() === SyntaxKind.ParenthesizedExpression) {\n const inner = (\n expr as import(\"ts-morph\").ParenthesizedExpression\n ).getExpression();\n if (inner.getKind() === SyntaxKind.ObjectLiteralExpression) {\n addUserProp(inner as import(\"ts-morph\").ObjectLiteralExpression);\n }\n }\n });\n }\n }\n\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return {\n status: \"success\",\n changed: sourceFile.getFullText() !== originalSource,\n };\n}\n","import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport {\n ensureImports,\n ensurePropsBinding,\n withInMemoryScript,\n} from \"../../../../runtime/ts-morph-helpers\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst AUTH_MENU_NAVBAR_ITEM = `\n\t\t<Navbar.Item\n\t\t\tclass=\"flex flex-col md:flex-row items-center space-y-2 md:space-y-0 md:space-x-4\"\n\t\t>\n\t\t\t<AuthMenu.Root>\n\t\t\t\t{#snippet user()}\n\t\t\t\t\t<AuthMenu.Trigger>\n\t\t\t\t\t\t<UserAvatar user={data.user} />\n\t\t\t\t\t</AuthMenu.Trigger>\n\n\t\t\t\t\t<AuthMenu.Content align=\"end\">\n\t\t\t\t\t\t<AuthMenu.Item href=\"/dashboard\">Dashboard</AuthMenu.Item>\n\t\t\t\t\t\t<AuthMenu.Group>\n\t\t\t\t\t\t\t<AuthMenu.Item href=\"/settings\">Settings</AuthMenu.Item>\n\t\t\t\t\t\t\t<AuthMenu.Item>\n\t\t\t\t\t\t\t\t<form action=\"/logout\" method=\"post\">\n\t\t\t\t\t\t\t\t\t<button type=\"submit\" class=\"contents\">Logout</button>\n\t\t\t\t\t\t\t\t</form>\n\t\t\t\t\t\t\t</AuthMenu.Item>\n\t\t\t\t\t\t</AuthMenu.Group>\n\t\t\t\t\t</AuthMenu.Content>\n\t\t\t\t{/snippet}\n\n\t\t\t\t{#snippet guest()}\n\t\t\t\t\t<Button\n\t\t\t\t\t\tclass=\"w-full justify-start md:justify-center md:w-auto\"\n\t\t\t\t\t\tvariant=\"ghost\"\n\t\t\t\t\t\thref=\"/login\">Login</Button\n\t\t\t\t\t>\n\t\t\t\t\t<Button\n\t\t\t\t\t\tclass=\"w-full justify-start md:justify-center md:w-auto\"\n\t\t\t\t\t\tvariant=\"outline\"\n\t\t\t\t\t\thref=\"/signup\">Sign up</Button\n\t\t\t\t\t>\n\t\t\t\t{/snippet}\n\t\t\t</AuthMenu.Root>\n\t\t</Navbar.Item>\n\t`;\n\nconst IMPORT_SNIPPET = dedent`\n import * as AuthMenu from '#lib/components/ui/auth-menu/index.js';\n import UserAvatar from '#lib/components/user-avatar.svelte';\n`;\n\nconst FAILURE_HINT = [\n \"Add the auth menu inside your <Navbar.List> in the root layout.\",\n \"\",\n \"Imports to add to the <script> tag:\",\n \"\",\n IMPORT_SNIPPET,\n \"\",\n \"Markup to add inside <Navbar.List>:\",\n AUTH_MENU_NAVBAR_ITEM,\n].join(\"\\n\");\n\nconst NOT_FOUND_HINT = [\n \"Create a root layout that includes an auth menu inside <Navbar.List>.\",\n \"\",\n \"Imports for the <script> tag:\",\n \"\",\n IMPORT_SNIPPET,\n \"\",\n \"Markup inside <Navbar.List>:\",\n AUTH_MENU_NAVBAR_ITEM,\n].join(\"\\n\");\n\nexport function modifyRootLayoutSvelte(layoutPath: string): ModifyOutcome {\n if (!fs.existsSync(layoutPath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const file = SvelteFile.fromPath(layoutPath);\n if (!file.hasElement(\"Navbar.List\")) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n if (file.hasElement(\"AuthMenu.Root\")) {\n return { status: \"success\", changed: false };\n }\n\n file.modifyScript((source) => {\n const { source: out } = withInMemoryScript(source, (sf) => {\n ensureImports(sf, [\n {\n namespaceImport: \"AuthMenu\",\n moduleSpecifier: \"#lib/components/ui/auth-menu/index.js\",\n },\n {\n defaultImport: \"UserAvatar\",\n moduleSpecifier: \"#lib/components/user-avatar.svelte\",\n },\n ]);\n // The menu reads `data.user`; the template's layout takes no props.\n ensurePropsBinding(sf, \"data\");\n });\n return out;\n });\n\n file.insertBeforeClosingTag(\"Navbar.List\", AUTH_MENU_NAVBAR_ITEM);\n file.writeTo(layoutPath);\n return { status: \"success\", changed: file.hasChanged() };\n}\n","import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { Project, SyntaxKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport { formatLikeSource } from \"../../../../runtime/ts-morph-helpers\";\n\nconst FAILURE_HINT = dedent`\n Configure handlePocketbase() with the auth option in hooks.server.ts:\n\n handlePocketbase({\n auth: { protectedRoutes: ['/(app)'] },\n });\n`;\n\nconst NOT_FOUND_HINT = dedent`\n Create src/hooks.server.ts with handlePocketbase:\n\n import { handlePocketbase } from '@velastack/pocketbase';\n\n export const handle = handlePocketbase({\n auth: { protectedRoutes: ['/(app)'] },\n });\n`;\n\nexport function modifyHooksServer(hooksServerPath: string): ModifyOutcome {\n if (!fs.existsSync(hooksServerPath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const originalSource = fs.readFileSync(hooksServerPath, \"utf8\");\n const project = new Project();\n const sourceFile = project.addSourceFileAtPath(hooksServerPath);\n\n // Find the handlePocketbase(...) call\n const callExpr = sourceFile\n .getDescendantsOfKind(SyntaxKind.CallExpression)\n .find((ce) => ce.getExpression().getText() === \"handlePocketbase\");\n\n if (!callExpr) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n const args = callExpr.getArguments();\n if (args.length === 0) {\n callExpr.addArgument(`{ auth: { protectedRoutes: ['/(app)'] } }`);\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n }\n\n const firstArg = args[0];\n if (firstArg.getKind() !== SyntaxKind.ObjectLiteralExpression) {\n callExpr.insertArgument(0, `{ auth: { protectedRoutes: ['/(app)'] } }`);\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n }\n\n const optionsObj = firstArg.asKindOrThrow(SyntaxKind.ObjectLiteralExpression);\n\n // Ensure auth property exists\n const authProp = optionsObj.getProperty(\"auth\");\n if (!authProp) {\n optionsObj.addPropertyAssignment({\n name: \"auth\",\n initializer: `{ protectedRoutes: ['/(app)'] }`,\n });\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n }\n\n // If auth exists, ensure protectedRoutes includes '/(app)'\n if (authProp.getKind() === SyntaxKind.PropertyAssignment) {\n const authInit = (\n authProp as import(\"ts-morph\").PropertyAssignment\n ).getInitializer();\n if (authInit && authInit.getKind() === SyntaxKind.ObjectLiteralExpression) {\n const authObj = authInit as import(\"ts-morph\").ObjectLiteralExpression;\n const prProp = authObj.getProperty(\"protectedRoutes\");\n if (!prProp) {\n authObj.addPropertyAssignment({\n name: \"protectedRoutes\",\n initializer: `['/(app)']`,\n });\n } else if (prProp.getKind() === SyntaxKind.PropertyAssignment) {\n const prInit = (\n prProp as import(\"ts-morph\").PropertyAssignment\n ).getInitializer();\n if (prInit && prInit.getKind() === SyntaxKind.ArrayLiteralExpression) {\n const arr = prInit as import(\"ts-morph\").ArrayLiteralExpression;\n const hasApp = arr\n .getElements()\n .some((el) => el.getText().replace(/['\"`]/g, \"\") === \"/(app)\");\n if (!hasApp) {\n arr.addElement(`'/(app)'`);\n }\n } else {\n (prProp as import(\"ts-morph\").PropertyAssignment).setInitializer(\n `['/(app)']`,\n );\n }\n }\n }\n }\n\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return {\n status: \"success\",\n changed: sourceFile.getFullText() !== originalSource,\n };\n}\n","import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst VARIANTS = [\n {\n from: \"'data-active': isActive,\",\n to: \"'data-active': isActive ? true : undefined,\",\n },\n {\n from: '\"data-active\": isActive,',\n to: '\"data-active\": isActive ? true : undefined,',\n },\n];\n\nconst NOT_FOUND_HINT = dedent`\n The shadcn-svelte sidebar component was not installed at the expected path.\n Run: vela enable auth (or install the 'sidebar' shadcn-svelte component).\n`;\n\nexport function modifySidebarMenuButton(filePath: string): ModifyOutcome {\n if (!fs.existsSync(filePath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const original = fs.readFileSync(filePath, \"utf8\");\n\n if (VARIANTS.some(({ to }) => original.includes(to))) {\n return { status: \"success\", changed: false };\n }\n\n const variant = VARIANTS.find(({ from }) => original.includes(from));\n if (!variant) {\n return { status: \"success\", changed: false };\n }\n\n const updated = original.replace(variant.from, variant.to);\n fs.writeFileSync(filePath, updated, \"utf8\");\n return { status: \"success\", changed: true };\n}\n","import path from \"node:path\";\nimport fs from \"node:fs\";\nimport { Options, Result, File } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport {\n getMigrationFile,\n migrationDelay,\n withPocketbase,\n} from \"../../../runtime/pocketbase\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { ensureSiteFile } from \"../../../runtime/site\";\n\nimport { modifyLayoutServer } from \"./modifies/+layout.server\";\nimport { modifyRootLayoutSvelte } from \"./modifies/root-layout.svelte\";\nimport { modifyHooksServer } from \"./modifies/hooks.server\";\nimport { modifySidebarMenuButton } from \"./modifies/sidebar-menu-button.svelte\";\n\nexport async function generate(options: Options) {\n const { input } = options;\n const logger = getLogger(options);\n\n let creates: File[] = [];\n\n // Update PocketBase\n await withPocketbase(options.root, async (pb) => {\n logger.info(\"Updating PocketBase mail settings\");\n await pb.settings.update({\n meta: {\n senderName: input.senderName,\n senderAddress: input.senderAddress,\n },\n });\n await migrationDelay();\n\n const userCollection = await pb.collections.getOne(\"users\");\n\n if (!userCollection) {\n throw new Error(\"Users collection not found\");\n }\n\n const verificationTemplate =\n userCollection.verificationTemplate.body.replace(\n \"{APP_URL}/_/#/auth/confirm-verification/{TOKEN}\",\n \"{APP_URL}/confirm-verification/{TOKEN}\",\n );\n const resetPasswordTemplate =\n userCollection.resetPasswordTemplate.body.replace(\n \"{APP_URL}/_/#/auth/confirm-reset/{TOKEN}\",\n \"{APP_URL}/confirm-reset/{TOKEN}\",\n );\n const confirmEmailChangeTemplate =\n userCollection.confirmEmailChangeTemplate.body.replace(\n \"{APP_URL}/_/#/auth/confirm-email-change/{TOKEN}\",\n \"{APP_URL}/confirm-email-change/{TOKEN}\",\n );\n\n logger.info(\"Locking down users collection rules and email templates\");\n // Update user auth rules to lock down access to the user's own account\n await pb.collections.update(\"users\", {\n listRule: \"@request.auth.id = id\",\n viewRule: \"@request.auth.id = id\",\n createRule: \"@request.auth.id = id\",\n updateRule: \"@request.auth.id = id\",\n deleteRule: \"@request.auth.id = id\",\n\n // Update email templates to VelaStack auth urls\n verificationTemplate: {\n body: verificationTemplate,\n },\n resetPasswordTemplate: {\n body: resetPasswordTemplate,\n },\n confirmEmailChangeTemplate: {\n body: confirmEmailChangeTemplate,\n },\n });\n await migrationDelay();\n\n const migrationFile = getMigrationFile(\"users\", \"updated\", options);\n if (migrationFile) {\n creates.push({\n path: migrationFile,\n language: \"ts\",\n content: fs.readFileSync(migrationFile, \"utf8\"),\n status: \"success\",\n });\n }\n });\n\n // Modify files\n const modifies: File[] = [];\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n logger.info(\"Modifying +layout.server.ts\");\n const layoutServerFile = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"+layout.server.ts\",\n );\n pushResult(\n modifyOutcomeToFile(layoutServerFile, modifyLayoutServer(layoutServerFile)),\n );\n\n logger.info(\"Modifying root layout\");\n // TODO: make this more robust by searching for Navbar.Root > Navbar.List\n // src/routes/(public)/root-layout.svelte is what vela creates by default\n const layoutCandidates = [\n path.join(options.root, \"src\", \"routes\", \"(public)\", \"root-layout.svelte\"),\n path.join(options.root, \"src\", \"routes\", \"root-layout.svelte\"),\n path.join(options.root, \"src\", \"routes\", \"(public)\", \"+layout.svelte\"),\n path.join(options.root, \"src\", \"routes\", \"+layout.svelte\"),\n ];\n const layoutFile =\n layoutCandidates.find((p) => fs.existsSync(p)) ?? layoutCandidates[0];\n pushResult(\n modifyOutcomeToFile(layoutFile, modifyRootLayoutSvelte(layoutFile)),\n );\n\n logger.info(\"Modifying hooks.server.ts\");\n const hooksServerFile = path.join(options.root, \"src\", \"hooks.server.ts\");\n pushResult(\n modifyOutcomeToFile(hooksServerFile, modifyHooksServer(hooksServerFile)),\n );\n\n logger.info(\"Modifying sidebar-menu-button.svelte\");\n const sidebarMenuButtonFile = path.join(\n options.root,\n \"src\",\n \"lib\",\n \"components\",\n \"ui\",\n \"sidebar\",\n \"sidebar-menu-button.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(\n sidebarMenuButtonFile,\n modifySidebarMenuButton(sidebarMenuButtonFile),\n ),\n );\n\n // The auth pages and the app sidebar show `site.name`.\n const siteFile = await ensureSiteFile(options);\n\n return {\n creates: siteFile ? [siteFile] : [],\n modifies,\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n } satisfies Result;\n}\n"],"mappings":";;;;;;;;;;;AAMA,SAAgBiB,EAAmB,GAAmC;CACpE,IAAI,CAACF,EAAG,WAAWG,CAAU,GAAG;EAC9B,IAAMC,IAAU,CAAM;;;;;EAOtB,OADAJ,EAAG,cAAcG,GAAYC,CAAO,GAC7B;GAAE,QAAQ;GAAW,SAAS;EAAK;CAC5C;CAEA,IAAMC,IAAiBL,EAAG,aAAaG,GAAY,MAAM,GAEnDG,IAAa,IADCC,EACD,CAAA,C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INT","NOT_FOUND_HINT","NOT_FOUND_HINT","dedent","getLogger","withPocketbase","migrationDelay","getMigrationFile","ensureSiteFile","withInMemoryScript","ensurePropsBinding","formatLikeSource","ensureImports","modifyOutcomeToFile","SvelteFile","fs","path","modifyLayoutServer","layoutPath","snippet","originalSource","sourceFile","Project","addUserProp","obj","loadArrow","loadFn","varDecl","SyntaxKind","directArrow","init","innerArrow","innerFnExpr","maybeFn","fnLike","params","first","original","nameNode","obp","el","parts","tail","currentName","body","expr","ret","inner","bodyExpr","AUTH_MENU_NAVBAR_ITEM","IMPORT_SNIPPET","FAILURE_HINT$1","NOT_FOUND_HINT$2","modifyRootLayoutSvelte","file","out","source","sf","FAILURE_HINT","NOT_FOUND_HINT$1","modifyHooksServer","hooksServerPath","callExpr","ce","args","firstArg","optionsObj","authProp","authInit","authObj","prProp","prInit","arr","VARIANTS","NOT_FOUND_HINT","modifySidebarMenuButton","filePath","to","variant","from","updated","generate","options","logger","creates","pb","input","userCollection","verificationTemplate","resetPasswordTemplate","confirmEmailChangeTemplate","migrationFile","modifies","pushResult","layoutServerFile","layoutCandidates","layoutFile","p","hooksServerFile","sidebarMenuButtonFile","siteFile"],"sources":["../../src/patterns/enable/auth/modifies/+layout.server.ts","../../src/patterns/enable/auth/modifies/root-layout.svelte.ts","../../src/patterns/enable/auth/modifies/hooks.server.ts","../../src/patterns/enable/auth/modifies/sidebar-menu-button.svelte.ts","../../src/patterns/enable/auth/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { Project, SyntaxKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport { formatLikeSource } from \"../../../../runtime/ts-morph-helpers\";\n\nexport function modifyLayoutServer(layoutPath: string): ModifyOutcome {\n if (!fs.existsSync(layoutPath)) {\n const snippet = dedent`\n\t\t\texport const load = async ({ locals }) => {\n\t\t\t\treturn { user: locals.pb.authStore.record };\n\t\t\t};\n\t\t`;\n\n fs.writeFileSync(layoutPath, snippet);\n return { status: \"success\", changed: true };\n }\n\n const originalSource = fs.readFileSync(layoutPath, \"utf8\");\n const project = new Project();\n const sourceFile = project.addSourceFileAtPath(layoutPath);\n\n // helper to add user property to an object literal if missing\n const addUserProp = (obj: import(\"ts-morph\").ObjectLiteralExpression) => {\n const hasUser = !!obj.getProperty(\"user\");\n if (!hasUser) {\n obj.addPropertyAssignment({\n name: \"user\",\n initializer: \"locals.pb.authStore.record\",\n });\n }\n };\n\n // find existing exported load (function or const with arrow)\n let loadArrow: import(\"ts-morph\").ArrowFunction | undefined;\n let loadFn:\n | import(\"ts-morph\").FunctionDeclaration\n | import(\"ts-morph\").FunctionExpression\n | undefined;\n\n const varDecl = sourceFile.getVariableDeclaration(\"load\");\n if (varDecl) {\n const vs = varDecl.getFirstAncestorByKind(SyntaxKind.VariableStatement);\n const isExported = !!vs?.hasExportKeyword();\n if (isExported) {\n const directArrow = varDecl.getInitializerIfKind(\n SyntaxKind.ArrowFunction,\n );\n if (directArrow) {\n loadArrow = directArrow;\n } else {\n const init = varDecl.getInitializer();\n if (init) {\n const innerArrow = init.getFirstDescendantByKind(\n SyntaxKind.ArrowFunction,\n );\n if (innerArrow) {\n loadArrow = innerArrow;\n } else {\n const innerFnExpr = init.getFirstDescendantByKind(\n SyntaxKind.FunctionExpression,\n );\n if (innerFnExpr) {\n loadFn = innerFnExpr;\n }\n }\n }\n }\n }\n }\n\n if (!loadArrow) {\n const maybeFn = sourceFile.getFunction(\"load\");\n if (maybeFn && maybeFn.isExported()) {\n loadFn = maybeFn;\n }\n }\n\n // if no load found, create one\n if (!loadArrow && !loadFn) {\n sourceFile.addFunction({\n isExported: true,\n isAsync: true,\n name: \"load\",\n parameters: [{ name: \"{ locals }\" }],\n statements: `return { user: locals.pb.authStore.record };`,\n });\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n }\n\n // normalize function-like to a single handle\n const fnLike:\n | import(\"ts-morph\").ArrowFunction\n | import(\"ts-morph\").FunctionDeclaration\n | import(\"ts-morph\").FunctionExpression = (loadArrow ?? loadFn!) as any;\n\n // ensure first parameter destructures locals, preserving existing information\n const params = fnLike.getParameters();\n if (params.length === 0) {\n fnLike.insertParameter(0, { name: \"{ locals }\" });\n } else {\n const first = params[0];\n const original = first.getStructure();\n const nameNode = first.getNameNode();\n if (nameNode.getKind() === SyntaxKind.ObjectBindingPattern) {\n const obp = nameNode as import(\"ts-morph\").ObjectBindingPattern;\n const hasLocals = obp\n .getElements()\n .some((el) => el.getName() === \"locals\");\n if (!hasLocals) {\n const parts = obp\n .getElements()\n .map((el) => el.getText())\n .filter(Boolean);\n const tail = parts.length > 0 ? \", \" + parts.join(\", \") : \"\";\n first.set({\n name: `{ locals${tail} }`,\n type: original.type,\n initializer: (original as any).initializer,\n });\n }\n } else {\n const currentName = first.getName();\n if (currentName !== \"locals\") {\n first.set({\n name: `{ locals, ...${currentName} }`,\n type: original.type,\n initializer: (original as any).initializer,\n });\n }\n }\n }\n\n // add user to returned object literals without altering other properties\n if (loadArrow) {\n const body = loadArrow.getBody();\n if (body.getKind() === SyntaxKind.Block) {\n const returns = body.getDescendantsOfKind(SyntaxKind.ReturnStatement);\n returns.forEach((ret) => {\n const expr = ret.getExpression();\n if (!expr) return;\n if (expr.getKind() === SyntaxKind.ObjectLiteralExpression) {\n addUserProp(expr as import(\"ts-morph\").ObjectLiteralExpression);\n } else if (expr.getKind() === SyntaxKind.ParenthesizedExpression) {\n const inner = (\n expr as import(\"ts-morph\").ParenthesizedExpression\n ).getExpression();\n if (inner.getKind() === SyntaxKind.ObjectLiteralExpression) {\n addUserProp(inner as import(\"ts-morph\").ObjectLiteralExpression);\n }\n }\n });\n } else {\n // concise body\n const bodyExpr = body as import(\"ts-morph\").Expression;\n if (bodyExpr.getKind() === SyntaxKind.ParenthesizedExpression) {\n const inner = (\n bodyExpr as import(\"ts-morph\").ParenthesizedExpression\n ).getExpression();\n if (inner.getKind() === SyntaxKind.ObjectLiteralExpression) {\n addUserProp(inner as import(\"ts-morph\").ObjectLiteralExpression);\n }\n } else if (bodyExpr.getKind() === SyntaxKind.ObjectLiteralExpression) {\n addUserProp(bodyExpr as import(\"ts-morph\").ObjectLiteralExpression);\n }\n }\n } else if (loadFn) {\n const body = loadFn.getBody();\n if (body) {\n const returns = body.getDescendantsOfKind(SyntaxKind.ReturnStatement);\n returns.forEach((ret) => {\n const expr = ret.getExpression();\n if (!expr) return;\n if (expr.getKind() === SyntaxKind.ObjectLiteralExpression) {\n addUserProp(expr as import(\"ts-morph\").ObjectLiteralExpression);\n } else if (expr.getKind() === SyntaxKind.ParenthesizedExpression) {\n const inner = (\n expr as import(\"ts-morph\").ParenthesizedExpression\n ).getExpression();\n if (inner.getKind() === SyntaxKind.ObjectLiteralExpression) {\n addUserProp(inner as import(\"ts-morph\").ObjectLiteralExpression);\n }\n }\n });\n }\n }\n\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return {\n status: \"success\",\n changed: sourceFile.getFullText() !== originalSource,\n };\n}\n","import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport {\n ensureImports,\n ensurePropsBinding,\n withInMemoryScript,\n} from \"../../../../runtime/ts-morph-helpers\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst AUTH_MENU_NAVBAR_ITEM = `\n\t\t<Navbar.Item\n\t\t\tclass=\"flex flex-col md:flex-row items-center space-y-2 md:space-y-0 md:space-x-4\"\n\t\t>\n\t\t\t<AuthMenu.Root>\n\t\t\t\t{#snippet user()}\n\t\t\t\t\t<AuthMenu.Trigger>\n\t\t\t\t\t\t<UserAvatar user={data.user} />\n\t\t\t\t\t</AuthMenu.Trigger>\n\n\t\t\t\t\t<AuthMenu.Content align=\"end\">\n\t\t\t\t\t\t<AuthMenu.Item href=\"/dashboard\">Dashboard</AuthMenu.Item>\n\t\t\t\t\t\t<AuthMenu.Group>\n\t\t\t\t\t\t\t<AuthMenu.Item href=\"/settings\">Settings</AuthMenu.Item>\n\t\t\t\t\t\t\t<AuthMenu.Item>\n\t\t\t\t\t\t\t\t<form action=\"/logout\" method=\"post\">\n\t\t\t\t\t\t\t\t\t<button type=\"submit\" class=\"contents\">Logout</button>\n\t\t\t\t\t\t\t\t</form>\n\t\t\t\t\t\t\t</AuthMenu.Item>\n\t\t\t\t\t\t</AuthMenu.Group>\n\t\t\t\t\t</AuthMenu.Content>\n\t\t\t\t{/snippet}\n\n\t\t\t\t{#snippet guest()}\n\t\t\t\t\t<Button\n\t\t\t\t\t\tclass=\"w-full justify-start md:justify-center md:w-auto\"\n\t\t\t\t\t\tvariant=\"ghost\"\n\t\t\t\t\t\thref=\"/login\">Login</Button\n\t\t\t\t\t>\n\t\t\t\t\t<Button\n\t\t\t\t\t\tclass=\"w-full justify-start md:justify-center md:w-auto\"\n\t\t\t\t\t\tvariant=\"outline\"\n\t\t\t\t\t\thref=\"/signup\">Sign up</Button\n\t\t\t\t\t>\n\t\t\t\t{/snippet}\n\t\t\t</AuthMenu.Root>\n\t\t</Navbar.Item>\n\t`;\n\nconst IMPORT_SNIPPET = dedent`\n import * as AuthMenu from '#lib/components/ui/auth-menu/index.js';\n import UserAvatar from '#lib/components/user-avatar.svelte';\n`;\n\nconst FAILURE_HINT = [\n \"Add the auth menu inside your <Navbar.List> in the root layout.\",\n \"\",\n \"Imports to add to the <script> tag:\",\n \"\",\n IMPORT_SNIPPET,\n \"\",\n \"Markup to add inside <Navbar.List>:\",\n AUTH_MENU_NAVBAR_ITEM,\n].join(\"\\n\");\n\nconst NOT_FOUND_HINT = [\n \"Create a root layout that includes an auth menu inside <Navbar.List>.\",\n \"\",\n \"Imports for the <script> tag:\",\n \"\",\n IMPORT_SNIPPET,\n \"\",\n \"Markup inside <Navbar.List>:\",\n AUTH_MENU_NAVBAR_ITEM,\n].join(\"\\n\");\n\nexport function modifyRootLayoutSvelte(layoutPath: string): ModifyOutcome {\n if (!fs.existsSync(layoutPath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const file = SvelteFile.fromPath(layoutPath);\n if (!file.hasElement(\"Navbar.List\")) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n if (file.hasElement(\"AuthMenu.Root\")) {\n return { status: \"success\", changed: false };\n }\n\n file.modifyScript((source) => {\n const { source: out } = withInMemoryScript(source, (sf) => {\n ensureImports(sf, [\n {\n namespaceImport: \"AuthMenu\",\n moduleSpecifier: \"#lib/components/ui/auth-menu/index.js\",\n },\n {\n defaultImport: \"UserAvatar\",\n moduleSpecifier: \"#lib/components/user-avatar.svelte\",\n },\n ]);\n // The menu reads `data.user`; the template's layout takes no props.\n ensurePropsBinding(sf, \"data\");\n });\n return out;\n });\n\n file.insertBeforeClosingTag(\"Navbar.List\", AUTH_MENU_NAVBAR_ITEM);\n file.writeTo(layoutPath);\n return { status: \"success\", changed: file.hasChanged() };\n}\n","import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { Project, SyntaxKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport { formatLikeSource } from \"../../../../runtime/ts-morph-helpers\";\n\nconst FAILURE_HINT = dedent`\n Configure handlePocketbase() with the auth option in hooks.server.ts:\n\n handlePocketbase({\n auth: { protectedRoutes: ['/(app)'] },\n });\n`;\n\nconst NOT_FOUND_HINT = dedent`\n Create src/hooks.server.ts with handlePocketbase:\n\n import { handlePocketbase } from '@velastack/pocketbase';\n\n export const handle = handlePocketbase({\n auth: { protectedRoutes: ['/(app)'] },\n });\n`;\n\nexport function modifyHooksServer(hooksServerPath: string): ModifyOutcome {\n if (!fs.existsSync(hooksServerPath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const originalSource = fs.readFileSync(hooksServerPath, \"utf8\");\n const project = new Project();\n const sourceFile = project.addSourceFileAtPath(hooksServerPath);\n\n // Find the handlePocketbase(...) call\n const callExpr = sourceFile\n .getDescendantsOfKind(SyntaxKind.CallExpression)\n .find((ce) => ce.getExpression().getText() === \"handlePocketbase\");\n\n if (!callExpr) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n const args = callExpr.getArguments();\n if (args.length === 0) {\n callExpr.addArgument(`{ auth: { protectedRoutes: ['/(app)'] } }`);\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n }\n\n const firstArg = args[0];\n if (firstArg.getKind() !== SyntaxKind.ObjectLiteralExpression) {\n callExpr.insertArgument(0, `{ auth: { protectedRoutes: ['/(app)'] } }`);\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n }\n\n const optionsObj = firstArg.asKindOrThrow(SyntaxKind.ObjectLiteralExpression);\n\n // Ensure auth property exists\n const authProp = optionsObj.getProperty(\"auth\");\n if (!authProp) {\n optionsObj.addPropertyAssignment({\n name: \"auth\",\n initializer: `{ protectedRoutes: ['/(app)'] }`,\n });\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n }\n\n // If auth exists, ensure protectedRoutes includes '/(app)'\n if (authProp.getKind() === SyntaxKind.PropertyAssignment) {\n const authInit = (\n authProp as import(\"ts-morph\").PropertyAssignment\n ).getInitializer();\n if (authInit && authInit.getKind() === SyntaxKind.ObjectLiteralExpression) {\n const authObj = authInit as import(\"ts-morph\").ObjectLiteralExpression;\n const prProp = authObj.getProperty(\"protectedRoutes\");\n if (!prProp) {\n authObj.addPropertyAssignment({\n name: \"protectedRoutes\",\n initializer: `['/(app)']`,\n });\n } else if (prProp.getKind() === SyntaxKind.PropertyAssignment) {\n const prInit = (\n prProp as import(\"ts-morph\").PropertyAssignment\n ).getInitializer();\n if (prInit && prInit.getKind() === SyntaxKind.ArrayLiteralExpression) {\n const arr = prInit as import(\"ts-morph\").ArrayLiteralExpression;\n const hasApp = arr\n .getElements()\n .some((el) => el.getText().replace(/['\"`]/g, \"\") === \"/(app)\");\n if (!hasApp) {\n arr.addElement(`'/(app)'`);\n }\n } else {\n (prProp as import(\"ts-morph\").PropertyAssignment).setInitializer(\n `['/(app)']`,\n );\n }\n }\n }\n }\n\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return {\n status: \"success\",\n changed: sourceFile.getFullText() !== originalSource,\n };\n}\n","import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst VARIANTS = [\n {\n from: \"'data-active': isActive,\",\n to: \"'data-active': isActive ? true : undefined,\",\n },\n {\n from: '\"data-active\": isActive,',\n to: '\"data-active\": isActive ? true : undefined,',\n },\n];\n\nconst NOT_FOUND_HINT = dedent`\n The shadcn-svelte sidebar component was not installed at the expected path.\n Run: vela enable auth (or install the 'sidebar' shadcn-svelte component).\n`;\n\nexport function modifySidebarMenuButton(filePath: string): ModifyOutcome {\n if (!fs.existsSync(filePath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const original = fs.readFileSync(filePath, \"utf8\");\n\n if (VARIANTS.some(({ to }) => original.includes(to))) {\n return { status: \"success\", changed: false };\n }\n\n const variant = VARIANTS.find(({ from }) => original.includes(from));\n if (!variant) {\n return { status: \"success\", changed: false };\n }\n\n const updated = original.replace(variant.from, variant.to);\n fs.writeFileSync(filePath, updated, \"utf8\");\n return { status: \"success\", changed: true };\n}\n","import path from \"node:path\";\nimport fs from \"node:fs\";\nimport { Options, Result, File } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport {\n getMigrationFile,\n migrationDelay,\n withPocketbase,\n} from \"../../../runtime/pocketbase\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { ensureSiteFile } from \"../../../runtime/site\";\n\nimport { modifyLayoutServer } from \"./modifies/+layout.server\";\nimport { modifyRootLayoutSvelte } from \"./modifies/root-layout.svelte\";\nimport { modifyHooksServer } from \"./modifies/hooks.server\";\nimport { modifySidebarMenuButton } from \"./modifies/sidebar-menu-button.svelte\";\n\nexport async function generate(options: Options) {\n const { input } = options;\n const logger = getLogger(options);\n\n let creates: File[] = [];\n\n // Update PocketBase\n await withPocketbase(options.root, async (pb) => {\n logger.info(\"Updating PocketBase mail settings\");\n await pb.settings.update({\n meta: {\n senderName: input.senderName,\n senderAddress: input.senderAddress,\n },\n });\n await migrationDelay();\n\n const userCollection = await pb.collections.getOne(\"users\");\n\n if (!userCollection) {\n throw new Error(\"Users collection not found\");\n }\n\n const verificationTemplate =\n userCollection.verificationTemplate.body.replace(\n \"{APP_URL}/_/#/auth/confirm-verification/{TOKEN}\",\n \"{APP_URL}/confirm-verification/{TOKEN}\",\n );\n const resetPasswordTemplate =\n userCollection.resetPasswordTemplate.body.replace(\n \"{APP_URL}/_/#/auth/confirm-reset/{TOKEN}\",\n \"{APP_URL}/confirm-reset/{TOKEN}\",\n );\n const confirmEmailChangeTemplate =\n userCollection.confirmEmailChangeTemplate.body.replace(\n \"{APP_URL}/_/#/auth/confirm-email-change/{TOKEN}\",\n \"{APP_URL}/confirm-email-change/{TOKEN}\",\n );\n\n logger.info(\"Locking down users collection rules and email templates\");\n // Update user auth rules to lock down access to the user's own account\n await pb.collections.update(\"users\", {\n listRule: \"@request.auth.id = id\",\n viewRule: \"@request.auth.id = id\",\n createRule: \"@request.auth.id = id\",\n updateRule: \"@request.auth.id = id\",\n deleteRule: \"@request.auth.id = id\",\n\n // Update email templates to VelaStack auth urls\n verificationTemplate: {\n body: verificationTemplate,\n },\n resetPasswordTemplate: {\n body: resetPasswordTemplate,\n },\n confirmEmailChangeTemplate: {\n body: confirmEmailChangeTemplate,\n },\n });\n await migrationDelay();\n\n const migrationFile = getMigrationFile(\"users\", \"updated\", options);\n if (migrationFile) {\n creates.push({\n path: migrationFile,\n language: \"ts\",\n content: fs.readFileSync(migrationFile, \"utf8\"),\n status: \"success\",\n });\n }\n });\n\n // Modify files\n const modifies: File[] = [];\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n logger.info(\"Modifying +layout.server.ts\");\n const layoutServerFile = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"+layout.server.ts\",\n );\n pushResult(\n modifyOutcomeToFile(layoutServerFile, modifyLayoutServer(layoutServerFile)),\n );\n\n logger.info(\"Modifying root layout\");\n // TODO: make this more robust by searching for Navbar.Root > Navbar.List\n // src/routes/(public)/root-layout.svelte is what vela creates by default\n const layoutCandidates = [\n path.join(options.root, \"src\", \"routes\", \"(public)\", \"root-layout.svelte\"),\n path.join(options.root, \"src\", \"routes\", \"root-layout.svelte\"),\n path.join(options.root, \"src\", \"routes\", \"(public)\", \"+layout.svelte\"),\n path.join(options.root, \"src\", \"routes\", \"+layout.svelte\"),\n ];\n const layoutFile =\n layoutCandidates.find((p) => fs.existsSync(p)) ?? layoutCandidates[0];\n pushResult(\n modifyOutcomeToFile(layoutFile, modifyRootLayoutSvelte(layoutFile)),\n );\n\n logger.info(\"Modifying hooks.server.ts\");\n const hooksServerFile = path.join(options.root, \"src\", \"hooks.server.ts\");\n pushResult(\n modifyOutcomeToFile(hooksServerFile, modifyHooksServer(hooksServerFile)),\n );\n\n logger.info(\"Modifying sidebar-menu-button.svelte\");\n const sidebarMenuButtonFile = path.join(\n options.root,\n \"src\",\n \"lib\",\n \"components\",\n \"ui\",\n \"sidebar\",\n \"sidebar-menu-button.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(\n sidebarMenuButtonFile,\n modifySidebarMenuButton(sidebarMenuButtonFile),\n ),\n );\n\n // The auth pages and the app sidebar show `site.name`.\n const siteFile = await ensureSiteFile(options);\n\n return {\n creates: siteFile ? [siteFile] : [],\n modifies,\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n } satisfies Result;\n}\n"],"mappings":";;;;;;;;;;;AAMA,SAAgBiB,EAAmB,GAAmC;CACpE,IAAI,CAACF,EAAG,WAAWG,CAAU,GAAG;EAC9B,IAAMC,IAAU,CAAM;;;;;EAOtB,OADAJ,EAAG,cAAcG,GAAYC,CAAO,GAC7B;GAAE,QAAQ;GAAW,SAAS;EAAK;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,iBAAiB,CAAC;CACpB;AACF"}
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import { r as e } from "./lib-specifier-Cngo1zF_.js";
|
|
2
2
|
import { n as t } from "./logger-CQONztPm.js";
|
|
3
|
-
import { n, t as r } from "./generate-
|
|
3
|
+
import { n, t as r } from "./generate-Crdzw45a.js";
|
|
4
4
|
import { n as i } from "./env-BugddEjd.js";
|
|
5
5
|
import { _ as a, n as o, u as s } from "./ts-morph-helpers-CHI9wAil.js";
|
|
6
|
-
import { r as c, t as l } from "./modify-file-
|
|
7
|
-
import { unmodifyEnvVarsFiles as u } from "./env-vars-
|
|
6
|
+
import { r as c, t as l } from "./modify-file-D9U2LXEa.js";
|
|
7
|
+
import { unmodifyEnvVarsFiles as u } from "./env-vars-XvAeH6u5.js";
|
|
8
8
|
import { t as d } from "./svelte-file-Dv5-bl79.js";
|
|
9
9
|
import f from "node:fs";
|
|
10
10
|
import p from "node:path";
|
|
@@ -62,4 +62,4 @@ async function g(e) {
|
|
|
62
62
|
//#endregion
|
|
63
63
|
export { g as generate };
|
|
64
64
|
|
|
65
|
-
//# sourceMappingURL=generate.runtime-
|
|
65
|
+
//# sourceMappingURL=generate.runtime-taYl9Tg5.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"generate.runtime-
|
|
1
|
+
{"version":3,"file":"generate.runtime-taYl9Tg5.js","names":["libModule","getLogger","allEnvEdits","modifyEnvRemove","withInMemoryScript","ensureBlankLineAfterImports","removeImportByModuleSpecifier","modifyOutcomeToFile","envRevertOutcomeToFile","SvelteFile","fs","path","MODULE","unmodifyLayoutSvelte","layoutPath","original","file","out","source","sf","updated","generate","logger","options","modifies","deletes","pushResult","envVars","unmodifyEnvVarsFiles","allEnvNames","envPath","env"],"sources":["../../src/patterns/disable/analytics/modifies/layout.svelte.ts","../../src/patterns/disable/analytics/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport {\n ensureBlankLineAfterImports,\n removeImportByModuleSpecifier,\n withInMemoryScript,\n} from \"../../../../runtime/ts-morph-helpers\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport { libModule } from \"../../../../runtime/lib-specifier\";\n\nconst MODULE = \"components/analytics/analytics.svelte\";\n\n/**\n * Takes `<Analytics />` and its import back out of the root layout. The\n * element goes with its whole line, since enable-analytics put it on one of\n * its own. A layout without it, or no layout at all, is left alone.\n */\nexport function unmodifyLayoutSvelte(layoutPath: string): ModifyOutcome {\n if (!fs.existsSync(layoutPath)) {\n return { status: \"success\", changed: false };\n }\n\n const original = fs.readFileSync(layoutPath, \"utf8\");\n if (!original.includes(MODULE) && !original.includes(\"<Analytics\")) {\n return { status: \"success\", changed: false };\n }\n\n const file = SvelteFile.fromPath(layoutPath);\n file.modifyScript((source) => {\n const { source: out } = withInMemoryScript(source, (sf) => {\n removeImportByModuleSpecifier(sf, libModule(MODULE));\n ensureBlankLineAfterImports(sf);\n });\n return out;\n });\n\n const updated = file\n .toString()\n .replace(/[ \\t]*<Analytics\\s*\\/>[ \\t]*\\r?\\n?/g, \"\");\n\n if (updated === original) {\n return { status: \"success\", changed: false };\n }\n fs.writeFileSync(layoutPath, updated, \"utf8\");\n return { status: \"success\", changed: true };\n}\n","import path from \"node:path\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport { modifyEnvRemove } from \"../../../runtime/env\";\nimport {\n envRevertOutcomeToFile,\n modifyOutcomeToFile,\n} from \"../../../runtime/modify-file\";\nimport { allEnvEdits, allEnvNames } from \"./generate\";\nimport { unmodifyEnvVarsFiles } from \"../../../runtime/env-vars\";\nimport { unmodifyLayoutSvelte } from \"./modifies/layout.svelte\";\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const modifies: File[] = [];\n const deletes: File[] = [];\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n logger.info(\"Reverting src/routes/+layout.svelte\");\n const layoutPath = path.join(options.root, \"src\", \"routes\", \"+layout.svelte\");\n pushResult(modifyOutcomeToFile(layoutPath, unmodifyLayoutSvelte(layoutPath)));\n\n // Which provider was chosen is not recorded, so every one's variables go;\n // the file goes too when these were all it declared.\n logger.info(\"Removing analytics variables from src/env.ts\");\n const envVars = unmodifyEnvVarsFiles(options.root, allEnvNames());\n pushResult(envVars.modify);\n if (envVars.delete) deletes.push(envVars.delete);\n\n logger.info(\"Removing analytics variables from .env\");\n const envPath = path.join(options.root, \".env\");\n const env = envRevertOutcomeToFile(\n envPath,\n modifyEnvRemove(envPath, allEnvEdits()),\n );\n pushResult(env.modify);\n if (env.delete) deletes.push(env.delete);\n\n return {\n creates: [],\n modifies,\n deletes,\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n } satisfies Result;\n}\n"],"mappings":";;;;;;;;;;;AAUA,IAAMY,IAAS;AAOf,SAAgBC,EAAqB,GAAmC;CACtE,IAAI,CAACH,EAAG,WAAWI,CAAU,GAC3B,OAAO;EAAE,QAAQ;EAAW,SAAS;CAAM;CAG7C,IAAMC,IAAWL,EAAG,aAAaI,GAAY,MAAM;CACnD,IAAI,CAACC,EAAS,SAASH,CAAM,KAAK,CAACG,EAAS,SAAS,YAAY,GAC/D,OAAO;EAAE,QAAQ;EAAW,SAAS;CAAM;CAG7C,IAAMC,IAAOP,EAAW,SAASK,CAAU;CAC3C,EAAK,cAAc,MAAW;EAC5B,IAAM,EAAE,QAAQG,MAAQb,EAAmBc,IAAS,MAAO;GAEzD,AADAZ,EAA8Ba,GAAInB,EAAUY,CAAM,CAAC,GACnDP,EAA4Bc,CAAE;EAChC,CAAC;EACD,OAAOF;CACT,CAAC;CAED,IAAMG,IAAUJ,EACb,SAAS,CAAC,CACV,QAAQ,uCAAuC,EAAE;CAMpD,OAJII,MAAYL,IACP;EAAE,QAAQ;EAAW,SAAS;CAAM,KAE7CL,EAAG,cAAcI,GAAYM,GAAS,MAAM,GACrC;EAAE,QAAQ;EAAW,SAAS;CAAK;AAC5C;;;ACjCA,eAAsBC,EAAS,GAAkB;CAC/C,IAAMC,IAASrB,EAAUsB,CAAO,GAC1BC,IAAmB,CAAC,GACpBC,IAAkB,CAAC,GACnBC,KAAc,MAAsB;EACxC,AAAIV,KAAMQ,EAAS,KAAKR,CAAI;CAC9B;CAEA,EAAO,KAAK,qCAAqC;CACjD,IAAMF,IAAaH,EAAK,KAAKY,EAAQ,MAAM,OAAO,UAAU,gBAAgB;CAK5E,AAJAG,EAAWnB,EAAoBO,GAAYD,EAAqBC,CAAU,CAAC,CAAC,GAI5EQ,EAAO,KAAK,8CAA8C;CAC1D,IAAMK,IAAUC,EAAqBL,EAAQ,MAAMM,EAAY,CAAC;CAIhE,AAHAH,EAAWC,EAAQ,MAAM,GACrBA,EAAQ,UAAQF,EAAQ,KAAKE,EAAQ,MAAM,GAE/CL,EAAO,KAAK,wCAAwC;CACpD,IAAMQ,IAAUnB,EAAK,KAAKY,EAAQ,MAAM,MAAM,GACxCQ,IAAMvB,EACVsB,GACA3B,EAAgB2B,GAAS5B,EAAY,CAAC,CACxC;CAIA,OAHAwB,EAAWK,EAAI,MAAM,GACjBA,EAAI,UAAQN,EAAQ,KAAKM,EAAI,MAAM,GAEhC;EACL,SAAS,CAAC;EACV;EACA;EACA,YAAY,CAAC;EACb,UAAU,CAAC;EACX,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAiB,CAAC;CACpB;AACF"}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { t as e } from "./dedent-Gq6Krl4n.js";
|
|
2
|
+
import { _ as t, r as n } from "./ts-morph-helpers-CHI9wAil.js";
|
|
3
|
+
import { t as r } from "./svelte-file-Dv5-bl79.js";
|
|
4
|
+
import i from "node:fs";
|
|
5
|
+
import { Node as a, SyntaxKind as o } from "ts-morph";
|
|
6
|
+
//#region src/patterns/enable/og/modifies/layout.svelte.ts
|
|
7
|
+
var s = "#lib/og/index.js", c = [
|
|
8
|
+
"Pass the meta tags the root src/routes/+layout.svelte renders through withCard.",
|
|
9
|
+
"",
|
|
10
|
+
"Imports for the <script lang=\"ts\"> tag:",
|
|
11
|
+
"",
|
|
12
|
+
e`
|
|
13
|
+
import { page } from '$app/state';
|
|
14
|
+
import { withCard } from '${s}';
|
|
15
|
+
`,
|
|
16
|
+
"",
|
|
17
|
+
"Then wrap what <MetaTags> is given:",
|
|
18
|
+
"",
|
|
19
|
+
"let metaTags = $derived(withCard(deepMerge(data.baseMetaTags, page.data.pageMetaTags), page.url));"
|
|
20
|
+
].join("\n");
|
|
21
|
+
function l(e) {
|
|
22
|
+
let t = e.getDescendantsOfKind(o.VariableDeclaration).find((e) => e.getName() === "metaTags")?.getInitializer();
|
|
23
|
+
return !t || !a.isCallExpression(t) || t.getExpression().getText() !== "$derived" ? null : t.getArguments().length === 1 ? t : null;
|
|
24
|
+
}
|
|
25
|
+
function u(e) {
|
|
26
|
+
if (!i.existsSync(e)) return {
|
|
27
|
+
status: "not-found",
|
|
28
|
+
message: c
|
|
29
|
+
};
|
|
30
|
+
let a = r.fromPath(e), o = a.getScript();
|
|
31
|
+
if (!o) return {
|
|
32
|
+
status: "failed",
|
|
33
|
+
message: c
|
|
34
|
+
};
|
|
35
|
+
if (o.content.includes("withCard(")) return {
|
|
36
|
+
status: "success",
|
|
37
|
+
changed: !1
|
|
38
|
+
};
|
|
39
|
+
let u = !1;
|
|
40
|
+
return a.modifyScript((e) => {
|
|
41
|
+
let { source: r } = t(e, (e) => {
|
|
42
|
+
let t = l(e);
|
|
43
|
+
if (!t) return;
|
|
44
|
+
let [r] = t.getArguments();
|
|
45
|
+
r.replaceWithText(`withCard(${r.getText()}, page.url)`), u = !0, n(e, [{
|
|
46
|
+
namedImports: ["page"],
|
|
47
|
+
moduleSpecifier: "$app/state"
|
|
48
|
+
}, {
|
|
49
|
+
namedImports: ["withCard"],
|
|
50
|
+
moduleSpecifier: s
|
|
51
|
+
}]);
|
|
52
|
+
});
|
|
53
|
+
return u ? r : e;
|
|
54
|
+
}), u ? (a.writeTo(e), {
|
|
55
|
+
status: "success",
|
|
56
|
+
changed: a.hasChanged()
|
|
57
|
+
}) : {
|
|
58
|
+
status: "failed",
|
|
59
|
+
message: c
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
//#endregion
|
|
63
|
+
export { l as n, u as r, s as t };
|
|
64
|
+
|
|
65
|
+
//# sourceMappingURL=layout.svelte-Cb12mxua.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"layout.svelte-Cb12mxua.js","names":["dedent","withInMemoryScript","ensureImports","SvelteFile","fs","MODULE_SPECIFIER","HINT","findMetaTagsDerived","init","sf","SyntaxKind","d","Node","modifyLayoutSvelte","layoutPath","file","script","wrapped","out","source","derived","arg"],"sources":["../../src/patterns/enable/og/modifies/layout.svelte.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { Node, SyntaxKind, type CallExpression } from \"ts-morph\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport {\n ensureImports,\n withInMemoryScript,\n} from \"../../../../runtime/ts-morph-helpers\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nexport const MODULE_SPECIFIER = \"#lib/og/index.js\";\n\nconst HINT = [\n \"Pass the meta tags the root src/routes/+layout.svelte renders through withCard.\",\n \"\",\n 'Imports for the <script lang=\"ts\"> tag:',\n \"\",\n dedent`\n import { page } from '$app/state';\n import { withCard } from '${MODULE_SPECIFIER}';\n `,\n \"\",\n \"Then wrap what <MetaTags> is given:\",\n \"\",\n \"let metaTags = $derived(withCard(deepMerge(data.baseMetaTags, page.data.pageMetaTags), page.url));\",\n].join(\"\\n\");\n\n/** The `$derived(...)` call that `let metaTags = ...` is initialised with. */\nexport function findMetaTagsDerived(\n sf: import(\"ts-morph\").SourceFile,\n): CallExpression | null {\n const declaration = sf\n .getDescendantsOfKind(SyntaxKind.VariableDeclaration)\n .find((d) => d.getName() === \"metaTags\");\n const init = declaration?.getInitializer();\n if (!init || !Node.isCallExpression(init)) return null;\n if (init.getExpression().getText() !== \"$derived\") return null;\n return init.getArguments().length === 1 ? init : null;\n}\n\n/**\n * Wraps the root layout's `metaTags` in `withCard(..., page.url)`, which swaps\n * the site-wide `/og.jpg` for the page's generated card. Vela's templates all\n * build `metaTags` the same way; a layout that does not gets the snippet to\n * paste instead.\n */\nexport function modifyLayoutSvelte(layoutPath: string): ModifyOutcome {\n if (!fs.existsSync(layoutPath)) {\n return { status: \"not-found\", message: HINT };\n }\n\n const file = SvelteFile.fromPath(layoutPath);\n const script = file.getScript();\n if (!script) return { status: \"failed\", message: HINT };\n if (script.content.includes(\"withCard(\")) {\n return { status: \"success\", changed: false };\n }\n\n let wrapped = false;\n file.modifyScript((source) => {\n const { source: out } = withInMemoryScript(source, (sf) => {\n const derived = findMetaTagsDerived(sf);\n if (!derived) return;\n const [arg] = derived.getArguments();\n arg.replaceWithText(`withCard(${arg.getText()}, page.url)`);\n wrapped = true;\n ensureImports(sf, [\n { namedImports: [\"page\"], moduleSpecifier: \"$app/state\" },\n { namedImports: [\"withCard\"], moduleSpecifier: MODULE_SPECIFIER },\n ]);\n });\n return wrapped ? out : source;\n });\n\n if (!wrapped) return { status: \"failed\", message: HINT };\n file.writeTo(layoutPath);\n return { status: \"success\", changed: file.hasChanged() };\n}\n"],"mappings":";;;;;;AAUA,IAAaK,IAAmB,oBAE1BC,IAAO;CACX;CACA;CACA;CACA;CACA,CAAM;;gCAEwBD,EAAiB;;CAE/C;CACA;CACA;CACA;AACF,CAAC,CAAC,KAAK,IAAI;AAGX,SAAgBE,EACd,GACuB;CAIvB,IAAMC,IAHcC,EACjB,qBAAqBC,EAAW,mBAAmB,CAAC,CACpD,MAAM,MAAMC,EAAE,QAAQ,MAAM,UAClB,CAAA,EAAa,eAAe;CAGzC,OAFI,CAACH,KAAQ,CAACI,EAAK,iBAAiBJ,CAAI,KACpCA,EAAK,cAAc,CAAC,CAAC,QAAQ,MAAM,aAAmB,OACnDA,EAAK,aAAa,CAAC,CAAC,WAAW,IAAIA,IAAO;AACnD;AAQA,SAAgBK,EAAmB,GAAmC;CACpE,IAAI,CAACT,EAAG,WAAWU,CAAU,GAC3B,OAAO;EAAE,QAAQ;EAAa,SAASR;CAAK;CAG9C,IAAMS,IAAOZ,EAAW,SAASW,CAAU,GACrCE,IAASD,EAAK,UAAU;CAC9B,IAAI,CAACC,GAAQ,OAAO;EAAE,QAAQ;EAAU,SAASV;CAAK;CACtD,IAAIU,EAAO,QAAQ,SAAS,WAAW,GACrC,OAAO;EAAE,QAAQ;EAAW,SAAS;CAAM;CAG7C,IAAIC,IAAU;CAkBd,OAjBAF,EAAK,cAAc,MAAW;EAC5B,IAAM,EAAE,QAAQG,MAAQjB,EAAmBkB,IAAS,MAAO;GACzD,IAAMC,IAAUb,EAAoBE,CAAE;GACtC,IAAI,CAACW,GAAS;GACd,IAAM,CAACC,KAAOD,EAAQ,aAAa;GAGnC,AAFAC,EAAI,gBAAgB,YAAYA,EAAI,QAAQ,EAAE,YAAY,GAC1D,IAAU,IACVnB,EAAcO,GAAI,CAChB;IAAE,cAAc,CAAC,MAAM;IAAG,iBAAiB;GAAa,GACxD;IAAE,cAAc,CAAC,UAAU;IAAG,iBAAiBJ;GAAiB,CAClE,CAAC;EACH,CAAC;EACD,OAAOY,IAAUC,IAAMC;CACzB,CAAC,GAEIF,KACLF,EAAK,QAAQD,CAAU,GAChB;EAAE,QAAQ;EAAW,SAASC,EAAK,WAAW;CAAE,KAFlC;EAAE,QAAQ;EAAU,SAAST;CAAK;AAGzD"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { n as e } from "./rolldown-runtime-5HNE8Q1r.js";
|
|
2
2
|
import { a as t } from "./util-BLYliuUK.js";
|
|
3
|
-
import { n } from "./shared-
|
|
3
|
+
import { n } from "./shared-CAjLx_8Z.js";
|
|
4
4
|
import { _ as r, s as i } from "./ts-morph-helpers-CHI9wAil.js";
|
|
5
5
|
import a from "node:fs";
|
|
6
6
|
import o from "node:path";
|
|
@@ -50,4 +50,4 @@ function d(e, t) {
|
|
|
50
50
|
//#endregion
|
|
51
51
|
export { l as a, s as i, d as n, c as r, u as t };
|
|
52
52
|
|
|
53
|
-
//# sourceMappingURL=modify-file-
|
|
53
|
+
//# sourceMappingURL=modify-file-D9U2LXEa.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"modify-file-
|
|
1
|
+
{"version":3,"file":"modify-file-D9U2LXEa.js","names":["__exportAll","languageFromPath","withInMemoryScript","isEffectivelyEmpty","fs","path","modify_file_exports","envRevertOutcomeToFile","keepMissing","modifyOutcomeToFile","revertOutcomeToFile","language","filePath","outcome","toDeleteEntry","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,SAAgBS,EACd,GACA,GACa;CACb,IAAME,IAAWV,EAAiBW,CAAQ;CAiB1C,OAfIC,EAAQ,WAAW,YAChBA,EAAQ,UACN;EACL,MAAMD;EACN;EACA,SAASR,EAAG,aAAaQ,GAAU,MAAM;EACzC,QAAQ;CACV,IAN6B,OAcxB;EACL,MAAMA;EACN;EACA,SAPAC,EAAQ,WAAW,YAAYT,EAAG,WAAWQ,CAAQ,IACjDR,EAAG,aAAaQ,GAAU,MAAM,IAChC;EAMJ,QAAQC,EAAQ;EAChB,SAASA,EAAQ;CACnB;AACF;AAQA,SAAgBH,EACd,GACA,GAC8C;CAU9C,OAREG,EAAQ,WAAW,aACnBA,EAAQ,WACRT,EAAG,WAAWQ,CAAQ,KACtBV,EAAmBE,EAAG,aAAaQ,GAAU,MAAM,GAAGT,CAAkB,CAAC,CACtE,SAEI;EAAE,QAAQ;EAAM,QAAQW,EAAcF,CAAQ;CAAE,IAElD;EAAE,QAAQH,EAAoBG,GAAUC,CAAO;EAAG,QAAQ;CAAK;AACxE;AAOA,SAAgBN,EACd,GACA,GAC8C;CAS9C,OAPEM,EAAQ,WAAW,aACnBA,EAAQ,WACRT,EAAG,WAAWW,CAAO,KACrBX,EAAG,aAAaW,GAAS,MAAM,CAAC,CAAC,KAAK,MAAM,KAErC;EAAE,QAAQ;EAAM,QAAQD,EAAcC,CAAO;CAAE,IAEjD;EAAE,QAAQN,EAAoBM,GAASF,CAAO;EAAG,QAAQ;CAAK;AACvE;AAWA,SAAgBL,EAAY,GAAiB,GAAsB;CACjE,OAAOQ,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-5HNE8Q1r.js";
|
|
2
|
-
import { i as t, s as n } from "./constants-
|
|
2
|
+
import { i as t, s as n } from "./constants-CUv536Rj.js";
|
|
3
3
|
import { existsSync as r, readFileSync as i, readdirSync as a } from "node:fs";
|
|
4
4
|
import o from "node:path";
|
|
5
5
|
import s from "pocketbase";
|
|
@@ -224,4 +224,4 @@ function T(e, t) {
|
|
|
224
224
|
//#endregion
|
|
225
225
|
export { w as i, b as n, v as r, x as t };
|
|
226
226
|
|
|
227
|
-
//# sourceMappingURL=pocketbase-
|
|
227
|
+
//# sourceMappingURL=pocketbase-BTR3gI8o.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pocketbase-BtN-wL8f.js","names":["__exportAll","DATA_DIR","MIGRATIONS_DIR","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","authWithRetries","getMigrationFile","getPocketbaseMetadata","migrationDelay","withPocketbase","MIGRATION_DELAY_MS","ending","action","collectionName","migrationFile","readdirSync","options","file","metadataPath","cwd","existsSync","readFileSync","authSuccess","attempt","pb","email","password","dir","migrationsDir","metadata","fn","commandArgs","packageManager","detect","resolveCommand","args","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 { DATA_DIR, MIGRATIONS_DIR } 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\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 commandArgs = [\n \"pocketbase-server\",\n \"serve\",\n \"--dir\",\n dir,\n \"--migrationsDir\",\n migrationsDir,\n \"--http\",\n `${host}:${port}`,\n ];\n\n const packageManager = (await detect({ cwd }))?.name ?? \"npm\";\n const { command, args } = resolveCommand(\n packageManager,\n \"execute\",\n commandArgs,\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 // Start the PocketBase server process. The 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-server 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,IAAaO,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;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AAeD,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-BTR3gI8o.js","names":["__exportAll","DATA_DIR","MIGRATIONS_DIR","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","authWithRetries","getMigrationFile","getPocketbaseMetadata","migrationDelay","withPocketbase","MIGRATION_DELAY_MS","ending","action","collectionName","migrationFile","readdirSync","options","file","metadataPath","cwd","existsSync","readFileSync","authSuccess","attempt","pb","email","password","dir","migrationsDir","metadata","fn","commandArgs","packageManager","detect","resolveCommand","args","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 { DATA_DIR, MIGRATIONS_DIR } 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\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 commandArgs = [\n \"pocketbase-server\",\n \"serve\",\n \"--dir\",\n dir,\n \"--migrationsDir\",\n migrationsDir,\n \"--http\",\n `${host}:${port}`,\n ];\n\n const packageManager = (await detect({ cwd }))?.name ?? \"npm\";\n const { command, args } = resolveCommand(\n packageManager,\n \"execute\",\n commandArgs,\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 // Start the PocketBase server process. The 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-server 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,IAAaO,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;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ED,IAAI;EAEF,MAAM,QAAQ,KAAK,EAChB,YAAY;GAEX,AADA,MAAMK,EAAYF,GAAMF,CAAI,GAC5B,MAAMY,EAAc,UAAUZ,EAAK,GAAGE,GAAM;EAC9C,EAAA,CAAG,GACHkD,CACF,CAAC;EAED,IAAMf,IAAK,IAAI5C,EAAW,UAAUO,EAAK,GAAGE,GAAM;EAMlD,AALA,MAAMgB,EACJmB,GACA,QAAQ,IAAI,4BACZ,QAAQ,IAAI,6BACd,GACA,MAAMM,EAAGN,CAAE;CACb,UAAU;EAER,EAAgBa,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-CL9kQ4hp.js";
|
|
2
|
-
import { readEnvVarNames as n } from "./env-vars-
|
|
2
|
+
import { readEnvVarNames as n } from "./env-vars-XvAeH6u5.js";
|
|
3
3
|
import r from "node:fs";
|
|
4
4
|
import i from "node:path";
|
|
5
5
|
//#region src/runtime/providers.ts
|
|
@@ -35,4 +35,4 @@ function s(e) {
|
|
|
35
35
|
//#endregion
|
|
36
36
|
export { a as detectProviders };
|
|
37
37
|
|
|
38
|
-
//# sourceMappingURL=providers-
|
|
38
|
+
//# sourceMappingURL=providers-CpRRQdMg.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"providers-
|
|
1
|
+
{"version":3,"file":"providers-CpRRQdMg.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,GAC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|
exists: !0,
|
|
16
16
|
rowCount: 0
|
|
17
17
|
}));
|
|
18
|
-
let { withPocketbase: n } = await import("./pocketbase-
|
|
18
|
+
let { withPocketbase: n } = await import("./pocketbase-BTR3gI8o.js").then((e) => e.r), { planCollectionDrops: r } = await import("./collections-zEoRuILr.js").then((e) => e.n), i = [];
|
|
19
19
|
return await n(t.root, async (t) => {
|
|
20
20
|
let n = await r(t, e);
|
|
21
21
|
i.push(...n);
|
|
@@ -24,4 +24,4 @@ async function n(e, t) {
|
|
|
24
24
|
//#endregion
|
|
25
25
|
export { t as n, n as t };
|
|
26
26
|
|
|
27
|
-
//# sourceMappingURL=shared-
|
|
27
|
+
//# sourceMappingURL=shared-CAjLx_8Z.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"shared-
|
|
1
|
+
{"version":3,"file":"shared-CAjLx_8Z.js","names":["languageFromPath","toDeleteEntry","path","planDropsForCollections","collectionNames","options","n","drops","withPocketbase","plans","planCollectionDrops","pb"],"sources":["../../src/patterns/destroy/shared.ts"],"sourcesContent":["import type { CollectionDropSpec, File, Options } from \"../../core/types\";\nimport { languageFromPath } from \"../../core/util\";\n\nexport function toDeleteEntry(path: string): File {\n return {\n path,\n language: languageFromPath(path),\n content: \"\",\n status: \"success\",\n };\n}\n\n/**\n * Build `CollectionDropSpec` entries for each collection name, with live row\n * counts from PocketBase when `env === \"runtime\"`. In preview mode, returns\n * `{ exists: true, rowCount: 0 }` placeholders.\n */\nexport async function planDropsForCollections(\n collectionNames: string[],\n options: Options,\n): Promise<CollectionDropSpec[]> {\n if (collectionNames.length === 0) return [];\n\n if (options.env !== \"runtime\") {\n return collectionNames.map((name) => ({\n name,\n exists: true,\n rowCount: 0,\n }));\n }\n\n const { withPocketbase } = await import(\"../../runtime/pocketbase\");\n const { planCollectionDrops } = await import(\"../../runtime/collections\");\n const drops: CollectionDropSpec[] = [];\n await withPocketbase(options.root, async (pb) => {\n const plans = await planCollectionDrops(pb, collectionNames);\n drops.push(...plans);\n });\n return drops;\n}\n"],"mappings":";;AAGA,SAAgBC,EAAc,GAAoB;CAChD,OAAO;EACL;EACA,UAAUD,EAAiBE,CAAI;EAC/B,SAAS;EACT,QAAQ;CACV;AACF;AAOA,eAAsBC,EACpB,GACA,GAC+B;CAC/B,IAAIC,EAAgB,WAAW,GAAG,OAAO,CAAC;CAE1C,IAAIC,EAAQ,QAAQ,WAClB,OAAOD,EAAgB,KAAK,OAAU;EACpC;EACA,QAAQ;EACR,UAAU;CACZ,EAAE;CAGJ,IAAM,EAAE,sBAAmB,MAAM,OAAO,2BAAA,CAAA,MAAA,MAAAE,EAAA,CAAA,GAClC,EAAE,2BAAwB,MAAM,OAAO,4BAAA,CAAA,MAAA,MAAAA,EAAA,CAAA,GACvCC,IAA8B,CAAC;CAKrC,OAJA,MAAMC,EAAeH,EAAQ,MAAM,OAAO,MAAO;EAC/C,IAAMI,IAAQ,MAAMC,EAAoBC,GAAIP,CAAe;EAC3D,EAAM,KAAK,GAAGK,CAAK;CACrB,CAAC,GACMF;AACT"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { a as e } from "./util-BLYliuUK.js";
|
|
2
2
|
import { n as t } from "./logger-CQONztPm.js";
|
|
3
|
-
import { i as n } from "./pocketbase-
|
|
3
|
+
import { i as n } from "./pocketbase-BTR3gI8o.js";
|
|
4
4
|
import r from "node:fs";
|
|
5
5
|
import i from "node:path";
|
|
6
6
|
//#region src/runtime/site.ts
|
|
@@ -146,4 +146,4 @@ async function b(n, i) {
|
|
|
146
146
|
//#endregion
|
|
147
147
|
export { d as a, p as i, y as n, s as o, f as r, a as s, b as t };
|
|
148
148
|
|
|
149
|
-
//# sourceMappingURL=site-
|
|
149
|
+
//# sourceMappingURL=site-D0IuWkAR.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"site-VrqOvuiU.js","names":["languageFromPath","getLogger","withPocketbase","fs","path","sitePath","root","BUSINESS_KEYS","siteModule","declared","business","lines","key","propertyLines","properties","quote","name","url","entry","i","ensureComma","value","SUPPORTED_CURRENCIES","normalizeCurrency","raw","code","normalizeCountry","normalizeCurrencies","entries","codes","home","SITE_OBJECT","withSiteProperty","match","source","body","siteBusiness","text","shape","list","currency","country","m","existingName","options","appName","pb","pkg","ensureSiteFile","file","ensureSiteBusiness","wanted","existing","added","next"],"sources":["../../src/runtime/site.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 { languageFromPath } from \"../core/util\";\nimport { withPocketbase } from \"./pocketbase\";\n\n/** Where every VelaStack app keeps its name and public URL. */\nexport function sitePath(root: string): string {\n return path.join(root, \"src\", \"lib\", \"site.ts\");\n}\n\n/**\n * What a business declares about itself in `src/lib/site.ts`, next to the\n * app's name: the currency it prices in and is paid in, the country it is in\n * (prices format for it: `es-MX`, not `es`) and the other currencies it shows\n * prices in, as estimates. Every property is optional; a payments provider\n * asks for what it needs.\n */\nexport interface SiteBusiness {\n /** ISO 4217, e.g. `MXN`. */\n currency?: string;\n /** ISO 3166-1 alpha-2, e.g. `MX`. */\n country?: string;\n /** ISO 4217 codes the site also shows prices in; empty means the home currency only. */\n currencies?: string[];\n}\n\ntype BusinessKey = keyof SiteBusiness;\n\nconst BUSINESS_KEYS: BusinessKey[] = [\"currency\", \"country\", \"currencies\"];\n\n/**\n * `src/lib/site.ts` as the CLI templates ship it (`site.template.ts`), with\n * the placeholders filled in, plus whatever the business declares.\n */\nexport function siteModule(\n name: string,\n url = \"http://localhost:5173\",\n business: SiteBusiness | string = {},\n): string {\n // The old third argument was the currency alone.\n const declared: SiteBusiness =\n typeof business === \"string\" ? { currency: business } : business;\n const lines = BUSINESS_KEYS.filter((key) => declared[key] !== undefined).map(\n (key) => propertyLines(key, declared[key]!),\n );\n const properties = [\n `\\tname: ${quote(name)},`,\n `\\turl: ${quote(url)}`,\n ...lines.map((entry) => entry.join(\"\\n\")),\n ];\n return [\n \"/**\",\n \" * Site-wide metadata, and the one place the app's name and public URL live.\",\n \" *\",\n \" * Set `url` to where the site is deployed: canonical links, Open Graph images\",\n \" * and feeds are built from it, including in prerendered pages. With a backend,\",\n \" * `vela dev` and `vela deploy` copy `name` into PocketBase's application name\",\n \" * for the emails it sends, so change it here rather than in the admin panel.\",\n \" */\",\n \"export const site = {\",\n // Every property but the last ends in a comma.\n ...properties.map((entry, i) =>\n i < properties.length - 1 ? ensureComma(entry) : entry,\n ),\n \"};\",\n \"\",\n ].join(\"\\n\");\n}\n\nfunction ensureComma(entry: string): string {\n return entry.endsWith(\",\") ? entry : `${entry},`;\n}\n\n/** A property's lines: its doc comment, then `key: value` with no trailing comma. */\nfunction propertyLines(key: BusinessKey, value: string | string[]): string[] {\n switch (key) {\n case \"currency\":\n return [\n \"\\t/** ISO 4217: the currency the business prices in and is paid in. */\",\n `\\tcurrency: ${quote(value as string)}`,\n ];\n case \"country\":\n return [\n \"\\t/** ISO 3166-1: the country the business is in; prices format for it. */\",\n `\\tcountry: ${quote(value as string)}`,\n ];\n case \"currencies\":\n return [\n \"\\t/** Other currencies prices are shown in, as estimates at the day's rate. */\",\n `\\tcurrencies: [${(value as string[]).map(quote).join(\", \")}]`,\n ];\n }\n}\n\nconst SUPPORTED_CURRENCIES = (\n Intl as unknown as {\n supportedValuesOf: (key: \"currency\") => string[];\n }\n).supportedValuesOf(\"currency\");\n\n/** A three-letter code `Intl` knows, upper-cased; anything else is refused. */\nexport function normalizeCurrency(raw: unknown): string | null {\n if (typeof raw !== \"string\") return null;\n const code = raw.trim().toUpperCase();\n if (!/^[A-Z]{3}$/.test(code)) return null;\n // Any well-formed code formats, so ask for the list of real ones. Node has\n // had it since 18; the repo's ES2020 lib types just don't declare it.\n return SUPPORTED_CURRENCIES.includes(code) ? code : null;\n}\n\n/** A two-letter ISO 3166-1 code, upper-cased; anything else is refused. */\nexport function normalizeCountry(raw: unknown): string | null {\n if (typeof raw !== \"string\") return null;\n const code = raw.trim().toUpperCase();\n if (!/^[A-Z]{2}$/.test(code)) return null;\n // `Intl.DisplayNames` knows every region; an unknown one comes back as is.\n const names = new Intl.DisplayNames([\"en\"], { type: \"region\" });\n return names.of(code) !== code ? code : null;\n}\n\n/**\n * A list of currency codes, from an array or a comma-separated string,\n * upper-cased and deduplicated; `null` when any entry is not a currency.\n * `home` is left out: the business's own currency is never a display one.\n */\nexport function normalizeCurrencies(\n raw: unknown,\n home?: string,\n): string[] | null {\n const entries = Array.isArray(raw)\n ? raw\n : typeof raw === \"string\"\n ? raw.split(/[,\\s]+/)\n : null;\n if (!entries) return null;\n const codes: string[] = [];\n for (const entry of entries) {\n if (entry === \"\" || entry === undefined) continue;\n const code = normalizeCurrency(entry);\n if (!code) return null;\n if (code !== home && !codes.includes(code)) codes.push(code);\n }\n return codes;\n}\n\nconst SITE_OBJECT = /export const site = \\{\\n([\\s\\S]*?)\\n\\};/;\n\n/**\n * `src/lib/site.ts` with `key` added as the object's last property, or\n * `null` when it already has one (a project's declaration is never changed\n * behind its back) or has no `export const site = { ... };` to add it to.\n */\nexport function withSiteProperty(\n source: string,\n key: BusinessKey,\n value: string | string[],\n): string | null {\n const match = SITE_OBJECT.exec(source);\n if (!match || new RegExp(`^\\\\s*${key}\\\\s*:`, \"m\").test(match[1])) return null;\n const body = match[1].replace(/,?\\s*$/, \",\");\n return source.replace(\n match[0],\n `export const site = {\\n${body}\\n${propertyLines(key, value).join(\"\\n\")}\\n};`,\n );\n}\n\n/** `withSiteProperty` for the currency, as the Phase 1.5 code called it. */\nexport function withSiteCurrency(\n source: string,\n currency: string,\n): string | null {\n return withSiteProperty(source, \"currency\", currency);\n}\n\n/** What `src/lib/site.ts` declares about the business, if anything. */\nexport function siteBusiness(root: string): SiteBusiness {\n let source: string;\n try {\n source = fs.readFileSync(sitePath(root), \"utf8\");\n } catch {\n return {};\n }\n const text = (key: string, shape: string) =>\n new RegExp(`^\\\\s*${key}\\\\s*:\\\\s*['\"](${shape})['\"]`, \"m\").exec(source)?.[1];\n const list = /^\\s*currencies\\s*:\\s*\\[([^\\]]*)\\]/m.exec(source)?.[1];\n const business: SiteBusiness = {};\n const currency = text(\"currency\", \"[A-Za-z]{3}\");\n if (currency) business.currency = currency;\n const country = text(\"country\", \"[A-Za-z]{2}\");\n if (country) business.country = country;\n if (list !== undefined) {\n business.currencies = [...list.matchAll(/['\"]([A-Za-z]{3})['\"]/g)].map(\n (m) => m[1],\n );\n }\n return business;\n}\n\n/** The currency `src/lib/site.ts` declares, if any. */\nexport function siteCurrency(root: string): string | null {\n return siteBusiness(root).currency ?? null;\n}\n\n/** Single-quoted, as the templates write their strings. */\nfunction quote(value: string): string {\n return `'${value.replace(/\\\\/g, \"\\\\\\\\\").replace(/'/g, \"\\\\'\")}'`;\n}\n\n/**\n * The name a project created before `site.ts` existed already goes by.\n *\n * Those projects kept it in PocketBase's settings, so that is asked first; the\n * package name is the fallback for a project without a backend, or one whose\n * database can't be reached.\n */\nasync function existingName(options: Options): Promise<string> {\n if (options.features.backend) {\n try {\n let appName: unknown;\n await withPocketbase(options.root, async (pb) => {\n const settings = (await pb.settings.getAll()) as {\n meta?: { appName?: unknown };\n };\n appName = settings.meta?.appName;\n });\n if (typeof appName === \"string\" && appName.trim()) return appName;\n } catch {\n // No database to ask; fall through to package.json.\n }\n }\n\n try {\n const pkg = JSON.parse(\n fs.readFileSync(path.join(options.root, \"package.json\"), \"utf8\"),\n ) as { name?: unknown };\n if (typeof pkg.name === \"string\" && pkg.name.trim()) return pkg.name;\n } catch {\n // No package.json to name the site after; the placeholder stands.\n }\n return \"My App\";\n}\n\n/**\n * Create `src/lib/site.ts` for a pattern whose files import `#lib/site.js`, when\n * the project doesn't have one yet. Every template ships it; projects created\n * before that read the app name from `locals.meta` instead.\n *\n * Returns null when the file exists, so an existing one is never overwritten.\n */\nexport async function ensureSiteFile(options: Options): Promise<File | null> {\n const file = sitePath(options.root);\n if (fs.existsSync(file)) return null;\n\n getLogger(options).info(\"Creating src/lib/site.ts\");\n return {\n path: file,\n language: languageFromPath(file),\n content: siteModule(await existingName(options)),\n status: \"success\",\n };\n}\n\n/**\n * Make `src/lib/site.ts` declare what the business says about itself: create\n * the file with it, or add the properties an existing one lacks. A property\n * already there is kept, whatever `business` says; the result says what the\n * file declares after the call, and the file to write, if anything changed.\n */\nexport async function ensureSiteBusiness(\n options: Options,\n business: SiteBusiness,\n): Promise<{ file: File | null; business: SiteBusiness }> {\n const file = sitePath(options.root);\n const wanted = BUSINESS_KEYS.filter((key) => business[key] !== undefined);\n if (!fs.existsSync(file)) {\n if (wanted.length === 0) return { file: null, business: {} };\n getLogger(options).info(\"Creating src/lib/site.ts\");\n return {\n file: {\n path: file,\n language: languageFromPath(file),\n content: siteModule(await existingName(options), undefined, business),\n status: \"success\",\n },\n business,\n };\n }\n\n const existing = siteBusiness(options.root);\n let source = fs.readFileSync(file, \"utf8\");\n const added: string[] = [];\n for (const key of wanted) {\n if (existing[key] !== undefined) continue;\n const next = withSiteProperty(source, key, business[key]!);\n if (next === null) continue;\n source = next;\n added.push(key);\n (existing as Record<string, unknown>)[key] = business[key];\n }\n if (added.length === 0) return { file: null, business: existing };\n getLogger(options).info(`Adding ${added.join(\", \")} to src/lib/site.ts`);\n return {\n file: {\n path: file,\n language: languageFromPath(file),\n content: source,\n status: \"success\",\n },\n business: existing,\n };\n}\n\n/** `ensureSiteBusiness` for the currency alone, as the Phase 1.5 code called it. */\nexport async function ensureSiteCurrency(\n options: Options,\n currency: string,\n): Promise<{ file: File | null; currency: string }> {\n const { file, business } = await ensureSiteBusiness(options, { currency });\n return { file, currency: business.currency ?? currency };\n}\n"],"mappings":";;;;;;AAQA,SAAgBK,EAAS,GAAsB;CAC7C,OAAOD,EAAK,KAAKE,GAAM,OAAO,OAAO,SAAS;AAChD;AAoBA,IAAMC,IAA+B;CAAC;CAAY;CAAW;AAAY;AAMzE,SAAgBC,EACd,GACA,IAAM,yBACN,IAAkC,CAAC,GAC3B;CAER,IAAMC,IACJ,OAAOC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D,IAAO5C,EAASuC,EAAQ,IAAI,GAC5BO,IAAS5C,EAAc,QAAQ,MAAQG,EAASE,OAAS,KAAA,CAAS;CACxE,IAAI,CAACT,EAAG,WAAW8C,CAAI,GAGrB,OAFIE,EAAO,WAAW,IAAU;EAAE,MAAM;EAAM,UAAU,CAAC;CAAE,KAC3DlD,EAAU2C,CAAO,CAAC,CAAC,KAAK,0BAA0B,GAC3C;EACL,MAAM;GACJ,MAAMK;GACN,UAAUjD,EAAiBiD,CAAI;GAC/B,SAASzC,EAAW,MAAMmC,EAAaC,CAAO,GAAG,KAAA,GAAWlC,CAAQ;GACpE,QAAQ;EACV;EACA;CACF;CAGF,IAAM0C,IAAWhB,EAAaQ,EAAQ,IAAI,GACtCV,IAAS/B,EAAG,aAAa8C,GAAM,MAAM,GACnCI,IAAkB,CAAC;CACzB,KAAK,IAAMzC,KAAOuC,GAAQ;EACxB,IAAIC,EAASxC,OAAS,KAAA,GAAW;EACjC,IAAM0C,IAAOtB,EAAiBE,GAAQtB,GAAKF,EAASE,EAAK;EACzD,AAAI0C,MAAS,SACb,IAASA,GACTD,EAAM,KAAKzC,CAAG,GACd,EAAsCA,KAAOF,EAASE;CACxD;CAGA,OAFIyC,EAAM,WAAW,IAAU;EAAE,MAAM;EAAM,UAAUD;CAAS,KAChEnD,EAAU2C,CAAO,CAAC,CAAC,KAAK,UAAUS,EAAM,KAAK,IAAI,EAAE,oBAAoB,GAChE;EACL,MAAM;GACJ,MAAMJ;GACN,UAAUjD,EAAiBiD,CAAI;GAC/B,SAASf;GACT,QAAQ;EACV;EACA,UAAUkB;CACZ;AACF"}
|
|
1
|
+
{"version":3,"file":"site-D0IuWkAR.js","names":["languageFromPath","getLogger","withPocketbase","fs","path","sitePath","root","BUSINESS_KEYS","siteModule","declared","business","lines","key","propertyLines","properties","quote","name","url","entry","i","ensureComma","value","SUPPORTED_CURRENCIES","normalizeCurrency","raw","code","normalizeCountry","normalizeCurrencies","entries","codes","home","SITE_OBJECT","withSiteProperty","match","source","body","siteBusiness","text","shape","list","currency","country","m","existingName","options","appName","pb","pkg","ensureSiteFile","file","ensureSiteBusiness","wanted","existing","added","next"],"sources":["../../src/runtime/site.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 { languageFromPath } from \"../core/util\";\nimport { withPocketbase } from \"./pocketbase\";\n\n/** Where every VelaStack app keeps its name and public URL. */\nexport function sitePath(root: string): string {\n return path.join(root, \"src\", \"lib\", \"site.ts\");\n}\n\n/**\n * What a business declares about itself in `src/lib/site.ts`, next to the\n * app's name: the currency it prices in and is paid in, the country it is in\n * (prices format for it: `es-MX`, not `es`) and the other currencies it shows\n * prices in, as estimates. Every property is optional; a payments provider\n * asks for what it needs.\n */\nexport interface SiteBusiness {\n /** ISO 4217, e.g. `MXN`. */\n currency?: string;\n /** ISO 3166-1 alpha-2, e.g. `MX`. */\n country?: string;\n /** ISO 4217 codes the site also shows prices in; empty means the home currency only. */\n currencies?: string[];\n}\n\ntype BusinessKey = keyof SiteBusiness;\n\nconst BUSINESS_KEYS: BusinessKey[] = [\"currency\", \"country\", \"currencies\"];\n\n/**\n * `src/lib/site.ts` as the CLI templates ship it (`site.template.ts`), with\n * the placeholders filled in, plus whatever the business declares.\n */\nexport function siteModule(\n name: string,\n url = \"http://localhost:5173\",\n business: SiteBusiness | string = {},\n): string {\n // The old third argument was the currency alone.\n const declared: SiteBusiness =\n typeof business === \"string\" ? { currency: business } : business;\n const lines = BUSINESS_KEYS.filter((key) => declared[key] !== undefined).map(\n (key) => propertyLines(key, declared[key]!),\n );\n const properties = [\n `\\tname: ${quote(name)},`,\n `\\turl: ${quote(url)}`,\n ...lines.map((entry) => entry.join(\"\\n\")),\n ];\n return [\n \"/**\",\n \" * Site-wide metadata, and the one place the app's name and public URL live.\",\n \" *\",\n \" * Set `url` to where the site is deployed: canonical links, Open Graph images\",\n \" * and feeds are built from it, including in prerendered pages. With a backend,\",\n \" * `vela dev` and `vela deploy` copy `name` into PocketBase's application name\",\n \" * for the emails it sends, so change it here rather than in the admin panel.\",\n \" */\",\n \"export const site = {\",\n // Every property but the last ends in a comma.\n ...properties.map((entry, i) =>\n i < properties.length - 1 ? ensureComma(entry) : entry,\n ),\n \"};\",\n \"\",\n ].join(\"\\n\");\n}\n\nfunction ensureComma(entry: string): string {\n return entry.endsWith(\",\") ? entry : `${entry},`;\n}\n\n/** A property's lines: its doc comment, then `key: value` with no trailing comma. */\nfunction propertyLines(key: BusinessKey, value: string | string[]): string[] {\n switch (key) {\n case \"currency\":\n return [\n \"\\t/** ISO 4217: the currency the business prices in and is paid in. */\",\n `\\tcurrency: ${quote(value as string)}`,\n ];\n case \"country\":\n return [\n \"\\t/** ISO 3166-1: the country the business is in; prices format for it. */\",\n `\\tcountry: ${quote(value as string)}`,\n ];\n case \"currencies\":\n return [\n \"\\t/** Other currencies prices are shown in, as estimates at the day's rate. */\",\n `\\tcurrencies: [${(value as string[]).map(quote).join(\", \")}]`,\n ];\n }\n}\n\nconst SUPPORTED_CURRENCIES = (\n Intl as unknown as {\n supportedValuesOf: (key: \"currency\") => string[];\n }\n).supportedValuesOf(\"currency\");\n\n/** A three-letter code `Intl` knows, upper-cased; anything else is refused. */\nexport function normalizeCurrency(raw: unknown): string | null {\n if (typeof raw !== \"string\") return null;\n const code = raw.trim().toUpperCase();\n if (!/^[A-Z]{3}$/.test(code)) return null;\n // Any well-formed code formats, so ask for the list of real ones. Node has\n // had it since 18; the repo's ES2020 lib types just don't declare it.\n return SUPPORTED_CURRENCIES.includes(code) ? code : null;\n}\n\n/** A two-letter ISO 3166-1 code, upper-cased; anything else is refused. */\nexport function normalizeCountry(raw: unknown): string | null {\n if (typeof raw !== \"string\") return null;\n const code = raw.trim().toUpperCase();\n if (!/^[A-Z]{2}$/.test(code)) return null;\n // `Intl.DisplayNames` knows every region; an unknown one comes back as is.\n const names = new Intl.DisplayNames([\"en\"], { type: \"region\" });\n return names.of(code) !== code ? code : null;\n}\n\n/**\n * A list of currency codes, from an array or a comma-separated string,\n * upper-cased and deduplicated; `null` when any entry is not a currency.\n * `home` is left out: the business's own currency is never a display one.\n */\nexport function normalizeCurrencies(\n raw: unknown,\n home?: string,\n): string[] | null {\n const entries = Array.isArray(raw)\n ? raw\n : typeof raw === \"string\"\n ? raw.split(/[,\\s]+/)\n : null;\n if (!entries) return null;\n const codes: string[] = [];\n for (const entry of entries) {\n if (entry === \"\" || entry === undefined) continue;\n const code = normalizeCurrency(entry);\n if (!code) return null;\n if (code !== home && !codes.includes(code)) codes.push(code);\n }\n return codes;\n}\n\nconst SITE_OBJECT = /export const site = \\{\\n([\\s\\S]*?)\\n\\};/;\n\n/**\n * `src/lib/site.ts` with `key` added as the object's last property, or\n * `null` when it already has one (a project's declaration is never changed\n * behind its back) or has no `export const site = { ... };` to add it to.\n */\nexport function withSiteProperty(\n source: string,\n key: BusinessKey,\n value: string | string[],\n): string | null {\n const match = SITE_OBJECT.exec(source);\n if (!match || new RegExp(`^\\\\s*${key}\\\\s*:`, \"m\").test(match[1])) return null;\n const body = match[1].replace(/,?\\s*$/, \",\");\n return source.replace(\n match[0],\n `export const site = {\\n${body}\\n${propertyLines(key, value).join(\"\\n\")}\\n};`,\n );\n}\n\n/** `withSiteProperty` for the currency, as the Phase 1.5 code called it. */\nexport function withSiteCurrency(\n source: string,\n currency: string,\n): string | null {\n return withSiteProperty(source, \"currency\", currency);\n}\n\n/** What `src/lib/site.ts` declares about the business, if anything. */\nexport function siteBusiness(root: string): SiteBusiness {\n let source: string;\n try {\n source = fs.readFileSync(sitePath(root), \"utf8\");\n } catch {\n return {};\n }\n const text = (key: string, shape: string) =>\n new RegExp(`^\\\\s*${key}\\\\s*:\\\\s*['\"](${shape})['\"]`, \"m\").exec(source)?.[1];\n const list = /^\\s*currencies\\s*:\\s*\\[([^\\]]*)\\]/m.exec(source)?.[1];\n const business: SiteBusiness = {};\n const currency = text(\"currency\", \"[A-Za-z]{3}\");\n if (currency) business.currency = currency;\n const country = text(\"country\", \"[A-Za-z]{2}\");\n if (country) business.country = country;\n if (list !== undefined) {\n business.currencies = [...list.matchAll(/['\"]([A-Za-z]{3})['\"]/g)].map(\n (m) => m[1],\n );\n }\n return business;\n}\n\n/** The currency `src/lib/site.ts` declares, if any. */\nexport function siteCurrency(root: string): string | null {\n return siteBusiness(root).currency ?? null;\n}\n\n/** Single-quoted, as the templates write their strings. */\nfunction quote(value: string): string {\n return `'${value.replace(/\\\\/g, \"\\\\\\\\\").replace(/'/g, \"\\\\'\")}'`;\n}\n\n/**\n * The name a project created before `site.ts` existed already goes by.\n *\n * Those projects kept it in PocketBase's settings, so that is asked first; the\n * package name is the fallback for a project without a backend, or one whose\n * database can't be reached.\n */\nasync function existingName(options: Options): Promise<string> {\n if (options.features.backend) {\n try {\n let appName: unknown;\n await withPocketbase(options.root, async (pb) => {\n const settings = (await pb.settings.getAll()) as {\n meta?: { appName?: unknown };\n };\n appName = settings.meta?.appName;\n });\n if (typeof appName === \"string\" && appName.trim()) return appName;\n } catch {\n // No database to ask; fall through to package.json.\n }\n }\n\n try {\n const pkg = JSON.parse(\n fs.readFileSync(path.join(options.root, \"package.json\"), \"utf8\"),\n ) as { name?: unknown };\n if (typeof pkg.name === \"string\" && pkg.name.trim()) return pkg.name;\n } catch {\n // No package.json to name the site after; the placeholder stands.\n }\n return \"My App\";\n}\n\n/**\n * Create `src/lib/site.ts` for a pattern whose files import `#lib/site.js`, when\n * the project doesn't have one yet. Every template ships it; projects created\n * before that read the app name from `locals.meta` instead.\n *\n * Returns null when the file exists, so an existing one is never overwritten.\n */\nexport async function ensureSiteFile(options: Options): Promise<File | null> {\n const file = sitePath(options.root);\n if (fs.existsSync(file)) return null;\n\n getLogger(options).info(\"Creating src/lib/site.ts\");\n return {\n path: file,\n language: languageFromPath(file),\n content: siteModule(await existingName(options)),\n status: \"success\",\n };\n}\n\n/**\n * Make `src/lib/site.ts` declare what the business says about itself: create\n * the file with it, or add the properties an existing one lacks. A property\n * already there is kept, whatever `business` says; the result says what the\n * file declares after the call, and the file to write, if anything changed.\n */\nexport async function ensureSiteBusiness(\n options: Options,\n business: SiteBusiness,\n): Promise<{ file: File | null; business: SiteBusiness }> {\n const file = sitePath(options.root);\n const wanted = BUSINESS_KEYS.filter((key) => business[key] !== undefined);\n if (!fs.existsSync(file)) {\n if (wanted.length === 0) return { file: null, business: {} };\n getLogger(options).info(\"Creating src/lib/site.ts\");\n return {\n file: {\n path: file,\n language: languageFromPath(file),\n content: siteModule(await existingName(options), undefined, business),\n status: \"success\",\n },\n business,\n };\n }\n\n const existing = siteBusiness(options.root);\n let source = fs.readFileSync(file, \"utf8\");\n const added: string[] = [];\n for (const key of wanted) {\n if (existing[key] !== undefined) continue;\n const next = withSiteProperty(source, key, business[key]!);\n if (next === null) continue;\n source = next;\n added.push(key);\n (existing as Record<string, unknown>)[key] = business[key];\n }\n if (added.length === 0) return { file: null, business: existing };\n getLogger(options).info(`Adding ${added.join(\", \")} to src/lib/site.ts`);\n return {\n file: {\n path: file,\n language: languageFromPath(file),\n content: source,\n status: \"success\",\n },\n business: existing,\n };\n}\n\n/** `ensureSiteBusiness` for the currency alone, as the Phase 1.5 code called it. */\nexport async function ensureSiteCurrency(\n options: Options,\n currency: string,\n): Promise<{ file: File | null; currency: string }> {\n const { file, business } = await ensureSiteBusiness(options, { currency });\n return { file, currency: business.currency ?? currency };\n}\n"],"mappings":";;;;;;AAQA,SAAgBK,EAAS,GAAsB;CAC7C,OAAOD,EAAK,KAAKE,GAAM,OAAO,OAAO,SAAS;AAChD;AAoBA,IAAMC,IAA+B;CAAC;CAAY;CAAW;AAAY;AAMzE,SAAgBC,EACd,GACA,IAAM,yBACN,IAAkC,CAAC,GAC3B;CAER,IAAMC,IACJ,OAAOC,KAAa,WAAW,EAAE,UAAUA,EAAS,IAAIA,GACpDC,IAAQJ,EAAc,QAAQ,MAAQE,EAASG,OAAS,KAAA,CAAS,CAAC,CAAC,KACtE,MAAQC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