@velastack/patterns 0.0.30 → 0.0.32

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/dist/chunks/collections-BRIAYJ-Q.js +94 -0
  2. package/dist/chunks/collections-BRIAYJ-Q.js.map +1 -0
  3. package/dist/chunks/{constants-B5Ub2oFy.js → constants-BMZmCRiI.js} +1 -1
  4. package/dist/chunks/{constants-B5Ub2oFy.js.map → constants-BMZmCRiI.js.map} +1 -1
  5. package/dist/chunks/{dedent-BFNYR8cb.js → dedent-C4qKBQXh.js} +1 -1
  6. package/dist/chunks/{dedent-BFNYR8cb.js.map → dedent-C4qKBQXh.js.map} +1 -1
  7. package/dist/chunks/{env.preview-kw0hC6y8.js → env.preview-NYMljYNr.js} +1 -1
  8. package/dist/chunks/{env.preview-kw0hC6y8.js.map → env.preview-NYMljYNr.js.map} +1 -1
  9. package/dist/chunks/{env.runtime-CJS54CZX.js → env.runtime-ZUZgxjxf.js} +2 -2
  10. package/dist/chunks/{env.runtime-CJS54CZX.js.map → env.runtime-ZUZgxjxf.js.map} +1 -1
  11. package/dist/chunks/errors-Co77I4oK.js +10 -0
  12. package/dist/chunks/errors-Co77I4oK.js.map +1 -0
  13. package/dist/chunks/{generate.runtime-InE8X2Ly.js → generate.runtime-4zd9-8H_.js} +17 -16
  14. package/dist/chunks/{generate.runtime-InE8X2Ly.js.map → generate.runtime-4zd9-8H_.js.map} +1 -1
  15. package/dist/chunks/{generate.runtime-6QnXtCSG.js → generate.runtime-BKrtBCRk.js} +14 -13
  16. package/dist/chunks/{generate.runtime-6QnXtCSG.js.map → generate.runtime-BKrtBCRk.js.map} +1 -1
  17. package/dist/chunks/{generate.runtime-BayXS2PL.js → generate.runtime-BkjQiaP_.js} +12 -11
  18. package/dist/chunks/{generate.runtime-BayXS2PL.js.map → generate.runtime-BkjQiaP_.js.map} +1 -1
  19. package/dist/chunks/{generate.runtime-BpZPXyba.js → generate.runtime-CXqD8em8.js} +13 -12
  20. package/dist/chunks/{generate.runtime-BpZPXyba.js.map → generate.runtime-CXqD8em8.js.map} +1 -1
  21. package/dist/chunks/{generate.runtime-DpT7Jzh4.js → generate.runtime-CbiQhqdL.js} +5 -4
  22. package/dist/chunks/{generate.runtime-DpT7Jzh4.js.map → generate.runtime-CbiQhqdL.js.map} +1 -1
  23. package/dist/chunks/{generate.runtime-BUbI1GmK.js → generate.runtime-DpeB3h-P.js} +15 -14
  24. package/dist/chunks/{generate.runtime-BUbI1GmK.js.map → generate.runtime-DpeB3h-P.js.map} +1 -1
  25. package/dist/chunks/{generate.runtime-B8_5O6Qr.js → generate.runtime-uk9-KOP-.js} +19 -18
  26. package/dist/chunks/{generate.runtime-B8_5O6Qr.js.map → generate.runtime-uk9-KOP-.js.map} +1 -1
  27. package/dist/chunks/{modify-file-CpqC7kMR.js → modify-file-D3OuKUEp.js} +2 -2
  28. package/dist/chunks/{modify-file-CpqC7kMR.js.map → modify-file-D3OuKUEp.js.map} +1 -1
  29. package/dist/chunks/{modify-svelte-config-remote-DWsScM6m.js → modify-svelte-config-remote-Dzgk1OIN.js} +1 -1
  30. package/dist/chunks/{modify-svelte-config-remote-DWsScM6m.js.map → modify-svelte-config-remote-Dzgk1OIN.js.map} +1 -1
  31. package/dist/chunks/{pocketbase-CDu4GzZD.js → pocketbase--dNkFDJ5.js} +1 -1
  32. package/dist/chunks/{pocketbase-CDu4GzZD.js.map → pocketbase--dNkFDJ5.js.map} +1 -1
  33. package/dist/chunks/{pocketbase-CmKcAXDf.js → pocketbase-W_FJaYZ3.js} +3 -3
  34. package/dist/chunks/{pocketbase-CmKcAXDf.js.map → pocketbase-W_FJaYZ3.js.map} +1 -1
  35. package/dist/chunks/{ts-morph-helpers-BMxk6lHK.js → ts-morph-helpers-digNcfBD.js} +1 -1
  36. package/dist/chunks/{ts-morph-helpers-BMxk6lHK.js.map → ts-morph-helpers-digNcfBD.js.map} +1 -1
  37. package/dist/chunks/{util-k-qPjL06.js → util-C064WO8o.js} +4 -3
  38. package/dist/chunks/{util-k-qPjL06.js.map → util-C064WO8o.js.map} +1 -1
  39. package/dist/chunks/{write-result-ENWLDQtP.js → write-result-C80dpjr-.js} +1 -1
  40. package/dist/chunks/{write-result-ENWLDQtP.js.map → write-result-C80dpjr-.js.map} +1 -1
  41. package/dist/index.d.ts +102 -22
  42. package/dist/index.js +1102 -937
  43. package/dist/index.js.map +1 -1
  44. package/package.json +1 -1
  45. package/dist/chunks/collections-Bs9xy7nU.js +0 -54
  46. package/dist/chunks/collections-Bs9xy7nU.js.map +0 -1
  47. /package/dist/chunks/{taggedTemplateLiteral-BLWebVbJ.js → taggedTemplateLiteral-Bfbldyfk.js} +0 -0
package/dist/index.js CHANGED
@@ -1,26 +1,27 @@
1
- import { t as e } from "./chunks/dedent-BFNYR8cb.js";
2
- import { n as t, r as n, t as r } from "./chunks/util-k-qPjL06.js";
3
- import { i, t as a } from "./chunks/constants-B5Ub2oFy.js";
4
- import { t as o } from "./chunks/taggedTemplateLiteral-BLWebVbJ.js";
5
- import { t as s } from "./chunks/pocketbase-CDu4GzZD.js";
6
- import c from "prettier";
7
- import l from "prettier-plugin-svelte";
1
+ import { t as e } from "./chunks/errors-Co77I4oK.js";
2
+ import { t } from "./chunks/dedent-C4qKBQXh.js";
3
+ import { n, r, t as i } from "./chunks/util-C064WO8o.js";
4
+ import { i as a, t as o } from "./chunks/constants-BMZmCRiI.js";
5
+ import { t as s } from "./chunks/taggedTemplateLiteral-Bfbldyfk.js";
6
+ import { t as c } from "./chunks/pocketbase--dNkFDJ5.js";
7
+ import l from "prettier";
8
+ import u from "prettier-plugin-svelte";
8
9
  //#region \0rolldown/runtime.js
9
- var u = Object.create, d = Object.defineProperty, f = Object.getOwnPropertyDescriptor, p = Object.getOwnPropertyNames, m = Object.getPrototypeOf, h = Object.prototype.hasOwnProperty, ee = (e, t) => () => (t || e((t = { exports: {} }).exports, t), t.exports), g = (e, t, n, r) => {
10
- if (t && typeof t == "object" || typeof t == "function") for (var i = p(t), a = 0, o = i.length, s; a < o; a++) s = i[a], !h.call(e, s) && s !== n && d(e, s, {
10
+ var d = Object.create, f = Object.defineProperty, p = Object.getOwnPropertyDescriptor, m = Object.getOwnPropertyNames, h = Object.getPrototypeOf, ee = Object.prototype.hasOwnProperty, g = (e, t) => () => (t || e((t = { exports: {} }).exports, t), t.exports), te = (e, t, n, r) => {
11
+ if (t && typeof t == "object" || typeof t == "function") for (var i = m(t), a = 0, o = i.length, s; a < o; a++) s = i[a], !ee.call(e, s) && s !== n && f(e, s, {
11
12
  get: ((e) => t[e]).bind(null, s),
12
- enumerable: !(r = f(t, s)) || r.enumerable
13
+ enumerable: !(r = p(t, s)) || r.enumerable
13
14
  });
14
15
  return e;
15
- }, te = (e, t, n) => (n = e == null ? {} : u(m(e)), g(t || !e || !e.__esModule ? d(n, "default", {
16
+ }, ne = (e, t, n) => (n = e == null ? {} : d(h(e)), te(t || !e || !e.__esModule ? f(n, "default", {
16
17
  value: e,
17
18
  enumerable: !0
18
- }) : n, e)), ne = /* @__PURE__ */ ((e) => typeof require < "u" ? require : typeof Proxy < "u" ? new Proxy(e, { get: (e, t) => (typeof require < "u" ? require : e)[t] }) : e)(function(e) {
19
+ }) : n, e)), re = /* @__PURE__ */ ((e) => typeof require < "u" ? require : typeof Proxy < "u" ? new Proxy(e, { get: (e, t) => (typeof require < "u" ? require : e)[t] }) : e)(function(e) {
19
20
  if (typeof require < "u") return require.apply(this, arguments);
20
21
  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.");
21
- }), re = {
22
+ }), ie = {
22
23
  name: "@velastack/patterns",
23
- version: "0.0.30",
24
+ version: "0.0.32",
24
25
  type: "module",
25
26
  private: !1,
26
27
  main: "./dist/index.js",
@@ -84,22 +85,18 @@ var u = Object.create, d = Object.defineProperty, f = Object.getOwnPropertyDescr
84
85
  "vite-plugin-dts": "^4.5.4",
85
86
  vitest: "^4.1.4"
86
87
  }
87
- }, _ = class extends Error {
88
- constructor(e) {
89
- super(e), this.name = "InvalidArgumentError";
90
- }
91
88
  };
92
89
  //#endregion
93
90
  //#region src/core/format-result.ts
94
- function ie(e) {
91
+ function ae(e) {
95
92
  return e.language === "ts" || e.language === "svelte" || e.path.endsWith(".json");
96
93
  }
97
- async function ae(e) {
98
- if (e.status !== "success" || !ie(e)) return e;
94
+ async function oe(e) {
95
+ if (e.status !== "success" || !ae(e)) return e;
99
96
  try {
100
- let t = await c.format(e.content, {
97
+ let t = await l.format(e.content, {
101
98
  filepath: e.path,
102
- plugins: [l]
99
+ plugins: [u]
103
100
  });
104
101
  return {
105
102
  ...e,
@@ -109,11 +106,11 @@ async function ae(e) {
109
106
  return e;
110
107
  }
111
108
  }
112
- async function oe(e) {
113
- return Promise.all(e.map((e) => ae(e)));
109
+ async function se(e) {
110
+ return Promise.all(e.map((e) => oe(e)));
114
111
  }
115
- async function v(e) {
116
- let [t, n] = await Promise.all([oe(e.creates), oe(e.modifies)]);
112
+ async function _(e) {
113
+ let [t, n] = await Promise.all([se(e.creates), se(e.modifies)]);
117
114
  return {
118
115
  ...e,
119
116
  creates: t,
@@ -122,7 +119,7 @@ async function v(e) {
122
119
  }
123
120
  //#endregion
124
121
  //#region src/core/field/index.ts
125
- var se = {
122
+ var ce = {
126
123
  text: ["form", "input"],
127
124
  number: ["form", "input"],
128
125
  email: ["form", "input"],
@@ -142,7 +139,7 @@ var se = {
142
139
  url: ["form", "input"],
143
140
  editor: ["form", "textarea"],
144
141
  autodate: ["form", "input"]
145
- }, ce = {
142
+ }, le = {
146
143
  form: ["import * as Form from \"$lib/components/ui/form\";"],
147
144
  "file-form": ["import * as FileForm from \"$lib/components/ui/file-form\";"],
148
145
  multiselect: ["import * as MultiSelect from \"$lib/components/ui/multiselect\";", "import * as Command from \"$lib/components/ui/command\";"],
@@ -153,82 +150,82 @@ var se = {
153
150
  geopoint: ["import { GeopointInput } from \"$lib/components/ui/geopoint\";"],
154
151
  button: ["import { Button } from \"$lib/components/ui/button\";"]
155
152
  };
156
- function y(e) {
153
+ function v(e) {
157
154
  return `$formData.${e.name}`;
158
155
  }
159
- function b(e) {
156
+ function y(e) {
160
157
  return e.inputProps ? Object.entries(e.inputProps).flatMap(([e, t]) => t == null || t === !1 ? [] : t === !0 ? [` ${e}`] : [` ${e}=${JSON.stringify(String(t))}`]).join("") : "";
161
158
  }
162
- function x(t) {
163
- return t.labelAside ? e`
159
+ function b(e) {
160
+ return e.labelAside ? t`
164
161
  <div class="flex justify-between">
165
- <Form.Label>${t.title}</Form.Label>
166
- ${t.labelAside}
162
+ <Form.Label>${e.title}</Form.Label>
163
+ ${e.labelAside}
167
164
  </div>
168
- ` : `<Form.Label>${t.title}</Form.Label>`;
165
+ ` : `<Form.Label>${e.title}</Form.Label>`;
169
166
  }
170
- function S(t, n) {
171
- let r = t.required ? " required" : "";
172
- return e`
173
- <Form.Field {form} name="${t.name}" class="col-span-1">
167
+ function x(e, n) {
168
+ let r = e.required ? " required" : "";
169
+ return t`
170
+ <Form.Field {form} name="${e.name}" class="col-span-1">
174
171
  <Form.Control>
175
172
  {#snippet children({ props })}
176
- ${x(t)}
177
- <Input {...props} type="${n}" bind:value={${y(t)}}${r}${b(t)} />
173
+ ${b(e)}
174
+ <Input {...props} type="${n}" bind:value={${v(e)}}${r}${y(e)} />
178
175
  {/snippet}
179
176
  </Form.Control>
180
177
  <Form.FieldErrors class="contents text-destructive" />
181
178
  </Form.Field>
182
179
  `;
183
180
  }
184
- function le(t) {
185
- let n = t.required ? " required" : "";
186
- return e`
187
- <Form.Field {form} name="${t.name}" class="col-span-2">
181
+ function ue(e) {
182
+ let n = e.required ? " required" : "";
183
+ return t`
184
+ <Form.Field {form} name="${e.name}" class="col-span-2">
188
185
  <Form.Control>
189
186
  {#snippet children({ props })}
190
- ${x(t)}
191
- <Textarea {...props} bind:value={${y(t)}}${n}${b(t)} />
187
+ ${b(e)}
188
+ <Textarea {...props} bind:value={${v(e)}}${n}${y(e)} />
192
189
  {/snippet}
193
190
  </Form.Control>
194
191
  <Form.FieldErrors class="contents text-destructive" />
195
192
  </Form.Field>
196
193
  `;
197
194
  }
198
- function ue(t) {
199
- let n = t.required ? " required" : "";
200
- return e`
201
- <Form.Field {form} name="${t.name}" class="col-span-1 flex items-start space-x-2">
195
+ function de(e) {
196
+ let n = e.required ? " required" : "";
197
+ return t`
198
+ <Form.Field {form} name="${e.name}" class="col-span-1 flex items-start space-x-2">
202
199
  <Form.Control>
203
200
  {#snippet children({ props })}
204
- <Checkbox {...props} bind:checked={${y(t)}}${n}${b(t)} />
205
- ${x(t)}
201
+ <Checkbox {...props} bind:checked={${v(e)}}${n}${y(e)} />
202
+ ${b(e)}
206
203
  {/snippet}
207
204
  </Form.Control>
208
205
  <Form.FieldErrors class="contents text-destructive" />
209
206
  </Form.Field>
210
207
  `;
211
208
  }
212
- function de(t) {
213
- return e`
214
- <Form.Field {form} name="${t.name}" class="col-span-1">
209
+ function fe(e) {
210
+ return t`
211
+ <Form.Field {form} name="${e.name}" class="col-span-1">
215
212
  <Form.Control>
216
213
  {#snippet children({ props })}
217
- ${x(t)}
218
- <GeopointInput {...props} bind:value={${y(t)}} />
214
+ ${b(e)}
215
+ <GeopointInput {...props} bind:value={${v(e)}} />
219
216
  {/snippet}
220
217
  </Form.Control>
221
218
  <Form.FieldErrors class="contents text-destructive" />
222
219
  </Form.Field>
223
220
  `;
224
221
  }
225
- function fe(t) {
226
- let n = t.required ? " required" : "", r = t.maxSelect > 1 ? "Multiple" : "Single";
227
- return e`
228
- <FileForm.Field {form} name="${t.name}" class="col-span-1">
222
+ function pe(e) {
223
+ let n = e.required ? " required" : "", r = e.maxSelect > 1 ? "Multiple" : "Single";
224
+ return t`
225
+ <FileForm.Field {form} name="${e.name}" class="col-span-1">
229
226
  <Form.Control>
230
227
  {#snippet children({ props })}
231
- ${x(t)}
228
+ ${b(e)}
232
229
  <FileForm.${r}>
233
230
  {#snippet display({ file, filename, onremove })}
234
231
  <div class="flex gap-2 justify-between items-center">
@@ -240,7 +237,7 @@ function fe(t) {
240
237
  </div>
241
238
  {/snippet}
242
239
  {#snippet input()}
243
- <FileForm.Input {...props}${n}${b(t)} />
240
+ <FileForm.Input {...props}${n}${y(e)} />
244
241
  {/snippet}
245
242
  </FileForm.${r}>
246
243
  {/snippet}
@@ -249,19 +246,19 @@ function fe(t) {
249
246
  </FileForm.Field>
250
247
  `;
251
248
  }
252
- function pe(t) {
253
- let n = t.maxSelect > 1 ? "multiple" : "single", r = t.required ? " required" : "", i = t.maxSelect > 1 ? "Select options" : "Select an option", a = t.options.map((e) => `<MultiSelect.Item value=${JSON.stringify(e.value)} label={${t.name}Labels[${JSON.stringify(e.value)}].label} />`).join("\n ");
254
- return e`
255
- <MultiSelect.Field {form} type="${n}" name="${t.name}"${r} class="col-span-1">
249
+ function me(e) {
250
+ let n = e.maxSelect > 1 ? "multiple" : "single", r = e.required ? " required" : "", i = e.maxSelect > 1 ? "Select options" : "Select an option", a = e.options.map((t) => `<MultiSelect.Item value=${JSON.stringify(t.value)} label={${e.name}Labels[${JSON.stringify(t.value)}].label} />`).join("\n ");
251
+ return t`
252
+ <MultiSelect.Field {form} type="${n}" name="${e.name}"${r} class="col-span-1">
256
253
  <Form.Control>
257
254
  {#snippet children({ props })}
258
- ${x(t)}
255
+ ${b(e)}
259
256
  <MultiSelect.Trigger class="w-full justify-between">
260
- <MultiSelect.Input bind:value={${y(t)}} placeholder="${i}" {...props}>
257
+ <MultiSelect.Input bind:value={${v(e)}} placeholder="${i}" {...props}>
261
258
  {#snippet children({ selected })}
262
259
  <div class="flex flex-wrap gap-1">
263
260
  {#each selected as value}
264
- <MultiSelect.Chip>{${t.name}Labels[value].label}</MultiSelect.Chip>
261
+ <MultiSelect.Chip>{${e.name}Labels[value].label}</MultiSelect.Chip>
265
262
  {/each}
266
263
  </div>
267
264
  {/snippet}
@@ -284,20 +281,20 @@ function pe(t) {
284
281
  </MultiSelect.Field>
285
282
  `;
286
283
  }
287
- function me(t) {
288
- let n = t.maxSelect > 1 ? "multiple" : "single", r = t.maxSelect > 1 ? `Select ${t.relatedModel.pluralDisplayName.toLowerCase()}` : `Select ${t.relatedModel.displayName.toLowerCase()}`, i = `Search ${t.relatedModel.pluralDisplayName.toLowerCase()}...`, a = `No ${t.relatedModel.pluralDisplayName.toLowerCase()} found`, o = t.relatedModel.name, s = t.relatedModel.pluralName;
289
- return e`
290
- <MultiSelect.Field {form} type="${n}" name="${t.name}" class="col-span-1">
284
+ function he(e) {
285
+ let n = e.maxSelect > 1 ? "multiple" : "single", r = e.maxSelect > 1 ? `Select ${e.relatedModel.pluralDisplayName.toLowerCase()}` : `Select ${e.relatedModel.displayName.toLowerCase()}`, i = `Search ${e.relatedModel.pluralDisplayName.toLowerCase()}...`, a = `No ${e.relatedModel.pluralDisplayName.toLowerCase()} found`, o = e.relatedModel.name, s = e.relatedModel.pluralName;
286
+ return t`
287
+ <MultiSelect.Field {form} type="${n}" name="${e.name}" class="col-span-1">
291
288
  <Form.Control>
292
289
  {#snippet children({ props })}
293
- <Form.Label>${t.title}</Form.Label>
290
+ <Form.Label>${e.title}</Form.Label>
294
291
  <MultiSelect.Trigger class="w-full justify-between">
295
- <MultiSelect.Input bind:value={${y(t)}} placeholder="${r}" {...props}>
292
+ <MultiSelect.Input bind:value={${v(e)}} placeholder="${r}" {...props}>
296
293
  {#snippet children({ selected })}
297
294
  <div class="flex flex-wrap gap-1">
298
295
  {#each selected as value}
299
296
  {@const ${o} = data.${s}.find((${o}) => ${o}.id === value)!}
300
- <MultiSelect.Chip>{${o}.${t.displayField}}</MultiSelect.Chip>
297
+ <MultiSelect.Chip>{${o}.${e.displayField}}</MultiSelect.Chip>
301
298
  {/each}
302
299
  </div>
303
300
  {/snippet}
@@ -312,7 +309,7 @@ function me(t) {
312
309
  <Command.Empty>${a}</Command.Empty>
313
310
  <Command.Group>
314
311
  {#each data.${s} as ${o}}
315
- <MultiSelect.Item value={${o}.id} label={${o}.${t.displayField}} />
312
+ <MultiSelect.Item value={${o}.id} label={${o}.${e.displayField}} />
316
313
  {/each}
317
314
  </Command.Group>
318
315
  </Command.Root>
@@ -322,93 +319,93 @@ function me(t) {
322
319
  </MultiSelect.Field>
323
320
  `;
324
321
  }
325
- function he(t) {
326
- return e`
327
- <Form.Field {form} name="${t.name}" class="col-span-1">
322
+ function ge(e) {
323
+ return t`
324
+ <Form.Field {form} name="${e.name}" class="col-span-1">
328
325
  <Form.Control>
329
326
  {#snippet children({ props })}
330
- ${x(t)}
331
- <Input {...props} type="text" value={${y(t)}}${b(t)} readonly />
327
+ ${b(e)}
328
+ <Input {...props} type="text" value={${v(e)}}${y(e)} readonly />
332
329
  {/snippet}
333
330
  </Form.Control>
334
331
  <Form.FieldErrors class="contents text-destructive" />
335
332
  </Form.Field>
336
333
  `;
337
334
  }
338
- function ge(e) {
335
+ function _e(e) {
339
336
  switch (e.type) {
340
- case "text": return S(e, "text");
341
- case "number": return S(e, "number");
342
- case "date": return S(e, "date");
343
- case "email": return S(e, "email");
344
- case "password": return S(e, "password");
345
- case "url": return S(e, "url");
346
- case "autodate": return he(e);
337
+ case "text": return x(e, "text");
338
+ case "number": return x(e, "number");
339
+ case "date": return x(e, "date");
340
+ case "email": return x(e, "email");
341
+ case "password": return x(e, "password");
342
+ case "url": return x(e, "url");
343
+ case "autodate": return ge(e);
347
344
  case "editor":
348
- case "json": return le(e);
349
- case "bool": return ue(e);
350
- case "geoPoint": return de(e);
351
- case "file": return fe(e);
352
- case "select": return pe(e);
353
- case "relation": return me(e);
345
+ case "json": return ue(e);
346
+ case "bool": return de(e);
347
+ case "geoPoint": return fe(e);
348
+ case "file": return pe(e);
349
+ case "select": return me(e);
350
+ case "relation": return he(e);
354
351
  default: return e;
355
352
  }
356
353
  }
357
- function _e(t) {
358
- let n = t.options.map((t) => e`
359
- ${JSON.stringify(t.value)}: {
360
- label: ${JSON.stringify(t.label)},
361
- value: ${JSON.stringify(t.value)}
354
+ function S(e) {
355
+ let n = e.options.map((e) => t`
356
+ ${JSON.stringify(e.value)}: {
357
+ label: ${JSON.stringify(e.label)},
358
+ value: ${JSON.stringify(e.value)}
362
359
  }
363
360
  `).join(",\n");
364
- return e`
365
- const ${t.name}Labels = {
361
+ return t`
362
+ const ${e.name}Labels = {
366
363
  ${n}
367
364
  } as const;
368
365
  `;
369
366
  }
370
367
  function C(e) {
371
- let t = e.flatMap((e) => se[e.type]);
368
+ let t = e.flatMap((e) => ce[e.type]);
372
369
  return [...new Set(t)];
373
370
  }
374
- function ve(e) {
375
- return [...new Set(e.flatMap((e) => ce[e]))];
371
+ function w(e) {
372
+ return [...new Set(e.flatMap((e) => le[e]))];
376
373
  }
377
- function w(e, t) {
374
+ function T(e, t) {
378
375
  return `data.${e.name}.${t.name}`;
379
376
  }
380
- function T(t, n, r) {
381
- return e`
377
+ function ve(e, n, r) {
378
+ return t`
382
379
  <div class="space-y-2">
383
380
  <h3 class="font-medium leading-none">${n.title}</h3>
384
381
  <p class="text-muted-foreground">${r}</p>
385
382
  </div>
386
383
  `;
387
384
  }
388
- function ye(t, n) {
389
- let r = w(t, n), i = `<p class="text-muted-foreground">{new Date(${r}).toLocaleDateString()}</p>`, a = n.required ? i : e`
385
+ function ye(e, n) {
386
+ let r = T(e, n), i = `<p class="text-muted-foreground">{new Date(${r}).toLocaleDateString()}</p>`, a = n.required ? i : t`
390
387
  {#if ${r}}
391
388
  ${i}
392
389
  {/if}
393
390
  `;
394
- return e`
391
+ return t`
395
392
  <div class="space-y-2">
396
393
  <h3 class="font-medium leading-none">${n.title}</h3>
397
394
  ${a}
398
395
  </div>
399
396
  `;
400
397
  }
401
- function be(t, n) {
402
- let r = w(t, n), i = e`
398
+ function be(e, n) {
399
+ let r = T(e, n), i = t`
403
400
  <a href={${r}} target="_blank" rel="noopener noreferrer">
404
401
  {${r}}
405
402
  </a>
406
- `, a = n.required ? i : e`
403
+ `, a = n.required ? i : t`
407
404
  {#if ${r}}
408
405
  ${i}
409
406
  {/if}
410
407
  `;
411
- return e`
408
+ return t`
412
409
  <div class="space-y-2">
413
410
  <h3 class="font-medium leading-none">${n.title}</h3>
414
411
  <p class="text-muted-foreground">
@@ -417,9 +414,9 @@ function be(t, n) {
417
414
  </div>
418
415
  `;
419
416
  }
420
- function xe(t, n) {
421
- let r = w(t, n);
422
- if (n.maxSelect > 1) return e`
417
+ function xe(e, n) {
418
+ let r = T(e, n);
419
+ if (n.maxSelect > 1) return t`
423
420
  <div class="space-y-2">
424
421
  <h3 class="font-medium leading-none">${n.title}</h3>
425
422
  {#each ${r} as ${n.name}}
@@ -427,21 +424,21 @@ function xe(t, n) {
427
424
  {/each}
428
425
  </div>
429
426
  `;
430
- let i = `<Badge variant="outline" class="mr-1">{${n.name}Labels[${r}].label}</Badge>`, a = n.required ? i : e`
427
+ let i = `<Badge variant="outline" class="mr-1">{${n.name}Labels[${r}].label}</Badge>`, a = n.required ? i : t`
431
428
  {#if ${r}}
432
429
  ${i}
433
430
  {/if}
434
431
  `;
435
- return e`
432
+ return t`
436
433
  <div class="space-y-2">
437
434
  <h3 class="font-medium leading-none">${n.title}</h3>
438
435
  ${a}
439
436
  </div>
440
437
  `;
441
438
  }
442
- function Se(t, n) {
443
- let r = w(t, n);
444
- return n.maxSelect > 1 ? e`
439
+ function Se(e, n) {
440
+ let r = T(e, n);
441
+ return n.maxSelect > 1 ? t`
445
442
  <div class="space-y-2">
446
443
  <h3 class="font-medium leading-none">${n.title}</h3>
447
444
  {#if ${r}}
@@ -449,7 +446,7 @@ function Se(t, n) {
449
446
  <div class="flex gap-2 items-center">
450
447
  {#if [".jpg", ".png", ".jpeg", ".webp", ".gif"].some((ext) => filename.endsWith(ext))}
451
448
  <img
452
- src="/api/files/{data.${t.name}.collectionId}/{data.${t.name}.id}/{filename}"
449
+ src="/api/files/{data.${e.name}.collectionId}/{data.${e.name}.id}/{filename}"
453
450
  alt={filename}
454
451
  class="w-16 h-16 rounded-md object-cover"
455
452
  />
@@ -463,14 +460,14 @@ function Se(t, n) {
463
460
  {/each}
464
461
  {/if}
465
462
  </div>
466
- ` : e`
463
+ ` : t`
467
464
  <div class="space-y-2">
468
465
  <h3 class="font-medium leading-none">${n.title}</h3>
469
466
  {#if ${r}}
470
467
  <div class="flex gap-2 items-center">
471
468
  {#if [".jpg", ".png", ".jpeg", ".webp", ".gif"].some((ext) => ${r}?.endsWith(ext))}
472
469
  <img
473
- src="/api/files/{data.${t.name}.collectionId}/{data.${t.name}.id}/{${r}}"
470
+ src="/api/files/{data.${e.name}.collectionId}/{data.${e.name}.id}/{${r}}"
474
471
  alt={${r}}
475
472
  class="w-16 h-16 rounded-md object-cover"
476
473
  />
@@ -488,9 +485,9 @@ function Se(t, n) {
488
485
  function Ce(e) {
489
486
  return `/${e.relatedModel.routeSegment}`;
490
487
  }
491
- function we(t, n) {
492
- let r = `data.${t.name}.expand?.${n.name}`, i = Ce(n);
493
- return n.maxSelect > 1 ? e`
488
+ function we(e, n) {
489
+ let r = `data.${e.name}.expand?.${n.name}`, i = Ce(n);
490
+ return n.maxSelect > 1 ? t`
494
491
  <div class="space-y-2">
495
492
  <h3 class="font-medium leading-none">${n.title}</h3>
496
493
  {#each ${r} ?? [] as ${n.singularRelationName}}
@@ -502,7 +499,7 @@ function we(t, n) {
502
499
  </a>
503
500
  {/each}
504
501
  </div>
505
- ` : e`
502
+ ` : t`
506
503
  <div class="space-y-2">
507
504
  <h3 class="font-medium leading-none">${n.title}</h3>
508
505
  {#if ${r}}
@@ -516,8 +513,8 @@ function we(t, n) {
516
513
  </div>
517
514
  `;
518
515
  }
519
- function Te(t, n) {
520
- let r = w(t, n), i = e`
516
+ function Te(e, n) {
517
+ let r = T(e, n), i = t`
521
518
  {#await import("$lib/components/ui/leaflet/leaflet.svelte")}
522
519
  <div class="h-56.25 w-full bg-input rounded-md"></div>
523
520
  {:then { default: Leaflet }}
@@ -526,25 +523,25 @@ function Te(t, n) {
526
523
  <p class="text-muted-foreground">
527
524
  {${r}?.lat.toFixed(6)}, {${r}?.lon.toFixed(6)}
528
525
  </p>
529
- `, a = n.required ? i : e`
526
+ `, a = n.required ? i : t`
530
527
  {#if ${r}}
531
528
  ${i}
532
529
  {/if}
533
530
  `;
534
- return e`
531
+ return t`
535
532
  <div class="space-y-2">
536
533
  <h3 class="font-medium leading-none">${n.title}</h3>
537
534
  ${a}
538
535
  </div>
539
536
  `;
540
537
  }
541
- function Ee(t, n) {
538
+ function Ee(e, n) {
542
539
  switch (n.type) {
543
540
  case "text":
544
541
  case "number":
545
542
  case "email":
546
- case "editor": return T(t, n, `{${w(t, n)}}`);
547
- case "password": return e`
543
+ case "editor": return ve(e, n, `{${T(e, n)}}`);
544
+ case "password": return t`
548
545
  <div class="space-y-2">
549
546
  <h3 class="font-medium leading-none">${n.title}</h3>
550
547
  <p class="text-muted-foreground">
@@ -552,15 +549,15 @@ function Ee(t, n) {
552
549
  </p>
553
550
  </div>
554
551
  `;
555
- case "bool": return T(t, n, `{${w(t, n)} ? "Yes" : "No"}`);
552
+ case "bool": return ve(e, n, `{${T(e, n)} ? "Yes" : "No"}`);
556
553
  case "date":
557
- case "autodate": return ye(t, n);
558
- case "url": return be(t, n);
559
- case "select": return xe(t, n);
560
- case "file": return Se(t, n);
561
- case "json": return T(t, n, `{JSON.stringify(${w(t, n)})}`);
562
- case "geoPoint": return Te(t, n);
563
- case "relation": return we(t, n);
554
+ case "autodate": return ye(e, n);
555
+ case "url": return be(e, n);
556
+ case "select": return xe(e, n);
557
+ case "file": return Se(e, n);
558
+ case "json": return ve(e, n, `{JSON.stringify(${T(e, n)})}`);
559
+ case "geoPoint": return Te(e, n);
560
+ case "relation": return we(e, n);
564
561
  default: return n;
565
562
  }
566
563
  }
@@ -650,10 +647,10 @@ function O(e, t = {}) {
650
647
  }
651
648
  //#endregion
652
649
  //#region src/parse/model.ts
653
- var k = /* @__PURE__ */ te((/* @__PURE__ */ ee(((e, t) => {
650
+ var k = /* @__PURE__ */ ne((/* @__PURE__ */ g(((e, t) => {
654
651
  (function(n, r) {
655
652
  /* istanbul ignore else */
656
- typeof ne == "function" && typeof e == "object" && typeof t == "object" ? t.exports = r() : typeof define == "function" && define.amd ? define(function() {
653
+ typeof re == "function" && typeof e == "object" && typeof t == "object" ? t.exports = r() : typeof define == "function" && define.amd ? define(function() {
657
654
  return r();
658
655
  }) : n.pluralize = r();
659
656
  })(e, function() {
@@ -972,11 +969,11 @@ var k = /* @__PURE__ */ te((/* @__PURE__ */ ee(((e, t) => {
972
969
  function Ge(e) {
973
970
  return Ue.has(e) ? We[e] ?? `${e}_` : e;
974
971
  }
975
- function Ke(e) {
976
- if (!/^[a-zA-Z][a-zA-Z0-9-_/]*$/.test(e)) throw new _("Model path must start with a letter and contain only alphanumeric characters, dash, slash, or underscore");
972
+ function Ke(t) {
973
+ if (!/^[a-zA-Z][a-zA-Z0-9-_/]*$/.test(t)) throw new e("Model path must start with a letter and contain only alphanumeric characters, dash, slash, or underscore");
977
974
  }
978
975
  function qe(e) {
979
- return e.features.auth ? `src/routes/${a}` : `src/routes/${i}`;
976
+ return e.features.auth ? `src/routes/${o}` : `src/routes/${a}`;
980
977
  }
981
978
  function A(e, t) {
982
979
  let n = e.split("/"), r = n[n.length - 1], i = n.slice(0, -1), a = k.default.singular(Le(r)), o = k.default.plural(a), s = E(a), c = Re(o), l = [...i, c].join("/");
@@ -1109,9 +1106,9 @@ function rt(e, t, n = {}) {
1109
1106
  let n = f(e) - f(t);
1110
1107
  return n === 0 ? p(e).localeCompare(p(t)) : n;
1111
1108
  });
1112
- let g = m[0], te = g.map((e) => e.fieldName), ne = [t, ...g.map((e) => e.to)], re = g[g.length - 1].isMulti ? "?=" : "=", _ = te.join(".");
1109
+ let g = m[0], te = g.map((e) => e.fieldName), ne = [t, ...g.map((e) => e.to)], re = g[g.length - 1].isMulti ? "?=" : "=", ie = te.join(".");
1113
1110
  return {
1114
- rule: `@request.auth.id ${re} ${n.includeRootPrefix ? (n.rootPrefix ?? t) + "." : ""}${_}.id`,
1111
+ rule: `@request.auth.id ${re} ${n.includeRootPrefix ? (n.rootPrefix ?? t) + "." : ""}${ie}.id`,
1115
1112
  ownershipChainCollections: ne,
1116
1113
  ownershipChainFields: te,
1117
1114
  operator: re
@@ -1260,91 +1257,91 @@ function M(e, t, n, r, i, a) {
1260
1257
  maxSelect: e === c ? 999 : 1
1261
1258
  };
1262
1259
  }
1263
- function dt(e, t, n, r, i) {
1264
- let a = Le(e), { type: o, required: s, selectOptions: c } = t, l = Qe(r), u = $e(r), d = et(r), f = l.map((e) => k.default.singular(e));
1265
- if (i.features.auth && o === "current_user" && u.users) {
1266
- let t = M(e, "users", n, u, d, i);
1260
+ function dt(t, n, r, i, a) {
1261
+ let o = Le(t), { type: s, required: c, selectOptions: l } = n, u = Qe(i), d = $e(i), f = et(i), p = u.map((e) => k.default.singular(e));
1262
+ if (a.features.auth && s === "current_user" && d.users) {
1263
+ let e = M(t, "users", r, d, f, a);
1267
1264
  return {
1268
1265
  type: "relation",
1269
- name: e,
1270
- title: a,
1271
- required: s,
1272
- collectionId: t.collectionId,
1266
+ name: t,
1267
+ title: o,
1268
+ required: c,
1269
+ collectionId: e.collectionId,
1273
1270
  maxSelect: 1,
1274
- displayField: t.displayField,
1275
- relatedModel: t.relatedModel,
1276
- singularRelationName: t.singularRelationName,
1277
- pluralRelationName: t.pluralRelationName,
1271
+ displayField: e.displayField,
1272
+ relatedModel: e.relatedModel,
1273
+ singularRelationName: e.singularRelationName,
1274
+ pluralRelationName: e.pluralRelationName,
1278
1275
  isCurrentUser: !0
1279
1276
  };
1280
1277
  }
1281
- if (o === "autodate") {
1282
- let t = e.includes("create"), n = e.includes("update");
1283
- if (!t && !n) throw new _(`Invalid autodate field: ${e}. Must be one of created/created_at/updated/updated_at.`);
1278
+ if (s === "autodate") {
1279
+ let n = t.includes("create"), r = t.includes("update");
1280
+ if (!n && !r) throw new e(`Invalid autodate field: ${t}. Must be one of created/created_at/updated/updated_at.`);
1284
1281
  return {
1285
1282
  type: "autodate",
1286
- name: e,
1287
- title: a,
1288
- required: s,
1289
- onCreate: t,
1290
- onUpdate: n
1283
+ name: t,
1284
+ title: o,
1285
+ required: c,
1286
+ onCreate: n,
1287
+ onUpdate: r
1291
1288
  };
1292
1289
  }
1293
- if (o === "select") return {
1290
+ if (s === "select") return {
1294
1291
  type: "select",
1295
- name: e,
1296
- title: a,
1297
- required: s,
1298
- maxSelect: ut(e),
1299
- options: c
1292
+ name: t,
1293
+ title: o,
1294
+ required: c,
1295
+ maxSelect: ut(t),
1296
+ options: l
1300
1297
  };
1301
- if (o === "file") return {
1298
+ if (s === "file") return {
1302
1299
  type: "file",
1303
- name: e,
1304
- title: a,
1305
- required: s,
1306
- maxSelect: ut(e)
1300
+ name: t,
1301
+ title: o,
1302
+ required: c,
1303
+ maxSelect: ut(t)
1307
1304
  };
1308
- if (o === "relation") {
1309
- let t = k.default.singular(e), r = k.default.plural(t);
1310
- if (!l.includes(r)) throw new _(`Invalid relation field: ${e}. Must be one of ${l.join(", ")} (singular or plural)`);
1305
+ if (s === "relation") {
1306
+ let n = k.default.singular(t), i = k.default.plural(n);
1307
+ if (!u.includes(i)) throw new e(`Invalid relation field: ${t}. Must be one of ${u.join(", ")} (singular or plural)`);
1311
1308
  return {
1312
1309
  type: "relation",
1313
- name: e,
1314
- title: a,
1315
- required: s,
1316
- ...M(e, r, n, u, d, i),
1310
+ name: t,
1311
+ title: o,
1312
+ required: c,
1313
+ ...M(t, i, r, d, f, a),
1317
1314
  isCurrentUser: !1
1318
1315
  };
1319
1316
  }
1320
- if (l.includes(o)) return {
1317
+ if (u.includes(s)) return {
1321
1318
  type: "relation",
1322
- name: e,
1323
- title: a,
1324
- required: s,
1325
- ...M(e, o, n, u, d, i),
1319
+ name: t,
1320
+ title: o,
1321
+ required: c,
1322
+ ...M(t, s, r, d, f, a),
1326
1323
  isCurrentUser: !1
1327
1324
  };
1328
- if (f.includes(o)) {
1329
- let t = k.default.plural(o);
1330
- if (l.includes(t)) {
1331
- let r = M(e, t, n, u, d, i);
1325
+ if (p.includes(s)) {
1326
+ let e = k.default.plural(s);
1327
+ if (u.includes(e)) {
1328
+ let n = M(t, e, r, d, f, a);
1332
1329
  return {
1333
1330
  type: "relation",
1334
- name: e,
1335
- title: a,
1336
- required: s,
1337
- collectionId: r.collectionId,
1338
- displayField: r.displayField,
1339
- relatedModel: r.relatedModel,
1340
- singularRelationName: r.singularRelationName,
1341
- pluralRelationName: r.pluralRelationName,
1331
+ name: t,
1332
+ title: o,
1333
+ required: c,
1334
+ collectionId: n.collectionId,
1335
+ displayField: n.displayField,
1336
+ relatedModel: n.relatedModel,
1337
+ singularRelationName: n.singularRelationName,
1338
+ pluralRelationName: n.pluralRelationName,
1342
1339
  maxSelect: 1,
1343
1340
  isCurrentUser: !1
1344
1341
  };
1345
1342
  }
1346
1343
  }
1347
- let p = [...new Set([
1344
+ let m = [...new Set([
1348
1345
  "text",
1349
1346
  "number",
1350
1347
  "bool",
@@ -1359,8 +1356,8 @@ function dt(e, t, n, r, i) {
1359
1356
  "select",
1360
1357
  "file",
1361
1358
  "relation",
1362
- ...i.features.auth ? ["current_user"] : [],
1363
- ...l
1359
+ ...a.features.auth ? ["current_user"] : [],
1360
+ ...u
1364
1361
  ])];
1365
1362
  if (![
1366
1363
  "text",
@@ -1373,36 +1370,36 @@ function dt(e, t, n, r, i) {
1373
1370
  "editor",
1374
1371
  "json",
1375
1372
  "geoPoint"
1376
- ].includes(o)) throw new _(`Invalid field type: ${o}. Valid types are: ${p.join(", ").replace("relation", "references")}`);
1373
+ ].includes(s)) throw new e(`Invalid field type: ${s}. Valid types are: ${m.join(", ").replace("relation", "references")}`);
1377
1374
  return {
1378
- type: o,
1379
- name: e,
1380
- title: a,
1381
- required: s
1375
+ type: s,
1376
+ name: t,
1377
+ title: o,
1378
+ required: c
1382
1379
  };
1383
1380
  }
1384
- function ft(e, t, n, r) {
1385
- let i = [];
1386
- for (let a of e) {
1387
- let [e, o] = it(a);
1388
- if (!e || !o) throw new _(`Invalid field format: ${a}. Expected format: name:type or name:type!`);
1389
- if (!/^[a-zA-Z][a-zA-Z0-9]*$/.test(e)) throw new _(`Invalid field name: ${e}. Must start with a letter and contain only alphanumeric characters`);
1390
- let s = lt(o);
1391
- i.push(dt(e, s, t, n, r));
1381
+ function ft(t, n, r, i) {
1382
+ let a = [];
1383
+ for (let o of t) {
1384
+ let [t, s] = it(o);
1385
+ if (!t || !s) throw new e(`Invalid field format: ${o}. Expected format: name:type or name:type!`);
1386
+ if (!/^[a-zA-Z][a-zA-Z0-9]*$/.test(t)) throw new e(`Invalid field name: ${t}. Must start with a letter and contain only alphanumeric characters`);
1387
+ let c = lt(s);
1388
+ a.push(dt(t, c, n, r, i));
1392
1389
  }
1393
1390
  return {
1394
- fields: i,
1395
- auth: r.features.auth ? rt([...n, {
1391
+ fields: a,
1392
+ auth: i.features.auth ? rt([...r, {
1396
1393
  id: "new",
1397
- name: t.tableName,
1394
+ name: n.tableName,
1398
1395
  type: "base",
1399
- fields: i.map((e) => ({
1396
+ fields: a.map((e) => ({
1400
1397
  name: e.name,
1401
1398
  type: e.type,
1402
1399
  collectionId: e.type === "relation" ? e.collectionId : void 0,
1403
1400
  maxSelect: "maxSelect" in e ? e.maxSelect : void 0
1404
1401
  }))
1405
- }], t.tableName) : void 0
1402
+ }], n.tableName) : void 0
1406
1403
  };
1407
1404
  }
1408
1405
  //#endregion
@@ -1566,8 +1563,8 @@ function xt(e, t) {
1566
1563
  })
1567
1564
  };
1568
1565
  }
1569
- function L(t, n, r, i) {
1570
- let a = yt(i.find((e) => e.name === t.tableName) ?? xt(t, n), i).filter((e) => !(r.features.auth && e.name === "users")), o = {}, s = [], c = /* @__PURE__ */ new Set();
1566
+ function L(e, n, r, i) {
1567
+ let a = yt(i.find((t) => t.name === e.tableName) ?? xt(e, n), i).filter((e) => !(r.features.auth && e.name === "users")), o = {}, s = [], c = /* @__PURE__ */ new Set();
1571
1568
  for (let e of a) {
1572
1569
  let t = bt(A(e.name, r).name, c);
1573
1570
  s.push({
@@ -1579,11 +1576,11 @@ function L(t, n, r, i) {
1579
1576
  let n = _t(t.fields, o, r);
1580
1577
  return t.type === "auth" && vt(n), `${e} = await context.admin.collection("${t.name}").create(${F(n)});`;
1581
1578
  }), d = s.slice().reverse().map(({ varName: e, collection: t }) => `await context.admin.collection("${t.name}").delete(${e}.id);`), f = r.features.auth ? "context.agent" : "context.request", p = r.features.auth ? "await context.agent.authenticateUser();\n " : "", m = "";
1582
- return (u.length > 0 || r.features.auth) && (m += e`
1579
+ return (u.length > 0 || r.features.auth) && (m += t`
1583
1580
  beforeEach(async (context) => {
1584
1581
  ${p}${u.join("\n ")}
1585
1582
  });
1586
- `), d.length > 0 && (m += "\n\n" + e`
1583
+ `), d.length > 0 && (m += "\n\n" + t`
1587
1584
  afterEach(async (context) => {
1588
1585
  ${d.join("\n ")}
1589
1586
  });
@@ -1601,12 +1598,12 @@ function L(t, n, r, i) {
1601
1598
  }))
1602
1599
  };
1603
1600
  }
1604
- function St(t, n, r, i, a) {
1605
- let { declarations: o, setupSection: s, requestAgent: c, modelDbData: l, modelFormData: u } = L(t, r, i, a);
1606
- return e`
1601
+ function St(e, n, r, i, a) {
1602
+ let { declarations: o, setupSection: s, requestAgent: c, modelDbData: l, modelFormData: u } = L(e, r, i, a);
1603
+ return t`
1607
1604
  import { afterEach, beforeEach, describe, expect, it } from "vitest";
1608
1605
 
1609
- describe("${t.pluralName}", () => {
1606
+ describe("${e.pluralName}", () => {
1610
1607
  ${o}${s}
1611
1608
 
1612
1609
  describe("GET ${n.list}", () => {
@@ -1624,7 +1621,7 @@ function St(t, n, r, i, a) {
1624
1621
  });
1625
1622
 
1626
1623
  describe("POST ${n.new}", () => {
1627
- it("should create a new ${t.displayName.toLowerCase()}", async (context) => {
1624
+ it("should create a new ${e.displayName.toLowerCase()}", async (context) => {
1628
1625
  const response = await ${c}.post("${n.new}").type("form").send(${u});
1629
1626
  expect(response.body.status).toBe(303);
1630
1627
 
@@ -1635,7 +1632,7 @@ function St(t, n, r, i, a) {
1635
1632
 
1636
1633
  describe("GET ${n.show}", () => {
1637
1634
  it("should return a 200 status code", async (context) => {
1638
- const { id } = await context.admin.collection("${t.tableName}").create(${l});
1635
+ const { id } = await context.admin.collection("${e.tableName}").create(${l});
1639
1636
  const response = await ${c}.get(\`${I(n.show, "id")}\`);
1640
1637
  expect(response.status).toBe(200);
1641
1638
  });
@@ -1647,8 +1644,8 @@ function St(t, n, r, i, a) {
1647
1644
  });
1648
1645
 
1649
1646
  describe("POST ${n.show}", () => {
1650
- it("should delete a ${t.displayName.toLowerCase()}", async (context) => {
1651
- const { id } = await context.admin.collection("${t.tableName}").create(${l});
1647
+ it("should delete a ${e.displayName.toLowerCase()}", async (context) => {
1648
+ const { id } = await context.admin.collection("${e.tableName}").create(${l});
1652
1649
  const response = await ${c}.post(\`${I(n.show, "id")}\`).type("form");
1653
1650
  expect(response.body.status).toBe(303);
1654
1651
 
@@ -1659,15 +1656,15 @@ function St(t, n, r, i, a) {
1659
1656
 
1660
1657
  describe("GET ${n.edit}", () => {
1661
1658
  it("should return a 200 status code", async (context) => {
1662
- const { id } = await context.admin.collection("${t.tableName}").create(${l});
1659
+ const { id } = await context.admin.collection("${e.tableName}").create(${l});
1663
1660
  const response = await ${c}.get(\`${I(n.edit, "id")}\`);
1664
1661
  expect(response.status).toBe(200);
1665
1662
  });
1666
1663
  });
1667
1664
 
1668
1665
  describe("POST ${n.edit}", () => {
1669
- it("should update a ${t.displayName.toLowerCase()}", async (context) => {
1670
- const { id } = await context.admin.collection("${t.tableName}").create(${l});
1666
+ it("should update a ${e.displayName.toLowerCase()}", async (context) => {
1667
+ const { id } = await context.admin.collection("${e.tableName}").create(${l});
1671
1668
  const response = await ${c}
1672
1669
  .post(\`${I(n.edit, "id")}\`)
1673
1670
  .type("form")
@@ -1679,12 +1676,12 @@ function St(t, n, r, i, a) {
1679
1676
  });
1680
1677
  `;
1681
1678
  }
1682
- function Ct(t, n, r, i, a) {
1683
- let { declarations: o, setupSection: s, requestAgent: c, modelDbData: l } = L(t, r, i, a);
1684
- return e`
1679
+ function Ct(e, n, r, i, a) {
1680
+ let { declarations: o, setupSection: s, requestAgent: c, modelDbData: l } = L(e, r, i, a);
1681
+ return t`
1685
1682
  import { afterEach, beforeEach, describe, expect, it } from "vitest";
1686
1683
 
1687
- describe("${t.pluralName}", () => {
1684
+ describe("${e.pluralName}", () => {
1688
1685
  ${o}${s}
1689
1686
 
1690
1687
  describe("GET ${n.list}", () => {
@@ -1703,7 +1700,7 @@ function Ct(t, n, r, i, a) {
1703
1700
 
1704
1701
  describe("GET ${n.show}", () => {
1705
1702
  it("should return a 200 status code", async (context) => {
1706
- const { id } = await context.admin.collection("${t.tableName}").create(${l});
1703
+ const { id } = await context.admin.collection("${e.tableName}").create(${l});
1707
1704
  const response = await ${c}.get(\`${I(n.show, "id")}\`);
1708
1705
  expect(response.status).toBe(200);
1709
1706
  });
@@ -1715,8 +1712,8 @@ function Ct(t, n, r, i, a) {
1715
1712
  });
1716
1713
 
1717
1714
  describe("POST ${n.show}", () => {
1718
- it("should delete a ${t.displayName.toLowerCase()}", async (context) => {
1719
- const { id } = await context.admin.collection("${t.tableName}").create(${l});
1715
+ it("should delete a ${e.displayName.toLowerCase()}", async (context) => {
1716
+ const { id } = await context.admin.collection("${e.tableName}").create(${l});
1720
1717
  const response = await ${c}.post(\`${I(n.show, "id")}\`).type("form");
1721
1718
  expect(response.body.status).toBe(303);
1722
1719
 
@@ -1727,7 +1724,7 @@ function Ct(t, n, r, i, a) {
1727
1724
 
1728
1725
  describe("GET ${n.edit}", () => {
1729
1726
  it("should return a 200 status code", async (context) => {
1730
- const { id } = await context.admin.collection("${t.tableName}").create(${l});
1727
+ const { id } = await context.admin.collection("${e.tableName}").create(${l});
1731
1728
  const response = await ${c}.get(\`${I(n.edit, "id")}\`);
1732
1729
  expect(response.status).toBe(200);
1733
1730
  });
@@ -1735,9 +1732,9 @@ function Ct(t, n, r, i, a) {
1735
1732
  });
1736
1733
  `;
1737
1734
  }
1738
- function wt(t, n, r, i, a) {
1739
- let { declarations: o, setupSection: s, requestAgent: c, modelFormData: l } = L(t, r, i, a);
1740
- return e`
1735
+ function wt(e, n, r, i, a) {
1736
+ let { declarations: o, setupSection: s, requestAgent: c, modelFormData: l } = L(e, r, i, a);
1737
+ return t`
1741
1738
  import { afterEach, beforeEach, describe, expect, it } from "vitest";
1742
1739
 
1743
1740
  describe("${n}", () => {
@@ -1759,9 +1756,9 @@ function wt(t, n, r, i, a) {
1759
1756
  });
1760
1757
  `;
1761
1758
  }
1762
- function Tt(t, n, r, i, a) {
1763
- let { declarations: o, setupSection: s, requestAgent: c } = L(t, r, i, a);
1764
- return e`
1759
+ function Tt(e, n, r, i, a) {
1760
+ let { declarations: o, setupSection: s, requestAgent: c } = L(e, r, i, a);
1761
+ return t`
1765
1762
  import { afterEach, beforeEach, describe, expect, it } from "vitest";
1766
1763
 
1767
1764
  describe("${n}", () => {
@@ -1808,9 +1805,9 @@ var Et = ["text"], Dt = {
1808
1805
  function Ot(e) {
1809
1806
  return /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(e) ? e : `'${e}'`;
1810
1807
  }
1811
- function R(t, n) {
1812
- let r = t.type === "select" ? `[${(t.options ?? []).map((e) => JSON.stringify(e.value)).join(", ")}]` : "", i;
1813
- switch (t.type) {
1808
+ function R(e, n) {
1809
+ let r = e.type === "select" ? `[${(e.options ?? []).map((e) => JSON.stringify(e.value)).join(", ")}]` : "", i;
1810
+ switch (e.type) {
1814
1811
  case "text":
1815
1812
  i = "z.string()";
1816
1813
  break;
@@ -1839,10 +1836,10 @@ function R(t, n) {
1839
1836
  i = n.forForm ? "z.string()" : "z.date()";
1840
1837
  break;
1841
1838
  case "select":
1842
- i = r ? (t.maxSelect ?? 1) > 1 ? `z.array(z.enum(${r}))` : `z.enum(${r})` : "z.string()";
1839
+ i = r ? (e.maxSelect ?? 1) > 1 ? `z.array(z.enum(${r}))` : `z.enum(${r})` : "z.string()";
1843
1840
  break;
1844
1841
  case "file":
1845
- i = (t.maxSelect ?? 1) > 1 ? "z.string().array()" : "z.union([z.instanceof(File), z.string()])";
1842
+ i = (e.maxSelect ?? 1) > 1 ? "z.string().array()" : "z.union([z.instanceof(File), z.string()])";
1846
1843
  break;
1847
1844
  case "json":
1848
1845
  i = "z.any()";
@@ -1853,7 +1850,7 @@ function R(t, n) {
1853
1850
  return val;
1854
1851
  }
1855
1852
  return JSON.stringify(val);
1856
- }, z.string()${t.required ? "" : ".optional()"})` : e`
1853
+ }, z.string()${e.required ? "" : ".optional()"})` : t`
1857
1854
  z.object({
1858
1855
  lat: z.number().min(-90).max(90),
1859
1856
  lon: z.number().min(-180).max(180)
@@ -1861,18 +1858,18 @@ function R(t, n) {
1861
1858
  `;
1862
1859
  break;
1863
1860
  case "relation":
1864
- i = (t.maxSelect ?? 1) > 1 ? "z.array(z.string())" : "z.string()";
1861
+ i = (e.maxSelect ?? 1) > 1 ? "z.array(z.string())" : "z.string()";
1865
1862
  break;
1866
- default: return t.type;
1863
+ default: return e.type;
1867
1864
  }
1868
- return Et.includes(t.type) ? t.required ? `${i}.nonempty()` : `${i}.optional()` : t.required || t.type === "geoPoint" ? i : t.type === "file" && (t.maxSelect ?? 1) <= 1 ? `${i}.optional().default("")` : `${i}.optional()`;
1865
+ return Et.includes(e.type) ? e.required ? `${i}.nonempty()` : `${i}.optional()` : e.required || e.type === "geoPoint" ? i : e.type === "file" && (e.maxSelect ?? 1) <= 1 ? `${i}.optional().default("")` : `${i}.optional()`;
1869
1866
  }
1870
1867
  async function kt(e) {
1871
1868
  if (e.env === "runtime") {
1872
- let { getCollections: e } = await import("./chunks/env.runtime-CJS54CZX.js");
1869
+ let { getCollections: e } = await import("./chunks/env.runtime-ZUZgxjxf.js");
1873
1870
  return await e();
1874
1871
  }
1875
- let { getPreviewCollections: t } = await import("./chunks/env.preview-kw0hC6y8.js");
1872
+ let { getPreviewCollections: t } = await import("./chunks/env.preview-NYMljYNr.js");
1876
1873
  return t(e);
1877
1874
  }
1878
1875
  async function z(e, t, n) {
@@ -1896,7 +1893,7 @@ async function z(e, t, n) {
1896
1893
  collections: i
1897
1894
  };
1898
1895
  }
1899
- function B(t, n, r) {
1896
+ function B(e, n, r) {
1900
1897
  let i = [];
1901
1898
  r.includeModelFields && (i.push({
1902
1899
  name: "id",
@@ -1935,11 +1932,11 @@ function B(t, n, r) {
1935
1932
  schema: R(e, r)
1936
1933
  });
1937
1934
  }
1938
- let a = i.map((e) => `${Ot(e.name)}: ${e.schema}`).join(",\n "), o = r.includeModelFields ? "\nimport type { Schemas } from \"@velastack/pocketbase\";" : "", s = r.includeModelFields ? ` satisfies Schemas["${t.tableName}"]` : "";
1939
- return e`
1935
+ let a = i.map((e) => `${Ot(e.name)}: ${e.schema}`).join(",\n "), o = r.includeModelFields ? "\nimport type { Schemas } from \"@velastack/pocketbase\";" : "", s = r.includeModelFields ? ` satisfies Schemas["${e.tableName}"]` : "";
1936
+ return t`
1940
1937
  import { z } from "zod";${o}
1941
1938
 
1942
- export const ${t.schemaName} = z.object({
1939
+ export const ${e.schemaName} = z.object({
1943
1940
  ${a}
1944
1941
  })${s};
1945
1942
  `;
@@ -2076,13 +2073,13 @@ function Ft(e, t) {
2076
2073
  pageUrl: `/${n}`
2077
2074
  };
2078
2075
  }
2079
- function It(e) {
2080
- let [t, ...n] = e;
2081
- if (!t) throw new _("Invalid command arguments. Expected: <model> <fields...>");
2082
- if (n.length === 0) throw new _("At least one field definition is required.");
2076
+ function It(t) {
2077
+ let [n, ...r] = t;
2078
+ if (!n) throw new e("Invalid command arguments. Expected: <model> <fields...>");
2079
+ if (r.length === 0) throw new e("At least one field definition is required.");
2083
2080
  return {
2084
- modelPath: t,
2085
- fieldDefs: n
2081
+ modelPath: n,
2082
+ fieldDefs: r
2086
2083
  };
2087
2084
  }
2088
2085
  function Lt(e) {
@@ -2094,50 +2091,50 @@ function Rt(e, t) {
2094
2091
  "import { superForm } from \"sveltekit-superforms\";",
2095
2092
  "import { zod4Client } from \"sveltekit-superforms/adapters\";",
2096
2093
  `import { ${e.schemaName} } from "$lib/schemas/${e.name}";`,
2097
- ...ve(n)
2094
+ ...w(n)
2098
2095
  ];
2099
2096
  return [...new Set(r)];
2100
2097
  }
2101
- function zt(t, n) {
2102
- return e`
2103
- ${n.filter((e) => e.type === "select").map((e) => _e(e)).join("\n\n")}
2098
+ function zt(e, n) {
2099
+ return t`
2100
+ ${n.filter((e) => e.type === "select").map((e) => S(e)).join("\n\n")}
2104
2101
 
2105
2102
  const form = superForm(untrack(() => data.form), {
2106
- validators: zod4Client(${t.schemaName}),
2103
+ validators: zod4Client(${e.schemaName}),
2107
2104
  });
2108
2105
 
2109
2106
  const { form: formData } = form;
2110
2107
  `;
2111
2108
  }
2112
- function Bt(t, n) {
2113
- let r = Rt(t, n).join("\n"), i = zt(t, n), a = n.map((e) => ge(e)).join("\n"), s = Lt(n) ? " enctype=\"multipart/form-data\"" : "";
2114
- return e(Pt ||= o([
2109
+ function Bt(e, n) {
2110
+ let r = Rt(e, n).join("\n"), i = zt(e, n), a = n.map((e) => _e(e)).join("\n"), o = Lt(n) ? " enctype=\"multipart/form-data\"" : "";
2111
+ return t(Pt ||= s([
2115
2112
  "\n <script lang=\"ts\">\n ",
2116
2113
  "\n\n let { data } = $props();\n ",
2117
2114
  "\n <\/script>\n\n <section data-role=\"content\">\n <div class=\"flex justify-between items-center mb-4\">\n <h1 class=\"text-3xl font-bold tracking-tight\">",
2118
2115
  "</h1>\n </div>\n <div class=\"bg-card rounded-lg shadow-sm border p-4\">\n <form method=\"POST\"",
2119
2116
  ">\n <div class=\"grid grid-cols-1 md:grid-cols-2 gap-4\">\n ",
2120
2117
  "\n </div>\n <div class=\"mt-4 flex gap-2 border-t pt-4 -mx-4 px-4\">\n <Form.Button>Submit</Form.Button>\n </div>\n </form>\n </div>\n </section>\n "
2121
- ]), r, i, t.displayName, s, a);
2118
+ ]), r, i, e.displayName, o, a);
2122
2119
  }
2123
- function Vt(t, n) {
2120
+ function Vt(e, n) {
2124
2121
  let r = Lt(n);
2125
- return e`
2126
- ${e`
2122
+ return t`
2123
+ ${t`
2127
2124
  import { fail, superValidate${r ? ", withFiles" : ""} } from "sveltekit-superforms";
2128
2125
  import { zod4 } from "sveltekit-superforms/adapters";
2129
- import { ${t.schemaName} } from "$lib/schemas/${t.name}";
2126
+ import { ${e.schemaName} } from "$lib/schemas/${e.name}";
2130
2127
  import { setFlash } from "sveltekit-flash-message/server";
2131
2128
  `}
2132
2129
 
2133
2130
  export const load = async () => {
2134
- const form = await superValidate(zod4(${t.schemaName}));
2131
+ const form = await superValidate(zod4(${e.schemaName}));
2135
2132
  return { form };
2136
2133
  };
2137
2134
 
2138
2135
  export const actions = {
2139
2136
  default: async ({ request, cookies }) => {
2140
- const form = await superValidate(request, zod4(${t.schemaName}));
2137
+ const form = await superValidate(request, zod4(${e.schemaName}));
2141
2138
 
2142
2139
  if (!form.valid) {
2143
2140
  return fail(400, { form });
@@ -2150,11 +2147,11 @@ function Vt(t, n) {
2150
2147
  };
2151
2148
  `;
2152
2149
  }
2153
- function U(e, n) {
2150
+ function U(e, t) {
2154
2151
  return {
2155
2152
  path: e,
2156
- language: t(e),
2157
- content: n,
2153
+ language: n(e),
2154
+ content: t,
2158
2155
  status: "success"
2159
2156
  };
2160
2157
  }
@@ -2174,7 +2171,8 @@ async function Ht(e) {
2174
2171
  deletes: [],
2175
2172
  components: C(i),
2176
2173
  packages: [],
2177
- collections: []
2174
+ collections: [],
2175
+ collectionPatches: []
2178
2176
  };
2179
2177
  }
2180
2178
  //#endregion
@@ -2182,9 +2180,9 @@ async function Ht(e) {
2182
2180
  var Ut = "generate-form", Wt = "1.0.7", Gt = "src/patterns/generate/form", Kt = "/generate/form";
2183
2181
  async function qt(e) {
2184
2182
  let t = await Ht(e);
2185
- if (e.env !== "runtime") return v(t);
2186
- let { writeResult: n } = await import("./chunks/write-result-ENWLDQtP.js");
2187
- return n(await v(t), e);
2183
+ if (e.env !== "runtime") return _(t);
2184
+ let { writeResult: n } = await import("./chunks/write-result-C80dpjr-.js");
2185
+ return n(await _(t), e);
2188
2186
  }
2189
2187
  var Jt = {
2190
2188
  version: Wt,
@@ -2266,70 +2264,70 @@ function Zt(e) {
2266
2264
  function G(e, t, n) {
2267
2265
  return `{...${e}.fields.${t.name}.as(${JSON.stringify(n)})}`;
2268
2266
  }
2269
- function K(t, n) {
2270
- return e`
2271
- {#each ${t}.fields.${n.name}.issues() as issue}
2267
+ function K(e, n) {
2268
+ return t`
2269
+ {#each ${e}.fields.${n.name}.issues() as issue}
2272
2270
  <p class="text-destructive text-sm">{issue.message}</p>
2273
2271
  {/each}
2274
2272
  `;
2275
2273
  }
2276
- function q(t, n, r, i) {
2277
- let a = t.required ? " required" : "", o = i ? ` type="${i}"` : "";
2278
- return e`
2274
+ function q(e, n, r, i) {
2275
+ let a = e.required ? " required" : "", o = i ? ` type="${i}"` : "";
2276
+ return t`
2279
2277
  <div class="space-y-2 col-span-1">
2280
- <label for="${t.name}" class="text-sm font-medium">${t.title}</label>
2281
- <Input id="${t.name}" ${G(n, t, r)}${o}${a} />
2282
- ${K(n, t)}
2278
+ <label for="${e.name}" class="text-sm font-medium">${e.title}</label>
2279
+ <Input id="${e.name}" ${G(n, e, r)}${o}${a} />
2280
+ ${K(n, e)}
2283
2281
  </div>
2284
2282
  `;
2285
2283
  }
2286
- function Qt(t, n) {
2287
- let r = t.required ? " required" : "";
2288
- return e`
2284
+ function Qt(e, n) {
2285
+ let r = e.required ? " required" : "";
2286
+ return t`
2289
2287
  <div class="space-y-2 col-span-2">
2290
- <label for="${t.name}" class="text-sm font-medium">${t.title}</label>
2291
- <Textarea id="${t.name}" ${G(n, t, "text")}${r} />
2292
- ${K(n, t)}
2288
+ <label for="${e.name}" class="text-sm font-medium">${e.title}</label>
2289
+ <Textarea id="${e.name}" ${G(n, e, "text")}${r} />
2290
+ ${K(n, e)}
2293
2291
  </div>
2294
2292
  `;
2295
2293
  }
2296
- function $t(t, n) {
2297
- let r = t.required ? " required" : "";
2298
- return e`
2294
+ function $t(e, n) {
2295
+ let r = e.required ? " required" : "";
2296
+ return t`
2299
2297
  <div class="col-span-1 flex items-start space-x-2">
2300
- <input id="${t.name}" type="checkbox" ${G(n, t, "checkbox")}${r} />
2301
- <label for="${t.name}" class="text-sm font-medium">${t.title}</label>
2302
- ${K(n, t)}
2298
+ <input id="${e.name}" type="checkbox" ${G(n, e, "checkbox")}${r} />
2299
+ <label for="${e.name}" class="text-sm font-medium">${e.title}</label>
2300
+ ${K(n, e)}
2303
2301
  </div>
2304
2302
  `;
2305
2303
  }
2306
- function en(t, n) {
2307
- let r = t.maxSelect > 1 ? " multiple" : "", i = t.required ? " required" : "", a = t.options.map((e) => `<option value=${JSON.stringify(e.value)}>${e.label}</option>`).join("\n ");
2308
- return e`
2304
+ function en(e, n) {
2305
+ let r = e.maxSelect > 1 ? " multiple" : "", i = e.required ? " required" : "", a = e.options.map((e) => `<option value=${JSON.stringify(e.value)}>${e.label}</option>`).join("\n ");
2306
+ return t`
2309
2307
  <div class="space-y-2 col-span-1">
2310
- <label for="${t.name}" class="text-sm font-medium">${t.title}</label>
2311
- <select id="${t.name}" ${G(n, t, "select")}${r}${i} class="border-input bg-background flex h-9 w-full rounded-md border px-3 py-1 text-sm">
2308
+ <label for="${e.name}" class="text-sm font-medium">${e.title}</label>
2309
+ <select id="${e.name}" ${G(n, e, "select")}${r}${i} class="border-input bg-background flex h-9 w-full rounded-md border px-3 py-1 text-sm">
2312
2310
  ${a}
2313
2311
  </select>
2314
- ${K(n, t)}
2312
+ ${K(n, e)}
2315
2313
  </div>
2316
2314
  `;
2317
2315
  }
2318
- function tn(t, n) {
2319
- let r = t.maxSelect > 1 ? " multiple" : "", i = t.required ? " required" : "";
2320
- return e`
2316
+ function tn(e, n) {
2317
+ let r = e.maxSelect > 1 ? " multiple" : "", i = e.required ? " required" : "";
2318
+ return t`
2321
2319
  <div class="space-y-2 col-span-1">
2322
- <label for="${t.name}" class="text-sm font-medium">${t.title}</label>
2323
- <input id="${t.name}" ${G(n, t, "file")}${r}${i} class="text-sm" />
2324
- ${K(n, t)}
2320
+ <label for="${e.name}" class="text-sm font-medium">${e.title}</label>
2321
+ <input id="${e.name}" ${G(n, e, "file")}${r}${i} class="text-sm" />
2322
+ ${K(n, e)}
2325
2323
  </div>
2326
2324
  `;
2327
2325
  }
2328
- function nn(t, n) {
2329
- return e`
2326
+ function nn(e, n) {
2327
+ return t`
2330
2328
  <div class="space-y-2 col-span-1">
2331
- <label for="${t.name}" class="text-sm font-medium">${t.title}</label>
2332
- <Input id="${t.name}" ${G(n, t, "text")} readonly />
2329
+ <label for="${e.name}" class="text-sm font-medium">${e.title}</label>
2330
+ <Input id="${e.name}" ${G(n, e, "text")} readonly />
2333
2331
  </div>
2334
2332
  `;
2335
2333
  }
@@ -2366,13 +2364,13 @@ function sn(e, t) {
2366
2364
  pageUrl: `/${n}`
2367
2365
  };
2368
2366
  }
2369
- function cn(e) {
2370
- let [t, ...n] = e;
2371
- if (!t) throw new _("Invalid command arguments. Expected: <model> <fields...>");
2372
- if (n.length === 0) throw new _("At least one field definition is required.");
2367
+ function cn(t) {
2368
+ let [n, ...r] = t;
2369
+ if (!n) throw new e("Invalid command arguments. Expected: <model> <fields...>");
2370
+ if (r.length === 0) throw new e("At least one field definition is required.");
2373
2371
  return {
2374
- modelPath: t,
2375
- fieldDefs: n
2372
+ modelPath: n,
2373
+ fieldDefs: r
2376
2374
  };
2377
2375
  }
2378
2376
  function ln(e) {
@@ -2389,35 +2387,35 @@ function dn(e, t) {
2389
2387
  ];
2390
2388
  return [...new Set(r)];
2391
2389
  }
2392
- function fn(t, n, r) {
2393
- let i = dn(n, r).join("\n"), a = n.map((e) => an(e, { formVar: r })).join("\n"), s = ln(n) ? " enctype=\"multipart/form-data\"" : "";
2394
- return e(on ||= o([
2390
+ function fn(e, n, r) {
2391
+ let i = dn(n, r).join("\n"), a = n.map((e) => an(e, { formVar: r })).join("\n"), o = ln(n) ? " enctype=\"multipart/form-data\"" : "";
2392
+ return t(on ||= s([
2395
2393
  "\n <script lang=\"ts\">\n ",
2396
2394
  "\n <\/script>\n\n <section data-role=\"content\">\n <div class=\"flex justify-between items-center mb-4\">\n <h1 class=\"text-3xl font-bold tracking-tight\">",
2397
2395
  "</h1>\n </div>\n <div class=\"bg-card rounded-lg shadow-sm border p-4\">\n <form {...",
2398
2396
  "}",
2399
2397
  ">\n <div class=\"grid grid-cols-1 md:grid-cols-2 gap-4\">\n ",
2400
2398
  "\n </div>\n <div class=\"mt-4 flex gap-2 border-t pt-4 -mx-4 px-4\">\n <Button type=\"submit\">Submit</Button>\n </div>\n </form>\n </div>\n </section>\n "
2401
- ]), i, t.displayName, r, s, a);
2399
+ ]), i, e.displayName, r, o, a);
2402
2400
  }
2403
- function pn(t, n) {
2404
- return e`
2401
+ function pn(e, n) {
2402
+ return t`
2405
2403
  import { form, getRequestEvent } from "$app/server";
2406
2404
  import { setFlash } from "sveltekit-flash-message/server";
2407
- import { ${t.schemaName} } from "$lib/schemas/${t.name}";
2405
+ import { ${e.schemaName} } from "$lib/schemas/${e.name}";
2408
2406
 
2409
- export const ${n} = form(${t.schemaName}, async (data) => {
2407
+ export const ${n} = form(${e.schemaName}, async (data) => {
2410
2408
  const { cookies } = getRequestEvent();
2411
2409
  setFlash({ type: "toast", message: "Form posted successfully" }, cookies);
2412
2410
  return { success: true };
2413
2411
  });
2414
2412
  `;
2415
2413
  }
2416
- function J(e, n) {
2414
+ function J(e, t) {
2417
2415
  return {
2418
2416
  path: e,
2419
- language: t(e),
2420
- content: n,
2417
+ language: n(e),
2418
+ content: t,
2421
2419
  status: "success"
2422
2420
  };
2423
2421
  }
@@ -2437,7 +2435,8 @@ async function mn(e) {
2437
2435
  deletes: [],
2438
2436
  components: u,
2439
2437
  packages: [],
2440
- collections: []
2438
+ collections: [],
2439
+ collectionPatches: []
2441
2440
  };
2442
2441
  }
2443
2442
  //#endregion
@@ -2446,19 +2445,20 @@ var hn = /* @__PURE__ */ Object.assign({ "./preview-modifies/svelte.config.js":
2446
2445
  async function _n(e) {
2447
2446
  return {
2448
2447
  creates: [],
2449
- modifies: Object.entries(hn).map(([e, n]) => {
2450
- let i = r(e, gn);
2448
+ modifies: Object.entries(hn).map(([e, t]) => {
2449
+ let r = i(e, gn);
2451
2450
  return {
2452
- path: i,
2453
- language: t(i),
2454
- content: n,
2451
+ path: r,
2452
+ language: n(r),
2453
+ content: t,
2455
2454
  status: "success"
2456
2455
  };
2457
2456
  }).sort((e, t) => e.path.localeCompare(t.path)),
2458
2457
  deletes: [],
2459
2458
  components: [],
2460
2459
  packages: [],
2461
- collections: []
2460
+ collections: [],
2461
+ collectionPatches: []
2462
2462
  };
2463
2463
  }
2464
2464
  //#endregion
@@ -2466,13 +2466,13 @@ async function _n(e) {
2466
2466
  var vn = "generate-form-remote", yn = "1.0.0", bn = "src/patterns/generate/form-remote", xn = "/generate/form-remote";
2467
2467
  async function Sn(e) {
2468
2468
  let t = await mn(e);
2469
- if (e.env === "preview") return v(n([t, await _n(e)]));
2470
- if (e.env !== "runtime") return v(t);
2471
- let { modifyOutcomeToFile: r } = await import("./chunks/modify-file-CpqC7kMR.js"), { findSvelteConfigPath: i, modifySvelteConfigRemote: a } = await import("./chunks/modify-svelte-config-remote-DWsScM6m.js"), o = i(e.root), s = r(o, a(o)), c = {
2469
+ if (e.env === "preview") return _(r([t, await _n(e)]));
2470
+ if (e.env !== "runtime") return _(t);
2471
+ let { modifyOutcomeToFile: n } = await import("./chunks/modify-file-D3OuKUEp.js"), { findSvelteConfigPath: i, modifySvelteConfigRemote: a } = await import("./chunks/modify-svelte-config-remote-Dzgk1OIN.js"), o = i(e.root), s = n(o, a(o)), c = {
2472
2472
  ...t,
2473
2473
  modifies: [...t.modifies, ...s ? [s] : []]
2474
- }, { writeResult: l } = await import("./chunks/write-result-ENWLDQtP.js");
2475
- return l(await v(c), e);
2474
+ }, { writeResult: l } = await import("./chunks/write-result-C80dpjr-.js");
2475
+ return l(await _(c), e);
2476
2476
  }
2477
2477
  var Cn = {
2478
2478
  version: yn,
@@ -2524,29 +2524,174 @@ var Cn = {
2524
2524
  tests: 1,
2525
2525
  baseline: "velastack",
2526
2526
  generate: Sn
2527
+ }, wn = new Set([
2528
+ "add",
2529
+ "remove",
2530
+ "rename",
2531
+ "references"
2532
+ ]);
2533
+ function Tn(t) {
2534
+ let [n, r, ...i] = t;
2535
+ if (!n || !r) throw new e("Invalid command arguments. Expected: <collection> <add|remove|rename|references> <args...>");
2536
+ if (!wn.has(r)) throw new e(`Invalid op: "${r}". Expected one of: add, remove, rename, references`);
2537
+ return {
2538
+ collectionName: n,
2539
+ op: r,
2540
+ rest: i
2541
+ };
2542
+ }
2543
+ async function En(t) {
2544
+ let { collectionName: n, op: r, rest: i } = Tn(t.argv);
2545
+ Ke(n);
2546
+ let a = await kt(t), o = a.find((e) => e.name === n);
2547
+ if (!o) throw new e(`Collection "${n}" not found`);
2548
+ let s = A(n, t), c = new Set(o.fields.map((e) => e.name)), l = [];
2549
+ if (r === "add" || r === "references") {
2550
+ let { fields: o } = ft(r === "references" ? [Dn(i)] : On(i, "Expected at least one field definition for add"), s, a, t);
2551
+ for (let t of o) {
2552
+ if (c.has(t.name)) throw new e(`Field "${t.name}" already exists on collection "${n}"`);
2553
+ l.push({
2554
+ op: "add",
2555
+ field: Mt(t)
2556
+ });
2557
+ }
2558
+ } else if (r === "remove") {
2559
+ let t = On(i, "Expected at least one field name for remove");
2560
+ for (let r of t) {
2561
+ if (!c.has(r)) throw new e(`Field "${r}" does not exist on collection "${n}"`);
2562
+ l.push({
2563
+ op: "remove",
2564
+ fieldName: r
2565
+ });
2566
+ }
2567
+ } else {
2568
+ if (i.length !== 2) throw new e(`Expected exactly two arguments for rename (old and new), got ${i.length}`);
2569
+ let [t, r] = i;
2570
+ if (!c.has(t)) throw new e(`Field "${t}" does not exist on collection "${n}"`);
2571
+ if (c.has(r)) throw new e(`Field "${r}" already exists on collection "${n}"`);
2572
+ l.push({
2573
+ op: "rename",
2574
+ from: t,
2575
+ to: r
2576
+ });
2577
+ }
2578
+ return {
2579
+ creates: [],
2580
+ modifies: [],
2581
+ deletes: [],
2582
+ components: [],
2583
+ packages: [],
2584
+ collections: [],
2585
+ collectionPatches: [{
2586
+ collectionName: n,
2587
+ changes: l
2588
+ }]
2589
+ };
2590
+ }
2591
+ function Dn(t) {
2592
+ if (t.length !== 1) throw new e(`Expected exactly one argument for references, got ${t.length}`);
2593
+ let n = t[0];
2594
+ return `${n}:${k.default.plural(k.default.singular(n))}`;
2595
+ }
2596
+ function On(t, n) {
2597
+ if (t.length === 0) throw new e(n);
2598
+ return t;
2599
+ }
2600
+ //#endregion
2601
+ //#region src/patterns/generate/migration/index.ts
2602
+ var kn = "generate-migration", An = "1.0.0", jn = "src/patterns/generate/migration", Mn = "/generate/migration";
2603
+ async function Nn(e) {
2604
+ let t = await En(e);
2605
+ if (e.env !== "runtime") return _(t);
2606
+ let { applyCollectionFieldsPatches: n } = await import("./chunks/collections-BRIAYJ-Q.js"), { withPocketbase: r } = await import("./chunks/pocketbase-W_FJaYZ3.js"), i = [];
2607
+ await r(e.root, async (r) => {
2608
+ i = await n(r, t.collectionPatches, e);
2609
+ });
2610
+ let a = {
2611
+ ...t,
2612
+ creates: [...t.creates, ...i]
2613
+ }, { writeResult: o } = await import("./chunks/write-result-C80dpjr-.js");
2614
+ return o(await _(a), e);
2615
+ }
2616
+ var Pn = {
2617
+ version: An,
2618
+ slug: kn,
2619
+ source: jn,
2620
+ docs: Mn,
2621
+ plan: "open",
2622
+ title: "Generate a migration",
2623
+ summary: "Adds, removes, renames, or references fields on an existing collection.",
2624
+ requires: {
2625
+ auth: !1,
2626
+ api: !1,
2627
+ apiKeys: !1,
2628
+ i18n: !1,
2629
+ teams: !1,
2630
+ payments: !1
2631
+ },
2632
+ category: "generators",
2633
+ tags: [
2634
+ "pocketbase",
2635
+ "migration",
2636
+ "schema"
2637
+ ],
2638
+ command: {
2639
+ raw: "vela generate migration users add birthday:date",
2640
+ base: "vela generate migration",
2641
+ argv: [
2642
+ "users",
2643
+ "add",
2644
+ "birthday:date"
2645
+ ]
2646
+ },
2647
+ examples: [
2648
+ {
2649
+ command: "posts add title:text! body:editor",
2650
+ description: "Add two fields to the posts collection."
2651
+ },
2652
+ {
2653
+ command: "posts remove legacy_flag",
2654
+ description: "Drop a deprecated field from the posts collection."
2655
+ },
2656
+ {
2657
+ command: "posts rename title heading",
2658
+ description: "Rename a field on the posts collection."
2659
+ },
2660
+ {
2661
+ command: "posts references users",
2662
+ description: "Add a multi-relation field named users (maxSelect: 999)."
2663
+ },
2664
+ {
2665
+ command: "posts references user",
2666
+ description: "Add a single-relation field named user (maxSelect: 1)."
2667
+ }
2668
+ ],
2669
+ tests: 0,
2670
+ baseline: "velastack",
2671
+ generate: Nn
2527
2672
  };
2528
2673
  //#endregion
2529
2674
  //#region src/patterns/generate/resource/generate.ts
2530
- function wn(e) {
2531
- let [t, ...n] = e;
2532
- if (!t) throw new _("Invalid command arguments. Expected: <model> [fields...]");
2675
+ function Fn(t) {
2676
+ let [n, ...r] = t;
2677
+ if (!n) throw new e("Invalid command arguments. Expected: <model> [fields...]");
2533
2678
  return {
2534
- modelPath: t,
2535
- fields: n
2679
+ modelPath: n,
2680
+ fields: r
2536
2681
  };
2537
2682
  }
2538
- function Tn(e, n) {
2683
+ function In(e, t) {
2539
2684
  return {
2540
2685
  path: e,
2541
- language: t(e),
2542
- content: n,
2686
+ language: n(e),
2687
+ content: t,
2543
2688
  status: "success"
2544
2689
  };
2545
2690
  }
2546
- async function En(e) {
2547
- let { modelPath: t, fields: n } = wn(e.argv), { model: r, fields: i, auth: a, shouldCreateCollection: o } = await z(e, t, n);
2691
+ async function Ln(e) {
2692
+ let { modelPath: t, fields: n } = Fn(e.argv), { model: r, fields: i, auth: a, shouldCreateCollection: o } = await z(e, t, n);
2548
2693
  return {
2549
- creates: [Tn(`src/lib/schemas/${r.name}.ts`, B(r, i, {
2694
+ creates: [In(`src/lib/schemas/${r.name}.ts`, B(r, i, {
2550
2695
  includeModelFields: !0,
2551
2696
  forForm: !0
2552
2697
  }))],
@@ -2554,26 +2699,27 @@ async function En(e) {
2554
2699
  deletes: [],
2555
2700
  components: [],
2556
2701
  packages: [],
2557
- collections: o ? [Nt(r, i, a)] : []
2702
+ collections: o ? [Nt(r, i, a)] : [],
2703
+ collectionPatches: []
2558
2704
  };
2559
2705
  }
2560
2706
  //#endregion
2561
2707
  //#region src/patterns/generate/resource/index.ts
2562
- var Dn = "generate-resource", On = "1.0.7", kn = "src/patterns/generate/resource", An = "/generate/resource";
2563
- async function jn(e) {
2564
- let t = await En(e);
2565
- if (e.env !== "runtime") return v(t);
2566
- let { createCollections: n } = await import("./chunks/collections-Bs9xy7nU.js"), r = await n(t.collections, e), i = {
2708
+ var Rn = "generate-resource", zn = "1.0.7", Bn = "src/patterns/generate/resource", Vn = "/generate/resource";
2709
+ async function Hn(e) {
2710
+ let t = await Ln(e);
2711
+ if (e.env !== "runtime") return _(t);
2712
+ let { createCollections: n } = await import("./chunks/collections-BRIAYJ-Q.js"), r = await n(t.collections, e), i = {
2567
2713
  ...t,
2568
2714
  creates: [...t.creates, ...r]
2569
- }, { writeResult: a } = await import("./chunks/write-result-ENWLDQtP.js");
2570
- return a(await v(i), e);
2571
- }
2572
- var Mn = {
2573
- version: On,
2574
- slug: Dn,
2575
- source: kn,
2576
- docs: An,
2715
+ }, { writeResult: a } = await import("./chunks/write-result-C80dpjr-.js");
2716
+ return a(await _(i), e);
2717
+ }
2718
+ var Un = {
2719
+ version: zn,
2720
+ slug: Rn,
2721
+ source: Bn,
2722
+ docs: Vn,
2577
2723
  plan: "open",
2578
2724
  title: "Generate a resource",
2579
2725
  summary: "Generates model schema resources.",
@@ -2616,67 +2762,67 @@ var Mn = {
2616
2762
  ],
2617
2763
  tests: 0,
2618
2764
  baseline: "velastack",
2619
- generate: jn
2620
- }, Nn, Pn, Fn, In;
2621
- function Ln(e) {
2622
- let [t, ...n] = e;
2623
- if (!t) throw new _("Invalid command arguments. Expected: <model> [fields...]");
2765
+ generate: Hn
2766
+ }, Wn, Gn, Kn, qn;
2767
+ function Jn(t) {
2768
+ let [n, ...r] = t;
2769
+ if (!n) throw new e("Invalid command arguments. Expected: <model> [fields...]");
2624
2770
  return {
2625
- modelPath: t,
2626
- fields: n
2771
+ modelPath: n,
2772
+ fields: r
2627
2773
  };
2628
2774
  }
2629
- function Y(e, n) {
2775
+ function Y(e, t) {
2630
2776
  return {
2631
2777
  path: e,
2632
- language: t(e),
2633
- content: n,
2778
+ language: n(e),
2779
+ content: t,
2634
2780
  status: "success"
2635
2781
  };
2636
2782
  }
2637
2783
  function X(e) {
2638
2784
  return e.some((e) => e.type === "file");
2639
2785
  }
2640
- function Rn(e) {
2786
+ function Yn(e) {
2641
2787
  return [...new Set(e.filter(Boolean))];
2642
2788
  }
2643
- function zn(e) {
2644
- return e.filter((e) => e.type === "select").map((e) => _e(e)).join("\n\n");
2789
+ function Xn(e) {
2790
+ return e.filter((e) => e.type === "select").map((e) => S(e)).join("\n\n");
2645
2791
  }
2646
- function Bn(e, t) {
2792
+ function Zn(e, t) {
2647
2793
  return H(e).map((e) => `const ${e.pluralName} = await ${t}.collection("${e.tableName}").getFullList();`).join("\n ");
2648
2794
  }
2649
- function Vn(e) {
2795
+ function Qn(e) {
2650
2796
  return H(e).map((e) => e.pluralName).join(", ");
2651
2797
  }
2652
- function Hn(e) {
2798
+ function $n(e) {
2653
2799
  return e.features.auth ? "locals.pb" : "locals.admin";
2654
2800
  }
2655
- function Un(t, n, r = !1) {
2656
- return e`
2657
- ${zn(n)}
2801
+ function er(e, n, r = !1) {
2802
+ return t`
2803
+ ${Xn(n)}
2658
2804
  ${r ? "let { data, params } = $props();" : "let { data } = $props();"}
2659
2805
 
2660
2806
  const form = superForm(untrack(() => data.form), {
2661
- validators: zod4Client(${t.schemaName}),
2807
+ validators: zod4Client(${e.schemaName}),
2662
2808
  });
2663
2809
 
2664
2810
  const { form: formData } = form;
2665
2811
  `;
2666
2812
  }
2667
- function Wn(t, n, r) {
2668
- let i = r.some((e) => e.type === "select"), a = Rn([
2813
+ function tr(e, n, r) {
2814
+ let i = r.some((e) => e.type === "select"), a = Yn([
2669
2815
  "import { untrack } from \"svelte\";",
2670
2816
  "import { superForm } from \"sveltekit-superforms\";",
2671
2817
  "import { zod4Client } from \"sveltekit-superforms/adapters\";",
2672
- `import { ${t.schemaName} } from "$lib/schemas/${t.name}";`,
2673
- ...ve(C(r)),
2818
+ `import { ${e.schemaName} } from "$lib/schemas/${e.name}";`,
2819
+ ...w(C(r)),
2674
2820
  "import { Button } from \"$lib/components/ui/button\";",
2675
2821
  "import ArrowLeftIcon from \"@lucide/svelte/icons/arrow-left\";",
2676
2822
  "import * as Form from \"$lib/components/ui/form\";",
2677
2823
  i ? "import type { Models } from \"@velastack/pocketbase\";" : ""
2678
- ]).join("\n"), s = r.map((e) => ge(e)).join("\n"), c = X(r) ? " enctype=\"multipart/form-data\"" : "";
2679
- return e(Nn ||= o([
2824
+ ]).join("\n"), o = r.map((e) => _e(e)).join("\n"), c = X(r) ? " enctype=\"multipart/form-data\"" : "";
2825
+ return t(Wn ||= s([
2680
2826
  "\n <script lang=\"ts\">\n ",
2681
2827
  "\n ",
2682
2828
  "\n <\/script>\n\n <section data-role=\"content\">\n <div class=\"flex justify-between items-center mb-4\">\n <h1 class=\"text-3xl font-bold tracking-tight\">New ",
@@ -2685,21 +2831,21 @@ function Wn(t, n, r) {
2685
2831
  ">\n <div class=\"grid grid-cols-1 md:grid-cols-2 gap-4\">\n ",
2686
2832
  "\n </div>\n <div class=\"mt-4 flex gap-2 border-t pt-4 -mx-4 px-4\">\n <Form.Button size=\"sm\">Save</Form.Button>\n <Button href=\"",
2687
2833
  "\" variant=\"outline\" size=\"sm\">Cancel</Button>\n </div>\n </form>\n </div>\n </section>\n "
2688
- ]), a, Un(t, r), t.displayName.toLowerCase(), n.list, c, s, n.list);
2834
+ ]), a, er(e, r), e.displayName.toLowerCase(), n.list, c, o, n.list);
2689
2835
  }
2690
- function Gn(t, n, r) {
2691
- let i = r.some((e) => e.type === "select"), a = Rn([
2836
+ function nr(e, n, r) {
2837
+ let i = r.some((e) => e.type === "select"), a = Yn([
2692
2838
  "import { untrack } from \"svelte\";",
2693
2839
  "import { superForm } from \"sveltekit-superforms\";",
2694
2840
  "import { zod4Client } from \"sveltekit-superforms/adapters\";",
2695
- `import { ${t.schemaName} } from "$lib/schemas/${t.name}";`,
2696
- ...ve(C(r)),
2841
+ `import { ${e.schemaName} } from "$lib/schemas/${e.name}";`,
2842
+ ...w(C(r)),
2697
2843
  "import { Button } from \"$lib/components/ui/button\";",
2698
2844
  "import ArrowLeftIcon from \"@lucide/svelte/icons/arrow-left\";",
2699
2845
  "import * as Form from \"$lib/components/ui/form\";",
2700
2846
  i ? "import type { Models } from \"@velastack/pocketbase\";" : ""
2701
- ]).join("\n"), s = r.map((e) => ge(e)).join("\n"), c = X(r) ? " enctype=\"multipart/form-data\"" : "";
2702
- return e(Pn ||= o([
2847
+ ]).join("\n"), o = r.map((e) => _e(e)).join("\n"), c = X(r) ? " enctype=\"multipart/form-data\"" : "";
2848
+ return t(Gn ||= s([
2703
2849
  "\n <script lang=\"ts\">\n ",
2704
2850
  "\n ",
2705
2851
  "\n <\/script>\n\n <section data-role=\"content\">\n <div class=\"flex justify-between items-center mb-4\">\n <h1 class=\"text-3xl font-bold tracking-tight\">Edit ",
@@ -2717,19 +2863,19 @@ function Gn(t, n, r) {
2717
2863
  ">\n <div class=\"grid grid-cols-1 md:grid-cols-2 gap-4\">\n ",
2718
2864
  "\n </div>\n <div class=\"mt-4 flex gap-2 border-t pt-4 -mx-4 px-4\">\n <Form.Button size=\"sm\">Save changes</Form.Button>\n <Button href=\"",
2719
2865
  "/\\${params.id}\" variant=\"outline\" size=\"sm\">Cancel</Button>\n </div>\n </form>\n </div>\n </section>\n "
2720
- ]), a, Un(t, r, !0), t.displayName.toLowerCase(), n.list, c, s, n.list);
2866
+ ]), a, er(e, r, !0), e.displayName.toLowerCase(), n.list, c, o, n.list);
2721
2867
  }
2722
- function Kn(t, n, r) {
2723
- let i = r.some((e) => e.type === "select"), a = i ? `${zn(r)}` : "", s = r.map((t) => {
2868
+ function rr(e, n, r) {
2869
+ let i = r.some((e) => e.type === "select"), a = i ? `${Xn(r)}` : "", o = r.map((e) => {
2724
2870
  let n = "{ getValue }", r = "{ value: getValue() }";
2725
- return t.type === "relation" && (n = "{ getValue, row }", r = `{ value: getValue(), expanded: row.original.expand?.${t.name}, displayField: "${t.displayField}" }`), t.type === "select" && (r = `{ value: getValue(), options: ${t.name}Labels }`), t.type === "file" && (n = "{ getValue, row }", r = "{ value: getValue(), collectionId: row.original.collectionId, id: row.original.id }"), e`
2726
- columnHelper.accessor("${t.name}", {
2727
- header: ({ column }) => renderComponent(ColumnHeader, { column, title: "${t.title}" }),
2728
- cell: (${n}) => renderComponent(Cells.${t.type.charAt(0).toUpperCase() + t.type.slice(1)}Cell, ${r})
2871
+ return e.type === "relation" && (n = "{ getValue, row }", r = `{ value: getValue(), expanded: row.original.expand?.${e.name}, displayField: "${e.displayField}" }`), e.type === "select" && (r = `{ value: getValue(), options: ${e.name}Labels }`), e.type === "file" && (n = "{ getValue, row }", r = "{ value: getValue(), collectionId: row.original.collectionId, id: row.original.id }"), t`
2872
+ columnHelper.accessor("${e.name}", {
2873
+ header: ({ column }) => renderComponent(ColumnHeader, { column, title: "${e.title}" }),
2874
+ cell: (${n}) => renderComponent(Cells.${e.type.charAt(0).toUpperCase() + e.type.slice(1)}Cell, ${r})
2729
2875
  })
2730
2876
  `;
2731
2877
  }).join(",\n"), c = r.filter((e) => e.type === "select").map((e) => `<FacetedFilter column={table.getColumn("${e.name}")!} title="${e.title}" options={Object.values(${e.name}Labels)} />`).join("\n");
2732
- return e(Fn ||= o([
2878
+ return t(Kn ||= s([
2733
2879
  "\n <script lang=\"ts\">\n import {\n type ColumnFiltersState,\n type PaginationState,\n type RowSelectionState,\n type SortingState,\n type VisibilityState,\n getCoreRowModel,\n getFacetedRowModel,\n getFacetedUniqueValues,\n getFilteredRowModel,\n getPaginationRowModel,\n getSortedRowModel,\n createColumnHelper\n } from \"@tanstack/table-core\";\n import { createSvelteTable, FlexRender, renderComponent } from \"$lib/components/ui/data-table\";\n import * as Table from \"$lib/components/ui/table\";\n import { Checkbox } from \"$lib/components/ui/checkbox\";\n import { ColumnHeader } from \"$lib/components/ui/column-header\";\n import { Pagination } from \"$lib/components/ui/pagination\";\n import { RowActions } from \"$lib/components/ui/row-actions\";\n import * as Cells from \"$lib/components/ui/cells\";\n import { Button } from \"$lib/components/ui/button\";\n import { Input } from \"$lib/components/ui/input\";\n ",
2734
2880
  "\n import XIcon from \"@lucide/svelte/icons/x\";\n import PlusIcon from \"@lucide/svelte/icons/plus\";\n import type { Models } from \"@velastack/pocketbase\";\n\n let { data } = $props();\n let rowSelection = $state<RowSelectionState>({});\n let columnVisibility = $state<VisibilityState>({});\n let columnFilters = $state<ColumnFiltersState>([]);\n let sorting = $state<SortingState>([]);\n let pagination = $state<PaginationState>({ pageIndex: 0, pageSize: 10 });\n\n ",
2735
2881
  "\n\n const columnHelper = createColumnHelper<Models[\"",
@@ -2761,48 +2907,48 @@ function Kn(t, n, r) {
2761
2907
  "\n {#if table.getState().columnFilters.length > 0}\n <Button variant=\"ghost\" onclick={() => table.resetColumnFilters()} class=\"h-8 px-2 lg:px-3\">\n Reset\n <XIcon />\n </Button>\n {/if}\n </div>\n\n <Button href=\"",
2762
2908
  "\" variant=\"outline\" size=\"sm\">\n <PlusIcon class=\"w-4 h-4\" />\n New ",
2763
2909
  "\n </Button>\n </div>\n\n <div class=\"rounded-md border overflow-hidden\">\n <Table.Root>\n <Table.Header>\n {#each table.getHeaderGroups() as headerGroup (headerGroup.id)}\n <Table.Row>\n {#each headerGroup.headers as header (header.id)}\n <Table.Head colspan={header.colSpan} class={header.column.columnDef.meta?.class}>\n {#if !header.isPlaceholder}\n <FlexRender content={header.column.columnDef.header} context={header.getContext()} />\n {/if}\n </Table.Head>\n {/each}\n </Table.Row>\n {/each}\n </Table.Header>\n <Table.Body>\n {#each table.getRowModel().rows as row (row.id)}\n <Table.Row data-state={row.getIsSelected() && \"selected\"}>\n {#each row.getVisibleCells() as cell (cell.id)}\n <Table.Cell class={cell.column.columnDef.meta?.class}>\n <FlexRender content={cell.column.columnDef.cell} context={cell.getContext()} />\n </Table.Cell>\n {/each}\n </Table.Row>\n {:else}\n <Table.Row>\n <Table.Cell colspan={columns.length} class=\"h-24 text-center\">No results.</Table.Cell>\n </Table.Row>\n {/each}\n </Table.Body>\n </Table.Root>\n </div>\n\n <Pagination {table} />\n </div>\n </section>\n "
2764
- ]), i ? "import { FacetedFilter } from \"$lib/components/ui/faceted-filter\";" : "", a, t.tableName, s, r.length > 0 ? "," : "", n.list, n.list, n.list, t.pluralName, t.pluralDisplayName, t.pluralDisplayName.toLowerCase(), c, n.new, t.displayName.toLowerCase());
2910
+ ]), i ? "import { FacetedFilter } from \"$lib/components/ui/faceted-filter\";" : "", a, e.tableName, o, r.length > 0 ? "," : "", n.list, n.list, n.list, e.pluralName, e.pluralDisplayName, e.pluralDisplayName.toLowerCase(), c, n.new, e.displayName.toLowerCase());
2765
2911
  }
2766
- function qn(t, n, r) {
2912
+ function ir(e, n, r) {
2767
2913
  let i = V(n), a = i ? `{ expand: "${i}" }` : "";
2768
- return e`
2914
+ return t`
2769
2915
  export const load = async ({ locals }) => {
2770
- const ${t.pluralName} = await ${r}.collection("${t.tableName}").getFullList(${a});
2771
- return { ${t.pluralName} };
2916
+ const ${e.pluralName} = await ${r}.collection("${e.tableName}").getFullList(${a});
2917
+ return { ${e.pluralName} };
2772
2918
  };
2773
2919
  `;
2774
2920
  }
2775
- function Jn(t, n, r, i, a) {
2776
- let o = X(r), s = Bn(r, i), c = Vn(r), l = c ? `, ${c}` : "", u = r.find((e) => e.type === "relation" && e.isCurrentUser), d = a && u ? e`
2921
+ function ar(e, n, r, i, a) {
2922
+ let o = X(r), s = Zn(r, i), c = Qn(r), l = c ? `, ${c}` : "", u = r.find((e) => e.type === "relation" && e.isCurrentUser), d = a && u ? t`
2777
2923
  {
2778
2924
  ...form.data,
2779
2925
  ${u.name}: locals.pb.authStore.record?.id
2780
2926
  }
2781
2927
  ` : "form.data";
2782
- return e`
2928
+ return t`
2783
2929
  import { fail, redirect } from "@sveltejs/kit";
2784
2930
  import { superValidate${o ? ", withFiles" : ""} } from "sveltekit-superforms";
2785
2931
  import { zod4 } from "sveltekit-superforms/adapters";
2786
2932
  import { setPocketbaseErrors } from "@velastack/pocketbase";
2787
- import { ${t.schemaName} } from "$lib/schemas/${t.name}";
2933
+ import { ${e.schemaName} } from "$lib/schemas/${e.name}";
2788
2934
 
2789
2935
  export const load = async ({ locals }) => {
2790
2936
  ${s}
2791
- return { form: await superValidate(zod4(${t.schemaName}))${l} };
2937
+ return { form: await superValidate(zod4(${e.schemaName}))${l} };
2792
2938
  };
2793
2939
 
2794
2940
  export const actions = {
2795
2941
  default: async ({ locals, request }) => {
2796
- const form = await superValidate(request, zod4(${t.schemaName}));
2942
+ const form = await superValidate(request, zod4(${e.schemaName}));
2797
2943
 
2798
2944
  if (!form.valid) {
2799
2945
  return fail(400, ${o ? "withFiles({ form })" : "{ form }"});
2800
2946
  }
2801
2947
 
2802
- let ${t.name};
2948
+ let ${e.name};
2803
2949
 
2804
2950
  try {
2805
- ${t.name} = await ${i}.collection("${t.tableName}").create(
2951
+ ${e.name} = await ${i}.collection("${e.tableName}").create(
2806
2952
  ${d}
2807
2953
  );
2808
2954
  } catch (error) {
@@ -2810,20 +2956,20 @@ function Jn(t, n, r, i, a) {
2810
2956
  return fail(400, ${o ? "withFiles({ form })" : "{ form }"});
2811
2957
  }
2812
2958
 
2813
- return redirect(303, \`${n.list}/\${${t.name}.id}\`);
2959
+ return redirect(303, \`${n.list}/\${${e.name}.id}\`);
2814
2960
  },
2815
2961
  };
2816
2962
  `;
2817
2963
  }
2818
- function Yn(t, n, r, i) {
2964
+ function or(e, n, r, i) {
2819
2965
  let a = V(r), o = a ? `, { expand: "${a}" }` : "";
2820
- return e`
2966
+ return t`
2821
2967
  import { error, redirect } from "@sveltejs/kit";
2822
2968
 
2823
2969
  export const load = async ({ locals, params }) => {
2824
2970
  try {
2825
- const ${t.name} = await ${i}.collection("${t.tableName}").getOne(params.id${o});
2826
- return { ${t.name} };
2971
+ const ${e.name} = await ${i}.collection("${e.tableName}").getOne(params.id${o});
2972
+ return { ${e.name} };
2827
2973
  } catch {
2828
2974
  throw error(404, "Not found");
2829
2975
  }
@@ -2831,21 +2977,21 @@ function Yn(t, n, r, i) {
2831
2977
 
2832
2978
  export const actions = {
2833
2979
  default: async ({ locals, params }) => {
2834
- await ${i}.collection("${t.tableName}").delete(params.id);
2980
+ await ${i}.collection("${e.tableName}").delete(params.id);
2835
2981
  throw redirect(303, "${n.list}");
2836
2982
  },
2837
2983
  };
2838
2984
  `;
2839
2985
  }
2840
- function Xn(t, n, r) {
2841
- let i = r.some((e) => e.type === "select"), a = r.some((e) => e.type === "relation"), s = r.some((e) => e.type === "file"), c = [
2986
+ function sr(e, n, r) {
2987
+ let i = r.some((e) => e.type === "select"), a = r.some((e) => e.type === "relation"), o = r.some((e) => e.type === "file"), c = [
2842
2988
  "import { Button } from \"$lib/components/ui/button\";",
2843
2989
  "import ArrowLeftIcon from \"@lucide/svelte/icons/arrow-left\";",
2844
2990
  i || a ? "import { Badge } from \"$lib/components/ui/badge\";" : "",
2845
2991
  a ? "import CircleArrowRightIcon from \"@lucide/svelte/icons/circle-arrow-right\";" : "",
2846
- s ? "import FileIcon from \"@lucide/svelte/icons/file\";" : ""
2847
- ].filter(Boolean).join("\n"), l = zn(r), u = r.map((e) => Ee(t, e)).join("\n");
2848
- return e(In ||= o([
2992
+ o ? "import FileIcon from \"@lucide/svelte/icons/file\";" : ""
2993
+ ].filter(Boolean).join("\n"), l = Xn(r), u = r.map((t) => Ee(e, t)).join("\n");
2994
+ return t(qn ||= s([
2849
2995
  "\n <script lang=\"ts\">\n ",
2850
2996
  "\n ",
2851
2997
  "\n\n let { data } = $props();\n <\/script>\n\n <section data-role=\"content\">\n <div class=\"flex justify-between items-center mb-4\">\n <h1 class=\"text-3xl font-bold tracking-tight\">",
@@ -2854,64 +3000,64 @@ function Xn(t, n, r) {
2854
3000
  "\n </div>\n\n <div class=\"mt-4 flex gap-2 border-t pt-4 -mx-4 px-4 justify-between\">\n <Button href=\"",
2855
3001
  "/{data.",
2856
3002
  ".id}/edit\" variant=\"outline\" size=\"sm\">\n Edit\n </Button>\n <form method=\"POST\">\n <Button type=\"submit\" variant=\"destructive\" size=\"sm\">Delete</Button>\n </form>\n </div>\n </div>\n </section>\n "
2857
- ]), c, l, t.displayName, n.list, u, n.list, t.name);
3003
+ ]), c, l, e.displayName, n.list, u, n.list, e.name);
2858
3004
  }
2859
- function Zn(t, n, r, i) {
2860
- let a = X(r), o = Bn(r, i), s = Vn(r), c = s ? `, ${s}` : "";
2861
- return e`
3005
+ function cr(e, n, r, i) {
3006
+ let a = X(r), o = Zn(r, i), s = Qn(r), c = s ? `, ${s}` : "";
3007
+ return t`
2862
3008
  import { error, fail, redirect } from "@sveltejs/kit";
2863
3009
  import { setPocketbaseErrors, setDefaultData } from "@velastack/pocketbase";
2864
3010
  import { superValidate${a ? ", withFiles" : ""} } from "sveltekit-superforms";
2865
3011
  import { zod4 } from "sveltekit-superforms/adapters";
2866
- import { ${t.schemaName} } from "$lib/schemas/${t.name}";
3012
+ import { ${e.schemaName} } from "$lib/schemas/${e.name}";
2867
3013
 
2868
3014
  export const load = async ({ locals, params }) => {
2869
- let ${t.name};
3015
+ let ${e.name};
2870
3016
  try {
2871
- ${t.name} = await ${i}.collection("${t.tableName}").getOne(params.id);
3017
+ ${e.name} = await ${i}.collection("${e.tableName}").getOne(params.id);
2872
3018
  } catch {
2873
3019
  throw error(404, "Not found");
2874
3020
  }
2875
3021
  ${o}
2876
- return { form: await superValidate(${t.name}, zod4(${t.schemaName}))${c} };
3022
+ return { form: await superValidate(${e.name}, zod4(${e.schemaName}))${c} };
2877
3023
  };
2878
3024
 
2879
3025
  export const actions = {
2880
3026
  default: async ({ locals, params, request }) => {
2881
- const ${t.name} = await ${i}.collection("${t.tableName}").getOne(params.id);
2882
- const form = await superValidate(request, zod4(${t.schemaName}));
3027
+ const ${e.name} = await ${i}.collection("${e.tableName}").getOne(params.id);
3028
+ const form = await superValidate(request, zod4(${e.schemaName}));
2883
3029
 
2884
3030
  if (!form.valid) {
2885
- setDefaultData(form, ${t.name});
3031
+ setDefaultData(form, ${e.name});
2886
3032
  return fail(400, ${a ? "withFiles({ form })" : "{ form }"});
2887
3033
  }
2888
3034
 
2889
3035
  try {
2890
- await ${i}.collection("${t.tableName}").update(params.id, form.data);
3036
+ await ${i}.collection("${e.tableName}").update(params.id, form.data);
2891
3037
  return redirect(303, \`${n.list}/\${params.id}\`);
2892
3038
  } catch (error) {
2893
3039
  setPocketbaseErrors(form, error);
2894
- setDefaultData(form, ${t.name});
3040
+ setDefaultData(form, ${e.name});
2895
3041
  return fail(400, ${a ? "withFiles({ form })" : "{ form }"});
2896
3042
  }
2897
3043
  },
2898
3044
  };
2899
3045
  `;
2900
3046
  }
2901
- async function Qn(e) {
2902
- let { modelPath: t, fields: n } = Ln(e.argv), { model: r, fields: i, auth: a, shouldCreateCollection: o, collections: s } = await z(e, t, n), c = Je(r), l = Ye(r), u = Hn(e), d = i.filter((e) => !(e.type === "relation" && e.isCurrentUser)), f = [
3047
+ async function lr(e) {
3048
+ let { modelPath: t, fields: n } = Jn(e.argv), { model: r, fields: i, auth: a, shouldCreateCollection: o, collections: s } = await z(e, t, n), c = Je(r), l = Ye(r), u = $n(e), d = i.filter((e) => !(e.type === "relation" && e.isCurrentUser)), f = [
2903
3049
  Y(`src/lib/schemas/${r.name}.ts`, B(r, i, {
2904
3050
  includeModelFields: !0,
2905
3051
  forForm: !0
2906
3052
  })),
2907
- Y(`${c.list}/+page.server.ts`, qn(r, d, u)),
2908
- Y(`${c.list}/+page.svelte`, Kn(r, l, d)),
2909
- Y(`${c.new}/+page.server.ts`, Jn(r, l, d, u, e.features.auth)),
2910
- Y(`${c.new}/+page.svelte`, Wn(r, l, d)),
2911
- Y(`${c.show}/+page.server.ts`, Yn(r, l, d, u)),
2912
- Y(`${c.show}/+page.svelte`, Xn(r, l, d)),
2913
- Y(`${c.edit}/+page.server.ts`, Zn(r, l, d, u)),
2914
- Y(`${c.edit}/+page.svelte`, Gn(r, l, d)),
3053
+ Y(`${c.list}/+page.server.ts`, ir(r, d, u)),
3054
+ Y(`${c.list}/+page.svelte`, rr(r, l, d)),
3055
+ Y(`${c.new}/+page.server.ts`, ar(r, l, d, u, e.features.auth)),
3056
+ Y(`${c.new}/+page.svelte`, tr(r, l, d)),
3057
+ Y(`${c.show}/+page.server.ts`, or(r, l, d, u)),
3058
+ Y(`${c.show}/+page.svelte`, sr(r, l, d)),
3059
+ Y(`${c.edit}/+page.server.ts`, cr(r, l, d, u)),
3060
+ Y(`${c.edit}/+page.svelte`, nr(r, l, d)),
2915
3061
  Y(`${c.list}/server.test.ts`, St(r, l, i, e, s))
2916
3062
  ], p = [
2917
3063
  ...C(d),
@@ -2937,26 +3083,27 @@ async function Qn(e) {
2937
3083
  deletes: [],
2938
3084
  components: [...new Set(p)],
2939
3085
  packages: ["@tanstack/table-core"],
2940
- collections: o ? [Nt(r, i, a)] : []
3086
+ collections: o ? [Nt(r, i, a)] : [],
3087
+ collectionPatches: []
2941
3088
  };
2942
3089
  }
2943
3090
  //#endregion
2944
3091
  //#region src/patterns/generate/scaffold/index.ts
2945
- var $n = "generate-scaffold", er = "1.0.7", tr = "src/patterns/generate/scaffold", nr = "/generate/scaffold";
2946
- async function rr(e) {
2947
- let t = await Qn(e);
2948
- if (e.env !== "runtime") return v(t);
2949
- let { createCollections: n } = await import("./chunks/collections-Bs9xy7nU.js"), r = await n(t.collections, e), i = {
3092
+ var ur = "generate-scaffold", dr = "1.0.7", fr = "src/patterns/generate/scaffold", pr = "/generate/scaffold";
3093
+ async function mr(e) {
3094
+ let t = await lr(e);
3095
+ if (e.env !== "runtime") return _(t);
3096
+ let { createCollections: n } = await import("./chunks/collections-BRIAYJ-Q.js"), r = await n(t.collections, e), i = {
2950
3097
  ...t,
2951
3098
  creates: [...t.creates, ...r]
2952
- }, { writeResult: a } = await import("./chunks/write-result-ENWLDQtP.js");
2953
- return a(await v(i), e);
2954
- }
2955
- var ir = {
2956
- version: er,
2957
- slug: $n,
2958
- source: tr,
2959
- docs: nr,
3099
+ }, { writeResult: a } = await import("./chunks/write-result-C80dpjr-.js");
3100
+ return a(await _(i), e);
3101
+ }
3102
+ var hr = {
3103
+ version: dr,
3104
+ slug: ur,
3105
+ source: fr,
3106
+ docs: pr,
2960
3107
  plan: "open",
2961
3108
  title: "Generate a scaffold",
2962
3109
  summary: "Generates CRUD routes and schema.",
@@ -3000,56 +3147,56 @@ var ir = {
3000
3147
  ],
3001
3148
  tests: 8,
3002
3149
  baseline: "velastack",
3003
- generate: rr
3004
- }, ar, or, sr, cr;
3005
- function lr(e) {
3006
- let [t, ...n] = e;
3007
- if (!t) throw new _("Invalid command arguments. Expected: <model> [fields...]");
3150
+ generate: mr
3151
+ }, gr, _r, vr, yr;
3152
+ function br(t) {
3153
+ let [n, ...r] = t;
3154
+ if (!n) throw new e("Invalid command arguments. Expected: <model> [fields...]");
3008
3155
  return {
3009
- modelPath: t,
3010
- fields: n
3156
+ modelPath: n,
3157
+ fields: r
3011
3158
  };
3012
3159
  }
3013
- function Z(e, n) {
3160
+ function Z(e, t) {
3014
3161
  return {
3015
3162
  path: e,
3016
- language: t(e),
3017
- content: n,
3163
+ language: n(e),
3164
+ content: t,
3018
3165
  status: "success"
3019
3166
  };
3020
3167
  }
3021
- function ur(e) {
3168
+ function xr(e) {
3022
3169
  return e.some((e) => e.type === "file");
3023
3170
  }
3024
- function dr(e) {
3025
- return e.filter((e) => e.type === "select").map((e) => _e(e)).join("\n\n");
3171
+ function Sr(e) {
3172
+ return e.filter((e) => e.type === "select").map((e) => S(e)).join("\n\n");
3026
3173
  }
3027
- function fr(e, t) {
3174
+ function Cr(e, t) {
3028
3175
  return H(e).map((e) => `const ${e.pluralName} = await ${t}.collection("${e.tableName}").getFullList();`).join("\n ");
3029
3176
  }
3030
- function pr(e) {
3177
+ function wr(e) {
3031
3178
  return H(e).map((e) => e.pluralName).join(", ");
3032
3179
  }
3033
- function mr(e) {
3180
+ function Tr(e) {
3034
3181
  return e.features.auth ? "locals.pb" : "locals.admin";
3035
3182
  }
3036
- function hr(e) {
3183
+ function Er(e) {
3037
3184
  return `create${e.typeName}Form`;
3038
3185
  }
3039
- function gr(e) {
3186
+ function Dr(e) {
3040
3187
  return `update${e.typeName}Form`;
3041
3188
  }
3042
- function _r(e) {
3189
+ function Or(e) {
3043
3190
  return H(e).length > 0;
3044
3191
  }
3045
- function vr(t, n, r) {
3046
- let i = hr(t), a = W(r), s = [
3192
+ function kr(e, n, r) {
3193
+ let i = Er(e), a = W(r), o = [
3047
3194
  `import { ${i} } from "./form.remote";`,
3048
3195
  "import { Button } from \"$lib/components/ui/button\";",
3049
3196
  "import ArrowLeftIcon from \"@lucide/svelte/icons/arrow-left\";",
3050
3197
  ...Zt(a)
3051
- ].join("\n"), c = r.map((e) => an(e, { formVar: i })).join("\n"), l = ur(r) ? " enctype=\"multipart/form-data\"" : "";
3052
- return e(ar ||= o([
3198
+ ].join("\n"), c = r.map((e) => an(e, { formVar: i })).join("\n"), l = xr(r) ? " enctype=\"multipart/form-data\"" : "";
3199
+ return t(gr ||= s([
3053
3200
  "\n <script lang=\"ts\">\n ",
3054
3201
  "\n <\/script>\n\n <section data-role=\"content\">\n <div class=\"flex justify-between items-center mb-4\">\n <h1 class=\"text-3xl font-bold tracking-tight\">New ",
3055
3202
  "</h1>\n <Button href=\"",
@@ -3058,16 +3205,16 @@ function vr(t, n, r) {
3058
3205
  ">\n <div class=\"grid grid-cols-1 md:grid-cols-2 gap-4\">\n ",
3059
3206
  "\n </div>\n <div class=\"mt-4 flex gap-2 border-t pt-4 -mx-4 px-4\">\n <Button type=\"submit\" size=\"sm\">Save</Button>\n <Button href=\"",
3060
3207
  "\" variant=\"outline\" size=\"sm\">Cancel</Button>\n </div>\n </form>\n </div>\n </section>\n "
3061
- ]), s, t.displayName.toLowerCase(), n.list, i, l, c, n.list);
3208
+ ]), o, e.displayName.toLowerCase(), n.list, i, l, c, n.list);
3062
3209
  }
3063
- function yr(t, n, r) {
3064
- let i = gr(t), a = W(r), s = [
3210
+ function Ar(e, n, r) {
3211
+ let i = Dr(e), a = W(r), o = [
3065
3212
  `import { ${i} } from "./form.remote";`,
3066
3213
  "import { Button } from \"$lib/components/ui/button\";",
3067
3214
  "import ArrowLeftIcon from \"@lucide/svelte/icons/arrow-left\";",
3068
3215
  ...Zt(a)
3069
- ].join("\n"), c = r.map((e) => an(e, { formVar: i })).join("\n"), l = ur(r) ? " enctype=\"multipart/form-data\"" : "";
3070
- return e(or ||= o([
3216
+ ].join("\n"), c = r.map((e) => an(e, { formVar: i })).join("\n"), l = xr(r) ? " enctype=\"multipart/form-data\"" : "";
3217
+ return t(_r ||= s([
3071
3218
  "\n <script lang=\"ts\">\n ",
3072
3219
  "\n\n let { data, params } = $props();\n <\/script>\n\n <section data-role=\"content\">\n <div class=\"flex justify-between items-center mb-4\">\n <h1 class=\"text-3xl font-bold tracking-tight\">Edit ",
3073
3220
  "</h1>\n <Button href=\"",
@@ -3087,19 +3234,19 @@ function yr(t, n, r) {
3087
3234
  ".id} />\n <div class=\"grid grid-cols-1 md:grid-cols-2 gap-4\">\n ",
3088
3235
  "\n </div>\n <div class=\"mt-4 flex gap-2 border-t pt-4 -mx-4 px-4\">\n <Button type=\"submit\" size=\"sm\">Save changes</Button>\n <Button href=\"",
3089
3236
  "/\\${params.id}\" variant=\"outline\" size=\"sm\">Cancel</Button>\n </div>\n </form>\n </div>\n </section>\n "
3090
- ]), s, t.displayName.toLowerCase(), n.list, i, l, t.name, c, n.list);
3237
+ ]), o, e.displayName.toLowerCase(), n.list, i, l, e.name, c, n.list);
3091
3238
  }
3092
- function br(t, n, r) {
3093
- let i = r.some((e) => e.type === "select"), a = i ? `${dr(r)}` : "", s = r.map((t) => {
3239
+ function jr(e, n, r) {
3240
+ let i = r.some((e) => e.type === "select"), a = i ? `${Sr(r)}` : "", o = r.map((e) => {
3094
3241
  let n = "{ getValue }", r = "{ value: getValue() }";
3095
- return t.type === "relation" && (n = "{ getValue, row }", r = `{ value: getValue(), expanded: row.original.expand?.${t.name}, displayField: "${t.displayField}" }`), t.type === "select" && (r = `{ value: getValue(), options: ${t.name}Labels }`), t.type === "file" && (n = "{ getValue, row }", r = "{ value: getValue(), collectionId: row.original.collectionId, id: row.original.id }"), e`
3096
- columnHelper.accessor("${t.name}", {
3097
- header: ({ column }) => renderComponent(ColumnHeader, { column, title: "${t.title}" }),
3098
- cell: (${n}) => renderComponent(Cells.${t.type.charAt(0).toUpperCase() + t.type.slice(1)}Cell, ${r})
3242
+ return e.type === "relation" && (n = "{ getValue, row }", r = `{ value: getValue(), expanded: row.original.expand?.${e.name}, displayField: "${e.displayField}" }`), e.type === "select" && (r = `{ value: getValue(), options: ${e.name}Labels }`), e.type === "file" && (n = "{ getValue, row }", r = "{ value: getValue(), collectionId: row.original.collectionId, id: row.original.id }"), t`
3243
+ columnHelper.accessor("${e.name}", {
3244
+ header: ({ column }) => renderComponent(ColumnHeader, { column, title: "${e.title}" }),
3245
+ cell: (${n}) => renderComponent(Cells.${e.type.charAt(0).toUpperCase() + e.type.slice(1)}Cell, ${r})
3099
3246
  })
3100
3247
  `;
3101
3248
  }).join(",\n"), c = r.filter((e) => e.type === "select").map((e) => `<FacetedFilter column={table.getColumn("${e.name}")!} title="${e.title}" options={Object.values(${e.name}Labels)} />`).join("\n");
3102
- return e(sr ||= o([
3249
+ return t(vr ||= s([
3103
3250
  "\n <script lang=\"ts\">\n import {\n type ColumnFiltersState,\n type PaginationState,\n type RowSelectionState,\n type SortingState,\n type VisibilityState,\n getCoreRowModel,\n getFacetedRowModel,\n getFacetedUniqueValues,\n getFilteredRowModel,\n getPaginationRowModel,\n getSortedRowModel,\n createColumnHelper\n } from \"@tanstack/table-core\";\n import { createSvelteTable, FlexRender, renderComponent } from \"$lib/components/ui/data-table\";\n import * as Table from \"$lib/components/ui/table\";\n import { Checkbox } from \"$lib/components/ui/checkbox\";\n import { ColumnHeader } from \"$lib/components/ui/column-header\";\n import { Pagination } from \"$lib/components/ui/pagination\";\n import { RowActions } from \"$lib/components/ui/row-actions\";\n import * as Cells from \"$lib/components/ui/cells\";\n import { Button } from \"$lib/components/ui/button\";\n import { Input } from \"$lib/components/ui/input\";\n ",
3104
3251
  "\n import XIcon from \"@lucide/svelte/icons/x\";\n import PlusIcon from \"@lucide/svelte/icons/plus\";\n import type { Models } from \"@velastack/pocketbase\";\n\n let { data } = $props();\n let rowSelection = $state<RowSelectionState>({});\n let columnVisibility = $state<VisibilityState>({});\n let columnFilters = $state<ColumnFiltersState>([]);\n let sorting = $state<SortingState>([]);\n let pagination = $state<PaginationState>({ pageIndex: 0, pageSize: 10 });\n\n ",
3105
3252
  "\n\n const columnHelper = createColumnHelper<Models[\"",
@@ -3131,55 +3278,55 @@ function br(t, n, r) {
3131
3278
  "\n {#if table.getState().columnFilters.length > 0}\n <Button variant=\"ghost\" onclick={() => table.resetColumnFilters()} class=\"h-8 px-2 lg:px-3\">\n Reset\n <XIcon />\n </Button>\n {/if}\n </div>\n\n <Button href=\"",
3132
3279
  "\" variant=\"outline\" size=\"sm\">\n <PlusIcon class=\"w-4 h-4\" />\n New ",
3133
3280
  "\n </Button>\n </div>\n\n <div class=\"rounded-md border overflow-hidden\">\n <Table.Root>\n <Table.Header>\n {#each table.getHeaderGroups() as headerGroup (headerGroup.id)}\n <Table.Row>\n {#each headerGroup.headers as header (header.id)}\n <Table.Head colspan={header.colSpan} class={header.column.columnDef.meta?.class}>\n {#if !header.isPlaceholder}\n <FlexRender content={header.column.columnDef.header} context={header.getContext()} />\n {/if}\n </Table.Head>\n {/each}\n </Table.Row>\n {/each}\n </Table.Header>\n <Table.Body>\n {#each table.getRowModel().rows as row (row.id)}\n <Table.Row data-state={row.getIsSelected() && \"selected\"}>\n {#each row.getVisibleCells() as cell (cell.id)}\n <Table.Cell class={cell.column.columnDef.meta?.class}>\n <FlexRender content={cell.column.columnDef.cell} context={cell.getContext()} />\n </Table.Cell>\n {/each}\n </Table.Row>\n {:else}\n <Table.Row>\n <Table.Cell colspan={columns.length} class=\"h-24 text-center\">No results.</Table.Cell>\n </Table.Row>\n {/each}\n </Table.Body>\n </Table.Root>\n </div>\n\n <Pagination {table} />\n </div>\n </section>\n "
3134
- ]), i ? "import { FacetedFilter } from \"$lib/components/ui/faceted-filter\";" : "", a, t.tableName, s, r.length > 0 ? "," : "", n.list, n.list, n.list, t.pluralName, t.pluralDisplayName, t.pluralDisplayName.toLowerCase(), c, n.new, t.displayName.toLowerCase());
3281
+ ]), i ? "import { FacetedFilter } from \"$lib/components/ui/faceted-filter\";" : "", a, e.tableName, o, r.length > 0 ? "," : "", n.list, n.list, n.list, e.pluralName, e.pluralDisplayName, e.pluralDisplayName.toLowerCase(), c, n.new, e.displayName.toLowerCase());
3135
3282
  }
3136
- function xr(t, n, r) {
3283
+ function Mr(e, n, r) {
3137
3284
  let i = V(n), a = i ? `{ expand: "${i}" }` : "";
3138
- return e`
3285
+ return t`
3139
3286
  export const load = async ({ locals }) => {
3140
- const ${t.pluralName} = await ${r}.collection("${t.tableName}").getFullList(${a});
3141
- return { ${t.pluralName} };
3287
+ const ${e.pluralName} = await ${r}.collection("${e.tableName}").getFullList(${a});
3288
+ return { ${e.pluralName} };
3142
3289
  };
3143
3290
  `;
3144
3291
  }
3145
- function Sr(t, n, r) {
3146
- return _r(n) ? e`
3292
+ function Nr(e, n, r) {
3293
+ return Or(n) ? t`
3147
3294
  export const load = async ({ locals }) => {
3148
- ${fr(n, r)}
3149
- return { ${pr(n)} };
3295
+ ${Cr(n, r)}
3296
+ return { ${wr(n)} };
3150
3297
  };
3151
3298
  ` : "";
3152
3299
  }
3153
- function Cr(t, n, r, i, a) {
3154
- let o = hr(t), s = r.find((e) => e.type === "relation" && e.isCurrentUser), c = a && s ? e`
3300
+ function Pr(e, n, r, i, a) {
3301
+ let o = Er(e), s = r.find((e) => e.type === "relation" && e.isCurrentUser), c = a && s ? t`
3155
3302
  {
3156
3303
  ...data,
3157
3304
  ${s.name}: locals.pb.authStore.record?.id
3158
3305
  }
3159
3306
  ` : "data";
3160
- return e`
3307
+ return t`
3161
3308
  import { form, getRequestEvent } from "$app/server";
3162
3309
  import { redirect } from "@sveltejs/kit";
3163
- import { ${t.schemaName} } from "$lib/schemas/${t.name}";
3310
+ import { ${e.schemaName} } from "$lib/schemas/${e.name}";
3164
3311
 
3165
- export const ${o} = form(${t.schemaName}, async (data) => {
3312
+ export const ${o} = form(${e.schemaName}, async (data) => {
3166
3313
  const { locals } = getRequestEvent();
3167
- const ${t.name} = await ${i}.collection("${t.tableName}").create(
3314
+ const ${e.name} = await ${i}.collection("${e.tableName}").create(
3168
3315
  ${c}
3169
3316
  );
3170
- redirect(303, \`${n.list}/\${${t.name}.id}\`);
3317
+ redirect(303, \`${n.list}/\${${e.name}.id}\`);
3171
3318
  });
3172
3319
  `;
3173
3320
  }
3174
- function wr(t, n, r, i) {
3321
+ function Fr(e, n, r, i) {
3175
3322
  let a = V(r), o = a ? `, { expand: "${a}" }` : "";
3176
- return e`
3323
+ return t`
3177
3324
  import { error, redirect } from "@sveltejs/kit";
3178
3325
 
3179
3326
  export const load = async ({ locals, params }) => {
3180
3327
  try {
3181
- const ${t.name} = await ${i}.collection("${t.tableName}").getOne(params.id${o});
3182
- return { ${t.name} };
3328
+ const ${e.name} = await ${i}.collection("${e.tableName}").getOne(params.id${o});
3329
+ return { ${e.name} };
3183
3330
  } catch {
3184
3331
  throw error(404, "Not found");
3185
3332
  }
@@ -3187,21 +3334,21 @@ function wr(t, n, r, i) {
3187
3334
 
3188
3335
  export const actions = {
3189
3336
  default: async ({ locals, params }) => {
3190
- await ${i}.collection("${t.tableName}").delete(params.id);
3337
+ await ${i}.collection("${e.tableName}").delete(params.id);
3191
3338
  throw redirect(303, "${n.list}");
3192
3339
  },
3193
3340
  };
3194
3341
  `;
3195
3342
  }
3196
- function Tr(t, n, r) {
3197
- let i = r.some((e) => e.type === "select"), a = r.some((e) => e.type === "relation"), s = r.some((e) => e.type === "file"), c = [
3343
+ function Ir(e, n, r) {
3344
+ let i = r.some((e) => e.type === "select"), a = r.some((e) => e.type === "relation"), o = r.some((e) => e.type === "file"), c = [
3198
3345
  "import { Button } from \"$lib/components/ui/button\";",
3199
3346
  "import ArrowLeftIcon from \"@lucide/svelte/icons/arrow-left\";",
3200
3347
  i || a ? "import { Badge } from \"$lib/components/ui/badge\";" : "",
3201
3348
  a ? "import CircleArrowRightIcon from \"@lucide/svelte/icons/circle-arrow-right\";" : "",
3202
- s ? "import FileIcon from \"@lucide/svelte/icons/file\";" : ""
3203
- ].filter(Boolean).join("\n"), l = dr(r), u = r.map((e) => Ee(t, e)).join("\n");
3204
- return e(cr ||= o([
3349
+ o ? "import FileIcon from \"@lucide/svelte/icons/file\";" : ""
3350
+ ].filter(Boolean).join("\n"), l = Sr(r), u = r.map((t) => Ee(e, t)).join("\n");
3351
+ return t(yr ||= s([
3205
3352
  "\n <script lang=\"ts\">\n ",
3206
3353
  "\n ",
3207
3354
  "\n\n let { data } = $props();\n <\/script>\n\n <section data-role=\"content\">\n <div class=\"flex justify-between items-center mb-4\">\n <h1 class=\"text-3xl font-bold tracking-tight\">",
@@ -3210,51 +3357,51 @@ function Tr(t, n, r) {
3210
3357
  "\n </div>\n\n <div class=\"mt-4 flex gap-2 border-t pt-4 -mx-4 px-4 justify-between\">\n <Button href=\"",
3211
3358
  "/{data.",
3212
3359
  ".id}/edit\" variant=\"outline\" size=\"sm\">\n Edit\n </Button>\n <form method=\"POST\">\n <Button type=\"submit\" variant=\"destructive\" size=\"sm\">Delete</Button>\n </form>\n </div>\n </div>\n </section>\n "
3213
- ]), c, l, t.displayName, n.list, u, n.list, t.name);
3360
+ ]), c, l, e.displayName, n.list, u, n.list, e.name);
3214
3361
  }
3215
- function Er(t, n, r) {
3216
- let i = fr(n, r), a = pr(n), o = a ? `, ${a}` : "";
3217
- return e`
3362
+ function Lr(e, n, r) {
3363
+ let i = Cr(n, r), a = wr(n), o = a ? `, ${a}` : "";
3364
+ return t`
3218
3365
  import { error } from "@sveltejs/kit";
3219
3366
 
3220
3367
  export const load = async ({ locals, params }) => {
3221
- let ${t.name};
3368
+ let ${e.name};
3222
3369
  try {
3223
- ${t.name} = await ${r}.collection("${t.tableName}").getOne(params.id);
3370
+ ${e.name} = await ${r}.collection("${e.tableName}").getOne(params.id);
3224
3371
  } catch {
3225
3372
  throw error(404, "Not found");
3226
3373
  }
3227
3374
  ${i}
3228
- return { ${t.name}${o} };
3375
+ return { ${e.name}${o} };
3229
3376
  };
3230
3377
  `;
3231
3378
  }
3232
- function Dr(t, n, r) {
3233
- let i = gr(t);
3234
- return e`
3379
+ function Rr(e, n, r) {
3380
+ let i = Dr(e);
3381
+ return t`
3235
3382
  import { form, getRequestEvent, error } from "$app/server";
3236
3383
  import { redirect } from "@sveltejs/kit";
3237
- import { ${t.schemaName} } from "$lib/schemas/${t.name}";
3384
+ import { ${e.schemaName} } from "$lib/schemas/${e.name}";
3238
3385
 
3239
- export const ${i} = form(${t.schemaName}, async (data) => {
3386
+ export const ${i} = form(${e.schemaName}, async (data) => {
3240
3387
  const { locals } = getRequestEvent();
3241
3388
  const { id, collectionId, ...rest } = data;
3242
3389
  if (!id) error(400, "id is required");
3243
- await ${r}.collection("${t.tableName}").update(id, rest);
3390
+ await ${r}.collection("${e.tableName}").update(id, rest);
3244
3391
  redirect(303, \`${n.list}/\${id}\`);
3245
3392
  });
3246
3393
  `;
3247
3394
  }
3248
- async function Or(e) {
3249
- let { modelPath: t, fields: n } = lr(e.argv), { model: r, fields: i, auth: a, shouldCreateCollection: o, collections: s } = await z(e, t, n), c = Je(r), l = Ye(r), u = mr(e), d = i.filter((e) => !(e.type === "relation" && e.isCurrentUser)), f = [
3395
+ async function zr(e) {
3396
+ let { modelPath: t, fields: n } = br(e.argv), { model: r, fields: i, auth: a, shouldCreateCollection: o, collections: s } = await z(e, t, n), c = Je(r), l = Ye(r), u = Tr(e), d = i.filter((e) => !(e.type === "relation" && e.isCurrentUser)), f = [
3250
3397
  Z(`src/lib/schemas/${r.name}.ts`, B(r, i, {
3251
3398
  includeModelFields: !0,
3252
3399
  forForm: !0
3253
3400
  })),
3254
- Z(`${c.list}/+page.server.ts`, xr(r, d, u)),
3255
- Z(`${c.list}/+page.svelte`, br(r, l, d))
3256
- ], p = Sr(r, d, u);
3257
- p && f.push(Z(`${c.new}/+page.server.ts`, p)), f.push(Z(`${c.new}/form.remote.ts`, Cr(r, l, i, u, e.features.auth)), Z(`${c.new}/+page.svelte`, vr(r, l, d)), Z(`${c.show}/+page.server.ts`, wr(r, l, d, u)), Z(`${c.show}/+page.svelte`, Tr(r, l, d)), Z(`${c.edit}/+page.server.ts`, Er(r, d, u)), Z(`${c.edit}/form.remote.ts`, Dr(r, l, u)), Z(`${c.edit}/+page.svelte`, yr(r, l, d)), Z(`${c.list}/server.test.ts`, Ct(r, l, i, e, s)));
3401
+ Z(`${c.list}/+page.server.ts`, Mr(r, d, u)),
3402
+ Z(`${c.list}/+page.svelte`, jr(r, l, d))
3403
+ ], p = Nr(r, d, u);
3404
+ p && f.push(Z(`${c.new}/+page.server.ts`, p)), f.push(Z(`${c.new}/form.remote.ts`, Pr(r, l, i, u, e.features.auth)), Z(`${c.new}/+page.svelte`, kr(r, l, d)), Z(`${c.show}/+page.server.ts`, Fr(r, l, d, u)), Z(`${c.show}/+page.svelte`, Ir(r, l, d)), Z(`${c.edit}/+page.server.ts`, Lr(r, d, u)), Z(`${c.edit}/form.remote.ts`, Rr(r, l, u)), Z(`${c.edit}/+page.svelte`, Ar(r, l, d)), Z(`${c.list}/server.test.ts`, Ct(r, l, i, e, s)));
3258
3405
  let m = [
3259
3406
  ...W(d),
3260
3407
  "button",
@@ -3278,49 +3425,51 @@ async function Or(e) {
3278
3425
  deletes: [],
3279
3426
  components: [...new Set(m)],
3280
3427
  packages: ["@tanstack/table-core"],
3281
- collections: o ? [Nt(r, i, a)] : []
3428
+ collections: o ? [Nt(r, i, a)] : [],
3429
+ collectionPatches: []
3282
3430
  };
3283
3431
  }
3284
3432
  //#endregion
3285
3433
  //#region src/patterns/generate/scaffold-remote/generate.preview.ts
3286
- var kr = /* @__PURE__ */ Object.assign({ "./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" }), Ar = "./preview-modifies/";
3287
- async function jr(e) {
3434
+ var Br = /* @__PURE__ */ Object.assign({ "./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" }), Vr = "./preview-modifies/";
3435
+ async function Hr(e) {
3288
3436
  return {
3289
3437
  creates: [],
3290
- modifies: Object.entries(kr).map(([e, n]) => {
3291
- let i = r(e, Ar);
3438
+ modifies: Object.entries(Br).map(([e, t]) => {
3439
+ let r = i(e, Vr);
3292
3440
  return {
3293
- path: i,
3294
- language: t(i),
3295
- content: n,
3441
+ path: r,
3442
+ language: n(r),
3443
+ content: t,
3296
3444
  status: "success"
3297
3445
  };
3298
3446
  }).sort((e, t) => e.path.localeCompare(t.path)),
3299
3447
  deletes: [],
3300
3448
  components: [],
3301
3449
  packages: [],
3302
- collections: []
3450
+ collections: [],
3451
+ collectionPatches: []
3303
3452
  };
3304
3453
  }
3305
3454
  //#endregion
3306
3455
  //#region src/patterns/generate/scaffold-remote/index.ts
3307
- var Mr = "generate-scaffold-remote", Nr = "1.0.0", Pr = "src/patterns/generate/scaffold-remote", Fr = "/generate/scaffold-remote";
3308
- async function Ir(e) {
3309
- let t = await Or(e);
3310
- if (e.env === "preview") return v(n([t, await jr(e)]));
3311
- if (e.env !== "runtime") return v(t);
3312
- let { createCollections: r } = await import("./chunks/collections-Bs9xy7nU.js"), i = await r(t.collections, e), { modifyOutcomeToFile: a } = await import("./chunks/modify-file-CpqC7kMR.js"), { findSvelteConfigPath: o, modifySvelteConfigRemote: s } = await import("./chunks/modify-svelte-config-remote-DWsScM6m.js"), c = o(e.root), l = a(c, s(c)), u = {
3456
+ var Ur = "generate-scaffold-remote", Wr = "1.0.0", Gr = "src/patterns/generate/scaffold-remote", Kr = "/generate/scaffold-remote";
3457
+ async function qr(e) {
3458
+ let t = await zr(e);
3459
+ if (e.env === "preview") return _(r([t, await Hr(e)]));
3460
+ if (e.env !== "runtime") return _(t);
3461
+ let { createCollections: n } = await import("./chunks/collections-BRIAYJ-Q.js"), i = await n(t.collections, e), { modifyOutcomeToFile: a } = await import("./chunks/modify-file-D3OuKUEp.js"), { findSvelteConfigPath: o, modifySvelteConfigRemote: s } = await import("./chunks/modify-svelte-config-remote-Dzgk1OIN.js"), c = o(e.root), l = a(c, s(c)), u = {
3313
3462
  ...t,
3314
3463
  creates: [...t.creates, ...i],
3315
3464
  modifies: [...t.modifies, ...l ? [l] : []]
3316
- }, { writeResult: d } = await import("./chunks/write-result-ENWLDQtP.js");
3317
- return d(await v(u), e);
3318
- }
3319
- var Lr = {
3320
- version: Nr,
3321
- slug: Mr,
3322
- source: Pr,
3323
- docs: Fr,
3465
+ }, { writeResult: d } = await import("./chunks/write-result-C80dpjr-.js");
3466
+ return d(await _(u), e);
3467
+ }
3468
+ var Jr = {
3469
+ version: Wr,
3470
+ slug: Ur,
3471
+ source: Gr,
3472
+ docs: Kr,
3324
3473
  plan: "open",
3325
3474
  title: "Generate a scaffold (remote functions)",
3326
3475
  summary: "Generates CRUD routes and schema using SvelteKit remote functions for create/update forms.",
@@ -3365,30 +3514,30 @@ var Lr = {
3365
3514
  ],
3366
3515
  tests: 6,
3367
3516
  baseline: "velastack",
3368
- generate: Ir
3517
+ generate: qr
3369
3518
  };
3370
3519
  //#endregion
3371
3520
  //#region src/patterns/generate/schema/generate.ts
3372
- function Rr(e) {
3373
- let [t, ...n] = e;
3374
- if (!t) throw new _("Invalid command arguments. Expected: <model> [fields...]");
3521
+ function Yr(t) {
3522
+ let [n, ...r] = t;
3523
+ if (!n) throw new e("Invalid command arguments. Expected: <model> [fields...]");
3375
3524
  return {
3376
- modelPath: t,
3377
- fields: n
3525
+ modelPath: n,
3526
+ fields: r
3378
3527
  };
3379
3528
  }
3380
- function zr(e, n) {
3529
+ function Xr(e, t) {
3381
3530
  return {
3382
3531
  path: e,
3383
- language: t(e),
3384
- content: n,
3532
+ language: n(e),
3533
+ content: t,
3385
3534
  status: "success"
3386
3535
  };
3387
3536
  }
3388
- async function Br(e) {
3389
- let { modelPath: t, fields: n } = Rr(e.argv), { model: r, fields: i, shouldCreateCollection: a } = await z(e, t, n);
3537
+ async function Zr(e) {
3538
+ let { modelPath: t, fields: n } = Yr(e.argv), { model: r, fields: i, shouldCreateCollection: a } = await z(e, t, n);
3390
3539
  return {
3391
- creates: [zr(`src/lib/schemas/${r.name}.ts`, B(r, i, {
3540
+ creates: [Xr(`src/lib/schemas/${r.name}.ts`, B(r, i, {
3392
3541
  includeModelFields: !a,
3393
3542
  forForm: !0
3394
3543
  }))],
@@ -3396,23 +3545,24 @@ async function Br(e) {
3396
3545
  deletes: [],
3397
3546
  components: [],
3398
3547
  packages: [],
3399
- collections: []
3548
+ collections: [],
3549
+ collectionPatches: []
3400
3550
  };
3401
3551
  }
3402
3552
  //#endregion
3403
3553
  //#region src/patterns/generate/schema/index.ts
3404
- var Vr = "generate-schema", Hr = "1.0.7", Ur = "src/patterns/generate/schema", Wr = "/generate/schema";
3405
- async function Gr(e) {
3406
- let t = await Br(e);
3407
- if (e.env !== "runtime") return v(t);
3408
- let { writeResult: n } = await import("./chunks/write-result-ENWLDQtP.js");
3409
- return n(await v(t), e);
3410
- }
3411
- var Kr = {
3412
- version: Hr,
3413
- slug: Vr,
3414
- source: Ur,
3415
- docs: Wr,
3554
+ var Qr = "generate-schema", $r = "1.0.7", ei = "src/patterns/generate/schema", ti = "/generate/schema";
3555
+ async function ni(e) {
3556
+ let t = await Zr(e);
3557
+ if (e.env !== "runtime") return _(t);
3558
+ let { writeResult: n } = await import("./chunks/write-result-C80dpjr-.js");
3559
+ return n(await _(t), e);
3560
+ }
3561
+ var ri = {
3562
+ version: $r,
3563
+ slug: Qr,
3564
+ source: ei,
3565
+ docs: ti,
3416
3566
  plan: "open",
3417
3567
  title: "Generate a schema",
3418
3568
  summary: "Generates a zod schema.",
@@ -3455,8 +3605,8 @@ var Kr = {
3455
3605
  ],
3456
3606
  tests: 0,
3457
3607
  baseline: "velastack",
3458
- generate: Gr
3459
- }, qr = /* @__PURE__ */ Object.assign({
3608
+ generate: ni
3609
+ }, ii = /* @__PURE__ */ Object.assign({
3460
3610
  "./creates/src/lib/components/app-sidebar.svelte": "<script lang=\"ts\">\n import type { ComponentProps } from 'svelte';\n import HomeIcon from '@lucide/svelte/icons/home';\n import * as Sidebar from '$lib/components/ui/sidebar';\n import NavMain from './nav-main.svelte';\n import NavUser from './nav-user.svelte';\n\n let data = {\n navMain: [\n {\n title: 'Dashboard',\n url: '/dashboard',\n icon: HomeIcon\n }\n ]\n };\n\n let {\n user,\n meta,\n ref = $bindable(null),\n ...restProps\n }: ComponentProps<typeof Sidebar.Root> & { user: any; meta: any } = $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} />\n </Sidebar.Footer>\n</Sidebar.Root>\n",
3461
3611
  "./creates/src/lib/components/nav-main.svelte": "<script lang=\"ts\">\n import type { Component } from 'svelte';\n import * as Sidebar from '$lib/components/ui/sidebar';\n import { page } from '$app/state';\n\n const isActive = (url: string) => {\n return page.url.pathname.startsWith(url);\n };\n\n let {\n items\n }: {\n items: {\n title: string;\n url: string;\n icon: Component;\n items?: {\n title: string;\n url: string;\n }[];\n }[];\n } = $props();\n<\/script>\n\n<Sidebar.Group>\n <Sidebar.Menu>\n {#each items as item (item.title)}\n <Sidebar.MenuItem>\n <Sidebar.MenuButton isActive={isActive(item.url)}>\n {#snippet child({ props })}\n <a href={item.url} {...props}>\n <item.icon />\n <span>{item.title}</span>\n </a>\n {/snippet}\n </Sidebar.MenuButton>\n </Sidebar.MenuItem>\n {/each}\n </Sidebar.Menu>\n</Sidebar.Group>\n",
3462
3612
  "./creates/src/lib/components/nav-user.svelte": "<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 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 };\n\n let {\n user\n }: {\n user: {\n id: string;\n name: string;\n email: string;\n avatar: string;\n };\n } = $props();\n\n const sidebar = Sidebar.useSidebar();\n<\/script>\n\n<Sidebar.Menu>\n <Sidebar.MenuItem>\n <DropdownMenu.Root>\n <DropdownMenu.Trigger>\n {#snippet child({ props })}\n <Sidebar.MenuButton\n size=\"lg\"\n class=\"data-[state=open]:bg-sidebar-accent data-[state=open]:text-sidebar-accent-foreground\"\n {...props}\n >\n <Avatar.Root class=\"size-8 rounded-lg\">\n {#if user.avatar}\n <Avatar.Image src=\"/api/files/users/{user.id}/{user.avatar}\" alt={user.name} />\n {/if}\n <Avatar.Fallback class=\"rounded-lg\">\n {user.email?.charAt(0).toUpperCase()}\n </Avatar.Fallback>\n </Avatar.Root>\n <div class=\"grid flex-1 text-left text-sm leading-tight\">\n <span class=\"truncate font-medium\">{user.name}</span>\n <span class=\"truncate text-xs\">{user.email}</span>\n </div>\n <ChevronsUpDownIcon class=\"ml-auto size-4\" />\n </Sidebar.MenuButton>\n {/snippet}\n </DropdownMenu.Trigger>\n <DropdownMenu.Content\n class=\"w-(--bits-dropdown-menu-anchor-width) min-w-56 rounded-lg\"\n side={sidebar.isMobile ? 'bottom' : 'right'}\n align=\"end\"\n sideOffset={4}\n >\n <DropdownMenu.Label class=\"p-0 font-normal\">\n <div class=\"flex items-center gap-2 px-1 py-1.5 text-left text-sm\">\n <Avatar.Root class=\"size-8 rounded-lg\">\n {#if user.avatar}\n <Avatar.Image src=\"/api/files/users/{user.id}/{user.avatar}\" alt={user.name} />\n {/if}\n <Avatar.Fallback class=\"rounded-lg\">\n {user.email?.charAt(0).toUpperCase()}\n </Avatar.Fallback>\n </Avatar.Root>\n <div class=\"grid flex-1 text-left text-sm leading-tight\">\n <span class=\"truncate font-medium\">{user.name}</span>\n <span class=\"truncate text-xs\">{user.email}</span>\n </div>\n </div>\n </DropdownMenu.Label>\n <DropdownMenu.Separator />\n <DropdownMenu.Group>\n <DropdownMenu.Item onclick={toggleMode}>\n {#if mode.current === 'dark'}\n <SunIcon />\n Light mode\n {:else}\n <MoonIcon />\n Dark mode\n {/if}\n </DropdownMenu.Item>\n {#each data.navUser as item}\n <DropdownMenu.Item class=\"p-0\">\n <a href={item.url} class=\"flex cursor-default items-center gap-2 px-2 py-1.5 w-full\">\n <item.icon />\n {item.title}\n </a>\n </DropdownMenu.Item>\n {/each}\n </DropdownMenu.Group>\n <DropdownMenu.Separator />\n <DropdownMenu.Item class=\"p-0\">\n <form action=\"/logout\" method=\"post\" class=\"w-full\">\n <button type=\"submit\" class=\"flex cursor-default items-center gap-2 px-2 py-1.5 w-full\">\n <LogOutIcon />\n Log out\n </button>\n </form>\n </DropdownMenu.Item>\n </DropdownMenu.Content>\n </DropdownMenu.Root>\n </Sidebar.MenuItem>\n</Sidebar.Menu>\n",
@@ -3498,17 +3648,17 @@ var Kr = {
3498
3648
  "./creates/src/routes/(public)/signup/+page.server.ts": "import { redirect } from \"@sveltejs/kit\";\nimport { fail, superValidate } from \"sveltekit-superforms\";\nimport { zod4 } from \"sveltekit-superforms/adapters\";\nimport { setFlash } from \"sveltekit-flash-message/server\";\nimport { setPocketbaseErrors } from \"@velastack/pocketbase\";\nimport { dev } from \"$app/environment\";\nimport { signupSchema } from \"$lib/schemas/signup\";\n\nexport const load = async ({ locals }) => {\n const authMethods = await locals.admin.collection(\"users\").listAuthMethods();\n\n if (locals.pb.authStore.isValid) {\n redirect(303, \"/dashboard\");\n }\n\n return { form: await superValidate(zod4(signupSchema)), authMethods };\n};\n\nexport const actions = {\n default: async ({ locals, request, cookies, url }) => {\n const form = await superValidate(request, zod4(signupSchema));\n\n if (!form.valid) {\n return fail(400, { form });\n }\n\n let user;\n\n try {\n user = await locals.admin.collection(\"users\").create({\n email: form.data.email,\n password: form.data.password,\n passwordConfirm: form.data.passwordConfirm,\n });\n } catch (error) {\n setPocketbaseErrors(form, error);\n return fail(400, { form });\n }\n\n await locals.pb.collection(\"users\").requestVerification(user.email);\n await locals.pb\n .collection(\"users\")\n .authWithPassword(form.data.email, form.data.password);\n\n const redirectUrl = url.searchParams.get(\"redirect\") ?? \"/dashboard\";\n const cookie = locals.pb.authStore.getCookie();\n cookies.set(\"pb_auth\", cookie, {\n path: \"/\",\n httpOnly: true,\n sameSite: \"lax\",\n secure: !dev,\n maxAge: 60 * 60 * 24 * 30,\n });\n\n setFlash(\n { type: \"toast\", message: \"We sent a confirmation link to your email.\" },\n cookies,\n );\n return redirect(303, redirectUrl);\n },\n};\n",
3499
3649
  "./creates/src/routes/(public)/signup/+page.svelte": "<script lang=\"ts\">\n import { untrack } from \"svelte\";\n import { Button } from \"$lib/components/ui/button\";\n import * as Card from \"$lib/components/ui/card\";\n import { superForm } from \"sveltekit-superforms\";\n import { zod4Client } from \"sveltekit-superforms/adapters\";\n import { signupSchema } from \"$lib/schemas/signup\";\n import * as Form from \"$lib/components/ui/form\";\n import { Input } from \"$lib/components/ui/input\";\n import PocketBase from \"pocketbase-sveltekit\";\n import { goto } from \"$app/navigation\";\n import { page } from \"$app/state\";\n\n let { data } = $props();\n let authMethods = $derived(data.authMethods);\n\n const redirect = page.url.searchParams.get(\"redirect\");\n const hasOAuth2 = $derived(\n authMethods.oauth2.enabled && authMethods.oauth2.providers.length > 0,\n );\n const hasAuthMethods = $derived(\n authMethods.password.enabled || authMethods.otp.enabled || hasOAuth2,\n );\n\n const form = superForm(\n untrack(() => data.form),\n {\n validators: zod4Client(signupSchema),\n },\n );\n\n const handleOAuth2 = (provider: string) => {\n const pb = new PocketBase(\"/\");\n\n pb.collection(\"users\")\n .authWithOAuth2({ provider, createData: {} })\n .then(() => goto(\"/dashboard\"));\n };\n\n const { form: formData } = form;\n<\/script>\n\n<div class=\"h-full flex flex-col items-center justify-center gap-6 p-6 md:p-10\">\n <div class=\"flex w-full max-w-sm flex-col gap-6\">\n <a href=\"/\" class=\"flex items-center gap-2 self-center font-medium\">\n <div\n class=\"bg-primary text-primary-foreground flex size-6 items-center justify-center rounded-md\"\n >\n <img src=\"/favicon.svg\" alt=\"logo\" class=\"size-4\" />\n </div>\n {data.meta.appName}\n </a>\n\n <div class=\"flex flex-col gap-6\">\n <Card.Root>\n {#if hasAuthMethods}\n <Card.Header class=\"text-center\">\n <Card.Title class=\"text-xl\">Create an account</Card.Title>\n {#if hasOAuth2}\n <Card.Description>Choose a sign up method</Card.Description>\n {:else}\n <Card.Description>Use your email to sign up</Card.Description>\n {/if}\n </Card.Header>\n {:else}\n <Card.Header class=\"text-center\">\n <Card.Title class=\"text-xl\">Signups are disabled</Card.Title>\n <Card.Description\n >Check back later for signup options</Card.Description\n >\n </Card.Header>\n {/if}\n <Card.Content>\n <form method=\"POST\">\n <div class=\"grid gap-6\">\n {#if hasOAuth2}\n <div class=\"flex flex-col gap-4\">\n {#each authMethods.oauth2.providers as provider}\n <Button\n variant=\"outline\"\n class=\"w-full\"\n onclick={() => handleOAuth2(provider.name)}\n >\n <img\n src=\"/admin/_/images/oauth2/{provider.name}.svg\"\n class=\"size-5 bg-white p-0.5 rounded-sm\"\n alt=\"\"\n />\n Login with {provider.displayName}\n </Button>\n {/each}\n </div>\n {/if}\n\n {#if authMethods.password.enabled}\n {#if hasOAuth2}\n <div\n class=\"after:border-border relative text-center text-sm after:absolute after:inset-0 after:top-1/2 after:z-0 after:flex after:items-center after:border-t\"\n >\n <span\n class=\"bg-card text-muted-foreground relative z-10 px-2\"\n >\n Or continue with\n </span>\n </div>\n {/if}\n\n <div class=\"grid gap-2\">\n <Form.Field {form} name=\"email\" class=\"col-span-1\">\n <Form.Control>\n {#snippet children({ props })}\n <Form.Label>Email</Form.Label>\n <Input\n {...props}\n type=\"email\"\n bind:value={$formData.email}\n required\n />\n {/snippet}\n </Form.Control>\n <Form.FieldErrors class=\"contents text-destructive\" />\n </Form.Field>\n\n <Form.Field {form} name=\"password\" class=\"col-span-1\">\n <Form.Control>\n {#snippet children({ props })}\n <Form.Label>Password</Form.Label>\n <Input\n {...props}\n type=\"password\"\n bind:value={$formData.password}\n required\n autocomplete=\"new-password\"\n />\n {/snippet}\n </Form.Control>\n <Form.FieldErrors class=\"contents text-destructive\" />\n </Form.Field>\n\n <Form.Field {form} name=\"passwordConfirm\" class=\"col-span-1\">\n <Form.Control>\n {#snippet children({ props })}\n <Form.Label>Confirm Password</Form.Label>\n <Input\n {...props}\n type=\"password\"\n bind:value={$formData.passwordConfirm}\n required\n autocomplete=\"new-password\"\n />\n {/snippet}\n </Form.Control>\n <Form.FieldErrors class=\"contents text-destructive\" />\n </Form.Field>\n <Button type=\"submit\" class=\"w-full\">Create account</Button>\n </div>\n {/if}\n\n <div class=\"text-center text-sm\">\n Already have an account?\n <a\n href=\"/login{redirect\n ? `?redirect=${encodeURIComponent(redirect)}`\n : ''}\"\n class=\"underline underline-offset-4\"\n >\n Log in\n </a>\n </div>\n </div>\n </form>\n </Card.Content>\n </Card.Root>\n <div\n class=\"text-muted-foreground *:[a]:hover:text-primary *:[a]:underline *:[a]:underline-offset-4 text-balance text-center text-xs\"\n >\n By clicking continue, you agree to our <a href=\"/terms\"\n >Terms of Service</a\n >\n and <a href=\"/privacy\">Privacy Policy</a>.\n </div>\n </div>\n </div>\n</div>\n",
3500
3650
  "./creates/src/routes/(public)/signup/server.test.ts": "import { describe, it, expect } from \"vitest\";\nimport type { Match } from \"@velastack/pocketbase\";\nimport * as devalue from \"devalue\";\nimport type { RouteId } from \"./$types\";\n\ndescribe(\"GET /signup\", () => {\n it(\"should render the signup page\", async (context) => {\n const response = await context.request.get(\n \"/signup\" satisfies Match<RouteId>,\n );\n expect(response.status).toBe(200);\n });\n});\n\ndescribe(\"POST /signup\", () => {\n it(\"should signup with password\", async (context) => {\n const response = await context.agent\n .post(\"/signup\" satisfies Match<RouteId>)\n .type(\"form\")\n .send({\n email: `test-${Math.random().toString(36).slice(2)}@example.com`,\n password: \"password\",\n passwordConfirm: \"password\",\n });\n expect(response.body.status).toBe(303);\n expect(response.body.location).toBe(\"/dashboard\");\n });\n\n it(\"should error if the password does not match\", async (context) => {\n const response = await context.agent\n .post(\"/signup\" satisfies Match<RouteId>)\n .type(\"form\")\n .send({\n email: `test-${Math.random().toString(36).slice(2)}@example.com`,\n password: \"password\",\n passwordConfirm: \"password2\",\n });\n expect(response.body.status).toBe(400);\n const data = devalue.parse(response.body.data);\n expect(data.form.errors.passwordConfirm).toBeDefined();\n expect(data.form.errors.passwordConfirm[0]).toBe(\"Values don't match.\");\n });\n\n it(\"should error if the email is already taken\", async (context) => {\n const response = await context.agent\n .post(\"/signup\" satisfies Match<RouteId>)\n .type(\"form\")\n .send({\n email: context.user.email,\n password: \"password\",\n passwordConfirm: \"password\",\n });\n expect(response.body.status).toBe(400);\n const data = devalue.parse(response.body.data);\n expect(data.form.errors.email).toBeDefined();\n expect(data.form.errors.email[0]).toBe(\"Value must be unique.\");\n });\n});\n"
3501
- }), Jr = "./creates/";
3502
- async function Yr(e) {
3503
- let n = Object.entries(qr).map(([e, n]) => {
3504
- let i = r(e, Jr);
3651
+ }), ai = "./creates/";
3652
+ async function oi(e) {
3653
+ let t = Object.entries(ii).map(([e, t]) => {
3654
+ let r = i(e, ai);
3505
3655
  return {
3506
- path: i,
3507
- language: t(i),
3508
- content: n,
3656
+ path: r,
3657
+ language: n(r),
3658
+ content: t,
3509
3659
  status: "success"
3510
3660
  };
3511
- }).sort((e, t) => e.path.localeCompare(t.path)), i = [
3661
+ }).sort((e, t) => e.path.localeCompare(t.path)), r = [
3512
3662
  "sidebar",
3513
3663
  "breadcrumb",
3514
3664
  "separator",
@@ -3526,11 +3676,11 @@ async function Yr(e) {
3526
3676
  "file-form",
3527
3677
  "auth-menu"
3528
3678
  ];
3529
- return e.features.payments && i.push("alert-dialog"), {
3530
- creates: n,
3679
+ return e.features.payments && r.push("alert-dialog"), {
3680
+ creates: t,
3531
3681
  modifies: [],
3532
3682
  deletes: [],
3533
- components: i,
3683
+ components: r,
3534
3684
  packages: [],
3535
3685
  collections: [{
3536
3686
  listRule: "@request.auth.id = user.id",
@@ -3588,48 +3738,50 @@ async function Yr(e) {
3588
3738
  type: "json"
3589
3739
  }
3590
3740
  ]
3591
- }]
3741
+ }],
3742
+ collectionPatches: []
3592
3743
  };
3593
3744
  }
3594
3745
  //#endregion
3595
3746
  //#region src/patterns/enable/auth/generate.preview.ts
3596
- var Xr = /* @__PURE__ */ Object.assign({
3747
+ var si = /* @__PURE__ */ Object.assign({
3597
3748
  "./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",
3598
3749
  "./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",
3599
3750
  "./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"
3600
- }), Zr = "./preview-modifies/";
3601
- async function Qr(e) {
3751
+ }), ci = "./preview-modifies/";
3752
+ async function li(e) {
3602
3753
  return {
3603
3754
  creates: [],
3604
- modifies: Object.entries(Xr).map(([e, n]) => {
3605
- let i = r(e, Zr);
3755
+ modifies: Object.entries(si).map(([e, t]) => {
3756
+ let r = i(e, ci);
3606
3757
  return {
3607
- path: i,
3608
- language: t(i),
3609
- content: n,
3758
+ path: r,
3759
+ language: n(r),
3760
+ content: t,
3610
3761
  status: "success"
3611
3762
  };
3612
3763
  }).sort((e, t) => e.path.localeCompare(t.path)),
3613
3764
  deletes: [],
3614
3765
  components: [],
3615
3766
  packages: [],
3616
- collections: []
3767
+ collections: [],
3768
+ collectionPatches: []
3617
3769
  };
3618
3770
  }
3619
3771
  //#endregion
3620
3772
  //#region src/patterns/enable/auth/index.ts
3621
- var $r = "enable-auth", ei = "1.0.7", ti = "src/patterns/enable/auth", ni = "/enable/auth";
3622
- async function ri(e) {
3623
- let t = await Yr(e);
3624
- if (e.env === "preview") return v(n([t, await Qr(e)]));
3625
- let { generate: r } = await import("./chunks/generate.runtime-6QnXtCSG.js"), i = await r(e), { writeResult: a } = await import("./chunks/write-result-ENWLDQtP.js");
3626
- return a(await v(n([t, i])), e);
3627
- }
3628
- var ii = {
3629
- version: ei,
3630
- slug: $r,
3631
- source: ti,
3632
- docs: ni,
3773
+ var ui = "enable-auth", di = "1.0.7", fi = "src/patterns/enable/auth", pi = "/enable/auth";
3774
+ async function mi(e) {
3775
+ let t = await oi(e);
3776
+ if (e.env === "preview") return _(r([t, await li(e)]));
3777
+ let { generate: n } = await import("./chunks/generate.runtime-BKrtBCRk.js"), i = await n(e), { writeResult: a } = await import("./chunks/write-result-C80dpjr-.js");
3778
+ return a(await _(r([t, i])), e);
3779
+ }
3780
+ var hi = {
3781
+ version: di,
3782
+ slug: ui,
3783
+ source: fi,
3784
+ docs: pi,
3633
3785
  plan: "open",
3634
3786
  title: "Enable authentication",
3635
3787
  summary: "Enables authentication.",
@@ -3658,8 +3810,8 @@ var ii = {
3658
3810
  examples: [],
3659
3811
  tests: 18,
3660
3812
  baseline: "velastack",
3661
- generate: ri
3662
- }, ai = /* @__PURE__ */ Object.assign({
3813
+ generate: mi
3814
+ }, gi = /* @__PURE__ */ Object.assign({
3663
3815
  "./creates/src/lib/components/app-sidebar.svelte": "<script lang=\"ts\">\n import type { ComponentProps } from 'svelte';\n import HomeIcon from '@lucide/svelte/icons/home';\n import * as Sidebar from '$lib/components/ui/sidebar';\n import NavMain from './nav-main.svelte';\n import NavUser from './nav-user.svelte';\n\n let data = {\n navMain: [\n {\n title: 'Dashboard',\n url: '/dashboard',\n icon: HomeIcon\n }\n ]\n };\n\n let {\n user,\n meta,\n ref = $bindable(null),\n ...restProps\n }: ComponentProps<typeof Sidebar.Root> & { user: any; meta: any } = $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} />\n </Sidebar.Footer>\n</Sidebar.Root>\n",
3664
3816
  "./creates/src/lib/components/nav-main.svelte": "<script lang=\"ts\">\n import type { Component } from 'svelte';\n import * as Sidebar from '$lib/components/ui/sidebar';\n import { page } from '$app/state';\n\n const isActive = (url: string) => {\n return page.url.pathname.startsWith(url);\n };\n\n let {\n items\n }: {\n items: {\n title: string;\n url: string;\n icon: Component;\n items?: {\n title: string;\n url: string;\n }[];\n }[];\n } = $props();\n<\/script>\n\n<Sidebar.Group>\n <Sidebar.Menu>\n {#each items as item (item.title)}\n <Sidebar.MenuItem>\n <Sidebar.MenuButton isActive={isActive(item.url)}>\n {#snippet child({ props })}\n <a href={item.url} {...props}>\n <item.icon />\n <span>{item.title}</span>\n </a>\n {/snippet}\n </Sidebar.MenuButton>\n </Sidebar.MenuItem>\n {/each}\n </Sidebar.Menu>\n</Sidebar.Group>\n",
3665
3817
  "./creates/src/lib/components/nav-user.svelte": "<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 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 };\n\n let {\n user\n }: {\n user: {\n id: string;\n name: string;\n email: string;\n avatar: string;\n };\n } = $props();\n\n const sidebar = Sidebar.useSidebar();\n<\/script>\n\n<Sidebar.Menu>\n <Sidebar.MenuItem>\n <DropdownMenu.Root>\n <DropdownMenu.Trigger>\n {#snippet child({ props })}\n <Sidebar.MenuButton\n size=\"lg\"\n class=\"data-[state=open]:bg-sidebar-accent data-[state=open]:text-sidebar-accent-foreground\"\n {...props}\n >\n <Avatar.Root class=\"size-8 rounded-lg\">\n {#if user.avatar}\n <Avatar.Image src=\"/api/files/users/{user.id}/{user.avatar}\" alt={user.name} />\n {/if}\n <Avatar.Fallback class=\"rounded-lg\">\n {user.email?.charAt(0).toUpperCase()}\n </Avatar.Fallback>\n </Avatar.Root>\n <div class=\"grid flex-1 text-left text-sm leading-tight\">\n <span class=\"truncate font-medium\">{user.name}</span>\n <span class=\"truncate text-xs\">{user.email}</span>\n </div>\n <ChevronsUpDownIcon class=\"ml-auto size-4\" />\n </Sidebar.MenuButton>\n {/snippet}\n </DropdownMenu.Trigger>\n <DropdownMenu.Content\n class=\"w-(--bits-dropdown-menu-anchor-width) min-w-56 rounded-lg\"\n side={sidebar.isMobile ? 'bottom' : 'right'}\n align=\"end\"\n sideOffset={4}\n >\n <DropdownMenu.Label class=\"p-0 font-normal\">\n <div class=\"flex items-center gap-2 px-1 py-1.5 text-left text-sm\">\n <Avatar.Root class=\"size-8 rounded-lg\">\n {#if user.avatar}\n <Avatar.Image src=\"/api/files/users/{user.id}/{user.avatar}\" alt={user.name} />\n {/if}\n <Avatar.Fallback class=\"rounded-lg\">\n {user.email?.charAt(0).toUpperCase()}\n </Avatar.Fallback>\n </Avatar.Root>\n <div class=\"grid flex-1 text-left text-sm leading-tight\">\n <span class=\"truncate font-medium\">{user.name}</span>\n <span class=\"truncate text-xs\">{user.email}</span>\n </div>\n </div>\n </DropdownMenu.Label>\n <DropdownMenu.Separator />\n <DropdownMenu.Group>\n <DropdownMenu.Item onclick={toggleMode}>\n {#if mode.current === 'dark'}\n <SunIcon />\n Light mode\n {:else}\n <MoonIcon />\n Dark mode\n {/if}\n </DropdownMenu.Item>\n {#each data.navUser as item}\n <DropdownMenu.Item class=\"p-0\">\n <a href={item.url} class=\"flex cursor-default items-center gap-2 px-2 py-1.5 w-full\">\n <item.icon />\n {item.title}\n </a>\n </DropdownMenu.Item>\n {/each}\n </DropdownMenu.Group>\n <DropdownMenu.Separator />\n <DropdownMenu.Item class=\"p-0\">\n <form action=\"/logout\" method=\"post\" class=\"w-full\">\n <button type=\"submit\" class=\"flex cursor-default items-center gap-2 px-2 py-1.5 w-full\">\n <LogOutIcon />\n Log out\n </button>\n </form>\n </DropdownMenu.Item>\n </DropdownMenu.Content>\n </DropdownMenu.Root>\n </Sidebar.MenuItem>\n</Sidebar.Menu>\n",
@@ -3708,17 +3860,17 @@ var ii = {
3708
3860
  "./creates/src/routes/(public)/signup/+page.svelte": "<script lang=\"ts\">\n import { Button } from \"$lib/components/ui/button\";\n import * as Card from \"$lib/components/ui/card\";\n import { Input } from \"$lib/components/ui/input\";\n import PocketBase from \"pocketbase-sveltekit\";\n import { goto } from \"$app/navigation\";\n import { page } from \"$app/state\";\n import { signupForm } from \"./form.remote\";\n\n let { data } = $props();\n let authMethods = $derived(data.authMethods);\n\n const redirect = page.url.searchParams.get(\"redirect\");\n const hasOAuth2 = $derived(\n authMethods.oauth2.enabled && authMethods.oauth2.providers.length > 0,\n );\n const hasAuthMethods = $derived(\n authMethods.password.enabled || authMethods.otp.enabled || hasOAuth2,\n );\n\n const handleOAuth2 = (provider: string) => {\n const pb = new PocketBase(\"/\");\n\n pb.collection(\"users\")\n .authWithOAuth2({ provider, createData: {} })\n .then(() => goto(\"/dashboard\"));\n };\n<\/script>\n\n<div class=\"h-full flex flex-col items-center justify-center gap-6 p-6 md:p-10\">\n <div class=\"flex w-full max-w-sm flex-col gap-6\">\n <a href=\"/\" class=\"flex items-center gap-2 self-center font-medium\">\n <div\n class=\"bg-primary text-primary-foreground flex size-6 items-center justify-center rounded-md\"\n >\n <img src=\"/favicon.svg\" alt=\"logo\" class=\"size-4\" />\n </div>\n {data.meta.appName}\n </a>\n\n <div class=\"flex flex-col gap-6\">\n <Card.Root>\n {#if hasAuthMethods}\n <Card.Header class=\"text-center\">\n <Card.Title class=\"text-xl\">Create an account</Card.Title>\n {#if hasOAuth2}\n <Card.Description>Choose a sign up method</Card.Description>\n {:else}\n <Card.Description>Use your email to sign up</Card.Description>\n {/if}\n </Card.Header>\n {:else}\n <Card.Header class=\"text-center\">\n <Card.Title class=\"text-xl\">Signups are disabled</Card.Title>\n <Card.Description\n >Check back later for signup options</Card.Description\n >\n </Card.Header>\n {/if}\n <Card.Content>\n <form {...signupForm}>\n <div class=\"grid gap-6\">\n {#if hasOAuth2}\n <div class=\"flex flex-col gap-4\">\n {#each authMethods.oauth2.providers as provider}\n <Button\n variant=\"outline\"\n class=\"w-full\"\n onclick={() => handleOAuth2(provider.name)}\n >\n <img\n src=\"/admin/_/images/oauth2/{provider.name}.svg\"\n class=\"size-5 bg-white p-0.5 rounded-sm\"\n alt=\"\"\n />\n Login with {provider.displayName}\n </Button>\n {/each}\n </div>\n {/if}\n\n {#if authMethods.password.enabled}\n {#if hasOAuth2}\n <div\n class=\"after:border-border relative text-center text-sm after:absolute after:inset-0 after:top-1/2 after:z-0 after:flex after:items-center after:border-t\"\n >\n <span\n class=\"bg-card text-muted-foreground relative z-10 px-2\"\n >\n Or continue with\n </span>\n </div>\n {/if}\n\n <div class=\"grid gap-2\">\n <div class=\"space-y-2 col-span-1\">\n <label for=\"email\" class=\"text-sm font-medium\">Email</label>\n <Input\n id=\"email\"\n {...signupForm.fields.email.as(\"text\")}\n type=\"email\"\n required\n />\n {#each signupForm.fields.email.issues() as issue}\n <p class=\"text-destructive text-sm\">{issue.message}</p>\n {/each}\n </div>\n\n <div class=\"space-y-2 col-span-1\">\n <label for=\"password\" class=\"text-sm font-medium\"\n >Password</label\n >\n <Input\n id=\"password\"\n {...signupForm.fields.password.as(\"text\")}\n type=\"password\"\n required\n autocomplete=\"new-password\"\n />\n {#each signupForm.fields.password.issues() as issue}\n <p class=\"text-destructive text-sm\">{issue.message}</p>\n {/each}\n </div>\n\n <div class=\"space-y-2 col-span-1\">\n <label for=\"passwordConfirm\" class=\"text-sm font-medium\"\n >Confirm Password</label\n >\n <Input\n id=\"passwordConfirm\"\n {...signupForm.fields.passwordConfirm.as(\"text\")}\n type=\"password\"\n required\n autocomplete=\"new-password\"\n />\n {#each signupForm.fields.passwordConfirm.issues() as issue}\n <p class=\"text-destructive text-sm\">{issue.message}</p>\n {/each}\n </div>\n\n {#if signupForm.result?.message}\n <div class=\"text-destructive text-sm font-medium -mt-2\">\n {signupForm.result.message}\n </div>\n {/if}\n\n <Button type=\"submit\" class=\"w-full\">Create account</Button>\n </div>\n {/if}\n\n <div class=\"text-center text-sm\">\n Already have an account?\n <a\n href=\"/login{redirect\n ? `?redirect=${encodeURIComponent(redirect)}`\n : ''}\"\n class=\"underline underline-offset-4\"\n >\n Log in\n </a>\n </div>\n </div>\n </form>\n </Card.Content>\n </Card.Root>\n <div\n class=\"text-muted-foreground *:[a]:hover:text-primary *:[a]:underline *:[a]:underline-offset-4 text-balance text-center text-xs\"\n >\n By clicking continue, you agree to our <a href=\"/terms\"\n >Terms of Service</a\n >\n and <a href=\"/privacy\">Privacy Policy</a>.\n </div>\n </div>\n </div>\n</div>\n",
3709
3861
  "./creates/src/routes/(public)/signup/form.remote.ts": "import { form, getRequestEvent } from \"$app/server\";\nimport { error, redirect } from \"@sveltejs/kit\";\nimport { setFlash } from \"sveltekit-flash-message/server\";\nimport { dev } from \"$app/environment\";\nimport { signupSchema } from \"$lib/schemas/signup\";\n\nexport const signupForm = form(signupSchema, async (data) => {\n const { locals, cookies, url } = getRequestEvent();\n\n let user;\n\n try {\n user = await locals.admin.collection(\"users\").create({\n email: data.email,\n password: data.password,\n passwordConfirm: data.passwordConfirm,\n });\n } catch (err: any) {\n const response = err?.response ?? {};\n const fieldError = response?.data\n ? Object.values(response.data)[0]\n : undefined;\n const message =\n (fieldError as any)?.message ??\n response?.message ??\n \"Failed to create account.\";\n error(400, message);\n }\n\n await locals.pb.collection(\"users\").requestVerification(user.email);\n await locals.pb\n .collection(\"users\")\n .authWithPassword(data.email, data.password);\n\n const redirectUrl = url.searchParams.get(\"redirect\") ?? \"/dashboard\";\n const cookie = locals.pb.authStore.getCookie();\n cookies.set(\"pb_auth\", cookie, {\n path: \"/\",\n httpOnly: true,\n sameSite: \"lax\",\n secure: !dev,\n maxAge: 60 * 60 * 24 * 30,\n });\n\n setFlash(\n { type: \"toast\", message: \"We sent a confirmation link to your email.\" },\n cookies,\n );\n redirect(303, redirectUrl);\n});\n",
3710
3862
  "./creates/src/routes/(public)/signup/server.test.ts": "import { describe, it, expect } from \"vitest\";\nimport type { Match } from \"@velastack/pocketbase\";\nimport type { RouteId } from \"./$types\";\n\ndescribe(\"GET /signup\", () => {\n it(\"should render the signup page\", async (context) => {\n const response = await context.request.get(\n \"/signup\" satisfies Match<RouteId>,\n );\n expect(response.status).toBe(200);\n });\n});\n"
3711
- }), oi = "./creates/";
3712
- async function si(e) {
3713
- let n = Object.entries(ai).map(([e, n]) => {
3714
- let i = r(e, oi);
3863
+ }), _i = "./creates/";
3864
+ async function vi(e) {
3865
+ let t = Object.entries(gi).map(([e, t]) => {
3866
+ let r = i(e, _i);
3715
3867
  return {
3716
- path: i,
3717
- language: t(i),
3718
- content: n,
3868
+ path: r,
3869
+ language: n(r),
3870
+ content: t,
3719
3871
  status: "success"
3720
3872
  };
3721
- }).sort((e, t) => e.path.localeCompare(t.path)), i = [
3873
+ }).sort((e, t) => e.path.localeCompare(t.path)), r = [
3722
3874
  "sidebar",
3723
3875
  "breadcrumb",
3724
3876
  "separator",
@@ -3734,11 +3886,11 @@ async function si(e) {
3734
3886
  "checkbox",
3735
3887
  "auth-menu"
3736
3888
  ];
3737
- return e.features.payments && i.push("alert-dialog"), {
3738
- creates: n,
3889
+ return e.features.payments && r.push("alert-dialog"), {
3890
+ creates: t,
3739
3891
  modifies: [],
3740
3892
  deletes: [],
3741
- components: i,
3893
+ components: r,
3742
3894
  packages: [],
3743
3895
  collections: [{
3744
3896
  listRule: "@request.auth.id = user.id",
@@ -3796,49 +3948,51 @@ async function si(e) {
3796
3948
  type: "json"
3797
3949
  }
3798
3950
  ]
3799
- }]
3951
+ }],
3952
+ collectionPatches: []
3800
3953
  };
3801
3954
  }
3802
3955
  //#endregion
3803
3956
  //#region src/patterns/enable/auth-remote/generate.preview.ts
3804
- var ci = /* @__PURE__ */ Object.assign({
3957
+ var yi = /* @__PURE__ */ Object.assign({
3805
3958
  "./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",
3806
3959
  "./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",
3807
3960
  "./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",
3808
3961
  "./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"
3809
- }), li = "./preview-modifies/";
3810
- async function ui(e) {
3962
+ }), bi = "./preview-modifies/";
3963
+ async function xi(e) {
3811
3964
  return {
3812
3965
  creates: [],
3813
- modifies: Object.entries(ci).map(([e, n]) => {
3814
- let i = r(e, li);
3966
+ modifies: Object.entries(yi).map(([e, t]) => {
3967
+ let r = i(e, bi);
3815
3968
  return {
3816
- path: i,
3817
- language: t(i),
3818
- content: n,
3969
+ path: r,
3970
+ language: n(r),
3971
+ content: t,
3819
3972
  status: "success"
3820
3973
  };
3821
3974
  }).sort((e, t) => e.path.localeCompare(t.path)),
3822
3975
  deletes: [],
3823
3976
  components: [],
3824
3977
  packages: [],
3825
- collections: []
3978
+ collections: [],
3979
+ collectionPatches: []
3826
3980
  };
3827
3981
  }
3828
3982
  //#endregion
3829
3983
  //#region src/patterns/enable/auth-remote/index.ts
3830
- var di = "enable-auth-remote", fi = "1.0.0", pi = "src/patterns/enable/auth-remote", mi = "/enable/auth-remote";
3831
- async function hi(e) {
3832
- let t = await si(e);
3833
- if (e.env === "preview") return v(n([t, await ui(e)]));
3834
- let { generate: r } = await import("./chunks/generate.runtime-BUbI1GmK.js"), i = await r(e), { writeResult: a } = await import("./chunks/write-result-ENWLDQtP.js");
3835
- return a(await v(n([t, i])), e);
3836
- }
3837
- var gi = {
3838
- version: fi,
3839
- slug: di,
3840
- source: pi,
3841
- docs: mi,
3984
+ var Si = "enable-auth-remote", Ci = "1.0.0", wi = "src/patterns/enable/auth-remote", Ti = "/enable/auth-remote";
3985
+ async function Ei(e) {
3986
+ let t = await vi(e);
3987
+ if (e.env === "preview") return _(r([t, await xi(e)]));
3988
+ let { generate: n } = await import("./chunks/generate.runtime-DpeB3h-P.js"), i = await n(e), { writeResult: a } = await import("./chunks/write-result-C80dpjr-.js");
3989
+ return a(await _(r([t, i])), e);
3990
+ }
3991
+ var Di = {
3992
+ version: Ci,
3993
+ slug: Si,
3994
+ source: wi,
3995
+ docs: Ti,
3842
3996
  plan: "open",
3843
3997
  title: "Enable authentication (remote functions)",
3844
3998
  summary: "Enables authentication using SvelteKit remote functions for login, signup, reset, and settings forms.",
@@ -3868,16 +4022,16 @@ var gi = {
3868
4022
  examples: [],
3869
4023
  tests: 18,
3870
4024
  baseline: "velastack",
3871
- generate: hi
3872
- }, _i = /* @__PURE__ */ Object.assign({ "./creates/src/routes/api/server.test.ts": "import { describe, expect, it } from \"vitest\";\n\ndescribe(\"GET /api/health\", () => {\n it(\"should return a 200 status code\", async (context) => {\n const response = await context.request.get(\"/api/health\");\n expect(response.status).toBe(200);\n });\n});\n" }), vi = "./creates/";
3873
- async function yi(e) {
4025
+ generate: Ei
4026
+ }, Oi = /* @__PURE__ */ Object.assign({ "./creates/src/routes/api/server.test.ts": "import { describe, expect, it } from \"vitest\";\n\ndescribe(\"GET /api/health\", () => {\n it(\"should return a 200 status code\", async (context) => {\n const response = await context.request.get(\"/api/health\");\n expect(response.status).toBe(200);\n });\n});\n" }), ki = "./creates/";
4027
+ async function Ai(e) {
3874
4028
  return {
3875
- creates: Object.entries(_i).map(([e, n]) => {
3876
- let i = r(e, vi);
4029
+ creates: Object.entries(Oi).map(([e, t]) => {
4030
+ let r = i(e, ki);
3877
4031
  return {
3878
- path: i,
3879
- language: t(i),
3880
- content: n,
4032
+ path: r,
4033
+ language: n(r),
4034
+ content: t,
3881
4035
  status: "success"
3882
4036
  };
3883
4037
  }).sort((e, t) => e.path.localeCompare(t.path)),
@@ -3885,44 +4039,46 @@ async function yi(e) {
3885
4039
  deletes: [],
3886
4040
  components: [],
3887
4041
  packages: [],
3888
- collections: []
4042
+ collections: [],
4043
+ collectionPatches: []
3889
4044
  };
3890
4045
  }
3891
4046
  //#endregion
3892
4047
  //#region src/patterns/enable/api/generate.preview.ts
3893
- var bi = /* @__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" }), xi = "./preview-modifies/";
3894
- async function Si(e) {
4048
+ var ji = /* @__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" }), Mi = "./preview-modifies/";
4049
+ async function Ni(e) {
3895
4050
  return {
3896
4051
  creates: [],
3897
- modifies: Object.entries(bi).map(([e, n]) => {
3898
- let i = r(e, xi);
4052
+ modifies: Object.entries(ji).map(([e, t]) => {
4053
+ let r = i(e, Mi);
3899
4054
  return {
3900
- path: i,
3901
- language: t(i),
3902
- content: n,
4055
+ path: r,
4056
+ language: n(r),
4057
+ content: t,
3903
4058
  status: "success"
3904
4059
  };
3905
4060
  }).sort((e, t) => e.path.localeCompare(t.path)),
3906
4061
  deletes: [],
3907
4062
  components: [],
3908
4063
  packages: [],
3909
- collections: []
4064
+ collections: [],
4065
+ collectionPatches: []
3910
4066
  };
3911
4067
  }
3912
4068
  //#endregion
3913
4069
  //#region src/patterns/enable/api/index.ts
3914
- var Ci = "enable-api", wi = "1.0.7", Ti = "src/patterns/enable/api", Ei = "/enable/api";
3915
- async function Di(e) {
3916
- let t = await yi(e);
3917
- if (e.env === "preview") return v(n([t, await Si(e)]));
3918
- let { generate: r } = await import("./chunks/generate.runtime-DpT7Jzh4.js"), i = await r(e), { writeResult: a } = await import("./chunks/write-result-ENWLDQtP.js");
3919
- return a(await v(n([t, i])), e);
3920
- }
3921
- var Oi = {
3922
- version: wi,
3923
- slug: Ci,
3924
- source: Ti,
3925
- docs: Ei,
4070
+ var Pi = "enable-api", Fi = "1.0.7", Ii = "src/patterns/enable/api", Li = "/enable/api";
4071
+ async function Ri(e) {
4072
+ let t = await Ai(e);
4073
+ if (e.env === "preview") return _(r([t, await Ni(e)]));
4074
+ let { generate: n } = await import("./chunks/generate.runtime-CbiQhqdL.js"), i = await n(e), { writeResult: a } = await import("./chunks/write-result-C80dpjr-.js");
4075
+ return a(await _(r([t, i])), e);
4076
+ }
4077
+ var zi = {
4078
+ version: Fi,
4079
+ slug: Pi,
4080
+ source: Ii,
4081
+ docs: Li,
3926
4082
  plan: "open",
3927
4083
  title: "Enable API",
3928
4084
  summary: "Enables the PocketBase API.",
@@ -3951,8 +4107,8 @@ var Oi = {
3951
4107
  examples: [],
3952
4108
  tests: 1,
3953
4109
  baseline: "velastack",
3954
- generate: Di
3955
- }, ki = /* @__PURE__ */ Object.assign({
4110
+ generate: Ri
4111
+ }, Bi = /* @__PURE__ */ Object.assign({
3956
4112
  "./creates/src/lib/schemas/apiKey.ts": "import { z } from \"zod\";\nimport type { Schemas } from \"@velastack/pocketbase\";\n\nexport const apiKeySchema = z.object({\n label: z.string().optional(),\n}) satisfies Schemas[\"api_keys\"];\n",
3957
4113
  "./creates/src/routes/(app)/api-keys/+page.server.ts": "export const load = async ({ locals }) => {\n const apiKeys = await locals.pb.collection(\"api_keys\").getFullList();\n return { apiKeys };\n};\n",
3958
4114
  "./creates/src/routes/(app)/api-keys/+page.svelte": "<script lang=\"ts\">\n import { getFlash } from 'sveltekit-flash-message';\n import { page } from '$app/state';\n import * as AlertDialog from '$lib/components/ui/alert-dialog';\n import { Button } from '$lib/components/ui/button';\n import { Badge } from '$lib/components/ui/badge';\n import PlusIcon from '@lucide/svelte/icons/plus';\n import SquareDashedMousePointerIcon from '@lucide/svelte/icons/square-dashed-mouse-pointer';\n\n const flash = getFlash(page);\n\n let open = $state(false);\n let message = $state('');\n let title = $state('');\n let apiKey = $state('');\n\n $effect(() => {\n if (!$flash) return;\n\n if ($flash.type === 'success') {\n message = $flash.message;\n title = $flash.title;\n apiKey = $flash.apiKey;\n open = true;\n }\n\n $flash = undefined;\n });\n\n async function handleAction() {\n open = false;\n await navigator.clipboard.writeText(apiKey);\n }\n\n let { data } = $props();\n<\/script>\n\n<section data-role=\"content\">\n <div class=\"flex justify-between items-center mb-4\">\n <h1 class=\"text-3xl font-bold tracking-tight\">API keys</h1>\n <Button href=\"/api-keys/new\" variant=\"outline\">\n <PlusIcon class=\"w-4 h-4\" />\n New API key\n </Button>\n </div>\n\n <AlertDialog.Root bind:open>\n <AlertDialog.Content>\n <AlertDialog.Header>\n <AlertDialog.Title>{title}</AlertDialog.Title>\n <AlertDialog.Description>\n <p>{@html message}</p>\n <Badge variant=\"outline\" class=\"font-mono my-3 text-base\">{apiKey}</Badge>\n </AlertDialog.Description>\n </AlertDialog.Header>\n <AlertDialog.Footer>\n <AlertDialog.Cancel>Close</AlertDialog.Cancel>\n <AlertDialog.Action onclick={handleAction}>Copy</AlertDialog.Action>\n </AlertDialog.Footer>\n </AlertDialog.Content>\n </AlertDialog.Root>\n\n <div class=\"rounded-lg border bg-card overflow-hidden\">\n <div class=\"relative w-full overflow-auto\">\n {#if data.apiKeys.length === 0}\n <div class=\"p-4 text-center text-muted-foreground space-y-4 py-12\">\n <SquareDashedMousePointerIcon strokeWidth={1.2} class=\"w-8 h-8 mx-auto mb-2\" />\n <p>Seems like there are no API keys yet, but you can create the first one</p>\n <p class=\"text-sm text-muted-foreground\">\n <Button href=\"/api-keys/new\" variant=\"outline\">\n <PlusIcon class=\"w-4 h-4\" />\n New API key\n </Button>\n </p>\n </div>\n {:else}\n <table class=\"w-full caption-bottom text-sm\">\n <thead>\n <tr class=\"border-b\">\n <th class=\"h-12 px-4 text-left align-middle font-medium text-muted-foreground\"\n >Label</th\n >\n <th class=\"h-12 px-4 text-left align-middle font-medium text-muted-foreground\"\n >API key</th\n >\n <th class=\"h-12 px-4 text-left align-middle font-medium text-muted-foreground\"\n >Created</th\n >\n <th class=\"h-12 px-4 text-left align-middle font-medium text-muted-foreground\"\n >Last used</th\n >\n <th class=\"h-12 px-4 text-right align-middle font-medium text-muted-foreground\"></th>\n </tr>\n </thead>\n <tbody>\n {#each data.apiKeys as apiKey}\n <tr\n class=\"border-t transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted\"\n >\n <td class=\"p-4 align-middle font-medium\">{apiKey.label}</td>\n\n <td class=\"p-4 align-middle font-medium\">\n <Badge variant=\"outline\" class=\"font-mono\">\n {apiKey.id}.***************\n </Badge>\n </td>\n\n <td class=\"p-4 align-middle font-medium\">\n {#if apiKey.created}\n {new Date(apiKey.created).toLocaleDateString()}\n {/if}\n </td>\n\n <td class=\"p-4 align-middle font-medium\">\n {#if apiKey.last_used}\n {new Date(apiKey.last_used).toLocaleDateString()}\n {:else}\n Never\n {/if}\n </td>\n\n <td class=\"p-4 align-middle text-right\">\n <form method=\"POST\" action=\"/api-keys/{apiKey.id}?/delete\" class=\"contents\">\n <Button\n variant=\"ghost\"\n class=\"h-8 px-2 text-destructive hover:text-destructive\"\n type=\"submit\">Delete</Button\n >\n </form>\n </td>\n </tr>\n {/each}\n </tbody>\n </table>\n {/if}\n </div>\n </div>\n</section>\n",
@@ -3962,15 +4118,15 @@ var Oi = {
3962
4118
  "./creates/src/routes/(app)/api-keys/new/create-api-key.ts": "import PocketBase from \"pocketbase-sveltekit\";\nimport argon2 from \"argon2\";\nimport { randomBytes } from \"node:crypto\";\n\nexport const createApiKey = async (\n pb: PocketBase,\n userId: string | undefined,\n label: string,\n) => {\n const keySecret = randomBytes(10).toString(\"hex\");\n const keyHash = await argon2.hash(keySecret, { type: argon2.argon2id });\n const apiKey = await pb\n .collection(\"api_keys\")\n .create({ key_hash: keyHash, user: userId, label });\n\n return `${apiKey.id}.${keySecret}`;\n};\n",
3963
4119
  "./creates/src/routes/(app)/api-keys/new/server.test.ts": "import { describe, it, expect, beforeEach } from \"vitest\";\nimport type { Match } from \"@velastack/pocketbase\";\nimport { createApiKey } from \"./create-api-key\";\nimport type { RouteId } from \"./$types\";\n\ndescribe(\"GET /api-keys/new\", () => {\n beforeEach(async (context) => {\n await context.agent.authenticateUser();\n });\n\n it(\"should return a 200 status code\", async (context) => {\n const response = await context.agent.get(\n \"/api-keys/new\" satisfies Match<RouteId>,\n );\n expect(response.status).toBe(200);\n });\n});\n\ndescribe(\"POST /api-keys/new\", () => {\n beforeEach(async (context) => {\n await context.agent.authenticateUser();\n });\n\n it(\"should create a new API key\", async (context) => {\n const response = await context.agent\n .post(\"/api-keys/new\")\n .type(\"form\")\n .send({ label: \"Test API Key\" });\n expect(response.body.status).toBe(303);\n expect(response.body.location).toBe(\"/api-keys\");\n });\n});\n\ndescribe(\"api keys authenticate as a user\", () => {\n it(\"should create a new api key\", async (context) => {\n const apiKey = await createApiKey(\n context.pb,\n context.user.id,\n \"Test API Key\",\n );\n expect(apiKey).toBeDefined();\n });\n\n it(\"should throw an error when creating for a non-existent user\", async (context) => {\n await expect(async () => {\n await createApiKey(context.pb, \"non-existent-user-id\", \"Test API Key\");\n }).rejects.toThrow();\n });\n\n it(\"should give access to the api\", async (context) => {\n const response = await context.request.get(\n `/api/collections/users/records/${context.user.id}`,\n );\n expect(response.status).toBe(404);\n\n const apiKey = await createApiKey(\n context.pb,\n context.user.id,\n \"Test API Key\",\n );\n const response2 = await context.request\n .get(`/api/collections/users/records/${context.user.id}`)\n .set(\"Authorization\", `Bearer ${apiKey}`);\n expect(response2.status).toBe(200);\n });\n});\n",
3964
4120
  "./creates/src/routes/(app)/api-keys/server.test.ts": "import { describe, it, expect, beforeEach } from \"vitest\";\nimport type { Match } from \"@velastack/pocketbase\";\nimport type { RouteId } from \"./$types\";\n\ndescribe(\"GET /api-keys\", () => {\n beforeEach(async (context) => {\n await context.agent.authenticateUser();\n });\n\n it(\"should return a 200 status code\", async (context) => {\n const response = await context.agent.get(\n \"/api-keys\" satisfies Match<RouteId>,\n );\n expect(response.status).toBe(200);\n });\n});\n"
3965
- }), Ai = "./creates/";
3966
- async function ji(e) {
4121
+ }), Vi = "./creates/";
4122
+ async function Hi(e) {
3967
4123
  return {
3968
- creates: Object.entries(ki).map(([e, n]) => {
3969
- let i = r(e, Ai);
4124
+ creates: Object.entries(Bi).map(([e, t]) => {
4125
+ let r = i(e, Vi);
3970
4126
  return {
3971
- path: i,
3972
- language: t(i),
3973
- content: n,
4127
+ path: r,
4128
+ language: n(r),
4129
+ content: t,
3974
4130
  status: "success"
3975
4131
  };
3976
4132
  }).sort((e, t) => e.path.localeCompare(t.path)),
@@ -3982,44 +4138,46 @@ async function ji(e) {
3982
4138
  "badge"
3983
4139
  ],
3984
4140
  packages: ["argon2", "@types/node"],
3985
- collections: []
4141
+ collections: [],
4142
+ collectionPatches: []
3986
4143
  };
3987
4144
  }
3988
4145
  //#endregion
3989
4146
  //#region src/patterns/enable/api-keys/generate.preview.ts
3990
- var Mi = /* @__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 api: {\n enabled: true,\n // [!code highlight:1]\n apiKeys: { enabled: true },\n },\n});\n" }), Ni = "./preview-modifies/";
3991
- async function Pi(e) {
4147
+ var Ui = /* @__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 api: {\n enabled: true,\n // [!code highlight:1]\n apiKeys: { enabled: true },\n },\n});\n" }), Wi = "./preview-modifies/";
4148
+ async function Gi(e) {
3992
4149
  return {
3993
4150
  creates: [],
3994
- modifies: Object.entries(Mi).map(([e, n]) => {
3995
- let i = r(e, Ni);
4151
+ modifies: Object.entries(Ui).map(([e, t]) => {
4152
+ let r = i(e, Wi);
3996
4153
  return {
3997
- path: i,
3998
- language: t(i),
3999
- content: n,
4154
+ path: r,
4155
+ language: n(r),
4156
+ content: t,
4000
4157
  status: "success"
4001
4158
  };
4002
4159
  }).sort((e, t) => e.path.localeCompare(t.path)),
4003
4160
  deletes: [],
4004
4161
  components: [],
4005
4162
  packages: [],
4006
- collections: []
4163
+ collections: [],
4164
+ collectionPatches: []
4007
4165
  };
4008
4166
  }
4009
4167
  //#endregion
4010
4168
  //#region src/patterns/enable/api-keys/index.ts
4011
- var Fi = "enable-api-keys", Ii = "1.0.0", Li = "src/patterns/enable/api-keys", Ri = "/enable/api-keys";
4012
- async function zi(e) {
4013
- let t = await ji(e);
4014
- if (e.env === "preview") return v(n([t, await Pi(e)]));
4015
- let { generate: r } = await import("./chunks/generate.runtime-BayXS2PL.js"), i = await r(e), { writeResult: a } = await import("./chunks/write-result-ENWLDQtP.js");
4016
- return a(await v(n([t, i])), e);
4017
- }
4018
- var Bi = {
4019
- version: Ii,
4020
- slug: Fi,
4021
- source: Li,
4022
- docs: Ri,
4169
+ var Ki = "enable-api-keys", qi = "1.0.0", Ji = "src/patterns/enable/api-keys", Yi = "/enable/api-keys";
4170
+ async function Xi(e) {
4171
+ let t = await Hi(e);
4172
+ if (e.env === "preview") return _(r([t, await Gi(e)]));
4173
+ let { generate: n } = await import("./chunks/generate.runtime-BkjQiaP_.js"), i = await n(e), { writeResult: a } = await import("./chunks/write-result-C80dpjr-.js");
4174
+ return a(await _(r([t, i])), e);
4175
+ }
4176
+ var Zi = {
4177
+ version: qi,
4178
+ slug: Ki,
4179
+ source: Ji,
4180
+ docs: Yi,
4023
4181
  plan: "open",
4024
4182
  title: "Enable API keys",
4025
4183
  summary: "Adds API key management for authenticated users and PocketBase API access.",
@@ -4048,21 +4206,21 @@ var Bi = {
4048
4206
  examples: [],
4049
4207
  tests: 6,
4050
4208
  baseline: "velastack",
4051
- generate: zi
4052
- }, Vi = /* @__PURE__ */ Object.assign({
4209
+ generate: Xi
4210
+ }, Qi = /* @__PURE__ */ Object.assign({
4053
4211
  "./creates/src/hooks.ts": "import { deLocalizeDefault } from \"wuchale/url\";\nimport { matchUrl } from \"$locales/main.url\";\nimport { locales } from \"$locales/data\";\n\nexport const reroute = ({ url }) => {\n const [upath, locale] = deLocalizeDefault(url.pathname, locales);\n const { path } = matchUrl(upath, locale);\n return path ?? url.pathname;\n};\n",
4054
4212
  "./creates/src/lib/components/language-select.svelte": "<script lang=\"ts\">\n import * as Select from \"$lib/components/ui/select/index.js\";\n import { locales, type Locale } from \"$locales/data.js\";\n import { page } from \"$app/state\";\n import { goto } from \"$app/navigation\";\n import { deLocalizeDefault } from \"wuchale/url\";\n import { defaultLocale, translateUrl } from \"$lib/url\";\n\n let locale: Locale = $derived.by(() => {\n const [_, locale] = deLocalizeDefault(page.url.pathname, locales);\n return locale ?? defaultLocale;\n });\n\n function localeDisplayName(code: Locale): string {\n const names = new Intl.DisplayNames([code], { type: \"language\" });\n const raw = names.of(code);\n if (!raw) return code;\n return raw.charAt(0).toLocaleUpperCase(code) + raw.slice(1);\n }\n\n const localeNames: Record<string, string> = locales.reduce(\n (acc, loc) => {\n acc[loc] = localeDisplayName(loc);\n return acc;\n },\n {} as Record<string, string>,\n );\n\n const handleValueChange = (value: string) => {\n const translatedUrl = translateUrl(\n page.url.pathname,\n locale,\n value as Locale,\n );\n goto(translatedUrl, { invalidateAll: true });\n };\n\n let { class: className }: { class?: string } = $props();\n<\/script>\n\n<Select.Root type=\"single\" value={locale} onValueChange={handleValueChange}>\n <Select.Trigger class={className}>{localeNames[locale]}</Select.Trigger>\n <Select.Content>\n {#each locales as locale}\n <Select.Item value={locale}>{localeNames[locale]}</Select.Item>\n {/each}\n </Select.Content>\n</Select.Root>\n",
4055
4213
  "./creates/src/lib/url.ts": "import { deLocalizeDefault, fillParams } from \"wuchale/url\";\nimport type { Locale } from \"../locales/data\";\nimport { matchUrl } from \"../locales/main.url\";\nimport { locales } from \"../locales/data\";\n\nexport const defaultLocale = \"en\";\n\nexport function localize(path: string, locale: Locale) {\n if (locale === defaultLocale) {\n return path;\n }\n\n return `/${locale}${path}`;\n}\n\nexport function translateUrl(\n url: string,\n fromLocale: Locale,\n toLocale: Locale,\n) {\n const [pathOnly] = deLocalizeDefault(url, locales);\n const result = matchUrl(pathOnly, fromLocale);\n if (result.path !== null) {\n const targetPath = fillParams(result.params, result.altPatterns[toLocale]);\n return localize(targetPath, toLocale);\n }\n return localize(url, toLocale);\n}\n",
4056
4214
  "./creates/wuchale.config.js": "// @ts-check\nimport { adapter as svelte } from \"@wuchale/svelte\";\nimport { adapter as js } from \"wuchale/adapter-vanilla\";\nimport { defineConfig } from \"wuchale\";\n\nexport default defineConfig({\n locales: [\"en\", \"es\"],\n adapters: {\n main: svelte({\n loader: \"sveltekit\",\n url: { localize: true, patterns: [\"/\"] },\n }),\n js: js({\n loader: \"vite\",\n files: [\n \"src/**/+{page,layout}.{js,ts}\",\n \"src/**/+{page,layout}.server.{js,ts}\",\n ],\n }),\n },\n});\n"
4057
- }), Hi = "./creates/";
4058
- async function Ui(e) {
4215
+ }), $i = "./creates/";
4216
+ async function ea(e) {
4059
4217
  return {
4060
- creates: Object.entries(Vi).map(([e, n]) => {
4061
- let i = r(e, Hi);
4218
+ creates: Object.entries(Qi).map(([e, t]) => {
4219
+ let r = i(e, $i);
4062
4220
  return {
4063
- path: i,
4064
- language: t(i),
4065
- content: n,
4221
+ path: r,
4222
+ language: n(r),
4223
+ content: t,
4066
4224
  status: "success"
4067
4225
  };
4068
4226
  }).sort((e, t) => e.path.localeCompare(t.path)),
@@ -4070,51 +4228,53 @@ async function Ui(e) {
4070
4228
  deletes: [],
4071
4229
  components: ["select"],
4072
4230
  packages: ["wuchale", "@wuchale/svelte"],
4073
- collections: []
4231
+ collections: [],
4232
+ collectionPatches: []
4074
4233
  };
4075
4234
  }
4076
4235
  //#endregion
4077
4236
  //#region src/patterns/enable/i18n/generate.preview.ts
4078
- var Wi = /* @__PURE__ */ Object.assign({
4237
+ var ta = /* @__PURE__ */ Object.assign({
4079
4238
  "./preview-modifies/src/app.html": "<!doctype html>\n<!-- [!code highlight:1] -->\n<html lang=\"%sveltekit.lang%\">\n <head>\n <meta charset=\"utf-8\" />\n </head>\n\n <body>\n <div style=\"display: contents\">%sveltekit.body%</div>\n </body>\n</html>\n",
4080
4239
  "./preview-modifies/src/hooks.server.ts": "import { env } from \"$env/dynamic/private\";\nimport { handlePocketbase } from \"@velastack/pocketbase\";\n// [!code highlight:6]\nimport { sequence } from \"@sveltejs/kit/hooks\";\nimport { runWithLocale, loadLocales } from \"wuchale/load-utils/server\";\nimport { getLocale } from \"$locales/main.url\";\nimport { locales } from \"$locales/data\";\nimport * as main from \"$locales/main.loader.server.svelte.js\";\nimport * as js from \"$locales/js.loader.server.js\";\n\n// [!code highlight:2]\nloadLocales(main.key, main.loadIDs, main.loadCatalog, locales);\nloadLocales(js.key, js.loadIDs, js.loadCatalog, locales);\n\n// [!code highlight:9]\nconst handleWuchale = async ({ event, resolve }: any) => {\n const locale = getLocale(event.url);\n return await runWithLocale(locale, () =>\n resolve(event, {\n transformPageChunk: ({ html }: { html: string }) =>\n html.replace(\"%sveltekit.lang%\", locale),\n }),\n );\n};\n\nexport const handle = sequence(\n // [!code highlight:1]\n handleWuchale,\n handlePocketbase({\n pocketbaseUrl: env.POCKETBASE_URL,\n superuserEmail: env.POCKETBASE_SUPERUSER_EMAIL,\n superuserPassword: env.POCKETBASE_SUPERUSER_PASSWORD,\n }),\n);\n",
4081
- "./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]\n import LanguageSelect from '$lib/components/language-select.svelte';\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 class=\"w-full justify-start md:justify-center md:w-auto\" href=\"/\" variant=\"ghost\">\n Home\n </Button>\n </Navbar.Item>\n </Navbar.List>\n\n <!-- [!code highlight] -->\n <LanguageSelect />\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 <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",
4240
+ "./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]\n import LanguageSelect from '$lib/components/language-select.svelte';\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 class=\"w-full justify-start md:justify-center md:w-auto\" href=\"/\" variant=\"ghost\">\n Home\n </Button>\n </Navbar.Item>\n <!-- [!code highlight:3] -->\n <Navbar.Item>\n <LanguageSelect />\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 <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",
4082
4241
  "./preview-modifies/src/routes/+layout.ts": "import { browser } from \"$app/environment\";\n// [!code highlight:4]\nimport { loadLocale } from \"wuchale/load-utils\";\nimport { getLocale } from \"$locales/main.url\";\nimport \"$locales/main.loader.svelte\";\nimport \"$locales/js.loader\";\n\nexport const load = async ({ url, data }) => {\n // [!code highlight:5]\n const locale = getLocale(url);\n\n if (browser) {\n await loadLocale(locale);\n }\n\n return data;\n};\n",
4083
4242
  "./preview-modifies/svelte.config.js": "import adapter from \"@sveltejs/adapter-auto\";\nimport { vitePreprocess } from \"@sveltejs/vite-plugin-svelte\";\n\nconst config = {\n preprocess: vitePreprocess(),\n kit: {\n adapter,\n // [!code highlight:3]\n alias: {\n $locales: \"src/locales\",\n },\n },\n};\n\nexport default config;\n",
4084
4243
  "./preview-modifies/vite.config.ts": "import { defineConfig } from \"vite\";\nimport { sveltekit } from \"@sveltejs/kit/vite\";\nimport tailwindcss from \"@tailwindcss/vite\";\n// [!code highlight:1]\nimport { wuchale } from \"wuchale/vite\";\n\nexport default defineConfig({\n // [!code highlight:1]\n plugins: [wuchale(), tailwindcss(), sveltekit()],\n});\n"
4085
- }), Gi = "./preview-modifies/";
4086
- async function Ki(e) {
4244
+ }), na = "./preview-modifies/";
4245
+ async function ra(e) {
4087
4246
  return {
4088
4247
  creates: [],
4089
- modifies: Object.entries(Wi).map(([e, n]) => {
4090
- let i = r(e, Gi);
4248
+ modifies: Object.entries(ta).map(([e, t]) => {
4249
+ let r = i(e, na);
4091
4250
  return {
4092
- path: i,
4093
- language: t(i),
4094
- content: n,
4251
+ path: r,
4252
+ language: n(r),
4253
+ content: t,
4095
4254
  status: "success"
4096
4255
  };
4097
4256
  }).sort((e, t) => e.path.localeCompare(t.path)),
4098
4257
  deletes: [],
4099
4258
  components: [],
4100
4259
  packages: [],
4101
- collections: []
4260
+ collections: [],
4261
+ collectionPatches: []
4102
4262
  };
4103
4263
  }
4104
4264
  //#endregion
4105
4265
  //#region src/patterns/enable/i18n/index.ts
4106
- var qi = "enable-i18n", Ji = "1.0.0", Yi = "src/patterns/enable/i18n", Xi = "/enable/i18n";
4107
- async function Zi(e) {
4108
- let t = await Ui(e);
4109
- if (e.env === "preview") return v(n([t, await Ki(e)]));
4110
- let { generate: r } = await import("./chunks/generate.runtime-BpZPXyba.js"), i = await r(e), { writeResult: a } = await import("./chunks/write-result-ENWLDQtP.js");
4111
- return a(await v(n([t, i])), e);
4112
- }
4113
- var Qi = {
4114
- version: Ji,
4115
- slug: qi,
4116
- source: Yi,
4117
- docs: Xi,
4266
+ var ia = "enable-i18n", aa = "1.0.0", oa = "src/patterns/enable/i18n", sa = "/enable/i18n";
4267
+ async function ca(e) {
4268
+ let t = await ea(e);
4269
+ if (e.env === "preview") return _(r([t, await ra(e)]));
4270
+ let { generate: n } = await import("./chunks/generate.runtime-CXqD8em8.js"), i = await n(e), { writeResult: a } = await import("./chunks/write-result-C80dpjr-.js");
4271
+ return a(await _(r([t, i])), e);
4272
+ }
4273
+ var la = {
4274
+ version: aa,
4275
+ slug: ia,
4276
+ source: oa,
4277
+ docs: sa,
4118
4278
  plan: "open",
4119
4279
  title: "Enable i18n",
4120
4280
  summary: "Enables i18n with Wuchale and locale-aware routing.",
@@ -4142,63 +4302,63 @@ var Qi = {
4142
4302
  examples: [],
4143
4303
  tests: 0,
4144
4304
  baseline: "velastack",
4145
- generate: Zi
4146
- }, $i = "/// <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", ea = "/// <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", ta = "<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", na = "<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", ra = "<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", ia = "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", aa = "<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", oa = "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", sa = "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", ca = "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", la = "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", ua = "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", da = "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", fa = "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", pa = "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", ma = "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", ha = "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", ga = "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", _a = "/// <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", va = "/// <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", ya = "<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", ba = "<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", xa = "export const load = async ({ parent }) => {\n const { breadcrumbs } = await parent();\n\n return {\n breadcrumbs: [...breadcrumbs, { title: \"Billing\", url: \"/billing\" }],\n };\n};\n", Sa = "import { error } from \"@sveltejs/kit\";\nimport stripe from \"$lib/stripe\";\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 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 };\n};\n\nexport const actions = {\n setDefaultPaymentMethod: async ({ locals, request }) => {\n const formData = await request.formData();\n const paymentMethodId = formData.get(\"paymentMethodId\") as string;\n\n const customer = await locals.admin\n .collection(\"stripe_customers\")\n .getFirstListItem(`user.id = \"${locals.pb.authStore.record?.id}\"`);\n\n if (!customer || !customer.id) {\n return error(400, \"Customer not found\");\n }\n\n await stripe.customers.update(customer.id, {\n invoice_settings: {\n default_payment_method: paymentMethodId,\n },\n });\n\n await locals.admin.collection(\"stripe_customers\").update(customer.id, {\n default_payment_method: paymentMethodId,\n });\n },\n deletePaymentMethod: async ({ locals, request }) => {\n const formData = await request.formData();\n const paymentMethodId = formData.get(\"paymentMethodId\") as string;\n\n const customer = await locals.admin\n .collection(\"stripe_customers\")\n .getFirstListItem(`user.id = \"${locals.pb.authStore.record?.id}\"`);\n\n const defaultPaymentMethod = customer.default_payment_method;\n\n await stripe.paymentMethods.detach(paymentMethodId);\n\n // If default payment method was deleted, update default payment method\n if (defaultPaymentMethod === paymentMethodId) {\n const paymentMethods = await stripe.paymentMethods.list({\n customer: customer.id,\n });\n\n if (paymentMethods.data.length > 0) {\n const defaultPaymentMethod = paymentMethods.data[0];\n\n await stripe.customers.update(customer.id, {\n invoice_settings: {\n default_payment_method: defaultPaymentMethod.id,\n },\n });\n\n await locals.admin.collection(\"stripe_customers\").update(customer.id, {\n default_payment_method: defaultPaymentMethod.id,\n });\n } else {\n await locals.admin.collection(\"stripe_customers\").update(customer.id, {\n default_payment_method: null,\n });\n }\n }\n },\n};\n", Ca = "<script lang=\"ts\">\n import { Button } from '$lib/components/ui/button';\n import * as Card from '$lib/components/ui/card';\n import { Badge } from '$lib/components/ui/badge';\n import * as AlertDialog from '$lib/components/ui/alert-dialog';\n import SetupButton from '$lib/components/payments/setup-button.svelte';\n import { CreditCard, Trash2, Check } from '@lucide/svelte';\n import { toast } from 'svelte-sonner';\n import { invalidate } from '$app/navigation';\n\n let { data } = $props();\n let paymentMethods = $derived(data.paymentMethods);\n let showDeleteDialog = $state(false);\n let selectedPaymentMethodId = $state<string | null>(null);\n let isProcessing = $state(false);\n\n function openDeleteDialog(paymentMethodId: string) {\n selectedPaymentMethodId = paymentMethodId;\n showDeleteDialog = true;\n }\n\n function closeDeleteDialog() {\n showDeleteDialog = false;\n selectedPaymentMethodId = null;\n }\n\n async function handleDeletePaymentMethod() {\n if (!selectedPaymentMethodId) return;\n isProcessing = true;\n\n try {\n const formData = new FormData();\n formData.append('paymentMethodId', selectedPaymentMethodId);\n\n await fetch('?/deletePaymentMethod', {\n method: 'POST',\n body: formData\n });\n\n await invalidate('app:billing');\n toast.success('Payment method removed successfully');\n closeDeleteDialog();\n } catch (err) {\n console.error('Error deleting payment method:', err);\n toast.error('Failed to remove payment method');\n } finally {\n isProcessing = false;\n }\n }\n\n async function setDefaultPaymentMethod(paymentMethodId: string) {\n try {\n const formData = new FormData();\n formData.append('paymentMethodId', paymentMethodId);\n\n await fetch('?/setDefaultPaymentMethod', {\n method: 'POST',\n body: formData\n });\n\n await invalidate('app:billing');\n toast.success('Default payment method updated');\n } catch (err) {\n console.error('Error setting default payment method:', err);\n toast.error('Failed to update default payment method');\n }\n }\n\n function getCardBrandIcon(brand: string) {\n // You can customize these icons or use actual card brand icons\n const brands: Record<string, string> = {\n visa: '💳',\n mastercard: '💳',\n amex: '💳',\n discover: '💳',\n unknown: '💳'\n };\n return brands[brand.toLowerCase()] || brands.unknown;\n }\n\n function formatCardBrand(brand: string) {\n return brand.charAt(0).toUpperCase() + brand.slice(1);\n }\n<\/script>\n\n<div class=\"divide-y divide-gray-900/10 dark:divide-white/10\">\n <div class=\"grid grid-cols-1 gap-x-8 gap-y-8 py-10 md:grid-cols-3\">\n <div class=\"px-4 sm:px-0\">\n <h2 class=\"text-base/7 font-semibold text-gray-900 dark:text-white\">Payment Methods</h2>\n <p class=\"mt-1 text-sm/6 text-gray-600 dark:text-gray-400\">\n Manage your payment methods for subscriptions and purchases.\n </p>\n </div>\n\n <div class=\"md:col-span-2\">\n <Card.Root>\n <Card.Content>\n {#if 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</div>\n\n<!-- Delete Confirmation Dialog -->\n<AlertDialog.Root bind:open={showDeleteDialog}>\n <AlertDialog.Content>\n <AlertDialog.Header>\n <AlertDialog.Title>Remove Payment Method</AlertDialog.Title>\n <AlertDialog.Description>\n Are you sure you want to remove this payment method? This action cannot be undone.\n </AlertDialog.Description>\n </AlertDialog.Header>\n <AlertDialog.Footer>\n <AlertDialog.Cancel onclick={closeDeleteDialog}>Cancel</AlertDialog.Cancel>\n <AlertDialog.Action onclick={handleDeletePaymentMethod} disabled={isProcessing}>\n {isProcessing ? 'Removing...' : 'Remove'}\n </AlertDialog.Action>\n </AlertDialog.Footer>\n </AlertDialog.Content>\n</AlertDialog.Root>\n", wa = "# 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", Ta = "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", Ea = "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", Da = "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", Oa = "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", ka = "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", Aa = "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", ja = "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", Ma = "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", Na = "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", Pa = "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", Fa = /* @__PURE__ */ Object.assign({
4147
- "./creates/data/hooks/stripe.pb.js": $i,
4148
- "./creates/data/hooks/utils.js": ea,
4149
- "./creates/src/lib/components/payments/confirm-dialog.svelte": ta,
4150
- "./creates/src/lib/components/payments/payment-button.svelte": na,
4151
- "./creates/src/lib/components/payments/payment-dialog.svelte": ra,
4152
- "./creates/src/lib/components/payments/stripe-constants.ts": ia,
4153
- "./creates/src/lib/components/payments/stripe-payment-form.svelte": aa,
4154
- "./creates/src/lib/components/payments/use-payment-intent.svelte.ts": oa,
4155
- "./creates/src/lib/components/payments/use-stripe.svelte.ts": sa,
4156
- "./creates/src/lib/stripe.ts": ca,
4157
- "./creates/src/routes/api/stripe/payment-intent/+server.ts": la,
4158
- "./creates/src/routes/api/stripe/payment-intent/server.test.ts": ua,
4159
- "./creates/src/routes/api/stripe/sync/prices/+server.ts": da,
4160
- "./creates/src/routes/api/stripe/sync/products/+server.ts": fa,
4161
- "./creates/src/routes/webhooks/stripe/+server.ts": pa,
4162
- "./creates/src/routes/webhooks/stripe/handlers/payment-intent/server.test.ts": ma,
4163
- "./creates/src/routes/webhooks/stripe/handlers/payment-intent/succeeded.ts": ha,
4164
- "./creates/src/routes/webhooks/stripe/server.test.ts": ga
4165
- }), Ia = /* @__PURE__ */ Object.assign({
4166
- "./creates-app-mode/data/hooks/stripe.pb.js": _a,
4167
- "./creates-app-mode/data/hooks/utils.js": va,
4168
- "./creates-app-mode/src/lib/components/payments/setup-button.svelte": ya,
4169
- "./creates-app-mode/src/lib/components/payments/setup-dialog.svelte": ba,
4170
- "./creates-app-mode/src/routes/(app)/billing/+layout.server.ts": xa,
4171
- "./creates-app-mode/src/routes/(app)/billing/+page.server.ts": Sa,
4172
- "./creates-app-mode/src/routes/(app)/billing/+page.svelte": Ca,
4173
- "./creates-app-mode/src/routes/(app)/billing/README.md": wa,
4174
- "./creates-app-mode/src/routes/api/stripe/payment-intent/+server.ts": Ta,
4175
- "./creates-app-mode/src/routes/api/stripe/payment-intent/server.test.ts": Ea,
4176
- "./creates-app-mode/src/routes/api/stripe/setup-intent/+server.ts": Da,
4177
- "./creates-app-mode/src/routes/api/stripe/setup-intent/server.test.ts": Oa,
4178
- "./creates-app-mode/src/routes/api/stripe/sync/customers/+server.ts": ka,
4179
- "./creates-app-mode/src/routes/webhooks/stripe/+server.ts": Aa,
4180
- "./creates-app-mode/src/routes/webhooks/stripe/handlers/payment-intent/server.test.ts": ja,
4181
- "./creates-app-mode/src/routes/webhooks/stripe/handlers/payment-intent/succeeded.ts": Ma,
4182
- "./creates-app-mode/src/routes/webhooks/stripe/handlers/payment-method/attached.ts": Na,
4183
- "./creates-app-mode/src/routes/webhooks/stripe/handlers/payment-method/server.test.ts": Pa
4184
- }), La = "./creates/", Ra = "./creates-app-mode/";
4185
- function za(e, n) {
4186
- let i = {};
4305
+ generate: ca
4306
+ }, ua = "/// <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", da = "/// <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", fa = "<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", pa = "<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", ma = "<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", ha = "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", ga = "<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", _a = "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", va = "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", ya = "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", ba = "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", xa = "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", Sa = "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", Ca = "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", wa = "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", Ta = "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", Ea = "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", Da = "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", Oa = "/// <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", ka = "/// <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", Aa = "<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", ja = "<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", Ma = "export const load = async ({ parent }) => {\n const { breadcrumbs } = await parent();\n\n return {\n breadcrumbs: [...breadcrumbs, { title: \"Billing\", url: \"/billing\" }],\n };\n};\n", Na = "import { error } from \"@sveltejs/kit\";\nimport stripe from \"$lib/stripe\";\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 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 };\n};\n\nexport const actions = {\n setDefaultPaymentMethod: async ({ locals, request }) => {\n const formData = await request.formData();\n const paymentMethodId = formData.get(\"paymentMethodId\") as string;\n\n const customer = await locals.admin\n .collection(\"stripe_customers\")\n .getFirstListItem(`user.id = \"${locals.pb.authStore.record?.id}\"`);\n\n if (!customer || !customer.id) {\n return error(400, \"Customer not found\");\n }\n\n await stripe.customers.update(customer.id, {\n invoice_settings: {\n default_payment_method: paymentMethodId,\n },\n });\n\n await locals.admin.collection(\"stripe_customers\").update(customer.id, {\n default_payment_method: paymentMethodId,\n });\n },\n deletePaymentMethod: async ({ locals, request }) => {\n const formData = await request.formData();\n const paymentMethodId = formData.get(\"paymentMethodId\") as string;\n\n const customer = await locals.admin\n .collection(\"stripe_customers\")\n .getFirstListItem(`user.id = \"${locals.pb.authStore.record?.id}\"`);\n\n const defaultPaymentMethod = customer.default_payment_method;\n\n await stripe.paymentMethods.detach(paymentMethodId);\n\n // If default payment method was deleted, update default payment method\n if (defaultPaymentMethod === paymentMethodId) {\n const paymentMethods = await stripe.paymentMethods.list({\n customer: customer.id,\n });\n\n if (paymentMethods.data.length > 0) {\n const defaultPaymentMethod = paymentMethods.data[0];\n\n await stripe.customers.update(customer.id, {\n invoice_settings: {\n default_payment_method: defaultPaymentMethod.id,\n },\n });\n\n await locals.admin.collection(\"stripe_customers\").update(customer.id, {\n default_payment_method: defaultPaymentMethod.id,\n });\n } else {\n await locals.admin.collection(\"stripe_customers\").update(customer.id, {\n default_payment_method: null,\n });\n }\n }\n },\n};\n", Pa = "<script lang=\"ts\">\n import { Button } from '$lib/components/ui/button';\n import * as Card from '$lib/components/ui/card';\n import { Badge } from '$lib/components/ui/badge';\n import * as AlertDialog from '$lib/components/ui/alert-dialog';\n import SetupButton from '$lib/components/payments/setup-button.svelte';\n import { CreditCard, Trash2, Check } from '@lucide/svelte';\n import { toast } from 'svelte-sonner';\n import { invalidate } from '$app/navigation';\n\n let { data } = $props();\n let paymentMethods = $derived(data.paymentMethods);\n let showDeleteDialog = $state(false);\n let selectedPaymentMethodId = $state<string | null>(null);\n let isProcessing = $state(false);\n\n function openDeleteDialog(paymentMethodId: string) {\n selectedPaymentMethodId = paymentMethodId;\n showDeleteDialog = true;\n }\n\n function closeDeleteDialog() {\n showDeleteDialog = false;\n selectedPaymentMethodId = null;\n }\n\n async function handleDeletePaymentMethod() {\n if (!selectedPaymentMethodId) return;\n isProcessing = true;\n\n try {\n const formData = new FormData();\n formData.append('paymentMethodId', selectedPaymentMethodId);\n\n await fetch('?/deletePaymentMethod', {\n method: 'POST',\n body: formData\n });\n\n await invalidate('app:billing');\n toast.success('Payment method removed successfully');\n closeDeleteDialog();\n } catch (err) {\n console.error('Error deleting payment method:', err);\n toast.error('Failed to remove payment method');\n } finally {\n isProcessing = false;\n }\n }\n\n async function setDefaultPaymentMethod(paymentMethodId: string) {\n try {\n const formData = new FormData();\n formData.append('paymentMethodId', paymentMethodId);\n\n await fetch('?/setDefaultPaymentMethod', {\n method: 'POST',\n body: formData\n });\n\n await invalidate('app:billing');\n toast.success('Default payment method updated');\n } catch (err) {\n console.error('Error setting default payment method:', err);\n toast.error('Failed to update default payment method');\n }\n }\n\n function getCardBrandIcon(brand: string) {\n // You can customize these icons or use actual card brand icons\n const brands: Record<string, string> = {\n visa: '💳',\n mastercard: '💳',\n amex: '💳',\n discover: '💳',\n unknown: '💳'\n };\n return brands[brand.toLowerCase()] || brands.unknown;\n }\n\n function formatCardBrand(brand: string) {\n return brand.charAt(0).toUpperCase() + brand.slice(1);\n }\n<\/script>\n\n<div class=\"divide-y divide-gray-900/10 dark:divide-white/10\">\n <div class=\"grid grid-cols-1 gap-x-8 gap-y-8 py-10 md:grid-cols-3\">\n <div class=\"px-4 sm:px-0\">\n <h2 class=\"text-base/7 font-semibold text-gray-900 dark:text-white\">Payment Methods</h2>\n <p class=\"mt-1 text-sm/6 text-gray-600 dark:text-gray-400\">\n Manage your payment methods for subscriptions and purchases.\n </p>\n </div>\n\n <div class=\"md:col-span-2\">\n <Card.Root>\n <Card.Content>\n {#if 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</div>\n\n<!-- Delete Confirmation Dialog -->\n<AlertDialog.Root bind:open={showDeleteDialog}>\n <AlertDialog.Content>\n <AlertDialog.Header>\n <AlertDialog.Title>Remove Payment Method</AlertDialog.Title>\n <AlertDialog.Description>\n Are you sure you want to remove this payment method? This action cannot be undone.\n </AlertDialog.Description>\n </AlertDialog.Header>\n <AlertDialog.Footer>\n <AlertDialog.Cancel onclick={closeDeleteDialog}>Cancel</AlertDialog.Cancel>\n <AlertDialog.Action onclick={handleDeletePaymentMethod} disabled={isProcessing}>\n {isProcessing ? 'Removing...' : 'Remove'}\n </AlertDialog.Action>\n </AlertDialog.Footer>\n </AlertDialog.Content>\n</AlertDialog.Root>\n", Fa = "# 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", Ia = "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", La = "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", Ra = "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", za = "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", Ba = "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", Va = "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", Ha = "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", Ua = "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", Wa = "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", Ga = "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", Ka = /* @__PURE__ */ Object.assign({
4307
+ "./creates/data/hooks/stripe.pb.js": ua,
4308
+ "./creates/data/hooks/utils.js": da,
4309
+ "./creates/src/lib/components/payments/confirm-dialog.svelte": fa,
4310
+ "./creates/src/lib/components/payments/payment-button.svelte": pa,
4311
+ "./creates/src/lib/components/payments/payment-dialog.svelte": ma,
4312
+ "./creates/src/lib/components/payments/stripe-constants.ts": ha,
4313
+ "./creates/src/lib/components/payments/stripe-payment-form.svelte": ga,
4314
+ "./creates/src/lib/components/payments/use-payment-intent.svelte.ts": _a,
4315
+ "./creates/src/lib/components/payments/use-stripe.svelte.ts": va,
4316
+ "./creates/src/lib/stripe.ts": ya,
4317
+ "./creates/src/routes/api/stripe/payment-intent/+server.ts": ba,
4318
+ "./creates/src/routes/api/stripe/payment-intent/server.test.ts": xa,
4319
+ "./creates/src/routes/api/stripe/sync/prices/+server.ts": Sa,
4320
+ "./creates/src/routes/api/stripe/sync/products/+server.ts": Ca,
4321
+ "./creates/src/routes/webhooks/stripe/+server.ts": wa,
4322
+ "./creates/src/routes/webhooks/stripe/handlers/payment-intent/server.test.ts": Ta,
4323
+ "./creates/src/routes/webhooks/stripe/handlers/payment-intent/succeeded.ts": Ea,
4324
+ "./creates/src/routes/webhooks/stripe/server.test.ts": Da
4325
+ }), qa = /* @__PURE__ */ Object.assign({
4326
+ "./creates-app-mode/data/hooks/stripe.pb.js": Oa,
4327
+ "./creates-app-mode/data/hooks/utils.js": ka,
4328
+ "./creates-app-mode/src/lib/components/payments/setup-button.svelte": Aa,
4329
+ "./creates-app-mode/src/lib/components/payments/setup-dialog.svelte": ja,
4330
+ "./creates-app-mode/src/routes/(app)/billing/+layout.server.ts": Ma,
4331
+ "./creates-app-mode/src/routes/(app)/billing/+page.server.ts": Na,
4332
+ "./creates-app-mode/src/routes/(app)/billing/+page.svelte": Pa,
4333
+ "./creates-app-mode/src/routes/(app)/billing/README.md": Fa,
4334
+ "./creates-app-mode/src/routes/api/stripe/payment-intent/+server.ts": Ia,
4335
+ "./creates-app-mode/src/routes/api/stripe/payment-intent/server.test.ts": La,
4336
+ "./creates-app-mode/src/routes/api/stripe/setup-intent/+server.ts": Ra,
4337
+ "./creates-app-mode/src/routes/api/stripe/setup-intent/server.test.ts": za,
4338
+ "./creates-app-mode/src/routes/api/stripe/sync/customers/+server.ts": Ba,
4339
+ "./creates-app-mode/src/routes/webhooks/stripe/+server.ts": Va,
4340
+ "./creates-app-mode/src/routes/webhooks/stripe/handlers/payment-intent/server.test.ts": Ha,
4341
+ "./creates-app-mode/src/routes/webhooks/stripe/handlers/payment-intent/succeeded.ts": Ua,
4342
+ "./creates-app-mode/src/routes/webhooks/stripe/handlers/payment-method/attached.ts": Wa,
4343
+ "./creates-app-mode/src/routes/webhooks/stripe/handlers/payment-method/server.test.ts": Ga
4344
+ }), Ja = "./creates/", Ya = "./creates-app-mode/";
4345
+ function Xa(e, t) {
4346
+ let r = {};
4187
4347
  for (let [a, o] of Object.entries(e)) {
4188
- let e = r(a, n);
4189
- i[e] = {
4348
+ let e = i(a, t);
4349
+ r[e] = {
4190
4350
  path: e,
4191
- language: t(e),
4351
+ language: n(e),
4192
4352
  content: o,
4193
4353
  status: "success"
4194
4354
  };
4195
4355
  }
4196
- return i;
4356
+ return r;
4197
4357
  }
4198
- async function Ba(e) {
4199
- let t = e.features.auth, n = { ...za(Fa, La) };
4358
+ async function Za(e) {
4359
+ let t = e.features.auth, n = { ...Xa(Ka, Ja) };
4200
4360
  if (t) {
4201
- let e = za(Ia, Ra);
4361
+ let e = Xa(qa, Ya);
4202
4362
  Object.assign(n, e);
4203
4363
  }
4204
4364
  let r = Object.values(n).sort((e, t) => e.path.localeCompare(t.path)), i = [
@@ -4212,12 +4372,13 @@ async function Ba(e) {
4212
4372
  deletes: [],
4213
4373
  components: i,
4214
4374
  packages: ["stripe", "@stripe/stripe-js"],
4215
- collections: []
4375
+ collections: [],
4376
+ collectionPatches: []
4216
4377
  };
4217
4378
  }
4218
4379
  //#endregion
4219
4380
  //#region src/patterns/enable/payments/preview-modifies/src/lib/components/nav-user.svelte?raw
4220
- var Va = "<script lang=\"ts\">\n import { toggleMode, mode } from 'mode-watcher';\n import ChevronsUpDownIcon from '@lucide/svelte/icons/chevrons-up-down';\n import Settings2Icon from '@lucide/svelte/icons/settings-2';\n // [!code highlight:1]\n import CreditCardIcon from '@lucide/svelte/icons/credit-card';\n import LogOutIcon from '@lucide/svelte/icons/log-out';\n import MoonIcon from '@lucide/svelte/icons/moon';\n import SunIcon from '@lucide/svelte/icons/sun';\n import * as Avatar from '$lib/components/ui/avatar';\n import * as DropdownMenu from '$lib/components/ui/dropdown-menu';\n import * as Sidebar from '$lib/components/ui/sidebar';\n\n let data = {\n navUser: [\n {\n title: 'Settings',\n url: '/settings',\n icon: Settings2Icon\n },\n // [!code highlight:5]\n {\n title: 'Billing',\n url: '/billing',\n icon: CreditCardIcon\n }\n ]\n };\n\n let {\n user\n }: {\n user: {\n id: string;\n name: string;\n email: string;\n avatar: string;\n };\n } = $props();\n\n const sidebar = Sidebar.useSidebar();\n<\/script>\n\n<Sidebar.Menu>\n <Sidebar.MenuItem>\n <DropdownMenu.Root>\n <DropdownMenu.Trigger>\n {#snippet child({ props })}\n <Sidebar.MenuButton\n size=\"lg\"\n class=\"data-[state=open]:bg-sidebar-accent data-[state=open]:text-sidebar-accent-foreground\"\n {...props}\n >\n <Avatar.Root class=\"size-8 rounded-lg\">\n {#if user.avatar}\n <Avatar.Image src=\"/api/files/users/{user.id}/{user.avatar}\" alt={user.name} />\n {/if}\n <Avatar.Fallback class=\"rounded-lg\">\n {user.email?.charAt(0).toUpperCase()}\n </Avatar.Fallback>\n </Avatar.Root>\n <div class=\"grid flex-1 text-left text-sm leading-tight\">\n <span class=\"truncate font-medium\">{user.name}</span>\n <span class=\"truncate text-xs\">{user.email}</span>\n </div>\n <ChevronsUpDownIcon class=\"ml-auto size-4\" />\n </Sidebar.MenuButton>\n {/snippet}\n </DropdownMenu.Trigger>\n <DropdownMenu.Content\n class=\"w-(--bits-dropdown-menu-anchor-width) min-w-56 rounded-lg\"\n side={sidebar.isMobile ? 'bottom' : 'right'}\n align=\"end\"\n sideOffset={4}\n >\n <DropdownMenu.Label class=\"p-0 font-normal\">\n <div class=\"flex items-center gap-2 px-1 py-1.5 text-left text-sm\">\n <Avatar.Root class=\"size-8 rounded-lg\">\n {#if user.avatar}\n <Avatar.Image src=\"/api/files/users/{user.id}/{user.avatar}\" alt={user.name} />\n {/if}\n <Avatar.Fallback class=\"rounded-lg\">\n {user.email?.charAt(0).toUpperCase()}\n </Avatar.Fallback>\n </Avatar.Root>\n <div class=\"grid flex-1 text-left text-sm leading-tight\">\n <span class=\"truncate font-medium\">{user.name}</span>\n <span class=\"truncate text-xs\">{user.email}</span>\n </div>\n </div>\n </DropdownMenu.Label>\n <DropdownMenu.Separator />\n <DropdownMenu.Group>\n <DropdownMenu.Item onclick={toggleMode}>\n {#if mode.current === 'dark'}\n <SunIcon />\n Light mode\n {:else}\n <MoonIcon />\n Dark mode\n {/if}\n </DropdownMenu.Item>\n {#each data.navUser as item}\n <DropdownMenu.Item class=\"p-0\">\n <a href={item.url} class=\"flex cursor-default items-center gap-2 px-2 py-1.5 w-full\">\n <item.icon />\n {item.title}\n </a>\n </DropdownMenu.Item>\n {/each}\n </DropdownMenu.Group>\n <DropdownMenu.Separator />\n <DropdownMenu.Item class=\"p-0\">\n <form action=\"/logout\" method=\"post\" class=\"w-full\">\n <button type=\"submit\" class=\"flex cursor-default items-center gap-2 px-2 py-1.5 w-full\">\n <LogOutIcon />\n Log out\n </button>\n </form>\n </DropdownMenu.Item>\n </DropdownMenu.Content>\n </DropdownMenu.Root>\n </Sidebar.MenuItem>\n</Sidebar.Menu>\n", Ha = "import { redirect } from \"@sveltejs/kit\";\nimport { fail, superValidate } from \"sveltekit-superforms\";\nimport { zod4 } from \"sveltekit-superforms/adapters\";\nimport { setFlash } from \"sveltekit-flash-message/server\";\nimport { setPocketbaseErrors } from \"@velastack/pocketbase\";\nimport { dev } from \"$app/environment\";\nimport { signupSchema } from \"$lib/schemas/signup\";\n// [!code highlight:1]\nimport stripe from \"$lib/stripe\";\n\nexport const load = async ({ locals }) => {\n const authMethods = await locals.admin.collection(\"users\").listAuthMethods();\n\n if (locals.pb.authStore.isValid) {\n redirect(303, \"/dashboard\");\n }\n\n return { form: await superValidate(zod4(signupSchema)), authMethods };\n};\n\nexport const actions = {\n default: async ({ locals, request, cookies, url }) => {\n const form = await superValidate(request, zod4(signupSchema));\n\n if (!form.valid) {\n return fail(400, { form });\n }\n\n let user;\n\n try {\n user = await locals.admin.collection(\"users\").create({\n email: form.data.email,\n password: form.data.password,\n passwordConfirm: form.data.passwordConfirm,\n });\n } catch (error) {\n setPocketbaseErrors(form, error);\n return fail(400, { form });\n }\n\n // [!code highlight:1]\n await linkStripeCustomer(form.data.email, user, locals);\n\n await locals.pb.collection(\"users\").requestVerification(user.email);\n await locals.pb\n .collection(\"users\")\n .authWithPassword(form.data.email, form.data.password);\n\n const redirectUrl = url.searchParams.get(\"redirect\") ?? \"/dashboard\";\n const cookie = locals.pb.authStore.getCookie();\n cookies.set(\"pb_auth\", cookie, {\n path: \"/\",\n httpOnly: true,\n sameSite: \"lax\",\n secure: !dev,\n maxAge: 60 * 60 * 24 * 30,\n });\n\n setFlash(\n { type: \"toast\", message: \"We sent a confirmation link to your email.\" },\n cookies,\n );\n return redirect(303, redirectUrl);\n },\n};\n\n// [!code highlight:66]\nconst linkStripeCustomer = async (\n email: string,\n user: { id: string },\n locals: App.Locals,\n) => {\n const matchingCustomer = await stripe.customers.list({\n email: email,\n limit: 1,\n expand: [\"data.invoice_settings\"],\n });\n\n let customer;\n let isExistingCustomer = false;\n\n if (matchingCustomer.data.length > 0) {\n isExistingCustomer = true;\n customer = matchingCustomer.data[0];\n } else {\n customer = await stripe.customers.create({\n email: email,\n });\n }\n\n await locals.admin.collection(\"stripe_customers\").create({\n id: customer.id,\n user: user.id,\n });\n\n if (!isExistingCustomer) {\n return;\n }\n\n const paymentMethods = await stripe.customers.listPaymentMethods(\n customer.id,\n {\n type: \"card\",\n allow_redisplay: \"always\",\n },\n );\n\n for (const paymentMethod of paymentMethods.data) {\n if (paymentMethod.allow_redisplay === \"unspecified\") {\n continue;\n }\n\n await locals.admin.collection(\"stripe_payment_methods\").create({\n id: paymentMethod.id,\n customer: customer.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\n const defaultPaymentMethod =\n customer.invoice_settings?.default_payment_method;\n\n if (defaultPaymentMethod) {\n try {\n await locals.admin.collection(\"stripe_customers\").update(customer.id, {\n default_payment_method: defaultPaymentMethod,\n });\n } catch {}\n }\n};\n", Ua = "users", Wa = "stripe_customers", Ga = "stripe_payment_methods", Ka = {
4381
+ var Qa = "<script lang=\"ts\">\n import { toggleMode, mode } from 'mode-watcher';\n import ChevronsUpDownIcon from '@lucide/svelte/icons/chevrons-up-down';\n import Settings2Icon from '@lucide/svelte/icons/settings-2';\n // [!code highlight:1]\n import CreditCardIcon from '@lucide/svelte/icons/credit-card';\n import LogOutIcon from '@lucide/svelte/icons/log-out';\n import MoonIcon from '@lucide/svelte/icons/moon';\n import SunIcon from '@lucide/svelte/icons/sun';\n import * as Avatar from '$lib/components/ui/avatar';\n import * as DropdownMenu from '$lib/components/ui/dropdown-menu';\n import * as Sidebar from '$lib/components/ui/sidebar';\n\n let data = {\n navUser: [\n {\n title: 'Settings',\n url: '/settings',\n icon: Settings2Icon\n },\n // [!code highlight:5]\n {\n title: 'Billing',\n url: '/billing',\n icon: CreditCardIcon\n }\n ]\n };\n\n let {\n user\n }: {\n user: {\n id: string;\n name: string;\n email: string;\n avatar: string;\n };\n } = $props();\n\n const sidebar = Sidebar.useSidebar();\n<\/script>\n\n<Sidebar.Menu>\n <Sidebar.MenuItem>\n <DropdownMenu.Root>\n <DropdownMenu.Trigger>\n {#snippet child({ props })}\n <Sidebar.MenuButton\n size=\"lg\"\n class=\"data-[state=open]:bg-sidebar-accent data-[state=open]:text-sidebar-accent-foreground\"\n {...props}\n >\n <Avatar.Root class=\"size-8 rounded-lg\">\n {#if user.avatar}\n <Avatar.Image src=\"/api/files/users/{user.id}/{user.avatar}\" alt={user.name} />\n {/if}\n <Avatar.Fallback class=\"rounded-lg\">\n {user.email?.charAt(0).toUpperCase()}\n </Avatar.Fallback>\n </Avatar.Root>\n <div class=\"grid flex-1 text-left text-sm leading-tight\">\n <span class=\"truncate font-medium\">{user.name}</span>\n <span class=\"truncate text-xs\">{user.email}</span>\n </div>\n <ChevronsUpDownIcon class=\"ml-auto size-4\" />\n </Sidebar.MenuButton>\n {/snippet}\n </DropdownMenu.Trigger>\n <DropdownMenu.Content\n class=\"w-(--bits-dropdown-menu-anchor-width) min-w-56 rounded-lg\"\n side={sidebar.isMobile ? 'bottom' : 'right'}\n align=\"end\"\n sideOffset={4}\n >\n <DropdownMenu.Label class=\"p-0 font-normal\">\n <div class=\"flex items-center gap-2 px-1 py-1.5 text-left text-sm\">\n <Avatar.Root class=\"size-8 rounded-lg\">\n {#if user.avatar}\n <Avatar.Image src=\"/api/files/users/{user.id}/{user.avatar}\" alt={user.name} />\n {/if}\n <Avatar.Fallback class=\"rounded-lg\">\n {user.email?.charAt(0).toUpperCase()}\n </Avatar.Fallback>\n </Avatar.Root>\n <div class=\"grid flex-1 text-left text-sm leading-tight\">\n <span class=\"truncate font-medium\">{user.name}</span>\n <span class=\"truncate text-xs\">{user.email}</span>\n </div>\n </div>\n </DropdownMenu.Label>\n <DropdownMenu.Separator />\n <DropdownMenu.Group>\n <DropdownMenu.Item onclick={toggleMode}>\n {#if mode.current === 'dark'}\n <SunIcon />\n Light mode\n {:else}\n <MoonIcon />\n Dark mode\n {/if}\n </DropdownMenu.Item>\n {#each data.navUser as item}\n <DropdownMenu.Item class=\"p-0\">\n <a href={item.url} class=\"flex cursor-default items-center gap-2 px-2 py-1.5 w-full\">\n <item.icon />\n {item.title}\n </a>\n </DropdownMenu.Item>\n {/each}\n </DropdownMenu.Group>\n <DropdownMenu.Separator />\n <DropdownMenu.Item class=\"p-0\">\n <form action=\"/logout\" method=\"post\" class=\"w-full\">\n <button type=\"submit\" class=\"flex cursor-default items-center gap-2 px-2 py-1.5 w-full\">\n <LogOutIcon />\n Log out\n </button>\n </form>\n </DropdownMenu.Item>\n </DropdownMenu.Content>\n </DropdownMenu.Root>\n </Sidebar.MenuItem>\n</Sidebar.Menu>\n", $a = "import { redirect } from \"@sveltejs/kit\";\nimport { fail, superValidate } from \"sveltekit-superforms\";\nimport { zod4 } from \"sveltekit-superforms/adapters\";\nimport { setFlash } from \"sveltekit-flash-message/server\";\nimport { setPocketbaseErrors } from \"@velastack/pocketbase\";\nimport { dev } from \"$app/environment\";\nimport { signupSchema } from \"$lib/schemas/signup\";\n// [!code highlight:1]\nimport stripe from \"$lib/stripe\";\n\nexport const load = async ({ locals }) => {\n const authMethods = await locals.admin.collection(\"users\").listAuthMethods();\n\n if (locals.pb.authStore.isValid) {\n redirect(303, \"/dashboard\");\n }\n\n return { form: await superValidate(zod4(signupSchema)), authMethods };\n};\n\nexport const actions = {\n default: async ({ locals, request, cookies, url }) => {\n const form = await superValidate(request, zod4(signupSchema));\n\n if (!form.valid) {\n return fail(400, { form });\n }\n\n let user;\n\n try {\n user = await locals.admin.collection(\"users\").create({\n email: form.data.email,\n password: form.data.password,\n passwordConfirm: form.data.passwordConfirm,\n });\n } catch (error) {\n setPocketbaseErrors(form, error);\n return fail(400, { form });\n }\n\n // [!code highlight:1]\n await linkStripeCustomer(form.data.email, user, locals);\n\n await locals.pb.collection(\"users\").requestVerification(user.email);\n await locals.pb\n .collection(\"users\")\n .authWithPassword(form.data.email, form.data.password);\n\n const redirectUrl = url.searchParams.get(\"redirect\") ?? \"/dashboard\";\n const cookie = locals.pb.authStore.getCookie();\n cookies.set(\"pb_auth\", cookie, {\n path: \"/\",\n httpOnly: true,\n sameSite: \"lax\",\n secure: !dev,\n maxAge: 60 * 60 * 24 * 30,\n });\n\n setFlash(\n { type: \"toast\", message: \"We sent a confirmation link to your email.\" },\n cookies,\n );\n return redirect(303, redirectUrl);\n },\n};\n\n// [!code highlight:66]\nconst linkStripeCustomer = async (\n email: string,\n user: { id: string },\n locals: App.Locals,\n) => {\n const matchingCustomer = await stripe.customers.list({\n email: email,\n limit: 1,\n expand: [\"data.invoice_settings\"],\n });\n\n let customer;\n let isExistingCustomer = false;\n\n if (matchingCustomer.data.length > 0) {\n isExistingCustomer = true;\n customer = matchingCustomer.data[0];\n } else {\n customer = await stripe.customers.create({\n email: email,\n });\n }\n\n await locals.admin.collection(\"stripe_customers\").create({\n id: customer.id,\n user: user.id,\n });\n\n if (!isExistingCustomer) {\n return;\n }\n\n const paymentMethods = await stripe.customers.listPaymentMethods(\n customer.id,\n {\n type: \"card\",\n allow_redisplay: \"always\",\n },\n );\n\n for (const paymentMethod of paymentMethods.data) {\n if (paymentMethod.allow_redisplay === \"unspecified\") {\n continue;\n }\n\n await locals.admin.collection(\"stripe_payment_methods\").create({\n id: paymentMethod.id,\n customer: customer.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\n const defaultPaymentMethod =\n customer.invoice_settings?.default_payment_method;\n\n if (defaultPaymentMethod) {\n try {\n await locals.admin.collection(\"stripe_customers\").update(customer.id, {\n default_payment_method: defaultPaymentMethod,\n });\n } catch {}\n }\n};\n", eo = "users", to = "stripe_customers", no = "stripe_payment_methods", ro = {
4221
4382
  name: "stripe_products",
4222
4383
  type: "base",
4223
4384
  fields: [
@@ -4256,7 +4417,7 @@ var Va = "<script lang=\"ts\">\n import { toggleMode, mode } from 'mode-watcher'
4256
4417
  type: "autodate"
4257
4418
  }
4258
4419
  ]
4259
- }, qa = {
4420
+ }, io = {
4260
4421
  name: "stripe_prices",
4261
4422
  type: "base",
4262
4423
  fields: [
@@ -4315,8 +4476,8 @@ var Va = "<script lang=\"ts\">\n import { toggleMode, mode } from 'mode-watcher'
4315
4476
  type: "autodate"
4316
4477
  }
4317
4478
  ]
4318
- }, Ja = {
4319
- name: Wa,
4479
+ }, ao = {
4480
+ name: to,
4320
4481
  type: "base",
4321
4482
  fields: [
4322
4483
  {
@@ -4327,7 +4488,7 @@ var Va = "<script lang=\"ts\">\n import { toggleMode, mode } from 'mode-watcher'
4327
4488
  type: "text"
4328
4489
  },
4329
4490
  {
4330
- collectionId: Ua,
4491
+ collectionId: eo,
4331
4492
  maxSelect: 1,
4332
4493
  minSelect: 0,
4333
4494
  name: "user",
@@ -4335,7 +4496,7 @@ var Va = "<script lang=\"ts\">\n import { toggleMode, mode } from 'mode-watcher'
4335
4496
  type: "relation"
4336
4497
  },
4337
4498
  {
4338
- collectionId: Ga,
4499
+ collectionId: no,
4339
4500
  maxSelect: 1,
4340
4501
  minSelect: 0,
4341
4502
  name: "default_payment_method",
@@ -4355,8 +4516,8 @@ var Va = "<script lang=\"ts\">\n import { toggleMode, mode } from 'mode-watcher'
4355
4516
  type: "autodate"
4356
4517
  }
4357
4518
  ]
4358
- }, Ya = {
4359
- name: Ga,
4519
+ }, oo = {
4520
+ name: no,
4360
4521
  type: "base",
4361
4522
  fields: [
4362
4523
  {
@@ -4387,7 +4548,7 @@ var Va = "<script lang=\"ts\">\n import { toggleMode, mode } from 'mode-watcher'
4387
4548
  type: "number"
4388
4549
  },
4389
4550
  {
4390
- collectionId: Wa,
4551
+ collectionId: to,
4391
4552
  maxSelect: 1,
4392
4553
  minSelect: 0,
4393
4554
  name: "customer",
@@ -4408,7 +4569,7 @@ var Va = "<script lang=\"ts\">\n import { toggleMode, mode } from 'mode-watcher'
4408
4569
  type: "autodate"
4409
4570
  }
4410
4571
  ]
4411
- }, Xa = {
4572
+ }, so = {
4412
4573
  name: "transactions",
4413
4574
  type: "base",
4414
4575
  fields: [
@@ -4463,7 +4624,7 @@ var Va = "<script lang=\"ts\">\n import { toggleMode, mode } from 'mode-watcher'
4463
4624
  type: "text"
4464
4625
  },
4465
4626
  {
4466
- collectionId: Ua,
4627
+ collectionId: eo,
4467
4628
  maxSelect: 1,
4468
4629
  minSelect: 0,
4469
4630
  name: "user",
@@ -4476,55 +4637,56 @@ var Va = "<script lang=\"ts\">\n import { toggleMode, mode } from 'mode-watcher'
4476
4637
  type: "url"
4477
4638
  }
4478
4639
  ]
4479
- }, Za = [Ka, qa], Qa = [
4480
- Ja,
4481
- Ya,
4482
- Xa
4483
- ], $a, eo = /* @__PURE__ */ Object.assign({
4484
- "./preview-modifies/src/lib/components/nav-user.svelte": Va,
4485
- "./preview-modifies/src/routes/(public)/signup/+page.server.ts": Ha
4486
- }), to = "./preview-modifies/", no = "price_preview_placeholder";
4487
- function ro(t) {
4488
- return e($a ||= o(["\n <script lang=\"ts\">\n import PaymentButton from '$lib/components/payments/payment-button.svelte';\n <\/script>\n\n <section data-role=\"content\">\n <PaymentButton priceId=\"", "\" />\n </section>\n "]), t);
4489
- }
4490
- async function io(e) {
4491
- let n = e.features.auth, i = Object.entries(eo).map(([e, n]) => {
4492
- let i = r(e, to);
4640
+ }, co = [ro, io], lo = [
4641
+ ao,
4642
+ oo,
4643
+ so
4644
+ ], uo, fo = /* @__PURE__ */ Object.assign({
4645
+ "./preview-modifies/src/lib/components/nav-user.svelte": Qa,
4646
+ "./preview-modifies/src/routes/(public)/signup/+page.server.ts": $a
4647
+ }), po = "./preview-modifies/", mo = "price_preview_placeholder";
4648
+ function ho(e) {
4649
+ return t(uo ||= s(["\n <script lang=\"ts\">\n import PaymentButton from '$lib/components/payments/payment-button.svelte';\n <\/script>\n\n <section data-role=\"content\">\n <PaymentButton priceId=\"", "\" />\n </section>\n "]), e);
4650
+ }
4651
+ async function go(e) {
4652
+ let t = e.features.auth, r = Object.entries(fo).map(([e, t]) => {
4653
+ let r = i(e, po);
4493
4654
  return {
4494
- path: i,
4495
- language: t(i),
4496
- content: n,
4655
+ path: r,
4656
+ language: n(r),
4657
+ content: t,
4497
4658
  status: "success"
4498
4659
  };
4499
4660
  }).sort((e, t) => e.path.localeCompare(t.path)), a = {
4500
4661
  path: "src/routes/(public)/payment/+page.svelte",
4501
4662
  language: "svelte",
4502
- content: ro(no),
4663
+ content: ho(mo),
4503
4664
  status: "success"
4504
- }, o = [...Za, ...n ? Qa : []];
4665
+ }, o = [...co, ...t ? lo : []];
4505
4666
  return {
4506
4667
  creates: [a],
4507
- modifies: i,
4668
+ modifies: r,
4508
4669
  deletes: [],
4509
4670
  components: [],
4510
4671
  packages: [],
4511
- collections: o
4672
+ collections: o,
4673
+ collectionPatches: []
4512
4674
  };
4513
4675
  }
4514
4676
  //#endregion
4515
4677
  //#region src/patterns/enable/payments/index.ts
4516
- var ao = "enable-payments", oo = "1.0.0", so = "src/patterns/enable/payments", co = "/enable/payments";
4517
- async function lo(e) {
4518
- let t = await Ba(e);
4519
- if (e.env === "preview") return v(n([t, await io(e)]));
4520
- let { generate: r } = await import("./chunks/generate.runtime-InE8X2Ly.js"), i = await r(e), { writeResult: a } = await import("./chunks/write-result-ENWLDQtP.js");
4521
- return a(await v(n([t, i])), e);
4522
- }
4523
- var uo = {
4524
- version: oo,
4525
- slug: ao,
4526
- source: so,
4527
- docs: co,
4678
+ var _o = "enable-payments", vo = "1.0.0", yo = "src/patterns/enable/payments", bo = "/enable/payments";
4679
+ async function xo(e) {
4680
+ let t = await Za(e);
4681
+ if (e.env === "preview") return _(r([t, await go(e)]));
4682
+ let { generate: n } = await import("./chunks/generate.runtime-4zd9-8H_.js"), i = await n(e), { writeResult: a } = await import("./chunks/write-result-C80dpjr-.js");
4683
+ return a(await _(r([t, i])), e);
4684
+ }
4685
+ var So = {
4686
+ version: vo,
4687
+ slug: _o,
4688
+ source: yo,
4689
+ docs: bo,
4528
4690
  plan: "pro",
4529
4691
  title: "Enable payments",
4530
4692
  summary: "Adds Stripe payments with product/price sync, checkout flow, and optional saved payment methods when auth is enabled.",
@@ -4553,8 +4715,8 @@ var uo = {
4553
4715
  examples: [],
4554
4716
  tests: 0,
4555
4717
  baseline: "velastack",
4556
- generate: lo
4557
- }, fo = /* @__PURE__ */ Object.assign({
4718
+ generate: xo
4719
+ }, Co = /* @__PURE__ */ Object.assign({
4558
4720
  "./creates/src/lib/components/team-switcher.svelte": "<script lang=\"ts\">\n import type { Snippet } from 'svelte';\n import * as DropdownMenu from '$lib/components/ui/dropdown-menu/index.js';\n import * as Sidebar from '$lib/components/ui/sidebar/index.js';\n import { useSidebar } from '$lib/components/ui/sidebar/index.js';\n import PlusIcon from '@lucide/svelte/icons/plus';\n import UsersIcon from '@lucide/svelte/icons/users';\n import { page } from '$app/state';\n import { goto, invalidate } from '$app/navigation';\n\n let { teams, children }: { teams: { id: string; name: string }[] } & { children: Snippet } =\n $props();\n\n const switchTeam = async (teamId: string) => {\n await goto(`/teams/switch/${teamId}?redirect=${encodeURIComponent(page.url.pathname)}`);\n invalidate('app:team');\n };\n\n const 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 {...props}\n size=\"lg\"\n class=\"data-[state=open]:bg-sidebar-accent data-[state=open]:text-sidebar-accent-foreground\"\n >\n {@render children?.()}\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 align=\"start\"\n side={sidebar.isMobile ? 'bottom' : 'right'}\n sideOffset={4}\n >\n <DropdownMenu.Label class=\"text-muted-foreground text-xs\">Teams</DropdownMenu.Label>\n {#each teams as team (team.name)}\n <DropdownMenu.Item onSelect={() => switchTeam(team.id)} class=\"gap-2 p-2\">\n <div class=\"flex size-6 items-center justify-center rounded-md border\">\n <UsersIcon class=\"size-3.5 shrink-0\" />\n </div>\n {team.name}\n </DropdownMenu.Item>\n {/each}\n <DropdownMenu.Separator />\n <DropdownMenu.Item class=\"gap-2 p-2\">\n <div class=\"flex size-6 items-center justify-center rounded-md border bg-transparent\">\n <PlusIcon class=\"size-4\" />\n </div>\n <a href=\"/teams/new\" class=\"text-muted-foreground font-medium\">Add team</a>\n </DropdownMenu.Item>\n </DropdownMenu.Content>\n </DropdownMenu.Root>\n </Sidebar.MenuItem>\n</Sidebar.Menu>\n",
4559
4721
  "./creates/src/lib/schemas/team.ts": "import { z } from \"zod\";\n\nexport const teamSchema = z.object({\n name: z.string(),\n});\n",
4560
4722
  "./creates/src/lib/schemas/teamInvite.ts": "import { z } from \"zod\";\n\nexport const teamInviteSchema = z.object({\n email: z.email(),\n});\n",
@@ -4587,15 +4749,15 @@ var uo = {
4587
4749
  "./creates/src/routes/(app)/teams/server.test.ts": "import { describe, it, expect } from \"vitest\";\nimport type { Match } from \"@velastack/pocketbase\";\nimport type { RouteId } from \"./$types\";\n\ndescribe(\"GET /teams\", () => {\n it(\"authenticated user should be able to access the teams page\", async (context) => {\n await context.agent.authenticateUser();\n const response = await context.agent.get(\"/teams\" satisfies Match<RouteId>);\n expect(response.status).toBe(200);\n });\n});\n",
4588
4750
  "./creates/src/routes/(app)/teams/switch/[id]/+page.server.ts": "import { error, redirect } from \"@sveltejs/kit\";\nimport { dev } from \"$app/environment\";\n\nexport const load = async ({ params, cookies, url, locals }) => {\n const { id } = params;\n const redirectUrl = url.searchParams.get(\"redirect\") ?? \"/dashboard\";\n\n try {\n await locals.pb.collection(\"teams\").getOne(id);\n } catch {\n return error(404, { message: \"Team not found\" });\n }\n\n cookies.set(\"team\", id, {\n path: \"/\",\n httpOnly: true,\n sameSite: \"lax\",\n secure: !dev,\n maxAge: 60 * 60 * 24 * 30,\n });\n\n return redirect(303, redirectUrl);\n};\n",
4589
4751
  "./creates/src/routes/(app)/teams/switch/[id]/server.test.ts": "import { describe, it, expect, beforeEach, afterEach } from \"vitest\";\nimport type { Match } from \"@velastack/pocketbase\";\nimport type { RouteId } from \"./$types\";\n\nlet team: { id: string; name: string; owner: string };\n\nbeforeEach(async (context) => {\n await context.agent.authenticateUser();\n\n // Create a test team for the user\n const teamName = `Test Team ${Math.random().toString(36).slice(2)}`;\n team = await context.admin.collection(\"teams\").create({\n name: teamName,\n owner: context.user.id,\n });\n\n // Create team membership\n await context.admin.collection(\"team_memberships\").create({\n user: context.user.id,\n team: team.id,\n role: \"owner\",\n });\n});\n\nafterEach(async (context) => {\n try {\n await context.admin.collection(\"teams\").delete(team.id);\n } catch {}\n});\n\ndescribe(\"GET /teams/switch/[id]\", () => {\n it(\"should set team cookie and redirect to dashboard for valid team\", async (context) => {\n const response = await context.agent.get(\n `/teams/switch/${team.id}` satisfies Match<RouteId>,\n );\n\n expect(response.status).toBe(303);\n expect(response.headers.location).toBe(\"/dashboard\");\n\n // Check that the team cookie is set\n const cookies = response.headers[\"set-cookie\"]?.[0];\n expect(cookies).toBeDefined();\n expect(cookies).toContain(`team=${team.id}`);\n });\n\n it(\"should redirect to custom redirect URL when provided\", async (context) => {\n const customRedirect = \"/teams\";\n const response = await context.agent.get(\n `/teams/switch/${team.id}?redirect=${encodeURIComponent(customRedirect)}` satisfies Match<RouteId>,\n );\n\n expect(response.status).toBe(303);\n expect(response.headers.location).toBe(customRedirect);\n\n // Check that the team cookie is still set\n const cookies = response.headers[\"set-cookie\"]?.[0];\n expect(cookies).toBeDefined();\n expect(cookies).toContain(\"team=\" + team.id);\n });\n\n it(\"should return 404 error for non-existent team\", async (context) => {\n const nonExistentTeamId = \"non-existent-team-id\";\n const response = await context.agent.get(\n `/teams/switch/${nonExistentTeamId}` satisfies Match<RouteId>,\n );\n\n expect(response.status).toBe(404);\n\n const cookies = response.headers[\"set-cookie\"]?.[0];\n expect(cookies).toBeUndefined();\n });\n\n it(\"should return 404 error for invalid team ID format\", async (context) => {\n const invalidTeamId = \"invalid-id-format\";\n const response = await context.agent.get(\n `/teams/switch/${invalidTeamId}` satisfies Match<RouteId>,\n );\n\n expect(response.status).toBe(404);\n\n // Check that no team cookie is set\n const cookies = response.headers[\"set-cookie\"]?.[0];\n expect(cookies).toBeUndefined();\n });\n});\n"
4590
- }), po = "./creates/";
4591
- async function mo(e) {
4752
+ }), wo = "./creates/";
4753
+ async function To(e) {
4592
4754
  return {
4593
- creates: Object.entries(fo).map(([e, n]) => {
4594
- let i = r(e, po);
4755
+ creates: Object.entries(Co).map(([e, t]) => {
4756
+ let r = i(e, wo);
4595
4757
  return {
4596
- path: i,
4597
- language: t(i),
4598
- content: n,
4758
+ path: r,
4759
+ language: n(r),
4760
+ content: t,
4599
4761
  status: "success"
4600
4762
  };
4601
4763
  }).sort((e, t) => e.path.localeCompare(t.path)),
@@ -4615,14 +4777,15 @@ async function mo(e) {
4615
4777
  "dropdown-menu"
4616
4778
  ],
4617
4779
  packages: [],
4618
- collections: []
4780
+ collections: [],
4781
+ collectionPatches: []
4619
4782
  };
4620
4783
  }
4621
4784
  //#endregion
4622
4785
  //#region src/patterns/enable/teams/preview-modifies/src/lib/components/app-sidebar.svelte?raw
4623
- var ho = "<script lang=\"ts\">\n import type { ComponentProps } from 'svelte';\n import HomeIcon from '@lucide/svelte/icons/home';\n import * as Sidebar from '$lib/components/ui/sidebar';\n import NavMain from './nav-main.svelte';\n import NavUser from './nav-user.svelte';\n // [!code highlight:3]\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\n let data = {\n navMain: [\n {\n title: 'Dashboard',\n url: '/dashboard',\n icon: HomeIcon\n }\n ]\n };\n\n let {\n user,\n meta,\n team,\n teams = [],\n ref = $bindable(null),\n ...restProps\n }: ComponentProps<typeof Sidebar.Root> & {\n user: any;\n meta: any;\n team?: string | undefined;\n teams?: { id: string; name: string }[];\n } = $props();\n<\/script>\n\n<Sidebar.Root bind:ref variant=\"inset\" {...restProps}>\n <Sidebar.Header>\n <Sidebar.Menu>\n <TeamSwitcher {teams}>\n {#snippet children()}\n {@const activeTeam = teams.find((t) => t.id === team)}\n {#if activeTeam}\n <Avatar.Root class=\"size-8 rounded-lg\">\n <Avatar.Fallback class=\"rounded-lg bg-primary text-primary-foreground font-medium\">\n {activeTeam.name?.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 {activeTeam.name}\n </span>\n </div>\n {:else}\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 {/if}\n <ChevronsUpDownIcon class=\"ml-auto\" />\n {/snippet}\n </TeamSwitcher>\n </Sidebar.Menu>\n </Sidebar.Header>\n <Sidebar.Content>\n <NavMain items={data.navMain} />\n </Sidebar.Content>\n <Sidebar.Footer>\n <NavUser {user} />\n </Sidebar.Footer>\n</Sidebar.Root>\n", go = "<script lang=\"ts\">\n import { toggleMode, mode } from 'mode-watcher';\n import ChevronsUpDownIcon from '@lucide/svelte/icons/chevrons-up-down';\n import Settings2Icon from '@lucide/svelte/icons/settings-2';\n // [!code highlight:1]\n import UsersIcon from '@lucide/svelte/icons/users';\n import LogOutIcon from '@lucide/svelte/icons/log-out';\n import MoonIcon from '@lucide/svelte/icons/moon';\n import SunIcon from '@lucide/svelte/icons/sun';\n import * as Avatar from '$lib/components/ui/avatar';\n import * as DropdownMenu from '$lib/components/ui/dropdown-menu';\n import * as Sidebar from '$lib/components/ui/sidebar';\n\n let data = {\n navUser: [\n {\n title: 'Settings',\n url: '/settings',\n icon: Settings2Icon\n },\n // [!code highlight:5]\n {\n title: 'Teams',\n url: '/teams',\n icon: UsersIcon\n }\n ]\n };\n\n let {\n user\n }: {\n user: {\n id: string;\n name: string;\n email: string;\n avatar: string;\n };\n } = $props();\n\n const sidebar = Sidebar.useSidebar();\n<\/script>\n\n<Sidebar.Menu>\n <Sidebar.MenuItem>\n <DropdownMenu.Root>\n <DropdownMenu.Trigger>\n {#snippet child({ props })}\n <Sidebar.MenuButton\n size=\"lg\"\n class=\"data-[state=open]:bg-sidebar-accent data-[state=open]:text-sidebar-accent-foreground\"\n {...props}\n >\n <Avatar.Root class=\"size-8 rounded-lg\">\n {#if user.avatar}\n <Avatar.Image src=\"/api/files/users/{user.id}/{user.avatar}\" alt={user.name} />\n {/if}\n <Avatar.Fallback class=\"rounded-lg\">\n {user.email?.charAt(0).toUpperCase()}\n </Avatar.Fallback>\n </Avatar.Root>\n <div class=\"grid flex-1 text-left text-sm leading-tight\">\n <span class=\"truncate font-medium\">{user.name}</span>\n <span class=\"truncate text-xs\">{user.email}</span>\n </div>\n <ChevronsUpDownIcon class=\"ml-auto size-4\" />\n </Sidebar.MenuButton>\n {/snippet}\n </DropdownMenu.Trigger>\n <DropdownMenu.Content\n class=\"w-(--bits-dropdown-menu-anchor-width) min-w-56 rounded-lg\"\n side={sidebar.isMobile ? 'bottom' : 'right'}\n align=\"end\"\n sideOffset={4}\n >\n <DropdownMenu.Label class=\"p-0 font-normal\">\n <div class=\"flex items-center gap-2 px-1 py-1.5 text-left text-sm\">\n <Avatar.Root class=\"size-8 rounded-lg\">\n {#if user.avatar}\n <Avatar.Image src=\"/api/files/users/{user.id}/{user.avatar}\" alt={user.name} />\n {/if}\n <Avatar.Fallback class=\"rounded-lg\">\n {user.email?.charAt(0).toUpperCase()}\n </Avatar.Fallback>\n </Avatar.Root>\n <div class=\"grid flex-1 text-left text-sm leading-tight\">\n <span class=\"truncate font-medium\">{user.name}</span>\n <span class=\"truncate text-xs\">{user.email}</span>\n </div>\n </div>\n </DropdownMenu.Label>\n <DropdownMenu.Separator />\n <DropdownMenu.Group>\n <DropdownMenu.Item onclick={toggleMode}>\n {#if mode.current === 'dark'}\n <SunIcon />\n Light mode\n {:else}\n <MoonIcon />\n Dark mode\n {/if}\n </DropdownMenu.Item>\n {#each data.navUser as item}\n <DropdownMenu.Item class=\"p-0\">\n <a href={item.url} class=\"flex cursor-default items-center gap-2 px-2 py-1.5 w-full\">\n <item.icon />\n {item.title}\n </a>\n </DropdownMenu.Item>\n {/each}\n </DropdownMenu.Group>\n <DropdownMenu.Separator />\n <DropdownMenu.Item class=\"p-0\">\n <form action=\"/logout\" method=\"post\" class=\"w-full\">\n <button type=\"submit\" class=\"flex cursor-default items-center gap-2 px-2 py-1.5 w-full\">\n <LogOutIcon />\n Log out\n </button>\n </form>\n </DropdownMenu.Item>\n </DropdownMenu.Content>\n </DropdownMenu.Root>\n </Sidebar.MenuItem>\n</Sidebar.Menu>\n", _o = "export const load = async ({ locals, depends }) => {\n const user = locals.pb.authStore.record!;\n // [!code highlight:3]\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\n return { user, team, teams, breadcrumbs };\n};\n", vo = "<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 { title: string; url: string }[];\n let { data, children } = $props();\n<\/script>\n\n<div class=\"min-h-dvh dashboard\">\n <Sidebar.Provider>\n <!-- [!code highlight:1] -->\n <AppSidebar user={data.user} meta={data.meta} team={data.team} teams={data.teams ?? []} />\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 orientation=\"vertical\" class=\"mr-2 data-[orientation=vertical]:h-4\" />\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}>{breadcrumb.title}</Breadcrumb.Link>\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", yo = "users", Q = "teams", bo = "team_memberships";
4786
+ var Eo = "<script lang=\"ts\">\n import type { ComponentProps } from 'svelte';\n import HomeIcon from '@lucide/svelte/icons/home';\n import * as Sidebar from '$lib/components/ui/sidebar';\n import NavMain from './nav-main.svelte';\n import NavUser from './nav-user.svelte';\n // [!code highlight:3]\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\n let data = {\n navMain: [\n {\n title: 'Dashboard',\n url: '/dashboard',\n icon: HomeIcon\n }\n ]\n };\n\n let {\n user,\n meta,\n team,\n teams = [],\n ref = $bindable(null),\n ...restProps\n }: ComponentProps<typeof Sidebar.Root> & {\n user: any;\n meta: any;\n team?: string | undefined;\n teams?: { id: string; name: string }[];\n } = $props();\n<\/script>\n\n<Sidebar.Root bind:ref variant=\"inset\" {...restProps}>\n <Sidebar.Header>\n <Sidebar.Menu>\n <TeamSwitcher {teams}>\n {#snippet children()}\n {@const activeTeam = teams.find((t) => t.id === team)}\n {#if activeTeam}\n <Avatar.Root class=\"size-8 rounded-lg\">\n <Avatar.Fallback class=\"rounded-lg bg-primary text-primary-foreground font-medium\">\n {activeTeam.name?.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 {activeTeam.name}\n </span>\n </div>\n {:else}\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 {/if}\n <ChevronsUpDownIcon class=\"ml-auto\" />\n {/snippet}\n </TeamSwitcher>\n </Sidebar.Menu>\n </Sidebar.Header>\n <Sidebar.Content>\n <NavMain items={data.navMain} />\n </Sidebar.Content>\n <Sidebar.Footer>\n <NavUser {user} />\n </Sidebar.Footer>\n</Sidebar.Root>\n", Do = "<script lang=\"ts\">\n import { toggleMode, mode } from 'mode-watcher';\n import ChevronsUpDownIcon from '@lucide/svelte/icons/chevrons-up-down';\n import Settings2Icon from '@lucide/svelte/icons/settings-2';\n // [!code highlight:1]\n import UsersIcon from '@lucide/svelte/icons/users';\n import LogOutIcon from '@lucide/svelte/icons/log-out';\n import MoonIcon from '@lucide/svelte/icons/moon';\n import SunIcon from '@lucide/svelte/icons/sun';\n import * as Avatar from '$lib/components/ui/avatar';\n import * as DropdownMenu from '$lib/components/ui/dropdown-menu';\n import * as Sidebar from '$lib/components/ui/sidebar';\n\n let data = {\n navUser: [\n {\n title: 'Settings',\n url: '/settings',\n icon: Settings2Icon\n },\n // [!code highlight:5]\n {\n title: 'Teams',\n url: '/teams',\n icon: UsersIcon\n }\n ]\n };\n\n let {\n user\n }: {\n user: {\n id: string;\n name: string;\n email: string;\n avatar: string;\n };\n } = $props();\n\n const sidebar = Sidebar.useSidebar();\n<\/script>\n\n<Sidebar.Menu>\n <Sidebar.MenuItem>\n <DropdownMenu.Root>\n <DropdownMenu.Trigger>\n {#snippet child({ props })}\n <Sidebar.MenuButton\n size=\"lg\"\n class=\"data-[state=open]:bg-sidebar-accent data-[state=open]:text-sidebar-accent-foreground\"\n {...props}\n >\n <Avatar.Root class=\"size-8 rounded-lg\">\n {#if user.avatar}\n <Avatar.Image src=\"/api/files/users/{user.id}/{user.avatar}\" alt={user.name} />\n {/if}\n <Avatar.Fallback class=\"rounded-lg\">\n {user.email?.charAt(0).toUpperCase()}\n </Avatar.Fallback>\n </Avatar.Root>\n <div class=\"grid flex-1 text-left text-sm leading-tight\">\n <span class=\"truncate font-medium\">{user.name}</span>\n <span class=\"truncate text-xs\">{user.email}</span>\n </div>\n <ChevronsUpDownIcon class=\"ml-auto size-4\" />\n </Sidebar.MenuButton>\n {/snippet}\n </DropdownMenu.Trigger>\n <DropdownMenu.Content\n class=\"w-(--bits-dropdown-menu-anchor-width) min-w-56 rounded-lg\"\n side={sidebar.isMobile ? 'bottom' : 'right'}\n align=\"end\"\n sideOffset={4}\n >\n <DropdownMenu.Label class=\"p-0 font-normal\">\n <div class=\"flex items-center gap-2 px-1 py-1.5 text-left text-sm\">\n <Avatar.Root class=\"size-8 rounded-lg\">\n {#if user.avatar}\n <Avatar.Image src=\"/api/files/users/{user.id}/{user.avatar}\" alt={user.name} />\n {/if}\n <Avatar.Fallback class=\"rounded-lg\">\n {user.email?.charAt(0).toUpperCase()}\n </Avatar.Fallback>\n </Avatar.Root>\n <div class=\"grid flex-1 text-left text-sm leading-tight\">\n <span class=\"truncate font-medium\">{user.name}</span>\n <span class=\"truncate text-xs\">{user.email}</span>\n </div>\n </div>\n </DropdownMenu.Label>\n <DropdownMenu.Separator />\n <DropdownMenu.Group>\n <DropdownMenu.Item onclick={toggleMode}>\n {#if mode.current === 'dark'}\n <SunIcon />\n Light mode\n {:else}\n <MoonIcon />\n Dark mode\n {/if}\n </DropdownMenu.Item>\n {#each data.navUser as item}\n <DropdownMenu.Item class=\"p-0\">\n <a href={item.url} class=\"flex cursor-default items-center gap-2 px-2 py-1.5 w-full\">\n <item.icon />\n {item.title}\n </a>\n </DropdownMenu.Item>\n {/each}\n </DropdownMenu.Group>\n <DropdownMenu.Separator />\n <DropdownMenu.Item class=\"p-0\">\n <form action=\"/logout\" method=\"post\" class=\"w-full\">\n <button type=\"submit\" class=\"flex cursor-default items-center gap-2 px-2 py-1.5 w-full\">\n <LogOutIcon />\n Log out\n </button>\n </form>\n </DropdownMenu.Item>\n </DropdownMenu.Content>\n </DropdownMenu.Root>\n </Sidebar.MenuItem>\n</Sidebar.Menu>\n", Oo = "export const load = async ({ locals, depends }) => {\n const user = locals.pb.authStore.record!;\n // [!code highlight:3]\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\n return { user, team, teams, breadcrumbs };\n};\n", ko = "<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 { title: string; url: string }[];\n let { data, children } = $props();\n<\/script>\n\n<div class=\"min-h-dvh dashboard\">\n <Sidebar.Provider>\n <!-- [!code highlight:1] -->\n <AppSidebar user={data.user} meta={data.meta} team={data.team} teams={data.teams ?? []} />\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 orientation=\"vertical\" class=\"mr-2 data-[orientation=vertical]:h-4\" />\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}>{breadcrumb.title}</Breadcrumb.Link>\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", Ao = "users", Q = "teams", jo = "team_memberships";
4624
4787
  function $(e) {
4625
- let t = s.find((t) => t.collectionName === e);
4788
+ let t = c.find((t) => t.collectionName === e);
4626
4789
  if (!t) throw Error(`teams: missing TEAM_RULE_PATCHES entry for "${e}"`);
4627
4790
  return {
4628
4791
  listRule: t.listRule,
@@ -4632,7 +4795,7 @@ function $(e) {
4632
4795
  deleteRule: t.deleteRule
4633
4796
  };
4634
4797
  }
4635
- var xo = [
4798
+ var Mo = [
4636
4799
  {
4637
4800
  name: "teams",
4638
4801
  type: "base",
@@ -4657,7 +4820,7 @@ var xo = [
4657
4820
  name: "owner",
4658
4821
  type: "relation",
4659
4822
  cascadeDelete: !1,
4660
- collectionId: yo,
4823
+ collectionId: Ao,
4661
4824
  maxSelect: 1,
4662
4825
  minSelect: 0,
4663
4826
  required: !0
@@ -4703,7 +4866,7 @@ var xo = [
4703
4866
  {
4704
4867
  name: "user",
4705
4868
  cascadeDelete: !0,
4706
- collectionId: yo,
4869
+ collectionId: Ao,
4707
4870
  maxSelect: 1,
4708
4871
  minSelect: 0,
4709
4872
  required: !0,
@@ -4763,7 +4926,7 @@ var xo = [
4763
4926
  {
4764
4927
  name: "membership_id",
4765
4928
  cascadeDelete: !1,
4766
- collectionId: bo,
4929
+ collectionId: jo,
4767
4930
  maxSelect: 1,
4768
4931
  minSelect: 0,
4769
4932
  required: !1,
@@ -4873,44 +5036,45 @@ var xo = [
4873
5036
  }
4874
5037
  ]
4875
5038
  }
4876
- ], So = /* @__PURE__ */ Object.assign({
4877
- "./preview-modifies/src/lib/components/app-sidebar.svelte": ho,
4878
- "./preview-modifies/src/lib/components/nav-user.svelte": go,
4879
- "./preview-modifies/src/routes/(app)/+layout.server.ts": _o,
4880
- "./preview-modifies/src/routes/(app)/+layout.svelte": vo
4881
- }), Co = "./preview-modifies/";
4882
- async function wo(e) {
5039
+ ], No = /* @__PURE__ */ Object.assign({
5040
+ "./preview-modifies/src/lib/components/app-sidebar.svelte": Eo,
5041
+ "./preview-modifies/src/lib/components/nav-user.svelte": Do,
5042
+ "./preview-modifies/src/routes/(app)/+layout.server.ts": Oo,
5043
+ "./preview-modifies/src/routes/(app)/+layout.svelte": ko
5044
+ }), Po = "./preview-modifies/";
5045
+ async function Fo(e) {
4883
5046
  return {
4884
5047
  creates: [],
4885
- modifies: Object.entries(So).map(([e, n]) => {
4886
- let i = r(e, Co);
5048
+ modifies: Object.entries(No).map(([e, t]) => {
5049
+ let r = i(e, Po);
4887
5050
  return {
4888
- path: i,
4889
- language: t(i),
4890
- content: n,
5051
+ path: r,
5052
+ language: n(r),
5053
+ content: t,
4891
5054
  status: "success"
4892
5055
  };
4893
5056
  }).sort((e, t) => e.path.localeCompare(t.path)),
4894
5057
  deletes: [],
4895
5058
  components: [],
4896
5059
  packages: [],
4897
- collections: xo
5060
+ collections: Mo,
5061
+ collectionPatches: []
4898
5062
  };
4899
5063
  }
4900
5064
  //#endregion
4901
5065
  //#region src/patterns/enable/teams/index.ts
4902
- var To = "enable-teams", Eo = "1.0.0", Do = "src/patterns/enable/teams", Oo = "/enable/teams";
4903
- async function ko(e) {
4904
- let t = await mo(e);
4905
- if (e.env === "preview") return v(n([t, await wo(e)]));
4906
- let { generate: r } = await import("./chunks/generate.runtime-B8_5O6Qr.js"), i = await r(e), { writeResult: a } = await import("./chunks/write-result-ENWLDQtP.js");
4907
- return a(await v(n([t, i])), e);
4908
- }
4909
- var Ao = {
4910
- version: Eo,
4911
- slug: To,
4912
- source: Do,
4913
- docs: Oo,
5066
+ var Io = "enable-teams", Lo = "1.0.0", Ro = "src/patterns/enable/teams", zo = "/enable/teams";
5067
+ async function Bo(e) {
5068
+ let t = await To(e);
5069
+ if (e.env === "preview") return _(r([t, await Fo(e)]));
5070
+ let { generate: n } = await import("./chunks/generate.runtime-uk9-KOP-.js"), i = await n(e), { writeResult: a } = await import("./chunks/write-result-C80dpjr-.js");
5071
+ return a(await _(r([t, i])), e);
5072
+ }
5073
+ var Vo = {
5074
+ version: Lo,
5075
+ slug: Io,
5076
+ source: Ro,
5077
+ docs: zo,
4914
5078
  plan: "pro",
4915
5079
  title: "Enable teams",
4916
5080
  summary: "Adds multi-tenant teams with memberships, invites, and a sidebar team switcher.",
@@ -4939,26 +5103,27 @@ var Ao = {
4939
5103
  examples: [],
4940
5104
  tests: 36,
4941
5105
  baseline: "velastack",
4942
- generate: ko
4943
- }, jo = re.version, Mo = [
5106
+ generate: Bo
5107
+ }, Ho = ie.version, Uo = [
4944
5108
  Jt,
4945
5109
  Cn,
4946
- Kr,
4947
- Mn,
4948
- ir,
4949
- Lr,
4950
- ii,
4951
- gi,
4952
- Oi,
4953
- Bi,
4954
- Qi,
4955
- uo,
4956
- Ao
4957
- ], No = Object.fromEntries(Mo.map((e) => [e.slug, e])), Po = Mo.reduce((e, t) => {
5110
+ Pn,
5111
+ ri,
5112
+ Un,
5113
+ hr,
5114
+ Jr,
5115
+ hi,
5116
+ Di,
5117
+ zi,
5118
+ Zi,
5119
+ la,
5120
+ So,
5121
+ Vo
5122
+ ], Wo = Object.fromEntries(Uo.map((e) => [e.slug, e])), Go = Uo.reduce((e, t) => {
4958
5123
  let n = t.category;
4959
5124
  return e[n] ??= [], e[n].push(t), e;
4960
5125
  }, {});
4961
5126
  //#endregion
4962
- export { _ as InvalidArgumentError, Po as byCategory, No as bySlug, Mo as patterns, jo as version };
5127
+ export { e as InvalidArgumentError, Go as byCategory, Wo as bySlug, Uo as patterns, Ho as version };
4963
5128
 
4964
5129
  //# sourceMappingURL=index.js.map