@web-ts-toolkit/access-router 0.60.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.js CHANGED
@@ -131,6 +131,23 @@ var import_mongoose3 = __toESM(require("mongoose"));
131
131
  // src/validation/public-admission.ts
132
132
  var import_express_json_router = __toESM(require("@web-ts-toolkit/express-json-router"));
133
133
  var import_utils = require("@web-ts-toolkit/utils");
134
+
135
+ // src/acl/unsafe-snapshot-options.ts
136
+ var unsafeSnapshotCheckOptions = [
137
+ "unsafeSkipListDocumentSnapshotChecks",
138
+ "unsafeSkipReadDocumentSnapshotChecks",
139
+ "unsafeSkipListOutputSnapshotChecks",
140
+ "unsafeSkipReadOutputSnapshotChecks",
141
+ "unsafeSkipListNestedDocumentSnapshotChecks",
142
+ "unsafeSkipReadNestedDocumentSnapshotChecks"
143
+ ];
144
+ var unsafeInitialOutputCopyOptions = [
145
+ "unsafeSkipListInitialOutputSnapshotCopy",
146
+ "unsafeSkipReadInitialOutputSnapshotCopy"
147
+ ];
148
+ var unsafeSnapshotOptions = [...unsafeSnapshotCheckOptions, ...unsafeInitialOutputCopyOptions];
149
+
150
+ // src/validation/public-admission.ts
134
151
  var privateControls = [
135
152
  "authorization",
136
153
  "overrides",
@@ -139,6 +156,7 @@ var privateControls = [
139
156
  "execution",
140
157
  "executionContext",
141
158
  "serviceExecutionContext",
159
+ "snapshotDerivation",
142
160
  "resolvedAuthorization",
143
161
  "preparedQuery",
144
162
  "preparedFilter",
@@ -147,8 +165,7 @@ var privateControls = [
147
165
  "skipParsing",
148
166
  "skipAuthorization",
149
167
  "alreadyAuthorized",
150
- "unsafeSkipListDocumentSnapshotChecks",
151
- "unsafeSkipReadDocumentSnapshotChecks",
168
+ ...unsafeSnapshotOptions,
152
169
  "operation"
153
170
  ];
154
171
  var PublicAdmissionError = class extends import_express_json_router.default.clientErrors.BadRequestError {
@@ -176,7 +193,7 @@ function assertPublicAdmission(input, kind = "envelope") {
176
193
  for (const key of privateControls) {
177
194
  if (key in record2) {
178
195
  throw new PublicAdmissionError(
179
- key === "unsafeSkipListDocumentSnapshotChecks" || key === "unsafeSkipReadDocumentSnapshotChecks" ? `Unsupported public control ${path}.${key}; this unsafe flag is server model configuration only` : `Unsupported public control ${path}.${key}; use explicit per-call internal service options for backend authorization`
196
+ key.startsWith("unsafeSkip") ? `Unsupported public control ${path}.${key}; this unsafe flag is server model configuration only` : `Unsupported public control ${path}.${key}; use explicit per-call internal service options for backend authorization`
180
197
  );
181
198
  }
182
199
  }
@@ -196,9 +213,9 @@ function assertPublicAdmission(input, kind = "envelope") {
196
213
  for (const key of ["filter", "match", "data"]) add(record2[key], "data", key);
197
214
  }
198
215
  }
199
- function assertHydrationDefaults(defaults) {
200
- if (defaults && typeof defaults === "object") {
201
- const record2 = defaults;
216
+ function assertHydrationDefaults(defaults2) {
217
+ if (defaults2 && typeof defaults2 === "object") {
218
+ const record2 = defaults2;
202
219
  if ("hydration" in record2)
203
220
  throw new TypeError("defaults.hydration is unsupported; use model hydration configuration");
204
221
  for (const bucket of [
@@ -226,11 +243,11 @@ function assertHydrationDefaults(defaults) {
226
243
  }
227
244
  }
228
245
  }
229
- function assertPublicDefaults(defaults) {
230
- assertHydrationDefaults(defaults);
231
- assertPublicAdmission(defaults);
232
- if (defaults && typeof defaults === "object") {
233
- 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);
234
251
  }
235
252
  }
236
253
  var requestAuthorization = Object.freeze({ outputFields: Object.freeze({ mode: "request" }) });
@@ -260,6 +277,32 @@ function normalizeHydrationUpdate(current, key, value) {
260
277
  return normalizeHydration({ ...normalizeHydration(current), [method]: value });
261
278
  }
262
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
+
263
306
  // src/runtime.ts
264
307
  var import_mongoose_schema_jsonschema = __toESM(require("mongoose-schema-jsonschema"));
265
308
  var import_utils13 = require("@web-ts-toolkit/utils");
@@ -753,6 +796,7 @@ var freezeConfigValue = (value) => {
753
796
  return value;
754
797
  };
755
798
  var cloneAndFreezeForStore = (value) => freezeConfigValue(cloneForRead(value));
799
+ var cloneOptionsSnapshot = (value) => freezeConfigValue(cloneForRead(value));
756
800
  var getNestedOption = (manager, key, defaultValue) => resolveNestedOption((path, fallback) => manager.get(path, fallback), String(key), defaultValue);
757
801
  var resolveNestedOption = (read, key, defaultValue) => {
758
802
  const keys2 = key.split(".");
@@ -1243,6 +1287,7 @@ var import_utils12 = require("@web-ts-toolkit/utils");
1243
1287
 
1244
1288
  // src/acl/authorization-snapshot.ts
1245
1289
  var import_node_util3 = require("util");
1290
+ var import_node_buffer = require("buffer");
1246
1291
  var import_mongoose2 = require("mongoose");
1247
1292
  var import_express_json_router2 = __toESM(require("@web-ts-toolkit/express-json-router"));
1248
1293
  var ServiceAuthorizationError = class extends import_express_json_router2.default.clientErrors.BadRequestError {
@@ -1349,6 +1394,9 @@ function isSafeInputPath(path, requestIdentity = false) {
1349
1394
  return isSafeOutputPath(path) && path.split(".").every((part) => !inputControlSegments.has(part) && (requestIdentity || part !== "_id"));
1350
1395
  }
1351
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
+ }
1352
1400
  const expected = pattern.split(".");
1353
1401
  const actual = path.split(".");
1354
1402
  return (descendants ? actual.length >= expected.length : actual.length === expected.length) && expected.every((part, index) => part === "$*" || part === actual[index]);
@@ -1449,7 +1497,16 @@ function captureAuthorizationFieldCatalog(schema, virtuals, documentPermissionFi
1449
1497
 
1450
1498
  // src/acl/populate-target-configuration.ts
1451
1499
  var import_utils11 = require("@web-ts-toolkit/utils");
1452
- 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()) {
1453
1510
  const label = `Populate target "${modelName}" for ${source}`;
1454
1511
  if (!proposedOptions && !runtime.hasModel(modelName))
1455
1512
  authorizationError(
@@ -1458,7 +1515,7 @@ function capturePopulateTargetConfiguration(runtime, modelName, source, proposed
1458
1515
  const model = runtime.getModelInstance(modelName);
1459
1516
  if (!model) authorizationError(`${label} requires an actual registered Mongoose model in this runtime`);
1460
1517
  const options = proposedOptions ?? runtime.getModelOptions(modelName);
1461
- const permissionSchema = options.permissionSchema === void 0 ? runtime.getDefaultModelOption("permissionSchema") : options.permissionSchema;
1518
+ const permissionSchema = options.permissionSchema === void 0 ? defaults2.permissionSchema : options.permissionSchema;
1462
1519
  if (!(0, import_utils11.isPlainObject)(permissionSchema))
1463
1520
  authorizationError(
1464
1521
  `${label} requires an effective object permissionSchema; configure the model or runtime model defaults ({} explicitly closes business fields)`
@@ -1466,6 +1523,31 @@ function capturePopulateTargetConfiguration(runtime, modelName, source, proposed
1466
1523
  return { model, options: { ...options, permissionSchema } };
1467
1524
  }
1468
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
+
1469
1551
  // src/acl/virtual-populate-dependencies.ts
1470
1552
  var elementType = (type) => type.$embeddedSchemaType ?? type.embeddedSchemaType ?? type.caster;
1471
1553
  var join = (prefix, path) => prefix ? `${prefix}.${path}` : path;
@@ -1565,9 +1647,7 @@ function normalizeSelection(select, catalog, label) {
1565
1647
  includeId: selection.includes("_id")
1566
1648
  };
1567
1649
  }
1568
- function captureVirtualPopulateDependencies(runtime, modelName, options, globalOptions = runtime.getGlobalOptions()) {
1569
- const requireOperationAccessForPopulateDependencies = globalOptions.requireOperationAccessForPopulateDependencies !== false;
1570
- const requireOperationAccessForPopulateQueries = globalOptions.requireOperationAccessForPopulateQueries !== false;
1650
+ function captureVirtualPopulateDependencies(runtime, modelName, options, populatePolicyDefaults = capturePopulatePolicyDefaults(runtime), proposed) {
1571
1651
  const model = runtime.getModelInstance(modelName);
1572
1652
  const targets = /* @__PURE__ */ new Map();
1573
1653
  const scopes = [];
@@ -1611,18 +1691,19 @@ function captureVirtualPopulateDependencies(runtime, modelName, options, globalO
1611
1691
  runtime,
1612
1692
  ref,
1613
1693
  `dependsOnPopulate virtual "${label}"`,
1614
- ref === modelName ? options : void 0
1694
+ ref === modelName ? options : proposed?.models.get(ref),
1695
+ proposed?.defaults
1615
1696
  );
1616
- const defaults = runtime.getDefaultModelOptions();
1617
- const readOption = (key) => resolveNestedOption((path2, fallback) => (0, import_utils12.get)(targetOptions, path2, fallback), key, (0, import_utils12.get)(defaults, key));
1618
- 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;
1619
1700
  const catalog = captureAuthorizationFieldCatalog(targetModel.schema, void 0, documentPermissionField);
1620
1701
  const configuration = copyAuthorizationValue(
1621
1702
  {
1622
1703
  catalog,
1623
1704
  documentPermissionField,
1624
- requireOperationAccessForPopulateDependencies,
1625
- requireOperationAccessForPopulateQueries,
1705
+ populatePolicyDefaults,
1706
+ ...resolvePopulatePolicy(targetOptions, populatePolicyDefaults),
1626
1707
  permissionSchema: targetOptions.permissionSchema,
1627
1708
  operationAccess: { read: readOption("operationAccess.read") },
1628
1709
  baseFilter: { read: readOption("baseFilter.read") },
@@ -1717,6 +1798,15 @@ var defaultModelOptions = {
1717
1798
  basePath: null,
1718
1799
  alwaysSelectFields: []
1719
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
+ };
1720
1810
  var defaultDataOptions = {
1721
1811
  basePath: null,
1722
1812
  parentPath: "/",
@@ -1850,12 +1940,12 @@ var getNestedChildFields = (parentSchema, fieldName) => {
1850
1940
  }
1851
1941
  return fields;
1852
1942
  };
1853
- var cloneVirtualsForValidation = (value) => {
1854
- 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));
1855
1945
  if (!value || typeof value !== "object") return value;
1856
1946
  if (Object.getPrototypeOf(value) !== Object.prototype) return value;
1857
1947
  return Object.fromEntries(
1858
- Object.entries(value).map(([k, v]) => [k, cloneVirtualsForValidation(v)])
1948
+ Object.entries(value).map(([k, v]) => [k, cloneModelOptionForUpdate(v)])
1859
1949
  );
1860
1950
  };
1861
1951
  var validateVirtualDependsOn = (dependsOn, entryLabel, storedFields, siblingVirtualNames) => {
@@ -2051,8 +2141,6 @@ var AccessRuntime = class {
2051
2141
  {
2052
2142
  requestPermissionField: "_permissions",
2053
2143
  globalPermissions: () => ({}),
2054
- requireOperationAccessForPopulateQueries: true,
2055
- requireOperationAccessForPopulateDependencies: true,
2056
2144
  logger: defaultLogger,
2057
2145
  requestComplexity: defaultRequestComplexity
2058
2146
  },
@@ -2067,11 +2155,20 @@ var AccessRuntime = class {
2067
2155
  queryRouteSegment: "__query",
2068
2156
  mutationRouteSegment: "__mutation",
2069
2157
  operationAccess: false,
2158
+ requireOperationAccessForPopulateQueries: true,
2159
+ requireOperationAccessForPopulateDependencies: true,
2070
2160
  modelPermissionPrefix: "",
2071
2161
  unsafeSkipListDocumentSnapshotChecks: false,
2072
- unsafeSkipReadDocumentSnapshotChecks: false
2162
+ unsafeSkipReadDocumentSnapshotChecks: false,
2163
+ unsafeSkipListOutputSnapshotChecks: false,
2164
+ unsafeSkipReadOutputSnapshotChecks: false,
2165
+ unsafeSkipListNestedDocumentSnapshotChecks: false,
2166
+ unsafeSkipReadNestedDocumentSnapshotChecks: false,
2167
+ unsafeSkipListInitialOutputSnapshotCopy: false,
2168
+ unsafeSkipReadInitialOutputSnapshotCopy: false
2073
2169
  }).build();
2074
2170
  this.modelOptions = {};
2171
+ this.modelOptionOverrides = {};
2075
2172
  this.modelJsonSchemas = {};
2076
2173
  this.dataOptions = {};
2077
2174
  this.modelRefs = {};
@@ -2159,6 +2256,7 @@ var AccessRuntime = class {
2159
2256
  globalOptions: this.globalOptions.snapshot(),
2160
2257
  defaultModelOptions: this.defaultModelOptions.snapshot(),
2161
2258
  modelOptions: modelOptionsSnap,
2259
+ modelOptionOverrides: { ...this.modelOptionOverrides },
2162
2260
  dataOptions: dataOptionsSnap,
2163
2261
  modelInstances: { ...this.modelInstances },
2164
2262
  modelJsonSchemas: { ...this.modelJsonSchemas },
@@ -2173,6 +2271,10 @@ var AccessRuntime = class {
2173
2271
  restoreBootstrapSnapshot(snapshot) {
2174
2272
  this.globalOptions.restore(snapshot.globalOptions);
2175
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
+ }
2176
2278
  for (const name of Object.keys(this.modelOptions)) {
2177
2279
  if (!(name in snapshot.modelOptions)) {
2178
2280
  delete this.modelOptions[name];
@@ -2183,8 +2285,7 @@ var AccessRuntime = class {
2183
2285
  if (existing) {
2184
2286
  existing.restore(opts);
2185
2287
  } else {
2186
- const mgr = this.createModelOptions(name);
2187
- mgr.restore(opts);
2288
+ const mgr = this.createModelOptions(name, opts);
2188
2289
  this.modelOptions[name] = mgr;
2189
2290
  }
2190
2291
  }
@@ -2227,18 +2328,11 @@ var AccessRuntime = class {
2227
2328
  }
2228
2329
  /** Shallowly replace supplied global values; nested objects such as requestComplexity are not deep-merged. */
2229
2330
  setGlobalOptions(options) {
2230
- const next = { ...options };
2231
- if ("requireOperationAccessForPopulateQueries" in next)
2232
- next.requireOperationAccessForPopulateQueries = next.requireOperationAccessForPopulateQueries !== false;
2233
- if ("requireOperationAccessForPopulateDependencies" in next)
2234
- next.requireOperationAccessForPopulateDependencies = next.requireOperationAccessForPopulateDependencies !== false;
2235
- this.globalOptions.assign(next);
2331
+ for (const key of populatePolicyKeys) if (key in options) assertNoGlobalPopulatePolicy(key);
2332
+ this.globalOptions.assign({ ...options });
2236
2333
  }
2237
2334
  setGlobalOption(key, value) {
2238
- if (key === "requireOperationAccessForPopulateQueries" || key === "requireOperationAccessForPopulateDependencies") {
2239
- this.globalOptions.set(key, value !== false);
2240
- return;
2241
- }
2335
+ assertNoGlobalPopulatePolicy(String(key));
2242
2336
  this.globalOptions.set(key, value);
2243
2337
  }
2244
2338
  getGlobalOptions() {
@@ -2247,28 +2341,30 @@ var AccessRuntime = class {
2247
2341
  getGlobalOption(key, defaultValue) {
2248
2342
  return this.globalOptions.get(key, defaultValue);
2249
2343
  }
2250
- /** 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. */
2251
2345
  setDefaultModelOptions(options) {
2252
2346
  assertPublicDefaults(options.defaults);
2253
2347
  if ("hydration" in options) options = { ...options, hydration: normalizeHydration(options.hydration) };
2254
- this.defaultModelOptions.assign(options);
2348
+ const draft = new OptionsManager(
2349
+ this.getDefaultModelOptions()
2350
+ ).build();
2351
+ draft.assign(normalizePopulatePolicyOptions(options));
2352
+ this.publishDefaultModelOptions(draft.fetch());
2255
2353
  }
2256
2354
  setDefaultModelOption(key, value) {
2257
2355
  const keyStr = String(key);
2258
- if (keyStr === "hydration" || keyStr.startsWith("hydration.")) {
2259
- this.defaultModelOptions.set(
2260
- "hydration",
2261
- normalizeHydrationUpdate(this.getDefaultModelOptions().hydration, keyStr, value)
2262
- );
2263
- return;
2264
- }
2265
- if (keyStr === "defaults") assertPublicDefaults(value);
2266
- else if (keyStr.startsWith("defaults.")) {
2267
- const proposed = {};
2268
- (0, import_utils13.set)(proposed, keyStr.slice("defaults.".length), value);
2269
- 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);
2270
2365
  }
2271
- this.defaultModelOptions.set(key, value);
2366
+ assertPublicDefaults(draft.fetch().defaults);
2367
+ this.publishDefaultModelOptions(draft.fetch());
2272
2368
  }
2273
2369
  getDefaultModelOptions() {
2274
2370
  return this.defaultModelOptions.fetch();
@@ -2276,34 +2372,109 @@ var AccessRuntime = class {
2276
2372
  getDefaultModelOption(key, defaultValue) {
2277
2373
  return this.defaultModelOptions.get(key, defaultValue);
2278
2374
  }
2279
- 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)) {
2280
2461
  const model = this.getModelInstance(modelName);
2281
2462
  if (!model) {
2282
2463
  throw new Error(
2283
2464
  `Runtime model registry missing model "${modelName}". Pass a mongoose.Model instance to createRouter() or register it with registerModelInstance() before using this isolated runtime.`
2284
2465
  );
2285
2466
  }
2286
- const manager = new OptionsManager({
2287
- ...defaultModelOptions,
2288
- modelName
2289
- });
2467
+ const manager = new OptionsManager(options);
2290
2468
  const snapshotFlagChanged = (newValue, key, target, oldValue) => {
2291
2469
  target[key] = newValue === true;
2292
2470
  if (newValue !== true || oldValue === true) return;
2293
- const operation = key === "unsafeSkipReadDocumentSnapshotChecks" ? "read" : "list";
2294
- try {
2295
- this.getGlobalOption("logger")?.warn?.(
2296
- `UNSAFE: ${operation} document snapshot checks disabled; source mutation can leave stale authorization decisions. Restore ${key}=false after the temporary workaround.`,
2297
- { modelName }
2298
- );
2299
- } catch {
2300
- }
2471
+ this.warnSnapshotFlag(modelName, key);
2301
2472
  };
2302
2473
  manager.onchange("permissionSchema", function(_newval, _key, target) {
2303
2474
  refreshPermissionMetadata(target);
2304
2475
  }).onchange("modelPermissionPrefix", function(_newval, _key, target) {
2305
2476
  refreshPermissionMetadata(target);
2306
- }).onchange("unsafeSkipListDocumentSnapshotChecks", snapshotFlagChanged).onchange("unsafeSkipReadDocumentSnapshotChecks", snapshotFlagChanged).onchange("basePath", function(newval, key, target) {
2477
+ }).onchange("unsafeSkipListDocumentSnapshotChecks", snapshotFlagChanged).onchange("unsafeSkipReadDocumentSnapshotChecks", snapshotFlagChanged).onchange("unsafeSkipListOutputSnapshotChecks", snapshotFlagChanged).onchange("unsafeSkipReadOutputSnapshotChecks", snapshotFlagChanged).onchange("unsafeSkipListNestedDocumentSnapshotChecks", snapshotFlagChanged).onchange("unsafeSkipReadNestedDocumentSnapshotChecks", snapshotFlagChanged).onchange("basePath", function(newval, key, target) {
2307
2478
  target[key] = normalizeBasePath(
2308
2479
  modelName,
2309
2480
  (0, import_utils13.isString)(newval) || (0, import_utils13.isNil)(newval) ? newval : void 0
@@ -2315,13 +2486,17 @@ var AccessRuntime = class {
2315
2486
  getOrCreateModelOptions(modelName) {
2316
2487
  let manager = this.modelOptions[modelName];
2317
2488
  if (!manager) {
2318
- manager = this.createModelOptions(modelName);
2319
- this.modelOptions[modelName] = manager;
2489
+ manager = this.deferSnapshotWarnings(() => {
2490
+ const created = this.createModelOptions(modelName);
2491
+ this.modelOptions[modelName] = created;
2492
+ return created;
2493
+ });
2320
2494
  }
2321
2495
  return manager;
2322
2496
  }
2323
2497
  /**
2324
- * 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
2325
2500
  * operationAccess/defaults object replaces that whole value. Defaults accept only
2326
2501
  * query/presentation settings; virtual configuration is validated before assignment.
2327
2502
  * Existing router.options remains its construction-time snapshot. Fresh model-service
@@ -2329,22 +2504,23 @@ var AccessRuntime = class {
2329
2504
  */
2330
2505
  setModelOptions(modelName, options) {
2331
2506
  assertPublicDefaults(options.defaults);
2507
+ options = normalizePopulatePolicyOptions(options);
2332
2508
  if ("hydration" in options) options = { ...options, hydration: normalizeHydration(options.hydration) };
2333
- const defaultOptions = this.getDefaultModelOptions();
2334
- const currentModelOptions = this.modelOptions[modelName]?.fetch() ?? { ...defaultModelOptions, modelName };
2335
- const merged = { ...defaultOptions, ...currentModelOptions, ...options };
2336
- const model = this.getModelInstance(modelName);
2337
- const permissionField = merged.documentPermissionField ?? currentModelOptions.documentPermissionField ?? this.getDefaultModelOption("documentPermissionField") ?? "_permissions";
2338
- validateVirtualsTree(model, merged.virtuals, permissionField, modelName);
2339
- captureVirtualPopulateDependencies(this, modelName, merged);
2340
- const manager = this.getOrCreateModelOptions(modelName);
2341
- 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
+ });
2342
2518
  }
2343
2519
  setModelOption(modelName, key, value) {
2344
2520
  const keyStr = String(key);
2345
2521
  if (keyStr === "hydration" || keyStr.startsWith("hydration.")) {
2346
- const hydration = normalizeHydrationUpdate(this.modelOptions[modelName]?.get("hydration"), keyStr, value);
2347
- this.getOrCreateModelOptions(modelName).set("hydration", hydration);
2522
+ const hydration = normalizeHydrationUpdate(this.resolveModelOptions(modelName).hydration, keyStr, value);
2523
+ this.setModelOptions(modelName, { hydration });
2348
2524
  return;
2349
2525
  }
2350
2526
  if (keyStr === "defaults") assertPublicDefaults(value);
@@ -2353,47 +2529,20 @@ var AccessRuntime = class {
2353
2529
  (0, import_utils13.set)(proposed, keyStr.slice("defaults.".length), value);
2354
2530
  assertPublicDefaults(proposed);
2355
2531
  }
2356
- const manager = this.modelOptions[modelName];
2357
- if (keyStr === "virtuals" || keyStr.startsWith("virtuals.") || keyStr === "documentPermissionField") {
2358
- const model = this.getModelInstance(modelName);
2359
- const currentVirtuals = manager?.get("virtuals");
2360
- const currentPermissionField = manager?.get("documentPermissionField") ?? this.getDefaultModelOption("documentPermissionField") ?? "_permissions";
2361
- let proposedVirtuals = currentVirtuals;
2362
- let proposedPermissionField = currentPermissionField;
2363
- if (keyStr === "documentPermissionField") {
2364
- proposedPermissionField = value;
2365
- } else if (keyStr === "virtuals") {
2366
- proposedVirtuals = value;
2367
- } else {
2368
- const cloned = cloneVirtualsForValidation(currentVirtuals ?? {});
2369
- const nestedPath = keyStr.slice("virtuals.".length);
2370
- if (value === void 0) {
2371
- const segments = nestedPath.split(".");
2372
- let cursor = cloned;
2373
- for (let i = 0; i < segments.length - 1; i++) {
2374
- if (!(0, import_utils13.isPlainObject)(cursor)) break;
2375
- cursor = cursor[segments[i]];
2376
- }
2377
- if ((0, import_utils13.isPlainObject)(cursor)) {
2378
- delete cursor[segments[segments.length - 1]];
2379
- }
2380
- proposedVirtuals = cloned;
2381
- } else {
2382
- (0, import_utils13.set)(cloned, nestedPath, value);
2383
- proposedVirtuals = cloned;
2384
- }
2385
- }
2386
- validateVirtualsTree(model, proposedVirtuals, proposedPermissionField, modelName);
2387
- captureVirtualPopulateDependencies(this, modelName, {
2388
- ...this.getDefaultModelOptions(),
2389
- ...manager?.fetch(),
2390
- virtuals: proposedVirtuals,
2391
- documentPermissionField: proposedPermissionField
2392
- });
2532
+ const [root, ...path] = keyStr.split(".");
2533
+ if (!path.length) {
2534
+ this.setModelOptions(modelName, { [root]: value });
2535
+ return;
2393
2536
  }
2394
- this.getOrCreateModelOptions(modelName).set(key, value);
2395
- }
2396
- /** 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. */
2397
2546
  getModelOptions(modelName) {
2398
2547
  const manager = this.getOrCreateModelOptions(modelName);
2399
2548
  return manager.fetch();
@@ -2558,13 +2707,6 @@ var AccessRuntime = class {
2558
2707
  };
2559
2708
  var defaultRuntime = new AccessRuntime({ allowGlobalModelLookup: true });
2560
2709
 
2561
- // src/runtime-context.ts
2562
- var import_node_async_hooks = require("async_hooks");
2563
- var runtimeStorage = new import_node_async_hooks.AsyncLocalStorage();
2564
- function getActiveRuntime() {
2565
- return runtimeStorage.getStore() ?? null;
2566
- }
2567
-
2568
2710
  // src/options/global-options.ts
2569
2711
  var getRuntime = () => getActiveRuntime() ?? defaultRuntime;
2570
2712
  var getGlobalOption = (key, defaultValue) => {