@velastack/patterns 0.4.3 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (145) hide show
  1. package/README.md +22 -2
  2. package/dist/chunks/{_page-e_I-fdSR.js → _page-DoPdZgZv.js} +2 -2
  3. package/dist/chunks/_page-DoPdZgZv.js.map +1 -0
  4. package/dist/chunks/collections-B_DisSfA.js +203 -0
  5. package/dist/chunks/collections-B_DisSfA.js.map +1 -0
  6. package/dist/chunks/{constants-Rq8SCXwH.js → constants-iej3WkEa.js} +3 -3
  7. package/dist/chunks/constants-iej3WkEa.js.map +1 -0
  8. package/dist/chunks/dispatch-BIvOwbKN.js +6 -0
  9. package/dist/chunks/dispatch-BIvOwbKN.js.map +1 -0
  10. package/dist/chunks/{env-vars-CcE6ODqC.js → env-vars-cqQU0ECK.js} +32 -20
  11. package/dist/chunks/env-vars-cqQU0ECK.js.map +1 -0
  12. package/dist/chunks/generate-8FS2ROOJ.js +170 -0
  13. package/dist/chunks/generate-8FS2ROOJ.js.map +1 -0
  14. package/dist/chunks/{generate-CFqpRi9D.js → generate-Bm_jOMtF.js} +4 -4
  15. package/dist/chunks/{generate-CFqpRi9D.js.map → generate-Bm_jOMtF.js.map} +1 -1
  16. package/dist/chunks/{generate-Bg0E3eWm.js → generate-CXoQPz7n.js} +4 -4
  17. package/dist/chunks/{generate-Bg0E3eWm.js.map → generate-CXoQPz7n.js.map} +1 -1
  18. package/dist/chunks/{generate-B6Odfk5f.js → generate-Cqwa8kD9.js} +2 -2
  19. package/dist/chunks/{generate-B6Odfk5f.js.map → generate-Cqwa8kD9.js.map} +1 -1
  20. package/dist/chunks/{generate-CZGHByV3.js → generate-D3mSFPdT.js} +7 -7
  21. package/dist/chunks/{generate-CZGHByV3.js.map → generate-D3mSFPdT.js.map} +1 -1
  22. package/dist/chunks/{generate-DetW_gbr.js → generate-DyV5R8NP.js} +7 -7
  23. package/dist/chunks/{generate-DetW_gbr.js.map → generate-DyV5R8NP.js.map} +1 -1
  24. package/dist/chunks/generate-jx5Iuq5w.js +75 -0
  25. package/dist/chunks/generate-jx5Iuq5w.js.map +1 -0
  26. package/dist/chunks/{generate.runtime-Djas9UNy.js → generate.runtime-B2r11K7S.js} +4 -4
  27. package/dist/chunks/{generate.runtime-Djas9UNy.js.map → generate.runtime-B2r11K7S.js.map} +1 -1
  28. package/dist/chunks/{generate.runtime-Bcrht4M9.js → generate.runtime-B4u9C2YH.js} +9 -9
  29. package/dist/chunks/{generate.runtime-Bcrht4M9.js.map → generate.runtime-B4u9C2YH.js.map} +1 -1
  30. package/dist/chunks/{generate.runtime-DVB7uuht.js → generate.runtime-BRCzUO94.js} +3 -3
  31. package/dist/chunks/{generate.runtime-DVB7uuht.js.map → generate.runtime-BRCzUO94.js.map} +1 -1
  32. package/dist/chunks/{generate.runtime-IWEhGhWY.js → generate.runtime-BVavIXtX.js} +6 -6
  33. package/dist/chunks/{generate.runtime-IWEhGhWY.js.map → generate.runtime-BVavIXtX.js.map} +1 -1
  34. package/dist/chunks/generate.runtime-Bh9Z2cRN.js +82 -0
  35. package/dist/chunks/generate.runtime-Bh9Z2cRN.js.map +1 -0
  36. package/dist/chunks/{generate.runtime-DJHUBL4Z.js → generate.runtime-BxDUtkpT.js} +12 -12
  37. package/dist/chunks/{generate.runtime-DJHUBL4Z.js.map → generate.runtime-BxDUtkpT.js.map} +1 -1
  38. package/dist/chunks/{generate.runtime-hTKzxH2M.js → generate.runtime-BxUGDXIK.js} +7 -7
  39. package/dist/chunks/{generate.runtime-hTKzxH2M.js.map → generate.runtime-BxUGDXIK.js.map} +1 -1
  40. package/dist/chunks/{generate.runtime-5rIc-RNL.js → generate.runtime-CHb4znYx.js} +66 -66
  41. package/dist/chunks/{generate.runtime-5rIc-RNL.js.map → generate.runtime-CHb4znYx.js.map} +1 -1
  42. package/dist/chunks/{generate.runtime-E-zoeSKW.js → generate.runtime-CRhD98rs.js} +7 -7
  43. package/dist/chunks/{generate.runtime-E-zoeSKW.js.map → generate.runtime-CRhD98rs.js.map} +1 -1
  44. package/dist/chunks/{generate.runtime-BpMN5Uq-.js → generate.runtime-CWnIiXwV.js} +3 -3
  45. package/dist/chunks/{generate.runtime-BpMN5Uq-.js.map → generate.runtime-CWnIiXwV.js.map} +1 -1
  46. package/dist/chunks/{generate.runtime-kciwaXxh.js → generate.runtime-CYBs0JgY.js} +4 -4
  47. package/dist/chunks/{generate.runtime-kciwaXxh.js.map → generate.runtime-CYBs0JgY.js.map} +1 -1
  48. package/dist/chunks/{generate.runtime-CAn1qIQ_.js → generate.runtime-CkmledBw.js} +3 -3
  49. package/dist/chunks/{generate.runtime-CAn1qIQ_.js.map → generate.runtime-CkmledBw.js.map} +1 -1
  50. package/dist/chunks/generate.runtime-CyGR8VTx.js +48 -0
  51. package/dist/chunks/generate.runtime-CyGR8VTx.js.map +1 -0
  52. package/dist/chunks/{generate.runtime-a3R4hqFy.js → generate.runtime-DCqf7nYM.js} +12 -12
  53. package/dist/chunks/{generate.runtime-a3R4hqFy.js.map → generate.runtime-DCqf7nYM.js.map} +1 -1
  54. package/dist/chunks/{generate.runtime-uLUiPgqx.js → generate.runtime-DUo-pLRr.js} +6 -6
  55. package/dist/chunks/{generate.runtime-uLUiPgqx.js.map → generate.runtime-DUo-pLRr.js.map} +1 -1
  56. package/dist/chunks/{generate.runtime-CpMKXBkn.js → generate.runtime-DY5vQ3aZ.js} +7 -7
  57. package/dist/chunks/{generate.runtime-CpMKXBkn.js.map → generate.runtime-DY5vQ3aZ.js.map} +1 -1
  58. package/dist/chunks/{generate.runtime-CEqLgLT9.js → generate.runtime-DYdkrHJ1.js} +70 -70
  59. package/dist/chunks/{generate.runtime-CEqLgLT9.js.map → generate.runtime-DYdkrHJ1.js.map} +1 -1
  60. package/dist/chunks/{generate.runtime-DHHlYfTD.js → generate.runtime-DdcVnK8J.js} +3 -3
  61. package/dist/chunks/{generate.runtime-DHHlYfTD.js.map → generate.runtime-DdcVnK8J.js.map} +1 -1
  62. package/dist/chunks/{generate.runtime-koQxLywh.js → generate.runtime-DeniHg8L.js} +48 -48
  63. package/dist/chunks/{generate.runtime-koQxLywh.js.map → generate.runtime-DeniHg8L.js.map} +1 -1
  64. package/dist/chunks/{generate.runtime-DoZJHtZh.js → generate.runtime-Dmob2wFf.js} +6 -6
  65. package/dist/chunks/{generate.runtime-DoZJHtZh.js.map → generate.runtime-Dmob2wFf.js.map} +1 -1
  66. package/dist/chunks/{generate.runtime-Db0HZyj3.js → generate.runtime-Du4uf98c.js} +2 -2
  67. package/dist/chunks/{generate.runtime-Db0HZyj3.js.map → generate.runtime-Du4uf98c.js.map} +1 -1
  68. package/dist/chunks/{generate.runtime-axm9wcQv.js → generate.runtime-Dug2UIhV.js} +4 -4
  69. package/dist/chunks/{generate.runtime-axm9wcQv.js.map → generate.runtime-Dug2UIhV.js.map} +1 -1
  70. package/dist/chunks/{generate.runtime-rs1ZOIET.js → generate.runtime-FGYc365Q.js} +15 -15
  71. package/dist/chunks/{generate.runtime-rs1ZOIET.js.map → generate.runtime-FGYc365Q.js.map} +1 -1
  72. package/dist/chunks/{generate.runtime-BK3mR0Rj.js → generate.runtime-N1KtAG8C.js} +169 -129
  73. package/dist/chunks/generate.runtime-N1KtAG8C.js.map +1 -0
  74. package/dist/chunks/{generate.runtime-CbE9RHcf.js → generate.runtime-_c7daMAw.js} +5 -5
  75. package/dist/chunks/generate.runtime-_c7daMAw.js.map +1 -0
  76. package/dist/chunks/generate.runtime-aN5QWygO.js +106 -0
  77. package/dist/chunks/generate.runtime-aN5QWygO.js.map +1 -0
  78. package/dist/chunks/{generate.runtime-CZ46nkSL.js → generate.runtime-bpH3DB0t.js} +2 -2
  79. package/dist/chunks/{generate.runtime-CZ46nkSL.js.map → generate.runtime-bpH3DB0t.js.map} +1 -1
  80. package/dist/chunks/{generate.runtime-CqncBFNg.js → generate.runtime-gFr2Gsjz.js} +4 -4
  81. package/dist/chunks/{generate.runtime-CqncBFNg.js.map → generate.runtime-gFr2Gsjz.js.map} +1 -1
  82. package/dist/chunks/{generate.runtime-CK10Mum5.js → generate.runtime-kpqW3dVO.js} +25 -25
  83. package/dist/chunks/{generate.runtime-CK10Mum5.js.map → generate.runtime-kpqW3dVO.js.map} +1 -1
  84. package/dist/chunks/{generate.runtime-Dl6OQ7pe.js → generate.runtime-wGRE1zwZ.js} +4 -4
  85. package/dist/chunks/{generate.runtime-Dl6OQ7pe.js.map → generate.runtime-wGRE1zwZ.js.map} +1 -1
  86. package/dist/chunks/{generate.runtime-aQnBmH8D.js → generate.runtime-wziCW3ct.js} +69 -69
  87. package/dist/chunks/{generate.runtime-aQnBmH8D.js.map → generate.runtime-wziCW3ct.js.map} +1 -1
  88. package/dist/chunks/{generate.runtime-DJ9MVVPC.js → generate.runtime-x-o4LS8d.js} +123 -110
  89. package/dist/chunks/generate.runtime-x-o4LS8d.js.map +1 -0
  90. package/dist/chunks/modify-file-289rStJ2.js +53 -0
  91. package/dist/chunks/modify-file-289rStJ2.js.map +1 -0
  92. package/dist/chunks/{modify-nav-user-BLyrW2sK.js → modify-nav-user-B8h8WTrM.js} +2 -2
  93. package/dist/chunks/{modify-nav-user-BLyrW2sK.js.map → modify-nav-user-B8h8WTrM.js.map} +1 -1
  94. package/dist/chunks/{pocketbase-CgwbH1gI.js → pocketbase-B017Cqjq.js} +2 -2
  95. package/dist/chunks/{pocketbase-CgwbH1gI.js.map → pocketbase-B017Cqjq.js.map} +1 -1
  96. package/dist/chunks/providers-CL9kQ4hp.js +98 -0
  97. package/dist/chunks/providers-CL9kQ4hp.js.map +1 -0
  98. package/dist/chunks/providers-CN5J5_fY.js +38 -0
  99. package/dist/chunks/providers-CN5J5_fY.js.map +1 -0
  100. package/dist/chunks/{shared-Cc_ns5-y.js → shared-BPlAVf-T.js} +2 -2
  101. package/dist/chunks/{shared-Cc_ns5-y.js.map → shared-BPlAVf-T.js.map} +1 -1
  102. package/dist/chunks/shopify-page-D-VFwGxI.js +11 -0
  103. package/dist/chunks/shopify-page-D-VFwGxI.js.map +1 -0
  104. package/dist/chunks/site-DkU1-VRq.js +108 -0
  105. package/dist/chunks/site-DkU1-VRq.js.map +1 -0
  106. package/dist/chunks/stripe-customer-B3tP8gtD.js +6 -0
  107. package/dist/chunks/stripe-customer-B3tP8gtD.js.map +1 -0
  108. package/dist/chunks/{svelte-file-B3RfgVdt.js → svelte-file-Dv5-bl79.js} +37 -2
  109. package/dist/chunks/svelte-file-Dv5-bl79.js.map +1 -0
  110. package/dist/chunks/{table-core-DhDqT03G.js → table-core-vXEjJDYP.js} +2 -2
  111. package/dist/chunks/{table-core-DhDqT03G.js.map → table-core-vXEjJDYP.js.map} +1 -1
  112. package/dist/chunks/{test-setup-B9fQ5L_-.js → test-setup-CAfgVlwc.js} +3 -3
  113. package/dist/chunks/{test-setup-B9fQ5L_-.js.map → test-setup-CAfgVlwc.js.map} +1 -1
  114. package/dist/chunks/{ui-CuCsupFq.js → ui-CTdsenEv.js} +3 -3
  115. package/dist/chunks/{ui-CuCsupFq.js.map → ui-CTdsenEv.js.map} +1 -1
  116. package/dist/chunks/{whatsapp-CguKGTtw.js → whatsapp-5qJ_xCV1.js} +2 -2
  117. package/dist/chunks/{whatsapp-CguKGTtw.js.map → whatsapp-5qJ_xCV1.js.map} +1 -1
  118. package/dist/chunks/{write-result-DiZsCS_y.js → write-result-0HYIr5a6.js} +4 -4
  119. package/dist/chunks/write-result-0HYIr5a6.js.map +1 -0
  120. package/dist/index.d.ts +283 -22
  121. package/dist/index.js +2233 -2031
  122. package/dist/index.js.map +1 -1
  123. package/package.json +1 -1
  124. package/dist/chunks/_page-e_I-fdSR.js.map +0 -1
  125. package/dist/chunks/collections-zzZ_HQxB.js +0 -192
  126. package/dist/chunks/collections-zzZ_HQxB.js.map +0 -1
  127. package/dist/chunks/constants-Rq8SCXwH.js.map +0 -1
  128. package/dist/chunks/dispatch-D4TN9pdW.js +0 -6
  129. package/dist/chunks/dispatch-D4TN9pdW.js.map +0 -1
  130. package/dist/chunks/env-vars-CcE6ODqC.js.map +0 -1
  131. package/dist/chunks/env-vars-De0Xs0L2.js +0 -20
  132. package/dist/chunks/env-vars-De0Xs0L2.js.map +0 -1
  133. package/dist/chunks/generate.runtime-BK3mR0Rj.js.map +0 -1
  134. package/dist/chunks/generate.runtime-CbE9RHcf.js.map +0 -1
  135. package/dist/chunks/generate.runtime-DJ9MVVPC.js.map +0 -1
  136. package/dist/chunks/generate.runtime-EQnytCFL.js +0 -122
  137. package/dist/chunks/generate.runtime-EQnytCFL.js.map +0 -1
  138. package/dist/chunks/modify-file-DK-tCH9k.js +0 -46
  139. package/dist/chunks/modify-file-DK-tCH9k.js.map +0 -1
  140. package/dist/chunks/providers-BHR6-XZ7.js +0 -76
  141. package/dist/chunks/providers-BHR6-XZ7.js.map +0 -1
  142. package/dist/chunks/site-lj0CDdQ1.js +0 -55
  143. package/dist/chunks/site-lj0CDdQ1.js.map +0 -1
  144. package/dist/chunks/svelte-file-B3RfgVdt.js.map +0 -1
  145. package/dist/chunks/write-result-DiZsCS_y.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"generate.runtime-CEqLgLT9.js","names":["FAILURE_HINT","NOT_FOUND_HINT","dedent","getLogger","withInMemoryScript","ensurePropsBinding","formatLikeSource","ensureImports","SvelteFile","withPocketbase","migrationDelay","getMigrationFile","ensureSiteFile","fs","path","modifyLayoutServer","layoutPath","snippet","originalSource","sourceFile","Project","addUserProp","obj","loadArrow","loadFn","varDecl","SyntaxKind","directArrow","init","innerArrow","innerFnExpr","maybeFn","fnLike","params","first","original","nameNode","obp","el","parts","tail","currentName","body","expr","ret","inner","bodyExpr","AUTH_MENU_NAVBAR_ITEM","IMPORT_SNIPPET","FAILURE_HINT$1","NOT_FOUND_HINT$1","modifyRootLayoutSvelte","file","out","source","sf","FAILURE_HINT","NOT_FOUND_HINT","modifyHooksServer","hooksServerPath","callExpr","ce","args","firstArg","optionsObj","authProp","authInit","authObj","prProp","prInit","arr","COOKIE_LOGIN","modifyTestSetup","setupPath","helper","generate","options","logger","creates","pb","input","userCollection","verificationTemplate","resetPasswordTemplate","confirmEmailChangeTemplate","migrationFile","modifies","pushResult","layoutServerFile","modifyOutcomeToFile","layoutCandidates","layoutFile","p","hooksServerFile","testSetupFile","remote","modifySvelteConfigRemote","siteFile"],"sources":["../../src/patterns/enable/auth-remote/modifies/+layout.server.ts","../../src/patterns/enable/auth-remote/modifies/root-layout.svelte.ts","../../src/patterns/enable/auth-remote/modifies/hooks.server.ts","../../src/patterns/enable/auth-remote/modifies/test-setup.ts","../../src/patterns/enable/auth-remote/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { Project, SyntaxKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport { formatLikeSource } from \"../../../../runtime/ts-morph-helpers\";\n\nexport function modifyLayoutServer(layoutPath: string): ModifyOutcome {\n if (!fs.existsSync(layoutPath)) {\n const snippet = dedent`\n\t\t\texport const load = async ({ locals }) => {\n\t\t\t\treturn { user: locals.pb.authStore.record };\n\t\t\t};\n\t\t`;\n\n fs.writeFileSync(layoutPath, snippet);\n return { status: \"success\", changed: true };\n }\n\n const originalSource = fs.readFileSync(layoutPath, \"utf8\");\n const project = new Project();\n const sourceFile = project.addSourceFileAtPath(layoutPath);\n\n // helper to add user property to an object literal if missing\n const addUserProp = (obj: import(\"ts-morph\").ObjectLiteralExpression) => {\n const hasUser = !!obj.getProperty(\"user\");\n if (!hasUser) {\n obj.addPropertyAssignment({\n name: \"user\",\n initializer: \"locals.pb.authStore.record\",\n });\n }\n };\n\n // find existing exported load (function or const with arrow)\n let loadArrow: import(\"ts-morph\").ArrowFunction | undefined;\n let loadFn:\n | import(\"ts-morph\").FunctionDeclaration\n | import(\"ts-morph\").FunctionExpression\n | undefined;\n\n const varDecl = sourceFile.getVariableDeclaration(\"load\");\n if (varDecl) {\n const vs = varDecl.getFirstAncestorByKind(SyntaxKind.VariableStatement);\n const isExported = !!vs?.hasExportKeyword();\n if (isExported) {\n const directArrow = varDecl.getInitializerIfKind(\n SyntaxKind.ArrowFunction,\n );\n if (directArrow) {\n loadArrow = directArrow;\n } else {\n const init = varDecl.getInitializer();\n if (init) {\n const innerArrow = init.getFirstDescendantByKind(\n SyntaxKind.ArrowFunction,\n );\n if (innerArrow) {\n loadArrow = innerArrow;\n } else {\n const innerFnExpr = init.getFirstDescendantByKind(\n SyntaxKind.FunctionExpression,\n );\n if (innerFnExpr) {\n loadFn = innerFnExpr;\n }\n }\n }\n }\n }\n }\n\n if (!loadArrow) {\n const maybeFn = sourceFile.getFunction(\"load\");\n if (maybeFn && maybeFn.isExported()) {\n loadFn = maybeFn;\n }\n }\n\n // if no load found, create one\n if (!loadArrow && !loadFn) {\n sourceFile.addFunction({\n isExported: true,\n isAsync: true,\n name: \"load\",\n parameters: [{ name: \"{ locals }\" }],\n statements: `return { user: locals.pb.authStore.record };`,\n });\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n }\n\n // normalize function-like to a single handle\n const fnLike:\n | import(\"ts-morph\").ArrowFunction\n | import(\"ts-morph\").FunctionDeclaration\n | import(\"ts-morph\").FunctionExpression = (loadArrow ?? loadFn!) as any;\n\n // ensure first parameter destructures locals, preserving existing information\n const params = fnLike.getParameters();\n if (params.length === 0) {\n fnLike.insertParameter(0, { name: \"{ locals }\" });\n } else {\n const first = params[0];\n const original = first.getStructure();\n const nameNode = first.getNameNode();\n if (nameNode.getKind() === SyntaxKind.ObjectBindingPattern) {\n const obp = nameNode as import(\"ts-morph\").ObjectBindingPattern;\n const hasLocals = obp\n .getElements()\n .some((el) => el.getName() === \"locals\");\n if (!hasLocals) {\n const parts = obp\n .getElements()\n .map((el) => el.getText())\n .filter(Boolean);\n const tail = parts.length > 0 ? \", \" + parts.join(\", \") : \"\";\n first.set({\n name: `{ locals${tail} }`,\n type: original.type,\n initializer: (original as any).initializer,\n });\n }\n } else {\n const currentName = first.getName();\n if (currentName !== \"locals\") {\n first.set({\n name: `{ locals, ...${currentName} }`,\n type: original.type,\n initializer: (original as any).initializer,\n });\n }\n }\n }\n\n // add user to returned object literals without altering other properties\n if (loadArrow) {\n const body = loadArrow.getBody();\n if (body.getKind() === SyntaxKind.Block) {\n const returns = body.getDescendantsOfKind(SyntaxKind.ReturnStatement);\n returns.forEach((ret) => {\n const expr = ret.getExpression();\n if (!expr) return;\n if (expr.getKind() === SyntaxKind.ObjectLiteralExpression) {\n addUserProp(expr as import(\"ts-morph\").ObjectLiteralExpression);\n } else if (expr.getKind() === SyntaxKind.ParenthesizedExpression) {\n const inner = (\n expr as import(\"ts-morph\").ParenthesizedExpression\n ).getExpression();\n if (inner.getKind() === SyntaxKind.ObjectLiteralExpression) {\n addUserProp(inner as import(\"ts-morph\").ObjectLiteralExpression);\n }\n }\n });\n } else {\n // concise body\n const bodyExpr = body as import(\"ts-morph\").Expression;\n if (bodyExpr.getKind() === SyntaxKind.ParenthesizedExpression) {\n const inner = (\n bodyExpr as import(\"ts-morph\").ParenthesizedExpression\n ).getExpression();\n if (inner.getKind() === SyntaxKind.ObjectLiteralExpression) {\n addUserProp(inner as import(\"ts-morph\").ObjectLiteralExpression);\n }\n } else if (bodyExpr.getKind() === SyntaxKind.ObjectLiteralExpression) {\n addUserProp(bodyExpr as import(\"ts-morph\").ObjectLiteralExpression);\n }\n }\n } else if (loadFn) {\n const body = loadFn.getBody();\n if (body) {\n const returns = body.getDescendantsOfKind(SyntaxKind.ReturnStatement);\n returns.forEach((ret) => {\n const expr = ret.getExpression();\n if (!expr) return;\n if (expr.getKind() === SyntaxKind.ObjectLiteralExpression) {\n addUserProp(expr as import(\"ts-morph\").ObjectLiteralExpression);\n } else if (expr.getKind() === SyntaxKind.ParenthesizedExpression) {\n const inner = (\n expr as import(\"ts-morph\").ParenthesizedExpression\n ).getExpression();\n if (inner.getKind() === SyntaxKind.ObjectLiteralExpression) {\n addUserProp(inner as import(\"ts-morph\").ObjectLiteralExpression);\n }\n }\n });\n }\n }\n\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return {\n status: \"success\",\n changed: sourceFile.getFullText() !== originalSource,\n };\n}\n","import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport {\n ensureImports,\n ensurePropsBinding,\n withInMemoryScript,\n} from \"../../../../runtime/ts-morph-helpers\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst AUTH_MENU_NAVBAR_ITEM = `\n\t\t<Navbar.Item\n\t\t\tclass=\"flex flex-col md:flex-row items-center space-y-2 md:space-y-0 md:space-x-4\"\n\t\t>\n\t\t\t<AuthMenu.Root>\n\t\t\t\t{#snippet user()}\n\t\t\t\t\t<AuthMenu.Trigger>\n\t\t\t\t\t\t<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 { Project } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst COOKIE_LOGIN = dedent`\n // Login is a remote function, so there is no form action to post to: carry\n // the session the way the browser does, in the \\`pb_auth\\` cookie.\n async function authenticateUser(agent: Agent, user: { email?: string }) {\n // Logs in with the password, so it needs the email (made optional by\n // enable-whatsapp, for accounts that sign in with a phone number).\n if (!user.email) {\n throw new Error('authenticateUser needs a user with an email');\n }\n const client = new PocketBase(process.env.POCKETBASE_URL!);\n await client.collection(\"users\").authWithPassword(user.email, testUserPassword);\n agent.set(\"Cookie\", client.authStore.exportToCookie().split(\";\")[0]);\n }\n`;\n\n/**\n * The template's server-test helper logs in by posting the `/login` form\n * action, which this pattern replaces with a remote function. A project\n * without the helper (or with its own) has nothing to fix.\n */\nexport function modifyTestSetup(setupPath: string): ModifyOutcome {\n if (!fs.existsSync(setupPath)) {\n return { status: \"success\", changed: false };\n }\n\n const project = new Project();\n const sourceFile = project.addSourceFileAtPath(setupPath);\n const helper = sourceFile.getFunction(\"authenticateUser\");\n\n if (!helper || !/\\.post\\(\\s*[\"'`]\\/login[\"'`]\\s*\\)/.test(helper.getText())) {\n return { status: \"success\", changed: false };\n }\n\n helper.replaceWithText(COOKIE_LOGIN);\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n}\n","import path from \"node:path\";\nimport fs from \"node:fs\";\nimport { Options, Result, File } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport {\n getMigrationFile,\n migrationDelay,\n withPocketbase,\n} from \"../../../runtime/pocketbase\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { ensureSiteFile } from \"../../../runtime/site\";\nimport { modifySvelteConfigRemote } from \"../../../runtime/modify-svelte-config-remote\";\n\nimport { modifyLayoutServer } from \"./modifies/+layout.server\";\nimport { modifyRootLayoutSvelte } from \"./modifies/root-layout.svelte\";\nimport { modifyHooksServer } from \"./modifies/hooks.server\";\nimport { modifyTestSetup } from \"./modifies/test-setup\";\n\nexport async function generate(options: Options) {\n const { input } = options;\n const logger = getLogger(options);\n\n let creates: File[] = [];\n\n // Update PocketBase\n await withPocketbase(options.root, async (pb) => {\n logger.info(\"Updating PocketBase mail settings\");\n await pb.settings.update({\n meta: {\n senderName: input.senderName,\n senderAddress: input.senderAddress,\n },\n });\n await migrationDelay();\n\n const userCollection = await pb.collections.getOne(\"users\");\n\n if (!userCollection) {\n throw new Error(\"Users collection not found\");\n }\n\n const verificationTemplate =\n userCollection.verificationTemplate.body.replace(\n \"{APP_URL}/_/#/auth/confirm-verification/{TOKEN}\",\n \"{APP_URL}/confirm-verification/{TOKEN}\",\n );\n const resetPasswordTemplate =\n userCollection.resetPasswordTemplate.body.replace(\n \"{APP_URL}/_/#/auth/confirm-reset/{TOKEN}\",\n \"{APP_URL}/confirm-reset/{TOKEN}\",\n );\n const confirmEmailChangeTemplate =\n userCollection.confirmEmailChangeTemplate.body.replace(\n \"{APP_URL}/_/#/auth/confirm-email-change/{TOKEN}\",\n \"{APP_URL}/confirm-email-change/{TOKEN}\",\n );\n\n logger.info(\"Locking down users collection rules and email templates\");\n // Update user auth rules to lock down access to the user's own account\n await pb.collections.update(\"users\", {\n listRule: \"@request.auth.id = id\",\n viewRule: \"@request.auth.id = id\",\n createRule: \"@request.auth.id = id\",\n updateRule: \"@request.auth.id = id\",\n deleteRule: \"@request.auth.id = id\",\n\n // Update email templates to VelaStack auth urls\n verificationTemplate: {\n body: verificationTemplate,\n },\n resetPasswordTemplate: {\n body: resetPasswordTemplate,\n },\n confirmEmailChangeTemplate: {\n body: confirmEmailChangeTemplate,\n },\n });\n await migrationDelay();\n\n const migrationFile = getMigrationFile(\"users\", \"updated\", options);\n if (migrationFile) {\n creates.push({\n path: migrationFile,\n language: \"ts\",\n content: fs.readFileSync(migrationFile, \"utf8\"),\n status: \"success\",\n });\n }\n });\n\n // Modify files\n const modifies: File[] = [];\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n logger.info(\"Modifying +layout.server.ts\");\n const layoutServerFile = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"+layout.server.ts\",\n );\n pushResult(\n modifyOutcomeToFile(layoutServerFile, modifyLayoutServer(layoutServerFile)),\n );\n\n logger.info(\"Modifying root layout\");\n // TODO: make this more robust by searching for Navbar.Root > Navbar.List\n // src/routes/(public)/root-layout.svelte is what vela creates by default\n const layoutCandidates = [\n path.join(options.root, \"src\", \"routes\", \"(public)\", \"root-layout.svelte\"),\n path.join(options.root, \"src\", \"routes\", \"root-layout.svelte\"),\n path.join(options.root, \"src\", \"routes\", \"(public)\", \"+layout.svelte\"),\n path.join(options.root, \"src\", \"routes\", \"+layout.svelte\"),\n ];\n const layoutFile =\n layoutCandidates.find((p) => fs.existsSync(p)) ?? layoutCandidates[0];\n pushResult(\n modifyOutcomeToFile(layoutFile, modifyRootLayoutSvelte(layoutFile)),\n );\n\n logger.info(\"Modifying hooks.server.ts\");\n const hooksServerFile = path.join(options.root, \"src\", \"hooks.server.ts\");\n pushResult(\n modifyOutcomeToFile(hooksServerFile, modifyHooksServer(hooksServerFile)),\n );\n\n logger.info(\"Modifying test/setup.ts\");\n const testSetupFile = path.join(options.root, \"test\", \"setup.ts\");\n pushResult(\n modifyOutcomeToFile(testSetupFile, modifyTestSetup(testSetupFile)),\n );\n\n logger.info(\"Modifying config for remote functions\");\n const remote = modifySvelteConfigRemote(options.root);\n pushResult(modifyOutcomeToFile(remote.filePath, remote.outcome));\n\n // The auth pages and the app sidebar show `site.name`.\n const siteFile = await ensureSiteFile(options);\n\n return {\n creates: siteFile ? [siteFile] : [],\n modifies,\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n } satisfies Result;\n}\n"],"mappings":";;;;;;;;;;;;AAMA,SAAgBe,EAAmB,GAAmC;CACpE,IAAI,CAACF,EAAG,WAAWG,CAAU,GAAG;EAC9B,IAAMC,IAAU,CAAM;;;;;EAOtB,OADAJ,EAAG,cAAcG,GAAYC,CAAO,GAC7B;GAAE,QAAQ;GAAW,SAAS;EAAK;CAC5C;CAEA,IAAMC,IAAiBL,EAAG,aAAaG,GAAY,MAAM,GAEnDG,IAAa,IADCC,EACD,CAAA,CAAQ,oBAAoBJ,CAAU,GAGnDK,KAAe,MAAoD;EAEvE,AADkBC,EAAI,YAAY,MAAM,KAEtCA,EAAI,sBAAsB;GACxB,MAAM;GACN,aAAa;EACf,CAAC;CAEL,GAGIC,GACAC,GAKEC,IAAUN,EAAW,uBAAuB,MAAM;CACxD,IAAIM,KACSA,EAAQ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EAAQ,MAAM,OAAO,UAAU,gBAAgB;CAC3D,GACMe,IACJD,EAAiB,MAAM,MAAM7E,EAAG,WAAW+E,CAAC,CAAC,KAAKF,EAAiB;CAKrE,AAJAH,EACEE,EAAoBE,GAAYxC,EAAuBwC,CAAU,CAAC,CACpE,GAEAd,EAAO,KAAK,2BAA2B;CACvC,IAAMgB,IAAkB/E,EAAK,KAAK8D,EAAQ,MAAM,OAAO,iBAAiB;CAKxE,AAJAW,EACEE,EAAoBI,GAAiBnC,EAAkBmC,CAAe,CAAC,CACzE,GAEAhB,EAAO,KAAK,yBAAyB;CACrC,IAAMiB,IAAgBhF,EAAK,KAAK8D,EAAQ,MAAM,QAAQ,UAAU;CAKhE,AAJAW,EACEE,EAAoBK,GAAetB,EAAgBsB,CAAa,CAAC,CACnE,GAEAjB,EAAO,KAAK,uCAAuC;CACnD,IAAMkB,IAASC,EAAyBpB,EAAQ,IAAI;CACpD,EAAWa,EAAoBM,EAAO,UAAUA,EAAO,OAAO,CAAC;CAG/D,IAAME,IAAW,MAAMrF,EAAegE,CAAO;CAE7C,OAAO;EACL,SAASqB,IAAW,CAACA,CAAQ,IAAI,CAAC;EAClC;EACA,SAAS,CAAC;EACV,YAAY,CAAC;EACb,UAAU,CAAC;EACX,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAiB,CAAC;CACpB;AACF"}
1
+ {"version":3,"file":"generate.runtime-DYdkrHJ1.js","names":["FAILURE_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$1","modifyRootLayoutSvelte","file","out","source","sf","FAILURE_HINT","NOT_FOUND_HINT","modifyHooksServer","hooksServerPath","callExpr","ce","args","firstArg","optionsObj","authProp","authInit","authObj","prProp","prInit","arr","COOKIE_LOGIN","modifyTestSetup","setupPath","helper","generate","options","logger","creates","pb","input","userCollection","verificationTemplate","resetPasswordTemplate","confirmEmailChangeTemplate","migrationFile","modifies","pushResult","layoutServerFile","layoutCandidates","layoutFile","p","hooksServerFile","testSetupFile","remote","modifySvelteConfigRemote","siteFile"],"sources":["../../src/patterns/enable/auth-remote/modifies/+layout.server.ts","../../src/patterns/enable/auth-remote/modifies/root-layout.svelte.ts","../../src/patterns/enable/auth-remote/modifies/hooks.server.ts","../../src/patterns/enable/auth-remote/modifies/test-setup.ts","../../src/patterns/enable/auth-remote/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { Project, SyntaxKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport { formatLikeSource } from \"../../../../runtime/ts-morph-helpers\";\n\nexport function modifyLayoutServer(layoutPath: string): ModifyOutcome {\n if (!fs.existsSync(layoutPath)) {\n const snippet = dedent`\n\t\t\texport const load = async ({ locals }) => {\n\t\t\t\treturn { user: locals.pb.authStore.record };\n\t\t\t};\n\t\t`;\n\n fs.writeFileSync(layoutPath, snippet);\n return { status: \"success\", changed: true };\n }\n\n const originalSource = fs.readFileSync(layoutPath, \"utf8\");\n const project = new Project();\n const sourceFile = project.addSourceFileAtPath(layoutPath);\n\n // helper to add user property to an object literal if missing\n const addUserProp = (obj: import(\"ts-morph\").ObjectLiteralExpression) => {\n const hasUser = !!obj.getProperty(\"user\");\n if (!hasUser) {\n obj.addPropertyAssignment({\n name: \"user\",\n initializer: \"locals.pb.authStore.record\",\n });\n }\n };\n\n // find existing exported load (function or const with arrow)\n let loadArrow: import(\"ts-morph\").ArrowFunction | undefined;\n let loadFn:\n | import(\"ts-morph\").FunctionDeclaration\n | import(\"ts-morph\").FunctionExpression\n | undefined;\n\n const varDecl = sourceFile.getVariableDeclaration(\"load\");\n if (varDecl) {\n const vs = varDecl.getFirstAncestorByKind(SyntaxKind.VariableStatement);\n const isExported = !!vs?.hasExportKeyword();\n if (isExported) {\n const directArrow = varDecl.getInitializerIfKind(\n SyntaxKind.ArrowFunction,\n );\n if (directArrow) {\n loadArrow = directArrow;\n } else {\n const init = varDecl.getInitializer();\n if (init) {\n const innerArrow = init.getFirstDescendantByKind(\n SyntaxKind.ArrowFunction,\n );\n if (innerArrow) {\n loadArrow = innerArrow;\n } else {\n const innerFnExpr = init.getFirstDescendantByKind(\n SyntaxKind.FunctionExpression,\n );\n if (innerFnExpr) {\n loadFn = innerFnExpr;\n }\n }\n }\n }\n }\n }\n\n if (!loadArrow) {\n const maybeFn = sourceFile.getFunction(\"load\");\n if (maybeFn && maybeFn.isExported()) {\n loadFn = maybeFn;\n }\n }\n\n // if no load found, create one\n if (!loadArrow && !loadFn) {\n sourceFile.addFunction({\n isExported: true,\n isAsync: true,\n name: \"load\",\n parameters: [{ name: \"{ locals }\" }],\n statements: `return { user: locals.pb.authStore.record };`,\n });\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n }\n\n // normalize function-like to a single handle\n const fnLike:\n | import(\"ts-morph\").ArrowFunction\n | import(\"ts-morph\").FunctionDeclaration\n | import(\"ts-morph\").FunctionExpression = (loadArrow ?? loadFn!) as any;\n\n // ensure first parameter destructures locals, preserving existing information\n const params = fnLike.getParameters();\n if (params.length === 0) {\n fnLike.insertParameter(0, { name: \"{ locals }\" });\n } else {\n const first = params[0];\n const original = first.getStructure();\n const nameNode = first.getNameNode();\n if (nameNode.getKind() === SyntaxKind.ObjectBindingPattern) {\n const obp = nameNode as import(\"ts-morph\").ObjectBindingPattern;\n const hasLocals = obp\n .getElements()\n .some((el) => el.getName() === \"locals\");\n if (!hasLocals) {\n const parts = obp\n .getElements()\n .map((el) => el.getText())\n .filter(Boolean);\n const tail = parts.length > 0 ? \", \" + parts.join(\", \") : \"\";\n first.set({\n name: `{ locals${tail} }`,\n type: original.type,\n initializer: (original as any).initializer,\n });\n }\n } else {\n const currentName = first.getName();\n if (currentName !== \"locals\") {\n first.set({\n name: `{ locals, ...${currentName} }`,\n type: original.type,\n initializer: (original as any).initializer,\n });\n }\n }\n }\n\n // add user to returned object literals without altering other properties\n if (loadArrow) {\n const body = loadArrow.getBody();\n if (body.getKind() === SyntaxKind.Block) {\n const returns = body.getDescendantsOfKind(SyntaxKind.ReturnStatement);\n returns.forEach((ret) => {\n const expr = ret.getExpression();\n if (!expr) return;\n if (expr.getKind() === SyntaxKind.ObjectLiteralExpression) {\n addUserProp(expr as import(\"ts-morph\").ObjectLiteralExpression);\n } else if (expr.getKind() === SyntaxKind.ParenthesizedExpression) {\n const inner = (\n expr as import(\"ts-morph\").ParenthesizedExpression\n ).getExpression();\n if (inner.getKind() === SyntaxKind.ObjectLiteralExpression) {\n addUserProp(inner as import(\"ts-morph\").ObjectLiteralExpression);\n }\n }\n });\n } else {\n // concise body\n const bodyExpr = body as import(\"ts-morph\").Expression;\n if (bodyExpr.getKind() === SyntaxKind.ParenthesizedExpression) {\n const inner = (\n bodyExpr as import(\"ts-morph\").ParenthesizedExpression\n ).getExpression();\n if (inner.getKind() === SyntaxKind.ObjectLiteralExpression) {\n addUserProp(inner as import(\"ts-morph\").ObjectLiteralExpression);\n }\n } else if (bodyExpr.getKind() === SyntaxKind.ObjectLiteralExpression) {\n addUserProp(bodyExpr as import(\"ts-morph\").ObjectLiteralExpression);\n }\n }\n } else if (loadFn) {\n const body = loadFn.getBody();\n if (body) {\n const returns = body.getDescendantsOfKind(SyntaxKind.ReturnStatement);\n returns.forEach((ret) => {\n const expr = ret.getExpression();\n if (!expr) return;\n if (expr.getKind() === SyntaxKind.ObjectLiteralExpression) {\n addUserProp(expr as import(\"ts-morph\").ObjectLiteralExpression);\n } else if (expr.getKind() === SyntaxKind.ParenthesizedExpression) {\n const inner = (\n expr as import(\"ts-morph\").ParenthesizedExpression\n ).getExpression();\n if (inner.getKind() === SyntaxKind.ObjectLiteralExpression) {\n addUserProp(inner as import(\"ts-morph\").ObjectLiteralExpression);\n }\n }\n });\n }\n }\n\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return {\n status: \"success\",\n changed: sourceFile.getFullText() !== originalSource,\n };\n}\n","import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport {\n ensureImports,\n ensurePropsBinding,\n withInMemoryScript,\n} from \"../../../../runtime/ts-morph-helpers\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst AUTH_MENU_NAVBAR_ITEM = `\n\t\t<Navbar.Item\n\t\t\tclass=\"flex flex-col md:flex-row items-center space-y-2 md:space-y-0 md:space-x-4\"\n\t\t>\n\t\t\t<AuthMenu.Root>\n\t\t\t\t{#snippet user()}\n\t\t\t\t\t<AuthMenu.Trigger>\n\t\t\t\t\t\t<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 { Project } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst COOKIE_LOGIN = dedent`\n // Login is a remote function, so there is no form action to post to: carry\n // the session the way the browser does, in the \\`pb_auth\\` cookie.\n async function authenticateUser(agent: Agent, user: { email?: string }) {\n // Logs in with the password, so it needs the email (made optional by\n // enable-whatsapp, for accounts that sign in with a phone number).\n if (!user.email) {\n throw new Error('authenticateUser needs a user with an email');\n }\n const client = new PocketBase(process.env.POCKETBASE_URL!);\n await client.collection(\"users\").authWithPassword(user.email, testUserPassword);\n agent.set(\"Cookie\", client.authStore.exportToCookie().split(\";\")[0]);\n }\n`;\n\n/**\n * The template's server-test helper logs in by posting the `/login` form\n * action, which this pattern replaces with a remote function. A project\n * without the helper (or with its own) has nothing to fix.\n */\nexport function modifyTestSetup(setupPath: string): ModifyOutcome {\n if (!fs.existsSync(setupPath)) {\n return { status: \"success\", changed: false };\n }\n\n const project = new Project();\n const sourceFile = project.addSourceFileAtPath(setupPath);\n const helper = sourceFile.getFunction(\"authenticateUser\");\n\n if (!helper || !/\\.post\\(\\s*[\"'`]\\/login[\"'`]\\s*\\)/.test(helper.getText())) {\n return { status: \"success\", changed: false };\n }\n\n helper.replaceWithText(COOKIE_LOGIN);\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n}\n","import path from \"node:path\";\nimport fs from \"node:fs\";\nimport { Options, Result, File } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport {\n getMigrationFile,\n migrationDelay,\n withPocketbase,\n} from \"../../../runtime/pocketbase\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { ensureSiteFile } from \"../../../runtime/site\";\nimport { modifySvelteConfigRemote } from \"../../../runtime/modify-svelte-config-remote\";\n\nimport { modifyLayoutServer } from \"./modifies/+layout.server\";\nimport { modifyRootLayoutSvelte } from \"./modifies/root-layout.svelte\";\nimport { modifyHooksServer } from \"./modifies/hooks.server\";\nimport { modifyTestSetup } from \"./modifies/test-setup\";\n\nexport async function generate(options: Options) {\n const { input } = options;\n const logger = getLogger(options);\n\n let creates: File[] = [];\n\n // Update PocketBase\n await withPocketbase(options.root, async (pb) => {\n logger.info(\"Updating PocketBase mail settings\");\n await pb.settings.update({\n meta: {\n senderName: input.senderName,\n senderAddress: input.senderAddress,\n },\n });\n await migrationDelay();\n\n const userCollection = await pb.collections.getOne(\"users\");\n\n if (!userCollection) {\n throw new Error(\"Users collection not found\");\n }\n\n const verificationTemplate =\n userCollection.verificationTemplate.body.replace(\n \"{APP_URL}/_/#/auth/confirm-verification/{TOKEN}\",\n \"{APP_URL}/confirm-verification/{TOKEN}\",\n );\n const resetPasswordTemplate =\n userCollection.resetPasswordTemplate.body.replace(\n \"{APP_URL}/_/#/auth/confirm-reset/{TOKEN}\",\n \"{APP_URL}/confirm-reset/{TOKEN}\",\n );\n const confirmEmailChangeTemplate =\n userCollection.confirmEmailChangeTemplate.body.replace(\n \"{APP_URL}/_/#/auth/confirm-email-change/{TOKEN}\",\n \"{APP_URL}/confirm-email-change/{TOKEN}\",\n );\n\n logger.info(\"Locking down users collection rules and email templates\");\n // Update user auth rules to lock down access to the user's own account\n await pb.collections.update(\"users\", {\n listRule: \"@request.auth.id = id\",\n viewRule: \"@request.auth.id = id\",\n createRule: \"@request.auth.id = id\",\n updateRule: \"@request.auth.id = id\",\n deleteRule: \"@request.auth.id = id\",\n\n // Update email templates to VelaStack auth urls\n verificationTemplate: {\n body: verificationTemplate,\n },\n resetPasswordTemplate: {\n body: resetPasswordTemplate,\n },\n confirmEmailChangeTemplate: {\n body: confirmEmailChangeTemplate,\n },\n });\n await migrationDelay();\n\n const migrationFile = getMigrationFile(\"users\", \"updated\", options);\n if (migrationFile) {\n creates.push({\n path: migrationFile,\n language: \"ts\",\n content: fs.readFileSync(migrationFile, \"utf8\"),\n status: \"success\",\n });\n }\n });\n\n // Modify files\n const modifies: File[] = [];\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n logger.info(\"Modifying +layout.server.ts\");\n const layoutServerFile = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"+layout.server.ts\",\n );\n pushResult(\n modifyOutcomeToFile(layoutServerFile, modifyLayoutServer(layoutServerFile)),\n );\n\n logger.info(\"Modifying root layout\");\n // TODO: make this more robust by searching for Navbar.Root > Navbar.List\n // src/routes/(public)/root-layout.svelte is what vela creates by default\n const layoutCandidates = [\n path.join(options.root, \"src\", \"routes\", \"(public)\", \"root-layout.svelte\"),\n path.join(options.root, \"src\", \"routes\", \"root-layout.svelte\"),\n path.join(options.root, \"src\", \"routes\", \"(public)\", \"+layout.svelte\"),\n path.join(options.root, \"src\", \"routes\", \"+layout.svelte\"),\n ];\n const layoutFile =\n layoutCandidates.find((p) => fs.existsSync(p)) ?? layoutCandidates[0];\n pushResult(\n modifyOutcomeToFile(layoutFile, modifyRootLayoutSvelte(layoutFile)),\n );\n\n logger.info(\"Modifying hooks.server.ts\");\n const hooksServerFile = path.join(options.root, \"src\", \"hooks.server.ts\");\n pushResult(\n modifyOutcomeToFile(hooksServerFile, modifyHooksServer(hooksServerFile)),\n );\n\n logger.info(\"Modifying test/setup.ts\");\n const testSetupFile = path.join(options.root, \"test\", \"setup.ts\");\n pushResult(\n modifyOutcomeToFile(testSetupFile, modifyTestSetup(testSetupFile)),\n );\n\n logger.info(\"Modifying config for remote functions\");\n const remote = modifySvelteConfigRemote(options.root);\n pushResult(modifyOutcomeToFile(remote.filePath, remote.outcome));\n\n // The auth pages and the app sidebar show `site.name`.\n const siteFile = await ensureSiteFile(options);\n\n return {\n creates: siteFile ? [siteFile] : [],\n modifies,\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n } satisfies Result;\n}\n"],"mappings":";;;;;;;;;;;;AAMA,SAAgBgB,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,CAAQ,oBAAoBJ,CAAU,GAGnDK,KA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AQ,MAAM,OAAO,UAAU,YAAY,oBAAoB;EACzE9D,EAAK,KAAK8D,EAAQ,MAAM,OAAO,UAAU,oBAAoB;EAC7D9D,EAAK,KAAK8D,EAAQ,MAAM,OAAO,UAAU,YAAY,gBAAgB;EACrE9D,EAAK,KAAK8D,EAAQ,MAAM,OAAO,UAAU,gBAAgB;CAC3D,GACMc,IACJD,EAAiB,MAAM,MAAM5E,EAAG,WAAW8E,CAAC,CAAC,KAAKF,EAAiB;CAKrE,AAJAF,EACE5E,EAAoB+E,GAAYvC,EAAuBuC,CAAU,CAAC,CACpE,GAEAb,EAAO,KAAK,2BAA2B;CACvC,IAAMe,IAAkB9E,EAAK,KAAK8D,EAAQ,MAAM,OAAO,iBAAiB;CAKxE,AAJAW,EACE5E,EAAoBiF,GAAiBlC,EAAkBkC,CAAe,CAAC,CACzE,GAEAf,EAAO,KAAK,yBAAyB;CACrC,IAAMgB,IAAgB/E,EAAK,KAAK8D,EAAQ,MAAM,QAAQ,UAAU;CAKhE,AAJAW,EACE5E,EAAoBkF,GAAerB,EAAgBqB,CAAa,CAAC,CACnE,GAEAhB,EAAO,KAAK,uCAAuC;CACnD,IAAMiB,IAASC,EAAyBnB,EAAQ,IAAI;CACpD,EAAWjE,EAAoBmF,EAAO,UAAUA,EAAO,OAAO,CAAC;CAG/D,IAAME,IAAW,MAAM1F,EAAesE,CAAO;CAE7C,OAAO;EACL,SAASoB,IAAW,CAACA,CAAQ,IAAI,CAAC;EAClC;EACA,SAAS,CAAC;EACV,YAAY,CAAC;EACb,UAAU,CAAC;EACX,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAiB,CAAC;CACpB;AACF"}
@@ -2,8 +2,8 @@ import { t as e } from "./dedent-Gq6Krl4n.js";
2
2
  import { t } from "./ui-DD4NltyN.js";
3
3
  import { n } from "./logger-CQONztPm.js";
4
4
  import { _ as r, i, o as a, r as o } from "./ts-morph-helpers-Bepc-Es2.js";
5
- import { modifyOutcomeToFile as s } from "./modify-file-DK-tCH9k.js";
6
- import { t as c } from "./svelte-file-B3RfgVdt.js";
5
+ import { r as s } from "./modify-file-289rStJ2.js";
6
+ import { t as c } from "./svelte-file-Dv5-bl79.js";
7
7
  import { t as l } from "./compose-handle-BDlZ7Pif.js";
8
8
  import { a as u, t as d } from "./config-target-rHgjaA8u.js";
9
9
  import { i as f, n as p } from "./_layout-D-FzWqn0.js";
@@ -468,4 +468,4 @@ async function ne(e) {
468
468
  //#endregion
469
469
  export { ne as generate };
470
470
 
471
- //# sourceMappingURL=generate.runtime-DHHlYfTD.js.map
471
+ //# sourceMappingURL=generate.runtime-DdcVnK8J.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"generate.runtime-DHHlYfTD.js","names":["FAILURE_HINT","NOT_FOUND_HINT","FAILURE_HINT","FAILURE_HINT","FAILURE_HINT","NOT_FOUND_HINT","NOT_FOUND_HINT","dedent","withInMemoryScript","formatLikeSource","ensureImports","SvelteFile","addHandle","probeFirstExisting","VITE_CONFIG_CANDIDATES","modifyPackageImportsI18n","ensureRootLayoutI18n","fs","path","FAILURE_HINT$4","NOT_FOUND_HINT$3","modifyViteConfig","viteConfigPath","sourceFile","Project","QuoteKind","changed","failed","d","configArg","SyntaxKind","ce","configObj","pluginsProp","pluginsInit","arr","el","I18N_HANDLE","FAILURE_HINT$3","HOOKS_SERVER_SNIPPET","ensureNamespaceImport","moduleSpecifier","ns","modifyHooksServerI18n","hooksServerPath","original","composed","handleStmt","ensureNamedImport","startupSnippet","i18nHandleSnippet","DELOCALIZE_HELPER","HOOKS_SNIPPET","FAILURE_HINT$2","NEGOTIATE_ONLY_REROUTE","hasOtherReroute","n","ensureDeLocalizeImports","modifyHooksI18n","hooksPath","rerouteDecl","init","target","s","FAILURE_HINT$1","NOT_FOUND_HINT$2","modifyAppHtml","appHtmlPath","updated","match","NOT_FOUND_HINT$1","modifyGitignore","gitignorePath","block","LANGUAGE_SELECT_SNIPPET","PLAIN_LANGUAGE_SELECT_SNIPPET","IMPORT_SNIPPET","FAILURE_HINT","NOT_FOUND_HINT","PLAIN_FAILURE_HINT","PLAIN_NOT_FOUND_HINT","addImport","out","source","sf","modifyRootLayoutLanguageSelect","plain","ui","layoutPath","file","PAGE_PATH","CATALOG_PATH","WELCOME_PAGE","PAGE_ENTRIES","PLAIN_SELECT_ENTRY","HEADER","normalize","welcomePageCatalog","root","pagePath","entry","generate","logger","getLogger","options","modifies","pushResult","modifyOutcomeToFile","imports","rootLayoutCandidates","resolveUi","rootLayoutPath","p","catalog"],"sources":["../../src/patterns/enable/i18n/modifies/vite-config.ts","../../src/patterns/enable/i18n/modifies/hooks.server.ts","../../src/patterns/enable/i18n/modifies/hooks.ts","../../src/patterns/enable/i18n/modifies/app-html.ts","../../src/patterns/enable/i18n/modifies/gitignore.ts","../../src/patterns/enable/i18n/modifies/root-layout.svelte.ts","../../src/patterns/enable/i18n/welcome-catalog.ts","../../src/patterns/enable/i18n/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport { Project, QuoteKind, SyntaxKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport { formatLikeSource } from \"../../../../runtime/ts-morph-helpers\";\n\nconst FAILURE_HINT = [\n \"Add the wuchale plugin to your Vite config:\",\n \"\",\n \"import { wuchale } from 'wuchale/vite';\",\n \"\",\n \"export default defineConfig({\",\n \" plugins: [wuchale(), /* ...existing plugins */],\",\n \"});\",\n].join(\"\\n\");\n\nconst NOT_FOUND_HINT = [\n \"Create a Vite config with the wuchale plugin:\",\n \"\",\n \"import { defineConfig } from 'vite';\",\n \"import { wuchale } from 'wuchale/vite';\",\n \"\",\n \"export default defineConfig({\",\n \" plugins: [wuchale()],\",\n \"});\",\n].join(\"\\n\");\n\nexport function modifyViteConfig(viteConfigPath: string): ModifyOutcome {\n if (!fs.existsSync(viteConfigPath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const project = new Project({\n compilerOptions: { allowJs: true },\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n const sourceFile = project.addSourceFileAtPath(viteConfigPath);\n\n let changed = false;\n let failed = false;\n\n const hasImport = sourceFile\n .getImportDeclarations()\n .some((d) => d.getModuleSpecifierValue() === \"wuchale/vite\");\n\n if (!hasImport) {\n sourceFile.insertImportDeclaration(0, {\n namedImports: [\"wuchale\"],\n moduleSpecifier: \"wuchale/vite\",\n });\n changed = true;\n }\n\n const defineConfigCall = sourceFile\n .getDescendantsOfKind(SyntaxKind.CallExpression)\n .find((ce) => ce.getExpression().getText() === \"defineConfig\");\n\n const configArg = defineConfigCall?.getArguments()?.[0];\n const configObj =\n configArg?.getKind() === SyntaxKind.ObjectLiteralExpression\n ? (configArg as import(\"ts-morph\").ObjectLiteralExpression)\n : null;\n\n if (!configObj) {\n failed = true;\n } else {\n const pluginsProp = configObj.getProperty(\"plugins\");\n if (!pluginsProp) {\n configObj.addPropertyAssignment({\n name: \"plugins\",\n initializer: \"[wuchale()]\",\n });\n changed = true;\n } else if (pluginsProp.getKind() !== SyntaxKind.PropertyAssignment) {\n failed = true;\n } else {\n const pluginsInit = (\n pluginsProp as import(\"ts-morph\").PropertyAssignment\n ).getInitializer();\n\n if (!pluginsInit) {\n (pluginsProp as import(\"ts-morph\").PropertyAssignment).setInitializer(\n \"[wuchale()]\",\n );\n changed = true;\n } else if (pluginsInit.getKind() !== SyntaxKind.ArrayLiteralExpression) {\n failed = true;\n } else {\n const arr = pluginsInit as import(\"ts-morph\").ArrayLiteralExpression;\n const hasWuchale = arr\n .getElements()\n .some((el) => el.getText().replace(/\\s/g, \"\") === \"wuchale()\");\n\n if (!hasWuchale) {\n arr.insertElement(0, \"wuchale()\");\n changed = true;\n }\n }\n }\n }\n\n if (changed) {\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n }\n\n if (failed) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n return { status: \"success\", changed };\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport dedent from \"dedent\";\nimport { Project, QuoteKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport { addHandle } from \"../../../../runtime/compose-handle\";\nimport {\n ensureNamedImport,\n formatLikeSource,\n} from \"../../../../runtime/ts-morph-helpers\";\n\nconst I18N_HANDLE = \"handleWuchale\";\n\nconst FAILURE_HINT = dedent`\n Wrap your exported handle with the wuchale i18n handler:\n\n import { sequence } from '@sveltejs/kit/hooks';\n import { runWithLocale, loadLocales } from 'wuchale/load-utils/server';\n import { getLocale } from '#locales/main.url.js';\n import { locales } from '#locales/data.js';\n import * as main from '#locales/main.loader.server.svelte.js';\n import * as js from '#locales/js.loader.server.js';\n\n loadLocales(main.key, main.loadCount, main.loadCatalog, locales);\n loadLocales(js.key, js.loadCount, js.loadCatalog, locales);\n\n const handleWuchale = async ({ event, resolve }: any) => {\n const locale = getLocale(event.url);\n return await runWithLocale(locale, () =>\n resolve(event, {\n transformPageChunk: ({ html }: { html: string }) =>\n html.replace('%sveltekit.lang%', locale),\n }),\n );\n };\n\n export const handle = sequence(handleWuchale, /* your existing handle */);\n`;\n\n/**\n * The whole file, for a project that had no server hooks: a fresh `sv create`\n * app or a static site. `disable-i18n` deletes it again once the i18n handle\n * is all that is left.\n */\nexport const HOOKS_SERVER_SNIPPET = dedent`\n import type { Handle } from '@sveltejs/kit/hooks';\n import { runWithLocale, loadLocales } from 'wuchale/load-utils/server';\n import { getLocale } from '#locales/main.url.js';\n import { locales } from '#locales/data.js';\n import * as main from '#locales/main.loader.server.svelte.js';\n import * as js from '#locales/js.loader.server.js';\n\n loadLocales(main.key, main.loadCount, main.loadCatalog, locales);\n loadLocales(js.key, js.loadCount, js.loadCatalog, locales);\n\n const handleWuchale: Handle = async ({ event, resolve }) => {\n const locale = getLocale(event.url);\n return await runWithLocale(locale, () =>\n resolve(event, {\n transformPageChunk: ({ html }) => html.replace('%sveltekit.lang%', locale)\n })\n );\n };\n\n export const handle = handleWuchale;\n`;\n\nfunction ensureNamespaceImport(\n sourceFile: import(\"ts-morph\").SourceFile,\n moduleSpecifier: string,\n ns: string,\n) {\n const existing = sourceFile\n .getImportDeclarations()\n .find((d) => d.getModuleSpecifierValue() === moduleSpecifier);\n if (existing) return;\n sourceFile.addImportDeclaration({ namespaceImport: ns, moduleSpecifier });\n}\n\nexport function modifyHooksServerI18n(hooksServerPath: string): ModifyOutcome {\n if (!fs.existsSync(hooksServerPath)) {\n // SvelteKit loads the first `hooks.server.*` it finds, and `.js` sorts\n // first, so a new `.ts` beside it would never run.\n if (fs.existsSync(hooksServerPath.replace(/\\.ts$/, \".js\"))) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n fs.mkdirSync(path.dirname(hooksServerPath), { recursive: true });\n fs.writeFileSync(hooksServerPath, HOOKS_SERVER_SNIPPET + \"\\n\");\n return { status: \"success\", changed: true };\n }\n\n const original = fs.readFileSync(hooksServerPath, \"utf8\");\n if (original.includes(\"runWithLocale\") || original.includes(\"loadLocales(\")) {\n return { status: \"success\", changed: false };\n }\n\n const project = new Project({\n compilerOptions: { allowJs: true },\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n const sourceFile = project.addSourceFileAtPath(hooksServerPath);\n\n // Composed first: an unsupported handle leaves the file untouched.\n const composed = addHandle(sourceFile, { expression: I18N_HANDLE });\n if (composed.status === \"unsupported\" || !composed.statement) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n const handleStmt = composed.statement;\n\n ensureNamedImport(sourceFile, \"wuchale/load-utils/server\", \"runWithLocale\");\n ensureNamedImport(sourceFile, \"wuchale/load-utils/server\", \"loadLocales\");\n ensureNamedImport(sourceFile, \"#locales/main.url.js\", \"getLocale\");\n ensureNamedImport(sourceFile, \"#locales/data.js\", \"locales\");\n ensureNamespaceImport(\n sourceFile,\n \"#locales/main.loader.server.svelte.js\",\n \"main\",\n );\n ensureNamespaceImport(sourceFile, \"#locales/js.loader.server.js\", \"js\");\n\n const startupSnippet = dedent`\n loadLocales(main.key, main.loadCount, main.loadCatalog, locales);\n loadLocales(js.key, js.loadCount, js.loadCatalog, locales);\n `;\n\n const i18nHandleSnippet = dedent`\n const ${I18N_HANDLE} = async ({ event, resolve }: any) => {\n const locale = getLocale(event.url);\n return await runWithLocale(locale, () =>\n resolve(event, {\n transformPageChunk: ({ html }: { html: string }) =>\n html.replace('%sveltekit.lang%', locale)\n })\n );\n };\n `;\n\n // Above the handle and its JSDoc, so `handleWuchale` is declared before\n // the handle reads it.\n sourceFile.insertText(\n handleStmt.getStart(true),\n `${startupSnippet}\\n\\n${i18nHandleSnippet}\\n\\n`,\n );\n\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport dedent from \"dedent\";\nimport { Project, QuoteKind, SyntaxKind, type SourceFile } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport {\n ensureNamedImport,\n formatLikeSource,\n} from \"../../../../runtime/ts-morph-helpers\";\n\nconst DELOCALIZE_HELPER = dedent`\n const rerouteDeLocalize = (url: string) => {\n const [upath, locale] = deLocalizeDefault(url, locales);\n const { path } = matchUrl(upath, locale);\n return path ?? url;\n };\n`;\n\n/**\n * The whole file, for a project that had no universal hooks. `disable-i18n`\n * deletes it again once the de-localizing reroute is all that is left.\n */\nexport const HOOKS_SNIPPET = dedent`\n import { deLocalizeDefault } from 'wuchale/url';\n import { matchUrl } from '#locales/main.url.js';\n import { locales } from '#locales/data.js';\n\n const rerouteDeLocalize = (url: string) => {\n const [upath, locale] = deLocalizeDefault(url, locales);\n const { path } = matchUrl(upath, locale);\n return path ?? url;\n };\n\n export const reroute = ({ url }) => rerouteDeLocalize(url.pathname);\n`;\n\nconst FAILURE_HINT = dedent`\n Compose your existing reroute in src/hooks.ts with the wuchale de-localizer:\n\n import { deLocalizeDefault } from 'wuchale/url';\n import { matchUrl } from '#locales/main.url.js';\n import { locales } from '#locales/data.js';\n\n const rerouteDeLocalize = (url: string) => {\n const [upath, locale] = deLocalizeDefault(url, locales);\n const { path } = matchUrl(upath, locale);\n return path ?? url;\n };\n\n export const reroute = ({ url }) => rerouteDeLocalize(existingReroute(url.pathname));\n`;\n\n/** What `enable-content-negotiation` leaves behind, to the whitespace. */\nconst NEGOTIATE_ONLY_REROUTE =\n /^\\(\\s*\\{\\s*url\\s*\\}\\s*\\)\\s*=>\\s*negotiateReroute\\(\\s*url\\.pathname\\s*\\)$/;\n\n/** A `reroute` this modifier cannot compose with: not a variable declaration. */\nfunction hasOtherReroute(sourceFile: SourceFile): boolean {\n if (sourceFile.getFunction(\"reroute\")) return true;\n return sourceFile\n .getExportDeclarations()\n .some((d) =>\n d\n .getNamedExports()\n .some(\n (n) => (n.getAliasNode()?.getText() ?? n.getName()) === \"reroute\",\n ),\n );\n}\n\nfunction ensureDeLocalizeImports(sourceFile: SourceFile) {\n ensureNamedImport(sourceFile, \"wuchale/url\", \"deLocalizeDefault\");\n ensureNamedImport(sourceFile, \"#locales/main.url.js\", \"matchUrl\");\n ensureNamedImport(sourceFile, \"#locales/data.js\", \"locales\");\n}\n\n/**\n * Add the de-localizing reroute to `src/hooks.ts`, composing with the one\n * `enable-content-negotiation` wrote rather than replacing the file: either\n * pattern may be enabled first, and negotiation's `modifyHooksNegotiate`\n * composes the other way round.\n */\nexport function modifyHooksI18n(hooksPath: string): ModifyOutcome {\n if (!fs.existsSync(hooksPath)) {\n fs.mkdirSync(path.dirname(hooksPath), { recursive: true });\n fs.writeFileSync(hooksPath, HOOKS_SNIPPET + \"\\n\");\n return { status: \"success\", changed: true };\n }\n\n const original = fs.readFileSync(hooksPath, \"utf8\");\n if (original.includes(\"rerouteDeLocalize\")) {\n return { status: \"success\", changed: false };\n }\n\n const project = new Project({\n compilerOptions: { allowJs: true },\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n const sourceFile = project.addSourceFileAtPath(hooksPath);\n\n const rerouteDecl = sourceFile.getVariableDeclaration(\"reroute\");\n\n if (!rerouteDecl) {\n // A reroute in a shape ts-morph cannot rewrite (a function declaration,\n // a re-export) would collide with the one added below.\n if (hasOtherReroute(sourceFile)) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n ensureDeLocalizeImports(sourceFile);\n sourceFile.addStatements(\n `\\n${DELOCALIZE_HELPER}\\n\\nexport const reroute = ({ url }) => rerouteDeLocalize(url.pathname);\\n`,\n );\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n }\n\n const rerouteStmt = rerouteDecl.getFirstAncestorByKind(\n SyntaxKind.VariableStatement,\n );\n if (!rerouteStmt?.hasExportKeyword()) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n const init = rerouteDecl.getInitializer();\n if (!init || !NEGOTIATE_ONLY_REROUTE.test(init.getText())) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n ensureDeLocalizeImports(sourceFile);\n rerouteDecl.setInitializer(\n \"({ url }) => rerouteDeLocalize(negotiateReroute(url.pathname))\",\n );\n\n // Last: inserting text forgets the nodes above, and the helper has to be\n // declared before the reroute that reads it.\n const target = sourceFile\n .getVariableStatements()\n .find((s) => s.getDeclarations().some((d) => d.getName() === \"reroute\"))!;\n sourceFile.insertText(target.getStart(true), `${DELOCALIZE_HELPER}\\n\\n`);\n\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n}\n","import fs from \"node:fs\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst FAILURE_HINT = [\n \"Add the sveltekit lang placeholder to the <html> tag:\",\n \"\",\n '<html lang=\"%sveltekit.lang%\">',\n].join(\"\\n\");\n\nconst NOT_FOUND_HINT = [\n \"Create src/app.html with a lang placeholder:\",\n \"\",\n \"<!doctype html>\",\n '<html lang=\"%sveltekit.lang%\">',\n \" <head>\",\n ' <meta charset=\"utf-8\" />',\n \" %sveltekit.head%\",\n \" </head>\",\n ' <body data-sveltekit-preload-data=\"hover\">',\n ' <div style=\"display: contents\">%sveltekit.body%</div>',\n \" </body>\",\n \"</html>\",\n].join(\"\\n\");\n\nexport function modifyAppHtml(appHtmlPath: string): ModifyOutcome {\n if (!fs.existsSync(appHtmlPath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const original = fs.readFileSync(appHtmlPath, \"utf8\");\n if (\n original.includes('lang=\"%sveltekit.lang%\"') ||\n original.includes(\"lang='%sveltekit.lang%'\")\n ) {\n return { status: \"success\", changed: false };\n }\n\n const updated = original.replace(/<html(\\s[^>]*?)?>/i, (match) => {\n // A static lang (the templates ship lang=\"en\") is replaced by the\n // placeholder so the server hook can fill in the negotiated locale.\n if (/\\slang\\s*=/i.test(match)) {\n return match.replace(\n /\\slang\\s*=\\s*(?:\"[^\"]*\"|'[^']*'|[^\\s>]+)/i,\n ' lang=\"%sveltekit.lang%\"',\n );\n }\n return match.replace(/<html/i, '<html lang=\"%sveltekit.lang%\"');\n });\n\n if (updated === original) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n fs.writeFileSync(appHtmlPath, updated);\n return { status: \"success\", changed: true };\n}\n","import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst NOT_FOUND_HINT = [\n \"Create a .gitignore with the wuchale cache ignored:\",\n \"\",\n \"# Wuchale\",\n \"src/locales/.wuchale\",\n].join(\"\\n\");\n\nexport function modifyGitignore(gitignorePath: string): ModifyOutcome {\n if (!fs.existsSync(gitignorePath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const original = fs.readFileSync(gitignorePath, \"utf8\");\n if (original.includes(\"src/locales/.wuchale\")) {\n return { status: \"success\", changed: false };\n }\n\n const block = dedent`\n # Wuchale\n src/locales/.wuchale\n `;\n\n const needsNewline = original.length > 0 && !original.endsWith(\"\\n\");\n const updated = original + (needsNewline ? \"\\n\" : \"\") + \"\\n\" + block + \"\\n\";\n fs.writeFileSync(gitignorePath, updated);\n return { status: \"success\", changed: true };\n}\n","import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport {\n ensureImports,\n withInMemoryScript,\n} from \"../../../../runtime/ts-morph-helpers\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport type { Ui } from \"../../../../core/field/ui\";\n\nconst LANGUAGE_SELECT_SNIPPET = `<Navbar.Item>\n\t\t\t\t<LanguageSelect />\n\t\t\t</Navbar.Item>\n\t\t\t`;\n\nconst PLAIN_LANGUAGE_SELECT_SNIPPET = \"<LanguageSelect />\";\n\nconst IMPORT_SNIPPET = dedent`\n import LanguageSelect from '#lib/components/language-select.svelte';\n`;\n\nconst FAILURE_HINT = [\n \"Add the language select inside your <Navbar.List> in the root layout.\",\n \"\",\n \"Import to add to the <script> tag:\",\n \"\",\n IMPORT_SNIPPET,\n \"\",\n \"Markup to add at the end of <Navbar.List>:\",\n LANGUAGE_SELECT_SNIPPET,\n].join(\"\\n\");\n\nconst NOT_FOUND_HINT = [\n \"Create a root layout that includes a language select inside <Navbar.List>.\",\n \"\",\n \"Import for the <script> tag:\",\n \"\",\n IMPORT_SNIPPET,\n \"\",\n \"Markup at the end of <Navbar.List>:\",\n LANGUAGE_SELECT_SNIPPET,\n].join(\"\\n\");\n\nconst PLAIN_FAILURE_HINT = [\n \"Add the language select to your root layout.\",\n \"\",\n \"Import to add to the <script> tag:\",\n \"\",\n IMPORT_SNIPPET,\n \"\",\n \"Markup to add wherever it should render, e.g. above {@render children()}:\",\n \"\",\n PLAIN_LANGUAGE_SELECT_SNIPPET,\n].join(\"\\n\");\n\nconst PLAIN_NOT_FOUND_HINT = [\n \"Create a root layout that includes the language select.\",\n \"\",\n \"Import for the <script> tag:\",\n \"\",\n IMPORT_SNIPPET,\n \"\",\n \"Markup above {@render children()}:\",\n \"\",\n PLAIN_LANGUAGE_SELECT_SNIPPET,\n].join(\"\\n\");\n\nfunction addImport(file: SvelteFile): void {\n file.modifyScript((source) => {\n const { source: out } = withInMemoryScript(source, (sf) => {\n ensureImports(sf, [\n {\n defaultImport: \"LanguageSelect\",\n moduleSpecifier: \"#lib/components/language-select.svelte\",\n },\n ]);\n });\n return out;\n });\n}\n\n/**\n * A vela layout gets the select as the last `<Navbar.List>` item. A plain one\n * (a project vela did not create) has no navbar, so the select goes above the\n * layout's children.\n */\nexport function modifyRootLayoutLanguageSelect(\n layoutPath: string,\n ui: Ui = \"shadcn\",\n): ModifyOutcome {\n const plain = ui === \"plain\";\n if (!fs.existsSync(layoutPath)) {\n return {\n status: \"not-found\",\n message: plain ? PLAIN_NOT_FOUND_HINT : NOT_FOUND_HINT,\n };\n }\n\n const file = SvelteFile.fromPath(layoutPath);\n if (file.hasElement(\"LanguageSelect\")) {\n return { status: \"success\", changed: false };\n }\n\n if (plain) {\n // Without a <script> the import has nowhere to go, and the markup alone\n // would not compile.\n if (!file.getScript()) {\n return { status: \"failed\", message: PLAIN_FAILURE_HINT };\n }\n if (!file.insertBeforeChildren(PLAIN_LANGUAGE_SELECT_SNIPPET)) {\n return { status: \"failed\", message: PLAIN_FAILURE_HINT };\n }\n addImport(file);\n file.writeTo(layoutPath);\n return { status: \"success\", changed: file.hasChanged() };\n }\n\n if (!file.hasElement(\"Navbar.List\")) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n addImport(file);\n file.insertBeforeClosingTag(\"Navbar.List\", LANGUAGE_SELECT_SNIPPET);\n file.writeTo(layoutPath);\n return { status: \"success\", changed: file.hasChanged() };\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { File } from \"../../../core/types\";\nimport type { Ui } from \"../../../core/field/ui\";\n\nconst PAGE_PATH = \"src/routes/+page.svelte\";\nconst CATALOG_PATH = \"src/locales/es.po\";\n\n/** `src/routes/+page.svelte` as `sv create` writes it. */\nconst WELCOME_PAGE = [\n \"<h1>Welcome to SvelteKit</h1>\",\n '<p>Visit <a href=\"https://svelte.dev/docs/kit\">svelte.dev/docs/kit</a> to read the documentation</p>',\n].join(\"\\n\");\n\ninterface Entry {\n reference: string;\n msgid: string;\n msgstr: string;\n}\n\nconst PAGE_ENTRIES: Entry[] = [\n {\n reference: PAGE_PATH,\n msgid: \"Welcome to SvelteKit\",\n msgstr: \"Bienvenido a SvelteKit\",\n },\n {\n reference: PAGE_PATH,\n msgid: \"Visit <0>svelte.dev/docs/kit</0> to read the documentation\",\n msgstr: \"Visita <0>svelte.dev/docs/kit</0> para leer la documentación\",\n },\n];\n\n// The native <select>'s aria-label. The shadcn select has no text of its own:\n// locale names come from Intl.DisplayNames.\nconst PLAIN_SELECT_ENTRY: Entry = {\n reference: \"src/lib/components/language-select.svelte\",\n msgid: \"Language\",\n msgstr: \"Idioma\",\n};\n\n// What wuchale writes for `es`. It rewrites the file on the first extraction,\n// keeping these translations and adding the source locale's catalog.\nconst HEADER = [\n 'msgid \"\"',\n 'msgstr \"\"',\n '\"Source-Language: en\\\\n\"',\n '\"Language: es\\\\n\"',\n '\"MIME-Version: 1.0\\\\n\"',\n '\"Content-Type: text/plain; charset=utf-8\\\\n\"',\n '\"Content-Transfer-Encoding: 8bit\\\\n\"',\n '\"Plural-Forms: nplurals=3\\\\n\"',\n '\"X-Plurals-Order: one, many, other\\\\n\"',\n].join(\"\\n\");\n\n// Whitespace is ignored so a page prettier has rewrapped still counts.\nconst normalize = (source: string) => source.replace(/\\s+/g, \"\");\n\n/**\n * A Spanish catalog for the `sv create` welcome page, so the language select\n * visibly does something on a fresh project. Anything else in the project is\n * left for the user to translate. Null unless the page is untouched, and never\n * over an existing catalog.\n */\nexport function welcomePageCatalog(root: string, ui: Ui): File | null {\n if (fs.existsSync(path.join(root, CATALOG_PATH))) return null;\n\n const pagePath = path.join(root, PAGE_PATH);\n if (!fs.existsSync(pagePath)) return null;\n const page = fs.readFileSync(pagePath, \"utf8\");\n if (normalize(page) !== normalize(WELCOME_PAGE)) return null;\n\n const entries =\n ui === \"plain\" ? [...PAGE_ENTRIES, PLAIN_SELECT_ENTRY] : PAGE_ENTRIES;\n const blocks = entries.map((entry) =>\n [\n `#: ${entry.reference}`,\n `msgid \"${entry.msgid}\"`,\n `msgstr \"${entry.msgstr}\"`,\n ].join(\"\\n\"),\n );\n\n return {\n path: CATALOG_PATH,\n language: \"text\",\n content: [HEADER, ...blocks].join(\"\\n\\n\") + \"\\n\",\n status: \"success\",\n };\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport { resolveUi } from \"../../../core/field/ui\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport {\n probeFirstExisting,\n VITE_CONFIG_CANDIDATES,\n} from \"../../../runtime/config-target\";\nimport { modifyViteConfig } from \"./modifies/vite-config\";\nimport { modifyPackageImportsI18n } from \"./modifies/package-imports\";\nimport { modifyHooksServerI18n } from \"./modifies/hooks.server\";\nimport { modifyHooksI18n } from \"./modifies/hooks\";\nimport { modifyAppHtml } from \"./modifies/app-html\";\nimport { modifyGitignore } from \"./modifies/gitignore\";\nimport { ensureRootLayoutI18n } from \"./modifies/+layout\";\nimport { modifyRootLayoutLanguageSelect } from \"./modifies/root-layout.svelte\";\nimport { welcomePageCatalog } from \"./welcome-catalog\";\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const modifies: File[] = [];\n\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n logger.info(\"Modifying vite.config\");\n const viteConfigPath =\n probeFirstExisting(options.root, VITE_CONFIG_CANDIDATES) ??\n path.join(options.root, VITE_CONFIG_CANDIDATES[0]);\n pushResult(\n modifyOutcomeToFile(viteConfigPath, modifyViteConfig(viteConfigPath)),\n );\n\n logger.info(\"Adding #locales to package.json imports\");\n const imports = modifyPackageImportsI18n(options.root);\n pushResult(modifyOutcomeToFile(imports.filePath, imports.outcome));\n\n logger.info(\"Modifying hooks.server.ts\");\n const hooksServerPath = path.join(options.root, \"src\", \"hooks.server.ts\");\n pushResult(\n modifyOutcomeToFile(\n hooksServerPath,\n modifyHooksServerI18n(hooksServerPath),\n ),\n );\n\n logger.info(\"Modifying hooks.ts\");\n const hooksPath = path.join(options.root, \"src\", \"hooks.ts\");\n pushResult(modifyOutcomeToFile(hooksPath, modifyHooksI18n(hooksPath)));\n\n logger.info(\"Modifying app.html\");\n const appHtmlPath = path.join(options.root, \"src\", \"app.html\");\n pushResult(modifyOutcomeToFile(appHtmlPath, modifyAppHtml(appHtmlPath)));\n\n logger.info(\"Modifying root +layout.ts\");\n const layoutPath = path.join(options.root, \"src\", \"routes\", \"+layout.ts\");\n pushResult(modifyOutcomeToFile(layoutPath, ensureRootLayoutI18n(layoutPath)));\n\n logger.info(\"Modifying root layout language select\");\n const rootLayoutCandidates = [\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 ui = resolveUi(options);\n // With no layout at all, a plain project's not-found hint names the\n // +layout.svelte it would have rather than vela's root-layout.svelte.\n const rootLayoutPath =\n rootLayoutCandidates.find((p) => fs.existsSync(p)) ??\n (ui === \"plain\" ? rootLayoutCandidates[3] : rootLayoutCandidates[0]);\n pushResult(\n modifyOutcomeToFile(\n rootLayoutPath,\n modifyRootLayoutLanguageSelect(rootLayoutPath, ui),\n ),\n );\n\n logger.info(\"Updating .gitignore\");\n const gitignorePath = path.join(options.root, \".gitignore\");\n pushResult(\n modifyOutcomeToFile(gitignorePath, modifyGitignore(gitignorePath)),\n );\n\n const catalog = welcomePageCatalog(options.root, ui);\n if (catalog) logger.info(\"Translating the welcome page into Spanish\");\n\n return {\n creates: catalog ? [catalog] : [],\n modifies,\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n } satisfies Result;\n}\n"],"mappings":";;;;;;;;;;;;;AAKA,IAAMA,IAAe;CACnB;CACA;CACA;CACA;CACA;CACA;CAC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,EAAK,KAAKsF,EAAQ,MAAM,OAAO,UAAU,gBAAgB;CAC3D,GACMjB,IAAKuB,EAAUN,CAAO,GAGtBO,IACJF,EAAqB,MAAM,MAAM5F,EAAG,WAAW+F,CAAC,CAAC,MAChDzB,MAAO,UAAUsB,EAAqB,KAAKA,EAAqB;CAQnE,AAPAH,EACEC,EACEI,GACA1B,EAA+B0B,GAAgBxB,CAAE,CACnD,CACF,GAEAe,EAAO,KAAK,qBAAqB;CACjC,IAAM9B,IAAgBtD,EAAK,KAAKsF,EAAQ,MAAM,YAAY;CAC1D,EACEG,EAAoBnC,GAAeD,EAAgBC,CAAa,CAAC,CACnE;CAEA,IAAMyC,IAAUhB,GAAmBO,EAAQ,MAAMjB,CAAE;CAGnD,OAFI0B,KAASX,EAAO,KAAK,2CAA2C,GAE7D;EACL,SAASW,IAAU,CAACA,CAAO,IAAI,CAAC;EAChC;EACA,SAAS,CAAC;EACV,YAAY,CAAC;EACb,UAAU,CAAC;EACX,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAiB,CAAC;CACpB;AACF"}
1
+ {"version":3,"file":"generate.runtime-DdcVnK8J.js","names":["FAILURE_HINT","NOT_FOUND_HINT","FAILURE_HINT","FAILURE_HINT","FAILURE_HINT","NOT_FOUND_HINT","NOT_FOUND_HINT","dedent","withInMemoryScript","formatLikeSource","ensureImports","modifyOutcomeToFile","SvelteFile","addHandle","probeFirstExisting","VITE_CONFIG_CANDIDATES","modifyPackageImportsI18n","ensureRootLayoutI18n","fs","path","FAILURE_HINT$4","NOT_FOUND_HINT$3","modifyViteConfig","viteConfigPath","sourceFile","Project","QuoteKind","changed","failed","d","configArg","SyntaxKind","ce","configObj","pluginsProp","pluginsInit","arr","el","I18N_HANDLE","FAILURE_HINT$3","HOOKS_SERVER_SNIPPET","ensureNamespaceImport","moduleSpecifier","ns","modifyHooksServerI18n","hooksServerPath","original","composed","handleStmt","ensureNamedImport","startupSnippet","i18nHandleSnippet","DELOCALIZE_HELPER","HOOKS_SNIPPET","FAILURE_HINT$2","NEGOTIATE_ONLY_REROUTE","hasOtherReroute","n","ensureDeLocalizeImports","modifyHooksI18n","hooksPath","rerouteDecl","init","target","s","FAILURE_HINT$1","NOT_FOUND_HINT$2","modifyAppHtml","appHtmlPath","updated","match","NOT_FOUND_HINT$1","modifyGitignore","gitignorePath","block","LANGUAGE_SELECT_SNIPPET","PLAIN_LANGUAGE_SELECT_SNIPPET","IMPORT_SNIPPET","FAILURE_HINT","NOT_FOUND_HINT","PLAIN_FAILURE_HINT","PLAIN_NOT_FOUND_HINT","addImport","out","source","sf","modifyRootLayoutLanguageSelect","plain","ui","layoutPath","file","PAGE_PATH","CATALOG_PATH","WELCOME_PAGE","PAGE_ENTRIES","PLAIN_SELECT_ENTRY","HEADER","normalize","welcomePageCatalog","root","pagePath","entry","generate","logger","getLogger","options","modifies","pushResult","imports","rootLayoutCandidates","resolveUi","rootLayoutPath","p","catalog"],"sources":["../../src/patterns/enable/i18n/modifies/vite-config.ts","../../src/patterns/enable/i18n/modifies/hooks.server.ts","../../src/patterns/enable/i18n/modifies/hooks.ts","../../src/patterns/enable/i18n/modifies/app-html.ts","../../src/patterns/enable/i18n/modifies/gitignore.ts","../../src/patterns/enable/i18n/modifies/root-layout.svelte.ts","../../src/patterns/enable/i18n/welcome-catalog.ts","../../src/patterns/enable/i18n/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport { Project, QuoteKind, SyntaxKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport { formatLikeSource } from \"../../../../runtime/ts-morph-helpers\";\n\nconst FAILURE_HINT = [\n \"Add the wuchale plugin to your Vite config:\",\n \"\",\n \"import { wuchale } from 'wuchale/vite';\",\n \"\",\n \"export default defineConfig({\",\n \" plugins: [wuchale(), /* ...existing plugins */],\",\n \"});\",\n].join(\"\\n\");\n\nconst NOT_FOUND_HINT = [\n \"Create a Vite config with the wuchale plugin:\",\n \"\",\n \"import { defineConfig } from 'vite';\",\n \"import { wuchale } from 'wuchale/vite';\",\n \"\",\n \"export default defineConfig({\",\n \" plugins: [wuchale()],\",\n \"});\",\n].join(\"\\n\");\n\nexport function modifyViteConfig(viteConfigPath: string): ModifyOutcome {\n if (!fs.existsSync(viteConfigPath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const project = new Project({\n compilerOptions: { allowJs: true },\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n const sourceFile = project.addSourceFileAtPath(viteConfigPath);\n\n let changed = false;\n let failed = false;\n\n const hasImport = sourceFile\n .getImportDeclarations()\n .some((d) => d.getModuleSpecifierValue() === \"wuchale/vite\");\n\n if (!hasImport) {\n sourceFile.insertImportDeclaration(0, {\n namedImports: [\"wuchale\"],\n moduleSpecifier: \"wuchale/vite\",\n });\n changed = true;\n }\n\n const defineConfigCall = sourceFile\n .getDescendantsOfKind(SyntaxKind.CallExpression)\n .find((ce) => ce.getExpression().getText() === \"defineConfig\");\n\n const configArg = defineConfigCall?.getArguments()?.[0];\n const configObj =\n configArg?.getKind() === SyntaxKind.ObjectLiteralExpression\n ? (configArg as import(\"ts-morph\").ObjectLiteralExpression)\n : null;\n\n if (!configObj) {\n failed = true;\n } else {\n const pluginsProp = configObj.getProperty(\"plugins\");\n if (!pluginsProp) {\n configObj.addPropertyAssignment({\n name: \"plugins\",\n initializer: \"[wuchale()]\",\n });\n changed = true;\n } else if (pluginsProp.getKind() !== SyntaxKind.PropertyAssignment) {\n failed = true;\n } else {\n const pluginsInit = (\n pluginsProp as import(\"ts-morph\").PropertyAssignment\n ).getInitializer();\n\n if (!pluginsInit) {\n (pluginsProp as import(\"ts-morph\").PropertyAssignment).setInitializer(\n \"[wuchale()]\",\n );\n changed = true;\n } else if (pluginsInit.getKind() !== SyntaxKind.ArrayLiteralExpression) {\n failed = true;\n } else {\n const arr = pluginsInit as import(\"ts-morph\").ArrayLiteralExpression;\n const hasWuchale = arr\n .getElements()\n .some((el) => el.getText().replace(/\\s/g, \"\") === \"wuchale()\");\n\n if (!hasWuchale) {\n arr.insertElement(0, \"wuchale()\");\n changed = true;\n }\n }\n }\n }\n\n if (changed) {\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n }\n\n if (failed) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n return { status: \"success\", changed };\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport dedent from \"dedent\";\nimport { Project, QuoteKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport { addHandle } from \"../../../../runtime/compose-handle\";\nimport {\n ensureNamedImport,\n formatLikeSource,\n} from \"../../../../runtime/ts-morph-helpers\";\n\nconst I18N_HANDLE = \"handleWuchale\";\n\nconst FAILURE_HINT = dedent`\n Wrap your exported handle with the wuchale i18n handler:\n\n import { sequence } from '@sveltejs/kit/hooks';\n import { runWithLocale, loadLocales } from 'wuchale/load-utils/server';\n import { getLocale } from '#locales/main.url.js';\n import { locales } from '#locales/data.js';\n import * as main from '#locales/main.loader.server.svelte.js';\n import * as js from '#locales/js.loader.server.js';\n\n loadLocales(main.key, main.loadCount, main.loadCatalog, locales);\n loadLocales(js.key, js.loadCount, js.loadCatalog, locales);\n\n const handleWuchale = async ({ event, resolve }: any) => {\n const locale = getLocale(event.url);\n return await runWithLocale(locale, () =>\n resolve(event, {\n transformPageChunk: ({ html }: { html: string }) =>\n html.replace('%sveltekit.lang%', locale),\n }),\n );\n };\n\n export const handle = sequence(handleWuchale, /* your existing handle */);\n`;\n\n/**\n * The whole file, for a project that had no server hooks: a fresh `sv create`\n * app or a static site. `disable-i18n` deletes it again once the i18n handle\n * is all that is left.\n */\nexport const HOOKS_SERVER_SNIPPET = dedent`\n import type { Handle } from '@sveltejs/kit/hooks';\n import { runWithLocale, loadLocales } from 'wuchale/load-utils/server';\n import { getLocale } from '#locales/main.url.js';\n import { locales } from '#locales/data.js';\n import * as main from '#locales/main.loader.server.svelte.js';\n import * as js from '#locales/js.loader.server.js';\n\n loadLocales(main.key, main.loadCount, main.loadCatalog, locales);\n loadLocales(js.key, js.loadCount, js.loadCatalog, locales);\n\n const handleWuchale: Handle = async ({ event, resolve }) => {\n const locale = getLocale(event.url);\n return await runWithLocale(locale, () =>\n resolve(event, {\n transformPageChunk: ({ html }) => html.replace('%sveltekit.lang%', locale)\n })\n );\n };\n\n export const handle = handleWuchale;\n`;\n\nfunction ensureNamespaceImport(\n sourceFile: import(\"ts-morph\").SourceFile,\n moduleSpecifier: string,\n ns: string,\n) {\n const existing = sourceFile\n .getImportDeclarations()\n .find((d) => d.getModuleSpecifierValue() === moduleSpecifier);\n if (existing) return;\n sourceFile.addImportDeclaration({ namespaceImport: ns, moduleSpecifier });\n}\n\nexport function modifyHooksServerI18n(hooksServerPath: string): ModifyOutcome {\n if (!fs.existsSync(hooksServerPath)) {\n // SvelteKit loads the first `hooks.server.*` it finds, and `.js` sorts\n // first, so a new `.ts` beside it would never run.\n if (fs.existsSync(hooksServerPath.replace(/\\.ts$/, \".js\"))) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n fs.mkdirSync(path.dirname(hooksServerPath), { recursive: true });\n fs.writeFileSync(hooksServerPath, HOOKS_SERVER_SNIPPET + \"\\n\");\n return { status: \"success\", changed: true };\n }\n\n const original = fs.readFileSync(hooksServerPath, \"utf8\");\n if (original.includes(\"runWithLocale\") || original.includes(\"loadLocales(\")) {\n return { status: \"success\", changed: false };\n }\n\n const project = new Project({\n compilerOptions: { allowJs: true },\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n const sourceFile = project.addSourceFileAtPath(hooksServerPath);\n\n // Composed first: an unsupported handle leaves the file untouched.\n const composed = addHandle(sourceFile, { expression: I18N_HANDLE });\n if (composed.status === \"unsupported\" || !composed.statement) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n const handleStmt = composed.statement;\n\n ensureNamedImport(sourceFile, \"wuchale/load-utils/server\", \"runWithLocale\");\n ensureNamedImport(sourceFile, \"wuchale/load-utils/server\", \"loadLocales\");\n ensureNamedImport(sourceFile, \"#locales/main.url.js\", \"getLocale\");\n ensureNamedImport(sourceFile, \"#locales/data.js\", \"locales\");\n ensureNamespaceImport(\n sourceFile,\n \"#locales/main.loader.server.svelte.js\",\n \"main\",\n );\n ensureNamespaceImport(sourceFile, \"#locales/js.loader.server.js\", \"js\");\n\n const startupSnippet = dedent`\n loadLocales(main.key, main.loadCount, main.loadCatalog, locales);\n loadLocales(js.key, js.loadCount, js.loadCatalog, locales);\n `;\n\n const i18nHandleSnippet = dedent`\n const ${I18N_HANDLE} = async ({ event, resolve }: any) => {\n const locale = getLocale(event.url);\n return await runWithLocale(locale, () =>\n resolve(event, {\n transformPageChunk: ({ html }: { html: string }) =>\n html.replace('%sveltekit.lang%', locale)\n })\n );\n };\n `;\n\n // Above the handle and its JSDoc, so `handleWuchale` is declared before\n // the handle reads it.\n sourceFile.insertText(\n handleStmt.getStart(true),\n `${startupSnippet}\\n\\n${i18nHandleSnippet}\\n\\n`,\n );\n\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport dedent from \"dedent\";\nimport { Project, QuoteKind, SyntaxKind, type SourceFile } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport {\n ensureNamedImport,\n formatLikeSource,\n} from \"../../../../runtime/ts-morph-helpers\";\n\nconst DELOCALIZE_HELPER = dedent`\n const rerouteDeLocalize = (url: string) => {\n const [upath, locale] = deLocalizeDefault(url, locales);\n const { path } = matchUrl(upath, locale);\n return path ?? url;\n };\n`;\n\n/**\n * The whole file, for a project that had no universal hooks. `disable-i18n`\n * deletes it again once the de-localizing reroute is all that is left.\n */\nexport const HOOKS_SNIPPET = dedent`\n import { deLocalizeDefault } from 'wuchale/url';\n import { matchUrl } from '#locales/main.url.js';\n import { locales } from '#locales/data.js';\n\n const rerouteDeLocalize = (url: string) => {\n const [upath, locale] = deLocalizeDefault(url, locales);\n const { path } = matchUrl(upath, locale);\n return path ?? url;\n };\n\n export const reroute = ({ url }) => rerouteDeLocalize(url.pathname);\n`;\n\nconst FAILURE_HINT = dedent`\n Compose your existing reroute in src/hooks.ts with the wuchale de-localizer:\n\n import { deLocalizeDefault } from 'wuchale/url';\n import { matchUrl } from '#locales/main.url.js';\n import { locales } from '#locales/data.js';\n\n const rerouteDeLocalize = (url: string) => {\n const [upath, locale] = deLocalizeDefault(url, locales);\n const { path } = matchUrl(upath, locale);\n return path ?? url;\n };\n\n export const reroute = ({ url }) => rerouteDeLocalize(existingReroute(url.pathname));\n`;\n\n/** What `enable-content-negotiation` leaves behind, to the whitespace. */\nconst NEGOTIATE_ONLY_REROUTE =\n /^\\(\\s*\\{\\s*url\\s*\\}\\s*\\)\\s*=>\\s*negotiateReroute\\(\\s*url\\.pathname\\s*\\)$/;\n\n/** A `reroute` this modifier cannot compose with: not a variable declaration. */\nfunction hasOtherReroute(sourceFile: SourceFile): boolean {\n if (sourceFile.getFunction(\"reroute\")) return true;\n return sourceFile\n .getExportDeclarations()\n .some((d) =>\n d\n .getNamedExports()\n .some(\n (n) => (n.getAliasNode()?.getText() ?? n.getName()) === \"reroute\",\n ),\n );\n}\n\nfunction ensureDeLocalizeImports(sourceFile: SourceFile) {\n ensureNamedImport(sourceFile, \"wuchale/url\", \"deLocalizeDefault\");\n ensureNamedImport(sourceFile, \"#locales/main.url.js\", \"matchUrl\");\n ensureNamedImport(sourceFile, \"#locales/data.js\", \"locales\");\n}\n\n/**\n * Add the de-localizing reroute to `src/hooks.ts`, composing with the one\n * `enable-content-negotiation` wrote rather than replacing the file: either\n * pattern may be enabled first, and negotiation's `modifyHooksNegotiate`\n * composes the other way round.\n */\nexport function modifyHooksI18n(hooksPath: string): ModifyOutcome {\n if (!fs.existsSync(hooksPath)) {\n fs.mkdirSync(path.dirname(hooksPath), { recursive: true });\n fs.writeFileSync(hooksPath, HOOKS_SNIPPET + \"\\n\");\n return { status: \"success\", changed: true };\n }\n\n const original = fs.readFileSync(hooksPath, \"utf8\");\n if (original.includes(\"rerouteDeLocalize\")) {\n return { status: \"success\", changed: false };\n }\n\n const project = new Project({\n compilerOptions: { allowJs: true },\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n const sourceFile = project.addSourceFileAtPath(hooksPath);\n\n const rerouteDecl = sourceFile.getVariableDeclaration(\"reroute\");\n\n if (!rerouteDecl) {\n // A reroute in a shape ts-morph cannot rewrite (a function declaration,\n // a re-export) would collide with the one added below.\n if (hasOtherReroute(sourceFile)) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n ensureDeLocalizeImports(sourceFile);\n sourceFile.addStatements(\n `\\n${DELOCALIZE_HELPER}\\n\\nexport const reroute = ({ url }) => rerouteDeLocalize(url.pathname);\\n`,\n );\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n }\n\n const rerouteStmt = rerouteDecl.getFirstAncestorByKind(\n SyntaxKind.VariableStatement,\n );\n if (!rerouteStmt?.hasExportKeyword()) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n const init = rerouteDecl.getInitializer();\n if (!init || !NEGOTIATE_ONLY_REROUTE.test(init.getText())) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n ensureDeLocalizeImports(sourceFile);\n rerouteDecl.setInitializer(\n \"({ url }) => rerouteDeLocalize(negotiateReroute(url.pathname))\",\n );\n\n // Last: inserting text forgets the nodes above, and the helper has to be\n // declared before the reroute that reads it.\n const target = sourceFile\n .getVariableStatements()\n .find((s) => s.getDeclarations().some((d) => d.getName() === \"reroute\"))!;\n sourceFile.insertText(target.getStart(true), `${DELOCALIZE_HELPER}\\n\\n`);\n\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n}\n","import fs from \"node:fs\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst FAILURE_HINT = [\n \"Add the sveltekit lang placeholder to the <html> tag:\",\n \"\",\n '<html lang=\"%sveltekit.lang%\">',\n].join(\"\\n\");\n\nconst NOT_FOUND_HINT = [\n \"Create src/app.html with a lang placeholder:\",\n \"\",\n \"<!doctype html>\",\n '<html lang=\"%sveltekit.lang%\">',\n \" <head>\",\n ' <meta charset=\"utf-8\" />',\n \" %sveltekit.head%\",\n \" </head>\",\n ' <body data-sveltekit-preload-data=\"hover\">',\n ' <div style=\"display: contents\">%sveltekit.body%</div>',\n \" </body>\",\n \"</html>\",\n].join(\"\\n\");\n\nexport function modifyAppHtml(appHtmlPath: string): ModifyOutcome {\n if (!fs.existsSync(appHtmlPath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const original = fs.readFileSync(appHtmlPath, \"utf8\");\n if (\n original.includes('lang=\"%sveltekit.lang%\"') ||\n original.includes(\"lang='%sveltekit.lang%'\")\n ) {\n return { status: \"success\", changed: false };\n }\n\n const updated = original.replace(/<html(\\s[^>]*?)?>/i, (match) => {\n // A static lang (the templates ship lang=\"en\") is replaced by the\n // placeholder so the server hook can fill in the negotiated locale.\n if (/\\slang\\s*=/i.test(match)) {\n return match.replace(\n /\\slang\\s*=\\s*(?:\"[^\"]*\"|'[^']*'|[^\\s>]+)/i,\n ' lang=\"%sveltekit.lang%\"',\n );\n }\n return match.replace(/<html/i, '<html lang=\"%sveltekit.lang%\"');\n });\n\n if (updated === original) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n fs.writeFileSync(appHtmlPath, updated);\n return { status: \"success\", changed: true };\n}\n","import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst NOT_FOUND_HINT = [\n \"Create a .gitignore with the wuchale cache ignored:\",\n \"\",\n \"# Wuchale\",\n \"src/locales/.wuchale\",\n].join(\"\\n\");\n\nexport function modifyGitignore(gitignorePath: string): ModifyOutcome {\n if (!fs.existsSync(gitignorePath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const original = fs.readFileSync(gitignorePath, \"utf8\");\n if (original.includes(\"src/locales/.wuchale\")) {\n return { status: \"success\", changed: false };\n }\n\n const block = dedent`\n # Wuchale\n src/locales/.wuchale\n `;\n\n const needsNewline = original.length > 0 && !original.endsWith(\"\\n\");\n const updated = original + (needsNewline ? \"\\n\" : \"\") + \"\\n\" + block + \"\\n\";\n fs.writeFileSync(gitignorePath, updated);\n return { status: \"success\", changed: true };\n}\n","import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport {\n ensureImports,\n withInMemoryScript,\n} from \"../../../../runtime/ts-morph-helpers\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport type { Ui } from \"../../../../core/field/ui\";\n\nconst LANGUAGE_SELECT_SNIPPET = `<Navbar.Item>\n\t\t\t\t<LanguageSelect />\n\t\t\t</Navbar.Item>\n\t\t\t`;\n\nconst PLAIN_LANGUAGE_SELECT_SNIPPET = \"<LanguageSelect />\";\n\nconst IMPORT_SNIPPET = dedent`\n import LanguageSelect from '#lib/components/language-select.svelte';\n`;\n\nconst FAILURE_HINT = [\n \"Add the language select inside your <Navbar.List> in the root layout.\",\n \"\",\n \"Import to add to the <script> tag:\",\n \"\",\n IMPORT_SNIPPET,\n \"\",\n \"Markup to add at the end of <Navbar.List>:\",\n LANGUAGE_SELECT_SNIPPET,\n].join(\"\\n\");\n\nconst NOT_FOUND_HINT = [\n \"Create a root layout that includes a language select inside <Navbar.List>.\",\n \"\",\n \"Import for the <script> tag:\",\n \"\",\n IMPORT_SNIPPET,\n \"\",\n \"Markup at the end of <Navbar.List>:\",\n LANGUAGE_SELECT_SNIPPET,\n].join(\"\\n\");\n\nconst PLAIN_FAILURE_HINT = [\n \"Add the language select to your root layout.\",\n \"\",\n \"Import to add to the <script> tag:\",\n \"\",\n IMPORT_SNIPPET,\n \"\",\n \"Markup to add wherever it should render, e.g. above {@render children()}:\",\n \"\",\n PLAIN_LANGUAGE_SELECT_SNIPPET,\n].join(\"\\n\");\n\nconst PLAIN_NOT_FOUND_HINT = [\n \"Create a root layout that includes the language select.\",\n \"\",\n \"Import for the <script> tag:\",\n \"\",\n IMPORT_SNIPPET,\n \"\",\n \"Markup above {@render children()}:\",\n \"\",\n PLAIN_LANGUAGE_SELECT_SNIPPET,\n].join(\"\\n\");\n\nfunction addImport(file: SvelteFile): void {\n file.modifyScript((source) => {\n const { source: out } = withInMemoryScript(source, (sf) => {\n ensureImports(sf, [\n {\n defaultImport: \"LanguageSelect\",\n moduleSpecifier: \"#lib/components/language-select.svelte\",\n },\n ]);\n });\n return out;\n });\n}\n\n/**\n * A vela layout gets the select as the last `<Navbar.List>` item. A plain one\n * (a project vela did not create) has no navbar, so the select goes above the\n * layout's children.\n */\nexport function modifyRootLayoutLanguageSelect(\n layoutPath: string,\n ui: Ui = \"shadcn\",\n): ModifyOutcome {\n const plain = ui === \"plain\";\n if (!fs.existsSync(layoutPath)) {\n return {\n status: \"not-found\",\n message: plain ? PLAIN_NOT_FOUND_HINT : NOT_FOUND_HINT,\n };\n }\n\n const file = SvelteFile.fromPath(layoutPath);\n if (file.hasElement(\"LanguageSelect\")) {\n return { status: \"success\", changed: false };\n }\n\n if (plain) {\n // Without a <script> the import has nowhere to go, and the markup alone\n // would not compile.\n if (!file.getScript()) {\n return { status: \"failed\", message: PLAIN_FAILURE_HINT };\n }\n if (!file.insertBeforeChildren(PLAIN_LANGUAGE_SELECT_SNIPPET)) {\n return { status: \"failed\", message: PLAIN_FAILURE_HINT };\n }\n addImport(file);\n file.writeTo(layoutPath);\n return { status: \"success\", changed: file.hasChanged() };\n }\n\n if (!file.hasElement(\"Navbar.List\")) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n addImport(file);\n file.insertBeforeClosingTag(\"Navbar.List\", LANGUAGE_SELECT_SNIPPET);\n file.writeTo(layoutPath);\n return { status: \"success\", changed: file.hasChanged() };\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { File } from \"../../../core/types\";\nimport type { Ui } from \"../../../core/field/ui\";\n\nconst PAGE_PATH = \"src/routes/+page.svelte\";\nconst CATALOG_PATH = \"src/locales/es.po\";\n\n/** `src/routes/+page.svelte` as `sv create` writes it. */\nconst WELCOME_PAGE = [\n \"<h1>Welcome to SvelteKit</h1>\",\n '<p>Visit <a href=\"https://svelte.dev/docs/kit\">svelte.dev/docs/kit</a> to read the documentation</p>',\n].join(\"\\n\");\n\ninterface Entry {\n reference: string;\n msgid: string;\n msgstr: string;\n}\n\nconst PAGE_ENTRIES: Entry[] = [\n {\n reference: PAGE_PATH,\n msgid: \"Welcome to SvelteKit\",\n msgstr: \"Bienvenido a SvelteKit\",\n },\n {\n reference: PAGE_PATH,\n msgid: \"Visit <0>svelte.dev/docs/kit</0> to read the documentation\",\n msgstr: \"Visita <0>svelte.dev/docs/kit</0> para leer la documentación\",\n },\n];\n\n// The native <select>'s aria-label. The shadcn select has no text of its own:\n// locale names come from Intl.DisplayNames.\nconst PLAIN_SELECT_ENTRY: Entry = {\n reference: \"src/lib/components/language-select.svelte\",\n msgid: \"Language\",\n msgstr: \"Idioma\",\n};\n\n// What wuchale writes for `es`. It rewrites the file on the first extraction,\n// keeping these translations and adding the source locale's catalog.\nconst HEADER = [\n 'msgid \"\"',\n 'msgstr \"\"',\n '\"Source-Language: en\\\\n\"',\n '\"Language: es\\\\n\"',\n '\"MIME-Version: 1.0\\\\n\"',\n '\"Content-Type: text/plain; charset=utf-8\\\\n\"',\n '\"Content-Transfer-Encoding: 8bit\\\\n\"',\n '\"Plural-Forms: nplurals=3\\\\n\"',\n '\"X-Plurals-Order: one, many, other\\\\n\"',\n].join(\"\\n\");\n\n// Whitespace is ignored so a page prettier has rewrapped still counts.\nconst normalize = (source: string) => source.replace(/\\s+/g, \"\");\n\n/**\n * A Spanish catalog for the `sv create` welcome page, so the language select\n * visibly does something on a fresh project. Anything else in the project is\n * left for the user to translate. Null unless the page is untouched, and never\n * over an existing catalog.\n */\nexport function welcomePageCatalog(root: string, ui: Ui): File | null {\n if (fs.existsSync(path.join(root, CATALOG_PATH))) return null;\n\n const pagePath = path.join(root, PAGE_PATH);\n if (!fs.existsSync(pagePath)) return null;\n const page = fs.readFileSync(pagePath, \"utf8\");\n if (normalize(page) !== normalize(WELCOME_PAGE)) return null;\n\n const entries =\n ui === \"plain\" ? [...PAGE_ENTRIES, PLAIN_SELECT_ENTRY] : PAGE_ENTRIES;\n const blocks = entries.map((entry) =>\n [\n `#: ${entry.reference}`,\n `msgid \"${entry.msgid}\"`,\n `msgstr \"${entry.msgstr}\"`,\n ].join(\"\\n\"),\n );\n\n return {\n path: CATALOG_PATH,\n language: \"text\",\n content: [HEADER, ...blocks].join(\"\\n\\n\") + \"\\n\",\n status: \"success\",\n };\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport { resolveUi } from \"../../../core/field/ui\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport {\n probeFirstExisting,\n VITE_CONFIG_CANDIDATES,\n} from \"../../../runtime/config-target\";\nimport { modifyViteConfig } from \"./modifies/vite-config\";\nimport { modifyPackageImportsI18n } from \"./modifies/package-imports\";\nimport { modifyHooksServerI18n } from \"./modifies/hooks.server\";\nimport { modifyHooksI18n } from \"./modifies/hooks\";\nimport { modifyAppHtml } from \"./modifies/app-html\";\nimport { modifyGitignore } from \"./modifies/gitignore\";\nimport { ensureRootLayoutI18n } from \"./modifies/+layout\";\nimport { modifyRootLayoutLanguageSelect } from \"./modifies/root-layout.svelte\";\nimport { welcomePageCatalog } from \"./welcome-catalog\";\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const modifies: File[] = [];\n\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n logger.info(\"Modifying vite.config\");\n const viteConfigPath =\n probeFirstExisting(options.root, VITE_CONFIG_CANDIDATES) ??\n path.join(options.root, VITE_CONFIG_CANDIDATES[0]);\n pushResult(\n modifyOutcomeToFile(viteConfigPath, modifyViteConfig(viteConfigPath)),\n );\n\n logger.info(\"Adding #locales to package.json imports\");\n const imports = modifyPackageImportsI18n(options.root);\n pushResult(modifyOutcomeToFile(imports.filePath, imports.outcome));\n\n logger.info(\"Modifying hooks.server.ts\");\n const hooksServerPath = path.join(options.root, \"src\", \"hooks.server.ts\");\n pushResult(\n modifyOutcomeToFile(\n hooksServerPath,\n modifyHooksServerI18n(hooksServerPath),\n ),\n );\n\n logger.info(\"Modifying hooks.ts\");\n const hooksPath = path.join(options.root, \"src\", \"hooks.ts\");\n pushResult(modifyOutcomeToFile(hooksPath, modifyHooksI18n(hooksPath)));\n\n logger.info(\"Modifying app.html\");\n const appHtmlPath = path.join(options.root, \"src\", \"app.html\");\n pushResult(modifyOutcomeToFile(appHtmlPath, modifyAppHtml(appHtmlPath)));\n\n logger.info(\"Modifying root +layout.ts\");\n const layoutPath = path.join(options.root, \"src\", \"routes\", \"+layout.ts\");\n pushResult(modifyOutcomeToFile(layoutPath, ensureRootLayoutI18n(layoutPath)));\n\n logger.info(\"Modifying root layout language select\");\n const rootLayoutCandidates = [\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 ui = resolveUi(options);\n // With no layout at all, a plain project's not-found hint names the\n // +layout.svelte it would have rather than vela's root-layout.svelte.\n const rootLayoutPath =\n rootLayoutCandidates.find((p) => fs.existsSync(p)) ??\n (ui === \"plain\" ? rootLayoutCandidates[3] : rootLayoutCandidates[0]);\n pushResult(\n modifyOutcomeToFile(\n rootLayoutPath,\n modifyRootLayoutLanguageSelect(rootLayoutPath, ui),\n ),\n );\n\n logger.info(\"Updating .gitignore\");\n const gitignorePath = path.join(options.root, \".gitignore\");\n pushResult(\n modifyOutcomeToFile(gitignorePath, modifyGitignore(gitignorePath)),\n );\n\n const catalog = welcomePageCatalog(options.root, ui);\n if (catalog) logger.info(\"Translating the welcome page into Spanish\");\n\n return {\n creates: catalog ? [catalog] : [],\n modifies,\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n } satisfies Result;\n}\n"],"mappings":";;;;;;;;;;;;;AAKA,IAAMA,IAAe;CACnB;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC,CAAC,KAAK,IAAI,GAELC,IAAiB;CACrB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC,CAAC,KAAK,IAAI;AAEX,SAAgBqB,EAAiB,GAAuC;CACtE,IAAI,CAACJ,EAAG,WAAWK,CAAc,GAC/B,OAAO;EAAE,QAAQ;EAAa,SAAStB;CAAe;CAOxD,IAAMuB,IAAa,IAJCC,EAAQ;EAC1B,iBAAiB,EAAE,SAAS,GAAK;EACjC,sBAAsB,EAAE,WAAWC,EAAU,OAAO;CACtD,CACmB,CAAA,CAAQ,oBAAoBH,CAAc,GAEzDI,IAAU,IACVC,IAAS;CAMb,AAJkBJ,EACf,sBAAsB,CAAC,CACvB,MAAM,MAAMK,EAAE,wBAAwB,MAAM,cAE1C,MACHL,EAAW,wBAAwB,GAAG;EACpC,cAAc,CAAC,SAAS;EACxB,iBAAiB;CACnB,CAAC,GACD,IAAU;CAOZ,IAAMM,IAJmBN,EACtB,qBAAqBO,EAAW,cAAc,CAAC,CAC/C,MAAM,MAAOC,EAAG,cAAc,CAAC,CAAC,QAAQ,MAAM,cAE/B,CAAA,EAAkB,aAAa,CAAC,GAAG,IAC/CC,IACJH,GAAW,QAAQ,MAAMC,EAAW,0BAC/BD,IACD;CAEN,IAAI,CAACG,GACH,IAAS;MACJ;EACL,IAAMC,IAAcD,EAAU,YAAY,SAAS;EACnD,IAAI,CAACC,GAKH,AAJAD,EAAU,sBAAsB;GAC9B,MAAM;GACN,aAAa;EACf,CAAC,GACD,IAAU;OACL,IAAIC,EAAY,QAAQ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E,EAAqBwE,CAAU,CAAC,CAAC,GAE5Ec,EAAO,KAAK,uCAAuC;CACnD,IAAMM,IAAuB;EAC3B1F,EAAK,KAAKsF,EAAQ,MAAM,OAAO,UAAU,YAAY,oBAAoB;EACzEtF,EAAK,KAAKsF,EAAQ,MAAM,OAAO,UAAU,oBAAoB;EAC7DtF,EAAK,KAAKsF,EAAQ,MAAM,OAAO,UAAU,YAAY,gBAAgB;EACrEtF,EAAK,KAAKsF,EAAQ,MAAM,OAAO,UAAU,gBAAgB;CAC3D,GACMjB,IAAKsB,EAAUL,CAAO,GAGtBM,IACJF,EAAqB,MAAM,MAAM3F,EAAG,WAAW8F,CAAC,CAAC,MAChDxB,MAAO,UAAUqB,EAAqB,KAAKA,EAAqB;CAQnE,AAPAF,EACEhG,EACEoG,GACAzB,EAA+ByB,GAAgBvB,CAAE,CACnD,CACF,GAEAe,EAAO,KAAK,qBAAqB;CACjC,IAAM9B,IAAgBtD,EAAK,KAAKsF,EAAQ,MAAM,YAAY;CAC1D,EACE9F,EAAoB8D,GAAeD,EAAgBC,CAAa,CAAC,CACnE;CAEA,IAAMwC,IAAUf,GAAmBO,EAAQ,MAAMjB,CAAE;CAGnD,OAFIyB,KAASV,EAAO,KAAK,2CAA2C,GAE7D;EACL,SAASU,IAAU,CAACA,CAAO,IAAI,CAAC;EAChC;EACA,SAAS,CAAC;EACV,YAAY,CAAC;EACb,UAAU,CAAC;EACX,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAiB,CAAC;CACpB;AACF"}
@@ -2,12 +2,12 @@ import { a as e } from "./util-BLYliuUK.js";
2
2
  import { t } from "./dedent-Gq6Krl4n.js";
3
3
  import { n } from "./logger-CQONztPm.js";
4
4
  import { t as r } from "./pocketbase-DpudAAmd.js";
5
- import { _ as i, o as a, r as o } from "./ts-morph-helpers-Bepc-Es2.js";
6
- import { modifyOutcomeToFile as s } from "./modify-file-DK-tCH9k.js";
7
- import { t as c } from "./svelte-file-B3RfgVdt.js";
8
- import { i as l, n as u, t as d } from "./pocketbase-CgwbH1gI.js";
5
+ import { i, n as a, t as o } from "./pocketbase-B017Cqjq.js";
6
+ import { _ as s, o as c, r as l } from "./ts-morph-helpers-Bepc-Es2.js";
7
+ import { r as u } from "./modify-file-289rStJ2.js";
8
+ import { t as d } from "./svelte-file-Dv5-bl79.js";
9
9
  import { t as f } from "./modify-utils-Cw-on_cL.js";
10
- import { applyCollectionRulePatches as p, createCollectionIdempotent as m } from "./collections-zzZ_HQxB.js";
10
+ import { r as p, t as m } from "./collections-B_DisSfA.js";
11
11
  import h from "node:fs";
12
12
  import g from "node:path";
13
13
  import { Project as _, SyntaxKind as v } from "ts-morph";
@@ -38,13 +38,13 @@ function C(e) {
38
38
  status: "not-found",
39
39
  message: S
40
40
  };
41
- let t = c.fromPath(e);
41
+ let t = d.fromPath(e);
42
42
  return t.hasElement("header") ? t.hasElement("NotificationsBell") ? {
43
43
  status: "success",
44
44
  changed: !1
45
45
  } : (t.modifyScript((e) => {
46
- let { source: t } = i(e, (e) => {
47
- o(e, [{
46
+ let { source: t } = s(e, (e) => {
47
+ l(e, [{
48
48
  defaultImport: "NotificationsBell",
49
49
  moduleSpecifier: "#lib/components/notifications-bell.svelte"
50
50
  }]);
@@ -88,27 +88,27 @@ function D(e) {
88
88
  name: t,
89
89
  initializer: n
90
90
  }));
91
- }, o, s, c = r.getVariableDeclaration("load");
92
- if (c && c.getFirstAncestorByKind(v.VariableStatement)?.hasExportKeyword()) {
93
- let e = c.getInitializerIfKind(v.ArrowFunction);
94
- if (e) o = e;
91
+ }, a, o, s = r.getVariableDeclaration("load");
92
+ if (s && s.getFirstAncestorByKind(v.VariableStatement)?.hasExportKeyword()) {
93
+ let e = s.getInitializerIfKind(v.ArrowFunction);
94
+ if (e) a = e;
95
95
  else {
96
- let e = c.getInitializer();
96
+ let e = s.getInitializer();
97
97
  if (e) {
98
98
  let t = e.getFirstDescendantByKind(v.ArrowFunction);
99
- if (t) o = t;
99
+ if (t) a = t;
100
100
  else {
101
101
  let t = e.getFirstDescendantByKind(v.FunctionExpression);
102
- t && (s = t);
102
+ t && (o = t);
103
103
  }
104
104
  }
105
105
  }
106
106
  }
107
- if (!o && !s) {
107
+ if (!a && !o) {
108
108
  let e = r.getFunction("load");
109
- e && e.isExported() && (s = e);
109
+ e && e.isExported() && (o = e);
110
110
  }
111
- if (!o && !s) return r.addFunction({
111
+ if (!a && !o) return r.addFunction({
112
112
  isExported: !0,
113
113
  isAsync: !0,
114
114
  name: "load",
@@ -119,11 +119,11 @@ function D(e) {
119
119
  E,
120
120
  "return { notifications };"
121
121
  ]
122
- }), a(r), r.saveSync(), {
122
+ }), c(r), r.saveSync(), {
123
123
  status: "success",
124
124
  changed: !0
125
125
  };
126
- let l = o ?? s, u = l.getParameters();
126
+ let l = a ?? o, u = l.getParameters();
127
127
  if (u.length === 0) l.insertParameter(0, { name: "{ locals, depends }" });
128
128
  else {
129
129
  let e = u[0], t = e.getStructure(), n = e.getNameNode();
@@ -150,7 +150,7 @@ function D(e) {
150
150
  });
151
151
  }
152
152
  }
153
- o && !o.isAsync() ? o.setIsAsync(!0) : s && !s.isAsync() && s.setIsAsync(!0);
153
+ a && !a.isAsync() ? a.setIsAsync(!0) : o && !o.isAsync() && o.setIsAsync(!0);
154
154
  let d = l.getBody();
155
155
  if (d && d.getKind() === v.Block) {
156
156
  let e = d, t = e.getStatements(), n = (e) => t.some((t) => t.getKind() === v.VariableStatement && t.getDeclarations().some((t) => t.getName() === e)), r = t.some((e) => e.getKind() === v.ExpressionStatement && e.getDescendantsOfKind(v.CallExpression).some((e) => {
@@ -174,8 +174,8 @@ function D(e) {
174
174
  }
175
175
  });
176
176
  };
177
- if (o) {
178
- let e = o.getBody();
177
+ if (a) {
178
+ let e = a.getBody();
179
179
  if (e.getKind() === v.Block) p(e);
180
180
  else {
181
181
  let t = e;
@@ -184,11 +184,11 @@ function D(e) {
184
184
  e.getKind() === v.ObjectLiteralExpression && f(e);
185
185
  } else t.getKind() === v.ObjectLiteralExpression && f(t);
186
186
  }
187
- } else if (s) {
188
- let e = s.getBody();
187
+ } else if (o) {
188
+ let e = o.getBody();
189
189
  e && p(e);
190
190
  }
191
- return a(r), r.saveSync(), {
191
+ return c(r), r.saveSync(), {
192
192
  status: "success",
193
193
  changed: r.getFullText() !== n
194
194
  };
@@ -197,19 +197,19 @@ function D(e) {
197
197
  //#region src/patterns/enable/notifications/generate.runtime.ts
198
198
  async function O(t, n, r, i = !0) {
199
199
  if (!i) return;
200
- await u();
201
- let a = d(n, "created", r);
202
- a && t.push({
203
- path: a,
204
- language: e(a),
205
- content: h.readFileSync(a, "utf8"),
200
+ await a();
201
+ let s = o(n, "created", r);
202
+ s && t.push({
203
+ path: s,
204
+ language: e(s),
205
+ content: h.readFileSync(s, "utf8"),
206
206
  status: "success"
207
207
  });
208
208
  }
209
209
  async function k(e) {
210
- let t = n(e), i = [];
211
- await l(e.root, async (n) => {
212
- let a = await n.collections.getOne("users"), o = (e) => m(n, e, t);
210
+ let t = n(e), a = [];
211
+ await i(e.root, async (n) => {
212
+ let i = await n.collections.getOne("users"), o = (e) => p(n, e, t);
213
213
  t.info("Creating notifications collection");
214
214
  let s = await o({
215
215
  name: "notifications",
@@ -229,7 +229,7 @@ async function k(e) {
229
229
  name: "user",
230
230
  type: "relation",
231
231
  cascadeDelete: !0,
232
- collectionId: a.id,
232
+ collectionId: i.id,
233
233
  maxSelect: 1,
234
234
  minSelect: 0,
235
235
  required: !0
@@ -262,22 +262,22 @@ async function k(e) {
262
262
  ],
263
263
  indexes: ["CREATE INDEX `idx_notifications_user_read_created` ON `notifications` (`user`, `read`, `created` DESC)"]
264
264
  });
265
- await O(i, "notifications", e, s.created), t.info("Applying notifications rule patches");
266
- let c = await p(n, r, e, t);
267
- i.push(...c);
265
+ await O(a, "notifications", e, s.created), t.info("Applying notifications rule patches");
266
+ let c = await m(n, r, e, t);
267
+ a.push(...c);
268
268
  });
269
- let a = [], o = (e) => {
270
- e && a.push(e);
269
+ let o = [], s = (e) => {
270
+ e && o.push(e);
271
271
  };
272
272
  t.info("Modifying (app) +layout.svelte");
273
273
  let c = g.join(e.root, "src", "routes", "(app)", "+layout.svelte");
274
- o(s(c, C(c))), t.info("Modifying (app) +layout.server.ts");
275
- let u = g.join(e.root, "src", "routes", "(app)", "+layout.server.ts");
276
- o(s(u, D(u))), t.info("Modifying utils.ts");
274
+ s(u(c, C(c))), t.info("Modifying (app) +layout.server.ts");
275
+ let l = g.join(e.root, "src", "routes", "(app)", "+layout.server.ts");
276
+ s(u(l, D(l))), t.info("Modifying utils.ts");
277
277
  let d = g.join(e.root, "src", "lib", "utils.ts");
278
- return o(s(d, f(d))), {
279
- creates: i,
280
- modifies: a,
278
+ return s(u(d, f(d))), {
279
+ creates: a,
280
+ modifies: o,
281
281
  deletes: [],
282
282
  components: [],
283
283
  packages: [],
@@ -289,4 +289,4 @@ async function k(e) {
289
289
  //#endregion
290
290
  export { k as generate };
291
291
 
292
- //# sourceMappingURL=generate.runtime-koQxLywh.js.map
292
+ //# sourceMappingURL=generate.runtime-DeniHg8L.js.map