@niyamulahsan/create-deskapp 1.2.2 → 1.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/package.json +1 -1
  2. package/template/.env +1 -1
  3. package/template/src/core/api/generate.manifest.ts +4 -10
  4. package/template/src/core/api/registry.ts +1 -1
  5. package/template/src/core/config.ts +2 -2
  6. package/template/src/core/database/aggregate.ts +1 -1
  7. package/template/src/core/database/connection.ts +11 -11
  8. package/template/src/core/database/migrate-hooks.ts +1 -1
  9. package/template/src/core/database/paginate.ts +9 -9
  10. package/template/src/core/database/reset.ts +2 -2
  11. package/template/src/core/database/seed.ts +3 -5
  12. package/template/src/core/database/status.ts +4 -1
  13. package/template/src/core/env.ts +1 -1
  14. package/template/src/core/maker/db/fresh.ts +2 -2
  15. package/template/src/core/maker/db/generate.ts +1 -1
  16. package/template/src/core/maker/db/migrate.ts +3 -4
  17. package/template/src/core/maker/db/mod.ts +47 -19
  18. package/template/src/core/maker/db/module-migrate.ts +7 -6
  19. package/template/src/core/maker/db/push.ts +1 -1
  20. package/template/src/core/maker/db/reset.ts +1 -1
  21. package/template/src/core/maker/db/seed.ts +1 -1
  22. package/template/src/core/maker/db/status.ts +1 -1
  23. package/template/src/core/maker/help.ts +6 -15
  24. package/template/src/core/maker/make/controller.ts +5 -10
  25. package/template/src/core/maker/make/helpers.ts +6 -8
  26. package/template/src/core/maker/make/mod.ts +13 -14
  27. package/template/src/core/maker/make/model.ts +1 -1
  28. package/template/src/core/maker/make/module.ts +6 -29
  29. package/template/src/core/maker/make/seeder.ts +2 -2
  30. package/template/src/core/maker/make/test.ts +3 -3
  31. package/template/src/core/maker/mod.ts +4 -4
  32. package/template/src/core/maker/run/mod.ts +34 -14
  33. package/template/src/core/utils/playwright.ts +25 -25
  34. package/template/src/core/utils/queue.ts +17 -10
  35. package/template/src/core/utils/scheduler.ts +7 -17
  36. package/template/src/core/utils/storage.ts +1 -1
  37. package/template/src/core/utils/validation.ts +3 -3
  38. package/template/src/database/migrations/sqlite/meta/_journal.json +5 -1
  39. package/template/src/preload.ts +1 -1
  40. package/template/src/ui/src/plugins/gum.ts.bak +0 -683
@@ -1,683 +0,0 @@
1
- import { useStorage } from "@vueuse/core";
2
- import axios, { type AxiosError, type AxiosProgressEvent, type AxiosResponse } from "axios";
3
- import type { App } from "vue";
4
- import { computed, nextTick, reactive, ref, toRaw } from "vue";
5
- import { type LocationQueryRaw, useRoute, useRouter } from "vue-router";
6
-
7
- /* -------------------------------------------------------------------------- */
8
- /* Types */
9
- /* -------------------------------------------------------------------------- */
10
-
11
- export type GumPluginOptions = {
12
- rememberPrefix?: string;
13
- recentlySuccessfulDuration?: number;
14
- };
15
-
16
- type GumMethod = "get" | "post" | "put" | "patch" | "delete";
17
- type FormMethod = "post" | "put" | "patch" | "delete";
18
-
19
- type LifecycleHooks = {
20
- onBefore?: () => boolean | undefined | Promise<boolean | undefined>;
21
- onStart?: () => void | Promise<void>;
22
- onProgress?: (event: AxiosProgressEvent) => void;
23
- onSuccess?: (response: AxiosResponse) => void | Promise<void>;
24
- onError?: (errors: NormalizedErrors, error: AxiosError) => void | Promise<void>;
25
- onFinish?: () => void | Promise<void>;
26
- };
27
-
28
- /**
29
- * A fetcher returns either an AxiosResponse or any plain payload.
30
- * Gum wraps plain values into `{ data, status: 200 }`, so store methods
31
- * returning `Promise<string>` / `Promise<User>` work without a wrapper.
32
- *
33
- * Typing is intentionally loose (`Promise<unknown>`); callers should not
34
- * rely on the fetcher's return type being narrow.
35
- */
36
- type Fetcher = (payload: Record<string, unknown> | FormData) => Promise<unknown>;
37
-
38
- type GumVisitOptions = LifecycleHooks & {
39
- method?: GumMethod;
40
- data?: Record<string, unknown> | FormData;
41
- query?: Record<string, unknown>;
42
- routePath?: string;
43
- replace?: boolean;
44
- preserveState?: boolean;
45
- preserveScroll?: boolean;
46
- skipFetch?: boolean;
47
- fetcher?: Fetcher;
48
- };
49
-
50
- /** URL-less visit: fetcher REQUIRED, method injected by the helper. */
51
- type VisitWithFetcherOptions = Omit<GumVisitOptions, "method" | "fetcher"> & { fetcher: Fetcher };
52
- /** For body-carrying methods (post/put/patch/delete). */
53
- type VisitWithFetcherDataOptions = VisitWithFetcherOptions & {
54
- data?: Record<string, unknown> | FormData;
55
- };
56
-
57
- type FormSubmitOptions<T> = LifecycleHooks & {
58
- validate?: (data: T) => Record<string, string> | null | undefined;
59
- transform?: (data: T) => Record<string, unknown> | FormData;
60
- fetcher?: Fetcher;
61
- };
62
-
63
- /** URL-less form submit: fetcher REQUIRED, method injected by the helper. */
64
- type FormWithFetcherOptions<T> = Omit<FormSubmitOptions<T>, "fetcher"> & { fetcher: Fetcher };
65
-
66
- type FormErrors<T> = Partial<Record<keyof T | string, string>>;
67
- type NormalizedErrors = Record<string, string[] | string>;
68
-
69
- type ValidationErrorPayload = {
70
- errors?: Record<string, string[] | string>;
71
- error?: { issues?: Array<{ path?: Array<string | number>; message?: string }> };
72
- };
73
-
74
- /* -------------------------------------------------------------------------- */
75
- /* Config + registry */
76
- /* -------------------------------------------------------------------------- */
77
-
78
- const config: Required<GumPluginOptions> = {
79
- rememberPrefix: "gum",
80
- recentlySuccessfulDuration: 2000
81
- };
82
-
83
- const routeRememberKeys = new Map<string, Set<string>>();
84
-
85
- function normalizePath(path: string) {
86
- const clean = (path || "/").split("?")[0];
87
- return clean || "/";
88
- }
89
-
90
- function registerRememberKey(path: string, key: string) {
91
- const routePath = normalizePath(path);
92
- if (!routeRememberKeys.has(routePath)) routeRememberKeys.set(routePath, new Set());
93
- routeRememberKeys.get(routePath)!.add(key);
94
- }
95
-
96
- export function clearRememberForPath(path: string) {
97
- const routePath = normalizePath(path);
98
- const keys = routeRememberKeys.get(routePath);
99
- if (!keys) return;
100
- keys.forEach((key) => localStorage.removeItem(`${config.rememberPrefix}:${key}`));
101
- }
102
-
103
- /* -------------------------------------------------------------------------- */
104
- /* Global processing tracker (shared across all useGum() instances) */
105
- /* -------------------------------------------------------------------------- */
106
-
107
- const globalProcessing = ref(false);
108
- let activeRequests = 0;
109
-
110
- function trackStart() {
111
- activeRequests++;
112
- globalProcessing.value = true;
113
- }
114
-
115
- function trackEnd() {
116
- activeRequests = Math.max(0, activeRequests - 1);
117
- if (activeRequests === 0) globalProcessing.value = false;
118
- }
119
-
120
- /* -------------------------------------------------------------------------- */
121
- /* Small shared helpers */
122
- /* -------------------------------------------------------------------------- */
123
-
124
- export function normalizeValidationErrors(payload?: ValidationErrorPayload): NormalizedErrors {
125
- const normalized: NormalizedErrors = { ...payload?.errors };
126
- const issues = payload?.error?.issues;
127
- if (Array.isArray(issues)) {
128
- issues.forEach((issue) => {
129
- const key = issue.path?.map(String).join(".");
130
- if (key) normalized[key] = String(issue.message || "Invalid value");
131
- });
132
- }
133
- return normalized;
134
- }
135
-
136
- async function runBefore(onBefore?: LifecycleHooks["onBefore"]) {
137
- const allow = await onBefore?.();
138
- return allow !== false;
139
- }
140
-
141
- async function restoreScroll(enabled: boolean, y: number) {
142
- if (!enabled) return;
143
- await nextTick();
144
- // Double rAF: survives one layout pass (images/fonts shifting content).
145
- requestAnimationFrame(() => requestAnimationFrame(() => window.scrollTo({ top: y, behavior: "instant" as ScrollBehavior })));
146
- }
147
-
148
- function startRecentTimer(target: { recentlySuccessful: { value: boolean } }) {
149
- target.recentlySuccessful.value = true;
150
- setTimeout(() => {
151
- target.recentlySuccessful.value = false;
152
- }, config.recentlySuccessfulDuration);
153
- }
154
-
155
- function assertSource(url: string | undefined, fetcher: Fetcher | undefined, ctx: string) {
156
- if (!url && !fetcher) {
157
- throw new Error(
158
- `gum: ${ctx} requires either "url" or "fetcher". ` + `Pass a URL for axios, or a fetcher (e.g. a store method) to delegate the call.`
159
- );
160
- }
161
- if (import.meta.env?.DEV && url && fetcher) {
162
- console.warn(`gum: ${ctx} — "url" is ignored when "fetcher" is provided.`);
163
- }
164
- }
165
-
166
- /** Read the current scroll position — plain read, no per-instance listeners. */
167
- function readScrollY(): number {
168
- return typeof window !== "undefined" ? window.scrollY : 0;
169
- }
170
-
171
- /* -------------------------------------------------------------------------- */
172
- /* Shared core executor — dumb transport, never swallows errors */
173
- /* -------------------------------------------------------------------------- */
174
-
175
- type ExecuteOptions = {
176
- method: GumMethod;
177
- url?: string;
178
- payload: Record<string, unknown> | FormData | undefined;
179
- query?: Record<string, unknown>;
180
- fetcher?: Fetcher;
181
- onProgress?: (event: AxiosProgressEvent) => void;
182
- };
183
-
184
- /**
185
- * Execute the network call. Throws on error — the caller normalizes and
186
- * decides whether to rethrow based on whether `onError` was provided.
187
- *
188
- * Fetcher results:
189
- * - If it looks like an AxiosResponse (object with `data` and a numeric `status`),
190
- * it is returned as-is.
191
- * - Otherwise it is wrapped into `{ data: result, status: 200 }`.
192
- */
193
- async function execute(options: ExecuteOptions): Promise<AxiosResponse> {
194
- if (options.fetcher) {
195
- const result = await options.fetcher(options.payload ?? {});
196
- const looksLikeResponse =
197
- result !== null &&
198
- typeof result === "object" &&
199
- "data" in (result as Record<string, unknown>) &&
200
- typeof (result as { status?: unknown }).status === "number";
201
- if (looksLikeResponse) return result as AxiosResponse;
202
- return { data: result, status: 200, statusText: "OK", headers: {}, config: {} } as AxiosResponse;
203
- }
204
-
205
- return await axios.request({
206
- method: options.method,
207
- url: options.url,
208
- params: options.query,
209
- data: options.method === "get" ? undefined : options.payload,
210
- onUploadProgress: options.onProgress
211
- });
212
- }
213
-
214
- /* -------------------------------------------------------------------------- */
215
- /* Remember */
216
- /* -------------------------------------------------------------------------- */
217
-
218
- export function useGumRemember<T extends object>(key: string, initial: T) {
219
- const route = useRoute();
220
- registerRememberKey(route.path, key);
221
- return useStorage<T>(`${config.rememberPrefix}:${key}`, initial, localStorage, {
222
- mergeDefaults: true
223
- });
224
- }
225
-
226
- /* -------------------------------------------------------------------------- */
227
- /* Visit API */
228
- /* -------------------------------------------------------------------------- */
229
-
230
- function buildVisitApi() {
231
- const router = useRouter();
232
- const route = useRoute();
233
-
234
- /* ---------------------------- visit core ------------------------------- */
235
-
236
- async function runVisit(params: {
237
- method: GumMethod;
238
- url?: string;
239
- data?: Record<string, unknown> | FormData;
240
- query?: Record<string, unknown>;
241
- routePath?: string;
242
- replace?: boolean;
243
- preserveState?: boolean;
244
- preserveScroll?: boolean;
245
- skipFetch?: boolean;
246
- fetcher?: Fetcher;
247
- hooks?: GumVisitOptions;
248
- }) {
249
- const {
250
- method,
251
- url,
252
- data,
253
- query,
254
- routePath,
255
- replace = false,
256
- preserveState = method !== "get",
257
- preserveScroll = false,
258
- skipFetch = false,
259
- fetcher,
260
- hooks = {}
261
- } = params;
262
-
263
- const { onBefore, onStart, onProgress, onSuccess, onError, onFinish } = hooks;
264
-
265
- if (!(await runBefore(onBefore))) return;
266
-
267
- const savedY = readScrollY();
268
- trackStart();
269
-
270
- let response: AxiosResponse | undefined;
271
- try {
272
- // onStart is inside try so a throw still unwinds processing.
273
- await onStart?.();
274
-
275
- if (!skipFetch) {
276
- assertSource(url, fetcher, "visit");
277
- try {
278
- response = await execute({ method, url, payload: data, query, fetcher, onProgress });
279
- } catch (error) {
280
- const err = error as AxiosError<ValidationErrorPayload>;
281
- const normalized = normalizeValidationErrors(err.response?.data);
282
- await onError?.(normalized, err);
283
- if (!onError) throw error;
284
- return;
285
- }
286
- }
287
-
288
- if (method === "get") {
289
- const targetPath = routePath ?? route.path;
290
- if (!preserveState) clearRememberForPath(targetPath);
291
- const payload = { path: targetPath, query: (query ?? route.query) as LocationQueryRaw };
292
- if (replace) await router.replace(payload);
293
- else await router.push(payload);
294
- }
295
-
296
- await onSuccess?.(response!);
297
- return response;
298
- } finally {
299
- trackEnd();
300
- await onFinish?.();
301
- await restoreScroll(preserveScroll, savedY);
302
- }
303
- }
304
-
305
- function visit(url: string, options?: GumVisitOptions): Promise<AxiosResponse | undefined>;
306
- function visit(options: GumVisitOptions & { fetcher: Fetcher }): Promise<AxiosResponse | undefined>;
307
- function visit(urlOrOptions: string | (GumVisitOptions & { fetcher: Fetcher }), options: GumVisitOptions = {}) {
308
- if (typeof urlOrOptions === "object") {
309
- return runVisit({
310
- method: urlOrOptions.method ?? "get",
311
- fetcher: urlOrOptions.fetcher,
312
- data: urlOrOptions.data,
313
- query: urlOrOptions.query,
314
- routePath: urlOrOptions.routePath,
315
- replace: urlOrOptions.replace,
316
- preserveState: urlOrOptions.preserveState,
317
- preserveScroll: urlOrOptions.preserveScroll,
318
- skipFetch: urlOrOptions.skipFetch,
319
- hooks: urlOrOptions
320
- });
321
- }
322
- return runVisit({
323
- method: options.method ?? "get",
324
- url: urlOrOptions,
325
- data: options.data,
326
- query: options.query,
327
- routePath: options.routePath,
328
- replace: options.replace,
329
- preserveState: options.preserveState,
330
- preserveScroll: options.preserveScroll,
331
- skipFetch: options.skipFetch,
332
- fetcher: options.fetcher,
333
- hooks: options
334
- });
335
- }
336
-
337
- const api = {
338
- processing: globalProcessing,
339
- visit,
340
- get: (url: string, o: GumVisitOptions = {}) =>
341
- runVisit({
342
- method: "get",
343
- url,
344
- query: o.query,
345
- routePath: o.routePath,
346
- replace: o.replace,
347
- preserveState: o.preserveState,
348
- preserveScroll: o.preserveScroll,
349
- skipFetch: o.skipFetch,
350
- fetcher: o.fetcher,
351
- hooks: o
352
- }),
353
- post: (url: string, data?: GumVisitOptions["data"], o: GumVisitOptions = {}) =>
354
- runVisit({
355
- method: "post",
356
- url,
357
- data,
358
- query: o.query,
359
- routePath: o.routePath,
360
- replace: o.replace,
361
- preserveState: o.preserveState,
362
- preserveScroll: o.preserveScroll,
363
- skipFetch: o.skipFetch,
364
- fetcher: o.fetcher,
365
- hooks: o
366
- }),
367
- put: (url: string, data?: GumVisitOptions["data"], o: GumVisitOptions = {}) =>
368
- runVisit({
369
- method: "put",
370
- url,
371
- data,
372
- query: o.query,
373
- routePath: o.routePath,
374
- replace: o.replace,
375
- preserveState: o.preserveState,
376
- preserveScroll: o.preserveScroll,
377
- skipFetch: o.skipFetch,
378
- fetcher: o.fetcher,
379
- hooks: o
380
- }),
381
- patch: (url: string, data?: GumVisitOptions["data"], o: GumVisitOptions = {}) =>
382
- runVisit({
383
- method: "patch",
384
- url,
385
- data,
386
- query: o.query,
387
- routePath: o.routePath,
388
- replace: o.replace,
389
- preserveState: o.preserveState,
390
- preserveScroll: o.preserveScroll,
391
- skipFetch: o.skipFetch,
392
- fetcher: o.fetcher,
393
- hooks: o
394
- }),
395
- delete: (url: string, o: GumVisitOptions = {}) =>
396
- // Forward o.data so DELETE bodies keep working (legacy behavior).
397
- runVisit({
398
- method: "delete",
399
- url,
400
- data: o.data,
401
- query: o.query,
402
- routePath: o.routePath,
403
- replace: o.replace,
404
- preserveState: o.preserveState,
405
- preserveScroll: o.preserveScroll,
406
- skipFetch: o.skipFetch,
407
- fetcher: o.fetcher,
408
- hooks: o
409
- }),
410
- reload: (o: GumVisitOptions = {}) =>
411
- runVisit({
412
- method: "get",
413
- url: route.path,
414
- query: route.query as Record<string, unknown>,
415
- replace: true,
416
- preserveState: o.preserveState,
417
- preserveScroll: o.preserveScroll,
418
- skipFetch: o.skipFetch,
419
- fetcher: o.fetcher,
420
- hooks: o
421
- }),
422
-
423
- /* URL-less, fetcher-based variants */
424
- getWith: (o: VisitWithFetcherOptions): Promise<AxiosResponse | undefined> =>
425
- runVisit({
426
- method: "get",
427
- query: o.query,
428
- routePath: o.routePath,
429
- replace: o.replace,
430
- preserveState: o.preserveState,
431
- preserveScroll: o.preserveScroll,
432
- skipFetch: o.skipFetch,
433
- fetcher: o.fetcher,
434
- hooks: o
435
- }),
436
- postWith: (o: VisitWithFetcherDataOptions): Promise<AxiosResponse | undefined> =>
437
- runVisit({
438
- method: "post",
439
- data: o.data,
440
- query: o.query,
441
- routePath: o.routePath,
442
- replace: o.replace,
443
- preserveState: o.preserveState,
444
- preserveScroll: o.preserveScroll,
445
- skipFetch: o.skipFetch,
446
- fetcher: o.fetcher,
447
- hooks: o
448
- }),
449
- putWith: (o: VisitWithFetcherDataOptions): Promise<AxiosResponse | undefined> =>
450
- runVisit({
451
- method: "put",
452
- data: o.data,
453
- query: o.query,
454
- routePath: o.routePath,
455
- replace: o.replace,
456
- preserveState: o.preserveState,
457
- preserveScroll: o.preserveScroll,
458
- skipFetch: o.skipFetch,
459
- fetcher: o.fetcher,
460
- hooks: o
461
- }),
462
- patchWith: (o: VisitWithFetcherDataOptions): Promise<AxiosResponse | undefined> =>
463
- runVisit({
464
- method: "patch",
465
- data: o.data,
466
- query: o.query,
467
- routePath: o.routePath,
468
- replace: o.replace,
469
- preserveState: o.preserveState,
470
- preserveScroll: o.preserveScroll,
471
- skipFetch: o.skipFetch,
472
- fetcher: o.fetcher,
473
- hooks: o
474
- }),
475
- deleteWith: (o: VisitWithFetcherDataOptions): Promise<AxiosResponse | undefined> =>
476
- runVisit({
477
- method: "delete",
478
- data: o.data,
479
- query: o.query,
480
- routePath: o.routePath,
481
- replace: o.replace,
482
- preserveState: o.preserveState,
483
- preserveScroll: o.preserveScroll,
484
- skipFetch: o.skipFetch,
485
- fetcher: o.fetcher,
486
- hooks: o
487
- }),
488
- reloadWith: (o: VisitWithFetcherOptions): Promise<AxiosResponse | undefined> =>
489
- runVisit({
490
- method: "get",
491
- query: (o.query ?? route.query) as Record<string, unknown>,
492
- routePath: o.routePath,
493
- replace: true,
494
- preserveState: o.preserveState,
495
- preserveScroll: o.preserveScroll,
496
- skipFetch: o.skipFetch,
497
- fetcher: o.fetcher,
498
- hooks: o
499
- })
500
- };
501
-
502
- return api;
503
- }
504
-
505
- type GumApi = ReturnType<typeof buildVisitApi>;
506
-
507
- /* -------------------------------------------------------------------------- */
508
- /* Form state */
509
- /* -------------------------------------------------------------------------- */
510
-
511
- function createForm<T extends Record<string, unknown>>(defaults: T) {
512
- /* ------------------------ form state ----------------------------------- */
513
- const initial = structuredClone(defaults);
514
- const data = reactive(structuredClone(defaults)) as T;
515
- const errors = reactive<Record<string, string>>({});
516
- const progress = ref<number | null>(null);
517
- const formProcessing = ref(false);
518
- const wasSuccessful = ref(false);
519
- const recentlySuccessful = ref(false);
520
- const isDirty = computed(() => JSON.stringify(toRaw(data)) !== JSON.stringify(initial));
521
-
522
- function setError(field: keyof T | string, message: string) {
523
- errors[String(field)] = message;
524
- }
525
-
526
- function clearErrors(...fields: (keyof T | string)[]) {
527
- if (!fields.length) {
528
- Object.keys(errors).forEach((k) => delete errors[k]);
529
- return;
530
- }
531
- fields.forEach((f) => delete errors[String(f)]);
532
- }
533
-
534
- function reset(...fields: (keyof T)[]) {
535
- if (!fields.length) {
536
- Object.assign(data, structuredClone(initial));
537
- clearErrors();
538
- return;
539
- }
540
- fields.forEach((f) => {
541
- (data as any)[f] = structuredClone(initial[f]);
542
- delete errors[String(f)];
543
- });
544
- }
545
-
546
- async function submitForm(
547
- method: FormMethod,
548
- url: string | undefined,
549
- payload: Record<string, unknown> | undefined,
550
- opts: FormSubmitOptions<T>
551
- ): Promise<AxiosResponse | undefined> {
552
- const { onBefore, onStart, onProgress, onSuccess, onError, onFinish, validate, transform, fetcher } = opts;
553
- const userOnError = onError;
554
-
555
- if (!(await runBefore(onBefore))) return;
556
-
557
- assertSource(url, fetcher, "submit");
558
-
559
- // Local validation — only abort if there ARE errors (empty {} passes through).
560
- const validationErrors = validate?.(toRaw(data) as T);
561
- if (validationErrors && Object.keys(validationErrors).length > 0) {
562
- clearErrors();
563
- Object.entries(validationErrors).forEach(([k, v]) => setError(k, v));
564
- return;
565
- }
566
-
567
- const body = transform ? transform(toRaw(data) as T) : (payload ?? toRaw(data));
568
-
569
- wasSuccessful.value = false;
570
- clearErrors();
571
- formProcessing.value = true;
572
- trackStart();
573
-
574
- try {
575
- // onStart inside try — a throw still unwinds processing.
576
- await onStart?.();
577
-
578
- let response: AxiosResponse;
579
- try {
580
- response = await execute({
581
- method,
582
- url,
583
- payload: body,
584
- fetcher,
585
- onProgress: (event) => {
586
- onProgress?.(event);
587
- if (event.total) progress.value = Math.round((event.loaded * 100) / event.total);
588
- }
589
- });
590
- } catch (error) {
591
- const err = error as AxiosError<ValidationErrorPayload>;
592
- const normalized = normalizeValidationErrors(err.response?.data);
593
- Object.entries(normalized).forEach(([k, v]) => setError(k, Array.isArray(v) ? v[0] : v));
594
- await userOnError?.(normalized, err);
595
- if (!userOnError) throw error;
596
- return;
597
- }
598
-
599
- wasSuccessful.value = true;
600
- startRecentTimer({ recentlySuccessful });
601
- await onSuccess?.(response);
602
- return response;
603
- } finally {
604
- formProcessing.value = false;
605
- progress.value = null;
606
- trackEnd();
607
- await onFinish?.();
608
- }
609
- }
610
-
611
- return {
612
- data,
613
- errors: errors as FormErrors<T>,
614
- progress,
615
- processing: formProcessing,
616
- wasSuccessful,
617
- recentlySuccessful,
618
- isDirty,
619
- setError,
620
- clearErrors,
621
- reset,
622
- submit: (method: FormMethod, url: string | undefined, payload?: Record<string, unknown>, opts?: FormSubmitOptions<T>) =>
623
- submitForm(method, url, payload, opts ?? {}),
624
- post: (url: string, payload?: Record<string, unknown>, opts?: FormSubmitOptions<T>) => submitForm("post", url, payload, opts ?? {}),
625
- put: (url: string, payload?: Record<string, unknown>, opts?: FormSubmitOptions<T>) => submitForm("put", url, payload, opts ?? {}),
626
- patch: (url: string, payload?: Record<string, unknown>, opts?: FormSubmitOptions<T>) => submitForm("patch", url, payload, opts ?? {}),
627
- delete: (url: string, payload?: Record<string, unknown>, opts?: FormSubmitOptions<T>) => submitForm("delete", url, payload, opts ?? {}),
628
-
629
- /* URL-less, fetcher-based variants */
630
- postWith: (o: FormWithFetcherOptions<T>) => submitForm("post", undefined, undefined, o),
631
- putWith: (o: FormWithFetcherOptions<T>) => submitForm("put", undefined, undefined, o),
632
- patchWith: (o: FormWithFetcherOptions<T>) => submitForm("patch", undefined, undefined, o),
633
- deleteWith: (o: FormWithFetcherOptions<T>) => submitForm("delete", undefined, undefined, o)
634
- };
635
- }
636
-
637
- type GumForm<T extends Record<string, unknown>> = ReturnType<typeof createForm<T>>;
638
-
639
- /* -------------------------------------------------------------------------- */
640
- /* useGum — unified visit + form */
641
- /* -------------------------------------------------------------------------- */
642
-
643
- /**
644
- * Visit API only. `form` is not available when no defaults are passed.
645
- */
646
- export function useGum(): GumApi & { form?: undefined };
647
-
648
- /**
649
- * Visit API plus form state. Pass the form defaults as the first argument.
650
- */
651
- export function useGum<T extends Record<string, unknown>>(defaults: T): GumApi & { form: GumForm<T> };
652
-
653
- export function useGum<T extends Record<string, unknown>>(defaults?: T): GumApi & { form?: GumForm<T> } {
654
- const api = buildVisitApi();
655
- if (defaults === undefined) return api;
656
- return { ...api, form: createForm(defaults) };
657
- }
658
-
659
- /* -------------------------------------------------------------------------- */
660
- /* Backward-compat alias */
661
- /* -------------------------------------------------------------------------- */
662
-
663
- /**
664
- * @deprecated Use `useGum(defaults).form` instead.
665
- * Kept so existing pages don't break. Will be removed in a future major.
666
- */
667
- export function useGumForm<T extends Record<string, unknown>>(defaults: T): GumForm<T> {
668
- const { form } = useGum(defaults);
669
- return form;
670
- }
671
-
672
- /* -------------------------------------------------------------------------- */
673
- /* Plugin */
674
- /* -------------------------------------------------------------------------- */
675
-
676
- export const GumPlugin = {
677
- install(_app: App, options: GumPluginOptions = {}) {
678
- if (options.rememberPrefix) config.rememberPrefix = options.rememberPrefix;
679
- if (typeof options.recentlySuccessfulDuration === "number") {
680
- config.recentlySuccessfulDuration = options.recentlySuccessfulDuration;
681
- }
682
- }
683
- };