@velastack/patterns 0.0.26 → 0.0.28
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunks/{collections-DdGJC7Ip.js → collections-CwH8DO-2.js} +2 -2
- package/dist/chunks/{collections-DdGJC7Ip.js.map → collections-CwH8DO-2.js.map} +1 -1
- package/dist/chunks/{env.preview-Cpr4Im0G.js → env.preview-kw0hC6y8.js} +1 -1
- package/dist/chunks/{env.preview-Cpr4Im0G.js.map → env.preview-kw0hC6y8.js.map} +1 -1
- package/dist/chunks/{env.runtime-iw-bWvXM.js → env.runtime-CJS54CZX.js} +1 -1
- package/dist/chunks/{env.runtime-iw-bWvXM.js.map → env.runtime-CJS54CZX.js.map} +1 -1
- package/dist/chunks/{generate.runtime-Bt6kbkWX.js → generate.runtime-B3WXGKZY.js} +4 -4
- package/dist/chunks/{generate.runtime-Bt6kbkWX.js.map → generate.runtime-B3WXGKZY.js.map} +1 -1
- package/dist/chunks/{generate.runtime-B0EfMNMf.js → generate.runtime-BS_l-k-A.js} +6 -6
- package/dist/chunks/{generate.runtime-B0EfMNMf.js.map → generate.runtime-BS_l-k-A.js.map} +1 -1
- package/dist/chunks/{generate.runtime-BtGvtuWm.js → generate.runtime-Bhqdiykw.js} +2 -2
- package/dist/chunks/{generate.runtime-BtGvtuWm.js.map → generate.runtime-Bhqdiykw.js.map} +1 -1
- package/dist/chunks/{generate.runtime-DiJDMdAq.js → generate.runtime-CzKWz6BN.js} +4 -4
- package/dist/chunks/{generate.runtime-DiJDMdAq.js.map → generate.runtime-CzKWz6BN.js.map} +1 -1
- package/dist/chunks/{generate.runtime-CcKMIm9M.js → generate.runtime-DVRoiEhh.js} +2 -2
- package/dist/chunks/{generate.runtime-CcKMIm9M.js.map → generate.runtime-DVRoiEhh.js.map} +1 -1
- package/dist/chunks/generate.runtime-V7jzalbO.js +602 -0
- package/dist/chunks/generate.runtime-V7jzalbO.js.map +1 -0
- package/dist/chunks/{modify-file-Dxow9QKT.js → modify-file-Drki52pc.js} +1 -1
- package/dist/chunks/{modify-file-Dxow9QKT.js.map → modify-file-Drki52pc.js.map} +1 -1
- package/dist/chunks/{pocketbase-CSl9ydRr.js → pocketbase-CDu4GzZD.js} +1 -1
- package/dist/chunks/{pocketbase-CSl9ydRr.js.map → pocketbase-CDu4GzZD.js.map} +1 -1
- package/dist/chunks/{pocketbase-CPRrN7Qs.js → pocketbase-CmKcAXDf.js} +1 -1
- package/dist/chunks/{pocketbase-CPRrN7Qs.js.map → pocketbase-CmKcAXDf.js.map} +1 -1
- package/dist/chunks/taggedTemplateLiteral-BLWebVbJ.js +6 -0
- package/dist/chunks/{ts-morph-helpers-DmD7iwna.js → ts-morph-helpers-BMxk6lHK.js} +1 -1
- package/dist/chunks/{ts-morph-helpers-DmD7iwna.js.map → ts-morph-helpers-BMxk6lHK.js.map} +1 -1
- package/dist/chunks/{write-result-DhQIE6kA.js → write-result-C3SCX65t.js} +1 -1
- package/dist/chunks/{write-result-DhQIE6kA.js.map → write-result-C3SCX65t.js.map} +1 -1
- package/dist/index.d.ts +197 -17
- package/dist/index.js +1652 -561
- package/dist/index.js.map +1 -1
- package/package.json +6 -1
package/dist/index.js
CHANGED
|
@@ -1,25 +1,26 @@
|
|
|
1
1
|
import { t as e } from "./chunks/dedent-BFNYR8cb.js";
|
|
2
2
|
import { n as t, r as n, t as r } from "./chunks/util-k-qPjL06.js";
|
|
3
3
|
import { i, t as a } from "./chunks/constants-B5Ub2oFy.js";
|
|
4
|
-
import { t as o } from "./chunks/
|
|
5
|
-
import s from "
|
|
6
|
-
import c from "prettier
|
|
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";
|
|
7
8
|
//#region \0rolldown/runtime.js
|
|
8
|
-
var
|
|
9
|
-
if (t && typeof t == "object" || typeof t == "function") for (var i =
|
|
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
11
|
get: ((e) => t[e]).bind(null, s),
|
|
11
|
-
enumerable: !(r =
|
|
12
|
+
enumerable: !(r = f(t, s)) || r.enumerable
|
|
12
13
|
});
|
|
13
14
|
return e;
|
|
14
|
-
},
|
|
15
|
+
}, te = (e, t, n) => (n = e == null ? {} : u(m(e)), g(t || !e || !e.__esModule ? d(n, "default", {
|
|
15
16
|
value: e,
|
|
16
17
|
enumerable: !0
|
|
17
|
-
}) : n, e)),
|
|
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) {
|
|
18
19
|
if (typeof require < "u") return require.apply(this, arguments);
|
|
19
20
|
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.");
|
|
20
|
-
}),
|
|
21
|
+
}), re = {
|
|
21
22
|
name: "@velastack/patterns",
|
|
22
|
-
version: "0.0.
|
|
23
|
+
version: "0.0.28",
|
|
23
24
|
type: "module",
|
|
24
25
|
private: !1,
|
|
25
26
|
main: "./dist/index.js",
|
|
@@ -48,6 +49,7 @@ var l = Object.create, u = Object.defineProperty, d = Object.getOwnPropertyDescr
|
|
|
48
49
|
"magic-string": "^0.30.21",
|
|
49
50
|
"package-manager-detector": "^1.6.0",
|
|
50
51
|
pocketbase: "^0.26.8",
|
|
52
|
+
stripe: "^19.0.0",
|
|
51
53
|
svelte: "^5.55.4",
|
|
52
54
|
"ts-morph": "^28.0.0"
|
|
53
55
|
},
|
|
@@ -57,6 +59,7 @@ var l = Object.create, u = Object.defineProperty, d = Object.getOwnPropertyDescr
|
|
|
57
59
|
"magic-string": { optional: !0 },
|
|
58
60
|
"package-manager-detector": { optional: !0 },
|
|
59
61
|
pocketbase: { optional: !0 },
|
|
62
|
+
stripe: { optional: !0 },
|
|
60
63
|
svelte: { optional: !0 },
|
|
61
64
|
"ts-morph": { optional: !0 }
|
|
62
65
|
},
|
|
@@ -72,6 +75,7 @@ var l = Object.create, u = Object.defineProperty, d = Object.getOwnPropertyDescr
|
|
|
72
75
|
"package-manager-detector": "^1.6.0",
|
|
73
76
|
pluralize: "^8.0.0",
|
|
74
77
|
pocketbase: "^0.26.8",
|
|
78
|
+
stripe: "^19.3.0",
|
|
75
79
|
svelte: "^5.55.4",
|
|
76
80
|
"ts-morph": "^28.0.0",
|
|
77
81
|
typescript: "^5.0.0",
|
|
@@ -80,22 +84,22 @@ var l = Object.create, u = Object.defineProperty, d = Object.getOwnPropertyDescr
|
|
|
80
84
|
"vite-plugin-dts": "^4.5.4",
|
|
81
85
|
vitest: "^4.1.4"
|
|
82
86
|
}
|
|
83
|
-
},
|
|
87
|
+
}, _ = class extends Error {
|
|
84
88
|
constructor(e) {
|
|
85
89
|
super(e), this.name = "InvalidArgumentError";
|
|
86
90
|
}
|
|
87
91
|
};
|
|
88
92
|
//#endregion
|
|
89
93
|
//#region src/core/format-result.ts
|
|
90
|
-
function
|
|
94
|
+
function ie(e) {
|
|
91
95
|
return e.language === "ts" || e.language === "svelte" || e.path.endsWith(".json");
|
|
92
96
|
}
|
|
93
|
-
async function
|
|
94
|
-
if (e.status !== "success" || !
|
|
97
|
+
async function ae(e) {
|
|
98
|
+
if (e.status !== "success" || !ie(e)) return e;
|
|
95
99
|
try {
|
|
96
|
-
let t = await
|
|
100
|
+
let t = await c.format(e.content, {
|
|
97
101
|
filepath: e.path,
|
|
98
|
-
plugins: [
|
|
102
|
+
plugins: [l]
|
|
99
103
|
});
|
|
100
104
|
return {
|
|
101
105
|
...e,
|
|
@@ -105,11 +109,11 @@ async function ne(e) {
|
|
|
105
109
|
return e;
|
|
106
110
|
}
|
|
107
111
|
}
|
|
108
|
-
async function
|
|
109
|
-
return Promise.all(e.map((e) =>
|
|
112
|
+
async function oe(e) {
|
|
113
|
+
return Promise.all(e.map((e) => ae(e)));
|
|
110
114
|
}
|
|
111
|
-
async function
|
|
112
|
-
let [t, n] = await Promise.all([
|
|
115
|
+
async function v(e) {
|
|
116
|
+
let [t, n] = await Promise.all([oe(e.creates), oe(e.modifies)]);
|
|
113
117
|
return {
|
|
114
118
|
...e,
|
|
115
119
|
creates: t,
|
|
@@ -118,7 +122,7 @@ async function b(e) {
|
|
|
118
122
|
}
|
|
119
123
|
//#endregion
|
|
120
124
|
//#region src/core/field/index.ts
|
|
121
|
-
var
|
|
125
|
+
var se = {
|
|
122
126
|
text: ["form", "input"],
|
|
123
127
|
number: ["form", "input"],
|
|
124
128
|
email: ["form", "input"],
|
|
@@ -138,7 +142,7 @@ var ie = {
|
|
|
138
142
|
url: ["form", "input"],
|
|
139
143
|
editor: ["form", "textarea"],
|
|
140
144
|
autodate: ["form", "input"]
|
|
141
|
-
},
|
|
145
|
+
}, ce = {
|
|
142
146
|
form: ["import * as Form from \"$lib/components/ui/form\";"],
|
|
143
147
|
"file-form": ["import * as FileForm from \"$lib/components/ui/file-form\";"],
|
|
144
148
|
multiselect: ["import * as MultiSelect from \"$lib/components/ui/multiselect\";", "import * as Command from \"$lib/components/ui/command\";"],
|
|
@@ -149,13 +153,13 @@ var ie = {
|
|
|
149
153
|
geopoint: ["import { GeopointInput } from \"$lib/components/ui/geopoint\";"],
|
|
150
154
|
button: ["import { Button } from \"$lib/components/ui/button\";"]
|
|
151
155
|
};
|
|
152
|
-
function
|
|
156
|
+
function y(e) {
|
|
153
157
|
return `$formData.${e.name}`;
|
|
154
158
|
}
|
|
155
|
-
function
|
|
159
|
+
function b(e) {
|
|
156
160
|
return e.inputProps ? Object.entries(e.inputProps).flatMap(([e, t]) => t == null || t === !1 ? [] : t === !0 ? [` ${e}`] : [` ${e}=${JSON.stringify(String(t))}`]).join("") : "";
|
|
157
161
|
}
|
|
158
|
-
function
|
|
162
|
+
function x(t) {
|
|
159
163
|
return t.labelAside ? e`
|
|
160
164
|
<div class="flex justify-between">
|
|
161
165
|
<Form.Label>${t.title}</Form.Label>
|
|
@@ -163,68 +167,68 @@ function C(t) {
|
|
|
163
167
|
</div>
|
|
164
168
|
` : `<Form.Label>${t.title}</Form.Label>`;
|
|
165
169
|
}
|
|
166
|
-
function
|
|
170
|
+
function S(t, n) {
|
|
167
171
|
let r = t.required ? " required" : "";
|
|
168
172
|
return e`
|
|
169
173
|
<Form.Field {form} name="${t.name}" class="col-span-1">
|
|
170
174
|
<Form.Control>
|
|
171
175
|
{#snippet children({ props })}
|
|
172
|
-
${
|
|
173
|
-
<Input {...props} type="${n}" bind:value={${
|
|
176
|
+
${x(t)}
|
|
177
|
+
<Input {...props} type="${n}" bind:value={${y(t)}}${r}${b(t)} />
|
|
174
178
|
{/snippet}
|
|
175
179
|
</Form.Control>
|
|
176
180
|
<Form.FieldErrors class="contents text-destructive" />
|
|
177
181
|
</Form.Field>
|
|
178
182
|
`;
|
|
179
183
|
}
|
|
180
|
-
function
|
|
184
|
+
function le(t) {
|
|
181
185
|
let n = t.required ? " required" : "";
|
|
182
186
|
return e`
|
|
183
187
|
<Form.Field {form} name="${t.name}" class="col-span-2">
|
|
184
188
|
<Form.Control>
|
|
185
189
|
{#snippet children({ props })}
|
|
186
|
-
${
|
|
187
|
-
<Textarea {...props} bind:value={${
|
|
190
|
+
${x(t)}
|
|
191
|
+
<Textarea {...props} bind:value={${y(t)}}${n}${b(t)} />
|
|
188
192
|
{/snippet}
|
|
189
193
|
</Form.Control>
|
|
190
194
|
<Form.FieldErrors class="contents text-destructive" />
|
|
191
195
|
</Form.Field>
|
|
192
196
|
`;
|
|
193
197
|
}
|
|
194
|
-
function
|
|
198
|
+
function ue(t) {
|
|
195
199
|
let n = t.required ? " required" : "";
|
|
196
200
|
return e`
|
|
197
201
|
<Form.Field {form} name="${t.name}" class="col-span-1 flex items-start space-x-2">
|
|
198
202
|
<Form.Control>
|
|
199
203
|
{#snippet children({ props })}
|
|
200
|
-
<Checkbox {...props} bind:checked={${
|
|
201
|
-
${
|
|
204
|
+
<Checkbox {...props} bind:checked={${y(t)}}${n}${b(t)} />
|
|
205
|
+
${x(t)}
|
|
202
206
|
{/snippet}
|
|
203
207
|
</Form.Control>
|
|
204
208
|
<Form.FieldErrors class="contents text-destructive" />
|
|
205
209
|
</Form.Field>
|
|
206
210
|
`;
|
|
207
211
|
}
|
|
208
|
-
function
|
|
212
|
+
function de(t) {
|
|
209
213
|
return e`
|
|
210
214
|
<Form.Field {form} name="${t.name}" class="col-span-1">
|
|
211
215
|
<Form.Control>
|
|
212
216
|
{#snippet children({ props })}
|
|
213
|
-
${
|
|
214
|
-
<GeopointInput {...props} bind:value={${
|
|
217
|
+
${x(t)}
|
|
218
|
+
<GeopointInput {...props} bind:value={${y(t)}} />
|
|
215
219
|
{/snippet}
|
|
216
220
|
</Form.Control>
|
|
217
221
|
<Form.FieldErrors class="contents text-destructive" />
|
|
218
222
|
</Form.Field>
|
|
219
223
|
`;
|
|
220
224
|
}
|
|
221
|
-
function
|
|
225
|
+
function fe(t) {
|
|
222
226
|
let n = t.required ? " required" : "", r = t.maxSelect > 1 ? "Multiple" : "Single";
|
|
223
227
|
return e`
|
|
224
228
|
<FileForm.Field {form} name="${t.name}" class="col-span-1">
|
|
225
229
|
<Form.Control>
|
|
226
230
|
{#snippet children({ props })}
|
|
227
|
-
${
|
|
231
|
+
${x(t)}
|
|
228
232
|
<FileForm.${r}>
|
|
229
233
|
{#snippet display({ file, filename, onremove })}
|
|
230
234
|
<div class="flex gap-2 justify-between items-center">
|
|
@@ -236,7 +240,7 @@ function le(t) {
|
|
|
236
240
|
</div>
|
|
237
241
|
{/snippet}
|
|
238
242
|
{#snippet input()}
|
|
239
|
-
<FileForm.Input {...props}${n}${
|
|
243
|
+
<FileForm.Input {...props}${n}${b(t)} />
|
|
240
244
|
{/snippet}
|
|
241
245
|
</FileForm.${r}>
|
|
242
246
|
{/snippet}
|
|
@@ -245,15 +249,15 @@ function le(t) {
|
|
|
245
249
|
</FileForm.Field>
|
|
246
250
|
`;
|
|
247
251
|
}
|
|
248
|
-
function
|
|
252
|
+
function pe(t) {
|
|
249
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 ");
|
|
250
254
|
return e`
|
|
251
255
|
<MultiSelect.Field {form} type="${n}" name="${t.name}"${r} class="col-span-1">
|
|
252
256
|
<Form.Control>
|
|
253
257
|
{#snippet children({ props })}
|
|
254
|
-
${
|
|
258
|
+
${x(t)}
|
|
255
259
|
<MultiSelect.Trigger class="w-full justify-between">
|
|
256
|
-
<MultiSelect.Input bind:value={${
|
|
260
|
+
<MultiSelect.Input bind:value={${y(t)}} placeholder="${i}" {...props}>
|
|
257
261
|
{#snippet children({ selected })}
|
|
258
262
|
<div class="flex flex-wrap gap-1">
|
|
259
263
|
{#each selected as value}
|
|
@@ -280,7 +284,7 @@ function ue(t) {
|
|
|
280
284
|
</MultiSelect.Field>
|
|
281
285
|
`;
|
|
282
286
|
}
|
|
283
|
-
function
|
|
287
|
+
function me(t) {
|
|
284
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;
|
|
285
289
|
return e`
|
|
286
290
|
<MultiSelect.Field {form} type="${n}" name="${t.name}" class="col-span-1">
|
|
@@ -288,7 +292,7 @@ function de(t) {
|
|
|
288
292
|
{#snippet children({ props })}
|
|
289
293
|
<Form.Label>${t.title}</Form.Label>
|
|
290
294
|
<MultiSelect.Trigger class="w-full justify-between">
|
|
291
|
-
<MultiSelect.Input bind:value={${
|
|
295
|
+
<MultiSelect.Input bind:value={${y(t)}} placeholder="${r}" {...props}>
|
|
292
296
|
{#snippet children({ selected })}
|
|
293
297
|
<div class="flex flex-wrap gap-1">
|
|
294
298
|
{#each selected as value}
|
|
@@ -318,39 +322,39 @@ function de(t) {
|
|
|
318
322
|
</MultiSelect.Field>
|
|
319
323
|
`;
|
|
320
324
|
}
|
|
321
|
-
function
|
|
325
|
+
function he(t) {
|
|
322
326
|
return e`
|
|
323
327
|
<Form.Field {form} name="${t.name}" class="col-span-1">
|
|
324
328
|
<Form.Control>
|
|
325
329
|
{#snippet children({ props })}
|
|
326
|
-
${
|
|
327
|
-
<Input {...props} type="text" value={${
|
|
330
|
+
${x(t)}
|
|
331
|
+
<Input {...props} type="text" value={${y(t)}}${b(t)} readonly />
|
|
328
332
|
{/snippet}
|
|
329
333
|
</Form.Control>
|
|
330
334
|
<Form.FieldErrors class="contents text-destructive" />
|
|
331
335
|
</Form.Field>
|
|
332
336
|
`;
|
|
333
337
|
}
|
|
334
|
-
function
|
|
338
|
+
function C(e) {
|
|
335
339
|
switch (e.type) {
|
|
336
|
-
case "text": return
|
|
337
|
-
case "number": return
|
|
338
|
-
case "date": return
|
|
339
|
-
case "email": return
|
|
340
|
-
case "password": return
|
|
341
|
-
case "url": return
|
|
342
|
-
case "autodate": return
|
|
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);
|
|
343
347
|
case "editor":
|
|
344
|
-
case "json": return
|
|
345
|
-
case "bool": return
|
|
346
|
-
case "geoPoint": return
|
|
347
|
-
case "file": return
|
|
348
|
-
case "select": return
|
|
349
|
-
case "relation": return
|
|
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);
|
|
350
354
|
default: return e;
|
|
351
355
|
}
|
|
352
356
|
}
|
|
353
|
-
function
|
|
357
|
+
function w(t) {
|
|
354
358
|
let n = t.options.map((t) => e`
|
|
355
359
|
${JSON.stringify(t.value)}: {
|
|
356
360
|
label: ${JSON.stringify(t.label)},
|
|
@@ -363,17 +367,17 @@ function pe(t) {
|
|
|
363
367
|
} as const;
|
|
364
368
|
`;
|
|
365
369
|
}
|
|
366
|
-
function
|
|
367
|
-
let t = e.flatMap((e) =>
|
|
370
|
+
function T(e) {
|
|
371
|
+
let t = e.flatMap((e) => se[e.type]);
|
|
368
372
|
return [...new Set(t)];
|
|
369
373
|
}
|
|
370
|
-
function
|
|
371
|
-
return [...new Set(e.flatMap((e) =>
|
|
374
|
+
function ge(e) {
|
|
375
|
+
return [...new Set(e.flatMap((e) => ce[e]))];
|
|
372
376
|
}
|
|
373
|
-
function
|
|
377
|
+
function E(e, t) {
|
|
374
378
|
return `data.${e.name}.${t.name}`;
|
|
375
379
|
}
|
|
376
|
-
function
|
|
380
|
+
function _e(t, n, r) {
|
|
377
381
|
return e`
|
|
378
382
|
<div class="space-y-2">
|
|
379
383
|
<h3 class="font-medium leading-none">${n.title}</h3>
|
|
@@ -381,8 +385,8 @@ function k(t, n, r) {
|
|
|
381
385
|
</div>
|
|
382
386
|
`;
|
|
383
387
|
}
|
|
384
|
-
function
|
|
385
|
-
let r =
|
|
388
|
+
function ve(t, n) {
|
|
389
|
+
let r = E(t, n), i = `<p class="text-muted-foreground">{new Date(${r}).toLocaleDateString()}</p>`, a = n.required ? i : e`
|
|
386
390
|
{#if ${r}}
|
|
387
391
|
${i}
|
|
388
392
|
{/if}
|
|
@@ -394,8 +398,8 @@ function me(t, n) {
|
|
|
394
398
|
</div>
|
|
395
399
|
`;
|
|
396
400
|
}
|
|
397
|
-
function
|
|
398
|
-
let r =
|
|
401
|
+
function ye(t, n) {
|
|
402
|
+
let r = E(t, n), i = e`
|
|
399
403
|
<a href={${r}} target="_blank" rel="noopener noreferrer">
|
|
400
404
|
{${r}}
|
|
401
405
|
</a>
|
|
@@ -413,8 +417,8 @@ function he(t, n) {
|
|
|
413
417
|
</div>
|
|
414
418
|
`;
|
|
415
419
|
}
|
|
416
|
-
function
|
|
417
|
-
let r =
|
|
420
|
+
function be(t, n) {
|
|
421
|
+
let r = E(t, n);
|
|
418
422
|
if (n.maxSelect > 1) return e`
|
|
419
423
|
<div class="space-y-2">
|
|
420
424
|
<h3 class="font-medium leading-none">${n.title}</h3>
|
|
@@ -435,8 +439,8 @@ function ge(t, n) {
|
|
|
435
439
|
</div>
|
|
436
440
|
`;
|
|
437
441
|
}
|
|
438
|
-
function
|
|
439
|
-
let r =
|
|
442
|
+
function xe(t, n) {
|
|
443
|
+
let r = E(t, n);
|
|
440
444
|
return n.maxSelect > 1 ? e`
|
|
441
445
|
<div class="space-y-2">
|
|
442
446
|
<h3 class="font-medium leading-none">${n.title}</h3>
|
|
@@ -481,11 +485,11 @@ function _e(t, n) {
|
|
|
481
485
|
</div>
|
|
482
486
|
`;
|
|
483
487
|
}
|
|
484
|
-
function
|
|
488
|
+
function Se(e) {
|
|
485
489
|
return `/${e.relatedModel.routeSegment}`;
|
|
486
490
|
}
|
|
487
|
-
function
|
|
488
|
-
let r = `data.${t.name}.expand?.${n.name}`, i =
|
|
491
|
+
function Ce(t, n) {
|
|
492
|
+
let r = `data.${t.name}.expand?.${n.name}`, i = Se(n);
|
|
489
493
|
return n.maxSelect > 1 ? e`
|
|
490
494
|
<div class="space-y-2">
|
|
491
495
|
<h3 class="font-medium leading-none">${n.title}</h3>
|
|
@@ -512,8 +516,8 @@ function ye(t, n) {
|
|
|
512
516
|
</div>
|
|
513
517
|
`;
|
|
514
518
|
}
|
|
515
|
-
function
|
|
516
|
-
let r =
|
|
519
|
+
function we(t, n) {
|
|
520
|
+
let r = E(t, n), i = e`
|
|
517
521
|
{#await import("$lib/components/ui/leaflet/leaflet.svelte")}
|
|
518
522
|
<div class="h-56.25 w-full bg-input rounded-md"></div>
|
|
519
523
|
{:then { default: Leaflet }}
|
|
@@ -534,12 +538,12 @@ function be(t, n) {
|
|
|
534
538
|
</div>
|
|
535
539
|
`;
|
|
536
540
|
}
|
|
537
|
-
function
|
|
541
|
+
function Te(t, n) {
|
|
538
542
|
switch (n.type) {
|
|
539
543
|
case "text":
|
|
540
544
|
case "number":
|
|
541
545
|
case "email":
|
|
542
|
-
case "editor": return
|
|
546
|
+
case "editor": return _e(t, n, `{${E(t, n)}}`);
|
|
543
547
|
case "password": return e`
|
|
544
548
|
<div class="space-y-2">
|
|
545
549
|
<h3 class="font-medium leading-none">${n.title}</h3>
|
|
@@ -548,34 +552,34 @@ function xe(t, n) {
|
|
|
548
552
|
</p>
|
|
549
553
|
</div>
|
|
550
554
|
`;
|
|
551
|
-
case "bool": return
|
|
555
|
+
case "bool": return _e(t, n, `{${E(t, n)} ? "Yes" : "No"}`);
|
|
552
556
|
case "date":
|
|
553
|
-
case "autodate": return
|
|
554
|
-
case "url": return
|
|
555
|
-
case "select": return
|
|
556
|
-
case "file": return
|
|
557
|
-
case "json": return
|
|
558
|
-
case "geoPoint": return
|
|
559
|
-
case "relation": return
|
|
557
|
+
case "autodate": return ve(t, n);
|
|
558
|
+
case "url": return ye(t, n);
|
|
559
|
+
case "select": return be(t, n);
|
|
560
|
+
case "file": return xe(t, n);
|
|
561
|
+
case "json": return _e(t, n, `{JSON.stringify(${E(t, n)})}`);
|
|
562
|
+
case "geoPoint": return we(t, n);
|
|
563
|
+
case "relation": return Ce(t, n);
|
|
560
564
|
default: return n;
|
|
561
565
|
}
|
|
562
566
|
}
|
|
563
567
|
//#endregion
|
|
564
568
|
//#region node_modules/change-case/dist/index.js
|
|
565
|
-
var
|
|
566
|
-
function
|
|
569
|
+
var Ee = /([\p{Ll}\d])(\p{Lu})/gu, De = /(\p{Lu})([\p{Lu}][\p{Ll}])/gu, Oe = /(\d)\p{Ll}|(\p{L})\d/u, ke = /[^\p{L}\d]+/giu, Ae = "$1\0$2", je = "";
|
|
570
|
+
function Me(e) {
|
|
567
571
|
let t = e.trim();
|
|
568
|
-
t = t.replace(
|
|
572
|
+
t = t.replace(Ee, Ae).replace(De, Ae), t = t.replace(ke, "\0");
|
|
569
573
|
let n = 0, r = t.length;
|
|
570
574
|
for (; t.charAt(n) === "\0";) n++;
|
|
571
575
|
if (n === r) return [];
|
|
572
576
|
for (; t.charAt(r - 1) === "\0";) r--;
|
|
573
577
|
return t.slice(n, r).split(/\0/g);
|
|
574
578
|
}
|
|
575
|
-
function
|
|
576
|
-
let t =
|
|
579
|
+
function Ne(e) {
|
|
580
|
+
let t = Me(e);
|
|
577
581
|
for (let e = 0; e < t.length; e++) {
|
|
578
|
-
let n = t[e], r =
|
|
582
|
+
let n = t[e], r = Oe.exec(n);
|
|
579
583
|
if (r) {
|
|
580
584
|
let i = r.index + (r[1] ?? r[2]).length;
|
|
581
585
|
t.splice(e, 1, n.slice(0, i), n.slice(i));
|
|
@@ -583,51 +587,51 @@ function ke(e) {
|
|
|
583
587
|
}
|
|
584
588
|
return t;
|
|
585
589
|
}
|
|
586
|
-
function
|
|
587
|
-
let [n, r, i] =
|
|
588
|
-
return n + r.map(
|
|
590
|
+
function Pe(e, t) {
|
|
591
|
+
let [n, r, i] = k(e, t);
|
|
592
|
+
return n + r.map(O(t?.locale)).join(t?.delimiter ?? " ") + i;
|
|
589
593
|
}
|
|
590
|
-
function
|
|
591
|
-
let [n, r, i] =
|
|
594
|
+
function D(e, t) {
|
|
595
|
+
let [n, r, i] = k(e, t), a = O(t?.locale), o = ze(t?.locale), s = t?.mergeAmbiguousCharacters ? Be(a, o) : Ve(a, o);
|
|
592
596
|
return n + r.map((e, t) => t === 0 ? a(e) : s(e, t)).join(t?.delimiter ?? "") + i;
|
|
593
597
|
}
|
|
594
|
-
function
|
|
595
|
-
let [n, r, i] =
|
|
598
|
+
function Fe(e, t) {
|
|
599
|
+
let [n, r, i] = k(e, t), a = O(t?.locale), o = ze(t?.locale), s = t?.mergeAmbiguousCharacters ? Be(a, o) : Ve(a, o);
|
|
596
600
|
return n + r.map(s).join(t?.delimiter ?? "") + i;
|
|
597
601
|
}
|
|
598
|
-
function
|
|
599
|
-
let [n, r, i] =
|
|
600
|
-
return n + r.map(
|
|
602
|
+
function Ie(e, t) {
|
|
603
|
+
let [n, r, i] = k(e, t), a = O(t?.locale), o = ze(t?.locale);
|
|
604
|
+
return n + r.map(Be(a, o)).join(t?.delimiter ?? " ") + i;
|
|
601
605
|
}
|
|
602
|
-
function
|
|
603
|
-
return
|
|
606
|
+
function Le(e, t) {
|
|
607
|
+
return Pe(e, {
|
|
604
608
|
delimiter: "-",
|
|
605
609
|
...t
|
|
606
610
|
});
|
|
607
611
|
}
|
|
608
|
-
function
|
|
609
|
-
return
|
|
612
|
+
function Re(e, t) {
|
|
613
|
+
return Pe(e, {
|
|
610
614
|
delimiter: "_",
|
|
611
615
|
...t
|
|
612
616
|
});
|
|
613
617
|
}
|
|
614
|
-
function
|
|
618
|
+
function O(e) {
|
|
615
619
|
return e === !1 ? (e) => e.toLowerCase() : (t) => t.toLocaleLowerCase(e);
|
|
616
620
|
}
|
|
617
|
-
function
|
|
621
|
+
function ze(e) {
|
|
618
622
|
return e === !1 ? (e) => e.toUpperCase() : (t) => t.toLocaleUpperCase(e);
|
|
619
623
|
}
|
|
620
|
-
function
|
|
624
|
+
function Be(e, t) {
|
|
621
625
|
return (n) => `${t(n[0])}${e(n.slice(1))}`;
|
|
622
626
|
}
|
|
623
|
-
function
|
|
627
|
+
function Ve(e, t) {
|
|
624
628
|
return (n, r) => {
|
|
625
629
|
let i = n[0];
|
|
626
630
|
return (r > 0 && i >= "0" && i <= "9" ? "_" + i : t(i)) + e(n.slice(1));
|
|
627
631
|
};
|
|
628
632
|
}
|
|
629
|
-
function
|
|
630
|
-
let n = t.split ?? (t.separateNumbers ?
|
|
633
|
+
function k(e, t = {}) {
|
|
634
|
+
let n = t.split ?? (t.separateNumbers ? Ne : Me), r = t.prefixCharacters ?? je, i = t.suffixCharacters ?? je, a = 0, o = e.length;
|
|
631
635
|
for (; a < e.length;) {
|
|
632
636
|
let t = e.charAt(a);
|
|
633
637
|
if (!r.includes(t)) break;
|
|
@@ -646,10 +650,10 @@ function P(e, t = {}) {
|
|
|
646
650
|
}
|
|
647
651
|
//#endregion
|
|
648
652
|
//#region src/parse/model.ts
|
|
649
|
-
var
|
|
653
|
+
var A = /* @__PURE__ */ te((/* @__PURE__ */ ee(((e, t) => {
|
|
650
654
|
(function(n, r) {
|
|
651
655
|
/* istanbul ignore else */
|
|
652
|
-
typeof
|
|
656
|
+
typeof ne == "function" && typeof e == "object" && typeof t == "object" ? t.exports = r() : typeof define == "function" && define.amd ? define(function() {
|
|
653
657
|
return r();
|
|
654
658
|
}) : n.pluralize = r();
|
|
655
659
|
})(e, function() {
|
|
@@ -916,7 +920,7 @@ var F = /* @__PURE__ */ _((/* @__PURE__ */ h(((e, t) => {
|
|
|
916
920
|
/sheep$/i
|
|
917
921
|
].forEach(f.addUncountableRule), f;
|
|
918
922
|
});
|
|
919
|
-
})))(), 1),
|
|
923
|
+
})))(), 1), He = new Set(/* @__PURE__ */ "break.case.catch.class.const.continue.debugger.default.delete.do.else.export.extends.finally.for.function.if.import.in.instanceof.new.return.super.switch.this.throw.try.typeof.var.void.while.with.yield.let.static.package.protected.private.public.interface.enum.implements.type.namespace.null.true.false.await.async.arguments.constructor".split(".")), Ue = {
|
|
920
924
|
function: "fn",
|
|
921
925
|
interface: "iface",
|
|
922
926
|
type: "type_",
|
|
@@ -965,30 +969,30 @@ var F = /* @__PURE__ */ _((/* @__PURE__ */ h(((e, t) => {
|
|
|
965
969
|
arguments: "args",
|
|
966
970
|
constructor: "ctor"
|
|
967
971
|
};
|
|
968
|
-
function
|
|
969
|
-
return
|
|
972
|
+
function We(e) {
|
|
973
|
+
return He.has(e) ? Ue[e] ?? `${e}_` : e;
|
|
970
974
|
}
|
|
971
|
-
function
|
|
972
|
-
if (!/^[a-zA-Z][a-zA-Z0-9-_/]*$/.test(e)) throw new
|
|
975
|
+
function Ge(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");
|
|
973
977
|
}
|
|
974
|
-
function
|
|
978
|
+
function Ke(e) {
|
|
975
979
|
return e.features.auth ? `src/routes/${a}` : `src/routes/${i}`;
|
|
976
980
|
}
|
|
977
|
-
function
|
|
978
|
-
let n = e.split("/"), r = n[n.length - 1], i = n.slice(0, -1), a =
|
|
981
|
+
function j(e, t) {
|
|
982
|
+
let n = e.split("/"), r = n[n.length - 1], i = n.slice(0, -1), a = A.default.singular(Ie(r)), o = A.default.plural(a), s = D(a), c = Le(o), l = [...i, c].join("/");
|
|
979
983
|
return {
|
|
980
|
-
name:
|
|
981
|
-
pluralName:
|
|
982
|
-
typeName:
|
|
983
|
-
tableName:
|
|
984
|
+
name: We(s),
|
|
985
|
+
pluralName: We(D(o)),
|
|
986
|
+
typeName: Fe(a),
|
|
987
|
+
tableName: Re(o),
|
|
984
988
|
displayName: a,
|
|
985
989
|
pluralDisplayName: o,
|
|
986
|
-
schemaName: `${
|
|
990
|
+
schemaName: `${We(s)}Schema`,
|
|
987
991
|
routeSegment: l,
|
|
988
|
-
routesDir:
|
|
992
|
+
routesDir: Ke(t)
|
|
989
993
|
};
|
|
990
994
|
}
|
|
991
|
-
function
|
|
995
|
+
function qe(e) {
|
|
992
996
|
let t = `${e.routesDir}/${e.routeSegment}`;
|
|
993
997
|
return {
|
|
994
998
|
list: t,
|
|
@@ -997,7 +1001,7 @@ function Be(e) {
|
|
|
997
1001
|
edit: `${t}/[id]/edit`
|
|
998
1002
|
};
|
|
999
1003
|
}
|
|
1000
|
-
function
|
|
1004
|
+
function Je(e) {
|
|
1001
1005
|
let t = `/${e.routeSegment}`;
|
|
1002
1006
|
return {
|
|
1003
1007
|
list: t,
|
|
@@ -1008,23 +1012,23 @@ function Ve(e) {
|
|
|
1008
1012
|
}
|
|
1009
1013
|
//#endregion
|
|
1010
1014
|
//#region src/parse/collections.ts
|
|
1011
|
-
var
|
|
1012
|
-
function
|
|
1013
|
-
for (let t of
|
|
1015
|
+
var Ye = /* @__PURE__ */ "title.name.label.display.display_name.full_name.first_name.last_name.given_name.surname.family_name.username.handle.nickname.email.phone.phone_number.headline.subject.caption.summary.description.sku.code.key.identifier.ref.reference.slug.path.url.id".split(".");
|
|
1016
|
+
function Xe(e) {
|
|
1017
|
+
for (let t of Ye) if (e.some((e) => e.name === t)) return t;
|
|
1014
1018
|
return "id";
|
|
1015
1019
|
}
|
|
1016
|
-
function
|
|
1020
|
+
function Ze(e) {
|
|
1017
1021
|
return e.map((e) => e.name).filter((e) => !e.startsWith("_"));
|
|
1018
1022
|
}
|
|
1019
|
-
function
|
|
1023
|
+
function Qe(e) {
|
|
1020
1024
|
return Object.fromEntries(e.map((e) => [e.name, e.id]));
|
|
1021
1025
|
}
|
|
1022
|
-
function
|
|
1023
|
-
return Object.fromEntries(e.map((e) => [e.name,
|
|
1026
|
+
function $e(e) {
|
|
1027
|
+
return Object.fromEntries(e.map((e) => [e.name, Xe(e.fields)]));
|
|
1024
1028
|
}
|
|
1025
1029
|
//#endregion
|
|
1026
1030
|
//#region src/parse/permissions.ts
|
|
1027
|
-
var
|
|
1031
|
+
var et = [
|
|
1028
1032
|
"user",
|
|
1029
1033
|
"owner",
|
|
1030
1034
|
"created_by",
|
|
@@ -1033,10 +1037,10 @@ var qe = [
|
|
|
1033
1037
|
"account",
|
|
1034
1038
|
"creator"
|
|
1035
1039
|
];
|
|
1036
|
-
function
|
|
1040
|
+
function M(e) {
|
|
1037
1041
|
return e.toLowerCase();
|
|
1038
1042
|
}
|
|
1039
|
-
function
|
|
1043
|
+
function tt(e) {
|
|
1040
1044
|
return {
|
|
1041
1045
|
rule: "@request.auth.id != \"\"",
|
|
1042
1046
|
ownershipChainCollections: [e],
|
|
@@ -1044,18 +1048,18 @@ function Je(e) {
|
|
|
1044
1048
|
operator: "="
|
|
1045
1049
|
};
|
|
1046
1050
|
}
|
|
1047
|
-
function
|
|
1048
|
-
let r = new Set((n.authCollections ?? ["users"]).map(
|
|
1051
|
+
function nt(e, t, n = {}) {
|
|
1052
|
+
let r = new Set((n.authCollections ?? ["users"]).map(M)), i = new Set((n.userFieldHints ?? et).map(M)), a = n.maxDepth ?? 8, o = /* @__PURE__ */ new Map(), s = /* @__PURE__ */ new Map();
|
|
1049
1053
|
for (let t of e) o.set(t.name, t), s.set(t.id, t);
|
|
1050
|
-
if (!o.has(t)) return
|
|
1051
|
-
if (r.has(
|
|
1054
|
+
if (!o.has(t)) return tt(t);
|
|
1055
|
+
if (r.has(M(t))) return {
|
|
1052
1056
|
rule: "@request.auth.id = id",
|
|
1053
1057
|
ownershipChainCollections: [t],
|
|
1054
1058
|
ownershipChainFields: [],
|
|
1055
1059
|
operator: "="
|
|
1056
1060
|
};
|
|
1057
1061
|
function c(e) {
|
|
1058
|
-
let t =
|
|
1062
|
+
let t = M(e);
|
|
1059
1063
|
return t === "user" ? 50 : i.has(t) ? 20 : 0;
|
|
1060
1064
|
}
|
|
1061
1065
|
function l(e) {
|
|
@@ -1076,7 +1080,7 @@ function Ye(e, t, n = {}) {
|
|
|
1076
1080
|
return n.sort((e, t) => e.fieldName.localeCompare(t.fieldName)), n;
|
|
1077
1081
|
}
|
|
1078
1082
|
function u(e) {
|
|
1079
|
-
return r.has(
|
|
1083
|
+
return r.has(M(e));
|
|
1080
1084
|
}
|
|
1081
1085
|
function d(e) {
|
|
1082
1086
|
if (e.length === 0) return !1;
|
|
@@ -1084,38 +1088,38 @@ function Ye(e, t, n = {}) {
|
|
|
1084
1088
|
return u(e[e.length - 1].to);
|
|
1085
1089
|
}
|
|
1086
1090
|
function f(e) {
|
|
1087
|
-
let t = e[e.length - 1], n = +!!t.isMulti, r = +!!e.every((e) => !e.isMulti), i = e.reduce((e, t) => e + t.hintScore, 0), a = +(
|
|
1091
|
+
let t = e[e.length - 1], n = +!!t.isMulti, r = +!!e.every((e) => !e.isMulti), i = e.reduce((e, t) => e + t.hintScore, 0), a = +(M(t.fieldName) === "user");
|
|
1088
1092
|
return 100 * e.length + 50 * n - 40 * a - 15 * r - i;
|
|
1089
1093
|
}
|
|
1090
1094
|
function p(e) {
|
|
1091
1095
|
return e.map((e) => `${e.from}.${e.fieldName}->${e.to}`).join("|");
|
|
1092
1096
|
}
|
|
1093
1097
|
let m = [], h = new Set([t]);
|
|
1094
|
-
function
|
|
1098
|
+
function ee(e, t, n) {
|
|
1095
1099
|
if (!(n > a)) {
|
|
1096
1100
|
if (t.length > 0 && u(t[t.length - 1].to) && d(t)) {
|
|
1097
1101
|
m.push([...t]);
|
|
1098
1102
|
return;
|
|
1099
1103
|
}
|
|
1100
|
-
for (let r of l(e)) h.has(r.to) || r.isMulti && !u(r.to) || (h.add(r.to), t.push(r),
|
|
1104
|
+
for (let r of l(e)) h.has(r.to) || r.isMulti && !u(r.to) || (h.add(r.to), t.push(r), ee(r.to, t, n + 1), t.pop(), h.delete(r.to));
|
|
1101
1105
|
}
|
|
1102
1106
|
}
|
|
1103
|
-
if (
|
|
1107
|
+
if (ee(t, [], 0), m.length === 0) return tt(t);
|
|
1104
1108
|
m.sort((e, t) => {
|
|
1105
1109
|
let n = f(e) - f(t);
|
|
1106
1110
|
return n === 0 ? p(e).localeCompare(p(t)) : n;
|
|
1107
1111
|
});
|
|
1108
|
-
let
|
|
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
1113
|
return {
|
|
1110
|
-
rule: `@request.auth.id ${
|
|
1111
|
-
ownershipChainCollections:
|
|
1112
|
-
ownershipChainFields:
|
|
1113
|
-
operator:
|
|
1114
|
+
rule: `@request.auth.id ${re} ${n.includeRootPrefix ? (n.rootPrefix ?? t) + "." : ""}${_}.id`,
|
|
1115
|
+
ownershipChainCollections: ne,
|
|
1116
|
+
ownershipChainFields: te,
|
|
1117
|
+
operator: re
|
|
1114
1118
|
};
|
|
1115
1119
|
}
|
|
1116
1120
|
//#endregion
|
|
1117
1121
|
//#region src/parse/fields.ts
|
|
1118
|
-
function
|
|
1122
|
+
function rt(e) {
|
|
1119
1123
|
let t = null, n = !1, r = 0;
|
|
1120
1124
|
for (let i = 0; i < e.length; i++) {
|
|
1121
1125
|
let a = e[i];
|
|
@@ -1147,11 +1151,11 @@ function Xe(e) {
|
|
|
1147
1151
|
}
|
|
1148
1152
|
return [e, ""];
|
|
1149
1153
|
}
|
|
1150
|
-
function
|
|
1154
|
+
function it(e) {
|
|
1151
1155
|
let t = e.trim();
|
|
1152
1156
|
return t.startsWith("\"") && t.endsWith("\"") || t.startsWith("'") && t.endsWith("'") ? t.slice(1, -1).replace(/\\(["'])/g, "$1") : t;
|
|
1153
1157
|
}
|
|
1154
|
-
function
|
|
1158
|
+
function at(e) {
|
|
1155
1159
|
let t = -1, n = null, r = !1;
|
|
1156
1160
|
for (let i = 0; i < e.length; i++) {
|
|
1157
1161
|
let a = e[i];
|
|
@@ -1178,11 +1182,11 @@ function Qe(e) {
|
|
|
1178
1182
|
}
|
|
1179
1183
|
let i, a;
|
|
1180
1184
|
return t >= 0 ? (i = e.slice(0, t).trim(), a = e.slice(t + 1).trim()) : (i = e.trim(), a = i), {
|
|
1181
|
-
label:
|
|
1182
|
-
value:
|
|
1185
|
+
label: it(a),
|
|
1186
|
+
value: it(i)
|
|
1183
1187
|
};
|
|
1184
1188
|
}
|
|
1185
|
-
function
|
|
1189
|
+
function ot(e) {
|
|
1186
1190
|
let t = [], n = "", r = null, i = !1;
|
|
1187
1191
|
for (let a = 0; a < e.length; a++) {
|
|
1188
1192
|
let o = e[a];
|
|
@@ -1208,15 +1212,15 @@ function $e(e) {
|
|
|
1208
1212
|
}
|
|
1209
1213
|
if (o === ",") {
|
|
1210
1214
|
let e = n.trim();
|
|
1211
|
-
e.length > 0 && t.push(
|
|
1215
|
+
e.length > 0 && t.push(at(e)), n = "";
|
|
1212
1216
|
continue;
|
|
1213
1217
|
}
|
|
1214
1218
|
n += o;
|
|
1215
1219
|
}
|
|
1216
1220
|
let a = n.trim();
|
|
1217
|
-
return a.length > 0 && t.push(
|
|
1221
|
+
return a.length > 0 && t.push(at(a)), t;
|
|
1218
1222
|
}
|
|
1219
|
-
var
|
|
1223
|
+
var st = {
|
|
1220
1224
|
string: "text",
|
|
1221
1225
|
boolean: "bool",
|
|
1222
1226
|
geopoint: "geoPoint",
|
|
@@ -1229,37 +1233,37 @@ var et = {
|
|
|
1229
1233
|
datetime: "date",
|
|
1230
1234
|
timestamp: "date"
|
|
1231
1235
|
};
|
|
1232
|
-
function
|
|
1236
|
+
function ct(e) {
|
|
1233
1237
|
let t = e.endsWith("!"), n = t ? e.slice(0, -1) : e, r = [];
|
|
1234
|
-
return n.startsWith("select(") && n.endsWith(")") && (r =
|
|
1238
|
+
return n.startsWith("select(") && n.endsWith(")") && (r = ot(n.slice(7, -1)), n = "select"), n === "files" ? {
|
|
1235
1239
|
type: "file",
|
|
1236
1240
|
required: t,
|
|
1237
1241
|
selectOptions: r
|
|
1238
|
-
} : (n in
|
|
1242
|
+
} : (n in st && (n = st[n]), {
|
|
1239
1243
|
type: n,
|
|
1240
1244
|
required: t,
|
|
1241
1245
|
selectOptions: r
|
|
1242
1246
|
});
|
|
1243
1247
|
}
|
|
1244
|
-
function
|
|
1245
|
-
let t =
|
|
1246
|
-
return e ===
|
|
1248
|
+
function lt(e) {
|
|
1249
|
+
let t = A.default.singular(e);
|
|
1250
|
+
return e === A.default.plural(t) ? 99 : 1;
|
|
1247
1251
|
}
|
|
1248
|
-
function
|
|
1249
|
-
let o =
|
|
1252
|
+
function N(e, t, n, r, i, a) {
|
|
1253
|
+
let o = j(t, a), s = A.default.singular(e), c = A.default.plural(s);
|
|
1250
1254
|
return {
|
|
1251
1255
|
collectionId: r[t],
|
|
1252
1256
|
displayField: i[t] ?? "id",
|
|
1253
1257
|
relatedModel: o,
|
|
1254
|
-
singularRelationName:
|
|
1255
|
-
pluralRelationName:
|
|
1258
|
+
singularRelationName: D(`${n.displayName} ${o.displayName}`),
|
|
1259
|
+
pluralRelationName: D(`${n.displayName} ${o.pluralDisplayName}`),
|
|
1256
1260
|
maxSelect: e === c ? 999 : 1
|
|
1257
1261
|
};
|
|
1258
1262
|
}
|
|
1259
|
-
function
|
|
1260
|
-
let a =
|
|
1263
|
+
function ut(e, t, n, r, i) {
|
|
1264
|
+
let a = Ie(e), { type: o, required: s, selectOptions: c } = t, l = Ze(r), u = Qe(r), d = $e(r), f = l.map((e) => A.default.singular(e));
|
|
1261
1265
|
if (i.features.auth && o === "current_user" && u.users) {
|
|
1262
|
-
let t =
|
|
1266
|
+
let t = N(e, "users", n, u, d, i);
|
|
1263
1267
|
return {
|
|
1264
1268
|
type: "relation",
|
|
1265
1269
|
name: e,
|
|
@@ -1276,7 +1280,7 @@ function rt(e, t, n, r, i) {
|
|
|
1276
1280
|
}
|
|
1277
1281
|
if (o === "autodate") {
|
|
1278
1282
|
let t = e.includes("create"), n = e.includes("update");
|
|
1279
|
-
if (!t && !n) throw new
|
|
1283
|
+
if (!t && !n) throw new _(`Invalid autodate field: ${e}. Must be one of created/created_at/updated/updated_at.`);
|
|
1280
1284
|
return {
|
|
1281
1285
|
type: "autodate",
|
|
1282
1286
|
name: e,
|
|
@@ -1291,7 +1295,7 @@ function rt(e, t, n, r, i) {
|
|
|
1291
1295
|
name: e,
|
|
1292
1296
|
title: a,
|
|
1293
1297
|
required: s,
|
|
1294
|
-
maxSelect:
|
|
1298
|
+
maxSelect: lt(e),
|
|
1295
1299
|
options: c
|
|
1296
1300
|
};
|
|
1297
1301
|
if (o === "file") return {
|
|
@@ -1299,17 +1303,17 @@ function rt(e, t, n, r, i) {
|
|
|
1299
1303
|
name: e,
|
|
1300
1304
|
title: a,
|
|
1301
1305
|
required: s,
|
|
1302
|
-
maxSelect:
|
|
1306
|
+
maxSelect: lt(e)
|
|
1303
1307
|
};
|
|
1304
1308
|
if (o === "relation") {
|
|
1305
|
-
let t =
|
|
1306
|
-
if (!l.includes(r)) throw new
|
|
1309
|
+
let t = A.default.singular(e), r = A.default.plural(t);
|
|
1310
|
+
if (!l.includes(r)) throw new _(`Invalid relation field: ${e}. Must be one of ${l.join(", ")} (singular or plural)`);
|
|
1307
1311
|
return {
|
|
1308
1312
|
type: "relation",
|
|
1309
1313
|
name: e,
|
|
1310
1314
|
title: a,
|
|
1311
1315
|
required: s,
|
|
1312
|
-
...
|
|
1316
|
+
...N(e, r, n, u, d, i),
|
|
1313
1317
|
isCurrentUser: !1
|
|
1314
1318
|
};
|
|
1315
1319
|
}
|
|
@@ -1318,13 +1322,13 @@ function rt(e, t, n, r, i) {
|
|
|
1318
1322
|
name: e,
|
|
1319
1323
|
title: a,
|
|
1320
1324
|
required: s,
|
|
1321
|
-
...
|
|
1325
|
+
...N(e, o, n, u, d, i),
|
|
1322
1326
|
isCurrentUser: !1
|
|
1323
1327
|
};
|
|
1324
1328
|
if (f.includes(o)) {
|
|
1325
|
-
let t =
|
|
1329
|
+
let t = A.default.plural(o);
|
|
1326
1330
|
if (l.includes(t)) {
|
|
1327
|
-
let r =
|
|
1331
|
+
let r = N(e, t, n, u, d, i);
|
|
1328
1332
|
return {
|
|
1329
1333
|
type: "relation",
|
|
1330
1334
|
name: e,
|
|
@@ -1369,7 +1373,7 @@ function rt(e, t, n, r, i) {
|
|
|
1369
1373
|
"editor",
|
|
1370
1374
|
"json",
|
|
1371
1375
|
"geoPoint"
|
|
1372
|
-
].includes(o)) throw new
|
|
1376
|
+
].includes(o)) throw new _(`Invalid field type: ${o}. Valid types are: ${p.join(", ").replace("relation", "references")}`);
|
|
1373
1377
|
return {
|
|
1374
1378
|
type: o,
|
|
1375
1379
|
name: e,
|
|
@@ -1377,18 +1381,18 @@ function rt(e, t, n, r, i) {
|
|
|
1377
1381
|
required: s
|
|
1378
1382
|
};
|
|
1379
1383
|
}
|
|
1380
|
-
function
|
|
1384
|
+
function dt(e, t, n, r) {
|
|
1381
1385
|
let i = [];
|
|
1382
1386
|
for (let a of e) {
|
|
1383
|
-
let [e, o] =
|
|
1384
|
-
if (!e || !o) throw new
|
|
1385
|
-
if (!/^[a-zA-Z][a-zA-Z0-9]*$/.test(e)) throw new
|
|
1386
|
-
let s =
|
|
1387
|
-
i.push(
|
|
1387
|
+
let [e, o] = rt(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 = ct(o);
|
|
1391
|
+
i.push(ut(e, s, t, n, r));
|
|
1388
1392
|
}
|
|
1389
1393
|
return {
|
|
1390
1394
|
fields: i,
|
|
1391
|
-
auth: r.features.auth ?
|
|
1395
|
+
auth: r.features.auth ? nt([...n, {
|
|
1392
1396
|
id: "new",
|
|
1393
1397
|
name: t.tableName,
|
|
1394
1398
|
type: "base",
|
|
@@ -1403,18 +1407,18 @@ function it(e, t, n, r) {
|
|
|
1403
1407
|
}
|
|
1404
1408
|
//#endregion
|
|
1405
1409
|
//#region src/core/tests.ts
|
|
1406
|
-
var
|
|
1410
|
+
var ft = "2024-01-01T00:00:00.000Z", P = class {
|
|
1407
1411
|
constructor(e) {
|
|
1408
1412
|
this.expression = e;
|
|
1409
1413
|
}
|
|
1410
1414
|
};
|
|
1411
|
-
function
|
|
1412
|
-
return e instanceof
|
|
1415
|
+
function F(e) {
|
|
1416
|
+
return e instanceof P ? e.expression : Array.isArray(e) ? `[${e.map((e) => F(e)).join(", ")}]` : e && typeof e == "object" ? `{ ${Object.entries(e).map(([e, t]) => `${JSON.stringify(e)}: ${F(t)}`).join(", ")} }` : JSON.stringify(e);
|
|
1413
1417
|
}
|
|
1414
|
-
function
|
|
1415
|
-
return `{ ${Object.entries(e).map(([e, t]) => `${JSON.stringify(e)}: ${
|
|
1418
|
+
function pt(e) {
|
|
1419
|
+
return `{ ${Object.entries(e).map(([e, t]) => `${JSON.stringify(e)}: ${F(t)}`).join(", ")} }`;
|
|
1416
1420
|
}
|
|
1417
|
-
function
|
|
1421
|
+
function mt(e) {
|
|
1418
1422
|
switch (e) {
|
|
1419
1423
|
case "text":
|
|
1420
1424
|
case "number":
|
|
@@ -1443,16 +1447,16 @@ function ot(e) {
|
|
|
1443
1447
|
default: return;
|
|
1444
1448
|
}
|
|
1445
1449
|
}
|
|
1446
|
-
function
|
|
1450
|
+
function I(e, t) {
|
|
1447
1451
|
return e.replace("[id]", `\${${t}}`);
|
|
1448
1452
|
}
|
|
1449
|
-
function
|
|
1453
|
+
function ht(e, t, n) {
|
|
1450
1454
|
switch (e.type) {
|
|
1451
1455
|
case "text":
|
|
1452
1456
|
case "editor": return `${e.name} value`;
|
|
1453
1457
|
case "number": return 42;
|
|
1454
1458
|
case "bool": return !0;
|
|
1455
|
-
case "date": return
|
|
1459
|
+
case "date": return ft;
|
|
1456
1460
|
case "email": return `test-${e.name}@example.com`;
|
|
1457
1461
|
case "password": return "password";
|
|
1458
1462
|
case "url": return "https://example.com";
|
|
@@ -1469,40 +1473,40 @@ function st(e, t, n) {
|
|
|
1469
1473
|
return e.maxSelect && e.maxSelect > 1 ? [t] : t;
|
|
1470
1474
|
}
|
|
1471
1475
|
case "relation": {
|
|
1472
|
-
if (n.authEnabled && (e.isCurrentUser || e.relatedModel?.tableName === "users")) return new
|
|
1476
|
+
if (n.authEnabled && (e.isCurrentUser || e.relatedModel?.tableName === "users")) return new P("context.user.id");
|
|
1473
1477
|
let r = e.collectionId ? t[e.collectionId] : void 0;
|
|
1474
|
-
return r ? new
|
|
1478
|
+
return r ? new P(r) : "missing-relation-id";
|
|
1475
1479
|
}
|
|
1476
1480
|
case "file":
|
|
1477
1481
|
case "autodate": return;
|
|
1478
1482
|
default: return;
|
|
1479
1483
|
}
|
|
1480
1484
|
}
|
|
1481
|
-
function
|
|
1485
|
+
function gt(e, t, n) {
|
|
1482
1486
|
let r = {};
|
|
1483
1487
|
for (let i of e) {
|
|
1484
1488
|
if (i.type === "file" || i.type === "autodate") continue;
|
|
1485
1489
|
if (n.authEnabled && i.type === "relation" && i.isCurrentUser) {
|
|
1486
|
-
n.forForm || (r[i.name] = new
|
|
1490
|
+
n.forForm || (r[i.name] = new P("context.user.id"));
|
|
1487
1491
|
continue;
|
|
1488
1492
|
}
|
|
1489
|
-
let e =
|
|
1493
|
+
let e = ht(i, t, n);
|
|
1490
1494
|
e !== void 0 && (r[i.name] = e);
|
|
1491
1495
|
}
|
|
1492
1496
|
return r;
|
|
1493
1497
|
}
|
|
1494
|
-
function
|
|
1498
|
+
function _t(e, t, n) {
|
|
1495
1499
|
let r = {};
|
|
1496
1500
|
for (let i of e) {
|
|
1497
1501
|
if (i.system || i.name === "id") continue;
|
|
1498
|
-
let e =
|
|
1502
|
+
let e = mt(i.type);
|
|
1499
1503
|
if (!e || e === "file" || e === "autodate" || e === "relation" && !i.collectionId) continue;
|
|
1500
1504
|
let a;
|
|
1501
|
-
if (e === "relation") a = i.collectionId ? new
|
|
1505
|
+
if (e === "relation") a = i.collectionId ? new P(t[i.collectionId] ?? "\"missing-relation-id\"") : void 0;
|
|
1502
1506
|
else if (e === "select") {
|
|
1503
1507
|
let e = i.values?.[0] ?? "default";
|
|
1504
1508
|
a = (i.maxSelect ?? 1) > 1 ? [e] : e;
|
|
1505
|
-
} else a =
|
|
1509
|
+
} else a = ht({
|
|
1506
1510
|
name: i.name,
|
|
1507
1511
|
type: e
|
|
1508
1512
|
}, t, {
|
|
@@ -1513,10 +1517,10 @@ function lt(e, t, n) {
|
|
|
1513
1517
|
}
|
|
1514
1518
|
return r;
|
|
1515
1519
|
}
|
|
1516
|
-
function
|
|
1517
|
-
e.email = new
|
|
1520
|
+
function vt(e) {
|
|
1521
|
+
e.email = new P("`test-${Math.random().toString(36).slice(2)}@example.com`"), e.password = "password", e.passwordConfirm = "password";
|
|
1518
1522
|
}
|
|
1519
|
-
function
|
|
1523
|
+
function yt(e, t) {
|
|
1520
1524
|
if (!e) return [];
|
|
1521
1525
|
let n = new Map(t.map((e) => [e.id, e])), r = /* @__PURE__ */ new Set(), i = /* @__PURE__ */ new Set(), a = [], o = (e) => {
|
|
1522
1526
|
if (r.has(e) || i.has(e)) return;
|
|
@@ -1530,14 +1534,14 @@ function dt(e, t) {
|
|
|
1530
1534
|
for (let t of e.fields) t.type !== "relation" || !t.collectionId || o(t.collectionId);
|
|
1531
1535
|
return a;
|
|
1532
1536
|
}
|
|
1533
|
-
function
|
|
1537
|
+
function bt(e, t) {
|
|
1534
1538
|
if (!t.has(e)) return t.add(e), e;
|
|
1535
1539
|
let n = 2;
|
|
1536
1540
|
for (; t.has(`${e}${n}`);) n += 1;
|
|
1537
1541
|
let r = `${e}${n}`;
|
|
1538
1542
|
return t.add(r), r;
|
|
1539
1543
|
}
|
|
1540
|
-
function
|
|
1544
|
+
function xt(e, t) {
|
|
1541
1545
|
return {
|
|
1542
1546
|
id: `generated-${e.tableName}`,
|
|
1543
1547
|
name: e.tableName,
|
|
@@ -1562,18 +1566,18 @@ function pt(e, t) {
|
|
|
1562
1566
|
})
|
|
1563
1567
|
};
|
|
1564
1568
|
}
|
|
1565
|
-
function
|
|
1566
|
-
let a =
|
|
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();
|
|
1567
1571
|
for (let e of a) {
|
|
1568
|
-
let t =
|
|
1572
|
+
let t = bt(j(e.name, r).name, c);
|
|
1569
1573
|
s.push({
|
|
1570
1574
|
varName: t,
|
|
1571
1575
|
collection: e
|
|
1572
1576
|
}), o[e.id] = `${t}.id`;
|
|
1573
1577
|
}
|
|
1574
1578
|
let l = s.length ? `${s.map((e) => `let ${e.varName}: { id: string };`).join("\n")}\n\n` : "", u = s.map(({ varName: e, collection: t }) => {
|
|
1575
|
-
let n =
|
|
1576
|
-
return t.type === "auth" &&
|
|
1579
|
+
let n = _t(t.fields, o, r);
|
|
1580
|
+
return t.type === "auth" && vt(n), `${e} = await context.admin.collection("${t.name}").create(${pt(n)});`;
|
|
1577
1581
|
}), 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 = "";
|
|
1578
1582
|
return (u.length > 0 || r.features.auth) && (m += e`
|
|
1579
1583
|
beforeEach(async (context) => {
|
|
@@ -1587,18 +1591,18 @@ function mt(t, n, r, i) {
|
|
|
1587
1591
|
declarations: l,
|
|
1588
1592
|
setupSection: m,
|
|
1589
1593
|
requestAgent: f,
|
|
1590
|
-
modelDbData:
|
|
1594
|
+
modelDbData: pt(gt(n, o, {
|
|
1591
1595
|
forForm: !1,
|
|
1592
1596
|
authEnabled: r.features.auth
|
|
1593
1597
|
})),
|
|
1594
|
-
modelFormData:
|
|
1598
|
+
modelFormData: pt(gt(n, o, {
|
|
1595
1599
|
forForm: !0,
|
|
1596
1600
|
authEnabled: r.features.auth
|
|
1597
1601
|
}))
|
|
1598
1602
|
};
|
|
1599
1603
|
}
|
|
1600
|
-
function
|
|
1601
|
-
let { declarations: o, setupSection: s, requestAgent: c, modelDbData: l, modelFormData: u } =
|
|
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);
|
|
1602
1606
|
return e`
|
|
1603
1607
|
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
|
1604
1608
|
|
|
@@ -1632,7 +1636,7 @@ function ht(t, n, r, i, a) {
|
|
|
1632
1636
|
describe("GET ${n.show}", () => {
|
|
1633
1637
|
it("should return a 200 status code", async (context) => {
|
|
1634
1638
|
const { id } = await context.admin.collection("${t.tableName}").create(${l});
|
|
1635
|
-
const response = await ${c}.get(\`${
|
|
1639
|
+
const response = await ${c}.get(\`${I(n.show, "id")}\`);
|
|
1636
1640
|
expect(response.status).toBe(200);
|
|
1637
1641
|
});
|
|
1638
1642
|
|
|
@@ -1645,10 +1649,10 @@ function ht(t, n, r, i, a) {
|
|
|
1645
1649
|
describe("POST ${n.show}", () => {
|
|
1646
1650
|
it("should delete a ${t.displayName.toLowerCase()}", async (context) => {
|
|
1647
1651
|
const { id } = await context.admin.collection("${t.tableName}").create(${l});
|
|
1648
|
-
const response = await ${c}.post(\`${
|
|
1652
|
+
const response = await ${c}.post(\`${I(n.show, "id")}\`).type("form");
|
|
1649
1653
|
expect(response.body.status).toBe(303);
|
|
1650
1654
|
|
|
1651
|
-
const response2 = await ${c}.get(\`${
|
|
1655
|
+
const response2 = await ${c}.get(\`${I(n.show, "id")}\`);
|
|
1652
1656
|
expect(response2.status).toBe(404);
|
|
1653
1657
|
});
|
|
1654
1658
|
});
|
|
@@ -1656,7 +1660,7 @@ function ht(t, n, r, i, a) {
|
|
|
1656
1660
|
describe("GET ${n.edit}", () => {
|
|
1657
1661
|
it("should return a 200 status code", async (context) => {
|
|
1658
1662
|
const { id } = await context.admin.collection("${t.tableName}").create(${l});
|
|
1659
|
-
const response = await ${c}.get(\`${
|
|
1663
|
+
const response = await ${c}.get(\`${I(n.edit, "id")}\`);
|
|
1660
1664
|
expect(response.status).toBe(200);
|
|
1661
1665
|
});
|
|
1662
1666
|
});
|
|
@@ -1665,18 +1669,74 @@ function ht(t, n, r, i, a) {
|
|
|
1665
1669
|
it("should update a ${t.displayName.toLowerCase()}", async (context) => {
|
|
1666
1670
|
const { id } = await context.admin.collection("${t.tableName}").create(${l});
|
|
1667
1671
|
const response = await ${c}
|
|
1668
|
-
.post(\`${
|
|
1672
|
+
.post(\`${I(n.edit, "id")}\`)
|
|
1669
1673
|
.type("form")
|
|
1670
1674
|
.send(${u});
|
|
1671
1675
|
expect(response.body.status).toBe(303);
|
|
1672
|
-
expect(response.body.location).toBe(\`${
|
|
1676
|
+
expect(response.body.location).toBe(\`${I(n.show, "id")}\`);
|
|
1677
|
+
});
|
|
1678
|
+
});
|
|
1679
|
+
});
|
|
1680
|
+
`;
|
|
1681
|
+
}
|
|
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`
|
|
1685
|
+
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
|
1686
|
+
|
|
1687
|
+
describe("${t.pluralName}", () => {
|
|
1688
|
+
${o}${s}
|
|
1689
|
+
|
|
1690
|
+
describe("GET ${n.list}", () => {
|
|
1691
|
+
it("should return a 200 status code", async (context) => {
|
|
1692
|
+
const response = await ${c}.get("${n.list}");
|
|
1693
|
+
expect(response.status).toBe(200);
|
|
1694
|
+
});
|
|
1695
|
+
});
|
|
1696
|
+
|
|
1697
|
+
describe("GET ${n.new}", () => {
|
|
1698
|
+
it("should return a 200 status code", async (context) => {
|
|
1699
|
+
const response = await ${c}.get("${n.new}");
|
|
1700
|
+
expect(response.status).toBe(200);
|
|
1701
|
+
});
|
|
1702
|
+
});
|
|
1703
|
+
|
|
1704
|
+
describe("GET ${n.show}", () => {
|
|
1705
|
+
it("should return a 200 status code", async (context) => {
|
|
1706
|
+
const { id } = await context.admin.collection("${t.tableName}").create(${l});
|
|
1707
|
+
const response = await ${c}.get(\`${I(n.show, "id")}\`);
|
|
1708
|
+
expect(response.status).toBe(200);
|
|
1709
|
+
});
|
|
1710
|
+
|
|
1711
|
+
it("should return a 404 status code", async (context) => {
|
|
1712
|
+
const response = await ${c}.get("${n.show.replace("[id]", "non-existent")}");
|
|
1713
|
+
expect(response.status).toBe(404);
|
|
1714
|
+
});
|
|
1715
|
+
});
|
|
1716
|
+
|
|
1717
|
+
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});
|
|
1720
|
+
const response = await ${c}.post(\`${I(n.show, "id")}\`).type("form");
|
|
1721
|
+
expect(response.body.status).toBe(303);
|
|
1722
|
+
|
|
1723
|
+
const response2 = await ${c}.get(\`${I(n.show, "id")}\`);
|
|
1724
|
+
expect(response2.status).toBe(404);
|
|
1725
|
+
});
|
|
1726
|
+
});
|
|
1727
|
+
|
|
1728
|
+
describe("GET ${n.edit}", () => {
|
|
1729
|
+
it("should return a 200 status code", async (context) => {
|
|
1730
|
+
const { id } = await context.admin.collection("${t.tableName}").create(${l});
|
|
1731
|
+
const response = await ${c}.get(\`${I(n.edit, "id")}\`);
|
|
1732
|
+
expect(response.status).toBe(200);
|
|
1673
1733
|
});
|
|
1674
1734
|
});
|
|
1675
1735
|
});
|
|
1676
1736
|
`;
|
|
1677
1737
|
}
|
|
1678
|
-
function
|
|
1679
|
-
let { declarations: o, setupSection: s, requestAgent: c, modelFormData: l } =
|
|
1738
|
+
function wt(t, n, r, i, a) {
|
|
1739
|
+
let { declarations: o, setupSection: s, requestAgent: c, modelFormData: l } = L(t, r, i, a);
|
|
1680
1740
|
return e`
|
|
1681
1741
|
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
|
1682
1742
|
|
|
@@ -1699,9 +1759,26 @@ function gt(t, n, r, i, a) {
|
|
|
1699
1759
|
});
|
|
1700
1760
|
`;
|
|
1701
1761
|
}
|
|
1762
|
+
function Tt(t, n, r, i, a) {
|
|
1763
|
+
let { declarations: o, setupSection: s, requestAgent: c } = L(t, r, i, a);
|
|
1764
|
+
return e`
|
|
1765
|
+
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
|
1766
|
+
|
|
1767
|
+
describe("${n}", () => {
|
|
1768
|
+
${o}${s}
|
|
1769
|
+
|
|
1770
|
+
describe("GET ${n}", () => {
|
|
1771
|
+
it("should return a 200 status code", async (context) => {
|
|
1772
|
+
const response = await ${c}.get("${n}");
|
|
1773
|
+
expect(response.status).toBe(200);
|
|
1774
|
+
});
|
|
1775
|
+
});
|
|
1776
|
+
});
|
|
1777
|
+
`;
|
|
1778
|
+
}
|
|
1702
1779
|
//#endregion
|
|
1703
1780
|
//#region src/core/shared.ts
|
|
1704
|
-
var
|
|
1781
|
+
var Et = ["text"], Dt = {
|
|
1705
1782
|
string: "text",
|
|
1706
1783
|
boolean: "bool",
|
|
1707
1784
|
geopoint: "geoPoint",
|
|
@@ -1728,10 +1805,10 @@ var _t = ["text"], vt = {
|
|
|
1728
1805
|
geoPoint: "geoPoint",
|
|
1729
1806
|
relation: "relation"
|
|
1730
1807
|
};
|
|
1731
|
-
function
|
|
1808
|
+
function Ot(e) {
|
|
1732
1809
|
return /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(e) ? e : `'${e}'`;
|
|
1733
1810
|
}
|
|
1734
|
-
function
|
|
1811
|
+
function R(t, n) {
|
|
1735
1812
|
let r = t.type === "select" ? `[${(t.options ?? []).map((e) => JSON.stringify(e.value)).join(", ")}]` : "", i;
|
|
1736
1813
|
switch (t.type) {
|
|
1737
1814
|
case "text":
|
|
@@ -1788,21 +1865,21 @@ function W(t, n) {
|
|
|
1788
1865
|
break;
|
|
1789
1866
|
default: return t.type;
|
|
1790
1867
|
}
|
|
1791
|
-
return
|
|
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()`;
|
|
1792
1869
|
}
|
|
1793
|
-
async function
|
|
1870
|
+
async function kt(e) {
|
|
1794
1871
|
if (e.env === "runtime") {
|
|
1795
|
-
let { getCollections: e } = await import("./chunks/env.runtime-
|
|
1872
|
+
let { getCollections: e } = await import("./chunks/env.runtime-CJS54CZX.js");
|
|
1796
1873
|
return await e();
|
|
1797
1874
|
}
|
|
1798
|
-
let { getPreviewCollections: t } = await import("./chunks/env.preview-
|
|
1875
|
+
let { getPreviewCollections: t } = await import("./chunks/env.preview-kw0hC6y8.js");
|
|
1799
1876
|
return t(e);
|
|
1800
1877
|
}
|
|
1801
|
-
async function
|
|
1802
|
-
|
|
1803
|
-
let r =
|
|
1878
|
+
async function z(e, t, n) {
|
|
1879
|
+
Ge(t);
|
|
1880
|
+
let r = j(t, e), i = await kt(e);
|
|
1804
1881
|
if (n.length > 0) {
|
|
1805
|
-
let { fields: t, auth: a } =
|
|
1882
|
+
let { fields: t, auth: a } = dt(n, r, i, e);
|
|
1806
1883
|
return {
|
|
1807
1884
|
model: r,
|
|
1808
1885
|
fields: t,
|
|
@@ -1813,24 +1890,24 @@ async function G(e, t, n) {
|
|
|
1813
1890
|
}
|
|
1814
1891
|
return {
|
|
1815
1892
|
model: r,
|
|
1816
|
-
fields:
|
|
1893
|
+
fields: jt(r, i, e),
|
|
1817
1894
|
auth: void 0,
|
|
1818
1895
|
shouldCreateCollection: !1,
|
|
1819
1896
|
collections: i
|
|
1820
1897
|
};
|
|
1821
1898
|
}
|
|
1822
|
-
function
|
|
1899
|
+
function B(t, n, r) {
|
|
1823
1900
|
let i = [];
|
|
1824
1901
|
r.includeModelFields && (i.push({
|
|
1825
1902
|
name: "id",
|
|
1826
|
-
schema:
|
|
1903
|
+
schema: R({
|
|
1827
1904
|
name: "id",
|
|
1828
1905
|
type: "text",
|
|
1829
1906
|
required: !1
|
|
1830
1907
|
}, r)
|
|
1831
1908
|
}), i.push({
|
|
1832
1909
|
name: "collectionId",
|
|
1833
|
-
schema:
|
|
1910
|
+
schema: R({
|
|
1834
1911
|
name: "collectionId",
|
|
1835
1912
|
type: "text",
|
|
1836
1913
|
required: !1
|
|
@@ -1840,7 +1917,7 @@ function K(t, n, r) {
|
|
|
1840
1917
|
if (e.type === "file" && e.maxSelect > 1) {
|
|
1841
1918
|
i.push({
|
|
1842
1919
|
name: e.name,
|
|
1843
|
-
schema:
|
|
1920
|
+
schema: R({
|
|
1844
1921
|
...e,
|
|
1845
1922
|
required: !1
|
|
1846
1923
|
}, r)
|
|
@@ -1855,10 +1932,10 @@ function K(t, n, r) {
|
|
|
1855
1932
|
}
|
|
1856
1933
|
i.push({
|
|
1857
1934
|
name: e.name,
|
|
1858
|
-
schema:
|
|
1935
|
+
schema: R(e, r)
|
|
1859
1936
|
});
|
|
1860
1937
|
}
|
|
1861
|
-
let a = i.map((e) => `${
|
|
1938
|
+
let a = i.map((e) => `${Ot(e.name)}: ${e.schema}`).join(",\n "), o = r.includeModelFields ? "\nimport type { Schemas } from \"pocketbase-svelte\";" : "", s = r.includeModelFields ? ` satisfies Schemas["${t.tableName}"]` : "";
|
|
1862
1939
|
return e`
|
|
1863
1940
|
import { z } from "zod";${o}
|
|
1864
1941
|
|
|
@@ -1867,22 +1944,22 @@ function K(t, n, r) {
|
|
|
1867
1944
|
})${s};
|
|
1868
1945
|
`;
|
|
1869
1946
|
}
|
|
1870
|
-
function
|
|
1871
|
-
let t =
|
|
1947
|
+
function At(e) {
|
|
1948
|
+
let t = Dt[e];
|
|
1872
1949
|
if (!t) throw Error(`Unsupported collection field type "${e}" when generating from collection`);
|
|
1873
1950
|
return t;
|
|
1874
1951
|
}
|
|
1875
|
-
function
|
|
1952
|
+
function jt(e, t, n) {
|
|
1876
1953
|
let r = t.find((t) => t.name === e.tableName);
|
|
1877
1954
|
if (!r) throw Error(`Collection "${e.tableName}" not found`);
|
|
1878
|
-
let i =
|
|
1955
|
+
let i = $e(t), a = new Map(t.map((e) => [e.id, e])), o = [];
|
|
1879
1956
|
for (let t of r.fields) {
|
|
1880
1957
|
if (t.name === "id" || t.system) continue;
|
|
1881
|
-
let r =
|
|
1958
|
+
let r = At(t.type), s = !!t.required, c = Ie(t.name);
|
|
1882
1959
|
if (r === "relation") {
|
|
1883
1960
|
let r = t.collectionId ? a.get(t.collectionId) : void 0;
|
|
1884
1961
|
if (!r) continue;
|
|
1885
|
-
let l =
|
|
1962
|
+
let l = j(r.name, n);
|
|
1886
1963
|
o.push({
|
|
1887
1964
|
name: t.name,
|
|
1888
1965
|
title: c,
|
|
@@ -1892,8 +1969,8 @@ function St(e, t, n) {
|
|
|
1892
1969
|
maxSelect: t.maxSelect ?? 1,
|
|
1893
1970
|
displayField: i[r.name] ?? "id",
|
|
1894
1971
|
relatedModel: l,
|
|
1895
|
-
singularRelationName:
|
|
1896
|
-
pluralRelationName:
|
|
1972
|
+
singularRelationName: D(`${e.displayName} ${l.displayName}`),
|
|
1973
|
+
pluralRelationName: D(`${e.displayName} ${l.pluralDisplayName}`),
|
|
1897
1974
|
isCurrentUser: n.features.auth && r.name === "users" && /user|owner|author/i.test(t.name)
|
|
1898
1975
|
});
|
|
1899
1976
|
continue;
|
|
@@ -1942,16 +2019,16 @@ function St(e, t, n) {
|
|
|
1942
2019
|
}
|
|
1943
2020
|
return o.filter((e) => e.name !== "id");
|
|
1944
2021
|
}
|
|
1945
|
-
function
|
|
2022
|
+
function V(e) {
|
|
1946
2023
|
let t = e.filter((e) => e.type === "relation").map((e) => e.name);
|
|
1947
2024
|
return t.length > 0 ? t.join(",") : void 0;
|
|
1948
2025
|
}
|
|
1949
|
-
function
|
|
2026
|
+
function H(e) {
|
|
1950
2027
|
let t = /* @__PURE__ */ new Set(), n = [];
|
|
1951
2028
|
for (let r of e) r.type === "relation" && (t.has(r.relatedModel.tableName) || (t.add(r.relatedModel.tableName), n.push(r.relatedModel)));
|
|
1952
2029
|
return n;
|
|
1953
2030
|
}
|
|
1954
|
-
function
|
|
2031
|
+
function Mt(e) {
|
|
1955
2032
|
let t = {
|
|
1956
2033
|
name: e.name,
|
|
1957
2034
|
type: e.type,
|
|
@@ -1974,7 +2051,7 @@ function Tt(e) {
|
|
|
1974
2051
|
onUpdate: e.onUpdate
|
|
1975
2052
|
} : t;
|
|
1976
2053
|
}
|
|
1977
|
-
function
|
|
2054
|
+
function Nt(e, t, n) {
|
|
1978
2055
|
let r = n ? {
|
|
1979
2056
|
listRule: n.rule,
|
|
1980
2057
|
viewRule: n.rule,
|
|
@@ -1986,49 +2063,44 @@ function Et(e, t, n) {
|
|
|
1986
2063
|
name: e.tableName,
|
|
1987
2064
|
type: "base",
|
|
1988
2065
|
...r,
|
|
1989
|
-
fields: t.map(
|
|
2066
|
+
fields: t.map(Mt)
|
|
1990
2067
|
};
|
|
1991
2068
|
}
|
|
1992
2069
|
//#endregion
|
|
1993
|
-
//#region \0@oxc-project+runtime@0.124.0/helpers/taggedTemplateLiteral.js
|
|
1994
|
-
function q(e, t) {
|
|
1995
|
-
return t ||= e.slice(0), Object.freeze(Object.defineProperties(e, { raw: { value: Object.freeze(t) } }));
|
|
1996
|
-
}
|
|
1997
|
-
//#endregion
|
|
1998
2070
|
//#region src/patterns/generate/form/generate.ts
|
|
1999
|
-
var
|
|
2000
|
-
function
|
|
2071
|
+
var Pt;
|
|
2072
|
+
function Ft(e, t) {
|
|
2001
2073
|
let n = e.replace(/^\/+|\/+$/g, "");
|
|
2002
2074
|
return {
|
|
2003
2075
|
pagePath: `${t}/${n}`,
|
|
2004
2076
|
pageUrl: `/${n}`
|
|
2005
2077
|
};
|
|
2006
2078
|
}
|
|
2007
|
-
function
|
|
2079
|
+
function It(e) {
|
|
2008
2080
|
let [t, ...n] = e;
|
|
2009
|
-
if (!t) throw new
|
|
2010
|
-
if (n.length === 0) throw new
|
|
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.");
|
|
2011
2083
|
return {
|
|
2012
2084
|
modelPath: t,
|
|
2013
2085
|
fieldDefs: n
|
|
2014
2086
|
};
|
|
2015
2087
|
}
|
|
2016
|
-
function
|
|
2088
|
+
function Lt(e) {
|
|
2017
2089
|
return e.some((e) => e.type === "file");
|
|
2018
2090
|
}
|
|
2019
|
-
function
|
|
2020
|
-
let n =
|
|
2091
|
+
function Rt(e, t) {
|
|
2092
|
+
let n = T(t), r = [
|
|
2021
2093
|
"import { untrack } from \"svelte\";",
|
|
2022
2094
|
"import { superForm } from \"sveltekit-superforms\";",
|
|
2023
2095
|
"import { zod4Client } from \"sveltekit-superforms/adapters\";",
|
|
2024
2096
|
`import { ${e.schemaName} } from "$lib/schemas/${e.name}";`,
|
|
2025
|
-
...
|
|
2097
|
+
...ge(n)
|
|
2026
2098
|
];
|
|
2027
2099
|
return [...new Set(r)];
|
|
2028
2100
|
}
|
|
2029
|
-
function
|
|
2101
|
+
function zt(t, n) {
|
|
2030
2102
|
return e`
|
|
2031
|
-
${n.filter((e) => e.type === "select").map((e) =>
|
|
2103
|
+
${n.filter((e) => e.type === "select").map((e) => w(e)).join("\n\n")}
|
|
2032
2104
|
|
|
2033
2105
|
const form = superForm(untrack(() => data.form), {
|
|
2034
2106
|
validators: zod4Client(${t.schemaName}),
|
|
@@ -2037,19 +2109,19 @@ function Mt(t, n) {
|
|
|
2037
2109
|
const { form: formData } = form;
|
|
2038
2110
|
`;
|
|
2039
2111
|
}
|
|
2040
|
-
function
|
|
2041
|
-
let r =
|
|
2042
|
-
return e(
|
|
2112
|
+
function Bt(t, n) {
|
|
2113
|
+
let r = Rt(t, n).join("\n"), i = zt(t, n), a = n.map((e) => C(e)).join("\n"), s = Lt(n) ? " enctype=\"multipart/form-data\"" : "";
|
|
2114
|
+
return e(Pt ||= o([
|
|
2043
2115
|
"\n <script lang=\"ts\">\n ",
|
|
2044
2116
|
"\n\n let { data } = $props();\n ",
|
|
2045
2117
|
"\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\">",
|
|
2046
2118
|
"</h1>\n </div>\n <div class=\"bg-card rounded-lg shadow-sm border p-4\">\n <form method=\"POST\"",
|
|
2047
2119
|
">\n <div class=\"grid grid-cols-1 md:grid-cols-2 gap-4\">\n ",
|
|
2048
2120
|
"\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 "
|
|
2049
|
-
]), r, i, t.displayName,
|
|
2121
|
+
]), r, i, t.displayName, s, a);
|
|
2050
2122
|
}
|
|
2051
|
-
function
|
|
2052
|
-
let r =
|
|
2123
|
+
function Vt(t, n) {
|
|
2124
|
+
let r = Lt(n);
|
|
2053
2125
|
return e`
|
|
2054
2126
|
${e`
|
|
2055
2127
|
import { fail, superValidate${r ? ", withFiles" : ""} } from "sveltekit-superforms";
|
|
@@ -2078,7 +2150,7 @@ function Pt(t, n) {
|
|
|
2078
2150
|
};
|
|
2079
2151
|
`;
|
|
2080
2152
|
}
|
|
2081
|
-
function
|
|
2153
|
+
function U(e, n) {
|
|
2082
2154
|
return {
|
|
2083
2155
|
path: e,
|
|
2084
2156
|
language: t(e),
|
|
@@ -2086,39 +2158,39 @@ function J(e, n) {
|
|
|
2086
2158
|
status: "success"
|
|
2087
2159
|
};
|
|
2088
2160
|
}
|
|
2089
|
-
async function
|
|
2090
|
-
let { modelPath: t, fieldDefs: n } =
|
|
2161
|
+
async function Ht(e) {
|
|
2162
|
+
let { modelPath: t, fieldDefs: n } = It(e.argv), { model: r, fields: i, collections: a } = await z(e, t, n), { pagePath: o, pageUrl: s } = Ft(t, r.routesDir);
|
|
2091
2163
|
return {
|
|
2092
2164
|
creates: [
|
|
2093
|
-
|
|
2094
|
-
|
|
2095
|
-
|
|
2096
|
-
|
|
2165
|
+
U(`${o}/+page.svelte`, Bt(r, i)),
|
|
2166
|
+
U(`${o}/+page.server.ts`, Vt(r, i)),
|
|
2167
|
+
U(`${o}/server.test.ts`, wt(r, s, i, e, a)),
|
|
2168
|
+
U(`src/lib/schemas/${r.name}.ts`, B(r, i, {
|
|
2097
2169
|
includeModelFields: !1,
|
|
2098
2170
|
forForm: !0
|
|
2099
2171
|
}))
|
|
2100
2172
|
],
|
|
2101
2173
|
modifies: [],
|
|
2102
2174
|
deletes: [],
|
|
2103
|
-
components:
|
|
2175
|
+
components: T(i),
|
|
2104
2176
|
packages: [],
|
|
2105
2177
|
collections: []
|
|
2106
2178
|
};
|
|
2107
2179
|
}
|
|
2108
2180
|
//#endregion
|
|
2109
2181
|
//#region src/patterns/generate/form/index.ts
|
|
2110
|
-
var
|
|
2111
|
-
async function
|
|
2112
|
-
let t = await
|
|
2113
|
-
if (e.env !== "runtime") return
|
|
2114
|
-
let { writeResult: n } = await import("./chunks/write-result-
|
|
2115
|
-
return n(await
|
|
2116
|
-
}
|
|
2117
|
-
var
|
|
2118
|
-
version:
|
|
2119
|
-
slug:
|
|
2120
|
-
source:
|
|
2121
|
-
docs:
|
|
2182
|
+
var Ut = "generate-form", Wt = "1.0.7", Gt = "src/patterns/generate/form", Kt = "/generate/form";
|
|
2183
|
+
async function qt(e) {
|
|
2184
|
+
let t = await Ht(e);
|
|
2185
|
+
if (e.env !== "runtime") return v(t);
|
|
2186
|
+
let { writeResult: n } = await import("./chunks/write-result-C3SCX65t.js");
|
|
2187
|
+
return n(await v(t), e);
|
|
2188
|
+
}
|
|
2189
|
+
var Jt = {
|
|
2190
|
+
version: Wt,
|
|
2191
|
+
slug: Ut,
|
|
2192
|
+
source: Gt,
|
|
2193
|
+
docs: Kt,
|
|
2122
2194
|
plan: "open",
|
|
2123
2195
|
title: "Generate a form",
|
|
2124
2196
|
summary: "Generates a form.",
|
|
@@ -2163,19 +2235,282 @@ var Vt = {
|
|
|
2163
2235
|
],
|
|
2164
2236
|
tests: 2,
|
|
2165
2237
|
baseline: "velastack",
|
|
2166
|
-
generate:
|
|
2238
|
+
generate: qt
|
|
2239
|
+
}, Yt = {
|
|
2240
|
+
text: ["input"],
|
|
2241
|
+
number: ["input"],
|
|
2242
|
+
email: ["input"],
|
|
2243
|
+
password: ["input"],
|
|
2244
|
+
url: ["input"],
|
|
2245
|
+
date: ["input"],
|
|
2246
|
+
bool: [],
|
|
2247
|
+
editor: ["textarea"],
|
|
2248
|
+
json: ["textarea"],
|
|
2249
|
+
select: [],
|
|
2250
|
+
file: [],
|
|
2251
|
+
autodate: ["input"],
|
|
2252
|
+
geoPoint: [],
|
|
2253
|
+
relation: []
|
|
2254
|
+
}, Xt = {
|
|
2255
|
+
input: "import { Input } from \"$lib/components/ui/input\";",
|
|
2256
|
+
textarea: "import { Textarea } from \"$lib/components/ui/textarea\";",
|
|
2257
|
+
button: "import { Button } from \"$lib/components/ui/button\";"
|
|
2258
|
+
};
|
|
2259
|
+
function W(e) {
|
|
2260
|
+
let t = e.flatMap((e) => Yt[e.type]);
|
|
2261
|
+
return [...new Set(t)];
|
|
2262
|
+
}
|
|
2263
|
+
function Zt(e) {
|
|
2264
|
+
return e.map((e) => Xt[e]);
|
|
2265
|
+
}
|
|
2266
|
+
function G(e, t, n) {
|
|
2267
|
+
return `{...${e}.fields.${t.name}.as(${JSON.stringify(n)})}`;
|
|
2268
|
+
}
|
|
2269
|
+
function K(t, n) {
|
|
2270
|
+
return e`
|
|
2271
|
+
{#each ${t}.fields.${n.name}.issues() as issue}
|
|
2272
|
+
<p class="text-destructive text-sm">{issue.message}</p>
|
|
2273
|
+
{/each}
|
|
2274
|
+
`;
|
|
2275
|
+
}
|
|
2276
|
+
function q(t, n, r, i) {
|
|
2277
|
+
let a = t.required ? " required" : "", o = i ? ` type="${i}"` : "";
|
|
2278
|
+
return e`
|
|
2279
|
+
<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)}
|
|
2283
|
+
</div>
|
|
2284
|
+
`;
|
|
2285
|
+
}
|
|
2286
|
+
function Qt(t, n) {
|
|
2287
|
+
let r = t.required ? " required" : "";
|
|
2288
|
+
return e`
|
|
2289
|
+
<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)}
|
|
2293
|
+
</div>
|
|
2294
|
+
`;
|
|
2295
|
+
}
|
|
2296
|
+
function $t(t, n) {
|
|
2297
|
+
let r = t.required ? " required" : "";
|
|
2298
|
+
return e`
|
|
2299
|
+
<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)}
|
|
2303
|
+
</div>
|
|
2304
|
+
`;
|
|
2305
|
+
}
|
|
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`
|
|
2309
|
+
<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">
|
|
2312
|
+
${a}
|
|
2313
|
+
</select>
|
|
2314
|
+
${K(n, t)}
|
|
2315
|
+
</div>
|
|
2316
|
+
`;
|
|
2317
|
+
}
|
|
2318
|
+
function tn(t, n) {
|
|
2319
|
+
let r = t.maxSelect > 1 ? " multiple" : "", i = t.required ? " required" : "";
|
|
2320
|
+
return e`
|
|
2321
|
+
<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)}
|
|
2325
|
+
</div>
|
|
2326
|
+
`;
|
|
2327
|
+
}
|
|
2328
|
+
function nn(t, n) {
|
|
2329
|
+
return e`
|
|
2330
|
+
<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 />
|
|
2333
|
+
</div>
|
|
2334
|
+
`;
|
|
2335
|
+
}
|
|
2336
|
+
function rn(e) {
|
|
2337
|
+
return `<!-- TODO: ${e.type} field "${e.name}" is not yet supported by the remote form variant -->`;
|
|
2338
|
+
}
|
|
2339
|
+
function an(e, t) {
|
|
2340
|
+
let { formVar: n } = t;
|
|
2341
|
+
switch (e.type) {
|
|
2342
|
+
case "text": return q(e, n, "text");
|
|
2343
|
+
case "number": return q(e, n, "number");
|
|
2344
|
+
case "email": return q(e, n, "text", "email");
|
|
2345
|
+
case "password": return q(e, n, "text", "password");
|
|
2346
|
+
case "url": return q(e, n, "text", "url");
|
|
2347
|
+
case "date": return q(e, n, "text", "date");
|
|
2348
|
+
case "editor":
|
|
2349
|
+
case "json": return Qt(e, n);
|
|
2350
|
+
case "bool": return $t(e, n);
|
|
2351
|
+
case "select": return en(e, n);
|
|
2352
|
+
case "file": return tn(e, n);
|
|
2353
|
+
case "autodate": return nn(e, n);
|
|
2354
|
+
case "geoPoint":
|
|
2355
|
+
case "relation": return rn(e);
|
|
2356
|
+
default: return e;
|
|
2357
|
+
}
|
|
2358
|
+
}
|
|
2359
|
+
//#endregion
|
|
2360
|
+
//#region src/patterns/generate/form-remote/generate.ts
|
|
2361
|
+
var on;
|
|
2362
|
+
function sn(e, t) {
|
|
2363
|
+
let n = e.replace(/^\/+|\/+$/g, "");
|
|
2364
|
+
return {
|
|
2365
|
+
pagePath: `${t}/${n}`,
|
|
2366
|
+
pageUrl: `/${n}`
|
|
2367
|
+
};
|
|
2368
|
+
}
|
|
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.");
|
|
2373
|
+
return {
|
|
2374
|
+
modelPath: t,
|
|
2375
|
+
fieldDefs: n
|
|
2376
|
+
};
|
|
2377
|
+
}
|
|
2378
|
+
function ln(e) {
|
|
2379
|
+
return e.some((e) => e.type === "file");
|
|
2380
|
+
}
|
|
2381
|
+
function un(e) {
|
|
2382
|
+
return `submit${e.typeName}Form`;
|
|
2383
|
+
}
|
|
2384
|
+
function dn(e, t) {
|
|
2385
|
+
let n = W(e), r = [
|
|
2386
|
+
`import { ${t} } from "./form.remote";`,
|
|
2387
|
+
"import { Button } from \"$lib/components/ui/button\";",
|
|
2388
|
+
...Zt(n)
|
|
2389
|
+
];
|
|
2390
|
+
return [...new Set(r)];
|
|
2391
|
+
}
|
|
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([
|
|
2395
|
+
"\n <script lang=\"ts\">\n ",
|
|
2396
|
+
"\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
|
+
"</h1>\n </div>\n <div class=\"bg-card rounded-lg shadow-sm border p-4\">\n <form {...",
|
|
2398
|
+
"}",
|
|
2399
|
+
">\n <div class=\"grid grid-cols-1 md:grid-cols-2 gap-4\">\n ",
|
|
2400
|
+
"\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);
|
|
2402
|
+
}
|
|
2403
|
+
function pn(t, n) {
|
|
2404
|
+
return e`
|
|
2405
|
+
import { form, getRequestEvent } from "$app/server";
|
|
2406
|
+
import { setFlash } from "sveltekit-flash-message/server";
|
|
2407
|
+
import { ${t.schemaName} } from "$lib/schemas/${t.name}";
|
|
2408
|
+
|
|
2409
|
+
export const ${n} = form(${t.schemaName}, async (data) => {
|
|
2410
|
+
const { cookies } = getRequestEvent();
|
|
2411
|
+
setFlash({ type: "toast", message: "Form posted successfully" }, cookies);
|
|
2412
|
+
return { success: true };
|
|
2413
|
+
});
|
|
2414
|
+
`;
|
|
2415
|
+
}
|
|
2416
|
+
function J(e, n) {
|
|
2417
|
+
return {
|
|
2418
|
+
path: e,
|
|
2419
|
+
language: t(e),
|
|
2420
|
+
content: n,
|
|
2421
|
+
status: "success"
|
|
2422
|
+
};
|
|
2423
|
+
}
|
|
2424
|
+
async function mn(e) {
|
|
2425
|
+
let { modelPath: t, fieldDefs: n } = cn(e.argv), { model: r, fields: i, collections: a } = await z(e, t, n), { pagePath: o, pageUrl: s } = sn(t, r.routesDir), c = un(r), l = [
|
|
2426
|
+
J(`${o}/+page.svelte`, fn(r, i, c)),
|
|
2427
|
+
J(`${o}/form.remote.ts`, pn(r, c)),
|
|
2428
|
+
J(`${o}/server.test.ts`, Tt(r, s, i, e, a)),
|
|
2429
|
+
J(`src/lib/schemas/${r.name}.ts`, B(r, i, {
|
|
2430
|
+
includeModelFields: !1,
|
|
2431
|
+
forForm: !0
|
|
2432
|
+
}))
|
|
2433
|
+
], u = W(i);
|
|
2434
|
+
return u.includes("button") || u.push("button"), {
|
|
2435
|
+
creates: l,
|
|
2436
|
+
modifies: [],
|
|
2437
|
+
deletes: [],
|
|
2438
|
+
components: u,
|
|
2439
|
+
packages: [],
|
|
2440
|
+
collections: []
|
|
2441
|
+
};
|
|
2442
|
+
}
|
|
2443
|
+
//#endregion
|
|
2444
|
+
//#region src/patterns/generate/form-remote/index.ts
|
|
2445
|
+
var hn = "generate-form-remote", gn = "1.0.0", _n = "src/patterns/generate/form-remote", vn = "/generate/form-remote";
|
|
2446
|
+
async function yn(e) {
|
|
2447
|
+
let t = await mn(e);
|
|
2448
|
+
if (e.env !== "runtime") return v(t);
|
|
2449
|
+
let { writeResult: n } = await import("./chunks/write-result-C3SCX65t.js");
|
|
2450
|
+
return n(await v(t), e);
|
|
2451
|
+
}
|
|
2452
|
+
var bn = {
|
|
2453
|
+
version: gn,
|
|
2454
|
+
slug: hn,
|
|
2455
|
+
source: _n,
|
|
2456
|
+
docs: vn,
|
|
2457
|
+
plan: "open",
|
|
2458
|
+
title: "Generate a form (remote functions)",
|
|
2459
|
+
summary: "Generates a form using SvelteKit remote functions instead of sveltekit-superforms.",
|
|
2460
|
+
requires: {
|
|
2461
|
+
auth: !1,
|
|
2462
|
+
api: !1,
|
|
2463
|
+
apiKeys: !1,
|
|
2464
|
+
i18n: !1,
|
|
2465
|
+
teams: !1,
|
|
2466
|
+
payments: !1
|
|
2467
|
+
},
|
|
2468
|
+
category: "generators",
|
|
2469
|
+
tags: [
|
|
2470
|
+
"sveltekit",
|
|
2471
|
+
"remote-functions",
|
|
2472
|
+
"validation",
|
|
2473
|
+
"zod"
|
|
2474
|
+
],
|
|
2475
|
+
command: {
|
|
2476
|
+
raw: "vela generate form --remote contact name:text email:email message:editor",
|
|
2477
|
+
base: "vela generate form --remote",
|
|
2478
|
+
argv: [
|
|
2479
|
+
"contact",
|
|
2480
|
+
"name:text",
|
|
2481
|
+
"email:email",
|
|
2482
|
+
"message:editor"
|
|
2483
|
+
]
|
|
2484
|
+
},
|
|
2485
|
+
examples: [
|
|
2486
|
+
{
|
|
2487
|
+
command: "contact name:text! email:email! message:editor",
|
|
2488
|
+
description: "Contact form using remote functions."
|
|
2489
|
+
},
|
|
2490
|
+
{
|
|
2491
|
+
command: "profile avatar:file bio:editor website:url",
|
|
2492
|
+
description: "File upload (multipart) + editor + URL validation."
|
|
2493
|
+
},
|
|
2494
|
+
{
|
|
2495
|
+
command: "feedback rating:select(1,2,3,4,5) comment:editor",
|
|
2496
|
+
description: "Select enum with a long-form comment."
|
|
2497
|
+
}
|
|
2498
|
+
],
|
|
2499
|
+
tests: 1,
|
|
2500
|
+
baseline: "velastack",
|
|
2501
|
+
generate: yn
|
|
2167
2502
|
};
|
|
2168
2503
|
//#endregion
|
|
2169
2504
|
//#region src/patterns/generate/resource/generate.ts
|
|
2170
|
-
function
|
|
2505
|
+
function xn(e) {
|
|
2171
2506
|
let [t, ...n] = e;
|
|
2172
|
-
if (!t) throw new
|
|
2507
|
+
if (!t) throw new _("Invalid command arguments. Expected: <model> [fields...]");
|
|
2173
2508
|
return {
|
|
2174
2509
|
modelPath: t,
|
|
2175
2510
|
fields: n
|
|
2176
2511
|
};
|
|
2177
2512
|
}
|
|
2178
|
-
function
|
|
2513
|
+
function Sn(e, n) {
|
|
2179
2514
|
return {
|
|
2180
2515
|
path: e,
|
|
2181
2516
|
language: t(e),
|
|
@@ -2183,10 +2518,10 @@ function Ut(e, n) {
|
|
|
2183
2518
|
status: "success"
|
|
2184
2519
|
};
|
|
2185
2520
|
}
|
|
2186
|
-
async function
|
|
2187
|
-
let { modelPath: t, fields: n } =
|
|
2521
|
+
async function Cn(e) {
|
|
2522
|
+
let { modelPath: t, fields: n } = xn(e.argv), { model: r, fields: i, auth: a, shouldCreateCollection: o } = await z(e, t, n);
|
|
2188
2523
|
return {
|
|
2189
|
-
creates: [
|
|
2524
|
+
creates: [Sn(`src/lib/schemas/${r.name}.ts`, B(r, i, {
|
|
2190
2525
|
includeModelFields: !0,
|
|
2191
2526
|
forForm: !0
|
|
2192
2527
|
}))],
|
|
@@ -2194,26 +2529,26 @@ async function Wt(e) {
|
|
|
2194
2529
|
deletes: [],
|
|
2195
2530
|
components: [],
|
|
2196
2531
|
packages: [],
|
|
2197
|
-
collections: o ? [
|
|
2532
|
+
collections: o ? [Nt(r, i, a)] : []
|
|
2198
2533
|
};
|
|
2199
2534
|
}
|
|
2200
2535
|
//#endregion
|
|
2201
2536
|
//#region src/patterns/generate/resource/index.ts
|
|
2202
|
-
var
|
|
2203
|
-
async function
|
|
2204
|
-
let t = await
|
|
2205
|
-
if (e.env !== "runtime") return
|
|
2206
|
-
let { createCollections: n } = await import("./chunks/collections-
|
|
2537
|
+
var wn = "generate-resource", Tn = "1.0.7", En = "src/patterns/generate/resource", Dn = "/generate/resource";
|
|
2538
|
+
async function On(e) {
|
|
2539
|
+
let t = await Cn(e);
|
|
2540
|
+
if (e.env !== "runtime") return v(t);
|
|
2541
|
+
let { createCollections: n } = await import("./chunks/collections-CwH8DO-2.js"), r = await n(t.collections, e), i = {
|
|
2207
2542
|
...t,
|
|
2208
2543
|
creates: [...t.creates, ...r]
|
|
2209
|
-
}, { writeResult: a } = await import("./chunks/write-result-
|
|
2210
|
-
return a(await
|
|
2211
|
-
}
|
|
2212
|
-
var
|
|
2213
|
-
version:
|
|
2214
|
-
slug:
|
|
2215
|
-
source:
|
|
2216
|
-
docs:
|
|
2544
|
+
}, { writeResult: a } = await import("./chunks/write-result-C3SCX65t.js");
|
|
2545
|
+
return a(await v(i), e);
|
|
2546
|
+
}
|
|
2547
|
+
var kn = {
|
|
2548
|
+
version: Tn,
|
|
2549
|
+
slug: wn,
|
|
2550
|
+
source: En,
|
|
2551
|
+
docs: Dn,
|
|
2217
2552
|
plan: "open",
|
|
2218
2553
|
title: "Generate a resource",
|
|
2219
2554
|
summary: "Generates model schema resources.",
|
|
@@ -2256,11 +2591,11 @@ var Xt = {
|
|
|
2256
2591
|
],
|
|
2257
2592
|
tests: 0,
|
|
2258
2593
|
baseline: "velastack",
|
|
2259
|
-
generate:
|
|
2260
|
-
},
|
|
2261
|
-
function
|
|
2594
|
+
generate: On
|
|
2595
|
+
}, An, jn, Mn, Nn;
|
|
2596
|
+
function Pn(e) {
|
|
2262
2597
|
let [t, ...n] = e;
|
|
2263
|
-
if (!t) throw new
|
|
2598
|
+
if (!t) throw new _("Invalid command arguments. Expected: <model> [fields...]");
|
|
2264
2599
|
return {
|
|
2265
2600
|
modelPath: t,
|
|
2266
2601
|
fields: n
|
|
@@ -2277,24 +2612,24 @@ function Y(e, n) {
|
|
|
2277
2612
|
function X(e) {
|
|
2278
2613
|
return e.some((e) => e.type === "file");
|
|
2279
2614
|
}
|
|
2280
|
-
function
|
|
2615
|
+
function Fn(e) {
|
|
2281
2616
|
return [...new Set(e.filter(Boolean))];
|
|
2282
2617
|
}
|
|
2283
|
-
function
|
|
2284
|
-
return e.filter((e) => e.type === "select").map((e) =>
|
|
2618
|
+
function In(e) {
|
|
2619
|
+
return e.filter((e) => e.type === "select").map((e) => w(e)).join("\n\n");
|
|
2285
2620
|
}
|
|
2286
|
-
function
|
|
2287
|
-
return
|
|
2621
|
+
function Ln(e, t) {
|
|
2622
|
+
return H(e).map((e) => `const ${e.pluralName} = await ${t}.collection("${e.tableName}").getFullList();`).join("\n ");
|
|
2288
2623
|
}
|
|
2289
|
-
function
|
|
2290
|
-
return
|
|
2624
|
+
function Rn(e) {
|
|
2625
|
+
return H(e).map((e) => e.pluralName).join(", ");
|
|
2291
2626
|
}
|
|
2292
|
-
function
|
|
2627
|
+
function zn(e) {
|
|
2293
2628
|
return e.features.auth ? "locals.pb" : "locals.admin";
|
|
2294
2629
|
}
|
|
2295
|
-
function
|
|
2630
|
+
function Bn(t, n, r = !1) {
|
|
2296
2631
|
return e`
|
|
2297
|
-
${
|
|
2632
|
+
${In(n)}
|
|
2298
2633
|
${r ? "let { data, params } = $props();" : "let { data } = $props();"}
|
|
2299
2634
|
|
|
2300
2635
|
const form = superForm(untrack(() => data.form), {
|
|
@@ -2304,19 +2639,19 @@ function sn(t, n, r = !1) {
|
|
|
2304
2639
|
const { form: formData } = form;
|
|
2305
2640
|
`;
|
|
2306
2641
|
}
|
|
2307
|
-
function
|
|
2308
|
-
let i = r.some((e) => e.type === "select"), a =
|
|
2642
|
+
function Vn(t, n, r) {
|
|
2643
|
+
let i = r.some((e) => e.type === "select"), a = Fn([
|
|
2309
2644
|
"import { untrack } from \"svelte\";",
|
|
2310
2645
|
"import { superForm } from \"sveltekit-superforms\";",
|
|
2311
2646
|
"import { zod4Client } from \"sveltekit-superforms/adapters\";",
|
|
2312
2647
|
`import { ${t.schemaName} } from "$lib/schemas/${t.name}";`,
|
|
2313
|
-
...
|
|
2648
|
+
...ge(T(r)),
|
|
2314
2649
|
"import { Button } from \"$lib/components/ui/button\";",
|
|
2315
2650
|
"import ArrowLeftIcon from \"@lucide/svelte/icons/arrow-left\";",
|
|
2316
2651
|
"import * as Form from \"$lib/components/ui/form\";",
|
|
2317
2652
|
i ? "import type { Models } from \"pocketbase-svelte\";" : ""
|
|
2318
|
-
]).join("\n"),
|
|
2319
|
-
return e(
|
|
2653
|
+
]).join("\n"), s = r.map((e) => C(e)).join("\n"), c = X(r) ? " enctype=\"multipart/form-data\"" : "";
|
|
2654
|
+
return e(An ||= o([
|
|
2320
2655
|
"\n <script lang=\"ts\">\n ",
|
|
2321
2656
|
"\n ",
|
|
2322
2657
|
"\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 ",
|
|
@@ -2325,21 +2660,21 @@ function cn(t, n, r) {
|
|
|
2325
2660
|
">\n <div class=\"grid grid-cols-1 md:grid-cols-2 gap-4\">\n ",
|
|
2326
2661
|
"\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=\"",
|
|
2327
2662
|
"\" variant=\"outline\" size=\"sm\">Cancel</Button>\n </div>\n </form>\n </div>\n </section>\n "
|
|
2328
|
-
]), a,
|
|
2663
|
+
]), a, Bn(t, r), t.displayName.toLowerCase(), n.list, c, s, n.list);
|
|
2329
2664
|
}
|
|
2330
|
-
function
|
|
2331
|
-
let i = r.some((e) => e.type === "select"), a =
|
|
2665
|
+
function Hn(t, n, r) {
|
|
2666
|
+
let i = r.some((e) => e.type === "select"), a = Fn([
|
|
2332
2667
|
"import { untrack } from \"svelte\";",
|
|
2333
2668
|
"import { superForm } from \"sveltekit-superforms\";",
|
|
2334
2669
|
"import { zod4Client } from \"sveltekit-superforms/adapters\";",
|
|
2335
2670
|
`import { ${t.schemaName} } from "$lib/schemas/${t.name}";`,
|
|
2336
|
-
...
|
|
2671
|
+
...ge(T(r)),
|
|
2337
2672
|
"import { Button } from \"$lib/components/ui/button\";",
|
|
2338
2673
|
"import ArrowLeftIcon from \"@lucide/svelte/icons/arrow-left\";",
|
|
2339
2674
|
"import * as Form from \"$lib/components/ui/form\";",
|
|
2340
2675
|
i ? "import type { Models } from \"pocketbase-svelte\";" : ""
|
|
2341
|
-
]).join("\n"),
|
|
2342
|
-
return e(
|
|
2676
|
+
]).join("\n"), s = r.map((e) => C(e)).join("\n"), c = X(r) ? " enctype=\"multipart/form-data\"" : "";
|
|
2677
|
+
return e(jn ||= o([
|
|
2343
2678
|
"\n <script lang=\"ts\">\n ",
|
|
2344
2679
|
"\n ",
|
|
2345
2680
|
"\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 ",
|
|
@@ -2357,10 +2692,10 @@ function ln(t, n, r) {
|
|
|
2357
2692
|
">\n <div class=\"grid grid-cols-1 md:grid-cols-2 gap-4\">\n ",
|
|
2358
2693
|
"\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=\"",
|
|
2359
2694
|
"/\\${params.id}\" variant=\"outline\" size=\"sm\">Cancel</Button>\n </div>\n </form>\n </div>\n </section>\n "
|
|
2360
|
-
]), a,
|
|
2695
|
+
]), a, Bn(t, r, !0), t.displayName.toLowerCase(), n.list, c, s, n.list);
|
|
2361
2696
|
}
|
|
2362
|
-
function
|
|
2363
|
-
let i = r.some((e) => e.type === "select"), a = i ? `${
|
|
2697
|
+
function Un(t, n, r) {
|
|
2698
|
+
let i = r.some((e) => e.type === "select"), a = i ? `${In(r)}` : "", s = r.map((t) => {
|
|
2364
2699
|
let n = "{ getValue }", r = "{ value: getValue() }";
|
|
2365
2700
|
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`
|
|
2366
2701
|
columnHelper.accessor("${t.name}", {
|
|
@@ -2368,8 +2703,8 @@ function un(t, n, r) {
|
|
|
2368
2703
|
cell: (${n}) => renderComponent(Cells.${t.type.charAt(0).toUpperCase() + t.type.slice(1)}Cell, ${r})
|
|
2369
2704
|
})
|
|
2370
2705
|
`;
|
|
2371
|
-
}).join(",\n"),
|
|
2372
|
-
return e(
|
|
2706
|
+
}).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");
|
|
2707
|
+
return e(Mn ||= o([
|
|
2373
2708
|
"\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 ",
|
|
2374
2709
|
"\n import XIcon from \"@lucide/svelte/icons/x\";\n import PlusIcon from \"@lucide/svelte/icons/plus\";\n import type { Models } from \"pocketbase-svelte\";\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 ",
|
|
2375
2710
|
"\n\n const columnHelper = createColumnHelper<Models[\"",
|
|
@@ -2401,10 +2736,10 @@ function un(t, n, r) {
|
|
|
2401
2736
|
"\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=\"",
|
|
2402
2737
|
"\" variant=\"outline\" size=\"sm\">\n <PlusIcon class=\"w-4 h-4\" />\n New ",
|
|
2403
2738
|
"\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}>\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>\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 "
|
|
2404
|
-
]), i ? "import { FacetedFilter } from \"$lib/components/ui/faceted-filter\";" : "", a, t.tableName,
|
|
2739
|
+
]), 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());
|
|
2405
2740
|
}
|
|
2406
|
-
function
|
|
2407
|
-
let i =
|
|
2741
|
+
function Wn(t, n, r) {
|
|
2742
|
+
let i = V(n), a = i ? `{ expand: "${i}" }` : "";
|
|
2408
2743
|
return e`
|
|
2409
2744
|
export const load = async ({ locals }) => {
|
|
2410
2745
|
const ${t.pluralName} = await ${r}.collection("${t.tableName}").getFullList(${a});
|
|
@@ -2412,8 +2747,8 @@ function dn(t, n, r) {
|
|
|
2412
2747
|
};
|
|
2413
2748
|
`;
|
|
2414
2749
|
}
|
|
2415
|
-
function
|
|
2416
|
-
let o = X(r), s =
|
|
2750
|
+
function Gn(t, n, r, i, a) {
|
|
2751
|
+
let o = X(r), s = Ln(r, i), c = Rn(r), l = c ? `, ${c}` : "", u = r.find((e) => e.type === "relation" && e.isCurrentUser), d = a && u ? e`
|
|
2417
2752
|
{
|
|
2418
2753
|
...form.data,
|
|
2419
2754
|
${u.name}: locals.pb.authStore.record?.id
|
|
@@ -2455,8 +2790,8 @@ function fn(t, n, r, i, a) {
|
|
|
2455
2790
|
};
|
|
2456
2791
|
`;
|
|
2457
2792
|
}
|
|
2458
|
-
function
|
|
2459
|
-
let a =
|
|
2793
|
+
function Kn(t, n, r, i) {
|
|
2794
|
+
let a = V(r), o = a ? `, { expand: "${a}" }` : "";
|
|
2460
2795
|
return e`
|
|
2461
2796
|
import { error, redirect } from "@sveltejs/kit";
|
|
2462
2797
|
|
|
@@ -2477,15 +2812,15 @@ function pn(t, n, r, i) {
|
|
|
2477
2812
|
};
|
|
2478
2813
|
`;
|
|
2479
2814
|
}
|
|
2480
|
-
function
|
|
2481
|
-
let i = r.some((e) => e.type === "select"), a = r.some((e) => e.type === "relation"),
|
|
2815
|
+
function qn(t, n, r) {
|
|
2816
|
+
let i = r.some((e) => e.type === "select"), a = r.some((e) => e.type === "relation"), s = r.some((e) => e.type === "file"), c = [
|
|
2482
2817
|
"import { Button } from \"$lib/components/ui/button\";",
|
|
2483
2818
|
"import ArrowLeftIcon from \"@lucide/svelte/icons/arrow-left\";",
|
|
2484
2819
|
i || a ? "import { Badge } from \"$lib/components/ui/badge\";" : "",
|
|
2485
2820
|
a ? "import CircleArrowRightIcon from \"@lucide/svelte/icons/circle-arrow-right\";" : "",
|
|
2486
|
-
|
|
2487
|
-
].filter(Boolean).join("\n"),
|
|
2488
|
-
return e(
|
|
2821
|
+
s ? "import FileIcon from \"@lucide/svelte/icons/file\";" : ""
|
|
2822
|
+
].filter(Boolean).join("\n"), l = In(r), u = r.map((e) => Te(t, e)).join("\n");
|
|
2823
|
+
return e(Nn ||= o([
|
|
2489
2824
|
"\n <script lang=\"ts\">\n ",
|
|
2490
2825
|
"\n ",
|
|
2491
2826
|
"\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\">",
|
|
@@ -2494,10 +2829,10 @@ function mn(t, n, r) {
|
|
|
2494
2829
|
"\n </div>\n\n <div class=\"mt-4 flex gap-2 border-t pt-4 -mx-4 px-4 justify-between\">\n <Button href=\"",
|
|
2495
2830
|
"/{data.",
|
|
2496
2831
|
".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 "
|
|
2497
|
-
]),
|
|
2832
|
+
]), c, l, t.displayName, n.list, u, n.list, t.name);
|
|
2498
2833
|
}
|
|
2499
|
-
function
|
|
2500
|
-
let a = X(r), o =
|
|
2834
|
+
function Jn(t, n, r, i) {
|
|
2835
|
+
let a = X(r), o = Ln(r, i), s = Rn(r), c = s ? `, ${s}` : "";
|
|
2501
2836
|
return e`
|
|
2502
2837
|
import { error, fail, redirect } from "@sveltejs/kit";
|
|
2503
2838
|
import { setPocketbaseErrors, setDefaultData } from "@velastack/pocketbase";
|
|
@@ -2538,23 +2873,23 @@ function hn(t, n, r, i) {
|
|
|
2538
2873
|
};
|
|
2539
2874
|
`;
|
|
2540
2875
|
}
|
|
2541
|
-
async function
|
|
2542
|
-
let { modelPath: t, fields: n } =
|
|
2543
|
-
Y(`src/lib/schemas/${r.name}.ts`,
|
|
2876
|
+
async function Yn(e) {
|
|
2877
|
+
let { modelPath: t, fields: n } = Pn(e.argv), { model: r, fields: i, auth: a, shouldCreateCollection: o, collections: s } = await z(e, t, n), c = qe(r), l = Je(r), u = zn(e), d = i.filter((e) => !(e.type === "relation" && e.isCurrentUser)), f = [
|
|
2878
|
+
Y(`src/lib/schemas/${r.name}.ts`, B(r, i, {
|
|
2544
2879
|
includeModelFields: !0,
|
|
2545
2880
|
forForm: !0
|
|
2546
2881
|
})),
|
|
2547
|
-
Y(`${c.list}/+page.server.ts`,
|
|
2548
|
-
Y(`${c.list}/+page.svelte`,
|
|
2549
|
-
Y(`${c.new}/+page.server.ts`,
|
|
2550
|
-
Y(`${c.new}/+page.svelte`,
|
|
2551
|
-
Y(`${c.show}/+page.server.ts`,
|
|
2552
|
-
Y(`${c.show}/+page.svelte`,
|
|
2553
|
-
Y(`${c.edit}/+page.server.ts`,
|
|
2554
|
-
Y(`${c.edit}/+page.svelte`,
|
|
2555
|
-
Y(`${c.list}/server.test.ts`,
|
|
2882
|
+
Y(`${c.list}/+page.server.ts`, Wn(r, d, u)),
|
|
2883
|
+
Y(`${c.list}/+page.svelte`, Un(r, l, d)),
|
|
2884
|
+
Y(`${c.new}/+page.server.ts`, Gn(r, l, d, u, e.features.auth)),
|
|
2885
|
+
Y(`${c.new}/+page.svelte`, Vn(r, l, d)),
|
|
2886
|
+
Y(`${c.show}/+page.server.ts`, Kn(r, l, d, u)),
|
|
2887
|
+
Y(`${c.show}/+page.svelte`, qn(r, l, d)),
|
|
2888
|
+
Y(`${c.edit}/+page.server.ts`, Jn(r, l, d, u)),
|
|
2889
|
+
Y(`${c.edit}/+page.svelte`, Hn(r, l, d)),
|
|
2890
|
+
Y(`${c.list}/server.test.ts`, St(r, l, i, e, s))
|
|
2556
2891
|
], p = [
|
|
2557
|
-
...
|
|
2892
|
+
...T(d),
|
|
2558
2893
|
"button",
|
|
2559
2894
|
"table",
|
|
2560
2895
|
"data-table",
|
|
@@ -2577,26 +2912,26 @@ async function gn(e) {
|
|
|
2577
2912
|
deletes: [],
|
|
2578
2913
|
components: [...new Set(p)],
|
|
2579
2914
|
packages: ["@tanstack/table-core"],
|
|
2580
|
-
collections: o ? [
|
|
2915
|
+
collections: o ? [Nt(r, i, a)] : []
|
|
2581
2916
|
};
|
|
2582
2917
|
}
|
|
2583
2918
|
//#endregion
|
|
2584
2919
|
//#region src/patterns/generate/scaffold/index.ts
|
|
2585
|
-
var
|
|
2586
|
-
async function
|
|
2587
|
-
let t = await
|
|
2588
|
-
if (e.env !== "runtime") return
|
|
2589
|
-
let { createCollections: n } = await import("./chunks/collections-
|
|
2920
|
+
var Xn = "generate-scaffold", Zn = "1.0.7", Qn = "src/patterns/generate/scaffold", $n = "/generate/scaffold";
|
|
2921
|
+
async function er(e) {
|
|
2922
|
+
let t = await Yn(e);
|
|
2923
|
+
if (e.env !== "runtime") return v(t);
|
|
2924
|
+
let { createCollections: n } = await import("./chunks/collections-CwH8DO-2.js"), r = await n(t.collections, e), i = {
|
|
2590
2925
|
...t,
|
|
2591
2926
|
creates: [...t.creates, ...r]
|
|
2592
|
-
}, { writeResult: a } = await import("./chunks/write-result-
|
|
2593
|
-
return a(await
|
|
2594
|
-
}
|
|
2595
|
-
var
|
|
2596
|
-
version:
|
|
2597
|
-
slug:
|
|
2598
|
-
source:
|
|
2599
|
-
docs:
|
|
2927
|
+
}, { writeResult: a } = await import("./chunks/write-result-C3SCX65t.js");
|
|
2928
|
+
return a(await v(i), e);
|
|
2929
|
+
}
|
|
2930
|
+
var tr = {
|
|
2931
|
+
version: Zn,
|
|
2932
|
+
slug: Xn,
|
|
2933
|
+
source: Qn,
|
|
2934
|
+
docs: $n,
|
|
2600
2935
|
plan: "open",
|
|
2601
2936
|
title: "Generate a scaffold",
|
|
2602
2937
|
summary: "Generates CRUD routes and schema.",
|
|
@@ -2640,19 +2975,361 @@ var Sn = {
|
|
|
2640
2975
|
],
|
|
2641
2976
|
tests: 8,
|
|
2642
2977
|
baseline: "velastack",
|
|
2643
|
-
generate:
|
|
2644
|
-
};
|
|
2978
|
+
generate: er
|
|
2979
|
+
}, nr, rr, ir, ar;
|
|
2980
|
+
function or(e) {
|
|
2981
|
+
let [t, ...n] = e;
|
|
2982
|
+
if (!t) throw new _("Invalid command arguments. Expected: <model> [fields...]");
|
|
2983
|
+
return {
|
|
2984
|
+
modelPath: t,
|
|
2985
|
+
fields: n
|
|
2986
|
+
};
|
|
2987
|
+
}
|
|
2988
|
+
function Z(e, n) {
|
|
2989
|
+
return {
|
|
2990
|
+
path: e,
|
|
2991
|
+
language: t(e),
|
|
2992
|
+
content: n,
|
|
2993
|
+
status: "success"
|
|
2994
|
+
};
|
|
2995
|
+
}
|
|
2996
|
+
function sr(e) {
|
|
2997
|
+
return e.some((e) => e.type === "file");
|
|
2998
|
+
}
|
|
2999
|
+
function cr(e) {
|
|
3000
|
+
return e.filter((e) => e.type === "select").map((e) => w(e)).join("\n\n");
|
|
3001
|
+
}
|
|
3002
|
+
function lr(e, t) {
|
|
3003
|
+
return H(e).map((e) => `const ${e.pluralName} = await ${t}.collection("${e.tableName}").getFullList();`).join("\n ");
|
|
3004
|
+
}
|
|
3005
|
+
function ur(e) {
|
|
3006
|
+
return H(e).map((e) => e.pluralName).join(", ");
|
|
3007
|
+
}
|
|
3008
|
+
function dr(e) {
|
|
3009
|
+
return e.features.auth ? "locals.pb" : "locals.admin";
|
|
3010
|
+
}
|
|
3011
|
+
function fr(e) {
|
|
3012
|
+
return `create${e.typeName}Form`;
|
|
3013
|
+
}
|
|
3014
|
+
function pr(e) {
|
|
3015
|
+
return `update${e.typeName}Form`;
|
|
3016
|
+
}
|
|
3017
|
+
function mr(e) {
|
|
3018
|
+
return H(e).length > 0;
|
|
3019
|
+
}
|
|
3020
|
+
function hr(t, n, r) {
|
|
3021
|
+
let i = fr(t), a = W(r), s = [
|
|
3022
|
+
`import { ${i} } from "./form.remote";`,
|
|
3023
|
+
"import { Button } from \"$lib/components/ui/button\";",
|
|
3024
|
+
"import ArrowLeftIcon from \"@lucide/svelte/icons/arrow-left\";",
|
|
3025
|
+
...Zt(a)
|
|
3026
|
+
].join("\n"), c = r.map((e) => an(e, { formVar: i })).join("\n"), l = sr(r) ? " enctype=\"multipart/form-data\"" : "";
|
|
3027
|
+
return e(nr ||= o([
|
|
3028
|
+
"\n <script lang=\"ts\">\n ",
|
|
3029
|
+
"\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 ",
|
|
3030
|
+
"</h1>\n <Button href=\"",
|
|
3031
|
+
"\" variant=\"outline\" size=\"sm\">\n <ArrowLeftIcon class=\"w-4 h-4\" />\n Back to list\n </Button>\n </div>\n\n <div class=\"bg-card rounded-lg shadow-sm border p-4\">\n <form {...",
|
|
3032
|
+
"}",
|
|
3033
|
+
">\n <div class=\"grid grid-cols-1 md:grid-cols-2 gap-4\">\n ",
|
|
3034
|
+
"\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=\"",
|
|
3035
|
+
"\" variant=\"outline\" size=\"sm\">Cancel</Button>\n </div>\n </form>\n </div>\n </section>\n "
|
|
3036
|
+
]), s, t.displayName.toLowerCase(), n.list, i, l, c, n.list);
|
|
3037
|
+
}
|
|
3038
|
+
function gr(t, n, r) {
|
|
3039
|
+
let i = pr(t), a = W(r), s = [
|
|
3040
|
+
`import { ${i} } from "./form.remote";`,
|
|
3041
|
+
"import { Button } from \"$lib/components/ui/button\";",
|
|
3042
|
+
"import ArrowLeftIcon from \"@lucide/svelte/icons/arrow-left\";",
|
|
3043
|
+
...Zt(a)
|
|
3044
|
+
].join("\n"), c = r.map((e) => an(e, { formVar: i })).join("\n"), l = sr(r) ? " enctype=\"multipart/form-data\"" : "";
|
|
3045
|
+
return e(rr ||= o([
|
|
3046
|
+
"\n <script lang=\"ts\">\n ",
|
|
3047
|
+
"\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 ",
|
|
3048
|
+
"</h1>\n <Button href=\"",
|
|
3049
|
+
"\" variant=\"outline\" size=\"sm\">\n <ArrowLeftIcon class=\"w-4 h-4\" />\n Back to list\n </Button>\n </div>\n\n <div class=\"bg-card rounded-lg shadow-sm border p-4\">\n <form {...",
|
|
3050
|
+
"}",
|
|
3051
|
+
">\n <input type=\"hidden\" name=\"id\" value={data.",
|
|
3052
|
+
".id} />\n <div class=\"grid grid-cols-1 md:grid-cols-2 gap-4\">\n ",
|
|
3053
|
+
"\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=\"",
|
|
3054
|
+
"/${params.id}\" variant=\"outline\" size=\"sm\">Cancel</Button>\n </div>\n </form>\n </div>\n </section>\n "
|
|
3055
|
+
], [
|
|
3056
|
+
"\n <script lang=\"ts\">\n ",
|
|
3057
|
+
"\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 ",
|
|
3058
|
+
"</h1>\n <Button href=\"",
|
|
3059
|
+
"\" variant=\"outline\" size=\"sm\">\n <ArrowLeftIcon class=\"w-4 h-4\" />\n Back to list\n </Button>\n </div>\n\n <div class=\"bg-card rounded-lg shadow-sm border p-4\">\n <form {...",
|
|
3060
|
+
"}",
|
|
3061
|
+
">\n <input type=\"hidden\" name=\"id\" value={data.",
|
|
3062
|
+
".id} />\n <div class=\"grid grid-cols-1 md:grid-cols-2 gap-4\">\n ",
|
|
3063
|
+
"\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=\"",
|
|
3064
|
+
"/\\${params.id}\" variant=\"outline\" size=\"sm\">Cancel</Button>\n </div>\n </form>\n </div>\n </section>\n "
|
|
3065
|
+
]), s, t.displayName.toLowerCase(), n.list, i, l, t.name, c, n.list);
|
|
3066
|
+
}
|
|
3067
|
+
function _r(t, n, r) {
|
|
3068
|
+
let i = r.some((e) => e.type === "select"), a = i ? `${cr(r)}` : "", s = r.map((t) => {
|
|
3069
|
+
let n = "{ getValue }", r = "{ value: getValue() }";
|
|
3070
|
+
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`
|
|
3071
|
+
columnHelper.accessor("${t.name}", {
|
|
3072
|
+
header: ({ column }) => renderComponent(ColumnHeader, { column, title: "${t.title}" }),
|
|
3073
|
+
cell: (${n}) => renderComponent(Cells.${t.type.charAt(0).toUpperCase() + t.type.slice(1)}Cell, ${r})
|
|
3074
|
+
})
|
|
3075
|
+
`;
|
|
3076
|
+
}).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");
|
|
3077
|
+
return e(ir ||= o([
|
|
3078
|
+
"\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 ",
|
|
3079
|
+
"\n import XIcon from \"@lucide/svelte/icons/x\";\n import PlusIcon from \"@lucide/svelte/icons/plus\";\n import type { Models } from \"pocketbase-svelte\";\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 ",
|
|
3080
|
+
"\n\n const columnHelper = createColumnHelper<Models[\"",
|
|
3081
|
+
"\"]>();\n const columns = [\n columnHelper.display({\n id: \"select\",\n header: ({ table }) =>\n renderComponent(Checkbox, {\n checked: table.getIsAllPageRowsSelected(),\n onCheckedChange: (value) => table.toggleAllPageRowsSelected(value),\n indeterminate: table.getIsSomePageRowsSelected() && !table.getIsAllPageRowsSelected(),\n \"aria-label\": \"Select all\"\n }),\n cell: ({ row }) =>\n renderComponent(Checkbox, {\n checked: row.getIsSelected(),\n onCheckedChange: (value) => row.toggleSelected(value),\n \"aria-label\": \"Select row\"\n }),\n enableSorting: false,\n enableHiding: false,\n meta: { class: \"w-0\" },\n }),\n ",
|
|
3082
|
+
"",
|
|
3083
|
+
"\n columnHelper.display({\n id: \"actions\",\n cell: ({ row }) =>\n renderComponent(RowActions, {\n viewPath: `",
|
|
3084
|
+
"/${row.original.id}`,\n editPath: `",
|
|
3085
|
+
"/${row.original.id}/edit`,\n deletePath: `",
|
|
3086
|
+
"/${row.original.id}`\n }),\n meta: { class: \"w-0 text-right\" },\n })\n ];\n\n const table = createSvelteTable({\n get data() {\n return data.",
|
|
3087
|
+
";\n },\n state: {\n get sorting() {\n return sorting;\n },\n get columnVisibility() {\n return columnVisibility;\n },\n get rowSelection() {\n return rowSelection;\n },\n get columnFilters() {\n return columnFilters;\n },\n get pagination() {\n return pagination;\n }\n },\n columns,\n enableRowSelection: true,\n onRowSelectionChange: (updater) => {\n rowSelection = typeof updater === \"function\" ? updater(rowSelection) : updater;\n },\n onSortingChange: (updater) => {\n sorting = typeof updater === \"function\" ? updater(sorting) : updater;\n },\n onColumnFiltersChange: (updater) => {\n columnFilters = typeof updater === \"function\" ? updater(columnFilters) : updater;\n },\n onColumnVisibilityChange: (updater) => {\n columnVisibility = typeof updater === \"function\" ? updater(columnVisibility) : updater;\n },\n onPaginationChange: (updater) => {\n pagination = typeof updater === \"function\" ? updater(pagination) : updater;\n },\n getCoreRowModel: getCoreRowModel(),\n getFilteredRowModel: getFilteredRowModel(),\n getPaginationRowModel: getPaginationRowModel(),\n getSortedRowModel: getSortedRowModel(),\n getFacetedRowModel: getFacetedRowModel(),\n getFacetedUniqueValues: getFacetedUniqueValues()\n });\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\">",
|
|
3088
|
+
"</h1>\n </div>\n\n <div class=\"space-y-4\">\n <div class=\"flex items-center justify-between\">\n <div class=\"flex flex-1 items-center space-x-2\">\n <Input\n placeholder=\"Filter ",
|
|
3089
|
+
"...\"\n value={(table.getColumn(\"name\")?.getFilterValue() as string) ?? \"\"}\n oninput={(e) => {\n table.getColumn(\"name\")?.setFilterValue(e.currentTarget.value);\n }}\n onchange={(e) => {\n table.getColumn(\"name\")?.setFilterValue(e.currentTarget.value);\n }}\n class=\"h-8 w-[150px] lg:w-[250px]\"\n />\n ",
|
|
3090
|
+
"\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=\"",
|
|
3091
|
+
"\" variant=\"outline\" size=\"sm\">\n <PlusIcon class=\"w-4 h-4\" />\n New ",
|
|
3092
|
+
"\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}>\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>\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 "
|
|
3093
|
+
], [
|
|
3094
|
+
"\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 ",
|
|
3095
|
+
"\n import XIcon from \"@lucide/svelte/icons/x\";\n import PlusIcon from \"@lucide/svelte/icons/plus\";\n import type { Models } from \"pocketbase-svelte\";\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 ",
|
|
3096
|
+
"\n\n const columnHelper = createColumnHelper<Models[\"",
|
|
3097
|
+
"\"]>();\n const columns = [\n columnHelper.display({\n id: \"select\",\n header: ({ table }) =>\n renderComponent(Checkbox, {\n checked: table.getIsAllPageRowsSelected(),\n onCheckedChange: (value) => table.toggleAllPageRowsSelected(value),\n indeterminate: table.getIsSomePageRowsSelected() && !table.getIsAllPageRowsSelected(),\n \"aria-label\": \"Select all\"\n }),\n cell: ({ row }) =>\n renderComponent(Checkbox, {\n checked: row.getIsSelected(),\n onCheckedChange: (value) => row.toggleSelected(value),\n \"aria-label\": \"Select row\"\n }),\n enableSorting: false,\n enableHiding: false,\n meta: { class: \"w-0\" },\n }),\n ",
|
|
3098
|
+
"",
|
|
3099
|
+
"\n columnHelper.display({\n id: \"actions\",\n cell: ({ row }) =>\n renderComponent(RowActions, {\n viewPath: \\`",
|
|
3100
|
+
"/\\${row.original.id}\\`,\n editPath: \\`",
|
|
3101
|
+
"/\\${row.original.id}/edit\\`,\n deletePath: \\`",
|
|
3102
|
+
"/\\${row.original.id}\\`\n }),\n meta: { class: \"w-0 text-right\" },\n })\n ];\n\n const table = createSvelteTable({\n get data() {\n return data.",
|
|
3103
|
+
";\n },\n state: {\n get sorting() {\n return sorting;\n },\n get columnVisibility() {\n return columnVisibility;\n },\n get rowSelection() {\n return rowSelection;\n },\n get columnFilters() {\n return columnFilters;\n },\n get pagination() {\n return pagination;\n }\n },\n columns,\n enableRowSelection: true,\n onRowSelectionChange: (updater) => {\n rowSelection = typeof updater === \"function\" ? updater(rowSelection) : updater;\n },\n onSortingChange: (updater) => {\n sorting = typeof updater === \"function\" ? updater(sorting) : updater;\n },\n onColumnFiltersChange: (updater) => {\n columnFilters = typeof updater === \"function\" ? updater(columnFilters) : updater;\n },\n onColumnVisibilityChange: (updater) => {\n columnVisibility = typeof updater === \"function\" ? updater(columnVisibility) : updater;\n },\n onPaginationChange: (updater) => {\n pagination = typeof updater === \"function\" ? updater(pagination) : updater;\n },\n getCoreRowModel: getCoreRowModel(),\n getFilteredRowModel: getFilteredRowModel(),\n getPaginationRowModel: getPaginationRowModel(),\n getSortedRowModel: getSortedRowModel(),\n getFacetedRowModel: getFacetedRowModel(),\n getFacetedUniqueValues: getFacetedUniqueValues()\n });\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\">",
|
|
3104
|
+
"</h1>\n </div>\n\n <div class=\"space-y-4\">\n <div class=\"flex items-center justify-between\">\n <div class=\"flex flex-1 items-center space-x-2\">\n <Input\n placeholder=\"Filter ",
|
|
3105
|
+
"...\"\n value={(table.getColumn(\"name\")?.getFilterValue() as string) ?? \"\"}\n oninput={(e) => {\n table.getColumn(\"name\")?.setFilterValue(e.currentTarget.value);\n }}\n onchange={(e) => {\n table.getColumn(\"name\")?.setFilterValue(e.currentTarget.value);\n }}\n class=\"h-8 w-[150px] lg:w-[250px]\"\n />\n ",
|
|
3106
|
+
"\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=\"",
|
|
3107
|
+
"\" variant=\"outline\" size=\"sm\">\n <PlusIcon class=\"w-4 h-4\" />\n New ",
|
|
3108
|
+
"\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}>\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>\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 "
|
|
3109
|
+
]), 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());
|
|
3110
|
+
}
|
|
3111
|
+
function vr(t, n, r) {
|
|
3112
|
+
let i = V(n), a = i ? `{ expand: "${i}" }` : "";
|
|
3113
|
+
return e`
|
|
3114
|
+
export const load = async ({ locals }) => {
|
|
3115
|
+
const ${t.pluralName} = await ${r}.collection("${t.tableName}").getFullList(${a});
|
|
3116
|
+
return { ${t.pluralName} };
|
|
3117
|
+
};
|
|
3118
|
+
`;
|
|
3119
|
+
}
|
|
3120
|
+
function yr(t, n, r) {
|
|
3121
|
+
return mr(n) ? e`
|
|
3122
|
+
export const load = async ({ locals }) => {
|
|
3123
|
+
${lr(n, r)}
|
|
3124
|
+
return { ${ur(n)} };
|
|
3125
|
+
};
|
|
3126
|
+
` : "";
|
|
3127
|
+
}
|
|
3128
|
+
function br(t, n, r, i, a) {
|
|
3129
|
+
let o = fr(t), s = r.find((e) => e.type === "relation" && e.isCurrentUser), c = a && s ? e`
|
|
3130
|
+
{
|
|
3131
|
+
...data,
|
|
3132
|
+
${s.name}: locals.pb.authStore.record?.id
|
|
3133
|
+
}
|
|
3134
|
+
` : "data";
|
|
3135
|
+
return e`
|
|
3136
|
+
import { form, getRequestEvent } from "$app/server";
|
|
3137
|
+
import { redirect } from "@sveltejs/kit";
|
|
3138
|
+
import { ${t.schemaName} } from "$lib/schemas/${t.name}";
|
|
3139
|
+
|
|
3140
|
+
export const ${o} = form(${t.schemaName}, async (data) => {
|
|
3141
|
+
const { locals } = getRequestEvent();
|
|
3142
|
+
const ${t.name} = await ${i}.collection("${t.tableName}").create(
|
|
3143
|
+
${c}
|
|
3144
|
+
);
|
|
3145
|
+
redirect(303, \`${n.list}/\${${t.name}.id}\`);
|
|
3146
|
+
});
|
|
3147
|
+
`;
|
|
3148
|
+
}
|
|
3149
|
+
function xr(t, n, r, i) {
|
|
3150
|
+
let a = V(r), o = a ? `, { expand: "${a}" }` : "";
|
|
3151
|
+
return e`
|
|
3152
|
+
import { error, redirect } from "@sveltejs/kit";
|
|
3153
|
+
|
|
3154
|
+
export const load = async ({ locals, params }) => {
|
|
3155
|
+
try {
|
|
3156
|
+
const ${t.name} = await ${i}.collection("${t.tableName}").getOne(params.id${o});
|
|
3157
|
+
return { ${t.name} };
|
|
3158
|
+
} catch {
|
|
3159
|
+
throw error(404, "Not found");
|
|
3160
|
+
}
|
|
3161
|
+
};
|
|
3162
|
+
|
|
3163
|
+
export const actions = {
|
|
3164
|
+
default: async ({ locals, params }) => {
|
|
3165
|
+
await ${i}.collection("${t.tableName}").delete(params.id);
|
|
3166
|
+
throw redirect(303, "${n.list}");
|
|
3167
|
+
},
|
|
3168
|
+
};
|
|
3169
|
+
`;
|
|
3170
|
+
}
|
|
3171
|
+
function Sr(t, n, r) {
|
|
3172
|
+
let i = r.some((e) => e.type === "select"), a = r.some((e) => e.type === "relation"), s = r.some((e) => e.type === "file"), c = [
|
|
3173
|
+
"import { Button } from \"$lib/components/ui/button\";",
|
|
3174
|
+
"import ArrowLeftIcon from \"@lucide/svelte/icons/arrow-left\";",
|
|
3175
|
+
i || a ? "import { Badge } from \"$lib/components/ui/badge\";" : "",
|
|
3176
|
+
a ? "import CircleArrowRightIcon from \"@lucide/svelte/icons/circle-arrow-right\";" : "",
|
|
3177
|
+
s ? "import FileIcon from \"@lucide/svelte/icons/file\";" : ""
|
|
3178
|
+
].filter(Boolean).join("\n"), l = cr(r), u = r.map((e) => Te(t, e)).join("\n");
|
|
3179
|
+
return e(ar ||= o([
|
|
3180
|
+
"\n <script lang=\"ts\">\n ",
|
|
3181
|
+
"\n ",
|
|
3182
|
+
"\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\">",
|
|
3183
|
+
" details</h1>\n <Button href=\"",
|
|
3184
|
+
"\" variant=\"outline\" size=\"sm\">\n <ArrowLeftIcon class=\"w-4 h-4\" />\n Back to list\n </Button>\n </div>\n\n <div class=\"bg-card rounded-lg shadow-sm border p-4\">\n <div class=\"grid grid-cols-1 md:grid-cols-2 gap-4 text-sm\">\n ",
|
|
3185
|
+
"\n </div>\n\n <div class=\"mt-4 flex gap-2 border-t pt-4 -mx-4 px-4 justify-between\">\n <Button href=\"",
|
|
3186
|
+
"/{data.",
|
|
3187
|
+
".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 "
|
|
3188
|
+
]), c, l, t.displayName, n.list, u, n.list, t.name);
|
|
3189
|
+
}
|
|
3190
|
+
function Cr(t, n, r) {
|
|
3191
|
+
let i = lr(n, r), a = ur(n), o = a ? `, ${a}` : "";
|
|
3192
|
+
return e`
|
|
3193
|
+
import { error } from "@sveltejs/kit";
|
|
3194
|
+
|
|
3195
|
+
export const load = async ({ locals, params }) => {
|
|
3196
|
+
let ${t.name};
|
|
3197
|
+
try {
|
|
3198
|
+
${t.name} = await ${r}.collection("${t.tableName}").getOne(params.id);
|
|
3199
|
+
} catch {
|
|
3200
|
+
throw error(404, "Not found");
|
|
3201
|
+
}
|
|
3202
|
+
${i}
|
|
3203
|
+
return { ${t.name}${o} };
|
|
3204
|
+
};
|
|
3205
|
+
`;
|
|
3206
|
+
}
|
|
3207
|
+
function wr(t, n, r) {
|
|
3208
|
+
let i = pr(t);
|
|
3209
|
+
return e`
|
|
3210
|
+
import { form, getRequestEvent, error } from "$app/server";
|
|
3211
|
+
import { redirect } from "@sveltejs/kit";
|
|
3212
|
+
import { ${t.schemaName} } from "$lib/schemas/${t.name}";
|
|
3213
|
+
|
|
3214
|
+
export const ${i} = form(${t.schemaName}, async (data) => {
|
|
3215
|
+
const { locals } = getRequestEvent();
|
|
3216
|
+
const { id, collectionId, ...rest } = data;
|
|
3217
|
+
if (!id) error(400, "id is required");
|
|
3218
|
+
await ${r}.collection("${t.tableName}").update(id, rest);
|
|
3219
|
+
redirect(303, \`${n.list}/\${id}\`);
|
|
3220
|
+
});
|
|
3221
|
+
`;
|
|
3222
|
+
}
|
|
3223
|
+
async function Tr(e) {
|
|
3224
|
+
let { modelPath: t, fields: n } = or(e.argv), { model: r, fields: i, auth: a, shouldCreateCollection: o, collections: s } = await z(e, t, n), c = qe(r), l = Je(r), u = dr(e), d = i.filter((e) => !(e.type === "relation" && e.isCurrentUser)), f = [
|
|
3225
|
+
Z(`src/lib/schemas/${r.name}.ts`, B(r, i, {
|
|
3226
|
+
includeModelFields: !0,
|
|
3227
|
+
forForm: !0
|
|
3228
|
+
})),
|
|
3229
|
+
Z(`${c.list}/+page.server.ts`, vr(r, d, u)),
|
|
3230
|
+
Z(`${c.list}/+page.svelte`, _r(r, l, d))
|
|
3231
|
+
], p = yr(r, d, u);
|
|
3232
|
+
p && f.push(Z(`${c.new}/+page.server.ts`, p)), f.push(Z(`${c.new}/form.remote.ts`, br(r, l, i, u, e.features.auth)), Z(`${c.new}/+page.svelte`, hr(r, l, d)), Z(`${c.show}/+page.server.ts`, xr(r, l, d, u)), Z(`${c.show}/+page.svelte`, Sr(r, l, d)), Z(`${c.edit}/+page.server.ts`, Cr(r, d, u)), Z(`${c.edit}/form.remote.ts`, wr(r, l, u)), Z(`${c.edit}/+page.svelte`, gr(r, l, d)), Z(`${c.list}/server.test.ts`, Ct(r, l, i, e, s)));
|
|
3233
|
+
let m = [
|
|
3234
|
+
...W(d),
|
|
3235
|
+
"button",
|
|
3236
|
+
"table",
|
|
3237
|
+
"data-table",
|
|
3238
|
+
"popover",
|
|
3239
|
+
"separator",
|
|
3240
|
+
"badge",
|
|
3241
|
+
"dropdown-menu",
|
|
3242
|
+
"checkbox",
|
|
3243
|
+
"select",
|
|
3244
|
+
"cells",
|
|
3245
|
+
"column-header",
|
|
3246
|
+
"faceted-filter",
|
|
3247
|
+
"pagination",
|
|
3248
|
+
"row-actions"
|
|
3249
|
+
];
|
|
3250
|
+
return {
|
|
3251
|
+
creates: f,
|
|
3252
|
+
modifies: [],
|
|
3253
|
+
deletes: [],
|
|
3254
|
+
components: [...new Set(m)],
|
|
3255
|
+
packages: ["@tanstack/table-core"],
|
|
3256
|
+
collections: o ? [Nt(r, i, a)] : []
|
|
3257
|
+
};
|
|
3258
|
+
}
|
|
3259
|
+
//#endregion
|
|
3260
|
+
//#region src/patterns/generate/scaffold-remote/index.ts
|
|
3261
|
+
var Er = "generate-scaffold-remote", Dr = "1.0.0", Or = "src/patterns/generate/scaffold-remote", kr = "/generate/scaffold-remote";
|
|
3262
|
+
async function Ar(e) {
|
|
3263
|
+
let t = await Tr(e);
|
|
3264
|
+
if (e.env !== "runtime") return v(t);
|
|
3265
|
+
let { createCollections: n } = await import("./chunks/collections-CwH8DO-2.js"), r = await n(t.collections, e), i = {
|
|
3266
|
+
...t,
|
|
3267
|
+
creates: [...t.creates, ...r]
|
|
3268
|
+
}, { writeResult: a } = await import("./chunks/write-result-C3SCX65t.js");
|
|
3269
|
+
return a(await v(i), e);
|
|
3270
|
+
}
|
|
3271
|
+
var jr = {
|
|
3272
|
+
version: Dr,
|
|
3273
|
+
slug: Er,
|
|
3274
|
+
source: Or,
|
|
3275
|
+
docs: kr,
|
|
3276
|
+
plan: "open",
|
|
3277
|
+
title: "Generate a scaffold (remote functions)",
|
|
3278
|
+
summary: "Generates CRUD routes and schema using SvelteKit remote functions for create/update forms.",
|
|
3279
|
+
requires: {
|
|
3280
|
+
auth: !1,
|
|
3281
|
+
api: !1,
|
|
3282
|
+
apiKeys: !1,
|
|
3283
|
+
i18n: !1,
|
|
3284
|
+
teams: !1,
|
|
3285
|
+
payments: !1
|
|
3286
|
+
},
|
|
3287
|
+
category: "generators",
|
|
3288
|
+
tags: [
|
|
3289
|
+
"crud",
|
|
3290
|
+
"scaffold",
|
|
3291
|
+
"pocketbase",
|
|
3292
|
+
"sveltekit",
|
|
3293
|
+
"remote-functions"
|
|
3294
|
+
],
|
|
3295
|
+
command: {
|
|
3296
|
+
raw: "vela generate scaffold --remote contact name:text email:email",
|
|
3297
|
+
base: "vela generate scaffold --remote",
|
|
3298
|
+
argv: [
|
|
3299
|
+
"contact",
|
|
3300
|
+
"name:text",
|
|
3301
|
+
"email:email"
|
|
3302
|
+
]
|
|
3303
|
+
},
|
|
3304
|
+
examples: [
|
|
3305
|
+
{
|
|
3306
|
+
command: "todos title:text! done:bool",
|
|
3307
|
+
description: "Todos with required title and boolean flag."
|
|
3308
|
+
},
|
|
3309
|
+
{
|
|
3310
|
+
command: "pets type:select(dog:Dog,cat:Cat) owner:user",
|
|
3311
|
+
description: "Enum field and a one-to-many relation to user."
|
|
3312
|
+
},
|
|
3313
|
+
{
|
|
3314
|
+
command: "users/pets name:text! author:current_user",
|
|
3315
|
+
description: "Nested resource with auth-bound author."
|
|
3316
|
+
}
|
|
3317
|
+
],
|
|
3318
|
+
tests: 6,
|
|
3319
|
+
baseline: "velastack",
|
|
3320
|
+
generate: Ar
|
|
3321
|
+
};
|
|
2645
3322
|
//#endregion
|
|
2646
3323
|
//#region src/patterns/generate/schema/generate.ts
|
|
2647
|
-
function
|
|
3324
|
+
function Mr(e) {
|
|
2648
3325
|
let [t, ...n] = e;
|
|
2649
|
-
if (!t) throw new
|
|
3326
|
+
if (!t) throw new _("Invalid command arguments. Expected: <model> [fields...]");
|
|
2650
3327
|
return {
|
|
2651
3328
|
modelPath: t,
|
|
2652
3329
|
fields: n
|
|
2653
3330
|
};
|
|
2654
3331
|
}
|
|
2655
|
-
function
|
|
3332
|
+
function Nr(e, n) {
|
|
2656
3333
|
return {
|
|
2657
3334
|
path: e,
|
|
2658
3335
|
language: t(e),
|
|
@@ -2660,10 +3337,10 @@ function wn(e, n) {
|
|
|
2660
3337
|
status: "success"
|
|
2661
3338
|
};
|
|
2662
3339
|
}
|
|
2663
|
-
async function
|
|
2664
|
-
let { modelPath: t, fields: n } =
|
|
3340
|
+
async function Pr(e) {
|
|
3341
|
+
let { modelPath: t, fields: n } = Mr(e.argv), { model: r, fields: i, shouldCreateCollection: a } = await z(e, t, n);
|
|
2665
3342
|
return {
|
|
2666
|
-
creates: [
|
|
3343
|
+
creates: [Nr(`src/lib/schemas/${r.name}.ts`, B(r, i, {
|
|
2667
3344
|
includeModelFields: !a,
|
|
2668
3345
|
forForm: !0
|
|
2669
3346
|
}))],
|
|
@@ -2676,18 +3353,18 @@ async function Tn(e) {
|
|
|
2676
3353
|
}
|
|
2677
3354
|
//#endregion
|
|
2678
3355
|
//#region src/patterns/generate/schema/index.ts
|
|
2679
|
-
var
|
|
2680
|
-
async function
|
|
2681
|
-
let t = await
|
|
2682
|
-
if (e.env !== "runtime") return
|
|
2683
|
-
let { writeResult: n } = await import("./chunks/write-result-
|
|
2684
|
-
return n(await
|
|
2685
|
-
}
|
|
2686
|
-
var
|
|
2687
|
-
version:
|
|
2688
|
-
slug:
|
|
2689
|
-
source:
|
|
2690
|
-
docs:
|
|
3356
|
+
var Fr = "generate-schema", Ir = "1.0.7", Lr = "src/patterns/generate/schema", Rr = "/generate/schema";
|
|
3357
|
+
async function zr(e) {
|
|
3358
|
+
let t = await Pr(e);
|
|
3359
|
+
if (e.env !== "runtime") return v(t);
|
|
3360
|
+
let { writeResult: n } = await import("./chunks/write-result-C3SCX65t.js");
|
|
3361
|
+
return n(await v(t), e);
|
|
3362
|
+
}
|
|
3363
|
+
var Br = {
|
|
3364
|
+
version: Ir,
|
|
3365
|
+
slug: Fr,
|
|
3366
|
+
source: Lr,
|
|
3367
|
+
docs: Rr,
|
|
2691
3368
|
plan: "open",
|
|
2692
3369
|
title: "Generate a schema",
|
|
2693
3370
|
summary: "Generates a zod schema.",
|
|
@@ -2730,8 +3407,8 @@ var jn = {
|
|
|
2730
3407
|
],
|
|
2731
3408
|
tests: 0,
|
|
2732
3409
|
baseline: "velastack",
|
|
2733
|
-
generate:
|
|
2734
|
-
},
|
|
3410
|
+
generate: zr
|
|
3411
|
+
}, Vr = /* @__PURE__ */ Object.assign({
|
|
2735
3412
|
"./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",
|
|
2736
3413
|
"./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",
|
|
2737
3414
|
"./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",
|
|
@@ -2773,10 +3450,10 @@ var jn = {
|
|
|
2773
3450
|
"./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",
|
|
2774
3451
|
"./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-svelte';\n import { goto } from '$app/navigation';\n import { page } from '$app/state';\n\n let { data } = $props();\n let { authMethods } = data;\n\n const redirect = page.url.searchParams.get('redirect');\n const hasOAuth2 = authMethods.oauth2.enabled && authMethods.oauth2.providers.length > 0;\n const hasAuthMethods = authMethods.password.enabled || authMethods.otp.enabled || hasOAuth2;\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>Check back later for signup options</Card.Description>\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 class=\"bg-card text-muted-foreground relative z-10 px-2\">\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 {...props} type=\"email\" bind:value={$formData.email} required />\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 ? `?redirect=${encodeURIComponent(redirect)}` : ''}\"\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\">Terms of Service</a>\n and <a href=\"/privacy\">Privacy Policy</a>.\n </div>\n </div>\n </div>\n</div>\n",
|
|
2775
3452
|
"./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"
|
|
2776
|
-
}),
|
|
2777
|
-
async function
|
|
2778
|
-
let n = Object.entries(
|
|
2779
|
-
let i = r(e,
|
|
3453
|
+
}), Hr = "./creates/";
|
|
3454
|
+
async function Ur(e) {
|
|
3455
|
+
let n = Object.entries(Vr).map(([e, n]) => {
|
|
3456
|
+
let i = r(e, Hr);
|
|
2780
3457
|
return {
|
|
2781
3458
|
path: i,
|
|
2782
3459
|
language: t(i),
|
|
@@ -2868,16 +3545,16 @@ async function Pn(e) {
|
|
|
2868
3545
|
}
|
|
2869
3546
|
//#endregion
|
|
2870
3547
|
//#region src/patterns/enable/auth/generate.preview.ts
|
|
2871
|
-
var
|
|
3548
|
+
var Wr = /* @__PURE__ */ Object.assign({
|
|
2872
3549
|
"./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",
|
|
2873
3550
|
"./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 © {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",
|
|
2874
3551
|
"./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"
|
|
2875
|
-
}),
|
|
2876
|
-
async function
|
|
3552
|
+
}), Gr = "./preview-modifies/";
|
|
3553
|
+
async function Kr(e) {
|
|
2877
3554
|
return {
|
|
2878
3555
|
creates: [],
|
|
2879
|
-
modifies: Object.entries(
|
|
2880
|
-
let i = r(e,
|
|
3556
|
+
modifies: Object.entries(Wr).map(([e, n]) => {
|
|
3557
|
+
let i = r(e, Gr);
|
|
2881
3558
|
return {
|
|
2882
3559
|
path: i,
|
|
2883
3560
|
language: t(i),
|
|
@@ -2893,18 +3570,18 @@ async function Ln(e) {
|
|
|
2893
3570
|
}
|
|
2894
3571
|
//#endregion
|
|
2895
3572
|
//#region src/patterns/enable/auth/index.ts
|
|
2896
|
-
var
|
|
2897
|
-
async function
|
|
2898
|
-
let t = await
|
|
2899
|
-
if (e.env === "preview") return
|
|
2900
|
-
let { generate: r } = await import("./chunks/generate.runtime-
|
|
2901
|
-
return a(await
|
|
2902
|
-
}
|
|
2903
|
-
var
|
|
2904
|
-
version:
|
|
2905
|
-
slug:
|
|
2906
|
-
source:
|
|
2907
|
-
docs:
|
|
3573
|
+
var qr = "enable-auth", Jr = "1.0.7", Yr = "src/patterns/enable/auth", Xr = "/enable/auth";
|
|
3574
|
+
async function Zr(e) {
|
|
3575
|
+
let t = await Ur(e);
|
|
3576
|
+
if (e.env === "preview") return v(n([t, await Kr(e)]));
|
|
3577
|
+
let { generate: r } = await import("./chunks/generate.runtime-B3WXGKZY.js"), i = await r(e), { writeResult: a } = await import("./chunks/write-result-C3SCX65t.js");
|
|
3578
|
+
return a(await v(n([t, i])), e);
|
|
3579
|
+
}
|
|
3580
|
+
var Qr = {
|
|
3581
|
+
version: Jr,
|
|
3582
|
+
slug: qr,
|
|
3583
|
+
source: Yr,
|
|
3584
|
+
docs: Xr,
|
|
2908
3585
|
plan: "open",
|
|
2909
3586
|
title: "Enable authentication",
|
|
2910
3587
|
summary: "Enables authentication.",
|
|
@@ -2933,12 +3610,12 @@ var Un = {
|
|
|
2933
3610
|
examples: [],
|
|
2934
3611
|
tests: 18,
|
|
2935
3612
|
baseline: "velastack",
|
|
2936
|
-
generate:
|
|
2937
|
-
},
|
|
2938
|
-
async function
|
|
3613
|
+
generate: Zr
|
|
3614
|
+
}, $r = /* @__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" }), ei = "./creates/";
|
|
3615
|
+
async function ti(e) {
|
|
2939
3616
|
return {
|
|
2940
|
-
creates: Object.entries(
|
|
2941
|
-
let i = r(e,
|
|
3617
|
+
creates: Object.entries($r).map(([e, n]) => {
|
|
3618
|
+
let i = r(e, ei);
|
|
2942
3619
|
return {
|
|
2943
3620
|
path: i,
|
|
2944
3621
|
language: t(i),
|
|
@@ -2955,12 +3632,12 @@ async function Kn(e) {
|
|
|
2955
3632
|
}
|
|
2956
3633
|
//#endregion
|
|
2957
3634
|
//#region src/patterns/enable/api/generate.preview.ts
|
|
2958
|
-
var
|
|
2959
|
-
async function
|
|
3635
|
+
var ni = /* @__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" }), ri = "./preview-modifies/";
|
|
3636
|
+
async function ii(e) {
|
|
2960
3637
|
return {
|
|
2961
3638
|
creates: [],
|
|
2962
|
-
modifies: Object.entries(
|
|
2963
|
-
let i = r(e,
|
|
3639
|
+
modifies: Object.entries(ni).map(([e, n]) => {
|
|
3640
|
+
let i = r(e, ri);
|
|
2964
3641
|
return {
|
|
2965
3642
|
path: i,
|
|
2966
3643
|
language: t(i),
|
|
@@ -2976,18 +3653,18 @@ async function Yn(e) {
|
|
|
2976
3653
|
}
|
|
2977
3654
|
//#endregion
|
|
2978
3655
|
//#region src/patterns/enable/api/index.ts
|
|
2979
|
-
var
|
|
2980
|
-
async function
|
|
2981
|
-
let t = await
|
|
2982
|
-
if (e.env === "preview") return
|
|
2983
|
-
let { generate: r } = await import("./chunks/generate.runtime-
|
|
2984
|
-
return a(await
|
|
2985
|
-
}
|
|
2986
|
-
var
|
|
2987
|
-
version:
|
|
2988
|
-
slug:
|
|
2989
|
-
source:
|
|
2990
|
-
docs:
|
|
3656
|
+
var ai = "enable-api", oi = "1.0.7", si = "src/patterns/enable/api", ci = "/enable/api";
|
|
3657
|
+
async function li(e) {
|
|
3658
|
+
let t = await ti(e);
|
|
3659
|
+
if (e.env === "preview") return v(n([t, await ii(e)]));
|
|
3660
|
+
let { generate: r } = await import("./chunks/generate.runtime-Bhqdiykw.js"), i = await r(e), { writeResult: a } = await import("./chunks/write-result-C3SCX65t.js");
|
|
3661
|
+
return a(await v(n([t, i])), e);
|
|
3662
|
+
}
|
|
3663
|
+
var ui = {
|
|
3664
|
+
version: oi,
|
|
3665
|
+
slug: ai,
|
|
3666
|
+
source: si,
|
|
3667
|
+
docs: ci,
|
|
2991
3668
|
plan: "open",
|
|
2992
3669
|
title: "Enable API",
|
|
2993
3670
|
summary: "Enables the PocketBase API.",
|
|
@@ -3016,8 +3693,8 @@ var tr = {
|
|
|
3016
3693
|
examples: [],
|
|
3017
3694
|
tests: 1,
|
|
3018
3695
|
baseline: "velastack",
|
|
3019
|
-
generate:
|
|
3020
|
-
},
|
|
3696
|
+
generate: li
|
|
3697
|
+
}, di = /* @__PURE__ */ Object.assign({
|
|
3021
3698
|
"./creates/src/lib/schemas/apiKey.ts": "import { z } from \"zod\";\nimport type { Schemas } from \"pocketbase-svelte\";\n\nexport const apiKeySchema = z.object({\n label: z.string().optional(),\n}) satisfies Schemas[\"api_keys\"];\n",
|
|
3022
3699
|
"./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",
|
|
3023
3700
|
"./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",
|
|
@@ -3027,11 +3704,11 @@ var tr = {
|
|
|
3027
3704
|
"./creates/src/routes/(app)/api-keys/new/create-api-key.ts": "import PocketBase from \"pocketbase-svelte\";\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",
|
|
3028
3705
|
"./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",
|
|
3029
3706
|
"./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"
|
|
3030
|
-
}),
|
|
3031
|
-
async function
|
|
3707
|
+
}), fi = "./creates/";
|
|
3708
|
+
async function pi(e) {
|
|
3032
3709
|
return {
|
|
3033
|
-
creates: Object.entries(
|
|
3034
|
-
let i = r(e,
|
|
3710
|
+
creates: Object.entries(di).map(([e, n]) => {
|
|
3711
|
+
let i = r(e, fi);
|
|
3035
3712
|
return {
|
|
3036
3713
|
path: i,
|
|
3037
3714
|
language: t(i),
|
|
@@ -3052,12 +3729,12 @@ async function ir(e) {
|
|
|
3052
3729
|
}
|
|
3053
3730
|
//#endregion
|
|
3054
3731
|
//#region src/patterns/enable/api-keys/generate.preview.ts
|
|
3055
|
-
var
|
|
3056
|
-
async function
|
|
3732
|
+
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" }), hi = "./preview-modifies/";
|
|
3733
|
+
async function gi(e) {
|
|
3057
3734
|
return {
|
|
3058
3735
|
creates: [],
|
|
3059
|
-
modifies: Object.entries(
|
|
3060
|
-
let i = r(e,
|
|
3736
|
+
modifies: Object.entries(mi).map(([e, n]) => {
|
|
3737
|
+
let i = r(e, hi);
|
|
3061
3738
|
return {
|
|
3062
3739
|
path: i,
|
|
3063
3740
|
language: t(i),
|
|
@@ -3073,18 +3750,18 @@ async function sr(e) {
|
|
|
3073
3750
|
}
|
|
3074
3751
|
//#endregion
|
|
3075
3752
|
//#region src/patterns/enable/api-keys/index.ts
|
|
3076
|
-
var
|
|
3077
|
-
async function
|
|
3078
|
-
let t = await
|
|
3079
|
-
if (e.env === "preview") return
|
|
3080
|
-
let { generate: r } = await import("./chunks/generate.runtime-
|
|
3081
|
-
return a(await
|
|
3082
|
-
}
|
|
3083
|
-
var
|
|
3084
|
-
version:
|
|
3085
|
-
slug:
|
|
3086
|
-
source:
|
|
3087
|
-
docs:
|
|
3753
|
+
var _i = "enable-api-keys", vi = "1.0.0", yi = "src/patterns/enable/api-keys", bi = "/enable/api-keys";
|
|
3754
|
+
async function xi(e) {
|
|
3755
|
+
let t = await pi(e);
|
|
3756
|
+
if (e.env === "preview") return v(n([t, await gi(e)]));
|
|
3757
|
+
let { generate: r } = await import("./chunks/generate.runtime-CzKWz6BN.js"), i = await r(e), { writeResult: a } = await import("./chunks/write-result-C3SCX65t.js");
|
|
3758
|
+
return a(await v(n([t, i])), e);
|
|
3759
|
+
}
|
|
3760
|
+
var Si = {
|
|
3761
|
+
version: vi,
|
|
3762
|
+
slug: _i,
|
|
3763
|
+
source: yi,
|
|
3764
|
+
docs: bi,
|
|
3088
3765
|
plan: "open",
|
|
3089
3766
|
title: "Enable API keys",
|
|
3090
3767
|
summary: "Adds API key management for authenticated users and PocketBase API access.",
|
|
@@ -3113,16 +3790,16 @@ var pr = {
|
|
|
3113
3790
|
examples: [],
|
|
3114
3791
|
tests: 6,
|
|
3115
3792
|
baseline: "velastack",
|
|
3116
|
-
generate:
|
|
3117
|
-
},
|
|
3793
|
+
generate: xi
|
|
3794
|
+
}, Ci = /* @__PURE__ */ Object.assign({
|
|
3118
3795
|
"./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",
|
|
3119
3796
|
"./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",
|
|
3120
3797
|
"./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"
|
|
3121
|
-
}),
|
|
3122
|
-
async function
|
|
3798
|
+
}), wi = "./creates/";
|
|
3799
|
+
async function Ti(e) {
|
|
3123
3800
|
return {
|
|
3124
|
-
creates: Object.entries(
|
|
3125
|
-
let i = r(e,
|
|
3801
|
+
creates: Object.entries(Ci).map(([e, n]) => {
|
|
3802
|
+
let i = r(e, wi);
|
|
3126
3803
|
return {
|
|
3127
3804
|
path: i,
|
|
3128
3805
|
language: t(i),
|
|
@@ -3139,18 +3816,18 @@ async function gr(e) {
|
|
|
3139
3816
|
}
|
|
3140
3817
|
//#endregion
|
|
3141
3818
|
//#region src/patterns/enable/i18n/generate.preview.ts
|
|
3142
|
-
var
|
|
3819
|
+
var Ei = /* @__PURE__ */ Object.assign({
|
|
3143
3820
|
"./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",
|
|
3144
3821
|
"./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",
|
|
3145
3822
|
"./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",
|
|
3146
3823
|
"./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",
|
|
3147
3824
|
"./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"
|
|
3148
|
-
}),
|
|
3149
|
-
async function
|
|
3825
|
+
}), Di = "./preview-modifies/";
|
|
3826
|
+
async function Oi(e) {
|
|
3150
3827
|
return {
|
|
3151
3828
|
creates: [],
|
|
3152
|
-
modifies: Object.entries(
|
|
3153
|
-
let i = r(e,
|
|
3829
|
+
modifies: Object.entries(Ei).map(([e, n]) => {
|
|
3830
|
+
let i = r(e, Di);
|
|
3154
3831
|
return {
|
|
3155
3832
|
path: i,
|
|
3156
3833
|
language: t(i),
|
|
@@ -3166,18 +3843,18 @@ async function yr(e) {
|
|
|
3166
3843
|
}
|
|
3167
3844
|
//#endregion
|
|
3168
3845
|
//#region src/patterns/enable/i18n/index.ts
|
|
3169
|
-
var
|
|
3170
|
-
async function
|
|
3171
|
-
let t = await
|
|
3172
|
-
if (e.env === "preview") return
|
|
3173
|
-
let { generate: r } = await import("./chunks/generate.runtime-
|
|
3174
|
-
return a(await
|
|
3175
|
-
}
|
|
3176
|
-
var
|
|
3177
|
-
version:
|
|
3178
|
-
slug:
|
|
3179
|
-
source:
|
|
3180
|
-
docs:
|
|
3846
|
+
var ki = "enable-i18n", Ai = "1.0.0", ji = "src/patterns/enable/i18n", Mi = "/enable/i18n";
|
|
3847
|
+
async function Ni(e) {
|
|
3848
|
+
let t = await Ti(e);
|
|
3849
|
+
if (e.env === "preview") return v(n([t, await Oi(e)]));
|
|
3850
|
+
let { generate: r } = await import("./chunks/generate.runtime-DVRoiEhh.js"), i = await r(e), { writeResult: a } = await import("./chunks/write-result-C3SCX65t.js");
|
|
3851
|
+
return a(await v(n([t, i])), e);
|
|
3852
|
+
}
|
|
3853
|
+
var Pi = {
|
|
3854
|
+
version: Ai,
|
|
3855
|
+
slug: ki,
|
|
3856
|
+
source: ji,
|
|
3857
|
+
docs: Mi,
|
|
3181
3858
|
plan: "open",
|
|
3182
3859
|
title: "Enable i18n",
|
|
3183
3860
|
summary: "Enables i18n with Wuchale and locale-aware routing.",
|
|
@@ -3205,8 +3882,419 @@ var Tr = {
|
|
|
3205
3882
|
examples: [],
|
|
3206
3883
|
tests: 0,
|
|
3207
3884
|
baseline: "velastack",
|
|
3208
|
-
generate:
|
|
3209
|
-
}, Er = /* @__PURE__ */ Object.assign({
|
|
3885
|
+
generate: Ni
|
|
3886
|
+
}, Fi = "/// <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", Ii = "/// <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", Li = "<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", Ri = "<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", zi = "<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", Bi = "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", Vi = "<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", Hi = "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", Ui = "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", Wi = "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", Gi = "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", Ki = "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", qi = "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", Ji = "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", Yi = "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", Xi = "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", Zi = "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", Qi = "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", $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\ncronAdd(\"stripe-customers\", \"* * * * *\", () => {\n const utils = require(`${__hooks}/utils.js`);\n utils.triggerJob(\"/api/stripe/sync/customers\");\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 { 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", na = "<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", ra = "export const load = async ({ parent }) => {\n const { breadcrumbs } = await parent();\n\n return {\n breadcrumbs: [...breadcrumbs, { title: \"Billing\", url: \"/billing\" }],\n };\n};\n", ia = "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", aa = "<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", oa = "# 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", sa = "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", ca = "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", la = "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", ua = "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", da = "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", fa = "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", pa = "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", ha = "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", _a = /* @__PURE__ */ Object.assign({
|
|
3887
|
+
"./creates/data/hooks/stripe.pb.js": Fi,
|
|
3888
|
+
"./creates/data/hooks/utils.js": Ii,
|
|
3889
|
+
"./creates/src/lib/components/payments/confirm-dialog.svelte": Li,
|
|
3890
|
+
"./creates/src/lib/components/payments/payment-button.svelte": Ri,
|
|
3891
|
+
"./creates/src/lib/components/payments/payment-dialog.svelte": zi,
|
|
3892
|
+
"./creates/src/lib/components/payments/stripe-constants.ts": Bi,
|
|
3893
|
+
"./creates/src/lib/components/payments/stripe-payment-form.svelte": Vi,
|
|
3894
|
+
"./creates/src/lib/components/payments/use-payment-intent.svelte.ts": Hi,
|
|
3895
|
+
"./creates/src/lib/components/payments/use-stripe.svelte.ts": Ui,
|
|
3896
|
+
"./creates/src/lib/stripe.ts": Wi,
|
|
3897
|
+
"./creates/src/routes/api/stripe/payment-intent/+server.ts": Gi,
|
|
3898
|
+
"./creates/src/routes/api/stripe/payment-intent/server.test.ts": Ki,
|
|
3899
|
+
"./creates/src/routes/api/stripe/sync/prices/+server.ts": qi,
|
|
3900
|
+
"./creates/src/routes/api/stripe/sync/products/+server.ts": Ji,
|
|
3901
|
+
"./creates/src/routes/webhooks/stripe/+server.ts": Yi,
|
|
3902
|
+
"./creates/src/routes/webhooks/stripe/handlers/payment-intent/server.test.ts": Xi,
|
|
3903
|
+
"./creates/src/routes/webhooks/stripe/handlers/payment-intent/succeeded.ts": Zi,
|
|
3904
|
+
"./creates/src/routes/webhooks/stripe/server.test.ts": Qi
|
|
3905
|
+
}), va = /* @__PURE__ */ Object.assign({
|
|
3906
|
+
"./creates-app-mode/data/hooks/stripe.pb.js": $i,
|
|
3907
|
+
"./creates-app-mode/data/hooks/utils.js": ea,
|
|
3908
|
+
"./creates-app-mode/src/lib/components/payments/setup-button.svelte": ta,
|
|
3909
|
+
"./creates-app-mode/src/lib/components/payments/setup-dialog.svelte": na,
|
|
3910
|
+
"./creates-app-mode/src/routes/(app)/billing/+layout.server.ts": ra,
|
|
3911
|
+
"./creates-app-mode/src/routes/(app)/billing/+page.server.ts": ia,
|
|
3912
|
+
"./creates-app-mode/src/routes/(app)/billing/+page.svelte": aa,
|
|
3913
|
+
"./creates-app-mode/src/routes/(app)/billing/README.md": oa,
|
|
3914
|
+
"./creates-app-mode/src/routes/api/stripe/payment-intent/+server.ts": sa,
|
|
3915
|
+
"./creates-app-mode/src/routes/api/stripe/payment-intent/server.test.ts": ca,
|
|
3916
|
+
"./creates-app-mode/src/routes/api/stripe/setup-intent/+server.ts": la,
|
|
3917
|
+
"./creates-app-mode/src/routes/api/stripe/setup-intent/server.test.ts": ua,
|
|
3918
|
+
"./creates-app-mode/src/routes/api/stripe/sync/customers/+server.ts": da,
|
|
3919
|
+
"./creates-app-mode/src/routes/webhooks/stripe/+server.ts": fa,
|
|
3920
|
+
"./creates-app-mode/src/routes/webhooks/stripe/handlers/payment-intent/server.test.ts": pa,
|
|
3921
|
+
"./creates-app-mode/src/routes/webhooks/stripe/handlers/payment-intent/succeeded.ts": ma,
|
|
3922
|
+
"./creates-app-mode/src/routes/webhooks/stripe/handlers/payment-method/attached.ts": ha,
|
|
3923
|
+
"./creates-app-mode/src/routes/webhooks/stripe/handlers/payment-method/server.test.ts": ga
|
|
3924
|
+
}), ya = "./creates/", ba = "./creates-app-mode/";
|
|
3925
|
+
function xa(e, n) {
|
|
3926
|
+
let i = {};
|
|
3927
|
+
for (let [a, o] of Object.entries(e)) {
|
|
3928
|
+
let e = r(a, n);
|
|
3929
|
+
i[e] = {
|
|
3930
|
+
path: e,
|
|
3931
|
+
language: t(e),
|
|
3932
|
+
content: o,
|
|
3933
|
+
status: "success"
|
|
3934
|
+
};
|
|
3935
|
+
}
|
|
3936
|
+
return i;
|
|
3937
|
+
}
|
|
3938
|
+
async function Sa(e) {
|
|
3939
|
+
let t = e.features.auth, n = { ...xa(_a, ya) };
|
|
3940
|
+
if (t) {
|
|
3941
|
+
let e = xa(va, ba);
|
|
3942
|
+
Object.assign(n, e);
|
|
3943
|
+
}
|
|
3944
|
+
let r = Object.values(n).sort((e, t) => e.path.localeCompare(t.path)), i = [
|
|
3945
|
+
"dialog",
|
|
3946
|
+
"input",
|
|
3947
|
+
"label"
|
|
3948
|
+
];
|
|
3949
|
+
return t && i.push("alert-dialog"), {
|
|
3950
|
+
creates: r,
|
|
3951
|
+
modifies: [],
|
|
3952
|
+
deletes: [],
|
|
3953
|
+
components: i,
|
|
3954
|
+
packages: ["stripe", "@stripe/stripe-js"],
|
|
3955
|
+
collections: []
|
|
3956
|
+
};
|
|
3957
|
+
}
|
|
3958
|
+
//#endregion
|
|
3959
|
+
//#region src/patterns/enable/payments/preview-modifies/src/lib/components/nav-user.svelte?raw
|
|
3960
|
+
var Ca = "<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", wa = "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:2]\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:55]\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", Ta = "users", Ea = "stripe_customers", Da = "stripe_payment_methods", Oa = {
|
|
3961
|
+
name: "stripe_products",
|
|
3962
|
+
type: "base",
|
|
3963
|
+
fields: [
|
|
3964
|
+
{
|
|
3965
|
+
name: "id",
|
|
3966
|
+
pattern: "^[a-zA-Z0-9_]+$",
|
|
3967
|
+
primaryKey: !0,
|
|
3968
|
+
required: !0,
|
|
3969
|
+
type: "text"
|
|
3970
|
+
},
|
|
3971
|
+
{
|
|
3972
|
+
name: "name",
|
|
3973
|
+
required: !1,
|
|
3974
|
+
type: "text"
|
|
3975
|
+
},
|
|
3976
|
+
{
|
|
3977
|
+
name: "active",
|
|
3978
|
+
required: !1,
|
|
3979
|
+
type: "text"
|
|
3980
|
+
},
|
|
3981
|
+
{
|
|
3982
|
+
name: "default_price",
|
|
3983
|
+
required: !1,
|
|
3984
|
+
type: "text"
|
|
3985
|
+
},
|
|
3986
|
+
{
|
|
3987
|
+
name: "created",
|
|
3988
|
+
onCreate: !0,
|
|
3989
|
+
onUpdate: !1,
|
|
3990
|
+
type: "autodate"
|
|
3991
|
+
},
|
|
3992
|
+
{
|
|
3993
|
+
name: "updated",
|
|
3994
|
+
onCreate: !0,
|
|
3995
|
+
onUpdate: !0,
|
|
3996
|
+
type: "autodate"
|
|
3997
|
+
}
|
|
3998
|
+
]
|
|
3999
|
+
}, ka = {
|
|
4000
|
+
name: "stripe_prices",
|
|
4001
|
+
type: "base",
|
|
4002
|
+
fields: [
|
|
4003
|
+
{
|
|
4004
|
+
name: "id",
|
|
4005
|
+
pattern: "^[a-zA-Z0-9_]+$",
|
|
4006
|
+
primaryKey: !0,
|
|
4007
|
+
required: !0,
|
|
4008
|
+
type: "text"
|
|
4009
|
+
},
|
|
4010
|
+
{
|
|
4011
|
+
name: "billing_scheme",
|
|
4012
|
+
required: !1,
|
|
4013
|
+
type: "text"
|
|
4014
|
+
},
|
|
4015
|
+
{
|
|
4016
|
+
name: "currency",
|
|
4017
|
+
required: !1,
|
|
4018
|
+
type: "text"
|
|
4019
|
+
},
|
|
4020
|
+
{
|
|
4021
|
+
name: "product",
|
|
4022
|
+
required: !1,
|
|
4023
|
+
type: "text"
|
|
4024
|
+
},
|
|
4025
|
+
{
|
|
4026
|
+
name: "recurring",
|
|
4027
|
+
required: !1,
|
|
4028
|
+
type: "text"
|
|
4029
|
+
},
|
|
4030
|
+
{
|
|
4031
|
+
name: "type",
|
|
4032
|
+
required: !1,
|
|
4033
|
+
type: "text"
|
|
4034
|
+
},
|
|
4035
|
+
{
|
|
4036
|
+
name: "unit_amount",
|
|
4037
|
+
required: !1,
|
|
4038
|
+
type: "number"
|
|
4039
|
+
},
|
|
4040
|
+
{
|
|
4041
|
+
name: "active",
|
|
4042
|
+
required: !1,
|
|
4043
|
+
type: "bool"
|
|
4044
|
+
},
|
|
4045
|
+
{
|
|
4046
|
+
name: "created",
|
|
4047
|
+
onCreate: !0,
|
|
4048
|
+
onUpdate: !1,
|
|
4049
|
+
type: "autodate"
|
|
4050
|
+
},
|
|
4051
|
+
{
|
|
4052
|
+
name: "updated",
|
|
4053
|
+
onCreate: !0,
|
|
4054
|
+
onUpdate: !0,
|
|
4055
|
+
type: "autodate"
|
|
4056
|
+
}
|
|
4057
|
+
]
|
|
4058
|
+
}, Aa = {
|
|
4059
|
+
name: Ea,
|
|
4060
|
+
type: "base",
|
|
4061
|
+
fields: [
|
|
4062
|
+
{
|
|
4063
|
+
name: "id",
|
|
4064
|
+
pattern: "^[a-zA-Z0-9_]+$",
|
|
4065
|
+
primaryKey: !0,
|
|
4066
|
+
required: !0,
|
|
4067
|
+
type: "text"
|
|
4068
|
+
},
|
|
4069
|
+
{
|
|
4070
|
+
collectionId: Ta,
|
|
4071
|
+
maxSelect: 1,
|
|
4072
|
+
minSelect: 0,
|
|
4073
|
+
name: "user",
|
|
4074
|
+
required: !0,
|
|
4075
|
+
type: "relation"
|
|
4076
|
+
},
|
|
4077
|
+
{
|
|
4078
|
+
collectionId: Da,
|
|
4079
|
+
maxSelect: 1,
|
|
4080
|
+
minSelect: 0,
|
|
4081
|
+
name: "default_payment_method",
|
|
4082
|
+
required: !1,
|
|
4083
|
+
type: "relation"
|
|
4084
|
+
},
|
|
4085
|
+
{
|
|
4086
|
+
name: "created",
|
|
4087
|
+
onCreate: !0,
|
|
4088
|
+
onUpdate: !1,
|
|
4089
|
+
type: "autodate"
|
|
4090
|
+
},
|
|
4091
|
+
{
|
|
4092
|
+
name: "updated",
|
|
4093
|
+
onCreate: !0,
|
|
4094
|
+
onUpdate: !0,
|
|
4095
|
+
type: "autodate"
|
|
4096
|
+
}
|
|
4097
|
+
]
|
|
4098
|
+
}, ja = {
|
|
4099
|
+
name: Da,
|
|
4100
|
+
type: "base",
|
|
4101
|
+
fields: [
|
|
4102
|
+
{
|
|
4103
|
+
name: "id",
|
|
4104
|
+
pattern: "^[a-zA-Z0-9_]+$",
|
|
4105
|
+
primaryKey: !0,
|
|
4106
|
+
required: !0,
|
|
4107
|
+
type: "text"
|
|
4108
|
+
},
|
|
4109
|
+
{
|
|
4110
|
+
name: "brand",
|
|
4111
|
+
required: !0,
|
|
4112
|
+
type: "text"
|
|
4113
|
+
},
|
|
4114
|
+
{
|
|
4115
|
+
name: "last4",
|
|
4116
|
+
required: !0,
|
|
4117
|
+
type: "text"
|
|
4118
|
+
},
|
|
4119
|
+
{
|
|
4120
|
+
name: "exp_month",
|
|
4121
|
+
required: !0,
|
|
4122
|
+
type: "number"
|
|
4123
|
+
},
|
|
4124
|
+
{
|
|
4125
|
+
name: "exp_year",
|
|
4126
|
+
required: !0,
|
|
4127
|
+
type: "number"
|
|
4128
|
+
},
|
|
4129
|
+
{
|
|
4130
|
+
collectionId: Ea,
|
|
4131
|
+
maxSelect: 1,
|
|
4132
|
+
minSelect: 0,
|
|
4133
|
+
name: "customer",
|
|
4134
|
+
required: !0,
|
|
4135
|
+
type: "relation",
|
|
4136
|
+
cascadeDelete: !0
|
|
4137
|
+
},
|
|
4138
|
+
{
|
|
4139
|
+
name: "created",
|
|
4140
|
+
onCreate: !0,
|
|
4141
|
+
onUpdate: !1,
|
|
4142
|
+
type: "autodate"
|
|
4143
|
+
},
|
|
4144
|
+
{
|
|
4145
|
+
name: "updated",
|
|
4146
|
+
onCreate: !0,
|
|
4147
|
+
onUpdate: !0,
|
|
4148
|
+
type: "autodate"
|
|
4149
|
+
}
|
|
4150
|
+
]
|
|
4151
|
+
}, Ma = {
|
|
4152
|
+
name: "transactions",
|
|
4153
|
+
type: "base",
|
|
4154
|
+
fields: [
|
|
4155
|
+
{
|
|
4156
|
+
autogeneratePattern: "[a-z0-9]{15}",
|
|
4157
|
+
max: 15,
|
|
4158
|
+
min: 15,
|
|
4159
|
+
name: "id",
|
|
4160
|
+
pattern: "^[a-z0-9]+$",
|
|
4161
|
+
primaryKey: !0,
|
|
4162
|
+
required: !0,
|
|
4163
|
+
type: "text"
|
|
4164
|
+
},
|
|
4165
|
+
{
|
|
4166
|
+
name: "stripe_payment_intent",
|
|
4167
|
+
required: !0,
|
|
4168
|
+
type: "text"
|
|
4169
|
+
},
|
|
4170
|
+
{
|
|
4171
|
+
name: "amount",
|
|
4172
|
+
required: !0,
|
|
4173
|
+
type: "number"
|
|
4174
|
+
},
|
|
4175
|
+
{
|
|
4176
|
+
name: "currency",
|
|
4177
|
+
required: !0,
|
|
4178
|
+
type: "text"
|
|
4179
|
+
},
|
|
4180
|
+
{
|
|
4181
|
+
name: "last4",
|
|
4182
|
+
required: !0,
|
|
4183
|
+
type: "text"
|
|
4184
|
+
},
|
|
4185
|
+
{
|
|
4186
|
+
name: "brand",
|
|
4187
|
+
required: !0,
|
|
4188
|
+
type: "text"
|
|
4189
|
+
},
|
|
4190
|
+
{
|
|
4191
|
+
name: "created",
|
|
4192
|
+
required: !0,
|
|
4193
|
+
type: "date"
|
|
4194
|
+
},
|
|
4195
|
+
{
|
|
4196
|
+
name: "stripe_charge",
|
|
4197
|
+
required: !0,
|
|
4198
|
+
type: "text"
|
|
4199
|
+
},
|
|
4200
|
+
{
|
|
4201
|
+
name: "stripe_customer",
|
|
4202
|
+
required: !0,
|
|
4203
|
+
type: "text"
|
|
4204
|
+
},
|
|
4205
|
+
{
|
|
4206
|
+
collectionId: Ta,
|
|
4207
|
+
maxSelect: 1,
|
|
4208
|
+
minSelect: 0,
|
|
4209
|
+
name: "user",
|
|
4210
|
+
required: !0,
|
|
4211
|
+
type: "relation"
|
|
4212
|
+
},
|
|
4213
|
+
{
|
|
4214
|
+
name: "receipt_url",
|
|
4215
|
+
required: !0,
|
|
4216
|
+
type: "url"
|
|
4217
|
+
}
|
|
4218
|
+
]
|
|
4219
|
+
}, Na = [Oa, ka], Pa = [
|
|
4220
|
+
Aa,
|
|
4221
|
+
ja,
|
|
4222
|
+
Ma
|
|
4223
|
+
], Fa, Ia = /* @__PURE__ */ Object.assign({
|
|
4224
|
+
"./preview-modifies/src/lib/components/nav-user.svelte": Ca,
|
|
4225
|
+
"./preview-modifies/src/routes/(public)/signup/+page.server.ts": wa
|
|
4226
|
+
}), La = "./preview-modifies/", Ra = "price_preview_placeholder";
|
|
4227
|
+
function za(t) {
|
|
4228
|
+
return e(Fa ||= 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);
|
|
4229
|
+
}
|
|
4230
|
+
async function Ba(e) {
|
|
4231
|
+
let n = e.features.auth, i = Object.entries(Ia).map(([e, n]) => {
|
|
4232
|
+
let i = r(e, La);
|
|
4233
|
+
return {
|
|
4234
|
+
path: i,
|
|
4235
|
+
language: t(i),
|
|
4236
|
+
content: n,
|
|
4237
|
+
status: "success"
|
|
4238
|
+
};
|
|
4239
|
+
}).sort((e, t) => e.path.localeCompare(t.path)), a = {
|
|
4240
|
+
path: "src/routes/(public)/payment/+page.svelte",
|
|
4241
|
+
language: "svelte",
|
|
4242
|
+
content: za(Ra),
|
|
4243
|
+
status: "success"
|
|
4244
|
+
}, o = [...Na, ...n ? Pa : []];
|
|
4245
|
+
return {
|
|
4246
|
+
creates: [a],
|
|
4247
|
+
modifies: i,
|
|
4248
|
+
deletes: [],
|
|
4249
|
+
components: [],
|
|
4250
|
+
packages: [],
|
|
4251
|
+
collections: o
|
|
4252
|
+
};
|
|
4253
|
+
}
|
|
4254
|
+
//#endregion
|
|
4255
|
+
//#region src/patterns/enable/payments/index.ts
|
|
4256
|
+
var Va = "enable-payments", Ha = "1.0.0", Ua = "src/patterns/enable/payments", Wa = "/enable/payments";
|
|
4257
|
+
async function Ga(e) {
|
|
4258
|
+
let t = await Sa(e);
|
|
4259
|
+
if (e.env === "preview") return v(n([t, await Ba(e)]));
|
|
4260
|
+
let { generate: r } = await import("./chunks/generate.runtime-V7jzalbO.js"), i = await r(e), { writeResult: a } = await import("./chunks/write-result-C3SCX65t.js");
|
|
4261
|
+
return a(await v(n([t, i])), e);
|
|
4262
|
+
}
|
|
4263
|
+
var Ka = {
|
|
4264
|
+
version: Ha,
|
|
4265
|
+
slug: Va,
|
|
4266
|
+
source: Ua,
|
|
4267
|
+
docs: Wa,
|
|
4268
|
+
plan: "pro",
|
|
4269
|
+
title: "Enable payments",
|
|
4270
|
+
summary: "Adds Stripe payments with product/price sync, checkout flow, and optional saved payment methods when auth is enabled.",
|
|
4271
|
+
requires: {
|
|
4272
|
+
auth: !1,
|
|
4273
|
+
api: !1,
|
|
4274
|
+
apiKeys: !1,
|
|
4275
|
+
i18n: !1,
|
|
4276
|
+
teams: !1,
|
|
4277
|
+
payments: !1
|
|
4278
|
+
},
|
|
4279
|
+
category: "payments",
|
|
4280
|
+
tags: [
|
|
4281
|
+
"sveltekit",
|
|
4282
|
+
"payments",
|
|
4283
|
+
"stripe",
|
|
4284
|
+
"pocketbase",
|
|
4285
|
+
"velastack",
|
|
4286
|
+
"checkout"
|
|
4287
|
+
],
|
|
4288
|
+
command: {
|
|
4289
|
+
raw: "vela enable payments",
|
|
4290
|
+
base: "vela enable payments",
|
|
4291
|
+
argv: []
|
|
4292
|
+
},
|
|
4293
|
+
examples: [],
|
|
4294
|
+
tests: 0,
|
|
4295
|
+
baseline: "velastack",
|
|
4296
|
+
generate: Ga
|
|
4297
|
+
}, qa = /* @__PURE__ */ Object.assign({
|
|
3210
4298
|
"./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",
|
|
3211
4299
|
"./creates/src/lib/schemas/team.ts": "import { z } from \"zod\";\n\nexport const teamSchema = z.object({\n name: z.string(),\n});\n",
|
|
3212
4300
|
"./creates/src/lib/schemas/teamInvite.ts": "import { z } from \"zod\";\n\nexport const teamInviteSchema = z.object({\n email: z.email(),\n});\n",
|
|
@@ -3239,11 +4327,11 @@ var Tr = {
|
|
|
3239
4327
|
"./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",
|
|
3240
4328
|
"./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",
|
|
3241
4329
|
"./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"
|
|
3242
|
-
}),
|
|
3243
|
-
async function
|
|
4330
|
+
}), Ja = "./creates/";
|
|
4331
|
+
async function Ya(e) {
|
|
3244
4332
|
return {
|
|
3245
|
-
creates: Object.entries(
|
|
3246
|
-
let i = r(e,
|
|
4333
|
+
creates: Object.entries(qa).map(([e, n]) => {
|
|
4334
|
+
let i = r(e, Ja);
|
|
3247
4335
|
return {
|
|
3248
4336
|
path: i,
|
|
3249
4337
|
language: t(i),
|
|
@@ -3272,9 +4360,9 @@ async function Or(e) {
|
|
|
3272
4360
|
}
|
|
3273
4361
|
//#endregion
|
|
3274
4362
|
//#region src/patterns/enable/teams/preview-modifies/src/lib/components/app-sidebar.svelte?raw
|
|
3275
|
-
var
|
|
4363
|
+
var Xa = "<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", Za = "<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", Qa = "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", $a = "<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", eo = "users", Q = "teams", to = "team_memberships";
|
|
3276
4364
|
function $(e) {
|
|
3277
|
-
let t =
|
|
4365
|
+
let t = s.find((t) => t.collectionName === e);
|
|
3278
4366
|
if (!t) throw Error(`teams: missing TEAM_RULE_PATCHES entry for "${e}"`);
|
|
3279
4367
|
return {
|
|
3280
4368
|
listRule: t.listRule,
|
|
@@ -3284,7 +4372,7 @@ function $(e) {
|
|
|
3284
4372
|
deleteRule: t.deleteRule
|
|
3285
4373
|
};
|
|
3286
4374
|
}
|
|
3287
|
-
var
|
|
4375
|
+
var no = [
|
|
3288
4376
|
{
|
|
3289
4377
|
name: "teams",
|
|
3290
4378
|
type: "base",
|
|
@@ -3309,7 +4397,7 @@ var Fr = [
|
|
|
3309
4397
|
name: "owner",
|
|
3310
4398
|
type: "relation",
|
|
3311
4399
|
cascadeDelete: !1,
|
|
3312
|
-
collectionId:
|
|
4400
|
+
collectionId: eo,
|
|
3313
4401
|
maxSelect: 1,
|
|
3314
4402
|
minSelect: 0,
|
|
3315
4403
|
required: !0
|
|
@@ -3355,7 +4443,7 @@ var Fr = [
|
|
|
3355
4443
|
{
|
|
3356
4444
|
name: "user",
|
|
3357
4445
|
cascadeDelete: !0,
|
|
3358
|
-
collectionId:
|
|
4446
|
+
collectionId: eo,
|
|
3359
4447
|
maxSelect: 1,
|
|
3360
4448
|
minSelect: 0,
|
|
3361
4449
|
required: !0,
|
|
@@ -3415,7 +4503,7 @@ var Fr = [
|
|
|
3415
4503
|
{
|
|
3416
4504
|
name: "membership_id",
|
|
3417
4505
|
cascadeDelete: !1,
|
|
3418
|
-
collectionId:
|
|
4506
|
+
collectionId: to,
|
|
3419
4507
|
maxSelect: 1,
|
|
3420
4508
|
minSelect: 0,
|
|
3421
4509
|
required: !1,
|
|
@@ -3525,17 +4613,17 @@ var Fr = [
|
|
|
3525
4613
|
}
|
|
3526
4614
|
]
|
|
3527
4615
|
}
|
|
3528
|
-
],
|
|
3529
|
-
"./preview-modifies/src/lib/components/app-sidebar.svelte":
|
|
3530
|
-
"./preview-modifies/src/lib/components/nav-user.svelte":
|
|
3531
|
-
"./preview-modifies/src/routes/(app)/+layout.server.ts":
|
|
3532
|
-
"./preview-modifies/src/routes/(app)/+layout.svelte":
|
|
3533
|
-
}),
|
|
3534
|
-
async function
|
|
4616
|
+
], ro = /* @__PURE__ */ Object.assign({
|
|
4617
|
+
"./preview-modifies/src/lib/components/app-sidebar.svelte": Xa,
|
|
4618
|
+
"./preview-modifies/src/lib/components/nav-user.svelte": Za,
|
|
4619
|
+
"./preview-modifies/src/routes/(app)/+layout.server.ts": Qa,
|
|
4620
|
+
"./preview-modifies/src/routes/(app)/+layout.svelte": $a
|
|
4621
|
+
}), io = "./preview-modifies/";
|
|
4622
|
+
async function ao(e) {
|
|
3535
4623
|
return {
|
|
3536
4624
|
creates: [],
|
|
3537
|
-
modifies: Object.entries(
|
|
3538
|
-
let i = r(e,
|
|
4625
|
+
modifies: Object.entries(ro).map(([e, n]) => {
|
|
4626
|
+
let i = r(e, io);
|
|
3539
4627
|
return {
|
|
3540
4628
|
path: i,
|
|
3541
4629
|
language: t(i),
|
|
@@ -3546,23 +4634,23 @@ async function Rr(e) {
|
|
|
3546
4634
|
deletes: [],
|
|
3547
4635
|
components: [],
|
|
3548
4636
|
packages: [],
|
|
3549
|
-
collections:
|
|
4637
|
+
collections: no
|
|
3550
4638
|
};
|
|
3551
4639
|
}
|
|
3552
4640
|
//#endregion
|
|
3553
4641
|
//#region src/patterns/enable/teams/index.ts
|
|
3554
|
-
var
|
|
3555
|
-
async function
|
|
3556
|
-
let t = await
|
|
3557
|
-
if (e.env === "preview") return
|
|
3558
|
-
let { generate: r } = await import("./chunks/generate.runtime-
|
|
3559
|
-
return a(await
|
|
3560
|
-
}
|
|
3561
|
-
var
|
|
3562
|
-
version:
|
|
3563
|
-
slug:
|
|
3564
|
-
source:
|
|
3565
|
-
docs:
|
|
4642
|
+
var oo = "enable-teams", so = "1.0.0", co = "src/patterns/enable/teams", lo = "/enable/teams";
|
|
4643
|
+
async function uo(e) {
|
|
4644
|
+
let t = await Ya(e);
|
|
4645
|
+
if (e.env === "preview") return v(n([t, await ao(e)]));
|
|
4646
|
+
let { generate: r } = await import("./chunks/generate.runtime-BS_l-k-A.js"), i = await r(e), { writeResult: a } = await import("./chunks/write-result-C3SCX65t.js");
|
|
4647
|
+
return a(await v(n([t, i])), e);
|
|
4648
|
+
}
|
|
4649
|
+
var fo = {
|
|
4650
|
+
version: so,
|
|
4651
|
+
slug: oo,
|
|
4652
|
+
source: co,
|
|
4653
|
+
docs: lo,
|
|
3566
4654
|
plan: "pro",
|
|
3567
4655
|
title: "Enable teams",
|
|
3568
4656
|
summary: "Adds multi-tenant teams with memberships, invites, and a sidebar team switcher.",
|
|
@@ -3591,22 +4679,25 @@ var Wr = {
|
|
|
3591
4679
|
examples: [],
|
|
3592
4680
|
tests: 36,
|
|
3593
4681
|
baseline: "velastack",
|
|
3594
|
-
generate:
|
|
3595
|
-
},
|
|
3596
|
-
|
|
3597
|
-
|
|
3598
|
-
|
|
3599
|
-
|
|
3600
|
-
Un,
|
|
4682
|
+
generate: uo
|
|
4683
|
+
}, po = re.version, mo = [
|
|
4684
|
+
Jt,
|
|
4685
|
+
bn,
|
|
4686
|
+
Br,
|
|
4687
|
+
kn,
|
|
3601
4688
|
tr,
|
|
3602
|
-
|
|
3603
|
-
|
|
3604
|
-
|
|
3605
|
-
|
|
4689
|
+
jr,
|
|
4690
|
+
Qr,
|
|
4691
|
+
ui,
|
|
4692
|
+
Si,
|
|
4693
|
+
Pi,
|
|
4694
|
+
Ka,
|
|
4695
|
+
fo
|
|
4696
|
+
], ho = Object.fromEntries(mo.map((e) => [e.slug, e])), go = mo.reduce((e, t) => {
|
|
3606
4697
|
let n = t.category;
|
|
3607
4698
|
return e[n] ??= [], e[n].push(t), e;
|
|
3608
4699
|
}, {});
|
|
3609
4700
|
//#endregion
|
|
3610
|
-
export {
|
|
4701
|
+
export { _ as InvalidArgumentError, go as byCategory, ho as bySlug, mo as patterns, po as version };
|
|
3611
4702
|
|
|
3612
4703
|
//# sourceMappingURL=index.js.map
|