@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.mjs CHANGED
@@ -49,6 +49,23 @@ import mongoose from "mongoose";
49
49
  // src/validation/public-admission.ts
50
50
  import JsonRouter from "@web-ts-toolkit/express-json-router";
51
51
  import { isPlainObject } from "@web-ts-toolkit/utils";
52
+
53
+ // src/acl/unsafe-snapshot-options.ts
54
+ var unsafeSnapshotCheckOptions = [
55
+ "unsafeSkipListDocumentSnapshotChecks",
56
+ "unsafeSkipReadDocumentSnapshotChecks",
57
+ "unsafeSkipListOutputSnapshotChecks",
58
+ "unsafeSkipReadOutputSnapshotChecks",
59
+ "unsafeSkipListNestedDocumentSnapshotChecks",
60
+ "unsafeSkipReadNestedDocumentSnapshotChecks"
61
+ ];
62
+ var unsafeInitialOutputCopyOptions = [
63
+ "unsafeSkipListInitialOutputSnapshotCopy",
64
+ "unsafeSkipReadInitialOutputSnapshotCopy"
65
+ ];
66
+ var unsafeSnapshotOptions = [...unsafeSnapshotCheckOptions, ...unsafeInitialOutputCopyOptions];
67
+
68
+ // src/validation/public-admission.ts
52
69
  var privateControls = [
53
70
  "authorization",
54
71
  "overrides",
@@ -57,6 +74,7 @@ var privateControls = [
57
74
  "execution",
58
75
  "executionContext",
59
76
  "serviceExecutionContext",
77
+ "snapshotDerivation",
60
78
  "resolvedAuthorization",
61
79
  "preparedQuery",
62
80
  "preparedFilter",
@@ -65,8 +83,7 @@ var privateControls = [
65
83
  "skipParsing",
66
84
  "skipAuthorization",
67
85
  "alreadyAuthorized",
68
- "unsafeSkipListDocumentSnapshotChecks",
69
- "unsafeSkipReadDocumentSnapshotChecks",
86
+ ...unsafeSnapshotOptions,
70
87
  "operation"
71
88
  ];
72
89
  var PublicAdmissionError = class extends JsonRouter.clientErrors.BadRequestError {
@@ -94,7 +111,7 @@ function assertPublicAdmission(input, kind = "envelope") {
94
111
  for (const key of privateControls) {
95
112
  if (key in record2) {
96
113
  throw new PublicAdmissionError(
97
- 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`
114
+ 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`
98
115
  );
99
116
  }
100
117
  }
@@ -114,9 +131,9 @@ function assertPublicAdmission(input, kind = "envelope") {
114
131
  for (const key of ["filter", "match", "data"]) add(record2[key], "data", key);
115
132
  }
116
133
  }
117
- function assertHydrationDefaults(defaults) {
118
- if (defaults && typeof defaults === "object") {
119
- const record2 = defaults;
134
+ function assertHydrationDefaults(defaults2) {
135
+ if (defaults2 && typeof defaults2 === "object") {
136
+ const record2 = defaults2;
120
137
  if ("hydration" in record2)
121
138
  throw new TypeError("defaults.hydration is unsupported; use model hydration configuration");
122
139
  for (const bucket of [
@@ -144,11 +161,11 @@ function assertHydrationDefaults(defaults) {
144
161
  }
145
162
  }
146
163
  }
147
- function assertPublicDefaults(defaults) {
148
- assertHydrationDefaults(defaults);
149
- assertPublicAdmission(defaults);
150
- if (defaults && typeof defaults === "object") {
151
- for (const value of Object.values(defaults)) assertPublicAdmission(value);
164
+ function assertPublicDefaults(defaults2) {
165
+ assertHydrationDefaults(defaults2);
166
+ assertPublicAdmission(defaults2);
167
+ if (defaults2 && typeof defaults2 === "object") {
168
+ for (const value of Object.values(defaults2)) assertPublicAdmission(value);
152
169
  }
153
170
  }
154
171
  var requestAuthorization = Object.freeze({ outputFields: Object.freeze({ mode: "request" }) });
@@ -178,6 +195,32 @@ function normalizeHydrationUpdate(current, key, value) {
178
195
  return normalizeHydration({ ...normalizeHydration(current), [method]: value });
179
196
  }
180
197
 
198
+ // src/options/populate-policy.ts
199
+ var populatePolicyKeys = [
200
+ "requireOperationAccessForPopulateQueries",
201
+ "requireOperationAccessForPopulateDependencies"
202
+ ];
203
+ function isPopulatePolicyKey(key) {
204
+ return populatePolicyKeys.includes(key);
205
+ }
206
+ function normalizePopulatePolicyValue(value) {
207
+ return value === void 0 ? void 0 : value !== false;
208
+ }
209
+ function normalizePopulatePolicyOptions(options) {
210
+ const next = { ...options };
211
+ for (const key of populatePolicyKeys) {
212
+ if (key in options)
213
+ next[key] = normalizePopulatePolicyValue(options[key]);
214
+ }
215
+ return next;
216
+ }
217
+ function assertNoGlobalPopulatePolicy(key) {
218
+ if (isPopulatePolicyKey(key))
219
+ throw new TypeError(
220
+ `${key} is target-model configuration; migrate to setModelOptions(targetModelName, { ${key}: value }) or setDefaultModelOptions({ ${key}: value }) for runtime model defaults`
221
+ );
222
+ }
223
+
181
224
  // src/runtime.ts
182
225
  import mschema2Jsonschema from "mongoose-schema-jsonschema";
183
226
  import {
@@ -684,6 +727,7 @@ var freezeConfigValue = (value) => {
684
727
  return value;
685
728
  };
686
729
  var cloneAndFreezeForStore = (value) => freezeConfigValue(cloneForRead(value));
730
+ var cloneOptionsSnapshot = (value) => freezeConfigValue(cloneForRead(value));
687
731
  var getNestedOption = (manager, key, defaultValue) => resolveNestedOption((path, fallback) => manager.get(path, fallback), String(key), defaultValue);
688
732
  var resolveNestedOption = (read, key, defaultValue) => {
689
733
  const keys2 = key.split(".");
@@ -1173,7 +1217,8 @@ function resolveSnapshotDescriptor(scopeVirtuals, virtualName, access) {
1173
1217
  import { get as get2, isPlainObject as isPlainObject12 } from "@web-ts-toolkit/utils";
1174
1218
 
1175
1219
  // src/acl/authorization-snapshot.ts
1176
- import { isDeepStrictEqual } from "util";
1220
+ import { isDeepStrictEqual, types as types2 } from "util";
1221
+ import { Buffer as NodeBuffer } from "buffer";
1177
1222
  import { mongo } from "mongoose";
1178
1223
  import JsonRouter2 from "@web-ts-toolkit/express-json-router";
1179
1224
  var ServiceAuthorizationError = class extends JsonRouter2.clientErrors.BadRequestError {
@@ -1280,6 +1325,9 @@ function isSafeInputPath(path, requestIdentity = false) {
1280
1325
  return isSafeOutputPath(path) && path.split(".").every((part) => !inputControlSegments.has(part) && (requestIdentity || part !== "_id"));
1281
1326
  }
1282
1327
  function matchesCatalogPattern(pattern, path, descendants = false) {
1328
+ if (typeof pattern === "string" && typeof path === "string" && !pattern.includes("$*")) {
1329
+ return pattern === path || !!descendants && path.startsWith(pattern) && path[pattern.length] === ".";
1330
+ }
1283
1331
  const expected = pattern.split(".");
1284
1332
  const actual = path.split(".");
1285
1333
  return (descendants ? actual.length >= expected.length : actual.length === expected.length) && expected.every((part, index) => part === "$*" || part === actual[index]);
@@ -1380,7 +1428,16 @@ function captureAuthorizationFieldCatalog(schema, virtuals, documentPermissionFi
1380
1428
 
1381
1429
  // src/acl/populate-target-configuration.ts
1382
1430
  import { isPlainObject as isPlainObject11 } from "@web-ts-toolkit/utils";
1383
- function capturePopulateTargetConfiguration(runtime, modelName, source, proposedOptions) {
1431
+
1432
+ // src/runtime-context.ts
1433
+ import { AsyncLocalStorage } from "async_hooks";
1434
+ var runtimeStorage = new AsyncLocalStorage();
1435
+ function getActiveRuntime() {
1436
+ return runtimeStorage.getStore() ?? null;
1437
+ }
1438
+
1439
+ // src/acl/populate-target-configuration.ts
1440
+ function capturePopulateTargetConfiguration(runtime, modelName, source, proposedOptions, defaults2 = runtime.getDefaultModelOptions()) {
1384
1441
  const label = `Populate target "${modelName}" for ${source}`;
1385
1442
  if (!proposedOptions && !runtime.hasModel(modelName))
1386
1443
  authorizationError(
@@ -1389,7 +1446,7 @@ function capturePopulateTargetConfiguration(runtime, modelName, source, proposed
1389
1446
  const model = runtime.getModelInstance(modelName);
1390
1447
  if (!model) authorizationError(`${label} requires an actual registered Mongoose model in this runtime`);
1391
1448
  const options = proposedOptions ?? runtime.getModelOptions(modelName);
1392
- const permissionSchema = options.permissionSchema === void 0 ? runtime.getDefaultModelOption("permissionSchema") : options.permissionSchema;
1449
+ const permissionSchema = options.permissionSchema === void 0 ? defaults2.permissionSchema : options.permissionSchema;
1393
1450
  if (!isPlainObject11(permissionSchema))
1394
1451
  authorizationError(
1395
1452
  `${label} requires an effective object permissionSchema; configure the model or runtime model defaults ({} explicitly closes business fields)`
@@ -1397,6 +1454,31 @@ function capturePopulateTargetConfiguration(runtime, modelName, source, proposed
1397
1454
  return { model, options: { ...options, permissionSchema } };
1398
1455
  }
1399
1456
 
1457
+ // src/acl/populate-policy.ts
1458
+ var defaults = /* @__PURE__ */ new WeakMap();
1459
+ function capturePopulatePolicyDefaults(runtime) {
1460
+ const options = runtime.getDefaultModelOptions();
1461
+ const token = () => {
1462
+ };
1463
+ defaults.set(
1464
+ token,
1465
+ Object.freeze({
1466
+ requireOperationAccessForPopulateQueries: options.requireOperationAccessForPopulateQueries !== false,
1467
+ requireOperationAccessForPopulateDependencies: options.requireOperationAccessForPopulateDependencies !== false
1468
+ })
1469
+ );
1470
+ return token;
1471
+ }
1472
+ function resolvePopulatePolicy(options, token) {
1473
+ const captured = defaults.get(token);
1474
+ if (!captured) return authorizationError("invalid captured populate model defaults");
1475
+ const resolve = (key) => (options[key] === void 0 ? captured[key] : options[key]) !== false;
1476
+ return Object.freeze({
1477
+ requireOperationAccessForPopulateQueries: resolve(populatePolicyKeys[0]),
1478
+ requireOperationAccessForPopulateDependencies: resolve(populatePolicyKeys[1])
1479
+ });
1480
+ }
1481
+
1400
1482
  // src/acl/virtual-populate-dependencies.ts
1401
1483
  var elementType = (type) => type.$embeddedSchemaType ?? type.embeddedSchemaType ?? type.caster;
1402
1484
  var join = (prefix, path) => prefix ? `${prefix}.${path}` : path;
@@ -1496,9 +1578,7 @@ function normalizeSelection(select, catalog, label) {
1496
1578
  includeId: selection.includes("_id")
1497
1579
  };
1498
1580
  }
1499
- function captureVirtualPopulateDependencies(runtime, modelName, options, globalOptions = runtime.getGlobalOptions()) {
1500
- const requireOperationAccessForPopulateDependencies = globalOptions.requireOperationAccessForPopulateDependencies !== false;
1501
- const requireOperationAccessForPopulateQueries = globalOptions.requireOperationAccessForPopulateQueries !== false;
1581
+ function captureVirtualPopulateDependencies(runtime, modelName, options, populatePolicyDefaults = capturePopulatePolicyDefaults(runtime), proposed) {
1502
1582
  const model = runtime.getModelInstance(modelName);
1503
1583
  const targets = /* @__PURE__ */ new Map();
1504
1584
  const scopes = [];
@@ -1542,18 +1622,19 @@ function captureVirtualPopulateDependencies(runtime, modelName, options, globalO
1542
1622
  runtime,
1543
1623
  ref,
1544
1624
  `dependsOnPopulate virtual "${label}"`,
1545
- ref === modelName ? options : void 0
1625
+ ref === modelName ? options : proposed?.models.get(ref),
1626
+ proposed?.defaults
1546
1627
  );
1547
- const defaults = runtime.getDefaultModelOptions();
1548
- const readOption = (key) => resolveNestedOption((path2, fallback) => get2(targetOptions, path2, fallback), key, get2(defaults, key));
1549
- const documentPermissionField = targetOptions.documentPermissionField ?? defaults.documentPermissionField;
1628
+ const defaults2 = proposed?.defaults ?? runtime.getDefaultModelOptions();
1629
+ const readOption = (key) => resolveNestedOption((path2, fallback) => get2(targetOptions, path2, fallback), key, get2(defaults2, key));
1630
+ const documentPermissionField = targetOptions.documentPermissionField ?? defaults2.documentPermissionField;
1550
1631
  const catalog = captureAuthorizationFieldCatalog(targetModel.schema, void 0, documentPermissionField);
1551
1632
  const configuration = copyAuthorizationValue(
1552
1633
  {
1553
1634
  catalog,
1554
1635
  documentPermissionField,
1555
- requireOperationAccessForPopulateDependencies,
1556
- requireOperationAccessForPopulateQueries,
1636
+ populatePolicyDefaults,
1637
+ ...resolvePopulatePolicy(targetOptions, populatePolicyDefaults),
1557
1638
  permissionSchema: targetOptions.permissionSchema,
1558
1639
  operationAccess: { read: readOption("operationAccess.read") },
1559
1640
  baseFilter: { read: readOption("baseFilter.read") },
@@ -1648,6 +1729,15 @@ var defaultModelOptions = {
1648
1729
  basePath: null,
1649
1730
  alwaysSelectFields: []
1650
1731
  };
1732
+ var modelOverrides = (options) => {
1733
+ const result = Object.fromEntries(
1734
+ Object.entries(options).filter(
1735
+ ([key, value]) => value !== void 0 || key === "operationAccess" || isPopulatePolicyKey(key)
1736
+ )
1737
+ );
1738
+ for (const key of unsafeSnapshotOptions) if (key in result) result[key] = result[key] === true;
1739
+ return cloneOptionsSnapshot(result);
1740
+ };
1651
1741
  var defaultDataOptions = {
1652
1742
  basePath: null,
1653
1743
  parentPath: "/",
@@ -1781,12 +1871,12 @@ var getNestedChildFields = (parentSchema, fieldName) => {
1781
1871
  }
1782
1872
  return fields;
1783
1873
  };
1784
- var cloneVirtualsForValidation = (value) => {
1785
- if (Array.isArray(value)) return value.map((item) => cloneVirtualsForValidation(item));
1874
+ var cloneModelOptionForUpdate = (value) => {
1875
+ if (Array.isArray(value)) return value.map((item) => cloneModelOptionForUpdate(item));
1786
1876
  if (!value || typeof value !== "object") return value;
1787
1877
  if (Object.getPrototypeOf(value) !== Object.prototype) return value;
1788
1878
  return Object.fromEntries(
1789
- Object.entries(value).map(([k, v]) => [k, cloneVirtualsForValidation(v)])
1879
+ Object.entries(value).map(([k, v]) => [k, cloneModelOptionForUpdate(v)])
1790
1880
  );
1791
1881
  };
1792
1882
  var validateVirtualDependsOn = (dependsOn, entryLabel, storedFields, siblingVirtualNames) => {
@@ -1982,8 +2072,6 @@ var AccessRuntime = class {
1982
2072
  {
1983
2073
  requestPermissionField: "_permissions",
1984
2074
  globalPermissions: () => ({}),
1985
- requireOperationAccessForPopulateQueries: true,
1986
- requireOperationAccessForPopulateDependencies: true,
1987
2075
  logger: defaultLogger,
1988
2076
  requestComplexity: defaultRequestComplexity
1989
2077
  },
@@ -1998,11 +2086,20 @@ var AccessRuntime = class {
1998
2086
  queryRouteSegment: "__query",
1999
2087
  mutationRouteSegment: "__mutation",
2000
2088
  operationAccess: false,
2089
+ requireOperationAccessForPopulateQueries: true,
2090
+ requireOperationAccessForPopulateDependencies: true,
2001
2091
  modelPermissionPrefix: "",
2002
2092
  unsafeSkipListDocumentSnapshotChecks: false,
2003
- unsafeSkipReadDocumentSnapshotChecks: false
2093
+ unsafeSkipReadDocumentSnapshotChecks: false,
2094
+ unsafeSkipListOutputSnapshotChecks: false,
2095
+ unsafeSkipReadOutputSnapshotChecks: false,
2096
+ unsafeSkipListNestedDocumentSnapshotChecks: false,
2097
+ unsafeSkipReadNestedDocumentSnapshotChecks: false,
2098
+ unsafeSkipListInitialOutputSnapshotCopy: false,
2099
+ unsafeSkipReadInitialOutputSnapshotCopy: false
2004
2100
  }).build();
2005
2101
  this.modelOptions = {};
2102
+ this.modelOptionOverrides = {};
2006
2103
  this.modelJsonSchemas = {};
2007
2104
  this.dataOptions = {};
2008
2105
  this.modelRefs = {};
@@ -2090,6 +2187,7 @@ var AccessRuntime = class {
2090
2187
  globalOptions: this.globalOptions.snapshot(),
2091
2188
  defaultModelOptions: this.defaultModelOptions.snapshot(),
2092
2189
  modelOptions: modelOptionsSnap,
2190
+ modelOptionOverrides: { ...this.modelOptionOverrides },
2093
2191
  dataOptions: dataOptionsSnap,
2094
2192
  modelInstances: { ...this.modelInstances },
2095
2193
  modelJsonSchemas: { ...this.modelJsonSchemas },
@@ -2104,6 +2202,10 @@ var AccessRuntime = class {
2104
2202
  restoreBootstrapSnapshot(snapshot) {
2105
2203
  this.globalOptions.restore(snapshot.globalOptions);
2106
2204
  this.defaultModelOptions.restore(snapshot.defaultModelOptions);
2205
+ for (const name of Object.keys(this.modelOptionOverrides)) delete this.modelOptionOverrides[name];
2206
+ for (const [name, options] of Object.entries(snapshot.modelOptionOverrides)) {
2207
+ this.modelOptionOverrides[name] = modelOverrides(options);
2208
+ }
2107
2209
  for (const name of Object.keys(this.modelOptions)) {
2108
2210
  if (!(name in snapshot.modelOptions)) {
2109
2211
  delete this.modelOptions[name];
@@ -2114,8 +2216,7 @@ var AccessRuntime = class {
2114
2216
  if (existing) {
2115
2217
  existing.restore(opts);
2116
2218
  } else {
2117
- const mgr = this.createModelOptions(name);
2118
- mgr.restore(opts);
2219
+ const mgr = this.createModelOptions(name, opts);
2119
2220
  this.modelOptions[name] = mgr;
2120
2221
  }
2121
2222
  }
@@ -2158,18 +2259,11 @@ var AccessRuntime = class {
2158
2259
  }
2159
2260
  /** Shallowly replace supplied global values; nested objects such as requestComplexity are not deep-merged. */
2160
2261
  setGlobalOptions(options) {
2161
- const next = { ...options };
2162
- if ("requireOperationAccessForPopulateQueries" in next)
2163
- next.requireOperationAccessForPopulateQueries = next.requireOperationAccessForPopulateQueries !== false;
2164
- if ("requireOperationAccessForPopulateDependencies" in next)
2165
- next.requireOperationAccessForPopulateDependencies = next.requireOperationAccessForPopulateDependencies !== false;
2166
- this.globalOptions.assign(next);
2262
+ for (const key of populatePolicyKeys) if (key in options) assertNoGlobalPopulatePolicy(key);
2263
+ this.globalOptions.assign({ ...options });
2167
2264
  }
2168
2265
  setGlobalOption(key, value) {
2169
- if (key === "requireOperationAccessForPopulateQueries" || key === "requireOperationAccessForPopulateDependencies") {
2170
- this.globalOptions.set(key, value !== false);
2171
- return;
2172
- }
2266
+ assertNoGlobalPopulatePolicy(String(key));
2173
2267
  this.globalOptions.set(key, value);
2174
2268
  }
2175
2269
  getGlobalOptions() {
@@ -2178,28 +2272,30 @@ var AccessRuntime = class {
2178
2272
  getGlobalOption(key, defaultValue) {
2179
2273
  return this.globalOptions.get(key, defaultValue);
2180
2274
  }
2181
- /** Update model starting defaults shallowly; already-stored model values are not broadcast-replaced. */
2275
+ /** Update inherited model defaults shallowly. Explicit model values and captured calls are unchanged. */
2182
2276
  setDefaultModelOptions(options) {
2183
2277
  assertPublicDefaults(options.defaults);
2184
2278
  if ("hydration" in options) options = { ...options, hydration: normalizeHydration(options.hydration) };
2185
- this.defaultModelOptions.assign(options);
2279
+ const draft = new OptionsManager(
2280
+ this.getDefaultModelOptions()
2281
+ ).build();
2282
+ draft.assign(normalizePopulatePolicyOptions(options));
2283
+ this.publishDefaultModelOptions(draft.fetch());
2186
2284
  }
2187
2285
  setDefaultModelOption(key, value) {
2188
2286
  const keyStr = String(key);
2189
- if (keyStr === "hydration" || keyStr.startsWith("hydration.")) {
2190
- this.defaultModelOptions.set(
2191
- "hydration",
2192
- normalizeHydrationUpdate(this.getDefaultModelOptions().hydration, keyStr, value)
2193
- );
2194
- return;
2195
- }
2196
- if (keyStr === "defaults") assertPublicDefaults(value);
2197
- else if (keyStr.startsWith("defaults.")) {
2198
- const proposed = {};
2199
- set3(proposed, keyStr.slice("defaults.".length), value);
2200
- assertPublicDefaults(proposed);
2287
+ const draft = new OptionsManager(
2288
+ this.getDefaultModelOptions()
2289
+ ).build();
2290
+ if (isPopulatePolicyKey(keyStr)) {
2291
+ draft.set(keyStr, normalizePopulatePolicyValue(value));
2292
+ } else if (keyStr === "hydration" || keyStr.startsWith("hydration.")) {
2293
+ draft.set("hydration", normalizeHydrationUpdate(this.getDefaultModelOptions().hydration, keyStr, value));
2294
+ } else {
2295
+ draft.set(key, value);
2201
2296
  }
2202
- this.defaultModelOptions.set(key, value);
2297
+ assertPublicDefaults(draft.fetch().defaults);
2298
+ this.publishDefaultModelOptions(draft.fetch());
2203
2299
  }
2204
2300
  getDefaultModelOptions() {
2205
2301
  return this.defaultModelOptions.fetch();
@@ -2207,34 +2303,109 @@ var AccessRuntime = class {
2207
2303
  getDefaultModelOption(key, defaultValue) {
2208
2304
  return this.defaultModelOptions.get(key, defaultValue);
2209
2305
  }
2210
- createModelOptions(modelName) {
2306
+ resolveModelOptions(modelName, overrides = this.modelOptionOverrides[modelName] ?? {}, defaults2 = this.getDefaultModelOptions()) {
2307
+ const inherited = { ...defaults2 };
2308
+ for (const key of populatePolicyKeys) delete inherited[key];
2309
+ const effective = { ...defaultModelOptions, ...inherited, ...overrides, modelName };
2310
+ effective.basePath = normalizeBasePath(modelName, effective.basePath);
2311
+ for (const key of unsafeSnapshotOptions) effective[key] = effective[key] === true;
2312
+ refreshPermissionMetadata(effective);
2313
+ return cloneOptionsSnapshot(effective);
2314
+ }
2315
+ validateModelOptions(modelName, options, proposed) {
2316
+ validateVirtualsTree(
2317
+ this.getModelInstance(modelName),
2318
+ options.virtuals,
2319
+ options.documentPermissionField ?? "_permissions",
2320
+ modelName
2321
+ );
2322
+ captureVirtualPopulateDependencies(this, modelName, options, void 0, proposed);
2323
+ }
2324
+ publishDefaultModelOptions(options) {
2325
+ const next = { ...options };
2326
+ for (const key of unsafeSnapshotOptions) if (key in next) next[key] = next[key] === true;
2327
+ const defaults2 = cloneOptionsSnapshot(next);
2328
+ const models = new Map(
2329
+ Object.keys(this.modelOptions).map((name) => [name, this.resolveModelOptions(name, void 0, defaults2)])
2330
+ );
2331
+ for (const [name, options2] of models) this.validateModelOptions(name, options2, { defaults: defaults2, models });
2332
+ this.deferSnapshotWarnings(() => {
2333
+ this.defaultModelOptions.restore(defaults2);
2334
+ for (const [name, options2] of models) this.modelOptions[name].restore(options2);
2335
+ });
2336
+ }
2337
+ warnSnapshotFlag(modelName, key) {
2338
+ if (this.pendingSnapshotWarnings) {
2339
+ this.pendingSnapshotWarnings.push({ modelName, key });
2340
+ return;
2341
+ }
2342
+ const operation = key.startsWith("unsafeSkipRead") ? "read" : "list";
2343
+ const category = key.includes("NestedDocument") ? "nested-document" : key.includes("Output") ? "output" : "document";
2344
+ const risk = category === "output" ? "output mutation" : "source mutation";
2345
+ try {
2346
+ this.getGlobalOption("logger")?.warn?.(
2347
+ `UNSAFE: ${operation} ${category} snapshot checks disabled; ${risk} can leave stale authorization decisions. Restore ${key}=false after the temporary workaround.`,
2348
+ { modelName }
2349
+ );
2350
+ } catch {
2351
+ }
2352
+ }
2353
+ deferSnapshotWarnings(publish) {
2354
+ if (this.pendingSnapshotWarnings) return publish();
2355
+ const copyModes = this.initialOutputCopyModes();
2356
+ const pending = [];
2357
+ this.pendingSnapshotWarnings = pending;
2358
+ let result;
2359
+ try {
2360
+ result = publish();
2361
+ } finally {
2362
+ this.pendingSnapshotWarnings = void 0;
2363
+ }
2364
+ const nextCopyModes = this.initialOutputCopyModes();
2365
+ for (const { modelName, key } of pending) this.warnSnapshotFlag(modelName, key);
2366
+ for (const [modelName, modes] of nextCopyModes) {
2367
+ for (const operation of ["List", "Read"]) {
2368
+ const mode = modes[operation];
2369
+ if (mode === "off" || mode === copyModes.get(modelName)?.[operation]) continue;
2370
+ const key = `unsafeSkip${operation}InitialOutputSnapshotCopy`;
2371
+ const prerequisite = `unsafeSkip${operation}OutputSnapshotChecks`;
2372
+ try {
2373
+ this.getGlobalOption("logger")?.warn?.(
2374
+ 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.`,
2375
+ { modelName }
2376
+ );
2377
+ } catch {
2378
+ }
2379
+ }
2380
+ }
2381
+ return result;
2382
+ }
2383
+ initialOutputCopyModes() {
2384
+ return new Map(
2385
+ Object.entries(this.modelOptions).map(([modelName, options]) => {
2386
+ const mode = (operation) => options.get(`unsafeSkip${operation}InitialOutputSnapshotCopy`) !== true ? "off" : options.get(`unsafeSkip${operation}OutputSnapshotChecks`) === true ? "active" : "dormant";
2387
+ return [modelName, { List: mode("List"), Read: mode("Read") }];
2388
+ })
2389
+ );
2390
+ }
2391
+ createModelOptions(modelName, options = this.resolveModelOptions(modelName)) {
2211
2392
  const model = this.getModelInstance(modelName);
2212
2393
  if (!model) {
2213
2394
  throw new Error(
2214
2395
  `Runtime model registry missing model "${modelName}". Pass a mongoose.Model instance to createRouter() or register it with registerModelInstance() before using this isolated runtime.`
2215
2396
  );
2216
2397
  }
2217
- const manager = new OptionsManager({
2218
- ...defaultModelOptions,
2219
- modelName
2220
- });
2398
+ const manager = new OptionsManager(options);
2221
2399
  const snapshotFlagChanged = (newValue, key, target, oldValue) => {
2222
2400
  target[key] = newValue === true;
2223
2401
  if (newValue !== true || oldValue === true) return;
2224
- const operation = key === "unsafeSkipReadDocumentSnapshotChecks" ? "read" : "list";
2225
- try {
2226
- this.getGlobalOption("logger")?.warn?.(
2227
- `UNSAFE: ${operation} document snapshot checks disabled; source mutation can leave stale authorization decisions. Restore ${key}=false after the temporary workaround.`,
2228
- { modelName }
2229
- );
2230
- } catch {
2231
- }
2402
+ this.warnSnapshotFlag(modelName, key);
2232
2403
  };
2233
2404
  manager.onchange("permissionSchema", function(_newval, _key, target) {
2234
2405
  refreshPermissionMetadata(target);
2235
2406
  }).onchange("modelPermissionPrefix", function(_newval, _key, target) {
2236
2407
  refreshPermissionMetadata(target);
2237
- }).onchange("unsafeSkipListDocumentSnapshotChecks", snapshotFlagChanged).onchange("unsafeSkipReadDocumentSnapshotChecks", snapshotFlagChanged).onchange("basePath", function(newval, key, target) {
2408
+ }).onchange("unsafeSkipListDocumentSnapshotChecks", snapshotFlagChanged).onchange("unsafeSkipReadDocumentSnapshotChecks", snapshotFlagChanged).onchange("unsafeSkipListOutputSnapshotChecks", snapshotFlagChanged).onchange("unsafeSkipReadOutputSnapshotChecks", snapshotFlagChanged).onchange("unsafeSkipListNestedDocumentSnapshotChecks", snapshotFlagChanged).onchange("unsafeSkipReadNestedDocumentSnapshotChecks", snapshotFlagChanged).onchange("basePath", function(newval, key, target) {
2238
2409
  target[key] = normalizeBasePath(
2239
2410
  modelName,
2240
2411
  isString3(newval) || isNil2(newval) ? newval : void 0
@@ -2246,13 +2417,17 @@ var AccessRuntime = class {
2246
2417
  getOrCreateModelOptions(modelName) {
2247
2418
  let manager = this.modelOptions[modelName];
2248
2419
  if (!manager) {
2249
- manager = this.createModelOptions(modelName);
2250
- this.modelOptions[modelName] = manager;
2420
+ manager = this.deferSnapshotWarnings(() => {
2421
+ const created = this.createModelOptions(modelName);
2422
+ this.modelOptions[modelName] = created;
2423
+ return created;
2424
+ });
2251
2425
  }
2252
2426
  return manager;
2253
2427
  }
2254
2428
  /**
2255
- * Assign `{ ...modelDefaults, ...storedOptions, ...options }` shallowly. A supplied
2429
+ * Update explicit model overrides shallowly; undefined restores default inheritance
2430
+ * (operationAccess preserves its existing exact-key-only default fallback). A supplied
2256
2431
  * operationAccess/defaults object replaces that whole value. Defaults accept only
2257
2432
  * query/presentation settings; virtual configuration is validated before assignment.
2258
2433
  * Existing router.options remains its construction-time snapshot. Fresh model-service
@@ -2260,22 +2435,23 @@ var AccessRuntime = class {
2260
2435
  */
2261
2436
  setModelOptions(modelName, options) {
2262
2437
  assertPublicDefaults(options.defaults);
2438
+ options = normalizePopulatePolicyOptions(options);
2263
2439
  if ("hydration" in options) options = { ...options, hydration: normalizeHydration(options.hydration) };
2264
- const defaultOptions = this.getDefaultModelOptions();
2265
- const currentModelOptions = this.modelOptions[modelName]?.fetch() ?? { ...defaultModelOptions, modelName };
2266
- const merged = { ...defaultOptions, ...currentModelOptions, ...options };
2267
- const model = this.getModelInstance(modelName);
2268
- const permissionField = merged.documentPermissionField ?? currentModelOptions.documentPermissionField ?? this.getDefaultModelOption("documentPermissionField") ?? "_permissions";
2269
- validateVirtualsTree(model, merged.virtuals, permissionField, modelName);
2270
- captureVirtualPopulateDependencies(this, modelName, merged);
2271
- const manager = this.getOrCreateModelOptions(modelName);
2272
- manager.assign({ ...defaultOptions, ...currentModelOptions, ...options });
2440
+ const overrides = modelOverrides({ ...this.modelOptionOverrides[modelName], ...options });
2441
+ const effective = this.resolveModelOptions(modelName, overrides);
2442
+ this.validateModelOptions(modelName, effective);
2443
+ this.deferSnapshotWarnings(() => {
2444
+ const manager = this.modelOptions[modelName];
2445
+ if (manager) manager.restore(effective);
2446
+ else this.modelOptions[modelName] = this.createModelOptions(modelName, effective);
2447
+ this.modelOptionOverrides[modelName] = overrides;
2448
+ });
2273
2449
  }
2274
2450
  setModelOption(modelName, key, value) {
2275
2451
  const keyStr = String(key);
2276
2452
  if (keyStr === "hydration" || keyStr.startsWith("hydration.")) {
2277
- const hydration = normalizeHydrationUpdate(this.modelOptions[modelName]?.get("hydration"), keyStr, value);
2278
- this.getOrCreateModelOptions(modelName).set("hydration", hydration);
2453
+ const hydration = normalizeHydrationUpdate(this.resolveModelOptions(modelName).hydration, keyStr, value);
2454
+ this.setModelOptions(modelName, { hydration });
2279
2455
  return;
2280
2456
  }
2281
2457
  if (keyStr === "defaults") assertPublicDefaults(value);
@@ -2284,47 +2460,20 @@ var AccessRuntime = class {
2284
2460
  set3(proposed, keyStr.slice("defaults.".length), value);
2285
2461
  assertPublicDefaults(proposed);
2286
2462
  }
2287
- const manager = this.modelOptions[modelName];
2288
- if (keyStr === "virtuals" || keyStr.startsWith("virtuals.") || keyStr === "documentPermissionField") {
2289
- const model = this.getModelInstance(modelName);
2290
- const currentVirtuals = manager?.get("virtuals");
2291
- const currentPermissionField = manager?.get("documentPermissionField") ?? this.getDefaultModelOption("documentPermissionField") ?? "_permissions";
2292
- let proposedVirtuals = currentVirtuals;
2293
- let proposedPermissionField = currentPermissionField;
2294
- if (keyStr === "documentPermissionField") {
2295
- proposedPermissionField = value;
2296
- } else if (keyStr === "virtuals") {
2297
- proposedVirtuals = value;
2298
- } else {
2299
- const cloned = cloneVirtualsForValidation(currentVirtuals ?? {});
2300
- const nestedPath = keyStr.slice("virtuals.".length);
2301
- if (value === void 0) {
2302
- const segments = nestedPath.split(".");
2303
- let cursor = cloned;
2304
- for (let i = 0; i < segments.length - 1; i++) {
2305
- if (!isPlainObject13(cursor)) break;
2306
- cursor = cursor[segments[i]];
2307
- }
2308
- if (isPlainObject13(cursor)) {
2309
- delete cursor[segments[segments.length - 1]];
2310
- }
2311
- proposedVirtuals = cloned;
2312
- } else {
2313
- set3(cloned, nestedPath, value);
2314
- proposedVirtuals = cloned;
2315
- }
2316
- }
2317
- validateVirtualsTree(model, proposedVirtuals, proposedPermissionField, modelName);
2318
- captureVirtualPopulateDependencies(this, modelName, {
2319
- ...this.getDefaultModelOptions(),
2320
- ...manager?.fetch(),
2321
- virtuals: proposedVirtuals,
2322
- documentPermissionField: proposedPermissionField
2323
- });
2463
+ const [root, ...path] = keyStr.split(".");
2464
+ if (!path.length) {
2465
+ this.setModelOptions(modelName, { [root]: value });
2466
+ return;
2324
2467
  }
2325
- this.getOrCreateModelOptions(modelName).set(key, value);
2468
+ const current = this.resolveModelOptions(modelName);
2469
+ const nested = cloneModelOptionForUpdate(isPlainObject13(current[root]) ? current[root] : {});
2470
+ if (root === "virtuals" && value === void 0) {
2471
+ const parent = path.length === 1 ? nested : get3(nested, path.slice(0, -1));
2472
+ if (isPlainObject13(parent)) delete parent[path[path.length - 1]];
2473
+ } else set3(nested, path, value);
2474
+ this.setModelOptions(modelName, { [root]: nested });
2326
2475
  }
2327
- /** Frozen stored snapshot, not fully resolved per-path defaults. Read again for current configuration. */
2476
+ /** Frozen model/default snapshot; populate flags remain raw overrides. Read again for current values. */
2328
2477
  getModelOptions(modelName) {
2329
2478
  const manager = this.getOrCreateModelOptions(modelName);
2330
2479
  return manager.fetch();
@@ -2489,13 +2638,6 @@ var AccessRuntime = class {
2489
2638
  };
2490
2639
  var defaultRuntime = new AccessRuntime({ allowGlobalModelLookup: true });
2491
2640
 
2492
- // src/runtime-context.ts
2493
- import { AsyncLocalStorage } from "async_hooks";
2494
- var runtimeStorage = new AsyncLocalStorage();
2495
- function getActiveRuntime() {
2496
- return runtimeStorage.getStore() ?? null;
2497
- }
2498
-
2499
2641
  // src/options/global-options.ts
2500
2642
  var getRuntime = () => getActiveRuntime() ?? defaultRuntime;
2501
2643
  var getGlobalOption = (key, defaultValue) => {