@web-ts-toolkit/access-router 0.61.0 → 0.63.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
@@ -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 {
@@ -1313,6 +1346,7 @@ function copyAuthorizationValue(value, configuration = false) {
1313
1346
  if (array && input.length > 2e4) authorizationError("snapshot array exceeds structural limits");
1314
1347
  if (!array) authorizationRecord(input, "snapshot");
1315
1348
  const result = array ? [] : {};
1349
+ let definedProperty = false;
1316
1350
  for (const key of Reflect.ownKeys(input)) {
1317
1351
  if (array && key === "length") continue;
1318
1352
  if (typeof key !== "string" || unsafeKeys.has(key)) authorizationError("unsafe snapshot key");
@@ -1320,12 +1354,16 @@ function copyAuthorizationValue(value, configuration = false) {
1320
1354
  const descriptor = Object.getOwnPropertyDescriptor(input, key);
1321
1355
  if (!("value" in descriptor) || !descriptor.enumerable && configuration !== "document")
1322
1356
  authorizationError("accessor/non-enumerable input");
1323
- Object.defineProperty(result, key, {
1324
- value: copy(descriptor.value, depth + 1),
1325
- enumerable: true,
1326
- writable: true,
1327
- configurable: true
1328
- });
1357
+ const value2 = copy(descriptor.value, depth + 1);
1358
+ if (array || definedProperty && Object.getPrototypeOf(result) !== Object.prototype || key in result) {
1359
+ definedProperty = true;
1360
+ Object.defineProperty(result, key, {
1361
+ value: value2,
1362
+ enumerable: true,
1363
+ writable: true,
1364
+ configurable: true
1365
+ });
1366
+ } else result[key] = value2;
1329
1367
  }
1330
1368
  if (array) result.length = input.length;
1331
1369
  return Object.freeze(result);
@@ -1337,6 +1375,7 @@ function copyAuthorizationValue(value, configuration = false) {
1337
1375
  }
1338
1376
 
1339
1377
  // src/acl/field-catalog.ts
1378
+ var import_node_util4 = require("util");
1340
1379
  var safeSegment = (part) => !!part && part !== "sub" && !["__proto__", "constructor", "prototype", "_doc", "__v"].includes(part) && !/^[+$-]|[\s*]/.test(part) && !part.includes("[") && !part.includes("]") && !/^\d+$/.test(part) && ![...part].some((character) => character.charCodeAt(0) < 32 || character.charCodeAt(0) === 127);
1341
1380
  var isSafeOutputPath = (path) => path.split(".").every(safeSegment);
1342
1381
  var inputControlSegments = /* @__PURE__ */ new Set([
@@ -1361,6 +1400,9 @@ function isSafeInputPath(path, requestIdentity = false) {
1361
1400
  return isSafeOutputPath(path) && path.split(".").every((part) => !inputControlSegments.has(part) && (requestIdentity || part !== "_id"));
1362
1401
  }
1363
1402
  function matchesCatalogPattern(pattern, path, descendants = false) {
1403
+ if (typeof pattern === "string" && typeof path === "string" && !pattern.includes("$*")) {
1404
+ return pattern === path || !!descendants && path.startsWith(pattern) && path[pattern.length] === ".";
1405
+ }
1364
1406
  const expected = pattern.split(".");
1365
1407
  const actual = path.split(".");
1366
1408
  return (descendants ? actual.length >= expected.length : actual.length === expected.length) && expected.every((part, index) => part === "$*" || part === actual[index]);
@@ -1461,7 +1503,16 @@ function captureAuthorizationFieldCatalog(schema, virtuals, documentPermissionFi
1461
1503
 
1462
1504
  // src/acl/populate-target-configuration.ts
1463
1505
  var import_utils11 = require("@web-ts-toolkit/utils");
1464
- function capturePopulateTargetConfiguration(runtime, modelName, source, proposedOptions) {
1506
+
1507
+ // src/runtime-context.ts
1508
+ var import_node_async_hooks = require("async_hooks");
1509
+ var runtimeStorage = new import_node_async_hooks.AsyncLocalStorage();
1510
+ function getActiveRuntime() {
1511
+ return runtimeStorage.getStore() ?? null;
1512
+ }
1513
+
1514
+ // src/acl/populate-target-configuration.ts
1515
+ function capturePopulateTargetConfiguration(runtime, modelName, source, proposedOptions, defaults2 = runtime.getDefaultModelOptions()) {
1465
1516
  const label = `Populate target "${modelName}" for ${source}`;
1466
1517
  if (!proposedOptions && !runtime.hasModel(modelName))
1467
1518
  authorizationError(
@@ -1470,7 +1521,7 @@ function capturePopulateTargetConfiguration(runtime, modelName, source, proposed
1470
1521
  const model = runtime.getModelInstance(modelName);
1471
1522
  if (!model) authorizationError(`${label} requires an actual registered Mongoose model in this runtime`);
1472
1523
  const options = proposedOptions ?? runtime.getModelOptions(modelName);
1473
- const permissionSchema = options.permissionSchema === void 0 ? runtime.getDefaultModelOption("permissionSchema") : options.permissionSchema;
1524
+ const permissionSchema = options.permissionSchema === void 0 ? defaults2.permissionSchema : options.permissionSchema;
1474
1525
  if (!(0, import_utils11.isPlainObject)(permissionSchema))
1475
1526
  authorizationError(
1476
1527
  `${label} requires an effective object permissionSchema; configure the model or runtime model defaults ({} explicitly closes business fields)`
@@ -1478,6 +1529,31 @@ function capturePopulateTargetConfiguration(runtime, modelName, source, proposed
1478
1529
  return { model, options: { ...options, permissionSchema } };
1479
1530
  }
1480
1531
 
1532
+ // src/acl/populate-policy.ts
1533
+ var defaults = /* @__PURE__ */ new WeakMap();
1534
+ function capturePopulatePolicyDefaults(runtime) {
1535
+ const options = runtime.getDefaultModelOptions();
1536
+ const token = () => {
1537
+ };
1538
+ defaults.set(
1539
+ token,
1540
+ Object.freeze({
1541
+ requireOperationAccessForPopulateQueries: options.requireOperationAccessForPopulateQueries !== false,
1542
+ requireOperationAccessForPopulateDependencies: options.requireOperationAccessForPopulateDependencies !== false
1543
+ })
1544
+ );
1545
+ return token;
1546
+ }
1547
+ function resolvePopulatePolicy(options, token) {
1548
+ const captured = defaults.get(token);
1549
+ if (!captured) return authorizationError("invalid captured populate model defaults");
1550
+ const resolve = (key) => (options[key] === void 0 ? captured[key] : options[key]) !== false;
1551
+ return Object.freeze({
1552
+ requireOperationAccessForPopulateQueries: resolve(populatePolicyKeys[0]),
1553
+ requireOperationAccessForPopulateDependencies: resolve(populatePolicyKeys[1])
1554
+ });
1555
+ }
1556
+
1481
1557
  // src/acl/virtual-populate-dependencies.ts
1482
1558
  var elementType = (type) => type.$embeddedSchemaType ?? type.embeddedSchemaType ?? type.caster;
1483
1559
  var join = (prefix, path) => prefix ? `${prefix}.${path}` : path;
@@ -1577,9 +1653,7 @@ function normalizeSelection(select, catalog, label) {
1577
1653
  includeId: selection.includes("_id")
1578
1654
  };
1579
1655
  }
1580
- function captureVirtualPopulateDependencies(runtime, modelName, options, globalOptions = runtime.getGlobalOptions()) {
1581
- const requireOperationAccessForPopulateDependencies = globalOptions.requireOperationAccessForPopulateDependencies !== false;
1582
- const requireOperationAccessForPopulateQueries = globalOptions.requireOperationAccessForPopulateQueries !== false;
1656
+ function captureVirtualPopulateDependencies(runtime, modelName, options, populatePolicyDefaults = capturePopulatePolicyDefaults(runtime), proposed) {
1583
1657
  const model = runtime.getModelInstance(modelName);
1584
1658
  const targets = /* @__PURE__ */ new Map();
1585
1659
  const scopes = [];
@@ -1623,18 +1697,19 @@ function captureVirtualPopulateDependencies(runtime, modelName, options, globalO
1623
1697
  runtime,
1624
1698
  ref,
1625
1699
  `dependsOnPopulate virtual "${label}"`,
1626
- ref === modelName ? options : void 0
1700
+ ref === modelName ? options : proposed?.models.get(ref),
1701
+ proposed?.defaults
1627
1702
  );
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;
1703
+ const defaults2 = proposed?.defaults ?? runtime.getDefaultModelOptions();
1704
+ const readOption = (key) => resolveNestedOption((path2, fallback) => (0, import_utils12.get)(targetOptions, path2, fallback), key, (0, import_utils12.get)(defaults2, key));
1705
+ const documentPermissionField = targetOptions.documentPermissionField ?? defaults2.documentPermissionField;
1631
1706
  const catalog = captureAuthorizationFieldCatalog(targetModel.schema, void 0, documentPermissionField);
1632
1707
  const configuration = copyAuthorizationValue(
1633
1708
  {
1634
1709
  catalog,
1635
1710
  documentPermissionField,
1636
- requireOperationAccessForPopulateDependencies,
1637
- requireOperationAccessForPopulateQueries,
1711
+ populatePolicyDefaults,
1712
+ ...resolvePopulatePolicy(targetOptions, populatePolicyDefaults),
1638
1713
  permissionSchema: targetOptions.permissionSchema,
1639
1714
  operationAccess: { read: readOption("operationAccess.read") },
1640
1715
  baseFilter: { read: readOption("baseFilter.read") },
@@ -1729,6 +1804,15 @@ var defaultModelOptions = {
1729
1804
  basePath: null,
1730
1805
  alwaysSelectFields: []
1731
1806
  };
1807
+ var modelOverrides = (options) => {
1808
+ const result = Object.fromEntries(
1809
+ Object.entries(options).filter(
1810
+ ([key, value]) => value !== void 0 || key === "operationAccess" || isPopulatePolicyKey(key)
1811
+ )
1812
+ );
1813
+ for (const key of unsafeSnapshotOptions) if (key in result) result[key] = result[key] === true;
1814
+ return cloneOptionsSnapshot(result);
1815
+ };
1732
1816
  var defaultDataOptions = {
1733
1817
  basePath: null,
1734
1818
  parentPath: "/",
@@ -1862,12 +1946,12 @@ var getNestedChildFields = (parentSchema, fieldName) => {
1862
1946
  }
1863
1947
  return fields;
1864
1948
  };
1865
- var cloneVirtualsForValidation = (value) => {
1866
- if (Array.isArray(value)) return value.map((item) => cloneVirtualsForValidation(item));
1949
+ var cloneModelOptionForUpdate = (value) => {
1950
+ if (Array.isArray(value)) return value.map((item) => cloneModelOptionForUpdate(item));
1867
1951
  if (!value || typeof value !== "object") return value;
1868
1952
  if (Object.getPrototypeOf(value) !== Object.prototype) return value;
1869
1953
  return Object.fromEntries(
1870
- Object.entries(value).map(([k, v]) => [k, cloneVirtualsForValidation(v)])
1954
+ Object.entries(value).map(([k, v]) => [k, cloneModelOptionForUpdate(v)])
1871
1955
  );
1872
1956
  };
1873
1957
  var validateVirtualDependsOn = (dependsOn, entryLabel, storedFields, siblingVirtualNames) => {
@@ -2063,8 +2147,6 @@ var AccessRuntime = class {
2063
2147
  {
2064
2148
  requestPermissionField: "_permissions",
2065
2149
  globalPermissions: () => ({}),
2066
- requireOperationAccessForPopulateQueries: true,
2067
- requireOperationAccessForPopulateDependencies: true,
2068
2150
  logger: defaultLogger,
2069
2151
  requestComplexity: defaultRequestComplexity
2070
2152
  },
@@ -2079,15 +2161,20 @@ var AccessRuntime = class {
2079
2161
  queryRouteSegment: "__query",
2080
2162
  mutationRouteSegment: "__mutation",
2081
2163
  operationAccess: false,
2164
+ requireOperationAccessForPopulateQueries: true,
2165
+ requireOperationAccessForPopulateDependencies: true,
2082
2166
  modelPermissionPrefix: "",
2083
2167
  unsafeSkipListDocumentSnapshotChecks: false,
2084
2168
  unsafeSkipReadDocumentSnapshotChecks: false,
2085
2169
  unsafeSkipListOutputSnapshotChecks: false,
2086
2170
  unsafeSkipReadOutputSnapshotChecks: false,
2087
2171
  unsafeSkipListNestedDocumentSnapshotChecks: false,
2088
- unsafeSkipReadNestedDocumentSnapshotChecks: false
2172
+ unsafeSkipReadNestedDocumentSnapshotChecks: false,
2173
+ unsafeSkipListInitialOutputSnapshotCopy: false,
2174
+ unsafeSkipReadInitialOutputSnapshotCopy: false
2089
2175
  }).build();
2090
2176
  this.modelOptions = {};
2177
+ this.modelOptionOverrides = {};
2091
2178
  this.modelJsonSchemas = {};
2092
2179
  this.dataOptions = {};
2093
2180
  this.modelRefs = {};
@@ -2175,6 +2262,7 @@ var AccessRuntime = class {
2175
2262
  globalOptions: this.globalOptions.snapshot(),
2176
2263
  defaultModelOptions: this.defaultModelOptions.snapshot(),
2177
2264
  modelOptions: modelOptionsSnap,
2265
+ modelOptionOverrides: { ...this.modelOptionOverrides },
2178
2266
  dataOptions: dataOptionsSnap,
2179
2267
  modelInstances: { ...this.modelInstances },
2180
2268
  modelJsonSchemas: { ...this.modelJsonSchemas },
@@ -2189,6 +2277,10 @@ var AccessRuntime = class {
2189
2277
  restoreBootstrapSnapshot(snapshot) {
2190
2278
  this.globalOptions.restore(snapshot.globalOptions);
2191
2279
  this.defaultModelOptions.restore(snapshot.defaultModelOptions);
2280
+ for (const name of Object.keys(this.modelOptionOverrides)) delete this.modelOptionOverrides[name];
2281
+ for (const [name, options] of Object.entries(snapshot.modelOptionOverrides)) {
2282
+ this.modelOptionOverrides[name] = modelOverrides(options);
2283
+ }
2192
2284
  for (const name of Object.keys(this.modelOptions)) {
2193
2285
  if (!(name in snapshot.modelOptions)) {
2194
2286
  delete this.modelOptions[name];
@@ -2199,8 +2291,7 @@ var AccessRuntime = class {
2199
2291
  if (existing) {
2200
2292
  existing.restore(opts);
2201
2293
  } else {
2202
- const mgr = this.createModelOptions(name);
2203
- mgr.restore(opts);
2294
+ const mgr = this.createModelOptions(name, opts);
2204
2295
  this.modelOptions[name] = mgr;
2205
2296
  }
2206
2297
  }
@@ -2243,18 +2334,11 @@ var AccessRuntime = class {
2243
2334
  }
2244
2335
  /** Shallowly replace supplied global values; nested objects such as requestComplexity are not deep-merged. */
2245
2336
  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);
2337
+ for (const key of populatePolicyKeys) if (key in options) assertNoGlobalPopulatePolicy(key);
2338
+ this.globalOptions.assign({ ...options });
2252
2339
  }
2253
2340
  setGlobalOption(key, value) {
2254
- if (key === "requireOperationAccessForPopulateQueries" || key === "requireOperationAccessForPopulateDependencies") {
2255
- this.globalOptions.set(key, value !== false);
2256
- return;
2257
- }
2341
+ assertNoGlobalPopulatePolicy(String(key));
2258
2342
  this.globalOptions.set(key, value);
2259
2343
  }
2260
2344
  getGlobalOptions() {
@@ -2263,28 +2347,30 @@ var AccessRuntime = class {
2263
2347
  getGlobalOption(key, defaultValue) {
2264
2348
  return this.globalOptions.get(key, defaultValue);
2265
2349
  }
2266
- /** Update model starting defaults shallowly; already-stored model values are not broadcast-replaced. */
2350
+ /** Update inherited model defaults shallowly. Explicit model values and captured calls are unchanged. */
2267
2351
  setDefaultModelOptions(options) {
2268
2352
  assertPublicDefaults(options.defaults);
2269
2353
  if ("hydration" in options) options = { ...options, hydration: normalizeHydration(options.hydration) };
2270
- this.defaultModelOptions.assign(options);
2354
+ const draft = new OptionsManager(
2355
+ this.getDefaultModelOptions()
2356
+ ).build();
2357
+ draft.assign(normalizePopulatePolicyOptions(options));
2358
+ this.publishDefaultModelOptions(draft.fetch());
2271
2359
  }
2272
2360
  setDefaultModelOption(key, value) {
2273
2361
  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);
2362
+ const draft = new OptionsManager(
2363
+ this.getDefaultModelOptions()
2364
+ ).build();
2365
+ if (isPopulatePolicyKey(keyStr)) {
2366
+ draft.set(keyStr, normalizePopulatePolicyValue(value));
2367
+ } else if (keyStr === "hydration" || keyStr.startsWith("hydration.")) {
2368
+ draft.set("hydration", normalizeHydrationUpdate(this.getDefaultModelOptions().hydration, keyStr, value));
2369
+ } else {
2370
+ draft.set(key, value);
2286
2371
  }
2287
- this.defaultModelOptions.set(key, value);
2372
+ assertPublicDefaults(draft.fetch().defaults);
2373
+ this.publishDefaultModelOptions(draft.fetch());
2288
2374
  }
2289
2375
  getDefaultModelOptions() {
2290
2376
  return this.defaultModelOptions.fetch();
@@ -2292,30 +2378,103 @@ var AccessRuntime = class {
2292
2378
  getDefaultModelOption(key, defaultValue) {
2293
2379
  return this.defaultModelOptions.get(key, defaultValue);
2294
2380
  }
2295
- createModelOptions(modelName) {
2381
+ resolveModelOptions(modelName, overrides = this.modelOptionOverrides[modelName] ?? {}, defaults2 = this.getDefaultModelOptions()) {
2382
+ const inherited = { ...defaults2 };
2383
+ for (const key of populatePolicyKeys) delete inherited[key];
2384
+ const effective = { ...defaultModelOptions, ...inherited, ...overrides, modelName };
2385
+ effective.basePath = normalizeBasePath(modelName, effective.basePath);
2386
+ for (const key of unsafeSnapshotOptions) effective[key] = effective[key] === true;
2387
+ refreshPermissionMetadata(effective);
2388
+ return cloneOptionsSnapshot(effective);
2389
+ }
2390
+ validateModelOptions(modelName, options, proposed) {
2391
+ validateVirtualsTree(
2392
+ this.getModelInstance(modelName),
2393
+ options.virtuals,
2394
+ options.documentPermissionField ?? "_permissions",
2395
+ modelName
2396
+ );
2397
+ captureVirtualPopulateDependencies(this, modelName, options, void 0, proposed);
2398
+ }
2399
+ publishDefaultModelOptions(options) {
2400
+ const next = { ...options };
2401
+ for (const key of unsafeSnapshotOptions) if (key in next) next[key] = next[key] === true;
2402
+ const defaults2 = cloneOptionsSnapshot(next);
2403
+ const models = new Map(
2404
+ Object.keys(this.modelOptions).map((name) => [name, this.resolveModelOptions(name, void 0, defaults2)])
2405
+ );
2406
+ for (const [name, options2] of models) this.validateModelOptions(name, options2, { defaults: defaults2, models });
2407
+ this.deferSnapshotWarnings(() => {
2408
+ this.defaultModelOptions.restore(defaults2);
2409
+ for (const [name, options2] of models) this.modelOptions[name].restore(options2);
2410
+ });
2411
+ }
2412
+ warnSnapshotFlag(modelName, key) {
2413
+ if (this.pendingSnapshotWarnings) {
2414
+ this.pendingSnapshotWarnings.push({ modelName, key });
2415
+ return;
2416
+ }
2417
+ const operation = key.startsWith("unsafeSkipRead") ? "read" : "list";
2418
+ const category = key.includes("NestedDocument") ? "nested-document" : key.includes("Output") ? "output" : "document";
2419
+ const risk = category === "output" ? "output mutation" : "source mutation";
2420
+ try {
2421
+ this.getGlobalOption("logger")?.warn?.(
2422
+ `UNSAFE: ${operation} ${category} snapshot checks disabled; ${risk} can leave stale authorization decisions. Restore ${key}=false after the temporary workaround.`,
2423
+ { modelName }
2424
+ );
2425
+ } catch {
2426
+ }
2427
+ }
2428
+ deferSnapshotWarnings(publish) {
2429
+ if (this.pendingSnapshotWarnings) return publish();
2430
+ const copyModes = this.initialOutputCopyModes();
2431
+ const pending = [];
2432
+ this.pendingSnapshotWarnings = pending;
2433
+ let result;
2434
+ try {
2435
+ result = publish();
2436
+ } finally {
2437
+ this.pendingSnapshotWarnings = void 0;
2438
+ }
2439
+ const nextCopyModes = this.initialOutputCopyModes();
2440
+ for (const { modelName, key } of pending) this.warnSnapshotFlag(modelName, key);
2441
+ for (const [modelName, modes] of nextCopyModes) {
2442
+ for (const operation of ["List", "Read"]) {
2443
+ const mode = modes[operation];
2444
+ if (mode === "off" || mode === copyModes.get(modelName)?.[operation]) continue;
2445
+ const key = `unsafeSkip${operation}InitialOutputSnapshotCopy`;
2446
+ const prerequisite = `unsafeSkip${operation}OutputSnapshotChecks`;
2447
+ try {
2448
+ this.getGlobalOption("logger")?.warn?.(
2449
+ 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.`,
2450
+ { modelName }
2451
+ );
2452
+ } catch {
2453
+ }
2454
+ }
2455
+ }
2456
+ return result;
2457
+ }
2458
+ initialOutputCopyModes() {
2459
+ return new Map(
2460
+ Object.entries(this.modelOptions).map(([modelName, options]) => {
2461
+ const mode = (operation) => options.get(`unsafeSkip${operation}InitialOutputSnapshotCopy`) !== true ? "off" : options.get(`unsafeSkip${operation}OutputSnapshotChecks`) === true ? "active" : "dormant";
2462
+ return [modelName, { List: mode("List"), Read: mode("Read") }];
2463
+ })
2464
+ );
2465
+ }
2466
+ createModelOptions(modelName, options = this.resolveModelOptions(modelName)) {
2296
2467
  const model = this.getModelInstance(modelName);
2297
2468
  if (!model) {
2298
2469
  throw new Error(
2299
2470
  `Runtime model registry missing model "${modelName}". Pass a mongoose.Model instance to createRouter() or register it with registerModelInstance() before using this isolated runtime.`
2300
2471
  );
2301
2472
  }
2302
- const manager = new OptionsManager({
2303
- ...defaultModelOptions,
2304
- modelName
2305
- });
2473
+ const manager = new OptionsManager(options);
2306
2474
  const snapshotFlagChanged = (newValue, key, target, oldValue) => {
2307
2475
  target[key] = newValue === true;
2308
2476
  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
- }
2477
+ this.warnSnapshotFlag(modelName, key);
2319
2478
  };
2320
2479
  manager.onchange("permissionSchema", function(_newval, _key, target) {
2321
2480
  refreshPermissionMetadata(target);
@@ -2333,13 +2492,17 @@ var AccessRuntime = class {
2333
2492
  getOrCreateModelOptions(modelName) {
2334
2493
  let manager = this.modelOptions[modelName];
2335
2494
  if (!manager) {
2336
- manager = this.createModelOptions(modelName);
2337
- this.modelOptions[modelName] = manager;
2495
+ manager = this.deferSnapshotWarnings(() => {
2496
+ const created = this.createModelOptions(modelName);
2497
+ this.modelOptions[modelName] = created;
2498
+ return created;
2499
+ });
2338
2500
  }
2339
2501
  return manager;
2340
2502
  }
2341
2503
  /**
2342
- * Assign `{ ...modelDefaults, ...storedOptions, ...options }` shallowly. A supplied
2504
+ * Update explicit model overrides shallowly; undefined restores default inheritance
2505
+ * (operationAccess preserves its existing exact-key-only default fallback). A supplied
2343
2506
  * operationAccess/defaults object replaces that whole value. Defaults accept only
2344
2507
  * query/presentation settings; virtual configuration is validated before assignment.
2345
2508
  * Existing router.options remains its construction-time snapshot. Fresh model-service
@@ -2347,22 +2510,23 @@ var AccessRuntime = class {
2347
2510
  */
2348
2511
  setModelOptions(modelName, options) {
2349
2512
  assertPublicDefaults(options.defaults);
2513
+ options = normalizePopulatePolicyOptions(options);
2350
2514
  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 });
2515
+ const overrides = modelOverrides({ ...this.modelOptionOverrides[modelName], ...options });
2516
+ const effective = this.resolveModelOptions(modelName, overrides);
2517
+ this.validateModelOptions(modelName, effective);
2518
+ this.deferSnapshotWarnings(() => {
2519
+ const manager = this.modelOptions[modelName];
2520
+ if (manager) manager.restore(effective);
2521
+ else this.modelOptions[modelName] = this.createModelOptions(modelName, effective);
2522
+ this.modelOptionOverrides[modelName] = overrides;
2523
+ });
2360
2524
  }
2361
2525
  setModelOption(modelName, key, value) {
2362
2526
  const keyStr = String(key);
2363
2527
  if (keyStr === "hydration" || keyStr.startsWith("hydration.")) {
2364
- const hydration = normalizeHydrationUpdate(this.modelOptions[modelName]?.get("hydration"), keyStr, value);
2365
- this.getOrCreateModelOptions(modelName).set("hydration", hydration);
2528
+ const hydration = normalizeHydrationUpdate(this.resolveModelOptions(modelName).hydration, keyStr, value);
2529
+ this.setModelOptions(modelName, { hydration });
2366
2530
  return;
2367
2531
  }
2368
2532
  if (keyStr === "defaults") assertPublicDefaults(value);
@@ -2371,47 +2535,20 @@ var AccessRuntime = class {
2371
2535
  (0, import_utils13.set)(proposed, keyStr.slice("defaults.".length), value);
2372
2536
  assertPublicDefaults(proposed);
2373
2537
  }
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
- });
2538
+ const [root, ...path] = keyStr.split(".");
2539
+ if (!path.length) {
2540
+ this.setModelOptions(modelName, { [root]: value });
2541
+ return;
2411
2542
  }
2412
- this.getOrCreateModelOptions(modelName).set(key, value);
2413
- }
2414
- /** Frozen stored snapshot, not fully resolved per-path defaults. Read again for current configuration. */
2543
+ const current = this.resolveModelOptions(modelName);
2544
+ const nested = cloneModelOptionForUpdate((0, import_utils13.isPlainObject)(current[root]) ? current[root] : {});
2545
+ if (root === "virtuals" && value === void 0) {
2546
+ const parent = path.length === 1 ? nested : (0, import_utils13.get)(nested, path.slice(0, -1));
2547
+ if ((0, import_utils13.isPlainObject)(parent)) delete parent[path[path.length - 1]];
2548
+ } else (0, import_utils13.set)(nested, path, value);
2549
+ this.setModelOptions(modelName, { [root]: nested });
2550
+ }
2551
+ /** Frozen model/default snapshot; populate flags remain raw overrides. Read again for current values. */
2415
2552
  getModelOptions(modelName) {
2416
2553
  const manager = this.getOrCreateModelOptions(modelName);
2417
2554
  return manager.fetch();
@@ -2576,13 +2713,6 @@ var AccessRuntime = class {
2576
2713
  };
2577
2714
  var defaultRuntime = new AccessRuntime({ allowGlobalModelLookup: true });
2578
2715
 
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
2716
  // src/options/global-options.ts
2587
2717
  var getRuntime = () => getActiveRuntime() ?? defaultRuntime;
2588
2718
  var getGlobalOption = (key, defaultValue) => {