@sanity/validation 6.21.0-next.1 → 6.21.0-next.106

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.
@@ -1,10 +1,11 @@
1
+ import { isInternalValidator, markInternalValidator } from "@sanity/schema/_internal";
1
2
  import { isArrayOfBlocksSchemaType, isArrayOfObjectsSchemaType, isKeyedObject, isReference, isSlug, isTypedObject } from "@sanity/types";
2
3
  import { createClientConcurrencyLimiter } from "@sanity/util/client";
3
4
  import { ConcurrencyLimiter } from "@sanity/util/concurrency-limiter";
4
5
  import { dequal } from "dequal/lite";
5
6
  import flatten from "lodash-es/flatten.js";
6
- import { EMPTY, Observable, Subject, asapScheduler, bufferTime, concat, defer, filter, firstValueFrom, from, lastValueFrom, map, merge, mergeMap, of, share, takeUntil, throwError } from "rxjs";
7
- import { catchError, filter as filter$1, ignoreElements, map as map$1, mergeAll, mergeMap as mergeMap$1, observeOn, switchMap, takeUntil as takeUntil$1, toArray } from "rxjs/operators";
7
+ import { Observable } from "rxjs";
8
+ import { map } from "rxjs/operators";
8
9
  import { createInstance } from "i18next";
9
10
  import { Rule as Rule$1 } from "@sanity/schema";
10
11
  import get from "lodash-es/get.js";
@@ -60,16 +61,6 @@ const validationMarkerCodes = {
60
61
  valueRequired: "value.required",
61
62
  valueTypeMismatch: "value.type-mismatch"
62
63
  };
63
- function abortSignalAsObservable(signal) {
64
- return new Observable((subscriber) => {
65
- let onAbort = () => subscriber.error(signal.reason);
66
- if (signal.aborted) onAbort();
67
- else return signal.addEventListener("abort", onAbort, { once: !0 }), () => signal.removeEventListener("abort", onAbort);
68
- });
69
- }
70
- function cancelWith(signal) {
71
- return (source) => signal ? source.pipe(takeUntil(abortSignalAsObservable(signal))) : source;
72
- }
73
64
  var ClientUnavailableError = class extends Error {
74
65
  name = "ClientUnavailableError";
75
66
  constructor() {
@@ -140,13 +131,6 @@ function getFallbackLocaleSource() {
140
131
  t: i18n.t
141
132
  }, fallbackLocaleSource;
142
133
  }
143
- const internalValidators = /* @__PURE__ */ new WeakSet();
144
- function markInternalValidator(validator) {
145
- return internalValidators.add(validator), validator;
146
- }
147
- function isInternalValidator(validator) {
148
- return typeof validator == "function" && internalValidators.has(validator);
149
- }
150
134
  function resolveConditionalProperty(property, context) {
151
135
  let { currentUser, document, parent, value, path } = context;
152
136
  return typeof property == "boolean" || property === void 0 ? !!property : property({
@@ -157,27 +141,62 @@ function resolveConditionalProperty(property, context) {
157
141
  path
158
142
  }) === !0;
159
143
  }
144
+ function settleCheck(check, result) {
145
+ check.settled || (check.settled = !0, check.signal && check.onAbort && check.signal.removeEventListener("abort", check.onAbort), "error" in result ? check.reject(result.error) : check.resolve(result.exists));
146
+ }
160
147
  function createBatchedGetDocumentExists(client, defaultSignal) {
161
- let id$ = new Subject(), existence$ = id$.pipe(bufferTime(250, null, 100), map((ids) => Array.from(new Set(ids))), filter((ids) => ids.length > 0), mergeMap((ids) => client.observable.request({
162
- url: client.getDataUrl("doc", ids.join(",")),
163
- query: { excludeContent: "true" },
164
- signal: defaultSignal,
165
- tag: "documents-availability"
166
- }).pipe(map((availability) => ({
167
- availability,
168
- ids
169
- }))), 1), mergeMap(({ availability, ids }) => {
170
- let missingIds = new Set(availability.omitted.filter(({ reason }) => reason === "existence").map(({ id }) => id));
171
- return ids.map((id) => ({
172
- id,
173
- exists: !missingIds.has(id)
174
- }));
175
- }), share());
176
- return async function getDocumentExists(options) {
148
+ let buffer = /* @__PURE__ */ new Map(), queuedBatches = [], bufferTimer, draining = !1, rejectBatch = (batch, reason) => {
149
+ for (let checks of batch.values()) for (let check of checks) settleCheck(check, { error: reason });
150
+ }, rejectPending = (reason) => {
151
+ bufferTimer !== void 0 && clearTimeout(bufferTimer), bufferTimer = void 0, rejectBatch(buffer, reason), buffer = /* @__PURE__ */ new Map();
152
+ for (let batch of queuedBatches.splice(0)) rejectBatch(batch, reason);
153
+ }, flush = () => {
154
+ bufferTimer !== void 0 && clearTimeout(bufferTimer), bufferTimer = void 0, buffer.size !== 0 && (queuedBatches.push(buffer), buffer = /* @__PURE__ */ new Map(), drain());
155
+ }, scheduleFlush = () => {
156
+ buffer.size >= 100 ? flush() : bufferTimer === void 0 && (bufferTimer = setTimeout(flush, 250));
157
+ };
158
+ async function drain() {
159
+ if (!draining) {
160
+ draining = !0;
161
+ try {
162
+ for (; queuedBatches.length > 0;) {
163
+ defaultSignal?.throwIfAborted();
164
+ let batch = queuedBatches.shift();
165
+ if (!batch) continue;
166
+ let ids = [...batch.entries()].filter(([, checks]) => checks.some((check) => !check.settled)).map(([id]) => id);
167
+ if (ids.length !== 0) try {
168
+ let availability = await client.request({
169
+ url: client.getDataUrl("doc", ids.join(",")),
170
+ query: { excludeContent: "true" },
171
+ signal: defaultSignal,
172
+ tag: "documents-availability"
173
+ }), missingIds = new Set(availability.omitted.filter(({ reason }) => reason === "existence").map(({ id }) => id));
174
+ for (let id of ids) for (let check of batch.get(id) ?? []) settleCheck(check, { exists: !missingIds.has(id) });
175
+ } catch (error) {
176
+ rejectBatch(batch, error), rejectPending(error);
177
+ return;
178
+ }
179
+ }
180
+ } catch (error) {
181
+ rejectPending(error);
182
+ } finally {
183
+ draining = !1;
184
+ }
185
+ }
186
+ }
187
+ return function getDocumentExists(options) {
177
188
  let signal = options.signal || defaultSignal;
178
- signal?.throwIfAborted();
179
- let result = firstValueFrom(existence$.pipe(filter(({ id }) => id === options.id), map(({ exists }) => exists), cancelWith(signal)));
180
- return id$.next(options.id), result;
189
+ return signal?.aborted ? Promise.reject(signal.reason) : new Promise((resolve, reject) => {
190
+ let check = {
191
+ reject,
192
+ resolve,
193
+ settled: !1,
194
+ signal
195
+ };
196
+ signal && (check.onAbort = () => settleCheck(check, { error: signal.reason }), signal.addEventListener("abort", check.onAbort, { once: !0 }));
197
+ let checks = buffer.get(options.id);
198
+ checks ? checks.push(check) : buffer.set(options.id, [check]), scheduleFlush();
199
+ });
181
200
  };
182
201
  }
183
202
  function pathToString(path = []) {
@@ -856,9 +875,13 @@ const slugUniquenessValidator = (value, context) => {
856
875
  }
857
876
  let message = isLocalizedMessages(this._message) ? localizeMessage(this._message, context.i18n) : this._message;
858
877
  try {
859
- return convertToValidationMarker(await validator(specConstraint, value, message, context), this._level, context, { code: fallbackCodeForRule(curr.flag) });
878
+ let validatorContext = curr.flag === "all" || curr.flag === "either" ? {
879
+ ...context,
880
+ __internal
881
+ } : context;
882
+ return convertToValidationMarker(await validator(specConstraint, value, message, validatorContext), this._level, context, { code: fallbackCodeForRule(curr.flag) });
860
883
  } catch (err) {
861
- if (context.signal?.throwIfAborted(), err instanceof ClientUnavailableError) return markIncomplete?.(), [];
884
+ if (context.signal?.throwIfAborted(), markIncomplete?.(), err instanceof ClientUnavailableError) return [];
862
885
  let errorMessage = `${pathToString(context.path)}: Exception occurred while validating value: ${err.message}`;
863
886
  return convertToValidationMarker({
864
887
  code: validationMarkerCodes.validationException,
@@ -938,15 +961,7 @@ const requestIdleCallbackShim = function requestIdleCallbackShim(callback, _opti
938
961
  }, 0);
939
962
  }, cancelIdleCallbackShim = function cancelIdleCallbackShim(handle) {
940
963
  return globalThis.clearTimeout(handle);
941
- }, win = typeof window > "u" ? void 0 : window, requestIdleCallback = win?.requestIdleCallback || requestIdleCallbackShim, cancelIdleCallback = win?.cancelIdleCallback || cancelIdleCallbackShim, microtask = EMPTY.pipe(observeOn(asapScheduler));
942
- /**
943
- * How an `immediate` run hands the thread back. `scheduler.yield()` resumes the run ahead of the
944
- * tasks that were already waiting. Where the browser has none (Safari), the run resumes in a task
945
- * of its own, behind them, which it gets the way React's scheduler does: from `setImmediate` where
946
- * there is one (Node), because a `MessageChannel` would keep a Node process alive; otherwise from
947
- * a `MessageChannel`, because chained timeouts are clamped to 4 ms and throttled in background
948
- * tabs; and from `setTimeout` as a last resort.
949
- */
964
+ }, win = typeof window > "u" ? void 0 : window, requestIdleCallback = win?.requestIdleCallback || requestIdleCallbackShim, cancelIdleCallback = win?.cancelIdleCallback || cancelIdleCallbackShim, microtask = Promise.resolve();
950
965
  function getYieldToBrowser() {
951
966
  let { scheduler, setImmediate } = globalThis;
952
967
  return typeof scheduler?.yield == "function" ? scheduler.yield.bind(scheduler) : typeof setImmediate == "function" ? () => new Promise((resolve) => setImmediate(resolve)) : typeof MessageChannel == "function" ? yieldThroughMessageChannel : yieldThroughTimeout;
@@ -966,42 +981,83 @@ function yieldThroughMessageChannel() {
966
981
  function yieldThroughTimeout() {
967
982
  return new Promise((resolve) => setTimeout(resolve, 0));
968
983
  }
969
- function idle() {
970
- return new Observable((observer) => {
971
- let handle = requestIdleCallback(() => {
972
- observer.complete();
984
+ function abortReason(signal) {
985
+ return signal.reason ?? new DOMException("Validation aborted", "AbortError");
986
+ }
987
+ function cancelWithSignal(wait, signal) {
988
+ return signal ? signal.aborted ? Promise.reject(abortReason(signal)) : new Promise((resolve, reject) => {
989
+ let onAbort = () => {
990
+ signal.removeEventListener("abort", onAbort), reject(abortReason(signal));
991
+ };
992
+ signal.addEventListener("abort", onAbort, { once: !0 }), wait.then(() => {
993
+ signal.removeEventListener("abort", onAbort), resolve();
994
+ }, (error) => {
995
+ signal.removeEventListener("abort", onAbort), reject(error);
973
996
  });
974
- return () => cancelIdleCallback(handle);
997
+ }) : wait;
998
+ }
999
+ function waitForIdle(signal, waiters) {
1000
+ return new Promise((resolve, reject) => {
1001
+ let settled = !1, handle, finish = (reason) => {
1002
+ settled || (settled = !0, handle !== void 0 && cancelIdleCallback(handle), waiters?.delete(finish), signal?.removeEventListener("abort", onAbort), reason === void 0 ? resolve() : reject(reason));
1003
+ }, onAbort = () => {
1004
+ signal && finish(abortReason(signal));
1005
+ };
1006
+ signal?.aborted ? onAbort() : (waiters?.add(finish), signal?.addEventListener("abort", onAbort, { once: !0 }), handle = requestIdleCallback(() => finish()));
975
1007
  });
976
1008
  }
977
1009
  /**
978
1010
  * Yields to the browser once every `every` nodes and lets the others through on a microtask.
979
- * Every node that comes along while the yield is pending waits for that same yield (rather than
980
- * requesting one of its own, which would let the run carry on around the waiting nodes), and the
981
- * count starts over when it resolves.
1011
+ * Every node that comes along while the yield is pending waits for that same yield.
982
1012
  */
983
1013
  function createYieldingPace(yieldToBrowser, every) {
984
1014
  let count = 0, pending;
985
- return () => {
986
- if (pending) return pending;
987
- if (count += 1, count < every) return microtask;
988
- count = 0;
989
- let settle = () => {
990
- pending === yielded && (pending = void 0);
991
- }, yielded = from(yieldToBrowser().then(settle, settle)).pipe(ignoreElements());
992
- return pending = yielded, yielded;
1015
+ return {
1016
+ wait(signal) {
1017
+ if (signal?.throwIfAborted(), pending) return cancelWithSignal(pending, signal);
1018
+ if (count += 1, count < every) return cancelWithSignal(microtask, signal);
1019
+ count = 0;
1020
+ let settle = () => {
1021
+ pending === yielded && (pending = void 0);
1022
+ }, yielded = yieldToBrowser().then(settle, settle);
1023
+ return pending = yielded, cancelWithSignal(yielded, signal);
1024
+ },
1025
+ dispose() {}
1026
+ };
1027
+ }
1028
+ /** A pacer for server validation, where yielding to a browser is unnecessary. */
1029
+ function createUnpacedPace() {
1030
+ return {
1031
+ wait(signal) {
1032
+ signal?.throwIfAborted();
1033
+ },
1034
+ dispose() {}
993
1035
  };
994
1036
  }
995
1037
  /**
996
- * The pacer for one run, `idle` without a scheduling. The scheduling can change while the run is in
997
- * flight: each node waits the way the scheduling is when its turn comes, and a switch to
998
- * `immediate` lets the nodes that are waiting for idle time go ahead, so the run picks up speed
999
- * where it is instead of starting over.
1038
+ * The pacer for one Studio run, `idle` without a scheduling. One subscription observes scheduling
1039
+ * changes for the whole run rather than creating one RxJS subscription per validation node.
1000
1040
  */
1001
1041
  function createPace(scheduling) {
1002
- if (!scheduling) return idle;
1003
- let immediate = createYieldingPace(getYieldToBrowser(), 100), switchedToImmediate = scheduling.pipe(filter$1((mode) => mode === "immediate"));
1004
- return () => scheduling.getValue() === "immediate" ? immediate() : idle().pipe(takeUntil$1(switchedToImmediate));
1042
+ if (!scheduling) return {
1043
+ wait: (signal) => waitForIdle(signal),
1044
+ dispose() {}
1045
+ };
1046
+ let current = scheduling.getValue(), disposed = !1, waiters = /* @__PURE__ */ new Set(), immediate = createYieldingPace(getYieldToBrowser(), 100), subscription = scheduling.subscribe((next) => {
1047
+ if (current = next, next === "immediate") for (let release of waiters) release();
1048
+ });
1049
+ return {
1050
+ wait(signal) {
1051
+ return disposed ? Promise.reject(/* @__PURE__ */ Error("Validation pace has been disposed")) : current === "immediate" ? immediate.wait(signal) : waitForIdle(signal, waiters);
1052
+ },
1053
+ dispose() {
1054
+ if (!disposed) {
1055
+ disposed = !0, subscription.unsubscribe();
1056
+ for (let release of waiters) release(/* @__PURE__ */ Error("Validation pace has been disposed"));
1057
+ immediate.dispose();
1058
+ }
1059
+ }
1060
+ };
1005
1061
  }
1006
1062
  /**
1007
1063
  * Given a schema type, returns a custom validator used to warn users of unknown
@@ -1020,6 +1076,19 @@ const unknownFieldsValidator = (type) => (value) => {
1020
1076
  path: [unknownField]
1021
1077
  }));
1022
1078
  }, DEFAULT_VALIDATION_CLIENT_OPTIONS = { apiVersion: "2025-02-19" }, isRecord = (maybeRecord) => typeof maybeRecord == "object" && !!maybeRecord && !Array.isArray(maybeRecord);
1079
+ /** Rejects on abort without waiting for work that does not observe the signal itself. */
1080
+ function raceWithSignal(promise, signal) {
1081
+ return signal ? signal.aborted ? Promise.reject(signal.reason) : new Promise((resolve, reject) => {
1082
+ let onAbort = () => {
1083
+ signal.removeEventListener("abort", onAbort), reject(signal.reason);
1084
+ };
1085
+ signal.addEventListener("abort", onAbort, { once: !0 }), promise.then((value) => {
1086
+ signal.removeEventListener("abort", onAbort), resolve(value);
1087
+ }, (error) => {
1088
+ signal.removeEventListener("abort", onAbort), reject(error);
1089
+ });
1090
+ }) : promise;
1091
+ }
1023
1092
  function throwClientUnavailable() {
1024
1093
  throw new ClientUnavailableError();
1025
1094
  }
@@ -1106,11 +1175,23 @@ function normalizeValidationOptions(options) {
1106
1175
  };
1107
1176
  }
1108
1177
  function createDocumentValidationResult(markers, complete) {
1178
+ let isComplete = complete && !markers.some(hasEvaluationFailure);
1109
1179
  return {
1110
- status: getDocumentValidationStatus(markers, complete),
1180
+ status: getDocumentValidationStatus(markers, isComplete),
1181
+ complete: isComplete,
1111
1182
  markers: markers.map(toDocumentValidationMarker)
1112
1183
  };
1113
1184
  }
1185
+ function hasEvaluationFailure(value) {
1186
+ if (!isRecord(value)) return !1;
1187
+ switch (value.code) {
1188
+ case validationMarkerCodes.validationException:
1189
+ case validationMarkerCodes.documentUnknownType: return !0;
1190
+ case validationMarkerCodes.ruleAllFailed:
1191
+ case validationMarkerCodes.ruleEitherFailed: return isRecord(value.details) && Array.isArray(value.details.causes) && value.details.causes.some(hasEvaluationFailure);
1192
+ default: return !1;
1193
+ }
1194
+ }
1114
1195
  function getDocumentValidationStatus(markers, complete) {
1115
1196
  return markers.length > 0 ? "failed" : complete ? "passed" : "notEvaluated";
1116
1197
  }
@@ -1130,7 +1211,7 @@ function evaluateDocumentsInternal({ documents, schema, getClient, getDocumentEx
1130
1211
  if (signal?.aborted) return Promise.reject(signal.reason);
1131
1212
  if (documents.length === 0) return Promise.resolve([]);
1132
1213
  let limitConcurrency = createClientConcurrencyLimiter(maxFetchConcurrency ?? 25, signal), getConcurrencyLimitedClient = (clientOptions) => limitConcurrency(getClient(clientOptions)), sharedGetDocumentExists = getDocumentExists || createBatchedGetDocumentExists(getClient(DEFAULT_VALIDATION_CLIENT_OPTIONS), signal);
1133
- return Promise.all(documents.map((document) => lastValueFrom(evaluateDocumentObservable({
1214
+ return Promise.all(documents.map((document) => evaluateDocument({
1134
1215
  document,
1135
1216
  getClient: getConcurrencyLimitedClient,
1136
1217
  i18n,
@@ -1140,8 +1221,9 @@ function evaluateDocumentsInternal({ documents, schema, getClient, getDocumentEx
1140
1221
  maxCustomValidationConcurrency,
1141
1222
  currentUser,
1142
1223
  customValidation,
1143
- signal
1144
- }))));
1224
+ signal,
1225
+ pace: createUnpacedPace()
1226
+ })));
1145
1227
  }
1146
1228
  const customValidationConcurrencyLimiters = /* @__PURE__ */ new WeakMap();
1147
1229
  /**
@@ -1149,28 +1231,47 @@ const customValidationConcurrencyLimiters = /* @__PURE__ */ new WeakMap();
1149
1231
  * @internal
1150
1232
  */
1151
1233
  function validateDocumentObservable(options) {
1152
- return evaluateDocumentObservable(options).pipe(map$1(({ markers }) => markers));
1234
+ return evaluateDocumentObservable(options).pipe(map(({ markers }) => markers));
1153
1235
  }
1154
1236
  /**
1155
1237
  * Validates a document against the given schema, including completion status.
1156
1238
  * @internal
1157
1239
  */
1158
1240
  function evaluateDocumentObservable(options) {
1159
- let { signal } = options;
1160
- return defer(() => (signal?.throwIfAborted(), evaluateDocumentObservableWithoutCancellation(options))).pipe(cancelWith(signal));
1241
+ return new Observable((subscriber) => {
1242
+ let controller = new AbortController(), { signal } = options, abort = () => controller.abort(signal?.reason);
1243
+ return signal?.aborted ? abort() : signal?.addEventListener("abort", abort, { once: !0 }), evaluateDocument({
1244
+ ...options,
1245
+ signal: controller.signal,
1246
+ pace: createPace(options.scheduling)
1247
+ }).then((result) => {
1248
+ subscriber.next(result), subscriber.complete();
1249
+ }, (error) => subscriber.error(error)), () => {
1250
+ signal?.removeEventListener("abort", abort), controller.abort();
1251
+ };
1252
+ });
1253
+ }
1254
+ async function evaluateDocument(options) {
1255
+ let { pace, signal } = options;
1256
+ try {
1257
+ return signal?.throwIfAborted(), await raceWithSignal(evaluateDocumentWithoutCancellation(options), signal);
1258
+ } finally {
1259
+ pace.dispose();
1260
+ }
1161
1261
  }
1162
- function evaluateDocumentObservableWithoutCancellation({ document, getClient, i18n = getFallbackLocaleSource(), schema, getDocumentExists, environment, maxCustomValidationConcurrency, currentUser, customValidation = !0, signal, scheduling }) {
1163
- if (typeof document?._type != "string") throw Error("Tried to validate a value without a '_type'");
1164
- let documentType = schema.get(document._type);
1165
- if (!documentType) return environment === "studio" ? (console.warn("Schema type for object type \"%s\" not found, skipping validation", document._type), of(createDocumentValidationResult([], !0))) : of(createDocumentValidationResult([{
1166
- code: validationMarkerCodes.documentUnknownType,
1167
- details: { documentType: document._type },
1168
- level: "warning",
1169
- message: `Could not find schema type for type '${document._type}', skipping validation`,
1170
- path: []
1171
- }], !0));
1172
- let customValidationConcurrencyLimiter = customValidationConcurrencyLimiters.get(schema);
1173
- return customValidationConcurrencyLimiter || (customValidationConcurrencyLimiter = new ConcurrencyLimiter(maxCustomValidationConcurrency ?? 5), customValidationConcurrencyLimiters.set(schema, customValidationConcurrencyLimiter)), defer(() => {
1262
+ async function evaluateDocumentWithoutCancellation({ document, getClient, i18n = getFallbackLocaleSource(), schema, getDocumentExists, environment, maxCustomValidationConcurrency, currentUser, customValidation = !0, signal, pace }) {
1263
+ try {
1264
+ if (typeof document?._type != "string") throw Error("Tried to validate a value without a '_type'");
1265
+ let documentType = schema.get(document._type);
1266
+ if (!documentType) return environment === "studio" ? (console.warn("Schema type for object type \"%s\" not found, skipping validation", document._type), createDocumentValidationResult([], !1)) : createDocumentValidationResult([{
1267
+ code: validationMarkerCodes.documentUnknownType,
1268
+ details: { documentType: document._type },
1269
+ level: "warning",
1270
+ message: `Could not find schema type for type '${document._type}', skipping validation`,
1271
+ path: []
1272
+ }], !1);
1273
+ let customValidationConcurrencyLimiter = customValidationConcurrencyLimiters.get(schema);
1274
+ customValidationConcurrencyLimiter || (customValidationConcurrencyLimiter = new ConcurrencyLimiter(maxCustomValidationConcurrency ?? 5), customValidationConcurrencyLimiters.set(schema, customValidationConcurrencyLimiter));
1174
1275
  let complete = !0, validationOptions = {
1175
1276
  getClient,
1176
1277
  schema,
@@ -1186,39 +1287,66 @@ function evaluateDocumentObservableWithoutCancellation({ document, getClient, i1
1186
1287
  currentUser,
1187
1288
  customValidation,
1188
1289
  signal,
1189
- scheduling,
1190
1290
  __internal: {
1191
1291
  markIncomplete: () => {
1192
1292
  complete = !1;
1193
1293
  },
1194
- pace: createPace(scheduling)
1294
+ pace
1195
1295
  }
1196
1296
  };
1197
- return from(i18n.loadNamespaces(["validation"])).pipe(switchMap(() => validateItemObservable(validationOptions)), map$1((markers) => createDocumentValidationResult(markers, complete)), catchError((err) => {
1198
- if (signal?.aborted) return throwError(() => signal.reason);
1199
- console.error(err);
1200
- let message = err?.message || "Unknown error", errorMarker = {
1201
- code: validationMarkerCodes.validationException,
1202
- level: "error",
1203
- message,
1204
- item: { message },
1205
- path: []
1206
- };
1207
- return of(createDocumentValidationResult([errorMarker], complete));
1208
- }));
1209
- });
1297
+ return await i18n.loadNamespaces(["validation"]), createDocumentValidationResult(await validateItemAsync(validationOptions), complete);
1298
+ } catch (err) {
1299
+ if (signal?.aborted) throw signal.reason;
1300
+ if (typeof document?._type != "string") throw err;
1301
+ console.error(err);
1302
+ let message = err instanceof Error || isRecord(err) && typeof err.message == "string" ? err.message : "Unknown error";
1303
+ return createDocumentValidationResult([{
1304
+ code: validationMarkerCodes.validationException,
1305
+ level: "error",
1306
+ message,
1307
+ item: { message },
1308
+ path: []
1309
+ }], !1);
1310
+ }
1210
1311
  }
1211
- function validateItem(opts) {
1212
- return lastValueFrom(defer(() => (opts.signal?.throwIfAborted(), validateItemObservable(opts))).pipe(cancelWith(opts.signal)));
1312
+ async function validateItem(opts) {
1313
+ opts.signal?.throwIfAborted();
1314
+ let inheritedPace = opts.__internal?.pace, pace = inheritedPace ?? createPace(opts.scheduling);
1315
+ try {
1316
+ return await raceWithSignal(validateItemAsync(inheritedPace ? opts : {
1317
+ ...opts,
1318
+ __internal: {
1319
+ ...opts.__internal,
1320
+ pace
1321
+ }
1322
+ }), opts.signal);
1323
+ } finally {
1324
+ inheritedPace || pace.dispose();
1325
+ }
1213
1326
  }
1214
1327
  function validateRule(rule, value, context) {
1215
1328
  return rule.validate(value, context);
1216
1329
  }
1217
- function validateItemObservable({ value, type, path = [], parent, customValidationConcurrencyLimiter, environment, customValidation = !0, scheduling, __internal: inheritedInternal, ...restOfContext }) {
1218
- let pace = inheritedInternal?.pace ?? createPace(scheduling), __internal = inheritedInternal?.pace ? inheritedInternal : {
1219
- ...inheritedInternal,
1220
- pace
1221
- }, ancestorHidden = restOfContext.hidden === !0, resolveHiddenForType = (schemaType, schemaValue, schemaParent, schemaPath, ancestorHiddenValue) => schemaType ? ancestorHiddenValue || resolveConditionalProperty(schemaType.hidden, {
1330
+ async function runValidationTasks(tasks, concurrency) {
1331
+ let results = [], nextIndex = 0, failed = !1, failure;
1332
+ async function worker() {
1333
+ for (; !failed && nextIndex < tasks.length;) {
1334
+ let task = tasks[nextIndex];
1335
+ nextIndex += 1;
1336
+ try {
1337
+ results.push(await task());
1338
+ } catch (error) {
1339
+ failed || (failed = !0, failure = error);
1340
+ }
1341
+ }
1342
+ }
1343
+ if (await Promise.all(Array.from({ length: Math.min(concurrency, tasks.length) }, () => worker())), failed) throw failure;
1344
+ return results;
1345
+ }
1346
+ async function validateItemAsync({ value, type, path = [], parent, customValidationConcurrencyLimiter, environment, customValidation = !0, scheduling: _scheduling, __internal: inheritedInternal, ...restOfContext }) {
1347
+ let pace = inheritedInternal?.pace;
1348
+ if (!pace) throw Error("Validation item was started without a pace");
1349
+ let __internal = inheritedInternal, ancestorHidden = restOfContext.hidden === !0, resolveHiddenForType = (schemaType, schemaValue, schemaParent, schemaPath, ancestorHiddenValue) => schemaType ? ancestorHiddenValue || resolveConditionalProperty(schemaType.hidden, {
1222
1350
  ...restOfContext,
1223
1351
  parent: schemaParent,
1224
1352
  value: schemaValue,
@@ -1236,7 +1364,7 @@ function validateItemObservable({ value, type, path = [], parent, customValidati
1236
1364
  parent,
1237
1365
  path,
1238
1366
  type
1239
- }), selfChecks = rules.map(addUnknownFieldsValidator).map((rule) => defer(() => validateRule(rule, value, {
1367
+ }), selfChecks = rules.map(addUnknownFieldsValidator).map((rule) => () => validateRule(rule, value, {
1240
1368
  ...restOfContext,
1241
1369
  environment,
1242
1370
  hidden,
@@ -1248,8 +1376,8 @@ function validateItemObservable({ value, type, path = [], parent, customValidati
1248
1376
  customValidation,
1249
1377
  customValidationConcurrencyLimiter
1250
1378
  }
1251
- }))), nestedChecks = [], selfIsRequired = rules.some((rule) => rule.isRequired());
1252
- if (type?.jsonType === "object" && (value || value == null && selfIsRequired)) {
1379
+ })), nestedChecks = [];
1380
+ if (type?.jsonType === "object" && (value || value == null && rules.some((rule) => rule.isRequired()))) {
1253
1381
  let fieldTypes = type.fields.reduce((acc, field) => (acc[field.name] = field.type, acc), {});
1254
1382
  nestedChecks = nestedChecks.concat(rules.flatMap((rule) => extractFieldRulesFromRule(rule)).flatMap((fieldResults) => Object.entries(fieldResults)).flatMap(([name, validation]) => {
1255
1383
  let fieldType = fieldTypes[name], nestedValue = isRecord(value) ? value[name] : void 0, fieldContext = {
@@ -1263,15 +1391,15 @@ function validateItemObservable({ value, type, path = [], parent, customValidati
1263
1391
  return normalizeValidationRules({
1264
1392
  ...fieldType,
1265
1393
  validation
1266
- }, fieldContext).map(addUnknownFieldsValidator).map((subRule) => defer(() => validateRule(subRule, nestedValue, {
1394
+ }, fieldContext).map(addUnknownFieldsValidator).map((subRule) => () => validateRule(subRule, nestedValue, {
1267
1395
  ...fieldContext,
1268
1396
  __internal: {
1269
1397
  ...__internal,
1270
1398
  customValidation,
1271
1399
  customValidationConcurrencyLimiter
1272
1400
  }
1273
- })));
1274
- })), nestedChecks = nestedChecks.concat(type.fields.map((field) => defer(() => validateItemObservable({
1401
+ }));
1402
+ })), nestedChecks = nestedChecks.concat(type.fields.map((field) => () => validateItemAsync({
1275
1403
  ...restOfContext,
1276
1404
  hidden,
1277
1405
  parent: value,
@@ -1281,11 +1409,10 @@ function validateItemObservable({ value, type, path = [], parent, customValidati
1281
1409
  environment,
1282
1410
  customValidationConcurrencyLimiter,
1283
1411
  customValidation,
1284
- scheduling,
1285
1412
  __internal
1286
- }))));
1413
+ })));
1287
1414
  }
1288
- return type?.jsonType === "array" && Array.isArray(value) && (nestedChecks = nestedChecks.concat(value.map((item, index) => defer(() => validateItemObservable({
1415
+ if (type?.jsonType === "array" && Array.isArray(value) && (nestedChecks = nestedChecks.concat(value.map((item, index) => () => validateItemAsync({
1289
1416
  ...restOfContext,
1290
1417
  hidden,
1291
1418
  parent: value,
@@ -1295,9 +1422,16 @@ function validateItemObservable({ value, type, path = [], parent, customValidati
1295
1422
  environment,
1296
1423
  customValidationConcurrencyLimiter,
1297
1424
  customValidation,
1298
- scheduling,
1299
1425
  __internal
1300
- }))))), defer(() => merge([...selfChecks, ...nestedChecks])).pipe(mergeMap$1((validateNode) => concat(pace(), validateNode), 40), mergeAll(), toArray(), map$1(flatten), map$1((results) => rules.some((rule) => extractFieldRulesFromRule(rule).length > 0) ? deduplicateMarkers(results) : results));
1426
+ })))), selfChecks.length === 1 && nestedChecks.length === 0 && !rules.some((rule) => extractFieldRulesFromRule(rule).length > 0)) {
1427
+ let wait = pace.wait(restOfContext.signal);
1428
+ return wait && await wait, restOfContext.signal?.throwIfAborted(), selfChecks[0]();
1429
+ }
1430
+ let results = flatten(await runValidationTasks([...selfChecks, ...nestedChecks].map((validateNode) => async () => {
1431
+ let wait = pace.wait(restOfContext.signal);
1432
+ return wait && await wait, restOfContext.signal?.throwIfAborted(), validateNode();
1433
+ }), 40));
1434
+ return rules.some((rule) => extractFieldRulesFromRule(rule).length > 0) ? deduplicateMarkers(results) : results;
1301
1435
  }
1302
1436
  function deduplicateMarkers(markers) {
1303
1437
  let buckets = /* @__PURE__ */ new Map();
@@ -1322,4 +1456,4 @@ function toDocumentValidationMarker(marker) {
1322
1456
  }
1323
1457
  export { getFallbackLocaleSource as _, validateDocumentInternal as a, validateDocuments as c, normalizeValidationRules as d, Rule$2 as f, pathToString as g, convertToValidationMarker as h, validateDocument as i, validateItem as l, typeString as m, evaluateDocumentObservable as n, validateDocumentObservable as o, getTypeChain as p, resolveTypeForArrayItem as r, validateDocumentWithWorkspace as s, evaluateDocumentInternal as t, compileValidationRules as u, validationLocaleStrings as v, validationMarkerCodes as y };
1324
1458
 
1325
- //# sourceMappingURL=validateDocument-5SD3VaOT.js.map
1459
+ //# sourceMappingURL=validateDocument-lfNM88pm.js.map