@velastack/patterns 0.1.0 → 0.1.2

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@velastack/patterns",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
4
4
  "description": "Registry of VelaStack patterns: generators and modifications applied to SvelteKit projects by the VelaStack CLI.",
5
5
  "type": "module",
6
6
  "private": false,
@@ -106,12 +106,12 @@
106
106
  "pluralize": "^8.0.0",
107
107
  "pocketbase": "^0.28.0",
108
108
  "stripe": "^19.3.0",
109
- "svelte": "^5.55.4",
109
+ "svelte": "^5.56.10",
110
110
  "ts-morph": "^28.0.0",
111
111
  "typescript": "^5.0.0",
112
- "vite": "^8.0.8",
112
+ "vite": "^8.2.2",
113
113
  "vite-node": "^6.0.0",
114
114
  "vite-plugin-dts": "^4.5.4",
115
- "vitest": "^4.1.4"
115
+ "vitest": "^4.1.11"
116
116
  }
117
117
  }
@@ -1,6 +0,0 @@
1
- //#region src/patterns/enable/subscriptions/preview-modifies/data/hooks/stripe.pb.js?raw
2
- var e = "/// <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\n// [!code highlight:4]\ncronAdd(\"stripe-subscriptions\", \"*/2 * * * *\", () => {\n const utils = require(`${__hooks}/utils.js`);\n utils.triggerJob(\"/api/stripe/sync/subscriptions\");\n});\n", t = "<script lang=\"ts\" module>\n import HomeIcon from '@lucide/svelte/icons/home';\n\n let data = {\n navMain: [\n {\n title: 'Dashboard',\n url: '/dashboard',\n icon: HomeIcon\n }\n ]\n };\n<\/script>\n\n<script lang=\"ts\">\n import NavMain from './nav-main.svelte';\n import NavUser from './nav-user.svelte';\n import * as Sidebar from '$lib/components/ui/sidebar';\n import type { ComponentProps } from 'svelte';\n\n let {\n user,\n meta,\n // [!code highlight:1]\n subscription = null,\n ref = $bindable(null),\n ...restProps\n }: ComponentProps<typeof Sidebar.Root> & {\n user: any;\n meta: any;\n // [!code highlight:1]\n subscription?: { id: string; productName: string | null } | null;\n } = $props();\n<\/script>\n\n<Sidebar.Root bind:ref variant=\"inset\" {...restProps}>\n <Sidebar.Header>\n <Sidebar.Menu>\n <Sidebar.MenuItem>\n <Sidebar.MenuButton size=\"lg\">\n {#snippet child({ props })}\n <a href=\"/dashboard\" {...props}>\n <div\n class=\"bg-sidebar-accent text-sidebar-primary-foreground flex aspect-square size-8 items-center justify-center rounded-lg\"\n >\n <img src=\"/favicon.svg\" alt=\"logo\" class=\"size-6\" />\n </div>\n <div class=\"grid flex-1 text-left text-sm leading-tight\">\n <span class=\"truncate font-medium\">{meta.appName}</span>\n </div>\n </a>\n {/snippet}\n </Sidebar.MenuButton>\n </Sidebar.MenuItem>\n </Sidebar.Menu>\n </Sidebar.Header>\n <Sidebar.Content>\n <NavMain items={data.navMain} />\n </Sidebar.Content>\n <Sidebar.Footer>\n <NavUser {user} {subscription} />\n </Sidebar.Footer>\n</Sidebar.Root>\n", n = "<script lang=\"ts\">\n import { toggleMode, mode } from \"mode-watcher\";\n import ChevronsUpDownIcon from \"@lucide/svelte/icons/chevrons-up-down\";\n import Settings2Icon from \"@lucide/svelte/icons/settings-2\";\n import CreditCardIcon from \"@lucide/svelte/icons/credit-card\";\n import LogOutIcon from \"@lucide/svelte/icons/log-out\";\n import MoonIcon from \"@lucide/svelte/icons/moon\";\n import SunIcon from \"@lucide/svelte/icons/sun\";\n import * as Avatar from \"$lib/components/ui/avatar\";\n import * as DropdownMenu from \"$lib/components/ui/dropdown-menu\";\n import * as Sidebar from \"$lib/components/ui/sidebar\";\n\n let data = {\n navUser: [\n {\n title: \"Settings\",\n url: \"/settings\",\n icon: Settings2Icon,\n },\n {\n title: \"Billing\",\n url: \"/billing\",\n icon: CreditCardIcon,\n },\n ],\n };\n\n let {\n user,\n // [!code highlight:1]\n subscription = null,\n }: {\n user: {\n id: string;\n name: string;\n email: string;\n avatar: string;\n };\n // [!code highlight:1]\n subscription?: { id: string; productName: string | null } | null;\n } = $props();\n\n // [!code highlight:1]\n const planLabel = $derived(subscription?.productName ?? \"Free\");\n\n const sidebar = Sidebar.useSidebar();\n<\/script>\n\n<Sidebar.Menu>\n <Sidebar.MenuItem>\n <DropdownMenu.Root>\n <DropdownMenu.Trigger>\n {#snippet child({ props })}\n <Sidebar.MenuButton\n size=\"lg\"\n class=\"data-[state=open]:bg-sidebar-accent data-[state=open]:text-sidebar-accent-foreground\"\n {...props}\n >\n <Avatar.Root class=\"size-8 rounded-lg\">\n {#if user.avatar}\n <Avatar.Image\n src=\"/api/files/users/{user.id}/{user.avatar}\"\n alt={user.name}\n />\n {/if}\n <Avatar.Fallback class=\"rounded-lg\">\n {user.name?.charAt(0).toUpperCase() ||\n user.email?.charAt(0).toUpperCase()}\n </Avatar.Fallback>\n </Avatar.Root>\n <div class=\"grid flex-1 text-left text-sm leading-tight\">\n <span class=\"truncate font-medium\">\n {user.name || user.email}\n </span>\n <!-- [!code highlight:3] -->\n <span class=\"truncate text-xs text-muted-foreground\">\n {planLabel}\n </span>\n </div>\n <ChevronsUpDownIcon class=\"ml-auto size-4\" />\n </Sidebar.MenuButton>\n {/snippet}\n </DropdownMenu.Trigger>\n <DropdownMenu.Content\n class=\"w-(--bits-dropdown-menu-anchor-width) min-w-56 rounded-lg\"\n side={sidebar.isMobile ? \"bottom\" : \"right\"}\n align=\"end\"\n sideOffset={4}\n >\n <DropdownMenu.Label class=\"p-0 font-normal\">\n <div class=\"flex items-center gap-2 px-1 py-1.5 text-left text-sm\">\n <Avatar.Root class=\"size-8 rounded-lg\">\n {#if user.avatar}\n <Avatar.Image\n src=\"/api/files/users/{user.id}/{user.avatar}\"\n alt={user.name}\n />\n {/if}\n <Avatar.Fallback class=\"rounded-lg\">\n {user.name?.charAt(0).toUpperCase() ||\n user.email?.charAt(0).toUpperCase()}\n </Avatar.Fallback>\n </Avatar.Root>\n <div class=\"grid flex-1 text-left text-sm leading-tight\">\n <span class=\"truncate font-medium\">\n {user.name || user.email}\n </span>\n <!-- [!code highlight:3] -->\n <span class=\"truncate text-xs\">\n {planLabel}\n </span>\n </div>\n </div>\n </DropdownMenu.Label>\n <DropdownMenu.Separator />\n <DropdownMenu.Group>\n <DropdownMenu.Item onclick={toggleMode}>\n {#if mode.current === \"dark\"}\n <SunIcon />\n Light mode\n {:else}\n <MoonIcon />\n Dark mode\n {/if}\n </DropdownMenu.Item>\n {#each data.navUser as item}\n <DropdownMenu.Item class=\"p-0\">\n <a\n href={item.url}\n class=\"flex cursor-default items-center gap-2 px-2 py-1.5 w-full\"\n >\n <item.icon />\n {item.title}\n </a>\n </DropdownMenu.Item>\n {/each}\n </DropdownMenu.Group>\n <DropdownMenu.Separator />\n <DropdownMenu.Item class=\"p-0\">\n <form action=\"/logout\" method=\"post\" class=\"w-full\">\n <button\n type=\"submit\"\n class=\"flex cursor-default items-center gap-2 px-2 py-1.5 w-full\"\n >\n <LogOutIcon />\n Log out\n </button>\n </form>\n </DropdownMenu.Item>\n </DropdownMenu.Content>\n </DropdownMenu.Root>\n </Sidebar.MenuItem>\n</Sidebar.Menu>\n", r = "// [!code highlight:33]\nasync function loadActiveSubscription(locals: App.Locals, userId: string) {\n const subscriptions = await locals.admin\n .collection(\"stripe_subscriptions\")\n .getFullList({\n filter: locals.admin.filter(\n 'user = {:user} && (status = \"active\" || status = \"trialing\")',\n { user: userId },\n ),\n expand: \"price\",\n sort: \"-created\",\n })\n .catch(() => []);\n\n const sub = subscriptions[0];\n if (!sub) return null;\n\n const price = sub.expand?.price;\n let productName: string | null = null;\n if (price?.product) {\n const product = await locals.admin\n .collection(\"stripe_products\")\n .getOne(price.product)\n .catch(() => null);\n productName = product?.name ?? null;\n }\n\n return {\n id: sub.id,\n status: sub.status as string,\n productName,\n cancelAtPeriodEnd: Boolean(sub.cancel_at_period_end),\n };\n}\n\nexport const load = async ({ locals }) => {\n const user = locals.pb.authStore.record!;\n const breadcrumbs = [{ title: \"Home\", url: \"/dashboard\" }];\n // [!code highlight:1]\n const subscription = await loadActiveSubscription(locals, user.id);\n\n // [!code highlight:1]\n return { user, breadcrumbs, subscription };\n};\n", i = "<script lang=\"ts\">\n import * as Sidebar from \"$lib/components/ui/sidebar\";\n import { Separator } from \"$lib/components/ui/separator\";\n import AppSidebar from \"$lib/components/app-sidebar.svelte\";\n import * as Breadcrumb from \"$lib/components/ui/breadcrumb\";\n import { page } from \"$app/state\";\n\n let breadcrumbs = $derived(page.data.breadcrumbs || []) as {\n title: string;\n url: string;\n }[];\n let { data, children } = $props();\n<\/script>\n\n<div class=\"min-h-dvh dashboard\">\n <Sidebar.Provider>\n <!-- [!code highlight:5] -->\n <AppSidebar\n user={data.user}\n meta={data.meta}\n subscription={data.subscription}\n />\n <Sidebar.Inset>\n <header class=\"flex h-16 shrink-0 items-center gap-2\">\n <div class=\"flex items-center gap-2 px-4\">\n <Sidebar.Trigger class=\"-ml-1\" />\n <Separator\n orientation=\"vertical\"\n class=\"mr-2 data-[orientation=vertical]:h-4\"\n />\n {#if breadcrumbs.length > 0}\n <Breadcrumb.Root>\n <Breadcrumb.List>\n {#if breadcrumbs.length > 1}\n {#each breadcrumbs.slice(0, -1) as breadcrumb}\n <Breadcrumb.Item>\n <Breadcrumb.Link href={breadcrumb.url}\n >{breadcrumb.title}</Breadcrumb.Link\n >\n </Breadcrumb.Item>\n <Breadcrumb.Separator />\n {/each}\n {/if}\n <Breadcrumb.Page>\n {breadcrumbs[breadcrumbs.length - 1].title}\n </Breadcrumb.Page>\n </Breadcrumb.List>\n </Breadcrumb.Root>\n {/if}\n </div>\n </header>\n <div class=\"flex flex-1 flex-col p-4 pt-0\">\n {@render children?.()}\n </div>\n </Sidebar.Inset>\n </Sidebar.Provider>\n</div>\n\n<style>\n :global(body:has(div.dashboard)) {\n background-color: var(--color-sidebar);\n }\n</style>\n", a = "import { error } from \"@sveltejs/kit\";\nimport stripe from \"$lib/stripe\";\n\ntype RecurringInfo = {\n interval: string;\n interval_count: number;\n trial_period_days?: number | null;\n};\n\nfunction parseRecurring(value: unknown): RecurringInfo | null {\n if (!value) return null;\n if (typeof value === \"object\") return value as RecurringInfo;\n try {\n return JSON.parse(value as string) as RecurringInfo;\n } catch {\n return null;\n }\n}\n\nconst ACTIVE_SUBSCRIPTION_STATUSES = [\n \"active\",\n \"trialing\",\n \"past_due\",\n \"incomplete\",\n];\n\nexport const load = async ({ locals, depends, parent }) => {\n const { user } = await parent();\n const customer = await locals.admin\n .collection(\"stripe_customers\")\n .getFirstListItem(locals.admin.filter(\"user = {:user}\", { user: user.id }));\n\n if (!customer || !customer.id) {\n return error(400, \"Customer not found\");\n }\n\n const stripeCustomer = await stripe.customers.retrieve(customer.id);\n if (stripeCustomer.deleted) {\n return error(400, \"Customer not found\");\n }\n\n const paymentMethods = await stripe.customers.listPaymentMethods(\n customer.id,\n {\n type: \"card\",\n allow_redisplay: \"always\",\n },\n );\n\n const subscriptionRecords = await locals.admin\n .collection(\"stripe_subscriptions\")\n .getFullList({\n filter: locals.admin.filter(\"user = {:user}\", { user: user.id }),\n expand: \"price\",\n sort: \"-created\",\n });\n\n const recurringPrices = await locals.admin\n .collection(\"stripe_prices\")\n .getFullList({\n filter: locals.admin.filter(\"type = {:type} && active = true\", {\n type: \"recurring\",\n }),\n });\n\n const productIds: string[] = Array.from(\n new Set(\n recurringPrices\n .map((p) => p.product)\n .filter((id): id is string => Boolean(id)),\n ),\n );\n const productMap = new Map<string, string>();\n if (productIds.length > 0) {\n const products = await locals.admin\n .collection(\"stripe_products\")\n .getFullList({\n filter: productIds.map((id) => `id = \"${id}\"`).join(\" || \"),\n });\n for (const product of products) {\n productMap.set(product.id, product.name ?? product.id);\n }\n }\n\n const availablePlans = recurringPrices.map((price) => ({\n id: price.id,\n productName:\n (price.product && productMap.get(price.product)) ?? price.product ?? \"\",\n unitAmount: (price.unit_amount ?? 0) as number,\n currency: (price.currency ?? \"\") as string,\n recurring: parseRecurring(price.recurring),\n }));\n\n const subscriptions = subscriptionRecords.map((sub) => {\n const expanded = sub.expand?.price;\n return {\n id: sub.id,\n status: sub.status as string,\n currentPeriodStart: (sub.current_period_start as string | null) ?? null,\n currentPeriodEnd: (sub.current_period_end as string | null) ?? null,\n cancelAtPeriodEnd: Boolean(sub.cancel_at_period_end),\n canceledAt: (sub.canceled_at as string | null) || null,\n priceId: sub.price as string,\n productName: expanded\n ? ((expanded.product && productMap.get(expanded.product)) ??\n expanded.product ??\n null)\n : null,\n unitAmount: expanded ? ((expanded.unit_amount ?? null) as number | null) : null,\n currency: expanded ? ((expanded.currency ?? null) as string | null) : null,\n recurring: expanded ? parseRecurring(expanded.recurring) : null,\n };\n });\n\n const activeSubscription =\n subscriptions.find((s) => ACTIVE_SUBSCRIPTION_STATUSES.includes(s.status)) ||\n null;\n\n // If the active plan isn't in the list (e.g., price was deactivated), include\n // it so it can still be shown as the current plan.\n if (\n activeSubscription &&\n !availablePlans.some((p) => p.id === activeSubscription.priceId)\n ) {\n availablePlans.push({\n id: activeSubscription.priceId,\n productName: activeSubscription.productName ?? \"\",\n unitAmount: activeSubscription.unitAmount ?? 0,\n currency: activeSubscription.currency ?? \"\",\n recurring: activeSubscription.recurring,\n });\n }\n\n availablePlans.sort((a, b) => a.unitAmount - b.unitAmount);\n\n depends(\"app:billing\");\n\n return {\n paymentMethods: paymentMethods.data.map((pm) => ({\n id: pm.id,\n brand: pm.card!.brand,\n last4: pm.card!.last4,\n expMonth: pm.card!.exp_month,\n expYear: pm.card!.exp_year,\n isDefault: pm.id === customer.default_payment_method,\n })),\n user,\n hasDefaultPaymentMethod: Boolean(customer.default_payment_method),\n activeSubscription,\n availablePlans,\n };\n};\n\nasync function getUserCustomer(locals: App.Locals) {\n const userId = locals.pb.authStore.record?.id;\n if (!userId) {\n return error(401, \"Unauthorized\");\n }\n const customer = await locals.admin\n .collection(\"stripe_customers\")\n .getFirstListItem(`user.id = \"${userId}\"`);\n if (!customer || !customer.id) {\n return error(400, \"Customer not found\");\n }\n return customer;\n}\n\n// A subscription can be updated in-place unless it has fully terminated.\nconst UPDATABLE_STATUSES = [\n \"active\",\n \"trialing\",\n \"past_due\",\n \"incomplete\",\n \"paused\",\n];\n\nasync function findUpdatableSubscription(\n locals: App.Locals,\n userId: string,\n) {\n const filterClause = UPDATABLE_STATUSES.map(\n (s) => `status = \"${s}\"`,\n ).join(\" || \");\n const subs = await locals.admin\n .collection(\"stripe_subscriptions\")\n .getFullList({\n filter: locals.admin.filter(`user = {:user} && (${filterClause})`, {\n user: userId,\n }),\n sort: \"-created\",\n });\n return subs[0] ?? null;\n}\n\nexport const actions = {\n setDefaultPaymentMethod: async ({ locals, request }) => {\n const formData = await request.formData();\n const paymentMethodId = formData.get(\"paymentMethodId\") as string;\n\n const customer = await locals.admin\n .collection(\"stripe_customers\")\n .getFirstListItem(`user.id = \"${locals.pb.authStore.record?.id}\"`);\n\n if (!customer || !customer.id) {\n return error(400, \"Customer not found\");\n }\n\n await stripe.customers.update(customer.id, {\n invoice_settings: {\n default_payment_method: paymentMethodId,\n },\n });\n\n await locals.admin.collection(\"stripe_customers\").update(customer.id, {\n default_payment_method: paymentMethodId,\n });\n },\n deletePaymentMethod: async ({ locals, request }) => {\n const formData = await request.formData();\n const paymentMethodId = formData.get(\"paymentMethodId\") as string;\n\n const customer = await locals.admin\n .collection(\"stripe_customers\")\n .getFirstListItem(`user.id = \"${locals.pb.authStore.record?.id}\"`);\n\n const defaultPaymentMethod = customer.default_payment_method;\n\n await stripe.paymentMethods.detach(paymentMethodId);\n\n // If default payment method was deleted, update default payment method\n if (defaultPaymentMethod === paymentMethodId) {\n const paymentMethods = await stripe.paymentMethods.list({\n customer: customer.id,\n });\n\n if (paymentMethods.data.length > 0) {\n const defaultPaymentMethod = paymentMethods.data[0];\n\n await stripe.customers.update(customer.id, {\n invoice_settings: {\n default_payment_method: defaultPaymentMethod.id,\n },\n });\n\n await locals.admin.collection(\"stripe_customers\").update(customer.id, {\n default_payment_method: defaultPaymentMethod.id,\n });\n } else {\n await locals.admin.collection(\"stripe_customers\").update(customer.id, {\n default_payment_method: null,\n });\n }\n }\n },\n selectPlan: async ({ locals, request }) => {\n const formData = await request.formData();\n const priceId = formData.get(\"priceId\") as string;\n if (!priceId) return error(400, \"Price ID is required\");\n\n const userId = locals.pb.authStore.record?.id;\n if (!userId) return error(401, \"Unauthorized\");\n\n // If an updatable subscription already exists, change its price in place\n // rather than creating a duplicate. Covers switch, resume-to-different-plan,\n // and races where the webhook hasn't delivered the existing sub yet.\n const existing = await findUpdatableSubscription(locals, userId);\n if (existing) {\n const stripeSub = await stripe.subscriptions.retrieve(existing.id);\n const item = stripeSub.items.data[0];\n if (!item) return error(500, \"Subscription has no items\");\n\n await stripe.subscriptions.update(existing.id, {\n items: [{ id: item.id, price: priceId }],\n proration_behavior: \"create_prorations\",\n cancel_at_period_end: false,\n });\n return;\n }\n\n const customer = await getUserCustomer(locals);\n if (!customer.default_payment_method) {\n return error(400, \"Add a default payment method before subscribing\");\n }\n\n await stripe.subscriptions.create({\n customer: customer.id,\n items: [{ price: priceId }],\n default_payment_method: customer.default_payment_method,\n payment_behavior: \"error_if_incomplete\",\n off_session: true,\n });\n },\n cancelSubscription: async ({ locals, request }) => {\n const formData = await request.formData();\n const subscriptionId = formData.get(\"subscriptionId\") as string;\n if (!subscriptionId) return error(400, \"Subscription ID is required\");\n\n const userId = locals.pb.authStore.record?.id;\n if (!userId) return error(401, \"Unauthorized\");\n\n // Verify the subscription belongs to this user before touching Stripe.\n try {\n const record = await locals.admin\n .collection(\"stripe_subscriptions\")\n .getOne(subscriptionId);\n if (record.user !== userId) {\n return error(403, \"Forbidden\");\n }\n } catch {\n return error(404, \"Subscription not found\");\n }\n\n await stripe.subscriptions.update(subscriptionId, {\n cancel_at_period_end: true,\n });\n },\n resumeSubscription: async ({ locals, request }) => {\n const formData = await request.formData();\n const subscriptionId = formData.get(\"subscriptionId\") as string;\n if (!subscriptionId) return error(400, \"Subscription ID is required\");\n\n const userId = locals.pb.authStore.record?.id;\n if (!userId) return error(401, \"Unauthorized\");\n\n try {\n const record = await locals.admin\n .collection(\"stripe_subscriptions\")\n .getOne(subscriptionId);\n if (record.user !== userId) {\n return error(403, \"Forbidden\");\n }\n } catch {\n return error(404, \"Subscription not found\");\n }\n\n await stripe.subscriptions.update(subscriptionId, {\n cancel_at_period_end: false,\n });\n },\n};\n", o = "<script lang=\"ts\">\n import { Button } from '$lib/components/ui/button';\n import * as Card from '$lib/components/ui/card';\n import { Badge } from '$lib/components/ui/badge';\n import * as AlertDialog from '$lib/components/ui/alert-dialog';\n import SetupButton from '$lib/components/payments/setup-button.svelte';\n import { CreditCard, Trash2, Check, Package } from '@lucide/svelte';\n import { toast } from 'svelte-sonner';\n import { invalidate, invalidateAll } from '$app/navigation';\n import { untrack } from 'svelte';\n\n let { data } = $props();\n let paymentMethods = $derived(data.paymentMethods);\n let availablePlans = $derived(data.availablePlans);\n let hasDefaultPaymentMethod = $derived(data.hasDefaultPaymentMethod);\n\n // Local, mutable mirror of the server-side subscription. We optimistically\n // update it on user actions so the UI reflects the change immediately; the\n // $effect re-syncs from the server after the webhook has had a chance to\n // fire (invalidateAll runs on a short delay below).\n let activeSubscription = $state(untrack(() => data.activeSubscription));\n $effect(() => {\n activeSubscription = data.activeSubscription;\n });\n let showDeleteDialog = $state(false);\n let selectedPaymentMethodId = $state<string | null>(null);\n let isProcessing = $state(false);\n let showCancelDialog = $state(false);\n let isSubscribing = $state<string | null>(null);\n let isCanceling = $state(false);\n\n function openDeleteDialog(paymentMethodId: string) {\n selectedPaymentMethodId = paymentMethodId;\n showDeleteDialog = true;\n }\n\n function closeDeleteDialog() {\n showDeleteDialog = false;\n selectedPaymentMethodId = null;\n }\n\n async function handleDeletePaymentMethod() {\n if (!selectedPaymentMethodId) return;\n isProcessing = true;\n\n try {\n const formData = new FormData();\n formData.append('paymentMethodId', selectedPaymentMethodId);\n\n await fetch('?/deletePaymentMethod', {\n method: 'POST',\n body: formData\n });\n\n await invalidate('app:billing');\n toast.success('Payment method removed successfully');\n closeDeleteDialog();\n } catch (err) {\n console.error('Error deleting payment method:', err);\n toast.error('Failed to remove payment method');\n } finally {\n isProcessing = false;\n }\n }\n\n async function setDefaultPaymentMethod(paymentMethodId: string) {\n try {\n const formData = new FormData();\n formData.append('paymentMethodId', paymentMethodId);\n\n await fetch('?/setDefaultPaymentMethod', {\n method: 'POST',\n body: formData\n });\n\n await invalidate('app:billing');\n toast.success('Default payment method updated');\n } catch (err) {\n console.error('Error setting default payment method:', err);\n toast.error('Failed to update default payment method');\n }\n }\n\n function getCardBrandIcon(brand: string) {\n // You can customize these icons or use actual card brand icons\n const brands: Record<string, string> = {\n visa: '💳',\n mastercard: '💳',\n amex: '💳',\n discover: '💳',\n unknown: '💳'\n };\n return brands[brand.toLowerCase()] || brands.unknown;\n }\n\n function formatCardBrand(brand: string) {\n return brand.charAt(0).toUpperCase() + brand.slice(1);\n }\n\n function formatAmount(amount: number | null, currency: string | null) {\n if (amount === null || !currency) return '—';\n return new Intl.NumberFormat('en-US', {\n style: 'currency',\n currency: currency.toUpperCase()\n }).format(amount / 100);\n }\n\n function formatInterval(recurring: { interval: string; interval_count: number } | null) {\n if (!recurring) return '';\n if (recurring.interval_count === 1) return `/ ${recurring.interval}`;\n return `every ${recurring.interval_count} ${recurring.interval}s`;\n }\n\n function formatDate(iso: string | null) {\n if (!iso) return '—';\n return new Date(iso).toLocaleDateString(undefined, {\n year: 'numeric',\n month: 'short',\n day: 'numeric'\n });\n }\n\n async function selectPlan(priceId: string, successMessage: string) {\n if (!hasDefaultPaymentMethod) {\n toast.error('Add a default payment method first');\n return;\n }\n const previous = activeSubscription;\n const plan = availablePlans.find((p) => p.id === priceId);\n if (plan) {\n activeSubscription = previous\n ? {\n ...previous,\n priceId,\n productName: plan.productName,\n unitAmount: plan.unitAmount,\n currency: plan.currency,\n recurring: plan.recurring,\n cancelAtPeriodEnd: false\n }\n : {\n id: 'pending',\n status: 'active',\n priceId,\n productName: plan.productName,\n unitAmount: plan.unitAmount,\n currency: plan.currency,\n recurring: plan.recurring,\n cancelAtPeriodEnd: false,\n currentPeriodStart: null,\n currentPeriodEnd: null,\n canceledAt: null\n };\n }\n\n isSubscribing = priceId;\n try {\n const formData = new FormData();\n formData.append('priceId', priceId);\n\n const res = await fetch('?/selectPlan', {\n method: 'POST',\n body: formData\n });\n\n if (!res.ok) {\n throw new Error(`selectPlan failed: ${res.status}`);\n }\n\n toast.success(successMessage);\n setTimeout(() => {\n invalidateAll();\n }, 2000);\n } catch (err) {\n console.error('Error selecting plan:', err);\n toast.error('Failed to update plan');\n activeSubscription = previous;\n } finally {\n isSubscribing = null;\n }\n }\n\n async function subscribe(priceId: string) {\n await selectPlan(priceId, 'Subscription started');\n }\n\n async function switchPlan(priceId: string) {\n await selectPlan(priceId, 'Subscription updated');\n }\n\n async function resumeSubscription() {\n if (!activeSubscription) return;\n const previous = activeSubscription;\n isSubscribing = activeSubscription.priceId;\n activeSubscription = { ...activeSubscription, cancelAtPeriodEnd: false };\n try {\n const formData = new FormData();\n formData.append('subscriptionId', previous.id);\n\n const res = await fetch('?/resumeSubscription', {\n method: 'POST',\n body: formData\n });\n\n if (!res.ok) {\n throw new Error(`Resume failed: ${res.status}`);\n }\n\n toast.success('Subscription resumed');\n setTimeout(() => {\n invalidateAll();\n }, 2000);\n } catch (err) {\n console.error('Error resuming subscription:', err);\n toast.error('Failed to resume subscription');\n activeSubscription = previous;\n } finally {\n isSubscribing = null;\n }\n }\n\n async function handleCancelSubscription() {\n if (!activeSubscription) return;\n const previous = activeSubscription;\n isCanceling = true;\n activeSubscription = { ...activeSubscription, cancelAtPeriodEnd: true };\n try {\n const formData = new FormData();\n formData.append('subscriptionId', previous.id);\n\n const res = await fetch('?/cancelSubscription', {\n method: 'POST',\n body: formData\n });\n\n if (!res.ok) {\n throw new Error(`Cancel failed: ${res.status}`);\n }\n\n toast.success('Subscription will cancel at period end');\n showCancelDialog = false;\n setTimeout(() => {\n invalidateAll();\n }, 2000);\n } catch (err) {\n console.error('Error canceling subscription:', err);\n toast.error('Failed to cancel subscription');\n activeSubscription = previous;\n } finally {\n isCanceling = false;\n }\n }\n<\/script>\n\n<div class=\"divide-y divide-gray-900/10 dark:divide-white/10\">\n <div class=\"grid grid-cols-1 gap-x-8 gap-y-8 py-10 md:grid-cols-3\">\n <div class=\"px-4 sm:px-0\">\n <h2 class=\"text-base/7 font-semibold text-gray-900 dark:text-white\">Payment Methods</h2>\n <p class=\"mt-1 text-sm/6 text-gray-600 dark:text-gray-400\">\n Manage your payment methods for subscriptions and purchases.\n </p>\n </div>\n\n <div class=\"md:col-span-2\">\n <Card.Root>\n <Card.Content>\n {#if paymentMethods.length === 0}\n <div\n class=\"text-muted-foreground flex flex-col items-center justify-center py-12 text-center\"\n >\n <CreditCard class=\"mb-4 size-12 opacity-50\" />\n <p class=\"mb-2 text-lg font-medium\">No payment methods</p>\n <p class=\"text-sm\">Add a payment method to get started</p>\n </div>\n {:else}\n <div class=\"space-y-4\">\n {#each paymentMethods as method (method.id)}\n <div\n class=\"border-border hover:bg-accent/50 flex items-center justify-between rounded-lg border p-4 transition-colors\"\n >\n <div class=\"flex items-center gap-4\">\n <div\n class=\"bg-muted flex size-12 items-center justify-center rounded-lg text-2xl\"\n >\n {getCardBrandIcon(method.brand)}\n </div>\n <div>\n <div class=\"flex items-center gap-2\">\n <p class=\"font-medium\">\n {formatCardBrand(method.brand)} •••• {method.last4}\n </p>\n {#if method.isDefault}\n <Badge variant=\"secondary\">\n <Check class=\"mr-1 size-3\" />\n Default\n </Badge>\n {/if}\n </div>\n <p class=\"text-muted-foreground text-sm\">\n Expires {method.expMonth.toString().padStart(2, '0')}/{method.expYear}\n </p>\n </div>\n </div>\n <div class=\"flex items-center gap-2\">\n {#if !method.isDefault}\n <Button\n variant=\"outline\"\n size=\"sm\"\n onclick={() => setDefaultPaymentMethod(method.id)}\n >\n Set as Default\n </Button>\n {/if}\n <Button\n variant=\"outline\"\n size=\"icon-sm\"\n onclick={() => openDeleteDialog(method.id)}\n disabled={method.isDefault && paymentMethods.length === 1}\n >\n <Trash2 class=\"size-4\" />\n </Button>\n </div>\n </div>\n {/each}\n </div>\n {/if}\n </Card.Content>\n <Card.Footer class=\"border-t justify-end\">\n <SetupButton\n label=\"Add Payment Method\"\n processingLabel=\"Adding...\"\n onsuccess={() => invalidate('app:billing')}\n />\n </Card.Footer>\n </Card.Root>\n </div>\n </div>\n\n <div class=\"grid grid-cols-1 gap-x-8 gap-y-8 py-10 md:grid-cols-3\">\n <div class=\"px-4 sm:px-0\">\n <h2 class=\"text-base/7 font-semibold text-gray-900 dark:text-white\">Plan</h2>\n <p class=\"mt-1 text-sm/6 text-gray-600 dark:text-gray-400\">Manage your subscription.</p>\n </div>\n\n <div class=\"md:col-span-2\">\n <Card.Root>\n <Card.Content>\n {#if availablePlans.length === 0}\n <div\n class=\"text-muted-foreground flex flex-col items-center justify-center py-12 text-center\"\n >\n <Package class=\"mb-4 size-12 opacity-50\" />\n <p class=\"mb-2 text-lg font-medium\">No plans available</p>\n <p class=\"text-sm\">Check back soon.</p>\n </div>\n {:else}\n {#if !hasDefaultPaymentMethod}\n <p class=\"text-muted-foreground mb-4 rounded-md border border-dashed p-3 text-sm\">\n Add a default payment method above to subscribe.\n </p>\n {/if}\n <div class=\"space-y-4\">\n {#each availablePlans as plan (plan.id)}\n {@const isCurrent = activeSubscription?.priceId === plan.id}\n <div\n class=\"flex items-center justify-between rounded-lg border p-4 transition-colors {isCurrent\n ? 'border-primary ring-primary ring-1'\n : 'border-border hover:bg-accent/50'}\"\n >\n <div class=\"flex items-center gap-4\">\n <div class=\"bg-muted flex size-12 items-center justify-center rounded-lg\">\n <Package class=\"size-5\" />\n </div>\n <div>\n <div class=\"flex items-center gap-2\">\n <p class=\"font-medium\">{plan.productName}</p>\n {#if isCurrent && activeSubscription}\n {#if activeSubscription.cancelAtPeriodEnd}\n <Badge variant=\"outline\">Pending cancellation</Badge>\n {:else if activeSubscription.status === 'trialing'}\n <Badge variant=\"secondary\">Trial</Badge>\n {:else if activeSubscription.status === 'past_due'}\n <Badge variant=\"destructive\">Past due</Badge>\n {:else}\n <Badge variant=\"secondary\">\n <Check class=\"mr-1 size-3\" />\n Current\n </Badge>\n {/if}\n {/if}\n </div>\n <p class=\"text-muted-foreground text-sm\">\n {formatAmount(plan.unitAmount, plan.currency)}\n {formatInterval(plan.recurring)}\n {#if isCurrent && activeSubscription?.currentPeriodEnd}\n <span>\n &bull;\n {activeSubscription.cancelAtPeriodEnd ? 'Cancels on' : 'Renews on'}\n {formatDate(activeSubscription.currentPeriodEnd)}\n </span>\n {/if}\n </p>\n </div>\n </div>\n <div class=\"flex items-center gap-2\">\n {#if isCurrent && activeSubscription}\n {#if activeSubscription.cancelAtPeriodEnd}\n <Button\n variant=\"outline\"\n size=\"sm\"\n disabled={isSubscribing === plan.id}\n onclick={resumeSubscription}\n >\n {isSubscribing === plan.id ? 'Resuming...' : 'Resume'}\n </Button>\n {:else}\n <Button\n variant=\"outline\"\n size=\"sm\"\n onclick={() => (showCancelDialog = true)}\n >\n Cancel subscription\n </Button>\n {/if}\n {:else if activeSubscription}\n <Button\n variant=\"outline\"\n size=\"sm\"\n disabled={!hasDefaultPaymentMethod || isSubscribing === plan.id}\n onclick={() => switchPlan(plan.id)}\n >\n {isSubscribing === plan.id ? 'Switching...' : 'Switch'}\n </Button>\n {:else}\n <Button\n variant=\"outline\"\n size=\"sm\"\n disabled={!hasDefaultPaymentMethod || isSubscribing === plan.id}\n onclick={() => subscribe(plan.id)}\n >\n {isSubscribing === plan.id ? 'Subscribing...' : 'Subscribe'}\n </Button>\n {/if}\n </div>\n </div>\n {/each}\n </div>\n {/if}\n </Card.Content>\n </Card.Root>\n </div>\n </div>\n</div>\n\n<!-- Cancel Subscription Dialog -->\n<AlertDialog.Root bind:open={showCancelDialog}>\n <AlertDialog.Content>\n <AlertDialog.Header>\n <AlertDialog.Title>Cancel Subscription</AlertDialog.Title>\n <AlertDialog.Description>\n Your subscription will remain active until the end of the current billing period, then\n cancel automatically.\n </AlertDialog.Description>\n </AlertDialog.Header>\n <AlertDialog.Footer>\n <AlertDialog.Cancel onclick={() => (showCancelDialog = false)}>\n Keep Subscription\n </AlertDialog.Cancel>\n <AlertDialog.Action onclick={handleCancelSubscription} disabled={isCanceling}>\n {isCanceling ? 'Canceling...' : 'Cancel at Period End'}\n </AlertDialog.Action>\n </AlertDialog.Footer>\n </AlertDialog.Content>\n</AlertDialog.Root>\n\n<!-- Delete Confirmation Dialog -->\n<AlertDialog.Root bind:open={showDeleteDialog}>\n <AlertDialog.Content>\n <AlertDialog.Header>\n <AlertDialog.Title>Remove Payment Method</AlertDialog.Title>\n <AlertDialog.Description>\n Are you sure you want to remove this payment method? This action cannot be undone.\n </AlertDialog.Description>\n </AlertDialog.Header>\n <AlertDialog.Footer>\n <AlertDialog.Cancel onclick={closeDeleteDialog}>Cancel</AlertDialog.Cancel>\n <AlertDialog.Action onclick={handleDeletePaymentMethod} disabled={isProcessing}>\n {isProcessing ? 'Removing...' : 'Remove'}\n </AlertDialog.Action>\n </AlertDialog.Footer>\n </AlertDialog.Content>\n</AlertDialog.Root>\n", s = "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\";\nimport { handleSubscriptionCreated } from \"./handlers/subscription/created\";\nimport { handleSubscriptionUpdated } from \"./handlers/subscription/updated\";\nimport { handleSubscriptionDeleted } from \"./handlers/subscription/deleted\";\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 case \"customer.subscription.created\":\n await handleSubscriptionCreated(event.data.object, locals);\n break;\n\n case \"customer.subscription.updated\":\n await handleSubscriptionUpdated(event.data.object, locals);\n break;\n\n case \"customer.subscription.deleted\":\n await handleSubscriptionDeleted(event.data.object, locals);\n break;\n\n default:\n console.log(`Unhandled event type: ${event.type}`);\n }\n\n 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";
3
- //#endregion
4
- export { r as a, e as c, i, o as n, n as o, a as r, t as s, s as t };
5
-
6
- //# sourceMappingURL=_server-Cie287JZ.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"_server-Cie287JZ.js","names":[],"sources":[],"mappings":""}
@@ -1 +0,0 @@
1
- {"version":3,"file":"generate.runtime-yddwyo5X.js","names":[],"sources":["../../src/patterns/enable/teams/modifies/modify-app-layout.ts","../../src/patterns/enable/teams/modifies/modify-app-sidebar.ts","../../src/patterns/enable/teams/modifies/+layout.server.ts","../../src/patterns/enable/teams/modifies/modify-nav-user.ts","../../src/patterns/enable/teams/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst FAILURE_HINT = [\n \"Pass team props to <AppSidebar> in your app layout:\",\n \"\",\n \"<AppSidebar team={data.team} teams={data.teams ?? []} />\",\n].join(\"\\n\");\n\nconst NOT_FOUND_HINT = [\n \"Create an app layout that renders <AppSidebar> with team props:\",\n \"\",\n \"<AppSidebar team={data.team} teams={data.teams ?? []} />\",\n].join(\"\\n\");\n\nexport function modifyAppLayoutSvelte(layoutPath: string): ModifyOutcome {\n if (!fs.existsSync(layoutPath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const file = SvelteFile.fromPath(layoutPath);\n if (!file.hasElement(\"AppSidebar\")) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n if (file.hasAttribute(\"AppSidebar\", \"teams\")) {\n return { status: \"success\", changed: false };\n }\n\n file.appendToAttributes(\n \"AppSidebar\",\n \" team={data.team} teams={data.teams ?? []}\",\n );\n file.writeTo(layoutPath);\n return { status: \"success\", changed: file.hasChanged() };\n}\n","import fs from \"node:fs\";\nimport { SyntaxKind } from \"ts-morph\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport {\n ensureImports,\n withInMemoryScript,\n} from \"../../../../runtime/ts-morph-helpers\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst NEW_HEADER = `<Sidebar.Header>\n\t\t<Sidebar.Menu>\n\t\t\t<TeamSwitcher {teams}>\n\t\t\t\t{#snippet children()}\n\t\t\t\t\t{@const activeTeam = teams.find((t) => t.id === team)}\n\t\t\t\t\t{#if activeTeam}\n\t\t\t\t\t\t<Avatar.Root class=\"size-8 rounded-lg\">\n\t\t\t\t\t\t\t<Avatar.Fallback class=\"rounded-lg bg-primary text-primary-foreground font-medium\">\n\t\t\t\t\t\t\t\t{activeTeam.name?.charAt(0).toUpperCase()}\n\t\t\t\t\t\t\t</Avatar.Fallback>\n\t\t\t\t\t\t</Avatar.Root>\n\t\t\t\t\t\t<div class=\"grid flex-1 text-left text-sm leading-tight\">\n\t\t\t\t\t\t\t<span class=\"truncate font-medium\">\n\t\t\t\t\t\t\t\t{activeTeam.name}\n\t\t\t\t\t\t\t</span>\n\t\t\t\t\t\t</div>\n\t\t\t\t\t{:else}\n\t\t\t\t\t\t<div\n\t\t\t\t\t\t\tclass=\"bg-sidebar-accent text-sidebar-primary-foreground flex aspect-square size-8 items-center justify-center rounded-lg\"\n\t\t\t\t\t\t>\n\t\t\t\t\t\t\t<img src=\"/favicon.svg\" alt=\"logo\" class=\"size-6\" />\n\t\t\t\t\t\t</div>\n\t\t\t\t\t\t<div class=\"grid flex-1 text-left text-sm leading-tight\">\n\t\t\t\t\t\t\t<span class=\"truncate font-medium\">{meta.appName}</span>\n\t\t\t\t\t\t</div>\n\t\t\t\t\t{/if}\n\t\t\t\t\t<ChevronsUpDownIcon class=\"ml-auto\" />\n\t\t\t\t{/snippet}\n\t\t\t</TeamSwitcher>\n\t\t</Sidebar.Menu>\n\t</Sidebar.Header>`;\n\nconst IMPORT_SNIPPET = [\n \"import TeamSwitcher from '$lib/components/team-switcher.svelte';\",\n \"import ChevronsUpDownIcon from '@lucide/svelte/icons/chevrons-up-down';\",\n \"import * as Avatar from '$lib/components/ui/avatar';\",\n].join(\"\\n\");\n\nconst FAILURE_HINT = [\n \"Replace the <Sidebar.Header> in your app sidebar with the team switcher.\",\n \"\",\n \"Imports to add to the <script> tag:\",\n \"\",\n IMPORT_SNIPPET,\n \"\",\n \"Props to destructure in $props(): team, teams = []\",\n \"\",\n \"Markup to use as the header:\",\n NEW_HEADER,\n].join(\"\\n\");\n\nconst NOT_FOUND_HINT = [\n \"Create an app sidebar with a <Sidebar.Header> containing the team switcher.\",\n \"\",\n \"Imports:\",\n \"\",\n IMPORT_SNIPPET,\n \"\",\n \"Header markup:\",\n NEW_HEADER,\n].join(\"\\n\");\n\nfunction updateAppSidebarScript(source: string): string {\n const { source: out } = withInMemoryScript(source, (sf) => {\n ensureImports(sf, [\n {\n defaultImport: \"TeamSwitcher\",\n moduleSpecifier: \"$lib/components/team-switcher.svelte\",\n },\n {\n defaultImport: \"ChevronsUpDownIcon\",\n moduleSpecifier: \"@lucide/svelte/icons/chevrons-up-down\",\n },\n {\n namespaceImport: \"Avatar\",\n moduleSpecifier: \"$lib/components/ui/avatar\",\n },\n ]);\n\n for (const decl of sf.getVariableDeclarations()) {\n const init = decl.getInitializer();\n if (!init || init.getText() !== \"$props()\") continue;\n\n const nameNode = decl.getNameNode();\n if (nameNode.getKind() !== SyntaxKind.ObjectBindingPattern) continue;\n\n const pattern = nameNode.asKindOrThrow(SyntaxKind.ObjectBindingPattern);\n const elements = pattern.getElements();\n\n if (elements.some((e) => e.getName() === \"team\")) continue;\n\n // Type changes first — name change can shift positions and invalidate type node refs.\n const typeNode = decl.getTypeNode();\n if (typeNode?.getKind() === SyntaxKind.IntersectionType) {\n const intersection = typeNode.asKindOrThrow(\n SyntaxKind.IntersectionType,\n );\n for (const member of intersection.getTypeNodes()) {\n if (member.getKind() !== SyntaxKind.TypeLiteral) continue;\n const lit = member.asKindOrThrow(SyntaxKind.TypeLiteral);\n const propTexts = lit\n .getProperties()\n .map((p) => p.getText().replace(/[;,]\\s*$/, \"\"));\n if (propTexts.some((t) => /^team\\b/.test(t))) break;\n propTexts.push(\n \"team?: string | undefined\",\n \"teams?: { id: string; name: string }[]\",\n );\n lit.replaceWithText(`{ ${propTexts.join(\"; \")}; }`);\n break;\n }\n }\n\n // Rebuild binding pattern: insert team, teams = [] before first rest/initializer element.\n const elementTexts = elements.map((e) => e.getText());\n let insertIdx = elements.findIndex(\n (e) => e.getDotDotDotToken() || e.getInitializer(),\n );\n if (insertIdx === -1) insertIdx = elements.length;\n elementTexts.splice(insertIdx, 0, \"team\", \"teams = []\");\n pattern.replaceWithText(`{ ${elementTexts.join(\", \")} }`);\n }\n sf.formatText();\n });\n return out;\n}\n\nexport function modifyAppSidebar(appSidebarPath: string): ModifyOutcome {\n if (!fs.existsSync(appSidebarPath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const file = SvelteFile.fromPath(appSidebarPath);\n if (file.hasElement(\"TeamSwitcher\")) {\n return { status: \"success\", changed: false };\n }\n if (!file.hasElement(\"Sidebar.Header\")) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n file.modifyScript(updateAppSidebarScript);\n file.replaceElement(\"Sidebar.Header\", NEW_HEADER);\n file.writeTo(appSidebarPath);\n return { status: \"success\", changed: file.hasChanged() };\n}\n","import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { Project, SyntaxKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nexport function modifyLayoutServer(layoutServerPath: string): ModifyOutcome {\n if (!fs.existsSync(layoutServerPath)) {\n const snippet = dedent`\n export const load = async ({ locals, depends }) => {\n const user = locals.pb.authStore.record!;\n const team = locals.team;\n const teams = await locals.pb.collection(\"teams\").getFullList();\n depends(\"app:team\");\n\n const breadcrumbs = [{ title: \"Home\", url: \"/dashboard\" }];\n return { user, team, teams, breadcrumbs };\n };\n `;\n\n fs.writeFileSync(layoutServerPath, snippet);\n return { status: \"success\", changed: true };\n }\n\n const originalSource = fs.readFileSync(layoutServerPath, \"utf8\");\n const project = new Project();\n const sourceFile = project.addSourceFileAtPath(layoutServerPath);\n\n const addProperty = (\n obj: import(\"ts-morph\").ObjectLiteralExpression,\n name: string,\n initializer: string,\n ) => {\n const hasProperty = !!obj.getProperty(name);\n if (!hasProperty) {\n if (name === initializer) {\n obj.addShorthandPropertyAssignment({ name });\n } else {\n obj.addPropertyAssignment({ name, initializer });\n }\n }\n };\n\n let loadArrow: import(\"ts-morph\").ArrowFunction | undefined;\n let loadFn:\n | import(\"ts-morph\").FunctionDeclaration\n | import(\"ts-morph\").FunctionExpression\n | undefined;\n\n const varDecl = sourceFile.getVariableDeclaration(\"load\");\n if (varDecl) {\n const vs = varDecl.getFirstAncestorByKind(SyntaxKind.VariableStatement);\n const isExported = !!vs?.hasExportKeyword();\n if (isExported) {\n const directArrow = varDecl.getInitializerIfKind(\n SyntaxKind.ArrowFunction,\n );\n if (directArrow) {\n loadArrow = directArrow;\n } else {\n const init = varDecl.getInitializer();\n if (init) {\n const innerArrow = init.getFirstDescendantByKind(\n SyntaxKind.ArrowFunction,\n );\n if (innerArrow) {\n loadArrow = innerArrow;\n } else {\n const innerFnExpr = init.getFirstDescendantByKind(\n SyntaxKind.FunctionExpression,\n );\n if (innerFnExpr) {\n loadFn = innerFnExpr;\n }\n }\n }\n }\n }\n }\n\n if (!loadArrow) {\n const maybeFn = sourceFile.getFunction(\"load\");\n if (maybeFn && maybeFn.isExported()) {\n loadFn = maybeFn;\n }\n }\n\n if (!loadArrow && !loadFn) {\n sourceFile.addFunction({\n isExported: true,\n isAsync: true,\n name: \"load\",\n parameters: [{ name: \"{ locals, depends }\" }],\n statements: [\n \"const user = locals.pb.authStore.record!;\",\n \"const team = locals.team;\",\n 'const teams = await locals.pb.collection(\"teams\").getFullList();',\n 'depends(\"app:team\");',\n \"\",\n 'const breadcrumbs = [{ title: \"Home\", url: \"/dashboard\" }];',\n \"return { user, team, teams, breadcrumbs };\",\n ],\n });\n sourceFile.formatText();\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n }\n\n const fnLike:\n | import(\"ts-morph\").ArrowFunction\n | import(\"ts-morph\").FunctionDeclaration\n | import(\"ts-morph\").FunctionExpression = (loadArrow ?? loadFn!) as any;\n\n const params = fnLike.getParameters();\n if (params.length === 0) {\n fnLike.insertParameter(0, { name: \"{ locals, depends }\" });\n } else {\n const first = params[0];\n const original = first.getStructure();\n const nameNode = first.getNameNode();\n if (nameNode.getKind() === SyntaxKind.ObjectBindingPattern) {\n const obp = nameNode as import(\"ts-morph\").ObjectBindingPattern;\n const hasDepends = obp\n .getElements()\n .some((el) => el.getName() === \"depends\");\n const hasLocals = obp\n .getElements()\n .some((el) => el.getName() === \"locals\");\n\n if (!hasDepends) {\n const parts = obp\n .getElements()\n .map((el) => el.getText())\n .filter(Boolean);\n const tail = parts.length > 0 ? \", \" + parts.join(\", \") : \"\";\n\n if (hasLocals) {\n first.set({\n name: `{ depends${tail} }`,\n type: original.type,\n initializer: (original as any).initializer,\n });\n } else {\n first.set({\n name: `{ locals, depends${tail} }`,\n type: original.type,\n initializer: (original as any).initializer,\n });\n }\n }\n } else {\n const currentName = first.getName();\n if (currentName !== \"locals\") {\n first.set({\n name: `{ locals, depends, ...${currentName} }`,\n type: original.type,\n initializer: (original as any).initializer,\n });\n } else {\n first.set({\n name: `{ locals, depends }`,\n type: original.type,\n initializer: (original as any).initializer,\n });\n }\n }\n }\n\n if (loadArrow && !loadArrow.isAsync()) {\n loadArrow.setIsAsync(true);\n } else if (loadFn && !loadFn.isAsync()) {\n loadFn.setIsAsync(true);\n }\n\n const body = fnLike.getBody();\n if (body && body.getKind() === SyntaxKind.Block) {\n const blockBody = body as import(\"ts-morph\").Block;\n const statements = blockBody.getStatements();\n\n const hasTeam = statements.some(\n (stmt: import(\"ts-morph\").Statement) =>\n stmt.getKind() === SyntaxKind.VariableStatement &&\n stmt\n .getDescendantsOfKind(SyntaxKind.Identifier)\n .some((id: import(\"ts-morph\").Identifier) => id.getText() === \"team\"),\n );\n\n const hasTeams = statements.some(\n (stmt: import(\"ts-morph\").Statement) =>\n stmt.getKind() === SyntaxKind.VariableStatement &&\n stmt\n .getDescendantsOfKind(SyntaxKind.Identifier)\n .some(\n (id: import(\"ts-morph\").Identifier) => id.getText() === \"teams\",\n ),\n );\n\n const hasDependsTeam = statements.some(\n (stmt: import(\"ts-morph\").Statement) =>\n stmt.getKind() === SyntaxKind.ExpressionStatement &&\n stmt\n .getDescendantsOfKind(SyntaxKind.CallExpression)\n .some((ce: import(\"ts-morph\").CallExpression) => {\n const expr = ce.getExpression();\n if (expr.getText() !== \"depends\") return false;\n const args = ce.getArguments();\n const argText = args[0]?.getText() ?? \"\";\n return (\n args.length === 1 &&\n (argText === \"'app:team'\" || argText === '\"app:team\"')\n );\n }),\n );\n\n if (!hasTeam) {\n blockBody.insertStatements(1, \"const team = locals.team;\");\n }\n\n if (!hasTeams) {\n blockBody.insertStatements(\n 2,\n 'const teams = await locals.pb.collection(\"teams\").getFullList();',\n );\n }\n\n if (!hasDependsTeam) {\n blockBody.insertStatements(3, 'depends(\"app:team\");');\n }\n }\n\n if (loadArrow) {\n const body = loadArrow.getBody();\n if (body.getKind() === SyntaxKind.Block) {\n const returns = body.getDescendantsOfKind(SyntaxKind.ReturnStatement);\n returns.forEach((ret) => {\n const expr = ret.getExpression();\n if (!expr) return;\n if (expr.getKind() === SyntaxKind.ObjectLiteralExpression) {\n const obj = expr as import(\"ts-morph\").ObjectLiteralExpression;\n addProperty(obj, \"team\", \"team\");\n addProperty(obj, \"teams\", \"teams\");\n } else if (expr.getKind() === SyntaxKind.ParenthesizedExpression) {\n const inner = (\n expr as import(\"ts-morph\").ParenthesizedExpression\n ).getExpression();\n if (inner.getKind() === SyntaxKind.ObjectLiteralExpression) {\n const obj = inner as import(\"ts-morph\").ObjectLiteralExpression;\n addProperty(obj, \"team\", \"team\");\n addProperty(obj, \"teams\", \"teams\");\n }\n }\n });\n } else {\n const bodyExpr = body as import(\"ts-morph\").Expression;\n if (bodyExpr.getKind() === SyntaxKind.ParenthesizedExpression) {\n const inner = (\n bodyExpr as import(\"ts-morph\").ParenthesizedExpression\n ).getExpression();\n if (inner.getKind() === SyntaxKind.ObjectLiteralExpression) {\n const obj = inner as import(\"ts-morph\").ObjectLiteralExpression;\n addProperty(obj, \"team\", \"team\");\n addProperty(obj, \"teams\", \"teams\");\n }\n } else if (bodyExpr.getKind() === SyntaxKind.ObjectLiteralExpression) {\n const obj = bodyExpr as import(\"ts-morph\").ObjectLiteralExpression;\n addProperty(obj, \"team\", \"team\");\n addProperty(obj, \"teams\", \"teams\");\n }\n }\n } else if (loadFn) {\n const fnBody = loadFn.getBody();\n if (fnBody) {\n const returns = fnBody.getDescendantsOfKind(SyntaxKind.ReturnStatement);\n returns.forEach((ret) => {\n const expr = ret.getExpression();\n if (!expr) return;\n if (expr.getKind() === SyntaxKind.ObjectLiteralExpression) {\n const obj = expr as import(\"ts-morph\").ObjectLiteralExpression;\n addProperty(obj, \"team\", \"team\");\n addProperty(obj, \"teams\", \"teams\");\n } else if (expr.getKind() === SyntaxKind.ParenthesizedExpression) {\n const inner = (\n expr as import(\"ts-morph\").ParenthesizedExpression\n ).getExpression();\n if (inner.getKind() === SyntaxKind.ObjectLiteralExpression) {\n const obj = inner as import(\"ts-morph\").ObjectLiteralExpression;\n addProperty(obj, \"team\", \"team\");\n addProperty(obj, \"teams\", \"teams\");\n }\n }\n });\n }\n }\n\n sourceFile.formatText();\n sourceFile.saveSync();\n return {\n status: \"success\",\n changed: sourceFile.getFullText() !== originalSource,\n };\n}\n","import fs from \"node:fs\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport { addNavItemToScript } from \"../../../../runtime/ts-morph-helpers\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst TEAMS_NAV_SNIPPET = [\n \"import UsersIcon from '@lucide/svelte/icons/users';\",\n \"\",\n \"// Add to your navUser array:\",\n \"{ title: 'Teams', url: '/teams', icon: UsersIcon }\",\n].join(\"\\n\");\n\nconst FAILURE_HINT = [\n \"Add a Teams nav item to nav-user.svelte:\",\n \"\",\n TEAMS_NAV_SNIPPET,\n].join(\"\\n\");\n\nconst NOT_FOUND_HINT = [\n \"Create nav-user.svelte with a Teams entry:\",\n \"\",\n TEAMS_NAV_SNIPPET,\n].join(\"\\n\");\n\nexport function addItemToNavUser(\n navUserSnippet: string,\n title: string,\n url: string,\n icon: string,\n iconImportPath: string,\n): { newNavUserSnippet: string; wasAdded: boolean } {\n const file = new SvelteFile(navUserSnippet);\n let wasAdded = false;\n\n const tryAdd = (run: (fn: (s: string) => string) => boolean) => {\n if (wasAdded) return;\n run((source) => {\n const result = addNavItemToScript(\n source,\n title,\n url,\n icon,\n iconImportPath,\n );\n if (result.wasAdded) wasAdded = true;\n return result.source;\n });\n };\n\n tryAdd((fn) => file.modifyModuleScript(fn));\n if (!wasAdded) tryAdd((fn) => file.modifyScript(fn));\n\n return { newNavUserSnippet: file.toString(), wasAdded };\n}\n\nexport function modifyNavUser(navUserPath: string): ModifyOutcome {\n if (!fs.existsSync(navUserPath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const navUserSnippet = fs.readFileSync(navUserPath, \"utf8\");\n if (navUserSnippet.includes(\"/teams\")) {\n return { status: \"success\", changed: false };\n }\n\n const { newNavUserSnippet, wasAdded } = addItemToNavUser(\n navUserSnippet,\n \"Teams\",\n \"/teams\",\n \"UsersIcon\",\n \"@lucide/svelte/icons/users\",\n );\n\n if (!wasAdded) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n fs.writeFileSync(navUserPath, newNavUserSnippet, \"utf8\");\n return { status: \"success\", changed: true };\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport { languageFromPath } from \"../../../core/util\";\nimport {\n applyCollectionRulePatches,\n createCollectionIdempotent,\n} from \"../../../runtime/collections\";\nimport {\n getMigrationFile,\n migrationDelay,\n withPocketbase,\n} from \"../../../runtime/pocketbase\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { modifyAppLayoutSvelte } from \"./modifies/modify-app-layout\";\nimport { modifyAppSidebar } from \"./modifies/modify-app-sidebar\";\nimport { modifyLayoutServer } from \"./modifies/+layout.server\";\nimport { modifyNavUser } from \"./modifies/modify-nav-user\";\nimport { TEAM_RULE_PATCHES } from \"./runtime/pocketbase\";\n\nasync function pushMigrationCreates(\n creates: File[],\n collectionName: string,\n options: Options,\n created = true,\n) {\n if (!created) return;\n // Wait so the next schema op lands in a different PocketBase timestamp second.\n await migrationDelay();\n const migrationFile = getMigrationFile(collectionName, \"created\", options);\n if (!migrationFile) {\n return;\n }\n creates.push({\n path: migrationFile,\n language: languageFromPath(migrationFile),\n content: fs.readFileSync(migrationFile, \"utf8\"),\n status: \"success\",\n });\n}\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const creates: File[] = [];\n\n await withPocketbase(options.root, async (pb) => {\n const userCollection = await pb.collections.getOne(\"users\");\n const create = (spec: Parameters<typeof createCollectionIdempotent>[1]) =>\n createCollectionIdempotent(pb, spec, logger);\n\n logger.info(\"Creating teams collection\");\n const teamsResult = await create({\n name: \"teams\",\n type: \"base\",\n fields: [\n {\n name: \"id\",\n type: \"text\",\n primaryKey: true,\n autogeneratePattern: \"[a-z0-9]{15}\",\n max: 15,\n min: 15,\n pattern: \"^[a-z0-9]+$\",\n required: true,\n },\n {\n name: \"name\",\n type: \"text\",\n required: true,\n },\n {\n name: \"owner\",\n type: \"relation\",\n cascadeDelete: false,\n collectionId: userCollection.id,\n maxSelect: 1,\n minSelect: 0,\n required: true,\n },\n {\n name: \"created\",\n type: \"autodate\",\n onCreate: true,\n onUpdate: false,\n },\n {\n name: \"updated\",\n type: \"autodate\",\n onCreate: true,\n onUpdate: true,\n },\n ],\n });\n const teamsCollection = teamsResult.collection;\n await pushMigrationCreates(creates, \"teams\", options, teamsResult.created);\n\n logger.info(\"Creating team_memberships collection\");\n const teamMembershipsResult = await create({\n name: \"team_memberships\",\n type: \"base\",\n fields: [\n {\n name: \"id\",\n autogeneratePattern: \"[a-z0-9]{15}\",\n max: 15,\n min: 15,\n pattern: \"^[a-z0-9]+$\",\n primaryKey: true,\n required: true,\n type: \"text\",\n },\n {\n name: \"team\",\n cascadeDelete: true,\n collectionId: teamsCollection.id,\n maxSelect: 1,\n minSelect: 0,\n required: true,\n type: \"relation\",\n },\n {\n name: \"user\",\n cascadeDelete: true,\n collectionId: userCollection.id,\n maxSelect: 1,\n minSelect: 0,\n required: true,\n type: \"relation\",\n },\n {\n name: \"role\",\n maxSelect: 1,\n required: true,\n type: \"select\",\n values: [\"owner\", \"admin\", \"member\"],\n },\n {\n name: \"created\",\n onCreate: true,\n onUpdate: false,\n type: \"autodate\",\n },\n {\n name: \"updated\",\n onCreate: true,\n onUpdate: true,\n type: \"autodate\",\n },\n ],\n });\n const teamMembershipsCollection = teamMembershipsResult.collection;\n await pushMigrationCreates(\n creates,\n \"team_memberships\",\n options,\n teamMembershipsResult.created,\n );\n\n logger.info(\"Creating team_users view\");\n const teamUsersResult = await create({\n name: \"team_users\",\n type: \"view\",\n fields: [\n {\n name: \"id\",\n pattern: \"^[a-z0-9]+$\",\n primaryKey: true,\n required: true,\n type: \"text\",\n },\n {\n name: \"email\",\n exceptDomains: null,\n onlyDomains: null,\n required: true,\n type: \"email\",\n },\n {\n name: \"name\",\n max: 255,\n required: false,\n type: \"text\",\n },\n {\n name: \"membership_id\",\n cascadeDelete: false,\n collectionId: teamMembershipsCollection.id,\n maxSelect: 1,\n minSelect: 0,\n required: false,\n type: \"relation\",\n },\n {\n name: \"team\",\n cascadeDelete: true,\n collectionId: teamsCollection.id,\n maxSelect: 1,\n minSelect: 0,\n required: true,\n type: \"relation\",\n },\n {\n name: \"role\",\n maxSelect: 1,\n required: true,\n type: \"select\",\n values: [\"owner\", \"admin\", \"member\"],\n },\n ],\n viewQuery:\n \"select users.id, users.email, users.name, team_memberships.id as membership_id, team_memberships.team, team_memberships.role from users join team_memberships on team_memberships.user = users.id;\",\n });\n await pushMigrationCreates(\n creates,\n \"team_users\",\n options,\n teamUsersResult.created,\n );\n\n logger.info(\"Creating team_invites collection\");\n const teamInvitesResult = await create({\n name: \"team_invites\",\n type: \"base\",\n fields: [\n {\n name: \"id\",\n type: \"text\",\n primaryKey: true,\n autogeneratePattern: \"[a-z0-9]{15}\",\n max: 15,\n min: 15,\n pattern: \"^[a-z0-9]+$\",\n required: true,\n },\n {\n name: \"team\",\n type: \"relation\",\n cascadeDelete: true,\n collectionId: teamsCollection.id,\n maxSelect: 1,\n minSelect: 0,\n required: true,\n },\n {\n name: \"email\",\n type: \"email\",\n required: true,\n },\n {\n name: \"created\",\n onCreate: true,\n onUpdate: false,\n type: \"autodate\",\n },\n {\n name: \"updated\",\n onCreate: true,\n onUpdate: true,\n type: \"autodate\",\n },\n ],\n });\n await pushMigrationCreates(\n creates,\n \"team_invites\",\n options,\n teamInvitesResult.created,\n );\n\n logger.info(\"Creating team_invite_links collection\");\n const teamInviteLinksResult = await create({\n name: \"team_invite_links\",\n type: \"base\",\n fields: [\n {\n name: \"id\",\n autogeneratePattern: \"[a-z0-9]{15}\",\n max: 15,\n min: 15,\n pattern: \"^[a-z0-9]+$\",\n primaryKey: true,\n required: true,\n type: \"text\",\n },\n {\n name: \"team\",\n cascadeDelete: true,\n collectionId: teamsCollection.id,\n maxSelect: 1,\n minSelect: 0,\n required: true,\n type: \"relation\",\n },\n {\n name: \"created\",\n onCreate: true,\n onUpdate: false,\n type: \"autodate\",\n },\n {\n name: \"updated\",\n onCreate: true,\n onUpdate: true,\n type: \"autodate\",\n },\n ],\n indexes: [\n \"CREATE UNIQUE INDEX `idx_9y3Oz1KVzz` ON `team_invite_links` (`team`)\",\n ],\n });\n await pushMigrationCreates(\n creates,\n \"team_invite_links\",\n options,\n teamInviteLinksResult.created,\n );\n\n logger.info(\"Applying team rule patches\");\n const ruleMigrations = await applyCollectionRulePatches(\n pb,\n TEAM_RULE_PATCHES,\n options,\n logger,\n );\n creates.push(...ruleMigrations);\n });\n\n const modifies: File[] = [];\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n logger.info(\"Modifying (app) +layout.server.ts\");\n const layoutServerPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(app)\",\n \"+layout.server.ts\",\n );\n pushResult(\n modifyOutcomeToFile(layoutServerPath, modifyLayoutServer(layoutServerPath)),\n );\n\n logger.info(\"Modifying (app) +layout.svelte\");\n const appLayoutPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(app)\",\n \"+layout.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(appLayoutPath, modifyAppLayoutSvelte(appLayoutPath)),\n );\n\n logger.info(\"Modifying app-sidebar\");\n const appSidebarPath = path.join(\n options.root,\n \"src\",\n \"lib\",\n \"components\",\n \"app-sidebar.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(appSidebarPath, modifyAppSidebar(appSidebarPath)),\n );\n\n logger.info(\"Modifying nav-user\");\n const navUserPath = path.join(\n options.root,\n \"src\",\n \"lib\",\n \"components\",\n \"nav-user.svelte\",\n );\n pushResult(modifyOutcomeToFile(navUserPath, modifyNavUser(navUserPath)));\n\n return {\n creates,\n modifies,\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n } satisfies Result;\n}\n"],"mappings":";;;;;;;;;;;;AAIA,IAAM,IAAe;CACnB;CACA;CACA;AACF,CAAC,CAAC,KAAK,IAAI,GAEL,IAAiB;CACrB;CACA;CACA;AACF,CAAC,CAAC,KAAK,IAAI;AAEX,SAAgB,EAAsB,GAAmC;CACvE,IAAI,CAAC,EAAG,WAAW,CAAU,GAC3B,OAAO;EAAE,QAAQ;EAAa,SAAS;CAAe;CAGxD,IAAM,IAAO,EAAW,SAAS,CAAU;CAa3C,OAZK,EAAK,WAAW,YAAY,IAG7B,EAAK,aAAa,cAAc,OAAO,IAClC;EAAE,QAAQ;EAAW,SAAS;CAAM,KAG7C,EAAK,mBACH,cACA,4CACF,GACA,EAAK,QAAQ,CAAU,GAChB;EAAE,QAAQ;EAAW,SAAS,EAAK,WAAW;CAAE,KAX9C;EAAE,QAAQ;EAAU,SAAS;CAA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,SAAS,CACP,sEACF;EACF,CAAC;EAQD,AAPA,MAAM,EACJ,GACA,qBACA,GACA,EAAsB,OACxB,GAEA,EAAO,KAAK,4BAA4B;EACxC,IAAM,IAAiB,MAAM,EAC3B,GACA,GACA,GACA,CACF;EACA,EAAQ,KAAK,GAAG,CAAc;CAChC,CAAC;CAED,IAAM,IAAmB,CAAC,GACpB,KAAc,MAAsB;EACxC,AAAI,KAAM,EAAS,KAAK,CAAI;CAC9B;CAEA,EAAO,KAAK,mCAAmC;CAC/C,IAAM,IAAmB,EAAK,KAC5B,EAAQ,MACR,OACA,UACA,SACA,mBACF;CAKA,AAJA,EACE,EAAoB,GAAkB,EAAmB,CAAgB,CAAC,CAC5E,GAEA,EAAO,KAAK,gCAAgC;CAC5C,IAAM,IAAgB,EAAK,KACzB,EAAQ,MACR,OACA,UACA,SACA,gBACF;CAKA,AAJA,EACE,EAAoB,GAAe,EAAsB,CAAa,CAAC,CACzE,GAEA,EAAO,KAAK,uBAAuB;CACnC,IAAM,IAAiB,EAAK,KAC1B,EAAQ,MACR,OACA,OACA,cACA,oBACF;CAKA,AAJA,EACE,EAAoB,GAAgB,EAAiB,CAAc,CAAC,CACtE,GAEA,EAAO,KAAK,oBAAoB;CAChC,IAAM,IAAc,EAAK,KACvB,EAAQ,MACR,OACA,OACA,cACA,iBACF;CAGA,OAFA,EAAW,EAAoB,GAAa,EAAc,CAAW,CAAC,CAAC,GAEhE;EACL;EACA;EACA,SAAS,CAAC;EACV,YAAY,CAAC;EACb,UAAU,CAAC;EACX,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAiB,CAAC;CACpB;AACF"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"write-result-BhULcFGo.js","names":[],"sources":["../../src/runtime/write-result.ts"],"sourcesContent":["import {\n existsSync,\n mkdirSync,\n readFileSync,\n rmSync,\n writeFileSync,\n} from \"node:fs\";\nimport path from \"node:path\";\nimport { detect } from \"package-manager-detector\";\nimport { resolveCommand } from \"package-manager-detector/commands\";\nimport spawn from \"cross-spawn\";\nimport type { Options, Result } from \"../core/types\";\nimport { getLogger, NOOP_LOGGER, type Logger } from \"../core/logger\";\n\ntype PackageManagerOperation = \"execute\" | \"install\";\ntype ExecuteCommand = (\n cwd: string,\n operation: PackageManagerOperation,\n args: string[],\n) => Promise<void>;\n\ninterface WriteResultRuntime {\n executeCommand?: ExecuteCommand;\n}\n\ntype CustomNpmPackages = Record<string, string[]>;\n\nconst customDependencies: Record<string, string[]> = {\n \"file-form\": [\"input\", \"form\"],\n multiselect: [\"command\", \"popover\", \"button\", \"badge\"],\n geopoint: [\"button\", \"leaflet\"],\n cells: [],\n \"column-header\": [\"dropdown-menu\", \"button\"],\n \"faceted-filter\": [\"command\", \"popover\", \"button\", \"separator\", \"badge\"],\n pagination: [\"button\", \"select\"],\n \"row-actions\": [\"dropdown-menu\", \"button\"],\n leaflet: [],\n \"auth-menu\": [\"dropdown-menu\", \"button\"],\n};\n\nconst customNpmPackages: CustomNpmPackages = {\n \"file-form\": [],\n multiselect: [],\n geopoint: [],\n cells: [],\n \"column-header\": [\"@tanstack/table-core\"],\n \"faceted-filter\": [\"@tanstack/table-core\"],\n pagination: [\"@tanstack/table-core\"],\n \"row-actions\": [],\n leaflet: [\"leaflet\", \"@types/leaflet\"],\n};\n\nconst customComponentAssets = import.meta.glob<string>(\"../ui/components/**\", {\n query: \"?raw\",\n import: \"default\",\n eager: true,\n});\n\nfunction getAllCustomComponents() {\n return [\n ...new Set(\n Object.keys(customComponentAssets).map(componentNameFromAssetPath),\n ),\n ]\n .filter(Boolean)\n .sort();\n}\n\nfunction componentNameFromAssetPath(assetPath: string): string {\n const parts = assetPath.split(\"/\");\n const index = parts.indexOf(\"components\");\n return parts[index + 1] ?? \"\";\n}\n\nfunction componentRelativeAssetPath(assetPath: string): string {\n const parts = assetPath.split(\"/\");\n const index = parts.indexOf(\"components\");\n return parts.slice(index + 2).join(\"/\");\n}\n\nfunction toTargetPath(root: string, filePath: string): string {\n if (path.isAbsolute(filePath)) {\n return filePath;\n }\n return path.join(root, filePath);\n}\n\nfunction toRelativePath(root: string, filePath: string): string {\n if (path.isAbsolute(filePath)) {\n return path.relative(root, filePath);\n }\n return filePath;\n}\n\nfunction writeFile(filePath: string, content: string): void {\n mkdirSync(path.dirname(filePath), { recursive: true });\n writeFileSync(filePath, content, \"utf8\");\n}\n\nfunction removeFile(filePath: string): void {\n if (!existsSync(filePath)) {\n return;\n }\n\n rmSync(filePath, { force: true, recursive: true });\n}\n\nasync function executeWithDetectedPackageManager(\n cwd: string,\n operation: PackageManagerOperation,\n args: string[],\n): Promise<void> {\n const packageManager = (await detect({ cwd }))?.name ?? \"npm\";\n const resolved = resolveCommand(packageManager, operation, args);\n if (!resolved) {\n throw new Error(\n `Unable to resolve ${operation} command for ${packageManager}`,\n );\n }\n\n const commandArgs = [...resolved.args];\n if (packageManager === \"npm\") {\n commandArgs.unshift(\"--yes\");\n }\n\n await new Promise<void>((resolve, reject) => {\n const child = spawn(resolved.command, commandArgs, {\n cwd,\n stdio: \"inherit\",\n });\n child.on(\"error\", reject);\n child.on(\"exit\", (code) => {\n if (code === 0) {\n resolve();\n return;\n }\n reject(\n new Error(`${resolved.command} exited with code ${code ?? \"unknown\"}`),\n );\n });\n });\n}\n\nasync function executeCommand(\n cwd: string,\n operation: PackageManagerOperation,\n args: string[],\n runtime?: WriteResultRuntime,\n): Promise<void> {\n if (runtime?.executeCommand) {\n await runtime.executeCommand(cwd, operation, args);\n return;\n }\n\n await executeWithDetectedPackageManager(cwd, operation, args);\n}\n\nfunction installedPackagesFromProject(root: string): Set<string> {\n const packageJsonPath = path.join(root, \"package.json\");\n if (!existsSync(packageJsonPath)) {\n return new Set();\n }\n\n const packageJson = JSON.parse(readFileSync(packageJsonPath, \"utf8\")) as {\n dependencies?: Record<string, string>;\n devDependencies?: Record<string, string>;\n optionalDependencies?: Record<string, string>;\n peerDependencies?: Record<string, string>;\n };\n\n return new Set([\n ...Object.keys(packageJson.dependencies ?? {}),\n ...Object.keys(packageJson.devDependencies ?? {}),\n ...Object.keys(packageJson.optionalDependencies ?? {}),\n ...Object.keys(packageJson.peerDependencies ?? {}),\n ]);\n}\n\nasync function installPackages(\n root: string,\n packages: string[],\n runtime?: WriteResultRuntime,\n logger: Logger = NOOP_LOGGER,\n): Promise<string[]> {\n if (packages.length === 0) {\n return [];\n }\n\n const installed = installedPackagesFromProject(root);\n const toInstall = [...new Set(packages)].filter((pkg) => !installed.has(pkg));\n if (toInstall.length === 0) {\n return [];\n }\n\n logger.info(`Installing packages: ${toInstall.join(\", \")}`);\n await executeCommand(root, \"install\", toInstall, runtime);\n return toInstall;\n}\n\nfunction isCustomComponent(component: string): boolean {\n return getAllCustomComponents().includes(component);\n}\n\nfunction customNpmPackagesFor(components: string[]): string[] {\n return [\n ...new Set(\n components.flatMap((component) => customNpmPackages[component] ?? []),\n ),\n ];\n}\n\nfunction copyCustomComponent(\n component: string,\n targetComponentsDir: string,\n): void {\n const targetDir = path.join(targetComponentsDir, component);\n mkdirSync(targetDir, { recursive: true });\n\n for (const [assetPath, content] of Object.entries(customComponentAssets)) {\n if (componentNameFromAssetPath(assetPath) !== component) {\n continue;\n }\n const relativePath = componentRelativeAssetPath(assetPath);\n if (!relativePath) {\n continue;\n }\n\n const outputPath = path.join(targetDir, relativePath);\n mkdirSync(path.dirname(outputPath), { recursive: true });\n writeFileSync(outputPath, content, \"utf8\");\n }\n}\n\nasync function installComponents(\n root: string,\n components: string[],\n runtime?: WriteResultRuntime,\n logger: Logger = NOOP_LOGGER,\n): Promise<{ components: string[]; packages: string[] }> {\n if (components.length === 0) {\n return { components: [], packages: [] };\n }\n\n const componentsDir = path.join(root, \"src\", \"lib\", \"components\", \"ui\");\n mkdirSync(componentsDir, { recursive: true });\n\n const requested = [...new Set(components)];\n const missing = requested.filter(\n (component) => !existsSync(path.join(componentsDir, component)),\n );\n\n if (missing.length === 0) {\n return { components: [], packages: [] };\n }\n\n const customToInstall = new Set(missing.filter(isCustomComponent));\n const publicToInstall = new Set(\n missing.filter((component) => !isCustomComponent(component)),\n );\n\n for (const component of [...customToInstall]) {\n for (const dependency of customDependencies[component] ?? []) {\n if (existsSync(path.join(componentsDir, dependency))) {\n continue;\n }\n if (isCustomComponent(dependency)) {\n customToInstall.add(dependency);\n } else {\n publicToInstall.add(dependency);\n }\n }\n }\n\n const installedComponents: string[] = [];\n const customList = [...customToInstall].sort();\n if (customList.length > 0) {\n logger.info(`Installing custom components: ${customList.join(\", \")}`);\n }\n for (const component of customList) {\n copyCustomComponent(component, componentsDir);\n installedComponents.push(component);\n publicToInstall.delete(component);\n }\n\n const customPackages = await installPackages(\n root,\n customNpmPackagesFor([...customToInstall]),\n runtime,\n logger,\n );\n\n const publicList = [...publicToInstall].sort();\n if (publicList.length > 0) {\n logger.info(\n `Installing shadcn-svelte components: ${publicList.join(\", \")}`,\n );\n await executeCommand(\n root,\n \"execute\",\n [\"shadcn-svelte\", \"add\", \"--yes\", \"--overwrite\", ...publicList],\n runtime,\n );\n installedComponents.push(...publicList);\n }\n\n return {\n components: [...new Set(installedComponents)],\n packages: customPackages,\n };\n}\n\nexport async function writeResult(\n result: Result,\n options: Options,\n runtime?: WriteResultRuntime,\n): Promise<Result> {\n const logger = getLogger(options);\n\n const writtenResult: Result = {\n creates: [],\n modifies: [],\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n };\n\n let dropMigrationCreates: Result[\"creates\"] = [];\n if (result.collectionDrops.length > 0) {\n const { dropCollections } = await import(\"./collections\");\n dropMigrationCreates = await dropCollections(\n result.collectionDrops,\n options,\n );\n }\n\n const packageInstalls = await installPackages(\n options.root,\n result.packages,\n runtime,\n logger,\n );\n\n const componentInstalls = await installComponents(\n options.root,\n result.components,\n runtime,\n logger,\n );\n\n for (const file of [...result.creates, ...dropMigrationCreates]) {\n if (file.status !== \"success\") continue;\n const target = toTargetPath(options.root, file.path);\n if (!existsSync(target)) {\n writeFile(target, file.content);\n writtenResult.creates.push({\n ...file,\n path: toRelativePath(options.root, file.path),\n });\n continue;\n }\n if (readFileSync(target, \"utf8\") !== file.content) {\n writeFile(target, file.content);\n writtenResult.modifies.push({\n ...file,\n path: toRelativePath(options.root, file.path),\n });\n }\n }\n\n for (const file of result.modifies) {\n if (file.status !== \"success\") continue;\n writeFile(toTargetPath(options.root, file.path), file.content);\n writtenResult.modifies.push({\n ...file,\n path: toRelativePath(options.root, file.path),\n });\n }\n\n for (const file of result.deletes) {\n if (file.status !== \"success\") continue;\n if (existsSync(toTargetPath(options.root, file.path))) {\n removeFile(toTargetPath(options.root, file.path));\n writtenResult.deletes.push({\n ...file,\n path: toRelativePath(options.root, file.path),\n });\n }\n }\n\n return {\n ...result,\n creates: writtenResult.creates,\n modifies: writtenResult.modifies,\n deletes: writtenResult.deletes,\n components: componentInstalls.components,\n packages: [...new Set([...packageInstalls, ...componentInstalls.packages])],\n };\n}\n"],"mappings":";;;;;;;wv2CA2BM,KAA+C;CACnD,aAAa,CAAC,SAAS,MAAM;CAC7B,aAAa;EAAC;EAAW;EAAW;EAAU;CAAO;CACrD,UAAU,CAAC,UAAU,SAAS;CAC9B,OAAO,CAAC;CACR,iBAAiB,CAAC,iBAAiB,QAAQ;CAC3C,kBAAkB;EAAC;EAAW;EAAW;EAAU;EAAa;CAAO;CACvE,YAAY,CAAC,UAAU,QAAQ;CAC/B,eAAe,CAAC,iBAAiB,QAAQ;CACzC,SAAS,CAAC;CACV,aAAa,CAAC,iBAAiB,QAAQ;AACzC,GAEM,KAAuC;CAC3C,aAAa,CAAC;CACd,aAAa,CAAC;CACd,UAAU,CAAC;CACX,OAAO,CAAC;CACR,iBAAiB,CAAC,sBAAsB;CACxC,kBAAkB,CAAC,sBAAsB;CACzC,YAAY,CAAC,sBAAsB;CACnC,eAAe,CAAC;CAChB,SAAS,CAAC,WAAW,gBAAgB;AACvC,GAEM,IAAwB,uBAAA,OAAA;CAAA,uDAAA;CAAA,qDAAA;CAAA,oDAAA;CA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