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