@velastack/patterns 0.2.7 → 0.2.9

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 (78) hide show
  1. package/README.md +15 -0
  2. package/dist/chunks/{collections-B3lAtPlQ.js → collections-DDYlpDNO.js} +38 -22
  3. package/dist/chunks/collections-DDYlpDNO.js.map +1 -0
  4. package/dist/chunks/constants-DSFKQwtP.js +6 -0
  5. package/dist/chunks/{constants-PBCzh8eY.js.map → constants-DSFKQwtP.js.map} +1 -1
  6. package/dist/chunks/dispatch-B5PfQ2CA.js +6 -0
  7. package/dist/chunks/dispatch-B5PfQ2CA.js.map +1 -0
  8. package/dist/chunks/{generate.runtime-BKb9thdE.js → generate.runtime-AjCpCfv3.js} +2 -2
  9. package/dist/chunks/{generate.runtime-BKb9thdE.js.map → generate.runtime-AjCpCfv3.js.map} +1 -1
  10. package/dist/chunks/{generate.runtime-DCvLLO7w.js → generate.runtime-B6kxV3Bi.js} +67 -124
  11. package/dist/chunks/generate.runtime-B6kxV3Bi.js.map +1 -0
  12. package/dist/chunks/{generate.runtime-CXXwLatT.js → generate.runtime-BYJZB1ad.js} +2 -2
  13. package/dist/chunks/{generate.runtime-CXXwLatT.js.map → generate.runtime-BYJZB1ad.js.map} +1 -1
  14. package/dist/chunks/{generate.runtime-BsuyMwoj.js → generate.runtime-B_Fk1Jjs.js} +2 -2
  15. package/dist/chunks/{generate.runtime-BsuyMwoj.js.map → generate.runtime-B_Fk1Jjs.js.map} +1 -1
  16. package/dist/chunks/{generate.runtime-BjULAL3h.js → generate.runtime-BcVAKzoY.js} +3 -3
  17. package/dist/chunks/{generate.runtime-BjULAL3h.js.map → generate.runtime-BcVAKzoY.js.map} +1 -1
  18. package/dist/chunks/{generate.runtime-Dc98DCsh.js → generate.runtime-BgezGu15.js} +3 -3
  19. package/dist/chunks/{generate.runtime-Dc98DCsh.js.map → generate.runtime-BgezGu15.js.map} +1 -1
  20. package/dist/chunks/{generate.runtime-BdTCMGGB.js → generate.runtime-BpYOznG5.js} +3 -3
  21. package/dist/chunks/{generate.runtime-BdTCMGGB.js.map → generate.runtime-BpYOznG5.js.map} +1 -1
  22. package/dist/chunks/{generate.runtime-DKJaYtVZ.js → generate.runtime-BtX_9lLk.js} +42 -66
  23. package/dist/chunks/generate.runtime-BtX_9lLk.js.map +1 -0
  24. package/dist/chunks/{generate.runtime-lqPPXQyS.js → generate.runtime-CTiJEVF2.js} +4 -4
  25. package/dist/chunks/{generate.runtime-lqPPXQyS.js.map → generate.runtime-CTiJEVF2.js.map} +1 -1
  26. package/dist/chunks/{generate.runtime-BlQ1vx8j.js → generate.runtime-CZQoVNt3.js} +97 -138
  27. package/dist/chunks/generate.runtime-CZQoVNt3.js.map +1 -0
  28. package/dist/chunks/{generate.runtime-B9gdCz4t.js → generate.runtime-Cq1gqxzg.js} +2 -2
  29. package/dist/chunks/{generate.runtime-B9gdCz4t.js.map → generate.runtime-Cq1gqxzg.js.map} +1 -1
  30. package/dist/chunks/{generate.runtime-FMYR64DL.js → generate.runtime-CycY6kPr.js} +3 -3
  31. package/dist/chunks/{generate.runtime-FMYR64DL.js.map → generate.runtime-CycY6kPr.js.map} +1 -1
  32. package/dist/chunks/{generate.runtime-CGkVUKvz.js → generate.runtime-D2WfvXm2.js} +2 -2
  33. package/dist/chunks/{generate.runtime-CGkVUKvz.js.map → generate.runtime-D2WfvXm2.js.map} +1 -1
  34. package/dist/chunks/{generate.runtime-4Iplvp8f.js → generate.runtime-DEl6b1Ti.js} +2 -2
  35. package/dist/chunks/{generate.runtime-4Iplvp8f.js.map → generate.runtime-DEl6b1Ti.js.map} +1 -1
  36. package/dist/chunks/{generate.runtime-Wssys8A0.js → generate.runtime-DH9o-888.js} +18 -18
  37. package/dist/chunks/generate.runtime-DH9o-888.js.map +1 -0
  38. package/dist/chunks/{generate.runtime-kH6XaWQz.js → generate.runtime-DHRCNPVx.js} +3 -3
  39. package/dist/chunks/{generate.runtime-kH6XaWQz.js.map → generate.runtime-DHRCNPVx.js.map} +1 -1
  40. package/dist/chunks/{generate.runtime-BltGUllM.js → generate.runtime-DK7iXmAZ.js} +3 -3
  41. package/dist/chunks/{generate.runtime-BltGUllM.js.map → generate.runtime-DK7iXmAZ.js.map} +1 -1
  42. package/dist/chunks/{generate.runtime-tAbxWeq-.js → generate.runtime-DRcq4d5D.js} +4 -4
  43. package/dist/chunks/{generate.runtime-tAbxWeq-.js.map → generate.runtime-DRcq4d5D.js.map} +1 -1
  44. package/dist/chunks/{generate.runtime-C-Val7lP.js → generate.runtime-Dmwhwgji.js} +3 -3
  45. package/dist/chunks/{generate.runtime-C-Val7lP.js.map → generate.runtime-Dmwhwgji.js.map} +1 -1
  46. package/dist/chunks/generate.runtime-Dtf2BI_5.js +87 -0
  47. package/dist/chunks/generate.runtime-Dtf2BI_5.js.map +1 -0
  48. package/dist/chunks/{generate.runtime-DWeiewRj.js → generate.runtime-OjW1XETW.js} +3 -3
  49. package/dist/chunks/{generate.runtime-DWeiewRj.js.map → generate.runtime-OjW1XETW.js.map} +1 -1
  50. package/dist/chunks/{generate.runtime-QmFJI7G1.js → generate.runtime-vTneb2SY.js} +4 -4
  51. package/dist/chunks/{generate.runtime-QmFJI7G1.js.map → generate.runtime-vTneb2SY.js.map} +1 -1
  52. package/dist/chunks/nav-user-BYI-h8Od.js +6 -0
  53. package/dist/chunks/nav-user-BYI-h8Od.js.map +1 -0
  54. package/dist/chunks/{pocketbase-059B1oot.js → pocketbase-BerjVikJ.js} +2 -2
  55. package/dist/chunks/{pocketbase-059B1oot.js.map → pocketbase-BerjVikJ.js.map} +1 -1
  56. package/dist/chunks/{shared--_BWnGsc.js → shared-Cmbzu7Od.js} +2 -2
  57. package/dist/chunks/{shared--_BWnGsc.js.map → shared-Cmbzu7Od.js.map} +1 -1
  58. package/dist/chunks/{taggedTemplateLiteral-CPUMuLtk.js → taggedTemplateLiteral-Dx0fjWiw.js} +1 -1
  59. package/dist/chunks/{ts-morph-helpers-Bf5iuQW8.js → ts-morph-helpers-teS3yXg-.js} +2 -2
  60. package/dist/chunks/{ts-morph-helpers-Bf5iuQW8.js.map → ts-morph-helpers-teS3yXg-.js.map} +1 -1
  61. package/dist/chunks/{ui-BsG60gQg.js → ui-BdkuOXPw.js} +2 -2
  62. package/dist/chunks/{ui-BsG60gQg.js.map → ui-BdkuOXPw.js.map} +1 -1
  63. package/dist/chunks/{write-result-BN7Ff0rF.js → write-result-BVWPlGvE.js} +9 -9
  64. package/dist/chunks/{write-result-BN7Ff0rF.js.map → write-result-BVWPlGvE.js.map} +1 -1
  65. package/dist/index.d.ts +218 -64
  66. package/dist/index.js +2186 -1702
  67. package/dist/index.js.map +1 -1
  68. package/package.json +3 -3
  69. package/dist/chunks/_server-BSm1eAiY.js +0 -6
  70. package/dist/chunks/_server-BSm1eAiY.js.map +0 -1
  71. package/dist/chunks/collections-B3lAtPlQ.js.map +0 -1
  72. package/dist/chunks/constants-PBCzh8eY.js +0 -6
  73. package/dist/chunks/generate.runtime-BlQ1vx8j.js.map +0 -1
  74. package/dist/chunks/generate.runtime-DCvLLO7w.js.map +0 -1
  75. package/dist/chunks/generate.runtime-DKJaYtVZ.js.map +0 -1
  76. package/dist/chunks/generate.runtime-Wssys8A0.js.map +0 -1
  77. package/dist/chunks/nav-user-CndUO69x.js +0 -6
  78. package/dist/chunks/nav-user-CndUO69x.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"generate.runtime-QmFJI7G1.js","names":[],"sources":["../../src/patterns/enable/teams/modifies/modify-app-layout.ts","../../src/patterns/enable/teams/modifies/modify-app-sidebar.ts","../../src/patterns/enable/teams/modifies/+layout.server.ts","../../src/patterns/enable/teams/modifies/modify-nav-user.ts","../../src/patterns/enable/teams/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst FAILURE_HINT = [\n \"Pass team props to <AppSidebar> in your app layout:\",\n \"\",\n \"<AppSidebar team={data.team} teams={data.teams ?? []} />\",\n].join(\"\\n\");\n\nconst NOT_FOUND_HINT = [\n \"Create an app layout that renders <AppSidebar> with team props:\",\n \"\",\n \"<AppSidebar team={data.team} teams={data.teams ?? []} />\",\n].join(\"\\n\");\n\nexport function modifyAppLayoutSvelte(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(\"AppSidebar\")) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n if (file.hasAttribute(\"AppSidebar\", \"teams\")) {\n return { status: \"success\", changed: false };\n }\n\n file.appendToAttributes(\n \"AppSidebar\",\n \" team={data.team} teams={data.teams ?? []}\",\n );\n file.writeTo(layoutPath);\n return { status: \"success\", changed: file.hasChanged() };\n}\n","import fs from \"node:fs\";\nimport { SyntaxKind } from \"ts-morph\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport {\n ensureImports,\n withInMemoryScript,\n} from \"../../../../runtime/ts-morph-helpers\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst NEW_HEADER = `<Sidebar.Header>\n\t\t<Sidebar.Menu>\n\t\t\t<TeamSwitcher {teams}>\n\t\t\t\t{#snippet children()}\n\t\t\t\t\t{@const activeTeam = teams.find((t) => t.id === team)}\n\t\t\t\t\t{#if activeTeam}\n\t\t\t\t\t\t<Avatar.Root class=\"size-8 rounded-lg\">\n\t\t\t\t\t\t\t<Avatar.Fallback class=\"rounded-lg bg-primary text-primary-foreground font-medium\">\n\t\t\t\t\t\t\t\t{activeTeam.name?.charAt(0).toUpperCase()}\n\t\t\t\t\t\t\t</Avatar.Fallback>\n\t\t\t\t\t\t</Avatar.Root>\n\t\t\t\t\t\t<div class=\"grid flex-1 text-left text-sm leading-tight\">\n\t\t\t\t\t\t\t<span class=\"truncate font-medium\">\n\t\t\t\t\t\t\t\t{activeTeam.name}\n\t\t\t\t\t\t\t</span>\n\t\t\t\t\t\t</div>\n\t\t\t\t\t{:else}\n\t\t\t\t\t\t<div\n\t\t\t\t\t\t\tclass=\"bg-sidebar-accent text-sidebar-primary-foreground flex aspect-square size-8 items-center justify-center rounded-lg\"\n\t\t\t\t\t\t>\n\t\t\t\t\t\t\t<img src={favicon} alt=\"logo\" class=\"size-6\" />\n\t\t\t\t\t\t</div>\n\t\t\t\t\t\t<div class=\"grid flex-1 text-left text-sm leading-tight\">\n\t\t\t\t\t\t\t<span class=\"truncate font-medium\">{meta.appName}</span>\n\t\t\t\t\t\t</div>\n\t\t\t\t\t{/if}\n\t\t\t\t\t<ChevronsUpDownIcon class=\"ml-auto\" />\n\t\t\t\t{/snippet}\n\t\t\t</TeamSwitcher>\n\t\t</Sidebar.Menu>\n\t</Sidebar.Header>`;\n\nconst IMPORT_SNIPPET = [\n \"import favicon from '$lib/assets/favicon.svg';\",\n \"import TeamSwitcher from '$lib/components/team-switcher.svelte';\",\n \"import ChevronsUpDownIcon from '@lucide/svelte/icons/chevrons-up-down';\",\n \"import * as Avatar from '$lib/components/ui/avatar';\",\n].join(\"\\n\");\n\nconst FAILURE_HINT = [\n \"Replace the <Sidebar.Header> in your app sidebar with the team switcher.\",\n \"\",\n \"Imports to add to the <script> tag:\",\n \"\",\n IMPORT_SNIPPET,\n \"\",\n \"Props to destructure in $props(): team, teams = []\",\n \"\",\n \"Markup to use as the header:\",\n NEW_HEADER,\n].join(\"\\n\");\n\nconst NOT_FOUND_HINT = [\n \"Create an app sidebar with a <Sidebar.Header> containing the team switcher.\",\n \"\",\n \"Imports:\",\n \"\",\n IMPORT_SNIPPET,\n \"\",\n \"Header markup:\",\n NEW_HEADER,\n].join(\"\\n\");\n\nfunction updateAppSidebarScript(source: string): string {\n const { source: out } = withInMemoryScript(source, (sf) => {\n ensureImports(sf, [\n {\n defaultImport: \"favicon\",\n moduleSpecifier: \"$lib/assets/favicon.svg\",\n },\n {\n defaultImport: \"TeamSwitcher\",\n moduleSpecifier: \"$lib/components/team-switcher.svelte\",\n },\n {\n defaultImport: \"ChevronsUpDownIcon\",\n moduleSpecifier: \"@lucide/svelte/icons/chevrons-up-down\",\n },\n {\n namespaceImport: \"Avatar\",\n moduleSpecifier: \"$lib/components/ui/avatar\",\n },\n ]);\n\n for (const decl of sf.getVariableDeclarations()) {\n const init = decl.getInitializer();\n if (!init || init.getText() !== \"$props()\") continue;\n\n const nameNode = decl.getNameNode();\n if (nameNode.getKind() !== SyntaxKind.ObjectBindingPattern) continue;\n\n const pattern = nameNode.asKindOrThrow(SyntaxKind.ObjectBindingPattern);\n const elements = pattern.getElements();\n\n if (elements.some((e) => e.getName() === \"team\")) continue;\n\n // Type changes first — name change can shift positions and invalidate type node refs.\n const typeNode = decl.getTypeNode();\n if (typeNode?.getKind() === SyntaxKind.IntersectionType) {\n const intersection = typeNode.asKindOrThrow(\n SyntaxKind.IntersectionType,\n );\n for (const member of intersection.getTypeNodes()) {\n if (member.getKind() !== SyntaxKind.TypeLiteral) continue;\n const lit = member.asKindOrThrow(SyntaxKind.TypeLiteral);\n const propTexts = lit\n .getProperties()\n .map((p) => p.getText().replace(/[;,]\\s*$/, \"\"));\n if (propTexts.some((t) => /^team\\b/.test(t))) break;\n propTexts.push(\n \"team?: string | undefined\",\n \"teams?: { id: string; name: string }[]\",\n );\n lit.replaceWithText(`{ ${propTexts.join(\"; \")}; }`);\n break;\n }\n }\n\n // Rebuild binding pattern: insert team, teams = [] before first rest/initializer element.\n const elementTexts = elements.map((e) => e.getText());\n let insertIdx = elements.findIndex(\n (e) => e.getDotDotDotToken() || e.getInitializer(),\n );\n if (insertIdx === -1) insertIdx = elements.length;\n elementTexts.splice(insertIdx, 0, \"team\", \"teams = []\");\n pattern.replaceWithText(`{ ${elementTexts.join(\", \")} }`);\n }\n sf.formatText();\n });\n return out;\n}\n\nexport function modifyAppSidebar(appSidebarPath: string): ModifyOutcome {\n if (!fs.existsSync(appSidebarPath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const file = SvelteFile.fromPath(appSidebarPath);\n if (file.hasElement(\"TeamSwitcher\")) {\n return { status: \"success\", changed: false };\n }\n if (!file.hasElement(\"Sidebar.Header\")) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n file.modifyScript(updateAppSidebarScript);\n file.replaceElement(\"Sidebar.Header\", NEW_HEADER);\n file.writeTo(appSidebarPath);\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\";\n\nexport function modifyLayoutServer(layoutServerPath: string): ModifyOutcome {\n if (!fs.existsSync(layoutServerPath)) {\n const snippet = dedent`\n export const load = async ({ locals, depends }) => {\n const user = locals.pb.authStore.record!;\n const team = locals.team;\n const teams = await locals.pb.collection(\"teams\").getFullList();\n depends(\"app:team\");\n\n const breadcrumbs = [{ title: \"Home\", url: \"/dashboard\" }];\n return { user, team, teams, breadcrumbs };\n };\n `;\n\n fs.writeFileSync(layoutServerPath, snippet);\n return { status: \"success\", changed: true };\n }\n\n const originalSource = fs.readFileSync(layoutServerPath, \"utf8\");\n const project = new Project();\n const sourceFile = project.addSourceFileAtPath(layoutServerPath);\n\n const addProperty = (\n obj: import(\"ts-morph\").ObjectLiteralExpression,\n name: string,\n initializer: string,\n ) => {\n const hasProperty = !!obj.getProperty(name);\n if (!hasProperty) {\n if (name === initializer) {\n obj.addShorthandPropertyAssignment({ name });\n } else {\n obj.addPropertyAssignment({ name, initializer });\n }\n }\n };\n\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 (!loadArrow && !loadFn) {\n sourceFile.addFunction({\n isExported: true,\n isAsync: true,\n name: \"load\",\n parameters: [{ name: \"{ locals, depends }\" }],\n statements: [\n \"const user = locals.pb.authStore.record!;\",\n \"const team = locals.team;\",\n 'const teams = await locals.pb.collection(\"teams\").getFullList();',\n 'depends(\"app:team\");',\n \"\",\n 'const breadcrumbs = [{ title: \"Home\", url: \"/dashboard\" }];',\n \"return { user, team, teams, breadcrumbs };\",\n ],\n });\n sourceFile.formatText();\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n }\n\n const fnLike:\n | import(\"ts-morph\").ArrowFunction\n | import(\"ts-morph\").FunctionDeclaration\n | import(\"ts-morph\").FunctionExpression = (loadArrow ?? loadFn!) as any;\n\n const params = fnLike.getParameters();\n if (params.length === 0) {\n fnLike.insertParameter(0, { name: \"{ locals, depends }\" });\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 hasDepends = obp\n .getElements()\n .some((el) => el.getName() === \"depends\");\n const hasLocals = obp\n .getElements()\n .some((el) => el.getName() === \"locals\");\n\n if (!hasDepends) {\n const parts = obp\n .getElements()\n .map((el) => el.getText())\n .filter(Boolean);\n const tail = parts.length > 0 ? \", \" + parts.join(\", \") : \"\";\n\n if (hasLocals) {\n first.set({\n name: `{ depends${tail} }`,\n type: original.type,\n initializer: (original as any).initializer,\n });\n } else {\n first.set({\n name: `{ locals, depends${tail} }`,\n type: original.type,\n initializer: (original as any).initializer,\n });\n }\n }\n } else {\n const currentName = first.getName();\n if (currentName !== \"locals\") {\n first.set({\n name: `{ locals, depends, ...${currentName} }`,\n type: original.type,\n initializer: (original as any).initializer,\n });\n } else {\n first.set({\n name: `{ locals, depends }`,\n type: original.type,\n initializer: (original as any).initializer,\n });\n }\n }\n }\n\n if (loadArrow && !loadArrow.isAsync()) {\n loadArrow.setIsAsync(true);\n } else if (loadFn && !loadFn.isAsync()) {\n loadFn.setIsAsync(true);\n }\n\n const body = fnLike.getBody();\n if (body && body.getKind() === SyntaxKind.Block) {\n const blockBody = body as import(\"ts-morph\").Block;\n const statements = blockBody.getStatements();\n\n const hasTeam = statements.some(\n (stmt: import(\"ts-morph\").Statement) =>\n stmt.getKind() === SyntaxKind.VariableStatement &&\n stmt\n .getDescendantsOfKind(SyntaxKind.Identifier)\n .some((id: import(\"ts-morph\").Identifier) => id.getText() === \"team\"),\n );\n\n const hasTeams = statements.some(\n (stmt: import(\"ts-morph\").Statement) =>\n stmt.getKind() === SyntaxKind.VariableStatement &&\n stmt\n .getDescendantsOfKind(SyntaxKind.Identifier)\n .some(\n (id: import(\"ts-morph\").Identifier) => id.getText() === \"teams\",\n ),\n );\n\n const hasDependsTeam = statements.some(\n (stmt: import(\"ts-morph\").Statement) =>\n stmt.getKind() === SyntaxKind.ExpressionStatement &&\n stmt\n .getDescendantsOfKind(SyntaxKind.CallExpression)\n .some((ce: import(\"ts-morph\").CallExpression) => {\n const expr = ce.getExpression();\n if (expr.getText() !== \"depends\") return false;\n const args = ce.getArguments();\n const argText = args[0]?.getText() ?? \"\";\n return (\n args.length === 1 &&\n (argText === \"'app:team'\" || argText === '\"app:team\"')\n );\n }),\n );\n\n if (!hasTeam) {\n blockBody.insertStatements(1, \"const team = locals.team;\");\n }\n\n if (!hasTeams) {\n blockBody.insertStatements(\n 2,\n 'const teams = await locals.pb.collection(\"teams\").getFullList();',\n );\n }\n\n if (!hasDependsTeam) {\n blockBody.insertStatements(3, 'depends(\"app:team\");');\n }\n }\n\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 const obj = expr as import(\"ts-morph\").ObjectLiteralExpression;\n addProperty(obj, \"team\", \"team\");\n addProperty(obj, \"teams\", \"teams\");\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 const obj = inner as import(\"ts-morph\").ObjectLiteralExpression;\n addProperty(obj, \"team\", \"team\");\n addProperty(obj, \"teams\", \"teams\");\n }\n }\n });\n } else {\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 const obj = inner as import(\"ts-morph\").ObjectLiteralExpression;\n addProperty(obj, \"team\", \"team\");\n addProperty(obj, \"teams\", \"teams\");\n }\n } else if (bodyExpr.getKind() === SyntaxKind.ObjectLiteralExpression) {\n const obj = bodyExpr as import(\"ts-morph\").ObjectLiteralExpression;\n addProperty(obj, \"team\", \"team\");\n addProperty(obj, \"teams\", \"teams\");\n }\n }\n } else if (loadFn) {\n const fnBody = loadFn.getBody();\n if (fnBody) {\n const returns = fnBody.getDescendantsOfKind(SyntaxKind.ReturnStatement);\n returns.forEach((ret) => {\n const expr = ret.getExpression();\n if (!expr) return;\n if (expr.getKind() === SyntaxKind.ObjectLiteralExpression) {\n const obj = expr as import(\"ts-morph\").ObjectLiteralExpression;\n addProperty(obj, \"team\", \"team\");\n addProperty(obj, \"teams\", \"teams\");\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 const obj = inner as import(\"ts-morph\").ObjectLiteralExpression;\n addProperty(obj, \"team\", \"team\");\n addProperty(obj, \"teams\", \"teams\");\n }\n }\n });\n }\n }\n\n sourceFile.formatText();\n sourceFile.saveSync();\n return {\n status: \"success\",\n changed: sourceFile.getFullText() !== originalSource,\n };\n}\n","import fs from \"node:fs\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport { addNavItemToScript } from \"../../../../runtime/ts-morph-helpers\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst TEAMS_NAV_SNIPPET = [\n \"import UsersIcon from '@lucide/svelte/icons/users';\",\n \"\",\n \"// Add to your navUser array:\",\n \"{ title: 'Teams', url: '/teams', icon: UsersIcon }\",\n].join(\"\\n\");\n\nconst FAILURE_HINT = [\n \"Add a Teams nav item to nav-user.svelte:\",\n \"\",\n TEAMS_NAV_SNIPPET,\n].join(\"\\n\");\n\nconst NOT_FOUND_HINT = [\n \"Create nav-user.svelte with a Teams entry:\",\n \"\",\n TEAMS_NAV_SNIPPET,\n].join(\"\\n\");\n\nexport function addItemToNavUser(\n navUserSnippet: string,\n title: string,\n url: string,\n icon: string,\n iconImportPath: string,\n): { newNavUserSnippet: string; wasAdded: boolean } {\n const file = new SvelteFile(navUserSnippet);\n let wasAdded = false;\n\n const tryAdd = (run: (fn: (s: string) => string) => boolean) => {\n if (wasAdded) return;\n run((source) => {\n const result = addNavItemToScript(\n source,\n title,\n url,\n icon,\n iconImportPath,\n );\n if (result.wasAdded) wasAdded = true;\n return result.source;\n });\n };\n\n tryAdd((fn) => file.modifyModuleScript(fn));\n if (!wasAdded) tryAdd((fn) => file.modifyScript(fn));\n\n return { newNavUserSnippet: file.toString(), wasAdded };\n}\n\nexport function modifyNavUser(navUserPath: string): ModifyOutcome {\n if (!fs.existsSync(navUserPath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const navUserSnippet = fs.readFileSync(navUserPath, \"utf8\");\n if (navUserSnippet.includes(\"/teams\")) {\n return { status: \"success\", changed: false };\n }\n\n const { newNavUserSnippet, wasAdded } = addItemToNavUser(\n navUserSnippet,\n \"Teams\",\n \"/teams\",\n \"UsersIcon\",\n \"@lucide/svelte/icons/users\",\n );\n\n if (!wasAdded) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n fs.writeFileSync(navUserPath, newNavUserSnippet, \"utf8\");\n return { status: \"success\", changed: true };\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport { languageFromPath } from \"../../../core/util\";\nimport {\n applyCollectionRulePatches,\n createCollectionIdempotent,\n} from \"../../../runtime/collections\";\nimport {\n getMigrationFile,\n migrationDelay,\n withPocketbase,\n} from \"../../../runtime/pocketbase\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { modifyAppLayoutSvelte } from \"./modifies/modify-app-layout\";\nimport { modifyAppSidebar } from \"./modifies/modify-app-sidebar\";\nimport { modifyLayoutServer } from \"./modifies/+layout.server\";\nimport { modifyNavUser } from \"./modifies/modify-nav-user\";\nimport { TEAM_RULE_PATCHES } from \"./runtime/pocketbase\";\n\nasync function pushMigrationCreates(\n creates: File[],\n collectionName: string,\n options: Options,\n created = true,\n) {\n if (!created) return;\n // Wait so the next schema op lands in a different PocketBase timestamp second.\n await migrationDelay();\n const migrationFile = getMigrationFile(collectionName, \"created\", options);\n if (!migrationFile) {\n return;\n }\n creates.push({\n path: migrationFile,\n language: languageFromPath(migrationFile),\n content: fs.readFileSync(migrationFile, \"utf8\"),\n status: \"success\",\n });\n}\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const creates: File[] = [];\n\n await withPocketbase(options.root, async (pb) => {\n const userCollection = await pb.collections.getOne(\"users\");\n const create = (spec: Parameters<typeof createCollectionIdempotent>[1]) =>\n createCollectionIdempotent(pb, spec, logger);\n\n logger.info(\"Creating teams collection\");\n const teamsResult = await create({\n name: \"teams\",\n type: \"base\",\n fields: [\n {\n name: \"id\",\n type: \"text\",\n primaryKey: true,\n autogeneratePattern: \"[a-z0-9]{15}\",\n max: 15,\n min: 15,\n pattern: \"^[a-z0-9]+$\",\n required: true,\n },\n {\n name: \"name\",\n type: \"text\",\n required: true,\n },\n {\n name: \"owner\",\n type: \"relation\",\n cascadeDelete: false,\n collectionId: userCollection.id,\n maxSelect: 1,\n minSelect: 0,\n required: true,\n },\n {\n name: \"created\",\n type: \"autodate\",\n onCreate: true,\n onUpdate: false,\n },\n {\n name: \"updated\",\n type: \"autodate\",\n onCreate: true,\n onUpdate: true,\n },\n ],\n });\n const teamsCollection = teamsResult.collection;\n await pushMigrationCreates(creates, \"teams\", options, teamsResult.created);\n\n logger.info(\"Creating team_memberships collection\");\n const teamMembershipsResult = await create({\n name: \"team_memberships\",\n type: \"base\",\n fields: [\n {\n name: \"id\",\n autogeneratePattern: \"[a-z0-9]{15}\",\n max: 15,\n min: 15,\n pattern: \"^[a-z0-9]+$\",\n primaryKey: true,\n required: true,\n type: \"text\",\n },\n {\n name: \"team\",\n cascadeDelete: true,\n collectionId: teamsCollection.id,\n maxSelect: 1,\n minSelect: 0,\n required: true,\n type: \"relation\",\n },\n {\n name: \"user\",\n cascadeDelete: true,\n collectionId: userCollection.id,\n maxSelect: 1,\n minSelect: 0,\n required: true,\n type: \"relation\",\n },\n {\n name: \"role\",\n maxSelect: 1,\n required: true,\n type: \"select\",\n values: [\"owner\", \"admin\", \"member\"],\n },\n {\n name: \"created\",\n onCreate: true,\n onUpdate: false,\n type: \"autodate\",\n },\n {\n name: \"updated\",\n onCreate: true,\n onUpdate: true,\n type: \"autodate\",\n },\n ],\n });\n const teamMembershipsCollection = teamMembershipsResult.collection;\n await pushMigrationCreates(\n creates,\n \"team_memberships\",\n options,\n teamMembershipsResult.created,\n );\n\n logger.info(\"Creating team_users view\");\n const teamUsersResult = await create({\n name: \"team_users\",\n type: \"view\",\n fields: [\n {\n name: \"id\",\n pattern: \"^[a-z0-9]+$\",\n primaryKey: true,\n required: true,\n type: \"text\",\n },\n {\n name: \"email\",\n exceptDomains: null,\n onlyDomains: null,\n required: true,\n type: \"email\",\n },\n {\n name: \"name\",\n max: 255,\n required: false,\n type: \"text\",\n },\n {\n name: \"membership_id\",\n cascadeDelete: false,\n collectionId: teamMembershipsCollection.id,\n maxSelect: 1,\n minSelect: 0,\n required: false,\n type: \"relation\",\n },\n {\n name: \"team\",\n cascadeDelete: true,\n collectionId: teamsCollection.id,\n maxSelect: 1,\n minSelect: 0,\n required: true,\n type: \"relation\",\n },\n {\n name: \"role\",\n maxSelect: 1,\n required: true,\n type: \"select\",\n values: [\"owner\", \"admin\", \"member\"],\n },\n ],\n viewQuery:\n \"select users.id, users.email, users.name, team_memberships.id as membership_id, team_memberships.team, team_memberships.role from users join team_memberships on team_memberships.user = users.id;\",\n });\n await pushMigrationCreates(\n creates,\n \"team_users\",\n options,\n teamUsersResult.created,\n );\n\n logger.info(\"Creating team_invites collection\");\n const teamInvitesResult = await create({\n name: \"team_invites\",\n type: \"base\",\n fields: [\n {\n name: \"id\",\n type: \"text\",\n primaryKey: true,\n autogeneratePattern: \"[a-z0-9]{15}\",\n max: 15,\n min: 15,\n pattern: \"^[a-z0-9]+$\",\n required: true,\n },\n {\n name: \"team\",\n type: \"relation\",\n cascadeDelete: true,\n collectionId: teamsCollection.id,\n maxSelect: 1,\n minSelect: 0,\n required: true,\n },\n {\n name: \"email\",\n type: \"email\",\n required: true,\n },\n {\n name: \"created\",\n onCreate: true,\n onUpdate: false,\n type: \"autodate\",\n },\n {\n name: \"updated\",\n onCreate: true,\n onUpdate: true,\n type: \"autodate\",\n },\n ],\n });\n await pushMigrationCreates(\n creates,\n \"team_invites\",\n options,\n teamInvitesResult.created,\n );\n\n logger.info(\"Creating team_invite_links collection\");\n const teamInviteLinksResult = await create({\n name: \"team_invite_links\",\n type: \"base\",\n fields: [\n {\n name: \"id\",\n autogeneratePattern: \"[a-z0-9]{15}\",\n max: 15,\n min: 15,\n pattern: \"^[a-z0-9]+$\",\n primaryKey: true,\n required: true,\n type: \"text\",\n },\n {\n name: \"team\",\n cascadeDelete: true,\n collectionId: teamsCollection.id,\n maxSelect: 1,\n minSelect: 0,\n required: true,\n type: \"relation\",\n },\n {\n name: \"created\",\n onCreate: true,\n onUpdate: false,\n type: \"autodate\",\n },\n {\n name: \"updated\",\n onCreate: true,\n onUpdate: true,\n type: \"autodate\",\n },\n ],\n indexes: [\n \"CREATE UNIQUE INDEX `idx_9y3Oz1KVzz` ON `team_invite_links` (`team`)\",\n ],\n });\n await pushMigrationCreates(\n creates,\n \"team_invite_links\",\n options,\n teamInviteLinksResult.created,\n );\n\n logger.info(\"Applying team rule patches\");\n const ruleMigrations = await applyCollectionRulePatches(\n pb,\n TEAM_RULE_PATCHES,\n options,\n logger,\n );\n creates.push(...ruleMigrations);\n });\n\n const modifies: File[] = [];\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n logger.info(\"Modifying (app) +layout.server.ts\");\n const layoutServerPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(app)\",\n \"+layout.server.ts\",\n );\n pushResult(\n modifyOutcomeToFile(layoutServerPath, modifyLayoutServer(layoutServerPath)),\n );\n\n logger.info(\"Modifying (app) +layout.svelte\");\n const appLayoutPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(app)\",\n \"+layout.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(appLayoutPath, modifyAppLayoutSvelte(appLayoutPath)),\n );\n\n logger.info(\"Modifying app-sidebar\");\n const appSidebarPath = path.join(\n options.root,\n \"src\",\n \"lib\",\n \"components\",\n \"app-sidebar.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(appSidebarPath, modifyAppSidebar(appSidebarPath)),\n );\n\n logger.info(\"Modifying nav-user\");\n const navUserPath = path.join(\n options.root,\n \"src\",\n \"lib\",\n \"components\",\n \"nav-user.svelte\",\n );\n pushResult(modifyOutcomeToFile(navUserPath, modifyNavUser(navUserPath)));\n\n return {\n creates,\n modifies,\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n } satisfies Result;\n}\n"],"mappings":";;;;;;;;;;;;AAIA,IAAM,IAAe;CACnB;CACA;CACA;AACF,CAAC,CAAC,KAAK,IAAI,GAEL,IAAiB;CACrB;CACA;CACA;AACF,CAAC,CAAC,KAAK,IAAI;AAEX,SAAgB,EAAsB,GAAmC;CACvE,IAAI,CAAC,EAAG,WAAW,CAAU,GAC3B,OAAO;EAAE,QAAQ;EAAa,SAAS;CAAe;CAGxD,IAAM,IAAO,EAAW,SAAS,CAAU;CAa3C,OAZK,EAAK,WAAW,YAAY,IAG7B,EAAK,aAAa,cAAc,OAAO,IAClC;EAAE,QAAQ;EAAW,SAAS;CAAM,KAG7C,EAAK,mBACH,cACA,4CACF,GACA,EAAK,QAAQ,CAAU,GAChB;EAAE,QAAQ;EAAW,SAAS,EAAK,WAAW;CAAE,KAX9C;EAAE,QAAQ;EAAU,SAAS;CAAa;AAYrD;;;AC1BA,IAAM,IAAa,0lCAgCb,IAAiB;CACrB;CACA;CACA;CACA;AACF,CAAC,CAAC,KAAK,IAAI,GAEL,IAAe;CACnB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC,CAAC,KAAK,IAAI,GAEL,IAAiB;CACrB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC,CAAC,KAAK,IAAI;AAEX,SAAS,EAAuB,GAAwB;CACtD,IAAM,EAAE,QAAQ,MAA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C9B;CAEA,EAAO,KAAK,mCAAmC;CAC/C,IAAM,IAAmB,EAAK,KAC5B,EAAQ,MACR,OACA,UACA,SACA,mBACF;CAKA,AAJA,EACE,EAAoB,GAAkB,EAAmB,CAAgB,CAAC,CAC5E,GAEA,EAAO,KAAK,gCAAgC;CAC5C,IAAM,IAAgB,EAAK,KACzB,EAAQ,MACR,OACA,UACA,SACA,gBACF;CAKA,AAJA,EACE,EAAoB,GAAe,EAAsB,CAAa,CAAC,CACzE,GAEA,EAAO,KAAK,uBAAuB;CACnC,IAAM,IAAiB,EAAK,KAC1B,EAAQ,MACR,OACA,OACA,cACA,oBACF;CAKA,AAJA,EACE,EAAoB,GAAgB,EAAiB,CAAc,CAAC,CACtE,GAEA,EAAO,KAAK,oBAAoB;CAChC,IAAM,IAAc,EAAK,KACvB,EAAQ,MACR,OACA,OACA,cACA,iBACF;CAGA,OAFA,EAAW,EAAoB,GAAa,EAAc,CAAW,CAAC,CAAC,GAEhE;EACL;EACA;EACA,SAAS,CAAC;EACV,YAAY,CAAC;EACb,UAAU,CAAC;EACX,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAiB,CAAC;CACpB;AACF"}
1
+ {"version":3,"file":"generate.runtime-vTneb2SY.js","names":[],"sources":["../../src/patterns/enable/teams/modifies/modify-app-layout.ts","../../src/patterns/enable/teams/modifies/modify-app-sidebar.ts","../../src/patterns/enable/teams/modifies/+layout.server.ts","../../src/patterns/enable/teams/modifies/modify-nav-user.ts","../../src/patterns/enable/teams/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst FAILURE_HINT = [\n \"Pass team props to <AppSidebar> in your app layout:\",\n \"\",\n \"<AppSidebar team={data.team} teams={data.teams ?? []} />\",\n].join(\"\\n\");\n\nconst NOT_FOUND_HINT = [\n \"Create an app layout that renders <AppSidebar> with team props:\",\n \"\",\n \"<AppSidebar team={data.team} teams={data.teams ?? []} />\",\n].join(\"\\n\");\n\nexport function modifyAppLayoutSvelte(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(\"AppSidebar\")) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n if (file.hasAttribute(\"AppSidebar\", \"teams\")) {\n return { status: \"success\", changed: false };\n }\n\n file.appendToAttributes(\n \"AppSidebar\",\n \" team={data.team} teams={data.teams ?? []}\",\n );\n file.writeTo(layoutPath);\n return { status: \"success\", changed: file.hasChanged() };\n}\n","import fs from \"node:fs\";\nimport { SyntaxKind } from \"ts-morph\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport {\n ensureImports,\n withInMemoryScript,\n} from \"../../../../runtime/ts-morph-helpers\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst NEW_HEADER = `<Sidebar.Header>\n\t\t<Sidebar.Menu>\n\t\t\t<TeamSwitcher {teams}>\n\t\t\t\t{#snippet children()}\n\t\t\t\t\t{@const activeTeam = teams.find((t) => t.id === team)}\n\t\t\t\t\t{#if activeTeam}\n\t\t\t\t\t\t<Avatar.Root class=\"size-8 rounded-lg\">\n\t\t\t\t\t\t\t<Avatar.Fallback class=\"rounded-lg bg-primary text-primary-foreground font-medium\">\n\t\t\t\t\t\t\t\t{activeTeam.name?.charAt(0).toUpperCase()}\n\t\t\t\t\t\t\t</Avatar.Fallback>\n\t\t\t\t\t\t</Avatar.Root>\n\t\t\t\t\t\t<div class=\"grid flex-1 text-left text-sm leading-tight\">\n\t\t\t\t\t\t\t<span class=\"truncate font-medium\">\n\t\t\t\t\t\t\t\t{activeTeam.name}\n\t\t\t\t\t\t\t</span>\n\t\t\t\t\t\t</div>\n\t\t\t\t\t{:else}\n\t\t\t\t\t\t<div\n\t\t\t\t\t\t\tclass=\"bg-sidebar-accent text-sidebar-primary-foreground flex aspect-square size-8 items-center justify-center rounded-lg\"\n\t\t\t\t\t\t>\n\t\t\t\t\t\t\t<img src={favicon} alt=\"logo\" class=\"size-6\" />\n\t\t\t\t\t\t</div>\n\t\t\t\t\t\t<div class=\"grid flex-1 text-left text-sm leading-tight\">\n\t\t\t\t\t\t\t<span class=\"truncate font-medium\">{meta.appName}</span>\n\t\t\t\t\t\t</div>\n\t\t\t\t\t{/if}\n\t\t\t\t\t<ChevronsUpDownIcon class=\"ml-auto\" />\n\t\t\t\t{/snippet}\n\t\t\t</TeamSwitcher>\n\t\t</Sidebar.Menu>\n\t</Sidebar.Header>`;\n\nconst IMPORT_SNIPPET = [\n \"import favicon from '$lib/assets/favicon.svg';\",\n \"import TeamSwitcher from '$lib/components/team-switcher.svelte';\",\n \"import ChevronsUpDownIcon from '@lucide/svelte/icons/chevrons-up-down';\",\n \"import * as Avatar from '$lib/components/ui/avatar';\",\n].join(\"\\n\");\n\nconst FAILURE_HINT = [\n \"Replace the <Sidebar.Header> in your app sidebar with the team switcher.\",\n \"\",\n \"Imports to add to the <script> tag:\",\n \"\",\n IMPORT_SNIPPET,\n \"\",\n \"Props to destructure in $props(): team, teams = []\",\n \"\",\n \"Markup to use as the header:\",\n NEW_HEADER,\n].join(\"\\n\");\n\nconst NOT_FOUND_HINT = [\n \"Create an app sidebar with a <Sidebar.Header> containing the team switcher.\",\n \"\",\n \"Imports:\",\n \"\",\n IMPORT_SNIPPET,\n \"\",\n \"Header markup:\",\n NEW_HEADER,\n].join(\"\\n\");\n\nfunction updateAppSidebarScript(source: string): string {\n const { source: out } = withInMemoryScript(source, (sf) => {\n ensureImports(sf, [\n {\n defaultImport: \"favicon\",\n moduleSpecifier: \"$lib/assets/favicon.svg\",\n },\n {\n defaultImport: \"TeamSwitcher\",\n moduleSpecifier: \"$lib/components/team-switcher.svelte\",\n },\n {\n defaultImport: \"ChevronsUpDownIcon\",\n moduleSpecifier: \"@lucide/svelte/icons/chevrons-up-down\",\n },\n {\n namespaceImport: \"Avatar\",\n moduleSpecifier: \"$lib/components/ui/avatar\",\n },\n ]);\n\n for (const decl of sf.getVariableDeclarations()) {\n const init = decl.getInitializer();\n if (!init || init.getText() !== \"$props()\") continue;\n\n const nameNode = decl.getNameNode();\n if (nameNode.getKind() !== SyntaxKind.ObjectBindingPattern) continue;\n\n const pattern = nameNode.asKindOrThrow(SyntaxKind.ObjectBindingPattern);\n const elements = pattern.getElements();\n\n if (elements.some((e) => e.getName() === \"team\")) continue;\n\n // Type changes first — name change can shift positions and invalidate type node refs.\n const typeNode = decl.getTypeNode();\n if (typeNode?.getKind() === SyntaxKind.IntersectionType) {\n const intersection = typeNode.asKindOrThrow(\n SyntaxKind.IntersectionType,\n );\n for (const member of intersection.getTypeNodes()) {\n if (member.getKind() !== SyntaxKind.TypeLiteral) continue;\n const lit = member.asKindOrThrow(SyntaxKind.TypeLiteral);\n const propTexts = lit\n .getProperties()\n .map((p) => p.getText().replace(/[;,]\\s*$/, \"\"));\n if (propTexts.some((t) => /^team\\b/.test(t))) break;\n propTexts.push(\n \"team?: string | undefined\",\n \"teams?: { id: string; name: string }[]\",\n );\n lit.replaceWithText(`{ ${propTexts.join(\"; \")}; }`);\n break;\n }\n }\n\n // Rebuild binding pattern: insert team, teams = [] before first rest/initializer element.\n const elementTexts = elements.map((e) => e.getText());\n let insertIdx = elements.findIndex(\n (e) => e.getDotDotDotToken() || e.getInitializer(),\n );\n if (insertIdx === -1) insertIdx = elements.length;\n elementTexts.splice(insertIdx, 0, \"team\", \"teams = []\");\n pattern.replaceWithText(`{ ${elementTexts.join(\", \")} }`);\n }\n sf.formatText();\n });\n return out;\n}\n\nexport function modifyAppSidebar(appSidebarPath: string): ModifyOutcome {\n if (!fs.existsSync(appSidebarPath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const file = SvelteFile.fromPath(appSidebarPath);\n if (file.hasElement(\"TeamSwitcher\")) {\n return { status: \"success\", changed: false };\n }\n if (!file.hasElement(\"Sidebar.Header\")) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n file.modifyScript(updateAppSidebarScript);\n file.replaceElement(\"Sidebar.Header\", NEW_HEADER);\n file.writeTo(appSidebarPath);\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\";\n\nexport function modifyLayoutServer(layoutServerPath: string): ModifyOutcome {\n if (!fs.existsSync(layoutServerPath)) {\n const snippet = dedent`\n export const load = async ({ locals, depends }) => {\n const user = locals.pb.authStore.record!;\n const team = locals.team;\n const teams = await locals.pb.collection(\"teams\").getFullList();\n depends(\"app:team\");\n\n const breadcrumbs = [{ title: \"Home\", url: \"/dashboard\" }];\n return { user, team, teams, breadcrumbs };\n };\n `;\n\n fs.writeFileSync(layoutServerPath, snippet);\n return { status: \"success\", changed: true };\n }\n\n const originalSource = fs.readFileSync(layoutServerPath, \"utf8\");\n const project = new Project();\n const sourceFile = project.addSourceFileAtPath(layoutServerPath);\n\n const addProperty = (\n obj: import(\"ts-morph\").ObjectLiteralExpression,\n name: string,\n initializer: string,\n ) => {\n const hasProperty = !!obj.getProperty(name);\n if (!hasProperty) {\n if (name === initializer) {\n obj.addShorthandPropertyAssignment({ name });\n } else {\n obj.addPropertyAssignment({ name, initializer });\n }\n }\n };\n\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 (!loadArrow && !loadFn) {\n sourceFile.addFunction({\n isExported: true,\n isAsync: true,\n name: \"load\",\n parameters: [{ name: \"{ locals, depends }\" }],\n statements: [\n \"const user = locals.pb.authStore.record!;\",\n \"const team = locals.team;\",\n 'const teams = await locals.pb.collection(\"teams\").getFullList();',\n 'depends(\"app:team\");',\n \"\",\n 'const breadcrumbs = [{ title: \"Home\", url: \"/dashboard\" }];',\n \"return { user, team, teams, breadcrumbs };\",\n ],\n });\n sourceFile.formatText();\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n }\n\n const fnLike:\n | import(\"ts-morph\").ArrowFunction\n | import(\"ts-morph\").FunctionDeclaration\n | import(\"ts-morph\").FunctionExpression = (loadArrow ?? loadFn!) as any;\n\n const params = fnLike.getParameters();\n if (params.length === 0) {\n fnLike.insertParameter(0, { name: \"{ locals, depends }\" });\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 hasDepends = obp\n .getElements()\n .some((el) => el.getName() === \"depends\");\n const hasLocals = obp\n .getElements()\n .some((el) => el.getName() === \"locals\");\n\n if (!hasDepends) {\n const parts = obp\n .getElements()\n .map((el) => el.getText())\n .filter(Boolean);\n const tail = parts.length > 0 ? \", \" + parts.join(\", \") : \"\";\n\n if (hasLocals) {\n first.set({\n name: `{ depends${tail} }`,\n type: original.type,\n initializer: (original as any).initializer,\n });\n } else {\n first.set({\n name: `{ locals, depends${tail} }`,\n type: original.type,\n initializer: (original as any).initializer,\n });\n }\n }\n } else {\n const currentName = first.getName();\n if (currentName !== \"locals\") {\n first.set({\n name: `{ locals, depends, ...${currentName} }`,\n type: original.type,\n initializer: (original as any).initializer,\n });\n } else {\n first.set({\n name: `{ locals, depends }`,\n type: original.type,\n initializer: (original as any).initializer,\n });\n }\n }\n }\n\n if (loadArrow && !loadArrow.isAsync()) {\n loadArrow.setIsAsync(true);\n } else if (loadFn && !loadFn.isAsync()) {\n loadFn.setIsAsync(true);\n }\n\n const body = fnLike.getBody();\n if (body && body.getKind() === SyntaxKind.Block) {\n const blockBody = body as import(\"ts-morph\").Block;\n const statements = blockBody.getStatements();\n\n const hasTeam = statements.some(\n (stmt: import(\"ts-morph\").Statement) =>\n stmt.getKind() === SyntaxKind.VariableStatement &&\n stmt\n .getDescendantsOfKind(SyntaxKind.Identifier)\n .some((id: import(\"ts-morph\").Identifier) => id.getText() === \"team\"),\n );\n\n const hasTeams = statements.some(\n (stmt: import(\"ts-morph\").Statement) =>\n stmt.getKind() === SyntaxKind.VariableStatement &&\n stmt\n .getDescendantsOfKind(SyntaxKind.Identifier)\n .some(\n (id: import(\"ts-morph\").Identifier) => id.getText() === \"teams\",\n ),\n );\n\n const hasDependsTeam = statements.some(\n (stmt: import(\"ts-morph\").Statement) =>\n stmt.getKind() === SyntaxKind.ExpressionStatement &&\n stmt\n .getDescendantsOfKind(SyntaxKind.CallExpression)\n .some((ce: import(\"ts-morph\").CallExpression) => {\n const expr = ce.getExpression();\n if (expr.getText() !== \"depends\") return false;\n const args = ce.getArguments();\n const argText = args[0]?.getText() ?? \"\";\n return (\n args.length === 1 &&\n (argText === \"'app:team'\" || argText === '\"app:team\"')\n );\n }),\n );\n\n if (!hasTeam) {\n blockBody.insertStatements(1, \"const team = locals.team;\");\n }\n\n if (!hasTeams) {\n blockBody.insertStatements(\n 2,\n 'const teams = await locals.pb.collection(\"teams\").getFullList();',\n );\n }\n\n if (!hasDependsTeam) {\n blockBody.insertStatements(3, 'depends(\"app:team\");');\n }\n }\n\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 const obj = expr as import(\"ts-morph\").ObjectLiteralExpression;\n addProperty(obj, \"team\", \"team\");\n addProperty(obj, \"teams\", \"teams\");\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 const obj = inner as import(\"ts-morph\").ObjectLiteralExpression;\n addProperty(obj, \"team\", \"team\");\n addProperty(obj, \"teams\", \"teams\");\n }\n }\n });\n } else {\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 const obj = inner as import(\"ts-morph\").ObjectLiteralExpression;\n addProperty(obj, \"team\", \"team\");\n addProperty(obj, \"teams\", \"teams\");\n }\n } else if (bodyExpr.getKind() === SyntaxKind.ObjectLiteralExpression) {\n const obj = bodyExpr as import(\"ts-morph\").ObjectLiteralExpression;\n addProperty(obj, \"team\", \"team\");\n addProperty(obj, \"teams\", \"teams\");\n }\n }\n } else if (loadFn) {\n const fnBody = loadFn.getBody();\n if (fnBody) {\n const returns = fnBody.getDescendantsOfKind(SyntaxKind.ReturnStatement);\n returns.forEach((ret) => {\n const expr = ret.getExpression();\n if (!expr) return;\n if (expr.getKind() === SyntaxKind.ObjectLiteralExpression) {\n const obj = expr as import(\"ts-morph\").ObjectLiteralExpression;\n addProperty(obj, \"team\", \"team\");\n addProperty(obj, \"teams\", \"teams\");\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 const obj = inner as import(\"ts-morph\").ObjectLiteralExpression;\n addProperty(obj, \"team\", \"team\");\n addProperty(obj, \"teams\", \"teams\");\n }\n }\n });\n }\n }\n\n sourceFile.formatText();\n sourceFile.saveSync();\n return {\n status: \"success\",\n changed: sourceFile.getFullText() !== originalSource,\n };\n}\n","import fs from \"node:fs\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport { addNavItemToScript } from \"../../../../runtime/ts-morph-helpers\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst TEAMS_NAV_SNIPPET = [\n \"import UsersIcon from '@lucide/svelte/icons/users';\",\n \"\",\n \"// Add to your navUser array:\",\n \"{ title: 'Teams', url: '/teams', icon: UsersIcon }\",\n].join(\"\\n\");\n\nconst FAILURE_HINT = [\n \"Add a Teams nav item to nav-user.svelte:\",\n \"\",\n TEAMS_NAV_SNIPPET,\n].join(\"\\n\");\n\nconst NOT_FOUND_HINT = [\n \"Create nav-user.svelte with a Teams entry:\",\n \"\",\n TEAMS_NAV_SNIPPET,\n].join(\"\\n\");\n\nexport function addItemToNavUser(\n navUserSnippet: string,\n title: string,\n url: string,\n icon: string,\n iconImportPath: string,\n): { newNavUserSnippet: string; wasAdded: boolean } {\n const file = new SvelteFile(navUserSnippet);\n let wasAdded = false;\n\n const tryAdd = (run: (fn: (s: string) => string) => boolean) => {\n if (wasAdded) return;\n run((source) => {\n const result = addNavItemToScript(\n source,\n title,\n url,\n icon,\n iconImportPath,\n );\n if (result.wasAdded) wasAdded = true;\n return result.source;\n });\n };\n\n tryAdd((fn) => file.modifyModuleScript(fn));\n if (!wasAdded) tryAdd((fn) => file.modifyScript(fn));\n\n return { newNavUserSnippet: file.toString(), wasAdded };\n}\n\nexport function modifyNavUser(navUserPath: string): ModifyOutcome {\n if (!fs.existsSync(navUserPath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const navUserSnippet = fs.readFileSync(navUserPath, \"utf8\");\n if (navUserSnippet.includes(\"/teams\")) {\n return { status: \"success\", changed: false };\n }\n\n const { newNavUserSnippet, wasAdded } = addItemToNavUser(\n navUserSnippet,\n \"Teams\",\n \"/teams\",\n \"UsersIcon\",\n \"@lucide/svelte/icons/users\",\n );\n\n if (!wasAdded) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n fs.writeFileSync(navUserPath, newNavUserSnippet, \"utf8\");\n return { status: \"success\", changed: true };\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport { languageFromPath } from \"../../../core/util\";\nimport {\n applyCollectionRulePatches,\n createCollectionIdempotent,\n} from \"../../../runtime/collections\";\nimport {\n getMigrationFile,\n migrationDelay,\n withPocketbase,\n} from \"../../../runtime/pocketbase\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { modifyAppLayoutSvelte } from \"./modifies/modify-app-layout\";\nimport { modifyAppSidebar } from \"./modifies/modify-app-sidebar\";\nimport { modifyLayoutServer } from \"./modifies/+layout.server\";\nimport { modifyNavUser } from \"./modifies/modify-nav-user\";\nimport { TEAM_RULE_PATCHES } from \"./runtime/pocketbase\";\n\nasync function pushMigrationCreates(\n creates: File[],\n collectionName: string,\n options: Options,\n created = true,\n) {\n if (!created) return;\n // Wait so the next schema op lands in a different PocketBase timestamp second.\n await migrationDelay();\n const migrationFile = getMigrationFile(collectionName, \"created\", options);\n if (!migrationFile) {\n return;\n }\n creates.push({\n path: migrationFile,\n language: languageFromPath(migrationFile),\n content: fs.readFileSync(migrationFile, \"utf8\"),\n status: \"success\",\n });\n}\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const creates: File[] = [];\n\n await withPocketbase(options.root, async (pb) => {\n const userCollection = await pb.collections.getOne(\"users\");\n const create = (spec: Parameters<typeof createCollectionIdempotent>[1]) =>\n createCollectionIdempotent(pb, spec, logger);\n\n logger.info(\"Creating teams collection\");\n const teamsResult = await create({\n name: \"teams\",\n type: \"base\",\n fields: [\n {\n name: \"id\",\n type: \"text\",\n primaryKey: true,\n autogeneratePattern: \"[a-z0-9]{15}\",\n max: 15,\n min: 15,\n pattern: \"^[a-z0-9]+$\",\n required: true,\n },\n {\n name: \"name\",\n type: \"text\",\n required: true,\n },\n {\n name: \"owner\",\n type: \"relation\",\n cascadeDelete: false,\n collectionId: userCollection.id,\n maxSelect: 1,\n minSelect: 0,\n required: true,\n },\n {\n name: \"created\",\n type: \"autodate\",\n onCreate: true,\n onUpdate: false,\n },\n {\n name: \"updated\",\n type: \"autodate\",\n onCreate: true,\n onUpdate: true,\n },\n ],\n });\n const teamsCollection = teamsResult.collection;\n await pushMigrationCreates(creates, \"teams\", options, teamsResult.created);\n\n logger.info(\"Creating team_memberships collection\");\n const teamMembershipsResult = await create({\n name: \"team_memberships\",\n type: \"base\",\n fields: [\n {\n name: \"id\",\n autogeneratePattern: \"[a-z0-9]{15}\",\n max: 15,\n min: 15,\n pattern: \"^[a-z0-9]+$\",\n primaryKey: true,\n required: true,\n type: \"text\",\n },\n {\n name: \"team\",\n cascadeDelete: true,\n collectionId: teamsCollection.id,\n maxSelect: 1,\n minSelect: 0,\n required: true,\n type: \"relation\",\n },\n {\n name: \"user\",\n cascadeDelete: true,\n collectionId: userCollection.id,\n maxSelect: 1,\n minSelect: 0,\n required: true,\n type: \"relation\",\n },\n {\n name: \"role\",\n maxSelect: 1,\n required: true,\n type: \"select\",\n values: [\"owner\", \"admin\", \"member\"],\n },\n {\n name: \"created\",\n onCreate: true,\n onUpdate: false,\n type: \"autodate\",\n },\n {\n name: \"updated\",\n onCreate: true,\n onUpdate: true,\n type: \"autodate\",\n },\n ],\n });\n const teamMembershipsCollection = teamMembershipsResult.collection;\n await pushMigrationCreates(\n creates,\n \"team_memberships\",\n options,\n teamMembershipsResult.created,\n );\n\n logger.info(\"Creating team_users view\");\n const teamUsersResult = await create({\n name: \"team_users\",\n type: \"view\",\n fields: [\n {\n name: \"id\",\n pattern: \"^[a-z0-9]+$\",\n primaryKey: true,\n required: true,\n type: \"text\",\n },\n {\n name: \"email\",\n exceptDomains: null,\n onlyDomains: null,\n required: true,\n type: \"email\",\n },\n {\n name: \"name\",\n max: 255,\n required: false,\n type: \"text\",\n },\n {\n name: \"membership_id\",\n cascadeDelete: false,\n collectionId: teamMembershipsCollection.id,\n maxSelect: 1,\n minSelect: 0,\n required: false,\n type: \"relation\",\n },\n {\n name: \"team\",\n cascadeDelete: true,\n collectionId: teamsCollection.id,\n maxSelect: 1,\n minSelect: 0,\n required: true,\n type: \"relation\",\n },\n {\n name: \"role\",\n maxSelect: 1,\n required: true,\n type: \"select\",\n values: [\"owner\", \"admin\", \"member\"],\n },\n ],\n viewQuery:\n \"select users.id, users.email, users.name, team_memberships.id as membership_id, team_memberships.team, team_memberships.role from users join team_memberships on team_memberships.user = users.id;\",\n });\n await pushMigrationCreates(\n creates,\n \"team_users\",\n options,\n teamUsersResult.created,\n );\n\n logger.info(\"Creating team_invites collection\");\n const teamInvitesResult = await create({\n name: \"team_invites\",\n type: \"base\",\n fields: [\n {\n name: \"id\",\n type: \"text\",\n primaryKey: true,\n autogeneratePattern: \"[a-z0-9]{15}\",\n max: 15,\n min: 15,\n pattern: \"^[a-z0-9]+$\",\n required: true,\n },\n {\n name: \"team\",\n type: \"relation\",\n cascadeDelete: true,\n collectionId: teamsCollection.id,\n maxSelect: 1,\n minSelect: 0,\n required: true,\n },\n {\n name: \"email\",\n type: \"email\",\n required: true,\n },\n {\n name: \"created\",\n onCreate: true,\n onUpdate: false,\n type: \"autodate\",\n },\n {\n name: \"updated\",\n onCreate: true,\n onUpdate: true,\n type: \"autodate\",\n },\n ],\n });\n await pushMigrationCreates(\n creates,\n \"team_invites\",\n options,\n teamInvitesResult.created,\n );\n\n logger.info(\"Creating team_invite_links collection\");\n const teamInviteLinksResult = await create({\n name: \"team_invite_links\",\n type: \"base\",\n fields: [\n {\n name: \"id\",\n autogeneratePattern: \"[a-z0-9]{15}\",\n max: 15,\n min: 15,\n pattern: \"^[a-z0-9]+$\",\n primaryKey: true,\n required: true,\n type: \"text\",\n },\n {\n name: \"team\",\n cascadeDelete: true,\n collectionId: teamsCollection.id,\n maxSelect: 1,\n minSelect: 0,\n required: true,\n type: \"relation\",\n },\n {\n name: \"created\",\n onCreate: true,\n onUpdate: false,\n type: \"autodate\",\n },\n {\n name: \"updated\",\n onCreate: true,\n onUpdate: true,\n type: \"autodate\",\n },\n ],\n indexes: [\n \"CREATE UNIQUE INDEX `idx_9y3Oz1KVzz` ON `team_invite_links` (`team`)\",\n ],\n });\n await pushMigrationCreates(\n creates,\n \"team_invite_links\",\n options,\n teamInviteLinksResult.created,\n );\n\n logger.info(\"Applying team rule patches\");\n const ruleMigrations = await applyCollectionRulePatches(\n pb,\n TEAM_RULE_PATCHES,\n options,\n logger,\n );\n creates.push(...ruleMigrations);\n });\n\n const modifies: File[] = [];\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n logger.info(\"Modifying (app) +layout.server.ts\");\n const layoutServerPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(app)\",\n \"+layout.server.ts\",\n );\n pushResult(\n modifyOutcomeToFile(layoutServerPath, modifyLayoutServer(layoutServerPath)),\n );\n\n logger.info(\"Modifying (app) +layout.svelte\");\n const appLayoutPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(app)\",\n \"+layout.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(appLayoutPath, modifyAppLayoutSvelte(appLayoutPath)),\n );\n\n logger.info(\"Modifying app-sidebar\");\n const appSidebarPath = path.join(\n options.root,\n \"src\",\n \"lib\",\n \"components\",\n \"app-sidebar.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(appSidebarPath, modifyAppSidebar(appSidebarPath)),\n );\n\n logger.info(\"Modifying nav-user\");\n const navUserPath = path.join(\n options.root,\n \"src\",\n \"lib\",\n \"components\",\n \"nav-user.svelte\",\n );\n pushResult(modifyOutcomeToFile(navUserPath, modifyNavUser(navUserPath)));\n\n return {\n creates,\n modifies,\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n } satisfies Result;\n}\n"],"mappings":";;;;;;;;;;;;AAIA,IAAM,IAAe;CACnB;CACA;CACA;AACF,CAAC,CAAC,KAAK,IAAI,GAEL,IAAiB;CACrB;CACA;CACA;AACF,CAAC,CAAC,KAAK,IAAI;AAEX,SAAgB,EAAsB,GAAmC;CACvE,IAAI,CAAC,EAAG,WAAW,CAAU,GAC3B,OAAO;EAAE,QAAQ;EAAa,SAAS;CAAe;CAGxD,IAAM,IAAO,EAAW,SAAS,CAAU;CAa3C,OAZK,EAAK,WAAW,YAAY,IAG7B,EAAK,aAAa,cAAc,OAAO,IAClC;EAAE,QAAQ;EAAW,SAAS;CAAM,KAG7C,EAAK,mBACH,cACA,4CACF,GACA,EAAK,QAAQ,CAAU,GAChB;EAAE,QAAQ;EAAW,SAAS,EAAK,WAAW;CAAE,KAX9C;EAAE,QAAQ;EAAU,SAAS;CAAa;AAYrD;;;AC1BA,IAAM,IAAa,0lCAgCb,IAAiB;CACrB;CACA;CACA;CACA;AACF,CAAC,CAAC,KAAK,IAAI,GAEL,IAAe;CACnB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC,CAAC,KAAK,IAAI,GAEL,IAAiB;CACrB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC,CAAC,KAAK,IAAI;AAEX,SAAS,EAAuB,GAAwB;CACtD,IAAM,EAAE,QAAQ,MAAQ,EAAmB,IAAS,MAAO;EACzD,EAAc,GAAI;GAChB;IACE,eAAe;IACf,iBAAiB;GACnB;GACA;IACE,eAAe;IACf,iBAAiB;GACnB;GACA;IACE,eAAe;IACf,iBAAiB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gB,CAAC,CAC5E,GAEA,EAAO,KAAK,gCAAgC;CAC5C,IAAM,IAAgB,EAAK,KACzB,EAAQ,MACR,OACA,UACA,SACA,gBACF;CAKA,AAJA,EACE,EAAoB,GAAe,EAAsB,CAAa,CAAC,CACzE,GAEA,EAAO,KAAK,uBAAuB;CACnC,IAAM,IAAiB,EAAK,KAC1B,EAAQ,MACR,OACA,OACA,cACA,oBACF;CAKA,AAJA,EACE,EAAoB,GAAgB,EAAiB,CAAc,CAAC,CACtE,GAEA,EAAO,KAAK,oBAAoB;CAChC,IAAM,IAAc,EAAK,KACvB,EAAQ,MACR,OACA,OACA,cACA,iBACF;CAGA,OAFA,EAAW,EAAoB,GAAa,EAAc,CAAW,CAAC,CAAC,GAEhE;EACL;EACA;EACA,SAAS,CAAC;EACV,YAAY,CAAC;EACb,UAAU,CAAC;EACX,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAiB,CAAC;CACpB;AACF"}
@@ -0,0 +1,6 @@
1
+ //#region src/patterns/enable/payments/creates-app-mode/src/routes/(app)/billing/+page.server.ts?raw
2
+ var e = "import { error } from \"@sveltejs/kit\";\nimport stripe from \"$lib/stripe\";\n\nexport const load = async ({ locals, depends, parent }) => {\n const { user } = await parent();\n depends(\"app:billing\");\n\n let customer;\n try {\n customer = await locals.admin\n .collection(\"stripe_customers\")\n .getFirstListItem(\n locals.admin.filter(\"user = {:user}\", { user: user.id }),\n );\n } catch {\n // The link-stripe-customer workflow started at signup has not finished.\n return { paymentMethods: [], user, billingReady: false };\n }\n\n const stripeCustomer = await stripe.customers.retrieve(customer.id);\n if (stripeCustomer.deleted) {\n return error(400, \"Customer not found\");\n }\n\n const paymentMethods = await stripe.customers.listPaymentMethods(\n customer.id,\n {\n type: \"card\",\n allow_redisplay: \"always\",\n },\n );\n\n return {\n billingReady: true,\n paymentMethods: paymentMethods.data.map((pm) => ({\n id: pm.id,\n brand: pm.card!.brand,\n last4: pm.card!.last4,\n expMonth: pm.card!.exp_month,\n expYear: pm.card!.exp_year,\n isDefault: pm.id === customer.default_payment_method,\n })),\n user,\n };\n};\n\nexport const actions = {\n setDefaultPaymentMethod: async ({ locals, request }) => {\n const formData = await request.formData();\n const paymentMethodId = formData.get(\"paymentMethodId\") as string;\n\n const customer = await locals.admin\n .collection(\"stripe_customers\")\n .getFirstListItem(`user.id = \"${locals.pb.authStore.record?.id}\"`);\n\n if (!customer || !customer.id) {\n return error(400, \"Customer not found\");\n }\n\n await stripe.customers.update(customer.id, {\n invoice_settings: {\n default_payment_method: paymentMethodId,\n },\n });\n\n await locals.admin.collection(\"stripe_customers\").update(customer.id, {\n default_payment_method: paymentMethodId,\n });\n },\n deletePaymentMethod: async ({ locals, request }) => {\n const formData = await request.formData();\n const paymentMethodId = formData.get(\"paymentMethodId\") as string;\n\n const customer = await locals.admin\n .collection(\"stripe_customers\")\n .getFirstListItem(`user.id = \"${locals.pb.authStore.record?.id}\"`);\n\n const defaultPaymentMethod = customer.default_payment_method;\n\n await stripe.paymentMethods.detach(paymentMethodId);\n\n // If default payment method was deleted, update default payment method\n if (defaultPaymentMethod === paymentMethodId) {\n const paymentMethods = await stripe.paymentMethods.list({\n customer: customer.id,\n });\n\n if (paymentMethods.data.length > 0) {\n const defaultPaymentMethod = paymentMethods.data[0];\n\n await stripe.customers.update(customer.id, {\n invoice_settings: {\n default_payment_method: defaultPaymentMethod.id,\n },\n });\n\n await locals.admin.collection(\"stripe_customers\").update(customer.id, {\n default_payment_method: defaultPaymentMethod.id,\n });\n } else {\n await locals.admin.collection(\"stripe_customers\").update(customer.id, {\n default_payment_method: null,\n });\n }\n }\n },\n};\n", t = "<script lang=\"ts\">\n import { Button } from '$lib/components/ui/button';\n import * as Card from '$lib/components/ui/card';\n import { Badge } from '$lib/components/ui/badge';\n import * as AlertDialog from '$lib/components/ui/alert-dialog';\n import SetupButton from '$lib/components/payments/setup-button.svelte';\n import { CreditCard, Trash2, Check } from '@lucide/svelte';\n import { toast } from 'svelte-sonner';\n import { invalidate } from '$app/navigation';\n\n let { data } = $props();\n let paymentMethods = $derived(data.paymentMethods);\n let showDeleteDialog = $state(false);\n let selectedPaymentMethodId = $state<string | null>(null);\n let isProcessing = $state(false);\n\n function openDeleteDialog(paymentMethodId: string) {\n selectedPaymentMethodId = paymentMethodId;\n showDeleteDialog = true;\n }\n\n function closeDeleteDialog() {\n showDeleteDialog = false;\n selectedPaymentMethodId = null;\n }\n\n async function handleDeletePaymentMethod() {\n if (!selectedPaymentMethodId) return;\n isProcessing = true;\n\n try {\n const formData = new FormData();\n formData.append('paymentMethodId', selectedPaymentMethodId);\n\n await fetch('?/deletePaymentMethod', {\n method: 'POST',\n body: formData\n });\n\n await invalidate('app:billing');\n toast.success('Payment method removed successfully');\n closeDeleteDialog();\n } catch (err) {\n console.error('Error deleting payment method:', err);\n toast.error('Failed to remove payment method');\n } finally {\n isProcessing = false;\n }\n }\n\n async function setDefaultPaymentMethod(paymentMethodId: string) {\n try {\n const formData = new FormData();\n formData.append('paymentMethodId', paymentMethodId);\n\n await fetch('?/setDefaultPaymentMethod', {\n method: 'POST',\n body: formData\n });\n\n await invalidate('app:billing');\n toast.success('Default payment method updated');\n } catch (err) {\n console.error('Error setting default payment method:', err);\n toast.error('Failed to update default payment method');\n }\n }\n\n function getCardBrandIcon(brand: string) {\n // You can customize these icons or use actual card brand icons\n const brands: Record<string, string> = {\n visa: '💳',\n mastercard: '💳',\n amex: '💳',\n discover: '💳',\n unknown: '💳'\n };\n return brands[brand.toLowerCase()] || brands.unknown;\n }\n\n function formatCardBrand(brand: string) {\n return brand.charAt(0).toUpperCase() + brand.slice(1);\n }\n<\/script>\n\n<div class=\"divide-y divide-gray-900/10 dark:divide-white/10\">\n <div class=\"grid grid-cols-1 gap-x-8 gap-y-8 py-10 md:grid-cols-3\">\n <div class=\"px-4 sm:px-0\">\n <h2 class=\"text-base/7 font-semibold text-gray-900 dark:text-white\">Payment Methods</h2>\n <p class=\"mt-1 text-sm/6 text-gray-600 dark:text-gray-400\">\n Manage your payment methods for subscriptions and purchases.\n </p>\n </div>\n\n <div class=\"md:col-span-2\">\n <Card.Root>\n <Card.Content>\n {#if !data.billingReady}\n <div\n class=\"text-muted-foreground flex flex-col items-center justify-center py-12 text-center\"\n >\n <CreditCard class=\"mb-4 size-12 opacity-50\" />\n <p class=\"mb-2 text-lg font-medium\">Setting up billing</p>\n <p class=\"text-sm\">This takes a moment after signing up. Refresh to check again.</p>\n </div>\n {:else if paymentMethods.length === 0}\n <div\n class=\"text-muted-foreground flex flex-col items-center justify-center py-12 text-center\"\n >\n <CreditCard class=\"mb-4 size-12 opacity-50\" />\n <p class=\"mb-2 text-lg font-medium\">No payment methods</p>\n <p class=\"text-sm\">Add a payment method to get started</p>\n </div>\n {:else}\n <div class=\"space-y-4\">\n {#each paymentMethods as method (method.id)}\n <div\n class=\"border-border hover:bg-accent/50 flex items-center justify-between rounded-lg border p-4 transition-colors\"\n >\n <div class=\"flex items-center gap-4\">\n <div\n class=\"bg-muted flex size-12 items-center justify-center rounded-lg text-2xl\"\n >\n {getCardBrandIcon(method.brand)}\n </div>\n <div>\n <div class=\"flex items-center gap-2\">\n <p class=\"font-medium\">\n {formatCardBrand(method.brand)} •••• {method.last4}\n </p>\n {#if method.isDefault}\n <Badge variant=\"secondary\">\n <Check class=\"mr-1 size-3\" />\n Default\n </Badge>\n {/if}\n </div>\n <p class=\"text-muted-foreground text-sm\">\n Expires {method.expMonth.toString().padStart(2, '0')}/{method.expYear}\n </p>\n </div>\n </div>\n <div class=\"flex items-center gap-2\">\n {#if !method.isDefault}\n <Button\n variant=\"outline\"\n size=\"sm\"\n onclick={() => setDefaultPaymentMethod(method.id)}\n >\n Set as Default\n </Button>\n {/if}\n <Button\n variant=\"outline\"\n size=\"icon-sm\"\n onclick={() => openDeleteDialog(method.id)}\n disabled={method.isDefault && paymentMethods.length === 1}\n >\n <Trash2 class=\"size-4\" />\n </Button>\n </div>\n </div>\n {/each}\n </div>\n {/if}\n </Card.Content>\n {#if data.billingReady}\n <Card.Footer class=\"border-t justify-end\">\n <SetupButton\n label=\"Add Payment Method\"\n processingLabel=\"Adding...\"\n onsuccess={() => invalidate('app:billing')}\n />\n </Card.Footer>\n {/if}\n </Card.Root>\n </div>\n </div>\n</div>\n\n<!-- Delete Confirmation Dialog -->\n<AlertDialog.Root bind:open={showDeleteDialog}>\n <AlertDialog.Content>\n <AlertDialog.Header>\n <AlertDialog.Title>Remove Payment Method</AlertDialog.Title>\n <AlertDialog.Description>\n Are you sure you want to remove this payment method? This action cannot be undone.\n </AlertDialog.Description>\n </AlertDialog.Header>\n <AlertDialog.Footer>\n <AlertDialog.Cancel onclick={closeDeleteDialog}>Cancel</AlertDialog.Cancel>\n <AlertDialog.Action onclick={handleDeletePaymentMethod} disabled={isProcessing}>\n {isProcessing ? 'Removing...' : 'Remove'}\n </AlertDialog.Action>\n </AlertDialog.Footer>\n </AlertDialog.Content>\n</AlertDialog.Root>\n", n = "<script lang=\"ts\">\n import { toggleMode, mode } from 'mode-watcher';\n import ChevronsUpDownIcon from '@lucide/svelte/icons/chevrons-up-down';\n import Settings2Icon from '@lucide/svelte/icons/settings-2';\n // [!code highlight:1]\n import CreditCardIcon from '@lucide/svelte/icons/credit-card';\n import LogOutIcon from '@lucide/svelte/icons/log-out';\n import MoonIcon from '@lucide/svelte/icons/moon';\n import SunIcon from '@lucide/svelte/icons/sun';\n import * as Avatar from '$lib/components/ui/avatar';\n import * as DropdownMenu from '$lib/components/ui/dropdown-menu';\n import * as Sidebar from '$lib/components/ui/sidebar';\n\n let data = {\n navUser: [\n {\n title: 'Settings',\n url: '/settings',\n icon: Settings2Icon\n },\n // [!code highlight:5]\n {\n title: 'Billing',\n url: '/billing',\n icon: CreditCardIcon\n }\n ]\n };\n\n let {\n user\n }: {\n user: {\n id: string;\n name: string;\n email: string;\n avatar: string;\n };\n } = $props();\n\n const sidebar = Sidebar.useSidebar();\n<\/script>\n\n<Sidebar.Menu>\n <Sidebar.MenuItem>\n <DropdownMenu.Root>\n <DropdownMenu.Trigger>\n {#snippet child({ props })}\n <Sidebar.MenuButton\n size=\"lg\"\n class=\"data-[state=open]:bg-sidebar-accent data-[state=open]:text-sidebar-accent-foreground\"\n {...props}\n >\n <Avatar.Root class=\"size-8 rounded-lg\">\n {#if user.avatar}\n <Avatar.Image src=\"/api/files/users/{user.id}/{user.avatar}\" alt={user.name} />\n {/if}\n <Avatar.Fallback class=\"rounded-lg\">\n {user.name?.charAt(0).toUpperCase() || user.email?.charAt(0).toUpperCase()}\n </Avatar.Fallback>\n </Avatar.Root>\n <div class=\"grid flex-1 text-left text-sm leading-tight\">\n <span class=\"truncate font-medium\">{user.name || user.email}</span>\n </div>\n <ChevronsUpDownIcon class=\"ml-auto size-4\" />\n </Sidebar.MenuButton>\n {/snippet}\n </DropdownMenu.Trigger>\n <DropdownMenu.Content\n class=\"w-(--bits-dropdown-menu-anchor-width) min-w-56 rounded-lg\"\n side={sidebar.isMobile ? 'bottom' : 'right'}\n align=\"end\"\n sideOffset={4}\n >\n <DropdownMenu.Label class=\"p-0 font-normal\">\n <div class=\"flex items-center gap-2 px-1 py-1.5 text-left text-sm\">\n <Avatar.Root class=\"size-8 rounded-lg\">\n {#if user.avatar}\n <Avatar.Image src=\"/api/files/users/{user.id}/{user.avatar}\" alt={user.name} />\n {/if}\n <Avatar.Fallback class=\"rounded-lg\">\n {user.name?.charAt(0).toUpperCase() || user.email?.charAt(0).toUpperCase()}\n </Avatar.Fallback>\n </Avatar.Root>\n <div class=\"grid flex-1 text-left text-sm leading-tight\">\n <span class=\"truncate font-medium\">{user.name || user.email}</span>\n </div>\n </div>\n </DropdownMenu.Label>\n <DropdownMenu.Separator />\n <DropdownMenu.Group>\n <DropdownMenu.Item onclick={toggleMode}>\n {#if mode.current === 'dark'}\n <SunIcon />\n Light mode\n {:else}\n <MoonIcon />\n Dark mode\n {/if}\n </DropdownMenu.Item>\n {#each data.navUser as item}\n <DropdownMenu.Item class=\"p-0\">\n <a href={item.url} class=\"flex cursor-default items-center gap-2 px-2 py-1.5 w-full\">\n <item.icon />\n {item.title}\n </a>\n </DropdownMenu.Item>\n {/each}\n </DropdownMenu.Group>\n <DropdownMenu.Separator />\n <DropdownMenu.Item class=\"p-0\">\n <form action=\"/logout\" method=\"post\" class=\"w-full\">\n <button type=\"submit\" class=\"flex cursor-default items-center gap-2 px-2 py-1.5 w-full\">\n <LogOutIcon />\n Log out\n </button>\n </form>\n </DropdownMenu.Item>\n </DropdownMenu.Content>\n </DropdownMenu.Root>\n </Sidebar.MenuItem>\n</Sidebar.Menu>\n";
3
+ //#endregion
4
+ export { t as n, e as r, n as t };
5
+
6
+ //# sourceMappingURL=nav-user-BYI-h8Od.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"nav-user-BYI-h8Od.js","names":[],"sources":[],"mappings":""}
@@ -1,4 +1,4 @@
1
- import { i as e, n as t } from "./constants-PBCzh8eY.js";
1
+ import { i as e, n as t } from "./constants-DSFKQwtP.js";
2
2
  import n from "node:path";
3
3
  import { existsSync as r, readFileSync as i, readdirSync as a } from "node:fs";
4
4
  import o from "pocketbase";
@@ -225,4 +225,4 @@ function C(e, t) {
225
225
  //#endregion
226
226
  export { y as getMigrationFile, v as migrationDelay, S as withPocketbase };
227
227
 
228
- //# sourceMappingURL=pocketbase-059B1oot.js.map
228
+ //# sourceMappingURL=pocketbase-BerjVikJ.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"pocketbase-059B1oot.js","names":[],"sources":["../../src/runtime/net.ts","../../src/runtime/pocketbase.ts"],"sourcesContent":["import net from \"node:net\";\n\n/**\n * Ports the Fetch spec tells clients to refuse outright\n * (https://fetch.spec.whatwg.org/#port-blocking). Node's `fetch` enforces the\n * list, so a server bound to one of them is unreachable from `waitForHealth`\n * and the PocketBase SDK alike: the request fails with cause \"bad port\"\n * before a connection is even attempted. 10080 sat inside the 10000–19999\n * range ports used to be drawn from, and cost a CI run a 30-second health\n * timeout whenever the draw landed on it.\n */\nexport const BAD_PORTS: ReadonlySet<number> = new Set([\n 1, 7, 9, 11, 13, 15, 17, 19, 20, 21, 22, 23, 25, 37, 42, 43, 53, 69, 77, 79,\n 87, 95, 101, 102, 103, 104, 109, 110, 111, 113, 115, 117, 119, 123, 135, 137,\n 139, 143, 161, 179, 389, 427, 465, 512, 513, 514, 515, 526, 530, 531, 532,\n 540, 548, 554, 556, 563, 587, 601, 636, 989, 990, 993, 995, 1719, 1720, 1723,\n 2049, 3659, 4045, 4190, 5060, 5061, 6000, 6566, 6665, 6666, 6667, 6668, 6669,\n 6679, 6697, 10080,\n]);\n\nfunction osAssignedPort(host: string): Promise<number> {\n return new Promise((resolve, reject) => {\n const server = net.createServer();\n server.unref();\n server.once(\"error\", reject);\n server.listen(0, host, () => {\n const { port } = server.address() as net.AddressInfo;\n server.close(() => resolve(port));\n });\n });\n}\n\n/**\n * A port nothing is listening on right now, taken from the OS's ephemeral\n * range so it neither collides with whatever else the machine runs nor hits\n * `BAD_PORTS`. The port is released again before this resolves, so the\n * caller's server has to bind it promptly.\n */\nexport async function freePort(host: string): Promise<number> {\n for (;;) {\n const port = await osAssignedPort(host);\n if (!BAD_PORTS.has(port)) return port;\n }\n}\n\n// Wait for the port to be available. A cold `npx pocketbase-server` on a CI\n// runner can take well over the five seconds the old default allowed.\nexport function waitForPort(\n port: number,\n host: string,\n maxAttempts = 60,\n): Promise<void> {\n return new Promise((resolve, reject) => {\n let attempts = 0;\n\n const tryConnect = () => {\n attempts++;\n\n const socket = new net.Socket();\n\n const onError = () => {\n socket.destroy();\n\n if (attempts === maxAttempts) {\n reject(\n new Error(`Timed out waiting for port ${port} to be available`),\n );\n return;\n }\n\n setTimeout(tryConnect, 500);\n };\n\n socket.once(\"error\", onError);\n\n socket.connect(port, host, () => {\n socket.destroy();\n resolve();\n });\n };\n\n tryConnect();\n });\n}\n\n/**\n * `fetch` wraps the interesting part in `cause`: an errno error for a\n * connection that was refused, or a bare string such as \"bad port\" for a\n * request undici declined to make.\n */\nfunction describeFetchError(error: unknown): string {\n if (!(error instanceof Error)) return String(error);\n const { cause } = error as Error & { cause?: unknown };\n if (cause instanceof Error) {\n const code = (cause as NodeJS.ErrnoException).code;\n return code || cause.message || error.message;\n }\n if (cause !== undefined) return String(cause);\n return error.message;\n}\n\n// Wait for the health check to be successful\nexport function waitForHealth(url: string, maxAttempts = 60): Promise<void> {\n return new Promise((resolve, reject) => {\n let attempts = 0;\n let lastFailure = \"no attempt made\";\n\n const tryHealth = async () => {\n attempts++;\n\n try {\n const response = await fetch(`${url}/api/health`);\n if (response.status === 200) {\n resolve();\n return;\n }\n lastFailure = `HTTP ${response.status}`;\n } catch (error) {\n lastFailure = describeFetchError(error);\n }\n\n if (attempts === maxAttempts) {\n reject(\n new Error(\n `Timed out waiting for health check at ${url}/api/health (last attempt: ${lastFailure})`,\n ),\n );\n return;\n }\n\n setTimeout(tryHealth, 500);\n };\n\n tryHealth();\n });\n}\n","import { existsSync, readdirSync, readFileSync } from \"node:fs\";\nimport path from \"node:path\";\nimport PocketBase from \"pocketbase\";\nimport { detect } from \"package-manager-detector\";\nimport { resolveCommand } from \"package-manager-detector/commands\";\nimport spawn from \"cross-spawn\";\nimport { freePort, waitForPort, waitForHealth } from \"./net\";\nimport type { Options } from \"../core/types\";\nimport { DATA_DIR, MIGRATIONS_DIR } from \"../core/constants\";\n\n/**\n * PocketBase names migration files with a 1-second-resolution Unix timestamp\n * (e.g. `1776099881_created_users.js`). Two schema operations issued in the\n * same wall-clock second produce files that sort alphabetically by their\n * action/collection suffix — which reverses the intended order whenever a\n * later migration depends on an earlier one. Wait out the full second between\n * migration-producing calls so the timestamps stay distinct.\n */\nconst MIGRATION_DELAY_MS = 1100;\n\nexport function migrationDelay(): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, MIGRATION_DELAY_MS));\n}\n\nexport function getMigrationFile(\n collectionName: string,\n action: \"created\" | \"deleted\" | \"updated\",\n options: Options,\n): string | undefined {\n const ending = `${action}_${collectionName}.js`;\n\n // find last file with ending in migrations dir\n const migrationFiles = readdirSync(\n path.join(options.root, MIGRATIONS_DIR),\n ).filter((file) => file.endsWith(ending));\n\n const migrationFile = migrationFiles.sort().pop();\n\n if (!migrationFile) {\n return undefined;\n }\n\n return path.join(options.root, MIGRATIONS_DIR, migrationFile);\n}\n\nexport function getPocketbaseMetadata(cwd: string): {\n pocketbaseUrl: string;\n vitePort: number;\n} | null {\n const metadataPath = path.join(\n cwd,\n \"node_modules\",\n \".vite\",\n \"_pocketbase_metadata.json\",\n );\n if (existsSync(metadataPath)) {\n return JSON.parse(readFileSync(metadataPath, \"utf8\"));\n }\n return null;\n}\n\nexport async function authWithRetries(\n pb: PocketBase,\n email: string,\n password: string,\n) {\n // Retry authentication up to 3 times with 100ms backoff\n let authSuccess = false;\n for (let attempt = 1; attempt <= 3; attempt++) {\n try {\n await pb.collection(\"_superusers\").authWithPassword(email, password);\n authSuccess = true;\n break;\n } catch {\n if (attempt < 3) {\n await new Promise((resolve) => setTimeout(resolve, 100));\n }\n }\n }\n\n if (!authSuccess) {\n throw new Error(\n \"Failed to authenticate with PocketBase. Check your superuser credentials.\",\n );\n }\n}\n\nexport async function withPocketbase(\n cwd: string,\n fn: (pb: PocketBase) => Promise<void>,\n) {\n const dir = path.join(cwd, DATA_DIR);\n const migrationsDir = path.join(cwd, MIGRATIONS_DIR);\n const host = \"localhost\";\n\n if (!existsSync(dir)) {\n throw new Error(\"PocketBase data directory does not exist\");\n }\n\n // First check if the server is already running by reading node_modules/.vite/_pocketbase_metadata.json\n const metadata = getPocketbaseMetadata(cwd);\n if (metadata) {\n if (metadata.pocketbaseUrl) {\n const pb = new PocketBase(metadata.pocketbaseUrl);\n await authWithRetries(\n pb,\n process.env.POCKETBASE_SUPERUSER_EMAIL!,\n process.env.POCKETBASE_SUPERUSER_PASSWORD!,\n );\n await fn(pb);\n return;\n }\n }\n\n const port = await freePort(host);\n const commandArgs = [\n \"pocketbase-server\",\n \"serve\",\n \"--dir\",\n dir,\n \"--migrationsDir\",\n migrationsDir,\n \"--http\",\n `${host}:${port}`,\n ];\n\n const packageManager = (await detect({ cwd }))?.name ?? \"npm\";\n const { command, args } = resolveCommand(\n packageManager,\n \"execute\",\n commandArgs,\n )!;\n\n // adding --yes as the first parameter helps avoiding the \"Need to install the following packages:\" message\n if (packageManager === \"npm\") args.unshift(\"--yes\");\n\n // Start the PocketBase server process. The package manager wrapper (`npx`)\n // spawns the real binary as a grandchild; put the tree in its own process\n // group so it can be killed as a whole, otherwise `pocketbase serve` outlives\n // us and keeps the data directory open.\n const detached = process.platform !== \"win32\";\n const serverProcess = spawn(command, args, {\n cwd,\n stdio: \"ignore\",\n detached,\n });\n\n // A wrapper that dies before the server listens (missing binary, bad\n // arguments) would otherwise only surface as a port timeout a minute later.\n const exited = new Promise<never>((_, reject) => {\n serverProcess.once(\"exit\", (code, signal) => {\n reject(\n new Error(\n `pocketbase-server exited before listening on ${host}:${port} (${signal ?? `code ${code}`})`,\n ),\n );\n });\n serverProcess.once(\"error\", reject);\n });\n\n try {\n // Wait for the server to be ready\n await Promise.race([\n (async () => {\n await waitForPort(port, host);\n await waitForHealth(`http://${host}:${port}`);\n })(),\n exited,\n ]);\n\n const pb = new PocketBase(`http://${host}:${port}`);\n await authWithRetries(\n pb,\n process.env.POCKETBASE_SUPERUSER_EMAIL!,\n process.env.POCKETBASE_SUPERUSER_PASSWORD!,\n );\n await fn(pb);\n } finally {\n // Ensure we always clean up the process tree\n stopProcessTree(serverProcess, detached);\n }\n}\n\nfunction stopProcessTree(\n child: ReturnType<typeof spawn>,\n detached: boolean,\n): void {\n if (detached && child.pid) {\n try {\n process.kill(-child.pid, \"SIGTERM\");\n return;\n } catch {\n // Group already gone or unsupported; fall through to the plain kill.\n }\n }\n child.kill();\n}\n"],"mappings":";;;;;;;;;AAWA,IAAa,oBAAiC,IAAI,IAAI;CACpD;CAAG;CAAG;CAAG;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAA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I,KAAU,QAAQ,IAAO,EAC5F,CACF;EACF,CAAC,GACD,EAAc,KAAK,SAAS,CAAM;CACpC,CAAC;CAED,IAAI;EAEF,MAAM,QAAQ,KAAK,EAChB,YAAY;GAEX,AADA,MAAM,EAAY,GAAM,CAAI,GAC5B,MAAM,EAAc,UAAU,EAAK,GAAG,GAAM;EAC9C,EAAA,CAAG,GACH,CACF,CAAC;EAED,IAAM,IAAK,IAAI,EAAW,UAAU,EAAK,GAAG,GAAM;EAMlD,AALA,MAAM,EACJ,GACA,QAAQ,IAAI,4BACZ,QAAQ,IAAI,6BACd,GACA,MAAM,EAAG,CAAE;CACb,UAAU;EAER,EAAgB,GAAe,CAAQ;CACzC;AACF;AAEA,SAAS,EACP,GACA,GACM;CACN,IAAI,KAAY,EAAM,KACpB,IAAI;EACF,QAAQ,KAAK,CAAC,EAAM,KAAK,SAAS;EAClC;CACF,QAAQ,CAER;CAEF,EAAM,KAAK;AACb"}
1
+ {"version":3,"file":"pocketbase-BerjVikJ.js","names":[],"sources":["../../src/runtime/net.ts","../../src/runtime/pocketbase.ts"],"sourcesContent":["import net from \"node:net\";\n\n/**\n * Ports the Fetch spec tells clients to refuse outright\n * (https://fetch.spec.whatwg.org/#port-blocking). Node's `fetch` enforces the\n * list, so a server bound to one of them is unreachable from `waitForHealth`\n * and the PocketBase SDK alike: the request fails with cause \"bad port\"\n * before a connection is even attempted. 10080 sat inside the 10000–19999\n * range ports used to be drawn from, and cost a CI run a 30-second health\n * timeout whenever the draw landed on it.\n */\nexport const BAD_PORTS: ReadonlySet<number> = new Set([\n 1, 7, 9, 11, 13, 15, 17, 19, 20, 21, 22, 23, 25, 37, 42, 43, 53, 69, 77, 79,\n 87, 95, 101, 102, 103, 104, 109, 110, 111, 113, 115, 117, 119, 123, 135, 137,\n 139, 143, 161, 179, 389, 427, 465, 512, 513, 514, 515, 526, 530, 531, 532,\n 540, 548, 554, 556, 563, 587, 601, 636, 989, 990, 993, 995, 1719, 1720, 1723,\n 2049, 3659, 4045, 4190, 5060, 5061, 6000, 6566, 6665, 6666, 6667, 6668, 6669,\n 6679, 6697, 10080,\n]);\n\nfunction osAssignedPort(host: string): Promise<number> {\n return new Promise((resolve, reject) => {\n const server = net.createServer();\n server.unref();\n server.once(\"error\", reject);\n server.listen(0, host, () => {\n const { port } = server.address() as net.AddressInfo;\n server.close(() => resolve(port));\n });\n });\n}\n\n/**\n * A port nothing is listening on right now, taken from the OS's ephemeral\n * range so it neither collides with whatever else the machine runs nor hits\n * `BAD_PORTS`. The port is released again before this resolves, so the\n * caller's server has to bind it promptly.\n */\nexport async function freePort(host: string): Promise<number> {\n for (;;) {\n const port = await osAssignedPort(host);\n if (!BAD_PORTS.has(port)) return port;\n }\n}\n\n// Wait for the port to be available. A cold `npx pocketbase-server` on a CI\n// runner can take well over the five seconds the old default allowed.\nexport function waitForPort(\n port: number,\n host: string,\n maxAttempts = 60,\n): Promise<void> {\n return new Promise((resolve, reject) => {\n let attempts = 0;\n\n const tryConnect = () => {\n attempts++;\n\n const socket = new net.Socket();\n\n const onError = () => {\n socket.destroy();\n\n if (attempts === maxAttempts) {\n reject(\n new Error(`Timed out waiting for port ${port} to be available`),\n );\n return;\n }\n\n setTimeout(tryConnect, 500);\n };\n\n socket.once(\"error\", onError);\n\n socket.connect(port, host, () => {\n socket.destroy();\n resolve();\n });\n };\n\n tryConnect();\n });\n}\n\n/**\n * `fetch` wraps the interesting part in `cause`: an errno error for a\n * connection that was refused, or a bare string such as \"bad port\" for a\n * request undici declined to make.\n */\nfunction describeFetchError(error: unknown): string {\n if (!(error instanceof Error)) return String(error);\n const { cause } = error as Error & { cause?: unknown };\n if (cause instanceof Error) {\n const code = (cause as NodeJS.ErrnoException).code;\n return code || cause.message || error.message;\n }\n if (cause !== undefined) return String(cause);\n return error.message;\n}\n\n// Wait for the health check to be successful\nexport function waitForHealth(url: string, maxAttempts = 60): Promise<void> {\n return new Promise((resolve, reject) => {\n let attempts = 0;\n let lastFailure = \"no attempt made\";\n\n const tryHealth = async () => {\n attempts++;\n\n try {\n const response = await fetch(`${url}/api/health`);\n if (response.status === 200) {\n resolve();\n return;\n }\n lastFailure = `HTTP ${response.status}`;\n } catch (error) {\n lastFailure = describeFetchError(error);\n }\n\n if (attempts === maxAttempts) {\n reject(\n new Error(\n `Timed out waiting for health check at ${url}/api/health (last attempt: ${lastFailure})`,\n ),\n );\n return;\n }\n\n setTimeout(tryHealth, 500);\n };\n\n tryHealth();\n });\n}\n","import { existsSync, readdirSync, readFileSync } from \"node:fs\";\nimport path from \"node:path\";\nimport PocketBase from \"pocketbase\";\nimport { detect } from \"package-manager-detector\";\nimport { resolveCommand } from \"package-manager-detector/commands\";\nimport spawn from \"cross-spawn\";\nimport { freePort, waitForPort, waitForHealth } from \"./net\";\nimport type { Options } from \"../core/types\";\nimport { DATA_DIR, MIGRATIONS_DIR } from \"../core/constants\";\n\n/**\n * PocketBase names migration files with a 1-second-resolution Unix timestamp\n * (e.g. `1776099881_created_users.js`). Two schema operations issued in the\n * same wall-clock second produce files that sort alphabetically by their\n * action/collection suffix — which reverses the intended order whenever a\n * later migration depends on an earlier one. Wait out the full second between\n * migration-producing calls so the timestamps stay distinct.\n */\nconst MIGRATION_DELAY_MS = 1100;\n\nexport function migrationDelay(): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, MIGRATION_DELAY_MS));\n}\n\nexport function getMigrationFile(\n collectionName: string,\n action: \"created\" | \"deleted\" | \"updated\",\n options: Options,\n): string | undefined {\n const ending = `${action}_${collectionName}.js`;\n\n // find last file with ending in migrations dir\n const migrationFiles = readdirSync(\n path.join(options.root, MIGRATIONS_DIR),\n ).filter((file) => file.endsWith(ending));\n\n const migrationFile = migrationFiles.sort().pop();\n\n if (!migrationFile) {\n return undefined;\n }\n\n return path.join(options.root, MIGRATIONS_DIR, migrationFile);\n}\n\nexport function getPocketbaseMetadata(cwd: string): {\n pocketbaseUrl: string;\n vitePort: number;\n} | null {\n const metadataPath = path.join(\n cwd,\n \"node_modules\",\n \".vite\",\n \"_pocketbase_metadata.json\",\n );\n if (existsSync(metadataPath)) {\n return JSON.parse(readFileSync(metadataPath, \"utf8\"));\n }\n return null;\n}\n\nexport async function authWithRetries(\n pb: PocketBase,\n email: string,\n password: string,\n) {\n // Retry authentication up to 3 times with 100ms backoff\n let authSuccess = false;\n for (let attempt = 1; attempt <= 3; attempt++) {\n try {\n await pb.collection(\"_superusers\").authWithPassword(email, password);\n authSuccess = true;\n break;\n } catch {\n if (attempt < 3) {\n await new Promise((resolve) => setTimeout(resolve, 100));\n }\n }\n }\n\n if (!authSuccess) {\n throw new Error(\n \"Failed to authenticate with PocketBase. Check your superuser credentials.\",\n );\n }\n}\n\nexport async function withPocketbase(\n cwd: string,\n fn: (pb: PocketBase) => Promise<void>,\n) {\n const dir = path.join(cwd, DATA_DIR);\n const migrationsDir = path.join(cwd, MIGRATIONS_DIR);\n const host = \"localhost\";\n\n if (!existsSync(dir)) {\n throw new Error(\"PocketBase data directory does not exist\");\n }\n\n // First check if the server is already running by reading node_modules/.vite/_pocketbase_metadata.json\n const metadata = getPocketbaseMetadata(cwd);\n if (metadata) {\n if (metadata.pocketbaseUrl) {\n const pb = new PocketBase(metadata.pocketbaseUrl);\n await authWithRetries(\n pb,\n process.env.POCKETBASE_SUPERUSER_EMAIL!,\n process.env.POCKETBASE_SUPERUSER_PASSWORD!,\n );\n await fn(pb);\n return;\n }\n }\n\n const port = await freePort(host);\n const commandArgs = [\n \"pocketbase-server\",\n \"serve\",\n \"--dir\",\n dir,\n \"--migrationsDir\",\n migrationsDir,\n \"--http\",\n `${host}:${port}`,\n ];\n\n const packageManager = (await detect({ cwd }))?.name ?? \"npm\";\n const { command, args } = resolveCommand(\n packageManager,\n \"execute\",\n commandArgs,\n )!;\n\n // adding --yes as the first parameter helps avoiding the \"Need to install the following packages:\" message\n if (packageManager === \"npm\") args.unshift(\"--yes\");\n\n // Start the PocketBase server process. The package manager wrapper (`npx`)\n // spawns the real binary as a grandchild; put the tree in its own process\n // group so it can be killed as a whole, otherwise `pocketbase serve` outlives\n // us and keeps the data directory open.\n const detached = process.platform !== \"win32\";\n const serverProcess = spawn(command, args, {\n cwd,\n stdio: \"ignore\",\n detached,\n });\n\n // A wrapper that dies before the server listens (missing binary, bad\n // arguments) would otherwise only surface as a port timeout a minute later.\n const exited = new Promise<never>((_, reject) => {\n serverProcess.once(\"exit\", (code, signal) => {\n reject(\n new Error(\n `pocketbase-server exited before listening on ${host}:${port} (${signal ?? `code ${code}`})`,\n ),\n );\n });\n serverProcess.once(\"error\", reject);\n });\n\n try {\n // Wait for the server to be ready\n await Promise.race([\n (async () => {\n await waitForPort(port, host);\n await waitForHealth(`http://${host}:${port}`);\n })(),\n exited,\n ]);\n\n const pb = new PocketBase(`http://${host}:${port}`);\n await authWithRetries(\n pb,\n process.env.POCKETBASE_SUPERUSER_EMAIL!,\n process.env.POCKETBASE_SUPERUSER_PASSWORD!,\n );\n await fn(pb);\n } finally {\n // Ensure we always clean up the process tree\n stopProcessTree(serverProcess, detached);\n }\n}\n\nfunction stopProcessTree(\n child: ReturnType<typeof spawn>,\n detached: boolean,\n): void {\n if (detached && child.pid) {\n try {\n process.kill(-child.pid, \"SIGTERM\");\n return;\n } catch {\n // Group already gone or unsupported; fall through to the plain kill.\n }\n }\n child.kill();\n}\n"],"mappings":";;;;;;;;;AAWA,IAAa,oBAAiC,IAAI,IAAI;CACpD;CAAG;CAAG;CAAG;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CACzE;CAAI;CAAI;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CACzE;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CACtE;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;C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,EAAW,UAAU,EAAK,GAAG,GAAM;EAMlD,AALA,MAAM,EACJ,GACA,QAAQ,IAAI,4BACZ,QAAQ,IAAI,6BACd,GACA,MAAM,EAAG,CAAE;CACb,UAAU;EAER,EAAgB,GAAe,CAAQ;CACzC;AACF;AAEA,SAAS,EACP,GACA,GACM;CACN,IAAI,KAAY,EAAM,KACpB,IAAI;EACF,QAAQ,KAAK,CAAC,EAAM,KAAK,SAAS;EAClC;CACF,QAAQ,CAER;CAEF,EAAM,KAAK;AACb"}
@@ -15,7 +15,7 @@ async function n(e, t) {
15
15
  exists: !0,
16
16
  rowCount: 0
17
17
  }));
18
- let { withPocketbase: n } = await import("./pocketbase-059B1oot.js"), { planCollectionDrops: r } = await import("./collections-B3lAtPlQ.js"), i = [];
18
+ let { withPocketbase: n } = await import("./pocketbase-BerjVikJ.js"), { planCollectionDrops: r } = await import("./collections-DDYlpDNO.js"), i = [];
19
19
  return await n(t.root, async (t) => {
20
20
  let n = await r(t, e);
21
21
  i.push(...n);
@@ -24,4 +24,4 @@ async function n(e, t) {
24
24
  //#endregion
25
25
  export { t as n, n as t };
26
26
 
27
- //# sourceMappingURL=shared--_BWnGsc.js.map
27
+ //# sourceMappingURL=shared-Cmbzu7Od.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"shared--_BWnGsc.js","names":[],"sources":["../../src/patterns/destroy/shared.ts"],"sourcesContent":["import type { CollectionDropSpec, File, Options } from \"../../core/types\";\nimport { languageFromPath } from \"../../core/util\";\n\nexport function toDeleteEntry(path: string): File {\n return {\n path,\n language: languageFromPath(path),\n content: \"\",\n status: \"success\",\n };\n}\n\n/**\n * Build `CollectionDropSpec` entries for each collection name, with live row\n * counts from PocketBase when `env === \"runtime\"`. In preview mode, returns\n * `{ exists: true, rowCount: 0 }` placeholders.\n */\nexport async function planDropsForCollections(\n collectionNames: string[],\n options: Options,\n): Promise<CollectionDropSpec[]> {\n if (collectionNames.length === 0) return [];\n\n if (options.env !== \"runtime\") {\n return collectionNames.map((name) => ({\n name,\n exists: true,\n rowCount: 0,\n }));\n }\n\n const { withPocketbase } = await import(\"../../runtime/pocketbase\");\n const { planCollectionDrops } = await import(\"../../runtime/collections\");\n const drops: CollectionDropSpec[] = [];\n await withPocketbase(options.root, async (pb) => {\n const plans = await planCollectionDrops(pb, collectionNames);\n drops.push(...plans);\n });\n return drops;\n}\n"],"mappings":";;AAGA,SAAgB,EAAc,GAAoB;CAChD,OAAO;EACL;EACA,UAAU,EAAiB,CAAI;EAC/B,SAAS;EACT,QAAQ;CACV;AACF;AAOA,eAAsB,EACpB,GACA,GAC+B;CAC/B,IAAI,EAAgB,WAAW,GAAG,OAAO,CAAC;CAE1C,IAAI,EAAQ,QAAQ,WAClB,OAAO,EAAgB,KAAK,OAAU;EACpC;EACA,QAAQ;EACR,UAAU;CACZ,EAAE;CAGJ,IAAM,EAAE,sBAAmB,MAAM,OAAO,6BAClC,EAAE,2BAAwB,MAAM,OAAO,8BACvC,IAA8B,CAAC;CAKrC,OAJA,MAAM,EAAe,EAAQ,MAAM,OAAO,MAAO;EAC/C,IAAM,IAAQ,MAAM,EAAoB,GAAI,CAAe;EAC3D,EAAM,KAAK,GAAG,CAAK;CACrB,CAAC,GACM;AACT"}
1
+ {"version":3,"file":"shared-Cmbzu7Od.js","names":[],"sources":["../../src/patterns/destroy/shared.ts"],"sourcesContent":["import type { CollectionDropSpec, File, Options } from \"../../core/types\";\nimport { languageFromPath } from \"../../core/util\";\n\nexport function toDeleteEntry(path: string): File {\n return {\n path,\n language: languageFromPath(path),\n content: \"\",\n status: \"success\",\n };\n}\n\n/**\n * Build `CollectionDropSpec` entries for each collection name, with live row\n * counts from PocketBase when `env === \"runtime\"`. In preview mode, returns\n * `{ exists: true, rowCount: 0 }` placeholders.\n */\nexport async function planDropsForCollections(\n collectionNames: string[],\n options: Options,\n): Promise<CollectionDropSpec[]> {\n if (collectionNames.length === 0) return [];\n\n if (options.env !== \"runtime\") {\n return collectionNames.map((name) => ({\n name,\n exists: true,\n rowCount: 0,\n }));\n }\n\n const { withPocketbase } = await import(\"../../runtime/pocketbase\");\n const { planCollectionDrops } = await import(\"../../runtime/collections\");\n const drops: CollectionDropSpec[] = [];\n await withPocketbase(options.root, async (pb) => {\n const plans = await planCollectionDrops(pb, collectionNames);\n drops.push(...plans);\n });\n return drops;\n}\n"],"mappings":";;AAGA,SAAgB,EAAc,GAAoB;CAChD,OAAO;EACL;EACA,UAAU,EAAiB,CAAI;EAC/B,SAAS;EACT,QAAQ;CACV;AACF;AAOA,eAAsB,EACpB,GACA,GAC+B;CAC/B,IAAI,EAAgB,WAAW,GAAG,OAAO,CAAC;CAE1C,IAAI,EAAQ,QAAQ,WAClB,OAAO,EAAgB,KAAK,OAAU;EACpC;EACA,QAAQ;EACR,UAAU;CACZ,EAAE;CAGJ,IAAM,EAAE,sBAAmB,MAAM,OAAO,6BAClC,EAAE,2BAAwB,MAAM,OAAO,8BACvC,IAA8B,CAAC;CAKrC,OAJA,MAAM,EAAe,EAAQ,MAAM,OAAO,MAAO;EAC/C,IAAM,IAAQ,MAAM,EAAoB,GAAI,CAAe;EAC3D,EAAM,KAAK,GAAG,CAAK;CACrB,CAAC,GACM;AACT"}
@@ -1,4 +1,4 @@
1
- //#region \0@oxc-project+runtime@0.146.0/helpers/esm/taggedTemplateLiteral.js
1
+ //#region \0@oxc-project+runtime@0.149.0/helpers/esm/taggedTemplateLiteral.js
2
2
  function e(e, t) {
3
3
  return t ||= e.slice(0), Object.freeze(Object.defineProperties(e, { raw: { value: Object.freeze(t) } }));
4
4
  }
@@ -154,7 +154,7 @@ function d(e, t, n) {
154
154
  }
155
155
  function f(e) {
156
156
  let t = e.getImportDeclarations(), n = t[t.length - 1], r = n?.getNextSibling();
157
- !n || !r || (e.getFullText().slice(n.getEnd(), r.getStart()).match(/\n/g) ?? []).length >= 2 || e.insertText(n.getEnd(), "\n");
157
+ n && r && ((e.getFullText().slice(n.getEnd(), r.getStart()).match(/\n/g) ?? []).length >= 2 || e.insertText(n.getEnd(), "\n"));
158
158
  }
159
159
  function p(e, t) {
160
160
  let n = e.getFunction(t);
@@ -226,4 +226,4 @@ function h(e, t, n) {
226
226
  //#endregion
227
227
  export { d as a, c, u as i, o as l, f as n, h as o, l as r, p as s, m as t };
228
228
 
229
- //# sourceMappingURL=ts-morph-helpers-Bf5iuQW8.js.map
229
+ //# sourceMappingURL=ts-morph-helpers-teS3yXg-.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"ts-morph-helpers-Bf5iuQW8.js","names":[],"sources":["../../src/runtime/svelte-file.ts","../../src/runtime/ts-morph-helpers.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport { parse, type AST } from \"svelte/compiler\";\nimport MagicString from \"magic-string\";\n\ntype SvelteAst = AST.Root;\ntype SvelteNode = any;\n\ninterface ScriptBlock {\n content: string;\n start: number;\n end: number;\n}\n\n/**\n * Surgical, AST-aware editing of .svelte files.\n *\n * Parses the source with svelte/compiler to discover precise character offsets,\n * then applies edits via magic-string so untouched regions remain byte-for-byte\n * identical to the original. Script-block contents are exposed as plain strings\n * so callers can hand them to ts-morph.\n */\nexport class SvelteFile {\n private readonly source: string;\n private readonly ast: SvelteAst;\n private readonly s: MagicString;\n\n constructor(source: string) {\n this.source = source;\n this.ast = parse(source, { modern: true });\n this.s = new MagicString(source);\n }\n\n static fromPath(filePath: string): SvelteFile {\n return new SvelteFile(fs.readFileSync(filePath, \"utf8\"));\n }\n\n getScript(): ScriptBlock | null {\n return this.scriptInner((this.ast as any).instance);\n }\n\n getModuleScript(): ScriptBlock | null {\n return this.scriptInner((this.ast as any).module);\n }\n\n private scriptInner(script: SvelteNode | null): ScriptBlock | null {\n if (!script) return null;\n const start = script.content.start as number;\n const end = script.content.end as number;\n return { content: this.source.slice(start, end), start, end };\n }\n\n /**\n * Replace the inner contents of <script>. Use for ts-morph round-trips.\n * Returns true when an edit was made.\n */\n modifyScript(fn: (content: string) => string): boolean {\n return this.modifyScriptBlock(this.getScript(), fn);\n }\n\n modifyModuleScript(fn: (content: string) => string): boolean {\n return this.modifyScriptBlock(this.getModuleScript(), fn);\n }\n\n private modifyScriptBlock(\n block: ScriptBlock | null,\n fn: (content: string) => string,\n ): boolean {\n if (!block) return false;\n const next = fn(block.content);\n if (next === block.content) return false;\n this.s.overwrite(block.start, block.end, next);\n return true;\n }\n\n /** First Component or RegularElement node with the given name. */\n findElement(name: string): SvelteNode | null {\n return findNode(\n (this.ast as any).fragment,\n (node) =>\n (node.type === \"Component\" || node.type === \"RegularElement\") &&\n node.name === name,\n );\n }\n\n hasElement(name: string): boolean {\n return this.findElement(name) !== null;\n }\n\n hasAttribute(componentName: string, attrName: string): boolean {\n const node = this.findElement(componentName);\n if (!node) return false;\n return (node.attributes ?? []).some(\n (attr: SvelteNode) => attr.type === \"Attribute\" && attr.name === attrName,\n );\n }\n\n /**\n * Insert content at the end of <ComponentName>'s children, just before the\n * closing tag. No-op if the element is not found.\n */\n insertBeforeClosingTag(name: string, content: string): boolean {\n const node = this.findElement(name);\n if (!node) return false;\n const closingTag = `</${name}>`;\n const closingPos = this.source.lastIndexOf(closingTag, node.end);\n if (closingPos === -1) return false;\n this.s.appendLeft(closingPos, content);\n return true;\n }\n\n /** Replace the element entirely (start tag through close tag). */\n replaceElement(name: string, newContent: string): boolean {\n const node = this.findElement(name);\n if (!node) return false;\n this.s.overwrite(node.start, node.end, newContent);\n return true;\n }\n\n /** Remove the element (start tag through close tag). */\n removeElement(name: string): boolean {\n return this.replaceElement(name, \"\");\n }\n\n /** Append raw markup to the end of the source file. */\n appendMarkup(content: string): void {\n this.s.append(content);\n }\n\n /**\n * Insert markup so it renders before the layout's children — i.e. ahead of\n * the top-level `{@render children()}` (or legacy `<slot />`). The markup\n * lands on its own line directly after the preceding sibling, so\n *\n * <Toaster />\n *\n * {@render children?.()}\n *\n * becomes `<Toaster />\\n<AdminBar />\\n\\n{@render children?.()}`. When the\n * render tag is the first node the markup goes immediately before it.\n * Returns false (and changes nothing) if no such tag exists.\n */\n insertBeforeChildren(content: string): boolean {\n const nodes: SvelteNode[] = (this.ast as any).fragment?.nodes ?? [];\n const index = nodes.findIndex(\n (node) =>\n node.type === \"RenderTag\" ||\n node.type === \"SlotElement\" ||\n (node.type === \"RegularElement\" && node.name === \"slot\"),\n );\n if (index === -1) return false;\n\n const trimmed = content.trim();\n for (let i = index - 1; i >= 0; i--) {\n const prev = nodes[i]!;\n if (prev.type === \"Text\" && prev.data.trim() === \"\") continue;\n this.s.appendLeft(prev.end as number, `\\n${trimmed}`);\n return true;\n }\n this.s.appendLeft(nodes[index]!.start as number, `${trimmed}\\n\\n`);\n return true;\n }\n\n /**\n * Append attribute text (e.g. \" team={data.team}\") just after the last\n * existing attribute on the element's start tag.\n */\n appendToAttributes(name: string, attrs: string): boolean {\n const node = this.findElement(name);\n if (!node) return false;\n const last = (node.attributes ?? []).at(-1) as SvelteNode | undefined;\n const insertAt = last\n ? (last.end as number)\n : (node.start as number) + `<${name}`.length;\n this.s.appendLeft(insertAt, attrs);\n return true;\n }\n\n /**\n * Remove a named attribute from a component's start tag, including the\n * leading whitespace. No-op if the element or attribute isn't present.\n */\n removeAttribute(name: string, attrName: string): boolean {\n const node = this.findElement(name);\n if (!node) return false;\n const attr = (node.attributes ?? []).find(\n (a: SvelteNode) => a.type === \"Attribute\" && a.name === attrName,\n );\n if (!attr) return false;\n // Extend the removal backwards over the whitespace between the previous\n // token and this attribute so the tag doesn't collapse `<Foo />`.\n let start = attr.start as number;\n while (start > 0 && /\\s/.test(this.source[start - 1]!)) start--;\n this.s.remove(start, attr.end as number);\n return true;\n }\n\n hasChanged(): boolean {\n return this.s.hasChanged();\n }\n\n toString(): string {\n return this.s.toString();\n }\n\n writeTo(filePath: string): void {\n if (this.hasChanged()) {\n fs.writeFileSync(filePath, this.toString(), \"utf8\");\n }\n }\n}\n\nfunction findNode(\n root: unknown,\n predicate: (node: any) => boolean,\n): any | null {\n const seen = new WeakSet<object>();\n function visit(node: unknown): any | null {\n if (!node || typeof node !== \"object\" || seen.has(node as object)) {\n return null;\n }\n seen.add(node as object);\n if (predicate(node as any)) return node;\n for (const key of Object.keys(node as Record<string, unknown>)) {\n if (key === \"parent\") continue;\n const child = (node as Record<string, unknown>)[key];\n if (Array.isArray(child)) {\n for (const item of child) {\n const found = visit(item);\n if (found) return found;\n }\n } else if (\n child &&\n typeof child === \"object\" &&\n \"type\" in (child as object)\n ) {\n const found = visit(child);\n if (found) return found;\n }\n }\n return null;\n }\n return visit(root);\n}\n","import {\n Project,\n QuoteKind,\n SyntaxKind,\n type ImportDeclarationStructure,\n type OptionalKind,\n type SourceFile,\n type StringLiteral,\n} from \"ts-morph\";\n\nexport interface ImportSpec {\n defaultImport?: string;\n namespaceImport?: string;\n namedImports?: string[];\n moduleSpecifier: string;\n}\n\n/**\n * Run a function with an in-memory ts-morph SourceFile and return the resulting\n * source plus whatever the callback returned.\n */\nexport function withInMemoryScript<T>(\n source: string,\n fn: (sf: SourceFile) => T,\n): { source: string; result: T } {\n const project = new Project({\n useInMemoryFileSystem: true,\n skipFileDependencyResolution: true,\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n const sf = project.createSourceFile(\"script.ts\", source, { overwrite: true });\n const result = fn(sf);\n return { source: sf.getFullText(), result };\n}\n\n/** Add the given imports to the source file, skipping any whose module specifier already exists. */\nexport function ensureImports(sf: SourceFile, imports: ImportSpec[]): void {\n for (const spec of imports) {\n const existing = sf\n .getImportDeclarations()\n .find((d) => d.getModuleSpecifierValue() === spec.moduleSpecifier);\n if (existing) continue;\n\n const structure: OptionalKind<ImportDeclarationStructure> = {\n moduleSpecifier: spec.moduleSpecifier,\n };\n if (spec.defaultImport) structure.defaultImport = spec.defaultImport;\n if (spec.namespaceImport) structure.namespaceImport = spec.namespaceImport;\n if (spec.namedImports) structure.namedImports = spec.namedImports;\n sf.addImportDeclaration(structure);\n }\n}\n\n/** Remove the import declaration for the given module specifier, if present. */\nexport function removeImportByModuleSpecifier(\n sf: SourceFile,\n moduleSpecifier: string,\n): { wasRemoved: boolean } {\n const decl = sf\n .getImportDeclarations()\n .find((d) => d.getModuleSpecifierValue() === moduleSpecifier);\n if (!decl) return { wasRemoved: false };\n decl.remove();\n return { wasRemoved: true };\n}\n\n/**\n * Drop `name` from the import of `moduleSpecifier` once nothing else in the\n * file references it; the whole declaration goes when `name` was its only\n * import. For unwrapping `sequence(...)` and the like after a revert.\n */\nexport function removeNamedImportIfUnused(\n sf: SourceFile,\n moduleSpecifier: string,\n name: string,\n): { wasRemoved: boolean } {\n const decl = sf\n .getImportDeclarations()\n .find((d) => d.getModuleSpecifierValue() === moduleSpecifier);\n if (!decl) return { wasRemoved: false };\n\n const stillReferenced = sf\n .getDescendantsOfKind(SyntaxKind.Identifier)\n .some((id) => {\n if (id.getText() !== name) return false;\n const kind = id.getParent()?.getKind();\n return (\n kind !== SyntaxKind.ImportSpecifier && kind !== SyntaxKind.ImportClause\n );\n });\n if (stillReferenced) return { wasRemoved: false };\n\n const named = decl.getNamedImports().find((ni) => ni.getName() === name);\n if (!named) return { wasRemoved: false };\n\n if (decl.getNamedImports().length === 1 && !decl.getDefaultImport()) {\n decl.remove();\n } else {\n named.remove();\n }\n return { wasRemoved: true };\n}\n\n/**\n * Keep one blank line between the import block and what follows. Removing\n * statements right after the imports takes the separating blank line with\n * them, and prettier preserves whichever spacing it finds.\n */\nexport function ensureBlankLineAfterImports(sf: SourceFile): void {\n const imports = sf.getImportDeclarations();\n const last = imports[imports.length - 1];\n const next = last?.getNextSibling();\n if (!last || !next) return;\n const between = sf.getFullText().slice(last.getEnd(), next.getStart());\n if ((between.match(/\\n/g) ?? []).length >= 2) return;\n sf.insertText(last.getEnd(), \"\\n\");\n}\n\n/** Remove a top-level function or variable declaration by name, if present. */\nexport function removeTopLevelStatementByIdentifier(\n sf: SourceFile,\n name: string,\n): { wasRemoved: boolean } {\n const fn = sf.getFunction(name);\n if (fn) {\n fn.remove();\n return { wasRemoved: true };\n }\n const vs = sf\n .getVariableStatements()\n .find((s) => s.getDeclarations().some((d) => d.getName() === name));\n if (vs) {\n vs.remove();\n return { wasRemoved: true };\n }\n return { wasRemoved: false };\n}\n\n/**\n * Add an item to the `data.navUser` array in a Svelte component's script body.\n * Idempotent: if an entry with the same `title` already exists, no-op.\n */\nexport function addNavItemToScript(\n scriptSource: string,\n title: string,\n url: string,\n icon: string,\n iconImportPath: string,\n): { source: string; wasAdded: boolean } {\n const newNavItemSnippet = `\n {\n title: '${title}',\n url: '${url}',\n icon: ${icon}\n }\n `.trim();\n\n const { source, result } = withInMemoryScript(scriptSource, (sf) => {\n const dataDecl = sf\n .getVariableDeclarations()\n .find((d) => d.getName() === \"data\");\n const dataInit = dataDecl?.getInitializer();\n if (\n !dataInit ||\n dataInit.getKind() !== SyntaxKind.ObjectLiteralExpression\n ) {\n return { wasAdded: false };\n }\n\n const obj = dataInit.asKindOrThrow(SyntaxKind.ObjectLiteralExpression);\n const navProp = obj.getProperty(\"navUser\");\n if (!navProp || navProp.getKind() !== SyntaxKind.PropertyAssignment) {\n return { wasAdded: false };\n }\n\n const init = navProp\n .asKindOrThrow(SyntaxKind.PropertyAssignment)\n .getInitializer();\n if (!init || init.getKind() !== SyntaxKind.ArrayLiteralExpression) {\n return { wasAdded: false };\n }\n\n const arr = init.asKindOrThrow(SyntaxKind.ArrayLiteralExpression);\n const exists = arr.getElements().some((el) => {\n if (el.getKind() !== SyntaxKind.ObjectLiteralExpression) return false;\n const o = el.asKindOrThrow(SyntaxKind.ObjectLiteralExpression);\n const titleProp = o.getProperty(\"title\");\n if (!titleProp || titleProp.getKind() !== SyntaxKind.PropertyAssignment) {\n return false;\n }\n const value = titleProp\n .asKindOrThrow(SyntaxKind.PropertyAssignment)\n .getInitializer();\n return (\n value?.getKind() === SyntaxKind.StringLiteral &&\n (value as StringLiteral).getLiteralText() === title\n );\n });\n\n if (exists) return { wasAdded: false };\n\n ensureImports(sf, [\n { defaultImport: icon, moduleSpecifier: iconImportPath },\n ]);\n arr.addElement(newNavItemSnippet);\n sf.formatText();\n return { wasAdded: true };\n });\n\n return { source, wasAdded: result.wasAdded };\n}\n\n/**\n * Remove the entry with the given `title` from the `data.navUser` array in a\n * Svelte component's script body. Also removes the icon import if supplied and\n * no other navUser entry references it. Idempotent: no-op if the entry or\n * navUser structure is missing.\n */\nexport function removeNavItemFromScript(\n scriptSource: string,\n title: string,\n iconImportPath?: string,\n): { source: string; wasRemoved: boolean } {\n const { source, result } = withInMemoryScript(scriptSource, (sf) => {\n const dataDecl = sf\n .getVariableDeclarations()\n .find((d) => d.getName() === \"data\");\n const dataInit = dataDecl?.getInitializer();\n if (\n !dataInit ||\n dataInit.getKind() !== SyntaxKind.ObjectLiteralExpression\n ) {\n return { wasRemoved: false };\n }\n\n const obj = dataInit.asKindOrThrow(SyntaxKind.ObjectLiteralExpression);\n const navProp = obj.getProperty(\"navUser\");\n if (!navProp || navProp.getKind() !== SyntaxKind.PropertyAssignment) {\n return { wasRemoved: false };\n }\n\n const init = navProp\n .asKindOrThrow(SyntaxKind.PropertyAssignment)\n .getInitializer();\n if (!init || init.getKind() !== SyntaxKind.ArrayLiteralExpression) {\n return { wasRemoved: false };\n }\n\n const arr = init.asKindOrThrow(SyntaxKind.ArrayLiteralExpression);\n const elements = arr.getElements();\n const index = elements.findIndex((el) => {\n if (el.getKind() !== SyntaxKind.ObjectLiteralExpression) return false;\n const o = el.asKindOrThrow(SyntaxKind.ObjectLiteralExpression);\n const titleProp = o.getProperty(\"title\");\n if (!titleProp || titleProp.getKind() !== SyntaxKind.PropertyAssignment) {\n return false;\n }\n const value = titleProp\n .asKindOrThrow(SyntaxKind.PropertyAssignment)\n .getInitializer();\n return (\n value?.getKind() === SyntaxKind.StringLiteral &&\n (value as StringLiteral).getLiteralText() === title\n );\n });\n\n if (index === -1) return { wasRemoved: false };\n\n arr.removeElement(index);\n\n if (iconImportPath) {\n const importDecl = sf\n .getImportDeclarations()\n .find((d) => d.getModuleSpecifierValue() === iconImportPath);\n if (importDecl) {\n const importName = importDecl.getDefaultImport()?.getText();\n const stillUsed =\n importName &&\n sf\n .getDescendantsOfKind(SyntaxKind.Identifier)\n .some(\n (id) =>\n id.getText() === importName &&\n id.getParent()?.getKind() !== SyntaxKind.ImportClause &&\n id.getParent()?.getKind() !== SyntaxKind.ImportSpecifier,\n );\n if (!stillUsed) {\n importDecl.remove();\n }\n }\n }\n\n sf.formatText();\n return { wasRemoved: true };\n });\n\n return { source, wasRemoved: result.wasRemoved };\n}\n"],"mappings":";;;;;AAqBA,IAAa,IAAb,MAAa,EAAW;CAKtB,YAAY,GAAgB;EAG1B,AAFA,KAAK,SAAS,GACd,KAAK,MAAM,EAAM,GAAQ,EAAE,QAAQ,GAAK,CAAC,GACzC,KAAK,IAAI,IAAI,EAAY,CAAM;CACjC;CAEA,OAAO,SAAS,GAA8B;EAC5C,OAAO,IAAI,EAAW,EAAG,aAAa,GAAU,MAAM,CAAC;CACzD;CAEA,YAAgC;EAC9B,OAAO,KAAK,YAAa,KAAK,IAAY,QAAQ;CACpD;CAEA,kBAAsC;EACpC,OAAO,KAAK,YAAa,KAAK,IAAY,MAAM;CAClD;CAEA,YAAoB,GAA+C;EACjE,IAAI,CAAC,GAAQ,OAAO;EACpB,IAAM,IAAQ,EAAO,QAAQ,OACvB,IAAM,EAAO,QAAQ;EAC3B,OAAO;GAAE,SAAS,KAAK,OAAO,MAAM,GAAO,CAAG;GAAG;GAAO;EAAI;CAC9D;CAMA,aAAa,GAA0C;EACrD,OAAO,KAAK,kBAAkB,KAAK,UAAU,GAAG,CAAE;CACpD;CAEA,mBAAmB,GAA0C;EAC3D,OAAO,KAAK,kBAAkB,KAAK,gBAAgB,GAAG,CAAE;CAC1D;CAEA,kBACE,GACA,GACS;EACT,IAAI,CAAC,GAAO,OAAO;EACnB,IAAM,IAAO,EAAG,EAAM,OAAO;EAG7B,OAFI,MAAS,EAAM,YACnB,KAAK,EAAE,UAAU,EAAM,OAAO,EAAM,KAAK,CAAI,GACtC;CACT;CAGA,YAAY,GAAiC;EAC3C,OAA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CAAC,EAAE,QAAQ;IAW1D,AATE,KACA,EACG,qBAAqB,EAAW,UAAU,CAAC,CAC3C,MACE,MACC,EAAG,QAAQ,MAAM,KACjB,EAAG,UAAU,CAAC,EAAE,QAAQ,MAAM,EAAW,gBACzC,EAAG,UAAU,CAAC,EAAE,QAAQ,MAAM,EAAW,eAC7C,KAEF,EAAW,OAAO;GAEtB;EACF;EAGA,OADA,EAAG,WAAW,GACP,EAAE,YAAY,GAAK;CAC5B,CAAC;CAED,OAAO;EAAE;EAAQ,YAAY,EAAO;CAAW;AACjD"}
1
+ {"version":3,"file":"ts-morph-helpers-teS3yXg-.js","names":[],"sources":["../../src/runtime/svelte-file.ts","../../src/runtime/ts-morph-helpers.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport { parse, type AST } from \"svelte/compiler\";\nimport MagicString from \"magic-string\";\n\ntype SvelteAst = AST.Root;\ntype SvelteNode = any;\n\ninterface ScriptBlock {\n content: string;\n start: number;\n end: number;\n}\n\n/**\n * Surgical, AST-aware editing of .svelte files.\n *\n * Parses the source with svelte/compiler to discover precise character offsets,\n * then applies edits via magic-string so untouched regions remain byte-for-byte\n * identical to the original. Script-block contents are exposed as plain strings\n * so callers can hand them to ts-morph.\n */\nexport class SvelteFile {\n private readonly source: string;\n private readonly ast: SvelteAst;\n private readonly s: MagicString;\n\n constructor(source: string) {\n this.source = source;\n this.ast = parse(source, { modern: true });\n this.s = new MagicString(source);\n }\n\n static fromPath(filePath: string): SvelteFile {\n return new SvelteFile(fs.readFileSync(filePath, \"utf8\"));\n }\n\n getScript(): ScriptBlock | null {\n return this.scriptInner((this.ast as any).instance);\n }\n\n getModuleScript(): ScriptBlock | null {\n return this.scriptInner((this.ast as any).module);\n }\n\n private scriptInner(script: SvelteNode | null): ScriptBlock | null {\n if (!script) return null;\n const start = script.content.start as number;\n const end = script.content.end as number;\n return { content: this.source.slice(start, end), start, end };\n }\n\n /**\n * Replace the inner contents of <script>. Use for ts-morph round-trips.\n * Returns true when an edit was made.\n */\n modifyScript(fn: (content: string) => string): boolean {\n return this.modifyScriptBlock(this.getScript(), fn);\n }\n\n modifyModuleScript(fn: (content: string) => string): boolean {\n return this.modifyScriptBlock(this.getModuleScript(), fn);\n }\n\n private modifyScriptBlock(\n block: ScriptBlock | null,\n fn: (content: string) => string,\n ): boolean {\n if (!block) return false;\n const next = fn(block.content);\n if (next === block.content) return false;\n this.s.overwrite(block.start, block.end, next);\n return true;\n }\n\n /** First Component or RegularElement node with the given name. */\n findElement(name: string): SvelteNode | null {\n return findNode(\n (this.ast as any).fragment,\n (node) =>\n (node.type === \"Component\" || node.type === \"RegularElement\") &&\n node.name === name,\n );\n }\n\n hasElement(name: string): boolean {\n return this.findElement(name) !== null;\n }\n\n hasAttribute(componentName: string, attrName: string): boolean {\n const node = this.findElement(componentName);\n if (!node) return false;\n return (node.attributes ?? []).some(\n (attr: SvelteNode) => attr.type === \"Attribute\" && attr.name === attrName,\n );\n }\n\n /**\n * Insert content at the end of <ComponentName>'s children, just before the\n * closing tag. No-op if the element is not found.\n */\n insertBeforeClosingTag(name: string, content: string): boolean {\n const node = this.findElement(name);\n if (!node) return false;\n const closingTag = `</${name}>`;\n const closingPos = this.source.lastIndexOf(closingTag, node.end);\n if (closingPos === -1) return false;\n this.s.appendLeft(closingPos, content);\n return true;\n }\n\n /** Replace the element entirely (start tag through close tag). */\n replaceElement(name: string, newContent: string): boolean {\n const node = this.findElement(name);\n if (!node) return false;\n this.s.overwrite(node.start, node.end, newContent);\n return true;\n }\n\n /** Remove the element (start tag through close tag). */\n removeElement(name: string): boolean {\n return this.replaceElement(name, \"\");\n }\n\n /** Append raw markup to the end of the source file. */\n appendMarkup(content: string): void {\n this.s.append(content);\n }\n\n /**\n * Insert markup so it renders before the layout's children — i.e. ahead of\n * the top-level `{@render children()}` (or legacy `<slot />`). The markup\n * lands on its own line directly after the preceding sibling, so\n *\n * <Toaster />\n *\n * {@render children?.()}\n *\n * becomes `<Toaster />\\n<AdminBar />\\n\\n{@render children?.()}`. When the\n * render tag is the first node the markup goes immediately before it.\n * Returns false (and changes nothing) if no such tag exists.\n */\n insertBeforeChildren(content: string): boolean {\n const nodes: SvelteNode[] = (this.ast as any).fragment?.nodes ?? [];\n const index = nodes.findIndex(\n (node) =>\n node.type === \"RenderTag\" ||\n node.type === \"SlotElement\" ||\n (node.type === \"RegularElement\" && node.name === \"slot\"),\n );\n if (index === -1) return false;\n\n const trimmed = content.trim();\n for (let i = index - 1; i >= 0; i--) {\n const prev = nodes[i]!;\n if (prev.type === \"Text\" && prev.data.trim() === \"\") continue;\n this.s.appendLeft(prev.end as number, `\\n${trimmed}`);\n return true;\n }\n this.s.appendLeft(nodes[index]!.start as number, `${trimmed}\\n\\n`);\n return true;\n }\n\n /**\n * Append attribute text (e.g. \" team={data.team}\") just after the last\n * existing attribute on the element's start tag.\n */\n appendToAttributes(name: string, attrs: string): boolean {\n const node = this.findElement(name);\n if (!node) return false;\n const last = (node.attributes ?? []).at(-1) as SvelteNode | undefined;\n const insertAt = last\n ? (last.end as number)\n : (node.start as number) + `<${name}`.length;\n this.s.appendLeft(insertAt, attrs);\n return true;\n }\n\n /**\n * Remove a named attribute from a component's start tag, including the\n * leading whitespace. No-op if the element or attribute isn't present.\n */\n removeAttribute(name: string, attrName: string): boolean {\n const node = this.findElement(name);\n if (!node) return false;\n const attr = (node.attributes ?? []).find(\n (a: SvelteNode) => a.type === \"Attribute\" && a.name === attrName,\n );\n if (!attr) return false;\n // Extend the removal backwards over the whitespace between the previous\n // token and this attribute so the tag doesn't collapse `<Foo />`.\n let start = attr.start as number;\n while (start > 0 && /\\s/.test(this.source[start - 1]!)) start--;\n this.s.remove(start, attr.end as number);\n return true;\n }\n\n hasChanged(): boolean {\n return this.s.hasChanged();\n }\n\n toString(): string {\n return this.s.toString();\n }\n\n writeTo(filePath: string): void {\n if (this.hasChanged()) {\n fs.writeFileSync(filePath, this.toString(), \"utf8\");\n }\n }\n}\n\nfunction findNode(\n root: unknown,\n predicate: (node: any) => boolean,\n): any | null {\n const seen = new WeakSet<object>();\n function visit(node: unknown): any | null {\n if (!node || typeof node !== \"object\" || seen.has(node as object)) {\n return null;\n }\n seen.add(node as object);\n if (predicate(node as any)) return node;\n for (const key of Object.keys(node as Record<string, unknown>)) {\n if (key === \"parent\") continue;\n const child = (node as Record<string, unknown>)[key];\n if (Array.isArray(child)) {\n for (const item of child) {\n const found = visit(item);\n if (found) return found;\n }\n } else if (\n child &&\n typeof child === \"object\" &&\n \"type\" in (child as object)\n ) {\n const found = visit(child);\n if (found) return found;\n }\n }\n return null;\n }\n return visit(root);\n}\n","import {\n Project,\n QuoteKind,\n SyntaxKind,\n type ImportDeclarationStructure,\n type OptionalKind,\n type SourceFile,\n type StringLiteral,\n} from \"ts-morph\";\n\nexport interface ImportSpec {\n defaultImport?: string;\n namespaceImport?: string;\n namedImports?: string[];\n moduleSpecifier: string;\n}\n\n/**\n * Run a function with an in-memory ts-morph SourceFile and return the resulting\n * source plus whatever the callback returned.\n */\nexport function withInMemoryScript<T>(\n source: string,\n fn: (sf: SourceFile) => T,\n): { source: string; result: T } {\n const project = new Project({\n useInMemoryFileSystem: true,\n skipFileDependencyResolution: true,\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n const sf = project.createSourceFile(\"script.ts\", source, { overwrite: true });\n const result = fn(sf);\n return { source: sf.getFullText(), result };\n}\n\n/** Add the given imports to the source file, skipping any whose module specifier already exists. */\nexport function ensureImports(sf: SourceFile, imports: ImportSpec[]): void {\n for (const spec of imports) {\n const existing = sf\n .getImportDeclarations()\n .find((d) => d.getModuleSpecifierValue() === spec.moduleSpecifier);\n if (existing) continue;\n\n const structure: OptionalKind<ImportDeclarationStructure> = {\n moduleSpecifier: spec.moduleSpecifier,\n };\n if (spec.defaultImport) structure.defaultImport = spec.defaultImport;\n if (spec.namespaceImport) structure.namespaceImport = spec.namespaceImport;\n if (spec.namedImports) structure.namedImports = spec.namedImports;\n sf.addImportDeclaration(structure);\n }\n}\n\n/** Remove the import declaration for the given module specifier, if present. */\nexport function removeImportByModuleSpecifier(\n sf: SourceFile,\n moduleSpecifier: string,\n): { wasRemoved: boolean } {\n const decl = sf\n .getImportDeclarations()\n .find((d) => d.getModuleSpecifierValue() === moduleSpecifier);\n if (!decl) return { wasRemoved: false };\n decl.remove();\n return { wasRemoved: true };\n}\n\n/**\n * Drop `name` from the import of `moduleSpecifier` once nothing else in the\n * file references it; the whole declaration goes when `name` was its only\n * import. For unwrapping `sequence(...)` and the like after a revert.\n */\nexport function removeNamedImportIfUnused(\n sf: SourceFile,\n moduleSpecifier: string,\n name: string,\n): { wasRemoved: boolean } {\n const decl = sf\n .getImportDeclarations()\n .find((d) => d.getModuleSpecifierValue() === moduleSpecifier);\n if (!decl) return { wasRemoved: false };\n\n const stillReferenced = sf\n .getDescendantsOfKind(SyntaxKind.Identifier)\n .some((id) => {\n if (id.getText() !== name) return false;\n const kind = id.getParent()?.getKind();\n return (\n kind !== SyntaxKind.ImportSpecifier && kind !== SyntaxKind.ImportClause\n );\n });\n if (stillReferenced) return { wasRemoved: false };\n\n const named = decl.getNamedImports().find((ni) => ni.getName() === name);\n if (!named) return { wasRemoved: false };\n\n if (decl.getNamedImports().length === 1 && !decl.getDefaultImport()) {\n decl.remove();\n } else {\n named.remove();\n }\n return { wasRemoved: true };\n}\n\n/**\n * Keep one blank line between the import block and what follows. Removing\n * statements right after the imports takes the separating blank line with\n * them, and prettier preserves whichever spacing it finds.\n */\nexport function ensureBlankLineAfterImports(sf: SourceFile): void {\n const imports = sf.getImportDeclarations();\n const last = imports[imports.length - 1];\n const next = last?.getNextSibling();\n if (!last || !next) return;\n const between = sf.getFullText().slice(last.getEnd(), next.getStart());\n if ((between.match(/\\n/g) ?? []).length >= 2) return;\n sf.insertText(last.getEnd(), \"\\n\");\n}\n\n/** Remove a top-level function or variable declaration by name, if present. */\nexport function removeTopLevelStatementByIdentifier(\n sf: SourceFile,\n name: string,\n): { wasRemoved: boolean } {\n const fn = sf.getFunction(name);\n if (fn) {\n fn.remove();\n return { wasRemoved: true };\n }\n const vs = sf\n .getVariableStatements()\n .find((s) => s.getDeclarations().some((d) => d.getName() === name));\n if (vs) {\n vs.remove();\n return { wasRemoved: true };\n }\n return { wasRemoved: false };\n}\n\n/**\n * Add an item to the `data.navUser` array in a Svelte component's script body.\n * Idempotent: if an entry with the same `title` already exists, no-op.\n */\nexport function addNavItemToScript(\n scriptSource: string,\n title: string,\n url: string,\n icon: string,\n iconImportPath: string,\n): { source: string; wasAdded: boolean } {\n const newNavItemSnippet = `\n {\n title: '${title}',\n url: '${url}',\n icon: ${icon}\n }\n `.trim();\n\n const { source, result } = withInMemoryScript(scriptSource, (sf) => {\n const dataDecl = sf\n .getVariableDeclarations()\n .find((d) => d.getName() === \"data\");\n const dataInit = dataDecl?.getInitializer();\n if (\n !dataInit ||\n dataInit.getKind() !== SyntaxKind.ObjectLiteralExpression\n ) {\n return { wasAdded: false };\n }\n\n const obj = dataInit.asKindOrThrow(SyntaxKind.ObjectLiteralExpression);\n const navProp = obj.getProperty(\"navUser\");\n if (!navProp || navProp.getKind() !== SyntaxKind.PropertyAssignment) {\n return { wasAdded: false };\n }\n\n const init = navProp\n .asKindOrThrow(SyntaxKind.PropertyAssignment)\n .getInitializer();\n if (!init || init.getKind() !== SyntaxKind.ArrayLiteralExpression) {\n return { wasAdded: false };\n }\n\n const arr = init.asKindOrThrow(SyntaxKind.ArrayLiteralExpression);\n const exists = arr.getElements().some((el) => {\n if (el.getKind() !== SyntaxKind.ObjectLiteralExpression) return false;\n const o = el.asKindOrThrow(SyntaxKind.ObjectLiteralExpression);\n const titleProp = o.getProperty(\"title\");\n if (!titleProp || titleProp.getKind() !== SyntaxKind.PropertyAssignment) {\n return false;\n }\n const value = titleProp\n .asKindOrThrow(SyntaxKind.PropertyAssignment)\n .getInitializer();\n return (\n value?.getKind() === SyntaxKind.StringLiteral &&\n (value as StringLiteral).getLiteralText() === title\n );\n });\n\n if (exists) return { wasAdded: false };\n\n ensureImports(sf, [\n { defaultImport: icon, moduleSpecifier: iconImportPath },\n ]);\n arr.addElement(newNavItemSnippet);\n sf.formatText();\n return { wasAdded: true };\n });\n\n return { source, wasAdded: result.wasAdded };\n}\n\n/**\n * Remove the entry with the given `title` from the `data.navUser` array in a\n * Svelte component's script body. Also removes the icon import if supplied and\n * no other navUser entry references it. Idempotent: no-op if the entry or\n * navUser structure is missing.\n */\nexport function removeNavItemFromScript(\n scriptSource: string,\n title: string,\n iconImportPath?: string,\n): { source: string; wasRemoved: boolean } {\n const { source, result } = withInMemoryScript(scriptSource, (sf) => {\n const dataDecl = sf\n .getVariableDeclarations()\n .find((d) => d.getName() === \"data\");\n const dataInit = dataDecl?.getInitializer();\n if (\n !dataInit ||\n dataInit.getKind() !== SyntaxKind.ObjectLiteralExpression\n ) {\n return { wasRemoved: false };\n }\n\n const obj = dataInit.asKindOrThrow(SyntaxKind.ObjectLiteralExpression);\n const navProp = obj.getProperty(\"navUser\");\n if (!navProp || navProp.getKind() !== SyntaxKind.PropertyAssignment) {\n return { wasRemoved: false };\n }\n\n const init = navProp\n .asKindOrThrow(SyntaxKind.PropertyAssignment)\n .getInitializer();\n if (!init || init.getKind() !== SyntaxKind.ArrayLiteralExpression) {\n return { wasRemoved: false };\n }\n\n const arr = init.asKindOrThrow(SyntaxKind.ArrayLiteralExpression);\n const elements = arr.getElements();\n const index = elements.findIndex((el) => {\n if (el.getKind() !== SyntaxKind.ObjectLiteralExpression) return false;\n const o = el.asKindOrThrow(SyntaxKind.ObjectLiteralExpression);\n const titleProp = o.getProperty(\"title\");\n if (!titleProp || titleProp.getKind() !== SyntaxKind.PropertyAssignment) {\n return false;\n }\n const value = titleProp\n .asKindOrThrow(SyntaxKind.PropertyAssignment)\n .getInitializer();\n return (\n value?.getKind() === SyntaxKind.StringLiteral &&\n (value as StringLiteral).getLiteralText() === title\n );\n });\n\n if (index === -1) return { wasRemoved: false };\n\n arr.removeElement(index);\n\n if (iconImportPath) {\n const importDecl = sf\n .getImportDeclarations()\n .find((d) => d.getModuleSpecifierValue() === iconImportPath);\n if (importDecl) {\n const importName = importDecl.getDefaultImport()?.getText();\n const stillUsed =\n importName &&\n sf\n .getDescendantsOfKind(SyntaxKind.Identifier)\n .some(\n (id) =>\n id.getText() === importName &&\n id.getParent()?.getKind() !== SyntaxKind.ImportClause &&\n id.getParent()?.getKind() !== SyntaxKind.ImportSpecifier,\n );\n if (!stillUsed) {\n importDecl.remove();\n }\n }\n }\n\n sf.formatText();\n return { wasRemoved: true };\n });\n\n return { source, wasRemoved: result.wasRemoved };\n}\n"],"mappings":";;;;;AAqBA,IAAa,IAAb,MAAa,EAAW;CAKtB,YAAY,GAAgB;EAG1B,AAFA,KAAK,SAAS,GACd,KAAK,MAAM,EAAM,GAAQ,EAAE,QAAQ,GAAK,CAAC,GACzC,KAAK,IAAI,IAAI,EAAY,CAAM;CACjC;CAEA,OAAO,SAAS,GAA8B;EAC5C,OAAO,IAAI,EAAW,EAAG,aAAa,GAAU,MAAM,CAAC;CACzD;CAEA,YAAgC;EAC9B,OAAO,KAAK,YAAa,KAAK,IAAY,QAAQ;CACpD;CAEA,kBAAsC;EACpC,OAAO,KAAK,YAAa,KAAK,IAAY,MAAM;CAClD;CAEA,YAAoB,GAA+C;EACjE,IAAI,CAAC,GAAQ,OAAO;EACpB,IAAM,IAAQ,EAAO,QAAQ,OACvB,IAAM,EAAO,QAAQ;EAC3B,OAAO;GAAE,SAAS,KAAK,OAAO,MAAM,GAAO,CAAG;GAAG;GAAO;EAAI;CAC9D;CAMA,aAAa,GAA0C;EACrD,OAAO,KAAK,kBAAkB,KAAK,UAAU,GAAG,CAAE;CACpD;CAEA,mBAAmB,GAA0C;EAC3D,OAAO,KAAK,kBAAkB,KAAK,gBAAgB,GAAG,CAAE;CAC1D;CAEA,kBACE,GACA,GACS;EACT,IAAI,CAAC,GAAO,OAAO;EACnB,IAAM,IAAO,EAAG,EAAM,OAAO;EAG7B,OAFI,MAAS,EAAM,YACnB,KAAK,EAAE,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BAAwB,MAAM,CAAc;GAC7D,IAAI,GAAY;IACd,IAAM,IAAa,EAAW,iBAAiB,CAAC,EAAE,QAAQ;IAW1D,AATE,KACA,EACG,qBAAqB,EAAW,UAAU,CAAC,CAC3C,MACE,MACC,EAAG,QAAQ,MAAM,KACjB,EAAG,UAAU,CAAC,EAAE,QAAQ,MAAM,EAAW,gBACzC,EAAG,UAAU,CAAC,EAAE,QAAQ,MAAM,EAAW,eAC7C,KAEF,EAAW,OAAO;GAEtB;EACF;EAGA,OADA,EAAG,WAAW,GACP,EAAE,YAAY,GAAK;CAC5B,CAAC;CAED,OAAO;EAAE;EAAQ,YAAY,EAAO;CAAW;AACjD"}
@@ -1,6 +1,6 @@
1
1
  import { n as e, t } from "./errors-D6gyegUK.js";
2
2
  import { n } from "./logger-CQONztPm.js";
3
- import { executeCommand as r, formatPaths as i, getAllCustomComponents as a, installComponents as o, installedComponents as s, installedPackagesFromProject as c, isCustomComponent as l, n as u, t as d } from "./write-result-BN7Ff0rF.js";
3
+ import { executeCommand as r, formatPaths as i, getAllCustomComponents as a, installComponents as o, installedComponents as s, installedPackagesFromProject as c, isCustomComponent as l, n as u, t as d } from "./write-result-BVWPlGvE.js";
4
4
  import f from "node:path";
5
5
  import { existsSync as p, readFileSync as m, writeFileSync as h } from "node:fs";
6
6
  import { createRequire as g } from "node:module";
@@ -170,4 +170,4 @@ async function N(e, t) {
170
170
  //#endregion
171
171
  export { M as applyBaseColor, N as applyTheme, C as listComponents, D as switchStyle };
172
172
 
173
- //# sourceMappingURL=ui-BsG60gQg.js.map
173
+ //# sourceMappingURL=ui-BdkuOXPw.js.map