@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/index.mjs CHANGED
@@ -8,6 +8,26 @@ var __export = (target, all) => {
8
8
  __defProp(target, name, { get: all[name], enumerable: true });
9
9
  };
10
10
 
11
+ // src/acl/unsafe-snapshot-options.ts
12
+ var unsafeSnapshotCheckOptions, unsafeInitialOutputCopyOptions, unsafeSnapshotOptions;
13
+ var init_unsafe_snapshot_options = __esm({
14
+ "src/acl/unsafe-snapshot-options.ts"() {
15
+ unsafeSnapshotCheckOptions = [
16
+ "unsafeSkipListDocumentSnapshotChecks",
17
+ "unsafeSkipReadDocumentSnapshotChecks",
18
+ "unsafeSkipListOutputSnapshotChecks",
19
+ "unsafeSkipReadOutputSnapshotChecks",
20
+ "unsafeSkipListNestedDocumentSnapshotChecks",
21
+ "unsafeSkipReadNestedDocumentSnapshotChecks"
22
+ ];
23
+ unsafeInitialOutputCopyOptions = [
24
+ "unsafeSkipListInitialOutputSnapshotCopy",
25
+ "unsafeSkipReadInitialOutputSnapshotCopy"
26
+ ];
27
+ unsafeSnapshotOptions = [...unsafeSnapshotCheckOptions, ...unsafeInitialOutputCopyOptions];
28
+ }
29
+ });
30
+
11
31
  // src/validation/public-admission.ts
12
32
  import JsonRouter from "@web-ts-toolkit/express-json-router";
13
33
  import { isPlainObject } from "@web-ts-toolkit/utils";
@@ -29,7 +49,7 @@ function assertPublicAdmission(input, kind = "envelope") {
29
49
  for (const key of privateControls) {
30
50
  if (key in record3) {
31
51
  throw new PublicAdmissionError(
32
- 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`
52
+ 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`
33
53
  );
34
54
  }
35
55
  }
@@ -49,9 +69,9 @@ function assertPublicAdmission(input, kind = "envelope") {
49
69
  for (const key of ["filter", "match", "data"]) add(record3[key], "data", key);
50
70
  }
51
71
  }
52
- function assertHydrationDefaults(defaults) {
53
- if (defaults && typeof defaults === "object") {
54
- const record3 = defaults;
72
+ function assertHydrationDefaults(defaults2) {
73
+ if (defaults2 && typeof defaults2 === "object") {
74
+ const record3 = defaults2;
55
75
  if ("hydration" in record3)
56
76
  throw new TypeError("defaults.hydration is unsupported; use model hydration configuration");
57
77
  for (const bucket of [
@@ -79,11 +99,11 @@ function assertHydrationDefaults(defaults) {
79
99
  }
80
100
  }
81
101
  }
82
- function assertPublicDefaults(defaults) {
83
- assertHydrationDefaults(defaults);
84
- assertPublicAdmission(defaults);
85
- if (defaults && typeof defaults === "object") {
86
- for (const value of Object.values(defaults)) assertPublicAdmission(value);
102
+ function assertPublicDefaults(defaults2) {
103
+ assertHydrationDefaults(defaults2);
104
+ assertPublicAdmission(defaults2);
105
+ if (defaults2 && typeof defaults2 === "object") {
106
+ for (const value of Object.values(defaults2)) assertPublicAdmission(value);
87
107
  }
88
108
  }
89
109
  function pickPublicKeys(input, keys2) {
@@ -112,6 +132,7 @@ function requestOnlyServiceOptions(options) {
112
132
  var privateControls, PublicAdmissionError, listArgs, readArgs, listOptions, readOptions, requestAuthorization;
113
133
  var init_public_admission = __esm({
114
134
  "src/validation/public-admission.ts"() {
135
+ init_unsafe_snapshot_options();
115
136
  privateControls = [
116
137
  "authorization",
117
138
  "overrides",
@@ -120,6 +141,7 @@ var init_public_admission = __esm({
120
141
  "execution",
121
142
  "executionContext",
122
143
  "serviceExecutionContext",
144
+ "snapshotDerivation",
123
145
  "resolvedAuthorization",
124
146
  "preparedQuery",
125
147
  "preparedFilter",
@@ -128,8 +150,7 @@ var init_public_admission = __esm({
128
150
  "skipParsing",
129
151
  "skipAuthorization",
130
152
  "alreadyAuthorized",
131
- "unsafeSkipListDocumentSnapshotChecks",
132
- "unsafeSkipReadDocumentSnapshotChecks",
153
+ ...unsafeSnapshotOptions,
133
154
  "operation"
134
155
  ];
135
156
  PublicAdmissionError = class extends JsonRouter.clientErrors.BadRequestError {
@@ -183,6 +204,37 @@ var init_hydration = __esm({
183
204
  }
184
205
  });
185
206
 
207
+ // src/options/populate-policy.ts
208
+ function isPopulatePolicyKey(key) {
209
+ return populatePolicyKeys.includes(key);
210
+ }
211
+ function normalizePopulatePolicyValue(value) {
212
+ return value === void 0 ? void 0 : value !== false;
213
+ }
214
+ function normalizePopulatePolicyOptions(options) {
215
+ const next = { ...options };
216
+ for (const key of populatePolicyKeys) {
217
+ if (key in options)
218
+ next[key] = normalizePopulatePolicyValue(options[key]);
219
+ }
220
+ return next;
221
+ }
222
+ function assertNoGlobalPopulatePolicy(key) {
223
+ if (isPopulatePolicyKey(key))
224
+ throw new TypeError(
225
+ `${key} is target-model configuration; migrate to setModelOptions(targetModelName, { ${key}: value }) or setDefaultModelOptions({ ${key}: value }) for runtime model defaults`
226
+ );
227
+ }
228
+ var populatePolicyKeys;
229
+ var init_populate_policy = __esm({
230
+ "src/options/populate-policy.ts"() {
231
+ populatePolicyKeys = [
232
+ "requireOperationAccessForPopulateQueries",
233
+ "requireOperationAccessForPopulateDependencies"
234
+ ];
235
+ }
236
+ });
237
+
186
238
  // src/helpers/collection.ts
187
239
  import sift from "sift";
188
240
  import { filter, find } from "@web-ts-toolkit/utils";
@@ -1299,7 +1351,7 @@ var init_logger_default = __esm({
1299
1351
 
1300
1352
  // src/options/manager.ts
1301
1353
  import { assign, get as get3, isPlainObject as isPlainObject9, set as set2 } from "@web-ts-toolkit/utils";
1302
- var toPath, cloneConfigValue, cloneForRead, freezeConfigValue, cloneAndFreezeForStore, getNestedOption, resolveNestedOption, OptionsManager;
1354
+ var toPath, cloneConfigValue, cloneForRead, freezeConfigValue, cloneAndFreezeForStore, cloneOptionsSnapshot, getNestedOption, resolveNestedOption, OptionsManager;
1303
1355
  var init_manager = __esm({
1304
1356
  "src/options/manager.ts"() {
1305
1357
  toPath = (key) => {
@@ -1362,6 +1414,7 @@ var init_manager = __esm({
1362
1414
  return value;
1363
1415
  };
1364
1416
  cloneAndFreezeForStore = (value) => freezeConfigValue(cloneForRead(value));
1417
+ cloneOptionsSnapshot = (value) => freezeConfigValue(cloneForRead(value));
1365
1418
  getNestedOption = (manager, key, defaultValue) => resolveNestedOption((path, fallback) => manager.get(path, fallback), String(key), defaultValue);
1366
1419
  resolveNestedOption = (read, key, defaultValue) => {
1367
1420
  const keys2 = key.split(".");
@@ -1870,7 +1923,8 @@ var init_virtual_descriptor = __esm({
1870
1923
  });
1871
1924
 
1872
1925
  // src/acl/authorization-snapshot.ts
1873
- import { isDeepStrictEqual } from "util";
1926
+ import { isDeepStrictEqual, types as types2 } from "util";
1927
+ import { Buffer as NodeBuffer } from "buffer";
1874
1928
  import { mongo as mongo2 } from "mongoose";
1875
1929
  import JsonRouter3 from "@web-ts-toolkit/express-json-router";
1876
1930
  function authorizationError(detail) {
@@ -1973,6 +2027,71 @@ function outputIdentities(value) {
1973
2027
  visit(value);
1974
2028
  return Object.freeze(result2);
1975
2029
  }
2030
+ function tryOutputIdentitiesWithoutSnapshot(value) {
2031
+ const identities = [];
2032
+ const seen = /* @__PURE__ */ new WeakSet();
2033
+ const active = /* @__PURE__ */ new WeakSet();
2034
+ const fallback = {};
2035
+ let nodes = 0;
2036
+ function visit(input, depth) {
2037
+ if (++nodes > 2e4 || depth > 100) authorizationError("snapshot exceeds structural limits");
2038
+ if (typeof input === "function") authorizationError("functions are not policy values");
2039
+ if (typeof input === "symbol") authorizationError("symbols are not policy values");
2040
+ if (input === null || typeof input !== "object") return;
2041
+ if (types2.isProxy(input)) throw fallback;
2042
+ if (active.has(input)) authorizationError("cyclic input");
2043
+ if (!seen.has(input)) {
2044
+ seen.add(input);
2045
+ identities.push(input);
2046
+ }
2047
+ const prototype = Object.getPrototypeOf(input);
2048
+ if (types2.isDate(input)) {
2049
+ if (prototype === Date.prototype) return;
2050
+ throw fallback;
2051
+ }
2052
+ if (types2.isRegExp(input)) {
2053
+ if (prototype === RegExp.prototype) return;
2054
+ throw fallback;
2055
+ }
2056
+ if (types2.isUint8Array(input)) {
2057
+ if (prototype === NodeBuffer.prototype) return;
2058
+ throw fallback;
2059
+ }
2060
+ if (types2.isMap(input) || types2.isSet(input)) throw fallback;
2061
+ const array = Array.isArray(input);
2062
+ if (!array) {
2063
+ if (prototype !== Object.prototype && prototype !== null) {
2064
+ let parent = prototype;
2065
+ for (let count = 0; parent && count < 100; count++) {
2066
+ if (types2.isProxy(parent)) throw fallback;
2067
+ if (parent === mongo2.BSON.BSONValue.prototype) return;
2068
+ parent = Object.getPrototypeOf(parent);
2069
+ }
2070
+ throw fallback;
2071
+ }
2072
+ } else if (input.length > 2e4) authorizationError("snapshot array exceeds structural limits");
2073
+ active.add(input);
2074
+ try {
2075
+ for (const key of Reflect.ownKeys(input)) {
2076
+ if (array && key === "length") continue;
2077
+ if (typeof key !== "string" || unsafeKeys.has(key)) authorizationError("unsafe snapshot key");
2078
+ if (array && !/^(0|[1-9]\d*)$/.test(key)) authorizationError("invalid array property");
2079
+ const descriptor = Object.getOwnPropertyDescriptor(input, key);
2080
+ if (!("value" in descriptor)) authorizationError("accessor/non-enumerable input");
2081
+ visit(descriptor.value, depth + 1);
2082
+ }
2083
+ } finally {
2084
+ active.delete(input);
2085
+ }
2086
+ }
2087
+ try {
2088
+ visit(value, 0);
2089
+ return Object.freeze(identities);
2090
+ } catch (error2) {
2091
+ if (error2 !== fallback) throw error2;
2092
+ return void 0;
2093
+ }
2094
+ }
1976
2095
  var ServiceAuthorizationError, unsafeKeys;
1977
2096
  var init_authorization_snapshot = __esm({
1978
2097
  "src/acl/authorization-snapshot.ts"() {
@@ -2010,6 +2129,9 @@ function isInputVirtualPath(catalog, path) {
2010
2129
  return false;
2011
2130
  }
2012
2131
  function matchesCatalogPattern(pattern, path, descendants = false) {
2132
+ if (typeof pattern === "string" && typeof path === "string" && !pattern.includes("$*")) {
2133
+ return pattern === path || !!descendants && path.startsWith(pattern) && path[pattern.length] === ".";
2134
+ }
2013
2135
  const expected = pattern.split(".");
2014
2136
  const actual = path.split(".");
2015
2137
  return (descendants ? actual.length >= expected.length : actual.length === expected.length) && expected.every((part, index) => part === "$*" || part === actual[index]);
@@ -2142,9 +2264,46 @@ var init_field_catalog = __esm({
2142
2264
  }
2143
2265
  });
2144
2266
 
2267
+ // src/runtime-context.ts
2268
+ import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
2269
+ function runWithRuntime(runtime, callback) {
2270
+ return runtimeStorage.run(runtime, callback);
2271
+ }
2272
+ function getActiveRuntime() {
2273
+ return runtimeStorage.getStore() ?? null;
2274
+ }
2275
+ var runtimeStorage;
2276
+ var init_runtime_context = __esm({
2277
+ "src/runtime-context.ts"() {
2278
+ runtimeStorage = new AsyncLocalStorage2();
2279
+ }
2280
+ });
2281
+
2282
+ // src/meta.ts
2283
+ var getRuntime, getModelReference;
2284
+ var init_meta = __esm({
2285
+ "src/meta.ts"() {
2286
+ init_runtime();
2287
+ init_runtime_context();
2288
+ getRuntime = () => getActiveRuntime() ?? defaultRuntime;
2289
+ getModelReference = (modelName, refPath, runtime = getRuntime()) => {
2290
+ const instance = runtime.getModelInstance(modelName);
2291
+ let type = instance?.schema.path(refPath);
2292
+ const result2 = {};
2293
+ while (type) {
2294
+ result2.ref ??= type.options?.ref;
2295
+ result2.refPath ??= type.options?.refPath;
2296
+ if (type.instance !== "Array") break;
2297
+ type = type.$embeddedSchemaType ?? type.embeddedSchemaType ?? type.caster;
2298
+ }
2299
+ return result2;
2300
+ };
2301
+ }
2302
+ });
2303
+
2145
2304
  // src/acl/populate-target-configuration.ts
2146
2305
  import { isPlainObject as isPlainObject12 } from "@web-ts-toolkit/utils";
2147
- function capturePopulateTargetConfiguration(runtime, modelName, source, proposedOptions) {
2306
+ function capturePopulateTargetConfiguration(runtime, modelName, source, proposedOptions, defaults2 = runtime.getDefaultModelOptions()) {
2148
2307
  const label = `Populate target "${modelName}" for ${source}`;
2149
2308
  if (!proposedOptions && !runtime.hasModel(modelName))
2150
2309
  authorizationError(
@@ -2153,16 +2312,75 @@ function capturePopulateTargetConfiguration(runtime, modelName, source, proposed
2153
2312
  const model = runtime.getModelInstance(modelName);
2154
2313
  if (!model) authorizationError(`${label} requires an actual registered Mongoose model in this runtime`);
2155
2314
  const options = proposedOptions ?? runtime.getModelOptions(modelName);
2156
- const permissionSchema = options.permissionSchema === void 0 ? runtime.getDefaultModelOption("permissionSchema") : options.permissionSchema;
2315
+ const permissionSchema = options.permissionSchema === void 0 ? defaults2.permissionSchema : options.permissionSchema;
2157
2316
  if (!isPlainObject12(permissionSchema))
2158
2317
  authorizationError(
2159
2318
  `${label} requires an effective object permissionSchema; configure the model or runtime model defaults ({} explicitly closes business fields)`
2160
2319
  );
2161
2320
  return { model, options: { ...options, permissionSchema } };
2162
2321
  }
2322
+ function capturePopulateTargetBinding(runtime, sourceModelName, path) {
2323
+ const { ref, refPath } = getModelReference(sourceModelName, path, runtime);
2324
+ if (refPath !== void 0 || typeof ref === "function" && !("modelName" in ref))
2325
+ authorizationError(
2326
+ `Populate target for ${sourceModelName}.${path} requires a static string or Mongoose Model-valued source ref; dynamic refs/refPath cannot be bound before I/O`
2327
+ );
2328
+ const modelName = typeof ref === "string" ? ref : ref?.modelName;
2329
+ if (!modelName) return void 0;
2330
+ const target = capturePopulateTargetConfiguration(runtime, modelName, `${sourceModelName}.${path}`);
2331
+ const source = runtime.getModelInstance(sourceModelName);
2332
+ const actual = typeof ref === "string" ? source?.db.models[ref] : ref;
2333
+ if (!actual)
2334
+ authorizationError(
2335
+ `Populate target "${modelName}" for ${sourceModelName}.${path} is missing on the source connection; configure the actual model bound to the source ref in this runtime`
2336
+ );
2337
+ if (actual !== target.model)
2338
+ authorizationError(
2339
+ `Populate target "${modelName}" for ${sourceModelName}.${path} resolves to a different actual Mongoose model than this runtime configured; register and configure the actual source ref instance`
2340
+ );
2341
+ return { ...target, modelName };
2342
+ }
2163
2343
  var init_populate_target_configuration = __esm({
2164
2344
  "src/acl/populate-target-configuration.ts"() {
2165
2345
  init_authorization_snapshot();
2346
+ init_meta();
2347
+ }
2348
+ });
2349
+
2350
+ // src/acl/populate-policy.ts
2351
+ function capturePopulatePolicyDefaults(runtime) {
2352
+ const options = runtime.getDefaultModelOptions();
2353
+ const token = () => {
2354
+ };
2355
+ defaults.set(
2356
+ token,
2357
+ Object.freeze({
2358
+ requireOperationAccessForPopulateQueries: options.requireOperationAccessForPopulateQueries !== false,
2359
+ requireOperationAccessForPopulateDependencies: options.requireOperationAccessForPopulateDependencies !== false
2360
+ })
2361
+ );
2362
+ return token;
2363
+ }
2364
+ function resolvePopulatePolicy(options, token) {
2365
+ const captured = defaults.get(token);
2366
+ if (!captured) return authorizationError("invalid captured populate model defaults");
2367
+ const resolve = (key) => (options[key] === void 0 ? captured[key] : options[key]) !== false;
2368
+ return Object.freeze({
2369
+ requireOperationAccessForPopulateQueries: resolve(populatePolicyKeys[0]),
2370
+ requireOperationAccessForPopulateDependencies: resolve(populatePolicyKeys[1])
2371
+ });
2372
+ }
2373
+ function getCapturedPopulatePolicyDefaults(configuration) {
2374
+ const token = configuration.populatePolicyDefaults;
2375
+ if (!token || !defaults.has(token)) return authorizationError("missing captured populate model defaults");
2376
+ return token;
2377
+ }
2378
+ var defaults;
2379
+ var init_populate_policy2 = __esm({
2380
+ "src/acl/populate-policy.ts"() {
2381
+ init_populate_policy();
2382
+ init_authorization_snapshot();
2383
+ defaults = /* @__PURE__ */ new WeakMap();
2166
2384
  }
2167
2385
  });
2168
2386
 
@@ -2257,9 +2475,7 @@ function normalizeSelection(select, catalog, label) {
2257
2475
  includeId: selection.includes("_id")
2258
2476
  };
2259
2477
  }
2260
- function captureVirtualPopulateDependencies(runtime, modelName, options, globalOptions = runtime.getGlobalOptions()) {
2261
- const requireOperationAccessForPopulateDependencies = globalOptions.requireOperationAccessForPopulateDependencies !== false;
2262
- const requireOperationAccessForPopulateQueries = globalOptions.requireOperationAccessForPopulateQueries !== false;
2478
+ function captureVirtualPopulateDependencies(runtime, modelName, options, populatePolicyDefaults = capturePopulatePolicyDefaults(runtime), proposed) {
2263
2479
  const model = runtime.getModelInstance(modelName);
2264
2480
  const targets = /* @__PURE__ */ new Map();
2265
2481
  const scopes = [];
@@ -2303,18 +2519,19 @@ function captureVirtualPopulateDependencies(runtime, modelName, options, globalO
2303
2519
  runtime,
2304
2520
  ref,
2305
2521
  `dependsOnPopulate virtual "${label}"`,
2306
- ref === modelName ? options : void 0
2522
+ ref === modelName ? options : proposed?.models.get(ref),
2523
+ proposed?.defaults
2307
2524
  );
2308
- const defaults = runtime.getDefaultModelOptions();
2309
- const readOption = (key) => resolveNestedOption((path2, fallback) => get4(targetOptions, path2, fallback), key, get4(defaults, key));
2310
- const documentPermissionField = targetOptions.documentPermissionField ?? defaults.documentPermissionField;
2525
+ const defaults2 = proposed?.defaults ?? runtime.getDefaultModelOptions();
2526
+ const readOption = (key) => resolveNestedOption((path2, fallback) => get4(targetOptions, path2, fallback), key, get4(defaults2, key));
2527
+ const documentPermissionField = targetOptions.documentPermissionField ?? defaults2.documentPermissionField;
2311
2528
  const catalog = captureAuthorizationFieldCatalog(targetModel.schema, void 0, documentPermissionField);
2312
2529
  const configuration = copyAuthorizationValue(
2313
2530
  {
2314
2531
  catalog,
2315
2532
  documentPermissionField,
2316
- requireOperationAccessForPopulateDependencies,
2317
- requireOperationAccessForPopulateQueries,
2533
+ populatePolicyDefaults,
2534
+ ...resolvePopulatePolicy(targetOptions, populatePolicyDefaults),
2318
2535
  permissionSchema: targetOptions.permissionSchema,
2319
2536
  operationAccess: { read: readOption("operationAccess.read") },
2320
2537
  baseFilter: { read: readOption("baseFilter.read") },
@@ -2395,8 +2612,8 @@ function captureVirtualPopulateDependencies(runtime, modelName, options, globalO
2395
2612
  visit(options.virtuals ?? {}, model?.schema, "", [], !!model && varyingModel(model));
2396
2613
  return Object.freeze({ scopes: Object.freeze(scopes) });
2397
2614
  }
2398
- function captureVirtualPopulateSnapshot(runtime, modelName, options, globalOptions = runtime.getGlobalOptions()) {
2399
- const snapshot = captureVirtualPopulateDependencies(runtime, modelName, options, globalOptions);
2615
+ function captureVirtualPopulateSnapshot(runtime, modelName, options, populatePolicyDefaults = capturePopulatePolicyDefaults(runtime)) {
2616
+ const snapshot = captureVirtualPopulateDependencies(runtime, modelName, options, populatePolicyDefaults);
2400
2617
  const token = () => {
2401
2618
  };
2402
2619
  snapshots.set(token, snapshot);
@@ -2429,6 +2646,7 @@ var init_virtual_populate_dependencies = __esm({
2429
2646
  init_field_catalog();
2430
2647
  init_virtual_descriptor();
2431
2648
  init_populate_target_configuration();
2649
+ init_populate_policy2();
2432
2650
  elementType = (type) => type.$embeddedSchemaType ?? type.embeddedSchemaType ?? type.caster;
2433
2651
  join = (prefix, path) => prefix ? `${prefix}.${path}` : path;
2434
2652
  within = (path, parent) => path === parent || path.startsWith(`${parent}.`);
@@ -2459,11 +2677,12 @@ import {
2459
2677
  normalizeUrlPath,
2460
2678
  set as set4
2461
2679
  } from "@web-ts-toolkit/utils";
2462
- var mongooseJsonSchemaInitialized, ensureMongooseJsonSchemaInitialized, pluralize, FIELD_ACCESS_KEYS, defaultModelOptions, defaultDataOptions, normalizeBasePath, hasModelPermission, classifyPermissionSchema, refreshPermissionMetadata, VIRTUAL_SUPPORTED_ACCESSES, VIRTUAL_UNSUPPORTED_ACCESSES, VIRTUAL_RESERVED_NAMES, VIRTUAL_DANGEROUS_SEGMENTS, VIRTUAL_NAME_PATTERN, isVirtualContainerValue2, virtualFullPath, virtualPathsOverlap, collectStoredTopLevel, getChildSchemaForField, getNestedChildFields, cloneVirtualsForValidation, validateVirtualDependsOn, validateVirtualLeafValue, validateVirtualsScope, validateVirtualsTree, AccessRuntime, defaultRuntime;
2680
+ var mongooseJsonSchemaInitialized, ensureMongooseJsonSchemaInitialized, pluralize, FIELD_ACCESS_KEYS, defaultModelOptions, modelOverrides, defaultDataOptions, normalizeBasePath, hasModelPermission, classifyPermissionSchema, refreshPermissionMetadata, VIRTUAL_SUPPORTED_ACCESSES, VIRTUAL_UNSUPPORTED_ACCESSES, VIRTUAL_RESERVED_NAMES, VIRTUAL_DANGEROUS_SEGMENTS, VIRTUAL_NAME_PATTERN, isVirtualContainerValue2, virtualFullPath, virtualPathsOverlap, collectStoredTopLevel, getChildSchemaForField, getNestedChildFields, cloneModelOptionForUpdate, validateVirtualDependsOn, validateVirtualLeafValue, validateVirtualsScope, validateVirtualsTree, AccessRuntime, defaultRuntime;
2463
2681
  var init_runtime = __esm({
2464
2682
  "src/runtime.ts"() {
2465
2683
  init_public_admission();
2466
2684
  init_hydration();
2685
+ init_populate_policy();
2467
2686
  init_helpers();
2468
2687
  init_registry();
2469
2688
  init_logger_default();
@@ -2473,6 +2692,7 @@ var init_runtime = __esm({
2473
2692
  init_request_complexity();
2474
2693
  init_virtual_descriptor();
2475
2694
  init_virtual_populate_dependencies();
2695
+ init_unsafe_snapshot_options();
2476
2696
  mongooseJsonSchemaInitialized = false;
2477
2697
  ensureMongooseJsonSchemaInitialized = () => {
2478
2698
  if (mongooseJsonSchemaInitialized) return;
@@ -2485,6 +2705,15 @@ var init_runtime = __esm({
2485
2705
  basePath: null,
2486
2706
  alwaysSelectFields: []
2487
2707
  };
2708
+ modelOverrides = (options) => {
2709
+ const result2 = Object.fromEntries(
2710
+ Object.entries(options).filter(
2711
+ ([key, value]) => value !== void 0 || key === "operationAccess" || isPopulatePolicyKey(key)
2712
+ )
2713
+ );
2714
+ for (const key of unsafeSnapshotOptions) if (key in result2) result2[key] = result2[key] === true;
2715
+ return cloneOptionsSnapshot(result2);
2716
+ };
2488
2717
  defaultDataOptions = {
2489
2718
  basePath: null,
2490
2719
  parentPath: "/",
@@ -2618,12 +2847,12 @@ var init_runtime = __esm({
2618
2847
  }
2619
2848
  return fields;
2620
2849
  };
2621
- cloneVirtualsForValidation = (value) => {
2622
- if (Array.isArray(value)) return value.map((item) => cloneVirtualsForValidation(item));
2850
+ cloneModelOptionForUpdate = (value) => {
2851
+ if (Array.isArray(value)) return value.map((item) => cloneModelOptionForUpdate(item));
2623
2852
  if (!value || typeof value !== "object") return value;
2624
2853
  if (Object.getPrototypeOf(value) !== Object.prototype) return value;
2625
2854
  return Object.fromEntries(
2626
- Object.entries(value).map(([k, v]) => [k, cloneVirtualsForValidation(v)])
2855
+ Object.entries(value).map(([k, v]) => [k, cloneModelOptionForUpdate(v)])
2627
2856
  );
2628
2857
  };
2629
2858
  validateVirtualDependsOn = (dependsOn, entryLabel, storedFields, siblingVirtualNames) => {
@@ -2819,8 +3048,6 @@ var init_runtime = __esm({
2819
3048
  {
2820
3049
  requestPermissionField: "_permissions",
2821
3050
  globalPermissions: () => ({}),
2822
- requireOperationAccessForPopulateQueries: true,
2823
- requireOperationAccessForPopulateDependencies: true,
2824
3051
  logger: defaultLogger,
2825
3052
  requestComplexity: defaultRequestComplexity
2826
3053
  },
@@ -2835,11 +3062,20 @@ var init_runtime = __esm({
2835
3062
  queryRouteSegment: "__query",
2836
3063
  mutationRouteSegment: "__mutation",
2837
3064
  operationAccess: false,
3065
+ requireOperationAccessForPopulateQueries: true,
3066
+ requireOperationAccessForPopulateDependencies: true,
2838
3067
  modelPermissionPrefix: "",
2839
3068
  unsafeSkipListDocumentSnapshotChecks: false,
2840
- unsafeSkipReadDocumentSnapshotChecks: false
3069
+ unsafeSkipReadDocumentSnapshotChecks: false,
3070
+ unsafeSkipListOutputSnapshotChecks: false,
3071
+ unsafeSkipReadOutputSnapshotChecks: false,
3072
+ unsafeSkipListNestedDocumentSnapshotChecks: false,
3073
+ unsafeSkipReadNestedDocumentSnapshotChecks: false,
3074
+ unsafeSkipListInitialOutputSnapshotCopy: false,
3075
+ unsafeSkipReadInitialOutputSnapshotCopy: false
2841
3076
  }).build();
2842
3077
  this.modelOptions = {};
3078
+ this.modelOptionOverrides = {};
2843
3079
  this.modelJsonSchemas = {};
2844
3080
  this.dataOptions = {};
2845
3081
  this.modelRefs = {};
@@ -2927,6 +3163,7 @@ var init_runtime = __esm({
2927
3163
  globalOptions: this.globalOptions.snapshot(),
2928
3164
  defaultModelOptions: this.defaultModelOptions.snapshot(),
2929
3165
  modelOptions: modelOptionsSnap,
3166
+ modelOptionOverrides: { ...this.modelOptionOverrides },
2930
3167
  dataOptions: dataOptionsSnap,
2931
3168
  modelInstances: { ...this.modelInstances },
2932
3169
  modelJsonSchemas: { ...this.modelJsonSchemas },
@@ -2941,6 +3178,10 @@ var init_runtime = __esm({
2941
3178
  restoreBootstrapSnapshot(snapshot) {
2942
3179
  this.globalOptions.restore(snapshot.globalOptions);
2943
3180
  this.defaultModelOptions.restore(snapshot.defaultModelOptions);
3181
+ for (const name of Object.keys(this.modelOptionOverrides)) delete this.modelOptionOverrides[name];
3182
+ for (const [name, options] of Object.entries(snapshot.modelOptionOverrides)) {
3183
+ this.modelOptionOverrides[name] = modelOverrides(options);
3184
+ }
2944
3185
  for (const name of Object.keys(this.modelOptions)) {
2945
3186
  if (!(name in snapshot.modelOptions)) {
2946
3187
  delete this.modelOptions[name];
@@ -2951,8 +3192,7 @@ var init_runtime = __esm({
2951
3192
  if (existing) {
2952
3193
  existing.restore(opts);
2953
3194
  } else {
2954
- const mgr = this.createModelOptions(name);
2955
- mgr.restore(opts);
3195
+ const mgr = this.createModelOptions(name, opts);
2956
3196
  this.modelOptions[name] = mgr;
2957
3197
  }
2958
3198
  }
@@ -2995,18 +3235,11 @@ var init_runtime = __esm({
2995
3235
  }
2996
3236
  /** Shallowly replace supplied global values; nested objects such as requestComplexity are not deep-merged. */
2997
3237
  setGlobalOptions(options) {
2998
- const next = { ...options };
2999
- if ("requireOperationAccessForPopulateQueries" in next)
3000
- next.requireOperationAccessForPopulateQueries = next.requireOperationAccessForPopulateQueries !== false;
3001
- if ("requireOperationAccessForPopulateDependencies" in next)
3002
- next.requireOperationAccessForPopulateDependencies = next.requireOperationAccessForPopulateDependencies !== false;
3003
- this.globalOptions.assign(next);
3238
+ for (const key of populatePolicyKeys) if (key in options) assertNoGlobalPopulatePolicy(key);
3239
+ this.globalOptions.assign({ ...options });
3004
3240
  }
3005
3241
  setGlobalOption(key, value) {
3006
- if (key === "requireOperationAccessForPopulateQueries" || key === "requireOperationAccessForPopulateDependencies") {
3007
- this.globalOptions.set(key, value !== false);
3008
- return;
3009
- }
3242
+ assertNoGlobalPopulatePolicy(String(key));
3010
3243
  this.globalOptions.set(key, value);
3011
3244
  }
3012
3245
  getGlobalOptions() {
@@ -3015,28 +3248,30 @@ var init_runtime = __esm({
3015
3248
  getGlobalOption(key, defaultValue) {
3016
3249
  return this.globalOptions.get(key, defaultValue);
3017
3250
  }
3018
- /** Update model starting defaults shallowly; already-stored model values are not broadcast-replaced. */
3251
+ /** Update inherited model defaults shallowly. Explicit model values and captured calls are unchanged. */
3019
3252
  setDefaultModelOptions(options) {
3020
3253
  assertPublicDefaults(options.defaults);
3021
3254
  if ("hydration" in options) options = { ...options, hydration: normalizeHydration(options.hydration) };
3022
- this.defaultModelOptions.assign(options);
3255
+ const draft = new OptionsManager(
3256
+ this.getDefaultModelOptions()
3257
+ ).build();
3258
+ draft.assign(normalizePopulatePolicyOptions(options));
3259
+ this.publishDefaultModelOptions(draft.fetch());
3023
3260
  }
3024
3261
  setDefaultModelOption(key, value) {
3025
3262
  const keyStr = String(key);
3026
- if (keyStr === "hydration" || keyStr.startsWith("hydration.")) {
3027
- this.defaultModelOptions.set(
3028
- "hydration",
3029
- normalizeHydrationUpdate(this.getDefaultModelOptions().hydration, keyStr, value)
3030
- );
3031
- return;
3032
- }
3033
- if (keyStr === "defaults") assertPublicDefaults(value);
3034
- else if (keyStr.startsWith("defaults.")) {
3035
- const proposed = {};
3036
- set4(proposed, keyStr.slice("defaults.".length), value);
3037
- assertPublicDefaults(proposed);
3263
+ const draft = new OptionsManager(
3264
+ this.getDefaultModelOptions()
3265
+ ).build();
3266
+ if (isPopulatePolicyKey(keyStr)) {
3267
+ draft.set(keyStr, normalizePopulatePolicyValue(value));
3268
+ } else if (keyStr === "hydration" || keyStr.startsWith("hydration.")) {
3269
+ draft.set("hydration", normalizeHydrationUpdate(this.getDefaultModelOptions().hydration, keyStr, value));
3270
+ } else {
3271
+ draft.set(key, value);
3038
3272
  }
3039
- this.defaultModelOptions.set(key, value);
3273
+ assertPublicDefaults(draft.fetch().defaults);
3274
+ this.publishDefaultModelOptions(draft.fetch());
3040
3275
  }
3041
3276
  getDefaultModelOptions() {
3042
3277
  return this.defaultModelOptions.fetch();
@@ -3044,34 +3279,109 @@ var init_runtime = __esm({
3044
3279
  getDefaultModelOption(key, defaultValue) {
3045
3280
  return this.defaultModelOptions.get(key, defaultValue);
3046
3281
  }
3047
- createModelOptions(modelName) {
3282
+ resolveModelOptions(modelName, overrides = this.modelOptionOverrides[modelName] ?? {}, defaults2 = this.getDefaultModelOptions()) {
3283
+ const inherited = { ...defaults2 };
3284
+ for (const key of populatePolicyKeys) delete inherited[key];
3285
+ const effective = { ...defaultModelOptions, ...inherited, ...overrides, modelName };
3286
+ effective.basePath = normalizeBasePath(modelName, effective.basePath);
3287
+ for (const key of unsafeSnapshotOptions) effective[key] = effective[key] === true;
3288
+ refreshPermissionMetadata(effective);
3289
+ return cloneOptionsSnapshot(effective);
3290
+ }
3291
+ validateModelOptions(modelName, options, proposed) {
3292
+ validateVirtualsTree(
3293
+ this.getModelInstance(modelName),
3294
+ options.virtuals,
3295
+ options.documentPermissionField ?? "_permissions",
3296
+ modelName
3297
+ );
3298
+ captureVirtualPopulateDependencies(this, modelName, options, void 0, proposed);
3299
+ }
3300
+ publishDefaultModelOptions(options) {
3301
+ const next = { ...options };
3302
+ for (const key of unsafeSnapshotOptions) if (key in next) next[key] = next[key] === true;
3303
+ const defaults2 = cloneOptionsSnapshot(next);
3304
+ const models = new Map(
3305
+ Object.keys(this.modelOptions).map((name) => [name, this.resolveModelOptions(name, void 0, defaults2)])
3306
+ );
3307
+ for (const [name, options2] of models) this.validateModelOptions(name, options2, { defaults: defaults2, models });
3308
+ this.deferSnapshotWarnings(() => {
3309
+ this.defaultModelOptions.restore(defaults2);
3310
+ for (const [name, options2] of models) this.modelOptions[name].restore(options2);
3311
+ });
3312
+ }
3313
+ warnSnapshotFlag(modelName, key) {
3314
+ if (this.pendingSnapshotWarnings) {
3315
+ this.pendingSnapshotWarnings.push({ modelName, key });
3316
+ return;
3317
+ }
3318
+ const operation = key.startsWith("unsafeSkipRead") ? "read" : "list";
3319
+ const category = key.includes("NestedDocument") ? "nested-document" : key.includes("Output") ? "output" : "document";
3320
+ const risk = category === "output" ? "output mutation" : "source mutation";
3321
+ try {
3322
+ this.getGlobalOption("logger")?.warn?.(
3323
+ `UNSAFE: ${operation} ${category} snapshot checks disabled; ${risk} can leave stale authorization decisions. Restore ${key}=false after the temporary workaround.`,
3324
+ { modelName }
3325
+ );
3326
+ } catch {
3327
+ }
3328
+ }
3329
+ deferSnapshotWarnings(publish) {
3330
+ if (this.pendingSnapshotWarnings) return publish();
3331
+ const copyModes = this.initialOutputCopyModes();
3332
+ const pending = [];
3333
+ this.pendingSnapshotWarnings = pending;
3334
+ let result2;
3335
+ try {
3336
+ result2 = publish();
3337
+ } finally {
3338
+ this.pendingSnapshotWarnings = void 0;
3339
+ }
3340
+ const nextCopyModes = this.initialOutputCopyModes();
3341
+ for (const { modelName, key } of pending) this.warnSnapshotFlag(modelName, key);
3342
+ for (const [modelName, modes] of nextCopyModes) {
3343
+ for (const operation of ["List", "Read"]) {
3344
+ const mode = modes[operation];
3345
+ if (mode === "off" || mode === copyModes.get(modelName)?.[operation]) continue;
3346
+ const key = `unsafeSkip${operation}InitialOutputSnapshotCopy`;
3347
+ const prerequisite = `unsafeSkip${operation}OutputSnapshotChecks`;
3348
+ try {
3349
+ this.getGlobalOption("logger")?.warn?.(
3350
+ 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.`,
3351
+ { modelName }
3352
+ );
3353
+ } catch {
3354
+ }
3355
+ }
3356
+ }
3357
+ return result2;
3358
+ }
3359
+ initialOutputCopyModes() {
3360
+ return new Map(
3361
+ Object.entries(this.modelOptions).map(([modelName, options]) => {
3362
+ const mode = (operation) => options.get(`unsafeSkip${operation}InitialOutputSnapshotCopy`) !== true ? "off" : options.get(`unsafeSkip${operation}OutputSnapshotChecks`) === true ? "active" : "dormant";
3363
+ return [modelName, { List: mode("List"), Read: mode("Read") }];
3364
+ })
3365
+ );
3366
+ }
3367
+ createModelOptions(modelName, options = this.resolveModelOptions(modelName)) {
3048
3368
  const model = this.getModelInstance(modelName);
3049
3369
  if (!model) {
3050
3370
  throw new Error(
3051
3371
  `Runtime model registry missing model "${modelName}". Pass a mongoose.Model instance to createRouter() or register it with registerModelInstance() before using this isolated runtime.`
3052
3372
  );
3053
3373
  }
3054
- const manager = new OptionsManager({
3055
- ...defaultModelOptions,
3056
- modelName
3057
- });
3374
+ const manager = new OptionsManager(options);
3058
3375
  const snapshotFlagChanged = (newValue, key, target, oldValue) => {
3059
3376
  target[key] = newValue === true;
3060
3377
  if (newValue !== true || oldValue === true) return;
3061
- const operation = key === "unsafeSkipReadDocumentSnapshotChecks" ? "read" : "list";
3062
- try {
3063
- this.getGlobalOption("logger")?.warn?.(
3064
- `UNSAFE: ${operation} document snapshot checks disabled; source mutation can leave stale authorization decisions. Restore ${key}=false after the temporary workaround.`,
3065
- { modelName }
3066
- );
3067
- } catch {
3068
- }
3378
+ this.warnSnapshotFlag(modelName, key);
3069
3379
  };
3070
3380
  manager.onchange("permissionSchema", function(_newval, _key, target) {
3071
3381
  refreshPermissionMetadata(target);
3072
3382
  }).onchange("modelPermissionPrefix", function(_newval, _key, target) {
3073
3383
  refreshPermissionMetadata(target);
3074
- }).onchange("unsafeSkipListDocumentSnapshotChecks", snapshotFlagChanged).onchange("unsafeSkipReadDocumentSnapshotChecks", snapshotFlagChanged).onchange("basePath", function(newval, key, target) {
3384
+ }).onchange("unsafeSkipListDocumentSnapshotChecks", snapshotFlagChanged).onchange("unsafeSkipReadDocumentSnapshotChecks", snapshotFlagChanged).onchange("unsafeSkipListOutputSnapshotChecks", snapshotFlagChanged).onchange("unsafeSkipReadOutputSnapshotChecks", snapshotFlagChanged).onchange("unsafeSkipListNestedDocumentSnapshotChecks", snapshotFlagChanged).onchange("unsafeSkipReadNestedDocumentSnapshotChecks", snapshotFlagChanged).onchange("basePath", function(newval, key, target) {
3075
3385
  target[key] = normalizeBasePath(
3076
3386
  modelName,
3077
3387
  isString4(newval) || isNil2(newval) ? newval : void 0
@@ -3083,13 +3393,17 @@ var init_runtime = __esm({
3083
3393
  getOrCreateModelOptions(modelName) {
3084
3394
  let manager = this.modelOptions[modelName];
3085
3395
  if (!manager) {
3086
- manager = this.createModelOptions(modelName);
3087
- this.modelOptions[modelName] = manager;
3396
+ manager = this.deferSnapshotWarnings(() => {
3397
+ const created = this.createModelOptions(modelName);
3398
+ this.modelOptions[modelName] = created;
3399
+ return created;
3400
+ });
3088
3401
  }
3089
3402
  return manager;
3090
3403
  }
3091
3404
  /**
3092
- * Assign `{ ...modelDefaults, ...storedOptions, ...options }` shallowly. A supplied
3405
+ * Update explicit model overrides shallowly; undefined restores default inheritance
3406
+ * (operationAccess preserves its existing exact-key-only default fallback). A supplied
3093
3407
  * operationAccess/defaults object replaces that whole value. Defaults accept only
3094
3408
  * query/presentation settings; virtual configuration is validated before assignment.
3095
3409
  * Existing router.options remains its construction-time snapshot. Fresh model-service
@@ -3097,22 +3411,23 @@ var init_runtime = __esm({
3097
3411
  */
3098
3412
  setModelOptions(modelName, options) {
3099
3413
  assertPublicDefaults(options.defaults);
3414
+ options = normalizePopulatePolicyOptions(options);
3100
3415
  if ("hydration" in options) options = { ...options, hydration: normalizeHydration(options.hydration) };
3101
- const defaultOptions = this.getDefaultModelOptions();
3102
- const currentModelOptions = this.modelOptions[modelName]?.fetch() ?? { ...defaultModelOptions, modelName };
3103
- const merged = { ...defaultOptions, ...currentModelOptions, ...options };
3104
- const model = this.getModelInstance(modelName);
3105
- const permissionField = merged.documentPermissionField ?? currentModelOptions.documentPermissionField ?? this.getDefaultModelOption("documentPermissionField") ?? "_permissions";
3106
- validateVirtualsTree(model, merged.virtuals, permissionField, modelName);
3107
- captureVirtualPopulateDependencies(this, modelName, merged);
3108
- const manager = this.getOrCreateModelOptions(modelName);
3109
- manager.assign({ ...defaultOptions, ...currentModelOptions, ...options });
3416
+ const overrides = modelOverrides({ ...this.modelOptionOverrides[modelName], ...options });
3417
+ const effective = this.resolveModelOptions(modelName, overrides);
3418
+ this.validateModelOptions(modelName, effective);
3419
+ this.deferSnapshotWarnings(() => {
3420
+ const manager = this.modelOptions[modelName];
3421
+ if (manager) manager.restore(effective);
3422
+ else this.modelOptions[modelName] = this.createModelOptions(modelName, effective);
3423
+ this.modelOptionOverrides[modelName] = overrides;
3424
+ });
3110
3425
  }
3111
3426
  setModelOption(modelName, key, value) {
3112
3427
  const keyStr = String(key);
3113
3428
  if (keyStr === "hydration" || keyStr.startsWith("hydration.")) {
3114
- const hydration = normalizeHydrationUpdate(this.modelOptions[modelName]?.get("hydration"), keyStr, value);
3115
- this.getOrCreateModelOptions(modelName).set("hydration", hydration);
3429
+ const hydration = normalizeHydrationUpdate(this.resolveModelOptions(modelName).hydration, keyStr, value);
3430
+ this.setModelOptions(modelName, { hydration });
3116
3431
  return;
3117
3432
  }
3118
3433
  if (keyStr === "defaults") assertPublicDefaults(value);
@@ -3121,47 +3436,20 @@ var init_runtime = __esm({
3121
3436
  set4(proposed, keyStr.slice("defaults.".length), value);
3122
3437
  assertPublicDefaults(proposed);
3123
3438
  }
3124
- const manager = this.modelOptions[modelName];
3125
- if (keyStr === "virtuals" || keyStr.startsWith("virtuals.") || keyStr === "documentPermissionField") {
3126
- const model = this.getModelInstance(modelName);
3127
- const currentVirtuals = manager?.get("virtuals");
3128
- const currentPermissionField = manager?.get("documentPermissionField") ?? this.getDefaultModelOption("documentPermissionField") ?? "_permissions";
3129
- let proposedVirtuals = currentVirtuals;
3130
- let proposedPermissionField = currentPermissionField;
3131
- if (keyStr === "documentPermissionField") {
3132
- proposedPermissionField = value;
3133
- } else if (keyStr === "virtuals") {
3134
- proposedVirtuals = value;
3135
- } else {
3136
- const cloned = cloneVirtualsForValidation(currentVirtuals ?? {});
3137
- const nestedPath = keyStr.slice("virtuals.".length);
3138
- if (value === void 0) {
3139
- const segments = nestedPath.split(".");
3140
- let cursor = cloned;
3141
- for (let i = 0; i < segments.length - 1; i++) {
3142
- if (!isPlainObject14(cursor)) break;
3143
- cursor = cursor[segments[i]];
3144
- }
3145
- if (isPlainObject14(cursor)) {
3146
- delete cursor[segments[segments.length - 1]];
3147
- }
3148
- proposedVirtuals = cloned;
3149
- } else {
3150
- set4(cloned, nestedPath, value);
3151
- proposedVirtuals = cloned;
3152
- }
3153
- }
3154
- validateVirtualsTree(model, proposedVirtuals, proposedPermissionField, modelName);
3155
- captureVirtualPopulateDependencies(this, modelName, {
3156
- ...this.getDefaultModelOptions(),
3157
- ...manager?.fetch(),
3158
- virtuals: proposedVirtuals,
3159
- documentPermissionField: proposedPermissionField
3160
- });
3439
+ const [root, ...path] = keyStr.split(".");
3440
+ if (!path.length) {
3441
+ this.setModelOptions(modelName, { [root]: value });
3442
+ return;
3161
3443
  }
3162
- this.getOrCreateModelOptions(modelName).set(key, value);
3163
- }
3164
- /** Frozen stored snapshot, not fully resolved per-path defaults. Read again for current configuration. */
3444
+ const current = this.resolveModelOptions(modelName);
3445
+ const nested = cloneModelOptionForUpdate(isPlainObject14(current[root]) ? current[root] : {});
3446
+ if (root === "virtuals" && value === void 0) {
3447
+ const parent = path.length === 1 ? nested : get5(nested, path.slice(0, -1));
3448
+ if (isPlainObject14(parent)) delete parent[path[path.length - 1]];
3449
+ } else set4(nested, path, value);
3450
+ this.setModelOptions(modelName, { [root]: nested });
3451
+ }
3452
+ /** Frozen model/default snapshot; populate flags remain raw overrides. Read again for current values. */
3165
3453
  getModelOptions(modelName) {
3166
3454
  const manager = this.getOrCreateModelOptions(modelName);
3167
3455
  return manager.fetch();
@@ -3328,132 +3616,117 @@ var init_runtime = __esm({
3328
3616
  }
3329
3617
  });
3330
3618
 
3331
- // src/runtime-context.ts
3332
- import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
3333
- function runWithRuntime(runtime, callback) {
3334
- return runtimeStorage.run(runtime, callback);
3335
- }
3336
- function getActiveRuntime() {
3337
- return runtimeStorage.getStore() ?? null;
3338
- }
3339
- var runtimeStorage;
3340
- var init_runtime_context = __esm({
3341
- "src/runtime-context.ts"() {
3342
- runtimeStorage = new AsyncLocalStorage2();
3343
- }
3344
- });
3345
-
3346
3619
  // src/options/global-options.ts
3347
- var getRuntime, setGlobalOptions, setGlobalOption, getGlobalOptions, getGlobalOption;
3620
+ var getRuntime2, setGlobalOptions, setGlobalOption, getGlobalOptions, getGlobalOption;
3348
3621
  var init_global_options = __esm({
3349
3622
  "src/options/global-options.ts"() {
3350
3623
  init_runtime();
3351
3624
  init_runtime_context();
3352
- getRuntime = () => getActiveRuntime() ?? defaultRuntime;
3625
+ getRuntime2 = () => getActiveRuntime() ?? defaultRuntime;
3353
3626
  setGlobalOptions = (options) => {
3354
- getRuntime().setGlobalOptions(options);
3627
+ getRuntime2().setGlobalOptions(options);
3355
3628
  };
3356
3629
  setGlobalOption = (key, value) => {
3357
- getRuntime().setGlobalOption(key, value);
3630
+ getRuntime2().setGlobalOption(key, value);
3358
3631
  };
3359
3632
  getGlobalOptions = () => {
3360
- return getRuntime().getGlobalOptions();
3633
+ return getRuntime2().getGlobalOptions();
3361
3634
  };
3362
3635
  getGlobalOption = (key, defaultValue) => {
3363
- return getRuntime().getGlobalOption(key, defaultValue);
3636
+ return getRuntime2().getGlobalOption(key, defaultValue);
3364
3637
  };
3365
3638
  }
3366
3639
  });
3367
3640
 
3368
3641
  // src/options/model-options.ts
3369
- var getRuntime2, setModelOptions, setModelOption, getModelOptions, getModelOption, getExactModelOption, getModelNames, getModelJsonSchema, registerModelInstance, hasModelInstance, getModelInstance;
3642
+ var getRuntime3, setModelOptions, setModelOption, getModelOptions, getModelOption, getExactModelOption, getModelNames, getModelJsonSchema, registerModelInstance, hasModelInstance, getModelInstance;
3370
3643
  var init_model_options = __esm({
3371
3644
  "src/options/model-options.ts"() {
3372
3645
  init_runtime();
3373
3646
  init_runtime_context();
3374
- getRuntime2 = () => getActiveRuntime() ?? defaultRuntime;
3647
+ getRuntime3 = () => getActiveRuntime() ?? defaultRuntime;
3375
3648
  setModelOptions = (modelName, options) => {
3376
- getRuntime2().setModelOptions(modelName, options);
3649
+ getRuntime3().setModelOptions(modelName, options);
3377
3650
  };
3378
3651
  setModelOption = (modelName, key, value) => {
3379
- getRuntime2().setModelOption(modelName, key, value);
3652
+ getRuntime3().setModelOption(modelName, key, value);
3380
3653
  };
3381
3654
  getModelOptions = (modelName) => {
3382
- return getRuntime2().getModelOptions(modelName);
3655
+ return getRuntime3().getModelOptions(modelName);
3383
3656
  };
3384
3657
  getModelOption = (modelName, key, defaultValue) => {
3385
- return getRuntime2().getModelOption(modelName, key, defaultValue);
3658
+ return getRuntime3().getModelOption(modelName, key, defaultValue);
3386
3659
  };
3387
3660
  getExactModelOption = (modelName, key) => {
3388
- return getRuntime2().getExactModelOption(modelName, key);
3661
+ return getRuntime3().getExactModelOption(modelName, key);
3389
3662
  };
3390
3663
  getModelNames = () => {
3391
3664
  return (getActiveRuntime() ?? defaultRuntime).getModelNames();
3392
3665
  };
3393
3666
  getModelJsonSchema = (modelName) => {
3394
- return getRuntime2().getModelJsonSchema(modelName);
3667
+ return getRuntime3().getModelJsonSchema(modelName);
3395
3668
  };
3396
3669
  registerModelInstance = (modelName, model) => {
3397
- getRuntime2().registerModelInstance(modelName, model);
3670
+ getRuntime3().registerModelInstance(modelName, model);
3398
3671
  };
3399
3672
  hasModelInstance = (modelName) => {
3400
- return getRuntime2().hasModelInstance(modelName);
3673
+ return getRuntime3().hasModelInstance(modelName);
3401
3674
  };
3402
3675
  getModelInstance = (modelName) => {
3403
- return getRuntime2().getModelInstance(modelName);
3676
+ return getRuntime3().getModelInstance(modelName);
3404
3677
  };
3405
3678
  }
3406
3679
  });
3407
3680
 
3408
3681
  // src/options/default-model-options.ts
3409
- var getRuntime3, setDefaultModelOptions, setDefaultModelOption, getDefaultModelOptions, getDefaultModelOption;
3682
+ var getRuntime4, setDefaultModelOptions, setDefaultModelOption, getDefaultModelOptions, getDefaultModelOption;
3410
3683
  var init_default_model_options = __esm({
3411
3684
  "src/options/default-model-options.ts"() {
3412
3685
  init_runtime();
3413
3686
  init_runtime_context();
3414
- getRuntime3 = () => getActiveRuntime() ?? defaultRuntime;
3687
+ getRuntime4 = () => getActiveRuntime() ?? defaultRuntime;
3415
3688
  setDefaultModelOptions = (options) => {
3416
- getRuntime3().setDefaultModelOptions(options);
3689
+ getRuntime4().setDefaultModelOptions(options);
3417
3690
  };
3418
3691
  setDefaultModelOption = (key, value) => {
3419
- getRuntime3().setDefaultModelOption(key, value);
3692
+ getRuntime4().setDefaultModelOption(key, value);
3420
3693
  };
3421
3694
  getDefaultModelOptions = () => {
3422
- return getRuntime3().getDefaultModelOptions();
3695
+ return getRuntime4().getDefaultModelOptions();
3423
3696
  };
3424
3697
  getDefaultModelOption = (key, defaultValue) => {
3425
- return getRuntime3().getDefaultModelOption(key, defaultValue);
3698
+ return getRuntime4().getDefaultModelOption(key, defaultValue);
3426
3699
  };
3427
3700
  }
3428
3701
  });
3429
3702
 
3430
3703
  // src/options/data-options.ts
3431
- var getRuntime4, setDataOptions, setDataOption, getDataOptions, getDataSnapshot, getDataOption, getExactDataOption, getDataNames;
3704
+ var getRuntime5, setDataOptions, setDataOption, getDataOptions, getDataSnapshot, getDataOption, getExactDataOption, getDataNames;
3432
3705
  var init_data_options = __esm({
3433
3706
  "src/options/data-options.ts"() {
3434
3707
  init_runtime();
3435
3708
  init_runtime_context();
3436
- getRuntime4 = () => getActiveRuntime() ?? defaultRuntime;
3709
+ getRuntime5 = () => getActiveRuntime() ?? defaultRuntime;
3437
3710
  setDataOptions = (dataName, options) => {
3438
- getRuntime4().setDataOptions(dataName, options);
3711
+ getRuntime5().setDataOptions(dataName, options);
3439
3712
  };
3440
3713
  setDataOption = (dataName, key, value) => {
3441
- getRuntime4().setDataOption(dataName, key, value);
3714
+ getRuntime5().setDataOption(dataName, key, value);
3442
3715
  };
3443
3716
  getDataOptions = (dataName) => {
3444
- return getRuntime4().getDataOptions(dataName);
3717
+ return getRuntime5().getDataOptions(dataName);
3445
3718
  };
3446
3719
  getDataSnapshot = (dataName) => {
3447
- return getRuntime4().getDataSnapshot(dataName);
3720
+ return getRuntime5().getDataSnapshot(dataName);
3448
3721
  };
3449
3722
  getDataOption = (dataName, key, defaultValue) => {
3450
- return getRuntime4().getDataOption(dataName, key, defaultValue);
3723
+ return getRuntime5().getDataOption(dataName, key, defaultValue);
3451
3724
  };
3452
3725
  getExactDataOption = (dataName, key) => {
3453
- return getRuntime4().getExactDataOption(dataName, key);
3726
+ return getRuntime5().getExactDataOption(dataName, key);
3454
3727
  };
3455
3728
  getDataNames = () => {
3456
- return getRuntime4().getDataNames();
3729
+ return getRuntime5().getDataNames();
3457
3730
  };
3458
3731
  }
3459
3732
  });
@@ -3716,6 +3989,33 @@ function assertAuthorizationBinding(call, binding) {
3716
3989
  authorizationError("request/runtime/model/scope binding mismatch");
3717
3990
  }
3718
3991
  }
3992
+ function queryOutputAccess(access) {
3993
+ return (access.operation === "read" || access.operation === "list") && (access.rowAccess === "read" || access.rowAccess === "list") && access.outputAccess === access.rowAccess && access.virtualAccess === access.rowAccess && access.docPermissionsAccess === access.rowAccess;
3994
+ }
3995
+ function nestedQueryResponse(input, access) {
3996
+ const edge = input.snapshotDerivation;
3997
+ if (!edge || !input.parent) return false;
3998
+ assertAuthorizationBinding(input.parent, edge.parentBinding);
3999
+ const parent = callRecord(input.parent);
4000
+ if (!parent.responseSnapshots || (input.applicability ?? "service") !== "service" || !queryOutputAccess(access) || !queryOutputAccess(parent.output.access))
4001
+ return false;
4002
+ if (edge.kind === "retry") {
4003
+ if (!parent.nestedResponse || access.operation !== "read" || parent.output.access.operation !== "read")
4004
+ return false;
4005
+ assertAuthorizationBinding(input.parent, input.binding);
4006
+ return true;
4007
+ }
4008
+ if (edge.kind === "related") {
4009
+ const target = parent.relatedTargets.find((target2) => target2.path === edge.path);
4010
+ return !!target && target.kind !== "count" && target.modelName === input.binding.modelName && scope(input.binding).length === 0;
4011
+ }
4012
+ if (edge.kind !== "embedded") return false;
4013
+ assertAuthorizationBinding(input.parent, { ...input.binding, scopePath: parent.binding.scopePath });
4014
+ const childScope = scope(input.binding), parentScope = scope(parent.binding);
4015
+ return childScope.length > parentScope.length && parentScope.every((part, index) => childScope[index] === part) && Object.keys(parent.output.access).every(
4016
+ (key) => access[key] === parent.output.access[key]
4017
+ );
4018
+ }
3719
4019
  function resolveServiceAuthorization(input) {
3720
4020
  const raw = copyAuthorizationValue(input.authorization);
3721
4021
  const configuration = copyAuthorizationValue(input.configuration, true);
@@ -3743,6 +4043,17 @@ function resolveServiceAuthorization(input) {
3743
4043
  const readAccess = outputAccess.rowAccess;
3744
4044
  const readResponse = input.readResponse === true && (input.applicability ?? "service") === "service" && scopePath.length === 0 && outputAccess.operation === "read" && (readAccess === "read" || readAccess === "list") && outputAccess.outputAccess === readAccess && outputAccess.virtualAccess === readAccess && outputAccess.docPermissionsAccess === readAccess && (input.parent === void 0 || callRecord(input.parent).readResponse);
3745
4045
  if (readResponse && input.parent) assertAuthorizationBinding(input.parent, input.binding);
4046
+ const nestedResponse = nestedQueryResponse(input, outputAccess);
4047
+ const listResponse = input.listResponse === true && input.parent === void 0 && (input.applicability ?? "service") === "service" && scopePath.length === 0 && outputAccess.operation === "list" && outputAccess.rowAccess === "list" && queryOutputAccess(outputAccess);
4048
+ const responseSnapshots = input.parent && (nestedResponse || readResponse) ? callRecord(input.parent).responseSnapshots : listResponse ? Object.freeze({
4049
+ skipOutput: configuration.unsafeSkipListOutputSnapshotChecks === true,
4050
+ skipNested: configuration.unsafeSkipListNestedDocumentSnapshotChecks === true,
4051
+ skipInitialOutputCopy: configuration.unsafeSkipListOutputSnapshotChecks === true && configuration.unsafeSkipListInitialOutputSnapshotCopy === true
4052
+ }) : readResponse ? Object.freeze({
4053
+ skipOutput: configuration.unsafeSkipReadOutputSnapshotChecks === true,
4054
+ skipNested: configuration.unsafeSkipReadNestedDocumentSnapshotChecks === true,
4055
+ skipInitialOutputCopy: configuration.unsafeSkipReadOutputSnapshotChecks === true && configuration.unsafeSkipReadInitialOutputSnapshotCopy === true
4056
+ }) : void 0;
3746
4057
  const call = Object.freeze(/* @__PURE__ */ Object.create(null));
3747
4058
  calls.set(call, {
3748
4059
  binding: Object.freeze({ ...input.binding, scopePath: Object.freeze(scopePath) }),
@@ -3755,7 +4066,11 @@ function resolveServiceAuthorization(input) {
3755
4066
  permissions,
3756
4067
  provenance: input.parent ? callRecord(input.parent).provenance : call,
3757
4068
  readResponse,
3758
- validateDocumentSnapshots: !(input.listResponse === true && input.parent === void 0 && (input.applicability ?? "service") === "service" && outputAccess.operation === "list" && outputAccess.rowAccess === "list" && outputAccess.outputAccess === "list" && scopePath.length === 0 && configuration.unsafeSkipListDocumentSnapshotChecks === true || readResponse && configuration.unsafeSkipReadDocumentSnapshotChecks === true)
4069
+ nestedResponse,
4070
+ responseSnapshots,
4071
+ validateOutputSnapshots: responseSnapshots?.skipOutput !== true,
4072
+ skipInitialOutputSnapshotCopy: responseSnapshots?.skipInitialOutputCopy === true,
4073
+ validateDocumentSnapshots: !(input.listResponse === true && input.parent === void 0 && (input.applicability ?? "service") === "service" && outputAccess.operation === "list" && outputAccess.rowAccess === "list" && outputAccess.outputAccess === "list" && scopePath.length === 0 && configuration.unsafeSkipListDocumentSnapshotChecks === true || readResponse && configuration.unsafeSkipReadDocumentSnapshotChecks === true || nestedResponse && responseSnapshots?.skipNested === true)
3759
4074
  });
3760
4075
  return call;
3761
4076
  }
@@ -3780,6 +4095,14 @@ function requiresDocumentSnapshotChecks(call, binding) {
3780
4095
  assertAuthorizationBinding(call, binding);
3781
4096
  return callRecord(call).validateDocumentSnapshots;
3782
4097
  }
4098
+ function requiresOutputSnapshotChecks(call, binding) {
4099
+ assertAuthorizationBinding(call, binding);
4100
+ return callRecord(call).validateOutputSnapshots;
4101
+ }
4102
+ function skipsInitialOutputSnapshotCopy(call) {
4103
+ const record3 = callRecord(call);
4104
+ return !record3.validateOutputSnapshots && record3.skipInitialOutputSnapshotCopy;
4105
+ }
3783
4106
  function readServiceAuthorizationHydration(call, binding) {
3784
4107
  assertAuthorizationBinding(call, binding);
3785
4108
  return copyAuthorizationValue({ hydration: callRecord(call).configuration.hydration }, true);
@@ -4232,9 +4555,9 @@ var init_virtual_projection = __esm({
4232
4555
  });
4233
4556
 
4234
4557
  // src/acl/output-projection.ts
4235
- import { types as types2 } from "util";
4558
+ import { types as types3 } from "util";
4236
4559
  function copyOutputDecisionFields(value) {
4237
- if (!Array.isArray(value) || types2.isProxy(value) || Object.getPrototypeOf(value) !== Array.prototype) return;
4560
+ if (!Array.isArray(value) || types3.isProxy(value) || Object.getPrototypeOf(value) !== Array.prototype) return;
4238
4561
  const length = Object.getOwnPropertyDescriptor(value, "length").value;
4239
4562
  if (length > 2e4) return;
4240
4563
  const fields = [];
@@ -4247,14 +4570,14 @@ function copyOutputDecisionFields(value) {
4247
4570
  }
4248
4571
  function readStaticOutputPlanFields(plan, authorization) {
4249
4572
  const record3 = staticPlanFields.get(plan);
4250
- if (!record3 || record3.authorization !== authorization || types2.isProxy(plan)) return;
4573
+ if (!record3 || record3.authorization !== authorization || types3.isProxy(plan)) return;
4251
4574
  const ownValue2 = (key) => {
4252
4575
  const slot = Object.getOwnPropertyDescriptor(plan, key);
4253
4576
  return slot && "value" in slot ? slot.value : void 0;
4254
4577
  };
4255
4578
  if (ownValue2("authorization") !== authorization || ownValue2("authorizationBinding") !== record3.binding) return;
4256
4579
  const children = ownValue2("childPlans");
4257
- if (children !== record3.children || types2.isProxy(children) || Reflect.ownKeys(children).length) return;
4580
+ if (children !== record3.children || types3.isProxy(children) || Reflect.ownKeys(children).length) return;
4258
4581
  const persisted = copyOutputDecisionFields(ownValue2("outputPersistedFields"));
4259
4582
  const virtuals = copyOutputDecisionFields(ownValue2("outputVirtualNames"));
4260
4583
  const same = (a, b) => a?.length === b.length && a.every((field, index) => field === b[index]);
@@ -4509,7 +4832,7 @@ var init_output_projection = __esm({
4509
4832
  });
4510
4833
 
4511
4834
  // src/acl/output-field-policy.ts
4512
- import { types as types3 } from "util";
4835
+ import { types as types4 } from "util";
4513
4836
  import { isPlainObject as isPlainObject16 } from "@web-ts-toolkit/utils";
4514
4837
  function callFieldPolicy(authorization, binding) {
4515
4838
  assertAuthorizationBinding(authorization, binding);
@@ -4581,7 +4904,7 @@ function prepareOutputPath(policy, authorization, binding, path, access) {
4581
4904
  return prepared;
4582
4905
  }
4583
4906
  function ordinaryContainer(value) {
4584
- return value !== null && typeof value === "object" && !types3.isProxy(value) && Object.getPrototypeOf(value) === Object.prototype && Object.isFrozen(value);
4907
+ return value !== null && typeof value === "object" && !types4.isProxy(value) && Object.getPrototypeOf(value) === Object.prototype && Object.isFrozen(value);
4585
4908
  }
4586
4909
  function booleanRuleLookup(schema, path, access) {
4587
4910
  if (schema == null) return true;
@@ -4640,7 +4963,7 @@ var init_output_field_policy = __esm({
4640
4963
  });
4641
4964
 
4642
4965
  // src/acl/document-authorization.ts
4643
- import { types as types4 } from "util";
4966
+ import { types as types5 } from "util";
4644
4967
  import { Document as Document3 } from "mongoose";
4645
4968
  function bindOutputDocumentOwner(handle, knownOutput, owner, binding) {
4646
4969
  lookupDocumentOwner(handle);
@@ -4822,7 +5145,7 @@ function memoizeDocumentFieldDecision(handle, binding, field, evaluate) {
4822
5145
  return decision.promise;
4823
5146
  }
4824
5147
  function ordinaryDecisionBinding(binding) {
4825
- if (types4.isProxy(binding) || Object.getPrototypeOf(binding) !== Object.prototype) return false;
5148
+ if (types5.isProxy(binding) || Object.getPrototypeOf(binding) !== Object.prototype) return false;
4826
5149
  for (const key of ["request", "runtime", "model", "modelName", "scopePath"]) {
4827
5150
  const slot = Object.getOwnPropertyDescriptor(binding, key);
4828
5151
  if (slot && !("value" in slot)) return false;
@@ -4948,7 +5271,7 @@ function tryStaticRequestFieldPaths(handle, binding, access) {
4948
5271
  return decisions && [...decisions].filter(([, allowed]) => allowed).map(([field]) => field);
4949
5272
  }
4950
5273
  function unchangedOutput(output, record3) {
4951
- if (!matchesAuthorizationSnapshot(output, record3.snapshot)) return false;
5274
+ if (record3.validateSnapshot && !matchesAuthorizationSnapshot(output, record3.snapshot)) return false;
4952
5275
  const identities = outputIdentities(output);
4953
5276
  return identities.length === record3.identities.length && identities.every((identity, i) => identity === record3.identities[i]);
4954
5277
  }
@@ -4973,10 +5296,21 @@ function associateDocumentAuthorization(handle, binding, output) {
4973
5296
  authorizationError("output already associated");
4974
5297
  return;
4975
5298
  }
5299
+ if (skipsInitialOutputSnapshotCopy(stage.call) && ordinaryDecisionBinding(binding)) {
5300
+ if (requiresOutputSnapshotChecks(stage.call, binding))
5301
+ authorizationError("output snapshot copy requires skipped comparisons");
5302
+ const identities = tryOutputIdentitiesWithoutSnapshot(output);
5303
+ if (identities) {
5304
+ outputs.set(output, { handle, snapshotState: "omitted", identities, validateSnapshot: false });
5305
+ return;
5306
+ }
5307
+ }
4976
5308
  outputs.set(output, {
4977
5309
  handle,
5310
+ snapshotState: "copied",
4978
5311
  snapshot: copyAuthorizationValue(output, "document"),
4979
- identities: outputIdentities(output)
5312
+ identities: outputIdentities(output),
5313
+ validateSnapshot: requiresOutputSnapshotChecks(stage.call, binding)
4980
5314
  });
4981
5315
  }
4982
5316
  function transferDocumentAuthorization(handle, use, copy) {
@@ -5153,7 +5487,8 @@ function getCapturedAuthorizationOption(configuration, key) {
5153
5487
  const defaultValue = key.startsWith("operationAccess.") ? get7(configuration.operationAccessDefaults, key.slice("operationAccess.".length)) : void 0;
5154
5488
  return resolveNestedOption((path, fallback) => get7(configuration, path, fallback), key, defaultValue);
5155
5489
  }
5156
- function captureModelAuthorizationConfiguration(runtime, modelName, options = runtime.getModelOptions(modelName), globalOptions = runtime.getGlobalOptions()) {
5490
+ function captureModelAuthorizationConfiguration(runtime, modelName, options, populatePolicyDefaults = capturePopulatePolicyDefaults(runtime)) {
5491
+ options ??= runtime.getModelOptions(modelName);
5157
5492
  const model = runtime.getModelInstance(modelName);
5158
5493
  if (!model) return authorizationError(`unknown receiving model: ${modelName}`);
5159
5494
  const virtuals = options.virtuals;
@@ -5164,10 +5499,10 @@ function captureModelAuthorizationConfiguration(runtime, modelName, options = ru
5164
5499
  runtime,
5165
5500
  modelName,
5166
5501
  options,
5167
- globalOptions
5502
+ populatePolicyDefaults
5168
5503
  ),
5169
- requireOperationAccessForPopulateDependencies: globalOptions.requireOperationAccessForPopulateDependencies !== false,
5170
- requireOperationAccessForPopulateQueries: globalOptions.requireOperationAccessForPopulateQueries !== false,
5504
+ populatePolicyDefaults,
5505
+ ...resolvePopulatePolicy(options, populatePolicyDefaults),
5171
5506
  permissionSchema: options.permissionSchema === void 0 ? runtime.getDefaultModelOption("permissionSchema") : options.permissionSchema,
5172
5507
  virtuals,
5173
5508
  alwaysSelectFields: options.alwaysSelectFields,
@@ -5180,6 +5515,12 @@ function captureModelAuthorizationConfiguration(runtime, modelName, options = ru
5180
5515
  disableFieldPermissions: options.disableFieldPermissions,
5181
5516
  unsafeSkipListDocumentSnapshotChecks: options.unsafeSkipListDocumentSnapshotChecks === true,
5182
5517
  unsafeSkipReadDocumentSnapshotChecks: options.unsafeSkipReadDocumentSnapshotChecks === true,
5518
+ unsafeSkipListOutputSnapshotChecks: options.unsafeSkipListOutputSnapshotChecks === true,
5519
+ unsafeSkipReadOutputSnapshotChecks: options.unsafeSkipReadOutputSnapshotChecks === true,
5520
+ unsafeSkipListNestedDocumentSnapshotChecks: options.unsafeSkipListNestedDocumentSnapshotChecks === true,
5521
+ unsafeSkipReadNestedDocumentSnapshotChecks: options.unsafeSkipReadNestedDocumentSnapshotChecks === true,
5522
+ unsafeSkipListInitialOutputSnapshotCopy: options.unsafeSkipListInitialOutputSnapshotCopy === true,
5523
+ unsafeSkipReadInitialOutputSnapshotCopy: options.unsafeSkipReadInitialOutputSnapshotCopy === true,
5183
5524
  overrideFilter: options.overrideFilter,
5184
5525
  baseFilter: options.baseFilter,
5185
5526
  idField: options.idField,
@@ -5224,6 +5565,7 @@ var init_model_output_planning = __esm({
5224
5565
  init_virtual_populate_dependencies();
5225
5566
  init_document_authorization();
5226
5567
  init_output_projection();
5568
+ init_populate_policy2();
5227
5569
  }
5228
5570
  });
5229
5571
 
@@ -5702,6 +6044,13 @@ var init_logger_helpers = __esm({
5702
6044
 
5703
6045
  // src/acl/populate-target.ts
5704
6046
  function setPopulateTargetMeta(entry, meta) {
6047
+ if (meta.fetchBinding)
6048
+ Object.defineProperty(entry, "model", {
6049
+ value: meta.fetchBinding.model,
6050
+ enumerable: true,
6051
+ writable: false,
6052
+ configurable: false
6053
+ });
5705
6054
  Object.defineProperty(entry, POPULATE_TARGET_PLAN, {
5706
6055
  value: meta,
5707
6056
  enumerable: false,
@@ -6253,7 +6602,7 @@ var init_virtual_populate_execution = __esm({
6253
6602
  });
6254
6603
 
6255
6604
  // src/acl/output-field-filter.ts
6256
- import { types as types5 } from "util";
6605
+ import { types as types6 } from "util";
6257
6606
  import { isPlainObject as isPlainObject22 } from "@web-ts-toolkit/utils";
6258
6607
  function assertOwningOutputDocuments(handle) {
6259
6608
  const owner = readOutputDocumentOwner(handle);
@@ -6411,7 +6760,8 @@ function authorizeEmbeddedOutputPlan(parent, child) {
6411
6760
  ...view,
6412
6761
  requestPermissions: getAuthorizationPermissions(parent.authorization, parent.authorizationBinding),
6413
6762
  authorization: serviceAuthorizationInput(view.authorization, view.relatedTargets),
6414
- parent: parent.authorization
6763
+ parent: parent.authorization,
6764
+ snapshotDerivation: { kind: "embedded", parentBinding: parent.authorizationBinding }
6415
6765
  });
6416
6766
  return { ...child, authorization, authorizationBinding: binding };
6417
6767
  }
@@ -6481,7 +6831,7 @@ function helperPlan(authorization, binding) {
6481
6831
  return planAuthorizedModelProjection({ authorization, binding, effectiveSelect: [] });
6482
6832
  }
6483
6833
  function primitiveHelperFields(source, plan) {
6484
- if (types5.isProxy(source)) return;
6834
+ if (types6.isProxy(source)) return;
6485
6835
  const canonical = readStaticOutputPlanFields(plan, plan.authorization);
6486
6836
  if (!canonical) return;
6487
6837
  const fields = [];
@@ -7302,7 +7652,7 @@ init_sort_policy();
7302
7652
  init_concurrency();
7303
7653
  import {
7304
7654
  castArray as castArray2,
7305
- cloneDeep as cloneDeep2,
7655
+ cloneDeep as cloneDeep3,
7306
7656
  compact,
7307
7657
  flatten,
7308
7658
  forEach as forEach3,
@@ -7873,14 +8223,111 @@ function isCorrelatedInclude(value) {
7873
8223
  // src/services/base.ts
7874
8224
  init_request_complexity();
7875
8225
 
8226
+ // src/model.ts
8227
+ init_runtime_context();
8228
+ init_runtime();
8229
+ import { AsyncLocalStorage as AsyncLocalStorage3 } from "async_hooks";
8230
+ import { cloneDeep as cloneDeep2 } from "@web-ts-toolkit/utils";
8231
+ var capturedModelConstruction = new AsyncLocalStorage3();
8232
+ function withCapturedPopulateModel(runtime, modelName, model, construct) {
8233
+ return capturedModelConstruction.run({ runtime, modelName, model }, construct);
8234
+ }
8235
+ function admitModelPersistence(adapter, scheduler) {
8236
+ return {
8237
+ modelName: adapter.modelName,
8238
+ mongooseModel: adapter.mongooseModel,
8239
+ new: () => adapter.new(),
8240
+ // Mongoose create(array) otherwise starts all document saves at once. Keep
8241
+ // the adapter's array input/output contract, with one permit per item; all
8242
+ // items are submitted even if one rejects, as with unordered create(array).
8243
+ create: (data) => Array.isArray(data) ? Promise.all(data.map((item) => scheduler.work(async () => (await adapter.create([item]))[0]))) : scheduler.work(() => adapter.create(data)),
8244
+ find: (props) => scheduler.work(() => adapter.find(props)),
8245
+ findOne: (props) => scheduler.work(() => adapter.findOne(props)),
8246
+ exists: (filter2) => scheduler.work(() => adapter.exists(filter2)),
8247
+ countDocuments: (filter2) => scheduler.work(() => adapter.countDocuments(filter2)),
8248
+ distinct: (field, conditions) => scheduler.work(() => adapter.distinct(field, conditions)),
8249
+ aggregate: (pipeline) => scheduler.work(() => adapter.aggregate(pipeline)),
8250
+ // Casting builds no persistence work and must not acquire a recursive permit.
8251
+ ...adapter.castFilter ? { castFilter: (filter2) => adapter.castFilter(filter2) } : {}
8252
+ };
8253
+ }
8254
+ var Model = class {
8255
+ constructor(modelName, runtime) {
8256
+ this.modelName = modelName;
8257
+ this.runtime = runtime ?? null;
8258
+ const resolvedRuntime = runtime ?? getActiveRuntime() ?? defaultRuntime;
8259
+ const captured = capturedModelConstruction.getStore();
8260
+ const registered = captured?.runtime === resolvedRuntime && captured.modelName === modelName ? captured.model : resolvedRuntime.getModelInstance(modelName);
8261
+ if (!registered) {
8262
+ throw new Error(
8263
+ `Runtime model registry missing model "${modelName}". Pass a mongoose.Model instance to createRouter() or register it with registerModelInstance() before using this runtime.`
8264
+ );
8265
+ }
8266
+ this.mongooseModel = registered;
8267
+ if (!this.mongooseModel) return;
8268
+ }
8269
+ new() {
8270
+ const doc = new this.mongooseModel();
8271
+ return doc;
8272
+ }
8273
+ create(data) {
8274
+ return this.mongooseModel.create(data);
8275
+ }
8276
+ find({ filter: filter2, select, sort, populate, limit, hardLimit, skip, lean }) {
8277
+ const builder = this.mongooseModel.find(filter2);
8278
+ if (select) builder.select(select);
8279
+ if (skip) builder.skip(Number(skip));
8280
+ const normalizedLimit = Number(limit);
8281
+ if (Number.isSafeInteger(normalizedLimit) && normalizedLimit > 0) {
8282
+ builder.limit(normalizedLimit);
8283
+ } else if (Number.isSafeInteger(hardLimit) && Number(hardLimit) > 0) {
8284
+ builder.limit(Number(hardLimit));
8285
+ }
8286
+ if (sort) builder.sort(sort);
8287
+ if (populate) builder.populate(populate);
8288
+ if (lean) builder.lean();
8289
+ return builder;
8290
+ }
8291
+ findOne({ filter: filter2, select, sort, populate, lean }) {
8292
+ const builder = this.mongooseModel.findOne(filter2);
8293
+ if (select) builder.select(select);
8294
+ if (sort) builder.sort(sort);
8295
+ if (populate) builder.populate(populate);
8296
+ if (lean) builder.lean();
8297
+ return builder;
8298
+ }
8299
+ exists(filter2) {
8300
+ if (!filter2) return null;
8301
+ return this.findOne({ filter: filter2 }).select("_id").lean();
8302
+ }
8303
+ // see https://mongoosejs.com/docs/api.html#query_Query-countDocuments
8304
+ countDocuments(filter2 = {}) {
8305
+ return this.mongooseModel.countDocuments(filter2);
8306
+ }
8307
+ /** Cast a copy using this model's query schema/setters, without executing query middleware or persistence. */
8308
+ castFilter(filter2) {
8309
+ const query = this.mongooseModel.countDocuments(cloneDeep2(filter2));
8310
+ return query.cast(this.mongooseModel);
8311
+ }
8312
+ // see https://mongoosejs.com/docs/api.html#model_Model.distinct
8313
+ distinct(field, conditions = {}) {
8314
+ return this.mongooseModel.distinct(field, conditions);
8315
+ }
8316
+ aggregate(pipeline) {
8317
+ return this.mongooseModel.aggregate(pipeline);
8318
+ }
8319
+ };
8320
+ var model_default = Model;
8321
+
7876
8322
  // src/acl/model-service-owner.ts
7877
8323
  init_runtime();
7878
8324
  init_runtime_context();
7879
- import { AsyncLocalStorage as AsyncLocalStorage3 } from "async_hooks";
8325
+ init_populate_policy2();
8326
+ import { AsyncLocalStorage as AsyncLocalStorage4 } from "async_hooks";
7880
8327
  var cores = /* @__PURE__ */ new WeakMap();
7881
- var construction = new AsyncLocalStorage3();
7882
- var dispatch = new AsyncLocalStorage3();
7883
- var operationGuard = new AsyncLocalStorage3();
8328
+ var construction = new AsyncLocalStorage4();
8329
+ var dispatch = new AsyncLocalStorage4();
8330
+ var operationGuard = new AsyncLocalStorage4();
7884
8331
  function withCapturedModelOperationGuard(core, modelName, access, guard2, permissions, run) {
7885
8332
  return operationGuard.run({ captured: { core, modelName, access, guard: guard2, permissions } }, run);
7886
8333
  }
@@ -7929,15 +8376,16 @@ function bindModelOwnerMethods(receiver, runtime) {
7929
8376
  }
7930
8377
  }
7931
8378
  }
7932
- function modelServiceOptions(receiver, read) {
8379
+ function modelServiceOptions(receiver, runtime, read) {
8380
+ modelServicePopulatePolicyDefaults(receiver, runtime);
7933
8381
  const call = dispatch.getStore();
7934
8382
  if (call?.receiver !== receiver) return read();
7935
8383
  return call.options ??= read();
7936
8384
  }
7937
- function modelServiceGlobalOptions(receiver, runtime) {
8385
+ function modelServicePopulatePolicyDefaults(receiver, runtime) {
7938
8386
  const call = dispatch.getStore();
7939
- if (call?.receiver !== receiver) return runtime.getGlobalOptions();
7940
- return call.globalOptions ??= runtime.getGlobalOptions();
8387
+ if (call?.receiver !== receiver) return capturePopulatePolicyDefaults(runtime);
8388
+ return call.populatePolicyDefaults ??= capturePopulatePolicyDefaults(runtime);
7941
8389
  }
7942
8390
 
7943
8391
  // src/services/base.ts
@@ -8091,27 +8539,6 @@ function castCountGroups(input, values) {
8091
8539
  // src/services/base.ts
8092
8540
  init_service_authorization();
8093
8541
 
8094
- // src/meta.ts
8095
- init_runtime();
8096
- init_runtime_context();
8097
- var getRuntime5 = () => getActiveRuntime() ?? defaultRuntime;
8098
- var getModelRef = (modelName, refPath, runtime = getRuntime5()) => {
8099
- const direct = runtime.getModelRef(modelName, refPath);
8100
- if (direct) return direct;
8101
- if (!refPath.includes(".")) return null;
8102
- try {
8103
- const instance = runtime.getModelInstance?.(
8104
- modelName
8105
- );
8106
- const schemaPath = instance?.schema?.path?.(refPath);
8107
- const element = schemaPath?.$embeddedSchemaType ?? schemaPath?.embeddedSchemaType ?? schemaPath?.caster;
8108
- const ref = schemaPath?.options?.ref ?? element?.options?.ref ?? null;
8109
- return typeof ref === "string" && ref.length > 0 ? ref : null;
8110
- } catch {
8111
- return null;
8112
- }
8113
- };
8114
-
8115
8542
  // src/acl/related-execution.ts
8116
8543
  init_public_admission();
8117
8544
  init_model_output_planning();
@@ -8132,7 +8559,7 @@ function getServiceExecutors(receiver) {
8132
8559
  if (!registered) authorizationError("unregistered service receiver");
8133
8560
  return registered;
8134
8561
  }
8135
- function createServiceExecution(receiver, access, authorization, applicability = "service", relatedTargets = [], parent, configuration, requestPermissions, hydration = access.operation === "list" ? "find" : "findOne") {
8562
+ function createServiceExecution(receiver, access, authorization, applicability = "service", relatedTargets = [], parent, configuration, requestPermissions, hydration = access.operation === "list" ? "find" : "findOne", snapshotDerivation) {
8136
8563
  const registered = getServiceExecutors(receiver);
8137
8564
  const receiving = registered.binding();
8138
8565
  const binding = Object.freeze({ ...receiving, scopePath: Object.freeze([...receiving.scopePath ?? []]) });
@@ -8146,7 +8573,8 @@ function createServiceExecution(receiver, access, authorization, applicability =
8146
8573
  configuration: configuration ?? registered.configuration(),
8147
8574
  requestPermissions: requestPermissions ?? registered.permissions(),
8148
8575
  listResponse: access.operation === "list" && parent === void 0,
8149
- readResponse: access.operation === "read" && parent === void 0
8576
+ readResponse: access.operation === "read" && parent === void 0,
8577
+ snapshotDerivation
8150
8578
  });
8151
8579
  const execution = Object.freeze(/* @__PURE__ */ Object.create(null));
8152
8580
  executions.set(
@@ -8203,7 +8631,8 @@ function deriveServiceExecution(receiver, parent, access, applicability = "servi
8203
8631
  parent: record3.authorization,
8204
8632
  // The resolver authenticates root-read provenance and the unchanged owner tuple.
8205
8633
  // Effective list access is still a read; write branches cannot inherit this marker.
8206
- readResponse: record3.access.operation === "read" && access.operation === "read"
8634
+ readResponse: record3.access.operation === "read" && access.operation === "read",
8635
+ snapshotDerivation: { kind: "retry", parentBinding: record3.binding }
8207
8636
  });
8208
8637
  const execution = Object.freeze(/* @__PURE__ */ Object.create(null));
8209
8638
  executions.set(
@@ -8357,9 +8786,9 @@ function resolveExistsOptions(service, options = {}) {
8357
8786
 
8358
8787
  // src/services/model-service-intent.ts
8359
8788
  function captureModelServiceIntent(owner, method, args = {}, options = {}) {
8360
- const defaults = owner.defaults;
8789
+ const defaults2 = owner.defaults;
8361
8790
  const posture = owner.getPermissionsPosture();
8362
- const service = { defaults, getPermissionsPosture: () => posture };
8791
+ const service = { defaults: defaults2, getPermissionsPosture: () => posture };
8363
8792
  switch (method) {
8364
8793
  case "find":
8365
8794
  return deepIsolateValue({ args: resolveFindArgs(service, args), options: resolveFindOptions(service, options) });
@@ -8390,6 +8819,7 @@ function captureModelServiceIntent(owner, method, args = {}, options = {}) {
8390
8819
  }
8391
8820
 
8392
8821
  // src/acl/related-execution.ts
8822
+ init_populate_policy2();
8393
8823
  init_service_authorization();
8394
8824
  function staticObjectIdReference(runtime, source, path, target) {
8395
8825
  const model = runtime.getModelInstance(source), related = runtime.getModelInstance(target);
@@ -8406,7 +8836,7 @@ function staticObjectIdReference(runtime, source, path, target) {
8406
8836
  const scalar = type?.instance === "Array" ? type.$embeddedSchemaType ?? type.embeddedSchemaType ?? type.caster : type;
8407
8837
  return scalar?.instance === "ObjectId" && (type?.options?.ref ?? scalar.options?.ref) === target && type?.options?.refPath === void 0 && scalar.options?.refPath === void 0;
8408
8838
  }
8409
- function captureRelatedTargets(runtime, modelName, args = {}, depth = 0, globalOptions = runtime.getGlobalOptions()) {
8839
+ function captureRelatedTargets(runtime, modelName, args = {}, depth = 0, populatePolicyDefaults = capturePopulatePolicyDefaults(runtime)) {
8410
8840
  if (depth > 32) authorizationError("related descriptor depth exceeded");
8411
8841
  assertPublicAdmission(args.populate, "populate");
8412
8842
  assertPublicAdmission(args.include, "include");
@@ -8415,20 +8845,32 @@ function captureRelatedTargets(runtime, modelName, args = {}, depth = 0, globalO
8415
8845
  for (const entry of entries(args.populate)) {
8416
8846
  const path = typeof entry === "string" ? entry : entry.path;
8417
8847
  if (typeof entry !== "string") assertPopulateAccess(entry.access);
8418
- const model = getModelRef(modelName, path, runtime);
8419
- if (model) {
8420
- const target = capturePopulateTargetConfiguration(runtime, model, `${modelName}.${path}`);
8848
+ const target = capturePopulateTargetBinding(runtime, modelName, path);
8849
+ if (target) {
8421
8850
  targets.push({
8422
8851
  path,
8423
- modelName: model,
8424
- configuration: captureModelAuthorizationConfiguration(runtime, model, target.options, globalOptions),
8425
- staticObjectIdReference: staticObjectIdReference(runtime, modelName, path, model)
8852
+ modelName: target.modelName,
8853
+ model: target.model,
8854
+ configuration: captureModelAuthorizationConfiguration(
8855
+ runtime,
8856
+ target.modelName,
8857
+ target.options,
8858
+ populatePolicyDefaults
8859
+ ),
8860
+ staticObjectIdReference: staticObjectIdReference(runtime, modelName, path, target.modelName)
8426
8861
  });
8427
8862
  }
8428
8863
  }
8429
8864
  for (const entry of entries(args.include)) {
8430
8865
  if (!runtime.hasModel(entry.model)) authorizationError(`Model ${entry.model} not found`);
8431
- const configuration = captureModelAuthorizationConfiguration(runtime, entry.model, void 0, globalOptions);
8866
+ const model = runtime.getModelInstance(entry.model);
8867
+ if (!model) authorizationError(`unknown receiving model: ${entry.model}`);
8868
+ const configuration = captureModelAuthorizationConfiguration(
8869
+ runtime,
8870
+ entry.model,
8871
+ void 0,
8872
+ populatePolicyDefaults
8873
+ );
8432
8874
  const queryIntent = entry.op === "count" ? void 0 : captureModelServiceIntent(
8433
8875
  {
8434
8876
  defaults: configuration.defaults ?? {},
@@ -8450,6 +8892,7 @@ function captureRelatedTargets(runtime, modelName, args = {}, depth = 0, globalO
8450
8892
  targets.push({
8451
8893
  path: entry.path,
8452
8894
  modelName: entry.model,
8895
+ model,
8453
8896
  kind: entry.op === "count" ? "count" : "output",
8454
8897
  configuration,
8455
8898
  queryIntent,
@@ -8459,7 +8902,7 @@ function captureRelatedTargets(runtime, modelName, args = {}, depth = 0, globalO
8459
8902
  entry.model,
8460
8903
  queryIntent?.args ?? entry.args ?? {},
8461
8904
  depth + 1,
8462
- globalOptions
8905
+ populatePolicyDefaults
8463
8906
  )
8464
8907
  });
8465
8908
  }
@@ -8476,7 +8919,8 @@ function createRelatedExecution(receiver, access, parent, binding, path) {
8476
8919
  const captured = readServiceAuthorization(parent, binding);
8477
8920
  const target = captured.relatedTargets.find((entry) => entry.path === path);
8478
8921
  const policy = captured.authorization.related[path];
8479
- if (policy && (!target || target.modelName !== getServiceExecutors(receiver).binding().modelName))
8922
+ const receiving = getServiceExecutors(receiver).binding();
8923
+ if (policy && !target || target && (target.modelName !== receiving.modelName || target.model !== void 0 && target.model !== receiving.model))
8480
8924
  authorizationError(`related model mismatch: ${path}`);
8481
8925
  const execution = createServiceExecution(
8482
8926
  receiver,
@@ -8486,7 +8930,9 @@ function createRelatedExecution(receiver, access, parent, binding, path) {
8486
8930
  target?.relatedTargets ?? [],
8487
8931
  parent,
8488
8932
  target?.configuration,
8489
- getAuthorizationPermissions(parent, binding)
8933
+ getAuthorizationPermissions(parent, binding),
8934
+ access.operation === "list" ? "find" : "findOne",
8935
+ { kind: "related", parentBinding: binding, path }
8490
8936
  );
8491
8937
  return target?.queryIntent ? withExecutionQueryIntent(receiver, execution, target.queryIntent) : execution;
8492
8938
  }
@@ -8972,34 +9418,37 @@ var Base = class {
8972
9418
  });
8973
9419
  }
8974
9420
  async getAuthorizedTargetService(modelName, op, path, parentAuthorization) {
8975
- if (hasModelCoreOwner(this.requestCore) && !this.requestRuntime.hasModel(modelName)) {
9421
+ const binding = parentAuthorization ? this.relatedBinding() : void 0;
9422
+ const captured = parentAuthorization ? readServiceAuthorization(parentAuthorization, binding) : void 0;
9423
+ const target = captured?.relatedTargets.find((entry) => entry.path === path);
9424
+ const policy = path ? captured?.authorization.related[path] : void 0;
9425
+ if (target && target.modelName !== modelName)
9426
+ this.throwClientRequestError("bad_request" /* BadRequest */, `related model mismatch: ${path}`);
9427
+ if (hasModelCoreOwner(this.requestCore) && !target?.model && !this.requestRuntime.hasModel(modelName)) {
8976
9428
  this.throwClientRequestError("bad_request" /* BadRequest */, `Model ${modelName} not found`);
8977
9429
  }
8978
- const policy = path ? relatedPolicy(parentAuthorization, this.relatedBinding(), path) : void 0;
8979
- const captured = parentAuthorization ? readServiceAuthorization(parentAuthorization, this.relatedBinding()) : void 0;
8980
- const target = captured?.relatedTargets.find((entry) => entry.path === path);
8981
9430
  const allowed = policy?.operation.mode === "grant" || (target ? await getRequestWorkState(this.req, this.requestRuntime).hookGate.run(
8982
9431
  () => withCapturedModelOperationGuard(
8983
9432
  this.requestCore,
8984
9433
  modelName,
8985
9434
  op,
8986
9435
  target.operationGuard,
8987
- getAuthorizationPermissions(parentAuthorization, this.relatedBinding()),
9436
+ getAuthorizationPermissions(parentAuthorization, binding),
8988
9437
  () => this.requestCore.isAllowed(modelName, op)
8989
9438
  )
8990
9439
  ) : await this.requestCore.isAllowed(modelName, op));
8991
9440
  if (!allowed) {
8992
9441
  this.throwClientRequestError("unauthorized" /* Unauthorized */, "Unauthorized");
8993
9442
  }
8994
- return this.requestCore.getPublicService(modelName);
9443
+ return target?.model ? withCapturedPopulateModel(
9444
+ this.requestRuntime,
9445
+ modelName,
9446
+ target.model,
9447
+ () => this.requestCore.getPublicService(modelName)
9448
+ ) : this.requestCore.getPublicService(modelName);
8995
9449
  }
8996
9450
  relatedBinding() {
8997
- return {
8998
- request: this.req,
8999
- runtime: this.requestRuntime,
9000
- model: this.requestRuntime.getModelInstance(this.modelName),
9001
- modelName: this.modelName
9002
- };
9451
+ return getServiceExecutors(this).binding();
9003
9452
  }
9004
9453
  relatedExecution(svc, include, parentAuthorization) {
9005
9454
  const op = include.op;
@@ -9409,7 +9858,7 @@ var Base = class {
9409
9858
  }
9410
9859
  const state = this.getCorrelatedExecState();
9411
9860
  docs = docs.map(prepareIncludeOutput);
9412
- const resolvedSnapshots = snapshots2 ?? docs.map((doc) => cloneDeep2(toObject(getIncludeSource(doc))));
9861
+ const resolvedSnapshots = snapshots2 ?? docs.map((doc) => cloneDeep3(toObject(getIncludeSource(doc))));
9413
9862
  for (const include of correlatedIncludes) {
9414
9863
  switch (include.op) {
9415
9864
  case "read":
@@ -9788,96 +10237,6 @@ import {
9788
10237
  } from "@web-ts-toolkit/utils";
9789
10238
  import { diff } from "just-diff";
9790
10239
 
9791
- // src/model.ts
9792
- init_runtime_context();
9793
- init_runtime();
9794
- import { cloneDeep as cloneDeep3 } from "@web-ts-toolkit/utils";
9795
- function admitModelPersistence(adapter, scheduler) {
9796
- return {
9797
- modelName: adapter.modelName,
9798
- mongooseModel: adapter.mongooseModel,
9799
- new: () => adapter.new(),
9800
- // Mongoose create(array) otherwise starts all document saves at once. Keep
9801
- // the adapter's array input/output contract, with one permit per item; all
9802
- // items are submitted even if one rejects, as with unordered create(array).
9803
- create: (data) => Array.isArray(data) ? Promise.all(data.map((item) => scheduler.work(async () => (await adapter.create([item]))[0]))) : scheduler.work(() => adapter.create(data)),
9804
- find: (props) => scheduler.work(() => adapter.find(props)),
9805
- findOne: (props) => scheduler.work(() => adapter.findOne(props)),
9806
- exists: (filter2) => scheduler.work(() => adapter.exists(filter2)),
9807
- countDocuments: (filter2) => scheduler.work(() => adapter.countDocuments(filter2)),
9808
- distinct: (field, conditions) => scheduler.work(() => adapter.distinct(field, conditions)),
9809
- aggregate: (pipeline) => scheduler.work(() => adapter.aggregate(pipeline)),
9810
- // Casting builds no persistence work and must not acquire a recursive permit.
9811
- ...adapter.castFilter ? { castFilter: (filter2) => adapter.castFilter(filter2) } : {}
9812
- };
9813
- }
9814
- var Model = class {
9815
- constructor(modelName, runtime) {
9816
- this.modelName = modelName;
9817
- this.runtime = runtime ?? null;
9818
- const resolvedRuntime = runtime ?? getActiveRuntime() ?? defaultRuntime;
9819
- const registered = resolvedRuntime.getModelInstance(modelName);
9820
- if (!registered) {
9821
- throw new Error(
9822
- `Runtime model registry missing model "${modelName}". Pass a mongoose.Model instance to createRouter() or register it with registerModelInstance() before using this runtime.`
9823
- );
9824
- }
9825
- this.mongooseModel = registered;
9826
- if (!this.mongooseModel) return;
9827
- }
9828
- new() {
9829
- const doc = new this.mongooseModel();
9830
- return doc;
9831
- }
9832
- create(data) {
9833
- return this.mongooseModel.create(data);
9834
- }
9835
- find({ filter: filter2, select, sort, populate, limit, hardLimit, skip, lean }) {
9836
- const builder = this.mongooseModel.find(filter2);
9837
- if (select) builder.select(select);
9838
- if (skip) builder.skip(Number(skip));
9839
- const normalizedLimit = Number(limit);
9840
- if (Number.isSafeInteger(normalizedLimit) && normalizedLimit > 0) {
9841
- builder.limit(normalizedLimit);
9842
- } else if (Number.isSafeInteger(hardLimit) && Number(hardLimit) > 0) {
9843
- builder.limit(Number(hardLimit));
9844
- }
9845
- if (sort) builder.sort(sort);
9846
- if (populate) builder.populate(populate);
9847
- if (lean) builder.lean();
9848
- return builder;
9849
- }
9850
- findOne({ filter: filter2, select, sort, populate, lean }) {
9851
- const builder = this.mongooseModel.findOne(filter2);
9852
- if (select) builder.select(select);
9853
- if (sort) builder.sort(sort);
9854
- if (populate) builder.populate(populate);
9855
- if (lean) builder.lean();
9856
- return builder;
9857
- }
9858
- exists(filter2) {
9859
- if (!filter2) return null;
9860
- return this.findOne({ filter: filter2 }).select("_id").lean();
9861
- }
9862
- // see https://mongoosejs.com/docs/api.html#query_Query-countDocuments
9863
- countDocuments(filter2 = {}) {
9864
- return this.mongooseModel.countDocuments(filter2);
9865
- }
9866
- /** Cast a copy using this model's query schema/setters, without executing query middleware or persistence. */
9867
- castFilter(filter2) {
9868
- const query = this.mongooseModel.countDocuments(cloneDeep3(filter2));
9869
- return query.cast(this.mongooseModel);
9870
- }
9871
- // see https://mongoosejs.com/docs/api.html#model_Model.distinct
9872
- distinct(field, conditions = {}) {
9873
- return this.mongooseModel.distinct(field, conditions);
9874
- }
9875
- aggregate(pipeline) {
9876
- return this.mongooseModel.aggregate(pipeline);
9877
- }
9878
- };
9879
- var model_default = Model;
9880
-
9881
10240
  // src/acl/distinct-field-authorization.ts
9882
10241
  init_field_authorization();
9883
10242
  init_field_catalog();
@@ -10002,6 +10361,7 @@ init_document_authorization();
10002
10361
  init_output_field_filter();
10003
10362
  init_field_authorization();
10004
10363
  init_authorization_snapshot();
10364
+ init_unsafe_snapshot_options();
10005
10365
  init_public_admission();
10006
10366
 
10007
10367
  // src/acl/subdocument-output.ts
@@ -10014,6 +10374,7 @@ init_finalize_model_output();
10014
10374
  init_populate_target();
10015
10375
  init_virtual_populate_execution();
10016
10376
  init_request_work();
10377
+ init_populate_policy2();
10017
10378
  var populateExecutors = /* @__PURE__ */ new WeakMap();
10018
10379
  function registerSubdocumentPopulateExecutor(service, execute2, core) {
10019
10380
  populateExecutors.set(service, { execute: execute2, core });
@@ -10046,7 +10407,7 @@ function prepareSubdocumentOutput(service, sub, operation, virtualAccess, output
10046
10407
  service.getServiceModelName(),
10047
10408
  { populate },
10048
10409
  0,
10049
- configuration
10410
+ getCapturedPopulatePolicyDefaults(configuration)
10050
10411
  ),
10051
10412
  void 0,
10052
10413
  configuration,
@@ -11085,12 +11446,15 @@ var Service = class extends Base {
11085
11446
  model: this.model.mongooseModel,
11086
11447
  modelName: this.modelName
11087
11448
  }),
11088
- configuration: () => this.requestRuntime.getModelInstance(this.modelName) ? captureModelAuthorizationConfiguration(
11089
- this.requestRuntime,
11090
- this.modelName,
11091
- { ...this.options, defaults: this.defaults },
11092
- modelServiceGlobalOptions(this, this.requestRuntime)
11093
- ) : { catalog: { paths: [] }, ...this.options },
11449
+ configuration: () => {
11450
+ const populatePolicyDefaults = modelServicePopulatePolicyDefaults(this, this.requestRuntime);
11451
+ return this.requestRuntime.getModelInstance(this.modelName) ? captureModelAuthorizationConfiguration(
11452
+ this.requestRuntime,
11453
+ this.modelName,
11454
+ { ...this.options, defaults: this.defaults },
11455
+ populatePolicyDefaults
11456
+ ) : { catalog: { paths: [] }, ...this.options, populatePolicyDefaults };
11457
+ },
11094
11458
  permissions: () => this.requestCore.getPermissions?.() ?? new permission_default({}),
11095
11459
  parse: (filter2) => this.parseClientData(filter2, this.getCorrelatedExecState().scheduler),
11096
11460
  validate: (filter2, expanded) => {
@@ -11139,7 +11503,7 @@ var Service = class extends Base {
11139
11503
  });
11140
11504
  }
11141
11505
  get options() {
11142
- return modelServiceOptions(this, () => this.getModelRouterOptions(this.modelName));
11506
+ return modelServiceOptions(this, this.requestRuntime, () => this.getModelRouterOptions(this.modelName));
11143
11507
  }
11144
11508
  /**
11145
11509
  * Presentation/query defaults for this service instance; an explicit assignment
@@ -11193,7 +11557,7 @@ var Service = class extends Base {
11193
11557
  ["options", options]
11194
11558
  ]) {
11195
11559
  if (value !== null && (typeof value === "object" || typeof value === "function")) {
11196
- for (const key of ["unsafeSkipListDocumentSnapshotChecks", "unsafeSkipReadDocumentSnapshotChecks"]) {
11560
+ for (const key of unsafeSnapshotOptions) {
11197
11561
  if (key in value) authorizationError(`${slot}.${key} is server model configuration only`);
11198
11562
  }
11199
11563
  }
@@ -11624,14 +11988,14 @@ var Service = class extends Base {
11624
11988
  }
11625
11989
  });
11626
11990
  }
11627
- captureRelated(args, defaults) {
11628
- const globalOptions = modelServiceGlobalOptions(this, this.requestRuntime);
11629
- const effective = { populate: args?.populate ?? defaults?.populate, include: args?.include ?? defaults?.include };
11991
+ captureRelated(args, defaults2) {
11992
+ const populatePolicyDefaults = modelServicePopulatePolicyDefaults(this, this.requestRuntime);
11993
+ const effective = { populate: args?.populate ?? defaults2?.populate, include: args?.include ?? defaults2?.include };
11630
11994
  if (effective.include) {
11631
11995
  const processed = this.processInclude(effective.include);
11632
11996
  effective.include = [...processed.includes, ...processed.correlatedIncludes];
11633
11997
  }
11634
- return captureRelatedTargets(this.requestRuntime, this.modelName, effective, 0, globalOptions);
11998
+ return captureRelatedTargets(this.requestRuntime, this.modelName, effective, 0, populatePolicyDefaults);
11635
11999
  }
11636
12000
  /** Canonical population uses the target's retained policy for both fetch and output. */
11637
12001
  async genExecutionPopulate(execution, access, populate) {
@@ -11657,7 +12021,12 @@ var Service = class extends Base {
11657
12021
  const modelName = target?.modelName;
11658
12022
  if (!modelName) continue;
11659
12023
  const policy = relatedPolicy(state.authorization, state.binding, descriptor.path);
11660
- const svc = this.requestCore.getPublicService(modelName);
12024
+ const svc = withCapturedPopulateModel(
12025
+ this.requestRuntime,
12026
+ modelName,
12027
+ target.model,
12028
+ () => this.requestCore.getPublicService(modelName)
12029
+ );
11661
12030
  const child = createRelatedExecution(
11662
12031
  svc,
11663
12032
  {
@@ -11702,8 +12071,8 @@ var Service = class extends Base {
11702
12071
  snapshot: readServiceAuthorization(childState.authorization, childState.binding).configuration,
11703
12072
  fetchBinding: {
11704
12073
  runtime: this.requestRuntime,
11705
- model: childState.binding.model,
11706
- schema: childState.binding.model.schema,
12074
+ model: target.model,
12075
+ schema: target.model.schema,
11707
12076
  configuration: targetConfiguration,
11708
12077
  requestRead: targetAccess === "read" && policy?.operation.mode !== "grant" && readServiceAuthorization(childState.authorization, childState.binding).authorization.rows.mode === "request",
11709
12078
  staticObjectIdReference: captured.relatedTargets.find((target2) => target2.path === descriptor.path)?.staticObjectIdReference
@@ -14560,9 +14929,20 @@ var Core = class {
14560
14929
  if (!isString6(p)) assertPopulateAccess(p.access);
14561
14930
  }
14562
14931
  const runtime = this.requestRuntime;
14563
- const globalOptions = modelServiceGlobalOptions(this, runtime);
14564
- const relatedTargets = captureRelatedTargets(runtime, modelName, { populate: descriptors }, 0, globalOptions);
14565
- const sourceConfiguration = captureModelAuthorizationConfiguration(runtime, modelName, void 0, globalOptions);
14932
+ const populatePolicyDefaults = modelServicePopulatePolicyDefaults(this, runtime);
14933
+ const relatedTargets = captureRelatedTargets(
14934
+ runtime,
14935
+ modelName,
14936
+ { populate: descriptors },
14937
+ 0,
14938
+ populatePolicyDefaults
14939
+ );
14940
+ const sourceConfiguration = captureModelAuthorizationConfiguration(
14941
+ runtime,
14942
+ modelName,
14943
+ void 0,
14944
+ populatePolicyDefaults
14945
+ );
14566
14946
  const originalPermissions = this.getGlobalPermissions();
14567
14947
  const permissions = new permission_default(
14568
14948
  Object.fromEntries(originalPermissions.keys.map((key) => [key, originalPermissions.has(key)]))
@@ -14659,7 +15039,15 @@ var Core = class {
14659
15039
  docPermissionsAccess: planAccess,
14660
15040
  requestedSelect: originalSelect,
14661
15041
  plan: targetPlan,
14662
- snapshot: targetSnapshot
15042
+ snapshot: targetSnapshot,
15043
+ fetchBinding: {
15044
+ runtime,
15045
+ model: target.model,
15046
+ schema: target.model.schema,
15047
+ configuration: targetConfiguration,
15048
+ requestRead: populateAccess === "read",
15049
+ staticObjectIdReference: target.staticObjectIdReference
15050
+ }
14663
15051
  });
14664
15052
  return ret;
14665
15053
  })