@vizejs/composable 0.803.0 → 0.805.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.
package/dist/use-form.mjs CHANGED
@@ -1,482 +1,3 @@
1
- import { tryOnScopeDispose } from "./scope.mjs";
2
- import { validateStandardSchema } from "./standard-schema.mjs";
3
- import { computed, ref, shallowRef, toRaw, triggerRef } from "vue";
4
- //#region src/use-form.ts
5
- function isContainer(value) {
6
- if (Array.isArray(value)) return true;
7
- if (typeof value !== "object" || value === null) return false;
8
- const prototype = Object.getPrototypeOf(value);
9
- return prototype === Object.prototype || prototype === null;
10
- }
11
- function splitPath(path) {
12
- return path === "" ? [] : path.split(".");
13
- }
14
- function readChild(container, key) {
15
- return Array.isArray(container) ? container[Number(key)] : container[key];
16
- }
17
- function writeChild(container, key, value) {
18
- if (Array.isArray(container)) container[Number(key)] = value;
19
- else container[key] = value;
20
- }
21
- /** Read a dotted path. */
22
- function readPath(root, path) {
23
- let current = root;
24
- for (const key of splitPath(path)) {
25
- if (!isContainer(current)) return void 0;
26
- current = readChild(current, key);
27
- }
28
- return current;
29
- }
30
- /** Write a dotted path, creating intermediate containers. */
31
- function writePath(root, path, value) {
32
- const keys = splitPath(path);
33
- const last = keys.at(-1);
34
- if (last === void 0 || !isContainer(root)) return;
35
- let current = root;
36
- for (let index = 0; index < keys.length - 1; index += 1) {
37
- const key = keys[index] ?? "";
38
- let next = readChild(current, key);
39
- if (!isContainer(next)) {
40
- next = /^\d+$/.test(keys[index + 1] ?? "") ? [] : {};
41
- writeChild(current, key, next);
42
- }
43
- if (!isContainer(next)) return;
44
- current = next;
45
- }
46
- writeChild(current, last, value);
47
- }
48
- function cloneValue(value) {
49
- return structuredClone(toRaw(value));
50
- }
51
- function deepEqual(left, right) {
52
- if (Object.is(left, right)) return true;
53
- if (left instanceof Date && right instanceof Date) return left.getTime() === right.getTime();
54
- if (Array.isArray(left) && Array.isArray(right)) return left.length === right.length && left.every((item, index) => deepEqual(item, right[index]));
55
- if (isContainer(left) && isContainer(right) && !Array.isArray(left) && !Array.isArray(right)) {
56
- const keys = new Set([...Object.keys(left), ...Object.keys(right)]);
57
- for (const key of keys) if (!deepEqual(left[key], right[key])) return false;
58
- return true;
59
- }
60
- return false;
61
- }
62
- function toMessages(result) {
63
- if (result === void 0 || result === null || result === "") return [];
64
- return typeof result === "string" ? [result] : result.filter((message) => message !== "");
65
- }
66
- function unknownMessages(result) {
67
- if (typeof result === "string") return result === "" ? [] : [result];
68
- if (!Array.isArray(result)) return [];
69
- return result.filter((message) => typeof message === "string" && message !== "");
70
- }
71
- /** Rewrite `${arrayPath}.${index}…` keys through an index mapping (undefined drops). */
72
- function remapKeys(entries, arrayPath, mapIndex) {
73
- const prefix = `${arrayPath}.`;
74
- const result = [];
75
- for (const [key, entry] of entries) {
76
- if (!key.startsWith(prefix)) {
77
- result.push([key, entry]);
78
- continue;
79
- }
80
- const rest = key.slice(prefix.length);
81
- const dot = rest.indexOf(".");
82
- const indexText = dot === -1 ? rest : rest.slice(0, dot);
83
- const mapped = /^\d+$/.test(indexText) ? mapIndex(Number(indexText)) : NaN;
84
- if (mapped === void 0) continue;
85
- if (Number.isNaN(mapped)) {
86
- result.push([key, entry]);
87
- continue;
88
- }
89
- result.push([`${prefix}${String(mapped)}${dot === -1 ? "" : rest.slice(dot)}`, entry]);
90
- }
91
- return result;
92
- }
93
- /**
94
- * Fully typed form state with validation, field arrays, and submission.
95
- *
96
- * The value type is inferred from `initialValues`; every path is a
97
- * template-literal key, so `field("address.city")` returns controls whose
98
- * `value` is typed as the city's type and misspelled paths do not compile.
99
- * Validation combines a Standard Schema v1 validator (Zod, Valibot, ArkType,
100
- * … via the `~standard` protocol), a whole-form validator, and per-field
101
- * validators; all may be asynchronous. A newer validation aborts older ones
102
- * through their `signal` and their results are discarded, so a slow check
103
- * can never overwrite fresher errors.
104
- *
105
- * This composable owns the *values*. `@vizejs/ui/form` owns accessible
106
- * error presentation (error summaries, focus management, native constraint
107
- * validation); feed {@link FormControls.errors} into it to render them.
108
- *
109
- * Server rendering: pure state, no host access; validation never runs
110
- * automatically during setup, so server and client render the same markup.
111
- * Pending validations are aborted when the owning scope stops.
112
- *
113
- * @example
114
- * ```ts
115
- * const form = useForm({
116
- * initialValues: { name: "", address: { city: "" }, tags: [] as string[] },
117
- * validators: { name: (name) => (name ? undefined : "Required") },
118
- * onSubmit: (values) => api.save(values),
119
- * });
120
- * const city = form.field("address.city"); // city.value: Ref<string>
121
- * const tags = form.fieldArray("tags");
122
- * tags.append("vue");
123
- * ```
124
- *
125
- * @typeParam Values Form values, inferred from `initialValues`.
126
- * @typeParam Output Submitted value, inferred from `schema` (defaults to `Values`).
127
- * @param options Initial values, validators, triggers, and submit handler.
128
- * @returns Form state and actions.
129
- */
130
- function useForm(options) {
131
- const createInitial = () => typeof options.initialValues === "function" ? options.initialValues() : cloneValue(options.initialValues);
132
- let initial = createInitial();
133
- const values = ref(cloneValue(initial));
134
- const errors = shallowRef({});
135
- const touched = shallowRef(/* @__PURE__ */ new Set());
136
- const pending = ref(/* @__PURE__ */ new Map());
137
- const submitting = ref(false);
138
- const submitCount = ref(0);
139
- const arrayKeys = /* @__PURE__ */ new Map();
140
- let nextKey = 0;
141
- let formController;
142
- const fieldControllers = /* @__PURE__ */ new Map();
143
- const validators = Object.entries(options.validators ?? {});
144
- const runValidator = (validator, path, snapshot, signal) => {
145
- if (typeof validator !== "function") return Promise.resolve([]);
146
- const outcome = Reflect.apply(validator, void 0, [readPath(snapshot, path), {
147
- values: snapshot,
148
- path,
149
- signal
150
- }]);
151
- return Promise.resolve(outcome).then(unknownMessages);
152
- };
153
- const trigger = () => submitCount.value > 0 ? options.revalidateOn ?? "change" : options.validateOn ?? "submit";
154
- const beginPending = (path) => {
155
- pending.value.set(path, (pending.value.get(path) ?? 0) + 1);
156
- };
157
- const endPending = (path) => {
158
- const count = (pending.value.get(path) ?? 1) - 1;
159
- if (count <= 0) pending.value.delete(path);
160
- else pending.value.set(path, count);
161
- };
162
- const setErrorsFor = (path, messages) => {
163
- const next = { ...errors.value };
164
- if (messages.length === 0) Reflect.deleteProperty(next, path);
165
- else next[path] = messages;
166
- errors.value = next;
167
- };
168
- const readFieldValidator = (path) => validators.find(([candidate]) => candidate === path)?.[1];
169
- /** Collect every error source; resolves to errors keyed by path. */
170
- const collectErrors = async (signal) => {
171
- const snapshot = values.value;
172
- const collected = {};
173
- const add = (path, messages) => {
174
- if (messages.length === 0) return;
175
- (collected[path] ??= []).push(...messages);
176
- };
177
- let output = snapshot;
178
- const tasks = [];
179
- if (options.schema) {
180
- const schema = options.schema;
181
- tasks.push(validateStandardSchema(schema, cloneValue(snapshot)).then((result) => {
182
- if (result.status === "valid") output = result.value;
183
- else for (const issue of result.issues) add(issue.path, [issue.message]);
184
- }));
185
- }
186
- if (options.validate) {
187
- const validate = options.validate;
188
- tasks.push(Promise.resolve(validate(snapshot, { signal })).then((result) => {
189
- if (!result) return;
190
- for (const [path, messages] of Object.entries(result)) if (messages !== void 0) add(path, toMessages(messages));
191
- }));
192
- }
193
- for (const [path, validator] of validators) tasks.push(runValidator(validator, path, snapshot, signal).then((messages) => add(path, messages)));
194
- await Promise.all(tasks);
195
- return {
196
- errors: collected,
197
- output
198
- };
199
- };
200
- const validate = async () => {
201
- formController?.abort(new DOMException("A newer validation started.", "AbortError"));
202
- for (const controller of fieldControllers.values()) controller.abort();
203
- fieldControllers.clear();
204
- const controller = new AbortController();
205
- formController = controller;
206
- beginPending("");
207
- try {
208
- const outcome = await collectErrors(controller.signal);
209
- if (controller.signal.aborted) return { status: "superseded" };
210
- errors.value = outcome.errors;
211
- if (Object.keys(outcome.errors).length > 0) return {
212
- status: "invalid",
213
- errors: { ...outcome.errors }
214
- };
215
- return {
216
- status: "valid",
217
- value: outcome.output
218
- };
219
- } finally {
220
- endPending("");
221
- if (formController === controller) formController = void 0;
222
- }
223
- };
224
- const schemaIssuesFor = async (path) => {
225
- if (!options.schema) return [];
226
- const result = await validateStandardSchema(options.schema, cloneValue(values.value));
227
- if (result.status === "valid") return [];
228
- return result.issues.filter((issue) => issue.path === path).map((issue) => issue.message);
229
- };
230
- const validateField = async (path) => {
231
- fieldControllers.get(path)?.abort();
232
- const controller = new AbortController();
233
- fieldControllers.set(path, controller);
234
- beginPending(path);
235
- try {
236
- const validator = readFieldValidator(path);
237
- const snapshot = values.value;
238
- const [own, fromSchema, fromForm] = await Promise.all([
239
- runValidator(validator, path, snapshot, controller.signal),
240
- schemaIssuesFor(path),
241
- options.validate ? Promise.resolve(options.validate(snapshot, { signal: controller.signal })).then((result) => {
242
- const messages = result ? Reflect.get(result, path) : void 0;
243
- return Array.isArray(messages) ? messages.filter((message) => typeof message === "string") : [];
244
- }) : Promise.resolve([])
245
- ]);
246
- if (controller.signal.aborted) return false;
247
- const messages = [
248
- ...fromSchema,
249
- ...fromForm,
250
- ...own
251
- ];
252
- setErrorsFor(path, messages);
253
- return messages.length === 0;
254
- } finally {
255
- endPending(path);
256
- if (fieldControllers.get(path) === controller) fieldControllers.delete(path);
257
- }
258
- };
259
- const touch = (path) => {
260
- if (touched.value.has(path)) return;
261
- const next = new Set(touched.value);
262
- next.add(path);
263
- touched.value = next;
264
- };
265
- const setValueAt = (path, value, setOptions = {}) => {
266
- writePath(values.value, path, value);
267
- if (setOptions.touch) touch(path);
268
- if (setOptions.validate ?? trigger() === "change") validateField(path);
269
- };
270
- const syncKeys = (path, length) => {
271
- let keys = arrayKeys.get(path);
272
- if (!keys) {
273
- keys = [];
274
- arrayKeys.set(path, keys);
275
- }
276
- while (keys.length < length) keys.push(nextKey++);
277
- if (keys.length > length) keys.length = length;
278
- return keys;
279
- };
280
- const readArray = (path) => {
281
- const current = readPath(values.value, path);
282
- if (Array.isArray(current)) return current;
283
- const created = [];
284
- writePath(values.value, path, created);
285
- return created;
286
- };
287
- const remapState = (path, mapIndex) => {
288
- errors.value = Object.fromEntries(remapKeys(Object.entries(errors.value), path, mapIndex));
289
- touched.value = new Set(remapKeys([...touched.value].map((key) => [key, true]), path, mapIndex).map(([key]) => key));
290
- };
291
- const keysVersion = shallowRef(0);
292
- const bumpKeys = () => {
293
- keysVersion.value += 1;
294
- triggerRef(keysVersion);
295
- };
296
- const field = (path) => {
297
- const key = path;
298
- const read = () => readPath(values.value, key);
299
- return {
300
- path,
301
- value: computed({
302
- get: read,
303
- set: (next) => setValueAt(key, next)
304
- }),
305
- errors: computed(() => errors.value[key] ?? []),
306
- error: computed(() => errors.value[key]?.[0]),
307
- dirty: computed(() => !deepEqual(readPath(values.value, key), readPath(initial, key))),
308
- touched: computed(() => touched.value.has(key)),
309
- validating: computed(() => pending.value.has(key) || pending.value.has("")),
310
- onBlur: () => {
311
- touch(key);
312
- if (trigger() === "blur") validateField(key);
313
- },
314
- validate: () => validateField(key),
315
- reset: () => {
316
- writePath(values.value, key, cloneValue(readPath(initial, key)));
317
- setErrorsFor(key, []);
318
- const next = new Set(touched.value);
319
- next.delete(key);
320
- touched.value = next;
321
- }
322
- };
323
- };
324
- const fieldArray = (path) => {
325
- const key = path;
326
- const afterChange = () => {
327
- bumpKeys();
328
- if (trigger() === "change") validateField(key);
329
- };
330
- const insertAt = (index, items) => {
331
- const array = readArray(key);
332
- const keys = syncKeys(key, array.length);
333
- const at = Math.max(0, Math.min(index, array.length));
334
- remapState(key, (old) => old >= at ? old + items.length : old);
335
- array.splice(at, 0, ...items);
336
- keys.splice(at, 0, ...items.map(() => nextKey++));
337
- afterChange();
338
- };
339
- return {
340
- entries: computed(() => {
341
- keysVersion.value;
342
- const array = readPath(values.value, key);
343
- if (!Array.isArray(array)) return [];
344
- const keys = syncKeys(key, array.length);
345
- return array.map((value, index) => ({
346
- key: keys[index] ?? index,
347
- index,
348
- path: `${path}.${index}`,
349
- value
350
- }));
351
- }),
352
- append: (...items) => insertAt(Number.MAX_SAFE_INTEGER, items),
353
- prepend: (...items) => insertAt(0, items),
354
- insert: (index, item) => insertAt(index, [item]),
355
- remove: (index) => {
356
- const array = readArray(key);
357
- if (index < 0 || index >= array.length) return;
358
- const keys = syncKeys(key, array.length);
359
- remapState(key, (old) => old === index ? void 0 : old > index ? old - 1 : old);
360
- array.splice(index, 1);
361
- keys.splice(index, 1);
362
- afterChange();
363
- },
364
- move: (from, to) => {
365
- const array = readArray(key);
366
- if (from < 0 || from >= array.length || to < 0 || to >= array.length || from === to) return;
367
- const keys = syncKeys(key, array.length);
368
- remapState(key, (old) => {
369
- if (old === from) return to;
370
- if (from < to && old > from && old <= to) return old - 1;
371
- if (from > to && old >= to && old < from) return old + 1;
372
- return old;
373
- });
374
- const [item] = array.splice(from, 1);
375
- array.splice(to, 0, item);
376
- const [movedKey] = keys.splice(from, 1);
377
- keys.splice(to, 0, movedKey ?? nextKey++);
378
- afterChange();
379
- },
380
- swap: (first, second) => {
381
- const array = readArray(key);
382
- if (first < 0 || second < 0 || first >= array.length || second >= array.length) return;
383
- const keys = syncKeys(key, array.length);
384
- remapState(key, (old) => old === first ? second : old === second ? first : old);
385
- const firstItem = array[first];
386
- array[first] = array[second];
387
- array[second] = firstItem;
388
- const firstKey = keys[first] ?? nextKey++;
389
- keys[first] = keys[second] ?? nextKey++;
390
- keys[second] = firstKey;
391
- afterChange();
392
- },
393
- replace: (items) => {
394
- remapState(key, () => void 0);
395
- writePath(values.value, key, [...items]);
396
- arrayKeys.delete(key);
397
- afterChange();
398
- }
399
- };
400
- };
401
- const clearErrors = (path) => {
402
- if (path === void 0) errors.value = {};
403
- else setErrorsFor(path, []);
404
- };
405
- const submitWith = async (handler) => {
406
- submitCount.value += 1;
407
- submitting.value = true;
408
- try {
409
- const result = await validate();
410
- const signal = formController?.signal ?? new AbortController().signal;
411
- if (result.status === "valid") {
412
- const onSubmit = handler ?? options.onSubmit;
413
- if (onSubmit) await onSubmit(result.value, { signal });
414
- } else if (result.status === "invalid") {
415
- const next = new Set(touched.value);
416
- for (const path of Object.keys(result.errors)) if (path !== "") next.add(path);
417
- touched.value = next;
418
- }
419
- return result;
420
- } finally {
421
- submitting.value = false;
422
- }
423
- };
424
- const reset = (next) => {
425
- formController?.abort();
426
- for (const controller of fieldControllers.values()) controller.abort();
427
- fieldControllers.clear();
428
- initial = next === void 0 ? createInitial() : cloneValue(next);
429
- values.value = cloneValue(initial);
430
- errors.value = {};
431
- touched.value = /* @__PURE__ */ new Set();
432
- pending.value.clear();
433
- submitCount.value = 0;
434
- arrayKeys.clear();
435
- bumpKeys();
436
- };
437
- tryOnScopeDispose(() => {
438
- formController?.abort();
439
- for (const controller of fieldControllers.values()) controller.abort();
440
- });
441
- return {
442
- values,
443
- errors,
444
- valid: computed(() => Object.keys(errors.value).length === 0),
445
- dirty: computed(() => !deepEqual(values.value, initial)),
446
- validating: computed(() => pending.value.size > 0),
447
- submitting,
448
- submitCount,
449
- field,
450
- fieldArray,
451
- getValue: (path) => readPath(values.value, path),
452
- setValue: (path, value, setOptions) => setValueAt(path, value, setOptions),
453
- setValues: (next, setOptions = {}) => {
454
- if (setOptions.merge) values.value = {
455
- ...values.value,
456
- ...cloneValue(next)
457
- };
458
- else values.value = {
459
- ...cloneValue(initial),
460
- ...cloneValue(next)
461
- };
462
- arrayKeys.clear();
463
- bumpKeys();
464
- },
465
- isTouched: (path) => touched.value.has(path),
466
- setErrors: (next) => {
467
- const normalized = {};
468
- for (const [path, messages] of Object.entries(next)) if (messages !== void 0 && messages.length > 0) normalized[path] = messages;
469
- errors.value = normalized;
470
- },
471
- clearErrors,
472
- validate,
473
- submit: submitWith,
474
- handleSubmit: (handler) => (event) => {
475
- event?.preventDefault();
476
- return submitWith(handler);
477
- },
478
- reset
479
- };
480
- }
481
- //#endregion
1
+ import "./standard-schema.mjs";
2
+ import { t as useForm } from "./use-form-C2JXZ0i7.mjs";
482
3
  export { useForm };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vizejs/composable",
3
- "version": "0.803.0",
3
+ "version": "0.805.0",
4
4
  "description": "Lifecycle-safe composable foundations for Vize applications",
5
5
  "keywords": [
6
6
  "composables",
@@ -978,7 +978,7 @@
978
978
  },
979
979
  "devDependencies": {
980
980
  "@types/node": "25.9.2",
981
- "@vizejs/native": "0.803.0",
981
+ "@vizejs/native": "0.805.0",
982
982
  "happy-dom": "21.0.4",
983
983
  "typescript": "6.0.3",
984
984
  "vite-plus": "0.1.24",
@@ -1,28 +1,47 @@
1
1
  import { effectScope } from "vue";
2
2
 
3
+ /** Options for {@link createGlobalState}. */
4
+ export interface CreateGlobalStateOptions {
5
+ /**
6
+ * Share one state across callers on the server too. Disabled by default
7
+ * because module-level sharing leaks state between requests; without a
8
+ * browser `window` every call then gets its own state.
9
+ *
10
+ * @default false
11
+ */
12
+ readonly shareOnServer?: boolean;
13
+ }
14
+
3
15
  /**
4
16
  * Lift a state factory into application-wide state shared by every caller.
5
17
  *
6
18
  * The factory runs once, lazily on the first call, inside a detached effect
7
19
  * scope so its watchers and computeds outlive any component; every later
8
- * call returns the same state. Because the state is module-level, it is
9
- * shared across all server requests: on the server, keep per-request state
10
- * in `provide`/`createInjectionState` instead, or reset it per request.
20
+ * call returns the same state. On the server every call runs the factory
21
+ * afresh in the caller's scope unless `shareOnServer` is set, so request
22
+ * state never leaks; keep per-request state in
23
+ * `provide`/`createInjectionState` instead.
11
24
  *
12
25
  * @example
13
26
  * ```ts
14
- * const useSession = createGlobalState(() => ({ user: shallowRef<User | null>(null) }));
15
- * useSession().user.value = currentUser;
27
+ * const useCommandPalette = createGlobalState(() => ({ open: shallowRef(false) }));
28
+ * useCommandPalette().open.value = true;
16
29
  * ```
17
30
  *
18
31
  * @param factory Creates the state; may use any composable.
32
+ * @param options Server sharing policy.
33
+ * @default options {}
19
34
  * @throws `Error` tagged `VIZE_COMPOSE_GLOBAL_STATE_INACTIVE_SCOPE` if the
20
35
  * private scope cannot run (never expected in practice).
21
36
  * @returns Accessor returning the shared state.
22
37
  */
23
- export function createGlobalState<State>(factory: () => State): () => State {
38
+ export function createGlobalState<State>(
39
+ factory: () => State,
40
+ options: CreateGlobalStateOptions = {},
41
+ ): () => State {
24
42
  let created: { readonly state: State } | undefined;
25
43
  return () => {
44
+ if (typeof window === "undefined" && !(options.shareOnServer ?? false)) return factory();
26
45
  if (created === undefined) {
27
46
  created = effectScope(true).run(() => ({ state: factory() }));
28
47
  if (created === undefined) {
@@ -0,0 +1,71 @@
1
+ /**
2
+ * Dotted-path access into form values.
3
+ *
4
+ * `useForm` addresses every field by a dotted path (`"address.city"`,
5
+ * `"tags.0"`). Paths only walk plain objects and arrays, and a segment that
6
+ * names the prototype chain makes the whole path unreadable and unwritable,
7
+ * so a field path can never reach or pollute `Object.prototype`.
8
+ */
9
+
10
+ type Container = Record<string, unknown> | unknown[];
11
+
12
+ /** Whether a value is a plain object or an array that a path may descend into. */
13
+ export function isContainer(value: unknown): value is Container {
14
+ if (Array.isArray(value)) return true;
15
+ if (typeof value !== "object" || value === null) return false;
16
+ const prototype: unknown = Object.getPrototypeOf(value);
17
+ return prototype === Object.prototype || prototype === null;
18
+ }
19
+
20
+ /** Keys that reach an object's prototype chain instead of its own data. */
21
+ const prototypeKeys: ReadonlySet<string> = new Set(["__proto__", "constructor", "prototype"]);
22
+
23
+ /** Split a dotted path; undefined when a segment names the prototype chain. */
24
+ function splitPath(path: string): readonly string[] | undefined {
25
+ if (path === "") return [];
26
+ const keys = path.split(".");
27
+ return keys.some((key) => prototypeKeys.has(key)) ? undefined : keys;
28
+ }
29
+
30
+ function readChild(container: Container, key: string): unknown {
31
+ if (Array.isArray(container)) return container[Number(key)];
32
+ // Read first so a reactive container tracks the key even while it is absent.
33
+ const value = container[key];
34
+ return Object.hasOwn(container, key) ? value : undefined;
35
+ }
36
+
37
+ function writeChild(container: Container, key: string, value: unknown): void {
38
+ if (Array.isArray(container)) container[Number(key)] = value;
39
+ else container[key] = value;
40
+ }
41
+
42
+ /** Read a dotted path. */
43
+ export function readPath(root: unknown, path: string): unknown {
44
+ const keys = splitPath(path);
45
+ if (keys === undefined) return undefined;
46
+ let current = root;
47
+ for (const key of keys) {
48
+ if (!isContainer(current)) return undefined;
49
+ current = readChild(current, key);
50
+ }
51
+ return current;
52
+ }
53
+
54
+ /** Write a dotted path, creating intermediate containers. */
55
+ export function writePath(root: unknown, path: string, value: unknown): void {
56
+ const keys = splitPath(path);
57
+ const last = keys?.at(-1);
58
+ if (keys === undefined || last === undefined || !isContainer(root)) return;
59
+ let current: Container = root;
60
+ for (let index = 0; index < keys.length - 1; index += 1) {
61
+ const key = keys[index] ?? "";
62
+ let next = readChild(current, key);
63
+ if (!isContainer(next)) {
64
+ next = /^\d+$/.test(keys[index + 1] ?? "") ? [] : {};
65
+ writeChild(current, key, next);
66
+ }
67
+ if (!isContainer(next)) return;
68
+ current = next;
69
+ }
70
+ writeChild(current, last, value);
71
+ }