@niyamulahsan/create-deskapp 1.2.4 → 1.2.6

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 (104) hide show
  1. package/package.json +16 -16
  2. package/template/.env.example +20 -13
  3. package/template/AGENTS.md +699 -0
  4. package/template/package.json +3 -0
  5. package/template/src/config/app.ts +26 -24
  6. package/template/src/config/winsetup.ts +93 -91
  7. package/template/src/core/api/binding-error.ts +57 -0
  8. package/template/src/core/api/bindings.generated.ts +2 -0
  9. package/template/src/core/api/generate.manifest.ts +84 -80
  10. package/template/src/core/api/registry.ts +58 -48
  11. package/template/src/core/config.ts +101 -99
  12. package/template/src/core/database/aggregate.ts +89 -85
  13. package/template/src/core/database/config.ts +50 -48
  14. package/template/src/core/database/connection.ts +116 -114
  15. package/template/src/core/database/migrate-hooks.ts +86 -84
  16. package/template/src/core/database/paginate.ts +226 -224
  17. package/template/src/core/database/reset.ts +21 -19
  18. package/template/src/core/database/seed.ts +169 -167
  19. package/template/src/core/database/status.ts +37 -35
  20. package/template/src/core/env.ts +108 -106
  21. package/template/src/core/facade.ts +63 -61
  22. package/template/src/core/maker/db/fresh.ts +10 -8
  23. package/template/src/core/maker/db/generate.ts +13 -11
  24. package/template/src/core/maker/db/helpers.ts +92 -96
  25. package/template/src/core/maker/db/migrate.ts +37 -35
  26. package/template/src/core/maker/db/mod.ts +93 -91
  27. package/template/src/core/maker/db/module-migrate.ts +56 -54
  28. package/template/src/core/maker/db/push.ts +23 -21
  29. package/template/src/core/maker/db/reset.ts +8 -6
  30. package/template/src/core/maker/db/seed.ts +9 -7
  31. package/template/src/core/maker/db/status.ts +8 -6
  32. package/template/src/core/maker/help.ts +59 -57
  33. package/template/src/core/maker/make/controller.ts +25 -22
  34. package/template/src/core/maker/make/helpers.ts +97 -91
  35. package/template/src/core/maker/make/mod.ts +69 -67
  36. package/template/src/core/maker/make/model.ts +16 -14
  37. package/template/src/core/maker/make/module.ts +53 -39
  38. package/template/src/core/maker/make/seeder.ts +23 -21
  39. package/template/src/core/maker/make/test.ts +33 -30
  40. package/template/src/core/maker/mod.ts +85 -83
  41. package/template/src/core/maker/run/mod.ts +134 -132
  42. package/template/src/core/maker/stub.ts +26 -24
  43. package/template/src/core/maker/stubs/controller/controller.controller.stub +57 -55
  44. package/template/src/core/maker/stubs/controller/controller.schema.stub +18 -13
  45. package/template/src/core/maker/stubs/facade/facade.stub +21 -0
  46. package/template/src/core/maker/stubs/model/model.stub +10 -8
  47. package/template/src/core/maker/stubs/seeder/seeder.stub +18 -16
  48. package/template/src/core/maker/stubs/test/test.stub +9 -7
  49. package/template/src/core/maker/sync-config.ts +93 -94
  50. package/template/src/core/utils/password.ts +29 -27
  51. package/template/src/core/utils/playwright.ts +123 -121
  52. package/template/src/core/utils/queue.ts +68 -66
  53. package/template/src/core/utils/scheduler.ts +62 -60
  54. package/template/src/core/utils/storage.ts +3 -1
  55. package/template/src/core/utils/validation.ts +37 -35
  56. package/template/src/database/schema.ts +2 -0
  57. package/template/src/main.ts +120 -118
  58. package/template/src/modules/app/__tests__/demo.controller.test.ts +75 -0
  59. package/template/src/modules/app/__tests__/net.controller.test.ts +65 -0
  60. package/template/src/modules/app/__tests__/playwright.controller.test.ts +50 -0
  61. package/template/src/modules/app/__tests__/storage.controller.test.ts +114 -0
  62. package/template/src/modules/app/__tests__/window.controller.test.ts +98 -0
  63. package/template/src/modules/app/controllers/demo.controller.ts +120 -118
  64. package/template/src/modules/app/controllers/net.controller.ts +50 -48
  65. package/template/src/modules/app/controllers/playwright.controller.ts +142 -140
  66. package/template/src/modules/app/controllers/storage.controller.ts +231 -229
  67. package/template/src/modules/app/controllers/window.controller.ts +2 -0
  68. package/template/src/modules/app/facade.ts +21 -0
  69. package/template/src/preload.ts +25 -2
  70. package/template/src/ui/src/App.vue +4 -2
  71. package/template/src/ui/src/app.ts +38 -23
  72. package/template/src/ui/src/bindings.d.ts +18 -16
  73. package/template/src/ui/src/components/Button.vue +34 -32
  74. package/template/src/ui/src/components/Checkbox.vue +26 -29
  75. package/template/src/ui/src/components/Input.vue +221 -227
  76. package/template/src/ui/src/components/InputGroup.vue +141 -0
  77. package/template/src/ui/src/components/InputPasswordToggle.vue +204 -0
  78. package/template/src/ui/src/components/Modal.vue +65 -55
  79. package/template/src/ui/src/components/Spinner.vue +44 -42
  80. package/template/src/ui/src/components/Switch.vue +62 -65
  81. package/template/src/ui/src/components/TextArea.vue +108 -121
  82. package/template/src/ui/src/components/Toast.vue +55 -56
  83. package/template/src/ui/src/components/datatable/DataTableSkeleton.vue +100 -98
  84. package/template/src/ui/src/components/datatable/Pagination.vue +153 -125
  85. package/template/src/ui/src/components/datatable/SelectOpption.vue +36 -35
  86. package/template/src/ui/src/components/datatable/index.vue +336 -258
  87. package/template/src/ui/src/env.d.ts +16 -13
  88. package/template/src/ui/src/global.d.ts +21 -2
  89. package/template/src/ui/src/helpers/nformatter.ts +12 -10
  90. package/template/src/ui/src/pages/dashboard/index.vue +690 -687
  91. package/template/src/ui/src/plugins/browserDetect.ts +57 -0
  92. package/template/src/ui/src/plugins/gum.ts +576 -549
  93. package/template/src/ui/src/plugins/pulse.ts +181 -147
  94. package/template/src/ui/src/plugins/routeProgress.ts +89 -0
  95. package/template/src/ui/src/router/index.ts +44 -25
  96. package/template/src/ui/src/stores/example.ts +2 -0
  97. package/template/src/ui/vite.config.ts +40 -38
  98. package/template/src/window/app-menu.ts +89 -87
  99. package/template/src/window/config.ts +14 -12
  100. package/template/src/window/context-menu.ts +23 -21
  101. package/template/src/window/dialogs.ts +92 -90
  102. package/template/src/window/manager.ts +2 -0
  103. package/template/src/window/native.ts +47 -45
  104. package/template/src/window/tray.ts +132 -130
@@ -1,549 +1,576 @@
1
- import axios, { type AxiosError, type AxiosProgressEvent, type AxiosResponse } from "axios";
2
- import type { App } from "vue";
3
- import { computed, nextTick, reactive, ref, toRaw, watch } from "vue";
4
- import { type LocationQueryRaw, useRoute, useRouter } from "vue-router";
5
-
6
- /* -------------------------------------------------------------------------- */
7
- /* Types */
8
- /* -------------------------------------------------------------------------- */
9
-
10
- export type GumTransport = "bindings" | "http";
11
-
12
- export type GumPluginOptions = {
13
- rememberPrefix?: string;
14
- recentlySuccessfulDuration?: number;
15
- /** Default transport. Auto-detects: bindings when `globalThis.bindings` exists, else http. */
16
- transport?: GumTransport;
17
- /** Base URL for HTTP transport (e.g. "/api" or "https://api.example.com"). */
18
- baseURL?: string;
19
- };
20
-
21
- type GumMethod = "get" | "post" | "put" | "patch" | "delete";
22
- type FormMethod = "post" | "put" | "patch" | "delete";
23
-
24
- type LifecycleHooks = {
25
- onBefore?: () => boolean | undefined | Promise<boolean | undefined>;
26
- onStart?: () => void | Promise<void>;
27
- onProgress?: (event: AxiosProgressEvent) => void;
28
- onSuccess?: (response: AxiosResponse) => void | Promise<void>;
29
- onError?: (errors: NormalizedErrors, error: unknown) => void | Promise<void>;
30
- onFinish?: () => void | Promise<void>;
31
- };
32
-
33
- /**
34
- * A fetcher returns either an AxiosResponse-like payload or any plain value.
35
- * Gum wraps plain values into `{ data, status: 200, ... }`.
36
- */
37
- type Fetcher = (payload: Record<string, unknown> | FormData) => Promise<unknown>;
38
-
39
- type GumVisitOptions = LifecycleHooks & {
40
- method?: GumMethod;
41
- data?: Record<string, unknown> | FormData;
42
- query?: Record<string, unknown>;
43
- routePath?: string;
44
- replace?: boolean;
45
- preserveState?: boolean;
46
- preserveScroll?: boolean;
47
- skipFetch?: boolean;
48
- /** GET visits sync the route by default; set false to fetch without navigation. */
49
- navigate?: boolean;
50
- fetcher?: Fetcher;
51
- /** Per-call transport override. */
52
- transport?: GumTransport;
53
- /** Per-call baseURL override (HTTP transport). */
54
- baseURL?: string;
55
- };
56
-
57
- type VisitWithFetcherOptions = Omit<GumVisitOptions, "method" | "fetcher"> & { fetcher: Fetcher };
58
- type VisitWithFetcherDataOptions = VisitWithFetcherOptions & {
59
- data?: Record<string, unknown> | FormData;
60
- };
61
-
62
- type FormSubmitOptions<T> = LifecycleHooks & {
63
- validate?: (data: T) => Record<string, string> | null | undefined;
64
- transform?: (data: T) => Record<string, unknown> | FormData;
65
- fetcher?: Fetcher;
66
- };
67
-
68
- type FormWithFetcherOptions<T> = Omit<FormSubmitOptions<T>, "fetcher"> & { fetcher: Fetcher };
69
-
70
- type FormErrors<T> = Partial<Record<keyof T | string, string>>;
71
- export type NormalizedErrors = Record<string, string[] | string>;
72
-
73
- type ValidationErrorPayload = {
74
- errors?: Record<string, string[] | string>;
75
- error?: { issues?: Array<{ path?: Array<string | number>; message?: string }> };
76
- // bindings/zod-flatten style
77
- fieldErrors?: Record<string, string[] | string>;
78
- formErrors?: string[] | string;
79
- message?: string;
80
- };
81
-
82
- /* -------------------------------------------------------------------------- */
83
- /* Config + registry */
84
- /* -------------------------------------------------------------------------- */
85
-
86
- const config = {
87
- rememberPrefix: "gum",
88
- recentlySuccessfulDuration: 2000,
89
- transport: undefined as GumTransport | undefined,
90
- baseURL: ""
91
- };
92
-
93
- function effectiveTransport(override?: GumTransport): GumTransport {
94
- if (override) return override;
95
- if (config.transport) return config.transport;
96
- const g = globalThis as { bindings?: unknown };
97
- return g.bindings ? "bindings" : "http";
98
- }
99
-
100
- const routeRememberKeys = new Map<string, Set<string>>();
101
-
102
- function normalizePath(path: string) {
103
- const clean = (path || "/").split("?")[0];
104
- return clean || "/";
105
- }
106
-
107
- function registerRememberKey(path: string, key: string) {
108
- const routePath = normalizePath(path);
109
- if (!routeRememberKeys.has(routePath)) routeRememberKeys.set(routePath, new Set());
110
- routeRememberKeys.get(routePath)!.add(key);
111
- }
112
-
113
- export function clearRememberForPath(path: string) {
114
- const routePath = normalizePath(path);
115
- const keys = routeRememberKeys.get(routePath);
116
- if (!keys) return;
117
- keys.forEach((key) => localStorage.removeItem(`${config.rememberPrefix}:${key}`));
118
- }
119
-
120
- /* -------------------------------------------------------------------------- */
121
- /* Global processing tracker */
122
- /* -------------------------------------------------------------------------- */
123
-
124
- const globalProcessing = ref(false);
125
- let activeRequests = 0;
126
-
127
- function trackStart() {
128
- activeRequests++;
129
- globalProcessing.value = true;
130
- }
131
-
132
- function trackEnd() {
133
- activeRequests = Math.max(0, activeRequests - 1);
134
- if (activeRequests === 0) globalProcessing.value = false;
135
- }
136
-
137
- /* -------------------------------------------------------------------------- */
138
- /* Helpers */
139
- /* -------------------------------------------------------------------------- */
140
-
141
- export function normalizeValidationErrors(payload?: unknown): NormalizedErrors {
142
- if (!payload || typeof payload !== "object") return {};
143
- const p = payload as ValidationErrorPayload;
144
- const normalized: NormalizedErrors = { ...(p.errors ?? {}) };
145
-
146
- if (p.fieldErrors && typeof p.fieldErrors === "object") {
147
- for (const [k, v] of Object.entries(p.fieldErrors)) {
148
- if (k !== "_errors") normalized[k] = v;
149
- }
150
- }
151
- if (p.formErrors) {
152
- normalized.$root ??= Array.isArray(p.formErrors) ? p.formErrors : [p.formErrors];
153
- }
154
- const issues = p.error?.issues;
155
- if (Array.isArray(issues)) {
156
- issues.forEach((issue) => {
157
- const key = issue.path?.map(String).join(".");
158
- if (key) normalized[key] = String(issue.message || "Invalid value");
159
- });
160
- }
161
- if (p.message && Object.keys(normalized).length === 0) normalized.$root = p.message;
162
- return normalized;
163
- }
164
-
165
- async function runBefore(onBefore?: LifecycleHooks["onBefore"]) {
166
- const allow = await onBefore?.();
167
- return allow !== false;
168
- }
169
-
170
- async function restoreScroll(enabled: boolean, y: number) {
171
- if (!enabled) return;
172
- await nextTick();
173
- requestAnimationFrame(() => requestAnimationFrame(() => window.scrollTo({ top: y, behavior: "instant" as ScrollBehavior })));
174
- }
175
-
176
- function startRecentTimer(target: { recentlySuccessful: { value: boolean } }) {
177
- target.recentlySuccessful.value = true;
178
- setTimeout(() => {
179
- target.recentlySuccessful.value = false;
180
- }, config.recentlySuccessfulDuration);
181
- }
182
-
183
- function readScrollY(): number {
184
- return typeof window !== "undefined" ? window.scrollY : 0;
185
- }
186
-
187
- function asResponse(data: unknown, status = 200): AxiosResponse {
188
- return { data, status, statusText: "OK", headers: {}, config: {} as any } as AxiosResponse;
189
- }
190
-
191
- function resolveBindings(): Record<string, (...args: unknown[]) => Promise<unknown>> | undefined {
192
- const g = globalThis as { bindings?: Record<string, (...args: unknown[]) => Promise<unknown>> };
193
- return g.bindings;
194
- }
195
-
196
- function buildBindingPayload(method: GumMethod, data?: unknown, query?: unknown): unknown {
197
- const q = (query && typeof query === "object" ? query : undefined) as Record<string, unknown> | undefined;
198
- const d = (data && typeof data === "object" ? data : undefined) as Record<string, unknown> | undefined;
199
- if (method === "get" || method === "delete") return q ?? d ?? undefined;
200
- if (method === "put" || method === "patch") return { params: q ?? {}, body: d ?? {} };
201
- return d ?? data ?? undefined;
202
- }
203
-
204
- /* -------------------------------------------------------------------------- */
205
- /* Transport execution */
206
- /* -------------------------------------------------------------------------- */
207
-
208
- type ExecuteOptions = {
209
- method: GumMethod;
210
- url?: string;
211
- payload?: Record<string, unknown> | FormData;
212
- query?: Record<string, unknown>;
213
- fetcher?: Fetcher;
214
- onProgress?: (event: AxiosProgressEvent) => void;
215
- transport?: GumTransport;
216
- baseURL?: string;
217
- };
218
-
219
- async function execute(options: ExecuteOptions): Promise<AxiosResponse> {
220
- if (options.fetcher) {
221
- const result = await options.fetcher(options.payload ?? {});
222
- const looksLikeResponse =
223
- result !== null &&
224
- typeof result === "object" &&
225
- "data" in (result as Record<string, unknown>) &&
226
- typeof (result as { status?: unknown }).status === "number";
227
- return looksLikeResponse ? (result as AxiosResponse) : asResponse(result);
228
- }
229
-
230
- const transport = effectiveTransport(options.transport);
231
- if (transport === "bindings") {
232
- const bindings = resolveBindings();
233
- if (!bindings) {
234
- const err: any = new Error(
235
- 'Bindings unavailable. The desktop bridge (`globalThis.bindings`) is not injected. Run inside the desktop app, or use `GumPlugin` with `{ transport: "http", baseURL }` for web/API mode.'
236
- );
237
- err.response = { data: { message: err.message } };
238
- throw err;
239
- }
240
- if (!options.url) throw new Error("gum: bindings transport requires a binding name (url).");
241
- const handler = bindings[options.url];
242
- if (typeof handler !== "function") {
243
- const err: any = new Error(`Binding "${options.url}" not found.`);
244
- err.response = { status: 404, data: { message: err.message } };
245
- throw err;
246
- }
247
- const result = await handler(buildBindingPayload(options.method, options.payload, options.query));
248
- return asResponse(result);
249
- }
250
-
251
- // HTTP transport
252
- if (!options.url) throw new Error("gum: HTTP transport requires a URL.");
253
- const baseURL = options.baseURL ?? config.baseURL;
254
- return await axios.request({
255
- method: options.method,
256
- url: options.url,
257
- baseURL: baseURL || undefined,
258
- params: options.query,
259
- data: options.method === "get" ? undefined : options.payload,
260
- onUploadProgress: options.onProgress
261
- });
262
- }
263
-
264
- /* -------------------------------------------------------------------------- */
265
- /* Remember */
266
- /* -------------------------------------------------------------------------- */
267
-
268
- function useLocalStorage<T extends object>(key: string, initial: T) {
269
- const raw = typeof localStorage !== "undefined" ? localStorage.getItem(key) : null;
270
- let parsed: Partial<T> = {};
271
- if (raw) {
272
- try {
273
- parsed = JSON.parse(raw) as Partial<T>;
274
- } catch {}
275
- }
276
- const state = ref<T>({ ...structuredClone(initial), ...parsed }) as any;
277
- watch(
278
- state,
279
- (value) => {
280
- try {
281
- localStorage.setItem(key, JSON.stringify(value));
282
- } catch {}
283
- },
284
- { deep: true }
285
- );
286
- return state as { value: T };
287
- }
288
-
289
- export function useGumRemember<T extends object>(key: string, initial: T) {
290
- const route = useRoute();
291
- registerRememberKey(route.path, key);
292
- return useLocalStorage<T>(`${config.rememberPrefix}:${key}`, initial);
293
- }
294
-
295
- /* -------------------------------------------------------------------------- */
296
- /* Visit API */
297
- /* -------------------------------------------------------------------------- */
298
-
299
- function buildVisitApi() {
300
- const router = useRouter();
301
- const route = useRoute();
302
-
303
- async function runVisit(params: {
304
- method: GumMethod;
305
- url?: string;
306
- data?: Record<string, unknown> | FormData;
307
- query?: Record<string, unknown>;
308
- routePath?: string;
309
- replace?: boolean;
310
- preserveState?: boolean;
311
- preserveScroll?: boolean;
312
- skipFetch?: boolean;
313
- navigate?: boolean;
314
- fetcher?: Fetcher;
315
- transport?: GumTransport;
316
- baseURL?: string;
317
- hooks?: GumVisitOptions;
318
- }) {
319
- const {
320
- method,
321
- url,
322
- data,
323
- query,
324
- routePath,
325
- replace = false,
326
- preserveState = method !== "get",
327
- preserveScroll = false,
328
- skipFetch = false,
329
- navigate = method === "get",
330
- fetcher,
331
- transport,
332
- baseURL,
333
- hooks = {}
334
- } = params;
335
-
336
- const { onBefore, onStart, onProgress, onSuccess, onError, onFinish } = hooks;
337
- if (!(await runBefore(onBefore))) return;
338
-
339
- const savedY = readScrollY();
340
- trackStart();
341
-
342
- let response: AxiosResponse | undefined;
343
- try {
344
- await onStart?.();
345
- if (!skipFetch) {
346
- try {
347
- response = await execute({ method, url, payload: data, query, fetcher, onProgress, transport, baseURL });
348
- } catch (error) {
349
- const err = error as AxiosError<ValidationErrorPayload> & { response?: { data?: unknown } };
350
- const normalized = normalizeValidationErrors(err.response?.data ?? err);
351
- await onError?.(normalized, err);
352
- if (!onError) throw error;
353
- return;
354
- }
355
- }
356
-
357
- if (method === "get" && navigate) {
358
- const targetPath = routePath ?? route.path;
359
- if (!preserveState) clearRememberForPath(targetPath);
360
- const payload = { path: targetPath, query: (query ?? route.query) as LocationQueryRaw };
361
- if (replace) await router.replace(payload);
362
- else await router.push(payload);
363
- }
364
-
365
- await onSuccess?.(response!);
366
- return response;
367
- } finally {
368
- trackEnd();
369
- await onFinish?.();
370
- await restoreScroll(preserveScroll, savedY);
371
- }
372
- }
373
-
374
- function visit(url: string, options?: GumVisitOptions): Promise<AxiosResponse | undefined>;
375
- function visit(options: GumVisitOptions & { fetcher: Fetcher }): Promise<AxiosResponse | undefined>;
376
- function visit(urlOrOptions: string | (GumVisitOptions & { fetcher: Fetcher }), options: GumVisitOptions = {}) {
377
- if (typeof urlOrOptions === "object") {
378
- return runVisit({ method: urlOrOptions.method ?? "get", url: undefined, ...urlOrOptions, hooks: urlOrOptions });
379
- }
380
- return runVisit({ method: options.method ?? "get", url: urlOrOptions, ...options, hooks: options });
381
- }
382
-
383
- const api = {
384
- processing: globalProcessing,
385
- visit,
386
- get: (url: string, o: GumVisitOptions = {}) => runVisit({ method: "get", url, ...o, hooks: o }),
387
- post: (url: string, data?: GumVisitOptions["data"], o: GumVisitOptions = {}) => runVisit({ method: "post", url, data, ...o, hooks: o }),
388
- put: (url: string, data?: GumVisitOptions["data"], o: GumVisitOptions = {}) => runVisit({ method: "put", url, data, ...o, hooks: o }),
389
- patch: (url: string, data?: GumVisitOptions["data"], o: GumVisitOptions = {}) =>
390
- runVisit({ method: "patch", url, data, ...o, hooks: o }),
391
- delete: (url: string, o: GumVisitOptions = {}) => runVisit({ method: "delete", url, data: o.data, ...o, hooks: o }),
392
- reload: (o: GumVisitOptions = {}) =>
393
- runVisit({ method: "get", url: route.path, query: route.query as Record<string, unknown>, replace: true, ...o, hooks: o }),
394
-
395
- getWith: (o: VisitWithFetcherOptions) => runVisit({ method: "get", ...o, hooks: o }),
396
- postWith: (o: VisitWithFetcherDataOptions) => runVisit({ method: "post", ...o, hooks: o }),
397
- putWith: (o: VisitWithFetcherDataOptions) => runVisit({ method: "put", ...o, hooks: o }),
398
- patchWith: (o: VisitWithFetcherDataOptions) => runVisit({ method: "patch", ...o, hooks: o }),
399
- deleteWith: (o: VisitWithFetcherOptions) => runVisit({ method: "delete", ...o, hooks: o })
400
- };
401
-
402
- return api;
403
- }
404
-
405
- type GumApi = ReturnType<typeof buildVisitApi>;
406
-
407
- /* -------------------------------------------------------------------------- */
408
- /* Form */
409
- /* -------------------------------------------------------------------------- */
410
-
411
- function createForm<T extends Record<string, unknown>>(defaults: T) {
412
- const initial = structuredClone(defaults);
413
- const data = reactive(structuredClone(defaults)) as T;
414
- const errors = reactive<Record<string, string>>({});
415
- const progress = ref<number | null>(null);
416
- const formProcessing = ref(false);
417
- const wasSuccessful = ref(false);
418
- const recentlySuccessful = ref(false);
419
- const isDirty = computed(() => JSON.stringify(toRaw(data)) !== JSON.stringify(initial));
420
-
421
- function setError(field: keyof T | string, message: string) {
422
- errors[String(field)] = message;
423
- }
424
- function clearErrors(...fields: (keyof T | string)[]) {
425
- if (!fields.length) {
426
- Object.keys(errors).forEach((k) => delete errors[k]);
427
- return;
428
- }
429
- fields.forEach((f) => delete errors[String(f)]);
430
- }
431
- function reset(...fields: (keyof T)[]) {
432
- if (!fields.length) {
433
- Object.assign(data, structuredClone(initial));
434
- clearErrors();
435
- return;
436
- }
437
- fields.forEach((f) => {
438
- (data as any)[f] = structuredClone((initial as any)[f]);
439
- delete errors[String(f)];
440
- });
441
- }
442
-
443
- async function submitForm(method: FormMethod, url: string | undefined, payload: unknown, opts: FormSubmitOptions<T> & GumVisitOptions) {
444
- const { onBefore, onStart, onProgress, onSuccess, onError, onFinish, validate, transform, fetcher, transport, baseURL, query } =
445
- opts as any;
446
- if (!(await runBefore(onBefore))) return;
447
- if (validate) {
448
- const v = validate(toRaw(data) as T);
449
- if (v) {
450
- clearErrors();
451
- Object.entries(v).forEach(([k, val]) => (errors[k] = String(val)));
452
- return;
453
- }
454
- }
455
- clearErrors();
456
- formProcessing.value = true;
457
- progress.value = null;
458
- trackStart();
459
- try {
460
- await onStart?.();
461
- const body = (transform ? transform(toRaw(data) as T) : (payload ?? toRaw(data))) as any;
462
- const response = await execute({
463
- method,
464
- url,
465
- payload: body,
466
- query,
467
- fetcher,
468
- transport,
469
- baseURL,
470
- onProgress: (e) => {
471
- progress.value = e.total ? Math.round((e.loaded / e.total) * 100) : null;
472
- onProgress?.(e);
473
- }
474
- });
475
- wasSuccessful.value = true;
476
- startRecentTimer({ recentlySuccessful });
477
- await onSuccess?.(response);
478
- return response;
479
- } catch (error) {
480
- const err = error as any;
481
- const normalized = normalizeValidationErrors(err.response?.data ?? err);
482
- Object.entries(normalized).forEach(([k, v]) => (errors[k] = Array.isArray(v) ? v[0] : (v as string)));
483
- await onError?.(normalized, err);
484
- if (!onError) throw error;
485
- } finally {
486
- formProcessing.value = false;
487
- progress.value = null;
488
- trackEnd();
489
- await onFinish?.();
490
- }
491
- }
492
-
493
- return {
494
- data,
495
- errors: errors as FormErrors<T>,
496
- progress,
497
- processing: formProcessing,
498
- wasSuccessful,
499
- recentlySuccessful,
500
- isDirty,
501
- setError,
502
- clearErrors,
503
- reset,
504
- submit: (method: FormMethod, url: string | undefined, payload?: Record<string, unknown>, opts?: FormSubmitOptions<T>) =>
505
- submitForm(method, url, payload, opts ?? {}),
506
- post: (url: string, payload?: Record<string, unknown>, opts?: FormSubmitOptions<T>) => submitForm("post", url, payload, opts ?? {}),
507
- put: (url: string, payload?: Record<string, unknown>, opts?: FormSubmitOptions<T>) => submitForm("put", url, payload, opts ?? {}),
508
- patch: (url: string, payload?: Record<string, unknown>, opts?: FormSubmitOptions<T>) => submitForm("patch", url, payload, opts ?? {}),
509
- delete: (url: string, payload?: Record<string, unknown>, opts?: FormSubmitOptions<T>) => submitForm("delete", url, payload, opts ?? {}),
510
- postWith: (o: FormWithFetcherOptions<T>) => submitForm("post", undefined, undefined, o),
511
- putWith: (o: FormWithFetcherOptions<T>) => submitForm("put", undefined, undefined, o),
512
- patchWith: (o: FormWithFetcherOptions<T>) => submitForm("patch", undefined, undefined, o),
513
- deleteWith: (o: FormWithFetcherOptions<T>) => submitForm("delete", undefined, undefined, o)
514
- };
515
- }
516
-
517
- type GumForm<T extends Record<string, unknown>> = ReturnType<typeof createForm<T>>;
518
-
519
- /* -------------------------------------------------------------------------- */
520
- /* useGum */
521
- /* -------------------------------------------------------------------------- */
522
-
523
- export function useGum(): GumApi & { form?: undefined };
524
- export function useGum<T extends Record<string, unknown>>(defaults: T): GumApi & { form: GumForm<T> };
525
- export function useGum<T extends Record<string, unknown>>(defaults?: T): GumApi & { form?: GumForm<T> } {
526
- const api = buildVisitApi();
527
- if (defaults === undefined) return api as any;
528
- return { ...api, form: createForm(defaults) } as any;
529
- }
530
-
531
- /** @deprecated Use `useGum(defaults).form` instead. */
532
- export function useGumForm<T extends Record<string, unknown>>(defaults: T): GumForm<T> {
533
- return createForm(defaults);
534
- }
535
-
536
- /* -------------------------------------------------------------------------- */
537
- /* Plugin */
538
- /* -------------------------------------------------------------------------- */
539
-
540
- export const GumPlugin = {
541
- install(_app: App, options: GumPluginOptions = {}) {
542
- if (options.rememberPrefix) config.rememberPrefix = options.rememberPrefix;
543
- if (typeof options.recentlySuccessfulDuration === "number") {
544
- config.recentlySuccessfulDuration = options.recentlySuccessfulDuration;
545
- }
546
- if (options.transport) config.transport = options.transport;
547
- if (typeof options.baseURL === "string") config.baseURL = options.baseURL;
548
- }
549
- };
1
+ // ./src/ui/src/plugins/gum.ts
2
+
3
+ import axios, { type AxiosError, type AxiosProgressEvent, type AxiosResponse } from "axios";
4
+ import type { App } from "vue";
5
+ import { computed, nextTick, reactive, ref, toRaw, watch } from "vue";
6
+ import { type LocationQueryRaw, useRoute, useRouter } from "vue-router";
7
+
8
+ /* -------------------------------------------------------------------------- */
9
+ /* Types */
10
+ /* -------------------------------------------------------------------------- */
11
+
12
+ export type GumTransport = "bindings" | "http";
13
+
14
+ export type GumPluginOptions = {
15
+ rememberPrefix?: string;
16
+ recentlySuccessfulDuration?: number;
17
+ /** Default transport. Auto-detects: bindings when `globalThis.bindings` exists, else http. */
18
+ transport?: GumTransport;
19
+ /** Base URL for HTTP transport (e.g. "/api" or "https://api.example.com"). */
20
+ baseURL?: string;
21
+ };
22
+
23
+ type GumMethod = "get" | "post" | "put" | "patch" | "delete";
24
+ type FormMethod = "post" | "put" | "patch" | "delete";
25
+
26
+ type LifecycleHooks = {
27
+ onBefore?: () => boolean | undefined | Promise<boolean | undefined>;
28
+ onStart?: () => void | Promise<void>;
29
+ onProgress?: (event: AxiosProgressEvent) => void;
30
+ onSuccess?: (response: AxiosResponse) => void | Promise<void>;
31
+ onError?: (errors: NormalizedErrors, error: unknown) => void | Promise<void>;
32
+ onFinish?: () => void | Promise<void>;
33
+ };
34
+
35
+ /**
36
+ * A fetcher returns either an AxiosResponse-like payload or any plain value.
37
+ * Gum wraps plain values into `{ data, status: 200, ... }`.
38
+ */
39
+ type Fetcher = (payload: Record<string, unknown> | FormData) => Promise<unknown>;
40
+
41
+ type GumVisitOptions = LifecycleHooks & {
42
+ method?: GumMethod;
43
+ data?: Record<string, unknown> | FormData;
44
+ query?: Record<string, unknown>;
45
+ routePath?: string;
46
+ replace?: boolean;
47
+ preserveState?: boolean;
48
+ preserveScroll?: boolean;
49
+ skipFetch?: boolean;
50
+ /** GET visits sync the route by default; set false to fetch without navigation. */
51
+ navigate?: boolean;
52
+ fetcher?: Fetcher;
53
+ /** Per-call transport override. */
54
+ transport?: GumTransport;
55
+ /** Per-call baseURL override (HTTP transport). */
56
+ baseURL?: string;
57
+ };
58
+
59
+ type VisitWithFetcherOptions = Omit<GumVisitOptions, "method" | "fetcher"> & { fetcher: Fetcher };
60
+ type VisitWithFetcherDataOptions = VisitWithFetcherOptions & {
61
+ data?: Record<string, unknown> | FormData;
62
+ };
63
+
64
+ type FormSubmitOptions<T> = LifecycleHooks & {
65
+ validate?: (data: T) => Record<string, string> | null | undefined;
66
+ transform?: (data: T) => Record<string, unknown> | FormData;
67
+ fetcher?: Fetcher;
68
+ };
69
+
70
+ type FormWithFetcherOptions<T> = Omit<FormSubmitOptions<T>, "fetcher"> & { fetcher: Fetcher };
71
+
72
+ type FormErrors<T> = Partial<Record<keyof T | string, string>>;
73
+ export type NormalizedErrors = Record<string, string[] | string>;
74
+
75
+ type ValidationErrorPayload = {
76
+ /** Flat map (`{ field: "message" }`) or zod `flatten()` output. */
77
+ errors?:
78
+ | Record<string, string[] | string>
79
+ | {
80
+ fieldErrors?: Record<string, string[] | string>;
81
+ formErrors?: string[] | string;
82
+ [key: string]: unknown;
83
+ };
84
+ error?: { issues?: Array<{ path?: Array<string | number>; message?: string }> };
85
+ // bindings/zod-flatten style, top-level
86
+ fieldErrors?: Record<string, string[] | string>;
87
+ formErrors?: string[] | string;
88
+ message?: string;
89
+ };
90
+
91
+ /* -------------------------------------------------------------------------- */
92
+ /* Config + registry */
93
+ /* -------------------------------------------------------------------------- */
94
+
95
+ const config = {
96
+ rememberPrefix: "gum",
97
+ recentlySuccessfulDuration: 2000,
98
+ transport: undefined as GumTransport | undefined,
99
+ baseURL: ""
100
+ };
101
+
102
+ function effectiveTransport(override?: GumTransport): GumTransport {
103
+ if (override) return override;
104
+ if (config.transport) return config.transport;
105
+ const g = globalThis as { bindings?: unknown };
106
+ return g.bindings ? "bindings" : "http";
107
+ }
108
+
109
+ const routeRememberKeys = new Map<string, Set<string>>();
110
+
111
+ function normalizePath(path: string) {
112
+ const clean = (path || "/").split("?")[0];
113
+ return clean || "/";
114
+ }
115
+
116
+ function registerRememberKey(path: string, key: string) {
117
+ const routePath = normalizePath(path);
118
+ if (!routeRememberKeys.has(routePath)) routeRememberKeys.set(routePath, new Set());
119
+ routeRememberKeys.get(routePath)!.add(key);
120
+ }
121
+
122
+ export function clearRememberForPath(path: string) {
123
+ const routePath = normalizePath(path);
124
+ const keys = routeRememberKeys.get(routePath);
125
+ if (!keys) return;
126
+ keys.forEach((key) => localStorage.removeItem(`${config.rememberPrefix}:${key}`));
127
+ }
128
+
129
+ /* -------------------------------------------------------------------------- */
130
+ /* Global processing tracker */
131
+ /* -------------------------------------------------------------------------- */
132
+
133
+ const globalProcessing = ref(false);
134
+ let activeRequests = 0;
135
+
136
+ function trackStart() {
137
+ activeRequests++;
138
+ globalProcessing.value = true;
139
+ }
140
+
141
+ function trackEnd() {
142
+ activeRequests = Math.max(0, activeRequests - 1);
143
+ if (activeRequests === 0) globalProcessing.value = false;
144
+ }
145
+
146
+ /* -------------------------------------------------------------------------- */
147
+ /* Helpers */
148
+ /* -------------------------------------------------------------------------- */
149
+
150
+ export function normalizeValidationErrors(payload?: unknown): NormalizedErrors {
151
+ if (!payload || typeof payload !== "object") return {};
152
+ const p = payload as ValidationErrorPayload;
153
+ const normalized: NormalizedErrors = {};
154
+
155
+ const errors = (p.errors && typeof p.errors === "object" ? p.errors : undefined) as
156
+ | Record<string, unknown>
157
+ | undefined;
158
+
159
+ // Flat map: `errors: { field: "message" }`.
160
+ if (errors) {
161
+ for (const [key, value] of Object.entries(errors)) {
162
+ if (key === "fieldErrors" || key === "formErrors") continue;
163
+ normalized[key] = value as string[] | string;
164
+ }
165
+ }
166
+
167
+ // Zod `flatten()` output — either top-level or nested under `errors`.
168
+ const fieldErrors = (p.fieldErrors ?? errors?.fieldErrors) as
169
+ | Record<string, string[] | string>
170
+ | undefined;
171
+ if (fieldErrors && typeof fieldErrors === "object") {
172
+ for (const [key, value] of Object.entries(fieldErrors)) {
173
+ if (key !== "_errors") normalized[key] = value;
174
+ }
175
+ }
176
+ const formErrors = (p.formErrors ?? errors?.formErrors) as string[] | string | undefined;
177
+ if (formErrors) {
178
+ normalized.$root ??= Array.isArray(formErrors) ? formErrors : [formErrors];
179
+ }
180
+
181
+ const issues = p.error?.issues;
182
+ if (Array.isArray(issues)) {
183
+ issues.forEach((issue) => {
184
+ const key = issue.path?.map(String).join(".");
185
+ if (key) normalized[key] = String(issue.message || "Invalid value");
186
+ });
187
+ }
188
+ if (p.message && Object.keys(normalized).length === 0) normalized.$root = p.message;
189
+ return normalized;
190
+ }
191
+
192
+ async function runBefore(onBefore?: LifecycleHooks["onBefore"]) {
193
+ const allow = await onBefore?.();
194
+ return allow !== false;
195
+ }
196
+
197
+ async function restoreScroll(enabled: boolean, y: number) {
198
+ if (!enabled) return;
199
+ await nextTick();
200
+ requestAnimationFrame(() => requestAnimationFrame(() => window.scrollTo({ top: y, behavior: "instant" as ScrollBehavior })));
201
+ }
202
+
203
+ function startRecentTimer(target: { recentlySuccessful: { value: boolean } }) {
204
+ target.recentlySuccessful.value = true;
205
+ setTimeout(() => {
206
+ target.recentlySuccessful.value = false;
207
+ }, config.recentlySuccessfulDuration);
208
+ }
209
+
210
+ function readScrollY(): number {
211
+ return typeof window !== "undefined" ? window.scrollY : 0;
212
+ }
213
+
214
+ function asResponse(data: unknown, status = 200): AxiosResponse {
215
+ return { data, status, statusText: "OK", headers: {}, config: {} as any } as AxiosResponse;
216
+ }
217
+
218
+ function resolveBindings(): Record<string, (...args: unknown[]) => Promise<unknown>> | undefined {
219
+ const g = globalThis as { bindings?: Record<string, (...args: unknown[]) => Promise<unknown>> };
220
+ return g.bindings;
221
+ }
222
+
223
+ function buildBindingPayload(method: GumMethod, data?: unknown, query?: unknown): unknown {
224
+ const q = (query && typeof query === "object" ? query : undefined) as Record<string, unknown> | undefined;
225
+ const d = (data && typeof data === "object" ? data : undefined) as Record<string, unknown> | undefined;
226
+ if (method === "get" || method === "delete") return q ?? d ?? undefined;
227
+ if (method === "put" || method === "patch") return { params: q ?? {}, body: d ?? {} };
228
+ return d ?? data ?? undefined;
229
+ }
230
+
231
+ /* -------------------------------------------------------------------------- */
232
+ /* Transport execution */
233
+ /* -------------------------------------------------------------------------- */
234
+
235
+ type ExecuteOptions = {
236
+ method: GumMethod;
237
+ url?: string;
238
+ payload?: Record<string, unknown> | FormData;
239
+ query?: Record<string, unknown>;
240
+ fetcher?: Fetcher;
241
+ onProgress?: (event: AxiosProgressEvent) => void;
242
+ transport?: GumTransport;
243
+ baseURL?: string;
244
+ };
245
+
246
+ async function execute(options: ExecuteOptions): Promise<AxiosResponse> {
247
+ if (options.fetcher) {
248
+ const result = await options.fetcher(options.payload ?? {});
249
+ const looksLikeResponse =
250
+ result !== null &&
251
+ typeof result === "object" &&
252
+ "data" in (result as Record<string, unknown>) &&
253
+ typeof (result as { status?: unknown }).status === "number";
254
+ return looksLikeResponse ? (result as AxiosResponse) : asResponse(result);
255
+ }
256
+
257
+ const transport = effectiveTransport(options.transport);
258
+ if (transport === "bindings") {
259
+ const bindings = resolveBindings();
260
+ if (!bindings) {
261
+ const err: any = new Error(
262
+ 'Bindings unavailable. The desktop bridge (`globalThis.bindings`) is not injected. Run inside the desktop app, or use `GumPlugin` with `{ transport: "http", baseURL }` for web/API mode.'
263
+ );
264
+ err.response = { data: { message: err.message } };
265
+ throw err;
266
+ }
267
+ if (!options.url) throw new Error("gum: bindings transport requires a binding name (url).");
268
+ const handler = bindings[options.url];
269
+ if (typeof handler !== "function") {
270
+ const err: any = new Error(`Binding "${options.url}" not found.`);
271
+ err.response = { status: 404, data: { message: err.message } };
272
+ throw err;
273
+ }
274
+ const result = await handler(buildBindingPayload(options.method, options.payload, options.query));
275
+ return asResponse(result);
276
+ }
277
+
278
+ // HTTP transport
279
+ if (!options.url) throw new Error("gum: HTTP transport requires a URL.");
280
+ const baseURL = options.baseURL ?? config.baseURL;
281
+ return await axios.request({
282
+ method: options.method,
283
+ url: options.url,
284
+ baseURL: baseURL || undefined,
285
+ params: options.query,
286
+ data: options.method === "get" ? undefined : options.payload,
287
+ onUploadProgress: options.onProgress
288
+ });
289
+ }
290
+
291
+ /* -------------------------------------------------------------------------- */
292
+ /* Remember */
293
+ /* -------------------------------------------------------------------------- */
294
+
295
+ function useLocalStorage<T extends object>(key: string, initial: T) {
296
+ const raw = typeof localStorage !== "undefined" ? localStorage.getItem(key) : null;
297
+ let parsed: Partial<T> = {};
298
+ if (raw) {
299
+ try {
300
+ parsed = JSON.parse(raw) as Partial<T>;
301
+ } catch {}
302
+ }
303
+ const state = ref<T>({ ...structuredClone(initial), ...parsed }) as any;
304
+ watch(
305
+ state,
306
+ (value) => {
307
+ try {
308
+ localStorage.setItem(key, JSON.stringify(value));
309
+ } catch {}
310
+ },
311
+ { deep: true }
312
+ );
313
+ return state as { value: T };
314
+ }
315
+
316
+ export function useGumRemember<T extends object>(key: string, initial: T) {
317
+ const route = useRoute();
318
+ registerRememberKey(route.path, key);
319
+ return useLocalStorage<T>(`${config.rememberPrefix}:${key}`, initial);
320
+ }
321
+
322
+ /* -------------------------------------------------------------------------- */
323
+ /* Visit API */
324
+ /* -------------------------------------------------------------------------- */
325
+
326
+ function buildVisitApi() {
327
+ const router = useRouter();
328
+ const route = useRoute();
329
+
330
+ async function runVisit(params: {
331
+ method: GumMethod;
332
+ url?: string;
333
+ data?: Record<string, unknown> | FormData;
334
+ query?: Record<string, unknown>;
335
+ routePath?: string;
336
+ replace?: boolean;
337
+ preserveState?: boolean;
338
+ preserveScroll?: boolean;
339
+ skipFetch?: boolean;
340
+ navigate?: boolean;
341
+ fetcher?: Fetcher;
342
+ transport?: GumTransport;
343
+ baseURL?: string;
344
+ hooks?: GumVisitOptions;
345
+ }) {
346
+ const {
347
+ method,
348
+ url,
349
+ data,
350
+ query,
351
+ routePath,
352
+ replace = false,
353
+ preserveState = method !== "get",
354
+ preserveScroll = false,
355
+ skipFetch = false,
356
+ navigate = method === "get",
357
+ fetcher,
358
+ transport,
359
+ baseURL,
360
+ hooks = {}
361
+ } = params;
362
+
363
+ const { onBefore, onStart, onProgress, onSuccess, onError, onFinish } = hooks;
364
+ if (!(await runBefore(onBefore))) return;
365
+
366
+ const savedY = readScrollY();
367
+ trackStart();
368
+
369
+ let response: AxiosResponse | undefined;
370
+ try {
371
+ await onStart?.();
372
+ if (!skipFetch) {
373
+ try {
374
+ response = await execute({ method, url, payload: data, query, fetcher, onProgress, transport, baseURL });
375
+ } catch (error) {
376
+ const err = error as AxiosError<ValidationErrorPayload> & { response?: { data?: unknown } };
377
+ const normalized = normalizeValidationErrors(err.response?.data ?? err);
378
+ await onError?.(normalized, err);
379
+ if (!onError) throw error;
380
+ return;
381
+ }
382
+ }
383
+
384
+ if (method === "get" && navigate) {
385
+ const targetPath = routePath ?? route.path;
386
+ if (!preserveState) clearRememberForPath(targetPath);
387
+ const payload = { path: targetPath, query: (query ?? route.query) as LocationQueryRaw };
388
+ if (replace) await router.replace(payload);
389
+ else await router.push(payload);
390
+ }
391
+
392
+ await onSuccess?.(response!);
393
+ return response;
394
+ } finally {
395
+ trackEnd();
396
+ await onFinish?.();
397
+ await restoreScroll(preserveScroll, savedY);
398
+ }
399
+ }
400
+
401
+ function visit(url: string, options?: GumVisitOptions): Promise<AxiosResponse | undefined>;
402
+ function visit(options: GumVisitOptions & { fetcher: Fetcher }): Promise<AxiosResponse | undefined>;
403
+ function visit(urlOrOptions: string | (GumVisitOptions & { fetcher: Fetcher }), options: GumVisitOptions = {}) {
404
+ if (typeof urlOrOptions === "object") {
405
+ return runVisit({ method: urlOrOptions.method ?? "get", url: undefined, ...urlOrOptions, hooks: urlOrOptions });
406
+ }
407
+ return runVisit({ method: options.method ?? "get", url: urlOrOptions, ...options, hooks: options });
408
+ }
409
+
410
+ const api = {
411
+ processing: globalProcessing,
412
+ visit,
413
+ get: (url: string, o: GumVisitOptions = {}) => runVisit({ method: "get", url, ...o, hooks: o }),
414
+ post: (url: string, data?: GumVisitOptions["data"], o: GumVisitOptions = {}) => runVisit({ method: "post", url, data, ...o, hooks: o }),
415
+ put: (url: string, data?: GumVisitOptions["data"], o: GumVisitOptions = {}) => runVisit({ method: "put", url, data, ...o, hooks: o }),
416
+ patch: (url: string, data?: GumVisitOptions["data"], o: GumVisitOptions = {}) =>
417
+ runVisit({ method: "patch", url, data, ...o, hooks: o }),
418
+ delete: (url: string, o: GumVisitOptions = {}) => runVisit({ method: "delete", url, data: o.data, ...o, hooks: o }),
419
+ reload: (o: GumVisitOptions = {}) =>
420
+ runVisit({ method: "get", url: route.path, query: route.query as Record<string, unknown>, replace: true, ...o, hooks: o }),
421
+
422
+ getWith: (o: VisitWithFetcherOptions) => runVisit({ method: "get", ...o, hooks: o }),
423
+ postWith: (o: VisitWithFetcherDataOptions) => runVisit({ method: "post", ...o, hooks: o }),
424
+ putWith: (o: VisitWithFetcherDataOptions) => runVisit({ method: "put", ...o, hooks: o }),
425
+ patchWith: (o: VisitWithFetcherDataOptions) => runVisit({ method: "patch", ...o, hooks: o }),
426
+ deleteWith: (o: VisitWithFetcherOptions) => runVisit({ method: "delete", ...o, hooks: o })
427
+ };
428
+
429
+ return api;
430
+ }
431
+
432
+ type GumApi = ReturnType<typeof buildVisitApi>;
433
+
434
+ /* -------------------------------------------------------------------------- */
435
+ /* Form */
436
+ /* -------------------------------------------------------------------------- */
437
+
438
+ function createForm<T extends Record<string, unknown>>(defaults: T) {
439
+ const initial = structuredClone(defaults);
440
+ const data = reactive(structuredClone(defaults)) as T;
441
+ const errors = reactive<Record<string, string>>({});
442
+ const progress = ref<number | null>(null);
443
+ const formProcessing = ref(false);
444
+ const wasSuccessful = ref(false);
445
+ const recentlySuccessful = ref(false);
446
+ const isDirty = computed(() => JSON.stringify(toRaw(data)) !== JSON.stringify(initial));
447
+
448
+ function setError(field: keyof T | string, message: string) {
449
+ errors[String(field)] = message;
450
+ }
451
+ function clearErrors(...fields: (keyof T | string)[]) {
452
+ if (!fields.length) {
453
+ Object.keys(errors).forEach((k) => delete errors[k]);
454
+ return;
455
+ }
456
+ fields.forEach((f) => delete errors[String(f)]);
457
+ }
458
+ function reset(...fields: (keyof T)[]) {
459
+ if (!fields.length) {
460
+ Object.assign(data, structuredClone(initial));
461
+ clearErrors();
462
+ return;
463
+ }
464
+ fields.forEach((f) => {
465
+ (data as any)[f] = structuredClone((initial as any)[f]);
466
+ delete errors[String(f)];
467
+ });
468
+ }
469
+
470
+ async function submitForm(method: FormMethod, url: string | undefined, payload: unknown, opts: FormSubmitOptions<T> & GumVisitOptions) {
471
+ const { onBefore, onStart, onProgress, onSuccess, onError, onFinish, validate, transform, fetcher, transport, baseURL, query } =
472
+ opts as any;
473
+ if (!(await runBefore(onBefore))) return;
474
+ if (validate) {
475
+ const v = validate(toRaw(data) as T);
476
+ if (v) {
477
+ clearErrors();
478
+ Object.entries(v).forEach(([k, val]) => (errors[k] = String(val)));
479
+ return;
480
+ }
481
+ }
482
+ clearErrors();
483
+ formProcessing.value = true;
484
+ progress.value = null;
485
+ trackStart();
486
+ try {
487
+ await onStart?.();
488
+ const body = (transform ? transform(toRaw(data) as T) : (payload ?? toRaw(data))) as any;
489
+ const response = await execute({
490
+ method,
491
+ url,
492
+ payload: body,
493
+ query,
494
+ fetcher,
495
+ transport,
496
+ baseURL,
497
+ onProgress: (e) => {
498
+ progress.value = e.total ? Math.round((e.loaded / e.total) * 100) : null;
499
+ onProgress?.(e);
500
+ }
501
+ });
502
+ wasSuccessful.value = true;
503
+ startRecentTimer({ recentlySuccessful });
504
+ await onSuccess?.(response);
505
+ return response;
506
+ } catch (error) {
507
+ const err = error as any;
508
+ const normalized = normalizeValidationErrors(err.response?.data ?? err);
509
+ Object.entries(normalized).forEach(([k, v]) => (errors[k] = Array.isArray(v) ? v[0] : (v as string)));
510
+ await onError?.(normalized, err);
511
+ if (!onError) throw error;
512
+ } finally {
513
+ formProcessing.value = false;
514
+ progress.value = null;
515
+ trackEnd();
516
+ await onFinish?.();
517
+ }
518
+ }
519
+
520
+ return {
521
+ data,
522
+ errors: errors as FormErrors<T>,
523
+ progress,
524
+ processing: formProcessing,
525
+ wasSuccessful,
526
+ recentlySuccessful,
527
+ isDirty,
528
+ setError,
529
+ clearErrors,
530
+ reset,
531
+ submit: (method: FormMethod, url: string | undefined, payload?: Record<string, unknown>, opts?: FormSubmitOptions<T>) =>
532
+ submitForm(method, url, payload, opts ?? {}),
533
+ post: (url: string, payload?: Record<string, unknown>, opts?: FormSubmitOptions<T>) => submitForm("post", url, payload, opts ?? {}),
534
+ put: (url: string, payload?: Record<string, unknown>, opts?: FormSubmitOptions<T>) => submitForm("put", url, payload, opts ?? {}),
535
+ patch: (url: string, payload?: Record<string, unknown>, opts?: FormSubmitOptions<T>) => submitForm("patch", url, payload, opts ?? {}),
536
+ delete: (url: string, payload?: Record<string, unknown>, opts?: FormSubmitOptions<T>) => submitForm("delete", url, payload, opts ?? {}),
537
+ postWith: (o: FormWithFetcherOptions<T>) => submitForm("post", undefined, undefined, o),
538
+ putWith: (o: FormWithFetcherOptions<T>) => submitForm("put", undefined, undefined, o),
539
+ patchWith: (o: FormWithFetcherOptions<T>) => submitForm("patch", undefined, undefined, o),
540
+ deleteWith: (o: FormWithFetcherOptions<T>) => submitForm("delete", undefined, undefined, o)
541
+ };
542
+ }
543
+
544
+ type GumForm<T extends Record<string, unknown>> = ReturnType<typeof createForm<T>>;
545
+
546
+ /* -------------------------------------------------------------------------- */
547
+ /* useGum */
548
+ /* -------------------------------------------------------------------------- */
549
+
550
+ export function useGum(): GumApi & { form?: undefined };
551
+ export function useGum<T extends Record<string, unknown>>(defaults: T): GumApi & { form: GumForm<T> };
552
+ export function useGum<T extends Record<string, unknown>>(defaults?: T): GumApi & { form?: GumForm<T> } {
553
+ const api = buildVisitApi();
554
+ if (defaults === undefined) return api as any;
555
+ return { ...api, form: createForm(defaults) } as any;
556
+ }
557
+
558
+ /** @deprecated Use `useGum(defaults).form` instead. */
559
+ export function useGumForm<T extends Record<string, unknown>>(defaults: T): GumForm<T> {
560
+ return createForm(defaults);
561
+ }
562
+
563
+ /* -------------------------------------------------------------------------- */
564
+ /* Plugin */
565
+ /* -------------------------------------------------------------------------- */
566
+
567
+ export const GumPlugin = {
568
+ install(_app: App, options: GumPluginOptions = {}) {
569
+ if (options.rememberPrefix) config.rememberPrefix = options.rememberPrefix;
570
+ if (typeof options.recentlySuccessfulDuration === "number") {
571
+ config.recentlySuccessfulDuration = options.recentlySuccessfulDuration;
572
+ }
573
+ if (options.transport) config.transport = options.transport;
574
+ if (typeof options.baseURL === "string") config.baseURL = options.baseURL;
575
+ }
576
+ };