@niscorp/solid 0.1.2 → 0.2.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/index.cjs CHANGED
@@ -66,7 +66,8 @@ var deriveFromType = (schema) => {
66
66
  // src/incremental-parser.ts
67
67
  var createIncrementalParser = (base, opts = {}) => {
68
68
  const valueOpenHook = opts.valueOpenHook;
69
- const root = structuredClone(base);
69
+ let root = structuredClone(base);
70
+ let isRootNew = false;
70
71
  const containerStack = [];
71
72
  const containerTypeStack = [];
72
73
  const arrayIndexStack = [];
@@ -127,6 +128,11 @@ var createIncrementalParser = (base, opts = {}) => {
127
128
  };
128
129
  const enterContainer = (type) => {
129
130
  if (containerStack.length === 0) {
131
+ if (!isContainer(root)) {
132
+ root = type === "object" ? {} : [];
133
+ isRootNew = true;
134
+ isDirty = true;
135
+ }
130
136
  containerStack.push(root);
131
137
  containerTypeStack.push(type);
132
138
  return;
@@ -157,9 +163,9 @@ var createIncrementalParser = (base, opts = {}) => {
157
163
  }
158
164
  containerTypeStack.push(type);
159
165
  };
160
- const checkValueOpen = (path, kind) => {
166
+ const checkValueOpen = (kind) => {
161
167
  if (!valueOpenHook) return true;
162
- const decision = valueOpenHook(path, kind);
168
+ const decision = valueOpenHook([...pathStack], kind);
163
169
  if (decision === "accept") return true;
164
170
  return false;
165
171
  };
@@ -310,7 +316,7 @@ var createIncrementalParser = (base, opts = {}) => {
310
316
  hasUnpoppedValue = true;
311
317
  }
312
318
  const path = currentPath();
313
- if (!isRoot && !checkValueOpen(path, "object")) {
319
+ if ((!isRoot || !isContainer(root)) && !checkValueOpen("object")) {
314
320
  enterSkipObject();
315
321
  afterColon = false;
316
322
  expectingValue = false;
@@ -348,7 +354,7 @@ var createIncrementalParser = (base, opts = {}) => {
348
354
  hasUnpoppedValue = true;
349
355
  }
350
356
  const arrPath = currentPath();
351
- if (!isRootArr && !checkValueOpen(arrPath, "array")) {
357
+ if ((!isRootArr || !isContainer(root)) && !checkValueOpen("array")) {
352
358
  enterSkipArray();
353
359
  afterColon = false;
354
360
  expectingValue = false;
@@ -393,7 +399,7 @@ var createIncrementalParser = (base, opts = {}) => {
393
399
  expectingValue = false;
394
400
  hasUnpoppedValue = true;
395
401
  }
396
- if (!checkValueOpen(currentPath(), "string")) {
402
+ if (!checkValueOpen("string")) {
397
403
  enterSkipString();
398
404
  break;
399
405
  }
@@ -440,7 +446,7 @@ var createIncrementalParser = (base, opts = {}) => {
440
446
  hasUnpoppedValue = true;
441
447
  }
442
448
  const litKind = literalKindFromChar(ch);
443
- if (!checkValueOpen(currentPath(), litKind)) {
449
+ if (!checkValueOpen(litKind)) {
444
450
  enterSkipLiteral();
445
451
  expectingValue = false;
446
452
  break;
@@ -462,7 +468,8 @@ var createIncrementalParser = (base, opts = {}) => {
462
468
  };
463
469
  const snapshot = (previous) => {
464
470
  if (!isDirty) return { changed: false };
465
- const value = shareStructure(root, previous, "");
471
+ const value = isRootNew ? detachValue(root) : shareStructure(root, previous, "");
472
+ isRootNew = false;
466
473
  dirtyParents.clear();
467
474
  isDirty = false;
468
475
  return { changed: true, value };
@@ -479,15 +486,13 @@ var createIncrementalParser = (base, opts = {}) => {
479
486
  if (!dirtyKeys) return previous;
480
487
  if (Array.isArray(source)) {
481
488
  const prevArr = Array.isArray(previous) ? previous : [];
482
- const result = new Array(source.length);
483
- for (let i = 0; i < source.length; i++) {
484
- const key = String(i);
485
- if (dirtyKeys.has(key)) {
486
- const childPath = path === "" ? key : `${path}.${key}`;
487
- result[i] = dirtyParents.has(childPath) ? shareStructure(source[i], prevArr[i], childPath) : detachValue(source[i]);
488
- } else {
489
- result[i] = i < prevArr.length ? prevArr[i] : source[i];
490
- }
489
+ const result = prevArr.slice(0, source.length);
490
+ for (let i = result.length; i < source.length; i++) result.push(source[i]);
491
+ for (const key of dirtyKeys) {
492
+ const i = Number(key);
493
+ if (!Number.isInteger(i) || i < 0 || i >= source.length || String(i) !== key) continue;
494
+ const childPath = path === "" ? key : `${path}.${key}`;
495
+ result[i] = dirtyParents.has(childPath) ? shareStructure(source[i], prevArr[i], childPath) : detachValue(source[i]);
491
496
  }
492
497
  return result;
493
498
  }
@@ -509,6 +514,7 @@ var createIncrementalParser = (base, opts = {}) => {
509
514
  };
510
515
  return { write, snapshot };
511
516
  };
517
+ var isContainer = (value) => typeof value === "object" && value !== null;
512
518
  var unescapeChar = (ch) => {
513
519
  switch (ch) {
514
520
  case '"':
@@ -532,10 +538,12 @@ var unescapeChar = (ch) => {
532
538
  }
533
539
  };
534
540
  var isLiteralChar = (ch) => ch >= "0" && ch <= "9" || ch === "." || ch === "-" || ch === "+" || ch === "e" || ch === "E" || ch >= "a" && ch <= "z";
541
+ var JSON_NUMBER_SO_FAR = /^-?$|^-?(0|[1-9][0-9]*)(\.[0-9]*)?([eE][+-]?[0-9]*)?$/;
535
542
  var parseLiteral = (buf) => {
536
543
  if (buf === "true") return { ok: true, value: true };
537
544
  if (buf === "false") return { ok: true, value: false };
538
545
  if (buf === "null") return { ok: true, value: null };
546
+ if (!JSON_NUMBER_SO_FAR.test(buf)) return { ok: false };
539
547
  const num = Number(buf);
540
548
  if (!Number.isNaN(num)) return { ok: true, value: num };
541
549
  return { ok: false };
@@ -550,72 +558,50 @@ var literalKindFromChar = (ch) => {
550
558
  var createFinalizationTracker = () => {
551
559
  const finalized = /* @__PURE__ */ new Set();
552
560
  let isRootFinal = false;
553
- const keysPerContainer = /* @__PURE__ */ new Map();
554
- const finalizePath = (path) => {
555
- if (finalized.has(path)) return;
556
- finalized.add(path);
557
- };
558
- const finalizePreviousSiblings = (containerPath, newKey) => {
559
- const keys = keysPerContainer.get(containerPath);
560
- if (!keys) return;
561
- for (const key of keys) {
562
- if (key === newKey) break;
563
- const siblingPath = containerPath === "" ? key : `${containerPath}.${key}`;
564
- finalizePath(siblingPath);
565
- finalizeDescendants(siblingPath);
561
+ let openContainers = 0;
562
+ const containers = /* @__PURE__ */ new Map();
563
+ const childPathOf2 = (containerPath, key) => containerPath === "" ? key : `${containerPath}.${key}`;
564
+ const settle = (containerPath) => {
565
+ const container = containers.get(containerPath);
566
+ if (!container) return;
567
+ const { keys } = container;
568
+ for (let index = container.settled; index < keys.length; index += 1) {
569
+ const key = keys[index];
570
+ if (key === void 0) continue;
571
+ finalized.add(childPathOf2(containerPath, key));
566
572
  }
573
+ container.settled = keys.length;
567
574
  };
568
- const finalizeDescendants = (path) => {
569
- const prefix = path + ".";
570
- for (const [containerPath, keys] of keysPerContainer) {
571
- if (containerPath === path || containerPath.startsWith(prefix)) {
572
- for (const key of keys) {
573
- const childPath = containerPath === "" ? key : `${containerPath}.${key}`;
574
- finalizePath(childPath);
575
- }
576
- }
577
- }
575
+ const enterChild = (containerPath, key) => {
576
+ const container = containers.get(containerPath);
577
+ if (!container) return;
578
+ if (container.indexOf.has(key)) return;
579
+ settle(containerPath);
580
+ container.indexOf.set(key, container.keys.length);
581
+ container.keys.push(key);
578
582
  };
579
583
  const process = (events) => {
580
584
  for (const event of events) {
581
585
  switch (event.type) {
582
586
  case "enterObject":
583
587
  case "enterArray": {
584
- if (!keysPerContainer.has(event.path)) {
585
- keysPerContainer.set(event.path, []);
588
+ openContainers += 1;
589
+ if (!containers.has(event.path)) {
590
+ containers.set(event.path, { keys: [], indexOf: /* @__PURE__ */ new Map(), settled: 0 });
586
591
  }
587
592
  break;
588
593
  }
589
- case "enterKey": {
590
- const keys = keysPerContainer.get(event.path);
591
- if (keys && !keys.includes(event.key)) {
592
- finalizePreviousSiblings(event.path, event.key);
593
- keys.push(event.key);
594
- }
594
+ case "enterKey":
595
+ enterChild(event.path, event.key);
595
596
  break;
596
- }
597
- case "enterIndex": {
598
- const keys = keysPerContainer.get(event.path);
599
- const indexStr = String(event.index);
600
- if (keys && !keys.includes(indexStr)) {
601
- finalizePreviousSiblings(event.path, indexStr);
602
- keys.push(indexStr);
603
- }
597
+ case "enterIndex":
598
+ enterChild(event.path, String(event.index));
604
599
  break;
605
- }
606
600
  case "leaveObject":
607
601
  case "leaveArray": {
608
- const keys = keysPerContainer.get(event.path);
609
- if (keys) {
610
- for (const key of keys) {
611
- const childPath = event.path === "" ? key : `${event.path}.${key}`;
612
- finalizePath(childPath);
613
- finalizeDescendants(childPath);
614
- }
615
- }
616
- if (event.path === "") {
617
- isRootFinal = true;
618
- }
602
+ settle(event.path);
603
+ openContainers -= 1;
604
+ if (openContainers === 0) isRootFinal = true;
619
605
  break;
620
606
  }
621
607
  }
@@ -625,7 +611,8 @@ var createFinalizationTracker = () => {
625
611
  process,
626
612
  isFinal: (path) => finalized.has(path) || isRootFinal,
627
613
  isRootFinal: () => isRootFinal,
628
- getContainerKeys: (path) => keysPerContainer.get(path)
614
+ getContainerKeys: (path) => containers.get(path)?.keys,
615
+ getChildIndex: (path, key) => containers.get(path)?.indexOf.get(key)
629
616
  };
630
617
  };
631
618
 
@@ -671,12 +658,12 @@ var createSelectedStream = (deps) => {
671
658
  const notifyListeners = (value) => {
672
659
  isNotifying = true;
673
660
  for (const listener of listeners) {
674
- listener(value);
661
+ deps.deliver(() => listener(value));
675
662
  }
676
663
  isNotifying = false;
677
664
  while (pendingImmediateFires.length > 0) {
678
665
  const fire = pendingImmediateFires.shift();
679
- if (fire) fire();
666
+ if (fire) deps.deliver(fire);
680
667
  }
681
668
  };
682
669
  const resolveFinal = (value) => {
@@ -685,10 +672,16 @@ var createSelectedStream = (deps) => {
685
672
  finalState = { resolved: true, value };
686
673
  resolve(value);
687
674
  for (const listener of finalListeners) {
688
- listener(value);
675
+ deps.deliver(() => listener(value));
689
676
  }
690
677
  finalListeners.clear();
691
678
  };
679
+ const rejectFinal = (error) => {
680
+ if (finalState.resolved) return;
681
+ finalState.promise.catch(() => {
682
+ });
683
+ finalState.reject(error);
684
+ };
692
685
  const unsubChange = deps.onRootChange(() => {
693
686
  if (isDestroyed) return;
694
687
  const projected = project();
@@ -709,11 +702,17 @@ var createSelectedStream = (deps) => {
709
702
  const unsubError = deps.onRootError((err) => {
710
703
  if (isDestroyed) return;
711
704
  if (!coversPath(err.path, deps.path)) return;
712
- for (const listener of errorListeners) listener(err);
705
+ for (const listener of errorListeners) deps.deliver(() => listener(err));
713
706
  });
707
+ const unsubFail = deps.onRootFail(rejectFinal);
714
708
  const current = () => project();
715
709
  const final = () => {
716
710
  if (finalState.resolved) return Promise.resolve(finalState.value);
711
+ const failure = deps.failure();
712
+ if (failure && !deps.hasRootFinalized()) {
713
+ rejectFinal(failure);
714
+ return Promise.reject(failure);
715
+ }
717
716
  if (deps.isPathFinal() || deps.isTerminal()) {
718
717
  const value = project();
719
718
  resolveFinal(value);
@@ -765,6 +764,7 @@ var createSelectedStream = (deps) => {
765
764
  unsubChange();
766
765
  unsubFinalize();
767
766
  unsubError();
767
+ unsubFail();
768
768
  listeners.clear();
769
769
  finalListeners.clear();
770
770
  errorListeners.clear();
@@ -804,17 +804,45 @@ var createDeadStream = () => ({
804
804
  },
805
805
  select: () => createDeadStream()
806
806
  });
807
+ var ANY_INFO = { acceptedKinds: "any", subSchema: null };
807
808
  var walkSchema = (root, segments) => {
808
- let current = root;
809
+ let current = [root];
809
810
  for (const segment of segments) {
810
- if (!current) return null;
811
- current = stepInto(current, segment);
811
+ const next = current.flatMap((schema) => stepInto(schema, segment));
812
+ if (next.length === 0) {
813
+ return current.some((schema) => inspectSchema(enter(schema)).acceptedKinds === "any") ? ANY_INFO : null;
814
+ }
815
+ current = next;
812
816
  }
813
- if (!current) return null;
814
- return inspectSchema(current);
817
+ const [first, ...others] = current;
818
+ if (first === void 0) return null;
819
+ if (others.length === 0) return inspectSchema(first);
820
+ const kinds = /* @__PURE__ */ new Set();
821
+ for (const info of current.map(inspectSchema)) {
822
+ if (info.acceptedKinds === "any") return { acceptedKinds: "any", subSchema: first, alternatives: current };
823
+ for (const kind of info.acceptedKinds) kinds.add(kind);
824
+ }
825
+ return { acceptedKinds: kinds, subSchema: first, alternatives: current };
826
+ };
827
+ var enter = (schema) => {
828
+ let s = unwrap(schema);
829
+ for (let i = 0; i < 32; i++) {
830
+ if (s instanceof zod.z.ZodLazy) s = unwrap(s.unwrap());
831
+ else if (s instanceof zod.z.ZodPipe) s = unwrap(s._zod.def.in);
832
+ else return s;
833
+ }
834
+ return s;
815
835
  };
816
836
  var stepInto = (schema, segment) => {
817
- const s = unwrap(schema);
837
+ const s = enter(schema);
838
+ if (s instanceof zod.z.ZodUnion) {
839
+ const options = s._zod.def.options ?? [];
840
+ return options.flatMap((option) => stepInto(option, segment));
841
+ }
842
+ const next = stepIntoMember(s, segment);
843
+ return next ? [next] : [];
844
+ };
845
+ var stepIntoMember = (s, segment) => {
818
846
  if (s instanceof zod.z.ZodObject) {
819
847
  const shape = s.shape;
820
848
  return shape[segment] ?? null;
@@ -834,22 +862,6 @@ var stepInto = (schema, segment) => {
834
862
  if (s instanceof zod.z.ZodRecord) {
835
863
  return s._zod.def.valueType ?? null;
836
864
  }
837
- if (s instanceof zod.z.ZodUnion) {
838
- const options = s._zod.def.options ?? [];
839
- for (const opt of options) {
840
- const next = stepInto(opt, segment);
841
- if (next) return next;
842
- }
843
- return null;
844
- }
845
- if (isDiscriminatedUnion(s)) {
846
- const options = getDiscriminatedUnionOptions(s);
847
- for (const opt of options) {
848
- const next = stepInto(opt, segment);
849
- if (next) return next;
850
- }
851
- return null;
852
- }
853
865
  return null;
854
866
  };
855
867
  var inspectSchema = (schema) => {
@@ -859,7 +871,7 @@ var inspectSchema = (schema) => {
859
871
  if (nullable) kinds.add("null");
860
872
  return kinds;
861
873
  };
862
- if (s instanceof zod.z.ZodString) return { acceptedKinds: withNull(/* @__PURE__ */ new Set(["string"])), subSchema: schema };
874
+ if (s instanceof zod.z.ZodString || s._zod.def.type === "string") return { acceptedKinds: withNull(/* @__PURE__ */ new Set(["string"])), subSchema: schema };
863
875
  if (s instanceof zod.z.ZodNumber) return { acceptedKinds: withNull(/* @__PURE__ */ new Set(["number"])), subSchema: schema };
864
876
  if (s instanceof zod.z.ZodBoolean) return { acceptedKinds: withNull(/* @__PURE__ */ new Set(["boolean"])), subSchema: schema };
865
877
  if (s instanceof zod.z.ZodNull) return { acceptedKinds: /* @__PURE__ */ new Set(["null"]), subSchema: schema };
@@ -910,7 +922,6 @@ var isDiscriminatedUnion = (schema) => {
910
922
  const def = schema._zod?.def;
911
923
  return def?.type === "discriminatedUnion" || def?.type === "discriminated_union";
912
924
  };
913
- var getDiscriminatedUnionOptions = (schema) => schema._zod.def.options ?? [];
914
925
  var literalToKind = (v) => {
915
926
  if (v === null) return "null";
916
927
  switch (typeof v) {
@@ -942,15 +953,49 @@ var allowsNull = (schema) => {
942
953
  }
943
954
  return false;
944
955
  };
956
+ var kindOf = (value) => {
957
+ if (value === null) return "null";
958
+ if (Array.isArray(value)) return "array";
959
+ const type = typeof value;
960
+ return type === "string" || type === "number" || type === "boolean" ? type : "object";
961
+ };
962
+ var takesLiteral = (schema, value) => {
963
+ const s = enter(schema);
964
+ if (s instanceof zod.z.ZodLiteral) return [...s._zod.def.values ?? []].includes(value);
965
+ if (s instanceof zod.z.ZodEnum) return Object.values(s._zod.def.entries).some((entry) => entry === value);
966
+ return true;
967
+ };
968
+ var fitsShape = (root, value, segments = []) => {
969
+ if (value === void 0) return true;
970
+ const info = walkSchema(root, segments);
971
+ if (!info) return false;
972
+ if (info.acceptedKinds !== "any" && !info.acceptedKinds.has(kindOf(value))) return false;
973
+ if (value !== null && info.subSchema) {
974
+ const candidates = info.alternatives ?? [info.subSchema];
975
+ if (!candidates.some((candidate) => takesLiteral(candidate, value))) return false;
976
+ }
977
+ if (typeof value !== "object" || value === null) return true;
978
+ return Object.entries(value).every(([key, child]) => fitsShape(root, child, [...segments, key]));
979
+ };
980
+ var unionVariantsOf = (info) => {
981
+ const variants = (info.alternatives ?? (info.subSchema ? [info.subSchema] : [])).flatMap((schema) => {
982
+ const s = enter(schema);
983
+ return s instanceof zod.z.ZodUnion ? s._zod.def.options ?? [] : [s];
984
+ });
985
+ return variants.length > 1 ? variants : void 0;
986
+ };
945
987
 
946
988
  // src/validator.ts
989
+ var childPathOf = (containerPath, key) => containerPath === "" ? key : `${containerPath}.${key}`;
947
990
  var createValidator = (deps) => {
948
991
  let failed = false;
949
992
  const finalizeChecked = /* @__PURE__ */ new Set();
950
- const valueOpen = (path, kind) => {
993
+ const containerSegments = /* @__PURE__ */ new Map([["", []]]);
994
+ const checkedUpTo = /* @__PURE__ */ new Map();
995
+ const valueOpen = (segments, kind) => {
951
996
  if (deps.mode === "trust") return "accept";
952
997
  if (failed) return "skip";
953
- const segments = splitPath(path);
998
+ const path = segments.join(".");
954
999
  const info = walkSchema(deps.schema, segments);
955
1000
  if (!info) {
956
1001
  reportValueOpen(path, "<unknown path>", kind, deps);
@@ -968,17 +1013,19 @@ var createValidator = (deps) => {
968
1013
  }
969
1014
  return "skip";
970
1015
  }
1016
+ if (kind === "object" || kind === "array") containerSegments.set(path, segments);
971
1017
  return "accept";
972
1018
  };
973
- const finalizeField = (path, getRoot) => {
1019
+ const segmentsOf = (containerPath) => containerSegments.get(containerPath) ?? splitPath(containerPath);
1020
+ const finalizeField = (path, segments, getRoot) => {
974
1021
  if (failed) return;
975
1022
  if (finalizeChecked.has(path)) return;
976
1023
  finalizeChecked.add(path);
977
- const segments = splitPath(path);
978
1024
  const info = walkSchema(deps.schema, segments);
979
1025
  if (!info || !info.subSchema) return;
980
1026
  const value = getByPath(getRoot(), segments);
981
1027
  if (value === void 0) return;
1028
+ if (info.alternatives?.some((alternative) => alternative.safeParse(value).success)) return;
982
1029
  const result = info.subSchema.safeParse(value);
983
1030
  if (result.success) return;
984
1031
  const issue = result.error.issues[0];
@@ -996,27 +1043,56 @@ var createValidator = (deps) => {
996
1043
  };
997
1044
  const finalizeSiblingsBefore = (containerPath, newKey, getRoot) => {
998
1045
  const keys = deps.getContainerKeys(containerPath);
999
- if (!keys) return;
1000
- for (const key of keys) {
1001
- if (key === newKey) break;
1002
- const childPath = containerPath === "" ? key : `${containerPath}.${key}`;
1003
- finalizeField(childPath, getRoot);
1046
+ const end = deps.getChildIndex(containerPath, newKey);
1047
+ if (!keys || end === void 0) return;
1048
+ const start = checkedUpTo.get(containerPath) ?? 0;
1049
+ const base = segmentsOf(containerPath);
1050
+ for (let index = start; index < end; index += 1) {
1051
+ const key = keys[index];
1052
+ if (key === void 0) continue;
1053
+ finalizeField(childPathOf(containerPath, key), [...base, key], getRoot);
1004
1054
  if (failed) return;
1005
1055
  }
1056
+ checkedUpTo.set(containerPath, Math.max(start, end));
1006
1057
  };
1007
1058
  const finalizeAllChildren = (containerPath, getRoot) => {
1008
1059
  const keys = deps.getContainerKeys(containerPath);
1009
1060
  if (!keys) return;
1061
+ const base = segmentsOf(containerPath);
1010
1062
  for (const key of keys) {
1011
- const childPath = containerPath === "" ? key : `${containerPath}.${key}`;
1012
- finalizeField(childPath, getRoot);
1063
+ finalizeField(childPathOf(containerPath, key), [...base, key], getRoot);
1013
1064
  if (failed) return;
1014
1065
  }
1015
- finalizeField(containerPath, getRoot);
1066
+ finalizeField(containerPath, base, getRoot);
1067
+ };
1068
+ const checkUnionAtClose = (containerPath, getRoot) => {
1069
+ const segments = segmentsOf(containerPath);
1070
+ const info = walkSchema(deps.schema, segments);
1071
+ const variants = info ? unionVariantsOf(info) : void 0;
1072
+ if (!variants) return;
1073
+ const value = getByPath(getRoot(), segments);
1074
+ if (value === void 0 || variants.some((variant) => fitsShape(variant, value))) return;
1075
+ deps.emitError({
1076
+ path: containerPath,
1077
+ expected: "a variant of the union",
1078
+ received: describeValue(value),
1079
+ phase: "finalize",
1080
+ message: `[solid] ${containerPath || "<root>"}: matches no variant of the union`
1081
+ });
1082
+ if (deps.mode === "strict") {
1083
+ failed = true;
1084
+ deps.onFailed();
1085
+ }
1016
1086
  };
1017
1087
  const processEvents = (events, getRoot) => {
1018
1088
  if (deps.mode === "trust") return;
1019
- if (deps.constraints !== "finalize") return;
1089
+ if (deps.constraints !== "finalize") {
1090
+ for (const ev of events) {
1091
+ if (ev.type === "leaveObject" || ev.type === "leaveArray") checkUnionAtClose(ev.path, getRoot);
1092
+ if (failed) return;
1093
+ }
1094
+ return;
1095
+ }
1020
1096
  for (const ev of events) {
1021
1097
  switch (ev.type) {
1022
1098
  case "enterKey":
@@ -1061,9 +1137,10 @@ var describeValue = (value) => {
1061
1137
 
1062
1138
  // src/create-stream.ts
1063
1139
  var createStream = (options) => {
1064
- const base = resolveBase(options);
1140
+ const { base, isBaseValid } = resolveBase(options);
1065
1141
  const mode = options.mode ?? "recover";
1066
1142
  const constraints = options.constraints ?? "kind";
1143
+ const isFinalChecked = mode === "strict" && !isBaseValid;
1067
1144
  let currentValue = structuredClone(base);
1068
1145
  let isClosed = false;
1069
1146
  let isDestroyed = false;
@@ -1076,12 +1153,36 @@ var createStream = (options) => {
1076
1153
  const changeSubscribers = /* @__PURE__ */ new Set();
1077
1154
  const finalizeSubscribers = /* @__PURE__ */ new Set();
1078
1155
  const errorSubscribers = /* @__PURE__ */ new Set();
1156
+ const failSubscribers = /* @__PURE__ */ new Set();
1079
1157
  let finalState = createPendingFinal();
1080
1158
  const selectedStreams = /* @__PURE__ */ new Map();
1081
1159
  let isNotifying = false;
1082
1160
  const pendingImmediateFires = [];
1161
+ let thrownByListeners;
1162
+ const deliver = (call) => {
1163
+ if (thrownByListeners === void 0) {
1164
+ call();
1165
+ return;
1166
+ }
1167
+ try {
1168
+ call();
1169
+ } catch (error) {
1170
+ thrownByListeners.push(error);
1171
+ }
1172
+ };
1173
+ const throwingAfter = (operation) => {
1174
+ const outer = thrownByListeners;
1175
+ const thrown = [];
1176
+ thrownByListeners = thrown;
1177
+ try {
1178
+ operation();
1179
+ } finally {
1180
+ thrownByListeners = outer;
1181
+ }
1182
+ if (thrown.length > 0) throw thrown[0];
1183
+ };
1083
1184
  const emitError = (err) => {
1084
- for (const listener of errorListeners) listener(err);
1185
+ for (const listener of errorListeners) deliver(() => listener(err));
1085
1186
  for (const sub of errorSubscribers) sub(err);
1086
1187
  };
1087
1188
  const enterFailedState = () => {
@@ -1095,6 +1196,7 @@ var createStream = (options) => {
1095
1196
  });
1096
1197
  finalState.reject(error);
1097
1198
  }
1199
+ for (const sub of failSubscribers) sub(error);
1098
1200
  };
1099
1201
  const tracker = createFinalizationTracker();
1100
1202
  const validator = createValidator({
@@ -1103,7 +1205,8 @@ var createStream = (options) => {
1103
1205
  constraints,
1104
1206
  emitError,
1105
1207
  onFailed: enterFailedState,
1106
- getContainerKeys: (path) => tracker.getContainerKeys(path)
1208
+ getContainerKeys: (path) => tracker.getContainerKeys(path),
1209
+ getChildIndex: (path, key) => tracker.getChildIndex(path, key)
1107
1210
  });
1108
1211
  const parser = createIncrementalParser(base, {
1109
1212
  valueOpenHook: validator.valueOpen
@@ -1111,7 +1214,7 @@ var createStream = (options) => {
1111
1214
  const notify = (value) => {
1112
1215
  isNotifying = true;
1113
1216
  for (const listener of listeners) {
1114
- listener(value);
1217
+ deliver(() => listener(value));
1115
1218
  }
1116
1219
  for (const sub of changeSubscribers) {
1117
1220
  sub();
@@ -1119,16 +1222,30 @@ var createStream = (options) => {
1119
1222
  isNotifying = false;
1120
1223
  while (pendingImmediateFires.length > 0) {
1121
1224
  const fire = pendingImmediateFires.shift();
1122
- if (fire) fire();
1225
+ if (fire) deliver(fire);
1123
1226
  }
1124
1227
  };
1125
1228
  const notifyFinal = (value) => {
1126
1229
  if (finalState.resolved) return;
1230
+ if (isFinalChecked) {
1231
+ const checked = options.schema.safeParse(value);
1232
+ if (!checked.success) {
1233
+ emitError({
1234
+ path: "",
1235
+ expected: "a value the schema takes",
1236
+ received: value === null ? "null" : Array.isArray(value) ? "array" : typeof value,
1237
+ phase: "finalize",
1238
+ message: `[solid] <root>: ${checked.error.issues[0]?.message ?? "the schema refuses the value"}`
1239
+ });
1240
+ enterFailedState();
1241
+ return;
1242
+ }
1243
+ }
1127
1244
  const { resolve } = finalState;
1128
1245
  finalState = { resolved: true, value };
1129
1246
  resolve(value);
1130
1247
  for (const listener of finalListeners) {
1131
- listener(value);
1248
+ deliver(() => listener(value));
1132
1249
  }
1133
1250
  finalListeners.clear();
1134
1251
  for (const sub of finalizeSubscribers) {
@@ -1136,7 +1253,7 @@ var createStream = (options) => {
1136
1253
  }
1137
1254
  hasNotifiedFinal = true;
1138
1255
  };
1139
- const write = (chunk) => {
1256
+ const write = (chunk) => throwingAfter(() => {
1140
1257
  if (isClosed || isDestroyed || isFailed) return;
1141
1258
  const events = parser.write(chunk);
1142
1259
  if (isFailed) return;
@@ -1158,14 +1275,14 @@ var createStream = (options) => {
1158
1275
  if (tracker.isRootFinal()) {
1159
1276
  notifyFinal(currentValue);
1160
1277
  }
1161
- };
1162
- const close = () => {
1278
+ });
1279
+ const close = () => throwingAfter(() => {
1163
1280
  if (isDestroyed || isClosed) return;
1164
1281
  isClosed = true;
1165
1282
  if (!finalState.resolved) {
1166
1283
  notifyFinal(currentValue);
1167
1284
  }
1168
- };
1285
+ });
1169
1286
  const destroy = () => {
1170
1287
  if (isDestroyed) return;
1171
1288
  isDestroyed = true;
@@ -1175,6 +1292,7 @@ var createStream = (options) => {
1175
1292
  changeSubscribers.clear();
1176
1293
  finalizeSubscribers.clear();
1177
1294
  errorSubscribers.clear();
1295
+ failSubscribers.clear();
1178
1296
  pendingImmediateFires.length = 0;
1179
1297
  if (!finalState.resolved) {
1180
1298
  finalState.promise.catch(() => {
@@ -1188,8 +1306,8 @@ var createStream = (options) => {
1188
1306
  };
1189
1307
  const current = () => currentValue;
1190
1308
  const final = () => {
1191
- if (isFailed && failureError) return Promise.reject(failureError);
1192
1309
  if (finalState.resolved) return Promise.resolve(finalState.value);
1310
+ if (isFailed && failureError) return Promise.reject(failureError);
1193
1311
  return finalState.promise;
1194
1312
  };
1195
1313
  const on = (listener) => {
@@ -1254,7 +1372,15 @@ var createStream = (options) => {
1254
1372
  errorSubscribers.delete(listener);
1255
1373
  };
1256
1374
  },
1257
- resolveSubSelect: (fullPath) => select(fullPath)
1375
+ failure: () => failureError,
1376
+ onRootFail: (listener) => {
1377
+ failSubscribers.add(listener);
1378
+ return () => {
1379
+ failSubscribers.delete(listener);
1380
+ };
1381
+ },
1382
+ resolveSubSelect: (fullPath) => select(fullPath),
1383
+ deliver
1258
1384
  });
1259
1385
  selectedStreams.set(path, selected);
1260
1386
  return selected;
@@ -1268,16 +1394,17 @@ var resolveBase = (options) => {
1268
1394
  if (!result2.success) {
1269
1395
  throw new Error(`[solid] initial value is invalid: ${result2.error.message}`);
1270
1396
  }
1271
- return result2.data;
1397
+ return { base: result2.data, isBaseValid: true };
1272
1398
  }
1273
1399
  const candidate = deriveDefaults(schema);
1274
1400
  const result = schema.safeParse(candidate);
1401
+ if (!result.success && fitsShape(schema, candidate)) return { base: candidate, isBaseValid: false };
1275
1402
  if (!result.success) {
1276
1403
  throw new Error(
1277
1404
  `[solid] cannot derive valid base from schema defaults. Provide an explicit initial value. Error: ${result.error.message}`
1278
1405
  );
1279
1406
  }
1280
- return result.data;
1407
+ return { base: result.data, isBaseValid: true };
1281
1408
  };
1282
1409
 
1283
1410
  exports.createStream = createStream;