@velastack/patterns 0.2.11 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (132) hide show
  1. package/README.md +4 -3
  2. package/dist/chunks/{_layout-D0OmzCu1.js → _layout-DqH4lA_r.js} +8 -8
  3. package/dist/chunks/{_layout-D0OmzCu1.js.map → _layout-DqH4lA_r.js.map} +1 -1
  4. package/dist/chunks/{collections-DDYlpDNO.js → collections-CgdvZXmh.js} +17 -17
  5. package/dist/chunks/{collections-DDYlpDNO.js.map → collections-CgdvZXmh.js.map} +1 -1
  6. package/dist/chunks/compose-handle-Cg9jnCsS.js +322 -0
  7. package/dist/chunks/compose-handle-Cg9jnCsS.js.map +1 -0
  8. package/dist/chunks/{config-target-DOi8kI_f.js → config-target-Co-ij8p3.js} +9 -9
  9. package/dist/chunks/{config-target-DOi8kI_f.js.map → config-target-Co-ij8p3.js.map} +1 -1
  10. package/dist/chunks/dispatch-BRnt8PcW.js +6 -0
  11. package/dist/chunks/dispatch-BRnt8PcW.js.map +1 -0
  12. package/dist/chunks/format-result-Cb2hWsb8.js +64 -0
  13. package/dist/chunks/format-result-Cb2hWsb8.js.map +1 -0
  14. package/dist/chunks/generate-BkQ1xMDp.js +30 -0
  15. package/dist/chunks/generate-BkQ1xMDp.js.map +1 -0
  16. package/dist/chunks/{generate-Va1sxVPG.js → generate-DRA63W0r.js} +17 -64
  17. package/dist/chunks/generate-DRA63W0r.js.map +1 -0
  18. package/dist/chunks/generate-_LvrYK6i.js +55 -0
  19. package/dist/chunks/generate-_LvrYK6i.js.map +1 -0
  20. package/dist/chunks/generate-iQP31-m1.js +252 -0
  21. package/dist/chunks/generate-iQP31-m1.js.map +1 -0
  22. package/dist/chunks/{generate.runtime-Dtf2BI_5.js → generate.runtime-B0hhtyAL.js} +9 -9
  23. package/dist/chunks/{generate.runtime-Dtf2BI_5.js.map → generate.runtime-B0hhtyAL.js.map} +1 -1
  24. package/dist/chunks/generate.runtime-B49wetSx.js +122 -0
  25. package/dist/chunks/generate.runtime-B49wetSx.js.map +1 -0
  26. package/dist/chunks/{generate.runtime-SQhCLSah.js → generate.runtime-B7LRx-BU.js} +13 -13
  27. package/dist/chunks/{generate.runtime-SQhCLSah.js.map → generate.runtime-B7LRx-BU.js.map} +1 -1
  28. package/dist/chunks/generate.runtime-BKo-Nidn.js +38 -0
  29. package/dist/chunks/generate.runtime-BKo-Nidn.js.map +1 -0
  30. package/dist/chunks/{generate.runtime-vTneb2SY.js → generate.runtime-BORbegw_.js} +111 -101
  31. package/dist/chunks/generate.runtime-BORbegw_.js.map +1 -0
  32. package/dist/chunks/{generate.runtime-BtX_9lLk.js → generate.runtime-BbIN0tUZ.js} +34 -34
  33. package/dist/chunks/{generate.runtime-BtX_9lLk.js.map → generate.runtime-BbIN0tUZ.js.map} +1 -1
  34. package/dist/chunks/{generate.runtime-OjW1XETW.js → generate.runtime-BnWE4qsu.js} +42 -42
  35. package/dist/chunks/generate.runtime-BnWE4qsu.js.map +1 -0
  36. package/dist/chunks/{generate.runtime-B_Fk1Jjs.js → generate.runtime-BwhGDnGu.js} +32 -35
  37. package/dist/chunks/generate.runtime-BwhGDnGu.js.map +1 -0
  38. package/dist/chunks/{generate.runtime-BgezGu15.js → generate.runtime-CCg2Pjcv.js} +95 -94
  39. package/dist/chunks/generate.runtime-CCg2Pjcv.js.map +1 -0
  40. package/dist/chunks/{generate.runtime-DRcq4d5D.js → generate.runtime-CRYjWJRe.js} +31 -31
  41. package/dist/chunks/{generate.runtime-DRcq4d5D.js.map → generate.runtime-CRYjWJRe.js.map} +1 -1
  42. package/dist/chunks/generate.runtime-CcuAXuV2.js +60 -0
  43. package/dist/chunks/generate.runtime-CcuAXuV2.js.map +1 -0
  44. package/dist/chunks/{generate.runtime-DK7iXmAZ.js → generate.runtime-D0icLb5j.js} +50 -47
  45. package/dist/chunks/{generate.runtime-DK7iXmAZ.js.map → generate.runtime-D0icLb5j.js.map} +1 -1
  46. package/dist/chunks/{generate.runtime-fSDNxfGG.js → generate.runtime-D2e_KRj0.js} +11 -11
  47. package/dist/chunks/{generate.runtime-fSDNxfGG.js.map → generate.runtime-D2e_KRj0.js.map} +1 -1
  48. package/dist/chunks/{generate.runtime-CycY6kPr.js → generate.runtime-D44gjxRA.js} +102 -99
  49. package/dist/chunks/generate.runtime-D44gjxRA.js.map +1 -0
  50. package/dist/chunks/{generate.runtime-AjCpCfv3.js → generate.runtime-D8vgh5MH.js} +186 -138
  51. package/dist/chunks/generate.runtime-D8vgh5MH.js.map +1 -0
  52. package/dist/chunks/generate.runtime-DAmYsIvF.js +32 -0
  53. package/dist/chunks/generate.runtime-DAmYsIvF.js.map +1 -0
  54. package/dist/chunks/{generate.runtime-B6kxV3Bi.js → generate.runtime-DNaQxed-.js} +45 -45
  55. package/dist/chunks/{generate.runtime-B6kxV3Bi.js.map → generate.runtime-DNaQxed-.js.map} +1 -1
  56. package/dist/chunks/{generate.runtime-CZQoVNt3.js → generate.runtime-DOuufRLr.js} +35 -35
  57. package/dist/chunks/generate.runtime-DOuufRLr.js.map +1 -0
  58. package/dist/chunks/{generate.runtime-BpYOznG5.js → generate.runtime-DSqkXvps.js} +21 -21
  59. package/dist/chunks/{generate.runtime-BpYOznG5.js.map → generate.runtime-DSqkXvps.js.map} +1 -1
  60. package/dist/chunks/{generate.runtime-BYJZB1ad.js → generate.runtime-DhkaXTq3.js} +37 -57
  61. package/dist/chunks/generate.runtime-DhkaXTq3.js.map +1 -0
  62. package/dist/chunks/{generate.runtime-Cq1gqxzg.js → generate.runtime-DoZdSh9W.js} +22 -22
  63. package/dist/chunks/{generate.runtime-Cq1gqxzg.js.map → generate.runtime-DoZdSh9W.js.map} +1 -1
  64. package/dist/chunks/{generate.runtime-qjsxSPaH.js → generate.runtime-S5RIgbQx.js} +102 -99
  65. package/dist/chunks/generate.runtime-S5RIgbQx.js.map +1 -0
  66. package/dist/chunks/generate.runtime-WmSMWL15.js +82 -0
  67. package/dist/chunks/generate.runtime-WmSMWL15.js.map +1 -0
  68. package/dist/chunks/generate.runtime-acRmiU7e.js +81 -0
  69. package/dist/chunks/generate.runtime-acRmiU7e.js.map +1 -0
  70. package/dist/chunks/generate.runtime-flFRYzpi.js +145 -0
  71. package/dist/chunks/generate.runtime-flFRYzpi.js.map +1 -0
  72. package/dist/chunks/generate.runtime-gtpOuLNO.js +110 -0
  73. package/dist/chunks/generate.runtime-gtpOuLNO.js.map +1 -0
  74. package/dist/chunks/{generate.runtime-DHRCNPVx.js → generate.runtime-kLxeDGnS.js} +23 -23
  75. package/dist/chunks/{generate.runtime-DHRCNPVx.js.map → generate.runtime-kLxeDGnS.js.map} +1 -1
  76. package/dist/chunks/{generate.runtime-DH9o-888.js → generate.runtime-wA1G3tQ4.js} +27 -27
  77. package/dist/chunks/{generate.runtime-DH9o-888.js.map → generate.runtime-wA1G3tQ4.js.map} +1 -1
  78. package/dist/chunks/modify-file-GQD6uNgI.js +254 -0
  79. package/dist/chunks/modify-file-GQD6uNgI.js.map +1 -0
  80. package/dist/chunks/{modify-svelte-config-remote-D3eBzcZc.js → modify-svelte-config-remote-CDKs_Qi0.js} +2 -2
  81. package/dist/chunks/{modify-svelte-config-remote-D3eBzcZc.js.map → modify-svelte-config-remote-CDKs_Qi0.js.map} +1 -1
  82. package/dist/chunks/{pocketbase-BerjVikJ.js → pocketbase-CeG5BMN2.js} +57 -50
  83. package/dist/chunks/{pocketbase-BerjVikJ.js.map → pocketbase-CeG5BMN2.js.map} +1 -1
  84. package/dist/chunks/providers-DO9kMyzB.js +69 -0
  85. package/dist/chunks/providers-DO9kMyzB.js.map +1 -0
  86. package/dist/chunks/rolldown-runtime-DArdT4gl.js +23 -0
  87. package/dist/chunks/{shared-Cmbzu7Od.js → shared-BwHQM-a9.js} +2 -2
  88. package/dist/chunks/{shared-Cmbzu7Od.js.map → shared-BwHQM-a9.js.map} +1 -1
  89. package/dist/chunks/site-D027dpBm.js +55 -0
  90. package/dist/chunks/site-D027dpBm.js.map +1 -0
  91. package/dist/chunks/svelte-file-B3RfgVdt.js +123 -0
  92. package/dist/chunks/svelte-file-B3RfgVdt.js.map +1 -0
  93. package/dist/chunks/{test-setup-DjbhQYZC.js → test-setup-B2hd8I-s.js} +15 -15
  94. package/dist/chunks/{test-setup-DjbhQYZC.js.map → test-setup-B2hd8I-s.js.map} +1 -1
  95. package/dist/chunks/{ui-BdkuOXPw.js → ui-B4Tuit-7.js} +12 -12
  96. package/dist/chunks/{ui-BdkuOXPw.js.map → ui-B4Tuit-7.js.map} +1 -1
  97. package/dist/chunks/ui-jhXrsw4T.js +12 -0
  98. package/dist/chunks/ui-jhXrsw4T.js.map +1 -0
  99. package/dist/chunks/{write-result-BVWPlGvE.js → write-result-DewHCNhM.js} +51 -51
  100. package/dist/chunks/{write-result-BVWPlGvE.js.map → write-result-DewHCNhM.js.map} +1 -1
  101. package/dist/index.d.ts +272 -65
  102. package/dist/index.js +2279 -2268
  103. package/dist/index.js.map +1 -1
  104. package/package.json +1 -1
  105. package/dist/chunks/dispatch-B5PfQ2CA.js +0 -6
  106. package/dist/chunks/dispatch-B5PfQ2CA.js.map +0 -1
  107. package/dist/chunks/format-result-BdAy5M8C.js +0 -50
  108. package/dist/chunks/format-result-BdAy5M8C.js.map +0 -1
  109. package/dist/chunks/generate-Va1sxVPG.js.map +0 -1
  110. package/dist/chunks/generate.runtime-AjCpCfv3.js.map +0 -1
  111. package/dist/chunks/generate.runtime-BYJZB1ad.js.map +0 -1
  112. package/dist/chunks/generate.runtime-B_Fk1Jjs.js.map +0 -1
  113. package/dist/chunks/generate.runtime-BcVAKzoY.js +0 -138
  114. package/dist/chunks/generate.runtime-BcVAKzoY.js.map +0 -1
  115. package/dist/chunks/generate.runtime-BgezGu15.js.map +0 -1
  116. package/dist/chunks/generate.runtime-CTiJEVF2.js +0 -107
  117. package/dist/chunks/generate.runtime-CTiJEVF2.js.map +0 -1
  118. package/dist/chunks/generate.runtime-CZQoVNt3.js.map +0 -1
  119. package/dist/chunks/generate.runtime-CycY6kPr.js.map +0 -1
  120. package/dist/chunks/generate.runtime-D2WfvXm2.js +0 -106
  121. package/dist/chunks/generate.runtime-D2WfvXm2.js.map +0 -1
  122. package/dist/chunks/generate.runtime-DEl6b1Ti.js +0 -87
  123. package/dist/chunks/generate.runtime-DEl6b1Ti.js.map +0 -1
  124. package/dist/chunks/generate.runtime-DaPNrIyg.js +0 -28
  125. package/dist/chunks/generate.runtime-DaPNrIyg.js.map +0 -1
  126. package/dist/chunks/generate.runtime-OjW1XETW.js.map +0 -1
  127. package/dist/chunks/generate.runtime-qjsxSPaH.js.map +0 -1
  128. package/dist/chunks/generate.runtime-vTneb2SY.js.map +0 -1
  129. package/dist/chunks/modify-file-Cgu_WeFk.js +0 -22
  130. package/dist/chunks/modify-file-Cgu_WeFk.js.map +0 -1
  131. package/dist/chunks/ts-morph-helpers-teS3yXg-.js +0 -229
  132. package/dist/chunks/ts-morph-helpers-teS3yXg-.js.map +0 -1
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@velastack/patterns",
3
- "version": "0.2.11",
3
+ "version": "0.3.0",
4
4
  "description": "Registry of VelaStack patterns: generators and modifications applied to SvelteKit projects by the VelaStack CLI.",
5
5
  "type": "module",
6
6
  "private": false,
@@ -1,6 +0,0 @@
1
- //#region src/patterns/enable/subscriptions/preview-modifies/src/lib/components/app-sidebar.svelte?raw
2
- var e = "<script lang=\"ts\" module>\n import HomeIcon from '@lucide/svelte/icons/home';\n\n let data = {\n navMain: [\n {\n title: 'Dashboard',\n url: '/dashboard',\n icon: HomeIcon\n }\n ]\n };\n<\/script>\n\n<script lang=\"ts\">\n import favicon from '$lib/assets/favicon.svg';\n\n import NavMain from './nav-main.svelte';\n import NavUser from './nav-user.svelte';\n import * as Sidebar from '$lib/components/ui/sidebar';\n import type { ComponentProps } from 'svelte';\n\n let {\n user,\n meta,\n // [!code highlight:1]\n subscription = null,\n ref = $bindable(null),\n ...restProps\n }: ComponentProps<typeof Sidebar.Root> & {\n user: any;\n meta: any;\n // [!code highlight:1]\n subscription?: { id: string; productName: string | null } | null;\n } = $props();\n<\/script>\n\n<Sidebar.Root bind:ref variant=\"inset\" {...restProps}>\n <Sidebar.Header>\n <Sidebar.Menu>\n <Sidebar.MenuItem>\n <Sidebar.MenuButton size=\"lg\">\n {#snippet child({ props })}\n <a href=\"/dashboard\" {...props}>\n <div\n class=\"bg-sidebar-accent text-sidebar-primary-foreground flex aspect-square size-8 items-center justify-center rounded-lg\"\n >\n <img src={favicon} alt=\"logo\" class=\"size-6\" />\n </div>\n <div class=\"grid flex-1 text-left text-sm leading-tight\">\n <span class=\"truncate font-medium\">{meta.appName}</span>\n </div>\n </a>\n {/snippet}\n </Sidebar.MenuButton>\n </Sidebar.MenuItem>\n </Sidebar.Menu>\n </Sidebar.Header>\n <Sidebar.Content>\n <NavMain items={data.navMain} />\n </Sidebar.Content>\n <Sidebar.Footer>\n <NavUser {user} {subscription} />\n </Sidebar.Footer>\n</Sidebar.Root>\n", t = "<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 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 {\n title: \"Billing\",\n url: \"/billing\",\n icon: CreditCardIcon,\n },\n ],\n };\n\n let {\n user,\n // [!code highlight:1]\n subscription = null,\n }: {\n user: {\n id: string;\n name: string;\n email: string;\n avatar: string;\n };\n // [!code highlight:1]\n subscription?: { id: string; productName: string | null } | null;\n } = $props();\n\n // [!code highlight:1]\n const planLabel = $derived(subscription?.productName ?? \"Free\");\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\n src=\"/api/files/users/{user.id}/{user.avatar}\"\n alt={user.name}\n />\n {/if}\n <Avatar.Fallback class=\"rounded-lg\">\n {user.name?.charAt(0).toUpperCase() ||\n 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\">\n {user.name || user.email}\n </span>\n <!-- [!code highlight:3] -->\n <span class=\"truncate text-xs text-muted-foreground\">\n {planLabel}\n </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\n src=\"/api/files/users/{user.id}/{user.avatar}\"\n alt={user.name}\n />\n {/if}\n <Avatar.Fallback class=\"rounded-lg\">\n {user.name?.charAt(0).toUpperCase() ||\n 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\">\n {user.name || user.email}\n </span>\n <!-- [!code highlight:3] -->\n <span class=\"truncate text-xs\">\n {planLabel}\n </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\n href={item.url}\n class=\"flex cursor-default items-center gap-2 px-2 py-1.5 w-full\"\n >\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\n type=\"submit\"\n class=\"flex cursor-default items-center gap-2 px-2 py-1.5 w-full\"\n >\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", n = "// [!code highlight:33]\nasync function loadActiveSubscription(locals: App.Locals, userId: string) {\n const subscriptions = await locals.admin\n .collection(\"stripe_subscriptions\")\n .getFullList({\n filter: locals.admin.filter(\n 'user = {:user} && (status = \"active\" || status = \"trialing\")',\n { user: userId },\n ),\n expand: \"price\",\n sort: \"-created\",\n })\n .catch(() => []);\n\n const sub = subscriptions[0];\n if (!sub) return null;\n\n const price = sub.expand?.price;\n let productName: string | null = null;\n if (price?.product) {\n const product = await locals.admin\n .collection(\"stripe_products\")\n .getOne(price.product)\n .catch(() => null);\n productName = product?.name ?? null;\n }\n\n return {\n id: sub.id,\n status: sub.status as string,\n productName,\n cancelAtPeriodEnd: Boolean(sub.cancel_at_period_end),\n };\n}\n\nexport const load = async ({ locals }) => {\n const user = locals.pb.authStore.record!;\n const breadcrumbs = [{ title: \"Home\", url: \"/dashboard\" }];\n // [!code highlight:1]\n const subscription = await loadActiveSubscription(locals, user.id);\n\n // [!code highlight:1]\n return { user, breadcrumbs, subscription };\n};\n", r = "<script lang=\"ts\">\n import * as Sidebar from \"$lib/components/ui/sidebar\";\n import { Separator } from \"$lib/components/ui/separator\";\n import AppSidebar from \"$lib/components/app-sidebar.svelte\";\n import * as Breadcrumb from \"$lib/components/ui/breadcrumb\";\n import { page } from \"$app/state\";\n\n let breadcrumbs = $derived(page.data.breadcrumbs || []) as {\n title: string;\n url: string;\n }[];\n let { data, children } = $props();\n<\/script>\n\n<div class=\"min-h-dvh dashboard\">\n <Sidebar.Provider>\n <!-- [!code highlight:5] -->\n <AppSidebar\n user={data.user}\n meta={data.meta}\n subscription={data.subscription}\n />\n <Sidebar.Inset>\n <header class=\"flex h-16 shrink-0 items-center gap-2\">\n <div class=\"flex items-center gap-2 px-4\">\n <Sidebar.Trigger class=\"-ml-1\" />\n <Separator\n orientation=\"vertical\"\n class=\"mr-2 data-[orientation=vertical]:h-4\"\n />\n {#if breadcrumbs.length > 0}\n <Breadcrumb.Root>\n <Breadcrumb.List>\n {#if breadcrumbs.length > 1}\n {#each breadcrumbs.slice(0, -1) as breadcrumb}\n <Breadcrumb.Item>\n <Breadcrumb.Link href={breadcrumb.url}\n >{breadcrumb.title}</Breadcrumb.Link\n >\n </Breadcrumb.Item>\n <Breadcrumb.Separator />\n {/each}\n {/if}\n <Breadcrumb.Page>\n {breadcrumbs[breadcrumbs.length - 1].title}\n </Breadcrumb.Page>\n </Breadcrumb.List>\n </Breadcrumb.Root>\n {/if}\n </div>\n </header>\n <div class=\"flex flex-1 flex-col p-4 pt-0\">\n {@render children?.()}\n </div>\n </Sidebar.Inset>\n </Sidebar.Provider>\n</div>\n\n<style>\n :global(body:has(div.dashboard)) {\n background-color: var(--color-sidebar);\n }\n</style>\n", i = "import { error } from \"@sveltejs/kit\";\nimport stripe from \"$lib/stripe\";\n\ntype RecurringInfo = {\n interval: string;\n interval_count: number;\n trial_period_days?: number | null;\n};\n\nfunction parseRecurring(value: unknown): RecurringInfo | null {\n if (!value) return null;\n if (typeof value === \"object\") return value as RecurringInfo;\n try {\n return JSON.parse(value as string) as RecurringInfo;\n } catch {\n return null;\n }\n}\n\nconst ACTIVE_SUBSCRIPTION_STATUSES = [\n \"active\",\n \"trialing\",\n \"past_due\",\n \"incomplete\",\n];\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 {\n paymentMethods: [],\n user,\n billingReady: false,\n hasDefaultPaymentMethod: false,\n activeSubscription: null,\n availablePlans: [],\n };\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 const subscriptionRecords = await locals.admin\n .collection(\"stripe_subscriptions\")\n .getFullList({\n filter: locals.admin.filter(\"user = {:user}\", { user: user.id }),\n expand: \"price\",\n sort: \"-created\",\n });\n\n const recurringPrices = await locals.admin\n .collection(\"stripe_prices\")\n .getFullList({\n filter: locals.admin.filter(\"type = {:type} && active = true\", {\n type: \"recurring\",\n }),\n });\n\n const productIds: string[] = Array.from(\n new Set(\n recurringPrices\n .map((p) => p.product)\n .filter((id): id is string => Boolean(id)),\n ),\n );\n const productMap = new Map<string, string>();\n if (productIds.length > 0) {\n const products = await locals.admin\n .collection(\"stripe_products\")\n .getFullList({\n filter: productIds.map((id) => `id = \"${id}\"`).join(\" || \"),\n });\n for (const product of products) {\n productMap.set(product.id, product.name ?? product.id);\n }\n }\n\n const availablePlans = recurringPrices.map((price) => ({\n id: price.id,\n productName:\n (price.product && productMap.get(price.product)) ?? price.product ?? \"\",\n unitAmount: (price.unit_amount ?? 0) as number,\n currency: (price.currency ?? \"\") as string,\n recurring: parseRecurring(price.recurring),\n }));\n\n const subscriptions = subscriptionRecords.map((sub) => {\n const expanded = sub.expand?.price;\n return {\n id: sub.id,\n status: sub.status as string,\n currentPeriodStart: (sub.current_period_start as string | null) ?? null,\n currentPeriodEnd: (sub.current_period_end as string | null) ?? null,\n cancelAtPeriodEnd: Boolean(sub.cancel_at_period_end),\n canceledAt: (sub.canceled_at as string | null) || null,\n priceId: sub.price as string,\n productName: expanded\n ? ((expanded.product && productMap.get(expanded.product)) ??\n expanded.product ??\n null)\n : null,\n unitAmount: expanded ? ((expanded.unit_amount ?? null) as number | null) : null,\n currency: expanded ? ((expanded.currency ?? null) as string | null) : null,\n recurring: expanded ? parseRecurring(expanded.recurring) : null,\n };\n });\n\n const activeSubscription =\n subscriptions.find((s) => ACTIVE_SUBSCRIPTION_STATUSES.includes(s.status)) ||\n null;\n\n // If the active plan isn't in the list (e.g., price was deactivated), include\n // it so it can still be shown as the current plan.\n if (\n activeSubscription &&\n !availablePlans.some((p) => p.id === activeSubscription.priceId)\n ) {\n availablePlans.push({\n id: activeSubscription.priceId,\n productName: activeSubscription.productName ?? \"\",\n unitAmount: activeSubscription.unitAmount ?? 0,\n currency: activeSubscription.currency ?? \"\",\n recurring: activeSubscription.recurring,\n });\n }\n\n availablePlans.sort((a, b) => a.unitAmount - b.unitAmount);\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 hasDefaultPaymentMethod: Boolean(customer.default_payment_method),\n activeSubscription,\n availablePlans,\n };\n};\n\nasync function getUserCustomer(locals: App.Locals) {\n const userId = locals.pb.authStore.record?.id;\n if (!userId) {\n return error(401, \"Unauthorized\");\n }\n const customer = await locals.admin\n .collection(\"stripe_customers\")\n .getFirstListItem(`user.id = \"${userId}\"`);\n if (!customer || !customer.id) {\n return error(400, \"Customer not found\");\n }\n return customer;\n}\n\n// A subscription can be updated in-place unless it has fully terminated.\nconst UPDATABLE_STATUSES = [\n \"active\",\n \"trialing\",\n \"past_due\",\n \"incomplete\",\n \"paused\",\n];\n\nasync function findUpdatableSubscription(\n locals: App.Locals,\n userId: string,\n) {\n const filterClause = UPDATABLE_STATUSES.map(\n (s) => `status = \"${s}\"`,\n ).join(\" || \");\n const subs = await locals.admin\n .collection(\"stripe_subscriptions\")\n .getFullList({\n filter: locals.admin.filter(`user = {:user} && (${filterClause})`, {\n user: userId,\n }),\n sort: \"-created\",\n });\n return subs[0] ?? null;\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 selectPlan: async ({ locals, request }) => {\n const formData = await request.formData();\n const priceId = formData.get(\"priceId\") as string;\n if (!priceId) return error(400, \"Price ID is required\");\n\n const userId = locals.pb.authStore.record?.id;\n if (!userId) return error(401, \"Unauthorized\");\n\n // If an updatable subscription already exists, change its price in place\n // rather than creating a duplicate. Covers switch, resume-to-different-plan,\n // and races where the webhook hasn't delivered the existing sub yet.\n const existing = await findUpdatableSubscription(locals, userId);\n if (existing) {\n const stripeSub = await stripe.subscriptions.retrieve(existing.id);\n const item = stripeSub.items.data[0];\n if (!item) return error(500, \"Subscription has no items\");\n\n await stripe.subscriptions.update(existing.id, {\n items: [{ id: item.id, price: priceId }],\n proration_behavior: \"create_prorations\",\n cancel_at_period_end: false,\n });\n return;\n }\n\n const customer = await getUserCustomer(locals);\n if (!customer.default_payment_method) {\n return error(400, \"Add a default payment method before subscribing\");\n }\n\n await stripe.subscriptions.create({\n customer: customer.id,\n items: [{ price: priceId }],\n default_payment_method: customer.default_payment_method,\n payment_behavior: \"error_if_incomplete\",\n off_session: true,\n });\n },\n cancelSubscription: async ({ locals, request }) => {\n const formData = await request.formData();\n const subscriptionId = formData.get(\"subscriptionId\") as string;\n if (!subscriptionId) return error(400, \"Subscription ID is required\");\n\n const userId = locals.pb.authStore.record?.id;\n if (!userId) return error(401, \"Unauthorized\");\n\n // Verify the subscription belongs to this user before touching Stripe.\n try {\n const record = await locals.admin\n .collection(\"stripe_subscriptions\")\n .getOne(subscriptionId);\n if (record.user !== userId) {\n return error(403, \"Forbidden\");\n }\n } catch {\n return error(404, \"Subscription not found\");\n }\n\n await stripe.subscriptions.update(subscriptionId, {\n cancel_at_period_end: true,\n });\n },\n resumeSubscription: async ({ locals, request }) => {\n const formData = await request.formData();\n const subscriptionId = formData.get(\"subscriptionId\") as string;\n if (!subscriptionId) return error(400, \"Subscription ID is required\");\n\n const userId = locals.pb.authStore.record?.id;\n if (!userId) return error(401, \"Unauthorized\");\n\n try {\n const record = await locals.admin\n .collection(\"stripe_subscriptions\")\n .getOne(subscriptionId);\n if (record.user !== userId) {\n return error(403, \"Forbidden\");\n }\n } catch {\n return error(404, \"Subscription not found\");\n }\n\n await stripe.subscriptions.update(subscriptionId, {\n cancel_at_period_end: false,\n });\n },\n};\n", a = "<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, Package } from '@lucide/svelte';\n import { toast } from 'svelte-sonner';\n import { invalidate, invalidateAll } from '$app/navigation';\n import { untrack } from 'svelte';\n\n let { data } = $props();\n let paymentMethods = $derived(data.paymentMethods);\n let availablePlans = $derived(data.availablePlans);\n let hasDefaultPaymentMethod = $derived(data.hasDefaultPaymentMethod);\n\n // Local, mutable mirror of the server-side subscription. We optimistically\n // update it on user actions so the UI reflects the change immediately; the\n // $effect re-syncs from the server after the webhook has had a chance to\n // fire (invalidateAll runs on a short delay below).\n let activeSubscription = $state(untrack(() => data.activeSubscription));\n $effect(() => {\n activeSubscription = data.activeSubscription;\n });\n let showDeleteDialog = $state(false);\n let selectedPaymentMethodId = $state<string | null>(null);\n let isProcessing = $state(false);\n let showCancelDialog = $state(false);\n let isSubscribing = $state<string | null>(null);\n let isCanceling = $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\n function formatAmount(amount: number | null, currency: string | null) {\n if (amount === null || !currency) return '—';\n return new Intl.NumberFormat('en-US', {\n style: 'currency',\n currency: currency.toUpperCase()\n }).format(amount / 100);\n }\n\n function formatInterval(recurring: { interval: string; interval_count: number } | null) {\n if (!recurring) return '';\n if (recurring.interval_count === 1) return `/ ${recurring.interval}`;\n return `every ${recurring.interval_count} ${recurring.interval}s`;\n }\n\n function formatDate(iso: string | null) {\n if (!iso) return '—';\n return new Date(iso).toLocaleDateString(undefined, {\n year: 'numeric',\n month: 'short',\n day: 'numeric'\n });\n }\n\n async function selectPlan(priceId: string, successMessage: string) {\n if (!hasDefaultPaymentMethod) {\n toast.error('Add a default payment method first');\n return;\n }\n const previous = activeSubscription;\n const plan = availablePlans.find((p) => p.id === priceId);\n if (plan) {\n activeSubscription = previous\n ? {\n ...previous,\n priceId,\n productName: plan.productName,\n unitAmount: plan.unitAmount,\n currency: plan.currency,\n recurring: plan.recurring,\n cancelAtPeriodEnd: false\n }\n : {\n id: 'pending',\n status: 'active',\n priceId,\n productName: plan.productName,\n unitAmount: plan.unitAmount,\n currency: plan.currency,\n recurring: plan.recurring,\n cancelAtPeriodEnd: false,\n currentPeriodStart: null,\n currentPeriodEnd: null,\n canceledAt: null\n };\n }\n\n isSubscribing = priceId;\n try {\n const formData = new FormData();\n formData.append('priceId', priceId);\n\n const res = await fetch('?/selectPlan', {\n method: 'POST',\n body: formData\n });\n\n if (!res.ok) {\n throw new Error(`selectPlan failed: ${res.status}`);\n }\n\n toast.success(successMessage);\n setTimeout(() => {\n invalidateAll();\n }, 2000);\n } catch (err) {\n console.error('Error selecting plan:', err);\n toast.error('Failed to update plan');\n activeSubscription = previous;\n } finally {\n isSubscribing = null;\n }\n }\n\n async function subscribe(priceId: string) {\n await selectPlan(priceId, 'Subscription started');\n }\n\n async function switchPlan(priceId: string) {\n await selectPlan(priceId, 'Subscription updated');\n }\n\n async function resumeSubscription() {\n if (!activeSubscription) return;\n const previous = activeSubscription;\n isSubscribing = activeSubscription.priceId;\n activeSubscription = { ...activeSubscription, cancelAtPeriodEnd: false };\n try {\n const formData = new FormData();\n formData.append('subscriptionId', previous.id);\n\n const res = await fetch('?/resumeSubscription', {\n method: 'POST',\n body: formData\n });\n\n if (!res.ok) {\n throw new Error(`Resume failed: ${res.status}`);\n }\n\n toast.success('Subscription resumed');\n setTimeout(() => {\n invalidateAll();\n }, 2000);\n } catch (err) {\n console.error('Error resuming subscription:', err);\n toast.error('Failed to resume subscription');\n activeSubscription = previous;\n } finally {\n isSubscribing = null;\n }\n }\n\n async function handleCancelSubscription() {\n if (!activeSubscription) return;\n const previous = activeSubscription;\n isCanceling = true;\n activeSubscription = { ...activeSubscription, cancelAtPeriodEnd: true };\n try {\n const formData = new FormData();\n formData.append('subscriptionId', previous.id);\n\n const res = await fetch('?/cancelSubscription', {\n method: 'POST',\n body: formData\n });\n\n if (!res.ok) {\n throw new Error(`Cancel failed: ${res.status}`);\n }\n\n toast.success('Subscription will cancel at period end');\n showCancelDialog = false;\n setTimeout(() => {\n invalidateAll();\n }, 2000);\n } catch (err) {\n console.error('Error canceling subscription:', err);\n toast.error('Failed to cancel subscription');\n activeSubscription = previous;\n } finally {\n isCanceling = false;\n }\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\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\">Plan</h2>\n <p class=\"mt-1 text-sm/6 text-gray-600 dark:text-gray-400\">Manage your subscription.</p>\n </div>\n\n <div class=\"md:col-span-2\">\n <Card.Root>\n <Card.Content>\n {#if availablePlans.length === 0}\n <div\n class=\"text-muted-foreground flex flex-col items-center justify-center py-12 text-center\"\n >\n <Package class=\"mb-4 size-12 opacity-50\" />\n <p class=\"mb-2 text-lg font-medium\">No plans available</p>\n <p class=\"text-sm\">Check back soon.</p>\n </div>\n {:else}\n {#if !hasDefaultPaymentMethod}\n <p class=\"text-muted-foreground mb-4 rounded-md border border-dashed p-3 text-sm\">\n Add a default payment method above to subscribe.\n </p>\n {/if}\n <div class=\"space-y-4\">\n {#each availablePlans as plan (plan.id)}\n {@const isCurrent = activeSubscription?.priceId === plan.id}\n <div\n class=\"flex items-center justify-between rounded-lg border p-4 transition-colors {isCurrent\n ? 'border-primary ring-primary ring-1'\n : 'border-border hover:bg-accent/50'}\"\n >\n <div class=\"flex items-center gap-4\">\n <div class=\"bg-muted flex size-12 items-center justify-center rounded-lg\">\n <Package class=\"size-5\" />\n </div>\n <div>\n <div class=\"flex items-center gap-2\">\n <p class=\"font-medium\">{plan.productName}</p>\n {#if isCurrent && activeSubscription}\n {#if activeSubscription.cancelAtPeriodEnd}\n <Badge variant=\"outline\">Pending cancellation</Badge>\n {:else if activeSubscription.status === 'trialing'}\n <Badge variant=\"secondary\">Trial</Badge>\n {:else if activeSubscription.status === 'past_due'}\n <Badge variant=\"destructive\">Past due</Badge>\n {:else}\n <Badge variant=\"secondary\">\n <Check class=\"mr-1 size-3\" />\n Current\n </Badge>\n {/if}\n {/if}\n </div>\n <p class=\"text-muted-foreground text-sm\">\n {formatAmount(plan.unitAmount, plan.currency)}\n {formatInterval(plan.recurring)}\n {#if isCurrent && activeSubscription?.currentPeriodEnd}\n <span>\n &bull;\n {activeSubscription.cancelAtPeriodEnd ? 'Cancels on' : 'Renews on'}\n {formatDate(activeSubscription.currentPeriodEnd)}\n </span>\n {/if}\n </p>\n </div>\n </div>\n <div class=\"flex items-center gap-2\">\n {#if isCurrent && activeSubscription}\n {#if activeSubscription.cancelAtPeriodEnd}\n <Button\n variant=\"outline\"\n size=\"sm\"\n disabled={isSubscribing === plan.id}\n onclick={resumeSubscription}\n >\n {isSubscribing === plan.id ? 'Resuming...' : 'Resume'}\n </Button>\n {:else}\n <Button\n variant=\"outline\"\n size=\"sm\"\n onclick={() => (showCancelDialog = true)}\n >\n Cancel subscription\n </Button>\n {/if}\n {:else if activeSubscription}\n <Button\n variant=\"outline\"\n size=\"sm\"\n disabled={!hasDefaultPaymentMethod || isSubscribing === plan.id}\n onclick={() => switchPlan(plan.id)}\n >\n {isSubscribing === plan.id ? 'Switching...' : 'Switch'}\n </Button>\n {:else}\n <Button\n variant=\"outline\"\n size=\"sm\"\n disabled={!hasDefaultPaymentMethod || isSubscribing === plan.id}\n onclick={() => subscribe(plan.id)}\n >\n {isSubscribing === plan.id ? 'Subscribing...' : 'Subscribe'}\n </Button>\n {/if}\n </div>\n </div>\n {/each}\n </div>\n {/if}\n </Card.Content>\n </Card.Root>\n </div>\n </div>\n</div>\n\n<!-- Cancel Subscription Dialog -->\n<AlertDialog.Root bind:open={showCancelDialog}>\n <AlertDialog.Content>\n <AlertDialog.Header>\n <AlertDialog.Title>Cancel Subscription</AlertDialog.Title>\n <AlertDialog.Description>\n Your subscription will remain active until the end of the current billing period, then\n cancel automatically.\n </AlertDialog.Description>\n </AlertDialog.Header>\n <AlertDialog.Footer>\n <AlertDialog.Cancel onclick={() => (showCancelDialog = false)}>\n Keep Subscription\n </AlertDialog.Cancel>\n <AlertDialog.Action onclick={handleCancelSubscription} disabled={isCanceling}>\n {isCanceling ? 'Canceling...' : 'Cancel at Period End'}\n </AlertDialog.Action>\n </AlertDialog.Footer>\n </AlertDialog.Content>\n</AlertDialog.Root>\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", o = "import type Stripe from 'stripe';\nimport { handlePaymentIntentSucceeded } from './payment-intent/succeeded';\nimport { handlePaymentMethodAttached } from './payment-method/attached';\nimport { handleSubscriptionCreated } from './subscription/created';\nimport { handleSubscriptionUpdated } from './subscription/updated';\nimport { handleSubscriptionDeleted } from './subscription/deleted';\n\n/**\n * Routes a verified Stripe event to its handler. Runs inside the stripe-event\n * workflow, so a handler that throws is retried with backoff rather than lost.\n */\nexport async function dispatchStripeEvent(event: Stripe.Event, locals: App.Locals) {\n switch (event.type) {\n case 'payment_intent.succeeded':\n await handlePaymentIntentSucceeded(event.data.object, locals);\n break;\n\n case 'payment_method.attached':\n await handlePaymentMethodAttached(event.data.object, locals);\n break;\n\n case 'customer.subscription.created':\n await handleSubscriptionCreated(event.data.object, locals);\n break;\n\n case 'customer.subscription.updated':\n await handleSubscriptionUpdated(event.data.object, locals);\n break;\n\n case 'customer.subscription.deleted':\n await handleSubscriptionDeleted(event.data.object, locals);\n break;\n\n default:\n console.log(`Unhandled event type: ${event.type}`);\n }\n}\n";
3
- //#endregion
4
- export { n as a, r as i, a as n, t as o, i as r, e as s, o as t };
5
-
6
- //# sourceMappingURL=dispatch-B5PfQ2CA.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"dispatch-B5PfQ2CA.js","names":[],"sources":[],"mappings":""}
@@ -1,50 +0,0 @@
1
- import e from "node:path";
2
- import t from "prettier";
3
- import n from "prettier-plugin-svelte";
4
- //#region src/core/format-result.ts
5
- function r(e) {
6
- return e.language === "ts" || e.language === "js" || e.language === "svelte" || e.path.endsWith(".json");
7
- }
8
- async function i(n, r) {
9
- if (r?.env !== "runtime" || !r.root) return {};
10
- let i = e.isAbsolute(n.path) ? n.path : e.join(r.root, n.path), a = await t.resolveConfig(i, { editorconfig: !0 });
11
- if (!a) return {};
12
- let o = (a.plugins ?? []).filter((e) => e !== "prettier-plugin-svelte");
13
- return {
14
- ...a,
15
- plugins: o
16
- };
17
- }
18
- async function a(e, r, a) {
19
- try {
20
- let o = await i({ path: r }, a);
21
- return await t.format(e, {
22
- ...o,
23
- filepath: r,
24
- plugins: [...o.plugins ?? [], n]
25
- });
26
- } catch {
27
- return e;
28
- }
29
- }
30
- async function o(e, t) {
31
- return e.status !== "success" || !r(e) ? e : {
32
- ...e,
33
- content: await a(e.content, e.path, t)
34
- };
35
- }
36
- async function s(e, t) {
37
- return Promise.all(e.map((e) => o(e, t)));
38
- }
39
- async function c(e, t) {
40
- let [n, r] = await Promise.all([s(e.creates, t), s(e.modifies, t)]);
41
- return {
42
- ...e,
43
- creates: n,
44
- modifies: r
45
- };
46
- }
47
- //#endregion
48
- export { a as n, c as t };
49
-
50
- //# sourceMappingURL=format-result-BdAy5M8C.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"format-result-BdAy5M8C.js","names":[],"sources":["../../src/core/format-result.ts"],"sourcesContent":["import path from \"node:path\";\nimport prettier from \"prettier\";\nimport type { File, Options, Result } from \"./types\";\nimport sveltePlugin from \"prettier-plugin-svelte\";\n\n/** What the formatter needs to know about the run: where the project is, and whether it exists at all. */\nexport type FormatContext = Pick<Options, \"env\" | \"root\">;\n\nfunction canFormatFile(file: File): boolean {\n return (\n file.language === \"ts\" ||\n file.language === \"js\" ||\n file.language === \"svelte\" ||\n file.path.endsWith(\".json\")\n );\n}\n\n/**\n * The target project's own prettier settings (`.prettierrc`, `.editorconfig`,\n * `package.json#prettier`), so pattern output matches what `npm run lint`\n * expects there. Preview runs have no project and use prettier's defaults.\n *\n * The svelte plugin is always supplied as a module: a project's config names\n * it by string, which would resolve relative to this package instead.\n */\nasync function projectOptions(\n file: Pick<File, \"path\">,\n context?: FormatContext,\n): Promise<prettier.Options> {\n if (context?.env !== \"runtime\" || !context.root) return {};\n const target = path.isAbsolute(file.path)\n ? file.path\n : path.join(context.root, file.path);\n const resolved = await prettier.resolveConfig(target, { editorconfig: true });\n if (!resolved) return {};\n const plugins = (resolved.plugins ?? []).filter(\n (plugin) => plugin !== \"prettier-plugin-svelte\",\n );\n return { ...resolved, plugins };\n}\n\n/**\n * Formats one source text the way pattern output is formatted; the content\n * comes back unchanged when prettier cannot parse it. Also used for component\n * files that arrive on disk from `shadcn-svelte add` or the bundled\n * components, so `npm run lint` in the project stays clean after an install.\n */\nexport async function formatSource(\n content: string,\n filePath: string,\n context?: FormatContext,\n): Promise<string> {\n try {\n const options = await projectOptions({ path: filePath }, context);\n return await prettier.format(content, {\n ...options,\n filepath: filePath,\n plugins: [...(options.plugins ?? []), sveltePlugin],\n });\n } catch {\n return content;\n }\n}\n\nasync function formatFile(file: File, context?: FormatContext): Promise<File> {\n if (file.status !== \"success\" || !canFormatFile(file)) {\n return file;\n }\n return {\n ...file,\n content: await formatSource(file.content, file.path, context),\n };\n}\n\nasync function formatFiles(\n files: File[],\n context?: FormatContext,\n): Promise<File[]> {\n return Promise.all(files.map((file) => formatFile(file, context)));\n}\n\nexport async function formatResult(\n result: Result,\n context?: FormatContext,\n): Promise<Result> {\n const [creates, modifies] = await Promise.all([\n formatFiles(result.creates, context),\n formatFiles(result.modifies, context),\n ]);\n\n return {\n ...result,\n creates,\n modifies,\n };\n}\n"],"mappings":";;;;AAQA,SAAS,EAAc,GAAqB;CAC1C,OACE,EAAK,aAAa,QAClB,EAAK,aAAa,QAClB,EAAK,aAAa,YAClB,EAAK,KAAK,SAAS,OAAO;AAE9B;AAUA,eAAe,EACb,GACA,GAC2B;CAC3B,IAAI,GAAS,QAAQ,aAAa,CAAC,EAAQ,MAAM,OAAO,CAAC;CACzD,IAAM,IAAS,EAAK,WAAW,EAAK,IAAI,IACpC,EAAK,OACL,EAAK,KAAK,EAAQ,MAAM,EAAK,IAAI,GAC/B,IAAW,MAAM,EAAS,cAAc,GAAQ,EAAE,cAAc,GAAK,CAAC;CAC5E,IAAI,CAAC,GAAU,OAAO,CAAC;CACvB,IAAM,KAAW,EAAS,WAAW,CAAC,EAAA,CAAG,QACtC,MAAW,MAAW,wBACzB;CACA,OAAO;EAAE,GAAG;EAAU;CAAQ;AAChC;AAQA,eAAsB,EACpB,GACA,GACA,GACiB;CACjB,IAAI;EACF,IAAM,IAAU,MAAM,EAAe,EAAE,MAAM,EAAS,GAAG,CAAO;EAChE,OAAO,MAAM,EAAS,OAAO,GAAS;GACpC,GAAG;GACH,UAAU;GACV,SAAS,CAAC,GAAI,EAAQ,WAAW,CAAC,GAAI,CAAY;EACpD,CAAC;CACH,QAAQ;EACN,OAAO;CACT;AACF;AAEA,eAAe,EAAW,GAAY,GAAwC;CAI5E,OAHI,EAAK,WAAW,aAAa,CAAC,EAAc,CAAI,IAC3C,IAEF;EACL,GAAG;EACH,SAAS,MAAM,EAAa,EAAK,SAAS,EAAK,MAAM,CAAO;CAC9D;AACF;AAEA,eAAe,EACb,GACA,GACiB;CACjB,OAAO,QAAQ,IAAI,EAAM,KAAK,MAAS,EAAW,GAAM,CAAO,CAAC,CAAC;AACnE;AAEA,eAAsB,EACpB,GACA,GACiB;CACjB,IAAM,CAAC,GAAS,KAAY,MAAM,QAAQ,IAAI,CAC5C,EAAY,EAAO,SAAS,CAAO,GACnC,EAAY,EAAO,UAAU,CAAO,CACtC,CAAC;CAED,OAAO;EACL,GAAG;EACH;EACA;CACF;AACF"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"generate-Va1sxVPG.js","names":[],"sources":["../../src/core/providers.ts","../../src/patterns/enable/analytics/generate.ts"],"sourcesContent":["import { InvalidArgumentError } from \"./errors\";\nimport type { File, Options, Pattern, Provider } from \"./types\";\nimport { filesUnderPrefix } from \"./util\";\n\ntype ProviderPattern = Pick<Pattern, \"slug\" | \"providers\">;\n\n/** `analytics` for `enable-analytics`: how the capability is named to users. */\nexport function capabilityName(slug: string): string {\n return slug.replace(/^enable-/, \"\");\n}\n\n/** `--provider <id>` or `--provider=<id>`, for callers that hand flags through in argv. */\nexport function providerFromArgv(argv: string[]): string | undefined {\n for (let i = 0; i < argv.length; i++) {\n const arg = argv[i];\n if (arg === \"--provider\") return argv[i + 1];\n if (arg.startsWith(\"--provider=\")) return arg.slice(\"--provider=\".length);\n }\n return undefined;\n}\n\nexport function unknownProviderMessage(\n name: string,\n raw: string,\n providers: Provider[],\n): string {\n return [\n `Unknown provider \"${raw}\" for ${name}.`,\n \"\",\n \"Available providers:\",\n ...providers.map((provider) => ` ${provider.id}`),\n ].join(\"\\n\");\n}\n\nexport function providerChoices(providers: Provider[]): string {\n return `--provider <${providers.map((provider) => provider.id).join(\"|\")}>`;\n}\n\n/**\n * The provider a generate call should produce, from `input.provider` or\n * `--provider` in argv.\n *\n * An unknown id is rejected with the list of known ones. With no provider at\n * all, a runtime call is rejected too: the CLI always supplies one, so this\n * is a caller bug. A preview call falls back to the first declared provider,\n * because the website loads patterns with argv only.\n */\nexport function resolveProvider(\n pattern: ProviderPattern,\n options: Pick<Options, \"input\" | \"argv\" | \"env\">,\n): Provider {\n const providers = pattern.providers ?? [];\n const name = capabilityName(pattern.slug);\n if (providers.length === 0) {\n throw new Error(`${pattern.slug} declares no providers.`);\n }\n\n const raw =\n typeof options.input.provider === \"string\"\n ? options.input.provider\n : providerFromArgv(options.argv);\n\n if (raw === undefined || raw === \"\") {\n if (options.env === \"preview\") return providers[0];\n throw new InvalidArgumentError(\n `Choose a provider for ${name}: ${providerChoices(providers)}`,\n );\n }\n\n const provider = providers.find((candidate) => candidate.id === raw);\n if (!provider) {\n throw new InvalidArgumentError(\n unknownProviderMessage(name, raw, providers),\n );\n }\n return provider;\n}\n\n/**\n * The files under `providers/<id>/**` of a pattern, as creates. The glob map\n * is one `import.meta.glob(\"./providers/**\")` covering every provider.\n */\nexport function providerCreates(\n providersRaw: Record<string, string>,\n id: string,\n): File[] {\n const files = filesUnderPrefix(providersRaw, `./providers/${id}/`);\n return Object.values(files).sort((a, b) => a.path.localeCompare(b.path));\n}\n","import type { Options, Package, Provider, Result } from \"../../../core/types\";\nimport type { EnvEdit } from \"../../../runtime/env\";\nimport { providerCreates, resolveProvider } from \"../../../core/providers\";\n\n/** Every provider ships the same component, so the root layout mounts one path. */\nexport const COMPONENT_PATH = \"src/lib/components/analytics/analytics.svelte\";\n\n/**\n * The providers in prompt order. Each one's `env` keys are what the CLI asks\n * for and what `generate.runtime.ts` writes to `.env`; the generated\n * component reads them through `$env/dynamic/public` and stays inert while\n * they are blank.\n */\nexport const PROVIDERS: Provider[] = [\n {\n id: \"plausible\",\n label: \"Plausible\",\n env: [\n {\n key: \"PUBLIC_PLAUSIBLE_DOMAIN\",\n label: \"Plausible site domain\",\n placeholder: \"example.com\",\n },\n ],\n },\n {\n id: \"google\",\n label: \"Google Analytics\",\n env: [\n {\n key: \"PUBLIC_GA_MEASUREMENT_ID\",\n label: \"Google Analytics measurement ID\",\n placeholder: \"G-XXXXXXXXXX\",\n },\n ],\n },\n {\n id: \"posthog\",\n label: \"PostHog\",\n env: [\n {\n key: \"PUBLIC_POSTHOG_KEY\",\n label: \"PostHog project API key\",\n placeholder: \"phc_...\",\n },\n {\n key: \"PUBLIC_POSTHOG_HOST\",\n label: \"PostHog host\",\n default: \"https://us.i.posthog.com\",\n },\n ],\n },\n];\n\nconst PACKAGES: Record<string, Package[]> = {\n posthog: [\"posthog-js\"],\n};\n\n/** What `resolveProvider` needs; `index.ts` spreads the rest of the metadata. */\nexport const META = { slug: \"enable-analytics\", providers: PROVIDERS };\n\n/**\n * The `.env` lines for a provider: a comment naming it, then one `KEY=value`\n * per declared env var. `supplied` holds what the CLI collected; a blank\n * value falls back to the provider's default, else an empty assignment the\n * developer fills in later. Prompt placeholders are never written.\n */\nexport function envEditsFor(\n provider: Provider,\n supplied: Record<string, string> = {},\n): EnvEdit[] {\n return [\n { type: \"comment\", key: `${provider.label} analytics` },\n ...(provider.env ?? []).map((variable): EnvEdit => ({\n type: \"var\",\n key: variable.key,\n value: supplied[variable.key]?.trim() || variable.default || \"\",\n })),\n ];\n}\n\nconst providersRaw = import.meta.glob<string>(\"./providers/**\", {\n query: \"?raw\",\n import: \"default\",\n eager: true,\n});\n\nexport async function generate(options: Options) {\n const provider = resolveProvider(META, options);\n\n return {\n creates: providerCreates(providersRaw, provider.id),\n modifies: [],\n deletes: [],\n components: [],\n packages: PACKAGES[provider.id] ?? [],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n } satisfies Result;\n}\n"],"mappings":";;;AAOA,SAAgB,EAAe,GAAsB;CACnD,OAAO,EAAK,QAAQ,YAAY,EAAE;AACpC;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AI,CAAC;AACzE;;;4qGC3Ea,IAAwB;CACnC;EACE,IAAI;EACJ,OAAO;EACP,KAAK,CACH;GACE,KAAK;GACL,OAAO;GACP,aAAa;EACf,CACF;CACF;CACA;EACE,IAAI;EACJ,OAAO;EACP,KAAK,CACH;GACE,KAAK;GACL,OAAO;GACP,aAAa;EACf,CACF;CACF;CACA;EACE,IAAI;EACJ,OAAO;EACP,KAAK,CACH;GACE,KAAK;GACL,OAAO;GACP,aAAa;EACf,GACA;GACE,KAAK;GACL,OAAO;GACP,SAAS;EACX,CACF;CACF;AACF,GAEM,IAAsC,EAC1C,SAAS,CAAC,YAAY,EACxB,GAGa,IAAO;CAAE,MAAM;CAAoB,WAAW;AAAU;AAQrE,SAAgB,EACd,GACA,IAAmC,CAAC,GACzB;CACX,OAAO,CACL;EAAE,MAAM;EAAW,KAAK,GAAG,EAAS,MAAM;CAAY,GACtD,IAAI,EAAS,OAAO,CAAC,EAAA,CAAG,KAAK,OAAuB;EAClD,MAAM;EACN,KAAK,EAAS;EACd,OAAO,EAAS,EAAS,IAAI,EAAE,KAAK,KAAK,EAAS,WAAW;CAC/D,EAAE,CACJ;AACF;AAEA,IAAM,IAAe,uBAAA,OAAA;CAAA,oEAAA;CAAA,2DAAA;CAAA,uEAAA;CAAA,qEAAA;AAIpB,CAAA;AAED,eAAsB,EAAS,GAAkB;CAC/C,IAAM,IAAW,EAAgB,GAAM,CAAO;CAE9C,OAAO;EACL,SAAS,EAAgB,GAAc,EAAS,EAAE;EAClD,UAAU,CAAC;EACX,SAAS,CAAC;EACV,YAAY,CAAC;EACb,UAAU,EAAS,EAAS,OAAO,CAAC;EACpC,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAiB,CAAC;CACpB;AACF"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"generate.runtime-AjCpCfv3.js","names":[],"sources":["../../src/patterns/enable/i18n/modifies/vite-config.ts","../../src/patterns/enable/i18n/modifies/svelte-config.ts","../../src/patterns/enable/i18n/modifies/hooks.server.ts","../../src/patterns/enable/i18n/modifies/app-html.ts","../../src/patterns/enable/i18n/modifies/gitignore.ts","../../src/patterns/enable/i18n/modifies/root-layout.svelte.ts","../../src/patterns/enable/i18n/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport { Project, QuoteKind, SyntaxKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst FAILURE_HINT = [\n \"Add the wuchale plugin to your Vite config:\",\n \"\",\n \"import { wuchale } from 'wuchale/vite';\",\n \"\",\n \"export default defineConfig({\",\n \" plugins: [wuchale(), /* ...existing plugins */],\",\n \"});\",\n].join(\"\\n\");\n\nconst NOT_FOUND_HINT = [\n \"Create a Vite config with the wuchale plugin:\",\n \"\",\n \"import { defineConfig } from 'vite';\",\n \"import { wuchale } from 'wuchale/vite';\",\n \"\",\n \"export default defineConfig({\",\n \" plugins: [wuchale()],\",\n \"});\",\n].join(\"\\n\");\n\nexport function modifyViteConfig(viteConfigPath: string): ModifyOutcome {\n if (!fs.existsSync(viteConfigPath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const project = new Project({\n compilerOptions: { allowJs: true },\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n const sourceFile = project.addSourceFileAtPath(viteConfigPath);\n\n let changed = false;\n let failed = false;\n\n const hasImport = sourceFile\n .getImportDeclarations()\n .some((d) => d.getModuleSpecifierValue() === \"wuchale/vite\");\n\n if (!hasImport) {\n sourceFile.insertImportDeclaration(0, {\n namedImports: [\"wuchale\"],\n moduleSpecifier: \"wuchale/vite\",\n });\n changed = true;\n }\n\n const defineConfigCall = sourceFile\n .getDescendantsOfKind(SyntaxKind.CallExpression)\n .find((ce) => ce.getExpression().getText() === \"defineConfig\");\n\n const configArg = defineConfigCall?.getArguments()?.[0];\n const configObj =\n configArg?.getKind() === SyntaxKind.ObjectLiteralExpression\n ? (configArg as import(\"ts-morph\").ObjectLiteralExpression)\n : null;\n\n if (!configObj) {\n failed = true;\n } else {\n const pluginsProp = configObj.getProperty(\"plugins\");\n if (!pluginsProp) {\n configObj.addPropertyAssignment({\n name: \"plugins\",\n initializer: \"[wuchale()]\",\n });\n changed = true;\n } else if (pluginsProp.getKind() !== SyntaxKind.PropertyAssignment) {\n failed = true;\n } else {\n const pluginsInit = (\n pluginsProp as import(\"ts-morph\").PropertyAssignment\n ).getInitializer();\n\n if (!pluginsInit) {\n (pluginsProp as import(\"ts-morph\").PropertyAssignment).setInitializer(\n \"[wuchale()]\",\n );\n changed = true;\n } else if (pluginsInit.getKind() !== SyntaxKind.ArrayLiteralExpression) {\n failed = true;\n } else {\n const arr = pluginsInit as import(\"ts-morph\").ArrayLiteralExpression;\n const hasWuchale = arr\n .getElements()\n .some((el) => el.getText().replace(/\\s/g, \"\") === \"wuchale()\");\n\n if (!hasWuchale) {\n arr.insertElement(0, \"wuchale()\");\n changed = true;\n }\n }\n }\n }\n\n if (changed) {\n sourceFile.formatText();\n sourceFile.saveSync();\n }\n\n if (failed) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n return { status: \"success\", changed };\n}\n","import { SyntaxKind, type PropertyAssignment } from \"ts-morph\";\nimport {\n getOrCreateObjectLiteralProperty,\n modifyConfig,\n type ConfigModifyResult,\n} from \"../../../../runtime/config-target\";\n\nconst FAILURE_HINT = [\n \"Add the $locales alias to your config (sveltekit() arg in vite.config, or svelte.config):\",\n \"\",\n \"alias: {\",\n \" $locales: 'src/locales',\",\n \"},\",\n].join(\"\\n\");\n\nconst NOT_FOUND_HINT = [\n \"Add the $locales alias by passing config to the sveltekit() plugin in vite.config.ts:\",\n \"\",\n \"import { sveltekit } from '@sveltejs/kit/vite';\",\n \"import { defineConfig } from 'vite';\",\n \"\",\n \"export default defineConfig({\",\n \" plugins: [sveltekit({ alias: { $locales: 'src/locales' } })],\",\n \"});\",\n].join(\"\\n\");\n\n/** Ensure the `$locales` alias points at `src/locales`. */\nexport function modifySvelteConfig(root: string): ConfigModifyResult {\n return modifyConfig(\n root,\n { notFound: NOT_FOUND_HINT, failed: FAILURE_HINT },\n (target) => {\n const kit = target.kitContainer();\n if (!kit) return false;\n const aliasObj = getOrCreateObjectLiteralProperty(kit, \"alias\", \"{}\");\n if (!aliasObj) return false;\n\n const existing = aliasObj.getProperty(\"$locales\");\n if (!existing) {\n aliasObj.addPropertyAssignment({\n name: \"$locales\",\n initializer: \"'src/locales'\",\n });\n return true;\n }\n if (existing.getKind() !== SyntaxKind.PropertyAssignment) return false;\n\n const init = (existing as PropertyAssignment).getInitializer();\n const current = init?.getText()?.replace(/['\"`]/g, \"\");\n if (current !== \"src/locales\") {\n (existing as PropertyAssignment).setInitializer(\"'src/locales'\");\n }\n return true;\n },\n );\n}\n","import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { Project, QuoteKind, SyntaxKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst FAILURE_HINT = dedent`\n Wrap your exported handle with the wuchale i18n handler:\n\n import { sequence } from '@sveltejs/kit/hooks';\n import { runWithLocale, loadLocales } from 'wuchale/load-utils/server';\n import { getLocale } from '$locales/main.url';\n import { locales } from '$locales/data';\n import * as main from '$locales/main.loader.server.svelte.js';\n import * as js from '$locales/js.loader.server.js';\n\n loadLocales(main.key, main.loadCount, main.loadCatalog, locales);\n loadLocales(js.key, js.loadCount, js.loadCatalog, locales);\n\n const handleWuchale = async ({ event, resolve }: any) => {\n const locale = getLocale(event.url);\n return await runWithLocale(locale, () =>\n resolve(event, {\n transformPageChunk: ({ html }: { html: string }) =>\n html.replace('%sveltekit.lang%', locale),\n }),\n );\n };\n\n export const handle = sequence(handleWuchale, /* your existing handle */);\n`;\n\nconst NOT_FOUND_HINT = dedent`\n Create src/hooks.server.ts with an i18n handle:\n\n import { sequence } from '@sveltejs/kit/hooks';\n import { runWithLocale, loadLocales } from 'wuchale/load-utils/server';\n import { getLocale } from '$locales/main.url';\n import { locales } from '$locales/data';\n import * as main from '$locales/main.loader.server.svelte.js';\n import * as js from '$locales/js.loader.server.js';\n\n loadLocales(main.key, main.loadCount, main.loadCatalog, locales);\n loadLocales(js.key, js.loadCount, js.loadCatalog, locales);\n\n const handleWuchale = async ({ event, resolve }: any) => {\n const locale = getLocale(event.url);\n return await runWithLocale(locale, () =>\n resolve(event, {\n transformPageChunk: ({ html }: { html: string }) =>\n html.replace('%sveltekit.lang%', locale),\n }),\n );\n };\n\n export const handle = handleWuchale;\n`;\n\nfunction ensureNamedImport(\n sourceFile: import(\"ts-morph\").SourceFile,\n moduleSpecifier: string,\n name: string,\n) {\n const existing = sourceFile\n .getImportDeclarations()\n .find((d) => d.getModuleSpecifierValue() === moduleSpecifier);\n if (existing) {\n const has = existing.getNamedImports().some((ni) => ni.getName() === name);\n if (!has) existing.addNamedImport(name);\n return;\n }\n sourceFile.addImportDeclaration({ namedImports: [name], moduleSpecifier });\n}\n\nfunction ensureNamespaceImport(\n sourceFile: import(\"ts-morph\").SourceFile,\n moduleSpecifier: string,\n ns: string,\n) {\n const existing = sourceFile\n .getImportDeclarations()\n .find((d) => d.getModuleSpecifierValue() === moduleSpecifier);\n if (existing) return;\n sourceFile.addImportDeclaration({ namespaceImport: ns, moduleSpecifier });\n}\n\nexport function modifyHooksServerI18n(hooksServerPath: string): ModifyOutcome {\n if (!fs.existsSync(hooksServerPath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const original = fs.readFileSync(hooksServerPath, \"utf8\");\n if (original.includes(\"runWithLocale\") || original.includes(\"loadLocales(\")) {\n return { status: \"success\", changed: false };\n }\n\n const project = new Project({\n compilerOptions: { allowJs: true },\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n const sourceFile = project.addSourceFileAtPath(hooksServerPath);\n\n const handleDecl = sourceFile.getVariableDeclaration(\"handle\");\n if (!handleDecl) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n const handleStmt = handleDecl.getFirstAncestorByKind(\n SyntaxKind.VariableStatement,\n );\n if (!handleStmt?.hasExportKeyword()) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n ensureNamedImport(sourceFile, \"@sveltejs/kit/hooks\", \"sequence\");\n ensureNamedImport(sourceFile, \"wuchale/load-utils/server\", \"runWithLocale\");\n ensureNamedImport(sourceFile, \"wuchale/load-utils/server\", \"loadLocales\");\n ensureNamedImport(sourceFile, \"$locales/main.url\", \"getLocale\");\n ensureNamedImport(sourceFile, \"$locales/data\", \"locales\");\n ensureNamespaceImport(\n sourceFile,\n \"$locales/main.loader.server.svelte.js\",\n \"main\",\n );\n ensureNamespaceImport(sourceFile, \"$locales/js.loader.server.js\", \"js\");\n\n const statements = sourceFile.getStatements();\n const handleStmtIndex = statements.findIndex((s) => s === handleStmt);\n const i18nHandleName = \"handleWuchale\";\n\n const startupSnippet = dedent`\n loadLocales(main.key, main.loadCount, main.loadCatalog, locales);\n loadLocales(js.key, js.loadCount, js.loadCatalog, locales);\n `;\n\n const i18nHandleSnippet = dedent`\n const ${i18nHandleName} = async ({ event, resolve }: any) => {\n const locale = getLocale(event.url);\n return await runWithLocale(locale, () =>\n resolve(event, {\n transformPageChunk: ({ html }: { html: string }) =>\n html.replace('%sveltekit.lang%', locale)\n })\n );\n };\n `;\n\n if (handleStmtIndex >= 0) {\n sourceFile.insertStatements(\n handleStmtIndex,\n `\\n${startupSnippet}\\n\\n${i18nHandleSnippet}\\n`,\n );\n } else {\n sourceFile.addStatements(`\\n${startupSnippet}\\n\\n${i18nHandleSnippet}\\n`);\n }\n\n const init = handleDecl.getInitializer();\n if (!init) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n const initText = init.getText();\n if (initText.includes(i18nHandleName) || initText.includes(\"runWithLocale\")) {\n return { status: \"success\", changed: false };\n }\n\n handleDecl.setInitializer(`sequence(${i18nHandleName}, ${initText})`);\n sourceFile.formatText();\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n}\n","import fs from \"node:fs\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst FAILURE_HINT = [\n \"Add the sveltekit lang placeholder to the <html> tag:\",\n \"\",\n '<html lang=\"%sveltekit.lang%\">',\n].join(\"\\n\");\n\nconst NOT_FOUND_HINT = [\n \"Create src/app.html with a lang placeholder:\",\n \"\",\n \"<!doctype html>\",\n '<html lang=\"%sveltekit.lang%\">',\n \" <head>\",\n ' <meta charset=\"utf-8\" />',\n \" %sveltekit.head%\",\n \" </head>\",\n ' <body data-sveltekit-preload-data=\"hover\">',\n ' <div style=\"display: contents\">%sveltekit.body%</div>',\n \" </body>\",\n \"</html>\",\n].join(\"\\n\");\n\nexport function modifyAppHtml(appHtmlPath: string): ModifyOutcome {\n if (!fs.existsSync(appHtmlPath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const original = fs.readFileSync(appHtmlPath, \"utf8\");\n if (\n original.includes('lang=\"%sveltekit.lang%\"') ||\n original.includes(\"lang='%sveltekit.lang%'\")\n ) {\n return { status: \"success\", changed: false };\n }\n\n const updated = original.replace(/<html(\\s[^>]*?)?>/i, (match) => {\n // A static lang (the templates ship lang=\"en\") is replaced by the\n // placeholder so the server hook can fill in the negotiated locale.\n if (/\\slang\\s*=/i.test(match)) {\n return match.replace(\n /\\slang\\s*=\\s*(?:\"[^\"]*\"|'[^']*'|[^\\s>]+)/i,\n ' lang=\"%sveltekit.lang%\"',\n );\n }\n return match.replace(/<html/i, '<html lang=\"%sveltekit.lang%\"');\n });\n\n if (updated === original) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n fs.writeFileSync(appHtmlPath, updated);\n return { status: \"success\", changed: true };\n}\n","import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst NOT_FOUND_HINT = [\n \"Create a .gitignore with the wuchale cache ignored:\",\n \"\",\n \"# Wuchale\",\n \"src/locales/.wuchale\",\n].join(\"\\n\");\n\nexport function modifyGitignore(gitignorePath: string): ModifyOutcome {\n if (!fs.existsSync(gitignorePath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const original = fs.readFileSync(gitignorePath, \"utf8\");\n if (original.includes(\"src/locales/.wuchale\")) {\n return { status: \"success\", changed: false };\n }\n\n const block = dedent`\n # Wuchale\n src/locales/.wuchale\n `;\n\n const needsNewline = original.length > 0 && !original.endsWith(\"\\n\");\n const updated = original + (needsNewline ? \"\\n\" : \"\") + \"\\n\" + block + \"\\n\";\n fs.writeFileSync(gitignorePath, updated);\n return { status: \"success\", changed: true };\n}\n","import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport {\n ensureImports,\n withInMemoryScript,\n} from \"../../../../runtime/ts-morph-helpers\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst LANGUAGE_SELECT_SNIPPET = `<Navbar.Item>\n\t\t\t\t<LanguageSelect />\n\t\t\t</Navbar.Item>\n\t\t\t`;\n\nconst IMPORT_SNIPPET = dedent`\n import LanguageSelect from '$lib/components/language-select.svelte';\n`;\n\nconst FAILURE_HINT = [\n \"Add the language select inside your <Navbar.List> in the root layout.\",\n \"\",\n \"Import to add to the <script> tag:\",\n \"\",\n IMPORT_SNIPPET,\n \"\",\n \"Markup to add at the end of <Navbar.List>:\",\n LANGUAGE_SELECT_SNIPPET,\n].join(\"\\n\");\n\nconst NOT_FOUND_HINT = [\n \"Create a root layout that includes a language select inside <Navbar.List>.\",\n \"\",\n \"Import for the <script> tag:\",\n \"\",\n IMPORT_SNIPPET,\n \"\",\n \"Markup at the end of <Navbar.List>:\",\n LANGUAGE_SELECT_SNIPPET,\n].join(\"\\n\");\n\nexport function modifyRootLayoutLanguageSelect(\n layoutPath: string,\n): ModifyOutcome {\n if (!fs.existsSync(layoutPath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const file = SvelteFile.fromPath(layoutPath);\n if (!file.hasElement(\"Navbar.List\")) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n if (file.hasElement(\"LanguageSelect\")) {\n return { status: \"success\", changed: false };\n }\n\n file.modifyScript((source) => {\n const { source: out } = withInMemoryScript(source, (sf) => {\n ensureImports(sf, [\n {\n defaultImport: \"LanguageSelect\",\n moduleSpecifier: \"$lib/components/language-select.svelte\",\n },\n ]);\n });\n return out;\n });\n\n file.insertBeforeClosingTag(\"Navbar.List\", LANGUAGE_SELECT_SNIPPET);\n file.writeTo(layoutPath);\n return { status: \"success\", changed: file.hasChanged() };\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport {\n probeFirstExisting,\n VITE_CONFIG_CANDIDATES,\n} from \"../../../runtime/config-target\";\nimport { modifyViteConfig } from \"./modifies/vite-config\";\nimport { modifySvelteConfig } from \"./modifies/svelte-config\";\nimport { modifyHooksServerI18n } from \"./modifies/hooks.server\";\nimport { modifyAppHtml } from \"./modifies/app-html\";\nimport { modifyGitignore } from \"./modifies/gitignore\";\nimport { ensureRootLayoutI18n } from \"./modifies/+layout\";\nimport { modifyRootLayoutLanguageSelect } from \"./modifies/root-layout.svelte\";\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const modifies: File[] = [];\n\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n logger.info(\"Modifying vite.config\");\n const viteConfigPath =\n probeFirstExisting(options.root, VITE_CONFIG_CANDIDATES) ??\n path.join(options.root, VITE_CONFIG_CANDIDATES[0]);\n pushResult(\n modifyOutcomeToFile(viteConfigPath, modifyViteConfig(viteConfigPath)),\n );\n\n logger.info(\"Modifying config for i18n alias\");\n const alias = modifySvelteConfig(options.root);\n pushResult(modifyOutcomeToFile(alias.filePath, alias.outcome));\n\n logger.info(\"Modifying hooks.server.ts\");\n const hooksServerPath = path.join(options.root, \"src\", \"hooks.server.ts\");\n pushResult(\n modifyOutcomeToFile(\n hooksServerPath,\n modifyHooksServerI18n(hooksServerPath),\n ),\n );\n\n logger.info(\"Modifying app.html\");\n const appHtmlPath = path.join(options.root, \"src\", \"app.html\");\n pushResult(modifyOutcomeToFile(appHtmlPath, modifyAppHtml(appHtmlPath)));\n\n logger.info(\"Modifying root +layout.ts\");\n const layoutPath = path.join(options.root, \"src\", \"routes\", \"+layout.ts\");\n pushResult(modifyOutcomeToFile(layoutPath, ensureRootLayoutI18n(layoutPath)));\n\n logger.info(\"Modifying root layout language select\");\n const rootLayoutCandidates = [\n path.join(options.root, \"src\", \"routes\", \"(public)\", \"root-layout.svelte\"),\n path.join(options.root, \"src\", \"routes\", \"root-layout.svelte\"),\n path.join(options.root, \"src\", \"routes\", \"(public)\", \"+layout.svelte\"),\n path.join(options.root, \"src\", \"routes\", \"+layout.svelte\"),\n ];\n const rootLayoutPath =\n rootLayoutCandidates.find((p) => fs.existsSync(p)) ??\n rootLayoutCandidates[0];\n pushResult(\n modifyOutcomeToFile(\n rootLayoutPath,\n modifyRootLayoutLanguageSelect(rootLayoutPath),\n ),\n );\n\n logger.info(\"Updating .gitignore\");\n const gitignorePath = path.join(options.root, \".gitignore\");\n pushResult(\n modifyOutcomeToFile(gitignorePath, modifyGitignore(gitignorePath)),\n );\n\n 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;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,SAAgB,EAAiB,GAAuC;CACtE,IAAI,CAAC,EAAG,WAAW,CAAc,GAC/B,OAAO;EAAE,QAAQ;EAAa,SAAS;CAAe;CAOxD,IAAM,IAAa,IAJC,EAAQ;EAC1B,iBAAiB,EAAE,SAAS,GAAK;EACjC,sBAAsB,EAA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../../src/patterns/enable/content-negotiation/modifies/hooks.server.ts","../../src/patterns/enable/content-negotiation/modifies/hooks.ts","../../src/patterns/enable/content-negotiation/modifies/root-layout.svelte.ts","../../src/patterns/enable/content-negotiation/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { Project, QuoteKind, SyntaxKind, type SourceFile } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst FAILURE_HINT = dedent`\n Wrap your exported handle with the negotiation handler:\n\n import { sequence } from '@sveltejs/kit/hooks';\n import { handle as handleNegotiate } from '$lib/negotiate';\n\n export const handle = sequence(handleNegotiate, /* your existing handle */);\n`;\n\nconst NOT_FOUND_HINT = dedent`\n Create src/hooks.server.ts with a negotiation handle:\n\n export { handle } from '$lib/negotiate';\n`;\n\nfunction ensureSequenceImport(sourceFile: SourceFile) {\n const existing = sourceFile\n .getImportDeclarations()\n .find((d) => d.getModuleSpecifierValue() === \"@sveltejs/kit/hooks\");\n if (existing) {\n const has = existing\n .getNamedImports()\n .some((ni) => ni.getName() === \"sequence\");\n if (!has) existing.addNamedImport(\"sequence\");\n return;\n }\n sourceFile.addImportDeclaration({\n namedImports: [\"sequence\"],\n moduleSpecifier: \"@sveltejs/kit/hooks\",\n });\n}\n\nfunction ensureNegotiateHandleImport(sourceFile: SourceFile) {\n const existing = sourceFile\n .getImportDeclarations()\n .find((d) => d.getModuleSpecifierValue() === \"$lib/negotiate\");\n if (existing) {\n const has = existing.getNamedImports().some((ni) => {\n return (\n ni.getName() === \"handle\" &&\n ni.getAliasNode()?.getText() === \"handleNegotiate\"\n );\n });\n if (!has)\n existing.addNamedImport({ name: \"handle\", alias: \"handleNegotiate\" });\n return;\n }\n sourceFile.addImportDeclaration({\n namedImports: [{ name: \"handle\", alias: \"handleNegotiate\" }],\n moduleSpecifier: \"$lib/negotiate\",\n });\n}\n\nexport function modifyHooksServerNegotiate(\n hooksServerPath: string,\n): ModifyOutcome {\n if (!fs.existsSync(hooksServerPath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const original = fs.readFileSync(hooksServerPath, \"utf8\");\n if (original.includes(\"handleNegotiate\")) {\n return { status: \"success\", changed: false };\n }\n\n const project = new Project({\n compilerOptions: { allowJs: true },\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n const sourceFile = project.addSourceFileAtPath(hooksServerPath);\n\n const handleDecl = sourceFile.getVariableDeclaration(\"handle\");\n if (!handleDecl) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n const handleStmt = handleDecl.getFirstAncestorByKind(\n SyntaxKind.VariableStatement,\n );\n if (!handleStmt?.hasExportKeyword()) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n const init = handleDecl.getInitializer();\n if (!init) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n ensureNegotiateHandleImport(sourceFile);\n\n if (init.getKind() === SyntaxKind.CallExpression) {\n const call = init.asKindOrThrow(SyntaxKind.CallExpression);\n if (call.getExpression().getText() === \"sequence\") {\n call.insertArgument(0, \"handleNegotiate\");\n sourceFile.formatText();\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n }\n }\n\n ensureSequenceImport(sourceFile);\n handleDecl.setInitializer(`sequence(handleNegotiate, ${init.getText()})`);\n sourceFile.formatText();\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport dedent from \"dedent\";\nimport { Project, QuoteKind, SyntaxKind, type SourceFile } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst NEGOTIATE_ONLY_SNIPPET = dedent`\n import { reroute as negotiateReroute } from '$lib/negotiate';\n\n export const reroute = ({ url }) => negotiateReroute(url.pathname);\n`;\n\nconst FAILURE_HINT = dedent`\n Compose your existing reroute in src/hooks.ts with the negotiation reroute:\n\n import { reroute as negotiateReroute } from '$lib/negotiate';\n\n export const reroute = ({ url }) => existingReroute(negotiateReroute(url.pathname));\n`;\n\nfunction ensureNegotiateImport(sourceFile: SourceFile) {\n const existing = sourceFile\n .getImportDeclarations()\n .find((d) => d.getModuleSpecifierValue() === \"$lib/negotiate\");\n if (existing) {\n const has = existing.getNamedImports().some((ni) => {\n return (\n ni.getName() === \"reroute\" &&\n ni.getAliasNode()?.getText() === \"negotiateReroute\"\n );\n });\n if (!has) {\n existing.addNamedImport({ name: \"reroute\", alias: \"negotiateReroute\" });\n }\n return;\n }\n sourceFile.addImportDeclaration({\n namedImports: [{ name: \"reroute\", alias: \"negotiateReroute\" }],\n moduleSpecifier: \"$lib/negotiate\",\n });\n}\n\nexport function modifyHooksNegotiate(hooksPath: string): ModifyOutcome {\n if (!fs.existsSync(hooksPath)) {\n fs.mkdirSync(path.dirname(hooksPath), { recursive: true });\n fs.writeFileSync(hooksPath, NEGOTIATE_ONLY_SNIPPET + \"\\n\");\n return { status: \"success\", changed: true };\n }\n\n const original = fs.readFileSync(hooksPath, \"utf8\");\n if (original.includes(\"negotiateReroute\")) {\n return { status: \"success\", changed: false };\n }\n\n const project = new Project({\n compilerOptions: { allowJs: true },\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n const sourceFile = project.addSourceFileAtPath(hooksPath);\n\n const rerouteDecl = sourceFile.getVariableDeclaration(\"reroute\");\n\n if (!rerouteDecl) {\n ensureNegotiateImport(sourceFile);\n sourceFile.addStatements(\n `\\nexport const reroute = ({ url }) => negotiateReroute(url.pathname);\\n`,\n );\n sourceFile.formatText();\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n }\n\n const rerouteStmt = rerouteDecl.getFirstAncestorByKind(\n SyntaxKind.VariableStatement,\n );\n if (!rerouteStmt?.hasExportKeyword()) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n const init = rerouteDecl.getInitializer();\n if (!init) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n const hasI18nHelper = sourceFile\n .getVariableDeclarations()\n .some((d) => d.getName() === \"rerouteDeLocalize\");\n const initText = init.getText();\n\n if (hasI18nHelper && initText.includes(\"rerouteDeLocalize\")) {\n ensureNegotiateImport(sourceFile);\n rerouteDecl.setInitializer(\n \"({ url }) => rerouteDeLocalize(negotiateReroute(url.pathname))\",\n );\n sourceFile.formatText();\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n }\n\n return { status: \"failed\", message: FAILURE_HINT };\n}\n","import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport {\n ensureImports,\n withInMemoryScript,\n} from \"../../../../runtime/ts-morph-helpers\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst IMPORT_SNIPPET = dedent`\n import { Negotiate } from '$lib/negotiate';\n`;\n\nconst MARKUP_SNIPPET = \"\\n<Negotiate />\\n\";\n\nconst NOT_FOUND_HINT = [\n \"Create the root +layout.svelte and mount <Negotiate /> inside it.\",\n \"\",\n \"Import for the <script> tag:\",\n \"\",\n IMPORT_SNIPPET,\n \"\",\n \"Markup to add at the top level of the layout:\",\n MARKUP_SNIPPET.trim(),\n].join(\"\\n\");\n\nexport function modifyRootLayoutNegotiate(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(\"Negotiate\")) {\n return { status: \"success\", changed: false };\n }\n\n file.modifyScript((source) => {\n const { source: out } = withInMemoryScript(source, (sf) => {\n ensureImports(sf, [\n {\n namedImports: [\"Negotiate\"],\n moduleSpecifier: \"$lib/negotiate\",\n },\n ]);\n });\n return out;\n });\n\n file.appendMarkup(MARKUP_SNIPPET);\n file.writeTo(layoutPath);\n return { status: \"success\", changed: file.hasChanged() };\n}\n","import path from \"node:path\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { modifyHooksServerNegotiate } from \"./modifies/hooks.server\";\nimport { modifyHooksNegotiate } from \"./modifies/hooks\";\nimport { modifyRootLayoutNegotiate } from \"./modifies/root-layout.svelte\";\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const modifies: File[] = [];\n\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n logger.info(\"Modifying hooks.server.ts\");\n const hooksServerPath = path.join(options.root, \"src\", \"hooks.server.ts\");\n pushResult(\n modifyOutcomeToFile(\n hooksServerPath,\n modifyHooksServerNegotiate(hooksServerPath),\n ),\n );\n\n logger.info(\"Modifying hooks.ts\");\n const hooksPath = path.join(options.root, \"src\", \"hooks.ts\");\n pushResult(modifyOutcomeToFile(hooksPath, modifyHooksNegotiate(hooksPath)));\n\n logger.info(\"Modifying src/routes/+layout.svelte\");\n const rootLayoutPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"+layout.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(\n rootLayoutPath,\n modifyRootLayoutNegotiate(rootLayoutPath),\n ),\n );\n\n return {\n creates: [],\n modifies,\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n } satisfies Result;\n}\n"],"mappings":";;;;;;;;AAKA,IAAM,IAAe,CAAM;;;;;;;GASrB,IAAiB,CAAM;;;;;AAM7B,SAAS,EAAqB,GAAwB;CACpD,IAAM,IAAW,EACd,sBAAsB,CAAC,CACvB,MAAM,MAAM,EAAE,wBAAwB,MAAM,qBAAqB;CACpE,IAAI,GAAU;EAIZ,AAHY,EACT,gBAAgB,CAAC,CACjB,MAAM,MAAO,EAAG,QAAQ,MAAM,UAC5B,KAAK,EAAS,eAAe,UAAU;EAC5C;CACF;CACA,EAAW,qBAAqB;EAC9B,cAAc,CAAC,UAAU;EACzB,iBAAiB;CACnB,CAAC;AACH;AAEA,SAAS,EAA4B,GAAwB;CAC3D,IAAM,IAAW,EACd,sBAAsB,CAAC,CACvB,MAAM,MAAM,EAAE,wBAAwB,MAAM,gBAAgB;C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AAO,GAC1B,IAAmB,CAAC,GAEpB,KAAc,MAAsB;EACxC,AAAI,KAAM,EAAS,KAAK,CAAI;CAC9B;CAEA,EAAO,KAAK,2BAA2B;CACvC,IAAM,IAAkB,EAAK,KAAK,EAAQ,MAAM,OAAO,iBAAiB;CAQxE,AAPA,EACE,EACE,GACA,EAA2B,CAAe,CAC5C,CACF,GAEA,EAAO,KAAK,oBAAoB;CAChC,IAAM,IAAY,EAAK,KAAK,EAAQ,MAAM,OAAO,UAAU;CAG3D,AAFA,EAAW,EAAoB,GAAW,EAAqB,CAAS,CAAC,CAAC,GAE1E,EAAO,KAAK,qCAAqC;CACjD,IAAM,IAAiB,EAAK,KAC1B,EAAQ,MACR,OACA,UACA,gBACF;CAQA,OAPA,EACE,EACE,GACA,EAA0B,CAAc,CAC1C,CACF,GAEO;EACL,SAAS,CAAC;EACV;EACA,SAAS,CAAC;EACV,YAAY,CAAC;EACb,UAAU,CAAC;EACX,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAiB,CAAC;CACpB;AACF"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"generate.runtime-B_Fk1Jjs.js","names":[],"sources":["../../src/patterns/enable/cms/modifies/vite-config.ts","../../src/patterns/enable/cms/modifies/load-function.ts","../../src/patterns/enable/cms/modifies/layout.server.ts","../../src/patterns/enable/cms/modifies/layout.ts","../../src/patterns/enable/cms/modifies/layout.svelte.ts","../../src/patterns/enable/cms/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport {\n Project,\n QuoteKind,\n SyntaxKind,\n type ArrayLiteralExpression,\n type ObjectLiteralExpression,\n type PropertyAssignment,\n} from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst FAILURE_HINT = [\n \"Add the CMS plugin to your Vite config, ahead of sveltekit():\",\n \"\",\n \"import { cms } from '@velastack/cms/vite';\",\n \"\",\n \"export default defineConfig({\",\n \" plugins: [cms(), sveltekit(), /* ...existing plugins */],\",\n \"});\",\n].join(\"\\n\");\n\nconst NOT_FOUND_HINT = [\n \"Create a Vite config with the CMS plugin ahead of sveltekit():\",\n \"\",\n \"import { defineConfig } from 'vite';\",\n \"import { sveltekit } from '@sveltejs/kit/vite';\",\n \"import { cms } from '@velastack/cms/vite';\",\n \"\",\n \"export default defineConfig({\",\n \" plugins: [cms(), sveltekit()],\",\n \"});\",\n].join(\"\\n\");\n\nfunction elementName(text: string): string {\n return text.replace(/\\s/g, \"\");\n}\n\n/**\n * Registers `cms(...)` from `@velastack/cms/vite` in the Vite plugin list, just\n * ahead of `sveltekit()`. Only the plugin array is touched, so the inline\n * `sveltekit({ ... })` shape the templates use is left alone.\n */\nexport function modifyViteConfig(\n viteConfigPath: string,\n pluginArgs = \"\",\n): ModifyOutcome {\n const call = `cms(${pluginArgs})`;\n if (!fs.existsSync(viteConfigPath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const project = new Project({\n compilerOptions: { allowJs: true },\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n const sourceFile = project.addSourceFileAtPath(viteConfigPath);\n\n let changed = false;\n let failed = false;\n\n const hasImport = sourceFile\n .getImportDeclarations()\n .some((d) => d.getModuleSpecifierValue() === \"@velastack/cms/vite\");\n\n if (!hasImport) {\n sourceFile.insertImportDeclaration(0, {\n namedImports: [\"cms\"],\n moduleSpecifier: \"@velastack/cms/vite\",\n });\n changed = true;\n }\n\n const defineConfigCall = sourceFile\n .getDescendantsOfKind(SyntaxKind.CallExpression)\n .find((ce) => ce.getExpression().getText() === \"defineConfig\");\n\n const configArg = defineConfigCall?.getArguments()?.[0];\n const configObj =\n configArg?.getKind() === SyntaxKind.ObjectLiteralExpression\n ? (configArg as ObjectLiteralExpression)\n : null;\n\n if (!configObj) {\n failed = true;\n } else {\n const pluginsProp = configObj.getProperty(\"plugins\");\n if (!pluginsProp) {\n configObj.addPropertyAssignment({\n name: \"plugins\",\n initializer: `[${call}]`,\n });\n changed = true;\n } else if (pluginsProp.getKind() !== SyntaxKind.PropertyAssignment) {\n failed = true;\n } else {\n const pluginsInit = (pluginsProp as PropertyAssignment).getInitializer();\n\n if (!pluginsInit) {\n (pluginsProp as PropertyAssignment).setInitializer(`[${call}]`);\n changed = true;\n } else if (pluginsInit.getKind() !== SyntaxKind.ArrayLiteralExpression) {\n failed = true;\n } else {\n const arr = pluginsInit as ArrayLiteralExpression;\n const elements = arr.getElements();\n const hasCms = elements.some((el) =>\n elementName(el.getText()).startsWith(\"cms(\"),\n );\n\n if (!hasCms) {\n const sveltekitIndex = elements.findIndex((el) =>\n elementName(el.getText()).startsWith(\"sveltekit(\"),\n );\n arr.insertElement(sveltekitIndex === -1 ? 0 : sveltekitIndex, call);\n changed = true;\n }\n }\n }\n }\n\n if (changed) {\n sourceFile.formatText();\n sourceFile.saveSync();\n }\n\n if (failed) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n return { status: \"success\", changed };\n}\n","import {\n Node,\n Project,\n QuoteKind,\n SyntaxKind,\n type ArrowFunction,\n type Block,\n type FunctionDeclaration,\n type FunctionExpression,\n type ObjectLiteralExpression,\n type ParameterDeclaration,\n type ReturnStatement,\n type SourceFile,\n} from \"ts-morph\";\nimport type { ImportSpec } from \"../../../../runtime/ts-morph-helpers\";\n\n/**\n * What the two layout modifiers have in common: finding a SvelteKit `load`,\n * working out how it receives its event, and locating the object it returns.\n */\n\nexport type LoadFunction =\n ArrowFunction | FunctionExpression | FunctionDeclaration;\n\nexport function newProject(): Project {\n return new Project({\n compilerOptions: { allowJs: true },\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n}\n\nexport function ensureNamedImports(\n sourceFile: SourceFile,\n moduleSpecifier: string,\n names: string[],\n) {\n const existing = sourceFile\n .getImportDeclarations()\n .find((d) => d.getModuleSpecifierValue() === moduleSpecifier);\n if (!existing) {\n sourceFile.addImportDeclaration({ namedImports: names, moduleSpecifier });\n return;\n }\n for (const name of names) {\n const has = existing.getNamedImports().some((ni) => ni.getName() === name);\n if (!has) existing.addNamedImport(name);\n }\n}\n\nexport function ensureImportSpec(sourceFile: SourceFile, spec: ImportSpec) {\n if (spec.namedImports?.length) {\n ensureNamedImports(sourceFile, spec.moduleSpecifier, spec.namedImports);\n }\n const existing = sourceFile\n .getImportDeclarations()\n .find((d) => d.getModuleSpecifierValue() === spec.moduleSpecifier);\n if (existing) return;\n sourceFile.addImportDeclaration({\n moduleSpecifier: spec.moduleSpecifier,\n defaultImport: spec.defaultImport,\n namespaceImport: spec.namespaceImport,\n });\n}\n\n/** Peel wrappers (`loadFlash(fn)`, `(fn)`, `fn satisfies X`) down to the function. */\nfunction unwrapFunction(node: Node): ArrowFunction | FunctionExpression | null {\n if (Node.isArrowFunction(node) || Node.isFunctionExpression(node)) {\n return node;\n }\n if (\n Node.isParenthesizedExpression(node) ||\n Node.isAsExpression(node) ||\n Node.isSatisfiesExpression(node)\n ) {\n return unwrapFunction(node.getExpression());\n }\n if (Node.isCallExpression(node)) {\n for (const arg of node.getArguments()) {\n const fn = unwrapFunction(arg);\n if (fn) return fn;\n }\n }\n return null;\n}\n\n/** The exported `load`, whether declared as a function or wrapped in a const. */\nexport function findLoadFunction(sourceFile: SourceFile): LoadFunction | null {\n const declaration = sourceFile.getFunction(\"load\");\n if (declaration) {\n return declaration.isExported() ? declaration : null;\n }\n\n const variable = sourceFile.getVariableDeclaration(\"load\");\n if (!variable) return null;\n if (!variable.getVariableStatement()?.isExported()) return null;\n\n const initializer = variable.getInitializer();\n return initializer ? unwrapFunction(initializer) : null;\n}\n\nfunction isFunctionNode(node: Node): boolean {\n return (\n Node.isArrowFunction(node) ||\n Node.isFunctionExpression(node) ||\n Node.isFunctionDeclaration(node) ||\n Node.isMethodDeclaration(node)\n );\n}\n\n/**\n * The single, final `return <expression>` of the load body, or null when the\n * body has early returns — those would need any insertion hoisted above them,\n * and guessing where is worse than refusing.\n */\nexport function findFinalReturn(\n fn: LoadFunction,\n body: Block,\n): ReturnStatement | null {\n const statements = body.getStatements();\n const last = statements[statements.length - 1];\n if (!last || !Node.isReturnStatement(last)) return null;\n\n const returns = body\n .getDescendantsOfKind(SyntaxKind.ReturnStatement)\n .filter((r) => r.getFirstAncestor(isFunctionNode) === fn);\n if (returns.length !== 1) return null;\n\n return last;\n}\n\n/** The object literal a return statement yields, unwrapping parentheses. */\nexport function returnedObject(\n statement: ReturnStatement,\n): ObjectLiteralExpression | null {\n let expression = statement.getExpression();\n while (expression && Node.isParenthesizedExpression(expression)) {\n expression = expression.getExpression();\n }\n if (!expression || !Node.isObjectLiteralExpression(expression)) return null;\n return expression;\n}\n\nexport function hasProperty(\n object: ObjectLiteralExpression,\n name: string,\n): boolean {\n return object.getProperties().some((property) => {\n if (\n Node.isPropertyAssignment(property) ||\n Node.isShorthandPropertyAssignment(property)\n ) {\n return property.getName() === name;\n }\n return false;\n });\n}\n\nexport function hasSpreadOf(\n object: ObjectLiteralExpression,\n expressionText: string,\n): boolean {\n return object\n .getProperties()\n .some(\n (property) =>\n Node.isSpreadAssignment(property) &&\n property.getExpression().getText() === expressionText,\n );\n}\n\n/** How a load receives its event: not at all, by name, or destructured. */\nexport type EventParameter =\n | { kind: \"none\" }\n | { kind: \"identifier\"; name: string; param: ParameterDeclaration }\n | {\n kind: \"binding\";\n pattern: import(\"ts-morph\").ObjectBindingPattern;\n param: ParameterDeclaration;\n }\n | { kind: \"unsupported\" };\n\nexport function inspectEventParameter(fn: LoadFunction): EventParameter {\n const params = fn.getParameters();\n if (params.length === 0) return { kind: \"none\" };\n if (params.length > 1) return { kind: \"unsupported\" };\n\n const param = params[0];\n if (param.getInitializer() || param.isRestParameter()) {\n return { kind: \"unsupported\" };\n }\n const nameNode = param.getNameNode();\n if (Node.isIdentifier(nameNode)) {\n return { kind: \"identifier\", name: nameNode.getText(), param };\n }\n if (Node.isObjectBindingPattern(nameNode)) {\n return { kind: \"binding\", pattern: nameNode, param };\n }\n return { kind: \"unsupported\" };\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport dedent from \"dedent\";\nimport { Node } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport type { ImportSpec } from \"../../../../runtime/ts-morph-helpers\";\nimport {\n ensureImportSpec,\n ensureNamedImports,\n findFinalReturn,\n findLoadFunction,\n hasProperty,\n inspectEventParameter,\n newProject,\n returnedObject,\n} from \"./load-function\";\n\nexport interface LayoutServerLocale {\n /**\n * Expression passed as `locale` to `loadCms`, given the name of the load's\n * event parameter: `() => \"'en'\"` or `(event) => \\`getLocale(${event}.url)\\``.\n */\n expression: (eventName: string) => string;\n /** Imports the expression depends on. */\n imports?: ImportSpec[];\n}\n\n/** A single-locale site: the literal default locale. */\nexport const DEFAULT_LOCALE: LayoutServerLocale = {\n expression: () => \"'en'\",\n};\n\n/** A wuchale site: the locale enable-i18n's reroute already resolved from the URL. */\nexport const WUCHALE_LOCALE: LayoutServerLocale = {\n expression: (eventName) => `getLocale(${eventName}.url)`,\n imports: [\n { namedImports: [\"getLocale\"], moduleSpecifier: \"$locales/main.url\" },\n ],\n};\n\nfunction cmsSnippet(eventName: string, locale: string): string {\n return dedent`\n const { cms, notFound, gone, redirectTo } = await loadCms(${eventName}, { locale: ${locale} });\n if (redirectTo) redirect(308, redirectTo);\n if (gone) error(410, 'Gone');\n if (notFound) error(404, 'Not found');\n `;\n}\n\nfunction importLine(spec: ImportSpec): string {\n const parts: string[] = [];\n if (spec.defaultImport) parts.push(spec.defaultImport);\n if (spec.namespaceImport) parts.push(`* as ${spec.namespaceImport}`);\n if (spec.namedImports?.length)\n parts.push(`{ ${spec.namedImports.join(\", \")} }`);\n return `import ${parts.join(\", \")} from '${spec.moduleSpecifier}';`;\n}\n\n/**\n * A root `+layout.server.ts` written from scratch, for a project that has\n * none — the static template keeps its layout load universal.\n */\nexport function createdLayoutServer(locale: LayoutServerLocale): string {\n const imports = [\n \"import { error, redirect } from '@sveltejs/kit';\",\n \"import { loadCms } from '$lib/cms';\",\n ...(locale.imports ?? []).map(importLine),\n \"import type { LayoutServerLoad } from './$types';\",\n ].join(\"\\n\");\n const snippet = cmsSnippet(\"event\", locale.expression(\"event\"))\n .split(\"\\n\")\n .join(\"\\n\\t\");\n\n return dedent`\n ${imports}\n\n export const load: LayoutServerLoad = async (event) => {\n \t${snippet}\n\n \treturn { cms };\n };\n `.concat(\"\\n\");\n}\n\nconst FAILURE_HINT = [\n \"Call loadCms from the root +layout.server.ts load and return `cms`:\",\n \"\",\n createdLayoutServer(DEFAULT_LOCALE).trimEnd(),\n \"\",\n \"loadCms needs the whole event, so a destructured parameter has to become\",\n \"`event` with the destructuring moved into the body.\",\n].join(\"\\n\");\n\n/**\n * Wires `loadCms` into the root `+layout.server.ts`, creating the file when\n * the project has none:\n *\n * - `loadCms` needs the whole request event, so a destructured parameter is\n * renamed to `event` and the destructuring becomes the first statement.\n * - The tombstone triple (`redirectTo`, `gone`, `notFound`) is handled just\n * before the return.\n * - `cms` is added to the returned object, ahead of any spread so nothing\n * later can shadow it.\n *\n * Anything else — no exported `load`, an expression-bodied arrow, several\n * returns, a non-literal return — is reported as `failed` with the snippet to\n * paste, and the file is left exactly as it was.\n */\nexport function modifyLayoutServer(\n layoutServerPath: string,\n locale: LayoutServerLocale = DEFAULT_LOCALE,\n): ModifyOutcome {\n if (!fs.existsSync(layoutServerPath)) {\n fs.mkdirSync(path.dirname(layoutServerPath), { recursive: true });\n fs.writeFileSync(layoutServerPath, createdLayoutServer(locale));\n return { status: \"success\", changed: true };\n }\n\n const original = fs.readFileSync(layoutServerPath, \"utf8\");\n if (original.includes(\"loadCms(\")) {\n return { status: \"success\", changed: false };\n }\n\n const sourceFile = newProject().addSourceFileAtPath(layoutServerPath);\n\n // --- Inspect everything before touching anything. ---\n const fn = findLoadFunction(sourceFile);\n if (!fn) return { status: \"failed\", message: FAILURE_HINT };\n\n const body = fn.getBody();\n if (!body || !Node.isBlock(body)) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n const event = inspectEventParameter(fn);\n if (event.kind === \"unsupported\") {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n const returned = findFinalReturn(fn, body);\n const object = returned && returnedObject(returned);\n if (!returned || !object) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n const eventName = event.kind === \"identifier\" ? event.name : \"event\";\n\n // --- Mutate bottom-up so earlier node references stay valid. ---\n if (!hasProperty(object, \"cms\")) {\n const spreadIndex = object\n .getProperties()\n .findIndex((property) => Node.isSpreadAssignment(property));\n if (spreadIndex === -1) {\n object.addShorthandPropertyAssignment({ name: \"cms\" });\n } else {\n object.insertShorthandPropertyAssignment(spreadIndex, { name: \"cms\" });\n }\n }\n\n const returnIndex = body.getStatements().indexOf(returned);\n body.insertStatements(\n returnIndex,\n `\\n${cmsSnippet(eventName, locale.expression(eventName))}\\n`,\n );\n\n if (event.kind === \"binding\") {\n const destructuring = event.pattern.getText();\n body.insertStatements(0, `const ${destructuring} = ${eventName};`);\n const typeText = event.param.getTypeNode()?.getText();\n event.param.replaceWithText(\n typeText ? `${eventName}: ${typeText}` : eventName,\n );\n } else if (event.kind === \"none\") {\n fn.addParameter({ name: eventName });\n }\n\n if (!fn.isAsync()) fn.setIsAsync(true);\n\n ensureNamedImports(sourceFile, \"@sveltejs/kit\", [\"error\", \"redirect\"]);\n ensureNamedImports(sourceFile, \"$lib/cms\", [\"loadCms\"]);\n for (const spec of locale.imports ?? []) {\n ensureImportSpec(sourceFile, spec);\n }\n\n sourceFile.formatText();\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n}\n","import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { Node } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport {\n findFinalReturn,\n findLoadFunction,\n hasSpreadOf,\n inspectEventParameter,\n newProject,\n returnedObject,\n} from \"./load-function\";\n\nconst FAILURE_HINT = dedent`\n Forward the server load's data through the root +layout.ts, so \\`cms\\` reaches\n the page:\n\n export const load = async ({ url, data }) => {\n // ...existing code...\n return { ...data, /* existing keys */ };\n };\n`;\n\n/**\n * Make a universal root \\`+layout.ts\\` forward its server load's data.\n *\n * SvelteKit hands a universal load the server load's result as \\`data\\`, and\n * only what the universal load returns reaches the page. A layout that\n * returns its own object without spreading \\`data\\` — the static template\n * does — would drop \\`cms\\` on the floor once \\`+layout.server.ts\\` exists.\n *\n * No file, or a file without a \\`load\\`, needs nothing: server data flows\n * through on its own.\n */\nexport function modifyLayoutUniversal(layoutPath: string): ModifyOutcome {\n if (!fs.existsSync(layoutPath)) {\n return { status: \"success\", changed: false };\n }\n\n const sourceFile = newProject().addSourceFileAtPath(layoutPath);\n\n const fn = findLoadFunction(sourceFile);\n if (!fn) return { status: \"success\", changed: false };\n\n const body = fn.getBody();\n if (!body || !Node.isBlock(body)) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n const event = inspectEventParameter(fn);\n if (event.kind === \"unsupported\") {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n const returned = findFinalReturn(fn, body);\n if (!returned) return { status: \"failed\", message: FAILURE_HINT };\n\n const dataExpression =\n event.kind === \"identifier\" ? `${event.name}.data` : \"data\";\n\n // `return data;` already forwards everything.\n const expression = returned.getExpression();\n if (expression && expression.getText() === dataExpression) {\n return { status: \"success\", changed: false };\n }\n\n const object = returnedObject(returned);\n if (!object) return { status: \"failed\", message: FAILURE_HINT };\n if (hasSpreadOf(object, dataExpression)) {\n return { status: \"success\", changed: false };\n }\n\n // --- Mutate bottom-up so earlier node references stay valid. ---\n // First, so the layout's own keys still win over anything the server sent.\n object.insertSpreadAssignment(0, { expression: dataExpression });\n\n if (event.kind === \"binding\") {\n const hasData = event.pattern\n .getElements()\n .some((element) => element.getName() === \"data\");\n if (!hasData) {\n const text = event.pattern.getText();\n event.pattern.replaceWithText(text.replace(/^\\{\\s*/, \"{ data, \"));\n }\n } else if (event.kind === \"none\") {\n fn.addParameter({ name: \"{ data }\" });\n }\n\n sourceFile.formatText();\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n}\n","import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport {\n ensureImports,\n withInMemoryScript,\n} from \"../../../../runtime/ts-morph-helpers\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst IMPORT_SNIPPET = dedent`\n import { AdminBar } from '@velastack/cms';\n`;\n\nconst MARKUP_SNIPPET = \"\\n<AdminBar />\\n\";\n\nconst NOT_FOUND_HINT = [\n \"Create the root src/routes/+layout.svelte and mount <AdminBar /> inside it.\",\n \"\",\n \"Import for the <script> tag:\",\n \"\",\n IMPORT_SNIPPET,\n \"\",\n \"Markup to add at the top level of the layout, above {@render children()}:\",\n MARKUP_SNIPPET.trim(),\n].join(\"\\n\");\n\nconst FAILURE_HINT = [\n \"Mount <AdminBar /> in the root src/routes/+layout.svelte.\",\n \"\",\n 'Import for a <script lang=\"ts\"> tag:',\n \"\",\n IMPORT_SNIPPET,\n \"\",\n \"Markup to add at the top level of the layout, above {@render children()}:\",\n MARKUP_SNIPPET.trim(),\n].join(\"\\n\");\n\n/**\n * Mounts `<AdminBar />` at the top level of the root layout, ahead of\n * `{@render children()}` so the bar is in the DOM before the page content.\n * Falls back to appending when the layout has no render tag or slot.\n */\nexport function modifyLayoutSvelte(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(\"AdminBar\")) {\n return { status: \"success\", changed: false };\n }\n if (!file.getScript()) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n file.modifyScript((source) => {\n const { source: out } = withInMemoryScript(source, (sf) => {\n ensureImports(sf, [\n { namedImports: [\"AdminBar\"], moduleSpecifier: \"@velastack/cms\" },\n ]);\n });\n return out;\n });\n\n if (!file.insertBeforeChildren(MARKUP_SNIPPET)) {\n file.appendMarkup(MARKUP_SNIPPET);\n }\n file.writeTo(layoutPath);\n return { status: \"success\", changed: file.hasChanged() };\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport {\n probeFirstExisting,\n VITE_CONFIG_CANDIDATES,\n} from \"../../../runtime/config-target\";\nimport { resolveMode, type CmsMode } from \"./generate\";\nimport { modifyViteConfig } from \"./modifies/vite-config\";\nimport {\n DEFAULT_LOCALE,\n WUCHALE_LOCALE,\n modifyLayoutServer,\n} from \"./modifies/layout.server\";\nimport { modifyLayoutUniversal } from \"./modifies/layout\";\nimport { modifyLayoutSvelte } from \"./modifies/layout.svelte\";\n\n/**\n * Drop any create that already exists on disk.\n *\n * `writeResult` overwrites an existing create whose content differs and\n * reports it as a modify, which for these files would mean a re-run silently\n * resetting a developer's edits to `$lib/cms.ts` or the backend config. The\n * wiring is theirs once it has been written; a re-run only fills in what is\n * missing.\n */\nexport function keepMissing(creates: File[], root: string): File[] {\n return creates.filter((file) => !fs.existsSync(path.join(root, file.path)));\n}\n\n/** The locale list from `wuchale.config.js`, or null when it cannot be read. */\nexport function readWuchaleLocales(root: string): string[] | null {\n const configPath = path.join(root, \"wuchale.config.js\");\n if (!fs.existsSync(configPath)) return null;\n const match = fs\n .readFileSync(configPath, \"utf8\")\n .match(/locales:\\s*\\[([^\\]]*)\\]/);\n if (!match) return null;\n const locales = [...match[1].matchAll(/['\"]([^'\"]+)['\"]/g)].map((m) => m[1]);\n return locales.length > 0 ? locales : null;\n}\n\n/**\n * Arguments for the `cms()` Vite plugin.\n *\n * A hosted CMS needs the endpoint and locales at build time so media can be\n * downloaded into the prerendered site. An app hosting the backend itself\n * needs nothing: the media steps are no-ops without an endpoint.\n */\nexport function vitePluginArgs(mode: CmsMode, locales: string[]): string {\n if (mode.local) return \"\";\n const list = locales.map((locale) => `'${locale}'`).join(\", \");\n return `{ endpoint: '${mode.endpoint}', locales: [${list}] }`;\n}\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const modifies: File[] = [];\n const mode = resolveMode(options);\n const i18n = options.features.i18n;\n\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n logger.info(\"Modifying vite.config\");\n const viteConfigPath =\n probeFirstExisting(options.root, VITE_CONFIG_CANDIDATES) ??\n path.join(options.root, VITE_CONFIG_CANDIDATES[0]);\n const locales = (i18n && readWuchaleLocales(options.root)) || [\"en\"];\n pushResult(\n modifyOutcomeToFile(\n viteConfigPath,\n modifyViteConfig(viteConfigPath, vitePluginArgs(mode, locales)),\n ),\n );\n\n logger.info(\"Modifying src/routes/+layout.server.ts\");\n const layoutServerPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"+layout.server.ts\",\n );\n const locale = i18n ? WUCHALE_LOCALE : DEFAULT_LOCALE;\n pushResult(\n modifyOutcomeToFile(\n layoutServerPath,\n modifyLayoutServer(layoutServerPath, locale),\n ),\n );\n\n // A universal root layout has to pass the server load's data along, or\n // `cms` never reaches the page. The static template has one.\n logger.info(\"Modifying src/routes/+layout.ts\");\n const layoutUniversalPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"+layout.ts\",\n );\n pushResult(\n modifyOutcomeToFile(\n layoutUniversalPath,\n modifyLayoutUniversal(layoutUniversalPath),\n ),\n );\n\n logger.info(\"Modifying src/routes/+layout.svelte\");\n const layoutSveltePath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"+layout.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(layoutSveltePath, modifyLayoutSvelte(layoutSveltePath)),\n );\n\n return {\n creates: [],\n modifies,\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n } satisfies Result;\n}\n"],"mappings":";;;;;;;;;;AAWA,IAAM,IAAe;CACnB;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC,CAAC,KAAK,IAAI,GAEL,IAAiB;CACrB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC,CAAC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,CAAC,CAC5E,GAEO;EACL,SAAS,CAAC;EACV;EACA,SAAS,CAAC;EACV,YAAY,CAAC;EACb,UAAU,CAAC;EACX,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAiB,CAAC;CACpB;AACF"}
@@ -1,138 +0,0 @@
1
- import { n as e } from "./logger-CQONztPm.js";
2
- import { n as t } from "./shared-Cmbzu7Od.js";
3
- import { modifyOutcomeToFile as n } from "./modify-file-Cgu_WeFk.js";
4
- import { c as r, i, l as a } from "./ts-morph-helpers-teS3yXg-.js";
5
- import o from "node:path";
6
- import s from "node:fs";
7
- import { Project as c, QuoteKind as l, SyntaxKind as u } from "ts-morph";
8
- //#region src/patterns/disable/content-negotiation/modifies/hooks.server.ts
9
- function d(e) {
10
- let t = e.getImportDeclarations().find((e) => e.getModuleSpecifierValue() === "$lib/negotiate");
11
- if (!t) return !1;
12
- let n = t.getNamedImports().find((e) => e.getName() === "handle" && e.getAliasNode()?.getText() === "handleNegotiate");
13
- return n ? (t.getNamedImports().length === 1 && !t.getDefaultImport() ? t.remove() : n.remove(), !0) : !1;
14
- }
15
- function f(e) {
16
- let t = e.getImportDeclarations().find((e) => e.getModuleSpecifierValue() === "@sveltejs/kit/hooks");
17
- if (!t || e.getDescendantsOfKind(u.Identifier).some((e) => {
18
- if (e.getText() !== "sequence") return !1;
19
- let t = e.getParent()?.getKind();
20
- return t !== u.ImportSpecifier && t !== u.ImportClause;
21
- })) return;
22
- let n = t.getNamedImports().find((e) => e.getName() === "sequence");
23
- n && (t.getNamedImports().length === 1 && !t.getDefaultImport() ? t.remove() : n.remove());
24
- }
25
- function p(e) {
26
- if (!s.existsSync(e)) return {
27
- status: "success",
28
- changed: !1
29
- };
30
- let t = s.readFileSync(e, "utf8");
31
- if (!t.includes("handleNegotiate")) return {
32
- status: "success",
33
- changed: !1
34
- };
35
- let n = new c({
36
- compilerOptions: { allowJs: !0 },
37
- manipulationSettings: { quoteKind: l.Single }
38
- }).addSourceFileAtPath(e), r = n.getVariableDeclaration("handle");
39
- if (!r) return d(n), f(n), n.formatText(), n.saveSync(), {
40
- status: "success",
41
- changed: n.getFullText() !== t
42
- };
43
- let i = r.getInitializer();
44
- if (i?.getKind() === u.CallExpression) {
45
- let e = i.asKindOrThrow(u.CallExpression);
46
- if (e.getExpression().getText() === "sequence") {
47
- let t = e.getArguments(), n = t.findIndex((e) => e.getText() === "handleNegotiate");
48
- if (n >= 0) {
49
- if (t.length === 2) {
50
- let e = t[+(n === 0)].getText();
51
- r.setInitializer(e);
52
- } else e.removeArgument(n);
53
- }
54
- }
55
- }
56
- return d(n), f(n), n.formatText(), n.saveSync(), {
57
- status: "success",
58
- changed: n.getFullText() !== t
59
- };
60
- }
61
- //#endregion
62
- //#region src/patterns/disable/content-negotiation/modifies/hooks.ts
63
- function m(e) {
64
- let t = e.getImportDeclarations().find((e) => e.getModuleSpecifierValue() === "$lib/negotiate");
65
- if (!t) return !1;
66
- let n = t.getNamedImports().find((e) => e.getName() === "reroute" && e.getAliasNode()?.getText() === "negotiateReroute");
67
- return n ? (t.getNamedImports().length === 1 && !t.getDefaultImport() ? t.remove() : n.remove(), !0) : !1;
68
- }
69
- function h(e) {
70
- return e.getStatements().every((e) => e.getKind() === u.EmptyStatement);
71
- }
72
- function g(e) {
73
- if (!s.existsSync(e)) return {
74
- status: "success",
75
- changed: !1
76
- };
77
- let t = s.readFileSync(e, "utf8");
78
- if (!t.includes("negotiateReroute")) return {
79
- status: "success",
80
- changed: !1
81
- };
82
- let n = new c({
83
- compilerOptions: { allowJs: !0 },
84
- manipulationSettings: { quoteKind: l.Single }
85
- }).addSourceFileAtPath(e), r = n.getVariableDeclaration("reroute"), i = (r?.getInitializer())?.getText() ?? "", a = n.getVariableDeclarations().some((e) => e.getName() === "rerouteDeLocalize");
86
- return r && a && i.includes("rerouteDeLocalize") && i.includes("negotiateReroute") ? r.setInitializer("({ url }) => rerouteDeLocalize(url.pathname)") : r && i.includes("negotiateReroute") && r.getFirstAncestorByKind(u.VariableStatement)?.remove(), m(n), h(n) ? (s.writeFileSync(e, "", "utf8"), {
87
- status: "success",
88
- changed: !0
89
- }) : (n.formatText(), n.saveSync(), {
90
- status: "success",
91
- changed: n.getFullText() !== t
92
- });
93
- }
94
- //#endregion
95
- //#region src/patterns/disable/content-negotiation/modifies/root-layout.svelte.ts
96
- function _(e) {
97
- if (!s.existsSync(e)) return {
98
- status: "success",
99
- changed: !1
100
- };
101
- let t = a.fromPath(e), n = t.hasElement("Negotiate");
102
- return t.modifyScript((e) => {
103
- let { source: t } = r(e, (e) => {
104
- i(e, "$lib/negotiate");
105
- });
106
- return t;
107
- }), n && t.removeElement("Negotiate"), t.writeTo(e), {
108
- status: "success",
109
- changed: t.hasChanged()
110
- };
111
- }
112
- //#endregion
113
- //#region src/patterns/disable/content-negotiation/generate.runtime.ts
114
- async function v(r) {
115
- let i = e(r), a = [], c = [], l = (e) => {
116
- e && a.push(e);
117
- };
118
- i.info("Reverting hooks.server.ts");
119
- let u = o.join(r.root, "src", "hooks.server.ts");
120
- l(n(u, p(u))), i.info("Reverting hooks.ts");
121
- let d = o.join(r.root, "src", "hooks.ts"), f = g(d);
122
- s.existsSync(d) && s.readFileSync(d, "utf8").trim() === "" ? c.push(t(d)) : l(n(d, f)), i.info("Reverting src/routes/+layout.svelte");
123
- let m = o.join(r.root, "src", "routes", "+layout.svelte");
124
- return l(n(m, _(m))), {
125
- creates: [],
126
- modifies: a,
127
- deletes: c,
128
- components: [],
129
- packages: [],
130
- collections: [],
131
- collectionPatches: [],
132
- collectionDrops: []
133
- };
134
- }
135
- //#endregion
136
- export { v as generate };
137
-
138
- //# sourceMappingURL=generate.runtime-BcVAKzoY.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"generate.runtime-BcVAKzoY.js","names":[],"sources":["../../src/patterns/disable/content-negotiation/modifies/hooks.server.ts","../../src/patterns/disable/content-negotiation/modifies/hooks.ts","../../src/patterns/disable/content-negotiation/modifies/root-layout.svelte.ts","../../src/patterns/disable/content-negotiation/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport { Project, QuoteKind, SyntaxKind, type SourceFile } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nfunction removeNegotiateImport(sourceFile: SourceFile): boolean {\n const decl = sourceFile\n .getImportDeclarations()\n .find((d) => d.getModuleSpecifierValue() === \"$lib/negotiate\");\n if (!decl) return false;\n\n const named = decl.getNamedImports().find((ni) => {\n return (\n ni.getName() === \"handle\" &&\n ni.getAliasNode()?.getText() === \"handleNegotiate\"\n );\n });\n\n if (!named) return false;\n\n if (decl.getNamedImports().length === 1 && !decl.getDefaultImport()) {\n decl.remove();\n } else {\n named.remove();\n }\n return true;\n}\n\nfunction removeSequenceImportIfUnused(sourceFile: SourceFile): void {\n const decl = sourceFile\n .getImportDeclarations()\n .find((d) => d.getModuleSpecifierValue() === \"@sveltejs/kit/hooks\");\n if (!decl) return;\n\n const stillReferenced = sourceFile\n .getDescendantsOfKind(SyntaxKind.Identifier)\n .some((id) => {\n if (id.getText() !== \"sequence\") return false;\n const parent = id.getParent();\n const kind = parent?.getKind();\n return (\n kind !== SyntaxKind.ImportSpecifier && kind !== SyntaxKind.ImportClause\n );\n });\n\n if (stillReferenced) return;\n\n const named = decl\n .getNamedImports()\n .find((ni) => ni.getName() === \"sequence\");\n if (!named) return;\n\n if (decl.getNamedImports().length === 1 && !decl.getDefaultImport()) {\n decl.remove();\n } else {\n named.remove();\n }\n}\n\nexport function unmodifyHooksServerNegotiate(\n hooksServerPath: string,\n): ModifyOutcome {\n if (!fs.existsSync(hooksServerPath)) {\n return { status: \"success\", changed: false };\n }\n\n const original = fs.readFileSync(hooksServerPath, \"utf8\");\n if (!original.includes(\"handleNegotiate\")) {\n return { status: \"success\", changed: false };\n }\n\n const project = new Project({\n compilerOptions: { allowJs: true },\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n const sourceFile = project.addSourceFileAtPath(hooksServerPath);\n\n const handleDecl = sourceFile.getVariableDeclaration(\"handle\");\n if (!handleDecl) {\n removeNegotiateImport(sourceFile);\n removeSequenceImportIfUnused(sourceFile);\n sourceFile.formatText();\n sourceFile.saveSync();\n return {\n status: \"success\",\n changed: sourceFile.getFullText() !== original,\n };\n }\n\n const init = handleDecl.getInitializer();\n if (init?.getKind() === SyntaxKind.CallExpression) {\n const call = init.asKindOrThrow(SyntaxKind.CallExpression);\n if (call.getExpression().getText() === \"sequence\") {\n const args = call.getArguments();\n const idx = args.findIndex((arg) => arg.getText() === \"handleNegotiate\");\n if (idx >= 0) {\n if (args.length === 2) {\n const keepText = args[idx === 0 ? 1 : 0].getText();\n handleDecl.setInitializer(keepText);\n } else {\n call.removeArgument(idx);\n }\n }\n }\n }\n\n removeNegotiateImport(sourceFile);\n removeSequenceImportIfUnused(sourceFile);\n sourceFile.formatText();\n sourceFile.saveSync();\n\n return {\n status: \"success\",\n changed: sourceFile.getFullText() !== original,\n };\n}\n","import fs from \"node:fs\";\nimport { Project, QuoteKind, SyntaxKind, type SourceFile } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nfunction removeNegotiateImport(sourceFile: SourceFile): boolean {\n const decl = sourceFile\n .getImportDeclarations()\n .find((d) => d.getModuleSpecifierValue() === \"$lib/negotiate\");\n if (!decl) return false;\n\n const named = decl.getNamedImports().find((ni) => {\n return (\n ni.getName() === \"reroute\" &&\n ni.getAliasNode()?.getText() === \"negotiateReroute\"\n );\n });\n if (!named) return false;\n\n if (decl.getNamedImports().length === 1 && !decl.getDefaultImport()) {\n decl.remove();\n } else {\n named.remove();\n }\n return true;\n}\n\nfunction isMeaningfullyEmpty(sourceFile: SourceFile): boolean {\n return sourceFile\n .getStatements()\n .every((s) => s.getKind() === SyntaxKind.EmptyStatement);\n}\n\nexport function unmodifyHooksNegotiate(hooksPath: string): ModifyOutcome {\n if (!fs.existsSync(hooksPath)) {\n return { status: \"success\", changed: false };\n }\n\n const original = fs.readFileSync(hooksPath, \"utf8\");\n if (!original.includes(\"negotiateReroute\")) {\n return { status: \"success\", changed: false };\n }\n\n const project = new Project({\n compilerOptions: { allowJs: true },\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n const sourceFile = project.addSourceFileAtPath(hooksPath);\n\n const rerouteDecl = sourceFile.getVariableDeclaration(\"reroute\");\n const init = rerouteDecl?.getInitializer();\n const initText = init?.getText() ?? \"\";\n\n const hasI18nHelper = sourceFile\n .getVariableDeclarations()\n .some((d) => d.getName() === \"rerouteDeLocalize\");\n\n if (\n rerouteDecl &&\n hasI18nHelper &&\n initText.includes(\"rerouteDeLocalize\") &&\n initText.includes(\"negotiateReroute\")\n ) {\n rerouteDecl.setInitializer(\"({ url }) => rerouteDeLocalize(url.pathname)\");\n } else if (rerouteDecl && initText.includes(\"negotiateReroute\")) {\n const stmt = rerouteDecl.getFirstAncestorByKind(\n SyntaxKind.VariableStatement,\n );\n stmt?.remove();\n }\n\n removeNegotiateImport(sourceFile);\n\n if (isMeaningfullyEmpty(sourceFile)) {\n // Emptied rather than removed: the runtime turns an empty hooks.ts into a\n // delete entry, so the removal is written and reported like any other.\n fs.writeFileSync(hooksPath, \"\", \"utf8\");\n return { status: \"success\", changed: true };\n }\n\n sourceFile.formatText();\n sourceFile.saveSync();\n return {\n status: \"success\",\n changed: sourceFile.getFullText() !== original,\n };\n}\n","import fs from \"node:fs\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport {\n removeImportByModuleSpecifier,\n withInMemoryScript,\n} from \"../../../../runtime/ts-morph-helpers\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nexport function unmodifyRootLayoutNegotiate(layoutPath: string): ModifyOutcome {\n if (!fs.existsSync(layoutPath)) {\n return { status: \"success\", changed: false };\n }\n\n const file = SvelteFile.fromPath(layoutPath);\n const hasElement = file.hasElement(\"Negotiate\");\n\n file.modifyScript((source) => {\n const { source: out } = withInMemoryScript(source, (sf) => {\n removeImportByModuleSpecifier(sf, \"$lib/negotiate\");\n });\n return out;\n });\n\n if (hasElement) {\n file.removeElement(\"Negotiate\");\n }\n\n file.writeTo(layoutPath);\n return { status: \"success\", changed: file.hasChanged() };\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { toDeleteEntry } from \"../../destroy/shared\";\nimport { getLogger } from \"../../../core/logger\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { unmodifyHooksServerNegotiate } from \"./modifies/hooks.server\";\nimport { unmodifyHooksNegotiate } from \"./modifies/hooks\";\nimport { unmodifyRootLayoutNegotiate } from \"./modifies/root-layout.svelte\";\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const modifies: File[] = [];\n const deletes: File[] = [];\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n logger.info(\"Reverting hooks.server.ts\");\n const hooksServerPath = path.join(options.root, \"src\", \"hooks.server.ts\");\n pushResult(\n modifyOutcomeToFile(\n hooksServerPath,\n unmodifyHooksServerNegotiate(hooksServerPath),\n ),\n );\n\n logger.info(\"Reverting hooks.ts\");\n const hooksPath = path.join(options.root, \"src\", \"hooks.ts\");\n const hooksOutcome = unmodifyHooksNegotiate(hooksPath);\n if (\n fs.existsSync(hooksPath) &&\n fs.readFileSync(hooksPath, \"utf8\").trim() === \"\"\n ) {\n // The reroute was all it contained; the file goes with it.\n deletes.push(toDeleteEntry(hooksPath));\n } else {\n pushResult(modifyOutcomeToFile(hooksPath, hooksOutcome));\n }\n\n logger.info(\"Reverting src/routes/+layout.svelte\");\n const rootLayoutPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"+layout.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(\n rootLayoutPath,\n unmodifyRootLayoutNegotiate(rootLayoutPath),\n ),\n );\n\n return {\n creates: [],\n modifies,\n deletes,\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n } satisfies Result;\n}\n"],"mappings":";;;;;;;;AAIA,SAAS,EAAsB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