@web-ts-toolkit/access-router 0.61.0 → 0.63.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.mjs CHANGED
@@ -9,10 +9,10 @@ var __export = (target, all) => {
9
9
  };
10
10
 
11
11
  // src/acl/unsafe-snapshot-options.ts
12
- var unsafeSnapshotOptions;
12
+ var unsafeSnapshotCheckOptions, unsafeInitialOutputCopyOptions, unsafeSnapshotOptions;
13
13
  var init_unsafe_snapshot_options = __esm({
14
14
  "src/acl/unsafe-snapshot-options.ts"() {
15
- unsafeSnapshotOptions = [
15
+ unsafeSnapshotCheckOptions = [
16
16
  "unsafeSkipListDocumentSnapshotChecks",
17
17
  "unsafeSkipReadDocumentSnapshotChecks",
18
18
  "unsafeSkipListOutputSnapshotChecks",
@@ -20,6 +20,11 @@ var init_unsafe_snapshot_options = __esm({
20
20
  "unsafeSkipListNestedDocumentSnapshotChecks",
21
21
  "unsafeSkipReadNestedDocumentSnapshotChecks"
22
22
  ];
23
+ unsafeInitialOutputCopyOptions = [
24
+ "unsafeSkipListInitialOutputSnapshotCopy",
25
+ "unsafeSkipReadInitialOutputSnapshotCopy"
26
+ ];
27
+ unsafeSnapshotOptions = [...unsafeSnapshotCheckOptions, ...unsafeInitialOutputCopyOptions];
23
28
  }
24
29
  });
25
30
 
@@ -64,9 +69,9 @@ function assertPublicAdmission(input, kind = "envelope") {
64
69
  for (const key of ["filter", "match", "data"]) add(record3[key], "data", key);
65
70
  }
66
71
  }
67
- function assertHydrationDefaults(defaults) {
68
- if (defaults && typeof defaults === "object") {
69
- const record3 = defaults;
72
+ function assertHydrationDefaults(defaults2) {
73
+ if (defaults2 && typeof defaults2 === "object") {
74
+ const record3 = defaults2;
70
75
  if ("hydration" in record3)
71
76
  throw new TypeError("defaults.hydration is unsupported; use model hydration configuration");
72
77
  for (const bucket of [
@@ -94,11 +99,11 @@ function assertHydrationDefaults(defaults) {
94
99
  }
95
100
  }
96
101
  }
97
- function assertPublicDefaults(defaults) {
98
- assertHydrationDefaults(defaults);
99
- assertPublicAdmission(defaults);
100
- if (defaults && typeof defaults === "object") {
101
- for (const value of Object.values(defaults)) assertPublicAdmission(value);
102
+ function assertPublicDefaults(defaults2) {
103
+ assertHydrationDefaults(defaults2);
104
+ assertPublicAdmission(defaults2);
105
+ if (defaults2 && typeof defaults2 === "object") {
106
+ for (const value of Object.values(defaults2)) assertPublicAdmission(value);
102
107
  }
103
108
  }
104
109
  function pickPublicKeys(input, keys2) {
@@ -199,6 +204,37 @@ var init_hydration = __esm({
199
204
  }
200
205
  });
201
206
 
207
+ // src/options/populate-policy.ts
208
+ function isPopulatePolicyKey(key) {
209
+ return populatePolicyKeys.includes(key);
210
+ }
211
+ function normalizePopulatePolicyValue(value) {
212
+ return value === void 0 ? void 0 : value !== false;
213
+ }
214
+ function normalizePopulatePolicyOptions(options) {
215
+ const next = { ...options };
216
+ for (const key of populatePolicyKeys) {
217
+ if (key in options)
218
+ next[key] = normalizePopulatePolicyValue(options[key]);
219
+ }
220
+ return next;
221
+ }
222
+ function assertNoGlobalPopulatePolicy(key) {
223
+ if (isPopulatePolicyKey(key))
224
+ throw new TypeError(
225
+ `${key} is target-model configuration; migrate to setModelOptions(targetModelName, { ${key}: value }) or setDefaultModelOptions({ ${key}: value }) for runtime model defaults`
226
+ );
227
+ }
228
+ var populatePolicyKeys;
229
+ var init_populate_policy = __esm({
230
+ "src/options/populate-policy.ts"() {
231
+ populatePolicyKeys = [
232
+ "requireOperationAccessForPopulateQueries",
233
+ "requireOperationAccessForPopulateDependencies"
234
+ ];
235
+ }
236
+ });
237
+
202
238
  // src/helpers/collection.ts
203
239
  import sift from "sift";
204
240
  import { filter, find } from "@web-ts-toolkit/utils";
@@ -577,12 +613,9 @@ var init_document = __esm({
577
613
  const out = {};
578
614
  seen.set(value, out);
579
615
  for (const [key, entry] of Object.entries(value)) {
580
- Object.defineProperty(out, key, {
581
- value: deepIsolateValue(entry, seen, flattenMaps),
582
- enumerable: true,
583
- writable: true,
584
- configurable: true
585
- });
616
+ const copied = deepIsolateValue(entry, seen, flattenMaps);
617
+ if (Object.getPrototypeOf(out) === Object.prototype && !(key in out)) out[key] = copied;
618
+ else Object.defineProperty(out, key, { value: copied, enumerable: true, writable: true, configurable: true });
586
619
  }
587
620
  copyPermissionsAlias(value, out);
588
621
  return out;
@@ -1315,7 +1348,7 @@ var init_logger_default = __esm({
1315
1348
 
1316
1349
  // src/options/manager.ts
1317
1350
  import { assign, get as get3, isPlainObject as isPlainObject9, set as set2 } from "@web-ts-toolkit/utils";
1318
- var toPath, cloneConfigValue, cloneForRead, freezeConfigValue, cloneAndFreezeForStore, getNestedOption, resolveNestedOption, OptionsManager;
1351
+ var toPath, cloneConfigValue, cloneForRead, freezeConfigValue, cloneAndFreezeForStore, cloneOptionsSnapshot, getNestedOption, resolveNestedOption, OptionsManager;
1319
1352
  var init_manager = __esm({
1320
1353
  "src/options/manager.ts"() {
1321
1354
  toPath = (key) => {
@@ -1378,6 +1411,7 @@ var init_manager = __esm({
1378
1411
  return value;
1379
1412
  };
1380
1413
  cloneAndFreezeForStore = (value) => freezeConfigValue(cloneForRead(value));
1414
+ cloneOptionsSnapshot = (value) => freezeConfigValue(cloneForRead(value));
1381
1415
  getNestedOption = (manager, key, defaultValue) => resolveNestedOption((path, fallback) => manager.get(path, fallback), String(key), defaultValue);
1382
1416
  resolveNestedOption = (read, key, defaultValue) => {
1383
1417
  const keys2 = key.split(".");
@@ -1886,7 +1920,8 @@ var init_virtual_descriptor = __esm({
1886
1920
  });
1887
1921
 
1888
1922
  // src/acl/authorization-snapshot.ts
1889
- import { isDeepStrictEqual } from "util";
1923
+ import { isDeepStrictEqual, types as types2 } from "util";
1924
+ import { Buffer as NodeBuffer } from "buffer";
1890
1925
  import { mongo as mongo2 } from "mongoose";
1891
1926
  import JsonRouter3 from "@web-ts-toolkit/express-json-router";
1892
1927
  function authorizationError(detail) {
@@ -1937,6 +1972,7 @@ function copyAuthorizationValue(value, configuration = false) {
1937
1972
  if (array && input.length > 2e4) authorizationError("snapshot array exceeds structural limits");
1938
1973
  if (!array) authorizationRecord(input, "snapshot");
1939
1974
  const result2 = array ? [] : {};
1975
+ let definedProperty = false;
1940
1976
  for (const key of Reflect.ownKeys(input)) {
1941
1977
  if (array && key === "length") continue;
1942
1978
  if (typeof key !== "string" || unsafeKeys.has(key)) authorizationError("unsafe snapshot key");
@@ -1944,12 +1980,16 @@ function copyAuthorizationValue(value, configuration = false) {
1944
1980
  const descriptor = Object.getOwnPropertyDescriptor(input, key);
1945
1981
  if (!("value" in descriptor) || !descriptor.enumerable && configuration !== "document")
1946
1982
  authorizationError("accessor/non-enumerable input");
1947
- Object.defineProperty(result2, key, {
1948
- value: copy(descriptor.value, depth + 1),
1949
- enumerable: true,
1950
- writable: true,
1951
- configurable: true
1952
- });
1983
+ const value2 = copy(descriptor.value, depth + 1);
1984
+ if (array || definedProperty && Object.getPrototypeOf(result2) !== Object.prototype || key in result2) {
1985
+ definedProperty = true;
1986
+ Object.defineProperty(result2, key, {
1987
+ value: value2,
1988
+ enumerable: true,
1989
+ writable: true,
1990
+ configurable: true
1991
+ });
1992
+ } else result2[key] = value2;
1953
1993
  }
1954
1994
  if (array) result2.length = input.length;
1955
1995
  return Object.freeze(result2);
@@ -1989,6 +2029,71 @@ function outputIdentities(value) {
1989
2029
  visit(value);
1990
2030
  return Object.freeze(result2);
1991
2031
  }
2032
+ function tryOutputIdentitiesWithoutSnapshot(value) {
2033
+ const identities = [];
2034
+ const seen = /* @__PURE__ */ new WeakSet();
2035
+ const active = /* @__PURE__ */ new WeakSet();
2036
+ const fallback = {};
2037
+ let nodes = 0;
2038
+ function visit(input, depth) {
2039
+ if (++nodes > 2e4 || depth > 100) authorizationError("snapshot exceeds structural limits");
2040
+ if (typeof input === "function") authorizationError("functions are not policy values");
2041
+ if (typeof input === "symbol") authorizationError("symbols are not policy values");
2042
+ if (input === null || typeof input !== "object") return;
2043
+ if (types2.isProxy(input)) throw fallback;
2044
+ if (active.has(input)) authorizationError("cyclic input");
2045
+ if (!seen.has(input)) {
2046
+ seen.add(input);
2047
+ identities.push(input);
2048
+ }
2049
+ const prototype = Object.getPrototypeOf(input);
2050
+ if (types2.isDate(input)) {
2051
+ if (prototype === Date.prototype) return;
2052
+ throw fallback;
2053
+ }
2054
+ if (types2.isRegExp(input)) {
2055
+ if (prototype === RegExp.prototype) return;
2056
+ throw fallback;
2057
+ }
2058
+ if (types2.isUint8Array(input)) {
2059
+ if (prototype === NodeBuffer.prototype) return;
2060
+ throw fallback;
2061
+ }
2062
+ if (types2.isMap(input) || types2.isSet(input)) throw fallback;
2063
+ const array = Array.isArray(input);
2064
+ if (!array) {
2065
+ if (prototype !== Object.prototype && prototype !== null) {
2066
+ let parent = prototype;
2067
+ for (let count = 0; parent && count < 100; count++) {
2068
+ if (types2.isProxy(parent)) throw fallback;
2069
+ if (parent === mongo2.BSON.BSONValue.prototype) return;
2070
+ parent = Object.getPrototypeOf(parent);
2071
+ }
2072
+ throw fallback;
2073
+ }
2074
+ } else if (input.length > 2e4) authorizationError("snapshot array exceeds structural limits");
2075
+ active.add(input);
2076
+ try {
2077
+ for (const key of Reflect.ownKeys(input)) {
2078
+ if (array && key === "length") continue;
2079
+ if (typeof key !== "string" || unsafeKeys.has(key)) authorizationError("unsafe snapshot key");
2080
+ if (array && !/^(0|[1-9]\d*)$/.test(key)) authorizationError("invalid array property");
2081
+ const descriptor = Object.getOwnPropertyDescriptor(input, key);
2082
+ if (!("value" in descriptor)) authorizationError("accessor/non-enumerable input");
2083
+ visit(descriptor.value, depth + 1);
2084
+ }
2085
+ } finally {
2086
+ active.delete(input);
2087
+ }
2088
+ }
2089
+ try {
2090
+ visit(value, 0);
2091
+ return Object.freeze(identities);
2092
+ } catch (error2) {
2093
+ if (error2 !== fallback) throw error2;
2094
+ return void 0;
2095
+ }
2096
+ }
1992
2097
  var ServiceAuthorizationError, unsafeKeys;
1993
2098
  var init_authorization_snapshot = __esm({
1994
2099
  "src/acl/authorization-snapshot.ts"() {
@@ -2004,6 +2109,30 @@ var init_authorization_snapshot = __esm({
2004
2109
  });
2005
2110
 
2006
2111
  // src/acl/field-catalog.ts
2112
+ import { types as types3 } from "util";
2113
+ function prepareCapturedOutputCatalog(catalog) {
2114
+ preparedOutputCatalogs.set(catalog, 0);
2115
+ }
2116
+ function prepareOutputCatalog(catalog) {
2117
+ if (types3.isProxy(catalog) || Object.getPrototypeOf(catalog) !== Object.prototype || !Object.isFrozen(catalog))
2118
+ return false;
2119
+ const paths = /* @__PURE__ */ new Set();
2120
+ for (const key of ["paths", "protectedPaths", "referencePaths", "virtualPaths", "dynamicPaths", "opaquePaths"]) {
2121
+ const slot = Object.getOwnPropertyDescriptor(catalog, key);
2122
+ if (!slot || !("value" in slot)) return false;
2123
+ const entries = slot.value;
2124
+ if (!Array.isArray(entries) || types3.isProxy(entries) || Object.getPrototypeOf(entries) !== Array.prototype || !Object.isFrozen(entries))
2125
+ return false;
2126
+ const length = Object.getOwnPropertyDescriptor(entries, "length").value;
2127
+ if (length > 2e4 || Reflect.ownKeys(entries).length !== length + 1) return false;
2128
+ for (let index = 0; index < length; index++) {
2129
+ const entry = Object.getOwnPropertyDescriptor(entries, String(index));
2130
+ if (!entry || !("value" in entry) || typeof entry.value !== "string") return false;
2131
+ if (key === "paths") paths.add(entry.value);
2132
+ }
2133
+ }
2134
+ return { paths, results: /* @__PURE__ */ new Map() };
2135
+ }
2007
2136
  function isSafeInputPath(path, requestIdentity = false) {
2008
2137
  return isSafeOutputPath(path) && path.split(".").every((part) => !inputControlSegments.has(part) && (requestIdentity || part !== "_id"));
2009
2138
  }
@@ -2026,18 +2155,35 @@ function isInputVirtualPath(catalog, path) {
2026
2155
  return false;
2027
2156
  }
2028
2157
  function matchesCatalogPattern(pattern, path, descendants = false) {
2158
+ if (typeof pattern === "string" && typeof path === "string" && !pattern.includes("$*")) {
2159
+ return pattern === path || !!descendants && path.startsWith(pattern) && path[pattern.length] === ".";
2160
+ }
2029
2161
  const expected = pattern.split(".");
2030
2162
  const actual = path.split(".");
2031
2163
  return (descendants ? actual.length >= expected.length : actual.length === expected.length) && expected.every((part, index) => part === "$*" || part === actual[index]);
2032
2164
  }
2033
2165
  function isCatalogOutputPath(catalog, path) {
2166
+ let prepared = typeof path === "string" ? preparedOutputCatalogs.get(catalog) : void 0;
2167
+ if (typeof prepared === "number") {
2168
+ const lookups = prepared + 1;
2169
+ prepared = lookups < 32 ? lookups : prepareOutputCatalog(catalog);
2170
+ preparedOutputCatalogs.set(catalog, prepared);
2171
+ if (typeof prepared === "number") return catalogOutputPath(catalog, path);
2172
+ }
2173
+ const cached = prepared ? prepared.results.get(path) : void 0;
2174
+ if (cached !== void 0) return cached;
2175
+ const allowed = catalogOutputPath(catalog, path, prepared ? prepared.paths : void 0);
2176
+ if (prepared && prepared.results.size < 2e4) prepared.results.set(path, allowed);
2177
+ return allowed;
2178
+ }
2179
+ function catalogOutputPath(catalog, path, paths) {
2034
2180
  if (!isSafeOutputPath(path)) return false;
2035
2181
  if (catalog.protectedPaths?.some((p) => matchesCatalogPattern(p, path, true))) return false;
2036
2182
  if (catalog.referencePaths?.some((p) => matchesCatalogPattern(p, path, true) && !matchesCatalogPattern(p, path)))
2037
2183
  return false;
2038
2184
  if (catalog.virtualPaths?.some((p) => matchesCatalogPattern(p, path, true) && !matchesCatalogPattern(p, path)))
2039
2185
  return false;
2040
- return catalog.paths.includes(path) || !!catalog.dynamicPaths?.some((p) => matchesCatalogPattern(p, path)) || !!catalog.opaquePaths?.some((p) => matchesCatalogPattern(p, path, true));
2186
+ return (paths ? paths.has(path) : catalog.paths.includes(path)) || !!catalog.dynamicPaths?.some((p) => matchesCatalogPattern(p, path)) || !!catalog.opaquePaths?.some((p) => matchesCatalogPattern(p, path, true));
2041
2187
  }
2042
2188
  function captureAuthorizationFieldCatalog(schema, virtuals, documentPermissionField = "_permissions") {
2043
2189
  const paths = /* @__PURE__ */ new Set();
@@ -2132,9 +2278,10 @@ function captureAuthorizationFieldCatalog(schema, virtuals, documentPermissionFi
2132
2278
  protectedPaths: Object.freeze([...protectedPaths])
2133
2279
  });
2134
2280
  }
2135
- var safeSegment, isSafeOutputPath, inputControlSegments;
2281
+ var preparedOutputCatalogs, safeSegment, isSafeOutputPath, inputControlSegments;
2136
2282
  var init_field_catalog = __esm({
2137
2283
  "src/acl/field-catalog.ts"() {
2284
+ preparedOutputCatalogs = /* @__PURE__ */ new WeakMap();
2138
2285
  safeSegment = (part) => !!part && part !== "sub" && !["__proto__", "constructor", "prototype", "_doc", "__v"].includes(part) && !/^[+$-]|[\s*]/.test(part) && !part.includes("[") && !part.includes("]") && !/^\d+$/.test(part) && ![...part].some((character) => character.charCodeAt(0) < 32 || character.charCodeAt(0) === 127);
2139
2286
  isSafeOutputPath = (path) => path.split(".").every(safeSegment);
2140
2287
  inputControlSegments = /* @__PURE__ */ new Set([
@@ -2158,9 +2305,46 @@ var init_field_catalog = __esm({
2158
2305
  }
2159
2306
  });
2160
2307
 
2308
+ // src/runtime-context.ts
2309
+ import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
2310
+ function runWithRuntime(runtime, callback) {
2311
+ return runtimeStorage.run(runtime, callback);
2312
+ }
2313
+ function getActiveRuntime() {
2314
+ return runtimeStorage.getStore() ?? null;
2315
+ }
2316
+ var runtimeStorage;
2317
+ var init_runtime_context = __esm({
2318
+ "src/runtime-context.ts"() {
2319
+ runtimeStorage = new AsyncLocalStorage2();
2320
+ }
2321
+ });
2322
+
2323
+ // src/meta.ts
2324
+ var getRuntime, getModelReference;
2325
+ var init_meta = __esm({
2326
+ "src/meta.ts"() {
2327
+ init_runtime();
2328
+ init_runtime_context();
2329
+ getRuntime = () => getActiveRuntime() ?? defaultRuntime;
2330
+ getModelReference = (modelName, refPath, runtime = getRuntime()) => {
2331
+ const instance = runtime.getModelInstance(modelName);
2332
+ let type = instance?.schema.path(refPath);
2333
+ const result2 = {};
2334
+ while (type) {
2335
+ result2.ref ??= type.options?.ref;
2336
+ result2.refPath ??= type.options?.refPath;
2337
+ if (type.instance !== "Array") break;
2338
+ type = type.$embeddedSchemaType ?? type.embeddedSchemaType ?? type.caster;
2339
+ }
2340
+ return result2;
2341
+ };
2342
+ }
2343
+ });
2344
+
2161
2345
  // src/acl/populate-target-configuration.ts
2162
2346
  import { isPlainObject as isPlainObject12 } from "@web-ts-toolkit/utils";
2163
- function capturePopulateTargetConfiguration(runtime, modelName, source, proposedOptions) {
2347
+ function capturePopulateTargetConfiguration(runtime, modelName, source, proposedOptions, defaults2 = runtime.getDefaultModelOptions()) {
2164
2348
  const label = `Populate target "${modelName}" for ${source}`;
2165
2349
  if (!proposedOptions && !runtime.hasModel(modelName))
2166
2350
  authorizationError(
@@ -2169,16 +2353,75 @@ function capturePopulateTargetConfiguration(runtime, modelName, source, proposed
2169
2353
  const model = runtime.getModelInstance(modelName);
2170
2354
  if (!model) authorizationError(`${label} requires an actual registered Mongoose model in this runtime`);
2171
2355
  const options = proposedOptions ?? runtime.getModelOptions(modelName);
2172
- const permissionSchema = options.permissionSchema === void 0 ? runtime.getDefaultModelOption("permissionSchema") : options.permissionSchema;
2356
+ const permissionSchema = options.permissionSchema === void 0 ? defaults2.permissionSchema : options.permissionSchema;
2173
2357
  if (!isPlainObject12(permissionSchema))
2174
2358
  authorizationError(
2175
2359
  `${label} requires an effective object permissionSchema; configure the model or runtime model defaults ({} explicitly closes business fields)`
2176
2360
  );
2177
2361
  return { model, options: { ...options, permissionSchema } };
2178
2362
  }
2363
+ function capturePopulateTargetBinding(runtime, sourceModelName, path) {
2364
+ const { ref, refPath } = getModelReference(sourceModelName, path, runtime);
2365
+ if (refPath !== void 0 || typeof ref === "function" && !("modelName" in ref))
2366
+ authorizationError(
2367
+ `Populate target for ${sourceModelName}.${path} requires a static string or Mongoose Model-valued source ref; dynamic refs/refPath cannot be bound before I/O`
2368
+ );
2369
+ const modelName = typeof ref === "string" ? ref : ref?.modelName;
2370
+ if (!modelName) return void 0;
2371
+ const target = capturePopulateTargetConfiguration(runtime, modelName, `${sourceModelName}.${path}`);
2372
+ const source = runtime.getModelInstance(sourceModelName);
2373
+ const actual = typeof ref === "string" ? source?.db.models[ref] : ref;
2374
+ if (!actual)
2375
+ authorizationError(
2376
+ `Populate target "${modelName}" for ${sourceModelName}.${path} is missing on the source connection; configure the actual model bound to the source ref in this runtime`
2377
+ );
2378
+ if (actual !== target.model)
2379
+ authorizationError(
2380
+ `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`
2381
+ );
2382
+ return { ...target, modelName };
2383
+ }
2179
2384
  var init_populate_target_configuration = __esm({
2180
2385
  "src/acl/populate-target-configuration.ts"() {
2181
2386
  init_authorization_snapshot();
2387
+ init_meta();
2388
+ }
2389
+ });
2390
+
2391
+ // src/acl/populate-policy.ts
2392
+ function capturePopulatePolicyDefaults(runtime) {
2393
+ const options = runtime.getDefaultModelOptions();
2394
+ const token = () => {
2395
+ };
2396
+ defaults.set(
2397
+ token,
2398
+ Object.freeze({
2399
+ requireOperationAccessForPopulateQueries: options.requireOperationAccessForPopulateQueries !== false,
2400
+ requireOperationAccessForPopulateDependencies: options.requireOperationAccessForPopulateDependencies !== false
2401
+ })
2402
+ );
2403
+ return token;
2404
+ }
2405
+ function resolvePopulatePolicy(options, token) {
2406
+ const captured = defaults.get(token);
2407
+ if (!captured) return authorizationError("invalid captured populate model defaults");
2408
+ const resolve = (key) => (options[key] === void 0 ? captured[key] : options[key]) !== false;
2409
+ return Object.freeze({
2410
+ requireOperationAccessForPopulateQueries: resolve(populatePolicyKeys[0]),
2411
+ requireOperationAccessForPopulateDependencies: resolve(populatePolicyKeys[1])
2412
+ });
2413
+ }
2414
+ function getCapturedPopulatePolicyDefaults(configuration) {
2415
+ const token = configuration.populatePolicyDefaults;
2416
+ if (!token || !defaults.has(token)) return authorizationError("missing captured populate model defaults");
2417
+ return token;
2418
+ }
2419
+ var defaults;
2420
+ var init_populate_policy2 = __esm({
2421
+ "src/acl/populate-policy.ts"() {
2422
+ init_populate_policy();
2423
+ init_authorization_snapshot();
2424
+ defaults = /* @__PURE__ */ new WeakMap();
2182
2425
  }
2183
2426
  });
2184
2427
 
@@ -2273,9 +2516,7 @@ function normalizeSelection(select, catalog, label) {
2273
2516
  includeId: selection.includes("_id")
2274
2517
  };
2275
2518
  }
2276
- function captureVirtualPopulateDependencies(runtime, modelName, options, globalOptions = runtime.getGlobalOptions()) {
2277
- const requireOperationAccessForPopulateDependencies = globalOptions.requireOperationAccessForPopulateDependencies !== false;
2278
- const requireOperationAccessForPopulateQueries = globalOptions.requireOperationAccessForPopulateQueries !== false;
2519
+ function captureVirtualPopulateDependencies(runtime, modelName, options, populatePolicyDefaults = capturePopulatePolicyDefaults(runtime), proposed) {
2279
2520
  const model = runtime.getModelInstance(modelName);
2280
2521
  const targets = /* @__PURE__ */ new Map();
2281
2522
  const scopes = [];
@@ -2319,18 +2560,19 @@ function captureVirtualPopulateDependencies(runtime, modelName, options, globalO
2319
2560
  runtime,
2320
2561
  ref,
2321
2562
  `dependsOnPopulate virtual "${label}"`,
2322
- ref === modelName ? options : void 0
2563
+ ref === modelName ? options : proposed?.models.get(ref),
2564
+ proposed?.defaults
2323
2565
  );
2324
- const defaults = runtime.getDefaultModelOptions();
2325
- const readOption = (key) => resolveNestedOption((path2, fallback) => get4(targetOptions, path2, fallback), key, get4(defaults, key));
2326
- const documentPermissionField = targetOptions.documentPermissionField ?? defaults.documentPermissionField;
2566
+ const defaults2 = proposed?.defaults ?? runtime.getDefaultModelOptions();
2567
+ const readOption = (key) => resolveNestedOption((path2, fallback) => get4(targetOptions, path2, fallback), key, get4(defaults2, key));
2568
+ const documentPermissionField = targetOptions.documentPermissionField ?? defaults2.documentPermissionField;
2327
2569
  const catalog = captureAuthorizationFieldCatalog(targetModel.schema, void 0, documentPermissionField);
2328
2570
  const configuration = copyAuthorizationValue(
2329
2571
  {
2330
2572
  catalog,
2331
2573
  documentPermissionField,
2332
- requireOperationAccessForPopulateDependencies,
2333
- requireOperationAccessForPopulateQueries,
2574
+ populatePolicyDefaults,
2575
+ ...resolvePopulatePolicy(targetOptions, populatePolicyDefaults),
2334
2576
  permissionSchema: targetOptions.permissionSchema,
2335
2577
  operationAccess: { read: readOption("operationAccess.read") },
2336
2578
  baseFilter: { read: readOption("baseFilter.read") },
@@ -2411,8 +2653,8 @@ function captureVirtualPopulateDependencies(runtime, modelName, options, globalO
2411
2653
  visit(options.virtuals ?? {}, model?.schema, "", [], !!model && varyingModel(model));
2412
2654
  return Object.freeze({ scopes: Object.freeze(scopes) });
2413
2655
  }
2414
- function captureVirtualPopulateSnapshot(runtime, modelName, options, globalOptions = runtime.getGlobalOptions()) {
2415
- const snapshot = captureVirtualPopulateDependencies(runtime, modelName, options, globalOptions);
2656
+ function captureVirtualPopulateSnapshot(runtime, modelName, options, populatePolicyDefaults = capturePopulatePolicyDefaults(runtime)) {
2657
+ const snapshot = captureVirtualPopulateDependencies(runtime, modelName, options, populatePolicyDefaults);
2416
2658
  const token = () => {
2417
2659
  };
2418
2660
  snapshots.set(token, snapshot);
@@ -2445,6 +2687,7 @@ var init_virtual_populate_dependencies = __esm({
2445
2687
  init_field_catalog();
2446
2688
  init_virtual_descriptor();
2447
2689
  init_populate_target_configuration();
2690
+ init_populate_policy2();
2448
2691
  elementType = (type) => type.$embeddedSchemaType ?? type.embeddedSchemaType ?? type.caster;
2449
2692
  join = (prefix, path) => prefix ? `${prefix}.${path}` : path;
2450
2693
  within = (path, parent) => path === parent || path.startsWith(`${parent}.`);
@@ -2475,11 +2718,12 @@ import {
2475
2718
  normalizeUrlPath,
2476
2719
  set as set4
2477
2720
  } from "@web-ts-toolkit/utils";
2478
- var mongooseJsonSchemaInitialized, ensureMongooseJsonSchemaInitialized, pluralize, FIELD_ACCESS_KEYS, defaultModelOptions, defaultDataOptions, normalizeBasePath, hasModelPermission, classifyPermissionSchema, refreshPermissionMetadata, VIRTUAL_SUPPORTED_ACCESSES, VIRTUAL_UNSUPPORTED_ACCESSES, VIRTUAL_RESERVED_NAMES, VIRTUAL_DANGEROUS_SEGMENTS, VIRTUAL_NAME_PATTERN, isVirtualContainerValue2, virtualFullPath, virtualPathsOverlap, collectStoredTopLevel, getChildSchemaForField, getNestedChildFields, cloneVirtualsForValidation, validateVirtualDependsOn, validateVirtualLeafValue, validateVirtualsScope, validateVirtualsTree, AccessRuntime, defaultRuntime;
2721
+ var mongooseJsonSchemaInitialized, ensureMongooseJsonSchemaInitialized, pluralize, FIELD_ACCESS_KEYS, defaultModelOptions, modelOverrides, defaultDataOptions, normalizeBasePath, hasModelPermission, classifyPermissionSchema, refreshPermissionMetadata, VIRTUAL_SUPPORTED_ACCESSES, VIRTUAL_UNSUPPORTED_ACCESSES, VIRTUAL_RESERVED_NAMES, VIRTUAL_DANGEROUS_SEGMENTS, VIRTUAL_NAME_PATTERN, isVirtualContainerValue2, virtualFullPath, virtualPathsOverlap, collectStoredTopLevel, getChildSchemaForField, getNestedChildFields, cloneModelOptionForUpdate, validateVirtualDependsOn, validateVirtualLeafValue, validateVirtualsScope, validateVirtualsTree, AccessRuntime, defaultRuntime;
2479
2722
  var init_runtime = __esm({
2480
2723
  "src/runtime.ts"() {
2481
2724
  init_public_admission();
2482
2725
  init_hydration();
2726
+ init_populate_policy();
2483
2727
  init_helpers();
2484
2728
  init_registry();
2485
2729
  init_logger_default();
@@ -2489,6 +2733,7 @@ var init_runtime = __esm({
2489
2733
  init_request_complexity();
2490
2734
  init_virtual_descriptor();
2491
2735
  init_virtual_populate_dependencies();
2736
+ init_unsafe_snapshot_options();
2492
2737
  mongooseJsonSchemaInitialized = false;
2493
2738
  ensureMongooseJsonSchemaInitialized = () => {
2494
2739
  if (mongooseJsonSchemaInitialized) return;
@@ -2501,6 +2746,15 @@ var init_runtime = __esm({
2501
2746
  basePath: null,
2502
2747
  alwaysSelectFields: []
2503
2748
  };
2749
+ modelOverrides = (options) => {
2750
+ const result2 = Object.fromEntries(
2751
+ Object.entries(options).filter(
2752
+ ([key, value]) => value !== void 0 || key === "operationAccess" || isPopulatePolicyKey(key)
2753
+ )
2754
+ );
2755
+ for (const key of unsafeSnapshotOptions) if (key in result2) result2[key] = result2[key] === true;
2756
+ return cloneOptionsSnapshot(result2);
2757
+ };
2504
2758
  defaultDataOptions = {
2505
2759
  basePath: null,
2506
2760
  parentPath: "/",
@@ -2634,12 +2888,12 @@ var init_runtime = __esm({
2634
2888
  }
2635
2889
  return fields;
2636
2890
  };
2637
- cloneVirtualsForValidation = (value) => {
2638
- if (Array.isArray(value)) return value.map((item) => cloneVirtualsForValidation(item));
2891
+ cloneModelOptionForUpdate = (value) => {
2892
+ if (Array.isArray(value)) return value.map((item) => cloneModelOptionForUpdate(item));
2639
2893
  if (!value || typeof value !== "object") return value;
2640
2894
  if (Object.getPrototypeOf(value) !== Object.prototype) return value;
2641
2895
  return Object.fromEntries(
2642
- Object.entries(value).map(([k, v]) => [k, cloneVirtualsForValidation(v)])
2896
+ Object.entries(value).map(([k, v]) => [k, cloneModelOptionForUpdate(v)])
2643
2897
  );
2644
2898
  };
2645
2899
  validateVirtualDependsOn = (dependsOn, entryLabel, storedFields, siblingVirtualNames) => {
@@ -2835,8 +3089,6 @@ var init_runtime = __esm({
2835
3089
  {
2836
3090
  requestPermissionField: "_permissions",
2837
3091
  globalPermissions: () => ({}),
2838
- requireOperationAccessForPopulateQueries: true,
2839
- requireOperationAccessForPopulateDependencies: true,
2840
3092
  logger: defaultLogger,
2841
3093
  requestComplexity: defaultRequestComplexity
2842
3094
  },
@@ -2851,15 +3103,20 @@ var init_runtime = __esm({
2851
3103
  queryRouteSegment: "__query",
2852
3104
  mutationRouteSegment: "__mutation",
2853
3105
  operationAccess: false,
3106
+ requireOperationAccessForPopulateQueries: true,
3107
+ requireOperationAccessForPopulateDependencies: true,
2854
3108
  modelPermissionPrefix: "",
2855
3109
  unsafeSkipListDocumentSnapshotChecks: false,
2856
3110
  unsafeSkipReadDocumentSnapshotChecks: false,
2857
3111
  unsafeSkipListOutputSnapshotChecks: false,
2858
3112
  unsafeSkipReadOutputSnapshotChecks: false,
2859
3113
  unsafeSkipListNestedDocumentSnapshotChecks: false,
2860
- unsafeSkipReadNestedDocumentSnapshotChecks: false
3114
+ unsafeSkipReadNestedDocumentSnapshotChecks: false,
3115
+ unsafeSkipListInitialOutputSnapshotCopy: false,
3116
+ unsafeSkipReadInitialOutputSnapshotCopy: false
2861
3117
  }).build();
2862
3118
  this.modelOptions = {};
3119
+ this.modelOptionOverrides = {};
2863
3120
  this.modelJsonSchemas = {};
2864
3121
  this.dataOptions = {};
2865
3122
  this.modelRefs = {};
@@ -2947,6 +3204,7 @@ var init_runtime = __esm({
2947
3204
  globalOptions: this.globalOptions.snapshot(),
2948
3205
  defaultModelOptions: this.defaultModelOptions.snapshot(),
2949
3206
  modelOptions: modelOptionsSnap,
3207
+ modelOptionOverrides: { ...this.modelOptionOverrides },
2950
3208
  dataOptions: dataOptionsSnap,
2951
3209
  modelInstances: { ...this.modelInstances },
2952
3210
  modelJsonSchemas: { ...this.modelJsonSchemas },
@@ -2961,6 +3219,10 @@ var init_runtime = __esm({
2961
3219
  restoreBootstrapSnapshot(snapshot) {
2962
3220
  this.globalOptions.restore(snapshot.globalOptions);
2963
3221
  this.defaultModelOptions.restore(snapshot.defaultModelOptions);
3222
+ for (const name of Object.keys(this.modelOptionOverrides)) delete this.modelOptionOverrides[name];
3223
+ for (const [name, options] of Object.entries(snapshot.modelOptionOverrides)) {
3224
+ this.modelOptionOverrides[name] = modelOverrides(options);
3225
+ }
2964
3226
  for (const name of Object.keys(this.modelOptions)) {
2965
3227
  if (!(name in snapshot.modelOptions)) {
2966
3228
  delete this.modelOptions[name];
@@ -2971,8 +3233,7 @@ var init_runtime = __esm({
2971
3233
  if (existing) {
2972
3234
  existing.restore(opts);
2973
3235
  } else {
2974
- const mgr = this.createModelOptions(name);
2975
- mgr.restore(opts);
3236
+ const mgr = this.createModelOptions(name, opts);
2976
3237
  this.modelOptions[name] = mgr;
2977
3238
  }
2978
3239
  }
@@ -3015,18 +3276,11 @@ var init_runtime = __esm({
3015
3276
  }
3016
3277
  /** Shallowly replace supplied global values; nested objects such as requestComplexity are not deep-merged. */
3017
3278
  setGlobalOptions(options) {
3018
- const next = { ...options };
3019
- if ("requireOperationAccessForPopulateQueries" in next)
3020
- next.requireOperationAccessForPopulateQueries = next.requireOperationAccessForPopulateQueries !== false;
3021
- if ("requireOperationAccessForPopulateDependencies" in next)
3022
- next.requireOperationAccessForPopulateDependencies = next.requireOperationAccessForPopulateDependencies !== false;
3023
- this.globalOptions.assign(next);
3279
+ for (const key of populatePolicyKeys) if (key in options) assertNoGlobalPopulatePolicy(key);
3280
+ this.globalOptions.assign({ ...options });
3024
3281
  }
3025
3282
  setGlobalOption(key, value) {
3026
- if (key === "requireOperationAccessForPopulateQueries" || key === "requireOperationAccessForPopulateDependencies") {
3027
- this.globalOptions.set(key, value !== false);
3028
- return;
3029
- }
3283
+ assertNoGlobalPopulatePolicy(String(key));
3030
3284
  this.globalOptions.set(key, value);
3031
3285
  }
3032
3286
  getGlobalOptions() {
@@ -3035,28 +3289,30 @@ var init_runtime = __esm({
3035
3289
  getGlobalOption(key, defaultValue) {
3036
3290
  return this.globalOptions.get(key, defaultValue);
3037
3291
  }
3038
- /** Update model starting defaults shallowly; already-stored model values are not broadcast-replaced. */
3292
+ /** Update inherited model defaults shallowly. Explicit model values and captured calls are unchanged. */
3039
3293
  setDefaultModelOptions(options) {
3040
3294
  assertPublicDefaults(options.defaults);
3041
3295
  if ("hydration" in options) options = { ...options, hydration: normalizeHydration(options.hydration) };
3042
- this.defaultModelOptions.assign(options);
3296
+ const draft = new OptionsManager(
3297
+ this.getDefaultModelOptions()
3298
+ ).build();
3299
+ draft.assign(normalizePopulatePolicyOptions(options));
3300
+ this.publishDefaultModelOptions(draft.fetch());
3043
3301
  }
3044
3302
  setDefaultModelOption(key, value) {
3045
3303
  const keyStr = String(key);
3046
- if (keyStr === "hydration" || keyStr.startsWith("hydration.")) {
3047
- this.defaultModelOptions.set(
3048
- "hydration",
3049
- normalizeHydrationUpdate(this.getDefaultModelOptions().hydration, keyStr, value)
3050
- );
3051
- return;
3052
- }
3053
- if (keyStr === "defaults") assertPublicDefaults(value);
3054
- else if (keyStr.startsWith("defaults.")) {
3055
- const proposed = {};
3056
- set4(proposed, keyStr.slice("defaults.".length), value);
3057
- assertPublicDefaults(proposed);
3304
+ const draft = new OptionsManager(
3305
+ this.getDefaultModelOptions()
3306
+ ).build();
3307
+ if (isPopulatePolicyKey(keyStr)) {
3308
+ draft.set(keyStr, normalizePopulatePolicyValue(value));
3309
+ } else if (keyStr === "hydration" || keyStr.startsWith("hydration.")) {
3310
+ draft.set("hydration", normalizeHydrationUpdate(this.getDefaultModelOptions().hydration, keyStr, value));
3311
+ } else {
3312
+ draft.set(key, value);
3058
3313
  }
3059
- this.defaultModelOptions.set(key, value);
3314
+ assertPublicDefaults(draft.fetch().defaults);
3315
+ this.publishDefaultModelOptions(draft.fetch());
3060
3316
  }
3061
3317
  getDefaultModelOptions() {
3062
3318
  return this.defaultModelOptions.fetch();
@@ -3064,30 +3320,103 @@ var init_runtime = __esm({
3064
3320
  getDefaultModelOption(key, defaultValue) {
3065
3321
  return this.defaultModelOptions.get(key, defaultValue);
3066
3322
  }
3067
- createModelOptions(modelName) {
3323
+ resolveModelOptions(modelName, overrides = this.modelOptionOverrides[modelName] ?? {}, defaults2 = this.getDefaultModelOptions()) {
3324
+ const inherited = { ...defaults2 };
3325
+ for (const key of populatePolicyKeys) delete inherited[key];
3326
+ const effective = { ...defaultModelOptions, ...inherited, ...overrides, modelName };
3327
+ effective.basePath = normalizeBasePath(modelName, effective.basePath);
3328
+ for (const key of unsafeSnapshotOptions) effective[key] = effective[key] === true;
3329
+ refreshPermissionMetadata(effective);
3330
+ return cloneOptionsSnapshot(effective);
3331
+ }
3332
+ validateModelOptions(modelName, options, proposed) {
3333
+ validateVirtualsTree(
3334
+ this.getModelInstance(modelName),
3335
+ options.virtuals,
3336
+ options.documentPermissionField ?? "_permissions",
3337
+ modelName
3338
+ );
3339
+ captureVirtualPopulateDependencies(this, modelName, options, void 0, proposed);
3340
+ }
3341
+ publishDefaultModelOptions(options) {
3342
+ const next = { ...options };
3343
+ for (const key of unsafeSnapshotOptions) if (key in next) next[key] = next[key] === true;
3344
+ const defaults2 = cloneOptionsSnapshot(next);
3345
+ const models = new Map(
3346
+ Object.keys(this.modelOptions).map((name) => [name, this.resolveModelOptions(name, void 0, defaults2)])
3347
+ );
3348
+ for (const [name, options2] of models) this.validateModelOptions(name, options2, { defaults: defaults2, models });
3349
+ this.deferSnapshotWarnings(() => {
3350
+ this.defaultModelOptions.restore(defaults2);
3351
+ for (const [name, options2] of models) this.modelOptions[name].restore(options2);
3352
+ });
3353
+ }
3354
+ warnSnapshotFlag(modelName, key) {
3355
+ if (this.pendingSnapshotWarnings) {
3356
+ this.pendingSnapshotWarnings.push({ modelName, key });
3357
+ return;
3358
+ }
3359
+ const operation = key.startsWith("unsafeSkipRead") ? "read" : "list";
3360
+ const category = key.includes("NestedDocument") ? "nested-document" : key.includes("Output") ? "output" : "document";
3361
+ const risk = category === "output" ? "output mutation" : "source mutation";
3362
+ try {
3363
+ this.getGlobalOption("logger")?.warn?.(
3364
+ `UNSAFE: ${operation} ${category} snapshot checks disabled; ${risk} can leave stale authorization decisions. Restore ${key}=false after the temporary workaround.`,
3365
+ { modelName }
3366
+ );
3367
+ } catch {
3368
+ }
3369
+ }
3370
+ deferSnapshotWarnings(publish) {
3371
+ if (this.pendingSnapshotWarnings) return publish();
3372
+ const copyModes = this.initialOutputCopyModes();
3373
+ const pending = [];
3374
+ this.pendingSnapshotWarnings = pending;
3375
+ let result2;
3376
+ try {
3377
+ result2 = publish();
3378
+ } finally {
3379
+ this.pendingSnapshotWarnings = void 0;
3380
+ }
3381
+ const nextCopyModes = this.initialOutputCopyModes();
3382
+ for (const { modelName, key } of pending) this.warnSnapshotFlag(modelName, key);
3383
+ for (const [modelName, modes] of nextCopyModes) {
3384
+ for (const operation of ["List", "Read"]) {
3385
+ const mode = modes[operation];
3386
+ if (mode === "off" || mode === copyModes.get(modelName)?.[operation]) continue;
3387
+ const key = `unsafeSkip${operation}InitialOutputSnapshotCopy`;
3388
+ const prerequisite = `unsafeSkip${operation}OutputSnapshotChecks`;
3389
+ try {
3390
+ this.getGlobalOption("logger")?.warn?.(
3391
+ 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.`,
3392
+ { modelName }
3393
+ );
3394
+ } catch {
3395
+ }
3396
+ }
3397
+ }
3398
+ return result2;
3399
+ }
3400
+ initialOutputCopyModes() {
3401
+ return new Map(
3402
+ Object.entries(this.modelOptions).map(([modelName, options]) => {
3403
+ const mode = (operation) => options.get(`unsafeSkip${operation}InitialOutputSnapshotCopy`) !== true ? "off" : options.get(`unsafeSkip${operation}OutputSnapshotChecks`) === true ? "active" : "dormant";
3404
+ return [modelName, { List: mode("List"), Read: mode("Read") }];
3405
+ })
3406
+ );
3407
+ }
3408
+ createModelOptions(modelName, options = this.resolveModelOptions(modelName)) {
3068
3409
  const model = this.getModelInstance(modelName);
3069
3410
  if (!model) {
3070
3411
  throw new Error(
3071
3412
  `Runtime model registry missing model "${modelName}". Pass a mongoose.Model instance to createRouter() or register it with registerModelInstance() before using this isolated runtime.`
3072
3413
  );
3073
3414
  }
3074
- const manager = new OptionsManager({
3075
- ...defaultModelOptions,
3076
- modelName
3077
- });
3415
+ const manager = new OptionsManager(options);
3078
3416
  const snapshotFlagChanged = (newValue, key, target, oldValue) => {
3079
3417
  target[key] = newValue === true;
3080
3418
  if (newValue !== true || oldValue === true) return;
3081
- const operation = key.startsWith("unsafeSkipRead") ? "read" : "list";
3082
- const category = key.includes("NestedDocument") ? "nested-document" : key.includes("Output") ? "output" : "document";
3083
- const risk = category === "output" ? "output mutation" : "source mutation";
3084
- try {
3085
- this.getGlobalOption("logger")?.warn?.(
3086
- `UNSAFE: ${operation} ${category} snapshot checks disabled; ${risk} can leave stale authorization decisions. Restore ${key}=false after the temporary workaround.`,
3087
- { modelName }
3088
- );
3089
- } catch {
3090
- }
3419
+ this.warnSnapshotFlag(modelName, key);
3091
3420
  };
3092
3421
  manager.onchange("permissionSchema", function(_newval, _key, target) {
3093
3422
  refreshPermissionMetadata(target);
@@ -3105,13 +3434,17 @@ var init_runtime = __esm({
3105
3434
  getOrCreateModelOptions(modelName) {
3106
3435
  let manager = this.modelOptions[modelName];
3107
3436
  if (!manager) {
3108
- manager = this.createModelOptions(modelName);
3109
- this.modelOptions[modelName] = manager;
3437
+ manager = this.deferSnapshotWarnings(() => {
3438
+ const created = this.createModelOptions(modelName);
3439
+ this.modelOptions[modelName] = created;
3440
+ return created;
3441
+ });
3110
3442
  }
3111
3443
  return manager;
3112
3444
  }
3113
3445
  /**
3114
- * Assign `{ ...modelDefaults, ...storedOptions, ...options }` shallowly. A supplied
3446
+ * Update explicit model overrides shallowly; undefined restores default inheritance
3447
+ * (operationAccess preserves its existing exact-key-only default fallback). A supplied
3115
3448
  * operationAccess/defaults object replaces that whole value. Defaults accept only
3116
3449
  * query/presentation settings; virtual configuration is validated before assignment.
3117
3450
  * Existing router.options remains its construction-time snapshot. Fresh model-service
@@ -3119,22 +3452,23 @@ var init_runtime = __esm({
3119
3452
  */
3120
3453
  setModelOptions(modelName, options) {
3121
3454
  assertPublicDefaults(options.defaults);
3455
+ options = normalizePopulatePolicyOptions(options);
3122
3456
  if ("hydration" in options) options = { ...options, hydration: normalizeHydration(options.hydration) };
3123
- const defaultOptions = this.getDefaultModelOptions();
3124
- const currentModelOptions = this.modelOptions[modelName]?.fetch() ?? { ...defaultModelOptions, modelName };
3125
- const merged = { ...defaultOptions, ...currentModelOptions, ...options };
3126
- const model = this.getModelInstance(modelName);
3127
- const permissionField = merged.documentPermissionField ?? currentModelOptions.documentPermissionField ?? this.getDefaultModelOption("documentPermissionField") ?? "_permissions";
3128
- validateVirtualsTree(model, merged.virtuals, permissionField, modelName);
3129
- captureVirtualPopulateDependencies(this, modelName, merged);
3130
- const manager = this.getOrCreateModelOptions(modelName);
3131
- manager.assign({ ...defaultOptions, ...currentModelOptions, ...options });
3457
+ const overrides = modelOverrides({ ...this.modelOptionOverrides[modelName], ...options });
3458
+ const effective = this.resolveModelOptions(modelName, overrides);
3459
+ this.validateModelOptions(modelName, effective);
3460
+ this.deferSnapshotWarnings(() => {
3461
+ const manager = this.modelOptions[modelName];
3462
+ if (manager) manager.restore(effective);
3463
+ else this.modelOptions[modelName] = this.createModelOptions(modelName, effective);
3464
+ this.modelOptionOverrides[modelName] = overrides;
3465
+ });
3132
3466
  }
3133
3467
  setModelOption(modelName, key, value) {
3134
3468
  const keyStr = String(key);
3135
3469
  if (keyStr === "hydration" || keyStr.startsWith("hydration.")) {
3136
- const hydration = normalizeHydrationUpdate(this.modelOptions[modelName]?.get("hydration"), keyStr, value);
3137
- this.getOrCreateModelOptions(modelName).set("hydration", hydration);
3470
+ const hydration = normalizeHydrationUpdate(this.resolveModelOptions(modelName).hydration, keyStr, value);
3471
+ this.setModelOptions(modelName, { hydration });
3138
3472
  return;
3139
3473
  }
3140
3474
  if (keyStr === "defaults") assertPublicDefaults(value);
@@ -3143,47 +3477,20 @@ var init_runtime = __esm({
3143
3477
  set4(proposed, keyStr.slice("defaults.".length), value);
3144
3478
  assertPublicDefaults(proposed);
3145
3479
  }
3146
- const manager = this.modelOptions[modelName];
3147
- if (keyStr === "virtuals" || keyStr.startsWith("virtuals.") || keyStr === "documentPermissionField") {
3148
- const model = this.getModelInstance(modelName);
3149
- const currentVirtuals = manager?.get("virtuals");
3150
- const currentPermissionField = manager?.get("documentPermissionField") ?? this.getDefaultModelOption("documentPermissionField") ?? "_permissions";
3151
- let proposedVirtuals = currentVirtuals;
3152
- let proposedPermissionField = currentPermissionField;
3153
- if (keyStr === "documentPermissionField") {
3154
- proposedPermissionField = value;
3155
- } else if (keyStr === "virtuals") {
3156
- proposedVirtuals = value;
3157
- } else {
3158
- const cloned = cloneVirtualsForValidation(currentVirtuals ?? {});
3159
- const nestedPath = keyStr.slice("virtuals.".length);
3160
- if (value === void 0) {
3161
- const segments = nestedPath.split(".");
3162
- let cursor = cloned;
3163
- for (let i = 0; i < segments.length - 1; i++) {
3164
- if (!isPlainObject14(cursor)) break;
3165
- cursor = cursor[segments[i]];
3166
- }
3167
- if (isPlainObject14(cursor)) {
3168
- delete cursor[segments[segments.length - 1]];
3169
- }
3170
- proposedVirtuals = cloned;
3171
- } else {
3172
- set4(cloned, nestedPath, value);
3173
- proposedVirtuals = cloned;
3174
- }
3175
- }
3176
- validateVirtualsTree(model, proposedVirtuals, proposedPermissionField, modelName);
3177
- captureVirtualPopulateDependencies(this, modelName, {
3178
- ...this.getDefaultModelOptions(),
3179
- ...manager?.fetch(),
3180
- virtuals: proposedVirtuals,
3181
- documentPermissionField: proposedPermissionField
3182
- });
3480
+ const [root, ...path] = keyStr.split(".");
3481
+ if (!path.length) {
3482
+ this.setModelOptions(modelName, { [root]: value });
3483
+ return;
3183
3484
  }
3184
- this.getOrCreateModelOptions(modelName).set(key, value);
3185
- }
3186
- /** Frozen stored snapshot, not fully resolved per-path defaults. Read again for current configuration. */
3485
+ const current = this.resolveModelOptions(modelName);
3486
+ const nested = cloneModelOptionForUpdate(isPlainObject14(current[root]) ? current[root] : {});
3487
+ if (root === "virtuals" && value === void 0) {
3488
+ const parent = path.length === 1 ? nested : get5(nested, path.slice(0, -1));
3489
+ if (isPlainObject14(parent)) delete parent[path[path.length - 1]];
3490
+ } else set4(nested, path, value);
3491
+ this.setModelOptions(modelName, { [root]: nested });
3492
+ }
3493
+ /** Frozen model/default snapshot; populate flags remain raw overrides. Read again for current values. */
3187
3494
  getModelOptions(modelName) {
3188
3495
  const manager = this.getOrCreateModelOptions(modelName);
3189
3496
  return manager.fetch();
@@ -3350,132 +3657,117 @@ var init_runtime = __esm({
3350
3657
  }
3351
3658
  });
3352
3659
 
3353
- // src/runtime-context.ts
3354
- import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
3355
- function runWithRuntime(runtime, callback) {
3356
- return runtimeStorage.run(runtime, callback);
3357
- }
3358
- function getActiveRuntime() {
3359
- return runtimeStorage.getStore() ?? null;
3360
- }
3361
- var runtimeStorage;
3362
- var init_runtime_context = __esm({
3363
- "src/runtime-context.ts"() {
3364
- runtimeStorage = new AsyncLocalStorage2();
3365
- }
3366
- });
3367
-
3368
3660
  // src/options/global-options.ts
3369
- var getRuntime, setGlobalOptions, setGlobalOption, getGlobalOptions, getGlobalOption;
3661
+ var getRuntime2, setGlobalOptions, setGlobalOption, getGlobalOptions, getGlobalOption;
3370
3662
  var init_global_options = __esm({
3371
3663
  "src/options/global-options.ts"() {
3372
3664
  init_runtime();
3373
3665
  init_runtime_context();
3374
- getRuntime = () => getActiveRuntime() ?? defaultRuntime;
3666
+ getRuntime2 = () => getActiveRuntime() ?? defaultRuntime;
3375
3667
  setGlobalOptions = (options) => {
3376
- getRuntime().setGlobalOptions(options);
3668
+ getRuntime2().setGlobalOptions(options);
3377
3669
  };
3378
3670
  setGlobalOption = (key, value) => {
3379
- getRuntime().setGlobalOption(key, value);
3671
+ getRuntime2().setGlobalOption(key, value);
3380
3672
  };
3381
3673
  getGlobalOptions = () => {
3382
- return getRuntime().getGlobalOptions();
3674
+ return getRuntime2().getGlobalOptions();
3383
3675
  };
3384
3676
  getGlobalOption = (key, defaultValue) => {
3385
- return getRuntime().getGlobalOption(key, defaultValue);
3677
+ return getRuntime2().getGlobalOption(key, defaultValue);
3386
3678
  };
3387
3679
  }
3388
3680
  });
3389
3681
 
3390
3682
  // src/options/model-options.ts
3391
- var getRuntime2, setModelOptions, setModelOption, getModelOptions, getModelOption, getExactModelOption, getModelNames, getModelJsonSchema, registerModelInstance, hasModelInstance, getModelInstance;
3683
+ var getRuntime3, setModelOptions, setModelOption, getModelOptions, getModelOption, getExactModelOption, getModelNames, getModelJsonSchema, registerModelInstance, hasModelInstance, getModelInstance;
3392
3684
  var init_model_options = __esm({
3393
3685
  "src/options/model-options.ts"() {
3394
3686
  init_runtime();
3395
3687
  init_runtime_context();
3396
- getRuntime2 = () => getActiveRuntime() ?? defaultRuntime;
3688
+ getRuntime3 = () => getActiveRuntime() ?? defaultRuntime;
3397
3689
  setModelOptions = (modelName, options) => {
3398
- getRuntime2().setModelOptions(modelName, options);
3690
+ getRuntime3().setModelOptions(modelName, options);
3399
3691
  };
3400
3692
  setModelOption = (modelName, key, value) => {
3401
- getRuntime2().setModelOption(modelName, key, value);
3693
+ getRuntime3().setModelOption(modelName, key, value);
3402
3694
  };
3403
3695
  getModelOptions = (modelName) => {
3404
- return getRuntime2().getModelOptions(modelName);
3696
+ return getRuntime3().getModelOptions(modelName);
3405
3697
  };
3406
3698
  getModelOption = (modelName, key, defaultValue) => {
3407
- return getRuntime2().getModelOption(modelName, key, defaultValue);
3699
+ return getRuntime3().getModelOption(modelName, key, defaultValue);
3408
3700
  };
3409
3701
  getExactModelOption = (modelName, key) => {
3410
- return getRuntime2().getExactModelOption(modelName, key);
3702
+ return getRuntime3().getExactModelOption(modelName, key);
3411
3703
  };
3412
3704
  getModelNames = () => {
3413
3705
  return (getActiveRuntime() ?? defaultRuntime).getModelNames();
3414
3706
  };
3415
3707
  getModelJsonSchema = (modelName) => {
3416
- return getRuntime2().getModelJsonSchema(modelName);
3708
+ return getRuntime3().getModelJsonSchema(modelName);
3417
3709
  };
3418
3710
  registerModelInstance = (modelName, model) => {
3419
- getRuntime2().registerModelInstance(modelName, model);
3711
+ getRuntime3().registerModelInstance(modelName, model);
3420
3712
  };
3421
3713
  hasModelInstance = (modelName) => {
3422
- return getRuntime2().hasModelInstance(modelName);
3714
+ return getRuntime3().hasModelInstance(modelName);
3423
3715
  };
3424
3716
  getModelInstance = (modelName) => {
3425
- return getRuntime2().getModelInstance(modelName);
3717
+ return getRuntime3().getModelInstance(modelName);
3426
3718
  };
3427
3719
  }
3428
3720
  });
3429
3721
 
3430
3722
  // src/options/default-model-options.ts
3431
- var getRuntime3, setDefaultModelOptions, setDefaultModelOption, getDefaultModelOptions, getDefaultModelOption;
3723
+ var getRuntime4, setDefaultModelOptions, setDefaultModelOption, getDefaultModelOptions, getDefaultModelOption;
3432
3724
  var init_default_model_options = __esm({
3433
3725
  "src/options/default-model-options.ts"() {
3434
3726
  init_runtime();
3435
3727
  init_runtime_context();
3436
- getRuntime3 = () => getActiveRuntime() ?? defaultRuntime;
3728
+ getRuntime4 = () => getActiveRuntime() ?? defaultRuntime;
3437
3729
  setDefaultModelOptions = (options) => {
3438
- getRuntime3().setDefaultModelOptions(options);
3730
+ getRuntime4().setDefaultModelOptions(options);
3439
3731
  };
3440
3732
  setDefaultModelOption = (key, value) => {
3441
- getRuntime3().setDefaultModelOption(key, value);
3733
+ getRuntime4().setDefaultModelOption(key, value);
3442
3734
  };
3443
3735
  getDefaultModelOptions = () => {
3444
- return getRuntime3().getDefaultModelOptions();
3736
+ return getRuntime4().getDefaultModelOptions();
3445
3737
  };
3446
3738
  getDefaultModelOption = (key, defaultValue) => {
3447
- return getRuntime3().getDefaultModelOption(key, defaultValue);
3739
+ return getRuntime4().getDefaultModelOption(key, defaultValue);
3448
3740
  };
3449
3741
  }
3450
3742
  });
3451
3743
 
3452
3744
  // src/options/data-options.ts
3453
- var getRuntime4, setDataOptions, setDataOption, getDataOptions, getDataSnapshot, getDataOption, getExactDataOption, getDataNames;
3745
+ var getRuntime5, setDataOptions, setDataOption, getDataOptions, getDataSnapshot, getDataOption, getExactDataOption, getDataNames;
3454
3746
  var init_data_options = __esm({
3455
3747
  "src/options/data-options.ts"() {
3456
3748
  init_runtime();
3457
3749
  init_runtime_context();
3458
- getRuntime4 = () => getActiveRuntime() ?? defaultRuntime;
3750
+ getRuntime5 = () => getActiveRuntime() ?? defaultRuntime;
3459
3751
  setDataOptions = (dataName, options) => {
3460
- getRuntime4().setDataOptions(dataName, options);
3752
+ getRuntime5().setDataOptions(dataName, options);
3461
3753
  };
3462
3754
  setDataOption = (dataName, key, value) => {
3463
- getRuntime4().setDataOption(dataName, key, value);
3755
+ getRuntime5().setDataOption(dataName, key, value);
3464
3756
  };
3465
3757
  getDataOptions = (dataName) => {
3466
- return getRuntime4().getDataOptions(dataName);
3758
+ return getRuntime5().getDataOptions(dataName);
3467
3759
  };
3468
3760
  getDataSnapshot = (dataName) => {
3469
- return getRuntime4().getDataSnapshot(dataName);
3761
+ return getRuntime5().getDataSnapshot(dataName);
3470
3762
  };
3471
3763
  getDataOption = (dataName, key, defaultValue) => {
3472
- return getRuntime4().getDataOption(dataName, key, defaultValue);
3764
+ return getRuntime5().getDataOption(dataName, key, defaultValue);
3473
3765
  };
3474
3766
  getExactDataOption = (dataName, key) => {
3475
- return getRuntime4().getExactDataOption(dataName, key);
3767
+ return getRuntime5().getExactDataOption(dataName, key);
3476
3768
  };
3477
3769
  getDataNames = () => {
3478
- return getRuntime4().getDataNames();
3770
+ return getRuntime5().getDataNames();
3479
3771
  };
3480
3772
  }
3481
3773
  });
@@ -3611,7 +3903,9 @@ function captureAuthorizationCatalog(value) {
3611
3903
  }
3612
3904
  catalog[key] = paths;
3613
3905
  }
3614
- return Object.freeze(catalog);
3906
+ const captured = Object.freeze(catalog);
3907
+ prepareCapturedOutputCatalog(captured);
3908
+ return captured;
3615
3909
  }
3616
3910
  function assertAuthorizationPath(path) {
3617
3911
  if (typeof path !== "string" || !isSafeOutputPath(path)) {
@@ -3796,10 +4090,12 @@ function resolveServiceAuthorization(input) {
3796
4090
  const listResponse = input.listResponse === true && input.parent === void 0 && (input.applicability ?? "service") === "service" && scopePath.length === 0 && outputAccess.operation === "list" && outputAccess.rowAccess === "list" && queryOutputAccess(outputAccess);
3797
4091
  const responseSnapshots = input.parent && (nestedResponse || readResponse) ? callRecord(input.parent).responseSnapshots : listResponse ? Object.freeze({
3798
4092
  skipOutput: configuration.unsafeSkipListOutputSnapshotChecks === true,
3799
- skipNested: configuration.unsafeSkipListNestedDocumentSnapshotChecks === true
4093
+ skipNested: configuration.unsafeSkipListNestedDocumentSnapshotChecks === true,
4094
+ skipInitialOutputCopy: configuration.unsafeSkipListOutputSnapshotChecks === true && configuration.unsafeSkipListInitialOutputSnapshotCopy === true
3800
4095
  }) : readResponse ? Object.freeze({
3801
4096
  skipOutput: configuration.unsafeSkipReadOutputSnapshotChecks === true,
3802
- skipNested: configuration.unsafeSkipReadNestedDocumentSnapshotChecks === true
4097
+ skipNested: configuration.unsafeSkipReadNestedDocumentSnapshotChecks === true,
4098
+ skipInitialOutputCopy: configuration.unsafeSkipReadOutputSnapshotChecks === true && configuration.unsafeSkipReadInitialOutputSnapshotCopy === true
3803
4099
  }) : void 0;
3804
4100
  const call = Object.freeze(/* @__PURE__ */ Object.create(null));
3805
4101
  calls.set(call, {
@@ -3816,6 +4112,7 @@ function resolveServiceAuthorization(input) {
3816
4112
  nestedResponse,
3817
4113
  responseSnapshots,
3818
4114
  validateOutputSnapshots: responseSnapshots?.skipOutput !== true,
4115
+ skipInitialOutputSnapshotCopy: responseSnapshots?.skipInitialOutputCopy === true,
3819
4116
  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)
3820
4117
  });
3821
4118
  return call;
@@ -3845,6 +4142,10 @@ function requiresOutputSnapshotChecks(call, binding) {
3845
4142
  assertAuthorizationBinding(call, binding);
3846
4143
  return callRecord(call).validateOutputSnapshots;
3847
4144
  }
4145
+ function skipsInitialOutputSnapshotCopy(call) {
4146
+ const record3 = callRecord(call);
4147
+ return !record3.validateOutputSnapshots && record3.skipInitialOutputSnapshotCopy;
4148
+ }
3848
4149
  function readServiceAuthorizationHydration(call, binding) {
3849
4150
  assertAuthorizationBinding(call, binding);
3850
4151
  return copyAuthorizationValue({ hydration: callRecord(call).configuration.hydration }, true);
@@ -4297,9 +4598,9 @@ var init_virtual_projection = __esm({
4297
4598
  });
4298
4599
 
4299
4600
  // src/acl/output-projection.ts
4300
- import { types as types2 } from "util";
4601
+ import { types as types4 } from "util";
4301
4602
  function copyOutputDecisionFields(value) {
4302
- if (!Array.isArray(value) || types2.isProxy(value) || Object.getPrototypeOf(value) !== Array.prototype) return;
4603
+ if (!Array.isArray(value) || types4.isProxy(value) || Object.getPrototypeOf(value) !== Array.prototype) return;
4303
4604
  const length = Object.getOwnPropertyDescriptor(value, "length").value;
4304
4605
  if (length > 2e4) return;
4305
4606
  const fields = [];
@@ -4312,14 +4613,14 @@ function copyOutputDecisionFields(value) {
4312
4613
  }
4313
4614
  function readStaticOutputPlanFields(plan, authorization) {
4314
4615
  const record3 = staticPlanFields.get(plan);
4315
- if (!record3 || record3.authorization !== authorization || types2.isProxy(plan)) return;
4616
+ if (!record3 || record3.authorization !== authorization || types4.isProxy(plan)) return;
4316
4617
  const ownValue2 = (key) => {
4317
4618
  const slot = Object.getOwnPropertyDescriptor(plan, key);
4318
4619
  return slot && "value" in slot ? slot.value : void 0;
4319
4620
  };
4320
4621
  if (ownValue2("authorization") !== authorization || ownValue2("authorizationBinding") !== record3.binding) return;
4321
4622
  const children = ownValue2("childPlans");
4322
- if (children !== record3.children || types2.isProxy(children) || Reflect.ownKeys(children).length) return;
4623
+ if (children !== record3.children || types4.isProxy(children) || Reflect.ownKeys(children).length) return;
4323
4624
  const persisted = copyOutputDecisionFields(ownValue2("outputPersistedFields"));
4324
4625
  const virtuals = copyOutputDecisionFields(ownValue2("outputVirtualNames"));
4325
4626
  const same = (a, b) => a?.length === b.length && a.every((field, index) => field === b[index]);
@@ -4574,7 +4875,7 @@ var init_output_projection = __esm({
4574
4875
  });
4575
4876
 
4576
4877
  // src/acl/output-field-policy.ts
4577
- import { types as types3 } from "util";
4878
+ import { types as types5 } from "util";
4578
4879
  import { isPlainObject as isPlainObject16 } from "@web-ts-toolkit/utils";
4579
4880
  function callFieldPolicy(authorization, binding) {
4580
4881
  assertAuthorizationBinding(authorization, binding);
@@ -4646,7 +4947,7 @@ function prepareOutputPath(policy, authorization, binding, path, access) {
4646
4947
  return prepared;
4647
4948
  }
4648
4949
  function ordinaryContainer(value) {
4649
- return value !== null && typeof value === "object" && !types3.isProxy(value) && Object.getPrototypeOf(value) === Object.prototype && Object.isFrozen(value);
4950
+ return value !== null && typeof value === "object" && !types5.isProxy(value) && Object.getPrototypeOf(value) === Object.prototype && Object.isFrozen(value);
4650
4951
  }
4651
4952
  function booleanRuleLookup(schema, path, access) {
4652
4953
  if (schema == null) return true;
@@ -4705,7 +5006,7 @@ var init_output_field_policy = __esm({
4705
5006
  });
4706
5007
 
4707
5008
  // src/acl/document-authorization.ts
4708
- import { types as types4 } from "util";
5009
+ import { types as types6 } from "util";
4709
5010
  import { Document as Document3 } from "mongoose";
4710
5011
  function bindOutputDocumentOwner(handle, knownOutput, owner, binding) {
4711
5012
  lookupDocumentOwner(handle);
@@ -4887,7 +5188,7 @@ function memoizeDocumentFieldDecision(handle, binding, field, evaluate) {
4887
5188
  return decision.promise;
4888
5189
  }
4889
5190
  function ordinaryDecisionBinding(binding) {
4890
- if (types4.isProxy(binding) || Object.getPrototypeOf(binding) !== Object.prototype) return false;
5191
+ if (types6.isProxy(binding) || Object.getPrototypeOf(binding) !== Object.prototype) return false;
4891
5192
  for (const key of ["request", "runtime", "model", "modelName", "scopePath"]) {
4892
5193
  const slot = Object.getOwnPropertyDescriptor(binding, key);
4893
5194
  if (slot && !("value" in slot)) return false;
@@ -5038,8 +5339,18 @@ function associateDocumentAuthorization(handle, binding, output) {
5038
5339
  authorizationError("output already associated");
5039
5340
  return;
5040
5341
  }
5342
+ if (skipsInitialOutputSnapshotCopy(stage.call) && ordinaryDecisionBinding(binding)) {
5343
+ if (requiresOutputSnapshotChecks(stage.call, binding))
5344
+ authorizationError("output snapshot copy requires skipped comparisons");
5345
+ const identities = tryOutputIdentitiesWithoutSnapshot(output);
5346
+ if (identities) {
5347
+ outputs.set(output, { handle, snapshotState: "omitted", identities, validateSnapshot: false });
5348
+ return;
5349
+ }
5350
+ }
5041
5351
  outputs.set(output, {
5042
5352
  handle,
5353
+ snapshotState: "copied",
5043
5354
  snapshot: copyAuthorizationValue(output, "document"),
5044
5355
  identities: outputIdentities(output),
5045
5356
  validateSnapshot: requiresOutputSnapshotChecks(stage.call, binding)
@@ -5219,7 +5530,8 @@ function getCapturedAuthorizationOption(configuration, key) {
5219
5530
  const defaultValue = key.startsWith("operationAccess.") ? get7(configuration.operationAccessDefaults, key.slice("operationAccess.".length)) : void 0;
5220
5531
  return resolveNestedOption((path, fallback) => get7(configuration, path, fallback), key, defaultValue);
5221
5532
  }
5222
- function captureModelAuthorizationConfiguration(runtime, modelName, options = runtime.getModelOptions(modelName), globalOptions = runtime.getGlobalOptions()) {
5533
+ function captureModelAuthorizationConfiguration(runtime, modelName, options, populatePolicyDefaults = capturePopulatePolicyDefaults(runtime)) {
5534
+ options ??= runtime.getModelOptions(modelName);
5223
5535
  const model = runtime.getModelInstance(modelName);
5224
5536
  if (!model) return authorizationError(`unknown receiving model: ${modelName}`);
5225
5537
  const virtuals = options.virtuals;
@@ -5230,10 +5542,10 @@ function captureModelAuthorizationConfiguration(runtime, modelName, options = ru
5230
5542
  runtime,
5231
5543
  modelName,
5232
5544
  options,
5233
- globalOptions
5545
+ populatePolicyDefaults
5234
5546
  ),
5235
- requireOperationAccessForPopulateDependencies: globalOptions.requireOperationAccessForPopulateDependencies !== false,
5236
- requireOperationAccessForPopulateQueries: globalOptions.requireOperationAccessForPopulateQueries !== false,
5547
+ populatePolicyDefaults,
5548
+ ...resolvePopulatePolicy(options, populatePolicyDefaults),
5237
5549
  permissionSchema: options.permissionSchema === void 0 ? runtime.getDefaultModelOption("permissionSchema") : options.permissionSchema,
5238
5550
  virtuals,
5239
5551
  alwaysSelectFields: options.alwaysSelectFields,
@@ -5250,6 +5562,8 @@ function captureModelAuthorizationConfiguration(runtime, modelName, options = ru
5250
5562
  unsafeSkipReadOutputSnapshotChecks: options.unsafeSkipReadOutputSnapshotChecks === true,
5251
5563
  unsafeSkipListNestedDocumentSnapshotChecks: options.unsafeSkipListNestedDocumentSnapshotChecks === true,
5252
5564
  unsafeSkipReadNestedDocumentSnapshotChecks: options.unsafeSkipReadNestedDocumentSnapshotChecks === true,
5565
+ unsafeSkipListInitialOutputSnapshotCopy: options.unsafeSkipListInitialOutputSnapshotCopy === true,
5566
+ unsafeSkipReadInitialOutputSnapshotCopy: options.unsafeSkipReadInitialOutputSnapshotCopy === true,
5253
5567
  overrideFilter: options.overrideFilter,
5254
5568
  baseFilter: options.baseFilter,
5255
5569
  idField: options.idField,
@@ -5294,6 +5608,7 @@ var init_model_output_planning = __esm({
5294
5608
  init_virtual_populate_dependencies();
5295
5609
  init_document_authorization();
5296
5610
  init_output_projection();
5611
+ init_populate_policy2();
5297
5612
  }
5298
5613
  });
5299
5614
 
@@ -5772,6 +6087,13 @@ var init_logger_helpers = __esm({
5772
6087
 
5773
6088
  // src/acl/populate-target.ts
5774
6089
  function setPopulateTargetMeta(entry, meta) {
6090
+ if (meta.fetchBinding)
6091
+ Object.defineProperty(entry, "model", {
6092
+ value: meta.fetchBinding.model,
6093
+ enumerable: true,
6094
+ writable: false,
6095
+ configurable: false
6096
+ });
5775
6097
  Object.defineProperty(entry, POPULATE_TARGET_PLAN, {
5776
6098
  value: meta,
5777
6099
  enumerable: false,
@@ -6323,7 +6645,7 @@ var init_virtual_populate_execution = __esm({
6323
6645
  });
6324
6646
 
6325
6647
  // src/acl/output-field-filter.ts
6326
- import { types as types5 } from "util";
6648
+ import { types as types7 } from "util";
6327
6649
  import { isPlainObject as isPlainObject22 } from "@web-ts-toolkit/utils";
6328
6650
  function assertOwningOutputDocuments(handle) {
6329
6651
  const owner = readOutputDocumentOwner(handle);
@@ -6552,7 +6874,7 @@ function helperPlan(authorization, binding) {
6552
6874
  return planAuthorizedModelProjection({ authorization, binding, effectiveSelect: [] });
6553
6875
  }
6554
6876
  function primitiveHelperFields(source, plan) {
6555
- if (types5.isProxy(source)) return;
6877
+ if (types7.isProxy(source)) return;
6556
6878
  const canonical = readStaticOutputPlanFields(plan, plan.authorization);
6557
6879
  if (!canonical) return;
6558
6880
  const fields = [];
@@ -7373,7 +7695,7 @@ init_sort_policy();
7373
7695
  init_concurrency();
7374
7696
  import {
7375
7697
  castArray as castArray2,
7376
- cloneDeep as cloneDeep2,
7698
+ cloneDeep as cloneDeep3,
7377
7699
  compact,
7378
7700
  flatten,
7379
7701
  forEach as forEach3,
@@ -7944,14 +8266,111 @@ function isCorrelatedInclude(value) {
7944
8266
  // src/services/base.ts
7945
8267
  init_request_complexity();
7946
8268
 
8269
+ // src/model.ts
8270
+ init_runtime_context();
8271
+ init_runtime();
8272
+ import { AsyncLocalStorage as AsyncLocalStorage3 } from "async_hooks";
8273
+ import { cloneDeep as cloneDeep2 } from "@web-ts-toolkit/utils";
8274
+ var capturedModelConstruction = new AsyncLocalStorage3();
8275
+ function withCapturedPopulateModel(runtime, modelName, model, construct) {
8276
+ return capturedModelConstruction.run({ runtime, modelName, model }, construct);
8277
+ }
8278
+ function admitModelPersistence(adapter, scheduler) {
8279
+ return {
8280
+ modelName: adapter.modelName,
8281
+ mongooseModel: adapter.mongooseModel,
8282
+ new: () => adapter.new(),
8283
+ // Mongoose create(array) otherwise starts all document saves at once. Keep
8284
+ // the adapter's array input/output contract, with one permit per item; all
8285
+ // items are submitted even if one rejects, as with unordered create(array).
8286
+ create: (data) => Array.isArray(data) ? Promise.all(data.map((item) => scheduler.work(async () => (await adapter.create([item]))[0]))) : scheduler.work(() => adapter.create(data)),
8287
+ find: (props) => scheduler.work(() => adapter.find(props)),
8288
+ findOne: (props) => scheduler.work(() => adapter.findOne(props)),
8289
+ exists: (filter2) => scheduler.work(() => adapter.exists(filter2)),
8290
+ countDocuments: (filter2) => scheduler.work(() => adapter.countDocuments(filter2)),
8291
+ distinct: (field, conditions) => scheduler.work(() => adapter.distinct(field, conditions)),
8292
+ aggregate: (pipeline) => scheduler.work(() => adapter.aggregate(pipeline)),
8293
+ // Casting builds no persistence work and must not acquire a recursive permit.
8294
+ ...adapter.castFilter ? { castFilter: (filter2) => adapter.castFilter(filter2) } : {}
8295
+ };
8296
+ }
8297
+ var Model = class {
8298
+ constructor(modelName, runtime) {
8299
+ this.modelName = modelName;
8300
+ this.runtime = runtime ?? null;
8301
+ const resolvedRuntime = runtime ?? getActiveRuntime() ?? defaultRuntime;
8302
+ const captured = capturedModelConstruction.getStore();
8303
+ const registered = captured?.runtime === resolvedRuntime && captured.modelName === modelName ? captured.model : resolvedRuntime.getModelInstance(modelName);
8304
+ if (!registered) {
8305
+ throw new Error(
8306
+ `Runtime model registry missing model "${modelName}". Pass a mongoose.Model instance to createRouter() or register it with registerModelInstance() before using this runtime.`
8307
+ );
8308
+ }
8309
+ this.mongooseModel = registered;
8310
+ if (!this.mongooseModel) return;
8311
+ }
8312
+ new() {
8313
+ const doc = new this.mongooseModel();
8314
+ return doc;
8315
+ }
8316
+ create(data) {
8317
+ return this.mongooseModel.create(data);
8318
+ }
8319
+ find({ filter: filter2, select, sort, populate, limit, hardLimit, skip, lean }) {
8320
+ const builder = this.mongooseModel.find(filter2);
8321
+ if (select) builder.select(select);
8322
+ if (skip) builder.skip(Number(skip));
8323
+ const normalizedLimit = Number(limit);
8324
+ if (Number.isSafeInteger(normalizedLimit) && normalizedLimit > 0) {
8325
+ builder.limit(normalizedLimit);
8326
+ } else if (Number.isSafeInteger(hardLimit) && Number(hardLimit) > 0) {
8327
+ builder.limit(Number(hardLimit));
8328
+ }
8329
+ if (sort) builder.sort(sort);
8330
+ if (populate) builder.populate(populate);
8331
+ if (lean) builder.lean();
8332
+ return builder;
8333
+ }
8334
+ findOne({ filter: filter2, select, sort, populate, lean }) {
8335
+ const builder = this.mongooseModel.findOne(filter2);
8336
+ if (select) builder.select(select);
8337
+ if (sort) builder.sort(sort);
8338
+ if (populate) builder.populate(populate);
8339
+ if (lean) builder.lean();
8340
+ return builder;
8341
+ }
8342
+ exists(filter2) {
8343
+ if (!filter2) return null;
8344
+ return this.findOne({ filter: filter2 }).select("_id").lean();
8345
+ }
8346
+ // see https://mongoosejs.com/docs/api.html#query_Query-countDocuments
8347
+ countDocuments(filter2 = {}) {
8348
+ return this.mongooseModel.countDocuments(filter2);
8349
+ }
8350
+ /** Cast a copy using this model's query schema/setters, without executing query middleware or persistence. */
8351
+ castFilter(filter2) {
8352
+ const query = this.mongooseModel.countDocuments(cloneDeep2(filter2));
8353
+ return query.cast(this.mongooseModel);
8354
+ }
8355
+ // see https://mongoosejs.com/docs/api.html#model_Model.distinct
8356
+ distinct(field, conditions = {}) {
8357
+ return this.mongooseModel.distinct(field, conditions);
8358
+ }
8359
+ aggregate(pipeline) {
8360
+ return this.mongooseModel.aggregate(pipeline);
8361
+ }
8362
+ };
8363
+ var model_default = Model;
8364
+
7947
8365
  // src/acl/model-service-owner.ts
7948
8366
  init_runtime();
7949
8367
  init_runtime_context();
7950
- import { AsyncLocalStorage as AsyncLocalStorage3 } from "async_hooks";
8368
+ init_populate_policy2();
8369
+ import { AsyncLocalStorage as AsyncLocalStorage4 } from "async_hooks";
7951
8370
  var cores = /* @__PURE__ */ new WeakMap();
7952
- var construction = new AsyncLocalStorage3();
7953
- var dispatch = new AsyncLocalStorage3();
7954
- var operationGuard = new AsyncLocalStorage3();
8371
+ var construction = new AsyncLocalStorage4();
8372
+ var dispatch = new AsyncLocalStorage4();
8373
+ var operationGuard = new AsyncLocalStorage4();
7955
8374
  function withCapturedModelOperationGuard(core, modelName, access, guard2, permissions, run) {
7956
8375
  return operationGuard.run({ captured: { core, modelName, access, guard: guard2, permissions } }, run);
7957
8376
  }
@@ -8000,15 +8419,16 @@ function bindModelOwnerMethods(receiver, runtime) {
8000
8419
  }
8001
8420
  }
8002
8421
  }
8003
- function modelServiceOptions(receiver, read) {
8422
+ function modelServiceOptions(receiver, runtime, read) {
8423
+ modelServicePopulatePolicyDefaults(receiver, runtime);
8004
8424
  const call = dispatch.getStore();
8005
8425
  if (call?.receiver !== receiver) return read();
8006
8426
  return call.options ??= read();
8007
8427
  }
8008
- function modelServiceGlobalOptions(receiver, runtime) {
8428
+ function modelServicePopulatePolicyDefaults(receiver, runtime) {
8009
8429
  const call = dispatch.getStore();
8010
- if (call?.receiver !== receiver) return runtime.getGlobalOptions();
8011
- return call.globalOptions ??= runtime.getGlobalOptions();
8430
+ if (call?.receiver !== receiver) return capturePopulatePolicyDefaults(runtime);
8431
+ return call.populatePolicyDefaults ??= capturePopulatePolicyDefaults(runtime);
8012
8432
  }
8013
8433
 
8014
8434
  // src/services/base.ts
@@ -8162,27 +8582,6 @@ function castCountGroups(input, values) {
8162
8582
  // src/services/base.ts
8163
8583
  init_service_authorization();
8164
8584
 
8165
- // src/meta.ts
8166
- init_runtime();
8167
- init_runtime_context();
8168
- var getRuntime5 = () => getActiveRuntime() ?? defaultRuntime;
8169
- var getModelRef = (modelName, refPath, runtime = getRuntime5()) => {
8170
- const direct = runtime.getModelRef(modelName, refPath);
8171
- if (direct) return direct;
8172
- if (!refPath.includes(".")) return null;
8173
- try {
8174
- const instance = runtime.getModelInstance?.(
8175
- modelName
8176
- );
8177
- const schemaPath = instance?.schema?.path?.(refPath);
8178
- const element = schemaPath?.$embeddedSchemaType ?? schemaPath?.embeddedSchemaType ?? schemaPath?.caster;
8179
- const ref = schemaPath?.options?.ref ?? element?.options?.ref ?? null;
8180
- return typeof ref === "string" && ref.length > 0 ? ref : null;
8181
- } catch {
8182
- return null;
8183
- }
8184
- };
8185
-
8186
8585
  // src/acl/related-execution.ts
8187
8586
  init_public_admission();
8188
8587
  init_model_output_planning();
@@ -8430,9 +8829,9 @@ function resolveExistsOptions(service, options = {}) {
8430
8829
 
8431
8830
  // src/services/model-service-intent.ts
8432
8831
  function captureModelServiceIntent(owner, method, args = {}, options = {}) {
8433
- const defaults = owner.defaults;
8832
+ const defaults2 = owner.defaults;
8434
8833
  const posture = owner.getPermissionsPosture();
8435
- const service = { defaults, getPermissionsPosture: () => posture };
8834
+ const service = { defaults: defaults2, getPermissionsPosture: () => posture };
8436
8835
  switch (method) {
8437
8836
  case "find":
8438
8837
  return deepIsolateValue({ args: resolveFindArgs(service, args), options: resolveFindOptions(service, options) });
@@ -8463,6 +8862,7 @@ function captureModelServiceIntent(owner, method, args = {}, options = {}) {
8463
8862
  }
8464
8863
 
8465
8864
  // src/acl/related-execution.ts
8865
+ init_populate_policy2();
8466
8866
  init_service_authorization();
8467
8867
  function staticObjectIdReference(runtime, source, path, target) {
8468
8868
  const model = runtime.getModelInstance(source), related = runtime.getModelInstance(target);
@@ -8479,7 +8879,7 @@ function staticObjectIdReference(runtime, source, path, target) {
8479
8879
  const scalar = type?.instance === "Array" ? type.$embeddedSchemaType ?? type.embeddedSchemaType ?? type.caster : type;
8480
8880
  return scalar?.instance === "ObjectId" && (type?.options?.ref ?? scalar.options?.ref) === target && type?.options?.refPath === void 0 && scalar.options?.refPath === void 0;
8481
8881
  }
8482
- function captureRelatedTargets(runtime, modelName, args = {}, depth = 0, globalOptions = runtime.getGlobalOptions()) {
8882
+ function captureRelatedTargets(runtime, modelName, args = {}, depth = 0, populatePolicyDefaults = capturePopulatePolicyDefaults(runtime)) {
8483
8883
  if (depth > 32) authorizationError("related descriptor depth exceeded");
8484
8884
  assertPublicAdmission(args.populate, "populate");
8485
8885
  assertPublicAdmission(args.include, "include");
@@ -8488,20 +8888,32 @@ function captureRelatedTargets(runtime, modelName, args = {}, depth = 0, globalO
8488
8888
  for (const entry of entries(args.populate)) {
8489
8889
  const path = typeof entry === "string" ? entry : entry.path;
8490
8890
  if (typeof entry !== "string") assertPopulateAccess(entry.access);
8491
- const model = getModelRef(modelName, path, runtime);
8492
- if (model) {
8493
- const target = capturePopulateTargetConfiguration(runtime, model, `${modelName}.${path}`);
8891
+ const target = capturePopulateTargetBinding(runtime, modelName, path);
8892
+ if (target) {
8494
8893
  targets.push({
8495
8894
  path,
8496
- modelName: model,
8497
- configuration: captureModelAuthorizationConfiguration(runtime, model, target.options, globalOptions),
8498
- staticObjectIdReference: staticObjectIdReference(runtime, modelName, path, model)
8895
+ modelName: target.modelName,
8896
+ model: target.model,
8897
+ configuration: captureModelAuthorizationConfiguration(
8898
+ runtime,
8899
+ target.modelName,
8900
+ target.options,
8901
+ populatePolicyDefaults
8902
+ ),
8903
+ staticObjectIdReference: staticObjectIdReference(runtime, modelName, path, target.modelName)
8499
8904
  });
8500
8905
  }
8501
8906
  }
8502
8907
  for (const entry of entries(args.include)) {
8503
8908
  if (!runtime.hasModel(entry.model)) authorizationError(`Model ${entry.model} not found`);
8504
- const configuration = captureModelAuthorizationConfiguration(runtime, entry.model, void 0, globalOptions);
8909
+ const model = runtime.getModelInstance(entry.model);
8910
+ if (!model) authorizationError(`unknown receiving model: ${entry.model}`);
8911
+ const configuration = captureModelAuthorizationConfiguration(
8912
+ runtime,
8913
+ entry.model,
8914
+ void 0,
8915
+ populatePolicyDefaults
8916
+ );
8505
8917
  const queryIntent = entry.op === "count" ? void 0 : captureModelServiceIntent(
8506
8918
  {
8507
8919
  defaults: configuration.defaults ?? {},
@@ -8523,6 +8935,7 @@ function captureRelatedTargets(runtime, modelName, args = {}, depth = 0, globalO
8523
8935
  targets.push({
8524
8936
  path: entry.path,
8525
8937
  modelName: entry.model,
8938
+ model,
8526
8939
  kind: entry.op === "count" ? "count" : "output",
8527
8940
  configuration,
8528
8941
  queryIntent,
@@ -8532,7 +8945,7 @@ function captureRelatedTargets(runtime, modelName, args = {}, depth = 0, globalO
8532
8945
  entry.model,
8533
8946
  queryIntent?.args ?? entry.args ?? {},
8534
8947
  depth + 1,
8535
- globalOptions
8948
+ populatePolicyDefaults
8536
8949
  )
8537
8950
  });
8538
8951
  }
@@ -8549,7 +8962,8 @@ function createRelatedExecution(receiver, access, parent, binding, path) {
8549
8962
  const captured = readServiceAuthorization(parent, binding);
8550
8963
  const target = captured.relatedTargets.find((entry) => entry.path === path);
8551
8964
  const policy = captured.authorization.related[path];
8552
- if ((target || policy) && (!target || target.modelName !== getServiceExecutors(receiver).binding().modelName))
8965
+ const receiving = getServiceExecutors(receiver).binding();
8966
+ if (policy && !target || target && (target.modelName !== receiving.modelName || target.model !== void 0 && target.model !== receiving.model))
8553
8967
  authorizationError(`related model mismatch: ${path}`);
8554
8968
  const execution = createServiceExecution(
8555
8969
  receiver,
@@ -9047,34 +9461,37 @@ var Base = class {
9047
9461
  });
9048
9462
  }
9049
9463
  async getAuthorizedTargetService(modelName, op, path, parentAuthorization) {
9050
- if (hasModelCoreOwner(this.requestCore) && !this.requestRuntime.hasModel(modelName)) {
9464
+ const binding = parentAuthorization ? this.relatedBinding() : void 0;
9465
+ const captured = parentAuthorization ? readServiceAuthorization(parentAuthorization, binding) : void 0;
9466
+ const target = captured?.relatedTargets.find((entry) => entry.path === path);
9467
+ const policy = path ? captured?.authorization.related[path] : void 0;
9468
+ if (target && target.modelName !== modelName)
9469
+ this.throwClientRequestError("bad_request" /* BadRequest */, `related model mismatch: ${path}`);
9470
+ if (hasModelCoreOwner(this.requestCore) && !target?.model && !this.requestRuntime.hasModel(modelName)) {
9051
9471
  this.throwClientRequestError("bad_request" /* BadRequest */, `Model ${modelName} not found`);
9052
9472
  }
9053
- const policy = path ? relatedPolicy(parentAuthorization, this.relatedBinding(), path) : void 0;
9054
- const captured = parentAuthorization ? readServiceAuthorization(parentAuthorization, this.relatedBinding()) : void 0;
9055
- const target = captured?.relatedTargets.find((entry) => entry.path === path);
9056
9473
  const allowed = policy?.operation.mode === "grant" || (target ? await getRequestWorkState(this.req, this.requestRuntime).hookGate.run(
9057
9474
  () => withCapturedModelOperationGuard(
9058
9475
  this.requestCore,
9059
9476
  modelName,
9060
9477
  op,
9061
9478
  target.operationGuard,
9062
- getAuthorizationPermissions(parentAuthorization, this.relatedBinding()),
9479
+ getAuthorizationPermissions(parentAuthorization, binding),
9063
9480
  () => this.requestCore.isAllowed(modelName, op)
9064
9481
  )
9065
9482
  ) : await this.requestCore.isAllowed(modelName, op));
9066
9483
  if (!allowed) {
9067
9484
  this.throwClientRequestError("unauthorized" /* Unauthorized */, "Unauthorized");
9068
9485
  }
9069
- return this.requestCore.getPublicService(modelName);
9486
+ return target?.model ? withCapturedPopulateModel(
9487
+ this.requestRuntime,
9488
+ modelName,
9489
+ target.model,
9490
+ () => this.requestCore.getPublicService(modelName)
9491
+ ) : this.requestCore.getPublicService(modelName);
9070
9492
  }
9071
9493
  relatedBinding() {
9072
- return {
9073
- request: this.req,
9074
- runtime: this.requestRuntime,
9075
- model: this.requestRuntime.getModelInstance(this.modelName),
9076
- modelName: this.modelName
9077
- };
9494
+ return getServiceExecutors(this).binding();
9078
9495
  }
9079
9496
  relatedExecution(svc, include, parentAuthorization) {
9080
9497
  const op = include.op;
@@ -9484,7 +9901,7 @@ var Base = class {
9484
9901
  }
9485
9902
  const state = this.getCorrelatedExecState();
9486
9903
  docs = docs.map(prepareIncludeOutput);
9487
- const resolvedSnapshots = snapshots2 ?? docs.map((doc) => cloneDeep2(toObject(getIncludeSource(doc))));
9904
+ const resolvedSnapshots = snapshots2 ?? docs.map((doc) => cloneDeep3(toObject(getIncludeSource(doc))));
9488
9905
  for (const include of correlatedIncludes) {
9489
9906
  switch (include.op) {
9490
9907
  case "read":
@@ -9863,96 +10280,6 @@ import {
9863
10280
  } from "@web-ts-toolkit/utils";
9864
10281
  import { diff } from "just-diff";
9865
10282
 
9866
- // src/model.ts
9867
- init_runtime_context();
9868
- init_runtime();
9869
- import { cloneDeep as cloneDeep3 } from "@web-ts-toolkit/utils";
9870
- function admitModelPersistence(adapter, scheduler) {
9871
- return {
9872
- modelName: adapter.modelName,
9873
- mongooseModel: adapter.mongooseModel,
9874
- new: () => adapter.new(),
9875
- // Mongoose create(array) otherwise starts all document saves at once. Keep
9876
- // the adapter's array input/output contract, with one permit per item; all
9877
- // items are submitted even if one rejects, as with unordered create(array).
9878
- create: (data) => Array.isArray(data) ? Promise.all(data.map((item) => scheduler.work(async () => (await adapter.create([item]))[0]))) : scheduler.work(() => adapter.create(data)),
9879
- find: (props) => scheduler.work(() => adapter.find(props)),
9880
- findOne: (props) => scheduler.work(() => adapter.findOne(props)),
9881
- exists: (filter2) => scheduler.work(() => adapter.exists(filter2)),
9882
- countDocuments: (filter2) => scheduler.work(() => adapter.countDocuments(filter2)),
9883
- distinct: (field, conditions) => scheduler.work(() => adapter.distinct(field, conditions)),
9884
- aggregate: (pipeline) => scheduler.work(() => adapter.aggregate(pipeline)),
9885
- // Casting builds no persistence work and must not acquire a recursive permit.
9886
- ...adapter.castFilter ? { castFilter: (filter2) => adapter.castFilter(filter2) } : {}
9887
- };
9888
- }
9889
- var Model = class {
9890
- constructor(modelName, runtime) {
9891
- this.modelName = modelName;
9892
- this.runtime = runtime ?? null;
9893
- const resolvedRuntime = runtime ?? getActiveRuntime() ?? defaultRuntime;
9894
- const registered = resolvedRuntime.getModelInstance(modelName);
9895
- if (!registered) {
9896
- throw new Error(
9897
- `Runtime model registry missing model "${modelName}". Pass a mongoose.Model instance to createRouter() or register it with registerModelInstance() before using this runtime.`
9898
- );
9899
- }
9900
- this.mongooseModel = registered;
9901
- if (!this.mongooseModel) return;
9902
- }
9903
- new() {
9904
- const doc = new this.mongooseModel();
9905
- return doc;
9906
- }
9907
- create(data) {
9908
- return this.mongooseModel.create(data);
9909
- }
9910
- find({ filter: filter2, select, sort, populate, limit, hardLimit, skip, lean }) {
9911
- const builder = this.mongooseModel.find(filter2);
9912
- if (select) builder.select(select);
9913
- if (skip) builder.skip(Number(skip));
9914
- const normalizedLimit = Number(limit);
9915
- if (Number.isSafeInteger(normalizedLimit) && normalizedLimit > 0) {
9916
- builder.limit(normalizedLimit);
9917
- } else if (Number.isSafeInteger(hardLimit) && Number(hardLimit) > 0) {
9918
- builder.limit(Number(hardLimit));
9919
- }
9920
- if (sort) builder.sort(sort);
9921
- if (populate) builder.populate(populate);
9922
- if (lean) builder.lean();
9923
- return builder;
9924
- }
9925
- findOne({ filter: filter2, select, sort, populate, lean }) {
9926
- const builder = this.mongooseModel.findOne(filter2);
9927
- if (select) builder.select(select);
9928
- if (sort) builder.sort(sort);
9929
- if (populate) builder.populate(populate);
9930
- if (lean) builder.lean();
9931
- return builder;
9932
- }
9933
- exists(filter2) {
9934
- if (!filter2) return null;
9935
- return this.findOne({ filter: filter2 }).select("_id").lean();
9936
- }
9937
- // see https://mongoosejs.com/docs/api.html#query_Query-countDocuments
9938
- countDocuments(filter2 = {}) {
9939
- return this.mongooseModel.countDocuments(filter2);
9940
- }
9941
- /** Cast a copy using this model's query schema/setters, without executing query middleware or persistence. */
9942
- castFilter(filter2) {
9943
- const query = this.mongooseModel.countDocuments(cloneDeep3(filter2));
9944
- return query.cast(this.mongooseModel);
9945
- }
9946
- // see https://mongoosejs.com/docs/api.html#model_Model.distinct
9947
- distinct(field, conditions = {}) {
9948
- return this.mongooseModel.distinct(field, conditions);
9949
- }
9950
- aggregate(pipeline) {
9951
- return this.mongooseModel.aggregate(pipeline);
9952
- }
9953
- };
9954
- var model_default = Model;
9955
-
9956
10283
  // src/acl/distinct-field-authorization.ts
9957
10284
  init_field_authorization();
9958
10285
  init_field_catalog();
@@ -10090,6 +10417,7 @@ init_finalize_model_output();
10090
10417
  init_populate_target();
10091
10418
  init_virtual_populate_execution();
10092
10419
  init_request_work();
10420
+ init_populate_policy2();
10093
10421
  var populateExecutors = /* @__PURE__ */ new WeakMap();
10094
10422
  function registerSubdocumentPopulateExecutor(service, execute2, core) {
10095
10423
  populateExecutors.set(service, { execute: execute2, core });
@@ -10122,7 +10450,7 @@ function prepareSubdocumentOutput(service, sub, operation, virtualAccess, output
10122
10450
  service.getServiceModelName(),
10123
10451
  { populate },
10124
10452
  0,
10125
- configuration
10453
+ getCapturedPopulatePolicyDefaults(configuration)
10126
10454
  ),
10127
10455
  void 0,
10128
10456
  configuration,
@@ -11161,12 +11489,15 @@ var Service = class extends Base {
11161
11489
  model: this.model.mongooseModel,
11162
11490
  modelName: this.modelName
11163
11491
  }),
11164
- configuration: () => this.requestRuntime.getModelInstance(this.modelName) ? captureModelAuthorizationConfiguration(
11165
- this.requestRuntime,
11166
- this.modelName,
11167
- { ...this.options, defaults: this.defaults },
11168
- modelServiceGlobalOptions(this, this.requestRuntime)
11169
- ) : { catalog: { paths: [] }, ...this.options },
11492
+ configuration: () => {
11493
+ const populatePolicyDefaults = modelServicePopulatePolicyDefaults(this, this.requestRuntime);
11494
+ return this.requestRuntime.getModelInstance(this.modelName) ? captureModelAuthorizationConfiguration(
11495
+ this.requestRuntime,
11496
+ this.modelName,
11497
+ { ...this.options, defaults: this.defaults },
11498
+ populatePolicyDefaults
11499
+ ) : { catalog: { paths: [] }, ...this.options, populatePolicyDefaults };
11500
+ },
11170
11501
  permissions: () => this.requestCore.getPermissions?.() ?? new permission_default({}),
11171
11502
  parse: (filter2) => this.parseClientData(filter2, this.getCorrelatedExecState().scheduler),
11172
11503
  validate: (filter2, expanded) => {
@@ -11215,7 +11546,7 @@ var Service = class extends Base {
11215
11546
  });
11216
11547
  }
11217
11548
  get options() {
11218
- return modelServiceOptions(this, () => this.getModelRouterOptions(this.modelName));
11549
+ return modelServiceOptions(this, this.requestRuntime, () => this.getModelRouterOptions(this.modelName));
11219
11550
  }
11220
11551
  /**
11221
11552
  * Presentation/query defaults for this service instance; an explicit assignment
@@ -11700,14 +12031,14 @@ var Service = class extends Base {
11700
12031
  }
11701
12032
  });
11702
12033
  }
11703
- captureRelated(args, defaults) {
11704
- const globalOptions = modelServiceGlobalOptions(this, this.requestRuntime);
11705
- const effective = { populate: args?.populate ?? defaults?.populate, include: args?.include ?? defaults?.include };
12034
+ captureRelated(args, defaults2) {
12035
+ const populatePolicyDefaults = modelServicePopulatePolicyDefaults(this, this.requestRuntime);
12036
+ const effective = { populate: args?.populate ?? defaults2?.populate, include: args?.include ?? defaults2?.include };
11706
12037
  if (effective.include) {
11707
12038
  const processed = this.processInclude(effective.include);
11708
12039
  effective.include = [...processed.includes, ...processed.correlatedIncludes];
11709
12040
  }
11710
- return captureRelatedTargets(this.requestRuntime, this.modelName, effective, 0, globalOptions);
12041
+ return captureRelatedTargets(this.requestRuntime, this.modelName, effective, 0, populatePolicyDefaults);
11711
12042
  }
11712
12043
  /** Canonical population uses the target's retained policy for both fetch and output. */
11713
12044
  async genExecutionPopulate(execution, access, populate) {
@@ -11733,7 +12064,12 @@ var Service = class extends Base {
11733
12064
  const modelName = target?.modelName;
11734
12065
  if (!modelName) continue;
11735
12066
  const policy = relatedPolicy(state.authorization, state.binding, descriptor.path);
11736
- const svc = this.requestCore.getPublicService(modelName);
12067
+ const svc = withCapturedPopulateModel(
12068
+ this.requestRuntime,
12069
+ modelName,
12070
+ target.model,
12071
+ () => this.requestCore.getPublicService(modelName)
12072
+ );
11737
12073
  const child = createRelatedExecution(
11738
12074
  svc,
11739
12075
  {
@@ -11778,8 +12114,8 @@ var Service = class extends Base {
11778
12114
  snapshot: readServiceAuthorization(childState.authorization, childState.binding).configuration,
11779
12115
  fetchBinding: {
11780
12116
  runtime: this.requestRuntime,
11781
- model: childState.binding.model,
11782
- schema: childState.binding.model.schema,
12117
+ model: target.model,
12118
+ schema: target.model.schema,
11783
12119
  configuration: targetConfiguration,
11784
12120
  requestRead: targetAccess === "read" && policy?.operation.mode !== "grant" && readServiceAuthorization(childState.authorization, childState.binding).authorization.rows.mode === "request",
11785
12121
  staticObjectIdReference: captured.relatedTargets.find((target2) => target2.path === descriptor.path)?.staticObjectIdReference
@@ -14636,9 +14972,20 @@ var Core = class {
14636
14972
  if (!isString6(p)) assertPopulateAccess(p.access);
14637
14973
  }
14638
14974
  const runtime = this.requestRuntime;
14639
- const globalOptions = modelServiceGlobalOptions(this, runtime);
14640
- const relatedTargets = captureRelatedTargets(runtime, modelName, { populate: descriptors }, 0, globalOptions);
14641
- const sourceConfiguration = captureModelAuthorizationConfiguration(runtime, modelName, void 0, globalOptions);
14975
+ const populatePolicyDefaults = modelServicePopulatePolicyDefaults(this, runtime);
14976
+ const relatedTargets = captureRelatedTargets(
14977
+ runtime,
14978
+ modelName,
14979
+ { populate: descriptors },
14980
+ 0,
14981
+ populatePolicyDefaults
14982
+ );
14983
+ const sourceConfiguration = captureModelAuthorizationConfiguration(
14984
+ runtime,
14985
+ modelName,
14986
+ void 0,
14987
+ populatePolicyDefaults
14988
+ );
14642
14989
  const originalPermissions = this.getGlobalPermissions();
14643
14990
  const permissions = new permission_default(
14644
14991
  Object.fromEntries(originalPermissions.keys.map((key) => [key, originalPermissions.has(key)]))
@@ -14735,7 +15082,15 @@ var Core = class {
14735
15082
  docPermissionsAccess: planAccess,
14736
15083
  requestedSelect: originalSelect,
14737
15084
  plan: targetPlan,
14738
- snapshot: targetSnapshot
15085
+ snapshot: targetSnapshot,
15086
+ fetchBinding: {
15087
+ runtime,
15088
+ model: target.model,
15089
+ schema: target.model.schema,
15090
+ configuration: targetConfiguration,
15091
+ requestRead: populateAccess === "read",
15092
+ staticObjectIdReference: target.staticObjectIdReference
15093
+ }
14739
15094
  });
14740
15095
  return ret;
14741
15096
  })