@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.js CHANGED
@@ -29,6 +29,26 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
29
29
  ));
30
30
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
31
31
 
32
+ // src/acl/unsafe-snapshot-options.ts
33
+ var unsafeSnapshotCheckOptions, unsafeInitialOutputCopyOptions, unsafeSnapshotOptions;
34
+ var init_unsafe_snapshot_options = __esm({
35
+ "src/acl/unsafe-snapshot-options.ts"() {
36
+ unsafeSnapshotCheckOptions = [
37
+ "unsafeSkipListDocumentSnapshotChecks",
38
+ "unsafeSkipReadDocumentSnapshotChecks",
39
+ "unsafeSkipListOutputSnapshotChecks",
40
+ "unsafeSkipReadOutputSnapshotChecks",
41
+ "unsafeSkipListNestedDocumentSnapshotChecks",
42
+ "unsafeSkipReadNestedDocumentSnapshotChecks"
43
+ ];
44
+ unsafeInitialOutputCopyOptions = [
45
+ "unsafeSkipListInitialOutputSnapshotCopy",
46
+ "unsafeSkipReadInitialOutputSnapshotCopy"
47
+ ];
48
+ unsafeSnapshotOptions = [...unsafeSnapshotCheckOptions, ...unsafeInitialOutputCopyOptions];
49
+ }
50
+ });
51
+
32
52
  // src/validation/public-admission.ts
33
53
  function assertPublicAdmission(input, kind = "envelope") {
34
54
  const pending = [{ value: input, kind, path: "request" }];
@@ -48,7 +68,7 @@ function assertPublicAdmission(input, kind = "envelope") {
48
68
  for (const key of privateControls) {
49
69
  if (key in record3) {
50
70
  throw new PublicAdmissionError(
51
- 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`
71
+ 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`
52
72
  );
53
73
  }
54
74
  }
@@ -68,9 +88,9 @@ function assertPublicAdmission(input, kind = "envelope") {
68
88
  for (const key of ["filter", "match", "data"]) add(record3[key], "data", key);
69
89
  }
70
90
  }
71
- function assertHydrationDefaults(defaults) {
72
- if (defaults && typeof defaults === "object") {
73
- const record3 = defaults;
91
+ function assertHydrationDefaults(defaults2) {
92
+ if (defaults2 && typeof defaults2 === "object") {
93
+ const record3 = defaults2;
74
94
  if ("hydration" in record3)
75
95
  throw new TypeError("defaults.hydration is unsupported; use model hydration configuration");
76
96
  for (const bucket of [
@@ -98,11 +118,11 @@ function assertHydrationDefaults(defaults) {
98
118
  }
99
119
  }
100
120
  }
101
- function assertPublicDefaults(defaults) {
102
- assertHydrationDefaults(defaults);
103
- assertPublicAdmission(defaults);
104
- if (defaults && typeof defaults === "object") {
105
- for (const value of Object.values(defaults)) assertPublicAdmission(value);
121
+ function assertPublicDefaults(defaults2) {
122
+ assertHydrationDefaults(defaults2);
123
+ assertPublicAdmission(defaults2);
124
+ if (defaults2 && typeof defaults2 === "object") {
125
+ for (const value of Object.values(defaults2)) assertPublicAdmission(value);
106
126
  }
107
127
  }
108
128
  function pickPublicKeys(input, keys2) {
@@ -133,6 +153,7 @@ var init_public_admission = __esm({
133
153
  "src/validation/public-admission.ts"() {
134
154
  import_express_json_router = __toESM(require("@web-ts-toolkit/express-json-router"));
135
155
  import_utils = require("@web-ts-toolkit/utils");
156
+ init_unsafe_snapshot_options();
136
157
  privateControls = [
137
158
  "authorization",
138
159
  "overrides",
@@ -141,6 +162,7 @@ var init_public_admission = __esm({
141
162
  "execution",
142
163
  "executionContext",
143
164
  "serviceExecutionContext",
165
+ "snapshotDerivation",
144
166
  "resolvedAuthorization",
145
167
  "preparedQuery",
146
168
  "preparedFilter",
@@ -149,8 +171,7 @@ var init_public_admission = __esm({
149
171
  "skipParsing",
150
172
  "skipAuthorization",
151
173
  "alreadyAuthorized",
152
- "unsafeSkipListDocumentSnapshotChecks",
153
- "unsafeSkipReadDocumentSnapshotChecks",
174
+ ...unsafeSnapshotOptions,
154
175
  "operation"
155
176
  ];
156
177
  PublicAdmissionError = class extends import_express_json_router.default.clientErrors.BadRequestError {
@@ -204,6 +225,37 @@ var init_hydration = __esm({
204
225
  }
205
226
  });
206
227
 
228
+ // src/options/populate-policy.ts
229
+ function isPopulatePolicyKey(key) {
230
+ return populatePolicyKeys.includes(key);
231
+ }
232
+ function normalizePopulatePolicyValue(value) {
233
+ return value === void 0 ? void 0 : value !== false;
234
+ }
235
+ function normalizePopulatePolicyOptions(options) {
236
+ const next = { ...options };
237
+ for (const key of populatePolicyKeys) {
238
+ if (key in options)
239
+ next[key] = normalizePopulatePolicyValue(options[key]);
240
+ }
241
+ return next;
242
+ }
243
+ function assertNoGlobalPopulatePolicy(key) {
244
+ if (isPopulatePolicyKey(key))
245
+ throw new TypeError(
246
+ `${key} is target-model configuration; migrate to setModelOptions(targetModelName, { ${key}: value }) or setDefaultModelOptions({ ${key}: value }) for runtime model defaults`
247
+ );
248
+ }
249
+ var populatePolicyKeys;
250
+ var init_populate_policy = __esm({
251
+ "src/options/populate-policy.ts"() {
252
+ populatePolicyKeys = [
253
+ "requireOperationAccessForPopulateQueries",
254
+ "requireOperationAccessForPopulateDependencies"
255
+ ];
256
+ }
257
+ });
258
+
207
259
  // src/helpers/collection.ts
208
260
  var import_sift, import_utils2, filterCollection, findElement, findElementById;
209
261
  var init_collection = __esm({
@@ -1319,7 +1371,7 @@ var init_logger_default = __esm({
1319
1371
  });
1320
1372
 
1321
1373
  // src/options/manager.ts
1322
- var import_utils11, toPath, cloneConfigValue, cloneForRead, freezeConfigValue, cloneAndFreezeForStore, getNestedOption, resolveNestedOption, OptionsManager;
1374
+ var import_utils11, toPath, cloneConfigValue, cloneForRead, freezeConfigValue, cloneAndFreezeForStore, cloneOptionsSnapshot, getNestedOption, resolveNestedOption, OptionsManager;
1323
1375
  var init_manager = __esm({
1324
1376
  "src/options/manager.ts"() {
1325
1377
  import_utils11 = require("@web-ts-toolkit/utils");
@@ -1383,6 +1435,7 @@ var init_manager = __esm({
1383
1435
  return value;
1384
1436
  };
1385
1437
  cloneAndFreezeForStore = (value) => freezeConfigValue(cloneForRead(value));
1438
+ cloneOptionsSnapshot = (value) => freezeConfigValue(cloneForRead(value));
1386
1439
  getNestedOption = (manager, key, defaultValue) => resolveNestedOption((path, fallback) => manager.get(path, fallback), String(key), defaultValue);
1387
1440
  resolveNestedOption = (read, key, defaultValue) => {
1388
1441
  const keys2 = key.split(".");
@@ -1991,10 +2044,76 @@ function outputIdentities(value) {
1991
2044
  visit(value);
1992
2045
  return Object.freeze(result2);
1993
2046
  }
1994
- var import_node_util3, import_mongoose3, import_express_json_router3, ServiceAuthorizationError, unsafeKeys;
2047
+ function tryOutputIdentitiesWithoutSnapshot(value) {
2048
+ const identities = [];
2049
+ const seen = /* @__PURE__ */ new WeakSet();
2050
+ const active = /* @__PURE__ */ new WeakSet();
2051
+ const fallback = {};
2052
+ let nodes = 0;
2053
+ function visit(input, depth) {
2054
+ if (++nodes > 2e4 || depth > 100) authorizationError("snapshot exceeds structural limits");
2055
+ if (typeof input === "function") authorizationError("functions are not policy values");
2056
+ if (typeof input === "symbol") authorizationError("symbols are not policy values");
2057
+ if (input === null || typeof input !== "object") return;
2058
+ if (import_node_util3.types.isProxy(input)) throw fallback;
2059
+ if (active.has(input)) authorizationError("cyclic input");
2060
+ if (!seen.has(input)) {
2061
+ seen.add(input);
2062
+ identities.push(input);
2063
+ }
2064
+ const prototype = Object.getPrototypeOf(input);
2065
+ if (import_node_util3.types.isDate(input)) {
2066
+ if (prototype === Date.prototype) return;
2067
+ throw fallback;
2068
+ }
2069
+ if (import_node_util3.types.isRegExp(input)) {
2070
+ if (prototype === RegExp.prototype) return;
2071
+ throw fallback;
2072
+ }
2073
+ if (import_node_util3.types.isUint8Array(input)) {
2074
+ if (prototype === import_node_buffer.Buffer.prototype) return;
2075
+ throw fallback;
2076
+ }
2077
+ if (import_node_util3.types.isMap(input) || import_node_util3.types.isSet(input)) throw fallback;
2078
+ const array = Array.isArray(input);
2079
+ if (!array) {
2080
+ if (prototype !== Object.prototype && prototype !== null) {
2081
+ let parent = prototype;
2082
+ for (let count = 0; parent && count < 100; count++) {
2083
+ if (import_node_util3.types.isProxy(parent)) throw fallback;
2084
+ if (parent === import_mongoose3.mongo.BSON.BSONValue.prototype) return;
2085
+ parent = Object.getPrototypeOf(parent);
2086
+ }
2087
+ throw fallback;
2088
+ }
2089
+ } else if (input.length > 2e4) authorizationError("snapshot array exceeds structural limits");
2090
+ active.add(input);
2091
+ try {
2092
+ for (const key of Reflect.ownKeys(input)) {
2093
+ if (array && key === "length") continue;
2094
+ if (typeof key !== "string" || unsafeKeys.has(key)) authorizationError("unsafe snapshot key");
2095
+ if (array && !/^(0|[1-9]\d*)$/.test(key)) authorizationError("invalid array property");
2096
+ const descriptor = Object.getOwnPropertyDescriptor(input, key);
2097
+ if (!("value" in descriptor)) authorizationError("accessor/non-enumerable input");
2098
+ visit(descriptor.value, depth + 1);
2099
+ }
2100
+ } finally {
2101
+ active.delete(input);
2102
+ }
2103
+ }
2104
+ try {
2105
+ visit(value, 0);
2106
+ return Object.freeze(identities);
2107
+ } catch (error2) {
2108
+ if (error2 !== fallback) throw error2;
2109
+ return void 0;
2110
+ }
2111
+ }
2112
+ var import_node_util3, import_node_buffer, import_mongoose3, import_express_json_router3, ServiceAuthorizationError, unsafeKeys;
1995
2113
  var init_authorization_snapshot = __esm({
1996
2114
  "src/acl/authorization-snapshot.ts"() {
1997
2115
  import_node_util3 = require("util");
2116
+ import_node_buffer = require("buffer");
1998
2117
  import_mongoose3 = require("mongoose");
1999
2118
  import_express_json_router3 = __toESM(require("@web-ts-toolkit/express-json-router"));
2000
2119
  ServiceAuthorizationError = class extends import_express_json_router3.default.clientErrors.BadRequestError {
@@ -2031,6 +2150,9 @@ function isInputVirtualPath(catalog, path) {
2031
2150
  return false;
2032
2151
  }
2033
2152
  function matchesCatalogPattern(pattern, path, descendants = false) {
2153
+ if (typeof pattern === "string" && typeof path === "string" && !pattern.includes("$*")) {
2154
+ return pattern === path || !!descendants && path.startsWith(pattern) && path[pattern.length] === ".";
2155
+ }
2034
2156
  const expected = pattern.split(".");
2035
2157
  const actual = path.split(".");
2036
2158
  return (descendants ? actual.length >= expected.length : actual.length === expected.length) && expected.every((part, index) => part === "$*" || part === actual[index]);
@@ -2163,8 +2285,45 @@ var init_field_catalog = __esm({
2163
2285
  }
2164
2286
  });
2165
2287
 
2288
+ // src/runtime-context.ts
2289
+ function runWithRuntime(runtime, callback) {
2290
+ return runtimeStorage.run(runtime, callback);
2291
+ }
2292
+ function getActiveRuntime() {
2293
+ return runtimeStorage.getStore() ?? null;
2294
+ }
2295
+ var import_node_async_hooks2, runtimeStorage;
2296
+ var init_runtime_context = __esm({
2297
+ "src/runtime-context.ts"() {
2298
+ import_node_async_hooks2 = require("async_hooks");
2299
+ runtimeStorage = new import_node_async_hooks2.AsyncLocalStorage();
2300
+ }
2301
+ });
2302
+
2303
+ // src/meta.ts
2304
+ var getRuntime, getModelReference;
2305
+ var init_meta = __esm({
2306
+ "src/meta.ts"() {
2307
+ init_runtime();
2308
+ init_runtime_context();
2309
+ getRuntime = () => getActiveRuntime() ?? defaultRuntime;
2310
+ getModelReference = (modelName, refPath, runtime = getRuntime()) => {
2311
+ const instance = runtime.getModelInstance(modelName);
2312
+ let type = instance?.schema.path(refPath);
2313
+ const result2 = {};
2314
+ while (type) {
2315
+ result2.ref ??= type.options?.ref;
2316
+ result2.refPath ??= type.options?.refPath;
2317
+ if (type.instance !== "Array") break;
2318
+ type = type.$embeddedSchemaType ?? type.embeddedSchemaType ?? type.caster;
2319
+ }
2320
+ return result2;
2321
+ };
2322
+ }
2323
+ });
2324
+
2166
2325
  // src/acl/populate-target-configuration.ts
2167
- function capturePopulateTargetConfiguration(runtime, modelName, source, proposedOptions) {
2326
+ function capturePopulateTargetConfiguration(runtime, modelName, source, proposedOptions, defaults2 = runtime.getDefaultModelOptions()) {
2168
2327
  const label = `Populate target "${modelName}" for ${source}`;
2169
2328
  if (!proposedOptions && !runtime.hasModel(modelName))
2170
2329
  authorizationError(
@@ -2173,18 +2332,77 @@ function capturePopulateTargetConfiguration(runtime, modelName, source, proposed
2173
2332
  const model = runtime.getModelInstance(modelName);
2174
2333
  if (!model) authorizationError(`${label} requires an actual registered Mongoose model in this runtime`);
2175
2334
  const options = proposedOptions ?? runtime.getModelOptions(modelName);
2176
- const permissionSchema = options.permissionSchema === void 0 ? runtime.getDefaultModelOption("permissionSchema") : options.permissionSchema;
2335
+ const permissionSchema = options.permissionSchema === void 0 ? defaults2.permissionSchema : options.permissionSchema;
2177
2336
  if (!(0, import_utils15.isPlainObject)(permissionSchema))
2178
2337
  authorizationError(
2179
2338
  `${label} requires an effective object permissionSchema; configure the model or runtime model defaults ({} explicitly closes business fields)`
2180
2339
  );
2181
2340
  return { model, options: { ...options, permissionSchema } };
2182
2341
  }
2342
+ function capturePopulateTargetBinding(runtime, sourceModelName, path) {
2343
+ const { ref, refPath } = getModelReference(sourceModelName, path, runtime);
2344
+ if (refPath !== void 0 || typeof ref === "function" && !("modelName" in ref))
2345
+ authorizationError(
2346
+ `Populate target for ${sourceModelName}.${path} requires a static string or Mongoose Model-valued source ref; dynamic refs/refPath cannot be bound before I/O`
2347
+ );
2348
+ const modelName = typeof ref === "string" ? ref : ref?.modelName;
2349
+ if (!modelName) return void 0;
2350
+ const target = capturePopulateTargetConfiguration(runtime, modelName, `${sourceModelName}.${path}`);
2351
+ const source = runtime.getModelInstance(sourceModelName);
2352
+ const actual = typeof ref === "string" ? source?.db.models[ref] : ref;
2353
+ if (!actual)
2354
+ authorizationError(
2355
+ `Populate target "${modelName}" for ${sourceModelName}.${path} is missing on the source connection; configure the actual model bound to the source ref in this runtime`
2356
+ );
2357
+ if (actual !== target.model)
2358
+ authorizationError(
2359
+ `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`
2360
+ );
2361
+ return { ...target, modelName };
2362
+ }
2183
2363
  var import_utils15;
2184
2364
  var init_populate_target_configuration = __esm({
2185
2365
  "src/acl/populate-target-configuration.ts"() {
2186
2366
  import_utils15 = require("@web-ts-toolkit/utils");
2187
2367
  init_authorization_snapshot();
2368
+ init_meta();
2369
+ }
2370
+ });
2371
+
2372
+ // src/acl/populate-policy.ts
2373
+ function capturePopulatePolicyDefaults(runtime) {
2374
+ const options = runtime.getDefaultModelOptions();
2375
+ const token = () => {
2376
+ };
2377
+ defaults.set(
2378
+ token,
2379
+ Object.freeze({
2380
+ requireOperationAccessForPopulateQueries: options.requireOperationAccessForPopulateQueries !== false,
2381
+ requireOperationAccessForPopulateDependencies: options.requireOperationAccessForPopulateDependencies !== false
2382
+ })
2383
+ );
2384
+ return token;
2385
+ }
2386
+ function resolvePopulatePolicy(options, token) {
2387
+ const captured = defaults.get(token);
2388
+ if (!captured) return authorizationError("invalid captured populate model defaults");
2389
+ const resolve = (key) => (options[key] === void 0 ? captured[key] : options[key]) !== false;
2390
+ return Object.freeze({
2391
+ requireOperationAccessForPopulateQueries: resolve(populatePolicyKeys[0]),
2392
+ requireOperationAccessForPopulateDependencies: resolve(populatePolicyKeys[1])
2393
+ });
2394
+ }
2395
+ function getCapturedPopulatePolicyDefaults(configuration) {
2396
+ const token = configuration.populatePolicyDefaults;
2397
+ if (!token || !defaults.has(token)) return authorizationError("missing captured populate model defaults");
2398
+ return token;
2399
+ }
2400
+ var defaults;
2401
+ var init_populate_policy2 = __esm({
2402
+ "src/acl/populate-policy.ts"() {
2403
+ init_populate_policy();
2404
+ init_authorization_snapshot();
2405
+ defaults = /* @__PURE__ */ new WeakMap();
2188
2406
  }
2189
2407
  });
2190
2408
 
@@ -2278,9 +2496,7 @@ function normalizeSelection(select, catalog, label) {
2278
2496
  includeId: selection.includes("_id")
2279
2497
  };
2280
2498
  }
2281
- function captureVirtualPopulateDependencies(runtime, modelName, options, globalOptions = runtime.getGlobalOptions()) {
2282
- const requireOperationAccessForPopulateDependencies = globalOptions.requireOperationAccessForPopulateDependencies !== false;
2283
- const requireOperationAccessForPopulateQueries = globalOptions.requireOperationAccessForPopulateQueries !== false;
2499
+ function captureVirtualPopulateDependencies(runtime, modelName, options, populatePolicyDefaults = capturePopulatePolicyDefaults(runtime), proposed) {
2284
2500
  const model = runtime.getModelInstance(modelName);
2285
2501
  const targets = /* @__PURE__ */ new Map();
2286
2502
  const scopes = [];
@@ -2324,18 +2540,19 @@ function captureVirtualPopulateDependencies(runtime, modelName, options, globalO
2324
2540
  runtime,
2325
2541
  ref,
2326
2542
  `dependsOnPopulate virtual "${label}"`,
2327
- ref === modelName ? options : void 0
2543
+ ref === modelName ? options : proposed?.models.get(ref),
2544
+ proposed?.defaults
2328
2545
  );
2329
- const defaults = runtime.getDefaultModelOptions();
2330
- const readOption = (key) => resolveNestedOption((path2, fallback) => (0, import_utils16.get)(targetOptions, path2, fallback), key, (0, import_utils16.get)(defaults, key));
2331
- const documentPermissionField = targetOptions.documentPermissionField ?? defaults.documentPermissionField;
2546
+ const defaults2 = proposed?.defaults ?? runtime.getDefaultModelOptions();
2547
+ const readOption = (key) => resolveNestedOption((path2, fallback) => (0, import_utils16.get)(targetOptions, path2, fallback), key, (0, import_utils16.get)(defaults2, key));
2548
+ const documentPermissionField = targetOptions.documentPermissionField ?? defaults2.documentPermissionField;
2332
2549
  const catalog = captureAuthorizationFieldCatalog(targetModel.schema, void 0, documentPermissionField);
2333
2550
  const configuration = copyAuthorizationValue(
2334
2551
  {
2335
2552
  catalog,
2336
2553
  documentPermissionField,
2337
- requireOperationAccessForPopulateDependencies,
2338
- requireOperationAccessForPopulateQueries,
2554
+ populatePolicyDefaults,
2555
+ ...resolvePopulatePolicy(targetOptions, populatePolicyDefaults),
2339
2556
  permissionSchema: targetOptions.permissionSchema,
2340
2557
  operationAccess: { read: readOption("operationAccess.read") },
2341
2558
  baseFilter: { read: readOption("baseFilter.read") },
@@ -2416,8 +2633,8 @@ function captureVirtualPopulateDependencies(runtime, modelName, options, globalO
2416
2633
  visit(options.virtuals ?? {}, model?.schema, "", [], !!model && varyingModel(model));
2417
2634
  return Object.freeze({ scopes: Object.freeze(scopes) });
2418
2635
  }
2419
- function captureVirtualPopulateSnapshot(runtime, modelName, options, globalOptions = runtime.getGlobalOptions()) {
2420
- const snapshot = captureVirtualPopulateDependencies(runtime, modelName, options, globalOptions);
2636
+ function captureVirtualPopulateSnapshot(runtime, modelName, options, populatePolicyDefaults = capturePopulatePolicyDefaults(runtime)) {
2637
+ const snapshot = captureVirtualPopulateDependencies(runtime, modelName, options, populatePolicyDefaults);
2421
2638
  const token = () => {
2422
2639
  };
2423
2640
  snapshots.set(token, snapshot);
@@ -2451,6 +2668,7 @@ var init_virtual_populate_dependencies = __esm({
2451
2668
  init_field_catalog();
2452
2669
  init_virtual_descriptor();
2453
2670
  init_populate_target_configuration();
2671
+ init_populate_policy2();
2454
2672
  elementType = (type) => type.$embeddedSchemaType ?? type.embeddedSchemaType ?? type.caster;
2455
2673
  join = (prefix, path) => prefix ? `${prefix}.${path}` : path;
2456
2674
  within = (path, parent) => path === parent || path.startsWith(`${parent}.`);
@@ -2465,12 +2683,13 @@ var init_virtual_populate_dependencies = __esm({
2465
2683
  });
2466
2684
 
2467
2685
  // src/runtime.ts
2468
- var import_mongoose4, import_mongoose_schema_jsonschema, import_utils17, 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;
2686
+ var import_mongoose4, import_mongoose_schema_jsonschema, import_utils17, 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;
2469
2687
  var init_runtime = __esm({
2470
2688
  "src/runtime.ts"() {
2471
2689
  import_mongoose4 = __toESM(require("mongoose"));
2472
2690
  init_public_admission();
2473
2691
  init_hydration();
2692
+ init_populate_policy();
2474
2693
  import_mongoose_schema_jsonschema = __toESM(require("mongoose-schema-jsonschema"));
2475
2694
  import_utils17 = require("@web-ts-toolkit/utils");
2476
2695
  init_helpers();
@@ -2482,6 +2701,7 @@ var init_runtime = __esm({
2482
2701
  init_request_complexity();
2483
2702
  init_virtual_descriptor();
2484
2703
  init_virtual_populate_dependencies();
2704
+ init_unsafe_snapshot_options();
2485
2705
  mongooseJsonSchemaInitialized = false;
2486
2706
  ensureMongooseJsonSchemaInitialized = () => {
2487
2707
  if (mongooseJsonSchemaInitialized) return;
@@ -2494,6 +2714,15 @@ var init_runtime = __esm({
2494
2714
  basePath: null,
2495
2715
  alwaysSelectFields: []
2496
2716
  };
2717
+ modelOverrides = (options) => {
2718
+ const result2 = Object.fromEntries(
2719
+ Object.entries(options).filter(
2720
+ ([key, value]) => value !== void 0 || key === "operationAccess" || isPopulatePolicyKey(key)
2721
+ )
2722
+ );
2723
+ for (const key of unsafeSnapshotOptions) if (key in result2) result2[key] = result2[key] === true;
2724
+ return cloneOptionsSnapshot(result2);
2725
+ };
2497
2726
  defaultDataOptions = {
2498
2727
  basePath: null,
2499
2728
  parentPath: "/",
@@ -2627,12 +2856,12 @@ var init_runtime = __esm({
2627
2856
  }
2628
2857
  return fields;
2629
2858
  };
2630
- cloneVirtualsForValidation = (value) => {
2631
- if (Array.isArray(value)) return value.map((item) => cloneVirtualsForValidation(item));
2859
+ cloneModelOptionForUpdate = (value) => {
2860
+ if (Array.isArray(value)) return value.map((item) => cloneModelOptionForUpdate(item));
2632
2861
  if (!value || typeof value !== "object") return value;
2633
2862
  if (Object.getPrototypeOf(value) !== Object.prototype) return value;
2634
2863
  return Object.fromEntries(
2635
- Object.entries(value).map(([k, v]) => [k, cloneVirtualsForValidation(v)])
2864
+ Object.entries(value).map(([k, v]) => [k, cloneModelOptionForUpdate(v)])
2636
2865
  );
2637
2866
  };
2638
2867
  validateVirtualDependsOn = (dependsOn, entryLabel, storedFields, siblingVirtualNames) => {
@@ -2828,8 +3057,6 @@ var init_runtime = __esm({
2828
3057
  {
2829
3058
  requestPermissionField: "_permissions",
2830
3059
  globalPermissions: () => ({}),
2831
- requireOperationAccessForPopulateQueries: true,
2832
- requireOperationAccessForPopulateDependencies: true,
2833
3060
  logger: defaultLogger,
2834
3061
  requestComplexity: defaultRequestComplexity
2835
3062
  },
@@ -2844,11 +3071,20 @@ var init_runtime = __esm({
2844
3071
  queryRouteSegment: "__query",
2845
3072
  mutationRouteSegment: "__mutation",
2846
3073
  operationAccess: false,
3074
+ requireOperationAccessForPopulateQueries: true,
3075
+ requireOperationAccessForPopulateDependencies: true,
2847
3076
  modelPermissionPrefix: "",
2848
3077
  unsafeSkipListDocumentSnapshotChecks: false,
2849
- unsafeSkipReadDocumentSnapshotChecks: false
3078
+ unsafeSkipReadDocumentSnapshotChecks: false,
3079
+ unsafeSkipListOutputSnapshotChecks: false,
3080
+ unsafeSkipReadOutputSnapshotChecks: false,
3081
+ unsafeSkipListNestedDocumentSnapshotChecks: false,
3082
+ unsafeSkipReadNestedDocumentSnapshotChecks: false,
3083
+ unsafeSkipListInitialOutputSnapshotCopy: false,
3084
+ unsafeSkipReadInitialOutputSnapshotCopy: false
2850
3085
  }).build();
2851
3086
  this.modelOptions = {};
3087
+ this.modelOptionOverrides = {};
2852
3088
  this.modelJsonSchemas = {};
2853
3089
  this.dataOptions = {};
2854
3090
  this.modelRefs = {};
@@ -2936,6 +3172,7 @@ var init_runtime = __esm({
2936
3172
  globalOptions: this.globalOptions.snapshot(),
2937
3173
  defaultModelOptions: this.defaultModelOptions.snapshot(),
2938
3174
  modelOptions: modelOptionsSnap,
3175
+ modelOptionOverrides: { ...this.modelOptionOverrides },
2939
3176
  dataOptions: dataOptionsSnap,
2940
3177
  modelInstances: { ...this.modelInstances },
2941
3178
  modelJsonSchemas: { ...this.modelJsonSchemas },
@@ -2950,6 +3187,10 @@ var init_runtime = __esm({
2950
3187
  restoreBootstrapSnapshot(snapshot) {
2951
3188
  this.globalOptions.restore(snapshot.globalOptions);
2952
3189
  this.defaultModelOptions.restore(snapshot.defaultModelOptions);
3190
+ for (const name of Object.keys(this.modelOptionOverrides)) delete this.modelOptionOverrides[name];
3191
+ for (const [name, options] of Object.entries(snapshot.modelOptionOverrides)) {
3192
+ this.modelOptionOverrides[name] = modelOverrides(options);
3193
+ }
2953
3194
  for (const name of Object.keys(this.modelOptions)) {
2954
3195
  if (!(name in snapshot.modelOptions)) {
2955
3196
  delete this.modelOptions[name];
@@ -2960,8 +3201,7 @@ var init_runtime = __esm({
2960
3201
  if (existing) {
2961
3202
  existing.restore(opts);
2962
3203
  } else {
2963
- const mgr = this.createModelOptions(name);
2964
- mgr.restore(opts);
3204
+ const mgr = this.createModelOptions(name, opts);
2965
3205
  this.modelOptions[name] = mgr;
2966
3206
  }
2967
3207
  }
@@ -3004,18 +3244,11 @@ var init_runtime = __esm({
3004
3244
  }
3005
3245
  /** Shallowly replace supplied global values; nested objects such as requestComplexity are not deep-merged. */
3006
3246
  setGlobalOptions(options) {
3007
- const next = { ...options };
3008
- if ("requireOperationAccessForPopulateQueries" in next)
3009
- next.requireOperationAccessForPopulateQueries = next.requireOperationAccessForPopulateQueries !== false;
3010
- if ("requireOperationAccessForPopulateDependencies" in next)
3011
- next.requireOperationAccessForPopulateDependencies = next.requireOperationAccessForPopulateDependencies !== false;
3012
- this.globalOptions.assign(next);
3247
+ for (const key of populatePolicyKeys) if (key in options) assertNoGlobalPopulatePolicy(key);
3248
+ this.globalOptions.assign({ ...options });
3013
3249
  }
3014
3250
  setGlobalOption(key, value) {
3015
- if (key === "requireOperationAccessForPopulateQueries" || key === "requireOperationAccessForPopulateDependencies") {
3016
- this.globalOptions.set(key, value !== false);
3017
- return;
3018
- }
3251
+ assertNoGlobalPopulatePolicy(String(key));
3019
3252
  this.globalOptions.set(key, value);
3020
3253
  }
3021
3254
  getGlobalOptions() {
@@ -3024,28 +3257,30 @@ var init_runtime = __esm({
3024
3257
  getGlobalOption(key, defaultValue) {
3025
3258
  return this.globalOptions.get(key, defaultValue);
3026
3259
  }
3027
- /** Update model starting defaults shallowly; already-stored model values are not broadcast-replaced. */
3260
+ /** Update inherited model defaults shallowly. Explicit model values and captured calls are unchanged. */
3028
3261
  setDefaultModelOptions(options) {
3029
3262
  assertPublicDefaults(options.defaults);
3030
3263
  if ("hydration" in options) options = { ...options, hydration: normalizeHydration(options.hydration) };
3031
- this.defaultModelOptions.assign(options);
3264
+ const draft = new OptionsManager(
3265
+ this.getDefaultModelOptions()
3266
+ ).build();
3267
+ draft.assign(normalizePopulatePolicyOptions(options));
3268
+ this.publishDefaultModelOptions(draft.fetch());
3032
3269
  }
3033
3270
  setDefaultModelOption(key, value) {
3034
3271
  const keyStr = String(key);
3035
- if (keyStr === "hydration" || keyStr.startsWith("hydration.")) {
3036
- this.defaultModelOptions.set(
3037
- "hydration",
3038
- normalizeHydrationUpdate(this.getDefaultModelOptions().hydration, keyStr, value)
3039
- );
3040
- return;
3041
- }
3042
- if (keyStr === "defaults") assertPublicDefaults(value);
3043
- else if (keyStr.startsWith("defaults.")) {
3044
- const proposed = {};
3045
- (0, import_utils17.set)(proposed, keyStr.slice("defaults.".length), value);
3046
- assertPublicDefaults(proposed);
3272
+ const draft = new OptionsManager(
3273
+ this.getDefaultModelOptions()
3274
+ ).build();
3275
+ if (isPopulatePolicyKey(keyStr)) {
3276
+ draft.set(keyStr, normalizePopulatePolicyValue(value));
3277
+ } else if (keyStr === "hydration" || keyStr.startsWith("hydration.")) {
3278
+ draft.set("hydration", normalizeHydrationUpdate(this.getDefaultModelOptions().hydration, keyStr, value));
3279
+ } else {
3280
+ draft.set(key, value);
3047
3281
  }
3048
- this.defaultModelOptions.set(key, value);
3282
+ assertPublicDefaults(draft.fetch().defaults);
3283
+ this.publishDefaultModelOptions(draft.fetch());
3049
3284
  }
3050
3285
  getDefaultModelOptions() {
3051
3286
  return this.defaultModelOptions.fetch();
@@ -3053,34 +3288,109 @@ var init_runtime = __esm({
3053
3288
  getDefaultModelOption(key, defaultValue) {
3054
3289
  return this.defaultModelOptions.get(key, defaultValue);
3055
3290
  }
3056
- createModelOptions(modelName) {
3291
+ resolveModelOptions(modelName, overrides = this.modelOptionOverrides[modelName] ?? {}, defaults2 = this.getDefaultModelOptions()) {
3292
+ const inherited = { ...defaults2 };
3293
+ for (const key of populatePolicyKeys) delete inherited[key];
3294
+ const effective = { ...defaultModelOptions, ...inherited, ...overrides, modelName };
3295
+ effective.basePath = normalizeBasePath(modelName, effective.basePath);
3296
+ for (const key of unsafeSnapshotOptions) effective[key] = effective[key] === true;
3297
+ refreshPermissionMetadata(effective);
3298
+ return cloneOptionsSnapshot(effective);
3299
+ }
3300
+ validateModelOptions(modelName, options, proposed) {
3301
+ validateVirtualsTree(
3302
+ this.getModelInstance(modelName),
3303
+ options.virtuals,
3304
+ options.documentPermissionField ?? "_permissions",
3305
+ modelName
3306
+ );
3307
+ captureVirtualPopulateDependencies(this, modelName, options, void 0, proposed);
3308
+ }
3309
+ publishDefaultModelOptions(options) {
3310
+ const next = { ...options };
3311
+ for (const key of unsafeSnapshotOptions) if (key in next) next[key] = next[key] === true;
3312
+ const defaults2 = cloneOptionsSnapshot(next);
3313
+ const models = new Map(
3314
+ Object.keys(this.modelOptions).map((name) => [name, this.resolveModelOptions(name, void 0, defaults2)])
3315
+ );
3316
+ for (const [name, options2] of models) this.validateModelOptions(name, options2, { defaults: defaults2, models });
3317
+ this.deferSnapshotWarnings(() => {
3318
+ this.defaultModelOptions.restore(defaults2);
3319
+ for (const [name, options2] of models) this.modelOptions[name].restore(options2);
3320
+ });
3321
+ }
3322
+ warnSnapshotFlag(modelName, key) {
3323
+ if (this.pendingSnapshotWarnings) {
3324
+ this.pendingSnapshotWarnings.push({ modelName, key });
3325
+ return;
3326
+ }
3327
+ const operation = key.startsWith("unsafeSkipRead") ? "read" : "list";
3328
+ const category = key.includes("NestedDocument") ? "nested-document" : key.includes("Output") ? "output" : "document";
3329
+ const risk = category === "output" ? "output mutation" : "source mutation";
3330
+ try {
3331
+ this.getGlobalOption("logger")?.warn?.(
3332
+ `UNSAFE: ${operation} ${category} snapshot checks disabled; ${risk} can leave stale authorization decisions. Restore ${key}=false after the temporary workaround.`,
3333
+ { modelName }
3334
+ );
3335
+ } catch {
3336
+ }
3337
+ }
3338
+ deferSnapshotWarnings(publish) {
3339
+ if (this.pendingSnapshotWarnings) return publish();
3340
+ const copyModes = this.initialOutputCopyModes();
3341
+ const pending = [];
3342
+ this.pendingSnapshotWarnings = pending;
3343
+ let result2;
3344
+ try {
3345
+ result2 = publish();
3346
+ } finally {
3347
+ this.pendingSnapshotWarnings = void 0;
3348
+ }
3349
+ const nextCopyModes = this.initialOutputCopyModes();
3350
+ for (const { modelName, key } of pending) this.warnSnapshotFlag(modelName, key);
3351
+ for (const [modelName, modes] of nextCopyModes) {
3352
+ for (const operation of ["List", "Read"]) {
3353
+ const mode = modes[operation];
3354
+ if (mode === "off" || mode === copyModes.get(modelName)?.[operation]) continue;
3355
+ const key = `unsafeSkip${operation}InitialOutputSnapshotCopy`;
3356
+ const prerequisite = `unsafeSkip${operation}OutputSnapshotChecks`;
3357
+ try {
3358
+ this.getGlobalOption("logger")?.warn?.(
3359
+ 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.`,
3360
+ { modelName }
3361
+ );
3362
+ } catch {
3363
+ }
3364
+ }
3365
+ }
3366
+ return result2;
3367
+ }
3368
+ initialOutputCopyModes() {
3369
+ return new Map(
3370
+ Object.entries(this.modelOptions).map(([modelName, options]) => {
3371
+ const mode = (operation) => options.get(`unsafeSkip${operation}InitialOutputSnapshotCopy`) !== true ? "off" : options.get(`unsafeSkip${operation}OutputSnapshotChecks`) === true ? "active" : "dormant";
3372
+ return [modelName, { List: mode("List"), Read: mode("Read") }];
3373
+ })
3374
+ );
3375
+ }
3376
+ createModelOptions(modelName, options = this.resolveModelOptions(modelName)) {
3057
3377
  const model = this.getModelInstance(modelName);
3058
3378
  if (!model) {
3059
3379
  throw new Error(
3060
3380
  `Runtime model registry missing model "${modelName}". Pass a mongoose.Model instance to createRouter() or register it with registerModelInstance() before using this isolated runtime.`
3061
3381
  );
3062
3382
  }
3063
- const manager = new OptionsManager({
3064
- ...defaultModelOptions,
3065
- modelName
3066
- });
3383
+ const manager = new OptionsManager(options);
3067
3384
  const snapshotFlagChanged = (newValue, key, target, oldValue) => {
3068
3385
  target[key] = newValue === true;
3069
3386
  if (newValue !== true || oldValue === true) return;
3070
- const operation = key === "unsafeSkipReadDocumentSnapshotChecks" ? "read" : "list";
3071
- try {
3072
- this.getGlobalOption("logger")?.warn?.(
3073
- `UNSAFE: ${operation} document snapshot checks disabled; source mutation can leave stale authorization decisions. Restore ${key}=false after the temporary workaround.`,
3074
- { modelName }
3075
- );
3076
- } catch {
3077
- }
3387
+ this.warnSnapshotFlag(modelName, key);
3078
3388
  };
3079
3389
  manager.onchange("permissionSchema", function(_newval, _key, target) {
3080
3390
  refreshPermissionMetadata(target);
3081
3391
  }).onchange("modelPermissionPrefix", function(_newval, _key, target) {
3082
3392
  refreshPermissionMetadata(target);
3083
- }).onchange("unsafeSkipListDocumentSnapshotChecks", snapshotFlagChanged).onchange("unsafeSkipReadDocumentSnapshotChecks", snapshotFlagChanged).onchange("basePath", function(newval, key, target) {
3393
+ }).onchange("unsafeSkipListDocumentSnapshotChecks", snapshotFlagChanged).onchange("unsafeSkipReadDocumentSnapshotChecks", snapshotFlagChanged).onchange("unsafeSkipListOutputSnapshotChecks", snapshotFlagChanged).onchange("unsafeSkipReadOutputSnapshotChecks", snapshotFlagChanged).onchange("unsafeSkipListNestedDocumentSnapshotChecks", snapshotFlagChanged).onchange("unsafeSkipReadNestedDocumentSnapshotChecks", snapshotFlagChanged).onchange("basePath", function(newval, key, target) {
3084
3394
  target[key] = normalizeBasePath(
3085
3395
  modelName,
3086
3396
  (0, import_utils17.isString)(newval) || (0, import_utils17.isNil)(newval) ? newval : void 0
@@ -3092,13 +3402,17 @@ var init_runtime = __esm({
3092
3402
  getOrCreateModelOptions(modelName) {
3093
3403
  let manager = this.modelOptions[modelName];
3094
3404
  if (!manager) {
3095
- manager = this.createModelOptions(modelName);
3096
- this.modelOptions[modelName] = manager;
3405
+ manager = this.deferSnapshotWarnings(() => {
3406
+ const created = this.createModelOptions(modelName);
3407
+ this.modelOptions[modelName] = created;
3408
+ return created;
3409
+ });
3097
3410
  }
3098
3411
  return manager;
3099
3412
  }
3100
3413
  /**
3101
- * Assign `{ ...modelDefaults, ...storedOptions, ...options }` shallowly. A supplied
3414
+ * Update explicit model overrides shallowly; undefined restores default inheritance
3415
+ * (operationAccess preserves its existing exact-key-only default fallback). A supplied
3102
3416
  * operationAccess/defaults object replaces that whole value. Defaults accept only
3103
3417
  * query/presentation settings; virtual configuration is validated before assignment.
3104
3418
  * Existing router.options remains its construction-time snapshot. Fresh model-service
@@ -3106,22 +3420,23 @@ var init_runtime = __esm({
3106
3420
  */
3107
3421
  setModelOptions(modelName, options) {
3108
3422
  assertPublicDefaults(options.defaults);
3423
+ options = normalizePopulatePolicyOptions(options);
3109
3424
  if ("hydration" in options) options = { ...options, hydration: normalizeHydration(options.hydration) };
3110
- const defaultOptions = this.getDefaultModelOptions();
3111
- const currentModelOptions = this.modelOptions[modelName]?.fetch() ?? { ...defaultModelOptions, modelName };
3112
- const merged = { ...defaultOptions, ...currentModelOptions, ...options };
3113
- const model = this.getModelInstance(modelName);
3114
- const permissionField = merged.documentPermissionField ?? currentModelOptions.documentPermissionField ?? this.getDefaultModelOption("documentPermissionField") ?? "_permissions";
3115
- validateVirtualsTree(model, merged.virtuals, permissionField, modelName);
3116
- captureVirtualPopulateDependencies(this, modelName, merged);
3117
- const manager = this.getOrCreateModelOptions(modelName);
3118
- manager.assign({ ...defaultOptions, ...currentModelOptions, ...options });
3425
+ const overrides = modelOverrides({ ...this.modelOptionOverrides[modelName], ...options });
3426
+ const effective = this.resolveModelOptions(modelName, overrides);
3427
+ this.validateModelOptions(modelName, effective);
3428
+ this.deferSnapshotWarnings(() => {
3429
+ const manager = this.modelOptions[modelName];
3430
+ if (manager) manager.restore(effective);
3431
+ else this.modelOptions[modelName] = this.createModelOptions(modelName, effective);
3432
+ this.modelOptionOverrides[modelName] = overrides;
3433
+ });
3119
3434
  }
3120
3435
  setModelOption(modelName, key, value) {
3121
3436
  const keyStr = String(key);
3122
3437
  if (keyStr === "hydration" || keyStr.startsWith("hydration.")) {
3123
- const hydration = normalizeHydrationUpdate(this.modelOptions[modelName]?.get("hydration"), keyStr, value);
3124
- this.getOrCreateModelOptions(modelName).set("hydration", hydration);
3438
+ const hydration = normalizeHydrationUpdate(this.resolveModelOptions(modelName).hydration, keyStr, value);
3439
+ this.setModelOptions(modelName, { hydration });
3125
3440
  return;
3126
3441
  }
3127
3442
  if (keyStr === "defaults") assertPublicDefaults(value);
@@ -3130,47 +3445,20 @@ var init_runtime = __esm({
3130
3445
  (0, import_utils17.set)(proposed, keyStr.slice("defaults.".length), value);
3131
3446
  assertPublicDefaults(proposed);
3132
3447
  }
3133
- const manager = this.modelOptions[modelName];
3134
- if (keyStr === "virtuals" || keyStr.startsWith("virtuals.") || keyStr === "documentPermissionField") {
3135
- const model = this.getModelInstance(modelName);
3136
- const currentVirtuals = manager?.get("virtuals");
3137
- const currentPermissionField = manager?.get("documentPermissionField") ?? this.getDefaultModelOption("documentPermissionField") ?? "_permissions";
3138
- let proposedVirtuals = currentVirtuals;
3139
- let proposedPermissionField = currentPermissionField;
3140
- if (keyStr === "documentPermissionField") {
3141
- proposedPermissionField = value;
3142
- } else if (keyStr === "virtuals") {
3143
- proposedVirtuals = value;
3144
- } else {
3145
- const cloned = cloneVirtualsForValidation(currentVirtuals ?? {});
3146
- const nestedPath = keyStr.slice("virtuals.".length);
3147
- if (value === void 0) {
3148
- const segments = nestedPath.split(".");
3149
- let cursor = cloned;
3150
- for (let i = 0; i < segments.length - 1; i++) {
3151
- if (!(0, import_utils17.isPlainObject)(cursor)) break;
3152
- cursor = cursor[segments[i]];
3153
- }
3154
- if ((0, import_utils17.isPlainObject)(cursor)) {
3155
- delete cursor[segments[segments.length - 1]];
3156
- }
3157
- proposedVirtuals = cloned;
3158
- } else {
3159
- (0, import_utils17.set)(cloned, nestedPath, value);
3160
- proposedVirtuals = cloned;
3161
- }
3162
- }
3163
- validateVirtualsTree(model, proposedVirtuals, proposedPermissionField, modelName);
3164
- captureVirtualPopulateDependencies(this, modelName, {
3165
- ...this.getDefaultModelOptions(),
3166
- ...manager?.fetch(),
3167
- virtuals: proposedVirtuals,
3168
- documentPermissionField: proposedPermissionField
3169
- });
3448
+ const [root, ...path] = keyStr.split(".");
3449
+ if (!path.length) {
3450
+ this.setModelOptions(modelName, { [root]: value });
3451
+ return;
3170
3452
  }
3171
- this.getOrCreateModelOptions(modelName).set(key, value);
3172
- }
3173
- /** Frozen stored snapshot, not fully resolved per-path defaults. Read again for current configuration. */
3453
+ const current = this.resolveModelOptions(modelName);
3454
+ const nested = cloneModelOptionForUpdate((0, import_utils17.isPlainObject)(current[root]) ? current[root] : {});
3455
+ if (root === "virtuals" && value === void 0) {
3456
+ const parent = path.length === 1 ? nested : (0, import_utils17.get)(nested, path.slice(0, -1));
3457
+ if ((0, import_utils17.isPlainObject)(parent)) delete parent[path[path.length - 1]];
3458
+ } else (0, import_utils17.set)(nested, path, value);
3459
+ this.setModelOptions(modelName, { [root]: nested });
3460
+ }
3461
+ /** Frozen model/default snapshot; populate flags remain raw overrides. Read again for current values. */
3174
3462
  getModelOptions(modelName) {
3175
3463
  const manager = this.getOrCreateModelOptions(modelName);
3176
3464
  return manager.fetch();
@@ -3337,132 +3625,117 @@ var init_runtime = __esm({
3337
3625
  }
3338
3626
  });
3339
3627
 
3340
- // src/runtime-context.ts
3341
- function runWithRuntime(runtime, callback) {
3342
- return runtimeStorage.run(runtime, callback);
3343
- }
3344
- function getActiveRuntime() {
3345
- return runtimeStorage.getStore() ?? null;
3346
- }
3347
- var import_node_async_hooks2, runtimeStorage;
3348
- var init_runtime_context = __esm({
3349
- "src/runtime-context.ts"() {
3350
- import_node_async_hooks2 = require("async_hooks");
3351
- runtimeStorage = new import_node_async_hooks2.AsyncLocalStorage();
3352
- }
3353
- });
3354
-
3355
3628
  // src/options/global-options.ts
3356
- var getRuntime, setGlobalOptions, setGlobalOption, getGlobalOptions, getGlobalOption;
3629
+ var getRuntime2, setGlobalOptions, setGlobalOption, getGlobalOptions, getGlobalOption;
3357
3630
  var init_global_options = __esm({
3358
3631
  "src/options/global-options.ts"() {
3359
3632
  init_runtime();
3360
3633
  init_runtime_context();
3361
- getRuntime = () => getActiveRuntime() ?? defaultRuntime;
3634
+ getRuntime2 = () => getActiveRuntime() ?? defaultRuntime;
3362
3635
  setGlobalOptions = (options) => {
3363
- getRuntime().setGlobalOptions(options);
3636
+ getRuntime2().setGlobalOptions(options);
3364
3637
  };
3365
3638
  setGlobalOption = (key, value) => {
3366
- getRuntime().setGlobalOption(key, value);
3639
+ getRuntime2().setGlobalOption(key, value);
3367
3640
  };
3368
3641
  getGlobalOptions = () => {
3369
- return getRuntime().getGlobalOptions();
3642
+ return getRuntime2().getGlobalOptions();
3370
3643
  };
3371
3644
  getGlobalOption = (key, defaultValue) => {
3372
- return getRuntime().getGlobalOption(key, defaultValue);
3645
+ return getRuntime2().getGlobalOption(key, defaultValue);
3373
3646
  };
3374
3647
  }
3375
3648
  });
3376
3649
 
3377
3650
  // src/options/model-options.ts
3378
- var getRuntime2, setModelOptions, setModelOption, getModelOptions, getModelOption, getExactModelOption, getModelNames, getModelJsonSchema, registerModelInstance, hasModelInstance, getModelInstance;
3651
+ var getRuntime3, setModelOptions, setModelOption, getModelOptions, getModelOption, getExactModelOption, getModelNames, getModelJsonSchema, registerModelInstance, hasModelInstance, getModelInstance;
3379
3652
  var init_model_options = __esm({
3380
3653
  "src/options/model-options.ts"() {
3381
3654
  init_runtime();
3382
3655
  init_runtime_context();
3383
- getRuntime2 = () => getActiveRuntime() ?? defaultRuntime;
3656
+ getRuntime3 = () => getActiveRuntime() ?? defaultRuntime;
3384
3657
  setModelOptions = (modelName, options) => {
3385
- getRuntime2().setModelOptions(modelName, options);
3658
+ getRuntime3().setModelOptions(modelName, options);
3386
3659
  };
3387
3660
  setModelOption = (modelName, key, value) => {
3388
- getRuntime2().setModelOption(modelName, key, value);
3661
+ getRuntime3().setModelOption(modelName, key, value);
3389
3662
  };
3390
3663
  getModelOptions = (modelName) => {
3391
- return getRuntime2().getModelOptions(modelName);
3664
+ return getRuntime3().getModelOptions(modelName);
3392
3665
  };
3393
3666
  getModelOption = (modelName, key, defaultValue) => {
3394
- return getRuntime2().getModelOption(modelName, key, defaultValue);
3667
+ return getRuntime3().getModelOption(modelName, key, defaultValue);
3395
3668
  };
3396
3669
  getExactModelOption = (modelName, key) => {
3397
- return getRuntime2().getExactModelOption(modelName, key);
3670
+ return getRuntime3().getExactModelOption(modelName, key);
3398
3671
  };
3399
3672
  getModelNames = () => {
3400
3673
  return (getActiveRuntime() ?? defaultRuntime).getModelNames();
3401
3674
  };
3402
3675
  getModelJsonSchema = (modelName) => {
3403
- return getRuntime2().getModelJsonSchema(modelName);
3676
+ return getRuntime3().getModelJsonSchema(modelName);
3404
3677
  };
3405
3678
  registerModelInstance = (modelName, model) => {
3406
- getRuntime2().registerModelInstance(modelName, model);
3679
+ getRuntime3().registerModelInstance(modelName, model);
3407
3680
  };
3408
3681
  hasModelInstance = (modelName) => {
3409
- return getRuntime2().hasModelInstance(modelName);
3682
+ return getRuntime3().hasModelInstance(modelName);
3410
3683
  };
3411
3684
  getModelInstance = (modelName) => {
3412
- return getRuntime2().getModelInstance(modelName);
3685
+ return getRuntime3().getModelInstance(modelName);
3413
3686
  };
3414
3687
  }
3415
3688
  });
3416
3689
 
3417
3690
  // src/options/default-model-options.ts
3418
- var getRuntime3, setDefaultModelOptions, setDefaultModelOption, getDefaultModelOptions, getDefaultModelOption;
3691
+ var getRuntime4, setDefaultModelOptions, setDefaultModelOption, getDefaultModelOptions, getDefaultModelOption;
3419
3692
  var init_default_model_options = __esm({
3420
3693
  "src/options/default-model-options.ts"() {
3421
3694
  init_runtime();
3422
3695
  init_runtime_context();
3423
- getRuntime3 = () => getActiveRuntime() ?? defaultRuntime;
3696
+ getRuntime4 = () => getActiveRuntime() ?? defaultRuntime;
3424
3697
  setDefaultModelOptions = (options) => {
3425
- getRuntime3().setDefaultModelOptions(options);
3698
+ getRuntime4().setDefaultModelOptions(options);
3426
3699
  };
3427
3700
  setDefaultModelOption = (key, value) => {
3428
- getRuntime3().setDefaultModelOption(key, value);
3701
+ getRuntime4().setDefaultModelOption(key, value);
3429
3702
  };
3430
3703
  getDefaultModelOptions = () => {
3431
- return getRuntime3().getDefaultModelOptions();
3704
+ return getRuntime4().getDefaultModelOptions();
3432
3705
  };
3433
3706
  getDefaultModelOption = (key, defaultValue) => {
3434
- return getRuntime3().getDefaultModelOption(key, defaultValue);
3707
+ return getRuntime4().getDefaultModelOption(key, defaultValue);
3435
3708
  };
3436
3709
  }
3437
3710
  });
3438
3711
 
3439
3712
  // src/options/data-options.ts
3440
- var getRuntime4, setDataOptions, setDataOption, getDataOptions, getDataSnapshot, getDataOption, getExactDataOption, getDataNames;
3713
+ var getRuntime5, setDataOptions, setDataOption, getDataOptions, getDataSnapshot, getDataOption, getExactDataOption, getDataNames;
3441
3714
  var init_data_options = __esm({
3442
3715
  "src/options/data-options.ts"() {
3443
3716
  init_runtime();
3444
3717
  init_runtime_context();
3445
- getRuntime4 = () => getActiveRuntime() ?? defaultRuntime;
3718
+ getRuntime5 = () => getActiveRuntime() ?? defaultRuntime;
3446
3719
  setDataOptions = (dataName, options) => {
3447
- getRuntime4().setDataOptions(dataName, options);
3720
+ getRuntime5().setDataOptions(dataName, options);
3448
3721
  };
3449
3722
  setDataOption = (dataName, key, value) => {
3450
- getRuntime4().setDataOption(dataName, key, value);
3723
+ getRuntime5().setDataOption(dataName, key, value);
3451
3724
  };
3452
3725
  getDataOptions = (dataName) => {
3453
- return getRuntime4().getDataOptions(dataName);
3726
+ return getRuntime5().getDataOptions(dataName);
3454
3727
  };
3455
3728
  getDataSnapshot = (dataName) => {
3456
- return getRuntime4().getDataSnapshot(dataName);
3729
+ return getRuntime5().getDataSnapshot(dataName);
3457
3730
  };
3458
3731
  getDataOption = (dataName, key, defaultValue) => {
3459
- return getRuntime4().getDataOption(dataName, key, defaultValue);
3732
+ return getRuntime5().getDataOption(dataName, key, defaultValue);
3460
3733
  };
3461
3734
  getExactDataOption = (dataName, key) => {
3462
- return getRuntime4().getExactDataOption(dataName, key);
3735
+ return getRuntime5().getExactDataOption(dataName, key);
3463
3736
  };
3464
3737
  getDataNames = () => {
3465
- return getRuntime4().getDataNames();
3738
+ return getRuntime5().getDataNames();
3466
3739
  };
3467
3740
  }
3468
3741
  });
@@ -3725,6 +3998,33 @@ function assertAuthorizationBinding(call, binding) {
3725
3998
  authorizationError("request/runtime/model/scope binding mismatch");
3726
3999
  }
3727
4000
  }
4001
+ function queryOutputAccess(access) {
4002
+ 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;
4003
+ }
4004
+ function nestedQueryResponse(input, access) {
4005
+ const edge = input.snapshotDerivation;
4006
+ if (!edge || !input.parent) return false;
4007
+ assertAuthorizationBinding(input.parent, edge.parentBinding);
4008
+ const parent = callRecord(input.parent);
4009
+ if (!parent.responseSnapshots || (input.applicability ?? "service") !== "service" || !queryOutputAccess(access) || !queryOutputAccess(parent.output.access))
4010
+ return false;
4011
+ if (edge.kind === "retry") {
4012
+ if (!parent.nestedResponse || access.operation !== "read" || parent.output.access.operation !== "read")
4013
+ return false;
4014
+ assertAuthorizationBinding(input.parent, input.binding);
4015
+ return true;
4016
+ }
4017
+ if (edge.kind === "related") {
4018
+ const target = parent.relatedTargets.find((target2) => target2.path === edge.path);
4019
+ return !!target && target.kind !== "count" && target.modelName === input.binding.modelName && scope(input.binding).length === 0;
4020
+ }
4021
+ if (edge.kind !== "embedded") return false;
4022
+ assertAuthorizationBinding(input.parent, { ...input.binding, scopePath: parent.binding.scopePath });
4023
+ const childScope = scope(input.binding), parentScope = scope(parent.binding);
4024
+ return childScope.length > parentScope.length && parentScope.every((part, index) => childScope[index] === part) && Object.keys(parent.output.access).every(
4025
+ (key) => access[key] === parent.output.access[key]
4026
+ );
4027
+ }
3728
4028
  function resolveServiceAuthorization(input) {
3729
4029
  const raw = copyAuthorizationValue(input.authorization);
3730
4030
  const configuration = copyAuthorizationValue(input.configuration, true);
@@ -3752,6 +4052,17 @@ function resolveServiceAuthorization(input) {
3752
4052
  const readAccess = outputAccess.rowAccess;
3753
4053
  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);
3754
4054
  if (readResponse && input.parent) assertAuthorizationBinding(input.parent, input.binding);
4055
+ const nestedResponse = nestedQueryResponse(input, outputAccess);
4056
+ const listResponse = input.listResponse === true && input.parent === void 0 && (input.applicability ?? "service") === "service" && scopePath.length === 0 && outputAccess.operation === "list" && outputAccess.rowAccess === "list" && queryOutputAccess(outputAccess);
4057
+ const responseSnapshots = input.parent && (nestedResponse || readResponse) ? callRecord(input.parent).responseSnapshots : listResponse ? Object.freeze({
4058
+ skipOutput: configuration.unsafeSkipListOutputSnapshotChecks === true,
4059
+ skipNested: configuration.unsafeSkipListNestedDocumentSnapshotChecks === true,
4060
+ skipInitialOutputCopy: configuration.unsafeSkipListOutputSnapshotChecks === true && configuration.unsafeSkipListInitialOutputSnapshotCopy === true
4061
+ }) : readResponse ? Object.freeze({
4062
+ skipOutput: configuration.unsafeSkipReadOutputSnapshotChecks === true,
4063
+ skipNested: configuration.unsafeSkipReadNestedDocumentSnapshotChecks === true,
4064
+ skipInitialOutputCopy: configuration.unsafeSkipReadOutputSnapshotChecks === true && configuration.unsafeSkipReadInitialOutputSnapshotCopy === true
4065
+ }) : void 0;
3755
4066
  const call = Object.freeze(/* @__PURE__ */ Object.create(null));
3756
4067
  calls.set(call, {
3757
4068
  binding: Object.freeze({ ...input.binding, scopePath: Object.freeze(scopePath) }),
@@ -3764,7 +4075,11 @@ function resolveServiceAuthorization(input) {
3764
4075
  permissions,
3765
4076
  provenance: input.parent ? callRecord(input.parent).provenance : call,
3766
4077
  readResponse,
3767
- 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)
4078
+ nestedResponse,
4079
+ responseSnapshots,
4080
+ validateOutputSnapshots: responseSnapshots?.skipOutput !== true,
4081
+ skipInitialOutputSnapshotCopy: responseSnapshots?.skipInitialOutputCopy === true,
4082
+ 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)
3768
4083
  });
3769
4084
  return call;
3770
4085
  }
@@ -3789,6 +4104,14 @@ function requiresDocumentSnapshotChecks(call, binding) {
3789
4104
  assertAuthorizationBinding(call, binding);
3790
4105
  return callRecord(call).validateDocumentSnapshots;
3791
4106
  }
4107
+ function requiresOutputSnapshotChecks(call, binding) {
4108
+ assertAuthorizationBinding(call, binding);
4109
+ return callRecord(call).validateOutputSnapshots;
4110
+ }
4111
+ function skipsInitialOutputSnapshotCopy(call) {
4112
+ const record3 = callRecord(call);
4113
+ return !record3.validateOutputSnapshots && record3.skipInitialOutputSnapshotCopy;
4114
+ }
3792
4115
  function readServiceAuthorizationHydration(call, binding) {
3793
4116
  assertAuthorizationBinding(call, binding);
3794
4117
  return copyAuthorizationValue({ hydration: callRecord(call).configuration.hydration }, true);
@@ -4955,7 +5278,7 @@ function tryStaticRequestFieldPaths(handle, binding, access) {
4955
5278
  return decisions && [...decisions].filter(([, allowed]) => allowed).map(([field]) => field);
4956
5279
  }
4957
5280
  function unchangedOutput(output, record3) {
4958
- if (!matchesAuthorizationSnapshot(output, record3.snapshot)) return false;
5281
+ if (record3.validateSnapshot && !matchesAuthorizationSnapshot(output, record3.snapshot)) return false;
4959
5282
  const identities = outputIdentities(output);
4960
5283
  return identities.length === record3.identities.length && identities.every((identity, i) => identity === record3.identities[i]);
4961
5284
  }
@@ -4980,10 +5303,21 @@ function associateDocumentAuthorization(handle, binding, output) {
4980
5303
  authorizationError("output already associated");
4981
5304
  return;
4982
5305
  }
5306
+ if (skipsInitialOutputSnapshotCopy(stage.call) && ordinaryDecisionBinding(binding)) {
5307
+ if (requiresOutputSnapshotChecks(stage.call, binding))
5308
+ authorizationError("output snapshot copy requires skipped comparisons");
5309
+ const identities = tryOutputIdentitiesWithoutSnapshot(output);
5310
+ if (identities) {
5311
+ outputs.set(output, { handle, snapshotState: "omitted", identities, validateSnapshot: false });
5312
+ return;
5313
+ }
5314
+ }
4983
5315
  outputs.set(output, {
4984
5316
  handle,
5317
+ snapshotState: "copied",
4985
5318
  snapshot: copyAuthorizationValue(output, "document"),
4986
- identities: outputIdentities(output)
5319
+ identities: outputIdentities(output),
5320
+ validateSnapshot: requiresOutputSnapshotChecks(stage.call, binding)
4987
5321
  });
4988
5322
  }
4989
5323
  function transferDocumentAuthorization(handle, use, copy) {
@@ -5158,10 +5492,11 @@ var init_request_work = __esm({
5158
5492
 
5159
5493
  // src/acl/model-output-planning.ts
5160
5494
  function getCapturedAuthorizationOption(configuration, key) {
5161
- const defaultValue = key.startsWith("operationAccess.") ? (0, import_utils23.get)(configuration.operationAccessDefaults, key.slice("operationAccess.".length)) : void 0;
5162
- return resolveNestedOption((path, fallback) => (0, import_utils23.get)(configuration, path, fallback), key, defaultValue);
5495
+ const defaultValue = key.startsWith("operationAccess.") ? (0, import_utils24.get)(configuration.operationAccessDefaults, key.slice("operationAccess.".length)) : void 0;
5496
+ return resolveNestedOption((path, fallback) => (0, import_utils24.get)(configuration, path, fallback), key, defaultValue);
5163
5497
  }
5164
- function captureModelAuthorizationConfiguration(runtime, modelName, options = runtime.getModelOptions(modelName), globalOptions = runtime.getGlobalOptions()) {
5498
+ function captureModelAuthorizationConfiguration(runtime, modelName, options, populatePolicyDefaults = capturePopulatePolicyDefaults(runtime)) {
5499
+ options ??= runtime.getModelOptions(modelName);
5165
5500
  const model = runtime.getModelInstance(modelName);
5166
5501
  if (!model) return authorizationError(`unknown receiving model: ${modelName}`);
5167
5502
  const virtuals = options.virtuals;
@@ -5172,10 +5507,10 @@ function captureModelAuthorizationConfiguration(runtime, modelName, options = ru
5172
5507
  runtime,
5173
5508
  modelName,
5174
5509
  options,
5175
- globalOptions
5510
+ populatePolicyDefaults
5176
5511
  ),
5177
- requireOperationAccessForPopulateDependencies: globalOptions.requireOperationAccessForPopulateDependencies !== false,
5178
- requireOperationAccessForPopulateQueries: globalOptions.requireOperationAccessForPopulateQueries !== false,
5512
+ populatePolicyDefaults,
5513
+ ...resolvePopulatePolicy(options, populatePolicyDefaults),
5179
5514
  permissionSchema: options.permissionSchema === void 0 ? runtime.getDefaultModelOption("permissionSchema") : options.permissionSchema,
5180
5515
  virtuals,
5181
5516
  alwaysSelectFields: options.alwaysSelectFields,
@@ -5188,6 +5523,12 @@ function captureModelAuthorizationConfiguration(runtime, modelName, options = ru
5188
5523
  disableFieldPermissions: options.disableFieldPermissions,
5189
5524
  unsafeSkipListDocumentSnapshotChecks: options.unsafeSkipListDocumentSnapshotChecks === true,
5190
5525
  unsafeSkipReadDocumentSnapshotChecks: options.unsafeSkipReadDocumentSnapshotChecks === true,
5526
+ unsafeSkipListOutputSnapshotChecks: options.unsafeSkipListOutputSnapshotChecks === true,
5527
+ unsafeSkipReadOutputSnapshotChecks: options.unsafeSkipReadOutputSnapshotChecks === true,
5528
+ unsafeSkipListNestedDocumentSnapshotChecks: options.unsafeSkipListNestedDocumentSnapshotChecks === true,
5529
+ unsafeSkipReadNestedDocumentSnapshotChecks: options.unsafeSkipReadNestedDocumentSnapshotChecks === true,
5530
+ unsafeSkipListInitialOutputSnapshotCopy: options.unsafeSkipListInitialOutputSnapshotCopy === true,
5531
+ unsafeSkipReadInitialOutputSnapshotCopy: options.unsafeSkipReadInitialOutputSnapshotCopy === true,
5191
5532
  overrideFilter: options.overrideFilter,
5192
5533
  baseFilter: options.baseFilter,
5193
5534
  idField: options.idField,
@@ -5224,25 +5565,26 @@ function planModelOutputForHelper(args) {
5224
5565
  requestedSelect: args.select
5225
5566
  });
5226
5567
  }
5227
- var import_utils23;
5568
+ var import_utils24;
5228
5569
  var init_model_output_planning = __esm({
5229
5570
  "src/acl/model-output-planning.ts"() {
5230
- import_utils23 = require("@web-ts-toolkit/utils");
5571
+ import_utils24 = require("@web-ts-toolkit/utils");
5231
5572
  init_manager();
5232
5573
  init_field_catalog();
5233
5574
  init_authorization_snapshot();
5234
5575
  init_virtual_populate_dependencies();
5235
5576
  init_document_authorization();
5236
5577
  init_output_projection();
5578
+ init_populate_policy2();
5237
5579
  }
5238
5580
  });
5239
5581
 
5240
5582
  // src/core-shared.ts
5241
5583
  function isAndFilter(filter2) {
5242
- return !!filter2 && (0, import_utils24.isPlainObject)(filter2) && Object.keys(filter2).length === 1 && (0, import_utils24.isArray)(filter2.$and);
5584
+ return !!filter2 && (0, import_utils25.isPlainObject)(filter2) && Object.keys(filter2).length === 1 && (0, import_utils25.isArray)(filter2.$and);
5243
5585
  }
5244
5586
  function isMergeableClause(filter2) {
5245
- return !!filter2 && (0, import_utils24.isPlainObject)(filter2) && Object.keys(filter2).every((key) => !key.startsWith("$"));
5587
+ return !!filter2 && (0, import_utils25.isPlainObject)(filter2) && Object.keys(filter2).every((key) => !key.startsWith("$"));
5246
5588
  }
5247
5589
  function optimizeAndFilter(clausesInput) {
5248
5590
  const clauses = [];
@@ -5259,11 +5601,11 @@ function optimizeAndFilter(clausesInput) {
5259
5601
  const dedupeKey = (value) => {
5260
5602
  if (value instanceof RegExp) return `regexp:${JSON.stringify([value.source, value.flags])}`;
5261
5603
  if (value instanceof Date) return `date:${value.getTime()}`;
5262
- if ((0, import_utils24.isArray)(value)) {
5604
+ if ((0, import_utils25.isArray)(value)) {
5263
5605
  const entries = Array.from(value, dedupeKey);
5264
5606
  return entries.every((entry) => entry !== void 0) ? `array:${JSON.stringify(entries)}` : void 0;
5265
5607
  }
5266
- if ((0, import_utils24.isPlainObject)(value)) {
5608
+ if ((0, import_utils25.isPlainObject)(value)) {
5267
5609
  const entries = Object.keys(value).sort().map((key) => [key, dedupeKey(value[key])]);
5268
5610
  return entries.every(([, entry]) => entry !== void 0) ? `object:${JSON.stringify(entries)}` : void 0;
5269
5611
  }
@@ -5293,7 +5635,7 @@ function optimizeAndFilter(clausesInput) {
5293
5635
  }
5294
5636
  let canMerge = true;
5295
5637
  for (const [key, value] of Object.entries(clause)) {
5296
- if ((0, import_utils24.hasOwn)(mergedClause, key) && !(0, import_node_util7.isDeepStrictEqual)(mergedClause[key], value)) {
5638
+ if ((0, import_utils25.hasOwn)(mergedClause, key) && !(0, import_node_util7.isDeepStrictEqual)(mergedClause[key], value)) {
5297
5639
  canMerge = false;
5298
5640
  break;
5299
5641
  }
@@ -5304,24 +5646,24 @@ function optimizeAndFilter(clausesInput) {
5304
5646
  }
5305
5647
  Object.assign(mergedClause, clause);
5306
5648
  }
5307
- const finalClauses = (0, import_utils24.isEmpty)(mergedClause) ? remainingClauses : [mergedClause, ...remainingClauses];
5649
+ const finalClauses = (0, import_utils25.isEmpty)(mergedClause) ? remainingClauses : [mergedClause, ...remainingClauses];
5308
5650
  if (finalClauses.length === 0) return null;
5309
5651
  if (finalClauses.length === 1) return finalClauses[0];
5310
5652
  return { $and: finalClauses };
5311
5653
  }
5312
5654
  function normalizeFilter(filter2) {
5313
5655
  if (filter2 === false) return false;
5314
- if (!filter2 || !(0, import_utils24.isPlainObject)(filter2) || (0, import_utils24.isEmpty)(filter2)) return null;
5656
+ if (!filter2 || !(0, import_utils25.isPlainObject)(filter2) || (0, import_utils25.isEmpty)(filter2)) return null;
5315
5657
  if (!isAndFilter(filter2)) {
5316
5658
  return filter2;
5317
5659
  }
5318
5660
  return optimizeAndFilter(filter2.$and);
5319
5661
  }
5320
5662
  async function resolveIdentifierFilter(req, idField, resolveIdFilter, id) {
5321
- if ((0, import_utils24.isFunction)(resolveIdFilter)) {
5663
+ if ((0, import_utils25.isFunction)(resolveIdFilter)) {
5322
5664
  return await resolveIdFilter.call(req, id);
5323
5665
  }
5324
- if ((0, import_utils24.isString)(idField)) {
5666
+ if ((0, import_utils25.isString)(idField)) {
5325
5667
  return { [idField]: id };
5326
5668
  }
5327
5669
  return { _id: id };
@@ -5345,7 +5687,7 @@ async function resolveAccessFilterParts({
5345
5687
  }
5346
5688
  const overrideFilterFn = getOption(`overrideFilter.${access}`, null);
5347
5689
  const baseFilterFn = rows2.mode === "request" ? getOption(`baseFilter.${access}`, null) : null;
5348
- if (nextFilter !== false && (0, import_utils24.isFunction)(overrideFilterFn)) {
5690
+ if (nextFilter !== false && (0, import_utils25.isFunction)(overrideFilterFn)) {
5349
5691
  nextFilter = normalizeFilter(await overrideFilterFn.call(req, nextFilter, permissions));
5350
5692
  }
5351
5693
  if (nextFilter === false) return { transformed: false, scope: {}, filter: false };
@@ -5353,7 +5695,7 @@ async function resolveAccessFilterParts({
5353
5695
  const scope2 = rows2.mode === "scope" ? rows2.filter : {};
5354
5696
  return { transformed: nextFilter ?? {}, scope: scope2, filter: intersectFilters(nextFilter, scope2) };
5355
5697
  }
5356
- if (!(0, import_utils24.isFunction)(baseFilterFn)) return { transformed: nextFilter ?? {}, scope: {}, filter: nextFilter ?? {} };
5698
+ if (!(0, import_utils25.isFunction)(baseFilterFn)) return { transformed: nextFilter ?? {}, scope: {}, filter: nextFilter ?? {} };
5357
5699
  const cached = cache.get(cacheKey);
5358
5700
  const reusable = cached?.resolver === baseFilterFn;
5359
5701
  const baseFilter = normalizeFilter(
@@ -5388,34 +5730,34 @@ async function setRequestPermissions(req) {
5388
5730
  if (owner === activeRuntime) return;
5389
5731
  if (hasFieldValue && owner === void 0) return;
5390
5732
  const globalPermissions = getGlobalOption("globalPermissions");
5391
- const permissions = (0, import_utils24.isFunction)(globalPermissions) ? await globalPermissions.call(req, req) : void 0;
5392
- if ((0, import_utils24.isPlainObject)(permissions)) req[requestPermissionField] = permissions;
5393
- else if ((0, import_utils24.isArray)(permissions)) req[requestPermissionField] = (0, import_utils24.arrayToRecord)(permissions);
5394
- else if ((0, import_utils24.isString)(permissions)) req[requestPermissionField] = { [permissions]: true };
5733
+ const permissions = (0, import_utils25.isFunction)(globalPermissions) ? await globalPermissions.call(req, req) : void 0;
5734
+ if ((0, import_utils25.isPlainObject)(permissions)) req[requestPermissionField] = permissions;
5735
+ else if ((0, import_utils25.isArray)(permissions)) req[requestPermissionField] = (0, import_utils25.arrayToRecord)(permissions);
5736
+ else if ((0, import_utils25.isString)(permissions)) req[requestPermissionField] = { [permissions]: true };
5395
5737
  else req[requestPermissionField] = {};
5396
5738
  owners.set(requestPermissionField, activeRuntime);
5397
5739
  }
5398
5740
  async function evaluateRouteGuard(req, permissions, routeGuard) {
5399
5741
  const phas = (key) => permissions.has(key);
5400
5742
  const { stringHandler, arrayHandler } = createValidator(phas);
5401
- if ((0, import_utils24.isBoolean)(routeGuard)) {
5743
+ if ((0, import_utils25.isBoolean)(routeGuard)) {
5402
5744
  return routeGuard === true;
5403
5745
  }
5404
- if ((0, import_utils24.isString)(routeGuard)) {
5746
+ if ((0, import_utils25.isString)(routeGuard)) {
5405
5747
  return stringHandler(routeGuard);
5406
5748
  }
5407
- if ((0, import_utils24.isArray)(routeGuard)) {
5749
+ if ((0, import_utils25.isArray)(routeGuard)) {
5408
5750
  return arrayHandler(routeGuard);
5409
5751
  }
5410
- if ((0, import_utils24.isFunction)(routeGuard)) {
5752
+ if ((0, import_utils25.isFunction)(routeGuard)) {
5411
5753
  return routeGuard.call(req, permissions);
5412
5754
  }
5413
5755
  return false;
5414
5756
  }
5415
5757
  async function callHookChain(req, hook, doc, permissions, context) {
5416
- const hooks = (0, import_utils24.castArray)(hook);
5758
+ const hooks = (0, import_utils25.castArray)(hook);
5417
5759
  for (let x = 0; x < hooks.length; x++) {
5418
- if ((0, import_utils24.isFunction)(hooks[x])) {
5760
+ if ((0, import_utils25.isFunction)(hooks[x])) {
5419
5761
  doc = await hooks[x].call(req, doc, permissions, context);
5420
5762
  }
5421
5763
  }
@@ -5435,22 +5777,22 @@ async function collectSchemaFields({
5435
5777
  for (let x = 0; x < keys2.length; x++) {
5436
5778
  const key = keys2[x];
5437
5779
  const value = extractScopedOutputRule(permissionSchema, key, access);
5438
- if ((0, import_utils24.isBoolean)(value)) {
5780
+ if ((0, import_utils25.isBoolean)(value)) {
5439
5781
  if (value) fields.push(key);
5440
- } else if ((0, import_utils24.isString)(value)) {
5782
+ } else if ((0, import_utils25.isString)(value)) {
5441
5783
  if (stringHandler(value)) fields.push(key);
5442
- } else if ((0, import_utils24.isArray)(value)) {
5784
+ } else if ((0, import_utils25.isArray)(value)) {
5443
5785
  if (arrayHandler(value)) fields.push(key);
5444
- } else if ((0, import_utils24.isFunction)(value)) {
5786
+ } else if ((0, import_utils25.isFunction)(value)) {
5445
5787
  if (await value.call(req, ...functionArgs)) fields.push(key);
5446
5788
  }
5447
5789
  }
5448
5790
  return fields;
5449
5791
  }
5450
- var import_utils24, import_node_util7, permissionFieldOwners;
5792
+ var import_utils25, import_node_util7, permissionFieldOwners;
5451
5793
  var init_core_shared = __esm({
5452
5794
  "src/core-shared.ts"() {
5453
- import_utils24 = require("@web-ts-toolkit/utils");
5795
+ import_utils25 = require("@web-ts-toolkit/utils");
5454
5796
  import_node_util7 = require("util");
5455
5797
  init_helpers();
5456
5798
  init_options();
@@ -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,
@@ -6409,7 +6758,8 @@ function authorizeEmbeddedOutputPlan(parent, child) {
6409
6758
  ...view,
6410
6759
  requestPermissions: getAuthorizationPermissions(parent.authorization, parent.authorizationBinding),
6411
6760
  authorization: serviceAuthorizationInput(view.authorization, view.relatedTargets),
6412
- parent: parent.authorization
6761
+ parent: parent.authorization,
6762
+ snapshotDerivation: { kind: "embedded", parentBinding: parent.authorizationBinding }
6413
6763
  });
6414
6764
  return { ...child, authorization, authorizationBinding: binding };
6415
6765
  }
@@ -7333,7 +7683,7 @@ init_options();
7333
7683
  init_permission();
7334
7684
 
7335
7685
  // src/services/base.ts
7336
- var import_utils25 = require("@web-ts-toolkit/utils");
7686
+ var import_utils26 = require("@web-ts-toolkit/utils");
7337
7687
  init_options();
7338
7688
  init_helpers();
7339
7689
  init_document();
@@ -7901,14 +8251,111 @@ function isCorrelatedInclude(value) {
7901
8251
  // src/services/base.ts
7902
8252
  init_request_complexity();
7903
8253
 
7904
- // src/acl/model-service-owner.ts
8254
+ // src/model.ts
7905
8255
  var import_node_async_hooks3 = require("async_hooks");
8256
+ var import_utils23 = require("@web-ts-toolkit/utils");
8257
+ init_runtime_context();
8258
+ init_runtime();
8259
+ var capturedModelConstruction = new import_node_async_hooks3.AsyncLocalStorage();
8260
+ function withCapturedPopulateModel(runtime, modelName, model, construct) {
8261
+ return capturedModelConstruction.run({ runtime, modelName, model }, construct);
8262
+ }
8263
+ function admitModelPersistence(adapter, scheduler) {
8264
+ return {
8265
+ modelName: adapter.modelName,
8266
+ mongooseModel: adapter.mongooseModel,
8267
+ new: () => adapter.new(),
8268
+ // Mongoose create(array) otherwise starts all document saves at once. Keep
8269
+ // the adapter's array input/output contract, with one permit per item; all
8270
+ // items are submitted even if one rejects, as with unordered create(array).
8271
+ create: (data) => Array.isArray(data) ? Promise.all(data.map((item) => scheduler.work(async () => (await adapter.create([item]))[0]))) : scheduler.work(() => adapter.create(data)),
8272
+ find: (props) => scheduler.work(() => adapter.find(props)),
8273
+ findOne: (props) => scheduler.work(() => adapter.findOne(props)),
8274
+ exists: (filter2) => scheduler.work(() => adapter.exists(filter2)),
8275
+ countDocuments: (filter2) => scheduler.work(() => adapter.countDocuments(filter2)),
8276
+ distinct: (field, conditions) => scheduler.work(() => adapter.distinct(field, conditions)),
8277
+ aggregate: (pipeline) => scheduler.work(() => adapter.aggregate(pipeline)),
8278
+ // Casting builds no persistence work and must not acquire a recursive permit.
8279
+ ...adapter.castFilter ? { castFilter: (filter2) => adapter.castFilter(filter2) } : {}
8280
+ };
8281
+ }
8282
+ var Model = class {
8283
+ constructor(modelName, runtime) {
8284
+ this.modelName = modelName;
8285
+ this.runtime = runtime ?? null;
8286
+ const resolvedRuntime = runtime ?? getActiveRuntime() ?? defaultRuntime;
8287
+ const captured = capturedModelConstruction.getStore();
8288
+ const registered = captured?.runtime === resolvedRuntime && captured.modelName === modelName ? captured.model : resolvedRuntime.getModelInstance(modelName);
8289
+ if (!registered) {
8290
+ throw new Error(
8291
+ `Runtime model registry missing model "${modelName}". Pass a mongoose.Model instance to createRouter() or register it with registerModelInstance() before using this runtime.`
8292
+ );
8293
+ }
8294
+ this.mongooseModel = registered;
8295
+ if (!this.mongooseModel) return;
8296
+ }
8297
+ new() {
8298
+ const doc = new this.mongooseModel();
8299
+ return doc;
8300
+ }
8301
+ create(data) {
8302
+ return this.mongooseModel.create(data);
8303
+ }
8304
+ find({ filter: filter2, select, sort, populate, limit, hardLimit, skip, lean }) {
8305
+ const builder = this.mongooseModel.find(filter2);
8306
+ if (select) builder.select(select);
8307
+ if (skip) builder.skip(Number(skip));
8308
+ const normalizedLimit = Number(limit);
8309
+ if (Number.isSafeInteger(normalizedLimit) && normalizedLimit > 0) {
8310
+ builder.limit(normalizedLimit);
8311
+ } else if (Number.isSafeInteger(hardLimit) && Number(hardLimit) > 0) {
8312
+ builder.limit(Number(hardLimit));
8313
+ }
8314
+ if (sort) builder.sort(sort);
8315
+ if (populate) builder.populate(populate);
8316
+ if (lean) builder.lean();
8317
+ return builder;
8318
+ }
8319
+ findOne({ filter: filter2, select, sort, populate, lean }) {
8320
+ const builder = this.mongooseModel.findOne(filter2);
8321
+ if (select) builder.select(select);
8322
+ if (sort) builder.sort(sort);
8323
+ if (populate) builder.populate(populate);
8324
+ if (lean) builder.lean();
8325
+ return builder;
8326
+ }
8327
+ exists(filter2) {
8328
+ if (!filter2) return null;
8329
+ return this.findOne({ filter: filter2 }).select("_id").lean();
8330
+ }
8331
+ // see https://mongoosejs.com/docs/api.html#query_Query-countDocuments
8332
+ countDocuments(filter2 = {}) {
8333
+ return this.mongooseModel.countDocuments(filter2);
8334
+ }
8335
+ /** Cast a copy using this model's query schema/setters, without executing query middleware or persistence. */
8336
+ castFilter(filter2) {
8337
+ const query = this.mongooseModel.countDocuments((0, import_utils23.cloneDeep)(filter2));
8338
+ return query.cast(this.mongooseModel);
8339
+ }
8340
+ // see https://mongoosejs.com/docs/api.html#model_Model.distinct
8341
+ distinct(field, conditions = {}) {
8342
+ return this.mongooseModel.distinct(field, conditions);
8343
+ }
8344
+ aggregate(pipeline) {
8345
+ return this.mongooseModel.aggregate(pipeline);
8346
+ }
8347
+ };
8348
+ var model_default = Model;
8349
+
8350
+ // src/acl/model-service-owner.ts
8351
+ var import_node_async_hooks4 = require("async_hooks");
7906
8352
  init_runtime();
7907
8353
  init_runtime_context();
8354
+ init_populate_policy2();
7908
8355
  var cores = /* @__PURE__ */ new WeakMap();
7909
- var construction = new import_node_async_hooks3.AsyncLocalStorage();
7910
- var dispatch = new import_node_async_hooks3.AsyncLocalStorage();
7911
- var operationGuard = new import_node_async_hooks3.AsyncLocalStorage();
8356
+ var construction = new import_node_async_hooks4.AsyncLocalStorage();
8357
+ var dispatch = new import_node_async_hooks4.AsyncLocalStorage();
8358
+ var operationGuard = new import_node_async_hooks4.AsyncLocalStorage();
7912
8359
  function withCapturedModelOperationGuard(core, modelName, access, guard2, permissions, run) {
7913
8360
  return operationGuard.run({ captured: { core, modelName, access, guard: guard2, permissions } }, run);
7914
8361
  }
@@ -7957,15 +8404,16 @@ function bindModelOwnerMethods(receiver, runtime) {
7957
8404
  }
7958
8405
  }
7959
8406
  }
7960
- function modelServiceOptions(receiver, read) {
8407
+ function modelServiceOptions(receiver, runtime, read) {
8408
+ modelServicePopulatePolicyDefaults(receiver, runtime);
7961
8409
  const call = dispatch.getStore();
7962
8410
  if (call?.receiver !== receiver) return read();
7963
8411
  return call.options ??= read();
7964
8412
  }
7965
- function modelServiceGlobalOptions(receiver, runtime) {
8413
+ function modelServicePopulatePolicyDefaults(receiver, runtime) {
7966
8414
  const call = dispatch.getStore();
7967
- if (call?.receiver !== receiver) return runtime.getGlobalOptions();
7968
- return call.globalOptions ??= runtime.getGlobalOptions();
8415
+ if (call?.receiver !== receiver) return capturePopulatePolicyDefaults(runtime);
8416
+ return call.populatePolicyDefaults ??= capturePopulatePolicyDefaults(runtime);
7969
8417
  }
7970
8418
 
7971
8419
  // src/services/base.ts
@@ -8119,27 +8567,6 @@ function castCountGroups(input, values) {
8119
8567
  // src/services/base.ts
8120
8568
  init_service_authorization();
8121
8569
 
8122
- // src/meta.ts
8123
- init_runtime();
8124
- init_runtime_context();
8125
- var getRuntime5 = () => getActiveRuntime() ?? defaultRuntime;
8126
- var getModelRef = (modelName, refPath, runtime = getRuntime5()) => {
8127
- const direct = runtime.getModelRef(modelName, refPath);
8128
- if (direct) return direct;
8129
- if (!refPath.includes(".")) return null;
8130
- try {
8131
- const instance = runtime.getModelInstance?.(
8132
- modelName
8133
- );
8134
- const schemaPath = instance?.schema?.path?.(refPath);
8135
- const element = schemaPath?.$embeddedSchemaType ?? schemaPath?.embeddedSchemaType ?? schemaPath?.caster;
8136
- const ref = schemaPath?.options?.ref ?? element?.options?.ref ?? null;
8137
- return typeof ref === "string" && ref.length > 0 ? ref : null;
8138
- } catch {
8139
- return null;
8140
- }
8141
- };
8142
-
8143
8570
  // src/acl/related-execution.ts
8144
8571
  init_public_admission();
8145
8572
  init_model_output_planning();
@@ -8160,7 +8587,7 @@ function getServiceExecutors(receiver) {
8160
8587
  if (!registered) authorizationError("unregistered service receiver");
8161
8588
  return registered;
8162
8589
  }
8163
- function createServiceExecution(receiver, access, authorization, applicability = "service", relatedTargets = [], parent, configuration, requestPermissions, hydration = access.operation === "list" ? "find" : "findOne") {
8590
+ function createServiceExecution(receiver, access, authorization, applicability = "service", relatedTargets = [], parent, configuration, requestPermissions, hydration = access.operation === "list" ? "find" : "findOne", snapshotDerivation) {
8164
8591
  const registered = getServiceExecutors(receiver);
8165
8592
  const receiving = registered.binding();
8166
8593
  const binding = Object.freeze({ ...receiving, scopePath: Object.freeze([...receiving.scopePath ?? []]) });
@@ -8174,7 +8601,8 @@ function createServiceExecution(receiver, access, authorization, applicability =
8174
8601
  configuration: configuration ?? registered.configuration(),
8175
8602
  requestPermissions: requestPermissions ?? registered.permissions(),
8176
8603
  listResponse: access.operation === "list" && parent === void 0,
8177
- readResponse: access.operation === "read" && parent === void 0
8604
+ readResponse: access.operation === "read" && parent === void 0,
8605
+ snapshotDerivation
8178
8606
  });
8179
8607
  const execution = Object.freeze(/* @__PURE__ */ Object.create(null));
8180
8608
  executions.set(
@@ -8231,7 +8659,8 @@ function deriveServiceExecution(receiver, parent, access, applicability = "servi
8231
8659
  parent: record3.authorization,
8232
8660
  // The resolver authenticates root-read provenance and the unchanged owner tuple.
8233
8661
  // Effective list access is still a read; write branches cannot inherit this marker.
8234
- readResponse: record3.access.operation === "read" && access.operation === "read"
8662
+ readResponse: record3.access.operation === "read" && access.operation === "read",
8663
+ snapshotDerivation: { kind: "retry", parentBinding: record3.binding }
8235
8664
  });
8236
8665
  const execution = Object.freeze(/* @__PURE__ */ Object.create(null));
8237
8666
  executions.set(
@@ -8385,9 +8814,9 @@ function resolveExistsOptions(service, options = {}) {
8385
8814
 
8386
8815
  // src/services/model-service-intent.ts
8387
8816
  function captureModelServiceIntent(owner, method, args = {}, options = {}) {
8388
- const defaults = owner.defaults;
8817
+ const defaults2 = owner.defaults;
8389
8818
  const posture = owner.getPermissionsPosture();
8390
- const service = { defaults, getPermissionsPosture: () => posture };
8819
+ const service = { defaults: defaults2, getPermissionsPosture: () => posture };
8391
8820
  switch (method) {
8392
8821
  case "find":
8393
8822
  return deepIsolateValue({ args: resolveFindArgs(service, args), options: resolveFindOptions(service, options) });
@@ -8418,6 +8847,7 @@ function captureModelServiceIntent(owner, method, args = {}, options = {}) {
8418
8847
  }
8419
8848
 
8420
8849
  // src/acl/related-execution.ts
8850
+ init_populate_policy2();
8421
8851
  init_service_authorization();
8422
8852
  function staticObjectIdReference(runtime, source, path, target) {
8423
8853
  const model = runtime.getModelInstance(source), related = runtime.getModelInstance(target);
@@ -8434,7 +8864,7 @@ function staticObjectIdReference(runtime, source, path, target) {
8434
8864
  const scalar = type?.instance === "Array" ? type.$embeddedSchemaType ?? type.embeddedSchemaType ?? type.caster : type;
8435
8865
  return scalar?.instance === "ObjectId" && (type?.options?.ref ?? scalar.options?.ref) === target && type?.options?.refPath === void 0 && scalar.options?.refPath === void 0;
8436
8866
  }
8437
- function captureRelatedTargets(runtime, modelName, args = {}, depth = 0, globalOptions = runtime.getGlobalOptions()) {
8867
+ function captureRelatedTargets(runtime, modelName, args = {}, depth = 0, populatePolicyDefaults = capturePopulatePolicyDefaults(runtime)) {
8438
8868
  if (depth > 32) authorizationError("related descriptor depth exceeded");
8439
8869
  assertPublicAdmission(args.populate, "populate");
8440
8870
  assertPublicAdmission(args.include, "include");
@@ -8443,20 +8873,32 @@ function captureRelatedTargets(runtime, modelName, args = {}, depth = 0, globalO
8443
8873
  for (const entry of entries(args.populate)) {
8444
8874
  const path = typeof entry === "string" ? entry : entry.path;
8445
8875
  if (typeof entry !== "string") assertPopulateAccess(entry.access);
8446
- const model = getModelRef(modelName, path, runtime);
8447
- if (model) {
8448
- const target = capturePopulateTargetConfiguration(runtime, model, `${modelName}.${path}`);
8876
+ const target = capturePopulateTargetBinding(runtime, modelName, path);
8877
+ if (target) {
8449
8878
  targets.push({
8450
8879
  path,
8451
- modelName: model,
8452
- configuration: captureModelAuthorizationConfiguration(runtime, model, target.options, globalOptions),
8453
- staticObjectIdReference: staticObjectIdReference(runtime, modelName, path, model)
8880
+ modelName: target.modelName,
8881
+ model: target.model,
8882
+ configuration: captureModelAuthorizationConfiguration(
8883
+ runtime,
8884
+ target.modelName,
8885
+ target.options,
8886
+ populatePolicyDefaults
8887
+ ),
8888
+ staticObjectIdReference: staticObjectIdReference(runtime, modelName, path, target.modelName)
8454
8889
  });
8455
8890
  }
8456
8891
  }
8457
8892
  for (const entry of entries(args.include)) {
8458
8893
  if (!runtime.hasModel(entry.model)) authorizationError(`Model ${entry.model} not found`);
8459
- const configuration = captureModelAuthorizationConfiguration(runtime, entry.model, void 0, globalOptions);
8894
+ const model = runtime.getModelInstance(entry.model);
8895
+ if (!model) authorizationError(`unknown receiving model: ${entry.model}`);
8896
+ const configuration = captureModelAuthorizationConfiguration(
8897
+ runtime,
8898
+ entry.model,
8899
+ void 0,
8900
+ populatePolicyDefaults
8901
+ );
8460
8902
  const queryIntent = entry.op === "count" ? void 0 : captureModelServiceIntent(
8461
8903
  {
8462
8904
  defaults: configuration.defaults ?? {},
@@ -8478,6 +8920,7 @@ function captureRelatedTargets(runtime, modelName, args = {}, depth = 0, globalO
8478
8920
  targets.push({
8479
8921
  path: entry.path,
8480
8922
  modelName: entry.model,
8923
+ model,
8481
8924
  kind: entry.op === "count" ? "count" : "output",
8482
8925
  configuration,
8483
8926
  queryIntent,
@@ -8487,7 +8930,7 @@ function captureRelatedTargets(runtime, modelName, args = {}, depth = 0, globalO
8487
8930
  entry.model,
8488
8931
  queryIntent?.args ?? entry.args ?? {},
8489
8932
  depth + 1,
8490
- globalOptions
8933
+ populatePolicyDefaults
8491
8934
  )
8492
8935
  });
8493
8936
  }
@@ -8504,7 +8947,8 @@ function createRelatedExecution(receiver, access, parent, binding, path) {
8504
8947
  const captured = readServiceAuthorization(parent, binding);
8505
8948
  const target = captured.relatedTargets.find((entry) => entry.path === path);
8506
8949
  const policy = captured.authorization.related[path];
8507
- if (policy && (!target || target.modelName !== getServiceExecutors(receiver).binding().modelName))
8950
+ const receiving = getServiceExecutors(receiver).binding();
8951
+ if (policy && !target || target && (target.modelName !== receiving.modelName || target.model !== void 0 && target.model !== receiving.model))
8508
8952
  authorizationError(`related model mismatch: ${path}`);
8509
8953
  const execution = createServiceExecution(
8510
8954
  receiver,
@@ -8514,7 +8958,9 @@ function createRelatedExecution(receiver, access, parent, binding, path) {
8514
8958
  target?.relatedTargets ?? [],
8515
8959
  parent,
8516
8960
  target?.configuration,
8517
- getAuthorizationPermissions(parent, binding)
8961
+ getAuthorizationPermissions(parent, binding),
8962
+ access.operation === "list" ? "find" : "findOne",
8963
+ { kind: "related", parentBinding: binding, path }
8518
8964
  );
8519
8965
  return target?.queryIntent ? withExecutionQueryIntent(receiver, execution, target.queryIntent) : execution;
8520
8966
  }
@@ -8637,20 +9083,20 @@ var copyAuthorizedOutput = (value) => {
8637
9083
  transferDocumentAuthorizationGraph(value, copy);
8638
9084
  return copy;
8639
9085
  };
8640
- var isVirtualContainerValueForGuard = (value) => (0, import_utils25.isPlainObject)(value) && "sub" in value;
9086
+ var isVirtualContainerValueForGuard = (value) => (0, import_utils26.isPlainObject)(value) && "sub" in value;
8641
9087
  var getScopeVirtualsForGuard = (rootVirtuals, scopePath) => {
8642
- if (!rootVirtuals || !(0, import_utils25.isPlainObject)(rootVirtuals)) return null;
9088
+ if (!rootVirtuals || !(0, import_utils26.isPlainObject)(rootVirtuals)) return null;
8643
9089
  if (scopePath.length === 0) return rootVirtuals;
8644
9090
  let current = rootVirtuals;
8645
9091
  for (let i = 0; i < scopePath.length; i += 2) {
8646
9092
  const field = scopePath[i];
8647
9093
  const subMarker = scopePath[i + 1];
8648
9094
  if (!field || subMarker !== "sub") return null;
8649
- if (!(0, import_utils25.isPlainObject)(current)) return null;
9095
+ if (!(0, import_utils26.isPlainObject)(current)) return null;
8650
9096
  const container = current[field];
8651
9097
  if (!isVirtualContainerValueForGuard(container)) return null;
8652
9098
  current = container.sub;
8653
- if (!(0, import_utils25.isPlainObject)(current)) return null;
9099
+ if (!(0, import_utils26.isPlainObject)(current)) return null;
8654
9100
  }
8655
9101
  return current;
8656
9102
  };
@@ -8716,7 +9162,7 @@ var sanitizeSubScopeVirtualKeys = (data, snapshot, sub) => {
8716
9162
  for (const entry of value) stripScope(entry, currentScope);
8717
9163
  return;
8718
9164
  }
8719
- if (!(0, import_utils25.isPlainObject)(value)) return;
9165
+ if (!(0, import_utils26.isPlainObject)(value)) return;
8720
9166
  const record3 = value;
8721
9167
  const leaves = getScopeVirtualLeafNames(snapshot, currentScope);
8722
9168
  for (const leaf of leaves) {
@@ -8729,7 +9175,7 @@ var sanitizeSubScopeVirtualKeys = (data, snapshot, sub) => {
8729
9175
  for (const key of Object.keys(record3)) {
8730
9176
  if (leaves.has(key) || containers.has(key)) continue;
8731
9177
  const child = record3[key];
8732
- if (Array.isArray(child) || (0, import_utils25.isPlainObject)(child)) {
9178
+ if (Array.isArray(child) || (0, import_utils26.isPlainObject)(child)) {
8733
9179
  stripScope(child, currentScope);
8734
9180
  }
8735
9181
  }
@@ -8741,7 +9187,7 @@ var LOGICAL_FILTER_KEYS = /* @__PURE__ */ new Set(["$and", "$or", "$nor"]);
8741
9187
  var isOperatorKey = (key) => key.startsWith("$");
8742
9188
  var REMOVED_VIRTUAL_FILTER = /* @__PURE__ */ Symbol("removed virtual filter clause");
8743
9189
  var rewriteFilterObject = (value, visit) => {
8744
- if (!(0, import_utils25.isPlainObject)(value)) return value;
9190
+ if (!(0, import_utils26.isPlainObject)(value)) return value;
8745
9191
  let changed = false;
8746
9192
  const entries = [];
8747
9193
  for (const [key, child] of Object.entries(value)) {
@@ -8772,7 +9218,7 @@ var resolveVirtualFilterField = (path, scope2) => {
8772
9218
  if (!Object.hasOwn(scope2, segment) || scope2[segment] === void 0) return null;
8773
9219
  const definition = scope2[segment];
8774
9220
  if (!isVirtualContainerValueForGuard(definition)) return REMOVED_VIRTUAL_FILTER;
8775
- scope2 = (0, import_utils25.isPlainObject)(definition.sub) ? definition.sub : null;
9221
+ scope2 = (0, import_utils26.isPlainObject)(definition.sub) ? definition.sub : null;
8776
9222
  inContainer = true;
8777
9223
  }
8778
9224
  return scope2;
@@ -8784,7 +9230,7 @@ var stripVirtualFilterOperator = (key, value, scope2) => {
8784
9230
  }
8785
9231
  if (key === "$all") {
8786
9232
  return rewriteFilterClauses(value, (entry) => {
8787
- if (!(0, import_utils25.isPlainObject)(entry) || Object.keys(entry).length !== 1 || !Object.hasOwn(entry, "$elemMatch")) return entry;
9233
+ if (!(0, import_utils26.isPlainObject)(entry) || Object.keys(entry).length !== 1 || !Object.hasOwn(entry, "$elemMatch")) return entry;
8788
9234
  return rewriteFilterObject(entry, (operator, operand) => stripVirtualFilterOperator(operator, operand, scope2));
8789
9235
  });
8790
9236
  }
@@ -8799,7 +9245,7 @@ var stripVirtualFilterQuery = (value, scope2, element = false) => {
8799
9245
  if (isOperatorKey(key)) return element ? stripVirtualFilterOperator(key, child, scope2) : child;
8800
9246
  const fieldScope = resolveVirtualFilterField(key, scope2);
8801
9247
  if (fieldScope === REMOVED_VIRTUAL_FILTER) return REMOVED_VIRTUAL_FILTER;
8802
- if (!fieldScope || !(0, import_utils25.isPlainObject)(child)) return child;
9248
+ if (!fieldScope || !(0, import_utils26.isPlainObject)(child)) return child;
8803
9249
  if (Object.keys(child).some(isOperatorKey)) {
8804
9250
  return rewriteFilterObject(
8805
9251
  child,
@@ -8821,9 +9267,9 @@ var stripSubVirtualKeysFromFilter = (filter2, snapshot, sub) => {
8821
9267
  function getCorrelatedTemplateDepth(includes) {
8822
9268
  let max = 0;
8823
9269
  const visit = (entries, depth) => {
8824
- const list = (0, import_utils25.castArray)(entries).filter(Boolean);
9270
+ const list = (0, import_utils26.castArray)(entries).filter(Boolean);
8825
9271
  for (const entry of list) {
8826
- if (!(0, import_utils25.isPlainObject)(entry)) continue;
9272
+ if (!(0, import_utils26.isPlainObject)(entry)) continue;
8827
9273
  max = Math.max(max, depth);
8828
9274
  const nested = entry.args?.include;
8829
9275
  if (nested !== void 0) {
@@ -8848,11 +9294,11 @@ function validateClientFilter(filter2) {
8848
9294
  }
8849
9295
  const blockedOperators = /* @__PURE__ */ new Set(["$where", "$expr", "$function", "$accumulator"]);
8850
9296
  const visit = (value, path) => {
8851
- if ((0, import_utils25.isArray)(value)) {
9297
+ if ((0, import_utils26.isArray)(value)) {
8852
9298
  value.forEach((item, index) => visit(item, `${path}[${index}]`));
8853
9299
  return;
8854
9300
  }
8855
- if (!(0, import_utils25.isPlainObject)(value)) return;
9301
+ if (!(0, import_utils26.isPlainObject)(value)) return;
8856
9302
  Object.entries(value).forEach(([key, child]) => {
8857
9303
  const nextPath = path ? `${path}.${key}` : key;
8858
9304
  if (blockedOperators.has(key)) {
@@ -9000,34 +9446,37 @@ var Base = class {
9000
9446
  });
9001
9447
  }
9002
9448
  async getAuthorizedTargetService(modelName, op, path, parentAuthorization) {
9003
- if (hasModelCoreOwner(this.requestCore) && !this.requestRuntime.hasModel(modelName)) {
9449
+ const binding = parentAuthorization ? this.relatedBinding() : void 0;
9450
+ const captured = parentAuthorization ? readServiceAuthorization(parentAuthorization, binding) : void 0;
9451
+ const target = captured?.relatedTargets.find((entry) => entry.path === path);
9452
+ const policy = path ? captured?.authorization.related[path] : void 0;
9453
+ if (target && target.modelName !== modelName)
9454
+ this.throwClientRequestError("bad_request" /* BadRequest */, `related model mismatch: ${path}`);
9455
+ if (hasModelCoreOwner(this.requestCore) && !target?.model && !this.requestRuntime.hasModel(modelName)) {
9004
9456
  this.throwClientRequestError("bad_request" /* BadRequest */, `Model ${modelName} not found`);
9005
9457
  }
9006
- const policy = path ? relatedPolicy(parentAuthorization, this.relatedBinding(), path) : void 0;
9007
- const captured = parentAuthorization ? readServiceAuthorization(parentAuthorization, this.relatedBinding()) : void 0;
9008
- const target = captured?.relatedTargets.find((entry) => entry.path === path);
9009
9458
  const allowed = policy?.operation.mode === "grant" || (target ? await getRequestWorkState(this.req, this.requestRuntime).hookGate.run(
9010
9459
  () => withCapturedModelOperationGuard(
9011
9460
  this.requestCore,
9012
9461
  modelName,
9013
9462
  op,
9014
9463
  target.operationGuard,
9015
- getAuthorizationPermissions(parentAuthorization, this.relatedBinding()),
9464
+ getAuthorizationPermissions(parentAuthorization, binding),
9016
9465
  () => this.requestCore.isAllowed(modelName, op)
9017
9466
  )
9018
9467
  ) : await this.requestCore.isAllowed(modelName, op));
9019
9468
  if (!allowed) {
9020
9469
  this.throwClientRequestError("unauthorized" /* Unauthorized */, "Unauthorized");
9021
9470
  }
9022
- return this.requestCore.getPublicService(modelName);
9471
+ return target?.model ? withCapturedPopulateModel(
9472
+ this.requestRuntime,
9473
+ modelName,
9474
+ target.model,
9475
+ () => this.requestCore.getPublicService(modelName)
9476
+ ) : this.requestCore.getPublicService(modelName);
9023
9477
  }
9024
9478
  relatedBinding() {
9025
- return {
9026
- request: this.req,
9027
- runtime: this.requestRuntime,
9028
- model: this.requestRuntime.getModelInstance(this.modelName),
9029
- modelName: this.modelName
9030
- };
9479
+ return getServiceExecutors(this).binding();
9031
9480
  }
9032
9481
  relatedExecution(svc, include, parentAuthorization) {
9033
9482
  const op = include.op;
@@ -9057,7 +9506,7 @@ var Base = class {
9057
9506
  }
9058
9507
  processInclude(include, authorization) {
9059
9508
  assertPublicAdmission(include, "include");
9060
- const items = (0, import_utils25.compact)((0, import_utils25.castArray)(include));
9509
+ const items = (0, import_utils26.compact)((0, import_utils26.castArray)(include));
9061
9510
  const legacy = [];
9062
9511
  const correlated = [];
9063
9512
  const correlatedReferenceFields = [];
@@ -9093,23 +9542,23 @@ var Base = class {
9093
9542
  else this.assertIncludeOutputPaths([...legacy, ...correlated]);
9094
9543
  let includeLocalFields = [];
9095
9544
  let includePaths = [];
9096
- (0, import_utils25.forEach)(legacy, (inc) => {
9545
+ (0, import_utils26.forEach)(legacy, (inc) => {
9097
9546
  includeLocalFields.push(inc.localField);
9098
9547
  includePaths.push(inc.path);
9099
9548
  });
9100
- includeLocalFields = (0, import_utils25.uniq)((0, import_utils25.compact)(includeLocalFields));
9101
- includePaths = (0, import_utils25.uniq)((0, import_utils25.compact)(includePaths));
9549
+ includeLocalFields = (0, import_utils26.uniq)((0, import_utils26.compact)(includeLocalFields));
9550
+ includePaths = (0, import_utils26.uniq)((0, import_utils26.compact)(includePaths));
9102
9551
  return {
9103
9552
  includes: legacy,
9104
9553
  correlatedIncludes: correlated,
9105
9554
  includeLocalFields,
9106
9555
  includePaths,
9107
- correlatedReferenceFields: (0, import_utils25.uniq)((0, import_utils25.compact)(correlatedReferenceFields))
9556
+ correlatedReferenceFields: (0, import_utils26.uniq)((0, import_utils26.compact)(correlatedReferenceFields))
9108
9557
  };
9109
9558
  }
9110
9559
  validateIncludeOutputPath(path, modelName, configuration) {
9111
9560
  const permissionField = configuration ? configuration.documentPermissionField ?? "_permissions" : getModelOption(modelName, "documentPermissionField");
9112
- if ((0, import_utils25.get)((0, import_utils25.set)({}, path, true), permissionField) !== void 0 || (0, import_utils25.get)((0, import_utils25.set)({}, permissionField, true), path) !== void 0) {
9561
+ if ((0, import_utils26.get)((0, import_utils26.set)({}, path, true), permissionField) !== void 0 || (0, import_utils26.get)((0, import_utils26.set)({}, permissionField, true), path) !== void 0) {
9113
9562
  this.throwClientRequestError(
9114
9563
  "bad_request" /* BadRequest */,
9115
9564
  `Include output path ${path} overlaps document permission field ${permissionField} on model ${modelName}`
@@ -9134,9 +9583,9 @@ var Base = class {
9134
9583
  const walk = (node, prefix) => {
9135
9584
  for (const [key, value] of Object.entries(node)) {
9136
9585
  if (value === void 0) continue;
9137
- if ((0, import_utils25.isPlainObject)(value) && "sub" in value) {
9586
+ if ((0, import_utils26.isPlainObject)(value) && "sub" in value) {
9138
9587
  const sub = value.sub;
9139
- if ((0, import_utils25.isPlainObject)(sub)) walk(sub, prefix ? `${prefix}.${key}` : key);
9588
+ if ((0, import_utils26.isPlainObject)(sub)) walk(sub, prefix ? `${prefix}.${key}` : key);
9140
9589
  continue;
9141
9590
  }
9142
9591
  out.push(prefix ? `${prefix}.${key}` : key);
@@ -9189,7 +9638,7 @@ var Base = class {
9189
9638
  this.throwClientRequestError("bad_request" /* BadRequest */, `Model ${modelName} not found`);
9190
9639
  }
9191
9640
  for (const entry of entries) {
9192
- if (!(0, import_utils25.isPlainObject)(entry)) continue;
9641
+ if (!(0, import_utils26.isPlainObject)(entry)) continue;
9193
9642
  const models = visited.get(entry) ?? /* @__PURE__ */ new Set();
9194
9643
  if (models.has(modelName)) continue;
9195
9644
  models.add(modelName);
@@ -9202,7 +9651,7 @@ var Base = class {
9202
9651
  const target = targets?.find((target2) => target2.path === entry.path);
9203
9652
  if (nested)
9204
9653
  pending.push({
9205
- entries: (0, import_utils25.compact)((0, import_utils25.castArray)(nested)),
9654
+ entries: (0, import_utils26.compact)((0, import_utils26.castArray)(nested)),
9206
9655
  modelName: entry.model,
9207
9656
  configuration: target?.configuration,
9208
9657
  targets: target?.relatedTargets
@@ -9212,7 +9661,7 @@ var Base = class {
9212
9661
  }
9213
9662
  }
9214
9663
  getForeignKeyValues(value) {
9215
- return (0, import_utils25.flatten)((0, import_utils25.castArray)(value));
9664
+ return (0, import_utils26.flatten)((0, import_utils26.castArray)(value));
9216
9665
  }
9217
9666
  getForeignKey(value) {
9218
9667
  return String(value);
@@ -9220,7 +9669,7 @@ var Base = class {
9220
9669
  buildForeignKeyIndex(rows2, foreignField) {
9221
9670
  const index = /* @__PURE__ */ new Map();
9222
9671
  for (const row of rows2) {
9223
- for (const value of this.getForeignKeyValues((0, import_utils25.get)(row, foreignField))) {
9672
+ for (const value of this.getForeignKeyValues((0, import_utils26.get)(row, foreignField))) {
9224
9673
  const key = this.getForeignKey(value);
9225
9674
  const values = index.get(key);
9226
9675
  if (values) values.push(row);
@@ -9256,9 +9705,9 @@ var Base = class {
9256
9705
  async includeDocs(docs, include, parentAuthorization) {
9257
9706
  assertPublicAdmission(include, "include");
9258
9707
  if (!include) return docs;
9259
- const includes = (0, import_utils25.compact)((0, import_utils25.castArray)(include));
9708
+ const includes = (0, import_utils26.compact)((0, import_utils26.castArray)(include));
9260
9709
  if (includes.length === 0) return docs;
9261
- const isSingle = !(0, import_utils25.isArray)(docs);
9710
+ const isSingle = !(0, import_utils26.isArray)(docs);
9262
9711
  let docList = (isSingle ? [docs] : docs).map(prepareIncludeOutput);
9263
9712
  for (let x = 0; x < includes.length; x++) {
9264
9713
  const include2 = includes[x];
@@ -9288,7 +9737,7 @@ var Base = class {
9288
9737
  const svc = await this.getAuthorizedTargetService(model, "read", path, parentAuthorization);
9289
9738
  for (let y = 0; y < docs.length; y++) {
9290
9739
  const doc = docs[y];
9291
- const localValue = (0, import_utils25.get)(doc, localField);
9740
+ const localValue = (0, import_utils26.get)(doc, localField);
9292
9741
  const execution = this.relatedExecution(svc, include, parentAuthorization);
9293
9742
  const prepared = await prepareModelQuery(
9294
9743
  svc,
@@ -9323,15 +9772,15 @@ var Base = class {
9323
9772
  const { model, op, path, localField, foreignField, filter: _filters, args = {}, options = {} } = include;
9324
9773
  const svc = await this.getAuthorizedTargetService(model, op, path, parentAuthorization);
9325
9774
  const includeLocalValues = [];
9326
- (0, import_utils25.forEach)(docs, (doc) => {
9327
- includeLocalValues.push(...this.getForeignKeyValues((0, import_utils25.get)(doc, localField)));
9775
+ (0, import_utils26.forEach)(docs, (doc) => {
9776
+ includeLocalValues.push(...this.getForeignKeyValues((0, import_utils26.get)(doc, localField)));
9328
9777
  });
9329
9778
  const execution = this.relatedExecution(svc, include, parentAuthorization);
9330
9779
  const prepared = await prepareModelQuery(
9331
9780
  svc,
9332
9781
  execution,
9333
9782
  { kind: "client-read", filter: _filters ?? {} },
9334
- { [foreignField]: { $in: (0, import_utils25.flatten)(includeLocalValues) } },
9783
+ { [foreignField]: { $in: (0, import_utils26.flatten)(includeLocalValues) } },
9335
9784
  true
9336
9785
  );
9337
9786
  const trustedArgs = this.sanitizeIncludeArgs(args, "list");
@@ -9374,7 +9823,7 @@ var Base = class {
9374
9823
  }
9375
9824
  for (let y = 0; y < docs.length; y++) {
9376
9825
  const doc = docs[y];
9377
- const matches = this.getIndexedMatches(index, (0, import_utils25.get)(doc, localField));
9826
+ const matches = this.getIndexedMatches(index, (0, import_utils26.get)(doc, localField));
9378
9827
  const isolated = matches.map((m) => copyAuthorizedOutput(m));
9379
9828
  attachIncludeOutput(doc, path, op === "list" ? isolated : isolated[0]);
9380
9829
  }
@@ -9383,7 +9832,7 @@ var Base = class {
9383
9832
  async includeDocsCount(docs, include, parentAuthorization) {
9384
9833
  const { model, path, localField, foreignField, filter: _filters } = include;
9385
9834
  const svc = await this.getAuthorizedTargetService(model, "count", path, parentAuthorization);
9386
- const groups = prepareCountGroups(docs, (doc) => (0, import_utils25.get)(doc, localField));
9835
+ const groups = prepareCountGroups(docs, (doc) => (0, import_utils26.get)(doc, localField));
9387
9836
  const execution = this.relatedExecution(svc, include, parentAuthorization);
9388
9837
  const prepared = await prepareModelQuery(
9389
9838
  svc,
@@ -9437,7 +9886,7 @@ var Base = class {
9437
9886
  }
9438
9887
  const state = this.getCorrelatedExecState();
9439
9888
  docs = docs.map(prepareIncludeOutput);
9440
- const resolvedSnapshots = snapshots2 ?? docs.map((doc) => (0, import_utils25.cloneDeep)(toObject(getIncludeSource(doc))));
9889
+ const resolvedSnapshots = snapshots2 ?? docs.map((doc) => (0, import_utils26.cloneDeep)(toObject(getIncludeSource(doc))));
9441
9890
  for (const include of correlatedIncludes) {
9442
9891
  switch (include.op) {
9443
9892
  case "read":
@@ -9786,10 +10235,10 @@ var Base = class {
9786
10235
  }
9787
10236
  let ret = result2.data;
9788
10237
  if (sqOptions.path) {
9789
- ret = (0, import_utils25.isArray)(ret) ? (0, import_utils25.flatten)(ret.map((v) => (0, import_utils25.get)(v, sqOptions.path))) : (0, import_utils25.get)(ret, sqOptions.path);
10238
+ ret = (0, import_utils26.isArray)(ret) ? (0, import_utils26.flatten)(ret.map((v) => (0, import_utils26.get)(v, sqOptions.path))) : (0, import_utils26.get)(ret, sqOptions.path);
9790
10239
  }
9791
10240
  if (sqOptions.compact) {
9792
- ret = (0, import_utils25.compact)((0, import_utils25.castArray)(ret));
10241
+ ret = (0, import_utils26.compact)((0, import_utils26.castArray)(ret));
9793
10242
  }
9794
10243
  return ret;
9795
10244
  }
@@ -9804,96 +10253,6 @@ var Base = class {
9804
10253
  var import_utils36 = require("@web-ts-toolkit/utils");
9805
10254
  var import_just_diff = require("just-diff");
9806
10255
 
9807
- // src/model.ts
9808
- var import_utils26 = require("@web-ts-toolkit/utils");
9809
- init_runtime_context();
9810
- init_runtime();
9811
- function admitModelPersistence(adapter, scheduler) {
9812
- return {
9813
- modelName: adapter.modelName,
9814
- mongooseModel: adapter.mongooseModel,
9815
- new: () => adapter.new(),
9816
- // Mongoose create(array) otherwise starts all document saves at once. Keep
9817
- // the adapter's array input/output contract, with one permit per item; all
9818
- // items are submitted even if one rejects, as with unordered create(array).
9819
- create: (data) => Array.isArray(data) ? Promise.all(data.map((item) => scheduler.work(async () => (await adapter.create([item]))[0]))) : scheduler.work(() => adapter.create(data)),
9820
- find: (props) => scheduler.work(() => adapter.find(props)),
9821
- findOne: (props) => scheduler.work(() => adapter.findOne(props)),
9822
- exists: (filter2) => scheduler.work(() => adapter.exists(filter2)),
9823
- countDocuments: (filter2) => scheduler.work(() => adapter.countDocuments(filter2)),
9824
- distinct: (field, conditions) => scheduler.work(() => adapter.distinct(field, conditions)),
9825
- aggregate: (pipeline) => scheduler.work(() => adapter.aggregate(pipeline)),
9826
- // Casting builds no persistence work and must not acquire a recursive permit.
9827
- ...adapter.castFilter ? { castFilter: (filter2) => adapter.castFilter(filter2) } : {}
9828
- };
9829
- }
9830
- var Model = class {
9831
- constructor(modelName, runtime) {
9832
- this.modelName = modelName;
9833
- this.runtime = runtime ?? null;
9834
- const resolvedRuntime = runtime ?? getActiveRuntime() ?? defaultRuntime;
9835
- const registered = resolvedRuntime.getModelInstance(modelName);
9836
- if (!registered) {
9837
- throw new Error(
9838
- `Runtime model registry missing model "${modelName}". Pass a mongoose.Model instance to createRouter() or register it with registerModelInstance() before using this runtime.`
9839
- );
9840
- }
9841
- this.mongooseModel = registered;
9842
- if (!this.mongooseModel) return;
9843
- }
9844
- new() {
9845
- const doc = new this.mongooseModel();
9846
- return doc;
9847
- }
9848
- create(data) {
9849
- return this.mongooseModel.create(data);
9850
- }
9851
- find({ filter: filter2, select, sort, populate, limit, hardLimit, skip, lean }) {
9852
- const builder = this.mongooseModel.find(filter2);
9853
- if (select) builder.select(select);
9854
- if (skip) builder.skip(Number(skip));
9855
- const normalizedLimit = Number(limit);
9856
- if (Number.isSafeInteger(normalizedLimit) && normalizedLimit > 0) {
9857
- builder.limit(normalizedLimit);
9858
- } else if (Number.isSafeInteger(hardLimit) && Number(hardLimit) > 0) {
9859
- builder.limit(Number(hardLimit));
9860
- }
9861
- if (sort) builder.sort(sort);
9862
- if (populate) builder.populate(populate);
9863
- if (lean) builder.lean();
9864
- return builder;
9865
- }
9866
- findOne({ filter: filter2, select, sort, populate, lean }) {
9867
- const builder = this.mongooseModel.findOne(filter2);
9868
- if (select) builder.select(select);
9869
- if (sort) builder.sort(sort);
9870
- if (populate) builder.populate(populate);
9871
- if (lean) builder.lean();
9872
- return builder;
9873
- }
9874
- exists(filter2) {
9875
- if (!filter2) return null;
9876
- return this.findOne({ filter: filter2 }).select("_id").lean();
9877
- }
9878
- // see https://mongoosejs.com/docs/api.html#query_Query-countDocuments
9879
- countDocuments(filter2 = {}) {
9880
- return this.mongooseModel.countDocuments(filter2);
9881
- }
9882
- /** Cast a copy using this model's query schema/setters, without executing query middleware or persistence. */
9883
- castFilter(filter2) {
9884
- const query = this.mongooseModel.countDocuments((0, import_utils26.cloneDeep)(filter2));
9885
- return query.cast(this.mongooseModel);
9886
- }
9887
- // see https://mongoosejs.com/docs/api.html#model_Model.distinct
9888
- distinct(field, conditions = {}) {
9889
- return this.mongooseModel.distinct(field, conditions);
9890
- }
9891
- aggregate(pipeline) {
9892
- return this.mongooseModel.aggregate(pipeline);
9893
- }
9894
- };
9895
- var model_default = Model;
9896
-
9897
10256
  // src/acl/distinct-field-authorization.ts
9898
10257
  var import_utils27 = require("@web-ts-toolkit/utils");
9899
10258
  init_field_authorization();
@@ -10018,6 +10377,7 @@ init_document_authorization();
10018
10377
  init_output_field_filter();
10019
10378
  init_field_authorization();
10020
10379
  init_authorization_snapshot();
10380
+ init_unsafe_snapshot_options();
10021
10381
  init_public_admission();
10022
10382
 
10023
10383
  // src/acl/subdocument-output.ts
@@ -10030,6 +10390,7 @@ init_finalize_model_output();
10030
10390
  init_populate_target();
10031
10391
  init_virtual_populate_execution();
10032
10392
  init_request_work();
10393
+ init_populate_policy2();
10033
10394
  var populateExecutors = /* @__PURE__ */ new WeakMap();
10034
10395
  function registerSubdocumentPopulateExecutor(service, execute2, core) {
10035
10396
  populateExecutors.set(service, { execute: execute2, core });
@@ -10062,7 +10423,7 @@ function prepareSubdocumentOutput(service, sub, operation, virtualAccess, output
10062
10423
  service.getServiceModelName(),
10063
10424
  { populate },
10064
10425
  0,
10065
- configuration
10426
+ getCapturedPopulatePolicyDefaults(configuration)
10066
10427
  ),
10067
10428
  void 0,
10068
10429
  configuration,
@@ -11101,12 +11462,15 @@ var Service = class extends Base {
11101
11462
  model: this.model.mongooseModel,
11102
11463
  modelName: this.modelName
11103
11464
  }),
11104
- configuration: () => this.requestRuntime.getModelInstance(this.modelName) ? captureModelAuthorizationConfiguration(
11105
- this.requestRuntime,
11106
- this.modelName,
11107
- { ...this.options, defaults: this.defaults },
11108
- modelServiceGlobalOptions(this, this.requestRuntime)
11109
- ) : { catalog: { paths: [] }, ...this.options },
11465
+ configuration: () => {
11466
+ const populatePolicyDefaults = modelServicePopulatePolicyDefaults(this, this.requestRuntime);
11467
+ return this.requestRuntime.getModelInstance(this.modelName) ? captureModelAuthorizationConfiguration(
11468
+ this.requestRuntime,
11469
+ this.modelName,
11470
+ { ...this.options, defaults: this.defaults },
11471
+ populatePolicyDefaults
11472
+ ) : { catalog: { paths: [] }, ...this.options, populatePolicyDefaults };
11473
+ },
11110
11474
  permissions: () => this.requestCore.getPermissions?.() ?? new permission_default({}),
11111
11475
  parse: (filter2) => this.parseClientData(filter2, this.getCorrelatedExecState().scheduler),
11112
11476
  validate: (filter2, expanded) => {
@@ -11155,7 +11519,7 @@ var Service = class extends Base {
11155
11519
  });
11156
11520
  }
11157
11521
  get options() {
11158
- return modelServiceOptions(this, () => this.getModelRouterOptions(this.modelName));
11522
+ return modelServiceOptions(this, this.requestRuntime, () => this.getModelRouterOptions(this.modelName));
11159
11523
  }
11160
11524
  /**
11161
11525
  * Presentation/query defaults for this service instance; an explicit assignment
@@ -11209,7 +11573,7 @@ var Service = class extends Base {
11209
11573
  ["options", options]
11210
11574
  ]) {
11211
11575
  if (value !== null && (typeof value === "object" || typeof value === "function")) {
11212
- for (const key of ["unsafeSkipListDocumentSnapshotChecks", "unsafeSkipReadDocumentSnapshotChecks"]) {
11576
+ for (const key of unsafeSnapshotOptions) {
11213
11577
  if (key in value) authorizationError(`${slot}.${key} is server model configuration only`);
11214
11578
  }
11215
11579
  }
@@ -11640,14 +12004,14 @@ var Service = class extends Base {
11640
12004
  }
11641
12005
  });
11642
12006
  }
11643
- captureRelated(args, defaults) {
11644
- const globalOptions = modelServiceGlobalOptions(this, this.requestRuntime);
11645
- const effective = { populate: args?.populate ?? defaults?.populate, include: args?.include ?? defaults?.include };
12007
+ captureRelated(args, defaults2) {
12008
+ const populatePolicyDefaults = modelServicePopulatePolicyDefaults(this, this.requestRuntime);
12009
+ const effective = { populate: args?.populate ?? defaults2?.populate, include: args?.include ?? defaults2?.include };
11646
12010
  if (effective.include) {
11647
12011
  const processed = this.processInclude(effective.include);
11648
12012
  effective.include = [...processed.includes, ...processed.correlatedIncludes];
11649
12013
  }
11650
- return captureRelatedTargets(this.requestRuntime, this.modelName, effective, 0, globalOptions);
12014
+ return captureRelatedTargets(this.requestRuntime, this.modelName, effective, 0, populatePolicyDefaults);
11651
12015
  }
11652
12016
  /** Canonical population uses the target's retained policy for both fetch and output. */
11653
12017
  async genExecutionPopulate(execution, access, populate) {
@@ -11673,7 +12037,12 @@ var Service = class extends Base {
11673
12037
  const modelName = target?.modelName;
11674
12038
  if (!modelName) continue;
11675
12039
  const policy = relatedPolicy(state.authorization, state.binding, descriptor.path);
11676
- const svc = this.requestCore.getPublicService(modelName);
12040
+ const svc = withCapturedPopulateModel(
12041
+ this.requestRuntime,
12042
+ modelName,
12043
+ target.model,
12044
+ () => this.requestCore.getPublicService(modelName)
12045
+ );
11677
12046
  const child = createRelatedExecution(
11678
12047
  svc,
11679
12048
  {
@@ -11718,8 +12087,8 @@ var Service = class extends Base {
11718
12087
  snapshot: readServiceAuthorization(childState.authorization, childState.binding).configuration,
11719
12088
  fetchBinding: {
11720
12089
  runtime: this.requestRuntime,
11721
- model: childState.binding.model,
11722
- schema: childState.binding.model.schema,
12090
+ model: target.model,
12091
+ schema: target.model.schema,
11723
12092
  configuration: targetConfiguration,
11724
12093
  requestRead: targetAccess === "read" && policy?.operation.mode !== "grant" && readServiceAuthorization(childState.authorization, childState.binding).authorization.rows.mode === "request",
11725
12094
  staticObjectIdReference: captured.relatedTargets.find((target2) => target2.path === descriptor.path)?.staticObjectIdReference
@@ -14576,9 +14945,20 @@ var Core = class {
14576
14945
  if (!(0, import_utils40.isString)(p)) assertPopulateAccess(p.access);
14577
14946
  }
14578
14947
  const runtime = this.requestRuntime;
14579
- const globalOptions = modelServiceGlobalOptions(this, runtime);
14580
- const relatedTargets = captureRelatedTargets(runtime, modelName, { populate: descriptors }, 0, globalOptions);
14581
- const sourceConfiguration = captureModelAuthorizationConfiguration(runtime, modelName, void 0, globalOptions);
14948
+ const populatePolicyDefaults = modelServicePopulatePolicyDefaults(this, runtime);
14949
+ const relatedTargets = captureRelatedTargets(
14950
+ runtime,
14951
+ modelName,
14952
+ { populate: descriptors },
14953
+ 0,
14954
+ populatePolicyDefaults
14955
+ );
14956
+ const sourceConfiguration = captureModelAuthorizationConfiguration(
14957
+ runtime,
14958
+ modelName,
14959
+ void 0,
14960
+ populatePolicyDefaults
14961
+ );
14582
14962
  const originalPermissions = this.getGlobalPermissions();
14583
14963
  const permissions = new permission_default(
14584
14964
  Object.fromEntries(originalPermissions.keys.map((key) => [key, originalPermissions.has(key)]))
@@ -14675,7 +15055,15 @@ var Core = class {
14675
15055
  docPermissionsAccess: planAccess,
14676
15056
  requestedSelect: originalSelect,
14677
15057
  plan: targetPlan,
14678
- snapshot: targetSnapshot
15058
+ snapshot: targetSnapshot,
15059
+ fetchBinding: {
15060
+ runtime,
15061
+ model: target.model,
15062
+ schema: target.model.schema,
15063
+ configuration: targetConfiguration,
15064
+ requestRead: populateAccess === "read",
15065
+ staticObjectIdReference: target.staticObjectIdReference
15066
+ }
14679
15067
  });
14680
15068
  return ret;
14681
15069
  })