@web-ts-toolkit/access-router 0.61.0 → 0.62.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/advanced.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export { A as AccessRouterBaseRequest, a as AccessRouterFieldKey, b as AccessRouterLogger, c as AccessRouterRequest, d as AccessRouterRequestExtensions, e as AdvancedCreateBody, f as AdvancedListBody, g as AdvancedReadBody, h as AdvancedReadFilterBody, i as AdvancedUpdateBody, j as AdvancedUpsertBody, k as AfterPersistAccess, l as AjvErrorObjectLike, m as AjvValidationErrorLike, n as AjvValidatorLike, o as AllowedOutputFieldOptions, p as ArkTypeErrorsLike, q as ArkTypeLike, r as ArkTypeProblemLike, s as AuthorizedListResult, t as AuthorizedSingleResult, B as BaseFilterAccess, C as Change, u as Codes, v as CorrelatedCountInclude, w as CorrelatedFilter, x as CorrelatedInclude, y as CorrelatedIncludeArgs, z as CorrelatedListInclude, D as CorrelatedReadByFilterInclude, E as CorrelatedReadByIdInclude, F as CountBody, G as CreateArgs, H as CreateAuthorization, I as CreateOptions, J as CreateQueryInput, K as CustomHeaders, L as DATA_MIDDLEWARE, M as DataBaseFilterHook, N as DataFieldOptions, O as DataFilter, P as DataFindArgs, Q as DataFindOneArgs, R as DataFindOneOptions, S as DataFindOptions, T as DataHook, U as DataHookContext, V as DataIdentifierHook, W as DataListHook, X as DataOverrideFilterHook, Y as DataRequest, Z as DataRequestSchemas, _ as DataRouterOptions, $ as DecorateAccess, a0 as DecorateAllAccess, a1 as DeepFieldPath, a2 as DefaultModelRouterOptions, a3 as Defaults, a4 as DistinctArgs, a5 as DistinctBody, a6 as DocPermissionsAccess, a7 as DocumentAuthorization, a8 as ErrorResult, a9 as ExistsOptions, aa as ExtendedDataRouterOptions, ab as ExtendedDefaultModelRouterOptions, ac as ExtendedModelRouterOptions, ad as FieldAuthorization, ae as FieldOperationAccess, af as Filter, ag as FilterOperator, ah as FindAccess, ai as FindArgs, aj as FindByIdArgs, ak as FindByIdOptions, al as FindOneArgs, am as FindOneOptions, an as FindOptions, ao as GlobalOptions, ap as GlobalPermissionValue, aq as GuardHook, ar as HydrationMode, as as IdentifierHook, at as Include, au as InputFieldAuthorization, av as InputFieldPath, aw as IoTsContextEntryLike, ax as IoTsDecodeErrorLike, ay as IoTsDecoderLike, az as JoiSchemaLike, aA as JoiValidationErrorDetailLike, aB as KeyValueProjection, aC as LegacyInclude, aD as ListQueryInput, aE as ListResult, aF as MIDDLEWARE, aG as MaybePromise, aH as ModelBaseFilterHook, aI as ModelChangeHook, aJ as ModelDeleteHook, aK as ModelDocPermissionsHook, aL as ModelDocument, aM as ModelDocumentHook, aN as ModelHook, aO as ModelHookContext, aP as ModelHydrationOptions, aQ as ModelIdentifierHook, aR as ModelListHook, aS as ModelOverrideFilterHook, aT as ModelRequest, aU as ModelRouterOptions, aV as ModelValidateHook, aW as ModelVirtualAccess, aX as ModelVirtualAccessRecord, aY as ModelVirtualContext, aZ as ModelVirtualDescriptor, a_ as ModelVirtualDoc, a$ as ModelVirtualGetter, b0 as ModelVirtualLeaf, b1 as ModelVirtualPopulateDependency, b2 as ModelVirtualPopulateInputs, b3 as ModelVirtualRecordAccess, b4 as ModelVirtuals, b5 as MutationAuthorization, b6 as NewArgs, b7 as NewOptions, b8 as OperationAccess, b9 as OperationAuthorization, ba as OutputAuthorization, bb as OutputFieldOptions, bc as OutputFieldPath, bd as OutputPlanningOptions, be as PERMISSIONS, bf as PERMISSION_KEYS, bg as PairedRouteAccess, bh as ParentRef, bi as PathValue, bj as PermissionSchema, bk as Populate, bl as PopulateAccess, bm as PopulatePlanningOptions, bn as PrepareAccess, bo as Projection, bp as PublicCreateArgs, bq as PublicCreateOptions, br as PublicErrorResult, bs as PublicListArgs, bt as PublicListOptions, bu as PublicListResult, bv as PublicOutput, bw as PublicReadArgs, bx as PublicReadOptions, by as PublicServiceResult, bz as PublicSingleResult, bA as PublicSubdocumentCreateOptions, bB as PublicSubdocumentListOptions, bC as PublicSubdocumentMutationOptions, bD as PublicSubdocumentReadOptions, bE as PublicUpdateArgs, bF as PublicUpdateOptions, bG as PublicUpsertArgs, bH as PublicUpsertOptions, bI as ReadQueryInput, bJ as RelatedAuthorization, bK as Request, bL as RequestSchemaAdapter, bM as RequestSchemaFailure, bN as RequestSchemaIssue, bO as RequestSchemaLike, bP as RequestSchemaOptions, bQ as RequestSchemaResult, bR as RequestSchemaSuccess, bS as RequestSchemaValidator, bT as RequestSchemas, bU as RootDataListQueryEntry, bV as RootDataOperation, bW as RootDataReadByFilterQueryEntry, bX as RootDataReadByIdQueryEntry, bY as RootModelCountQueryEntry, bZ as RootModelCreateQueryEntry, b_ as RootModelDeleteQueryEntry, b$ as RootModelDistinctQueryEntry, c0 as RootModelListQueryEntry, c1 as RootModelNewQueryEntry, c2 as RootModelOperation, c3 as RootModelReadByFilterQueryEntry, c4 as RootModelReadByIdQueryEntry, c5 as RootModelSubBulkUpdateQueryEntry, c6 as RootModelSubCreateQueryEntry, c7 as RootModelSubDeleteQueryEntry, c8 as RootModelSubListQueryEntry, c9 as RootModelSubReadQueryEntry, ca as RootModelSubUpdateQueryEntry, cb as RootModelUpdateQueryEntry, cc as RootModelUpsertQueryEntry, cd as RootOperationResult, ce as RootQueryEntry, cf as RootRouterOptions, cg as RootSubOperation, ch as RootTarget, ci as RouteBaseAccess, cj as RouteGuardAccess, ck as RouteVariant, cl as RouteVariantAccess, cm as RowAuthorization, cn as SelectAccess, co as SelectedPopulatedPublicOutput, cp as SelectedPublicOutput, cq as ServiceAuthorization, cr as ServiceOutputContext, cs as ServiceOutputDecorator, ct as ServiceResult, cu as SingleResult, cv as Sort, cw as SortOrder, cx as StandardSchemaFailure, cy as StandardSchemaInferOutput, cz as StandardSchemaIssue, cA as StandardSchemaPathSegment, cB as StandardSchemaResult, cC as StandardSchemaSuccess, cD as StandardSchemaV1, cE as StatusCodes, cF as SubListBody, cG as SubOperationAccess, cH as SubPopulate, cI as SubQueryEntry, cJ as SubReadBody, cK as SubRouteGuardOptions, cL as SubdocumentBulkRecord, cM as SubdocumentBulkUpdateInput, cN as SubdocumentCreateAuthorization, cO as SubdocumentCreateInput, cP as SubdocumentCreateOptions, cQ as SubdocumentCreateVisibilityAuthorization, cR as SubdocumentDeleteAuthorization, cS as SubdocumentDeleteOptions, cT as SubdocumentGateAuthorization, cU as SubdocumentId, cV as SubdocumentInputAuthorization, cW as SubdocumentListOptions, cX as SubdocumentModel, cY as SubdocumentMutationAuthorization, cZ as SubdocumentName, c_ as SubdocumentOutputAuthorization, c$ as SubdocumentParentArgs, d0 as SubdocumentParentOptions, d1 as SubdocumentReadAuthorization, d2 as SubdocumentReadOptions, d3 as SubdocumentRecord, d4 as SubdocumentUpdateOptions, d5 as SubdocumentVirtuals, d6 as SubdocumentVisibilityAuthorization, d7 as SuperstructFailureLike, d8 as SuperstructValidateLike, d9 as Task, da as TaskType, db as TransformAccess, dc as TypedFilter, dd as UpdateByIdArgs, de as UpdateByIdOptions, df as UpdateOneArgs, dg as UpdateOneOptions, dh as UpdateQueryInput, di as UpsertArgs, dj as UpsertOptions, dk as UpsertQueryInput, dl as ValibotIssueLike, dm as ValibotPathItemLike, dn as ValibotSafeParseLike, dp as ValibotSafeParseResult, dq as ValidateAccess, dr as ValidateRule, ds as Validation, dt as ValidationError, du as VineValidationErrorLike, dv as VineValidationMessageLike, dw as VineValidatorLike, dx as VirtualSubModel, dy as WithVirtuals, dz as YupSchemaLike, dA as YupValidationErrorLike, dB as defineRequestSchema, dC as fromAjv, dD as fromArkType, dE as fromIoTs, dF as fromJoi, dG as fromStandardSchema, dH as fromSuperstruct, dI as fromValibot, dJ as fromVine, dK as fromYup, dL as fromZod, dM as parseBody, dN as parseBodyWithSchema, dO as parseNestedBodyWithSchema, dP as parsePathParam, dQ as parseQuery } from './parsers-DFZ_6fGl.js';
1
+ export { A as AccessRouterBaseRequest, a as AccessRouterFieldKey, b as AccessRouterLogger, c as AccessRouterRequest, d as AccessRouterRequestExtensions, e as AdvancedCreateBody, f as AdvancedListBody, g as AdvancedReadBody, h as AdvancedReadFilterBody, i as AdvancedUpdateBody, j as AdvancedUpsertBody, k as AfterPersistAccess, l as AjvErrorObjectLike, m as AjvValidationErrorLike, n as AjvValidatorLike, o as AllowedOutputFieldOptions, p as ArkTypeErrorsLike, q as ArkTypeLike, r as ArkTypeProblemLike, s as AuthorizedListResult, t as AuthorizedSingleResult, B as BaseFilterAccess, C as Change, u as Codes, v as CorrelatedCountInclude, w as CorrelatedFilter, x as CorrelatedInclude, y as CorrelatedIncludeArgs, z as CorrelatedListInclude, D as CorrelatedReadByFilterInclude, E as CorrelatedReadByIdInclude, F as CountBody, G as CreateArgs, H as CreateAuthorization, I as CreateOptions, J as CreateQueryInput, K as CustomHeaders, L as DATA_MIDDLEWARE, M as DataBaseFilterHook, N as DataFieldOptions, O as DataFilter, P as DataFindArgs, Q as DataFindOneArgs, R as DataFindOneOptions, S as DataFindOptions, T as DataHook, U as DataHookContext, V as DataIdentifierHook, W as DataListHook, X as DataOverrideFilterHook, Y as DataRequest, Z as DataRequestSchemas, _ as DataRouterOptions, $ as DecorateAccess, a0 as DecorateAllAccess, a1 as DeepFieldPath, a2 as DefaultModelRouterOptions, a3 as Defaults, a4 as DistinctArgs, a5 as DistinctBody, a6 as DocPermissionsAccess, a7 as DocumentAuthorization, a8 as ErrorResult, a9 as ExistsOptions, aa as ExtendedDataRouterOptions, ab as ExtendedDefaultModelRouterOptions, ac as ExtendedModelRouterOptions, ad as FieldAuthorization, ae as FieldOperationAccess, af as Filter, ag as FilterOperator, ah as FindAccess, ai as FindArgs, aj as FindByIdArgs, ak as FindByIdOptions, al as FindOneArgs, am as FindOneOptions, an as FindOptions, ao as GlobalOptions, ap as GlobalPermissionValue, aq as GuardHook, ar as HydrationMode, as as IdentifierHook, at as Include, au as InputFieldAuthorization, av as InputFieldPath, aw as IoTsContextEntryLike, ax as IoTsDecodeErrorLike, ay as IoTsDecoderLike, az as JoiSchemaLike, aA as JoiValidationErrorDetailLike, aB as KeyValueProjection, aC as LegacyInclude, aD as ListQueryInput, aE as ListResult, aF as MIDDLEWARE, aG as MaybePromise, aH as ModelBaseFilterHook, aI as ModelChangeHook, aJ as ModelDeleteHook, aK as ModelDocPermissionsHook, aL as ModelDocument, aM as ModelDocumentHook, aN as ModelHook, aO as ModelHookContext, aP as ModelHydrationOptions, aQ as ModelIdentifierHook, aR as ModelListHook, aS as ModelOverrideFilterHook, aT as ModelRequest, aU as ModelRouterOptions, aV as ModelValidateHook, aW as ModelVirtualAccess, aX as ModelVirtualAccessRecord, aY as ModelVirtualContext, aZ as ModelVirtualDescriptor, a_ as ModelVirtualDoc, a$ as ModelVirtualGetter, b0 as ModelVirtualLeaf, b1 as ModelVirtualPopulateDependency, b2 as ModelVirtualPopulateInputs, b3 as ModelVirtualRecordAccess, b4 as ModelVirtuals, b5 as MutationAuthorization, b6 as NewArgs, b7 as NewOptions, b8 as OperationAccess, b9 as OperationAuthorization, ba as OutputAuthorization, bb as OutputFieldOptions, bc as OutputFieldPath, bd as OutputPlanningOptions, be as PERMISSIONS, bf as PERMISSION_KEYS, bg as PairedRouteAccess, bh as ParentRef, bi as PathValue, bj as PermissionSchema, bk as Populate, bl as PopulateAccess, bm as PopulatePlanningOptions, bn as PrepareAccess, bo as Projection, bp as PublicCreateArgs, bq as PublicCreateOptions, br as PublicErrorResult, bs as PublicListArgs, bt as PublicListOptions, bu as PublicListResult, bv as PublicOutput, bw as PublicReadArgs, bx as PublicReadOptions, by as PublicServiceResult, bz as PublicSingleResult, bA as PublicSubdocumentCreateOptions, bB as PublicSubdocumentListOptions, bC as PublicSubdocumentMutationOptions, bD as PublicSubdocumentReadOptions, bE as PublicUpdateArgs, bF as PublicUpdateOptions, bG as PublicUpsertArgs, bH as PublicUpsertOptions, bI as ReadQueryInput, bJ as RelatedAuthorization, bK as Request, bL as RequestSchemaAdapter, bM as RequestSchemaFailure, bN as RequestSchemaIssue, bO as RequestSchemaLike, bP as RequestSchemaOptions, bQ as RequestSchemaResult, bR as RequestSchemaSuccess, bS as RequestSchemaValidator, bT as RequestSchemas, bU as RootDataListQueryEntry, bV as RootDataOperation, bW as RootDataReadByFilterQueryEntry, bX as RootDataReadByIdQueryEntry, bY as RootModelCountQueryEntry, bZ as RootModelCreateQueryEntry, b_ as RootModelDeleteQueryEntry, b$ as RootModelDistinctQueryEntry, c0 as RootModelListQueryEntry, c1 as RootModelNewQueryEntry, c2 as RootModelOperation, c3 as RootModelReadByFilterQueryEntry, c4 as RootModelReadByIdQueryEntry, c5 as RootModelSubBulkUpdateQueryEntry, c6 as RootModelSubCreateQueryEntry, c7 as RootModelSubDeleteQueryEntry, c8 as RootModelSubListQueryEntry, c9 as RootModelSubReadQueryEntry, ca as RootModelSubUpdateQueryEntry, cb as RootModelUpdateQueryEntry, cc as RootModelUpsertQueryEntry, cd as RootOperationResult, ce as RootQueryEntry, cf as RootRouterOptions, cg as RootSubOperation, ch as RootTarget, ci as RouteBaseAccess, cj as RouteGuardAccess, ck as RouteVariant, cl as RouteVariantAccess, cm as RowAuthorization, cn as SelectAccess, co as SelectedPopulatedPublicOutput, cp as SelectedPublicOutput, cq as ServiceAuthorization, cr as ServiceOutputContext, cs as ServiceOutputDecorator, ct as ServiceResult, cu as SingleResult, cv as Sort, cw as SortOrder, cx as StandardSchemaFailure, cy as StandardSchemaInferOutput, cz as StandardSchemaIssue, cA as StandardSchemaPathSegment, cB as StandardSchemaResult, cC as StandardSchemaSuccess, cD as StandardSchemaV1, cE as StatusCodes, cF as SubListBody, cG as SubOperationAccess, cH as SubPopulate, cI as SubQueryEntry, cJ as SubReadBody, cK as SubRouteGuardOptions, cL as SubdocumentBulkRecord, cM as SubdocumentBulkUpdateInput, cN as SubdocumentCreateAuthorization, cO as SubdocumentCreateInput, cP as SubdocumentCreateOptions, cQ as SubdocumentCreateVisibilityAuthorization, cR as SubdocumentDeleteAuthorization, cS as SubdocumentDeleteOptions, cT as SubdocumentGateAuthorization, cU as SubdocumentId, cV as SubdocumentInputAuthorization, cW as SubdocumentListOptions, cX as SubdocumentModel, cY as SubdocumentMutationAuthorization, cZ as SubdocumentName, c_ as SubdocumentOutputAuthorization, c$ as SubdocumentParentArgs, d0 as SubdocumentParentOptions, d1 as SubdocumentReadAuthorization, d2 as SubdocumentReadOptions, d3 as SubdocumentRecord, d4 as SubdocumentUpdateOptions, d5 as SubdocumentVirtuals, d6 as SubdocumentVisibilityAuthorization, d7 as SuperstructFailureLike, d8 as SuperstructValidateLike, d9 as Task, da as TaskType, db as TransformAccess, dc as TypedFilter, dd as UpdateByIdArgs, de as UpdateByIdOptions, df as UpdateOneArgs, dg as UpdateOneOptions, dh as UpdateQueryInput, di as UpsertArgs, dj as UpsertOptions, dk as UpsertQueryInput, dl as ValibotIssueLike, dm as ValibotPathItemLike, dn as ValibotSafeParseLike, dp as ValibotSafeParseResult, dq as ValidateAccess, dr as ValidateRule, ds as Validation, dt as ValidationError, du as VineValidationErrorLike, dv as VineValidationMessageLike, dw as VineValidatorLike, dx as VirtualSubModel, dy as WithVirtuals, dz as YupSchemaLike, dA as YupValidationErrorLike, dB as defineRequestSchema, dC as fromAjv, dD as fromArkType, dE as fromIoTs, dF as fromJoi, dG as fromStandardSchema, dH as fromSuperstruct, dI as fromValibot, dJ as fromVine, dK as fromYup, dL as fromZod, dM as parseBody, dN as parseBodyWithSchema, dO as parseNestedBodyWithSchema, dP as parsePathParam, dQ as parseQuery } from './parsers-Bdq0jg69.js';
2
2
  import { z } from 'zod';
3
3
  import 'mongoose';
4
4
  import 'express';
package/advanced.js CHANGED
@@ -133,7 +133,7 @@ var import_express_json_router = __toESM(require("@web-ts-toolkit/express-json-r
133
133
  var import_utils = require("@web-ts-toolkit/utils");
134
134
 
135
135
  // src/acl/unsafe-snapshot-options.ts
136
- var unsafeSnapshotOptions = [
136
+ var unsafeSnapshotCheckOptions = [
137
137
  "unsafeSkipListDocumentSnapshotChecks",
138
138
  "unsafeSkipReadDocumentSnapshotChecks",
139
139
  "unsafeSkipListOutputSnapshotChecks",
@@ -141,6 +141,11 @@ var unsafeSnapshotOptions = [
141
141
  "unsafeSkipListNestedDocumentSnapshotChecks",
142
142
  "unsafeSkipReadNestedDocumentSnapshotChecks"
143
143
  ];
144
+ var unsafeInitialOutputCopyOptions = [
145
+ "unsafeSkipListInitialOutputSnapshotCopy",
146
+ "unsafeSkipReadInitialOutputSnapshotCopy"
147
+ ];
148
+ var unsafeSnapshotOptions = [...unsafeSnapshotCheckOptions, ...unsafeInitialOutputCopyOptions];
144
149
 
145
150
  // src/validation/public-admission.ts
146
151
  var privateControls = [
@@ -208,9 +213,9 @@ function assertPublicAdmission(input, kind = "envelope") {
208
213
  for (const key of ["filter", "match", "data"]) add(record2[key], "data", key);
209
214
  }
210
215
  }
211
- function assertHydrationDefaults(defaults) {
212
- if (defaults && typeof defaults === "object") {
213
- const record2 = defaults;
216
+ function assertHydrationDefaults(defaults2) {
217
+ if (defaults2 && typeof defaults2 === "object") {
218
+ const record2 = defaults2;
214
219
  if ("hydration" in record2)
215
220
  throw new TypeError("defaults.hydration is unsupported; use model hydration configuration");
216
221
  for (const bucket of [
@@ -238,11 +243,11 @@ function assertHydrationDefaults(defaults) {
238
243
  }
239
244
  }
240
245
  }
241
- function assertPublicDefaults(defaults) {
242
- assertHydrationDefaults(defaults);
243
- assertPublicAdmission(defaults);
244
- if (defaults && typeof defaults === "object") {
245
- for (const value of Object.values(defaults)) assertPublicAdmission(value);
246
+ function assertPublicDefaults(defaults2) {
247
+ assertHydrationDefaults(defaults2);
248
+ assertPublicAdmission(defaults2);
249
+ if (defaults2 && typeof defaults2 === "object") {
250
+ for (const value of Object.values(defaults2)) assertPublicAdmission(value);
246
251
  }
247
252
  }
248
253
  var requestAuthorization = Object.freeze({ outputFields: Object.freeze({ mode: "request" }) });
@@ -272,6 +277,32 @@ function normalizeHydrationUpdate(current, key, value) {
272
277
  return normalizeHydration({ ...normalizeHydration(current), [method]: value });
273
278
  }
274
279
 
280
+ // src/options/populate-policy.ts
281
+ var populatePolicyKeys = [
282
+ "requireOperationAccessForPopulateQueries",
283
+ "requireOperationAccessForPopulateDependencies"
284
+ ];
285
+ function isPopulatePolicyKey(key) {
286
+ return populatePolicyKeys.includes(key);
287
+ }
288
+ function normalizePopulatePolicyValue(value) {
289
+ return value === void 0 ? void 0 : value !== false;
290
+ }
291
+ function normalizePopulatePolicyOptions(options) {
292
+ const next = { ...options };
293
+ for (const key of populatePolicyKeys) {
294
+ if (key in options)
295
+ next[key] = normalizePopulatePolicyValue(options[key]);
296
+ }
297
+ return next;
298
+ }
299
+ function assertNoGlobalPopulatePolicy(key) {
300
+ if (isPopulatePolicyKey(key))
301
+ throw new TypeError(
302
+ `${key} is target-model configuration; migrate to setModelOptions(targetModelName, { ${key}: value }) or setDefaultModelOptions({ ${key}: value }) for runtime model defaults`
303
+ );
304
+ }
305
+
275
306
  // src/runtime.ts
276
307
  var import_mongoose_schema_jsonschema = __toESM(require("mongoose-schema-jsonschema"));
277
308
  var import_utils13 = require("@web-ts-toolkit/utils");
@@ -765,6 +796,7 @@ var freezeConfigValue = (value) => {
765
796
  return value;
766
797
  };
767
798
  var cloneAndFreezeForStore = (value) => freezeConfigValue(cloneForRead(value));
799
+ var cloneOptionsSnapshot = (value) => freezeConfigValue(cloneForRead(value));
768
800
  var getNestedOption = (manager, key, defaultValue) => resolveNestedOption((path, fallback) => manager.get(path, fallback), String(key), defaultValue);
769
801
  var resolveNestedOption = (read, key, defaultValue) => {
770
802
  const keys2 = key.split(".");
@@ -1255,6 +1287,7 @@ var import_utils12 = require("@web-ts-toolkit/utils");
1255
1287
 
1256
1288
  // src/acl/authorization-snapshot.ts
1257
1289
  var import_node_util3 = require("util");
1290
+ var import_node_buffer = require("buffer");
1258
1291
  var import_mongoose2 = require("mongoose");
1259
1292
  var import_express_json_router2 = __toESM(require("@web-ts-toolkit/express-json-router"));
1260
1293
  var ServiceAuthorizationError = class extends import_express_json_router2.default.clientErrors.BadRequestError {
@@ -1361,6 +1394,9 @@ function isSafeInputPath(path, requestIdentity = false) {
1361
1394
  return isSafeOutputPath(path) && path.split(".").every((part) => !inputControlSegments.has(part) && (requestIdentity || part !== "_id"));
1362
1395
  }
1363
1396
  function matchesCatalogPattern(pattern, path, descendants = false) {
1397
+ if (typeof pattern === "string" && typeof path === "string" && !pattern.includes("$*")) {
1398
+ return pattern === path || !!descendants && path.startsWith(pattern) && path[pattern.length] === ".";
1399
+ }
1364
1400
  const expected = pattern.split(".");
1365
1401
  const actual = path.split(".");
1366
1402
  return (descendants ? actual.length >= expected.length : actual.length === expected.length) && expected.every((part, index) => part === "$*" || part === actual[index]);
@@ -1461,7 +1497,16 @@ function captureAuthorizationFieldCatalog(schema, virtuals, documentPermissionFi
1461
1497
 
1462
1498
  // src/acl/populate-target-configuration.ts
1463
1499
  var import_utils11 = require("@web-ts-toolkit/utils");
1464
- function capturePopulateTargetConfiguration(runtime, modelName, source, proposedOptions) {
1500
+
1501
+ // src/runtime-context.ts
1502
+ var import_node_async_hooks = require("async_hooks");
1503
+ var runtimeStorage = new import_node_async_hooks.AsyncLocalStorage();
1504
+ function getActiveRuntime() {
1505
+ return runtimeStorage.getStore() ?? null;
1506
+ }
1507
+
1508
+ // src/acl/populate-target-configuration.ts
1509
+ function capturePopulateTargetConfiguration(runtime, modelName, source, proposedOptions, defaults2 = runtime.getDefaultModelOptions()) {
1465
1510
  const label = `Populate target "${modelName}" for ${source}`;
1466
1511
  if (!proposedOptions && !runtime.hasModel(modelName))
1467
1512
  authorizationError(
@@ -1470,7 +1515,7 @@ function capturePopulateTargetConfiguration(runtime, modelName, source, proposed
1470
1515
  const model = runtime.getModelInstance(modelName);
1471
1516
  if (!model) authorizationError(`${label} requires an actual registered Mongoose model in this runtime`);
1472
1517
  const options = proposedOptions ?? runtime.getModelOptions(modelName);
1473
- const permissionSchema = options.permissionSchema === void 0 ? runtime.getDefaultModelOption("permissionSchema") : options.permissionSchema;
1518
+ const permissionSchema = options.permissionSchema === void 0 ? defaults2.permissionSchema : options.permissionSchema;
1474
1519
  if (!(0, import_utils11.isPlainObject)(permissionSchema))
1475
1520
  authorizationError(
1476
1521
  `${label} requires an effective object permissionSchema; configure the model or runtime model defaults ({} explicitly closes business fields)`
@@ -1478,6 +1523,31 @@ function capturePopulateTargetConfiguration(runtime, modelName, source, proposed
1478
1523
  return { model, options: { ...options, permissionSchema } };
1479
1524
  }
1480
1525
 
1526
+ // src/acl/populate-policy.ts
1527
+ var defaults = /* @__PURE__ */ new WeakMap();
1528
+ function capturePopulatePolicyDefaults(runtime) {
1529
+ const options = runtime.getDefaultModelOptions();
1530
+ const token = () => {
1531
+ };
1532
+ defaults.set(
1533
+ token,
1534
+ Object.freeze({
1535
+ requireOperationAccessForPopulateQueries: options.requireOperationAccessForPopulateQueries !== false,
1536
+ requireOperationAccessForPopulateDependencies: options.requireOperationAccessForPopulateDependencies !== false
1537
+ })
1538
+ );
1539
+ return token;
1540
+ }
1541
+ function resolvePopulatePolicy(options, token) {
1542
+ const captured = defaults.get(token);
1543
+ if (!captured) return authorizationError("invalid captured populate model defaults");
1544
+ const resolve = (key) => (options[key] === void 0 ? captured[key] : options[key]) !== false;
1545
+ return Object.freeze({
1546
+ requireOperationAccessForPopulateQueries: resolve(populatePolicyKeys[0]),
1547
+ requireOperationAccessForPopulateDependencies: resolve(populatePolicyKeys[1])
1548
+ });
1549
+ }
1550
+
1481
1551
  // src/acl/virtual-populate-dependencies.ts
1482
1552
  var elementType = (type) => type.$embeddedSchemaType ?? type.embeddedSchemaType ?? type.caster;
1483
1553
  var join = (prefix, path) => prefix ? `${prefix}.${path}` : path;
@@ -1577,9 +1647,7 @@ function normalizeSelection(select, catalog, label) {
1577
1647
  includeId: selection.includes("_id")
1578
1648
  };
1579
1649
  }
1580
- function captureVirtualPopulateDependencies(runtime, modelName, options, globalOptions = runtime.getGlobalOptions()) {
1581
- const requireOperationAccessForPopulateDependencies = globalOptions.requireOperationAccessForPopulateDependencies !== false;
1582
- const requireOperationAccessForPopulateQueries = globalOptions.requireOperationAccessForPopulateQueries !== false;
1650
+ function captureVirtualPopulateDependencies(runtime, modelName, options, populatePolicyDefaults = capturePopulatePolicyDefaults(runtime), proposed) {
1583
1651
  const model = runtime.getModelInstance(modelName);
1584
1652
  const targets = /* @__PURE__ */ new Map();
1585
1653
  const scopes = [];
@@ -1623,18 +1691,19 @@ function captureVirtualPopulateDependencies(runtime, modelName, options, globalO
1623
1691
  runtime,
1624
1692
  ref,
1625
1693
  `dependsOnPopulate virtual "${label}"`,
1626
- ref === modelName ? options : void 0
1694
+ ref === modelName ? options : proposed?.models.get(ref),
1695
+ proposed?.defaults
1627
1696
  );
1628
- const defaults = runtime.getDefaultModelOptions();
1629
- const readOption = (key) => resolveNestedOption((path2, fallback) => (0, import_utils12.get)(targetOptions, path2, fallback), key, (0, import_utils12.get)(defaults, key));
1630
- const documentPermissionField = targetOptions.documentPermissionField ?? defaults.documentPermissionField;
1697
+ const defaults2 = proposed?.defaults ?? runtime.getDefaultModelOptions();
1698
+ const readOption = (key) => resolveNestedOption((path2, fallback) => (0, import_utils12.get)(targetOptions, path2, fallback), key, (0, import_utils12.get)(defaults2, key));
1699
+ const documentPermissionField = targetOptions.documentPermissionField ?? defaults2.documentPermissionField;
1631
1700
  const catalog = captureAuthorizationFieldCatalog(targetModel.schema, void 0, documentPermissionField);
1632
1701
  const configuration = copyAuthorizationValue(
1633
1702
  {
1634
1703
  catalog,
1635
1704
  documentPermissionField,
1636
- requireOperationAccessForPopulateDependencies,
1637
- requireOperationAccessForPopulateQueries,
1705
+ populatePolicyDefaults,
1706
+ ...resolvePopulatePolicy(targetOptions, populatePolicyDefaults),
1638
1707
  permissionSchema: targetOptions.permissionSchema,
1639
1708
  operationAccess: { read: readOption("operationAccess.read") },
1640
1709
  baseFilter: { read: readOption("baseFilter.read") },
@@ -1729,6 +1798,15 @@ var defaultModelOptions = {
1729
1798
  basePath: null,
1730
1799
  alwaysSelectFields: []
1731
1800
  };
1801
+ var modelOverrides = (options) => {
1802
+ const result = Object.fromEntries(
1803
+ Object.entries(options).filter(
1804
+ ([key, value]) => value !== void 0 || key === "operationAccess" || isPopulatePolicyKey(key)
1805
+ )
1806
+ );
1807
+ for (const key of unsafeSnapshotOptions) if (key in result) result[key] = result[key] === true;
1808
+ return cloneOptionsSnapshot(result);
1809
+ };
1732
1810
  var defaultDataOptions = {
1733
1811
  basePath: null,
1734
1812
  parentPath: "/",
@@ -1862,12 +1940,12 @@ var getNestedChildFields = (parentSchema, fieldName) => {
1862
1940
  }
1863
1941
  return fields;
1864
1942
  };
1865
- var cloneVirtualsForValidation = (value) => {
1866
- if (Array.isArray(value)) return value.map((item) => cloneVirtualsForValidation(item));
1943
+ var cloneModelOptionForUpdate = (value) => {
1944
+ if (Array.isArray(value)) return value.map((item) => cloneModelOptionForUpdate(item));
1867
1945
  if (!value || typeof value !== "object") return value;
1868
1946
  if (Object.getPrototypeOf(value) !== Object.prototype) return value;
1869
1947
  return Object.fromEntries(
1870
- Object.entries(value).map(([k, v]) => [k, cloneVirtualsForValidation(v)])
1948
+ Object.entries(value).map(([k, v]) => [k, cloneModelOptionForUpdate(v)])
1871
1949
  );
1872
1950
  };
1873
1951
  var validateVirtualDependsOn = (dependsOn, entryLabel, storedFields, siblingVirtualNames) => {
@@ -2063,8 +2141,6 @@ var AccessRuntime = class {
2063
2141
  {
2064
2142
  requestPermissionField: "_permissions",
2065
2143
  globalPermissions: () => ({}),
2066
- requireOperationAccessForPopulateQueries: true,
2067
- requireOperationAccessForPopulateDependencies: true,
2068
2144
  logger: defaultLogger,
2069
2145
  requestComplexity: defaultRequestComplexity
2070
2146
  },
@@ -2079,15 +2155,20 @@ var AccessRuntime = class {
2079
2155
  queryRouteSegment: "__query",
2080
2156
  mutationRouteSegment: "__mutation",
2081
2157
  operationAccess: false,
2158
+ requireOperationAccessForPopulateQueries: true,
2159
+ requireOperationAccessForPopulateDependencies: true,
2082
2160
  modelPermissionPrefix: "",
2083
2161
  unsafeSkipListDocumentSnapshotChecks: false,
2084
2162
  unsafeSkipReadDocumentSnapshotChecks: false,
2085
2163
  unsafeSkipListOutputSnapshotChecks: false,
2086
2164
  unsafeSkipReadOutputSnapshotChecks: false,
2087
2165
  unsafeSkipListNestedDocumentSnapshotChecks: false,
2088
- unsafeSkipReadNestedDocumentSnapshotChecks: false
2166
+ unsafeSkipReadNestedDocumentSnapshotChecks: false,
2167
+ unsafeSkipListInitialOutputSnapshotCopy: false,
2168
+ unsafeSkipReadInitialOutputSnapshotCopy: false
2089
2169
  }).build();
2090
2170
  this.modelOptions = {};
2171
+ this.modelOptionOverrides = {};
2091
2172
  this.modelJsonSchemas = {};
2092
2173
  this.dataOptions = {};
2093
2174
  this.modelRefs = {};
@@ -2175,6 +2256,7 @@ var AccessRuntime = class {
2175
2256
  globalOptions: this.globalOptions.snapshot(),
2176
2257
  defaultModelOptions: this.defaultModelOptions.snapshot(),
2177
2258
  modelOptions: modelOptionsSnap,
2259
+ modelOptionOverrides: { ...this.modelOptionOverrides },
2178
2260
  dataOptions: dataOptionsSnap,
2179
2261
  modelInstances: { ...this.modelInstances },
2180
2262
  modelJsonSchemas: { ...this.modelJsonSchemas },
@@ -2189,6 +2271,10 @@ var AccessRuntime = class {
2189
2271
  restoreBootstrapSnapshot(snapshot) {
2190
2272
  this.globalOptions.restore(snapshot.globalOptions);
2191
2273
  this.defaultModelOptions.restore(snapshot.defaultModelOptions);
2274
+ for (const name of Object.keys(this.modelOptionOverrides)) delete this.modelOptionOverrides[name];
2275
+ for (const [name, options] of Object.entries(snapshot.modelOptionOverrides)) {
2276
+ this.modelOptionOverrides[name] = modelOverrides(options);
2277
+ }
2192
2278
  for (const name of Object.keys(this.modelOptions)) {
2193
2279
  if (!(name in snapshot.modelOptions)) {
2194
2280
  delete this.modelOptions[name];
@@ -2199,8 +2285,7 @@ var AccessRuntime = class {
2199
2285
  if (existing) {
2200
2286
  existing.restore(opts);
2201
2287
  } else {
2202
- const mgr = this.createModelOptions(name);
2203
- mgr.restore(opts);
2288
+ const mgr = this.createModelOptions(name, opts);
2204
2289
  this.modelOptions[name] = mgr;
2205
2290
  }
2206
2291
  }
@@ -2243,18 +2328,11 @@ var AccessRuntime = class {
2243
2328
  }
2244
2329
  /** Shallowly replace supplied global values; nested objects such as requestComplexity are not deep-merged. */
2245
2330
  setGlobalOptions(options) {
2246
- const next = { ...options };
2247
- if ("requireOperationAccessForPopulateQueries" in next)
2248
- next.requireOperationAccessForPopulateQueries = next.requireOperationAccessForPopulateQueries !== false;
2249
- if ("requireOperationAccessForPopulateDependencies" in next)
2250
- next.requireOperationAccessForPopulateDependencies = next.requireOperationAccessForPopulateDependencies !== false;
2251
- this.globalOptions.assign(next);
2331
+ for (const key of populatePolicyKeys) if (key in options) assertNoGlobalPopulatePolicy(key);
2332
+ this.globalOptions.assign({ ...options });
2252
2333
  }
2253
2334
  setGlobalOption(key, value) {
2254
- if (key === "requireOperationAccessForPopulateQueries" || key === "requireOperationAccessForPopulateDependencies") {
2255
- this.globalOptions.set(key, value !== false);
2256
- return;
2257
- }
2335
+ assertNoGlobalPopulatePolicy(String(key));
2258
2336
  this.globalOptions.set(key, value);
2259
2337
  }
2260
2338
  getGlobalOptions() {
@@ -2263,28 +2341,30 @@ var AccessRuntime = class {
2263
2341
  getGlobalOption(key, defaultValue) {
2264
2342
  return this.globalOptions.get(key, defaultValue);
2265
2343
  }
2266
- /** Update model starting defaults shallowly; already-stored model values are not broadcast-replaced. */
2344
+ /** Update inherited model defaults shallowly. Explicit model values and captured calls are unchanged. */
2267
2345
  setDefaultModelOptions(options) {
2268
2346
  assertPublicDefaults(options.defaults);
2269
2347
  if ("hydration" in options) options = { ...options, hydration: normalizeHydration(options.hydration) };
2270
- this.defaultModelOptions.assign(options);
2348
+ const draft = new OptionsManager(
2349
+ this.getDefaultModelOptions()
2350
+ ).build();
2351
+ draft.assign(normalizePopulatePolicyOptions(options));
2352
+ this.publishDefaultModelOptions(draft.fetch());
2271
2353
  }
2272
2354
  setDefaultModelOption(key, value) {
2273
2355
  const keyStr = String(key);
2274
- if (keyStr === "hydration" || keyStr.startsWith("hydration.")) {
2275
- this.defaultModelOptions.set(
2276
- "hydration",
2277
- normalizeHydrationUpdate(this.getDefaultModelOptions().hydration, keyStr, value)
2278
- );
2279
- return;
2280
- }
2281
- if (keyStr === "defaults") assertPublicDefaults(value);
2282
- else if (keyStr.startsWith("defaults.")) {
2283
- const proposed = {};
2284
- (0, import_utils13.set)(proposed, keyStr.slice("defaults.".length), value);
2285
- assertPublicDefaults(proposed);
2356
+ const draft = new OptionsManager(
2357
+ this.getDefaultModelOptions()
2358
+ ).build();
2359
+ if (isPopulatePolicyKey(keyStr)) {
2360
+ draft.set(keyStr, normalizePopulatePolicyValue(value));
2361
+ } else if (keyStr === "hydration" || keyStr.startsWith("hydration.")) {
2362
+ draft.set("hydration", normalizeHydrationUpdate(this.getDefaultModelOptions().hydration, keyStr, value));
2363
+ } else {
2364
+ draft.set(key, value);
2286
2365
  }
2287
- this.defaultModelOptions.set(key, value);
2366
+ assertPublicDefaults(draft.fetch().defaults);
2367
+ this.publishDefaultModelOptions(draft.fetch());
2288
2368
  }
2289
2369
  getDefaultModelOptions() {
2290
2370
  return this.defaultModelOptions.fetch();
@@ -2292,30 +2372,103 @@ var AccessRuntime = class {
2292
2372
  getDefaultModelOption(key, defaultValue) {
2293
2373
  return this.defaultModelOptions.get(key, defaultValue);
2294
2374
  }
2295
- createModelOptions(modelName) {
2375
+ resolveModelOptions(modelName, overrides = this.modelOptionOverrides[modelName] ?? {}, defaults2 = this.getDefaultModelOptions()) {
2376
+ const inherited = { ...defaults2 };
2377
+ for (const key of populatePolicyKeys) delete inherited[key];
2378
+ const effective = { ...defaultModelOptions, ...inherited, ...overrides, modelName };
2379
+ effective.basePath = normalizeBasePath(modelName, effective.basePath);
2380
+ for (const key of unsafeSnapshotOptions) effective[key] = effective[key] === true;
2381
+ refreshPermissionMetadata(effective);
2382
+ return cloneOptionsSnapshot(effective);
2383
+ }
2384
+ validateModelOptions(modelName, options, proposed) {
2385
+ validateVirtualsTree(
2386
+ this.getModelInstance(modelName),
2387
+ options.virtuals,
2388
+ options.documentPermissionField ?? "_permissions",
2389
+ modelName
2390
+ );
2391
+ captureVirtualPopulateDependencies(this, modelName, options, void 0, proposed);
2392
+ }
2393
+ publishDefaultModelOptions(options) {
2394
+ const next = { ...options };
2395
+ for (const key of unsafeSnapshotOptions) if (key in next) next[key] = next[key] === true;
2396
+ const defaults2 = cloneOptionsSnapshot(next);
2397
+ const models = new Map(
2398
+ Object.keys(this.modelOptions).map((name) => [name, this.resolveModelOptions(name, void 0, defaults2)])
2399
+ );
2400
+ for (const [name, options2] of models) this.validateModelOptions(name, options2, { defaults: defaults2, models });
2401
+ this.deferSnapshotWarnings(() => {
2402
+ this.defaultModelOptions.restore(defaults2);
2403
+ for (const [name, options2] of models) this.modelOptions[name].restore(options2);
2404
+ });
2405
+ }
2406
+ warnSnapshotFlag(modelName, key) {
2407
+ if (this.pendingSnapshotWarnings) {
2408
+ this.pendingSnapshotWarnings.push({ modelName, key });
2409
+ return;
2410
+ }
2411
+ const operation = key.startsWith("unsafeSkipRead") ? "read" : "list";
2412
+ const category = key.includes("NestedDocument") ? "nested-document" : key.includes("Output") ? "output" : "document";
2413
+ const risk = category === "output" ? "output mutation" : "source mutation";
2414
+ try {
2415
+ this.getGlobalOption("logger")?.warn?.(
2416
+ `UNSAFE: ${operation} ${category} snapshot checks disabled; ${risk} can leave stale authorization decisions. Restore ${key}=false after the temporary workaround.`,
2417
+ { modelName }
2418
+ );
2419
+ } catch {
2420
+ }
2421
+ }
2422
+ deferSnapshotWarnings(publish) {
2423
+ if (this.pendingSnapshotWarnings) return publish();
2424
+ const copyModes = this.initialOutputCopyModes();
2425
+ const pending = [];
2426
+ this.pendingSnapshotWarnings = pending;
2427
+ let result;
2428
+ try {
2429
+ result = publish();
2430
+ } finally {
2431
+ this.pendingSnapshotWarnings = void 0;
2432
+ }
2433
+ const nextCopyModes = this.initialOutputCopyModes();
2434
+ for (const { modelName, key } of pending) this.warnSnapshotFlag(modelName, key);
2435
+ for (const [modelName, modes] of nextCopyModes) {
2436
+ for (const operation of ["List", "Read"]) {
2437
+ const mode = modes[operation];
2438
+ if (mode === "off" || mode === copyModes.get(modelName)?.[operation]) continue;
2439
+ const key = `unsafeSkip${operation}InitialOutputSnapshotCopy`;
2440
+ const prerequisite = `unsafeSkip${operation}OutputSnapshotChecks`;
2441
+ try {
2442
+ this.getGlobalOption("logger")?.warn?.(
2443
+ mode === "active" ? `UNSAFE: ${operation.toLowerCase()} initial output snapshot copying disabled for eligible graphs; omitted native normalization/validation can change side effects and authorization outcomes. Restore ${key}=false after the temporary workaround.` : `UNSAFE: ${key} is dormant; requires ${prerequisite}=true. Initial copying and output comparisons remain enabled. Restore ${key}=false if not intended.`,
2444
+ { modelName }
2445
+ );
2446
+ } catch {
2447
+ }
2448
+ }
2449
+ }
2450
+ return result;
2451
+ }
2452
+ initialOutputCopyModes() {
2453
+ return new Map(
2454
+ Object.entries(this.modelOptions).map(([modelName, options]) => {
2455
+ const mode = (operation) => options.get(`unsafeSkip${operation}InitialOutputSnapshotCopy`) !== true ? "off" : options.get(`unsafeSkip${operation}OutputSnapshotChecks`) === true ? "active" : "dormant";
2456
+ return [modelName, { List: mode("List"), Read: mode("Read") }];
2457
+ })
2458
+ );
2459
+ }
2460
+ createModelOptions(modelName, options = this.resolveModelOptions(modelName)) {
2296
2461
  const model = this.getModelInstance(modelName);
2297
2462
  if (!model) {
2298
2463
  throw new Error(
2299
2464
  `Runtime model registry missing model "${modelName}". Pass a mongoose.Model instance to createRouter() or register it with registerModelInstance() before using this isolated runtime.`
2300
2465
  );
2301
2466
  }
2302
- const manager = new OptionsManager({
2303
- ...defaultModelOptions,
2304
- modelName
2305
- });
2467
+ const manager = new OptionsManager(options);
2306
2468
  const snapshotFlagChanged = (newValue, key, target, oldValue) => {
2307
2469
  target[key] = newValue === true;
2308
2470
  if (newValue !== true || oldValue === true) return;
2309
- const operation = key.startsWith("unsafeSkipRead") ? "read" : "list";
2310
- const category = key.includes("NestedDocument") ? "nested-document" : key.includes("Output") ? "output" : "document";
2311
- const risk = category === "output" ? "output mutation" : "source mutation";
2312
- try {
2313
- this.getGlobalOption("logger")?.warn?.(
2314
- `UNSAFE: ${operation} ${category} snapshot checks disabled; ${risk} can leave stale authorization decisions. Restore ${key}=false after the temporary workaround.`,
2315
- { modelName }
2316
- );
2317
- } catch {
2318
- }
2471
+ this.warnSnapshotFlag(modelName, key);
2319
2472
  };
2320
2473
  manager.onchange("permissionSchema", function(_newval, _key, target) {
2321
2474
  refreshPermissionMetadata(target);
@@ -2333,13 +2486,17 @@ var AccessRuntime = class {
2333
2486
  getOrCreateModelOptions(modelName) {
2334
2487
  let manager = this.modelOptions[modelName];
2335
2488
  if (!manager) {
2336
- manager = this.createModelOptions(modelName);
2337
- this.modelOptions[modelName] = manager;
2489
+ manager = this.deferSnapshotWarnings(() => {
2490
+ const created = this.createModelOptions(modelName);
2491
+ this.modelOptions[modelName] = created;
2492
+ return created;
2493
+ });
2338
2494
  }
2339
2495
  return manager;
2340
2496
  }
2341
2497
  /**
2342
- * Assign `{ ...modelDefaults, ...storedOptions, ...options }` shallowly. A supplied
2498
+ * Update explicit model overrides shallowly; undefined restores default inheritance
2499
+ * (operationAccess preserves its existing exact-key-only default fallback). A supplied
2343
2500
  * operationAccess/defaults object replaces that whole value. Defaults accept only
2344
2501
  * query/presentation settings; virtual configuration is validated before assignment.
2345
2502
  * Existing router.options remains its construction-time snapshot. Fresh model-service
@@ -2347,22 +2504,23 @@ var AccessRuntime = class {
2347
2504
  */
2348
2505
  setModelOptions(modelName, options) {
2349
2506
  assertPublicDefaults(options.defaults);
2507
+ options = normalizePopulatePolicyOptions(options);
2350
2508
  if ("hydration" in options) options = { ...options, hydration: normalizeHydration(options.hydration) };
2351
- const defaultOptions = this.getDefaultModelOptions();
2352
- const currentModelOptions = this.modelOptions[modelName]?.fetch() ?? { ...defaultModelOptions, modelName };
2353
- const merged = { ...defaultOptions, ...currentModelOptions, ...options };
2354
- const model = this.getModelInstance(modelName);
2355
- const permissionField = merged.documentPermissionField ?? currentModelOptions.documentPermissionField ?? this.getDefaultModelOption("documentPermissionField") ?? "_permissions";
2356
- validateVirtualsTree(model, merged.virtuals, permissionField, modelName);
2357
- captureVirtualPopulateDependencies(this, modelName, merged);
2358
- const manager = this.getOrCreateModelOptions(modelName);
2359
- manager.assign({ ...defaultOptions, ...currentModelOptions, ...options });
2509
+ const overrides = modelOverrides({ ...this.modelOptionOverrides[modelName], ...options });
2510
+ const effective = this.resolveModelOptions(modelName, overrides);
2511
+ this.validateModelOptions(modelName, effective);
2512
+ this.deferSnapshotWarnings(() => {
2513
+ const manager = this.modelOptions[modelName];
2514
+ if (manager) manager.restore(effective);
2515
+ else this.modelOptions[modelName] = this.createModelOptions(modelName, effective);
2516
+ this.modelOptionOverrides[modelName] = overrides;
2517
+ });
2360
2518
  }
2361
2519
  setModelOption(modelName, key, value) {
2362
2520
  const keyStr = String(key);
2363
2521
  if (keyStr === "hydration" || keyStr.startsWith("hydration.")) {
2364
- const hydration = normalizeHydrationUpdate(this.modelOptions[modelName]?.get("hydration"), keyStr, value);
2365
- this.getOrCreateModelOptions(modelName).set("hydration", hydration);
2522
+ const hydration = normalizeHydrationUpdate(this.resolveModelOptions(modelName).hydration, keyStr, value);
2523
+ this.setModelOptions(modelName, { hydration });
2366
2524
  return;
2367
2525
  }
2368
2526
  if (keyStr === "defaults") assertPublicDefaults(value);
@@ -2371,47 +2529,20 @@ var AccessRuntime = class {
2371
2529
  (0, import_utils13.set)(proposed, keyStr.slice("defaults.".length), value);
2372
2530
  assertPublicDefaults(proposed);
2373
2531
  }
2374
- const manager = this.modelOptions[modelName];
2375
- if (keyStr === "virtuals" || keyStr.startsWith("virtuals.") || keyStr === "documentPermissionField") {
2376
- const model = this.getModelInstance(modelName);
2377
- const currentVirtuals = manager?.get("virtuals");
2378
- const currentPermissionField = manager?.get("documentPermissionField") ?? this.getDefaultModelOption("documentPermissionField") ?? "_permissions";
2379
- let proposedVirtuals = currentVirtuals;
2380
- let proposedPermissionField = currentPermissionField;
2381
- if (keyStr === "documentPermissionField") {
2382
- proposedPermissionField = value;
2383
- } else if (keyStr === "virtuals") {
2384
- proposedVirtuals = value;
2385
- } else {
2386
- const cloned = cloneVirtualsForValidation(currentVirtuals ?? {});
2387
- const nestedPath = keyStr.slice("virtuals.".length);
2388
- if (value === void 0) {
2389
- const segments = nestedPath.split(".");
2390
- let cursor = cloned;
2391
- for (let i = 0; i < segments.length - 1; i++) {
2392
- if (!(0, import_utils13.isPlainObject)(cursor)) break;
2393
- cursor = cursor[segments[i]];
2394
- }
2395
- if ((0, import_utils13.isPlainObject)(cursor)) {
2396
- delete cursor[segments[segments.length - 1]];
2397
- }
2398
- proposedVirtuals = cloned;
2399
- } else {
2400
- (0, import_utils13.set)(cloned, nestedPath, value);
2401
- proposedVirtuals = cloned;
2402
- }
2403
- }
2404
- validateVirtualsTree(model, proposedVirtuals, proposedPermissionField, modelName);
2405
- captureVirtualPopulateDependencies(this, modelName, {
2406
- ...this.getDefaultModelOptions(),
2407
- ...manager?.fetch(),
2408
- virtuals: proposedVirtuals,
2409
- documentPermissionField: proposedPermissionField
2410
- });
2532
+ const [root, ...path] = keyStr.split(".");
2533
+ if (!path.length) {
2534
+ this.setModelOptions(modelName, { [root]: value });
2535
+ return;
2411
2536
  }
2412
- this.getOrCreateModelOptions(modelName).set(key, value);
2413
- }
2414
- /** Frozen stored snapshot, not fully resolved per-path defaults. Read again for current configuration. */
2537
+ const current = this.resolveModelOptions(modelName);
2538
+ const nested = cloneModelOptionForUpdate((0, import_utils13.isPlainObject)(current[root]) ? current[root] : {});
2539
+ if (root === "virtuals" && value === void 0) {
2540
+ const parent = path.length === 1 ? nested : (0, import_utils13.get)(nested, path.slice(0, -1));
2541
+ if ((0, import_utils13.isPlainObject)(parent)) delete parent[path[path.length - 1]];
2542
+ } else (0, import_utils13.set)(nested, path, value);
2543
+ this.setModelOptions(modelName, { [root]: nested });
2544
+ }
2545
+ /** Frozen model/default snapshot; populate flags remain raw overrides. Read again for current values. */
2415
2546
  getModelOptions(modelName) {
2416
2547
  const manager = this.getOrCreateModelOptions(modelName);
2417
2548
  return manager.fetch();
@@ -2576,13 +2707,6 @@ var AccessRuntime = class {
2576
2707
  };
2577
2708
  var defaultRuntime = new AccessRuntime({ allowGlobalModelLookup: true });
2578
2709
 
2579
- // src/runtime-context.ts
2580
- var import_node_async_hooks = require("async_hooks");
2581
- var runtimeStorage = new import_node_async_hooks.AsyncLocalStorage();
2582
- function getActiveRuntime() {
2583
- return runtimeStorage.getStore() ?? null;
2584
- }
2585
-
2586
2710
  // src/options/global-options.ts
2587
2711
  var getRuntime = () => getActiveRuntime() ?? defaultRuntime;
2588
2712
  var getGlobalOption = (key, defaultValue) => {