keits 0.0.3 → 0.1.0

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 (75) hide show
  1. package/README.md +93 -79
  2. package/dist/dev/api.js +275 -0
  3. package/dist/dev/forms.js +330 -0
  4. package/dist/dev/index.js +26 -326
  5. package/dist/dev/router.js +24 -5
  6. package/dist/dev/shared/computed-DrF8O8b4.js +40 -0
  7. package/dist/dev/shared/{element-C4DfKtZW.js → element-DXwmUAnz.js} +32 -111
  8. package/dist/dev/shared/{graph-D6-x_CWC.js → graph-SIvYLXSv.js} +62 -3
  9. package/dist/dev/shared/hydrate-C8cOsDDH.js +588 -0
  10. package/dist/dev/shared/mount-CDB2HgN5.js +23 -0
  11. package/dist/dev/shared/namespaces-Cz82B0Pr.js +84 -0
  12. package/dist/dev/shared/owner-BuwIoI4j.js +72 -0
  13. package/dist/dev/shared/render-context-k2uu_dM_.js +34 -0
  14. package/dist/dev/shared/render-effect-Uk9dDmuU.js +32 -0
  15. package/dist/dev/shared/resource-DlgzdtcG.js +145 -0
  16. package/dist/dev/shared/signal-B3xOKbVm.js +24 -0
  17. package/dist/dev/shared/store-0vEg2bQV.js +152 -0
  18. package/dist/dev/shared/unsafe-keys-CB1P22No.js +8 -0
  19. package/dist/dev/static.js +76 -0
  20. package/dist/dev/svg.js +2 -1
  21. package/dist/dev/testing.js +216 -0
  22. package/dist/dev/vite.js +141 -0
  23. package/dist/prod/api.js +215 -0
  24. package/dist/prod/forms.js +240 -0
  25. package/dist/prod/index.js +110 -327
  26. package/dist/prod/router.js +83 -68
  27. package/dist/prod/shared/computed-BjqJ6Pps.js +33 -0
  28. package/dist/prod/shared/element-DCit4-3e.js +129 -0
  29. package/dist/prod/shared/{graph-C_aA46c6.js → graph-CR2WKbwr.js} +107 -63
  30. package/dist/prod/shared/hydrate-kKnJbkV7.js +480 -0
  31. package/dist/prod/shared/mount-DbeKIoyD.js +18 -0
  32. package/dist/prod/shared/namespaces-BSRrBJIU.js +71 -0
  33. package/dist/prod/shared/owner-DBi3odT4.js +67 -0
  34. package/dist/prod/shared/render-context-DF8lr1uu.js +30 -0
  35. package/dist/prod/shared/render-effect-UFDi2Pfh.js +25 -0
  36. package/dist/prod/shared/resource-Ch5tVseZ.js +91 -0
  37. package/dist/prod/shared/signal-BDMlfa0Z.js +16 -0
  38. package/dist/prod/shared/store-CvW0DbmK.js +110 -0
  39. package/dist/prod/shared/unsafe-keys-C5PMlerl.js +7 -0
  40. package/dist/prod/static.js +48 -0
  41. package/dist/prod/svg.js +3 -2
  42. package/dist/prod/testing.js +144 -0
  43. package/dist/prod/vite.js +106 -0
  44. package/dist/types/api/cache.d.ts +16 -0
  45. package/dist/types/api/client.d.ts +42 -0
  46. package/dist/types/api/error.d.ts +16 -0
  47. package/dist/types/api/index.d.ts +3 -0
  48. package/dist/types/api/url.d.ts +5 -0
  49. package/dist/types/async/render-context.d.ts +10 -0
  50. package/dist/types/core/effect.d.ts +1 -0
  51. package/dist/types/core/graph.d.ts +11 -0
  52. package/dist/types/core/owner.d.ts +1 -0
  53. package/dist/types/core/unsafe-keys.d.ts +2 -0
  54. package/dist/types/dom/hooks.d.ts +4 -0
  55. package/dist/types/dom/types.d.ts +5 -0
  56. package/dist/types/forms/form.d.ts +55 -0
  57. package/dist/types/forms/index.d.ts +2 -0
  58. package/dist/types/forms/paths.d.ts +6 -0
  59. package/dist/types/forms/types.d.ts +38 -0
  60. package/dist/types/router/index.d.ts +1 -0
  61. package/dist/types/router/match.d.ts +1 -0
  62. package/dist/types/router/types.d.ts +1 -0
  63. package/dist/types/static/head.d.ts +36 -0
  64. package/dist/types/static/hydrate.d.ts +3 -0
  65. package/dist/types/static/index.d.ts +4 -0
  66. package/dist/types/static/island.d.ts +14 -0
  67. package/dist/types/static/json.d.ts +1 -0
  68. package/dist/types/static/render.d.ts +11 -0
  69. package/dist/types/static/server-dom.d.ts +100 -0
  70. package/dist/types/testing/index.d.ts +62 -0
  71. package/dist/types/vite/index.d.ts +24 -0
  72. package/package.json +46 -5
  73. package/dist/dev/shared/owner-DlUsXKXE.js +0 -122
  74. package/dist/prod/shared/element-DUtXb3px.js +0 -187
  75. package/dist/prod/shared/owner-DgJNPM0P.js +0 -104
@@ -0,0 +1,330 @@
1
+ import { t as computed } from "./shared/computed-DrF8O8b4.js";
2
+ import { S as untrack, i as batch } from "./shared/graph-SIvYLXSv.js";
3
+ import { t as signal } from "./shared/signal-B3xOKbVm.js";
4
+ import { n as store, r as unwrap } from "./shared/store-0vEg2bQV.js";
5
+ import { t as UNSAFE_KEYS } from "./shared/unsafe-keys-CB1P22No.js";
6
+ // src/forms/paths.ts
7
+ function getAt(source, path) {
8
+ if (path === "") return source;
9
+ let current = source;
10
+ for (const key of path.split(".")) {
11
+ if (current === null || typeof current !== "object") return void 0;
12
+ current = current[key];
13
+ }
14
+ return current;
15
+ }
16
+ function setAt(target, path, value) {
17
+ const keys = path.split(".");
18
+ if (keys.some((key) => UNSAFE_KEYS.has(key))) throw new Error(`[keits/forms] "${path}" is not a field path: "__proto__", "constructor" and "prototype" aren't allowed.`);
19
+ const last = keys.pop();
20
+ let current = target;
21
+ keys.forEach((key, i) => {
22
+ let next = current[key];
23
+ if (next === null || typeof next !== "object") {
24
+ next = /^\d+$/.test(keys[i + 1] ?? last) ? [] : {};
25
+ current[key] = next;
26
+ next = current[key];
27
+ }
28
+ current = next;
29
+ });
30
+ current[last] = value;
31
+ }
32
+ function deepEqual(a, b) {
33
+ if (Object.is(a, b)) return true;
34
+ if (a instanceof Date && b instanceof Date) return a.getTime() === b.getTime();
35
+ if (a === null || b === null || typeof a !== "object" || typeof b !== "object") return false;
36
+ if (Array.isArray(a) !== Array.isArray(b)) return false;
37
+ const keysA = Object.keys(a);
38
+ if (keysA.length !== Object.keys(b).length) return false;
39
+ return keysA.every((key) => deepEqual(a[key], b[key]));
40
+ }
41
+ function within(path, parent) {
42
+ return parent === "" || path === parent || path.startsWith(`${parent}.`);
43
+ }
44
+ function remapKeys(record, list, move) {
45
+ const result = {};
46
+ const prefix = `${list}.`;
47
+ for (const [key, value] of Object.entries(record)) {
48
+ if (!key.startsWith(prefix)) {
49
+ result[key] = value;
50
+ continue;
51
+ }
52
+ const rest = key.slice(prefix.length);
53
+ const dot = rest.indexOf(".");
54
+ const next = move(Number(dot < 0 ? rest : rest.slice(0, dot)));
55
+ if (next >= 0) result[`${prefix}${next}${dot < 0 ? "" : rest.slice(dot)}`] = value;
56
+ }
57
+ return result;
58
+ }
59
+ function serverErrors(body) {
60
+ const found = {};
61
+ const add = (path, message) => {
62
+ const text = Array.isArray(message) ? message.find((m) => typeof m === "string") : message;
63
+ if (typeof text === "string" && !(path in found)) found[path] = text;
64
+ };
65
+ const walk = (value, prefix) => {
66
+ for (const [key, inner] of Object.entries(value)) {
67
+ const path = prefix === "" ? key : `${prefix}.${key}`;
68
+ if (inner !== null && typeof inner === "object" && !Array.isArray(inner)) walk(inner, path);
69
+ else add(path, inner);
70
+ }
71
+ };
72
+ if (body === null || typeof body !== "object") return found;
73
+ const { errors, detail, message } = body;
74
+ if (Array.isArray(errors)) for (const item of errors) {
75
+ const path = item.path ?? item.field ?? item.name;
76
+ add(Array.isArray(path) ? path.join(".") : String(path ?? ""), item.message);
77
+ }
78
+ else if (errors !== null && typeof errors === "object") walk(errors, "");
79
+ if (Array.isArray(detail)) for (const item of detail) {
80
+ const loc = Array.isArray(item.loc) ? item.loc : [];
81
+ const start = loc[0] === "body" || loc[0] === "query" ? 1 : 0;
82
+ add(loc.slice(start).join("."), item.msg);
83
+ }
84
+ if (Object.keys(found).length === 0) add("", message);
85
+ return found;
86
+ }
87
+ // src/forms/form.ts
88
+ function form(options) {
89
+ const [values, setValues] = store(structuredClone(options.initial));
90
+ const [errors, setErrorStore] = store({});
91
+ const [server, setServer] = store({});
92
+ const [touchedPaths, setTouched] = store({});
93
+ const baseline = signal(structuredClone(options.initial), { equals: false });
94
+ const submitCount = signal(0);
95
+ const submitting = signal(false);
96
+ const validating = signal(false);
97
+ let checkId = 0;
98
+ const read = (value) => typeof value === "function" ? value() : value;
99
+ const snapshot = () => structuredClone(unwrap(values));
100
+ const runChecks = () => {
101
+ const current = snapshot();
102
+ const bySource = [
103
+ {},
104
+ {},
105
+ {}
106
+ ];
107
+ const result = {
108
+ errors: {},
109
+ output: void 0
110
+ };
111
+ const waiting = [];
112
+ const later = (value, use) => {
113
+ if (isPromiseLike(value)) waiting.push(value.then(use));
114
+ else use(value);
115
+ };
116
+ for (const [path, check] of Object.entries(options.fields ?? {})) later(check(getAt(current, path), current), (message) => {
117
+ if (message) bySource[0][path] = message;
118
+ });
119
+ if (options.validate) later(options.validate(current), (found) => {
120
+ for (const [path, message] of Object.entries(found ?? {})) if (typeof message === "string") bySource[1][path] = message;
121
+ });
122
+ if (options.schema) later(options.schema["~standard"].validate(current), (outcome) => {
123
+ if (outcome.issues === void 0) result.output = outcome.value;
124
+ else for (const issue of outcome.issues) {
125
+ const path = (issue.path ?? []).map((part) => String(typeof part === "object" ? part.key : part)).join(".");
126
+ bySource[2][path] ??= issue.message;
127
+ }
128
+ });
129
+ const finish = () => {
130
+ for (const source of bySource) for (const [path, message] of Object.entries(source)) result.errors[path] ??= message;
131
+ return result;
132
+ };
133
+ return waiting.length === 0 ? finish() : Promise.all(waiting).then(finish);
134
+ };
135
+ const check = () => {
136
+ const id = ++checkId;
137
+ const apply = (checked) => {
138
+ if (id !== checkId) return checked;
139
+ batch(() => {
140
+ replaceAll(setErrorStore, checked.errors);
141
+ validating.set(false);
142
+ });
143
+ return checked;
144
+ };
145
+ const outcome = runChecks();
146
+ if (!isPromiseLike(outcome)) return apply(outcome);
147
+ validating.set(true);
148
+ return outcome.then(apply);
149
+ };
150
+ const changed = (path) => {
151
+ setServer((draft) => {
152
+ for (const key of Object.keys(draft)) if (within(key, path) || within(path, key)) delete draft[key];
153
+ });
154
+ check();
155
+ };
156
+ const set = (path, value) => batch(() => {
157
+ setValues((draft) => setAt(draft, path, value));
158
+ changed(path);
159
+ });
160
+ const touch = (path) => setTouched((draft) => void (draft[path] = true));
161
+ const changeList = (path, change, move) => batch(() => {
162
+ setValues((draft) => {
163
+ if (!Array.isArray(getAt(draft, path))) setAt(draft, path, []);
164
+ change(getAt(draft, path));
165
+ });
166
+ setTouched((draft) => replaceKeys(draft, {
167
+ ...remapKeys(unwrap(draft), path, move),
168
+ [path]: true
169
+ }));
170
+ setServer((draft) => replaceKeys(draft, remapKeys(unwrap(draft), path, move)));
171
+ check();
172
+ });
173
+ const submitted = () => submitCount() > 0;
174
+ const shown = (path) => path === "" ? submitted() : touchedPaths[path] === true || submitted();
175
+ const valid = computed(() => Object.keys(errors).length === 0);
176
+ const dirtyAll = computed(() => !deepEqual(values, baseline()));
177
+ const result = {
178
+ values,
179
+ value: (path) => getAt(values, read(path)),
180
+ set: (path, value) => set(path, value),
181
+ update: (fn) => batch(() => {
182
+ setValues(fn);
183
+ changed("");
184
+ }),
185
+ bind(pathOrAccessor, bindOptions = {}) {
186
+ const path = () => read(pathOrAccessor);
187
+ const current = () => getAt(values, path());
188
+ const common = {
189
+ name: path,
190
+ onblur: () => touch(path()),
191
+ "aria-invalid": () => result.error(path()) ? "true" : void 0
192
+ };
193
+ const initial = untrack(current);
194
+ const choice = bindOptions.value;
195
+ if (choice !== void 0 && Array.isArray(initial)) return {
196
+ ...common,
197
+ type: "checkbox",
198
+ value: () => choice,
199
+ checked: () => current().includes(choice),
200
+ onchange: (event) => {
201
+ const list = untrack(current).filter((item) => item !== choice);
202
+ set(path(), event.currentTarget.checked ? [...list, choice] : list);
203
+ }
204
+ };
205
+ if (choice !== void 0) return {
206
+ ...common,
207
+ type: "radio",
208
+ value: () => choice,
209
+ checked: () => current() === choice,
210
+ onchange: () => set(path(), choice)
211
+ };
212
+ if (typeof initial === "boolean") return {
213
+ ...common,
214
+ type: "checkbox",
215
+ checked: () => current() === true,
216
+ onchange: (event) => set(path(), event.currentTarget.checked)
217
+ };
218
+ if (typeof initial === "number") return {
219
+ ...common,
220
+ value: () => {
221
+ const number = current();
222
+ return Number.isNaN(number) ? "" : String(number);
223
+ },
224
+ oninput: (event) => {
225
+ const text = event.currentTarget.value;
226
+ set(path(), text.trim() === "" ? NaN : Number(text));
227
+ }
228
+ };
229
+ return {
230
+ ...common,
231
+ value: () => String(current() ?? ""),
232
+ oninput: (event) => set(path(), event.currentTarget.value)
233
+ };
234
+ },
235
+ error(path = "") {
236
+ const key = read(path);
237
+ return (shown(key) ? errors[key] : void 0) ?? server[key];
238
+ },
239
+ touched: (path) => touchedPaths[read(path)] === true,
240
+ touch: (path) => touch(path),
241
+ dirty: (path) => path === void 0 ? dirtyAll() : !deepEqual(getAt(values, read(path)), getAt(baseline(), read(path))),
242
+ valid: () => valid(),
243
+ validating: () => validating(),
244
+ submitting: () => submitting(),
245
+ submitted,
246
+ array(path) {
247
+ return {
248
+ items: () => getAt(values, path) ?? [],
249
+ add: (item, at) => changeList(path, (list) => at === void 0 ? list.push(item) : list.splice(at, 0, item), (index) => at === void 0 || index < at ? index : index + 1),
250
+ remove: (index) => changeList(path, (list) => list.splice(index, 1), (i) => i === index ? -1 : i > index ? i - 1 : i),
251
+ move: (from, to) => changeList(path, (list) => list.splice(to, 0, ...list.splice(from, 1)), (i) => i === from ? to : from < to ? i > from && i <= to ? i - 1 : i : i >= to && i < from ? i + 1 : i)
252
+ };
253
+ },
254
+ setErrors(input) {
255
+ let found;
256
+ if (isHttpError(input)) {
257
+ if (input.status !== 400 && input.status !== 422) return false;
258
+ found = serverErrors(input.body);
259
+ } else {
260
+ found = {};
261
+ for (const [path, message] of Object.entries(input)) if (typeof message === "string") found[path] = message;
262
+ }
263
+ if (Object.keys(found).length === 0) return false;
264
+ setServer((draft) => replaceKeys(draft, found));
265
+ return true;
266
+ },
267
+ submit(handler) {
268
+ return async (event) => {
269
+ event?.preventDefault();
270
+ if (untrack(submitting)) return false;
271
+ const formElement = event?.currentTarget instanceof Element ? event.currentTarget : null;
272
+ const focusFirstError = () => formElement?.querySelector("[aria-invalid=\"true\"]")?.focus();
273
+ batch(() => {
274
+ submitCount.set(untrack(submitCount) + 1);
275
+ submitting.set(true);
276
+ setServer((draft) => replaceKeys(draft, {}));
277
+ });
278
+ try {
279
+ const sent = snapshot();
280
+ const checked = await check();
281
+ if (Object.keys(checked.errors).length > 0) {
282
+ focusFirstError();
283
+ return false;
284
+ }
285
+ await handler(options.schema ? checked.output : sent);
286
+ baseline.set(() => sent);
287
+ return true;
288
+ } catch (error) {
289
+ if (result.setErrors(error)) {
290
+ focusFirstError();
291
+ return false;
292
+ }
293
+ throw error;
294
+ } finally {
295
+ submitting.set(false);
296
+ }
297
+ };
298
+ },
299
+ reset(next) {
300
+ const start = structuredClone(next ?? untrack(baseline));
301
+ batch(() => {
302
+ setValues((draft) => replaceKeys(draft, structuredClone(start)));
303
+ baseline.set(() => start);
304
+ setTouched((draft) => replaceKeys(draft, {}));
305
+ setServer((draft) => replaceKeys(draft, {}));
306
+ submitCount.set(0);
307
+ check();
308
+ });
309
+ }
310
+ };
311
+ check();
312
+ return result;
313
+ }
314
+ function replaceKeys(draft, next) {
315
+ for (const key of Object.keys(draft)) if (!(key in next)) delete draft[key];
316
+ Object.assign(draft, next);
317
+ }
318
+ function replaceAll(setStore, next) {
319
+ setStore((draft) => {
320
+ for (const key of Object.keys(draft)) if (!(key in next)) delete draft[key];
321
+ for (const [key, message] of Object.entries(next)) if (draft[key] !== message) draft[key] = message;
322
+ });
323
+ }
324
+ function isHttpError(value) {
325
+ return value !== null && typeof value === "object" && typeof value.status === "number" && "body" in value;
326
+ }
327
+ function isPromiseLike(value) {
328
+ return typeof value?.then === "function";
329
+ }
330
+ export { form };