@velastack/patterns 0.0.40 → 0.0.42

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -5,7 +5,7 @@ import { i as s, t as c } from "./chunks/constants-BMZmCRiI.js";
5
5
  import { t as l } from "./chunks/taggedTemplateLiteral-Bfbldyfk.js";
6
6
  import { n as u } from "./chunks/logger-BpgCb-ZG.js";
7
7
  import { n as d, r as f, t as p } from "./chunks/nav-user-Jp5yYtw5.js";
8
- import { a as m, c as h, i as ee, n as g, o as _, r as te, s as ne, t as re } from "./chunks/_server-B3Rzajf2.js";
8
+ import { a as m, c as h, i as ee, n as g, o as _, r as te, s as ne, t as re } from "./chunks/_server-CsAmAg4q.js";
9
9
  import { t as ie } from "./chunks/pocketbase-D5p0NSdu.js";
10
10
  import { n as v, t as ae } from "./chunks/shared-4hq3AXC3.js";
11
11
  import oe from "prettier";
@@ -25,9 +25,26 @@ var ce = Object.create, le = Object.defineProperty, ue = Object.getOwnPropertyDe
25
25
  throw Error("Calling `require` for \"" + e + "\" in an environment that doesn't expose the `require` function. See https://rolldown.rs/in-depth/bundling-cjs#require-external-modules for more details.");
26
26
  }), ve = {
27
27
  name: "@velastack/patterns",
28
- version: "0.0.40",
28
+ version: "0.0.42",
29
+ description: "Registry of VelaStack patterns: generators and modifications applied to SvelteKit projects by the VelaStack CLI.",
29
30
  type: "module",
30
31
  private: !1,
32
+ license: "MIT",
33
+ repository: {
34
+ type: "git",
35
+ url: "git+https://github.com/velastack/patterns.git"
36
+ },
37
+ homepage: "https://github.com/velastack/patterns#readme",
38
+ bugs: { url: "https://github.com/velastack/patterns/issues" },
39
+ keywords: [
40
+ "velastack",
41
+ "sveltekit",
42
+ "patterns",
43
+ "generators",
44
+ "scaffolding",
45
+ "pocketbase"
46
+ ],
47
+ engines: { node: ">=20" },
31
48
  main: "./dist/index.js",
32
49
  types: "./dist/index.d.ts",
33
50
  files: ["dist"],
@@ -36,6 +53,7 @@ var ce = Object.create, le = Object.defineProperty, ue = Object.getOwnPropertyDe
36
53
  dev: "vite build --watch",
37
54
  clean: "rm -rf dist",
38
55
  demo: "vite-node scripts/demo.ts --",
56
+ format: "prettier --write .",
39
57
  lint: "npm run lint:ts && npm run lint:format",
40
58
  "lint:ts": "tsc --noEmit",
41
59
  "lint:format": "prettier --check .",
@@ -2186,7 +2204,7 @@ var on = "generate-form", sn = "1.0.7", cn = "src/patterns/generate/form", ln =
2186
2204
  async function un(e) {
2187
2205
  let t = await an(e);
2188
2206
  if (e.env !== "runtime") return y(t);
2189
- let { writeResult: n } = await import("./chunks/write-result-DJ32RMq5.js");
2207
+ let { writeResult: n } = await import("./chunks/write-result-BPDot58Z.js");
2190
2208
  return n(await y(t), e);
2191
2209
  }
2192
2210
  var dn = {
@@ -2482,7 +2500,7 @@ async function Rn(e) {
2482
2500
  let o = i(e.root), s = r(o, a(o)), c = {
2483
2501
  ...t,
2484
2502
  modifies: [...t.modifies, ...s ? [s] : []]
2485
- }, { writeResult: l } = await import("./chunks/write-result-DJ32RMq5.js");
2503
+ }, { writeResult: l } = await import("./chunks/write-result-BPDot58Z.js");
2486
2504
  return l(await y(c), e);
2487
2505
  }
2488
2506
  var zn = {
@@ -2624,7 +2642,7 @@ async function Yn(e) {
2624
2642
  let o = {
2625
2643
  ...t,
2626
2644
  creates: [...t.creates, ...a]
2627
- }, { writeResult: s } = await import("./chunks/write-result-DJ32RMq5.js");
2645
+ }, { writeResult: s } = await import("./chunks/write-result-BPDot58Z.js");
2628
2646
  return s(await y(o), e);
2629
2647
  }
2630
2648
  var Xn = {
@@ -2729,7 +2747,7 @@ async function ir(e) {
2729
2747
  let { createCollections: n } = await import("./chunks/collections-rD0M_Wxo.js"), r = await n(t.collections, e), i = {
2730
2748
  ...t,
2731
2749
  creates: [...t.creates, ...r]
2732
- }, { writeResult: a } = await import("./chunks/write-result-DJ32RMq5.js");
2750
+ }, { writeResult: a } = await import("./chunks/write-result-BPDot58Z.js");
2733
2751
  return a(await y(i), e);
2734
2752
  }
2735
2753
  var ar = {
@@ -3116,7 +3134,7 @@ async function Ar(e) {
3116
3134
  let { createCollections: n } = await import("./chunks/collections-rD0M_Wxo.js"), r = await n(t.collections, e), i = {
3117
3135
  ...t,
3118
3136
  creates: [...t.creates, ...r]
3119
- }, { writeResult: a } = await import("./chunks/write-result-DJ32RMq5.js");
3137
+ }, { writeResult: a } = await import("./chunks/write-result-BPDot58Z.js");
3120
3138
  return a(await y(i), e);
3121
3139
  }
3122
3140
  var jr = {
@@ -3488,7 +3506,7 @@ async function li(e) {
3488
3506
  ...t,
3489
3507
  creates: [...t.creates, ...i],
3490
3508
  modifies: [...t.modifies, ...l ? [l] : []]
3491
- }, { writeResult: f } = await import("./chunks/write-result-DJ32RMq5.js");
3509
+ }, { writeResult: f } = await import("./chunks/write-result-BPDot58Z.js");
3492
3510
  return f(await y(d), e);
3493
3511
  }
3494
3512
  var ui = {
@@ -3584,7 +3602,7 @@ var mi = "generate-schema", hi = "1.0.7", gi = "src/patterns/generate/schema", _
3584
3602
  async function vi(e) {
3585
3603
  let t = await pi(e);
3586
3604
  if (e.env !== "runtime") return y(t);
3587
- let { writeResult: n } = await import("./chunks/write-result-DJ32RMq5.js");
3605
+ let { writeResult: n } = await import("./chunks/write-result-BPDot58Z.js");
3588
3606
  return n(await y(t), e);
3589
3607
  }
3590
3608
  var yi = {
@@ -3780,7 +3798,8 @@ async function ya(e) {
3780
3798
  //#endregion
3781
3799
  //#region src/patterns/enable/auth/generate.preview.ts
3782
3800
  var ba = /* @__PURE__ */ Object.assign({
3783
- "./preview-modifies/src/hooks.server.ts": "import {\n POCKETBASE_URL,\n POCKETBASE_SUPERUSER_EMAIL,\n POCKETBASE_SUPERUSER_PASSWORD,\n} from \"$env/static/private\";\nimport { handlePocketbase } from \"@velastack/pocketbase\";\n\nexport const handle = handlePocketbase({\n pocketbaseUrl: POCKETBASE_URL,\n superuserEmail: POCKETBASE_SUPERUSER_EMAIL,\n superuserPassword: POCKETBASE_SUPERUSER_PASSWORD,\n // [!code highlight:1]\n auth: { protectedRoutes: [\"/(app)\"] },\n});\n",
3801
+ "./preview-modifies/src/hooks.server.ts": "import { env } from \"$env/dynamic/private\";\nimport { handlePocketbase } from \"@velastack/pocketbase\";\n\nexport const handle = handlePocketbase({\n pocketbaseUrl: env.POCKETBASE_URL,\n superuserEmail: env.POCKETBASE_SUPERUSER_EMAIL,\n superuserPassword: env.POCKETBASE_SUPERUSER_PASSWORD,\n // [!code highlight:1]\n auth: { protectedRoutes: [\"/(app)\"] },\n});\n",
3802
+ "./preview-modifies/src/lib/components/ui/sidebar/sidebar-menu-button.svelte": "<script lang=\"ts\" module>\n import { tv, type VariantProps } from 'tailwind-variants';\n\n export const sidebarMenuButtonVariants = tv({\n base: 'ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground active:bg-sidebar-accent active:text-sidebar-accent-foreground data-active:bg-sidebar-accent data-active:text-sidebar-accent-foreground data-open:hover:bg-sidebar-accent data-open:hover:text-sidebar-accent-foreground gap-2 rounded-md p-2 text-left text-sm transition-[width,height,padding] group-has-data-[sidebar=menu-action]/menu-item:pr-8 group-data-[collapsible=icon]:size-8! group-data-[collapsible=icon]:p-2! focus-visible:ring-2 data-active:font-medium peer/menu-button group/menu-button flex w-full items-center overflow-hidden outline-hidden disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 [&_svg]:size-4 [&_svg]:shrink-0 [&>span:last-child]:truncate',\n variants: {\n variant: {\n default: 'hover:bg-sidebar-accent hover:text-sidebar-accent-foreground',\n outline:\n 'bg-background hover:bg-sidebar-accent hover:text-sidebar-accent-foreground shadow-[0_0_0_1px_hsl(var(--sidebar-border))] hover:shadow-[0_0_0_1px_hsl(var(--sidebar-accent))]'\n },\n size: {\n default: 'h-8 text-sm',\n sm: 'h-7 text-xs',\n lg: 'h-12 text-sm group-data-[collapsible=icon]:p-0!'\n }\n },\n defaultVariants: {\n variant: 'default',\n size: 'default'\n }\n });\n\n export type SidebarMenuButtonVariant = VariantProps<typeof sidebarMenuButtonVariants>['variant'];\n export type SidebarMenuButtonSize = VariantProps<typeof sidebarMenuButtonVariants>['size'];\n<\/script>\n\n<script lang=\"ts\">\n import * as Tooltip from '$lib/components/ui/tooltip/index.js';\n import { cn, type WithElementRef, type WithoutChildrenOrChild } from '$lib/utils.js';\n import { mergeProps } from 'bits-ui';\n import type { ComponentProps, Snippet } from 'svelte';\n import type { HTMLAttributes } from 'svelte/elements';\n import { useSidebar } from './context.svelte.js';\n\n let {\n ref = $bindable(null),\n class: className,\n children,\n child,\n variant = 'default',\n size = 'default',\n isActive = false,\n tooltipContent,\n tooltipContentProps,\n ...restProps\n }: WithElementRef<HTMLAttributes<HTMLButtonElement>, HTMLButtonElement> & {\n isActive?: boolean;\n variant?: SidebarMenuButtonVariant;\n size?: SidebarMenuButtonSize;\n tooltipContent?: Snippet | string;\n tooltipContentProps?: WithoutChildrenOrChild<ComponentProps<typeof Tooltip.Content>>;\n child?: Snippet<[{ props: Record<string, unknown> }]>;\n } = $props();\n\n const sidebar = useSidebar();\n\n const buttonProps = $derived({\n class: cn(sidebarMenuButtonVariants({ variant, size }), className),\n 'data-slot': 'sidebar-menu-button',\n 'data-sidebar': 'menu-button',\n 'data-size': size,\n 'data-active': isActive ? true : undefined,\n ...restProps\n });\n<\/script>\n\n{#snippet Button({ props }: { props?: Record<string, unknown> })}\n {@const mergedProps = mergeProps(buttonProps, props)}\n {#if child}\n {@render child({ props: mergedProps })}\n {:else}\n <button bind:this={ref} {...mergedProps}>\n {@render children?.()}\n </button>\n {/if}\n{/snippet}\n\n{#if !tooltipContent}\n {@render Button({})}\n{:else}\n <Tooltip.Root>\n <Tooltip.Trigger>\n {#snippet child({ props })}\n {@render Button({ props })}\n {/snippet}\n </Tooltip.Trigger>\n <Tooltip.Content\n side=\"right\"\n align=\"center\"\n hidden={sidebar.state !== 'collapsed' || sidebar.isMobile}\n {...tooltipContentProps}\n >\n {#if typeof tooltipContent === 'string'}\n {tooltipContent}\n {:else if tooltipContent}\n {@render tooltipContent()}\n {/if}\n </Tooltip.Content>\n </Tooltip.Root>\n{/if}\n",
3784
3803
  "./preview-modifies/src/routes/(public)/root-layout.svelte": "<script lang=\"ts\">\n import { toggleMode } from \"mode-watcher\";\n import * as Navbar from \"$lib/components/ui/navbar\";\n import { Button } from \"$lib/components/ui/button\";\n // [!code highlight:2]\n import * as AuthMenu from \"$lib/components/ui/auth-menu\";\n import * as Avatar from \"$lib/components/ui/avatar\";\n\n let { children, data } = $props();\n<\/script>\n\n<div class=\"min-h-dvh grid grid-rows-[max-content_1fr_max-content] root-layout\">\n <Navbar.Root>\n <Navbar.Brand href=\"/\">\n <Navbar.Logo src=\"/favicon.svg\" alt=\"Logo\" />\n </Navbar.Brand>\n\n <Navbar.MobileToggle />\n\n <Navbar.List>\n <Navbar.Item>\n <Button\n class=\"w-full justify-start md:justify-center md:w-auto\"\n href=\"/\"\n variant=\"ghost\"\n >\n Home\n </Button>\n </Navbar.Item>\n\n <!-- [!code highlight:44] -->\n <Navbar.Item\n class=\"flex flex-col md:flex-row items-center space-y-2 md:space-y-0 md:space-x-4\"\n >\n <AuthMenu.Root>\n {#snippet user()}\n <AuthMenu.Trigger>\n <Avatar.Root>\n {#if data.user?.avatar}\n <Avatar.Image\n src=\"/api/files/users/{data.user?.id}/{data.user?.avatar}\"\n alt={data.user?.email}\n />\n {/if}\n <Avatar.Fallback>\n {data.user?.email?.charAt(0).toUpperCase()}\n </Avatar.Fallback>\n </Avatar.Root>\n </AuthMenu.Trigger>\n <AuthMenu.Content align=\"end\">\n <AuthMenu.Item href=\"/dashboard\">Dashboard</AuthMenu.Item>\n <AuthMenu.Group>\n <AuthMenu.Item href=\"/settings\">Settings</AuthMenu.Item>\n <AuthMenu.Item>\n <form action=\"/logout\" method=\"post\">\n <button type=\"submit\" class=\"contents\">Logout</button>\n </form>\n </AuthMenu.Item>\n </AuthMenu.Group>\n </AuthMenu.Content>\n {/snippet}\n {#snippet guest()}\n <Button\n class=\"w-full justify-start md:justify-center md:w-auto\"\n variant=\"ghost\"\n href=\"/login\">Login</Button\n >\n <Button\n class=\"w-full justify-start md:justify-center md:w-auto\"\n variant=\"outline\"\n href=\"/signup\">Sign up</Button\n >\n {/snippet}\n </AuthMenu.Root>\n </Navbar.Item>\n </Navbar.List>\n </Navbar.Root>\n\n {@render children?.()}\n\n <footer class=\"border-t border-border py-4\">\n <div\n class=\"mx-auto flex max-w-7xl px-4 flex-col items-center justify-between gap-3 sm:flex-row\"\n >\n <p class=\"text-muted-foreground text-sm\">\n &copy; {new Date().getFullYear()}\n {data.meta.appName}. All rights reserved.\n </p>\n <nav class=\"flex items-center gap-4 text-sm\">\n <Button onclick={toggleMode} variant=\"ghost\" size=\"icon\">\n <Navbar.Mode />\n </Button>\n <a href=\"/privacy\" class=\"underline-offset-4 hover:underline\">Privacy</a\n >\n <a href=\"/terms\" class=\"underline-offset-4 hover:underline\">Terms</a>\n </nav>\n </div>\n </footer>\n</div>\n\n<style lang=\"postcss\">\n @reference \"tailwindcss\";\n\n .root-layout :global(section[data-role=\"content\"]) {\n @apply container mx-auto max-w-7xl px-4 py-8 w-full;\n }\n</style>\n",
3785
3804
  "./preview-modifies/src/routes/+layout.server.ts": "import { loadFlash } from \"sveltekit-flash-message/server\";\n\nexport const load = loadFlash(async ({ locals }) => {\n return {\n // [!code highlight:1]\n user: locals.pb.authStore.record,\n };\n});\n"
3786
3805
  }), xa = "./preview-modifies/";
@@ -3806,11 +3825,11 @@ async function Sa(e) {
3806
3825
  }
3807
3826
  //#endregion
3808
3827
  //#region src/patterns/enable/auth/index.ts
3809
- var Ca = "enable-auth", wa = "1.0.7", Ta = "src/patterns/enable/auth", Ea = "/enable/auth";
3828
+ var Ca = "enable-auth", wa = "1.0.8", Ta = "src/patterns/enable/auth", Ea = "/enable/auth";
3810
3829
  async function Da(e) {
3811
3830
  let t = await ya(e);
3812
3831
  if (e.env === "preview") return y(n([t, await Sa(e)]));
3813
- let { generate: r } = await import("./chunks/generate.runtime-yNwWcppO.js"), i = await r(e), { writeResult: a } = await import("./chunks/write-result-DJ32RMq5.js");
3832
+ let { generate: r } = await import("./chunks/generate.runtime-BPsBAuGR.js"), i = await r(e), { writeResult: a } = await import("./chunks/write-result-BPDot58Z.js");
3814
3833
  return a(await y(n([t, i])), e);
3815
3834
  }
3816
3835
  var Oa = {
@@ -3846,7 +3865,7 @@ var Oa = {
3846
3865
  argv: []
3847
3866
  },
3848
3867
  examples: [],
3849
- tests: 18,
3868
+ tests: 21,
3850
3869
  baseline: "velastack",
3851
3870
  variants: ["split"],
3852
3871
  generate: Da
@@ -4003,7 +4022,7 @@ async function No(e) {
4003
4022
  //#endregion
4004
4023
  //#region src/patterns/enable/auth-remote/generate.preview.ts
4005
4024
  var Po = /* @__PURE__ */ Object.assign({
4006
- "./preview-modifies/src/hooks.server.ts": "import {\n POCKETBASE_URL,\n POCKETBASE_SUPERUSER_EMAIL,\n POCKETBASE_SUPERUSER_PASSWORD,\n} from \"$env/static/private\";\nimport { handlePocketbase } from \"@velastack/pocketbase\";\n\nexport const handle = handlePocketbase({\n pocketbaseUrl: POCKETBASE_URL,\n superuserEmail: POCKETBASE_SUPERUSER_EMAIL,\n superuserPassword: POCKETBASE_SUPERUSER_PASSWORD,\n // [!code highlight:1]\n auth: { protectedRoutes: [\"/(app)\"] },\n});\n",
4025
+ "./preview-modifies/src/hooks.server.ts": "import { env } from \"$env/dynamic/private\";\nimport { handlePocketbase } from \"@velastack/pocketbase\";\n\nexport const handle = handlePocketbase({\n pocketbaseUrl: env.POCKETBASE_URL,\n superuserEmail: env.POCKETBASE_SUPERUSER_EMAIL,\n superuserPassword: env.POCKETBASE_SUPERUSER_PASSWORD,\n // [!code highlight:1]\n auth: { protectedRoutes: [\"/(app)\"] },\n});\n",
4007
4026
  "./preview-modifies/src/routes/(public)/root-layout.svelte": "<script lang=\"ts\">\n import { toggleMode } from \"mode-watcher\";\n import * as Navbar from \"$lib/components/ui/navbar\";\n import { Button } from \"$lib/components/ui/button\";\n // [!code highlight:2]\n import * as AuthMenu from \"$lib/components/ui/auth-menu\";\n import * as Avatar from \"$lib/components/ui/avatar\";\n\n let { children, data } = $props();\n<\/script>\n\n<div class=\"min-h-dvh grid grid-rows-[max-content_1fr_max-content] root-layout\">\n <Navbar.Root>\n <Navbar.Brand href=\"/\">\n <Navbar.Logo src=\"/favicon.svg\" alt=\"Logo\" />\n </Navbar.Brand>\n\n <Navbar.MobileToggle />\n\n <Navbar.List>\n <Navbar.Item>\n <Button\n class=\"w-full justify-start md:justify-center md:w-auto\"\n href=\"/\"\n variant=\"ghost\"\n >\n Home\n </Button>\n </Navbar.Item>\n\n <!-- [!code highlight:44] -->\n <Navbar.Item\n class=\"flex flex-col md:flex-row items-center space-y-2 md:space-y-0 md:space-x-4\"\n >\n <AuthMenu.Root>\n {#snippet user()}\n <AuthMenu.Trigger>\n <Avatar.Root>\n {#if data.user?.avatar}\n <Avatar.Image\n src=\"/api/files/users/{data.user?.id}/{data.user?.avatar}\"\n alt={data.user?.email}\n />\n {/if}\n <Avatar.Fallback>\n {data.user?.email?.charAt(0).toUpperCase()}\n </Avatar.Fallback>\n </Avatar.Root>\n </AuthMenu.Trigger>\n <AuthMenu.Content align=\"end\">\n <AuthMenu.Item href=\"/dashboard\">Dashboard</AuthMenu.Item>\n <AuthMenu.Group>\n <AuthMenu.Item href=\"/settings\">Settings</AuthMenu.Item>\n <AuthMenu.Item>\n <form action=\"/logout\" method=\"post\">\n <button type=\"submit\" class=\"contents\">Logout</button>\n </form>\n </AuthMenu.Item>\n </AuthMenu.Group>\n </AuthMenu.Content>\n {/snippet}\n {#snippet guest()}\n <Button\n class=\"w-full justify-start md:justify-center md:w-auto\"\n variant=\"ghost\"\n href=\"/login\">Login</Button\n >\n <Button\n class=\"w-full justify-start md:justify-center md:w-auto\"\n variant=\"outline\"\n href=\"/signup\">Sign up</Button\n >\n {/snippet}\n </AuthMenu.Root>\n </Navbar.Item>\n </Navbar.List>\n </Navbar.Root>\n\n {@render children?.()}\n\n <footer class=\"border-t border-border py-4\">\n <div\n class=\"mx-auto flex max-w-7xl px-4 flex-col items-center justify-between gap-3 sm:flex-row\"\n >\n <p class=\"text-muted-foreground text-sm\">\n &copy; {new Date().getFullYear()}\n {data.meta.appName}. All rights reserved.\n </p>\n <nav class=\"flex items-center gap-4 text-sm\">\n <Button onclick={toggleMode} variant=\"ghost\" size=\"icon\">\n <Navbar.Mode />\n </Button>\n <a href=\"/privacy\" class=\"underline-offset-4 hover:underline\">Privacy</a\n >\n <a href=\"/terms\" class=\"underline-offset-4 hover:underline\">Terms</a>\n </nav>\n </div>\n </footer>\n</div>\n\n<style lang=\"postcss\">\n @reference \"tailwindcss\";\n\n .root-layout :global(section[data-role=\"content\"]) {\n @apply container mx-auto max-w-7xl px-4 py-8 w-full;\n }\n</style>\n",
4008
4027
  "./preview-modifies/src/routes/+layout.server.ts": "import { loadFlash } from \"sveltekit-flash-message/server\";\n\nexport const load = loadFlash(async ({ locals }) => {\n return {\n // [!code highlight:1]\n user: locals.pb.authStore.record,\n };\n});\n",
4009
4028
  "./preview-modifies/svelte.config.js": "import adapter from \"@sveltejs/adapter-auto\";\nimport { vitePreprocess } from \"@sveltejs/vite-plugin-svelte\";\n\n/** @type {import('@sveltejs/kit').Config} */\nconst config = {\n preprocess: vitePreprocess(),\n kit: {\n adapter,\n // [!code highlight:3]\n experimental: {\n remoteFunctions: true,\n },\n },\n // [!code highlight:5]\n compilerOptions: {\n experimental: {\n async: true,\n },\n },\n};\n\nexport default config;\n"
@@ -4034,7 +4053,7 @@ var Lo = "enable-auth-remote", Ro = "1.0.0", zo = "src/patterns/enable/auth-remo
4034
4053
  async function Vo(e) {
4035
4054
  let t = await No(e);
4036
4055
  if (e.env === "preview") return y(n([t, await Io(e)]));
4037
- let { generate: r } = await import("./chunks/generate.runtime-D24qi85n.js"), i = await r(e), { writeResult: a } = await import("./chunks/write-result-DJ32RMq5.js");
4056
+ let { generate: r } = await import("./chunks/generate.runtime-D24qi85n.js"), i = await r(e), { writeResult: a } = await import("./chunks/write-result-BPDot58Z.js");
4038
4057
  return a(await y(n([t, i])), e);
4039
4058
  }
4040
4059
  var Ho = {
@@ -4097,7 +4116,7 @@ async function Ko(e) {
4097
4116
  }
4098
4117
  //#endregion
4099
4118
  //#region src/patterns/enable/api/generate.preview.ts
4100
- var qo = /* @__PURE__ */ Object.assign({ "./preview-modifies/src/hooks.server.ts": "import {\n POCKETBASE_URL,\n POCKETBASE_SUPERUSER_EMAIL,\n POCKETBASE_SUPERUSER_PASSWORD,\n} from \"$env/static/private\";\nimport { handlePocketbase } from \"@velastack/pocketbase\";\n\nexport const handle = handlePocketbase({\n pocketbaseUrl: POCKETBASE_URL,\n superuserEmail: POCKETBASE_SUPERUSER_EMAIL,\n superuserPassword: POCKETBASE_SUPERUSER_PASSWORD,\n // [!code highlight:1]\n api: { enabled: true },\n});\n" }), Jo = "./preview-modifies/";
4119
+ var qo = /* @__PURE__ */ Object.assign({ "./preview-modifies/src/hooks.server.ts": "import { env } from \"$env/dynamic/private\";\nimport { handlePocketbase } from \"@velastack/pocketbase\";\n\nexport const handle = handlePocketbase({\n pocketbaseUrl: env.POCKETBASE_URL,\n superuserEmail: env.POCKETBASE_SUPERUSER_EMAIL,\n superuserPassword: env.POCKETBASE_SUPERUSER_PASSWORD,\n // [!code highlight:1]\n api: { enabled: true },\n});\n" }), Jo = "./preview-modifies/";
4101
4120
  async function Yo(e) {
4102
4121
  return {
4103
4122
  creates: [],
@@ -4124,7 +4143,7 @@ var Xo = "enable-api", Zo = "1.0.7", Qo = "src/patterns/enable/api", $o = "/enab
4124
4143
  async function es(e) {
4125
4144
  let t = await Ko(e);
4126
4145
  if (e.env === "preview") return y(n([t, await Yo(e)]));
4127
- let { generate: r } = await import("./chunks/generate.runtime-CPVMJTKB.js"), i = await r(e), { writeResult: a } = await import("./chunks/write-result-DJ32RMq5.js");
4146
+ let { generate: r } = await import("./chunks/generate.runtime-CPVMJTKB.js"), i = await r(e), { writeResult: a } = await import("./chunks/write-result-BPDot58Z.js");
4128
4147
  return a(await y(n([t, i])), e);
4129
4148
  }
4130
4149
  var ts = {
@@ -4245,7 +4264,7 @@ async function gs(e) {
4245
4264
  //#endregion
4246
4265
  //#region src/patterns/enable/api-keys/generate.preview.ts
4247
4266
  var _s = /* @__PURE__ */ Object.assign({
4248
- "./preview-modifies/src/hooks.server.ts": "import {\n POCKETBASE_URL,\n POCKETBASE_SUPERUSER_EMAIL,\n POCKETBASE_SUPERUSER_PASSWORD,\n} from \"$env/static/private\";\nimport { handlePocketbase } from \"@velastack/pocketbase\";\n\nexport const handle = handlePocketbase({\n pocketbaseUrl: POCKETBASE_URL,\n superuserEmail: POCKETBASE_SUPERUSER_EMAIL,\n superuserPassword: POCKETBASE_SUPERUSER_PASSWORD,\n api: {\n enabled: true,\n // [!code highlight:1]\n apiKeys: { enabled: true },\n },\n});\n",
4267
+ "./preview-modifies/src/hooks.server.ts": "import { env } from \"$env/dynamic/private\";\nimport { handlePocketbase } from \"@velastack/pocketbase\";\n\nexport const handle = handlePocketbase({\n pocketbaseUrl: env.POCKETBASE_URL,\n superuserEmail: env.POCKETBASE_SUPERUSER_EMAIL,\n superuserPassword: env.POCKETBASE_SUPERUSER_PASSWORD,\n api: {\n enabled: true,\n // [!code highlight:1]\n apiKeys: { enabled: true },\n },\n});\n",
4249
4268
  "./preview-modifies/src/lib/utils.ts": "import { clsx, type ClassValue } from \"clsx\";\nimport { twMerge } from \"tailwind-merge\";\n\nexport function cn(...inputs: ClassValue[]) {\n return twMerge(clsx(inputs));\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type WithoutChild<T> = T extends { child?: any } ? Omit<T, \"child\"> : T;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type WithoutChildren<T> = T extends { children?: any }\n ? Omit<T, \"children\">\n : T;\nexport type WithoutChildrenOrChild<T> = WithoutChildren<WithoutChild<T>>;\nexport type WithElementRef<T, U extends HTMLElement = HTMLElement> = T & {\n ref?: U | null;\n};\n\n// [!code highlight:9]\nconst TIME_AGO_UNITS: [Intl.RelativeTimeFormatUnit, number][] = [\n [\"year\", 60 * 60 * 24 * 365],\n [\"month\", 60 * 60 * 24 * 30],\n [\"day\", 60 * 60 * 24],\n [\"hour\", 60 * 60],\n [\"minute\", 60],\n [\"second\", 1],\n];\n\n// [!code highlight:10]\nexport function timeAgo(date: Date | string | number, locale?: string) {\n const rtf = new Intl.RelativeTimeFormat(locale, { numeric: \"auto\" });\n const diff = (new Date(date).getTime() - Date.now()) / 1000;\n\n for (const [unit, secs] of TIME_AGO_UNITS) {\n if (Math.abs(diff) >= secs || unit === \"second\") {\n return rtf.format(Math.round(diff / secs), unit);\n }\n }\n}\n"
4250
4269
  }), vs = "./preview-modifies/";
4251
4270
  async function ys(e) {
@@ -4274,7 +4293,7 @@ var bs = "enable-api-keys", xs = "1.0.0", Ss = "src/patterns/enable/api-keys", C
4274
4293
  async function ws(e) {
4275
4294
  let t = await gs(e);
4276
4295
  if (e.env === "preview") return y(n([t, await ys(e)]));
4277
- let { createCollections: r } = await import("./chunks/collections-rD0M_Wxo.js"), i = await r(t.collections, e), { generate: a } = await import("./chunks/generate.runtime-4WWju7dJ.js"), o = await a(e), { writeResult: s } = await import("./chunks/write-result-DJ32RMq5.js");
4296
+ let { createCollections: r } = await import("./chunks/collections-rD0M_Wxo.js"), i = await r(t.collections, e), { generate: a } = await import("./chunks/generate.runtime-4WWju7dJ.js"), o = await a(e), { writeResult: s } = await import("./chunks/write-result-BPDot58Z.js");
4278
4297
  return s(await y(n([{
4279
4298
  ...t,
4280
4299
  creates: [...t.creates, ...i]
@@ -4408,7 +4427,7 @@ var rc = "enable-blog", ic = "1.0.0", ac = "src/patterns/enable/blog", oc = "/en
4408
4427
  async function sc(e) {
4409
4428
  let t = await $s(e);
4410
4429
  if (e.env === "preview") return y(n([t, await nc(e)]));
4411
- let { generate: r } = await import("./chunks/generate.runtime-C7ZDF3hy.js"), i = await r(e), { writeResult: a } = await import("./chunks/write-result-DJ32RMq5.js");
4430
+ let { generate: r } = await import("./chunks/generate.runtime-C7ZDF3hy.js"), i = await r(e), { writeResult: a } = await import("./chunks/write-result-BPDot58Z.js");
4412
4431
  return a(await y(n([t, i])), e);
4413
4432
  }
4414
4433
  var cc = {
@@ -4486,7 +4505,7 @@ async function yc(e) {
4486
4505
  //#endregion
4487
4506
  //#region src/patterns/enable/content-negotiation/generate.preview.ts
4488
4507
  var bc = /* @__PURE__ */ Object.assign({
4489
- "./preview-modifies/src/hooks.server.ts": "import {\n POCKETBASE_URL,\n POCKETBASE_SUPERUSER_EMAIL,\n POCKETBASE_SUPERUSER_PASSWORD,\n} from \"$env/static/private\";\nimport { sequence } from \"@sveltejs/kit/hooks\";\nimport { handlePocketbase } from \"@velastack/pocketbase\";\n// [!code highlight:1]\nimport { handle as handleNegotiate } from \"$lib/negotiate\";\n\nexport const handle = sequence(\n // [!code highlight:1]\n handleNegotiate,\n handlePocketbase({\n pocketbaseUrl: POCKETBASE_URL,\n superuserEmail: POCKETBASE_SUPERUSER_EMAIL,\n superuserPassword: POCKETBASE_SUPERUSER_PASSWORD,\n }),\n);\n",
4508
+ "./preview-modifies/src/hooks.server.ts": "import { env } from \"$env/dynamic/private\";\nimport { sequence } from \"@sveltejs/kit/hooks\";\nimport { handlePocketbase } from \"@velastack/pocketbase\";\n// [!code highlight:1]\nimport { handle as handleNegotiate } from \"$lib/negotiate\";\n\nexport const handle = sequence(\n // [!code highlight:1]\n handleNegotiate,\n handlePocketbase({\n pocketbaseUrl: env.POCKETBASE_URL,\n superuserEmail: env.POCKETBASE_SUPERUSER_EMAIL,\n superuserPassword: env.POCKETBASE_SUPERUSER_PASSWORD,\n }),\n);\n",
4490
4509
  "./preview-modifies/src/hooks.ts": "import { reroute as negotiateReroute } from \"$lib/negotiate\";\n\nexport const reroute = ({ url }) => negotiateReroute(url.pathname);\n"
4491
4510
  }), xc = "./preview-modifies/";
4492
4511
  async function Sc(e) {
@@ -4515,7 +4534,7 @@ var Cc = "enable-content-negotiation", wc = "1.0.0", Tc = "src/patterns/enable/c
4515
4534
  async function Dc(e) {
4516
4535
  let t = await yc(e);
4517
4536
  if (e.env === "preview") return y(n([t, await Sc(e)]));
4518
- let { generate: r } = await import("./chunks/generate.runtime-BVPDsGmt.js"), i = await r(e), { writeResult: a } = await import("./chunks/write-result-DJ32RMq5.js");
4537
+ let { generate: r } = await import("./chunks/generate.runtime-BVPDsGmt.js"), i = await r(e), { writeResult: a } = await import("./chunks/write-result-BPDot58Z.js");
4519
4538
  return a(await y(n([t, i])), e);
4520
4539
  }
4521
4540
  var Oc = {
@@ -4615,7 +4634,7 @@ var zc = "enable-i18n", Bc = "1.0.0", Vc = "src/patterns/enable/i18n", Hc = "/en
4615
4634
  async function Uc(e) {
4616
4635
  let t = await Fc(e);
4617
4636
  if (e.env === "preview") return y(n([t, await Rc(e)]));
4618
- let { generate: r } = await import("./chunks/generate.runtime-D_8Nz9Kl.js"), i = await r(e), { writeResult: a } = await import("./chunks/write-result-DJ32RMq5.js");
4637
+ let { generate: r } = await import("./chunks/generate.runtime-D_8Nz9Kl.js"), i = await r(e), { writeResult: a } = await import("./chunks/write-result-BPDot58Z.js");
4619
4638
  return a(await y(n([t, i])), e);
4620
4639
  }
4621
4640
  var Wc = {
@@ -4653,7 +4672,7 @@ var Wc = {
4653
4672
  tests: 0,
4654
4673
  baseline: "velastack",
4655
4674
  generate: Uc
4656
- }, Gc = "/// <reference path=\"../types.d.ts\" />\n\ncronAdd(\"stripe-products\", \"*/2 * * * *\", () => {\n const utils = require(`${__hooks}/utils.js`);\n utils.triggerJob(\"/api/stripe/sync/products\");\n});\n\ncronAdd(\"stripe-prices\", \"*/2 * * * *\", () => {\n const utils = require(`${__hooks}/utils.js`);\n utils.triggerJob(\"/api/stripe/sync/prices\");\n});\n", Kc = "/// <reference path=\"../types.d.ts\" />\n\nmodule.exports = {\n triggerJob: (jobUrl) => {\n $http.send({\n method: \"POST\",\n url: `${$app.settings().meta.appURL}${jobUrl}`,\n headers: {\n Authorization: `Bearer ${$os.getenv(\"INTERNAL_JOB_SECRET\")}`,\n },\n });\n },\n};\n", qc = "<script lang=\"ts\">\n import type { Stripe } from '@stripe/stripe-js';\n import { Button } from '$lib/components/ui/button';\n import * as Dialog from '$lib/components/ui/dialog';\n import { toast } from 'svelte-sonner';\n import { page } from '$app/state';\n import { invalidate } from '$app/navigation';\n\n interface Props {\n stripe: Stripe | null;\n open: boolean;\n amount: number;\n currency: string;\n brand?: string;\n last4?: string;\n clientSecret?: string;\n onopenchange: (open: boolean) => void;\n onsuccess: () => void;\n }\n\n let {\n stripe,\n open = $bindable(),\n amount,\n currency,\n brand,\n last4,\n clientSecret,\n onopenchange,\n onsuccess\n }: Props = $props();\n\n const brandNames = {\n amex: 'American Express',\n cartes_bancaires: 'Cartes Bancaires',\n diners: 'Diners',\n discover: 'Discover',\n eftpos_au: 'Eftpos Au',\n jcb: 'Jcb',\n link: 'Link',\n mastercard: 'Mastercard',\n unionpay: 'Unionpay',\n visa: 'Visa',\n unknown: 'Unknown'\n };\n\n let isProcessing = $state(false);\n\n let amountFormatted = $derived.by(() => {\n let formatter = new Intl.NumberFormat('en-US', { style: 'currency', currency: currency });\n return formatter.format(amount / 100);\n });\n\n const handleOpenChangeComplete = (isOpen: boolean) => {\n if (!isOpen) {\n resetDialog();\n }\n onopenchange(isOpen);\n };\n\n function resetDialog() {\n open = false;\n isProcessing = false;\n }\n\n async function handlePaymentMethod() {\n if (!stripe || !clientSecret) return;\n\n isProcessing = true;\n\n try {\n const { error: confirmError } = await stripe.confirmPayment({\n clientSecret,\n confirmParams: {\n return_url: page.url.toString()\n },\n redirect: 'if_required'\n });\n\n if (confirmError) {\n toast.error(confirmError.message || 'Failed to pay for your purchase');\n return;\n }\n\n await invalidate('app:billing');\n toast.success('Payment successful');\n onsuccess();\n resetDialog();\n } catch (err) {\n console.error('Error paying for your purchase:', err);\n toast.error('Failed to pay for your purchase');\n } finally {\n isProcessing = false;\n }\n }\n<\/script>\n\n<Dialog.Root bind:open onOpenChangeComplete={handleOpenChangeComplete}>\n <Dialog.Content class=\"sm:max-w-[500px]\">\n <Dialog.Header>\n <Dialog.Title>Confirm payment</Dialog.Title>\n <Dialog.Description>\n Are you sure you want to pay {amountFormatted} with your\n {brandNames[brand as keyof typeof brandNames]}\n credit card ending in **** {last4}?\n </Dialog.Description>\n </Dialog.Header>\n <Dialog.Footer>\n <Button variant=\"outline\" onclick={resetDialog} disabled={isProcessing}>Cancel</Button>\n <Button onclick={handlePaymentMethod} disabled={isProcessing}>\n {isProcessing ? 'Processing...' : 'Pay Now'}\n </Button>\n </Dialog.Footer>\n </Dialog.Content>\n</Dialog.Root>\n", Jc = "<script lang=\"ts\">\n import { Button } from '$lib/components/ui/button';\n import PaymentDialog from '$lib/components/payments/payment-dialog.svelte';\n import ConfirmDialog from '$lib/components/payments/confirm-dialog.svelte';\n import { useStripe } from '$lib/components/payments/use-stripe.svelte';\n import { usePaymentIntent } from '$lib/components/payments/use-payment-intent.svelte';\n import type { ButtonProps } from '$lib/components/ui/button';\n\n interface Props {\n priceId: string;\n user?: { email: string; name: string } | null;\n disabled?: boolean;\n isProcessing?: boolean;\n label?: string;\n processingLabel?: string;\n onsuccess?: () => void;\n }\n\n let {\n priceId,\n user,\n disabled = false,\n isProcessing = false,\n label = 'Purchase',\n processingLabel = 'Processing...',\n onsuccess,\n ...rest\n }: Props & ButtonProps = $props();\n\n const stripeManager = useStripe();\n const paymentIntentManager = usePaymentIntent();\n\n let mode = $state<'payment' | 'confirm'>('payment');\n let showDialog = $state(false);\n let amount = $state<number>(0);\n let currency = $state<string>('usd');\n let clientSecret = $state<string>();\n let brand = $state<string>();\n let last4 = $state<string>();\n\n async function handleBuyClick() {\n const result = await paymentIntentManager.fetchPaymentIntent({\n priceId\n });\n\n if (!result) return;\n\n if (result.type === 'confirm') {\n mode = 'confirm';\n brand = result.brand;\n last4 = result.last4;\n } else if (result.type === 'payment') {\n mode = 'payment';\n }\n\n amount = result.amount || 0;\n currency = result.currency || 'usd';\n clientSecret = result.clientSecret;\n showDialog = true;\n }\n\n function handleDialogOpenChange(open: boolean) {\n showDialog = open;\n }\n\n function handlePaymentSuccess() {\n onsuccess?.();\n }\n<\/script>\n\n<Button disabled={disabled || isProcessing} onclick={handleBuyClick} {...rest}>\n {#if isProcessing}\n {processingLabel}\n {:else}\n {label}\n {/if}\n</Button>\n\n{#if mode === 'confirm'}\n <ConfirmDialog\n bind:open={showDialog}\n stripe={stripeManager.stripe}\n {amount}\n {currency}\n {brand}\n {last4}\n {clientSecret}\n onopenchange={handleDialogOpenChange}\n onsuccess={handlePaymentSuccess}\n />\n{:else if mode === 'payment'}\n <PaymentDialog\n bind:open={showDialog}\n stripe={stripeManager.stripe}\n {amount}\n {currency}\n {clientSecret}\n {user}\n onopenchange={handleDialogOpenChange}\n onsuccess={handlePaymentSuccess}\n />\n{/if}\n", Yc = "<script lang=\"ts\">\n import type { Stripe, StripeElements } from '@stripe/stripe-js';\n import { Button } from '$lib/components/ui/button';\n import * as Dialog from '$lib/components/ui/dialog';\n import { Input } from '$lib/components/ui/input';\n import { Label } from '$lib/components/ui/label';\n import { toast } from 'svelte-sonner';\n import { page } from '$app/state';\n import { invalidate } from '$app/navigation';\n import StripePaymentForm from './stripe-payment-form.svelte';\n\n interface Props {\n stripe: Stripe | null;\n open: boolean;\n amount: number;\n currency: string;\n clientSecret?: string;\n user?: { email: string; name: string } | null;\n onopenchange: (open: boolean) => void;\n onsuccess: () => void;\n }\n\n let {\n stripe,\n open = $bindable(),\n amount,\n currency,\n clientSecret,\n user = null,\n onopenchange,\n onsuccess\n }: Props = $props();\n\n let isProcessing = $state(false);\n let cardComplete = $state(false);\n let savePaymentMethod = $state(false);\n let email = $state<string>();\n let formRef = $state<{\n getElements: () => StripeElements | null;\n }>();\n\n let amountFormatted = $derived.by(() => {\n let formatter = new Intl.NumberFormat('en-US', { style: 'currency', currency: currency });\n return formatter.format(amount / 100);\n });\n\n const handleOpenChangeComplete = (isOpen: boolean) => {\n if (!isOpen) {\n resetDialog();\n }\n onopenchange(isOpen);\n };\n\n function resetDialog() {\n open = false;\n isProcessing = false;\n cardComplete = false;\n }\n\n function handleCardChange(complete: boolean) {\n cardComplete = complete;\n }\n\n async function handlePaymentMethod() {\n if (!stripe || !formRef || !cardComplete || !clientSecret) return;\n\n const elements = formRef.getElements();\n if (!elements) return;\n\n isProcessing = true;\n\n try {\n const { error: submitError } = await elements.submit();\n if (submitError) {\n toast.error(submitError.message || 'Failed to pay for your purchase');\n return;\n }\n\n const { error: confirmError } = await stripe.confirmPayment({\n elements,\n clientSecret,\n confirmParams: {\n return_url: page.url.toString(),\n payment_method_data: {\n billing_details: {\n email: email || user?.email\n },\n allow_redisplay: savePaymentMethod ? 'always' : 'unspecified'\n }\n },\n redirect: 'if_required'\n });\n\n if (confirmError) {\n toast.error(confirmError.message || 'Failed to pay for your purchase');\n return;\n }\n\n await invalidate('app:billing');\n toast.success('Payment successful');\n onsuccess();\n resetDialog();\n } catch (err) {\n console.error('Error paying for your purchase:', err);\n toast.error('Failed to pay for your purchase');\n } finally {\n isProcessing = false;\n }\n }\n<\/script>\n\n<Dialog.Root bind:open onOpenChangeComplete={handleOpenChangeComplete}>\n <Dialog.Content class=\"sm:max-w-[500px]\">\n <Dialog.Header>\n <Dialog.Title>{amountFormatted}</Dialog.Title>\n <Dialog.Description>Enter your card details to pay for your purchase.</Dialog.Description>\n </Dialog.Header>\n {#if !user}\n <div class=\"space-y-2\">\n <Label for=\"email\">Email</Label>\n <Input type=\"email\" bind:value={email} />\n </div>\n {/if}\n <div>\n {#if stripe && open}\n <StripePaymentForm\n bind:this={formRef}\n mode=\"payment\"\n {stripe}\n {amount}\n {currency}\n {savePaymentMethod}\n {user}\n onchange={handleCardChange}\n />\n {/if}\n </div>\n {#if user}\n <div class=\"flex items-center gap-2\">\n <input type=\"checkbox\" id=\"savePaymentMethod\" bind:checked={savePaymentMethod} />\n <label for=\"savePaymentMethod\" class=\"text-sm text-muted-foreground\">\n Save payment method for future purchases\n </label>\n </div>\n {/if}\n <Dialog.Footer>\n <Button variant=\"outline\" onclick={resetDialog} disabled={isProcessing}>Cancel</Button>\n <Button onclick={handlePaymentMethod} disabled={!cardComplete || isProcessing}>\n {isProcessing ? 'Processing...' : 'Pay Now'}\n </Button>\n </Dialog.Footer>\n </Dialog.Content>\n</Dialog.Root>\n", Xc = "export const TERMS_AUTO = {\n applePay: \"auto\" as const,\n auBecsDebit: \"auto\" as const,\n bancontact: \"auto\" as const,\n card: \"auto\" as const,\n cashapp: \"auto\" as const,\n googlePay: \"auto\" as const,\n ideal: \"auto\" as const,\n paypal: \"auto\" as const,\n sepaDebit: \"auto\" as const,\n sofort: \"auto\" as const,\n usBankAccount: \"auto\" as const,\n};\n\nexport const TERMS_NEVER = {\n applePay: \"never\" as const,\n auBecsDebit: \"never\" as const,\n bancontact: \"never\" as const,\n card: \"never\" as const,\n cashapp: \"never\" as const,\n googlePay: \"never\" as const,\n ideal: \"never\" as const,\n paypal: \"never\" as const,\n sepaDebit: \"never\" as const,\n sofort: \"never\" as const,\n usBankAccount: \"never\" as const,\n};\n", Zc = "<script lang=\"ts\">\n import type {\n Stripe,\n StripeElements,\n StripePaymentElement,\n StripeElementsOptionsMode\n } from '@stripe/stripe-js';\n import { mode as modeWatcher } from 'mode-watcher';\n import { TERMS_AUTO, TERMS_NEVER } from './stripe-constants';\n import { onMount } from 'svelte';\n\n interface Props {\n stripe: Stripe;\n mode: 'payment' | 'setup';\n amount?: number;\n currency?: string;\n savePaymentMethod?: boolean;\n user?: { email: string; name: string } | null;\n onchange: (complete: boolean) => void;\n }\n\n let {\n stripe,\n mode,\n amount = 0,\n currency = 'usd',\n savePaymentMethod = false,\n user,\n onchange\n }: Props = $props();\n\n let cardContainer = $state<HTMLDivElement | null>(null);\n let elements = $state<StripeElements | null>(null);\n let paymentElement = $state<StripePaymentElement | null>(null);\n\n function initializeElements() {\n if (!stripe) return;\n\n // Clean up previous elements\n if (paymentElement) {\n paymentElement.destroy();\n paymentElement = null;\n }\n\n const appearance = {\n theme: modeWatcher.current === 'dark' ? ('night' as const) : ('stripe' as const),\n inputs: 'condensed' as const,\n labels: 'floating' as const\n };\n\n elements = stripe.elements({\n mode,\n appearance,\n currency,\n ...(mode === 'payment' && {\n amount: amount\n }),\n ...(user || mode === 'setup'\n ? {\n setupFutureUsage: 'off_session' as const\n }\n : {})\n } as StripeElementsOptionsMode);\n\n paymentElement = elements.create('payment', {\n layout: 'tabs',\n defaultValues: {\n billingDetails: {\n email: user?.email,\n name: user?.name\n }\n },\n terms: savePaymentMethod ? TERMS_AUTO : TERMS_NEVER\n });\n\n if (cardContainer && paymentElement) {\n paymentElement.mount(cardContainer);\n paymentElement.on('change', (event: any) => {\n onchange(event.complete);\n });\n }\n }\n\n // Initialize elements when component mounts\n onMount(() => {\n initializeElements();\n\n return () => {\n if (paymentElement) {\n paymentElement.destroy();\n }\n };\n });\n\n // Update terms when savePaymentMethod changes\n $effect(() => {\n if (paymentElement) {\n paymentElement.update({\n terms: savePaymentMethod ? TERMS_AUTO : TERMS_NEVER\n });\n }\n });\n\n export function getElements() {\n return elements;\n }\n<\/script>\n\n<div bind:this={cardContainer}></div>\n", Qc = "import { toast } from \"svelte-sonner\";\n\nexport interface PaymentIntentResult {\n type: \"payment\" | \"confirm\";\n amount?: number;\n currency?: string;\n clientSecret?: string;\n brand?: string;\n last4?: string;\n}\n\nexport function usePaymentIntent() {\n let isLoading = $state(false);\n\n async function fetchPaymentIntent({\n priceId,\n }: {\n priceId: string;\n }): Promise<PaymentIntentResult | null> {\n isLoading = true;\n\n const res = await fetch(\"/api/stripe/payment-intent\", {\n method: \"POST\",\n body: JSON.stringify({\n priceId: priceId,\n }),\n headers: {\n \"Content-Type\": \"application/json\",\n },\n });\n\n if (!res.ok) {\n toast.error(\"Failed to initialize payment\");\n return null;\n }\n\n return res.json();\n }\n\n async function fetchSetupIntent(): Promise<PaymentIntentResult | null> {\n isLoading = true;\n\n const res = await fetch(\"/api/stripe/setup-intent\", {\n method: \"POST\",\n });\n\n if (!res.ok) {\n toast.error(\"Failed to initialize setup\");\n return null;\n }\n\n return res.json();\n }\n\n return {\n get isLoading() {\n return isLoading;\n },\n fetchPaymentIntent,\n fetchSetupIntent,\n };\n}\n", $c = "import { loadStripe, type Stripe } from \"@stripe/stripe-js\";\nimport { toast } from \"svelte-sonner\";\nimport { PUBLIC_STRIPE_PUBLISHABLE_KEY } from \"$env/static/public\";\n\nexport function useStripe() {\n let stripe = $state<Stripe | null>(null);\n let isLoading = $state(true);\n let error = $state<string | null>(null);\n\n async function initialize() {\n try {\n stripe = await loadStripe(PUBLIC_STRIPE_PUBLISHABLE_KEY);\n isLoading = false;\n } catch (err) {\n console.error(\"Failed to load Stripe:\", err);\n error = \"Failed to initialize payment system\";\n toast.error(\"Failed to initialize payment system\");\n isLoading = false;\n }\n }\n\n // Auto-initialize\n initialize();\n\n return {\n get stripe() {\n return stripe;\n },\n get isLoading() {\n return isLoading;\n },\n get error() {\n return error;\n },\n };\n}\n", el = "import { STRIPE_SECRET_KEY } from \"$env/static/private\";\nimport Stripe from \"stripe\";\n\nconst stripe = new Stripe(STRIPE_SECRET_KEY, {\n apiVersion: \"2025-09-30.clover\",\n});\n\nexport default stripe;\n", tl = "import { json } from \"@sveltejs/kit\";\nimport stripe from \"$lib/stripe\";\nimport type { Stripe } from \"stripe\";\n\nconst createPaymentIntent = async (price: Stripe.Price) => {\n if (price.unit_amount === null || price.unit_amount === undefined) {\n console.error(\"Price does not have a per unit amount\");\n throw new Error(\"Price does not have a per unit amount\");\n }\n\n const intent = await stripe.paymentIntents.create({\n amount: price.unit_amount,\n currency: price.currency,\n automatic_payment_methods: {\n enabled: true,\n allow_redirects: \"never\",\n },\n });\n\n if (!intent.client_secret) {\n console.error(\"Payment intent created without client secret\");\n throw new Error(\"Failed to create payment intent\");\n }\n\n return {\n type: \"payment\",\n clientSecret: intent.client_secret,\n amount: price.unit_amount,\n currency: price.currency,\n };\n};\n\nexport const POST = async ({ request, locals }) => {\n let body;\n try {\n body = await request.json();\n } catch (error) {\n console.error(\"Invalid JSON in request body\");\n return json({ error: \"Invalid request body\" }, { status: 400 });\n }\n\n const { priceId } = body as { priceId?: string };\n\n // Validate required fields\n if (!priceId || typeof priceId !== \"string\" || priceId === \"\") {\n console.error(\"Missing or invalid priceId\");\n return json({ error: \"Price ID is required\" }, { status: 400 });\n }\n\n // Retrieve price from Stripe\n let price;\n try {\n price = await stripe.prices.retrieve(priceId);\n } catch (error) {\n console.error(\"Failed to retrieve price from Stripe:\", priceId);\n return json(\n { error: \"Invalid price ID or price not found\" },\n { status: 404 },\n );\n }\n\n // Validate price is active\n if (!price.active) {\n console.error(\"Price is not active:\", priceId);\n return json(\n { error: \"This price is no longer available\" },\n { status: 400 },\n );\n }\n\n try {\n const res = await createPaymentIntent(price);\n return json(res, { status: 200 });\n } catch (error) {\n console.error(\"Error creating payment intent for price:\", priceId);\n const errorMessage =\n error instanceof Error\n ? error.message\n : \"Failed to create payment intent\";\n return json({ error: errorMessage }, { status: 500 });\n }\n};\n", nl = "import { describe, it, expect, beforeAll } from \"vitest\";\nimport type { Match } from \"@velastack/pocketbase\";\nimport type { RouteId } from \"./$types\";\nimport stripe from \"$lib/stripe\";\nimport type Stripe from \"stripe\";\n\ndescribe(\"POST /api/stripe/payment-intent\", () => {\n let product: Stripe.Product;\n let activePrice: Stripe.Price;\n let inactivePrice: Stripe.Price;\n\n beforeAll(async () => {\n const productName = \"Test Product - Payment Intent\";\n const products = await stripe.products.search({\n query: `name:\"${productName}\" AND metadata[\"test\"]:\"true\"`,\n limit: 1,\n });\n\n if (products.data.length > 0) {\n product = products.data[0];\n\n const prices = await stripe.prices.list({\n product: product.id,\n active: true,\n limit: 1,\n });\n\n if (prices.data.length > 0) {\n activePrice = prices.data[0];\n }\n\n const inactivePrices = await stripe.prices.list({\n product: product.id,\n active: false,\n limit: 1,\n });\n\n if (inactivePrices.data.length > 0) {\n inactivePrice = inactivePrices.data[0];\n }\n }\n\n // Create if not found or no active price\n if (!product) {\n product = await stripe.products.create({\n name: productName,\n metadata: {\n test: \"true\",\n test_type: \"payment-intent\",\n },\n });\n }\n\n if (!activePrice) {\n activePrice = await stripe.prices.create({\n product: product.id,\n unit_amount: 1000,\n currency: \"usd\",\n metadata: {\n test: \"true\",\n test_type: \"payment-intent\",\n },\n });\n }\n\n if (!inactivePrice) {\n inactivePrice = await stripe.prices.create({\n product: product.id,\n unit_amount: 2000,\n currency: \"usd\",\n active: false,\n metadata: {\n test: \"true\",\n test_type: \"payment-intent-inactive\",\n },\n });\n }\n });\n\n describe(\"Request validation\", () => {\n it(\"should return 400 if request body is not valid JSON\", async (context) => {\n const response = await context.agent\n .post(\"/api/stripe/payment-intent\" satisfies Match<RouteId>)\n .set(\"Content-Type\", \"application/json\")\n .send(\"invalid json\");\n\n expect(response.status).toBe(400);\n expect(response.body.error).toBe(\"Invalid request body\");\n });\n\n it(\"should return 400 if priceId is missing\", async (context) => {\n const response = await context.agent\n .post(\"/api/stripe/payment-intent\" satisfies Match<RouteId>)\n .send({});\n\n expect(response.status).toBe(400);\n expect(response.body.error).toBe(\"Price ID is required\");\n });\n\n it(\"should return 400 if priceId is not a string\", async (context) => {\n const response = await context.agent\n .post(\"/api/stripe/payment-intent\" satisfies Match<RouteId>)\n .send({ priceId: 12345 });\n\n expect(response.status).toBe(400);\n expect(response.body.error).toBe(\"Price ID is required\");\n });\n\n it(\"should return 400 if priceId is an empty string\", async (context) => {\n const response = await context.agent\n .post(\"/api/stripe/payment-intent\" satisfies Match<RouteId>)\n .send({ priceId: \"\" });\n\n expect(response.status).toBe(400);\n expect(response.body.error).toBe(\"Price ID is required\");\n });\n\n it(\"should return 404 if price does not exist\", async (context) => {\n const response = await context.agent\n .post(\"/api/stripe/payment-intent\" satisfies Match<RouteId>)\n .send({ priceId: \"price_nonexistent123\" });\n\n expect(response.status).toBe(404);\n expect(response.body.error).toBe(\"Invalid price ID or price not found\");\n });\n\n it(\"should return 400 if price is not active\", async (context) => {\n const response = await context.agent\n .post(\"/api/stripe/payment-intent\" satisfies Match<RouteId>)\n .send({ priceId: inactivePrice.id });\n\n expect(response.status).toBe(400);\n expect(response.body.error).toBe(\"This price is no longer available\");\n });\n });\n\n describe(\"Guest user (unauthenticated)\", () => {\n it(\"should create payment intent for guest user\", async (context) => {\n const response = await context.request\n .post(\"/api/stripe/payment-intent\" satisfies Match<RouteId>)\n .send({ priceId: activePrice.id });\n\n expect(response.status).toBe(200);\n expect(response.body.type).toBe(\"payment\");\n expect(response.body.clientSecret).toBeDefined();\n expect(response.body.amount).toBe(1000);\n expect(response.body.currency).toBe(\"usd\");\n expect(response.body.brand).toBeUndefined();\n expect(response.body.last4).toBeUndefined();\n\n // Verify the payment intent was created in Stripe\n const intentId = response.body.clientSecret.split(\"_secret_\")[0];\n const intent = await stripe.paymentIntents.retrieve(intentId);\n expect(intent.amount).toBe(1000);\n expect(intent.currency).toBe(\"usd\");\n expect(intent.customer).toBeNull();\n\n // Clean up\n await stripe.paymentIntents.cancel(intent.id);\n });\n });\n});\n", rl = "import { json } from \"@sveltejs/kit\";\nimport stripe from \"$lib/stripe\";\nimport { INTERNAL_JOB_SECRET } from \"$env/static/private\";\n\nexport const POST = async ({ request, locals }) => {\n const authHeader = request.headers.get(\"Authorization\");\n if (authHeader !== `Bearer ${INTERNAL_JOB_SECRET}`) {\n return json({ error: \"Unauthorized\" }, { status: 401 });\n }\n\n const prices = await stripe.prices.list();\n\n for (const price of prices.data) {\n try {\n await locals.admin\n .collection(\"stripe_prices\")\n .getFirstListItem(`id = \"${price.id}\"`);\n continue;\n } catch {}\n\n await locals.admin.collection(\"stripe_prices\").create({\n id: price.id,\n billing_scheme: price.billing_scheme,\n currency: price.currency,\n product: price.product,\n recurring: price.recurring,\n type: price.type,\n unit_amount: price.unit_amount,\n active: price.active,\n });\n }\n\n console.log(\"Prices synced\");\n return json({ message: \"Prices synced\" });\n};\n", il = "import { json } from \"@sveltejs/kit\";\nimport stripe from \"$lib/stripe\";\nimport { INTERNAL_JOB_SECRET } from \"$env/static/private\";\n\nexport const POST = async ({ request, locals }) => {\n const authHeader = request.headers.get(\"Authorization\");\n if (authHeader !== `Bearer ${INTERNAL_JOB_SECRET}`) {\n return json({ error: \"Unauthorized\" }, { status: 401 });\n }\n\n const products = await stripe.products.list();\n\n for (const product of products.data) {\n try {\n await locals.admin\n .collection(\"stripe_products\")\n .getFirstListItem(`id = \"${product.id}\"`);\n continue;\n } catch {}\n\n await locals.admin.collection(\"stripe_products\").create({\n id: product.id,\n name: product.name,\n active: product.active,\n default_price: product.default_price,\n });\n }\n\n console.log(\"Products synced\");\n return json({ message: \"Products synced\" });\n};\n", al = "import Stripe from \"stripe\";\nimport { json } from \"@sveltejs/kit\";\nimport { STRIPE_WEBHOOK_SECRET } from \"$env/static/private\";\nimport stripe from \"$lib/stripe\";\nimport { handlePaymentIntentSucceeded } from \"./handlers/payment-intent/succeeded\";\n\nconst processedEvents = new Set<string>();\n\nasync function verifyWebhookSignature(\n request: Request,\n webhookSecret: string,\n): Promise<Stripe.Event> {\n const body = await request.text();\n const signature = request.headers.get(\"stripe-signature\");\n\n if (!signature) {\n throw new Error(\"Missing stripe-signature header\");\n }\n\n if (!webhookSecret) {\n throw new Error(\"Missing webhook secret\");\n }\n\n try {\n return stripe.webhooks.constructEvent(body, signature, webhookSecret);\n } catch (err) {\n console.error(\"Webhook signature verification failed:\", err);\n throw new Error(\"Invalid signature\");\n }\n}\n\nexport const POST = async ({ request, locals }) => {\n try {\n const event = await verifyWebhookSignature(request, STRIPE_WEBHOOK_SECRET);\n\n if (processedEvents.has(event.id)) {\n console.log(`Event ${event.id} already processed, skipping`);\n return json({ received: true, message: \"Event already processed\" });\n }\n\n processedEvents.add(event.id);\n\n console.log(`Processing webhook event: ${event.type} (${event.id})`);\n\n switch (event.type) {\n case \"payment_intent.succeeded\":\n await handlePaymentIntentSucceeded(event.data.object, locals);\n break;\n\n default:\n console.log(`Unhandled event type: ${event.type}`);\n }\n\n return json({\n received: true,\n eventId: event.id,\n eventType: event.type,\n });\n } catch (error) {\n console.error(\"Webhook processing error:\", error);\n\n return json(\n {\n error: \"Webhook processing failed\",\n message: error instanceof Error ? error.message : \"Unknown error\",\n },\n { status: 400 },\n );\n }\n};\n", ol = "import { describe, it, expect } from \"vitest\";\nimport stripe from \"$lib/stripe\";\nimport { handlePaymentIntentSucceeded } from \"./succeeded\";\n\ndescribe(\"payment_intent.succeeded\", () => {\n it(\"handles a payment intent successfully\", async (context) => {\n const paymentIntent = await stripe.paymentIntents.create({\n amount: 2000,\n currency: \"usd\",\n });\n const locals = { admin: context.admin } as App.Locals;\n const result = await handlePaymentIntentSucceeded(paymentIntent, locals);\n\n expect(result).toEqual({});\n });\n});\n", sl = "import Stripe from \"stripe\";\n\n/**\n * Handles payment_intent.succeeded event\n */\nexport async function handlePaymentIntentSucceeded(\n paymentIntent: Stripe.PaymentIntent,\n locals: App.Locals,\n) {\n return {};\n}\n", cl = "import { describe, it, expect } from \"vitest\";\nimport type { RouteId } from \"./$types\";\nimport type { Match } from \"@velastack/pocketbase\";\nimport type Stripe from \"stripe\";\nimport stripe from \"$lib/stripe\";\n\ndescribe(\"POST /webhooks/stripe\", () => {\n it(\"accepts valid webhook signature\", async (context) => {\n const event = {\n id: `evt_test_${Date.now()}`,\n object: \"event\",\n api_version: \"2024-11-20.acacia\",\n created: Math.floor(Date.now() / 1000),\n type: \"test.event\",\n data: {\n object: {},\n },\n livemode: false,\n pending_webhooks: 0,\n request: {\n id: null,\n idempotency_key: null,\n },\n } as unknown as Stripe.Event;\n\n const payload = JSON.stringify(event);\n const webhookSecret = process.env.STRIPE_WEBHOOK_SECRET!;\n\n const signature = stripe.webhooks.generateTestHeaderString({\n payload,\n secret: webhookSecret,\n });\n\n const response = await context.request\n .post(\"/webhooks/stripe\" satisfies Match<RouteId>)\n .set(\"stripe-signature\", signature)\n .send(payload)\n .set(\"Content-Type\", \"application/json\");\n\n expect(response.status).toBe(200);\n expect(response.body.received).toBe(true);\n expect(response.body.eventId).toBe(event.id);\n expect(response.body.eventType).toBe(\"test.event\");\n });\n\n it(\"rejects invalid webhook signature\", async (context) => {\n const event = {\n id: `evt_test_${Date.now()}`,\n object: \"event\",\n api_version: \"2024-11-20.acacia\",\n created: Math.floor(Date.now() / 1000),\n type: \"test.event\",\n data: {\n object: {},\n },\n livemode: false,\n pending_webhooks: 0,\n request: {\n id: null,\n idempotency_key: null,\n },\n } as unknown as Stripe.Event;\n\n const payload = JSON.stringify(event);\n\n const response = await context.request\n .post(\"/webhooks/stripe\" satisfies Match<RouteId>)\n .set(\"stripe-signature\", \"invalid_signature\")\n .send(payload)\n .set(\"Content-Type\", \"application/json\");\n\n expect(response.status).toBe(400);\n expect(response.body.error).toBe(\"Webhook processing failed\");\n });\n\n it(\"rejects request without signature header\", async (context) => {\n const event = {\n id: `evt_test_${Date.now()}`,\n object: \"event\",\n api_version: \"2024-11-20.acacia\",\n created: Math.floor(Date.now() / 1000),\n type: \"test.event\",\n data: {\n object: {},\n },\n livemode: false,\n pending_webhooks: 0,\n request: {\n id: null,\n idempotency_key: null,\n },\n } as unknown as Stripe.Event;\n\n const payload = JSON.stringify(event);\n\n const response = await context.request\n .post(\"/webhooks/stripe\" satisfies Match<RouteId>)\n .send(payload)\n .set(\"Content-Type\", \"application/json\");\n\n expect(response.status).toBe(400);\n expect(response.body.error).toBe(\"Webhook processing failed\");\n expect(response.body.message).toBe(\"Missing stripe-signature header\");\n });\n\n it(\"handles duplicate webhook events\", async (context) => {\n const event = {\n id: `evt_test_${Date.now()}`,\n object: \"event\",\n api_version: \"2024-11-20.acacia\",\n created: Math.floor(Date.now() / 1000),\n type: \"test.event\",\n data: {\n object: {},\n },\n livemode: false,\n pending_webhooks: 0,\n request: {\n id: null,\n idempotency_key: null,\n },\n } as unknown as Stripe.Event;\n\n const payload = JSON.stringify(event);\n const webhookSecret = process.env.STRIPE_WEBHOOK_SECRET!;\n const signature = stripe.webhooks.generateTestHeaderString({\n payload,\n secret: webhookSecret,\n });\n\n // Send first webhook\n const response1 = await context.request\n .post(\"/webhooks/stripe\" satisfies Match<RouteId>)\n .set(\"stripe-signature\", signature)\n .send(payload)\n .set(\"Content-Type\", \"application/json\");\n\n expect(response1.status).toBe(200);\n expect(response1.body.received).toBe(true);\n\n // Send duplicate webhook\n const response2 = await context.request\n .post(\"/webhooks/stripe\" satisfies Match<RouteId>)\n .set(\"stripe-signature\", signature)\n .send(payload)\n .set(\"Content-Type\", \"application/json\");\n\n expect(response2.status).toBe(200);\n expect(response2.body.received).toBe(true);\n expect(response2.body.message).toBe(\"Event already processed\");\n });\n});\n", ll = "/// <reference path=\"../types.d.ts\" />\n\ncronAdd(\"stripe-products\", \"*/2 * * * *\", () => {\n const utils = require(`${__hooks}/utils.js`);\n utils.triggerJob(\"/api/stripe/sync/products\");\n});\n\ncronAdd(\"stripe-prices\", \"*/2 * * * *\", () => {\n const utils = require(`${__hooks}/utils.js`);\n utils.triggerJob(\"/api/stripe/sync/prices\");\n});\n\ncronAdd(\"stripe-customers\", \"* * * * *\", () => {\n const utils = require(`${__hooks}/utils.js`);\n utils.triggerJob(\"/api/stripe/sync/customers\");\n});\n", ul = "/// <reference path=\"../types.d.ts\" />\n\nmodule.exports = {\n triggerJob: (jobUrl) => {\n $http.send({\n method: \"POST\",\n url: `${$app.settings().meta.appURL}${jobUrl}`,\n headers: {\n Authorization: `Bearer ${$os.getenv(\"INTERNAL_JOB_SECRET\")}`,\n },\n });\n },\n};\n", dl = "<script lang=\"ts\">\n import { Button } from '$lib/components/ui/button';\n import SetupDialog from '$lib/components/payments/setup-dialog.svelte';\n import { useStripe } from '$lib/components/payments/use-stripe.svelte';\n import { usePaymentIntent } from '$lib/components/payments/use-payment-intent.svelte';\n\n interface Props {\n disabled?: boolean;\n isProcessing?: boolean;\n label?: string;\n processingLabel?: string;\n onsuccess?: () => void;\n }\n\n let {\n disabled = false,\n isProcessing = false,\n label,\n processingLabel,\n onsuccess\n }: Props = $props();\n\n const stripeManager = useStripe();\n const paymentIntentManager = usePaymentIntent();\n\n let showDialog = $state(false);\n let clientSecret = $state<string>();\n\n async function handleSetupClick() {\n const result = await paymentIntentManager.fetchSetupIntent();\n\n if (!result) return;\n\n clientSecret = result.clientSecret;\n showDialog = true;\n }\n\n function handleDialogOpenChange(open: boolean) {\n showDialog = open;\n }\n\n function handlePaymentSuccess() {\n onsuccess?.();\n }\n<\/script>\n\n<Button disabled={disabled || isProcessing} onclick={handleSetupClick}>\n {#if isProcessing}\n {processingLabel}\n {:else}\n {label}\n {/if}\n</Button>\n\n<SetupDialog\n bind:open={showDialog}\n stripe={stripeManager.stripe}\n {clientSecret}\n onopenchange={handleDialogOpenChange}\n onsuccess={handlePaymentSuccess}\n/>\n", fl = "<script lang=\"ts\">\n import type { Stripe, StripeElements } from '@stripe/stripe-js';\n import { Button } from '$lib/components/ui/button';\n import * as Dialog from '$lib/components/ui/dialog';\n import { toast } from 'svelte-sonner';\n import { page } from '$app/state';\n import { invalidate } from '$app/navigation';\n import StripePaymentForm from './stripe-payment-form.svelte';\n\n interface Props {\n stripe: Stripe | null;\n open: boolean;\n clientSecret?: string;\n onopenchange: (open: boolean) => void;\n onsuccess: () => void;\n }\n\n let { stripe, open = $bindable(), clientSecret, onopenchange, onsuccess }: Props = $props();\n\n let isProcessing = $state(false);\n let cardComplete = $state(false);\n let formRef = $state<{\n getElements: () => StripeElements | null;\n }>();\n\n const handleOpenChangeComplete = (isOpen: boolean) => {\n if (!isOpen) {\n resetDialog();\n }\n onopenchange(isOpen);\n };\n\n function resetDialog() {\n open = false;\n isProcessing = false;\n cardComplete = false;\n }\n\n function handleCardChange(complete: boolean) {\n cardComplete = complete;\n }\n\n async function handleSetupPaymentMethod() {\n if (!stripe || !formRef || !cardComplete || !clientSecret) return;\n\n const elements = formRef.getElements();\n if (!elements) return;\n\n isProcessing = true;\n\n try {\n const { error: submitError } = await elements.submit();\n if (submitError) {\n toast.error(submitError.message || 'Failed to add payment method');\n return;\n }\n\n const { error: confirmError } = await stripe.confirmSetup({\n elements,\n clientSecret,\n confirmParams: {\n return_url: page.url.toString(),\n payment_method_data: {\n allow_redisplay: 'always'\n }\n },\n redirect: 'if_required'\n });\n\n if (confirmError) {\n toast.error(confirmError.message || 'Failed to add payment method');\n return;\n }\n\n await invalidate('app:billing');\n toast.success('Payment method added successfully');\n onsuccess();\n resetDialog();\n } catch (err) {\n console.error('Error adding payment method:', err);\n toast.error('Failed to add payment method');\n } finally {\n isProcessing = false;\n }\n }\n<\/script>\n\n<Dialog.Root bind:open onOpenChangeComplete={handleOpenChangeComplete}>\n <Dialog.Content class=\"sm:max-w-[500px]\">\n <Dialog.Header>\n <Dialog.Title>Add payment method</Dialog.Title>\n <Dialog.Description>Enter your card details to add a new payment method.</Dialog.Description>\n </Dialog.Header>\n <div>\n {#if stripe && open}\n <StripePaymentForm\n bind:this={formRef}\n mode=\"setup\"\n {stripe}\n onchange={handleCardChange}\n savePaymentMethod={true}\n />\n {/if}\n </div>\n <Dialog.Footer>\n <Button variant=\"outline\" onclick={resetDialog} disabled={isProcessing}>Cancel</Button>\n <Button onclick={handleSetupPaymentMethod} disabled={!cardComplete || isProcessing}>\n {isProcessing ? 'Processing...' : 'Add Card'}\n </Button>\n </Dialog.Footer>\n </Dialog.Content>\n</Dialog.Root>\n", pl = "export const load = async ({ parent }) => {\n const { breadcrumbs } = await parent();\n\n return {\n breadcrumbs: [...breadcrumbs, { title: \"Billing\", url: \"/billing\" }],\n };\n};\n", ml = "# Billing Page - Stripe Payment Methods\n\nThis billing page provides a modern UI for managing payment methods with Stripe.\n\n## Features\n\n✅ **Display Payment Methods** - Shows all saved cards with brand, last 4 digits, and expiration\n✅ **Add Payment Methods** - Secure card input using Stripe Elements\n✅ **Remove Payment Methods** - Delete cards with confirmation dialog\n✅ **Default Payment Method** - Set and display the default payment method\n✅ **Responsive Design** - Mobile-friendly layout\n✅ **Error Handling** - Toast notifications for user feedback\n\n## Current Status\n\nThe frontend is **fully functional** with mock data. To connect to your backend, follow the integration steps below.\n\n## Backend Integration\n\n### 1. Update Stripe Publishable Key\n\nIn `+page.svelte`, replace the placeholder with your actual Stripe publishable key:\n\n```typescript\nconst STRIPE_PUBLISHABLE_KEY = \"pk_test_YOUR_KEY_HERE\";\n```\n\nOr better yet, load it from environment variables:\n\n```typescript\nimport { PUBLIC_STRIPE_PUBLISHABLE_KEY } from \"$env/static/public\";\nconst STRIPE_PUBLISHABLE_KEY = PUBLIC_STRIPE_PUBLISHABLE_KEY;\n```\n\n### 2. Fetch Payment Methods on Load\n\nUpdate `+page.server.ts` to fetch payment methods:\n\n```typescript\nexport const load: PageServerLoad = async ({ locals }) => {\n const user = locals.user;\n\n if (!user?.stripeCustomerId) {\n return { paymentMethods: [] };\n }\n\n // Fetch payment methods from Stripe\n const stripe = await import(\"$lib/stripe\").then((m) => m.default);\n const paymentMethods = await stripe.paymentMethods.list({\n customer: user.stripeCustomerId,\n type: \"card\",\n });\n\n return {\n paymentMethods: paymentMethods.data.map((pm) => ({\n id: pm.id,\n brand: pm.card?.brand || \"unknown\",\n last4: pm.card?.last4 || \"0000\",\n expMonth: pm.card?.exp_month || 1,\n expYear: pm.card?.exp_year || 2025,\n isDefault: false, // You'll need to track this separately\n })),\n };\n};\n```\n\n### 3. Create API Endpoints\n\nCreate the following server endpoints:\n\n#### Add Payment Method: `+page.server.ts`\n\n```typescript\nexport const actions = {\n addPaymentMethod: async ({ request, locals }) => {\n const formData = await request.formData();\n const paymentMethodId = formData.get(\"paymentMethodId\");\n\n // Attach payment method to customer\n const stripe = await import(\"$lib/stripe\").then((m) => m.default);\n await stripe.paymentMethods.attach(paymentMethodId, {\n customer: locals.user.stripeCustomerId,\n });\n\n return { success: true };\n },\n\n removePaymentMethod: async ({ request, locals }) => {\n const formData = await request.formData();\n const paymentMethodId = formData.get(\"paymentMethodId\");\n\n // Detach payment method from customer\n const stripe = await import(\"$lib/stripe\").then((m) => m.default);\n await stripe.paymentMethods.detach(paymentMethodId);\n\n return { success: true };\n },\n\n setDefaultPaymentMethod: async ({ request, locals }) => {\n const formData = await request.formData();\n const paymentMethodId = formData.get(\"paymentMethodId\");\n\n // Update customer's default payment method\n const stripe = await import(\"$lib/stripe\").then((m) => m.default);\n await stripe.customers.update(locals.user.stripeCustomerId, {\n invoice_settings: {\n default_payment_method: paymentMethodId,\n },\n });\n\n return { success: true };\n },\n};\n```\n\n### 4. Update Frontend to Use Actions\n\nReplace the mock functions in `+page.svelte`:\n\n```typescript\nasync function handleAddPaymentMethod() {\n if (!stripe || !cardElement || !cardComplete) return;\n\n isProcessing = true;\n\n try {\n const { error, paymentMethod } = await stripe.createPaymentMethod({\n type: \"card\",\n card: cardElement,\n });\n\n if (error) {\n toast.error(error.message);\n return;\n }\n\n // Submit to your backend\n const formData = new FormData();\n formData.append(\"paymentMethodId\", paymentMethod.id);\n\n const response = await fetch(\"?/addPaymentMethod\", {\n method: \"POST\",\n body: formData,\n });\n\n if (response.ok) {\n toast.success(\"Payment method added\");\n // Reload page to fetch updated payment methods\n window.location.reload();\n }\n } finally {\n isProcessing = false;\n }\n}\n```\n\n## Security Considerations\n\n⚠️ **Important**: Never expose your Stripe secret key on the frontend\n✅ All sensitive operations should happen on your backend\n✅ Use Stripe's publishable key for frontend operations\n✅ Validate user permissions before modifying payment methods\n✅ Use HTTPS in production\n\n## Testing\n\nUse [Stripe's test cards](https://stripe.com/docs/testing) for testing:\n\n- **Success**: 4242 4242 4242 4242\n- **Decline**: 4000 0000 0000 0002\n- **Requires authentication**: 4000 0025 0000 3155\n\nUse any future expiration date and any 3-digit CVC.\n\n## Styling\n\nThe page uses Tailwind CSS and shadcn/ui components. All components are styled to match your existing design system with support for light/dark modes.\n\n### Stripe Elements Styling\n\nSince Stripe Elements render in an iframe, they cannot access CSS variables directly. Additionally, Stripe only accepts HEX, RGB, or HSL colors (not modern formats like OKLCH).\n\nThe implementation:\n\n1. **Creates temporary DOM elements** with CSS variables applied\n2. **Lets the browser compute colors** - converts OKLCH/HSL/any format to RGB\n3. **Extracts RGB values** that Stripe Elements can understand\n4. **Passes computed colors** to Stripe Elements on initialization\n5. **Matches the current theme** automatically (light/dark mode)\n\nThis approach works with any CSS color format (oklch, hsl, rgb, hex) and ensures Stripe Elements always match your theme when the \"Add Payment Method\" dialog opens.\n\n## Dependencies\n\n- `@stripe/stripe-js` - Stripe.js for frontend\n- `stripe` - Stripe Node.js SDK for backend\n- `svelte-sonner` - Toast notifications\n- `@lucide/svelte` - Icons\n- shadcn/ui components\n", hl = "import { json } from \"@sveltejs/kit\";\nimport stripe from \"$lib/stripe\";\nimport type { Stripe } from \"stripe\";\n\nconst createPaymentIntent = async (\n price: Stripe.Price,\n customer?: { id: string; default_payment_method?: string },\n) => {\n if (price.unit_amount === null || price.unit_amount === undefined) {\n console.error(\"Price does not have a per unit amount\");\n throw new Error(\"Price does not have a per unit amount\");\n }\n\n // Guest\n if (!customer) {\n const intent = await stripe.paymentIntents.create({\n amount: price.unit_amount,\n currency: price.currency,\n automatic_payment_methods: {\n enabled: true,\n allow_redirects: \"never\",\n },\n });\n\n if (!intent.client_secret) {\n console.error(\"Payment intent created without client secret\");\n throw new Error(\"Failed to create payment intent\");\n }\n\n return {\n type: \"payment\",\n clientSecret: intent.client_secret,\n amount: price.unit_amount,\n currency: price.currency,\n };\n }\n\n // Customer with saved payment method\n if (customer.default_payment_method) {\n const paymentMethod = await stripe.customers.retrievePaymentMethod(\n customer.id,\n customer.default_payment_method,\n );\n\n const intent = await stripe.paymentIntents.create({\n amount: price.unit_amount,\n currency: price.currency,\n customer: customer.id,\n payment_method: customer.default_payment_method,\n automatic_payment_methods: {\n enabled: true,\n allow_redirects: \"never\",\n },\n });\n\n return {\n type: \"confirm\",\n clientSecret: intent.client_secret,\n amount: price.unit_amount,\n currency: price.currency,\n brand: paymentMethod.card?.brand,\n last4: paymentMethod.card?.last4,\n };\n }\n\n // Customer without saved payment method\n const intent = await stripe.paymentIntents.create({\n amount: price.unit_amount,\n currency: price.currency,\n customer: customer.id,\n setup_future_usage: \"off_session\",\n automatic_payment_methods: {\n enabled: true,\n allow_redirects: \"never\",\n },\n });\n\n if (!intent.client_secret) {\n console.error(\"Payment intent created without client secret\");\n throw new Error(\"Failed to create payment intent\");\n }\n\n return {\n type: \"payment\",\n clientSecret: intent.client_secret,\n amount: price.unit_amount,\n currency: price.currency,\n };\n};\n\nexport const POST = async ({ request, locals }) => {\n const user = locals.pb.authStore.record?.id;\n\n let body;\n try {\n body = await request.json();\n } catch (error) {\n console.error(\"Invalid JSON in request body\");\n return json({ error: \"Invalid request body\" }, { status: 400 });\n }\n\n const { priceId } = body as { priceId?: string };\n\n // Validate required fields\n if (!priceId || typeof priceId !== \"string\" || priceId === \"\") {\n console.error(\"Missing or invalid priceId\");\n return json({ error: \"Price ID is required\" }, { status: 400 });\n }\n\n // Retrieve price from Stripe\n let price;\n try {\n price = await stripe.prices.retrieve(priceId);\n } catch (error) {\n console.error(\"Failed to retrieve price from Stripe:\", priceId);\n return json(\n { error: \"Invalid price ID or price not found\" },\n { status: 404 },\n );\n }\n\n // Validate price is active\n if (!price.active) {\n console.error(\"Price is not active:\", priceId);\n return json(\n { error: \"This price is no longer available\" },\n { status: 400 },\n );\n }\n\n let customer;\n\n if (user) {\n try {\n customer = await locals.admin\n .collection(\"stripe_customers\")\n .getFirstListItem(\n locals.admin.filter(\"user = {:user}\", { user: user }),\n );\n } catch (error) {\n // Customer not found is expected for new users, log for debugging only\n console.log(\"No Stripe customer found for user:\", user);\n }\n }\n\n try {\n const res = await createPaymentIntent(price, customer);\n return json(res, { status: 200 });\n } catch (error) {\n console.error(\"Error creating payment intent for price:\", priceId);\n const errorMessage =\n error instanceof Error\n ? error.message\n : \"Failed to create payment intent\";\n return json({ error: errorMessage }, { status: 500 });\n }\n};\n", gl = "import { describe, it, expect, beforeAll, beforeEach, afterEach } from \"vitest\";\nimport type { Match } from \"@velastack/pocketbase\";\nimport type { RouteId } from \"./$types\";\nimport stripe from \"$lib/stripe\";\nimport type Stripe from \"stripe\";\n\ndescribe(\"POST /api/stripe/payment-intent\", () => {\n let product: Stripe.Product;\n let activePrice: Stripe.Price;\n let inactivePrice: Stripe.Price;\n let stripeCustomer: Stripe.Customer;\n let paymentMethod: Stripe.PaymentMethod;\n\n beforeAll(async () => {\n const productName = \"Test Product - Payment Intent\";\n const products = await stripe.products.search({\n query: `name:\"${productName}\" AND metadata[\"test\"]:\"true\"`,\n limit: 1,\n });\n\n if (products.data.length > 0) {\n product = products.data[0];\n\n const prices = await stripe.prices.list({\n product: product.id,\n active: true,\n limit: 1,\n });\n\n if (prices.data.length > 0) {\n activePrice = prices.data[0];\n }\n\n const inactivePrices = await stripe.prices.list({\n product: product.id,\n active: false,\n limit: 1,\n });\n\n if (inactivePrices.data.length > 0) {\n inactivePrice = inactivePrices.data[0];\n }\n }\n\n // Create if not found or no active price\n if (!product) {\n product = await stripe.products.create({\n name: productName,\n metadata: {\n test: \"true\",\n test_type: \"payment-intent\",\n },\n });\n }\n\n if (!activePrice) {\n activePrice = await stripe.prices.create({\n product: product.id,\n unit_amount: 1000,\n currency: \"usd\",\n metadata: {\n test: \"true\",\n test_type: \"payment-intent\",\n },\n });\n }\n\n if (!inactivePrice) {\n inactivePrice = await stripe.prices.create({\n product: product.id,\n unit_amount: 2000,\n currency: \"usd\",\n active: false,\n metadata: {\n test: \"true\",\n test_type: \"payment-intent-inactive\",\n },\n });\n }\n });\n\n beforeEach(async (context) => {\n // Create a Stripe customer for authenticated user tests\n stripeCustomer = await stripe.customers.create({\n email: context.user.email,\n metadata: {\n test: \"true\",\n },\n });\n\n // Create a payment method for the customer\n paymentMethod = await stripe.paymentMethods.create({\n type: \"card\",\n card: {\n token: \"tok_visa\",\n },\n });\n\n await stripe.paymentMethods.attach(paymentMethod.id, {\n customer: stripeCustomer.id,\n });\n });\n\n afterEach(async () => {\n if (paymentMethod?.id) {\n await stripe.paymentMethods.detach(paymentMethod.id);\n }\n\n if (stripeCustomer?.id) {\n await stripe.customers.del(stripeCustomer.id);\n }\n });\n\n describe(\"Request validation\", () => {\n it(\"should return 400 if request body is not valid JSON\", async (context) => {\n const response = await context.agent\n .post(\"/api/stripe/payment-intent\" satisfies Match<RouteId>)\n .set(\"Content-Type\", \"application/json\")\n .send(\"invalid json\");\n\n expect(response.status).toBe(400);\n expect(response.body.error).toBe(\"Invalid request body\");\n });\n\n it(\"should return 400 if priceId is missing\", async (context) => {\n const response = await context.agent\n .post(\"/api/stripe/payment-intent\" satisfies Match<RouteId>)\n .send({});\n\n expect(response.status).toBe(400);\n expect(response.body.error).toBe(\"Price ID is required\");\n });\n\n it(\"should return 400 if priceId is not a string\", async (context) => {\n const response = await context.agent\n .post(\"/api/stripe/payment-intent\" satisfies Match<RouteId>)\n .send({ priceId: 12345 });\n\n expect(response.status).toBe(400);\n expect(response.body.error).toBe(\"Price ID is required\");\n });\n\n it(\"should return 400 if priceId is an empty string\", async (context) => {\n const response = await context.agent\n .post(\"/api/stripe/payment-intent\" satisfies Match<RouteId>)\n .send({ priceId: \"\" });\n\n expect(response.status).toBe(400);\n expect(response.body.error).toBe(\"Price ID is required\");\n });\n\n it(\"should return 404 if price does not exist\", async (context) => {\n const response = await context.agent\n .post(\"/api/stripe/payment-intent\" satisfies Match<RouteId>)\n .send({ priceId: \"price_nonexistent123\" });\n\n expect(response.status).toBe(404);\n expect(response.body.error).toBe(\"Invalid price ID or price not found\");\n });\n\n it(\"should return 400 if price is not active\", async (context) => {\n const response = await context.agent\n .post(\"/api/stripe/payment-intent\" satisfies Match<RouteId>)\n .send({ priceId: inactivePrice.id });\n\n expect(response.status).toBe(400);\n expect(response.body.error).toBe(\"This price is no longer available\");\n });\n });\n\n describe(\"Guest user (unauthenticated)\", () => {\n it(\"should create payment intent for guest user\", async (context) => {\n const response = await context.request\n .post(\"/api/stripe/payment-intent\" satisfies Match<RouteId>)\n .send({ priceId: activePrice.id });\n\n expect(response.status).toBe(200);\n expect(response.body.type).toBe(\"payment\");\n expect(response.body.clientSecret).toBeDefined();\n expect(response.body.amount).toBe(1000);\n expect(response.body.currency).toBe(\"usd\");\n expect(response.body.brand).toBeUndefined();\n expect(response.body.last4).toBeUndefined();\n\n // Verify the payment intent was created in Stripe\n const intentId = response.body.clientSecret.split(\"_secret_\")[0];\n const intent = await stripe.paymentIntents.retrieve(intentId);\n expect(intent.amount).toBe(1000);\n expect(intent.currency).toBe(\"usd\");\n expect(intent.customer).toBeNull();\n\n // Clean up\n await stripe.paymentIntents.cancel(intent.id);\n });\n });\n\n describe(\"Authenticated user without Stripe customer\", () => {\n it(\"should create payment intent for user without Stripe customer\", async (context) => {\n await context.agent.authenticateUser();\n\n const response = await context.agent\n .post(\"/api/stripe/payment-intent\" satisfies Match<RouteId>)\n .send({ priceId: activePrice.id });\n\n expect(response.status).toBe(200);\n expect(response.body.type).toBe(\"payment\");\n expect(response.body.clientSecret).toBeDefined();\n expect(response.body.amount).toBe(1000);\n expect(response.body.currency).toBe(\"usd\");\n\n // Verify the payment intent\n const intentId = response.body.clientSecret.split(\"_secret_\")[0];\n const intent = await stripe.paymentIntents.retrieve(intentId);\n expect(intent.amount).toBe(1000);\n expect(intent.setup_future_usage).toBeNull();\n\n // Clean up\n await stripe.paymentIntents.cancel(intent.id);\n });\n });\n\n describe(\"Authenticated user with Stripe customer\", () => {\n let customerRecord: { id: string };\n\n beforeEach(async (context) => {\n // Link the Stripe customer to the PocketBase user\n customerRecord = await context.admin\n .collection(\"stripe_customers\")\n .create({\n user: context.user.id,\n id: stripeCustomer.id,\n email: stripeCustomer.email,\n });\n });\n\n afterEach(async (context) => {\n // Clean up the PocketBase customer record\n await context.admin\n .collection(\"stripe_customers\")\n .delete(customerRecord.id);\n });\n\n it(\"should create payment intent with setup_future_usage for user without default payment method\", async (context) => {\n await context.agent.authenticateUser();\n\n const response = await context.agent\n .post(\"/api/stripe/payment-intent\" satisfies Match<RouteId>)\n .send({ priceId: activePrice.id });\n\n expect(response.status).toBe(200);\n expect(response.body.type).toBe(\"payment\");\n expect(response.body.clientSecret).toBeDefined();\n expect(response.body.amount).toBe(1000);\n expect(response.body.currency).toBe(\"usd\");\n expect(response.body.brand).toBeUndefined();\n expect(response.body.last4).toBeUndefined();\n\n // Verify the payment intent has setup_future_usage\n const intentId = response.body.clientSecret.split(\"_secret_\")[0];\n const intent = await stripe.paymentIntents.retrieve(intentId);\n expect(intent.customer).toBe(stripeCustomer.id);\n expect(intent.setup_future_usage).toBe(\"off_session\");\n\n // Clean up\n await stripe.paymentIntents.cancel(intent.id);\n });\n\n it(\"should create payment intent with default payment method for customer with saved payment method\", async (context) => {\n // Set default payment method\n await stripe.customers.update(stripeCustomer.id, {\n invoice_settings: {\n default_payment_method: paymentMethod.id,\n },\n });\n\n const customerRecord = await context.admin\n .collection(\"stripe_customers\")\n .getFirstListItem(\n context.admin.filter(\"user = {:user}\", { user: context.user.id }),\n );\n\n await context.admin.collection(\"stripe_payment_methods\").create({\n id: paymentMethod.id,\n customer: customerRecord.id,\n brand: paymentMethod.card?.brand,\n last4: paymentMethod.card?.last4,\n exp_month: paymentMethod.card?.exp_month,\n exp_year: paymentMethod.card?.exp_year,\n });\n\n await context.admin\n .collection(\"stripe_customers\")\n .update(customerRecord.id, {\n default_payment_method: paymentMethod.id,\n });\n\n await context.agent.authenticateUser();\n\n const response = await context.agent\n .post(\"/api/stripe/payment-intent\" satisfies Match<RouteId>)\n .send({ priceId: activePrice.id });\n\n expect(response.status).toBe(200);\n expect(response.body.type).toBe(\"confirm\");\n expect(response.body.clientSecret).toBeDefined();\n expect(response.body.amount).toBe(1000);\n expect(response.body.currency).toBe(\"usd\");\n expect(response.body.brand).toBe(\"visa\");\n expect(response.body.last4).toBeDefined();\n expect(response.body.last4).toMatch(/^\\d{4}$/);\n\n // Verify the payment intent has the payment method attached\n const intentId = response.body.clientSecret.split(\"_secret_\")[0];\n const intent = await stripe.paymentIntents.retrieve(intentId);\n expect(intent.customer).toBe(stripeCustomer.id);\n expect(intent.payment_method).toBe(paymentMethod.id);\n\n // Clean up\n await stripe.paymentIntents.cancel(intent.id);\n });\n });\n});\n", _l = "import { json } from \"@sveltejs/kit\";\nimport stripe from \"$lib/stripe\";\n\nexport const POST = async ({ locals }) => {\n const user = locals.pb.authStore.record?.id;\n\n if (!user) {\n return json({ error: \"Unauthorized\" }, { status: 401 });\n }\n\n const customer = await locals.admin\n .collection(\"stripe_customers\")\n .getFirstListItem(locals.admin.filter(\"user = {:user}\", { user }));\n\n if (!customer) {\n return json({ error: \"Customer not found\" }, { status: 404 });\n }\n\n const setupIntent = await stripe.setupIntents.create({\n customer: customer.id,\n automatic_payment_methods: {\n enabled: true,\n allow_redirects: \"never\",\n },\n });\n\n return json({ clientSecret: setupIntent.client_secret });\n};\n", vl = "import { describe, it, expect, beforeEach, afterEach } from \"vitest\";\nimport type { Match } from \"@velastack/pocketbase\";\nimport type Stripe from \"stripe\";\nimport stripe from \"$lib/stripe\";\nimport type { RouteId } from \"./$types\";\n\ndescribe(\"POST /api/stripe/setup-intent\", () => {\n let stripeCustomer: Stripe.Customer;\n\n beforeEach(async (context) => {\n await context.agent.authenticateUser();\n\n stripeCustomer = await stripe.customers.create({\n email: context.user.email,\n metadata: {\n test: \"true\",\n },\n });\n\n await context.admin.collection(\"stripe_customers\").create({\n id: stripeCustomer.id,\n user: context.user.id,\n });\n });\n\n afterEach(async (context) => {\n await context.admin\n .collection(\"stripe_customers\")\n .delete(stripeCustomer.id);\n });\n\n it(\"creates a setup intent\", async (context) => {\n const response = await context.agent.post(\n \"/api/stripe/setup-intent\" satisfies Match<RouteId>,\n );\n expect(response.status).toBe(200);\n expect(response.body.clientSecret).toBeDefined();\n });\n});\n", yl = "import { json } from \"@sveltejs/kit\";\nimport stripe from \"$lib/stripe\";\nimport { INTERNAL_JOB_SECRET } from \"$env/static/private\";\n\n// Sync users to Stripe customers\nexport const POST = async ({ request, locals }) => {\n const authHeader = request.headers.get(\"Authorization\");\n if (authHeader !== `Bearer ${INTERNAL_JOB_SECRET}`) {\n return json({ error: \"Unauthorized\" }, { status: 401 });\n }\n\n // Ensure all users have a Stripe customer\n const users = await locals.admin\n .collection(\"users\")\n .getFullList({ filter: \"stripe_customers_via_user.id = null\" });\n\n for (const user of users) {\n const customer = await stripe.customers.create({\n email: user.email,\n name: user.name,\n });\n\n await locals.admin.collection(\"stripe_customers\").create({\n id: customer.id,\n user: user.id,\n });\n }\n\n console.log(\"Customers synced\");\n return json({ message: \"Customers synced\" });\n};\n", bl = "import Stripe from \"stripe\";\nimport { json } from \"@sveltejs/kit\";\nimport { STRIPE_WEBHOOK_SECRET } from \"$env/static/private\";\nimport stripe from \"$lib/stripe\";\nimport { handlePaymentIntentSucceeded } from \"./handlers/payment-intent/succeeded\";\nimport { handlePaymentMethodAttached } from \"./handlers/payment-method/attached\";\n\nconst processedEvents = new Set<string>();\n\nasync function verifyWebhookSignature(\n request: Request,\n webhookSecret: string,\n): Promise<Stripe.Event> {\n const body = await request.text();\n const signature = request.headers.get(\"stripe-signature\");\n\n if (!signature) {\n throw new Error(\"Missing stripe-signature header\");\n }\n\n if (!webhookSecret) {\n throw new Error(\"Missing webhook secret\");\n }\n\n try {\n return stripe.webhooks.constructEvent(body, signature, webhookSecret);\n } catch (err) {\n console.error(\"Webhook signature verification failed:\", err);\n throw new Error(\"Invalid signature\");\n }\n}\n\nexport const POST = async ({ request, locals }) => {\n try {\n const event = await verifyWebhookSignature(request, STRIPE_WEBHOOK_SECRET);\n\n if (processedEvents.has(event.id)) {\n console.log(`Event ${event.id} already processed, skipping`);\n return json({ received: true, message: \"Event already processed\" });\n }\n\n processedEvents.add(event.id);\n\n console.log(`Processing webhook event: ${event.type} (${event.id})`);\n\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 default:\n console.log(`Unhandled event type: ${event.type}`);\n }\n\n return json({\n received: true,\n eventId: event.id,\n eventType: event.type,\n });\n } catch (error) {\n console.error(\"Webhook processing error:\", error);\n\n return json(\n {\n error: \"Webhook processing failed\",\n message: error instanceof Error ? error.message : \"Unknown error\",\n },\n { status: 400 },\n );\n }\n};\n", xl = "import { describe, it, expect, beforeEach, afterEach } from \"vitest\";\nimport type Stripe from \"stripe\";\nimport stripe from \"$lib/stripe\";\nimport { handlePaymentIntentSucceeded } from \"./succeeded\";\n\ndescribe(\"payment_intent.succeeded\", () => {\n let stripeCustomer: Stripe.Customer;\n let paymentIntent: Stripe.PaymentIntent;\n let paymentMethod: Stripe.PaymentMethod;\n\n beforeEach(async (context) => {\n // Create a Stripe customer\n stripeCustomer = await stripe.customers.create({\n email: context.user.email,\n metadata: {\n test: \"true\",\n },\n });\n\n // Link the Stripe customer to the test user\n await context.admin.collection(\"stripe_customers\").create({\n id: stripeCustomer.id,\n user: context.user.id,\n });\n\n // Create a payment method for testing\n paymentMethod = await stripe.paymentMethods.create({\n type: \"card\",\n card: {\n token: \"tok_visa\",\n },\n });\n\n // Attach payment method to customer\n await stripe.paymentMethods.attach(paymentMethod.id, {\n customer: stripeCustomer.id,\n });\n\n // Create a payment intent\n paymentIntent = await stripe.paymentIntents.create({\n amount: 2000, // $20.00\n currency: \"usd\",\n customer: stripeCustomer.id,\n payment_method: paymentMethod.id,\n confirm: true,\n return_url: \"https://example.com/return\",\n });\n });\n\n afterEach(async (context) => {\n // Clean up transactions\n const transactions = await context.admin\n .collection(\"transactions\")\n .getFullList({\n filter: context.admin.filter(\"stripe_customer = {:stripeCustomer}\", {\n stripeCustomer: stripeCustomer.id,\n }),\n });\n for (const transaction of transactions) {\n await context.admin.collection(\"transactions\").delete(transaction.id);\n }\n\n // Clean up Stripe resources\n if (paymentMethod?.id) {\n try {\n await stripe.paymentMethods.detach(paymentMethod.id);\n } catch (e) {\n // Payment method may already be detached\n }\n }\n\n // Delete customer (this will also delete associated payment methods)\n if (stripeCustomer?.id) {\n await context.admin\n .collection(\"stripe_customers\")\n .delete(stripeCustomer.id);\n await stripe.customers.del(stripeCustomer.id);\n }\n });\n\n it(\"creates a transaction record when payment intent succeeds\", async (context) => {\n const locals = { admin: context.admin } as App.Locals;\n await handlePaymentIntentSucceeded(paymentIntent, locals);\n\n // Verify transaction was created\n const transactions = await context.admin\n .collection(\"transactions\")\n .getFullList({\n filter: context.admin.filter(\n \"stripe_payment_intent = {:paymentIntent}\",\n {\n paymentIntent: paymentIntent.id,\n },\n ),\n });\n\n expect(transactions).toHaveLength(1);\n const transaction = transactions[0];\n\n expect(transaction.stripe_payment_intent).toBe(paymentIntent.id);\n expect(transaction.stripe_customer).toBe(stripeCustomer.id);\n expect(transaction.amount).toBe(2000);\n expect(transaction.currency).toBe(\"usd\");\n expect(transaction.user).toBe(context.user.id);\n expect(transaction.stripe_charge).toBeDefined();\n expect(transaction.last4).toBeDefined();\n expect(transaction.brand).toBeDefined();\n expect(transaction.created).toBeDefined();\n expect(transaction.receipt_url).toBeDefined();\n });\n\n it(\"handles payment intent with charge object instead of string\", async (context) => {\n // Retrieve the payment intent with expanded charge\n const expandedPaymentIntent = await stripe.paymentIntents.retrieve(\n paymentIntent.id,\n {\n expand: [\"latest_charge\"],\n },\n );\n\n const locals = { admin: context.admin } as App.Locals;\n await handlePaymentIntentSucceeded(expandedPaymentIntent, locals);\n\n // Verify transaction was created\n const transactions = await context.admin\n .collection(\"transactions\")\n .getFullList({\n filter: context.admin.filter(\n \"stripe_payment_intent = {:paymentIntent}\",\n {\n paymentIntent: paymentIntent.id,\n },\n ),\n });\n\n expect(transactions).toHaveLength(1);\n const transaction = transactions[0];\n\n expect(transaction.stripe_payment_intent).toBe(paymentIntent.id);\n expect(transaction.stripe_charge).toBeDefined();\n });\n\n it(\"handles payment intent with customer object instead of string\", async (context) => {\n // Retrieve the payment intent with expanded customer\n const expandedPaymentIntent = await stripe.paymentIntents.retrieve(\n paymentIntent.id,\n {\n expand: [\"customer\"],\n },\n );\n\n const locals = { admin: context.admin } as App.Locals;\n await handlePaymentIntentSucceeded(expandedPaymentIntent, locals);\n\n // Verify transaction was created\n const transactions = await context.admin\n .collection(\"transactions\")\n .getFullList({\n filter: context.admin.filter(\n \"stripe_payment_intent = {:paymentIntent}\",\n {\n paymentIntent: paymentIntent.id,\n },\n ),\n });\n\n expect(transactions).toHaveLength(1);\n expect(transactions[0].stripe_customer).toBe(stripeCustomer.id);\n });\n\n it(\"handles missing charge ID gracefully\", async (context) => {\n const paymentIntentWithoutCharge = {\n ...paymentIntent,\n latest_charge: null,\n } as Stripe.PaymentIntent;\n\n const locals = { admin: context.admin } as App.Locals;\n await handlePaymentIntentSucceeded(paymentIntentWithoutCharge, locals);\n\n // Verify no transaction was created\n const transactions = await context.admin\n .collection(\"transactions\")\n .getFullList({\n filter: context.admin.filter(\n \"stripe_payment_intent = {:paymentIntent}\",\n {\n paymentIntent: paymentIntent.id,\n },\n ),\n });\n\n expect(transactions).toHaveLength(0);\n });\n\n it(\"handles missing customer ID gracefully\", async (context) => {\n const paymentIntentWithoutCustomer = {\n ...paymentIntent,\n customer: null,\n } as Stripe.PaymentIntent;\n\n const locals = { admin: context.admin } as App.Locals;\n await handlePaymentIntentSucceeded(paymentIntentWithoutCustomer, locals);\n\n // Verify no transaction was created\n const transactions = await context.admin\n .collection(\"transactions\")\n .getFullList({\n filter: context.admin.filter(\n \"stripe_payment_intent = {:paymentIntent}\",\n {\n paymentIntent: paymentIntent.id,\n },\n ),\n });\n\n expect(transactions).toHaveLength(0);\n });\n});\n", Sl = "import Stripe from \"stripe\";\nimport stripe from \"$lib/stripe\";\n/**\n * Handles payment_intent.succeeded event\n */\nexport async function handlePaymentIntentSucceeded(\n paymentIntent: Stripe.PaymentIntent,\n locals: App.Locals,\n) {\n const chargeId =\n typeof paymentIntent.latest_charge === \"string\"\n ? paymentIntent.latest_charge\n : paymentIntent.latest_charge?.id;\n\n if (!chargeId) {\n console.error(\"No charge ID found for payment intent\");\n return;\n }\n\n const charge = await stripe.charges.retrieve(chargeId);\n\n const customerId =\n typeof paymentIntent.customer === \"string\"\n ? paymentIntent.customer\n : paymentIntent.customer?.id;\n\n if (!customerId) {\n console.error(\"No customer ID found for payment intent\");\n return;\n }\n\n const customer = await locals.admin\n .collection(\"stripe_customers\")\n .getOne(customerId);\n const created = new Date(charge.created * 1000);\n\n await locals.admin.collection(\"transactions\").create({\n stripe_payment_intent: paymentIntent.id,\n stripe_charge: chargeId,\n stripe_customer: customerId,\n amount: paymentIntent.amount,\n currency: paymentIntent.currency,\n created: created.toISOString(),\n last4: charge.payment_method_details?.card?.last4,\n brand: charge.payment_method_details?.card?.brand,\n receipt_url: charge.receipt_url,\n user: customer.user,\n });\n}\n", Cl = "import Stripe from \"stripe\";\nimport stripe from \"$lib/stripe\";\n\n/**\n * Handles payment_method.attached event\n */\nexport async function handlePaymentMethodAttached(\n paymentMethod: Stripe.PaymentMethod,\n locals: App.Locals,\n) {\n if (\n paymentMethod.allow_redisplay === \"unspecified\" ||\n !paymentMethod.customer\n ) {\n return;\n }\n\n const customer =\n typeof paymentMethod.customer === \"string\"\n ? paymentMethod.customer\n : paymentMethod.customer?.id;\n\n await locals.admin.collection(\"stripe_payment_methods\").create({\n id: paymentMethod.id,\n customer: customer,\n brand: paymentMethod.card?.brand,\n last4: paymentMethod.card?.last4,\n exp_month: paymentMethod.card?.exp_month,\n exp_year: paymentMethod.card?.exp_year,\n });\n\n const paymentMethodRecords = await locals.admin\n .collection(\"stripe_payment_methods\")\n .getFullList({\n filter: locals.admin.filter(\"customer = {:customer}\", {\n customer: customer,\n }),\n });\n\n if (paymentMethodRecords.length === 1) {\n const paymentMethod = paymentMethodRecords[0];\n\n await stripe.customers.update(customer, {\n invoice_settings: {\n default_payment_method: paymentMethod.id,\n },\n });\n\n await locals.admin.collection(\"stripe_customers\").update(customer, {\n default_payment_method: paymentMethod.id,\n });\n }\n}\n", wl = "import { describe, it, expect, beforeEach, afterEach } from \"vitest\";\nimport type Stripe from \"stripe\";\nimport stripe from \"$lib/stripe\";\nimport { handlePaymentMethodAttached } from \"./attached\";\n\ndescribe(\"payment_method.attached\", () => {\n let stripeCustomer: Stripe.Customer;\n let paymentMethod: Stripe.PaymentMethod;\n\n beforeEach(async (context) => {\n stripeCustomer = await stripe.customers.create({\n email: context.user.email,\n metadata: {\n test: \"true\",\n },\n });\n\n await context.admin.collection(\"stripe_customers\").create({\n id: stripeCustomer.id,\n user: context.user.id,\n });\n\n paymentMethod = await stripe.paymentMethods.create({\n type: \"card\",\n card: {\n token: \"tok_visa\",\n },\n });\n\n await stripe.paymentMethods.attach(paymentMethod.id, {\n customer: stripeCustomer.id,\n });\n\n paymentMethod = await stripe.paymentMethods.update(paymentMethod.id, {\n allow_redisplay: \"always\",\n });\n });\n\n afterEach(async (context) => {\n const paymentMethods = await context.admin\n .collection(\"stripe_payment_methods\")\n .getFullList({\n filter: context.admin.filter(\"customer = {:stripeCustomer}\", {\n stripeCustomer: stripeCustomer.id,\n }),\n });\n\n for (const pm of paymentMethods) {\n await context.admin.collection(\"stripe_payment_methods\").delete(pm.id);\n }\n\n if (paymentMethod?.id) {\n try {\n await stripe.paymentMethods.detach(paymentMethod.id);\n } catch {}\n }\n\n if (stripeCustomer?.id) {\n await context.admin\n .collection(\"stripe_customers\")\n .delete(stripeCustomer.id);\n await stripe.customers.del(stripeCustomer.id);\n }\n });\n\n it(\"creates a payment method record when payment method is attached\", async (context) => {\n const locals = { admin: context.admin } as App.Locals;\n await handlePaymentMethodAttached(paymentMethod, locals);\n\n // Verify payment method was created\n const paymentMethods = await context.admin\n .collection(\"stripe_payment_methods\")\n .getFullList({\n filter: context.admin.filter(\"id = {:paymentMethod}\", {\n paymentMethod: paymentMethod.id,\n }),\n });\n\n expect(paymentMethods).toHaveLength(1);\n const pm = paymentMethods[0];\n\n expect(pm.id).toBe(paymentMethod.id);\n expect(pm.customer).toBe(stripeCustomer.id);\n expect(pm.brand).toBe(paymentMethod.card?.brand);\n expect(pm.last4).toBe(paymentMethod.card?.last4);\n expect(pm.exp_month).toBe(paymentMethod.card?.exp_month);\n expect(pm.exp_year).toBe(paymentMethod.card?.exp_year);\n });\n\n it(\"sets payment method as default when it is the first one\", async (context) => {\n const locals = { admin: context.admin } as App.Locals;\n await handlePaymentMethodAttached(paymentMethod, locals);\n\n // Verify it was set as default in database\n const customer = await context.admin\n .collection(\"stripe_customers\")\n .getOne(stripeCustomer.id);\n expect(customer.default_payment_method).toBe(paymentMethod.id);\n\n // Verify it was set as default in Stripe\n const stripeCustomerUpdated = await stripe.customers.retrieve(\n stripeCustomer.id,\n );\n if (\"deleted\" in stripeCustomerUpdated) {\n throw new Error(\"Customer should not be deleted\");\n }\n expect(stripeCustomerUpdated.invoice_settings.default_payment_method).toBe(\n paymentMethod.id,\n );\n });\n\n it(\"does not set as default when there are already payment methods\", async (context) => {\n // Handle the first payment method\n const locals = { admin: context.admin } as App.Locals;\n await handlePaymentMethodAttached(paymentMethod, locals);\n\n // Verify it was set as default\n let customer = await context.admin\n .collection(\"stripe_customers\")\n .getOne(stripeCustomer.id);\n expect(customer.default_payment_method).toBe(paymentMethod.id);\n\n // Create and attach a first payment method\n let secondPaymentMethod = await stripe.paymentMethods.create({\n type: \"card\",\n card: {\n token: \"tok_mastercard\",\n },\n });\n\n await stripe.paymentMethods.attach(secondPaymentMethod.id, {\n customer: stripeCustomer.id,\n });\n\n secondPaymentMethod = await stripe.paymentMethods.update(\n secondPaymentMethod.id,\n {\n allow_redisplay: \"always\",\n },\n );\n\n // Now handle the second payment method\n await handlePaymentMethodAttached(secondPaymentMethod, locals);\n\n // Verify the default did NOT change\n customer = await context.admin\n .collection(\"stripe_customers\")\n .getOne(stripeCustomer.id);\n expect(customer.default_payment_method).toBe(paymentMethod.id);\n\n // Clean up the second payment method\n await context.admin\n .collection(\"stripe_payment_methods\")\n .delete(secondPaymentMethod.id);\n await stripe.paymentMethods.detach(secondPaymentMethod.id);\n });\n\n it(\"handles payment method with customer object instead of string\", async (context) => {\n // Retrieve the payment method with expanded customer\n const expandedPaymentMethod = await stripe.paymentMethods.retrieve(\n paymentMethod.id,\n {\n expand: [\"customer\"],\n },\n );\n\n const locals = { admin: context.admin } as App.Locals;\n await handlePaymentMethodAttached(expandedPaymentMethod, locals);\n\n // Verify payment method was created\n const paymentMethods = await context.admin\n .collection(\"stripe_payment_methods\")\n .getFullList({\n filter: context.admin.filter(\"id = {:paymentMethod}\", {\n paymentMethod: paymentMethod.id,\n }),\n });\n\n expect(paymentMethods).toHaveLength(1);\n expect(paymentMethods[0].customer).toBe(stripeCustomer.id);\n });\n\n it(\"does not create record when allow_redisplay is unspecified\", async (context) => {\n // Update payment method to have unspecified allow_redisplay\n const unspecifiedPaymentMethod = await stripe.paymentMethods.update(\n paymentMethod.id,\n {\n allow_redisplay: \"unspecified\",\n },\n );\n\n const locals = { admin: context.admin } as App.Locals;\n await handlePaymentMethodAttached(unspecifiedPaymentMethod, locals);\n\n // Verify no payment method was created\n const paymentMethods = await context.admin\n .collection(\"stripe_payment_methods\")\n .getFullList({\n filter: context.admin.filter(\"id = {:paymentMethod}\", {\n paymentMethod: paymentMethod.id,\n }),\n });\n\n expect(paymentMethods).toHaveLength(0);\n });\n});\n", Tl = /* @__PURE__ */ Object.assign({
4675
+ }, Gc = "/// <reference path=\"../types.d.ts\" />\n\ncronAdd(\"stripe-products\", \"*/2 * * * *\", () => {\n const utils = require(`${__hooks}/utils.js`);\n utils.triggerJob(\"/api/stripe/sync/products\");\n});\n\ncronAdd(\"stripe-prices\", \"*/2 * * * *\", () => {\n const utils = require(`${__hooks}/utils.js`);\n utils.triggerJob(\"/api/stripe/sync/prices\");\n});\n", Kc = "/// <reference path=\"../types.d.ts\" />\n\nmodule.exports = {\n triggerJob: (jobUrl) => {\n $http.send({\n method: \"POST\",\n url: `${$app.settings().meta.appURL}${jobUrl}`,\n headers: {\n Authorization: `Bearer ${$os.getenv(\"INTERNAL_JOB_SECRET\")}`,\n },\n });\n },\n};\n", qc = "<script lang=\"ts\">\n import type { Stripe } from '@stripe/stripe-js';\n import { Button } from '$lib/components/ui/button';\n import * as Dialog from '$lib/components/ui/dialog';\n import { toast } from 'svelte-sonner';\n import { page } from '$app/state';\n import { invalidate } from '$app/navigation';\n\n interface Props {\n stripe: Stripe | null;\n open: boolean;\n amount: number;\n currency: string;\n brand?: string;\n last4?: string;\n clientSecret?: string;\n onopenchange: (open: boolean) => void;\n onsuccess: () => void;\n }\n\n let {\n stripe,\n open = $bindable(),\n amount,\n currency,\n brand,\n last4,\n clientSecret,\n onopenchange,\n onsuccess\n }: Props = $props();\n\n const brandNames = {\n amex: 'American Express',\n cartes_bancaires: 'Cartes Bancaires',\n diners: 'Diners',\n discover: 'Discover',\n eftpos_au: 'Eftpos Au',\n jcb: 'Jcb',\n link: 'Link',\n mastercard: 'Mastercard',\n unionpay: 'Unionpay',\n visa: 'Visa',\n unknown: 'Unknown'\n };\n\n let isProcessing = $state(false);\n\n let amountFormatted = $derived.by(() => {\n let formatter = new Intl.NumberFormat('en-US', { style: 'currency', currency: currency });\n return formatter.format(amount / 100);\n });\n\n const handleOpenChangeComplete = (isOpen: boolean) => {\n if (!isOpen) {\n resetDialog();\n }\n onopenchange(isOpen);\n };\n\n function resetDialog() {\n open = false;\n isProcessing = false;\n }\n\n async function handlePaymentMethod() {\n if (!stripe || !clientSecret) return;\n\n isProcessing = true;\n\n try {\n const { error: confirmError } = await stripe.confirmPayment({\n clientSecret,\n confirmParams: {\n return_url: page.url.toString()\n },\n redirect: 'if_required'\n });\n\n if (confirmError) {\n toast.error(confirmError.message || 'Failed to pay for your purchase');\n return;\n }\n\n await invalidate('app:billing');\n toast.success('Payment successful');\n onsuccess();\n resetDialog();\n } catch (err) {\n console.error('Error paying for your purchase:', err);\n toast.error('Failed to pay for your purchase');\n } finally {\n isProcessing = false;\n }\n }\n<\/script>\n\n<Dialog.Root bind:open onOpenChangeComplete={handleOpenChangeComplete}>\n <Dialog.Content class=\"sm:max-w-[500px]\">\n <Dialog.Header>\n <Dialog.Title>Confirm payment</Dialog.Title>\n <Dialog.Description>\n Are you sure you want to pay {amountFormatted} with your\n {brandNames[brand as keyof typeof brandNames]}\n credit card ending in **** {last4}?\n </Dialog.Description>\n </Dialog.Header>\n <Dialog.Footer>\n <Button variant=\"outline\" onclick={resetDialog} disabled={isProcessing}>Cancel</Button>\n <Button onclick={handlePaymentMethod} disabled={isProcessing}>\n {isProcessing ? 'Processing...' : 'Pay Now'}\n </Button>\n </Dialog.Footer>\n </Dialog.Content>\n</Dialog.Root>\n", Jc = "<script lang=\"ts\">\n import { Button } from '$lib/components/ui/button';\n import PaymentDialog from '$lib/components/payments/payment-dialog.svelte';\n import ConfirmDialog from '$lib/components/payments/confirm-dialog.svelte';\n import { useStripe } from '$lib/components/payments/use-stripe.svelte';\n import { usePaymentIntent } from '$lib/components/payments/use-payment-intent.svelte';\n import type { ButtonProps } from '$lib/components/ui/button';\n\n interface Props {\n priceId: string;\n user?: { email: string; name: string } | null;\n disabled?: boolean;\n isProcessing?: boolean;\n label?: string;\n processingLabel?: string;\n onsuccess?: () => void;\n }\n\n let {\n priceId,\n user,\n disabled = false,\n isProcessing = false,\n label = 'Purchase',\n processingLabel = 'Processing...',\n onsuccess,\n ...rest\n }: Props & ButtonProps = $props();\n\n const stripeManager = useStripe();\n const paymentIntentManager = usePaymentIntent();\n\n let mode = $state<'payment' | 'confirm'>('payment');\n let showDialog = $state(false);\n let amount = $state<number>(0);\n let currency = $state<string>('usd');\n let clientSecret = $state<string>();\n let brand = $state<string>();\n let last4 = $state<string>();\n\n async function handleBuyClick() {\n const result = await paymentIntentManager.fetchPaymentIntent({\n priceId\n });\n\n if (!result) return;\n\n if (result.type === 'confirm') {\n mode = 'confirm';\n brand = result.brand;\n last4 = result.last4;\n } else if (result.type === 'payment') {\n mode = 'payment';\n }\n\n amount = result.amount || 0;\n currency = result.currency || 'usd';\n clientSecret = result.clientSecret;\n showDialog = true;\n }\n\n function handleDialogOpenChange(open: boolean) {\n showDialog = open;\n }\n\n function handlePaymentSuccess() {\n onsuccess?.();\n }\n<\/script>\n\n<Button disabled={disabled || isProcessing} onclick={handleBuyClick} {...rest}>\n {#if isProcessing}\n {processingLabel}\n {:else}\n {label}\n {/if}\n</Button>\n\n{#if mode === 'confirm'}\n <ConfirmDialog\n bind:open={showDialog}\n stripe={stripeManager.stripe}\n {amount}\n {currency}\n {brand}\n {last4}\n {clientSecret}\n onopenchange={handleDialogOpenChange}\n onsuccess={handlePaymentSuccess}\n />\n{:else if mode === 'payment'}\n <PaymentDialog\n bind:open={showDialog}\n stripe={stripeManager.stripe}\n {amount}\n {currency}\n {clientSecret}\n {user}\n onopenchange={handleDialogOpenChange}\n onsuccess={handlePaymentSuccess}\n />\n{/if}\n", Yc = "<script lang=\"ts\">\n import type { Stripe, StripeElements } from '@stripe/stripe-js';\n import { Button } from '$lib/components/ui/button';\n import * as Dialog from '$lib/components/ui/dialog';\n import { Input } from '$lib/components/ui/input';\n import { Label } from '$lib/components/ui/label';\n import { toast } from 'svelte-sonner';\n import { page } from '$app/state';\n import { invalidate } from '$app/navigation';\n import StripePaymentForm from './stripe-payment-form.svelte';\n\n interface Props {\n stripe: Stripe | null;\n open: boolean;\n amount: number;\n currency: string;\n clientSecret?: string;\n user?: { email: string; name: string } | null;\n onopenchange: (open: boolean) => void;\n onsuccess: () => void;\n }\n\n let {\n stripe,\n open = $bindable(),\n amount,\n currency,\n clientSecret,\n user = null,\n onopenchange,\n onsuccess\n }: Props = $props();\n\n let isProcessing = $state(false);\n let cardComplete = $state(false);\n let savePaymentMethod = $state(false);\n let email = $state<string>();\n let formRef = $state<{\n getElements: () => StripeElements | null;\n }>();\n\n let amountFormatted = $derived.by(() => {\n let formatter = new Intl.NumberFormat('en-US', { style: 'currency', currency: currency });\n return formatter.format(amount / 100);\n });\n\n const handleOpenChangeComplete = (isOpen: boolean) => {\n if (!isOpen) {\n resetDialog();\n }\n onopenchange(isOpen);\n };\n\n function resetDialog() {\n open = false;\n isProcessing = false;\n cardComplete = false;\n }\n\n function handleCardChange(complete: boolean) {\n cardComplete = complete;\n }\n\n async function handlePaymentMethod() {\n if (!stripe || !formRef || !cardComplete || !clientSecret) return;\n\n const elements = formRef.getElements();\n if (!elements) return;\n\n isProcessing = true;\n\n try {\n const { error: submitError } = await elements.submit();\n if (submitError) {\n toast.error(submitError.message || 'Failed to pay for your purchase');\n return;\n }\n\n const { error: confirmError } = await stripe.confirmPayment({\n elements,\n clientSecret,\n confirmParams: {\n return_url: page.url.toString(),\n payment_method_data: {\n billing_details: {\n email: email || user?.email\n },\n allow_redisplay: savePaymentMethod ? 'always' : 'unspecified'\n }\n },\n redirect: 'if_required'\n });\n\n if (confirmError) {\n toast.error(confirmError.message || 'Failed to pay for your purchase');\n return;\n }\n\n await invalidate('app:billing');\n toast.success('Payment successful');\n onsuccess();\n resetDialog();\n } catch (err) {\n console.error('Error paying for your purchase:', err);\n toast.error('Failed to pay for your purchase');\n } finally {\n isProcessing = false;\n }\n }\n<\/script>\n\n<Dialog.Root bind:open onOpenChangeComplete={handleOpenChangeComplete}>\n <Dialog.Content class=\"sm:max-w-[500px]\">\n <Dialog.Header>\n <Dialog.Title>{amountFormatted}</Dialog.Title>\n <Dialog.Description>Enter your card details to pay for your purchase.</Dialog.Description>\n </Dialog.Header>\n {#if !user}\n <div class=\"space-y-2\">\n <Label for=\"email\">Email</Label>\n <Input type=\"email\" bind:value={email} />\n </div>\n {/if}\n <div>\n {#if stripe && open}\n <StripePaymentForm\n bind:this={formRef}\n mode=\"payment\"\n {stripe}\n {amount}\n {currency}\n {savePaymentMethod}\n {user}\n onchange={handleCardChange}\n />\n {/if}\n </div>\n {#if user}\n <div class=\"flex items-center gap-2\">\n <input type=\"checkbox\" id=\"savePaymentMethod\" bind:checked={savePaymentMethod} />\n <label for=\"savePaymentMethod\" class=\"text-sm text-muted-foreground\">\n Save payment method for future purchases\n </label>\n </div>\n {/if}\n <Dialog.Footer>\n <Button variant=\"outline\" onclick={resetDialog} disabled={isProcessing}>Cancel</Button>\n <Button onclick={handlePaymentMethod} disabled={!cardComplete || isProcessing}>\n {isProcessing ? 'Processing...' : 'Pay Now'}\n </Button>\n </Dialog.Footer>\n </Dialog.Content>\n</Dialog.Root>\n", Xc = "export const TERMS_AUTO = {\n applePay: \"auto\" as const,\n auBecsDebit: \"auto\" as const,\n bancontact: \"auto\" as const,\n card: \"auto\" as const,\n cashapp: \"auto\" as const,\n googlePay: \"auto\" as const,\n ideal: \"auto\" as const,\n paypal: \"auto\" as const,\n sepaDebit: \"auto\" as const,\n sofort: \"auto\" as const,\n usBankAccount: \"auto\" as const,\n};\n\nexport const TERMS_NEVER = {\n applePay: \"never\" as const,\n auBecsDebit: \"never\" as const,\n bancontact: \"never\" as const,\n card: \"never\" as const,\n cashapp: \"never\" as const,\n googlePay: \"never\" as const,\n ideal: \"never\" as const,\n paypal: \"never\" as const,\n sepaDebit: \"never\" as const,\n sofort: \"never\" as const,\n usBankAccount: \"never\" as const,\n};\n", Zc = "<script lang=\"ts\">\n import type {\n Stripe,\n StripeElements,\n StripePaymentElement,\n StripeElementsOptionsMode\n } from '@stripe/stripe-js';\n import { mode as modeWatcher } from 'mode-watcher';\n import { TERMS_AUTO, TERMS_NEVER } from './stripe-constants';\n import { onMount } from 'svelte';\n\n interface Props {\n stripe: Stripe;\n mode: 'payment' | 'setup';\n amount?: number;\n currency?: string;\n savePaymentMethod?: boolean;\n user?: { email: string; name: string } | null;\n onchange: (complete: boolean) => void;\n }\n\n let {\n stripe,\n mode,\n amount = 0,\n currency = 'usd',\n savePaymentMethod = false,\n user,\n onchange\n }: Props = $props();\n\n let cardContainer = $state<HTMLDivElement | null>(null);\n let elements = $state<StripeElements | null>(null);\n let paymentElement = $state<StripePaymentElement | null>(null);\n\n function initializeElements() {\n if (!stripe) return;\n\n // Clean up previous elements\n if (paymentElement) {\n paymentElement.destroy();\n paymentElement = null;\n }\n\n const appearance = {\n theme: modeWatcher.current === 'dark' ? ('night' as const) : ('stripe' as const),\n inputs: 'condensed' as const,\n labels: 'floating' as const\n };\n\n elements = stripe.elements({\n mode,\n appearance,\n currency,\n ...(mode === 'payment' && {\n amount: amount\n }),\n ...(user || mode === 'setup'\n ? {\n setupFutureUsage: 'off_session' as const\n }\n : {})\n } as StripeElementsOptionsMode);\n\n paymentElement = elements.create('payment', {\n layout: 'tabs',\n defaultValues: {\n billingDetails: {\n email: user?.email,\n name: user?.name\n }\n },\n terms: savePaymentMethod ? TERMS_AUTO : TERMS_NEVER\n });\n\n if (cardContainer && paymentElement) {\n paymentElement.mount(cardContainer);\n paymentElement.on('change', (event: any) => {\n onchange(event.complete);\n });\n }\n }\n\n // Initialize elements when component mounts\n onMount(() => {\n initializeElements();\n\n return () => {\n if (paymentElement) {\n paymentElement.destroy();\n }\n };\n });\n\n // Update terms when savePaymentMethod changes\n $effect(() => {\n if (paymentElement) {\n paymentElement.update({\n terms: savePaymentMethod ? TERMS_AUTO : TERMS_NEVER\n });\n }\n });\n\n export function getElements() {\n return elements;\n }\n<\/script>\n\n<div bind:this={cardContainer}></div>\n", Qc = "import { toast } from \"svelte-sonner\";\n\nexport interface PaymentIntentResult {\n type: \"payment\" | \"confirm\";\n amount?: number;\n currency?: string;\n clientSecret?: string;\n brand?: string;\n last4?: string;\n}\n\nexport function usePaymentIntent() {\n let isLoading = $state(false);\n\n async function fetchPaymentIntent({\n priceId,\n }: {\n priceId: string;\n }): Promise<PaymentIntentResult | null> {\n isLoading = true;\n\n const res = await fetch(\"/api/stripe/payment-intent\", {\n method: \"POST\",\n body: JSON.stringify({\n priceId: priceId,\n }),\n headers: {\n \"Content-Type\": \"application/json\",\n },\n });\n\n if (!res.ok) {\n toast.error(\"Failed to initialize payment\");\n return null;\n }\n\n return res.json();\n }\n\n async function fetchSetupIntent(): Promise<PaymentIntentResult | null> {\n isLoading = true;\n\n const res = await fetch(\"/api/stripe/setup-intent\", {\n method: \"POST\",\n });\n\n if (!res.ok) {\n toast.error(\"Failed to initialize setup\");\n return null;\n }\n\n return res.json();\n }\n\n return {\n get isLoading() {\n return isLoading;\n },\n fetchPaymentIntent,\n fetchSetupIntent,\n };\n}\n", $c = "import { loadStripe, type Stripe } from \"@stripe/stripe-js\";\nimport { toast } from \"svelte-sonner\";\nimport { env } from \"$env/dynamic/public\";\n\nexport function useStripe() {\n let stripe = $state<Stripe | null>(null);\n let isLoading = $state(true);\n let error = $state<string | null>(null);\n\n async function initialize() {\n try {\n stripe = await loadStripe(env.PUBLIC_STRIPE_PUBLISHABLE_KEY);\n isLoading = false;\n } catch (err) {\n console.error(\"Failed to load Stripe:\", err);\n error = \"Failed to initialize payment system\";\n toast.error(\"Failed to initialize payment system\");\n isLoading = false;\n }\n }\n\n // Auto-initialize\n initialize();\n\n return {\n get stripe() {\n return stripe;\n },\n get isLoading() {\n return isLoading;\n },\n get error() {\n return error;\n },\n };\n}\n", el = "import { env } from \"$env/dynamic/private\";\nimport Stripe from \"stripe\";\n\nconst stripe = new Stripe(env.STRIPE_SECRET_KEY, {\n apiVersion: \"2026-04-22.dahlia\",\n});\n\nexport default stripe;\n", tl = "import { json } from \"@sveltejs/kit\";\nimport stripe from \"$lib/stripe\";\nimport type { Stripe } from \"stripe\";\n\nconst createPaymentIntent = async (price: Stripe.Price) => {\n if (price.unit_amount === null || price.unit_amount === undefined) {\n console.error(\"Price does not have a per unit amount\");\n throw new Error(\"Price does not have a per unit amount\");\n }\n\n const intent = await stripe.paymentIntents.create({\n amount: price.unit_amount,\n currency: price.currency,\n automatic_payment_methods: {\n enabled: true,\n allow_redirects: \"never\",\n },\n });\n\n if (!intent.client_secret) {\n console.error(\"Payment intent created without client secret\");\n throw new Error(\"Failed to create payment intent\");\n }\n\n return {\n type: \"payment\",\n clientSecret: intent.client_secret,\n amount: price.unit_amount,\n currency: price.currency,\n };\n};\n\nexport const POST = async ({ request, locals }) => {\n let body;\n try {\n body = await request.json();\n } catch (error) {\n console.error(\"Invalid JSON in request body\");\n return json({ error: \"Invalid request body\" }, { status: 400 });\n }\n\n const { priceId } = body as { priceId?: string };\n\n // Validate required fields\n if (!priceId || typeof priceId !== \"string\" || priceId === \"\") {\n console.error(\"Missing or invalid priceId\");\n return json({ error: \"Price ID is required\" }, { status: 400 });\n }\n\n // Retrieve price from Stripe\n let price;\n try {\n price = await stripe.prices.retrieve(priceId);\n } catch (error) {\n console.error(\"Failed to retrieve price from Stripe:\", priceId);\n return json(\n { error: \"Invalid price ID or price not found\" },\n { status: 404 },\n );\n }\n\n // Validate price is active\n if (!price.active) {\n console.error(\"Price is not active:\", priceId);\n return json(\n { error: \"This price is no longer available\" },\n { status: 400 },\n );\n }\n\n try {\n const res = await createPaymentIntent(price);\n return json(res, { status: 200 });\n } catch (error) {\n console.error(\"Error creating payment intent for price:\", priceId);\n const errorMessage =\n error instanceof Error\n ? error.message\n : \"Failed to create payment intent\";\n return json({ error: errorMessage }, { status: 500 });\n }\n};\n", nl = "import { describe, it, expect, beforeAll } from \"vitest\";\nimport type { Match } from \"@velastack/pocketbase\";\nimport type { RouteId } from \"./$types\";\nimport stripe from \"$lib/stripe\";\nimport type Stripe from \"stripe\";\n\ndescribe(\"POST /api/stripe/payment-intent\", () => {\n let product: Stripe.Product;\n let activePrice: Stripe.Price;\n let inactivePrice: Stripe.Price;\n\n beforeAll(async () => {\n const productName = \"Test Product - Payment Intent\";\n const products = await stripe.products.search({\n query: `name:\"${productName}\" AND metadata[\"test\"]:\"true\"`,\n limit: 1,\n });\n\n if (products.data.length > 0) {\n product = products.data[0];\n\n const prices = await stripe.prices.list({\n product: product.id,\n active: true,\n limit: 1,\n });\n\n if (prices.data.length > 0) {\n activePrice = prices.data[0];\n }\n\n const inactivePrices = await stripe.prices.list({\n product: product.id,\n active: false,\n limit: 1,\n });\n\n if (inactivePrices.data.length > 0) {\n inactivePrice = inactivePrices.data[0];\n }\n }\n\n // Create if not found or no active price\n if (!product) {\n product = await stripe.products.create({\n name: productName,\n metadata: {\n test: \"true\",\n test_type: \"payment-intent\",\n },\n });\n }\n\n if (!activePrice) {\n activePrice = await stripe.prices.create({\n product: product.id,\n unit_amount: 1000,\n currency: \"usd\",\n metadata: {\n test: \"true\",\n test_type: \"payment-intent\",\n },\n });\n }\n\n if (!inactivePrice) {\n inactivePrice = await stripe.prices.create({\n product: product.id,\n unit_amount: 2000,\n currency: \"usd\",\n active: false,\n metadata: {\n test: \"true\",\n test_type: \"payment-intent-inactive\",\n },\n });\n }\n });\n\n describe(\"Request validation\", () => {\n it(\"should return 400 if request body is not valid JSON\", async (context) => {\n const response = await context.agent\n .post(\"/api/stripe/payment-intent\" satisfies Match<RouteId>)\n .set(\"Content-Type\", \"application/json\")\n .send(\"invalid json\");\n\n expect(response.status).toBe(400);\n expect(response.body.error).toBe(\"Invalid request body\");\n });\n\n it(\"should return 400 if priceId is missing\", async (context) => {\n const response = await context.agent\n .post(\"/api/stripe/payment-intent\" satisfies Match<RouteId>)\n .send({});\n\n expect(response.status).toBe(400);\n expect(response.body.error).toBe(\"Price ID is required\");\n });\n\n it(\"should return 400 if priceId is not a string\", async (context) => {\n const response = await context.agent\n .post(\"/api/stripe/payment-intent\" satisfies Match<RouteId>)\n .send({ priceId: 12345 });\n\n expect(response.status).toBe(400);\n expect(response.body.error).toBe(\"Price ID is required\");\n });\n\n it(\"should return 400 if priceId is an empty string\", async (context) => {\n const response = await context.agent\n .post(\"/api/stripe/payment-intent\" satisfies Match<RouteId>)\n .send({ priceId: \"\" });\n\n expect(response.status).toBe(400);\n expect(response.body.error).toBe(\"Price ID is required\");\n });\n\n it(\"should return 404 if price does not exist\", async (context) => {\n const response = await context.agent\n .post(\"/api/stripe/payment-intent\" satisfies Match<RouteId>)\n .send({ priceId: \"price_nonexistent123\" });\n\n expect(response.status).toBe(404);\n expect(response.body.error).toBe(\"Invalid price ID or price not found\");\n });\n\n it(\"should return 400 if price is not active\", async (context) => {\n const response = await context.agent\n .post(\"/api/stripe/payment-intent\" satisfies Match<RouteId>)\n .send({ priceId: inactivePrice.id });\n\n expect(response.status).toBe(400);\n expect(response.body.error).toBe(\"This price is no longer available\");\n });\n });\n\n describe(\"Guest user (unauthenticated)\", () => {\n it(\"should create payment intent for guest user\", async (context) => {\n const response = await context.request\n .post(\"/api/stripe/payment-intent\" satisfies Match<RouteId>)\n .send({ priceId: activePrice.id });\n\n expect(response.status).toBe(200);\n expect(response.body.type).toBe(\"payment\");\n expect(response.body.clientSecret).toBeDefined();\n expect(response.body.amount).toBe(1000);\n expect(response.body.currency).toBe(\"usd\");\n expect(response.body.brand).toBeUndefined();\n expect(response.body.last4).toBeUndefined();\n\n // Verify the payment intent was created in Stripe\n const intentId = response.body.clientSecret.split(\"_secret_\")[0];\n const intent = await stripe.paymentIntents.retrieve(intentId);\n expect(intent.amount).toBe(1000);\n expect(intent.currency).toBe(\"usd\");\n expect(intent.customer).toBeNull();\n\n // Clean up\n await stripe.paymentIntents.cancel(intent.id);\n });\n });\n});\n", rl = "import { json } from \"@sveltejs/kit\";\nimport stripe from \"$lib/stripe\";\nimport { env } from \"$env/dynamic/private\";\n\nexport const POST = async ({ request, locals }) => {\n const authHeader = request.headers.get(\"Authorization\");\n if (authHeader !== `Bearer ${env.INTERNAL_JOB_SECRET}`) {\n return json({ error: \"Unauthorized\" }, { status: 401 });\n }\n\n const prices = await stripe.prices.list();\n\n for (const price of prices.data) {\n try {\n await locals.admin\n .collection(\"stripe_prices\")\n .getFirstListItem(`id = \"${price.id}\"`);\n continue;\n } catch {}\n\n await locals.admin.collection(\"stripe_prices\").create({\n id: price.id,\n billing_scheme: price.billing_scheme,\n currency: price.currency,\n product: price.product,\n recurring: price.recurring,\n type: price.type,\n unit_amount: price.unit_amount,\n active: price.active,\n });\n }\n\n console.log(\"Prices synced\");\n return json({ message: \"Prices synced\" });\n};\n", il = "import { json } from \"@sveltejs/kit\";\nimport stripe from \"$lib/stripe\";\nimport { env } from \"$env/dynamic/private\";\n\nexport const POST = async ({ request, locals }) => {\n const authHeader = request.headers.get(\"Authorization\");\n if (authHeader !== `Bearer ${env.INTERNAL_JOB_SECRET}`) {\n return json({ error: \"Unauthorized\" }, { status: 401 });\n }\n\n const products = await stripe.products.list();\n\n for (const product of products.data) {\n try {\n await locals.admin\n .collection(\"stripe_products\")\n .getFirstListItem(`id = \"${product.id}\"`);\n continue;\n } catch {}\n\n await locals.admin.collection(\"stripe_products\").create({\n id: product.id,\n name: product.name,\n active: product.active,\n default_price: product.default_price,\n });\n }\n\n console.log(\"Products synced\");\n return json({ message: \"Products synced\" });\n};\n", al = "import Stripe from \"stripe\";\nimport { json } from \"@sveltejs/kit\";\nimport { env } from \"$env/dynamic/private\";\nimport stripe from \"$lib/stripe\";\nimport { handlePaymentIntentSucceeded } from \"./handlers/payment-intent/succeeded\";\n\nconst processedEvents = new Set<string>();\n\nasync function verifyWebhookSignature(\n request: Request,\n webhookSecret: string,\n): Promise<Stripe.Event> {\n const body = await request.text();\n const signature = request.headers.get(\"stripe-signature\");\n\n if (!signature) {\n throw new Error(\"Missing stripe-signature header\");\n }\n\n if (!webhookSecret) {\n throw new Error(\"Missing webhook secret\");\n }\n\n try {\n return stripe.webhooks.constructEvent(body, signature, webhookSecret);\n } catch (err) {\n console.error(\"Webhook signature verification failed:\", err);\n throw new Error(\"Invalid signature\");\n }\n}\n\nexport const POST = async ({ request, locals }) => {\n try {\n const event = await verifyWebhookSignature(\n request,\n env.STRIPE_WEBHOOK_SECRET,\n );\n\n if (processedEvents.has(event.id)) {\n console.log(`Event ${event.id} already processed, skipping`);\n return json({ received: true, message: \"Event already processed\" });\n }\n\n processedEvents.add(event.id);\n\n console.log(`Processing webhook event: ${event.type} (${event.id})`);\n\n switch (event.type) {\n case \"payment_intent.succeeded\":\n await handlePaymentIntentSucceeded(event.data.object, locals);\n break;\n\n default:\n console.log(`Unhandled event type: ${event.type}`);\n }\n\n return json({\n received: true,\n eventId: event.id,\n eventType: event.type,\n });\n } catch (error) {\n console.error(\"Webhook processing error:\", error);\n\n return json(\n {\n error: \"Webhook processing failed\",\n message: error instanceof Error ? error.message : \"Unknown error\",\n },\n { status: 400 },\n );\n }\n};\n", ol = "import { describe, it, expect } from \"vitest\";\nimport stripe from \"$lib/stripe\";\nimport { handlePaymentIntentSucceeded } from \"./succeeded\";\n\ndescribe(\"payment_intent.succeeded\", () => {\n it(\"handles a payment intent successfully\", async (context) => {\n const paymentIntent = await stripe.paymentIntents.create({\n amount: 2000,\n currency: \"usd\",\n });\n const locals = { admin: context.admin } as App.Locals;\n const result = await handlePaymentIntentSucceeded(paymentIntent, locals);\n\n expect(result).toEqual({});\n });\n});\n", sl = "import Stripe from \"stripe\";\n\n/**\n * Handles payment_intent.succeeded event\n */\nexport async function handlePaymentIntentSucceeded(\n paymentIntent: Stripe.PaymentIntent,\n locals: App.Locals,\n) {\n return {};\n}\n", cl = "import { describe, it, expect } from \"vitest\";\nimport type { RouteId } from \"./$types\";\nimport type { Match } from \"@velastack/pocketbase\";\nimport type Stripe from \"stripe\";\nimport stripe from \"$lib/stripe\";\n\ndescribe(\"POST /webhooks/stripe\", () => {\n it(\"accepts valid webhook signature\", async (context) => {\n const event = {\n id: `evt_test_${Date.now()}`,\n object: \"event\",\n api_version: \"2024-11-20.acacia\",\n created: Math.floor(Date.now() / 1000),\n type: \"test.event\",\n data: {\n object: {},\n },\n livemode: false,\n pending_webhooks: 0,\n request: {\n id: null,\n idempotency_key: null,\n },\n } as unknown as Stripe.Event;\n\n const payload = JSON.stringify(event);\n const webhookSecret = process.env.STRIPE_WEBHOOK_SECRET!;\n\n const signature = stripe.webhooks.generateTestHeaderString({\n payload,\n secret: webhookSecret,\n });\n\n const response = await context.request\n .post(\"/webhooks/stripe\" satisfies Match<RouteId>)\n .set(\"stripe-signature\", signature)\n .send(payload)\n .set(\"Content-Type\", \"application/json\");\n\n expect(response.status).toBe(200);\n expect(response.body.received).toBe(true);\n expect(response.body.eventId).toBe(event.id);\n expect(response.body.eventType).toBe(\"test.event\");\n });\n\n it(\"rejects invalid webhook signature\", async (context) => {\n const event = {\n id: `evt_test_${Date.now()}`,\n object: \"event\",\n api_version: \"2024-11-20.acacia\",\n created: Math.floor(Date.now() / 1000),\n type: \"test.event\",\n data: {\n object: {},\n },\n livemode: false,\n pending_webhooks: 0,\n request: {\n id: null,\n idempotency_key: null,\n },\n } as unknown as Stripe.Event;\n\n const payload = JSON.stringify(event);\n\n const response = await context.request\n .post(\"/webhooks/stripe\" satisfies Match<RouteId>)\n .set(\"stripe-signature\", \"invalid_signature\")\n .send(payload)\n .set(\"Content-Type\", \"application/json\");\n\n expect(response.status).toBe(400);\n expect(response.body.error).toBe(\"Webhook processing failed\");\n });\n\n it(\"rejects request without signature header\", async (context) => {\n const event = {\n id: `evt_test_${Date.now()}`,\n object: \"event\",\n api_version: \"2024-11-20.acacia\",\n created: Math.floor(Date.now() / 1000),\n type: \"test.event\",\n data: {\n object: {},\n },\n livemode: false,\n pending_webhooks: 0,\n request: {\n id: null,\n idempotency_key: null,\n },\n } as unknown as Stripe.Event;\n\n const payload = JSON.stringify(event);\n\n const response = await context.request\n .post(\"/webhooks/stripe\" satisfies Match<RouteId>)\n .send(payload)\n .set(\"Content-Type\", \"application/json\");\n\n expect(response.status).toBe(400);\n expect(response.body.error).toBe(\"Webhook processing failed\");\n expect(response.body.message).toBe(\"Missing stripe-signature header\");\n });\n\n it(\"handles duplicate webhook events\", async (context) => {\n const event = {\n id: `evt_test_${Date.now()}`,\n object: \"event\",\n api_version: \"2024-11-20.acacia\",\n created: Math.floor(Date.now() / 1000),\n type: \"test.event\",\n data: {\n object: {},\n },\n livemode: false,\n pending_webhooks: 0,\n request: {\n id: null,\n idempotency_key: null,\n },\n } as unknown as Stripe.Event;\n\n const payload = JSON.stringify(event);\n const webhookSecret = process.env.STRIPE_WEBHOOK_SECRET!;\n const signature = stripe.webhooks.generateTestHeaderString({\n payload,\n secret: webhookSecret,\n });\n\n // Send first webhook\n const response1 = await context.request\n .post(\"/webhooks/stripe\" satisfies Match<RouteId>)\n .set(\"stripe-signature\", signature)\n .send(payload)\n .set(\"Content-Type\", \"application/json\");\n\n expect(response1.status).toBe(200);\n expect(response1.body.received).toBe(true);\n\n // Send duplicate webhook\n const response2 = await context.request\n .post(\"/webhooks/stripe\" satisfies Match<RouteId>)\n .set(\"stripe-signature\", signature)\n .send(payload)\n .set(\"Content-Type\", \"application/json\");\n\n expect(response2.status).toBe(200);\n expect(response2.body.received).toBe(true);\n expect(response2.body.message).toBe(\"Event already processed\");\n });\n});\n", ll = "/// <reference path=\"../types.d.ts\" />\n\ncronAdd(\"stripe-products\", \"*/2 * * * *\", () => {\n const utils = require(`${__hooks}/utils.js`);\n utils.triggerJob(\"/api/stripe/sync/products\");\n});\n\ncronAdd(\"stripe-prices\", \"*/2 * * * *\", () => {\n const utils = require(`${__hooks}/utils.js`);\n utils.triggerJob(\"/api/stripe/sync/prices\");\n});\n\ncronAdd(\"stripe-customers\", \"* * * * *\", () => {\n const utils = require(`${__hooks}/utils.js`);\n utils.triggerJob(\"/api/stripe/sync/customers\");\n});\n", ul = "/// <reference path=\"../types.d.ts\" />\n\nmodule.exports = {\n triggerJob: (jobUrl) => {\n $http.send({\n method: \"POST\",\n url: `${$app.settings().meta.appURL}${jobUrl}`,\n headers: {\n Authorization: `Bearer ${$os.getenv(\"INTERNAL_JOB_SECRET\")}`,\n },\n });\n },\n};\n", dl = "<script lang=\"ts\">\n import { Button } from '$lib/components/ui/button';\n import SetupDialog from '$lib/components/payments/setup-dialog.svelte';\n import { useStripe } from '$lib/components/payments/use-stripe.svelte';\n import { usePaymentIntent } from '$lib/components/payments/use-payment-intent.svelte';\n\n interface Props {\n disabled?: boolean;\n isProcessing?: boolean;\n label?: string;\n processingLabel?: string;\n onsuccess?: () => void;\n }\n\n let {\n disabled = false,\n isProcessing = false,\n label,\n processingLabel,\n onsuccess\n }: Props = $props();\n\n const stripeManager = useStripe();\n const paymentIntentManager = usePaymentIntent();\n\n let showDialog = $state(false);\n let clientSecret = $state<string>();\n\n async function handleSetupClick() {\n const result = await paymentIntentManager.fetchSetupIntent();\n\n if (!result) return;\n\n clientSecret = result.clientSecret;\n showDialog = true;\n }\n\n function handleDialogOpenChange(open: boolean) {\n showDialog = open;\n }\n\n function handlePaymentSuccess() {\n onsuccess?.();\n }\n<\/script>\n\n<Button disabled={disabled || isProcessing} onclick={handleSetupClick}>\n {#if isProcessing}\n {processingLabel}\n {:else}\n {label}\n {/if}\n</Button>\n\n<SetupDialog\n bind:open={showDialog}\n stripe={stripeManager.stripe}\n {clientSecret}\n onopenchange={handleDialogOpenChange}\n onsuccess={handlePaymentSuccess}\n/>\n", fl = "<script lang=\"ts\">\n import type { Stripe, StripeElements } from '@stripe/stripe-js';\n import { Button } from '$lib/components/ui/button';\n import * as Dialog from '$lib/components/ui/dialog';\n import { toast } from 'svelte-sonner';\n import { page } from '$app/state';\n import { invalidate } from '$app/navigation';\n import StripePaymentForm from './stripe-payment-form.svelte';\n\n interface Props {\n stripe: Stripe | null;\n open: boolean;\n clientSecret?: string;\n onopenchange: (open: boolean) => void;\n onsuccess: () => void;\n }\n\n let { stripe, open = $bindable(), clientSecret, onopenchange, onsuccess }: Props = $props();\n\n let isProcessing = $state(false);\n let cardComplete = $state(false);\n let formRef = $state<{\n getElements: () => StripeElements | null;\n }>();\n\n const handleOpenChangeComplete = (isOpen: boolean) => {\n if (!isOpen) {\n resetDialog();\n }\n onopenchange(isOpen);\n };\n\n function resetDialog() {\n open = false;\n isProcessing = false;\n cardComplete = false;\n }\n\n function handleCardChange(complete: boolean) {\n cardComplete = complete;\n }\n\n async function handleSetupPaymentMethod() {\n if (!stripe || !formRef || !cardComplete || !clientSecret) return;\n\n const elements = formRef.getElements();\n if (!elements) return;\n\n isProcessing = true;\n\n try {\n const { error: submitError } = await elements.submit();\n if (submitError) {\n toast.error(submitError.message || 'Failed to add payment method');\n return;\n }\n\n const { error: confirmError } = await stripe.confirmSetup({\n elements,\n clientSecret,\n confirmParams: {\n return_url: page.url.toString(),\n payment_method_data: {\n allow_redisplay: 'always'\n }\n },\n redirect: 'if_required'\n });\n\n if (confirmError) {\n toast.error(confirmError.message || 'Failed to add payment method');\n return;\n }\n\n await invalidate('app:billing');\n toast.success('Payment method added successfully');\n onsuccess();\n resetDialog();\n } catch (err) {\n console.error('Error adding payment method:', err);\n toast.error('Failed to add payment method');\n } finally {\n isProcessing = false;\n }\n }\n<\/script>\n\n<Dialog.Root bind:open onOpenChangeComplete={handleOpenChangeComplete}>\n <Dialog.Content class=\"sm:max-w-[500px]\">\n <Dialog.Header>\n <Dialog.Title>Add payment method</Dialog.Title>\n <Dialog.Description>Enter your card details to add a new payment method.</Dialog.Description>\n </Dialog.Header>\n <div>\n {#if stripe && open}\n <StripePaymentForm\n bind:this={formRef}\n mode=\"setup\"\n {stripe}\n onchange={handleCardChange}\n savePaymentMethod={true}\n />\n {/if}\n </div>\n <Dialog.Footer>\n <Button variant=\"outline\" onclick={resetDialog} disabled={isProcessing}>Cancel</Button>\n <Button onclick={handleSetupPaymentMethod} disabled={!cardComplete || isProcessing}>\n {isProcessing ? 'Processing...' : 'Add Card'}\n </Button>\n </Dialog.Footer>\n </Dialog.Content>\n</Dialog.Root>\n", pl = "export const load = async ({ parent }) => {\n const { breadcrumbs } = await parent();\n\n return {\n breadcrumbs: [...breadcrumbs, { title: \"Billing\", url: \"/billing\" }],\n };\n};\n", ml = "# Billing Page - Stripe Payment Methods\n\nThis billing page provides a modern UI for managing payment methods with Stripe.\n\n## Features\n\n✅ **Display Payment Methods** - Shows all saved cards with brand, last 4 digits, and expiration\n✅ **Add Payment Methods** - Secure card input using Stripe Elements\n✅ **Remove Payment Methods** - Delete cards with confirmation dialog\n✅ **Default Payment Method** - Set and display the default payment method\n✅ **Responsive Design** - Mobile-friendly layout\n✅ **Error Handling** - Toast notifications for user feedback\n\n## Current Status\n\nThe frontend is **fully functional** with mock data. To connect to your backend, follow the integration steps below.\n\n## Backend Integration\n\n### 1. Update Stripe Publishable Key\n\nIn `+page.svelte`, replace the placeholder with your actual Stripe publishable key:\n\n```typescript\nconst STRIPE_PUBLISHABLE_KEY = \"pk_test_YOUR_KEY_HERE\";\n```\n\nOr better yet, load it from environment variables:\n\n```typescript\nimport { env } from \"$env/dynamic/public\";\nconst STRIPE_PUBLISHABLE_KEY = env.PUBLIC_STRIPE_PUBLISHABLE_KEY;\n```\n\n### 2. Fetch Payment Methods on Load\n\nUpdate `+page.server.ts` to fetch payment methods:\n\n```typescript\nexport const load: PageServerLoad = async ({ locals }) => {\n const user = locals.user;\n\n if (!user?.stripeCustomerId) {\n return { paymentMethods: [] };\n }\n\n // Fetch payment methods from Stripe\n const stripe = await import(\"$lib/stripe\").then((m) => m.default);\n const paymentMethods = await stripe.paymentMethods.list({\n customer: user.stripeCustomerId,\n type: \"card\",\n });\n\n return {\n paymentMethods: paymentMethods.data.map((pm) => ({\n id: pm.id,\n brand: pm.card?.brand || \"unknown\",\n last4: pm.card?.last4 || \"0000\",\n expMonth: pm.card?.exp_month || 1,\n expYear: pm.card?.exp_year || 2025,\n isDefault: false, // You'll need to track this separately\n })),\n };\n};\n```\n\n### 3. Create API Endpoints\n\nCreate the following server endpoints:\n\n#### Add Payment Method: `+page.server.ts`\n\n```typescript\nexport const actions = {\n addPaymentMethod: async ({ request, locals }) => {\n const formData = await request.formData();\n const paymentMethodId = formData.get(\"paymentMethodId\");\n\n // Attach payment method to customer\n const stripe = await import(\"$lib/stripe\").then((m) => m.default);\n await stripe.paymentMethods.attach(paymentMethodId, {\n customer: locals.user.stripeCustomerId,\n });\n\n return { success: true };\n },\n\n removePaymentMethod: async ({ request, locals }) => {\n const formData = await request.formData();\n const paymentMethodId = formData.get(\"paymentMethodId\");\n\n // Detach payment method from customer\n const stripe = await import(\"$lib/stripe\").then((m) => m.default);\n await stripe.paymentMethods.detach(paymentMethodId);\n\n return { success: true };\n },\n\n setDefaultPaymentMethod: async ({ request, locals }) => {\n const formData = await request.formData();\n const paymentMethodId = formData.get(\"paymentMethodId\");\n\n // Update customer's default payment method\n const stripe = await import(\"$lib/stripe\").then((m) => m.default);\n await stripe.customers.update(locals.user.stripeCustomerId, {\n invoice_settings: {\n default_payment_method: paymentMethodId,\n },\n });\n\n return { success: true };\n },\n};\n```\n\n### 4. Update Frontend to Use Actions\n\nReplace the mock functions in `+page.svelte`:\n\n```typescript\nasync function handleAddPaymentMethod() {\n if (!stripe || !cardElement || !cardComplete) return;\n\n isProcessing = true;\n\n try {\n const { error, paymentMethod } = await stripe.createPaymentMethod({\n type: \"card\",\n card: cardElement,\n });\n\n if (error) {\n toast.error(error.message);\n return;\n }\n\n // Submit to your backend\n const formData = new FormData();\n formData.append(\"paymentMethodId\", paymentMethod.id);\n\n const response = await fetch(\"?/addPaymentMethod\", {\n method: \"POST\",\n body: formData,\n });\n\n if (response.ok) {\n toast.success(\"Payment method added\");\n // Reload page to fetch updated payment methods\n window.location.reload();\n }\n } finally {\n isProcessing = false;\n }\n}\n```\n\n## Security Considerations\n\n⚠️ **Important**: Never expose your Stripe secret key on the frontend\n✅ All sensitive operations should happen on your backend\n✅ Use Stripe's publishable key for frontend operations\n✅ Validate user permissions before modifying payment methods\n✅ Use HTTPS in production\n\n## Testing\n\nUse [Stripe's test cards](https://stripe.com/docs/testing) for testing:\n\n- **Success**: 4242 4242 4242 4242\n- **Decline**: 4000 0000 0000 0002\n- **Requires authentication**: 4000 0025 0000 3155\n\nUse any future expiration date and any 3-digit CVC.\n\n## Styling\n\nThe page uses Tailwind CSS and shadcn/ui components. All components are styled to match your existing design system with support for light/dark modes.\n\n### Stripe Elements Styling\n\nSince Stripe Elements render in an iframe, they cannot access CSS variables directly. Additionally, Stripe only accepts HEX, RGB, or HSL colors (not modern formats like OKLCH).\n\nThe implementation:\n\n1. **Creates temporary DOM elements** with CSS variables applied\n2. **Lets the browser compute colors** - converts OKLCH/HSL/any format to RGB\n3. **Extracts RGB values** that Stripe Elements can understand\n4. **Passes computed colors** to Stripe Elements on initialization\n5. **Matches the current theme** automatically (light/dark mode)\n\nThis approach works with any CSS color format (oklch, hsl, rgb, hex) and ensures Stripe Elements always match your theme when the \"Add Payment Method\" dialog opens.\n\n## Dependencies\n\n- `@stripe/stripe-js` - Stripe.js for frontend\n- `stripe` - Stripe Node.js SDK for backend\n- `svelte-sonner` - Toast notifications\n- `@lucide/svelte` - Icons\n- shadcn/ui components\n", hl = "import { json } from \"@sveltejs/kit\";\nimport stripe from \"$lib/stripe\";\nimport type { Stripe } from \"stripe\";\n\nconst createPaymentIntent = async (\n price: Stripe.Price,\n customer?: { id: string; default_payment_method?: string },\n) => {\n if (price.unit_amount === null || price.unit_amount === undefined) {\n console.error(\"Price does not have a per unit amount\");\n throw new Error(\"Price does not have a per unit amount\");\n }\n\n // Guest\n if (!customer) {\n const intent = await stripe.paymentIntents.create({\n amount: price.unit_amount,\n currency: price.currency,\n automatic_payment_methods: {\n enabled: true,\n allow_redirects: \"never\",\n },\n });\n\n if (!intent.client_secret) {\n console.error(\"Payment intent created without client secret\");\n throw new Error(\"Failed to create payment intent\");\n }\n\n return {\n type: \"payment\",\n clientSecret: intent.client_secret,\n amount: price.unit_amount,\n currency: price.currency,\n };\n }\n\n // Customer with saved payment method\n if (customer.default_payment_method) {\n const paymentMethod = await stripe.customers.retrievePaymentMethod(\n customer.id,\n customer.default_payment_method,\n );\n\n const intent = await stripe.paymentIntents.create({\n amount: price.unit_amount,\n currency: price.currency,\n customer: customer.id,\n payment_method: customer.default_payment_method,\n automatic_payment_methods: {\n enabled: true,\n allow_redirects: \"never\",\n },\n });\n\n return {\n type: \"confirm\",\n clientSecret: intent.client_secret,\n amount: price.unit_amount,\n currency: price.currency,\n brand: paymentMethod.card?.brand,\n last4: paymentMethod.card?.last4,\n };\n }\n\n // Customer without saved payment method\n const intent = await stripe.paymentIntents.create({\n amount: price.unit_amount,\n currency: price.currency,\n customer: customer.id,\n setup_future_usage: \"off_session\",\n automatic_payment_methods: {\n enabled: true,\n allow_redirects: \"never\",\n },\n });\n\n if (!intent.client_secret) {\n console.error(\"Payment intent created without client secret\");\n throw new Error(\"Failed to create payment intent\");\n }\n\n return {\n type: \"payment\",\n clientSecret: intent.client_secret,\n amount: price.unit_amount,\n currency: price.currency,\n };\n};\n\nexport const POST = async ({ request, locals }) => {\n const user = locals.pb.authStore.record?.id;\n\n let body;\n try {\n body = await request.json();\n } catch (error) {\n console.error(\"Invalid JSON in request body\");\n return json({ error: \"Invalid request body\" }, { status: 400 });\n }\n\n const { priceId } = body as { priceId?: string };\n\n // Validate required fields\n if (!priceId || typeof priceId !== \"string\" || priceId === \"\") {\n console.error(\"Missing or invalid priceId\");\n return json({ error: \"Price ID is required\" }, { status: 400 });\n }\n\n // Retrieve price from Stripe\n let price;\n try {\n price = await stripe.prices.retrieve(priceId);\n } catch (error) {\n console.error(\"Failed to retrieve price from Stripe:\", priceId);\n return json(\n { error: \"Invalid price ID or price not found\" },\n { status: 404 },\n );\n }\n\n // Validate price is active\n if (!price.active) {\n console.error(\"Price is not active:\", priceId);\n return json(\n { error: \"This price is no longer available\" },\n { status: 400 },\n );\n }\n\n let customer;\n\n if (user) {\n try {\n customer = await locals.admin\n .collection(\"stripe_customers\")\n .getFirstListItem(\n locals.admin.filter(\"user = {:user}\", { user: user }),\n );\n } catch (error) {\n // Customer not found is expected for new users, log for debugging only\n console.log(\"No Stripe customer found for user:\", user);\n }\n }\n\n try {\n const res = await createPaymentIntent(price, customer);\n return json(res, { status: 200 });\n } catch (error) {\n console.error(\"Error creating payment intent for price:\", priceId);\n const errorMessage =\n error instanceof Error\n ? error.message\n : \"Failed to create payment intent\";\n return json({ error: errorMessage }, { status: 500 });\n }\n};\n", gl = "import { describe, it, expect, beforeAll, beforeEach, afterEach } from \"vitest\";\nimport type { Match } from \"@velastack/pocketbase\";\nimport type { RouteId } from \"./$types\";\nimport stripe from \"$lib/stripe\";\nimport type Stripe from \"stripe\";\n\ndescribe(\"POST /api/stripe/payment-intent\", () => {\n let product: Stripe.Product;\n let activePrice: Stripe.Price;\n let inactivePrice: Stripe.Price;\n let stripeCustomer: Stripe.Customer;\n let paymentMethod: Stripe.PaymentMethod;\n\n beforeAll(async () => {\n const productName = \"Test Product - Payment Intent\";\n const products = await stripe.products.search({\n query: `name:\"${productName}\" AND metadata[\"test\"]:\"true\"`,\n limit: 1,\n });\n\n if (products.data.length > 0) {\n product = products.data[0];\n\n const prices = await stripe.prices.list({\n product: product.id,\n active: true,\n limit: 1,\n });\n\n if (prices.data.length > 0) {\n activePrice = prices.data[0];\n }\n\n const inactivePrices = await stripe.prices.list({\n product: product.id,\n active: false,\n limit: 1,\n });\n\n if (inactivePrices.data.length > 0) {\n inactivePrice = inactivePrices.data[0];\n }\n }\n\n // Create if not found or no active price\n if (!product) {\n product = await stripe.products.create({\n name: productName,\n metadata: {\n test: \"true\",\n test_type: \"payment-intent\",\n },\n });\n }\n\n if (!activePrice) {\n activePrice = await stripe.prices.create({\n product: product.id,\n unit_amount: 1000,\n currency: \"usd\",\n metadata: {\n test: \"true\",\n test_type: \"payment-intent\",\n },\n });\n }\n\n if (!inactivePrice) {\n inactivePrice = await stripe.prices.create({\n product: product.id,\n unit_amount: 2000,\n currency: \"usd\",\n active: false,\n metadata: {\n test: \"true\",\n test_type: \"payment-intent-inactive\",\n },\n });\n }\n });\n\n beforeEach(async (context) => {\n // Create a Stripe customer for authenticated user tests\n stripeCustomer = await stripe.customers.create({\n email: context.user.email,\n metadata: {\n test: \"true\",\n },\n });\n\n // Create a payment method for the customer\n paymentMethod = await stripe.paymentMethods.create({\n type: \"card\",\n card: {\n token: \"tok_visa\",\n },\n });\n\n await stripe.paymentMethods.attach(paymentMethod.id, {\n customer: stripeCustomer.id,\n });\n });\n\n afterEach(async () => {\n if (paymentMethod?.id) {\n await stripe.paymentMethods.detach(paymentMethod.id);\n }\n\n if (stripeCustomer?.id) {\n await stripe.customers.del(stripeCustomer.id);\n }\n });\n\n describe(\"Request validation\", () => {\n it(\"should return 400 if request body is not valid JSON\", async (context) => {\n const response = await context.agent\n .post(\"/api/stripe/payment-intent\" satisfies Match<RouteId>)\n .set(\"Content-Type\", \"application/json\")\n .send(\"invalid json\");\n\n expect(response.status).toBe(400);\n expect(response.body.error).toBe(\"Invalid request body\");\n });\n\n it(\"should return 400 if priceId is missing\", async (context) => {\n const response = await context.agent\n .post(\"/api/stripe/payment-intent\" satisfies Match<RouteId>)\n .send({});\n\n expect(response.status).toBe(400);\n expect(response.body.error).toBe(\"Price ID is required\");\n });\n\n it(\"should return 400 if priceId is not a string\", async (context) => {\n const response = await context.agent\n .post(\"/api/stripe/payment-intent\" satisfies Match<RouteId>)\n .send({ priceId: 12345 });\n\n expect(response.status).toBe(400);\n expect(response.body.error).toBe(\"Price ID is required\");\n });\n\n it(\"should return 400 if priceId is an empty string\", async (context) => {\n const response = await context.agent\n .post(\"/api/stripe/payment-intent\" satisfies Match<RouteId>)\n .send({ priceId: \"\" });\n\n expect(response.status).toBe(400);\n expect(response.body.error).toBe(\"Price ID is required\");\n });\n\n it(\"should return 404 if price does not exist\", async (context) => {\n const response = await context.agent\n .post(\"/api/stripe/payment-intent\" satisfies Match<RouteId>)\n .send({ priceId: \"price_nonexistent123\" });\n\n expect(response.status).toBe(404);\n expect(response.body.error).toBe(\"Invalid price ID or price not found\");\n });\n\n it(\"should return 400 if price is not active\", async (context) => {\n const response = await context.agent\n .post(\"/api/stripe/payment-intent\" satisfies Match<RouteId>)\n .send({ priceId: inactivePrice.id });\n\n expect(response.status).toBe(400);\n expect(response.body.error).toBe(\"This price is no longer available\");\n });\n });\n\n describe(\"Guest user (unauthenticated)\", () => {\n it(\"should create payment intent for guest user\", async (context) => {\n const response = await context.request\n .post(\"/api/stripe/payment-intent\" satisfies Match<RouteId>)\n .send({ priceId: activePrice.id });\n\n expect(response.status).toBe(200);\n expect(response.body.type).toBe(\"payment\");\n expect(response.body.clientSecret).toBeDefined();\n expect(response.body.amount).toBe(1000);\n expect(response.body.currency).toBe(\"usd\");\n expect(response.body.brand).toBeUndefined();\n expect(response.body.last4).toBeUndefined();\n\n // Verify the payment intent was created in Stripe\n const intentId = response.body.clientSecret.split(\"_secret_\")[0];\n const intent = await stripe.paymentIntents.retrieve(intentId);\n expect(intent.amount).toBe(1000);\n expect(intent.currency).toBe(\"usd\");\n expect(intent.customer).toBeNull();\n\n // Clean up\n await stripe.paymentIntents.cancel(intent.id);\n });\n });\n\n describe(\"Authenticated user without Stripe customer\", () => {\n it(\"should create payment intent for user without Stripe customer\", async (context) => {\n await context.agent.authenticateUser();\n\n const response = await context.agent\n .post(\"/api/stripe/payment-intent\" satisfies Match<RouteId>)\n .send({ priceId: activePrice.id });\n\n expect(response.status).toBe(200);\n expect(response.body.type).toBe(\"payment\");\n expect(response.body.clientSecret).toBeDefined();\n expect(response.body.amount).toBe(1000);\n expect(response.body.currency).toBe(\"usd\");\n\n // Verify the payment intent\n const intentId = response.body.clientSecret.split(\"_secret_\")[0];\n const intent = await stripe.paymentIntents.retrieve(intentId);\n expect(intent.amount).toBe(1000);\n expect(intent.setup_future_usage).toBeNull();\n\n // Clean up\n await stripe.paymentIntents.cancel(intent.id);\n });\n });\n\n describe(\"Authenticated user with Stripe customer\", () => {\n let customerRecord: { id: string };\n\n beforeEach(async (context) => {\n // Link the Stripe customer to the PocketBase user\n customerRecord = await context.admin\n .collection(\"stripe_customers\")\n .create({\n user: context.user.id,\n id: stripeCustomer.id,\n email: stripeCustomer.email,\n });\n });\n\n afterEach(async (context) => {\n // Clean up the PocketBase customer record\n await context.admin\n .collection(\"stripe_customers\")\n .delete(customerRecord.id);\n });\n\n it(\"should create payment intent with setup_future_usage for user without default payment method\", async (context) => {\n await context.agent.authenticateUser();\n\n const response = await context.agent\n .post(\"/api/stripe/payment-intent\" satisfies Match<RouteId>)\n .send({ priceId: activePrice.id });\n\n expect(response.status).toBe(200);\n expect(response.body.type).toBe(\"payment\");\n expect(response.body.clientSecret).toBeDefined();\n expect(response.body.amount).toBe(1000);\n expect(response.body.currency).toBe(\"usd\");\n expect(response.body.brand).toBeUndefined();\n expect(response.body.last4).toBeUndefined();\n\n // Verify the payment intent has setup_future_usage\n const intentId = response.body.clientSecret.split(\"_secret_\")[0];\n const intent = await stripe.paymentIntents.retrieve(intentId);\n expect(intent.customer).toBe(stripeCustomer.id);\n expect(intent.setup_future_usage).toBe(\"off_session\");\n\n // Clean up\n await stripe.paymentIntents.cancel(intent.id);\n });\n\n it(\"should create payment intent with default payment method for customer with saved payment method\", async (context) => {\n // Set default payment method\n await stripe.customers.update(stripeCustomer.id, {\n invoice_settings: {\n default_payment_method: paymentMethod.id,\n },\n });\n\n const customerRecord = await context.admin\n .collection(\"stripe_customers\")\n .getFirstListItem(\n context.admin.filter(\"user = {:user}\", { user: context.user.id }),\n );\n\n await context.admin.collection(\"stripe_payment_methods\").create({\n id: paymentMethod.id,\n customer: customerRecord.id,\n brand: paymentMethod.card?.brand,\n last4: paymentMethod.card?.last4,\n exp_month: paymentMethod.card?.exp_month,\n exp_year: paymentMethod.card?.exp_year,\n });\n\n await context.admin\n .collection(\"stripe_customers\")\n .update(customerRecord.id, {\n default_payment_method: paymentMethod.id,\n });\n\n await context.agent.authenticateUser();\n\n const response = await context.agent\n .post(\"/api/stripe/payment-intent\" satisfies Match<RouteId>)\n .send({ priceId: activePrice.id });\n\n expect(response.status).toBe(200);\n expect(response.body.type).toBe(\"confirm\");\n expect(response.body.clientSecret).toBeDefined();\n expect(response.body.amount).toBe(1000);\n expect(response.body.currency).toBe(\"usd\");\n expect(response.body.brand).toBe(\"visa\");\n expect(response.body.last4).toBeDefined();\n expect(response.body.last4).toMatch(/^\\d{4}$/);\n\n // Verify the payment intent has the payment method attached\n const intentId = response.body.clientSecret.split(\"_secret_\")[0];\n const intent = await stripe.paymentIntents.retrieve(intentId);\n expect(intent.customer).toBe(stripeCustomer.id);\n expect(intent.payment_method).toBe(paymentMethod.id);\n\n // Clean up\n await stripe.paymentIntents.cancel(intent.id);\n });\n });\n});\n", _l = "import { json } from \"@sveltejs/kit\";\nimport stripe from \"$lib/stripe\";\n\nexport const POST = async ({ locals }) => {\n const user = locals.pb.authStore.record?.id;\n\n if (!user) {\n return json({ error: \"Unauthorized\" }, { status: 401 });\n }\n\n const customer = await locals.admin\n .collection(\"stripe_customers\")\n .getFirstListItem(locals.admin.filter(\"user = {:user}\", { user }));\n\n if (!customer) {\n return json({ error: \"Customer not found\" }, { status: 404 });\n }\n\n const setupIntent = await stripe.setupIntents.create({\n customer: customer.id,\n automatic_payment_methods: {\n enabled: true,\n allow_redirects: \"never\",\n },\n });\n\n return json({ clientSecret: setupIntent.client_secret });\n};\n", vl = "import { describe, it, expect, beforeEach, afterEach } from \"vitest\";\nimport type { Match } from \"@velastack/pocketbase\";\nimport type Stripe from \"stripe\";\nimport stripe from \"$lib/stripe\";\nimport type { RouteId } from \"./$types\";\n\ndescribe(\"POST /api/stripe/setup-intent\", () => {\n let stripeCustomer: Stripe.Customer;\n\n beforeEach(async (context) => {\n await context.agent.authenticateUser();\n\n stripeCustomer = await stripe.customers.create({\n email: context.user.email,\n metadata: {\n test: \"true\",\n },\n });\n\n await context.admin.collection(\"stripe_customers\").create({\n id: stripeCustomer.id,\n user: context.user.id,\n });\n });\n\n afterEach(async (context) => {\n await context.admin\n .collection(\"stripe_customers\")\n .delete(stripeCustomer.id);\n });\n\n it(\"creates a setup intent\", async (context) => {\n const response = await context.agent.post(\n \"/api/stripe/setup-intent\" satisfies Match<RouteId>,\n );\n expect(response.status).toBe(200);\n expect(response.body.clientSecret).toBeDefined();\n });\n});\n", yl = "import { json } from \"@sveltejs/kit\";\nimport stripe from \"$lib/stripe\";\nimport { env } from \"$env/dynamic/private\";\n\n// Sync users to Stripe customers\nexport const POST = async ({ request, locals }) => {\n const authHeader = request.headers.get(\"Authorization\");\n if (authHeader !== `Bearer ${env.INTERNAL_JOB_SECRET}`) {\n return json({ error: \"Unauthorized\" }, { status: 401 });\n }\n\n // Ensure all users have a Stripe customer\n const users = await locals.admin\n .collection(\"users\")\n .getFullList({ filter: \"stripe_customers_via_user.id = null\" });\n\n for (const user of users) {\n const customer = await stripe.customers.create({\n email: user.email,\n name: user.name,\n });\n\n await locals.admin.collection(\"stripe_customers\").create({\n id: customer.id,\n user: user.id,\n });\n }\n\n console.log(\"Customers synced\");\n return json({ message: \"Customers synced\" });\n};\n", bl = "import Stripe from \"stripe\";\nimport { json } from \"@sveltejs/kit\";\nimport { env } from \"$env/dynamic/private\";\nimport stripe from \"$lib/stripe\";\nimport { handlePaymentIntentSucceeded } from \"./handlers/payment-intent/succeeded\";\nimport { handlePaymentMethodAttached } from \"./handlers/payment-method/attached\";\n\nconst processedEvents = new Set<string>();\n\nasync function verifyWebhookSignature(\n request: Request,\n webhookSecret: string,\n): Promise<Stripe.Event> {\n const body = await request.text();\n const signature = request.headers.get(\"stripe-signature\");\n\n if (!signature) {\n throw new Error(\"Missing stripe-signature header\");\n }\n\n if (!webhookSecret) {\n throw new Error(\"Missing webhook secret\");\n }\n\n try {\n return stripe.webhooks.constructEvent(body, signature, webhookSecret);\n } catch (err) {\n console.error(\"Webhook signature verification failed:\", err);\n throw new Error(\"Invalid signature\");\n }\n}\n\nexport const POST = async ({ request, locals }) => {\n try {\n const event = await verifyWebhookSignature(\n request,\n env.STRIPE_WEBHOOK_SECRET,\n );\n\n if (processedEvents.has(event.id)) {\n console.log(`Event ${event.id} already processed, skipping`);\n return json({ received: true, message: \"Event already processed\" });\n }\n\n processedEvents.add(event.id);\n\n console.log(`Processing webhook event: ${event.type} (${event.id})`);\n\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 default:\n console.log(`Unhandled event type: ${event.type}`);\n }\n\n return json({\n received: true,\n eventId: event.id,\n eventType: event.type,\n });\n } catch (error) {\n console.error(\"Webhook processing error:\", error);\n\n return json(\n {\n error: \"Webhook processing failed\",\n message: error instanceof Error ? error.message : \"Unknown error\",\n },\n { status: 400 },\n );\n }\n};\n", xl = "import { describe, it, expect, beforeEach, afterEach } from \"vitest\";\nimport type Stripe from \"stripe\";\nimport stripe from \"$lib/stripe\";\nimport { handlePaymentIntentSucceeded } from \"./succeeded\";\n\ndescribe(\"payment_intent.succeeded\", () => {\n let stripeCustomer: Stripe.Customer;\n let paymentIntent: Stripe.PaymentIntent;\n let paymentMethod: Stripe.PaymentMethod;\n\n beforeEach(async (context) => {\n // Create a Stripe customer\n stripeCustomer = await stripe.customers.create({\n email: context.user.email,\n metadata: {\n test: \"true\",\n },\n });\n\n // Link the Stripe customer to the test user\n await context.admin.collection(\"stripe_customers\").create({\n id: stripeCustomer.id,\n user: context.user.id,\n });\n\n // Create a payment method for testing\n paymentMethod = await stripe.paymentMethods.create({\n type: \"card\",\n card: {\n token: \"tok_visa\",\n },\n });\n\n // Attach payment method to customer\n await stripe.paymentMethods.attach(paymentMethod.id, {\n customer: stripeCustomer.id,\n });\n\n // Create a payment intent\n paymentIntent = await stripe.paymentIntents.create({\n amount: 2000, // $20.00\n currency: \"usd\",\n customer: stripeCustomer.id,\n payment_method: paymentMethod.id,\n confirm: true,\n return_url: \"https://example.com/return\",\n });\n });\n\n afterEach(async (context) => {\n // Clean up transactions\n const transactions = await context.admin\n .collection(\"transactions\")\n .getFullList({\n filter: context.admin.filter(\"stripe_customer = {:stripeCustomer}\", {\n stripeCustomer: stripeCustomer.id,\n }),\n });\n for (const transaction of transactions) {\n await context.admin.collection(\"transactions\").delete(transaction.id);\n }\n\n // Clean up Stripe resources\n if (paymentMethod?.id) {\n try {\n await stripe.paymentMethods.detach(paymentMethod.id);\n } catch (e) {\n // Payment method may already be detached\n }\n }\n\n // Delete customer (this will also delete associated payment methods)\n if (stripeCustomer?.id) {\n await context.admin\n .collection(\"stripe_customers\")\n .delete(stripeCustomer.id);\n await stripe.customers.del(stripeCustomer.id);\n }\n });\n\n it(\"creates a transaction record when payment intent succeeds\", async (context) => {\n const locals = { admin: context.admin } as App.Locals;\n await handlePaymentIntentSucceeded(paymentIntent, locals);\n\n // Verify transaction was created\n const transactions = await context.admin\n .collection(\"transactions\")\n .getFullList({\n filter: context.admin.filter(\n \"stripe_payment_intent = {:paymentIntent}\",\n {\n paymentIntent: paymentIntent.id,\n },\n ),\n });\n\n expect(transactions).toHaveLength(1);\n const transaction = transactions[0];\n\n expect(transaction.stripe_payment_intent).toBe(paymentIntent.id);\n expect(transaction.stripe_customer).toBe(stripeCustomer.id);\n expect(transaction.amount).toBe(2000);\n expect(transaction.currency).toBe(\"usd\");\n expect(transaction.user).toBe(context.user.id);\n expect(transaction.stripe_charge).toBeDefined();\n expect(transaction.last4).toBeDefined();\n expect(transaction.brand).toBeDefined();\n expect(transaction.created).toBeDefined();\n expect(transaction.receipt_url).toBeDefined();\n });\n\n it(\"handles payment intent with charge object instead of string\", async (context) => {\n // Retrieve the payment intent with expanded charge\n const expandedPaymentIntent = await stripe.paymentIntents.retrieve(\n paymentIntent.id,\n {\n expand: [\"latest_charge\"],\n },\n );\n\n const locals = { admin: context.admin } as App.Locals;\n await handlePaymentIntentSucceeded(expandedPaymentIntent, locals);\n\n // Verify transaction was created\n const transactions = await context.admin\n .collection(\"transactions\")\n .getFullList({\n filter: context.admin.filter(\n \"stripe_payment_intent = {:paymentIntent}\",\n {\n paymentIntent: paymentIntent.id,\n },\n ),\n });\n\n expect(transactions).toHaveLength(1);\n const transaction = transactions[0];\n\n expect(transaction.stripe_payment_intent).toBe(paymentIntent.id);\n expect(transaction.stripe_charge).toBeDefined();\n });\n\n it(\"handles payment intent with customer object instead of string\", async (context) => {\n // Retrieve the payment intent with expanded customer\n const expandedPaymentIntent = await stripe.paymentIntents.retrieve(\n paymentIntent.id,\n {\n expand: [\"customer\"],\n },\n );\n\n const locals = { admin: context.admin } as App.Locals;\n await handlePaymentIntentSucceeded(expandedPaymentIntent, locals);\n\n // Verify transaction was created\n const transactions = await context.admin\n .collection(\"transactions\")\n .getFullList({\n filter: context.admin.filter(\n \"stripe_payment_intent = {:paymentIntent}\",\n {\n paymentIntent: paymentIntent.id,\n },\n ),\n });\n\n expect(transactions).toHaveLength(1);\n expect(transactions[0].stripe_customer).toBe(stripeCustomer.id);\n });\n\n it(\"handles missing charge ID gracefully\", async (context) => {\n const paymentIntentWithoutCharge = {\n ...paymentIntent,\n latest_charge: null,\n } as Stripe.PaymentIntent;\n\n const locals = { admin: context.admin } as App.Locals;\n await handlePaymentIntentSucceeded(paymentIntentWithoutCharge, locals);\n\n // Verify no transaction was created\n const transactions = await context.admin\n .collection(\"transactions\")\n .getFullList({\n filter: context.admin.filter(\n \"stripe_payment_intent = {:paymentIntent}\",\n {\n paymentIntent: paymentIntent.id,\n },\n ),\n });\n\n expect(transactions).toHaveLength(0);\n });\n\n it(\"handles missing customer ID gracefully\", async (context) => {\n const paymentIntentWithoutCustomer = {\n ...paymentIntent,\n customer: null,\n } as Stripe.PaymentIntent;\n\n const locals = { admin: context.admin } as App.Locals;\n await handlePaymentIntentSucceeded(paymentIntentWithoutCustomer, locals);\n\n // Verify no transaction was created\n const transactions = await context.admin\n .collection(\"transactions\")\n .getFullList({\n filter: context.admin.filter(\n \"stripe_payment_intent = {:paymentIntent}\",\n {\n paymentIntent: paymentIntent.id,\n },\n ),\n });\n\n expect(transactions).toHaveLength(0);\n });\n});\n", Sl = "import Stripe from \"stripe\";\nimport stripe from \"$lib/stripe\";\n/**\n * Handles payment_intent.succeeded event\n */\nexport async function handlePaymentIntentSucceeded(\n paymentIntent: Stripe.PaymentIntent,\n locals: App.Locals,\n) {\n const chargeId =\n typeof paymentIntent.latest_charge === \"string\"\n ? paymentIntent.latest_charge\n : paymentIntent.latest_charge?.id;\n\n if (!chargeId) {\n console.error(\"No charge ID found for payment intent\");\n return;\n }\n\n const charge = await stripe.charges.retrieve(chargeId);\n\n const customerId =\n typeof paymentIntent.customer === \"string\"\n ? paymentIntent.customer\n : paymentIntent.customer?.id;\n\n if (!customerId) {\n console.error(\"No customer ID found for payment intent\");\n return;\n }\n\n const customer = await locals.admin\n .collection(\"stripe_customers\")\n .getOne(customerId);\n const created = new Date(charge.created * 1000);\n\n await locals.admin.collection(\"transactions\").create({\n stripe_payment_intent: paymentIntent.id,\n stripe_charge: chargeId,\n stripe_customer: customerId,\n amount: paymentIntent.amount,\n currency: paymentIntent.currency,\n created: created.toISOString(),\n last4: charge.payment_method_details?.card?.last4,\n brand: charge.payment_method_details?.card?.brand,\n receipt_url: charge.receipt_url,\n user: customer.user,\n });\n}\n", Cl = "import Stripe from \"stripe\";\nimport stripe from \"$lib/stripe\";\n\n/**\n * Handles payment_method.attached event\n */\nexport async function handlePaymentMethodAttached(\n paymentMethod: Stripe.PaymentMethod,\n locals: App.Locals,\n) {\n if (\n paymentMethod.allow_redisplay === \"unspecified\" ||\n !paymentMethod.customer\n ) {\n return;\n }\n\n const customer =\n typeof paymentMethod.customer === \"string\"\n ? paymentMethod.customer\n : paymentMethod.customer?.id;\n\n await locals.admin.collection(\"stripe_payment_methods\").create({\n id: paymentMethod.id,\n customer: customer,\n brand: paymentMethod.card?.brand,\n last4: paymentMethod.card?.last4,\n exp_month: paymentMethod.card?.exp_month,\n exp_year: paymentMethod.card?.exp_year,\n });\n\n const paymentMethodRecords = await locals.admin\n .collection(\"stripe_payment_methods\")\n .getFullList({\n filter: locals.admin.filter(\"customer = {:customer}\", {\n customer: customer,\n }),\n });\n\n if (paymentMethodRecords.length === 1) {\n const paymentMethod = paymentMethodRecords[0];\n\n await stripe.customers.update(customer, {\n invoice_settings: {\n default_payment_method: paymentMethod.id,\n },\n });\n\n await locals.admin.collection(\"stripe_customers\").update(customer, {\n default_payment_method: paymentMethod.id,\n });\n }\n}\n", wl = "import { describe, it, expect, beforeEach, afterEach } from \"vitest\";\nimport type Stripe from \"stripe\";\nimport stripe from \"$lib/stripe\";\nimport { handlePaymentMethodAttached } from \"./attached\";\n\ndescribe(\"payment_method.attached\", () => {\n let stripeCustomer: Stripe.Customer;\n let paymentMethod: Stripe.PaymentMethod;\n\n beforeEach(async (context) => {\n stripeCustomer = await stripe.customers.create({\n email: context.user.email,\n metadata: {\n test: \"true\",\n },\n });\n\n await context.admin.collection(\"stripe_customers\").create({\n id: stripeCustomer.id,\n user: context.user.id,\n });\n\n paymentMethod = await stripe.paymentMethods.create({\n type: \"card\",\n card: {\n token: \"tok_visa\",\n },\n });\n\n await stripe.paymentMethods.attach(paymentMethod.id, {\n customer: stripeCustomer.id,\n });\n\n paymentMethod = await stripe.paymentMethods.update(paymentMethod.id, {\n allow_redisplay: \"always\",\n });\n });\n\n afterEach(async (context) => {\n const paymentMethods = await context.admin\n .collection(\"stripe_payment_methods\")\n .getFullList({\n filter: context.admin.filter(\"customer = {:stripeCustomer}\", {\n stripeCustomer: stripeCustomer.id,\n }),\n });\n\n for (const pm of paymentMethods) {\n await context.admin.collection(\"stripe_payment_methods\").delete(pm.id);\n }\n\n if (paymentMethod?.id) {\n try {\n await stripe.paymentMethods.detach(paymentMethod.id);\n } catch {}\n }\n\n if (stripeCustomer?.id) {\n await context.admin\n .collection(\"stripe_customers\")\n .delete(stripeCustomer.id);\n await stripe.customers.del(stripeCustomer.id);\n }\n });\n\n it(\"creates a payment method record when payment method is attached\", async (context) => {\n const locals = { admin: context.admin } as App.Locals;\n await handlePaymentMethodAttached(paymentMethod, locals);\n\n // Verify payment method was created\n const paymentMethods = await context.admin\n .collection(\"stripe_payment_methods\")\n .getFullList({\n filter: context.admin.filter(\"id = {:paymentMethod}\", {\n paymentMethod: paymentMethod.id,\n }),\n });\n\n expect(paymentMethods).toHaveLength(1);\n const pm = paymentMethods[0];\n\n expect(pm.id).toBe(paymentMethod.id);\n expect(pm.customer).toBe(stripeCustomer.id);\n expect(pm.brand).toBe(paymentMethod.card?.brand);\n expect(pm.last4).toBe(paymentMethod.card?.last4);\n expect(pm.exp_month).toBe(paymentMethod.card?.exp_month);\n expect(pm.exp_year).toBe(paymentMethod.card?.exp_year);\n });\n\n it(\"sets payment method as default when it is the first one\", async (context) => {\n const locals = { admin: context.admin } as App.Locals;\n await handlePaymentMethodAttached(paymentMethod, locals);\n\n // Verify it was set as default in database\n const customer = await context.admin\n .collection(\"stripe_customers\")\n .getOne(stripeCustomer.id);\n expect(customer.default_payment_method).toBe(paymentMethod.id);\n\n // Verify it was set as default in Stripe\n const stripeCustomerUpdated = await stripe.customers.retrieve(\n stripeCustomer.id,\n );\n if (\"deleted\" in stripeCustomerUpdated) {\n throw new Error(\"Customer should not be deleted\");\n }\n expect(stripeCustomerUpdated.invoice_settings.default_payment_method).toBe(\n paymentMethod.id,\n );\n });\n\n it(\"does not set as default when there are already payment methods\", async (context) => {\n // Handle the first payment method\n const locals = { admin: context.admin } as App.Locals;\n await handlePaymentMethodAttached(paymentMethod, locals);\n\n // Verify it was set as default\n let customer = await context.admin\n .collection(\"stripe_customers\")\n .getOne(stripeCustomer.id);\n expect(customer.default_payment_method).toBe(paymentMethod.id);\n\n // Create and attach a first payment method\n let secondPaymentMethod = await stripe.paymentMethods.create({\n type: \"card\",\n card: {\n token: \"tok_mastercard\",\n },\n });\n\n await stripe.paymentMethods.attach(secondPaymentMethod.id, {\n customer: stripeCustomer.id,\n });\n\n secondPaymentMethod = await stripe.paymentMethods.update(\n secondPaymentMethod.id,\n {\n allow_redisplay: \"always\",\n },\n );\n\n // Now handle the second payment method\n await handlePaymentMethodAttached(secondPaymentMethod, locals);\n\n // Verify the default did NOT change\n customer = await context.admin\n .collection(\"stripe_customers\")\n .getOne(stripeCustomer.id);\n expect(customer.default_payment_method).toBe(paymentMethod.id);\n\n // Clean up the second payment method\n await context.admin\n .collection(\"stripe_payment_methods\")\n .delete(secondPaymentMethod.id);\n await stripe.paymentMethods.detach(secondPaymentMethod.id);\n });\n\n it(\"handles payment method with customer object instead of string\", async (context) => {\n // Retrieve the payment method with expanded customer\n const expandedPaymentMethod = await stripe.paymentMethods.retrieve(\n paymentMethod.id,\n {\n expand: [\"customer\"],\n },\n );\n\n const locals = { admin: context.admin } as App.Locals;\n await handlePaymentMethodAttached(expandedPaymentMethod, locals);\n\n // Verify payment method was created\n const paymentMethods = await context.admin\n .collection(\"stripe_payment_methods\")\n .getFullList({\n filter: context.admin.filter(\"id = {:paymentMethod}\", {\n paymentMethod: paymentMethod.id,\n }),\n });\n\n expect(paymentMethods).toHaveLength(1);\n expect(paymentMethods[0].customer).toBe(stripeCustomer.id);\n });\n\n it(\"does not create record when allow_redisplay is unspecified\", async (context) => {\n // Update payment method to have unspecified allow_redisplay\n const unspecifiedPaymentMethod = await stripe.paymentMethods.update(\n paymentMethod.id,\n {\n allow_redisplay: \"unspecified\",\n },\n );\n\n const locals = { admin: context.admin } as App.Locals;\n await handlePaymentMethodAttached(unspecifiedPaymentMethod, locals);\n\n // Verify no payment method was created\n const paymentMethods = await context.admin\n .collection(\"stripe_payment_methods\")\n .getFullList({\n filter: context.admin.filter(\"id = {:paymentMethod}\", {\n paymentMethod: paymentMethod.id,\n }),\n });\n\n expect(paymentMethods).toHaveLength(0);\n });\n});\n", Tl = /* @__PURE__ */ Object.assign({
4657
4676
  "./creates/data/hooks/stripe.pb.js": Gc,
4658
4677
  "./creates/data/hooks/utils.js": Kc,
4659
4678
  "./creates/src/lib/components/payments/confirm-dialog.svelte": qc,
@@ -5018,7 +5037,7 @@ var ql = "enable-payments", Jl = "1.0.0", Yl = "src/patterns/enable/payments", X
5018
5037
  async function Zl(e) {
5019
5038
  let t = await kl(e);
5020
5039
  if (e.env === "preview") return y(n([t, await Kl(e)]));
5021
- let { generate: r } = await import("./chunks/generate.runtime-C4_8WPai.js"), i = await r(e), { writeResult: a } = await import("./chunks/write-result-DJ32RMq5.js");
5040
+ let { generate: r } = await import("./chunks/generate.runtime-C4_8WPai.js"), i = await r(e), { writeResult: a } = await import("./chunks/write-result-BPDot58Z.js");
5022
5041
  return a(await y(n([t, i])), e);
5023
5042
  }
5024
5043
  var Ql = {
@@ -5057,7 +5076,7 @@ var Ql = {
5057
5076
  tests: 0,
5058
5077
  baseline: "velastack",
5059
5078
  generate: Zl
5060
- }, $l = "import { json } from \"@sveltejs/kit\";\nimport stripe from \"$lib/stripe\";\nimport { INTERNAL_JOB_SECRET } from \"$env/static/private\";\nimport { subscriptionRecordFields } from \"../../../../webhooks/stripe/handlers/subscription/shared\";\n\nexport const POST = async ({ request, locals }) => {\n const authHeader = request.headers.get(\"Authorization\");\n if (authHeader !== `Bearer ${INTERNAL_JOB_SECRET}`) {\n return json({ error: \"Unauthorized\" }, { status: 401 });\n }\n\n const subscriptions = await stripe.subscriptions.list({\n status: \"all\",\n limit: 100,\n });\n\n for (const subscription of subscriptions.data) {\n const fields = subscriptionRecordFields(subscription);\n if (!fields) continue;\n\n let customer;\n try {\n customer = await locals.admin\n .collection(\"stripe_customers\")\n .getOne(fields.customer);\n } catch {\n console.log(\n `Skipping subscription ${subscription.id}: customer ${fields.customer} not found locally`,\n );\n continue;\n }\n\n try {\n await locals.admin\n .collection(\"stripe_subscriptions\")\n .update(subscription.id, fields);\n } catch {\n await locals.admin.collection(\"stripe_subscriptions\").create({\n ...fields,\n user: customer.user,\n });\n }\n }\n\n console.log(\"Subscriptions synced\");\n return json({ message: \"Subscriptions synced\" });\n};\n", eu = "import Stripe from \"stripe\";\nimport { subscriptionRecordFields } from \"./shared\";\n\n/**\n * Handles customer.subscription.created event\n */\nexport async function handleSubscriptionCreated(\n subscription: Stripe.Subscription,\n locals: App.Locals,\n) {\n const fields = subscriptionRecordFields(subscription);\n if (!fields) return;\n\n const customer = await locals.admin\n .collection(\"stripe_customers\")\n .getOne(fields.customer);\n\n await locals.admin.collection(\"stripe_subscriptions\").create({\n ...fields,\n user: customer.user,\n });\n}\n", tu = "import Stripe from \"stripe\";\nimport { subscriptionRecordFields } from \"./shared\";\n\n/**\n * Handles customer.subscription.deleted event\n */\nexport async function handleSubscriptionDeleted(\n subscription: Stripe.Subscription,\n locals: App.Locals,\n) {\n const fields = subscriptionRecordFields(subscription);\n if (!fields) return;\n\n try {\n await locals.admin\n .collection(\"stripe_subscriptions\")\n .update(subscription.id, {\n ...fields,\n status: \"canceled\",\n canceled_at: fields.canceled_at ?? new Date().toISOString(),\n });\n } catch {\n // Row may not exist; ignore.\n console.log(`Subscription ${subscription.id} not found for deletion`);\n }\n}\n", nu = "import Stripe from \"stripe\";\n\nfunction unixToIso(unix: number | null | undefined): string | null {\n if (!unix) return null;\n return new Date(unix * 1000).toISOString();\n}\n\n/**\n * Extracts the subset of Stripe.Subscription fields that map to a\n * stripe_subscriptions row. Returns null if the subscription has no\n * price (shouldn't happen, but guard).\n *\n * `current_period_start`/`current_period_end` live on the subscription item\n * in API versions >= 2025-03-31 — read from there with a fallback to the\n * subscription-level field for older events.\n */\nexport function subscriptionRecordFields(subscription: Stripe.Subscription) {\n const item = subscription.items.data[0];\n const priceId = item?.price.id;\n if (!priceId) {\n console.error(`Subscription ${subscription.id} has no price`);\n return null;\n }\n\n const customerId =\n typeof subscription.customer === \"string\"\n ? subscription.customer\n : subscription.customer.id;\n\n const itemPeriodStart = (item as unknown as { current_period_start?: number })\n .current_period_start;\n const itemPeriodEnd = (item as unknown as { current_period_end?: number })\n .current_period_end;\n const subPeriodStart = (\n subscription as unknown as { current_period_start?: number }\n ).current_period_start;\n const subPeriodEnd = (\n subscription as unknown as { current_period_end?: number }\n ).current_period_end;\n\n return {\n id: subscription.id,\n customer: customerId,\n price: priceId,\n status: subscription.status,\n current_period_start: unixToIso(itemPeriodStart ?? subPeriodStart),\n current_period_end: unixToIso(itemPeriodEnd ?? subPeriodEnd),\n cancel_at_period_end: subscription.cancel_at_period_end,\n canceled_at: unixToIso(subscription.canceled_at),\n };\n}\n", ru = "import Stripe from \"stripe\";\nimport { subscriptionRecordFields } from \"./shared\";\n\n/**\n * Handles customer.subscription.updated event\n */\nexport async function handleSubscriptionUpdated(\n subscription: Stripe.Subscription,\n locals: App.Locals,\n) {\n const fields = subscriptionRecordFields(subscription);\n if (!fields) return;\n\n try {\n await locals.admin\n .collection(\"stripe_subscriptions\")\n .update(subscription.id, fields);\n } catch {\n // Row may not exist if the created event was missed; upsert instead.\n const customer = await locals.admin\n .collection(\"stripe_customers\")\n .getOne(fields.customer);\n\n await locals.admin.collection(\"stripe_subscriptions\").create({\n ...fields,\n user: customer.user,\n });\n }\n}\n", iu = /* @__PURE__ */ Object.assign({
5079
+ }, $l = "import { json } from \"@sveltejs/kit\";\nimport stripe from \"$lib/stripe\";\nimport { env } from \"$env/dynamic/private\";\nimport { subscriptionRecordFields } from \"../../../../webhooks/stripe/handlers/subscription/shared\";\n\nexport const POST = async ({ request, locals }) => {\n const authHeader = request.headers.get(\"Authorization\");\n if (authHeader !== `Bearer ${env.INTERNAL_JOB_SECRET}`) {\n return json({ error: \"Unauthorized\" }, { status: 401 });\n }\n\n const subscriptions = await stripe.subscriptions.list({\n status: \"all\",\n limit: 100,\n });\n\n for (const subscription of subscriptions.data) {\n const fields = subscriptionRecordFields(subscription);\n if (!fields) continue;\n\n let customer;\n try {\n customer = await locals.admin\n .collection(\"stripe_customers\")\n .getOne(fields.customer);\n } catch {\n console.log(\n `Skipping subscription ${subscription.id}: customer ${fields.customer} not found locally`,\n );\n continue;\n }\n\n try {\n await locals.admin\n .collection(\"stripe_subscriptions\")\n .update(subscription.id, fields);\n } catch {\n await locals.admin.collection(\"stripe_subscriptions\").create({\n ...fields,\n user: customer.user,\n });\n }\n }\n\n console.log(\"Subscriptions synced\");\n return json({ message: \"Subscriptions synced\" });\n};\n", eu = "import Stripe from \"stripe\";\nimport { subscriptionRecordFields } from \"./shared\";\n\n/**\n * Handles customer.subscription.created event\n */\nexport async function handleSubscriptionCreated(\n subscription: Stripe.Subscription,\n locals: App.Locals,\n) {\n const fields = subscriptionRecordFields(subscription);\n if (!fields) return;\n\n const customer = await locals.admin\n .collection(\"stripe_customers\")\n .getOne(fields.customer);\n\n await locals.admin.collection(\"stripe_subscriptions\").create({\n ...fields,\n user: customer.user,\n });\n}\n", tu = "import Stripe from \"stripe\";\nimport { subscriptionRecordFields } from \"./shared\";\n\n/**\n * Handles customer.subscription.deleted event\n */\nexport async function handleSubscriptionDeleted(\n subscription: Stripe.Subscription,\n locals: App.Locals,\n) {\n const fields = subscriptionRecordFields(subscription);\n if (!fields) return;\n\n try {\n await locals.admin\n .collection(\"stripe_subscriptions\")\n .update(subscription.id, {\n ...fields,\n status: \"canceled\",\n canceled_at: fields.canceled_at ?? new Date().toISOString(),\n });\n } catch {\n // Row may not exist; ignore.\n console.log(`Subscription ${subscription.id} not found for deletion`);\n }\n}\n", nu = "import Stripe from \"stripe\";\n\nfunction unixToIso(unix: number | null | undefined): string | null {\n if (!unix) return null;\n return new Date(unix * 1000).toISOString();\n}\n\n/**\n * Extracts the subset of Stripe.Subscription fields that map to a\n * stripe_subscriptions row. Returns null if the subscription has no\n * price (shouldn't happen, but guard).\n *\n * `current_period_start`/`current_period_end` live on the subscription item\n * in API versions >= 2025-03-31 — read from there with a fallback to the\n * subscription-level field for older events.\n */\nexport function subscriptionRecordFields(subscription: Stripe.Subscription) {\n const item = subscription.items.data[0];\n const priceId = item?.price.id;\n if (!priceId) {\n console.error(`Subscription ${subscription.id} has no price`);\n return null;\n }\n\n const customerId =\n typeof subscription.customer === \"string\"\n ? subscription.customer\n : subscription.customer.id;\n\n const itemPeriodStart = (item as unknown as { current_period_start?: number })\n .current_period_start;\n const itemPeriodEnd = (item as unknown as { current_period_end?: number })\n .current_period_end;\n const subPeriodStart = (\n subscription as unknown as { current_period_start?: number }\n ).current_period_start;\n const subPeriodEnd = (\n subscription as unknown as { current_period_end?: number }\n ).current_period_end;\n\n return {\n id: subscription.id,\n customer: customerId,\n price: priceId,\n status: subscription.status,\n current_period_start: unixToIso(itemPeriodStart ?? subPeriodStart),\n current_period_end: unixToIso(itemPeriodEnd ?? subPeriodEnd),\n cancel_at_period_end: subscription.cancel_at_period_end,\n canceled_at: unixToIso(subscription.canceled_at),\n };\n}\n", ru = "import Stripe from \"stripe\";\nimport { subscriptionRecordFields } from \"./shared\";\n\n/**\n * Handles customer.subscription.updated event\n */\nexport async function handleSubscriptionUpdated(\n subscription: Stripe.Subscription,\n locals: App.Locals,\n) {\n const fields = subscriptionRecordFields(subscription);\n if (!fields) return;\n\n try {\n await locals.admin\n .collection(\"stripe_subscriptions\")\n .update(subscription.id, fields);\n } catch {\n // Row may not exist if the created event was missed; upsert instead.\n const customer = await locals.admin\n .collection(\"stripe_customers\")\n .getOne(fields.customer);\n\n await locals.admin.collection(\"stripe_subscriptions\").create({\n ...fields,\n user: customer.user,\n });\n }\n}\n", iu = /* @__PURE__ */ Object.assign({
5061
5080
  "./creates/src/routes/api/stripe/sync/subscriptions/+server.ts": $l,
5062
5081
  "./creates/src/routes/webhooks/stripe/handlers/subscription/created.ts": eu,
5063
5082
  "./creates/src/routes/webhooks/stripe/handlers/subscription/deleted.ts": tu,
@@ -5196,7 +5215,7 @@ var du = "enable-subscriptions", fu = "1.0.0", pu = "src/patterns/enable/subscri
5196
5215
  async function hu(e) {
5197
5216
  let t = await su(e);
5198
5217
  if (e.env === "preview") return y(n([t, await uu(e)]));
5199
- let { createCollections: r } = await import("./chunks/collections-rD0M_Wxo.js"), i = await r(t.collections, e), { generate: a } = await import("./chunks/generate.runtime-COXTDbqt.js"), o = await a(e), { writeResult: s } = await import("./chunks/write-result-DJ32RMq5.js");
5218
+ let { createCollections: r } = await import("./chunks/collections-rD0M_Wxo.js"), i = await r(t.collections, e), { generate: a } = await import("./chunks/generate.runtime-C7g-fJTr.js"), o = await a(e), { writeResult: s } = await import("./chunks/write-result-BPDot58Z.js");
5200
5219
  return s(await y(n([{
5201
5220
  ...t,
5202
5221
  creates: [...t.creates, ...i]
@@ -5599,7 +5618,7 @@ var pd = "enable-teams", md = "1.0.0", hd = "src/patterns/enable/teams", gd = "/
5599
5618
  async function _d(e) {
5600
5619
  let t = await nd(e);
5601
5620
  if (e.env === "preview") return y(n([t, await fd(e)]));
5602
- let { generate: r } = await import("./chunks/generate.runtime-zHO95VHU.js"), i = await r(e), { writeResult: a } = await import("./chunks/write-result-DJ32RMq5.js");
5621
+ let { generate: r } = await import("./chunks/generate.runtime-zHO95VHU.js"), i = await r(e), { writeResult: a } = await import("./chunks/write-result-BPDot58Z.js");
5603
5622
  return a(await y(n([t, i])), e);
5604
5623
  }
5605
5624
  var vd = {
@@ -5667,7 +5686,7 @@ var bd = "destroy-schema", xd = "1.0.0", Sd = "src/patterns/destroy/schema", Cd
5667
5686
  async function wd(e) {
5668
5687
  let t = await y(await yd(e));
5669
5688
  if (e.env !== "runtime" || e.input.destructive !== !0) return t;
5670
- let { writeResult: n } = await import("./chunks/write-result-DJ32RMq5.js");
5689
+ let { writeResult: n } = await import("./chunks/write-result-BPDot58Z.js");
5671
5690
  return n(t, e);
5672
5691
  }
5673
5692
  var Td = {
@@ -5721,7 +5740,7 @@ async function Ad(t) {
5721
5740
  collectionDrops: []
5722
5741
  });
5723
5742
  if (t.env !== "runtime" || t.input.destructive !== !0) return s;
5724
- let { writeResult: c } = await import("./chunks/write-result-DJ32RMq5.js");
5743
+ let { writeResult: c } = await import("./chunks/write-result-BPDot58Z.js");
5725
5744
  return c(s, t);
5726
5745
  }
5727
5746
  var jd = {
@@ -5775,7 +5794,7 @@ async function Id(t) {
5775
5794
  collectionDrops: a
5776
5795
  });
5777
5796
  if (t.env !== "runtime" || t.input.destructive !== !0) return o;
5778
- let { writeResult: s } = await import("./chunks/write-result-DJ32RMq5.js");
5797
+ let { writeResult: s } = await import("./chunks/write-result-BPDot58Z.js");
5779
5798
  return s(o, t);
5780
5799
  }
5781
5800
  var Ld = {
@@ -5829,7 +5848,7 @@ async function Hd(t) {
5829
5848
  collectionDrops: o
5830
5849
  });
5831
5850
  if (t.env !== "runtime" || t.input.destructive !== !0) return s;
5832
- let { writeResult: c } = await import("./chunks/write-result-DJ32RMq5.js");
5851
+ let { writeResult: c } = await import("./chunks/write-result-BPDot58Z.js");
5833
5852
  return c(s, t);
5834
5853
  }
5835
5854
  var Ud = {
@@ -5898,7 +5917,7 @@ async function Zd(e) {
5898
5917
  if (e.env !== "runtime") return y(t);
5899
5918
  let { generate: r } = await import("./chunks/generate.runtime-qlUWZTcR.js"), i = await y(n([t, await r(e)]));
5900
5919
  if (e.input.destructive !== !0) return i;
5901
- let { writeResult: a } = await import("./chunks/write-result-DJ32RMq5.js");
5920
+ let { writeResult: a } = await import("./chunks/write-result-BPDot58Z.js");
5902
5921
  return a(i, e);
5903
5922
  }
5904
5923
  var Qd = {
@@ -5979,7 +5998,7 @@ async function sf(e) {
5979
5998
  if (e.env !== "runtime") return y(t);
5980
5999
  let { generate: r } = await import("./chunks/generate.runtime-BSlNFRop.js"), i = await y(n([t, await r(e)]));
5981
6000
  if (e.input.destructive !== !0) return i;
5982
- let { writeResult: a } = await import("./chunks/write-result-DJ32RMq5.js");
6001
+ let { writeResult: a } = await import("./chunks/write-result-BPDot58Z.js");
5983
6002
  return a(i, e);
5984
6003
  }
5985
6004
  var cf = {
@@ -6154,7 +6173,7 @@ async function vf(e) {
6154
6173
  if (e.env !== "runtime") return y(t);
6155
6174
  let { generate: r } = await import("./chunks/generate.runtime-CTXSSehF.js"), i = await y(n([t, await r(e)]));
6156
6175
  if (e.input.destructive !== !0) return i;
6157
- let { writeResult: a } = await import("./chunks/write-result-DJ32RMq5.js");
6176
+ let { writeResult: a } = await import("./chunks/write-result-BPDot58Z.js");
6158
6177
  return a(i, e);
6159
6178
  }
6160
6179
  var yf = {
@@ -6225,7 +6244,7 @@ async function Df(e) {
6225
6244
  if (e.env !== "runtime") return y(t);
6226
6245
  let { generate: r } = await import("./chunks/generate.runtime-D6C-brcS.js"), i = await y(n([t, await r(e)]));
6227
6246
  if (e.input.destructive !== !0) return i;
6228
- let { writeResult: a } = await import("./chunks/write-result-DJ32RMq5.js");
6247
+ let { writeResult: a } = await import("./chunks/write-result-BPDot58Z.js");
6229
6248
  return a(i, e);
6230
6249
  }
6231
6250
  var Of = {
@@ -6297,7 +6316,7 @@ async function If(e) {
6297
6316
  if (e.env !== "runtime") return y(t);
6298
6317
  let { generate: r } = await import("./chunks/generate.runtime-Bcgms0O_.js"), i = await y(n([t, await r(e)]));
6299
6318
  if (e.input.destructive !== !0) return i;
6300
- let { writeResult: a } = await import("./chunks/write-result-DJ32RMq5.js");
6319
+ let { writeResult: a } = await import("./chunks/write-result-BPDot58Z.js");
6301
6320
  return a(i, e);
6302
6321
  }
6303
6322
  var Lf = {
@@ -6404,7 +6423,7 @@ async function Gf(e) {
6404
6423
  if (e.env !== "runtime") return y(t);
6405
6424
  let { generate: r } = await import("./chunks/generate.runtime-PFOJ6hwY.js"), i = await y(n([t, await r(e)]));
6406
6425
  if (e.input.destructive !== !0) return i;
6407
- let { writeResult: a } = await import("./chunks/write-result-DJ32RMq5.js");
6426
+ let { writeResult: a } = await import("./chunks/write-result-BPDot58Z.js");
6408
6427
  return a(i, e);
6409
6428
  }
6410
6429
  var Kf = {
@@ -6521,7 +6540,7 @@ async function rp(e) {
6521
6540
  let a = await ip(e), o = {
6522
6541
  ...i,
6523
6542
  creates: [...i.creates, ...a]
6524
- }, { writeResult: s } = await import("./chunks/write-result-DJ32RMq5.js");
6543
+ }, { writeResult: s } = await import("./chunks/write-result-BPDot58Z.js");
6525
6544
  return s(o, e);
6526
6545
  }
6527
6546
  async function ip(e) {
@@ -6614,7 +6633,7 @@ async function pp(e) {
6614
6633
  if (e.env !== "runtime") return y(t);
6615
6634
  let { generate: r } = await import("./chunks/generate.runtime-BbZ5w6b_.js"), i = await y(n([t, await r(e)]));
6616
6635
  if (e.input.destructive !== !0) return i;
6617
- let { writeResult: a } = await import("./chunks/write-result-DJ32RMq5.js");
6636
+ let { writeResult: a } = await import("./chunks/write-result-BPDot58Z.js");
6618
6637
  return a(i, e);
6619
6638
  }
6620
6639
  var mp = {