@web-ts-toolkit/access-router 0.57.0 → 0.59.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.
Files changed (3) hide show
  1. package/index.js +1563 -947
  2. package/index.mjs +1375 -760
  3. package/package.json +3 -3
package/index.js CHANGED
@@ -3543,6 +3543,47 @@ function serviceAuthorizationInput(policy, targets) {
3543
3543
  }
3544
3544
  return { rows: policy.rows, outputFields: policy.outputFields, related };
3545
3545
  }
3546
+ function hasStableConfigurationCopies(value) {
3547
+ if (value === null || typeof value !== "object") return true;
3548
+ if (!Array.isArray(value) && Object.getPrototypeOf(value) !== Object.prototype) return false;
3549
+ return Object.values(value).every(hasStableConfigurationCopies);
3550
+ }
3551
+ function captureAuthorizationAccess(value) {
3552
+ const input = authorizationRecord(value, "access");
3553
+ const access = {};
3554
+ for (const key of ["operation", "rowAccess", "virtualAccess", "outputAccess", "docPermissionsAccess"]) {
3555
+ if (key === "rowAccess" && input[key] === void 0) continue;
3556
+ if (typeof input[key] !== "string") authorizationError(`invalid access.${key}`);
3557
+ access[key] = input[key];
3558
+ }
3559
+ return Object.freeze(access);
3560
+ }
3561
+ function captureAuthorizationCatalog(value) {
3562
+ const input = authorizationRecord(value, "catalog");
3563
+ const catalog = {};
3564
+ for (const key of [
3565
+ "paths",
3566
+ "persistedPaths",
3567
+ "arrayPaths",
3568
+ "schemaVirtualPaths",
3569
+ "metadataPaths",
3570
+ "dynamicPaths",
3571
+ "containerPaths",
3572
+ "virtualPaths",
3573
+ "virtualScopePaths",
3574
+ "opaquePaths",
3575
+ "referencePaths",
3576
+ "protectedPaths"
3577
+ ]) {
3578
+ const paths = input[key];
3579
+ if (key !== "paths" && paths === void 0) continue;
3580
+ if (!Array.isArray(paths) || Array.from(paths).some((path) => typeof path !== "string")) {
3581
+ authorizationError(`invalid catalog.${key}`);
3582
+ }
3583
+ catalog[key] = paths;
3584
+ }
3585
+ return Object.freeze(catalog);
3586
+ }
3546
3587
  function assertAuthorizationPath(path) {
3547
3588
  if (typeof path !== "string" || !isSafeOutputPath(path)) {
3548
3589
  authorizationError(`invalid response path: ${String(path)}`);
@@ -3672,6 +3713,9 @@ function resolveServiceAuthorization(input) {
3672
3713
  const raw = copyAuthorizationValue(input.authorization);
3673
3714
  const configuration = copyAuthorizationValue(input.configuration, true);
3674
3715
  const targets = copyAuthorizationValue(input.relatedTargets ?? [], true);
3716
+ const access = copyAuthorizationValue(input.access);
3717
+ const outputAccess = captureAuthorizationAccess(access);
3718
+ const catalog = captureAuthorizationCatalog(configuration.catalog);
3675
3719
  const policy = copyAuthorizationValue(normalizePolicy(raw, input.applicability ?? "service", configuration, targets));
3676
3720
  const scopePath = Array.from(scope(input.binding));
3677
3721
  for (const part of scopePath) {
@@ -3684,17 +3728,21 @@ function resolveServiceAuthorization(input) {
3684
3728
  authorizationError("derived call request/runtime mismatch");
3685
3729
  }
3686
3730
  }
3687
- const permissions = Object.fromEntries(
3688
- input.requestPermissions.keys.map((key) => [key, input.requestPermissions.has(key)])
3731
+ const permissions = new permission_default(
3732
+ Object.fromEntries(input.requestPermissions.keys.map((key) => [key, input.requestPermissions.has(key) === true]))
3689
3733
  );
3734
+ for (const value of Object.values(permissions)) if (value && typeof value === "object") Object.freeze(value);
3735
+ Object.freeze(permissions);
3690
3736
  const call = Object.freeze(/* @__PURE__ */ Object.create(null));
3691
3737
  calls.set(call, {
3692
3738
  binding: Object.freeze({ ...input.binding, scopePath: Object.freeze(scopePath) }),
3693
- access: copyAuthorizationValue(input.access),
3739
+ access,
3694
3740
  configuration,
3695
3741
  policy,
3696
3742
  relatedTargets: targets,
3697
- permissions: Object.freeze(permissions),
3743
+ // normalizeFields constructs only mode strings and validated string paths.
3744
+ output: Object.freeze({ access: outputAccess, catalog, outputFields: policy.outputFields }),
3745
+ permissions,
3698
3746
  provenance: input.parent ? callRecord(input.parent).provenance : call
3699
3747
  });
3700
3748
  return call;
@@ -3712,12 +3760,84 @@ function readServiceAuthorization(call, binding) {
3712
3760
  true
3713
3761
  );
3714
3762
  }
3763
+ function readServiceAuthorizationAccess(call, binding) {
3764
+ assertAuthorizationBinding(call, binding);
3765
+ return callRecord(call).output.access;
3766
+ }
3767
+ function readServiceAuthorizationHydration(call, binding) {
3768
+ assertAuthorizationBinding(call, binding);
3769
+ return copyAuthorizationValue({ hydration: callRecord(call).configuration.hydration }, true);
3770
+ }
3771
+ function outputMetadata(configuration) {
3772
+ return {
3773
+ documentPermissionField: configuration.documentPermissionField,
3774
+ exposedDocPermissionKeys: configuration.exposedDocPermissionKeys,
3775
+ stripPermissionsField: configuration.stripPermissionsField,
3776
+ disableFieldPermissions: configuration.disableFieldPermissions
3777
+ };
3778
+ }
3779
+ function readServiceOutputMetadata(call, binding) {
3780
+ assertAuthorizationBinding(call, binding);
3781
+ return copyAuthorizationValue(outputMetadata(callRecord(call).configuration), true);
3782
+ }
3783
+ function readServiceDocumentPermissions(call, binding) {
3784
+ assertAuthorizationBinding(call, binding);
3785
+ const record3 = callRecord(call);
3786
+ return Object.freeze({
3787
+ catalog: record3.output.catalog,
3788
+ ...copyAuthorizationValue({ docPermissions: record3.configuration.docPermissions }, true)
3789
+ });
3790
+ }
3791
+ function readServiceFinalizerConfiguration(call, binding) {
3792
+ assertAuthorizationBinding(call, binding);
3793
+ const record3 = callRecord(call);
3794
+ return Object.freeze({
3795
+ catalog: record3.output.catalog,
3796
+ ...copyAuthorizationValue(
3797
+ {
3798
+ ...outputMetadata(record3.configuration),
3799
+ virtuals: record3.configuration.virtuals,
3800
+ docPermissions: record3.configuration.docPermissions
3801
+ },
3802
+ true
3803
+ )
3804
+ });
3805
+ }
3806
+ function readServiceOutputPolicy(call, binding) {
3807
+ assertAuthorizationBinding(call, binding);
3808
+ return callRecord(call).output;
3809
+ }
3810
+ function readServiceOutputFieldAuthorization(call, binding) {
3811
+ assertAuthorizationBinding(call, binding);
3812
+ const record3 = callRecord(call);
3813
+ const reusable = reusableOutputFieldConfiguration(record3);
3814
+ return Object.freeze({
3815
+ access: record3.output.access,
3816
+ catalog: record3.output.catalog,
3817
+ outputFields: record3.output.outputFields,
3818
+ reusable,
3819
+ ...copyAuthorizationValue(
3820
+ {
3821
+ permissionSchema: record3.configuration.permissionSchema,
3822
+ modelPermissionPrefix: record3.configuration.modelPermissionPrefix
3823
+ },
3824
+ true
3825
+ )
3826
+ });
3827
+ }
3828
+ function reusableOutputFieldConfiguration(record3) {
3829
+ return record3.reusableFieldConfiguration ??= hasStableConfigurationCopies(record3.configuration.permissionSchema) && // Coercion methods can observe an object's identity even without native
3830
+ // leaves. Keep those receivers local to the original resolution boundary.
3831
+ (record3.configuration.modelPermissionPrefix === null || typeof record3.configuration.modelPermissionPrefix !== "object");
3832
+ }
3833
+ function canPrepareStaticOutputPolicy(call, binding) {
3834
+ assertAuthorizationBinding(call, binding);
3835
+ const record3 = callRecord(call);
3836
+ return reusableOutputFieldConfiguration(record3) && typeof (record3.configuration.modelPermissionPrefix ?? "") === "string";
3837
+ }
3715
3838
  function getAuthorizationPermissions(call, binding) {
3716
3839
  assertAuthorizationBinding(call, binding);
3717
- const permission = new permission_default({ ...callRecord(call).permissions });
3718
- for (const value of Object.values(permission)) if (value && typeof value === "object") Object.freeze(value);
3719
- Object.freeze(permission);
3720
- return permission;
3840
+ return callRecord(call).permissions;
3721
3841
  }
3722
3842
  function getAuthorizationProvenance(call) {
3723
3843
  return callRecord(call).provenance;
@@ -3733,399 +3853,87 @@ var init_service_authorization = __esm({
3733
3853
  }
3734
3854
  });
3735
3855
 
3736
- // src/acl/document-authorization.ts
3737
- function normalizeOutputAuthorizationOptions(input, options, purpose) {
3738
- const value = authorizationRecord(options, "output options");
3739
- for (const key of Reflect.ownKeys(value)) {
3740
- const descriptor = Object.getOwnPropertyDescriptor(value, key);
3741
- if (typeof key !== "string" || !("value" in descriptor) || !descriptor.enumerable) {
3742
- authorizationError("invalid output option property");
3743
- }
3744
- }
3745
- assertAuthorizationKeys(
3746
- value,
3747
- ["authorization", "scopePath", "documentAuthorization", ...purpose ? ["purpose"] : []],
3748
- "output options"
3749
- );
3750
- if (purpose && value.purpose !== purpose) authorizationError("genAllowedFields requires purpose: output");
3751
- if (Object.prototype.hasOwnProperty.call(value, "documentAuthorization")) {
3752
- if (Object.prototype.hasOwnProperty.call(value, "authorization") || Object.prototype.hasOwnProperty.call(value, "scopePath")) {
3753
- authorizationError("document handle cannot be mixed with raw policy/scope");
3754
- }
3755
- const handle = value.documentAuthorization;
3756
- const stage = stageRecord(documentRecord(handle).stage);
3757
- const binding = Object.freeze({ ...input.binding, scopePath: stage.binding.scopePath });
3758
- assertAuthorizationBinding(stage.call, binding);
3759
- const access = readServiceAuthorization(stage.call, binding).access;
3760
- if (input.access.outputAccess !== access.outputAccess) authorizationError("document access mismatch");
3761
- return Object.freeze({ kind: "document", documentAuthorization: handle, binding });
3762
- }
3763
- if (value.scopePath !== void 0 && !Array.isArray(value.scopePath))
3764
- authorizationError("scopePath must be an array");
3765
- return Object.freeze({
3766
- kind: "policy",
3767
- authorization: resolveServiceAuthorization({
3768
- ...input,
3769
- binding: {
3770
- ...input.binding,
3771
- scopePath: copyAuthorizationValue(value.scopePath)
3772
- },
3773
- authorization: value.authorization,
3774
- applicability: "output"
3775
- })
3776
- });
3777
- }
3778
- function stageRecord(stage) {
3779
- const record3 = stages.get(stage);
3780
- if (!record3) authorizationError("invalid document stage");
3781
- if (!matchesAuthorizationSnapshot(record3.input, record3.snapshot)) authorizationError("changed document snapshot");
3782
- return record3;
3856
+ // src/acl/field-authorization.ts
3857
+ function extractScopedOutputRule(schema, field, access) {
3858
+ if (!schema || !Object.prototype.hasOwnProperty.call(schema, field)) return void 0;
3859
+ const raw = schema[field];
3860
+ return raw && typeof raw === "object" && !Array.isArray(raw) && Object.prototype.hasOwnProperty.call(raw, access) ? raw[access] : raw;
3783
3861
  }
3784
- function documentRecord(handle) {
3785
- const record3 = documents.get(handle);
3786
- if (!record3) authorizationError("invalid document handle");
3787
- stageRecord(record3.stage);
3788
- return record3;
3862
+ function extractOutputFieldRules(schema, path, access) {
3863
+ return extractOutputFieldRuleEntries(schema, path, access).map((entry) => entry.rule);
3789
3864
  }
3790
- function createDocumentAuthorizationStage(call, binding, projectedSnapshot) {
3791
- assertAuthorizationBinding(call, binding);
3792
- authorizationRecord(projectedSnapshot, "projected document snapshot");
3793
- const stage = Object.freeze(/* @__PURE__ */ Object.create(null));
3794
- stages.set(stage, {
3795
- call,
3796
- binding: Object.freeze({ ...binding, scopePath: Object.freeze([...binding.scopePath ?? []]) }),
3797
- input: projectedSnapshot,
3798
- snapshot: copyAuthorizationValue(projectedSnapshot, "document")
3799
- });
3800
- return stage;
3865
+ function extractOutputFieldRuleEntries(schema, path, access, prefix = "") {
3866
+ if (!schema) return [{ path: `${prefix}${path}`, rule: void 0 }];
3867
+ if (Object.prototype.hasOwnProperty.call(schema, path))
3868
+ return [{ path: `${prefix}${path}`, rule: extractScopedOutputRule(schema, path, access) }];
3869
+ const [head, ...rest] = path.split(".");
3870
+ const rule = extractScopedOutputRule(schema, head, access);
3871
+ const raw = schema[head];
3872
+ const entry = { path: `${prefix}${head}`, rule };
3873
+ if (!rest.length || !raw?.sub) return [entry];
3874
+ return [entry, ...extractOutputFieldRuleEntries(raw.sub, rest.join("."), access, `${prefix}${head}.`)];
3801
3875
  }
3802
- function assertDocumentAuthorizationStage(stage, call, binding, projectedSnapshot) {
3803
- const record3 = stageRecord(stage);
3804
- assertAuthorizationBinding(record3.call, binding);
3805
- if (record3.call !== call || record3.input !== projectedSnapshot || !matchesAuthorizationSnapshot(projectedSnapshot, record3.snapshot)) {
3806
- authorizationError("document call/stage/snapshot mismatch");
3807
- }
3876
+ function hasExplicitFieldGrant(policy, path) {
3877
+ return policy?.mode === "unrestricted" || policy?.mode === "grant" && policy.paths.some((grant) => path === grant || path.startsWith(`${grant}.`));
3808
3878
  }
3809
- function resolveDocumentAuthorization(stage, resolveGrants) {
3810
- const record3 = stageRecord(stage);
3811
- if (!record3.result) {
3812
- record3.result = Promise.resolve().then(async () => {
3813
- stageRecord(stage);
3814
- const result2 = resolveGrants.call(
3815
- record3.binding.request,
3816
- copyAuthorizationValue(record3.snapshot, "document"),
3817
- getAuthorizationPermissions(record3.call, record3.binding)
3818
- );
3819
- const grants = result2 && typeof result2.then === "function" ? await result2 : result2;
3820
- stageRecord(stage);
3821
- const ownedGrants = copyAuthorizationValue(authorizationRecord(grants, "document grants"));
3822
- const handle = Object.freeze(/* @__PURE__ */ Object.create(null));
3823
- documents.set(handle, { stage, grants: ownedGrants, decisions: /* @__PURE__ */ new Map() });
3824
- return handle;
3825
- });
3826
- }
3827
- return record3.result;
3879
+ function classifyRequestFieldRule(rule, permissions, modelPermissionPrefix = "") {
3880
+ if (typeof rule === "boolean") return rule ? "granted" : "denied";
3881
+ if (typeof rule === "function") return "deferred";
3882
+ const validator = createValidator((key) => permissions.has(key));
3883
+ if (typeof rule !== "string" && !Array.isArray(rule)) return "denied";
3884
+ if (typeof rule === "string" ? validator.stringHandler(rule) : validator.arrayHandler(rule)) return "granted";
3885
+ const possible = createValidator(
3886
+ (key) => permissions.has(key) || !modelPermissionPrefix || key.startsWith(modelPermissionPrefix)
3887
+ );
3888
+ return (typeof rule === "string" ? possible.stringHandler(rule) : possible.arrayHandler(rule)) ? "deferred" : "denied";
3828
3889
  }
3829
- function readDocumentAuthorization(handle, binding) {
3830
- const record3 = documentRecord(handle);
3831
- const stage = stageRecord(record3.stage);
3832
- assertAuthorizationBinding(stage.call, binding);
3833
- return Object.freeze({
3834
- authorization: stage.call,
3835
- stage: record3.stage,
3836
- grants: copyAuthorizationValue(record3.grants),
3837
- ...readServiceAuthorization(stage.call, binding).access
3838
- });
3890
+ function prepareRequestFieldRule(rule, permissions, modelPermissionPrefix = "") {
3891
+ const state = classifyRequestFieldRule(rule, permissions, modelPermissionPrefix);
3892
+ const invariant = state === "denied" && modelPermissionPrefix ? classifyRequestFieldRule(rule, permissions) : state;
3893
+ return Object.freeze({ state, decision: invariant === "deferred" ? void 0 : invariant === "granted" });
3839
3894
  }
3840
- function memoizeDocumentFieldDecision(handle, binding, field, evaluate) {
3841
- const record3 = documentRecord(handle);
3842
- const stage = stageRecord(record3.stage);
3843
- assertAuthorizationBinding(stage.call, binding);
3844
- let decision = record3.decisions.get(field);
3845
- if (!decision) {
3846
- decision = Promise.resolve().then(async () => {
3847
- stageRecord(record3.stage);
3848
- const result2 = await evaluate.call(
3849
- stage.binding.request,
3850
- getAuthorizationPermissions(stage.call, binding),
3851
- copyAuthorizationValue(record3.grants)
3852
- );
3853
- stageRecord(record3.stage);
3854
- if (typeof result2 !== "boolean") authorizationError("field decision must be boolean");
3855
- return result2;
3856
- });
3857
- record3.decisions.set(field, decision);
3858
- }
3859
- return decision;
3895
+ function combineFieldAuthorizationStates(states2) {
3896
+ return states2.includes("denied") ? "denied" : states2.includes("deferred") ? "deferred" : "granted";
3860
3897
  }
3861
- function unchangedOutput(output, record3) {
3862
- if (!matchesAuthorizationSnapshot(output, record3.snapshot)) return false;
3863
- const identities = outputIdentities(output);
3864
- return identities.length === record3.identities.length && identities.every((identity, i) => identity === record3.identities[i]);
3898
+ function classifyEffectiveFieldAuthorization(args) {
3899
+ if (hasExplicitFieldGrant(args.outputFields, args.path)) return "granted";
3900
+ const states2 = args.rules.map(
3901
+ (rule) => classifyRequestFieldRule(rule, args.globalPermissions, args.modelPermissionPrefix)
3902
+ );
3903
+ return combineFieldAuthorizationStates(states2);
3865
3904
  }
3866
- function assertDocumentAuthorization(handle, use) {
3867
- const record3 = documentRecord(handle);
3868
- const stage = stageRecord(record3.stage);
3869
- assertAuthorizationBinding(stage.call, use.binding);
3870
- if (use.authorization !== void 0 && stage.call !== use.authorization || use.stage !== void 0 && record3.stage !== use.stage || readServiceAuthorization(stage.call, use.binding).access.outputAccess !== use.outputAccess) {
3871
- authorizationError("document call/access/stage mismatch");
3872
- }
3873
- const association = outputs.get(use.output);
3874
- if (!association || association.handle !== handle || !unchangedOutput(use.output, association)) {
3875
- authorizationError("unknown, replaced or mutated authorized output");
3905
+ async function evaluateScopedAccessRule(args) {
3906
+ const { req, rule, globalPermissions, docPermissions, modelPermissionPrefix } = args;
3907
+ if (typeof rule === "boolean") return rule;
3908
+ const validator = createValidator((key) => {
3909
+ try {
3910
+ if (globalPermissions?.has(key)) return true;
3911
+ } catch {
3912
+ }
3913
+ try {
3914
+ return Boolean((docPermissions ?? {})[stripModelPermissionPrefix(key, modelPermissionPrefix)]);
3915
+ } catch {
3916
+ return false;
3917
+ }
3918
+ });
3919
+ if (typeof rule === "string") return validator.stringHandler(rule);
3920
+ if (Array.isArray(rule)) return validator.arrayHandler(rule);
3921
+ if (typeof rule === "function") {
3922
+ try {
3923
+ return Boolean(await rule.call(req, globalPermissions, docPermissions));
3924
+ } catch {
3925
+ return false;
3926
+ }
3876
3927
  }
3928
+ return false;
3877
3929
  }
3878
- function associateDocumentAuthorization(handle, binding, output) {
3879
- const record3 = documentRecord(handle);
3880
- assertAuthorizationBinding(stageRecord(record3.stage).call, binding);
3881
- if (!output || typeof output !== "object") authorizationError("output must be an object");
3882
- if (outputs.has(output)) {
3883
- const previous = outputs.get(output);
3884
- if (previous.handle !== handle || !unchangedOutput(output, previous))
3885
- authorizationError("output already associated");
3886
- return;
3930
+ async function evaluateEffectiveFieldAuthorization(args) {
3931
+ if (hasExplicitFieldGrant(args.outputFields, args.path)) return true;
3932
+ for (const [index, rule] of args.rules.entries()) {
3933
+ if (!await (args.evaluateRule ? args.evaluateRule(rule, index) : evaluateScopedAccessRule({ ...args, rule })))
3934
+ return false;
3887
3935
  }
3888
- outputs.set(output, {
3889
- handle,
3890
- snapshot: copyAuthorizationValue(output, "document"),
3891
- identities: outputIdentities(output)
3892
- });
3893
- }
3894
- function transferDocumentAuthorization(handle, use, copy) {
3895
- assertDocumentAuthorization(handle, use);
3896
- associateDocumentAuthorization(handle, use.binding, copy);
3897
- }
3898
- function isKnownAuthorizationOutput(output) {
3899
- return outputs.has(output);
3900
- }
3901
- function getAssociatedDocumentAuthorization(output, call) {
3902
- const record3 = outputs.get(output);
3903
- if (!record3 || !unchangedOutput(output, record3)) return void 0;
3904
- const stage = stageRecord(documentRecord(record3.handle).stage);
3905
- if (call && getAuthorizationProvenance(stage.call) !== getAuthorizationProvenance(call)) return void 0;
3906
- return record3.handle;
3907
- }
3908
- function transferDocumentAuthorizationGraph(source, copy, copyOrigins) {
3909
- const seen = /* @__PURE__ */ new WeakSet();
3910
- const visit = (source2, copy2) => {
3911
- if (!copy2 || typeof copy2 !== "object" || seen.has(copy2)) return;
3912
- seen.add(copy2);
3913
- source2 = copyOrigins?.get(copy2) ?? source2;
3914
- if (source2 instanceof import_mongoose5.Document) source2 = source2._doc;
3915
- const original = source2 && typeof source2 === "object" ? source2 : void 0;
3916
- if (!original && !copyOrigins) return;
3917
- const association = original && outputs.get(original);
3918
- if (association) {
3919
- const stage = stageRecord(documentRecord(association.handle).stage);
3920
- transferDocumentAuthorization(
3921
- association.handle,
3922
- {
3923
- binding: stage.binding,
3924
- output: original,
3925
- outputAccess: readServiceAuthorization(stage.call, stage.binding).access.outputAccess,
3926
- authorization: stage.call,
3927
- stage: documentRecord(association.handle).stage
3928
- },
3929
- copy2
3930
- );
3931
- }
3932
- for (const key of Object.keys(copy2)) {
3933
- const descriptor = original && Object.getOwnPropertyDescriptor(original, key);
3934
- if (descriptor && "value" in descriptor) {
3935
- visit(descriptor.value, copy2[key]);
3936
- } else if (copyOrigins) {
3937
- visit(void 0, copy2[key]);
3938
- }
3939
- }
3940
- };
3941
- visit(source, copy);
3942
- }
3943
- function createServiceOutputContext(diagnostic, handle, use) {
3944
- assertDocumentAuthorization(handle, use);
3945
- const rootOutput = use.output;
3946
- const root = outputs.get(rootOutput);
3947
- const graph = new Set(root.identities);
3948
- const call = stageRecord(documentRecord(handle).stage).call;
3949
- const context = { ...diagnostic };
3950
- Object.defineProperties(context, {
3951
- documentAuthorization: { value: handle, enumerable: false, writable: false, configurable: false },
3952
- getDocumentAuthorization: {
3953
- enumerable: false,
3954
- writable: false,
3955
- configurable: false,
3956
- value(output) {
3957
- if (!graph.has(output) || !unchangedOutput(rootOutput, root)) return void 0;
3958
- const association = outputs.get(output);
3959
- if (!association || !unchangedOutput(output, association)) return void 0;
3960
- try {
3961
- documentRecord(handle);
3962
- const child = stageRecord(documentRecord(association.handle).stage);
3963
- if (getAuthorizationProvenance(child.call) !== getAuthorizationProvenance(call)) return void 0;
3964
- return association.handle;
3965
- } catch {
3966
- return void 0;
3967
- }
3968
- }
3969
- }
3970
- });
3971
- return context;
3972
- }
3973
- var import_mongoose5, stages, documents, outputs;
3974
- var init_document_authorization = __esm({
3975
- "src/acl/document-authorization.ts"() {
3976
- import_mongoose5 = require("mongoose");
3977
- init_service_authorization();
3978
- init_authorization_snapshot();
3979
- stages = /* @__PURE__ */ new WeakMap();
3980
- documents = /* @__PURE__ */ new WeakMap();
3981
- outputs = /* @__PURE__ */ new WeakMap();
3982
- }
3983
- });
3984
-
3985
- // src/output/include-output.ts
3986
- function prepareIncludeOutput(doc) {
3987
- if (stateFor(doc)) return doc;
3988
- const source = isolateDocForOutput(doc);
3989
- transferDocumentAuthorizationGraph(doc, source);
3990
- const working = deepIsolateValue(source);
3991
- outputs2.set(working, { original: doc, source, attachments: [] });
3992
- return working;
3993
- }
3994
- function attachIncludeOutput(doc, path, value) {
3995
- const state = stateFor(doc);
3996
- if (!state) throw new Error("Include attachment requires a prepared output row");
3997
- state.attachments.push({ path, value });
3998
- (0, import_utils19.set)(doc, path, deepIsolateValue(value));
3999
- }
4000
- function getIncludeSource(doc) {
4001
- return stateFor(doc)?.source ?? doc;
4002
- }
4003
- function getIncludeOriginal(doc) {
4004
- return stateFor(doc)?.original ?? doc;
4005
- }
4006
- function restoreIncludeOutput(doc, output) {
4007
- const attachments = stateFor(doc)?.attachments;
4008
- if (!attachments?.length) return void 0;
4009
- const origins = /* @__PURE__ */ new WeakMap();
4010
- for (const { path, value } of attachments) {
4011
- const copy = deepIsolateValue(value);
4012
- if (copy !== null && typeof copy === "object") origins.set(copy, value);
4013
- (0, import_utils19.set)(output, path, copy);
4014
- }
4015
- return origins;
4016
- }
4017
- var import_utils19, outputs2, stateFor;
4018
- var init_include_output = __esm({
4019
- "src/output/include-output.ts"() {
4020
- import_utils19 = require("@web-ts-toolkit/utils");
4021
- init_document_authorization();
4022
- init_document();
4023
- outputs2 = /* @__PURE__ */ new WeakMap();
4024
- stateFor = (doc) => doc !== null && typeof doc === "object" ? outputs2.get(doc) : void 0;
4025
- }
4026
- });
4027
-
4028
- // src/helpers/request-work.ts
4029
- function getRequestWorkState(req, runtime) {
4030
- let owners = states.get(req);
4031
- if (!owners) {
4032
- owners = /* @__PURE__ */ new WeakMap();
4033
- states.set(req, owners);
4034
- }
4035
- let state = owners.get(runtime);
4036
- if (!state) {
4037
- const limits = resolveRequestComplexity(runtime.getGlobalOption("requestComplexity"));
4038
- state = {
4039
- totalQueries: 0,
4040
- scheduler: new RequestConcurrencyScheduler(limits.maxBulkConcurrency),
4041
- hookGate: new SharedHookGate(limits.maxHookConcurrency)
4042
- };
4043
- owners.set(runtime, state);
4044
- }
4045
- return state;
4046
- }
4047
- var states;
4048
- var init_request_work = __esm({
4049
- "src/helpers/request-work.ts"() {
4050
- init_request_complexity();
4051
- init_concurrency();
4052
- states = /* @__PURE__ */ new WeakMap();
4053
- }
4054
- });
4055
-
4056
- // src/acl/field-authorization.ts
4057
- function extractScopedOutputRule(schema, field, access) {
4058
- if (!schema || !Object.prototype.hasOwnProperty.call(schema, field)) return void 0;
4059
- const raw = schema[field];
4060
- return raw && typeof raw === "object" && !Array.isArray(raw) && Object.prototype.hasOwnProperty.call(raw, access) ? raw[access] : raw;
4061
- }
4062
- function extractOutputFieldRules(schema, path, access) {
4063
- return extractOutputFieldRuleEntries(schema, path, access).map((entry) => entry.rule);
4064
- }
4065
- function extractOutputFieldRuleEntries(schema, path, access, prefix = "") {
4066
- if (!schema) return [{ path: `${prefix}${path}`, rule: void 0 }];
4067
- if (Object.prototype.hasOwnProperty.call(schema, path))
4068
- return [{ path: `${prefix}${path}`, rule: extractScopedOutputRule(schema, path, access) }];
4069
- const [head, ...rest] = path.split(".");
4070
- const rule = extractScopedOutputRule(schema, head, access);
4071
- const raw = schema[head];
4072
- const entry = { path: `${prefix}${head}`, rule };
4073
- if (!rest.length || !raw?.sub) return [entry];
4074
- return [entry, ...extractOutputFieldRuleEntries(raw.sub, rest.join("."), access, `${prefix}${head}.`)];
4075
- }
4076
- function hasExplicitFieldGrant(policy, path) {
4077
- return policy?.mode === "unrestricted" || policy?.mode === "grant" && policy.paths.some((grant) => path === grant || path.startsWith(`${grant}.`));
4078
- }
4079
- function classifyRequestFieldRule(rule, permissions, modelPermissionPrefix = "") {
4080
- if (typeof rule === "boolean") return rule ? "granted" : "denied";
4081
- if (typeof rule === "function") return "deferred";
4082
- const validator = createValidator((key) => permissions.has(key));
4083
- if (typeof rule !== "string" && !Array.isArray(rule)) return "denied";
4084
- if (typeof rule === "string" ? validator.stringHandler(rule) : validator.arrayHandler(rule)) return "granted";
4085
- const possible = createValidator(
4086
- (key) => permissions.has(key) || !modelPermissionPrefix || key.startsWith(modelPermissionPrefix)
4087
- );
4088
- return (typeof rule === "string" ? possible.stringHandler(rule) : possible.arrayHandler(rule)) ? "deferred" : "denied";
4089
- }
4090
- function classifyEffectiveFieldAuthorization(args) {
4091
- if (hasExplicitFieldGrant(args.outputFields, args.path)) return "granted";
4092
- const states2 = args.rules.map(
4093
- (rule) => classifyRequestFieldRule(rule, args.globalPermissions, args.modelPermissionPrefix)
4094
- );
4095
- return states2.includes("denied") ? "denied" : states2.includes("deferred") ? "deferred" : "granted";
4096
- }
4097
- async function evaluateScopedAccessRule(args) {
4098
- const { req, rule, globalPermissions, docPermissions, modelPermissionPrefix } = args;
4099
- if (typeof rule === "boolean") return rule;
4100
- const validator = createValidator((key) => {
4101
- try {
4102
- if (globalPermissions?.has(key)) return true;
4103
- } catch {
4104
- }
4105
- try {
4106
- return Boolean((docPermissions ?? {})[stripModelPermissionPrefix(key, modelPermissionPrefix)]);
4107
- } catch {
4108
- return false;
4109
- }
4110
- });
4111
- if (typeof rule === "string") return validator.stringHandler(rule);
4112
- if (Array.isArray(rule)) return validator.arrayHandler(rule);
4113
- if (typeof rule === "function") {
4114
- try {
4115
- return Boolean(await rule.call(req, globalPermissions, docPermissions));
4116
- } catch {
4117
- return false;
4118
- }
4119
- }
4120
- return false;
4121
- }
4122
- async function evaluateEffectiveFieldAuthorization(args) {
4123
- if (hasExplicitFieldGrant(args.outputFields, args.path)) return true;
4124
- for (const [index, rule] of args.rules.entries()) {
4125
- if (!await (args.evaluateRule ? args.evaluateRule(rule, index) : evaluateScopedAccessRule({ ...args, rule })))
4126
- return false;
4127
- }
4128
- return true;
3936
+ return true;
4129
3937
  }
4130
3938
  var stripModelPermissionPrefix;
4131
3939
  var init_field_authorization = __esm({
@@ -4359,10 +4167,10 @@ function planVirtualProjection(args) {
4359
4167
  relatedPlans
4360
4168
  };
4361
4169
  }
4362
- var import_utils21, getScopedPermissionSchema, resolveAlwaysSelectForAccess, stripVirtualsFromNormalizedSelect, snapshotVirtualPaths, stripLeadingDash, dbPrefixForScope, toDbPath;
4170
+ var import_utils19, getScopedPermissionSchema, resolveAlwaysSelectForAccess, stripVirtualsFromNormalizedSelect, snapshotVirtualPaths, stripLeadingDash, dbPrefixForScope, toDbPath;
4363
4171
  var init_virtual_projection = __esm({
4364
4172
  "src/acl/virtual-projection.ts"() {
4365
- import_utils21 = require("@web-ts-toolkit/utils");
4173
+ import_utils19 = require("@web-ts-toolkit/utils");
4366
4174
  init_query();
4367
4175
  init_field_authorization();
4368
4176
  init_output_projection();
@@ -4370,20 +4178,20 @@ var init_virtual_projection = __esm({
4370
4178
  init_virtual_populate_dependencies();
4371
4179
  init_virtual_descriptor();
4372
4180
  getScopedPermissionSchema = (root, scopePath) => {
4373
- if (!root || !(0, import_utils21.isPlainObject)(root)) return null;
4181
+ if (!root || !(0, import_utils19.isPlainObject)(root)) return null;
4374
4182
  if (scopePath.length === 0) return root;
4375
- const scoped = (0, import_utils21.get)(root, scopePath.join("."));
4376
- return (0, import_utils21.isPlainObject)(scoped) ? scoped : null;
4183
+ const scoped = (0, import_utils19.get)(root, scopePath.join("."));
4184
+ return (0, import_utils19.isPlainObject)(scoped) ? scoped : null;
4377
4185
  };
4378
4186
  resolveAlwaysSelectForAccess = (raw, access) => {
4379
4187
  if (!raw) return [];
4380
- if ((0, import_utils21.isArray)(raw)) return [...raw];
4381
- if ((0, import_utils21.isPlainObject)(raw)) {
4188
+ if ((0, import_utils19.isArray)(raw)) return [...raw];
4189
+ if ((0, import_utils19.isPlainObject)(raw)) {
4382
4190
  const record3 = raw;
4383
4191
  const exact = record3[access];
4384
- if ((0, import_utils21.isArray)(exact)) return [...exact];
4192
+ if ((0, import_utils19.isArray)(exact)) return [...exact];
4385
4193
  const def = record3.default;
4386
- if ((0, import_utils21.isArray)(def)) return [...def];
4194
+ if ((0, import_utils19.isArray)(def)) return [...def];
4387
4195
  return [];
4388
4196
  }
4389
4197
  return [];
@@ -4408,6 +4216,34 @@ var init_virtual_projection = __esm({
4408
4216
  });
4409
4217
 
4410
4218
  // src/acl/output-projection.ts
4219
+ function copyOutputDecisionFields(value) {
4220
+ if (!Array.isArray(value) || import_node_util4.types.isProxy(value) || Object.getPrototypeOf(value) !== Array.prototype) return;
4221
+ const length = Object.getOwnPropertyDescriptor(value, "length").value;
4222
+ if (length > 2e4) return;
4223
+ const fields = [];
4224
+ for (let index = 0; index < length; index++) {
4225
+ const slot = Object.getOwnPropertyDescriptor(value, String(index));
4226
+ if (!slot || !("value" in slot) || typeof slot.value !== "string") return;
4227
+ fields.push(slot.value);
4228
+ }
4229
+ return Object.freeze(fields);
4230
+ }
4231
+ function readStaticOutputPlanFields(plan, authorization) {
4232
+ const record3 = staticPlanFields.get(plan);
4233
+ if (!record3 || record3.authorization !== authorization || import_node_util4.types.isProxy(plan)) return;
4234
+ const ownValue2 = (key) => {
4235
+ const slot = Object.getOwnPropertyDescriptor(plan, key);
4236
+ return slot && "value" in slot ? slot.value : void 0;
4237
+ };
4238
+ if (ownValue2("authorization") !== authorization || ownValue2("authorizationBinding") !== record3.binding) return;
4239
+ const children = ownValue2("childPlans");
4240
+ if (children !== record3.children || import_node_util4.types.isProxy(children) || Reflect.ownKeys(children).length) return;
4241
+ const persisted = copyOutputDecisionFields(ownValue2("outputPersistedFields"));
4242
+ const virtuals = copyOutputDecisionFields(ownValue2("outputVirtualNames"));
4243
+ const same = (a, b) => a?.length === b.length && a.every((field, index) => field === b[index]);
4244
+ if (!same(persisted, record3.persisted) || !same(virtuals, record3.virtuals)) return;
4245
+ return Object.freeze([.../* @__PURE__ */ new Set([...record3.persisted, ...record3.virtuals])]);
4246
+ }
4411
4247
  function compactPersistedProjection(paths) {
4412
4248
  const unique = [...new Set(paths.filter((p) => p && !p.startsWith("-")))];
4413
4249
  return unique.filter((path) => !unique.some((parent) => parent !== path && path.startsWith(`${parent}.`)));
@@ -4436,6 +4272,13 @@ function planAuthorizedModelProjection(args) {
4436
4272
  );
4437
4273
  plan.authorization = args.authorization;
4438
4274
  plan.authorizationBinding = Object.freeze({ ...args.binding, scopePath: Object.freeze(scope2) });
4275
+ staticPlanFields.set(plan, {
4276
+ authorization: args.authorization,
4277
+ binding: plan.authorizationBinding,
4278
+ persisted: Object.freeze([...plan.outputPersistedFields]),
4279
+ virtuals: Object.freeze([...plan.outputVirtualNames]),
4280
+ children: plan.childPlans
4281
+ });
4439
4282
  return plan;
4440
4283
  }
4441
4284
  function planCatalogProjection(args, outputFields = { mode: "request" }) {
@@ -4533,123 +4376,763 @@ function planCatalogProjection(args, outputFields = { mode: "request" }) {
4533
4376
  outputAccess
4534
4377
  });
4535
4378
  }
4536
- const ancestors = /* @__PURE__ */ new Set();
4537
- for (const path of [...persisted, ...allVirtuals]) {
4538
- const parts = path.split(".");
4539
- for (let i = 1; i < parts.length; i++) ancestors.add(parts.slice(0, i).join("."));
4379
+ const ancestors = /* @__PURE__ */ new Set();
4380
+ for (const path of [...persisted, ...allVirtuals]) {
4381
+ const parts = path.split(".");
4382
+ for (let i = 1; i < parts.length; i++) ancestors.add(parts.slice(0, i).join("."));
4383
+ }
4384
+ const children = {};
4385
+ for (const name of [...ancestors].filter((p) => !p.includes("."))) {
4386
+ const childIncludes = includes.filter((p) => p.startsWith(`${name}.`)).map((p) => p.slice(name.length + 1));
4387
+ const childExcludes = excludes.filter((p) => p.startsWith(`${name}.`)).map((p) => `-${p.slice(name.length + 1)}`);
4388
+ const childSelect = mode === "include" && !includes.includes(name) ? [...childIncludes, ...childExcludes] : childExcludes;
4389
+ children[name] = planCatalogProjection(
4390
+ {
4391
+ ...args,
4392
+ scopePath: [...args.scopePath ?? [], name, "sub"],
4393
+ requestedSelect: childSelect,
4394
+ effectiveSelect: childSelect,
4395
+ related: [],
4396
+ internalFetch: { baseFields: [] }
4397
+ },
4398
+ outputFields
4399
+ );
4400
+ }
4401
+ const internal = args.internalFetch ?? {};
4402
+ const fetchIdRetained = scope2.length === 0 || catalog.paths.includes(full("_id")) || !!catalog.dynamicPaths?.some((p) => p.endsWith("._id") && matchesCatalogPattern(p, full("_id")));
4403
+ const identity = fetchIdRetained ? ["_id"] : [];
4404
+ const always = scope2.length ? [] : [
4405
+ .../* @__PURE__ */ new Set([
4406
+ ...resolveAlwaysSelectForAccess(snapshot.alwaysSelectFields, outputAccess),
4407
+ ...resolveAlwaysSelectForAccess(snapshot.alwaysSelectFields, docPermissionsAccess)
4408
+ ])
4409
+ ];
4410
+ const joins = [...internal.joinFields ?? [], ...internal.extraPersistedFields ?? []];
4411
+ const forced = [...always, ...joins, ...internal.baseFields ?? identity, ...internal.identityFields ?? []];
4412
+ const fetchSafe = (path) => isSafeOutputPath(path) && !virtual(full(path));
4413
+ const dependencies = Object.keys(depProvenance).filter(fetchSafe);
4414
+ const childFetch = Object.entries(children).flatMap(([name, child]) => {
4415
+ if (child.persistedFetchSelection.length) return child.persistedFetchSelection.map((p) => `${name}.${p}`);
4416
+ depProvenance[name] = allVirtuals.filter((p) => p.startsWith(`${name}.`));
4417
+ return [name];
4418
+ });
4419
+ const publicChildFetch = Object.entries(children).flatMap(
4420
+ ([name, child]) => child.publicPersistedFetchSelection.length ? child.publicPersistedFetchSelection.map((path) => `${name}.${path}`) : [name]
4421
+ );
4422
+ const publicPersistedFetchSelection = compactPersistedProjection([
4423
+ ...persisted,
4424
+ ...dependencies,
4425
+ ...forced.filter(fetchSafe),
4426
+ ...identity,
4427
+ ...publicChildFetch
4428
+ ]);
4429
+ const publicStructurePaths = Object.entries(children).flatMap(([name, child]) => {
4430
+ if ([...persisted, ...dependencies, ...forced].some((path) => name === path || name.startsWith(`${path}.`)))
4431
+ return [];
4432
+ return child.publicPersistedFetchSelection.length ? (child.publicStructurePaths ?? []).map((path) => `${name}.${path}`) : [name];
4433
+ });
4434
+ const populateRefs = candidates.flatMap((candidate) => candidate.populateDependencies.map((dep) => dep.path));
4435
+ const privateFields = [...dependencies, ...populateRefs, ...forced.filter(fetchSafe), ...identity, ...childFetch];
4436
+ const fetch = compactPersistedProjection([...persisted, ...privateFields]);
4437
+ const outputIdExcluded = excludes.includes("_id");
4438
+ const coveredOutput = (path) => persisted.some((p) => p === path || path.startsWith(`${p}.`));
4439
+ const outputPersisted = [.../* @__PURE__ */ new Set([...persisted.filter((p) => !p.includes(".")), ...Object.keys(children)])];
4440
+ return {
4441
+ receivingModelName,
4442
+ scopePath: [...args.scopePath ?? []],
4443
+ responseScopePath: Object.freeze(scope2),
4444
+ virtualAccess,
4445
+ outputAccess,
4446
+ docPermissionsAccess,
4447
+ selectionMode: mode,
4448
+ effectiveSelectNorm: normalized,
4449
+ outputPersistedFields: outputPersisted,
4450
+ outputVirtualNames: candidates.map((c) => c.name),
4451
+ outputSelection: [...outputPersisted, ...candidates.map((c) => c.name), ...outputIdExcluded ? ["-_id"] : []],
4452
+ fieldStates: Object.freeze(states2),
4453
+ minimalAncestorPaths: Object.freeze([...ancestors]),
4454
+ persistedFetchSelection: fetch,
4455
+ publicPersistedFetchSelection,
4456
+ publicStructurePaths,
4457
+ candidates,
4458
+ depProvenance,
4459
+ virtualOnlyDeps: Object.keys(depProvenance).filter((p) => fetchSafe(p) && !coveredOutput(p)),
4460
+ internalOnlyFields: [
4461
+ ...new Set(privateFields.filter((p) => !coveredOutput(p) && (p !== "_id" || outputIdExcluded)))
4462
+ ],
4463
+ outputIdExcluded,
4464
+ fetchIdRetained,
4465
+ internalIdentityFields: identity,
4466
+ internalJoinFields: [...new Set(joins)],
4467
+ childPlans: children,
4468
+ // A parent never supplies its authority to a target; related execution will
4469
+ // call planAuthorizedModelProjection with the independently derived owner.
4470
+ relatedPlans: (args.related ?? []).map(
4471
+ (rel) => planVirtualProjection({
4472
+ ...rel,
4473
+ receivingModelName: rel.targetModelName,
4474
+ snapshot: rel.targetSnapshot,
4475
+ globalPermissions
4476
+ })
4477
+ )
4478
+ };
4479
+ }
4480
+ var import_node_util4, staticPlanFields;
4481
+ var init_output_projection = __esm({
4482
+ "src/acl/output-projection.ts"() {
4483
+ import_node_util4 = require("util");
4484
+ init_query();
4485
+ init_authorization_snapshot();
4486
+ init_field_catalog();
4487
+ init_field_authorization();
4488
+ init_virtual_populate_dependencies();
4489
+ init_service_authorization();
4490
+ init_virtual_projection();
4491
+ staticPlanFields = /* @__PURE__ */ new WeakMap();
4492
+ }
4493
+ });
4494
+
4495
+ // src/acl/output-field-policy.ts
4496
+ function callFieldPolicy(authorization, binding) {
4497
+ assertAuthorizationBinding(authorization, binding);
4498
+ let policy = fieldPolicies.get(authorization);
4499
+ if (!policy) {
4500
+ const view = readServiceOutputFieldAuthorization(authorization, binding);
4501
+ policy = {
4502
+ schema: view.permissionSchema,
4503
+ requestPaths: view.permissionSchema == null || (0, import_utils20.isPlainObject)(view.permissionSchema) && Object.isFrozen(view.permissionSchema) ? Object.freeze(Object.keys(view.permissionSchema ?? {})) : void 0,
4504
+ prefix: view.modelPermissionPrefix ?? "",
4505
+ outputFields: view.outputFields,
4506
+ catalog: view.catalog,
4507
+ reusable: view.reusable,
4508
+ accesses: /* @__PURE__ */ new Map()
4509
+ };
4510
+ if (view.reusable) fieldPolicies.set(authorization, policy);
4511
+ }
4512
+ return policy;
4513
+ }
4514
+ function requestRuleClassification(entry, authorization, permissions, prefix) {
4515
+ if (typeof prefix !== "string") return void 0;
4516
+ let classification = entry.classifications.get(authorization);
4517
+ if (!classification) {
4518
+ classification = prepareRequestFieldRule(entry.rule, permissions, prefix);
4519
+ entry.classifications.set(authorization, classification);
4520
+ }
4521
+ return classification;
4522
+ }
4523
+ function invariantRuleLookup(schema, path) {
4524
+ if (schema == null) return true;
4525
+ if (!(0, import_utils20.isPlainObject)(schema) || !Object.isFrozen(schema)) return false;
4526
+ const exact = Object.getOwnPropertyDescriptor(schema, path);
4527
+ if (exact) {
4528
+ const raw2 = exact.value;
4529
+ return !raw2 || typeof raw2 !== "object" || Array.isArray(raw2) || (0, import_utils20.isPlainObject)(raw2) && Object.isFrozen(raw2);
4530
+ }
4531
+ const [head, ...rest] = path.split(".");
4532
+ const raw = Object.getOwnPropertyDescriptor(schema, head)?.value;
4533
+ if (raw == null) return true;
4534
+ if (!(0, import_utils20.isPlainObject)(raw) || !Object.isFrozen(raw)) return false;
4535
+ const sub = Object.getOwnPropertyDescriptor(raw, "sub");
4536
+ return !rest.length || !sub || invariantRuleLookup(sub.value, rest.join("."));
4537
+ }
4538
+ function prepareOutputPath(policy, authorization, binding, path, access) {
4539
+ let cache = policy.accesses.get(access);
4540
+ if (!cache) {
4541
+ cache = /* @__PURE__ */ new Map();
4542
+ policy.accesses.set(access, cache);
4543
+ }
4544
+ let prepared = cache.get(path);
4545
+ if (!prepared) {
4546
+ const invariant = invariantRuleLookup(policy.schema, path);
4547
+ const permissions = getAuthorizationPermissions(authorization, binding);
4548
+ const entries = extractOutputFieldRuleEntries(policy.schema, path, access).map((entry) => ({
4549
+ ...entry,
4550
+ classifications: /* @__PURE__ */ new WeakMap()
4551
+ }));
4552
+ const classifications = entries.map(
4553
+ (entry) => requestRuleClassification(entry, authorization, permissions, policy.prefix)
4554
+ );
4555
+ const backendGrant = hasExplicitFieldGrant(policy.outputFields, path);
4556
+ prepared = {
4557
+ entries,
4558
+ backendGrant,
4559
+ state: backendGrant ? "granted" : classifications.every((value) => value !== void 0) ? combineFieldAuthorizationStates(classifications.map((value) => value.state)) : void 0
4560
+ };
4561
+ if (invariant) cache.set(path, prepared);
4562
+ }
4563
+ return prepared;
4564
+ }
4565
+ function ordinaryContainer(value) {
4566
+ return value !== null && typeof value === "object" && !import_node_util5.types.isProxy(value) && Object.getPrototypeOf(value) === Object.prototype && Object.isFrozen(value);
4567
+ }
4568
+ function booleanRuleLookup(schema, path, access) {
4569
+ if (schema == null) return true;
4570
+ if (!ordinaryContainer(schema)) return false;
4571
+ const booleanRule = (raw) => {
4572
+ if (typeof raw === "boolean" || raw === void 0) return true;
4573
+ if (!ordinaryContainer(raw)) return false;
4574
+ const slot2 = Object.getOwnPropertyDescriptor(raw, access);
4575
+ return !!slot2 && "value" in slot2 && (typeof slot2.value === "boolean" || slot2.value === void 0);
4576
+ };
4577
+ const exact = Object.getOwnPropertyDescriptor(schema, path);
4578
+ if (exact) return "value" in exact && booleanRule(exact.value);
4579
+ const [head, ...rest] = path.split(".");
4580
+ const slot = Object.getOwnPropertyDescriptor(schema, head);
4581
+ if (!slot) return !(head in schema);
4582
+ if (!("value" in slot) || !booleanRule(slot.value)) return false;
4583
+ if (!rest.length || slot.value == null) return true;
4584
+ if (!ordinaryContainer(slot.value)) return false;
4585
+ const sub = Object.getOwnPropertyDescriptor(slot.value, "sub");
4586
+ if (!sub) return !("sub" in slot.value);
4587
+ if (!("value" in sub)) return false;
4588
+ return !sub.value || booleanRuleLookup(sub.value, rest.join("."), access);
4589
+ }
4590
+ function staticFieldPolicy(authorization, binding) {
4591
+ return canPrepareStaticOutputPolicy(authorization, binding) ? callFieldPolicy(authorization, binding) : void 0;
4592
+ }
4593
+ function prepareStaticOutputPaths(authorization, binding, paths, access, requestOnly = false) {
4594
+ const policy = staticFieldPolicy(authorization, binding);
4595
+ if (!policy?.reusable || typeof policy.prefix !== "string") return void 0;
4596
+ const { catalog } = policy;
4597
+ if (paths.some(
4598
+ (path) => !requestOnly && !isCatalogOutputPath(catalog, path) || !booleanRuleLookup(policy.schema, path, access)
4599
+ ))
4600
+ return void 0;
4601
+ return paths.map((path) => {
4602
+ const prepared = prepareOutputPath(policy, authorization, binding, path, access);
4603
+ return {
4604
+ path,
4605
+ backendGrant: !requestOnly && prepared.backendGrant,
4606
+ granted: prepared.backendGrant || prepared.entries.every((entry) => entry.rule === true),
4607
+ entries: prepared.entries.map((entry) => ({
4608
+ key: `request:${access}:${entry.path}`,
4609
+ allowed: entry.rule === true
4610
+ }))
4611
+ };
4612
+ });
4613
+ }
4614
+ var import_node_util5, import_utils20, fieldPolicies;
4615
+ var init_output_field_policy = __esm({
4616
+ "src/acl/output-field-policy.ts"() {
4617
+ import_node_util5 = require("util");
4618
+ import_utils20 = require("@web-ts-toolkit/utils");
4619
+ init_service_authorization();
4620
+ init_field_authorization();
4621
+ init_field_catalog();
4622
+ fieldPolicies = /* @__PURE__ */ new WeakMap();
4623
+ }
4624
+ });
4625
+
4626
+ // src/acl/document-authorization.ts
4627
+ function bindOutputDocumentOwner(handle, knownOutput, owner, binding) {
4628
+ lookupDocumentOwner(handle);
4629
+ if (knownOutput || owner && unresolvedDocuments.has(owner)) unresolvedDocuments.add(handle);
4630
+ if (owner) {
4631
+ lookupDocumentOwner(owner);
4632
+ owningDocuments.set(handle, { handle: owner, binding });
4633
+ }
4634
+ }
4635
+ function readOutputDocumentOwner(handle) {
4636
+ return owningDocuments.get(handle);
4637
+ }
4638
+ function isUnresolvedOutputDocument(handle) {
4639
+ return unresolvedDocuments.has(handle);
4640
+ }
4641
+ function normalizeOutputAuthorizationOptions(input, options, purpose) {
4642
+ const value = authorizationRecord(options, "output options");
4643
+ for (const key of Reflect.ownKeys(value)) {
4644
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
4645
+ if (typeof key !== "string" || !("value" in descriptor) || !descriptor.enumerable) {
4646
+ authorizationError("invalid output option property");
4647
+ }
4648
+ }
4649
+ assertAuthorizationKeys(
4650
+ value,
4651
+ ["authorization", "scopePath", "documentAuthorization", ...purpose ? ["purpose"] : []],
4652
+ "output options"
4653
+ );
4654
+ if (purpose && value.purpose !== purpose) authorizationError("genAllowedFields requires purpose: output");
4655
+ if (Object.prototype.hasOwnProperty.call(value, "documentAuthorization")) {
4656
+ if (Object.prototype.hasOwnProperty.call(value, "authorization") || Object.prototype.hasOwnProperty.call(value, "scopePath")) {
4657
+ authorizationError("document handle cannot be mixed with raw policy/scope");
4658
+ }
4659
+ const handle = value.documentAuthorization;
4660
+ const { stage } = validateDocumentOwner(handle);
4661
+ const binding = Object.freeze({ ...input.binding, scopePath: stage.binding.scopePath });
4662
+ assertAuthorizationBinding(stage.call, binding);
4663
+ const access = readServiceAuthorizationAccess(stage.call, binding);
4664
+ if (input.access.outputAccess !== access.outputAccess) authorizationError("document access mismatch");
4665
+ return Object.freeze({ kind: "document", documentAuthorization: handle, binding });
4666
+ }
4667
+ if (value.scopePath !== void 0 && !Array.isArray(value.scopePath))
4668
+ authorizationError("scopePath must be an array");
4669
+ return Object.freeze({
4670
+ kind: "policy",
4671
+ authorization: resolveServiceAuthorization({
4672
+ ...input,
4673
+ binding: {
4674
+ ...input.binding,
4675
+ scopePath: copyAuthorizationValue(value.scopePath)
4676
+ },
4677
+ authorization: value.authorization,
4678
+ applicability: "output"
4679
+ })
4680
+ });
4681
+ }
4682
+ function lookupStageOwner(stage) {
4683
+ const record3 = stages.get(stage);
4684
+ if (!record3) authorizationError("invalid document stage");
4685
+ return record3;
4686
+ }
4687
+ function lookupDocumentOwner(handle) {
4688
+ const record3 = documents.get(handle);
4689
+ if (!record3) authorizationError("invalid document handle");
4690
+ return record3;
4691
+ }
4692
+ function validateStageOwner(record3) {
4693
+ if (!matchesAuthorizationSnapshot(record3.input, record3.snapshot)) authorizationError("changed document snapshot");
4694
+ }
4695
+ function validateDocumentOwner(handle) {
4696
+ const document = lookupDocumentOwner(handle);
4697
+ const stage = lookupStageOwner(document.stage);
4698
+ validateStageOwner(stage);
4699
+ validateStageOwner(stage);
4700
+ return { document, stage };
4701
+ }
4702
+ function createDocumentAuthorizationStage(call, binding, projectedSnapshot) {
4703
+ assertAuthorizationBinding(call, binding);
4704
+ authorizationRecord(projectedSnapshot, "projected document snapshot");
4705
+ const stage = Object.freeze(/* @__PURE__ */ Object.create(null));
4706
+ const ownedBinding = Object.freeze({ ...binding, scopePath: Object.freeze([...binding.scopePath ?? []]) });
4707
+ const snapshot = copyAuthorizationValue(projectedSnapshot, "document");
4708
+ stages.set(stage, {
4709
+ call,
4710
+ binding: ownedBinding,
4711
+ input: projectedSnapshot,
4712
+ snapshot
4713
+ });
4714
+ return stage;
4715
+ }
4716
+ function assertDocumentAuthorizationStage(stage, call, binding, projectedSnapshot) {
4717
+ const record3 = lookupStageOwner(stage);
4718
+ validateStageOwner(record3);
4719
+ assertAuthorizationBinding(record3.call, binding);
4720
+ if (record3.call !== call || record3.input !== projectedSnapshot || !matchesAuthorizationSnapshot(projectedSnapshot, record3.snapshot)) {
4721
+ authorizationError("document call/stage/snapshot mismatch");
4722
+ }
4723
+ }
4724
+ function resolveDocumentAuthorization(stage, resolveGrants) {
4725
+ const record3 = lookupStageOwner(stage);
4726
+ validateStageOwner(record3);
4727
+ if (!record3.result) {
4728
+ record3.result = Promise.resolve().then(async () => {
4729
+ validateStageOwner(record3);
4730
+ const result2 = resolveGrants.call(
4731
+ record3.binding.request,
4732
+ copyAuthorizationValue(record3.snapshot, "document"),
4733
+ getAuthorizationPermissions(record3.call, record3.binding)
4734
+ );
4735
+ const grants = result2 && typeof result2.then === "function" ? await result2 : result2;
4736
+ validateStageOwner(record3);
4737
+ const ownedGrants = copyAuthorizationValue(authorizationRecord(grants, "document grants"));
4738
+ const handle = Object.freeze(/* @__PURE__ */ Object.create(null));
4739
+ documents.set(handle, { stage, grants: ownedGrants, decisions: /* @__PURE__ */ new Map() });
4740
+ return handle;
4741
+ });
4742
+ }
4743
+ return record3.result;
4744
+ }
4745
+ function readDocumentAuthorization(handle, binding) {
4746
+ const { document: record3, stage } = validateDocumentOwner(handle);
4747
+ assertAuthorizationBinding(stage.call, binding);
4748
+ return Object.freeze({
4749
+ authorization: stage.call,
4750
+ stage: record3.stage,
4751
+ grants: copyAuthorizationValue(record3.grants),
4752
+ ...readServiceAuthorizationAccess(stage.call, binding)
4753
+ });
4754
+ }
4755
+ function readDocumentAuthorizationAccess(handle, binding) {
4756
+ const { document: record3, stage } = validateDocumentOwner(handle);
4757
+ return Object.freeze({
4758
+ authorization: stage.call,
4759
+ stage: record3.stage,
4760
+ ...readServiceAuthorizationAccess(stage.call, binding)
4761
+ });
4762
+ }
4763
+ function memoizeDocumentFieldDecision(handle, binding, field, evaluate) {
4764
+ const { document: record3, stage } = validateDocumentOwner(handle);
4765
+ assertAuthorizationBinding(stage.call, binding);
4766
+ let decision = record3.decisions.get(field);
4767
+ if (decision) {
4768
+ return decision.promise.then((result2) => {
4769
+ validateStageOwner(stage);
4770
+ assertAuthorizationBinding(stage.call, binding);
4771
+ return result2;
4772
+ });
4773
+ } else {
4774
+ const created = {
4775
+ state: "pending",
4776
+ promise: Promise.resolve().then(async () => {
4777
+ validateStageOwner(stage);
4778
+ assertAuthorizationBinding(stage.call, binding);
4779
+ const result2 = await evaluate.call(
4780
+ stage.binding.request,
4781
+ getAuthorizationPermissions(stage.call, binding),
4782
+ copyAuthorizationValue(record3.grants)
4783
+ );
4784
+ validateStageOwner(stage);
4785
+ assertAuthorizationBinding(stage.call, binding);
4786
+ if (typeof result2 !== "boolean") authorizationError("field decision must be boolean");
4787
+ return result2;
4788
+ })
4789
+ };
4790
+ void created.promise.then(
4791
+ (value) => {
4792
+ created.value = value;
4793
+ created.state = "fulfilled";
4794
+ },
4795
+ () => {
4796
+ created.state = "rejected";
4797
+ }
4798
+ );
4799
+ decision = created;
4800
+ record3.decisions.set(field, decision);
4801
+ }
4802
+ return decision.promise;
4803
+ }
4804
+ function ordinaryDecisionBinding(binding) {
4805
+ if (import_node_util6.types.isProxy(binding) || Object.getPrototypeOf(binding) !== Object.prototype) return false;
4806
+ for (const key of ["request", "runtime", "model", "modelName", "scopePath"]) {
4807
+ const slot = Object.getOwnPropertyDescriptor(binding, key);
4808
+ if (slot && !("value" in slot)) return false;
4809
+ if (!slot && key !== "scopePath") return false;
4810
+ if (!slot && key in binding) return false;
4811
+ }
4812
+ const scope2 = Object.getOwnPropertyDescriptor(binding, "scopePath")?.value;
4813
+ return scope2 === void 0 || copyOutputDecisionFields(scope2) !== void 0;
4814
+ }
4815
+ function settleStaticFieldBatch(handle, binding, paths) {
4816
+ const { document, stage } = validateDocumentOwner(handle);
4817
+ if (!ordinaryDecisionBinding(binding)) {
4818
+ validateDocumentOwner(handle);
4819
+ return;
4820
+ }
4821
+ assertAuthorizationBinding(stage.call, binding);
4822
+ const expected = /* @__PURE__ */ new Map();
4823
+ const journal = /* @__PURE__ */ new Map();
4824
+ const result2 = /* @__PURE__ */ new Map();
4825
+ const unresolved = unresolvedDocuments.has(handle);
4826
+ let available = !owningDocuments.has(handle);
4827
+ const read = (key) => {
4828
+ const memo = document.decisions.get(key);
4829
+ expected.set(key, memo);
4830
+ if (memo) {
4831
+ if (memo.state !== "fulfilled") available = false;
4832
+ return memo.value;
4833
+ }
4834
+ return journal.get(key);
4835
+ };
4836
+ for (const path of paths) {
4837
+ if (!available) break;
4838
+ let allowed = path.outputKey ? read(path.outputKey) : void 0;
4839
+ if (!available) break;
4840
+ if (allowed === void 0) {
4841
+ const policy = path.policy;
4842
+ if (!policy) {
4843
+ available = false;
4844
+ break;
4845
+ }
4846
+ if (path.outputKey && unresolved && !policy.granted) allowed = false;
4847
+ else if (path.outputKey && policy.backendGrant) allowed = true;
4848
+ else {
4849
+ allowed = true;
4850
+ for (const entry of policy.entries) {
4851
+ let decision = read(entry.key);
4852
+ if (!available) break;
4853
+ if (decision === void 0) {
4854
+ decision = entry.allowed;
4855
+ journal.set(entry.key, decision);
4856
+ }
4857
+ if (!decision) {
4858
+ allowed = false;
4859
+ break;
4860
+ }
4861
+ }
4862
+ }
4863
+ if (!available) break;
4864
+ if (path.outputKey) journal.set(path.outputKey, allowed);
4865
+ }
4866
+ result2.set(path.field, allowed);
4867
+ }
4868
+ validateDocumentOwner(handle);
4869
+ if (!ordinaryDecisionBinding(binding)) return;
4870
+ assertAuthorizationBinding(stage.call, binding);
4871
+ if (!available || owningDocuments.has(handle) || unresolvedDocuments.has(handle) !== unresolved || [...expected].some(([key, memo]) => document.decisions.get(key) !== memo))
4872
+ return;
4873
+ for (const [key, value] of journal) {
4874
+ document.decisions.set(key, { promise: Promise.resolve(value), state: "fulfilled", value });
4875
+ }
4876
+ return result2;
4877
+ }
4878
+ function tryStaticOutputFieldDecisions(handle, binding, plan, fields) {
4879
+ const document = lookupDocumentOwner(handle);
4880
+ const stage = lookupStageOwner(document.stage);
4881
+ if (!ordinaryDecisionBinding(binding) || owningDocuments.has(handle)) return;
4882
+ assertAuthorizationBinding(stage.call, binding);
4883
+ const canonical = readStaticOutputPlanFields(plan, stage.call);
4884
+ const ownedFields = copyOutputDecisionFields(fields);
4885
+ if (!canonical || !ownedFields) return;
4886
+ let index = 0;
4887
+ for (const field of ownedFields) {
4888
+ const next = canonical.indexOf(field, index);
4889
+ if (next < 0) return;
4890
+ index = next + 1;
4891
+ }
4892
+ const prefix = (binding.scopePath ?? []).join(".");
4893
+ const paths = ownedFields.map((field) => {
4894
+ const path = prefix ? `${prefix}.${field}` : field;
4895
+ return { field, path, outputKey: `output:${path}` };
4896
+ });
4897
+ const missing = [];
4898
+ for (const path of paths) {
4899
+ const memo = document.decisions.get(path.outputKey);
4900
+ if (memo && memo.state !== "fulfilled") return;
4901
+ if (!memo) missing.push(path.path);
4902
+ }
4903
+ const access = readServiceAuthorizationAccess(stage.call, binding).outputAccess;
4904
+ const prepared = missing.length ? prepareStaticOutputPaths(stage.call, binding, missing, access) : [];
4905
+ if (!prepared) return;
4906
+ const policies = new Map(prepared.map((policy) => [policy.path, policy]));
4907
+ const decisions = settleStaticFieldBatch(
4908
+ handle,
4909
+ binding,
4910
+ paths.map((path) => ({ ...path, policy: policies.get(path.path) }))
4911
+ );
4912
+ if (decisions && !readStaticOutputPlanFields(plan, stage.call)) authorizationError("changed static output plan");
4913
+ return decisions;
4914
+ }
4915
+ function tryStaticRequestFieldPaths(handle, binding, access) {
4916
+ const document = lookupDocumentOwner(handle);
4917
+ const stage = lookupStageOwner(document.stage);
4918
+ if (!ordinaryDecisionBinding(binding) || owningDocuments.has(handle) || typeof access !== "string") return;
4919
+ const policy = staticFieldPolicy(stage.call, binding);
4920
+ if (!policy?.reusable || !policy.requestPaths) return;
4921
+ const prepared = prepareStaticOutputPaths(stage.call, binding, policy.requestPaths, access, true);
4922
+ if (!prepared) return;
4923
+ const decisions = settleStaticFieldBatch(
4924
+ handle,
4925
+ binding,
4926
+ prepared.map((policy2) => ({ field: policy2.path, policy: policy2 }))
4927
+ );
4928
+ return decisions && [...decisions].filter(([, allowed]) => allowed).map(([field]) => field);
4929
+ }
4930
+ function unchangedOutput(output, record3) {
4931
+ if (!matchesAuthorizationSnapshot(output, record3.snapshot)) return false;
4932
+ const identities = outputIdentities(output);
4933
+ return identities.length === record3.identities.length && identities.every((identity, i) => identity === record3.identities[i]);
4934
+ }
4935
+ function assertDocumentAuthorization(handle, use) {
4936
+ const { document: record3, stage } = validateDocumentOwner(handle);
4937
+ assertAuthorizationBinding(stage.call, use.binding);
4938
+ if (use.authorization !== void 0 && stage.call !== use.authorization || use.stage !== void 0 && record3.stage !== use.stage || readServiceAuthorizationAccess(stage.call, use.binding).outputAccess !== use.outputAccess) {
4939
+ authorizationError("document call/access/stage mismatch");
4940
+ }
4941
+ const association = outputs.get(use.output);
4942
+ if (!association || association.handle !== handle || !unchangedOutput(use.output, association)) {
4943
+ authorizationError("unknown, replaced or mutated authorized output");
4944
+ }
4945
+ }
4946
+ function associateDocumentAuthorization(handle, binding, output) {
4947
+ const { stage } = validateDocumentOwner(handle);
4948
+ assertAuthorizationBinding(stage.call, binding);
4949
+ if (!output || typeof output !== "object") authorizationError("output must be an object");
4950
+ if (outputs.has(output)) {
4951
+ const previous = outputs.get(output);
4952
+ if (previous.handle !== handle || !unchangedOutput(output, previous))
4953
+ authorizationError("output already associated");
4954
+ return;
4955
+ }
4956
+ outputs.set(output, {
4957
+ handle,
4958
+ snapshot: copyAuthorizationValue(output, "document"),
4959
+ identities: outputIdentities(output)
4960
+ });
4961
+ }
4962
+ function transferDocumentAuthorization(handle, use, copy) {
4963
+ assertDocumentAuthorization(handle, use);
4964
+ associateDocumentAuthorization(handle, use.binding, copy);
4965
+ }
4966
+ function isKnownAuthorizationOutput(output) {
4967
+ return outputs.has(output);
4968
+ }
4969
+ function getAssociatedDocumentAuthorization(output, call) {
4970
+ const record3 = outputs.get(output);
4971
+ if (!record3 || !unchangedOutput(output, record3)) return void 0;
4972
+ const { stage } = validateDocumentOwner(record3.handle);
4973
+ if (call && getAuthorizationProvenance(stage.call) !== getAuthorizationProvenance(call)) return void 0;
4974
+ return record3.handle;
4975
+ }
4976
+ function transferDocumentAuthorizationGraph(source, copy, copyOrigins) {
4977
+ const seen = /* @__PURE__ */ new WeakSet();
4978
+ const visit = (source2, copy2) => {
4979
+ if (!copy2 || typeof copy2 !== "object" || seen.has(copy2)) return;
4980
+ seen.add(copy2);
4981
+ source2 = copyOrigins?.get(copy2) ?? source2;
4982
+ if (source2 instanceof import_mongoose5.Document) source2 = source2._doc;
4983
+ const original = source2 && typeof source2 === "object" ? source2 : void 0;
4984
+ if (!original && !copyOrigins) return;
4985
+ const association = original && outputs.get(original);
4986
+ if (association) {
4987
+ const { document, stage } = validateDocumentOwner(association.handle);
4988
+ const outputAccess = readServiceAuthorizationAccess(stage.call, stage.binding).outputAccess;
4989
+ validateStageOwner(stage);
4990
+ transferDocumentAuthorization(
4991
+ association.handle,
4992
+ {
4993
+ binding: stage.binding,
4994
+ output: original,
4995
+ outputAccess,
4996
+ authorization: stage.call,
4997
+ stage: document.stage
4998
+ },
4999
+ copy2
5000
+ );
5001
+ }
5002
+ for (const key of Object.keys(copy2)) {
5003
+ const descriptor = original && Object.getOwnPropertyDescriptor(original, key);
5004
+ if (descriptor && "value" in descriptor) {
5005
+ visit(descriptor.value, copy2[key]);
5006
+ } else if (copyOrigins) {
5007
+ visit(void 0, copy2[key]);
5008
+ }
5009
+ }
5010
+ };
5011
+ visit(source, copy);
5012
+ }
5013
+ function createServiceOutputContext(diagnostic, handle, use) {
5014
+ assertDocumentAuthorization(handle, use);
5015
+ const rootOutput = use.output;
5016
+ const root = outputs.get(rootOutput);
5017
+ const graph = new Set(root.identities);
5018
+ const { stage } = validateDocumentOwner(handle);
5019
+ const call = stage.call;
5020
+ const context = { ...diagnostic };
5021
+ Object.defineProperties(context, {
5022
+ documentAuthorization: { value: handle, enumerable: false, writable: false, configurable: false },
5023
+ getDocumentAuthorization: {
5024
+ enumerable: false,
5025
+ writable: false,
5026
+ configurable: false,
5027
+ value(output) {
5028
+ if (!graph.has(output) || !unchangedOutput(rootOutput, root)) return void 0;
5029
+ const association = outputs.get(output);
5030
+ if (!association || !unchangedOutput(output, association)) return void 0;
5031
+ try {
5032
+ validateStageOwner(lookupStageOwner(lookupDocumentOwner(handle).stage));
5033
+ const { stage: child } = validateDocumentOwner(association.handle);
5034
+ if (getAuthorizationProvenance(child.call) !== getAuthorizationProvenance(call)) return void 0;
5035
+ return association.handle;
5036
+ } catch {
5037
+ return void 0;
5038
+ }
5039
+ }
5040
+ }
5041
+ });
5042
+ return context;
5043
+ }
5044
+ var import_node_util6, import_mongoose5, stages, documents, outputs, unresolvedDocuments, owningDocuments;
5045
+ var init_document_authorization = __esm({
5046
+ "src/acl/document-authorization.ts"() {
5047
+ import_node_util6 = require("util");
5048
+ import_mongoose5 = require("mongoose");
5049
+ init_service_authorization();
5050
+ init_authorization_snapshot();
5051
+ init_output_projection();
5052
+ init_output_field_policy();
5053
+ stages = /* @__PURE__ */ new WeakMap();
5054
+ documents = /* @__PURE__ */ new WeakMap();
5055
+ outputs = /* @__PURE__ */ new WeakMap();
5056
+ unresolvedDocuments = /* @__PURE__ */ new WeakSet();
5057
+ owningDocuments = /* @__PURE__ */ new WeakMap();
5058
+ }
5059
+ });
5060
+
5061
+ // src/output/include-output.ts
5062
+ function prepareIncludeOutput(doc) {
5063
+ if (stateFor(doc)) return doc;
5064
+ const source = isolateDocForOutput(doc);
5065
+ transferDocumentAuthorizationGraph(doc, source);
5066
+ const working = deepIsolateValue(source);
5067
+ outputs2.set(working, { original: doc, source, attachments: [] });
5068
+ return working;
5069
+ }
5070
+ function attachIncludeOutput(doc, path, value) {
5071
+ const state = stateFor(doc);
5072
+ if (!state) throw new Error("Include attachment requires a prepared output row");
5073
+ state.attachments.push({ path, value });
5074
+ (0, import_utils21.set)(doc, path, deepIsolateValue(value));
5075
+ }
5076
+ function getIncludeSource(doc) {
5077
+ return stateFor(doc)?.source ?? doc;
5078
+ }
5079
+ function getIncludeOriginal(doc) {
5080
+ return stateFor(doc)?.original ?? doc;
5081
+ }
5082
+ function restoreIncludeOutput(doc, output) {
5083
+ const attachments = stateFor(doc)?.attachments;
5084
+ if (!attachments?.length) return void 0;
5085
+ const origins = /* @__PURE__ */ new WeakMap();
5086
+ for (const { path, value } of attachments) {
5087
+ const copy = deepIsolateValue(value);
5088
+ if (copy !== null && typeof copy === "object") origins.set(copy, value);
5089
+ (0, import_utils21.set)(output, path, copy);
5090
+ }
5091
+ return origins;
5092
+ }
5093
+ var import_utils21, outputs2, stateFor;
5094
+ var init_include_output = __esm({
5095
+ "src/output/include-output.ts"() {
5096
+ import_utils21 = require("@web-ts-toolkit/utils");
5097
+ init_document_authorization();
5098
+ init_document();
5099
+ outputs2 = /* @__PURE__ */ new WeakMap();
5100
+ stateFor = (doc) => doc !== null && typeof doc === "object" ? outputs2.get(doc) : void 0;
5101
+ }
5102
+ });
5103
+
5104
+ // src/helpers/request-work.ts
5105
+ function getRequestWorkState(req, runtime) {
5106
+ let owners = states.get(req);
5107
+ if (!owners) {
5108
+ owners = /* @__PURE__ */ new WeakMap();
5109
+ states.set(req, owners);
4540
5110
  }
4541
- const children = {};
4542
- for (const name of [...ancestors].filter((p) => !p.includes("."))) {
4543
- const childIncludes = includes.filter((p) => p.startsWith(`${name}.`)).map((p) => p.slice(name.length + 1));
4544
- const childExcludes = excludes.filter((p) => p.startsWith(`${name}.`)).map((p) => `-${p.slice(name.length + 1)}`);
4545
- const childSelect = mode === "include" && !includes.includes(name) ? [...childIncludes, ...childExcludes] : childExcludes;
4546
- children[name] = planCatalogProjection(
4547
- {
4548
- ...args,
4549
- scopePath: [...args.scopePath ?? [], name, "sub"],
4550
- requestedSelect: childSelect,
4551
- effectiveSelect: childSelect,
4552
- related: [],
4553
- internalFetch: { baseFields: [] }
4554
- },
4555
- outputFields
4556
- );
5111
+ let state = owners.get(runtime);
5112
+ if (!state) {
5113
+ const limits = resolveRequestComplexity(runtime.getGlobalOption("requestComplexity"));
5114
+ state = {
5115
+ totalQueries: 0,
5116
+ scheduler: new RequestConcurrencyScheduler(limits.maxBulkConcurrency),
5117
+ hookGate: new SharedHookGate(limits.maxHookConcurrency)
5118
+ };
5119
+ owners.set(runtime, state);
4557
5120
  }
4558
- const internal = args.internalFetch ?? {};
4559
- const fetchIdRetained = scope2.length === 0 || catalog.paths.includes(full("_id")) || !!catalog.dynamicPaths?.some((p) => p.endsWith("._id") && matchesCatalogPattern(p, full("_id")));
4560
- const identity = fetchIdRetained ? ["_id"] : [];
4561
- const always = scope2.length ? [] : [
4562
- .../* @__PURE__ */ new Set([
4563
- ...resolveAlwaysSelectForAccess(snapshot.alwaysSelectFields, outputAccess),
4564
- ...resolveAlwaysSelectForAccess(snapshot.alwaysSelectFields, docPermissionsAccess)
4565
- ])
4566
- ];
4567
- const joins = [...internal.joinFields ?? [], ...internal.extraPersistedFields ?? []];
4568
- const forced = [...always, ...joins, ...internal.baseFields ?? identity, ...internal.identityFields ?? []];
4569
- const fetchSafe = (path) => isSafeOutputPath(path) && !virtual(full(path));
4570
- const dependencies = Object.keys(depProvenance).filter(fetchSafe);
4571
- const childFetch = Object.entries(children).flatMap(([name, child]) => {
4572
- if (child.persistedFetchSelection.length) return child.persistedFetchSelection.map((p) => `${name}.${p}`);
4573
- depProvenance[name] = allVirtuals.filter((p) => p.startsWith(`${name}.`));
4574
- return [name];
4575
- });
4576
- const publicChildFetch = Object.entries(children).flatMap(
4577
- ([name, child]) => child.publicPersistedFetchSelection.length ? child.publicPersistedFetchSelection.map((path) => `${name}.${path}`) : [name]
4578
- );
4579
- const publicPersistedFetchSelection = compactPersistedProjection([
4580
- ...persisted,
4581
- ...dependencies,
4582
- ...forced.filter(fetchSafe),
4583
- ...identity,
4584
- ...publicChildFetch
4585
- ]);
4586
- const publicStructurePaths = Object.entries(children).flatMap(([name, child]) => {
4587
- if ([...persisted, ...dependencies, ...forced].some((path) => name === path || name.startsWith(`${path}.`)))
4588
- return [];
4589
- return child.publicPersistedFetchSelection.length ? (child.publicStructurePaths ?? []).map((path) => `${name}.${path}`) : [name];
4590
- });
4591
- const populateRefs = candidates.flatMap((candidate) => candidate.populateDependencies.map((dep) => dep.path));
4592
- const privateFields = [...dependencies, ...populateRefs, ...forced.filter(fetchSafe), ...identity, ...childFetch];
4593
- const fetch = compactPersistedProjection([...persisted, ...privateFields]);
4594
- const outputIdExcluded = excludes.includes("_id");
4595
- const coveredOutput = (path) => persisted.some((p) => p === path || path.startsWith(`${p}.`));
4596
- const outputPersisted = [.../* @__PURE__ */ new Set([...persisted.filter((p) => !p.includes(".")), ...Object.keys(children)])];
4597
- return {
4598
- receivingModelName,
4599
- scopePath: [...args.scopePath ?? []],
4600
- responseScopePath: Object.freeze(scope2),
4601
- virtualAccess,
4602
- outputAccess,
4603
- docPermissionsAccess,
4604
- selectionMode: mode,
4605
- effectiveSelectNorm: normalized,
4606
- outputPersistedFields: outputPersisted,
4607
- outputVirtualNames: candidates.map((c) => c.name),
4608
- outputSelection: [...outputPersisted, ...candidates.map((c) => c.name), ...outputIdExcluded ? ["-_id"] : []],
4609
- fieldStates: Object.freeze(states2),
4610
- minimalAncestorPaths: Object.freeze([...ancestors]),
4611
- persistedFetchSelection: fetch,
4612
- publicPersistedFetchSelection,
4613
- publicStructurePaths,
4614
- candidates,
4615
- depProvenance,
4616
- virtualOnlyDeps: Object.keys(depProvenance).filter((p) => fetchSafe(p) && !coveredOutput(p)),
4617
- internalOnlyFields: [
4618
- ...new Set(privateFields.filter((p) => !coveredOutput(p) && (p !== "_id" || outputIdExcluded)))
4619
- ],
4620
- outputIdExcluded,
4621
- fetchIdRetained,
4622
- internalIdentityFields: identity,
4623
- internalJoinFields: [...new Set(joins)],
4624
- childPlans: children,
4625
- // A parent never supplies its authority to a target; related execution will
4626
- // call planAuthorizedModelProjection with the independently derived owner.
4627
- relatedPlans: (args.related ?? []).map(
4628
- (rel) => planVirtualProjection({
4629
- ...rel,
4630
- receivingModelName: rel.targetModelName,
4631
- snapshot: rel.targetSnapshot,
4632
- globalPermissions
4633
- })
4634
- )
4635
- };
5121
+ return state;
4636
5122
  }
4637
- var init_output_projection = __esm({
4638
- "src/acl/output-projection.ts"() {
4639
- init_query();
4640
- init_authorization_snapshot();
4641
- init_field_catalog();
4642
- init_field_authorization();
4643
- init_virtual_populate_dependencies();
4644
- init_service_authorization();
4645
- init_virtual_projection();
5123
+ var states;
5124
+ var init_request_work = __esm({
5125
+ "src/helpers/request-work.ts"() {
5126
+ init_request_complexity();
5127
+ init_concurrency();
5128
+ states = /* @__PURE__ */ new WeakMap();
4646
5129
  }
4647
5130
  });
4648
5131
 
4649
5132
  // src/acl/model-output-planning.ts
4650
5133
  function getCapturedAuthorizationOption(configuration, key) {
4651
- const defaultValue = key.startsWith("operationAccess.") ? (0, import_utils22.get)(configuration.operationAccessDefaults, key.slice("operationAccess.".length)) : void 0;
4652
- return resolveNestedOption((path, fallback) => (0, import_utils22.get)(configuration, path, fallback), key, defaultValue);
5134
+ const defaultValue = key.startsWith("operationAccess.") ? (0, import_utils23.get)(configuration.operationAccessDefaults, key.slice("operationAccess.".length)) : void 0;
5135
+ return resolveNestedOption((path, fallback) => (0, import_utils23.get)(configuration, path, fallback), key, defaultValue);
4653
5136
  }
4654
5137
  function captureModelAuthorizationConfiguration(runtime, modelName, options = runtime.getModelOptions(modelName), globalOptions = runtime.getGlobalOptions()) {
4655
5138
  const model = runtime.getModelInstance(modelName);
@@ -4712,10 +5195,10 @@ function planModelOutputForHelper(args) {
4712
5195
  requestedSelect: args.select
4713
5196
  });
4714
5197
  }
4715
- var import_utils22;
5198
+ var import_utils23;
4716
5199
  var init_model_output_planning = __esm({
4717
5200
  "src/acl/model-output-planning.ts"() {
4718
- import_utils22 = require("@web-ts-toolkit/utils");
5201
+ import_utils23 = require("@web-ts-toolkit/utils");
4719
5202
  init_manager();
4720
5203
  init_field_catalog();
4721
5204
  init_authorization_snapshot();
@@ -4727,10 +5210,10 @@ var init_model_output_planning = __esm({
4727
5210
 
4728
5211
  // src/core-shared.ts
4729
5212
  function isAndFilter(filter2) {
4730
- return !!filter2 && (0, import_utils23.isPlainObject)(filter2) && Object.keys(filter2).length === 1 && (0, import_utils23.isArray)(filter2.$and);
5213
+ return !!filter2 && (0, import_utils24.isPlainObject)(filter2) && Object.keys(filter2).length === 1 && (0, import_utils24.isArray)(filter2.$and);
4731
5214
  }
4732
5215
  function isMergeableClause(filter2) {
4733
- return !!filter2 && (0, import_utils23.isPlainObject)(filter2) && Object.keys(filter2).every((key) => !key.startsWith("$"));
5216
+ return !!filter2 && (0, import_utils24.isPlainObject)(filter2) && Object.keys(filter2).every((key) => !key.startsWith("$"));
4734
5217
  }
4735
5218
  function optimizeAndFilter(clausesInput) {
4736
5219
  const clauses = [];
@@ -4747,11 +5230,11 @@ function optimizeAndFilter(clausesInput) {
4747
5230
  const dedupeKey = (value) => {
4748
5231
  if (value instanceof RegExp) return `regexp:${JSON.stringify([value.source, value.flags])}`;
4749
5232
  if (value instanceof Date) return `date:${value.getTime()}`;
4750
- if ((0, import_utils23.isArray)(value)) {
5233
+ if ((0, import_utils24.isArray)(value)) {
4751
5234
  const entries = Array.from(value, dedupeKey);
4752
5235
  return entries.every((entry) => entry !== void 0) ? `array:${JSON.stringify(entries)}` : void 0;
4753
5236
  }
4754
- if ((0, import_utils23.isPlainObject)(value)) {
5237
+ if ((0, import_utils24.isPlainObject)(value)) {
4755
5238
  const entries = Object.keys(value).sort().map((key) => [key, dedupeKey(value[key])]);
4756
5239
  return entries.every(([, entry]) => entry !== void 0) ? `object:${JSON.stringify(entries)}` : void 0;
4757
5240
  }
@@ -4781,7 +5264,7 @@ function optimizeAndFilter(clausesInput) {
4781
5264
  }
4782
5265
  let canMerge = true;
4783
5266
  for (const [key, value] of Object.entries(clause)) {
4784
- if ((0, import_utils23.hasOwn)(mergedClause, key) && !(0, import_node_util4.isDeepStrictEqual)(mergedClause[key], value)) {
5267
+ if ((0, import_utils24.hasOwn)(mergedClause, key) && !(0, import_node_util7.isDeepStrictEqual)(mergedClause[key], value)) {
4785
5268
  canMerge = false;
4786
5269
  break;
4787
5270
  }
@@ -4792,24 +5275,24 @@ function optimizeAndFilter(clausesInput) {
4792
5275
  }
4793
5276
  Object.assign(mergedClause, clause);
4794
5277
  }
4795
- const finalClauses = (0, import_utils23.isEmpty)(mergedClause) ? remainingClauses : [mergedClause, ...remainingClauses];
5278
+ const finalClauses = (0, import_utils24.isEmpty)(mergedClause) ? remainingClauses : [mergedClause, ...remainingClauses];
4796
5279
  if (finalClauses.length === 0) return null;
4797
5280
  if (finalClauses.length === 1) return finalClauses[0];
4798
5281
  return { $and: finalClauses };
4799
5282
  }
4800
5283
  function normalizeFilter(filter2) {
4801
5284
  if (filter2 === false) return false;
4802
- if (!filter2 || !(0, import_utils23.isPlainObject)(filter2) || (0, import_utils23.isEmpty)(filter2)) return null;
5285
+ if (!filter2 || !(0, import_utils24.isPlainObject)(filter2) || (0, import_utils24.isEmpty)(filter2)) return null;
4803
5286
  if (!isAndFilter(filter2)) {
4804
5287
  return filter2;
4805
5288
  }
4806
5289
  return optimizeAndFilter(filter2.$and);
4807
5290
  }
4808
5291
  async function resolveIdentifierFilter(req, idField, resolveIdFilter, id) {
4809
- if ((0, import_utils23.isFunction)(resolveIdFilter)) {
5292
+ if ((0, import_utils24.isFunction)(resolveIdFilter)) {
4810
5293
  return await resolveIdFilter.call(req, id);
4811
5294
  }
4812
- if ((0, import_utils23.isString)(idField)) {
5295
+ if ((0, import_utils24.isString)(idField)) {
4813
5296
  return { [idField]: id };
4814
5297
  }
4815
5298
  return { _id: id };
@@ -4833,7 +5316,7 @@ async function resolveAccessFilterParts({
4833
5316
  }
4834
5317
  const overrideFilterFn = getOption(`overrideFilter.${access}`, null);
4835
5318
  const baseFilterFn = rows2.mode === "request" ? getOption(`baseFilter.${access}`, null) : null;
4836
- if (nextFilter !== false && (0, import_utils23.isFunction)(overrideFilterFn)) {
5319
+ if (nextFilter !== false && (0, import_utils24.isFunction)(overrideFilterFn)) {
4837
5320
  nextFilter = normalizeFilter(await overrideFilterFn.call(req, nextFilter, permissions));
4838
5321
  }
4839
5322
  if (nextFilter === false) return { transformed: false, scope: {}, filter: false };
@@ -4841,7 +5324,7 @@ async function resolveAccessFilterParts({
4841
5324
  const scope2 = rows2.mode === "scope" ? rows2.filter : {};
4842
5325
  return { transformed: nextFilter ?? {}, scope: scope2, filter: intersectFilters(nextFilter, scope2) };
4843
5326
  }
4844
- if (!(0, import_utils23.isFunction)(baseFilterFn)) return { transformed: nextFilter ?? {}, scope: {}, filter: nextFilter ?? {} };
5327
+ if (!(0, import_utils24.isFunction)(baseFilterFn)) return { transformed: nextFilter ?? {}, scope: {}, filter: nextFilter ?? {} };
4845
5328
  const cached = cache.get(cacheKey);
4846
5329
  const reusable = cached?.resolver === baseFilterFn;
4847
5330
  const baseFilter = normalizeFilter(
@@ -4876,34 +5359,34 @@ async function setRequestPermissions(req) {
4876
5359
  if (owner === activeRuntime) return;
4877
5360
  if (hasFieldValue && owner === void 0) return;
4878
5361
  const globalPermissions = getGlobalOption("globalPermissions");
4879
- const permissions = (0, import_utils23.isFunction)(globalPermissions) ? await globalPermissions.call(req, req) : void 0;
4880
- if ((0, import_utils23.isPlainObject)(permissions)) req[requestPermissionField] = permissions;
4881
- else if ((0, import_utils23.isArray)(permissions)) req[requestPermissionField] = (0, import_utils23.arrayToRecord)(permissions);
4882
- else if ((0, import_utils23.isString)(permissions)) req[requestPermissionField] = { [permissions]: true };
5362
+ const permissions = (0, import_utils24.isFunction)(globalPermissions) ? await globalPermissions.call(req, req) : void 0;
5363
+ if ((0, import_utils24.isPlainObject)(permissions)) req[requestPermissionField] = permissions;
5364
+ else if ((0, import_utils24.isArray)(permissions)) req[requestPermissionField] = (0, import_utils24.arrayToRecord)(permissions);
5365
+ else if ((0, import_utils24.isString)(permissions)) req[requestPermissionField] = { [permissions]: true };
4883
5366
  else req[requestPermissionField] = {};
4884
5367
  owners.set(requestPermissionField, activeRuntime);
4885
5368
  }
4886
5369
  async function evaluateRouteGuard(req, permissions, routeGuard) {
4887
5370
  const phas = (key) => permissions.has(key);
4888
5371
  const { stringHandler, arrayHandler } = createValidator(phas);
4889
- if ((0, import_utils23.isBoolean)(routeGuard)) {
5372
+ if ((0, import_utils24.isBoolean)(routeGuard)) {
4890
5373
  return routeGuard === true;
4891
5374
  }
4892
- if ((0, import_utils23.isString)(routeGuard)) {
5375
+ if ((0, import_utils24.isString)(routeGuard)) {
4893
5376
  return stringHandler(routeGuard);
4894
5377
  }
4895
- if ((0, import_utils23.isArray)(routeGuard)) {
5378
+ if ((0, import_utils24.isArray)(routeGuard)) {
4896
5379
  return arrayHandler(routeGuard);
4897
5380
  }
4898
- if ((0, import_utils23.isFunction)(routeGuard)) {
5381
+ if ((0, import_utils24.isFunction)(routeGuard)) {
4899
5382
  return routeGuard.call(req, permissions);
4900
5383
  }
4901
5384
  return false;
4902
5385
  }
4903
5386
  async function callHookChain(req, hook, doc, permissions, context) {
4904
- const hooks = (0, import_utils23.castArray)(hook);
5387
+ const hooks = (0, import_utils24.castArray)(hook);
4905
5388
  for (let x = 0; x < hooks.length; x++) {
4906
- if ((0, import_utils23.isFunction)(hooks[x])) {
5389
+ if ((0, import_utils24.isFunction)(hooks[x])) {
4907
5390
  doc = await hooks[x].call(req, doc, permissions, context);
4908
5391
  }
4909
5392
  }
@@ -4923,23 +5406,23 @@ async function collectSchemaFields({
4923
5406
  for (let x = 0; x < keys2.length; x++) {
4924
5407
  const key = keys2[x];
4925
5408
  const value = extractScopedOutputRule(permissionSchema, key, access);
4926
- if ((0, import_utils23.isBoolean)(value)) {
5409
+ if ((0, import_utils24.isBoolean)(value)) {
4927
5410
  if (value) fields.push(key);
4928
- } else if ((0, import_utils23.isString)(value)) {
5411
+ } else if ((0, import_utils24.isString)(value)) {
4929
5412
  if (stringHandler(value)) fields.push(key);
4930
- } else if ((0, import_utils23.isArray)(value)) {
5413
+ } else if ((0, import_utils24.isArray)(value)) {
4931
5414
  if (arrayHandler(value)) fields.push(key);
4932
- } else if ((0, import_utils23.isFunction)(value)) {
5415
+ } else if ((0, import_utils24.isFunction)(value)) {
4933
5416
  if (await value.call(req, ...functionArgs)) fields.push(key);
4934
5417
  }
4935
5418
  }
4936
5419
  return fields;
4937
5420
  }
4938
- var import_utils23, import_node_util4, permissionFieldOwners;
5421
+ var import_utils24, import_node_util7, permissionFieldOwners;
4939
5422
  var init_core_shared = __esm({
4940
5423
  "src/core-shared.ts"() {
4941
- import_utils23 = require("@web-ts-toolkit/utils");
4942
- import_node_util4 = require("util");
5424
+ import_utils24 = require("@web-ts-toolkit/utils");
5425
+ import_node_util7 = require("util");
4943
5426
  init_helpers();
4944
5427
  init_options();
4945
5428
  init_runtime_context();
@@ -5307,8 +5790,8 @@ function equivalentVirtualPopulatePredicate(left, right) {
5307
5790
  }
5308
5791
  if (Array.isArray(left) || Array.isArray(right))
5309
5792
  return Array.isArray(left) && Array.isArray(right) && left.length === right.length && left.every((entry, index) => equivalentVirtualPopulatePredicate(entry, right[index]));
5310
- if ((0, import_utils27.isPlainObject)(left) || (0, import_utils27.isPlainObject)(right)) {
5311
- if (!(0, import_utils27.isPlainObject)(left) || !(0, import_utils27.isPlainObject)(right)) return false;
5793
+ if ((0, import_utils28.isPlainObject)(left) || (0, import_utils28.isPlainObject)(right)) {
5794
+ if (!(0, import_utils28.isPlainObject)(left) || !(0, import_utils28.isPlainObject)(right)) return false;
5312
5795
  const a = Object.keys(left), b = Object.keys(right);
5313
5796
  return a.length === b.length && a.every(
5314
5797
  (key, index) => key === b[index] && equivalentVirtualPopulatePredicate(
@@ -5317,7 +5800,7 @@ function equivalentVirtualPopulatePredicate(left, right) {
5317
5800
  )
5318
5801
  );
5319
5802
  }
5320
- return (0, import_node_util5.isDeepStrictEqual)(left, right);
5803
+ return (0, import_node_util8.isDeepStrictEqual)(left, right);
5321
5804
  }
5322
5805
  function createVirtualPopulateBatch(owner) {
5323
5806
  const batch = Object.freeze(/* @__PURE__ */ Object.create(null));
@@ -5692,12 +6175,12 @@ async function loadVirtualPopulateOutputRows(owner, inputs, plan, publicPopulate
5692
6175
  }
5693
6176
  return output;
5694
6177
  }
5695
- var import_mongoose7, import_node_util5, import_utils27, batches, rows, outputRows, fetchedPublicIdentities, publicViewIdentities, familyRawFetches, addressKey, storage, originalRef, copyOriginalValue, readPolicy, compatible, idKey, logUnavailable;
6178
+ var import_mongoose7, import_node_util8, import_utils28, batches, rows, outputRows, fetchedPublicIdentities, publicViewIdentities, familyRawFetches, addressKey, storage, originalRef, copyOriginalValue, readPolicy, compatible, idKey, logUnavailable;
5696
6179
  var init_virtual_populate_execution = __esm({
5697
6180
  "src/acl/virtual-populate-execution.ts"() {
5698
6181
  import_mongoose7 = require("mongoose");
5699
- import_node_util5 = require("util");
5700
- import_utils27 = require("@web-ts-toolkit/utils");
6182
+ import_node_util8 = require("util");
6183
+ import_utils28 = require("@web-ts-toolkit/utils");
5701
6184
  init_cache();
5702
6185
  init_core_shared();
5703
6186
  init_document();
@@ -5714,7 +6197,7 @@ var init_virtual_populate_execution = __esm({
5714
6197
  publicViewIdentities = /* @__PURE__ */ new WeakMap();
5715
6198
  familyRawFetches = /* @__PURE__ */ new WeakMap();
5716
6199
  addressKey = (address) => JSON.stringify(address);
5717
- storage = (value) => value instanceof import_mongoose7.Document ? value._doc : (0, import_utils27.isPlainObject)(value) ? value : void 0;
6200
+ storage = (value) => value instanceof import_mongoose7.Document ? value._doc : (0, import_utils28.isPlainObject)(value) ? value : void 0;
5718
6201
  originalRef = (source, key) => {
5719
6202
  const record3 = storage(source);
5720
6203
  return {
@@ -5741,20 +6224,48 @@ var init_virtual_populate_execution = __esm({
5741
6224
  });
5742
6225
 
5743
6226
  // src/acl/output-field-filter.ts
6227
+ function assertOwningOutputDocuments(handle) {
6228
+ const owner = readOutputDocumentOwner(handle);
6229
+ if (owner) {
6230
+ readDocumentAuthorizationAccess(owner.handle, owner.binding);
6231
+ assertOwningOutputDocuments(owner.handle);
6232
+ }
6233
+ }
6234
+ function prepareOutputDocumentAuthorization(authorization, binding, configuration) {
6235
+ const access = readServiceAuthorizationAccess(authorization, binding);
6236
+ const key = `docPermissions.${access.docPermissionsAccess}`;
6237
+ const docPermissions = configuration.docPermissions;
6238
+ const invariant = /^[A-Za-z0-9_-]+$/.test(access.docPermissionsAccess) && (docPermissions == null || (0, import_utils29.isPlainObject)(docPermissions));
6239
+ const option = invariant ? getCapturedAuthorizationOption(configuration, key) : void 0;
6240
+ const hook = typeof option === "function" ? option : void 0;
6241
+ const resolveHook = invariant ? () => hook : () => {
6242
+ const slice = { catalog: configuration.catalog, ...copyAuthorizationValue({ docPermissions }, true) };
6243
+ const option2 = getCapturedAuthorizationOption(slice, key);
6244
+ return typeof option2 === "function" ? option2 : void 0;
6245
+ };
6246
+ return async (args) => {
6247
+ if (args.authorization !== authorization) authorizationError("document resolver call mismatch");
6248
+ assertAuthorizationBinding(authorization, args.binding);
6249
+ return resolveOutputDocumentAuthorizationWithHook(args, access, resolveHook);
6250
+ };
6251
+ }
5744
6252
  async function resolveOutputDocumentAuthorization(args) {
6253
+ const configuration = readServiceDocumentPermissions(args.authorization, args.binding);
6254
+ return prepareOutputDocumentAuthorization(args.authorization, args.binding, configuration)(args);
6255
+ }
6256
+ async function resolveOutputDocumentAuthorizationWithHook(args, access, resolveHook) {
5745
6257
  const { authorization, binding } = args;
5746
- const { configuration, access } = readServiceAuthorization(authorization, binding);
5747
6258
  const stage = args.stage ?? createDocumentAuthorizationStage(authorization, binding, args.snapshot);
5748
6259
  if (args.stage) assertDocumentAuthorizationStage(stage, authorization, binding, args.snapshot);
5749
6260
  const handle = await resolveDocumentAuthorization(stage, async function(doc, permissions) {
5750
6261
  if (args.owningDocument) return readDocumentAuthorization(args.owningDocument, args.owningBinding).grants;
5751
6262
  if (args.knownOutput) return {};
5752
- const hook = getCapturedAuthorizationOption(configuration, `docPermissions.${access.docPermissionsAccess}`);
5753
- if (typeof hook !== "function") return {};
6263
+ const hook = resolveHook();
6264
+ if (!hook) return {};
5754
6265
  try {
5755
6266
  const run = () => hook.call(this, doc, permissions, args.context);
5756
6267
  const grants = await getRequestWorkState(binding.request, binding.runtime).hookGate.run(run);
5757
- return (0, import_utils28.isPlainObject)(grants) ? grants : {};
6268
+ return (0, import_utils29.isPlainObject)(grants) ? grants : {};
5758
6269
  } catch (error2) {
5759
6270
  warn("docPermissions hook failed; applying empty document permissions", {
5760
6271
  modelName: binding.modelName,
@@ -5765,13 +6276,12 @@ async function resolveOutputDocumentAuthorization(args) {
5765
6276
  return {};
5766
6277
  }
5767
6278
  });
5768
- if (args.knownOutput || args.owningDocument && unresolvedDocuments.has(args.owningDocument))
5769
- unresolvedDocuments.add(handle);
5770
- if (args.owningDocument) owningDocuments.set(handle, { handle: args.owningDocument, binding: args.owningBinding });
6279
+ bindOutputDocumentOwner(handle, args.knownOutput, args.owningDocument, args.owningBinding);
5771
6280
  return handle;
5772
6281
  }
5773
6282
  function evaluateRequestRule(handle, binding, entry, prefix, access) {
5774
- const owner = owningDocuments.get(handle);
6283
+ assertOwningOutputDocuments(handle);
6284
+ const owner = readOutputDocumentOwner(handle);
5775
6285
  if (owner && !entry.path.startsWith(`${(binding.scopePath ?? []).join(".")}.`)) {
5776
6286
  return evaluateRequestRule(owner.handle, owner.binding, entry, prefix, access);
5777
6287
  }
@@ -5779,65 +6289,84 @@ function evaluateRequestRule(handle, binding, entry, prefix, access) {
5779
6289
  handle,
5780
6290
  binding,
5781
6291
  `request:${access}:${entry.path}`,
5782
- function(permissions, grants) {
5783
- return evaluateScopedAccessRule({
5784
- req: this,
5785
- rule: entry.rule,
5786
- globalPermissions: permissions,
5787
- docPermissions: grants,
5788
- modelPermissionPrefix: prefix
5789
- });
6292
+ async function(permissions, grants) {
6293
+ const { authorization } = readDocumentAuthorizationAccess(handle, binding);
6294
+ const classification = requestRuleClassification(entry, authorization, permissions, prefix);
6295
+ let allowed = classification?.decision;
6296
+ if (allowed === void 0) {
6297
+ allowed = await evaluateScopedAccessRule({
6298
+ req: this,
6299
+ rule: entry.rule,
6300
+ globalPermissions: permissions,
6301
+ docPermissions: grants,
6302
+ modelPermissionPrefix: prefix
6303
+ });
6304
+ }
6305
+ assertOwningOutputDocuments(handle);
6306
+ return allowed;
5790
6307
  }
5791
6308
  );
5792
6309
  }
5793
6310
  function evaluateAuthorizedOutputField(handle, binding, field) {
5794
- const { authorization } = readDocumentAuthorization(handle, binding);
5795
- const { configuration, authorization: policy, access } = readServiceAuthorization(authorization, binding);
6311
+ const { authorization } = readDocumentAuthorizationAccess(handle, binding);
6312
+ assertOwningOutputDocuments(handle);
5796
6313
  const path = [...binding.scopePath ?? [], field].join(".");
5797
- const entries = extractOutputFieldRuleEntries(
5798
- configuration.permissionSchema,
5799
- path,
5800
- access.outputAccess
5801
- );
5802
- return memoizeDocumentFieldDecision(handle, binding, `output:${path}`, function(permissions, grants) {
5803
- const args = {
6314
+ const decision = memoizeDocumentFieldDecision(handle, binding, `output:${path}`, async function(permissions) {
6315
+ const policy = callFieldPolicy(authorization, binding);
6316
+ const { outputAccess } = readDocumentAuthorizationAccess(handle, binding);
6317
+ const prepared = prepareOutputPath(policy, authorization, binding, path, outputAccess);
6318
+ const unresolved = isUnresolvedOutputDocument(handle);
6319
+ const state = unresolved ? prepared.state ?? classifyEffectiveFieldAuthorization({
5804
6320
  path,
5805
- rules: entries.map((entry) => entry.rule),
6321
+ rules: prepared.entries.map((entry) => entry.rule),
6322
+ modelPermissionPrefix: policy.prefix,
5806
6323
  outputFields: policy.outputFields,
5807
- globalPermissions: permissions,
5808
- modelPermissionPrefix: configuration.modelPermissionPrefix ?? ""
5809
- };
5810
- if (unresolvedDocuments.has(handle) && classifyEffectiveFieldAuthorization(args) !== "granted") return false;
5811
- return evaluateEffectiveFieldAuthorization({
5812
- ...args,
5813
- req: this,
5814
- docPermissions: grants,
5815
- evaluateRule: (_rule, index) => evaluateRequestRule(handle, binding, entries[index], args.modelPermissionPrefix, access.outputAccess)
5816
- });
6324
+ globalPermissions: permissions
6325
+ }) : void 0;
6326
+ let allowed;
6327
+ if (unresolved && state !== "granted") allowed = false;
6328
+ else if (prepared.backendGrant) allowed = true;
6329
+ else {
6330
+ allowed = true;
6331
+ for (const entry of prepared.entries) {
6332
+ if (!await evaluateRequestRule(handle, binding, entry, policy.prefix, outputAccess)) {
6333
+ allowed = false;
6334
+ break;
6335
+ }
6336
+ }
6337
+ }
6338
+ assertOwningOutputDocuments(handle);
6339
+ return allowed;
5817
6340
  });
6341
+ return readOutputDocumentOwner(handle) ? decision.then((allowed) => {
6342
+ assertOwningOutputDocuments(handle);
6343
+ return allowed;
6344
+ }) : decision;
5818
6345
  }
5819
6346
  async function requestOutputFieldPaths(handle, binding, access) {
5820
- const { authorization } = readDocumentAuthorization(handle, binding);
5821
- const { configuration } = readServiceAuthorization(authorization, binding);
5822
- const schema = configuration.permissionSchema;
6347
+ const staticFields = tryStaticRequestFieldPaths(handle, binding, access);
6348
+ if (staticFields) {
6349
+ await Promise.resolve();
6350
+ readDocumentAuthorizationAccess(handle, binding);
6351
+ return staticFields;
6352
+ }
6353
+ const { authorization } = readDocumentAuthorizationAccess(handle, binding);
6354
+ assertOwningOutputDocuments(handle);
6355
+ const policy = callFieldPolicy(authorization, binding);
5823
6356
  const fields = [];
5824
- for (const path of Object.keys(schema ?? {})) {
5825
- const entries = extractOutputFieldRuleEntries(schema, path, access);
6357
+ for (const path of policy.requestPaths ?? Object.keys(policy.schema ?? {})) {
6358
+ const { entries } = prepareOutputPath(policy, authorization, binding, path, access);
5826
6359
  let allowed = true;
5827
6360
  for (const entry of entries) {
5828
- if (!await evaluateRequestRule(
5829
- handle,
5830
- binding,
5831
- entry,
5832
- configuration.modelPermissionPrefix ?? "",
5833
- access
5834
- )) {
6361
+ if (!await evaluateRequestRule(handle, binding, entry, policy.prefix, access)) {
5835
6362
  allowed = false;
5836
6363
  break;
5837
6364
  }
5838
6365
  }
5839
6366
  if (allowed && entries.length) fields.push(path);
5840
6367
  }
6368
+ assertOwningOutputDocuments(handle);
6369
+ readDocumentAuthorizationAccess(handle, binding);
5841
6370
  return fields;
5842
6371
  }
5843
6372
  function authorizeEmbeddedOutputPlan(parent, child) {
@@ -5858,24 +6387,24 @@ function authorizeEmbeddedOutputPlan(parent, child) {
5858
6387
  function hasWholeOutputValueGrant(plan, field) {
5859
6388
  if (plan.fieldStates?.[field] !== "granted") return false;
5860
6389
  const binding = plan.authorizationBinding;
5861
- const { authorization } = readServiceAuthorization(plan.authorization, binding);
5862
- return hasExplicitFieldGrant(authorization.outputFields, [...binding.scopePath ?? [], field].join("."));
6390
+ const { outputFields } = readServiceOutputPolicy(plan.authorization, binding);
6391
+ return hasExplicitFieldGrant(outputFields, [...binding.scopePath ?? [], field].join("."));
5863
6392
  }
5864
6393
  function copyOutputValue(value, plan, path) {
5865
- const { configuration } = readServiceAuthorization(plan.authorization, plan.authorizationBinding);
5866
- const virtualValue = configuration.catalog.virtualPaths?.some((p) => matchesCatalogPattern(p, path));
5867
- const opaque = configuration.catalog.opaquePaths?.some((p) => matchesCatalogPattern(p, path));
6394
+ const { catalog } = readServiceOutputPolicy(plan.authorization, plan.authorizationBinding);
6395
+ const virtualValue = catalog.virtualPaths?.some((p) => matchesCatalogPattern(p, path));
6396
+ const opaque = catalog.opaquePaths?.some((p) => matchesCatalogPattern(p, path));
5868
6397
  const excluded = plan.effectiveSelectNorm.filter((token) => token.startsWith("-")).map((token) => [...plan.authorizationBinding.scopePath ?? [], token.slice(1)].join("."));
5869
6398
  const visit = (input, current) => {
5870
6399
  if (Array.isArray(input)) return input.map((entry) => visit(entry, current));
5871
6400
  if (input instanceof Map) return visit(Object.fromEntries(input), current);
5872
- if (!(0, import_utils28.isPlainObject)(input)) return deepIsolateValue(input);
6401
+ if (!(0, import_utils29.isPlainObject)(input)) return deepIsolateValue(input);
5873
6402
  const output = {};
5874
6403
  for (const [key, entry] of Object.entries(input)) {
5875
6404
  const child = `${current}.${key}`;
5876
6405
  if (excluded.some((entry2) => child === entry2 || child.startsWith(`${entry2}.`))) continue;
5877
6406
  const safeValueKey = !["__proto__", "constructor", "prototype", "_doc", "$__", "__v"].includes(key);
5878
- if (!(opaque ? safeValueKey : isSafeOutputPath(key)) || configuration.catalog.protectedPaths?.some((p) => matchesCatalogPattern(p, child, true)) || !opaque && !virtualValue && !isCatalogOutputPath(configuration.catalog, child))
6407
+ if (!(opaque ? safeValueKey : isSafeOutputPath(key)) || catalog.protectedPaths?.some((p) => matchesCatalogPattern(p, child, true)) || !opaque && !virtualValue && !isCatalogOutputPath(catalog, child))
5879
6408
  continue;
5880
6409
  output[key] = visit(entry, child);
5881
6410
  }
@@ -5885,7 +6414,7 @@ function copyOutputValue(value, plan, path) {
5885
6414
  }
5886
6415
  function copyAuthorizedReference(value, plan, path) {
5887
6416
  if (Array.isArray(value)) return value.map((entry) => copyAuthorizedReference(entry, plan, path));
5888
- if (!(0, import_utils28.isPlainObject)(value)) return deepIsolateValue(value);
6417
+ if (!(0, import_utils29.isPlainObject)(value)) return deepIsolateValue(value);
5889
6418
  const handle = getAssociatedDocumentAuthorization(value, plan.authorization);
5890
6419
  if (handle) {
5891
6420
  const copy = deepIsolateValue(value);
@@ -5898,8 +6427,8 @@ function retainOutputMetadata(output, source, configuration, scope2) {
5898
6427
  if (scope2.length || configuration.stripPermissionsField) return;
5899
6428
  const parts = (configuration.documentPermissionField ?? "_permissions").split(".");
5900
6429
  let value = source;
5901
- for (const part of parts) value = (0, import_utils28.isPlainObject)(value) ? value[part] : void 0;
5902
- if (!(0, import_utils28.isPlainObject)(value)) return;
6430
+ for (const part of parts) value = (0, import_utils29.isPlainObject)(value) ? value[part] : void 0;
6431
+ if (!(0, import_utils29.isPlainObject)(value)) return;
5903
6432
  const keys2 = configuration.exposedDocPermissionKeys;
5904
6433
  const metadata = Object.fromEntries(
5905
6434
  Object.entries(value).filter(
@@ -5909,7 +6438,7 @@ function retainOutputMetadata(output, source, configuration, scope2) {
5909
6438
  const copy = { ...output };
5910
6439
  let target = copy;
5911
6440
  for (const part of parts.slice(0, -1)) {
5912
- target[part] = (0, import_utils28.isPlainObject)(target[part]) ? { ...target[part] } : {};
6441
+ target[part] = (0, import_utils29.isPlainObject)(target[part]) ? { ...target[part] } : {};
5913
6442
  target = target[part];
5914
6443
  }
5915
6444
  target[parts[parts.length - 1]] = deepIsolateValue(metadata);
@@ -5918,27 +6447,37 @@ function retainOutputMetadata(output, source, configuration, scope2) {
5918
6447
  attachPermissionsAlias(output, parts.join("."));
5919
6448
  }
5920
6449
  function helperPlan(authorization, binding) {
5921
- const { configuration, authorization: policy, access } = readServiceAuthorization(authorization, binding);
5922
- if (binding.scopePath?.length && !isCatalogOutputPath(configuration.catalog, binding.scopePath.join(".")))
5923
- authorizationError("unknown output scope");
5924
- const plan = planCatalogProjection(
5925
- {
5926
- receivingModelName: binding.modelName,
5927
- snapshot: configuration,
5928
- ...access,
5929
- effectiveSelect: [],
5930
- scopePath: (binding.scopePath ?? []).flatMap((part) => [part, "sub"]),
5931
- globalPermissions: getAuthorizationPermissions(authorization, binding)
5932
- },
5933
- policy.outputFields
5934
- );
5935
- return { ...plan, authorization, authorizationBinding: binding };
6450
+ return planAuthorizedModelProjection({ authorization, binding, effectiveSelect: [] });
6451
+ }
6452
+ function primitiveHelperFields(source, plan) {
6453
+ if (import_node_util9.types.isProxy(source)) return;
6454
+ const canonical = readStaticOutputPlanFields(plan, plan.authorization);
6455
+ if (!canonical) return;
6456
+ const fields = [];
6457
+ for (const field of canonical) {
6458
+ const slot = Object.getOwnPropertyDescriptor(source, field);
6459
+ if (!slot) continue;
6460
+ if (!("value" in slot)) return;
6461
+ const value = slot.value;
6462
+ if (value !== null && typeof value === "object" || typeof value === "function" || typeof value === "symbol")
6463
+ return;
6464
+ if (value !== void 0) fields.push(field);
6465
+ }
6466
+ return fields;
5936
6467
  }
5937
6468
  async function filterExistingOutput(source, plan, handle, associated) {
5938
6469
  const binding = plan.authorizationBinding;
5939
6470
  const { configuration } = readServiceAuthorization(plan.authorization, binding);
5940
6471
  const output = {};
5941
6472
  const fields = [];
6473
+ const primitiveFields = primitiveHelperFields(source, plan);
6474
+ const staticDecisions = primitiveFields && tryStaticOutputFieldDecisions(handle, binding, plan, primitiveFields);
6475
+ if (staticDecisions) {
6476
+ await Promise.resolve();
6477
+ if (associated) assertDocumentAuthorization(handle, { binding, output: source, outputAccess: plan.outputAccess });
6478
+ else readDocumentAuthorizationAccess(handle, binding);
6479
+ if (!readStaticOutputPlanFields(plan, plan.authorization)) authorizationError("changed static output plan");
6480
+ }
5942
6481
  for (const field of /* @__PURE__ */ new Set([...plan.outputPersistedFields, ...plan.outputVirtualNames])) {
5943
6482
  if (!Object.prototype.hasOwnProperty.call(source, field) || source[field] === void 0) continue;
5944
6483
  const childPlan = plan.childPlans[field];
@@ -5951,11 +6490,11 @@ async function filterExistingOutput(source, plan, handle, associated) {
5951
6490
  for (const entry of value2) values.push(await one(entry) ?? null);
5952
6491
  return values;
5953
6492
  }
5954
- if (!(0, import_utils28.isPlainObject)(value2)) return value2 === null ? null : void 0;
6493
+ if (!(0, import_utils29.isPlainObject)(value2)) return value2 === null ? null : void 0;
5955
6494
  const childHandle = associated ? getAssociatedDocumentAuthorization(value2) : void 0;
5956
6495
  let child = scoped;
5957
6496
  if (childHandle) {
5958
- const state = readDocumentAuthorization(childHandle, scoped.authorizationBinding);
6497
+ const state = readDocumentAuthorizationAccess(childHandle, scoped.authorizationBinding);
5959
6498
  if (getAuthorizationProvenance(state.authorization) !== getAuthorizationProvenance(plan.authorization))
5960
6499
  authorizationError("child call mismatch");
5961
6500
  child = helperPlan(state.authorization, scoped.authorizationBinding);
@@ -5979,7 +6518,7 @@ async function filterExistingOutput(source, plan, handle, associated) {
5979
6518
  const value = await one(source[field]);
5980
6519
  if (value !== void 0) output[field] = value;
5981
6520
  fields.push(...childFields);
5982
- } else if (await evaluateAuthorizedOutputField(handle, binding, field)) {
6521
+ } else if (staticDecisions ? staticDecisions.get(field) === true : await evaluateAuthorizedOutputField(handle, binding, field)) {
5983
6522
  const path = [...binding.scopePath ?? [], field].join(".");
5984
6523
  output[field] = configuration.catalog.referencePaths?.some((p) => matchesCatalogPattern(p, path)) ? copyAuthorizedReference(source[field], plan, path) : copyOutputValue(source[field], plan, path);
5985
6524
  if (associated) transferDocumentAuthorizationGraph(source[field], output[field]);
@@ -6019,7 +6558,7 @@ async function filterModelOutputForHelper(args) {
6019
6558
  if (normalized.kind === "document") {
6020
6559
  const { documentAuthorization: handle2, binding: binding2 } = normalized;
6021
6560
  assertDocumentAuthorization(handle2, { binding: binding2, output: args.doc, outputAccess: access });
6022
- const state = readDocumentAuthorization(handle2, binding2);
6561
+ const state = readDocumentAuthorizationAccess(handle2, binding2);
6023
6562
  return filterExistingOutput(
6024
6563
  args.doc,
6025
6564
  helperPlan(state.authorization, binding2),
@@ -6031,7 +6570,7 @@ async function filterModelOutputForHelper(args) {
6031
6570
  const plan = helperPlan(normalized.authorization, binding);
6032
6571
  if (args.doc == null) return { output: args.doc, fields: [] };
6033
6572
  const source = isolateDocForOutput(args.doc);
6034
- if (!(0, import_utils28.isPlainObject)(source)) return authorizationError("output helper requires one plain or hydrated document");
6573
+ if (!(0, import_utils29.isPlainObject)(source)) return authorizationError("output helper requires one plain or hydrated document");
6035
6574
  const knownOutput = !!args.doc && typeof args.doc === "object" && isKnownAuthorizationOutput(args.doc);
6036
6575
  const handle = await resolveOutputDocumentAuthorization({
6037
6576
  authorization: normalized.authorization,
@@ -6042,10 +6581,11 @@ async function filterModelOutputForHelper(args) {
6042
6581
  });
6043
6582
  return filterExistingOutput(source, plan, handle, false);
6044
6583
  }
6045
- var import_utils28, unresolvedDocuments, owningDocuments;
6584
+ var import_node_util9, import_utils29;
6046
6585
  var init_output_field_filter = __esm({
6047
6586
  "src/acl/output-field-filter.ts"() {
6048
- import_utils28 = require("@web-ts-toolkit/utils");
6587
+ import_node_util9 = require("util");
6588
+ import_utils29 = require("@web-ts-toolkit/utils");
6049
6589
  init_permissions_alias();
6050
6590
  init_document();
6051
6591
  init_request_work();
@@ -6057,8 +6597,7 @@ var init_output_field_filter = __esm({
6057
6597
  init_field_authorization();
6058
6598
  init_field_catalog();
6059
6599
  init_output_projection();
6060
- unresolvedDocuments = /* @__PURE__ */ new WeakSet();
6061
- owningDocuments = /* @__PURE__ */ new WeakMap();
6600
+ init_output_field_policy();
6062
6601
  }
6063
6602
  });
6064
6603
 
@@ -6127,27 +6666,53 @@ __export(finalize_model_output_exports, {
6127
6666
  finalizeModelOutput: () => finalizeModelOutput,
6128
6667
  finalizeModelOutputs: () => finalizeModelOutputs
6129
6668
  });
6130
- async function finalizeSingleDoc(args, input) {
6131
- const scopePath = args.scopePath;
6669
+ function assertFinalizerCall(args, prepared) {
6132
6670
  const plan = args.plan;
6133
6671
  const binding = plan.authorizationBinding;
6134
- const captured = plan.authorization && binding ? readServiceAuthorization(plan.authorization, binding) : void 0;
6135
- if (plan.authorization && (!binding || binding.request !== args.request || binding.modelName !== args.receivingModelName || captured?.access.virtualAccess !== args.virtualAccess || captured.access.outputAccess !== args.outputAccess || captured.access.docPermissionsAccess !== args.docPermissionsAccess || (binding.scopePath ?? []).join(".") !== scopePath.filter((p) => p !== "sub").join("."))) {
6672
+ if (plan.authorization !== prepared.authorization) authorizationError("finalizer call changed during pass");
6673
+ if (plan.authorization && binding) assertAuthorizationBinding(plan.authorization, binding);
6674
+ const access = prepared.policy?.access;
6675
+ if (plan.authorization && (!binding || binding.request !== args.request || binding.modelName !== args.receivingModelName || access?.virtualAccess !== args.virtualAccess || access.outputAccess !== args.outputAccess || access.docPermissionsAccess !== args.docPermissionsAccess || (binding.scopePath ?? []).join(".") !== args.scopePath.filter((p) => p !== "sub").join("."))) {
6136
6676
  authorizationError("finalizer call/model/scope/access mismatch");
6137
6677
  }
6138
- const snapshot = captured ? captured.configuration : args.snapshot;
6678
+ }
6679
+ function prepareFinalizer(args, sharedContext = false) {
6680
+ const { authorization, authorizationBinding: binding } = args.plan;
6681
+ const policy = authorization && binding ? readServiceOutputPolicy(authorization, binding) : void 0;
6682
+ assertFinalizerCall(args, { authorization, policy });
6683
+ const configuration = authorization ? readServiceFinalizerConfiguration(authorization, binding) : void 0;
6684
+ const snapshot = configuration ? configuration : deepIsolateValue(args.snapshot);
6685
+ return {
6686
+ authorization,
6687
+ policy,
6688
+ snapshot,
6689
+ baseContext: deepIsolateValue(args.context ?? {}),
6690
+ sharedContext,
6691
+ scopeVirtualNames: getScopeVirtualNames(snapshot, args.scopePath),
6692
+ scopedSchema: configuration ? null : getScopedPermissionSchema2(snapshot.permissionSchema, args.scopePath),
6693
+ permissions: authorization ? getAuthorizationPermissions(authorization, binding) : void 0,
6694
+ resolveDocument: authorization ? prepareOutputDocumentAuthorization(authorization, binding, configuration) : void 0
6695
+ };
6696
+ }
6697
+ async function finalizeSingleDoc(args, input, prepared) {
6698
+ assertFinalizerCall(args, prepared);
6699
+ const scopePath = args.scopePath;
6700
+ const plan = args.plan;
6701
+ const binding = plan.authorizationBinding;
6702
+ const captured = prepared.policy;
6703
+ const snapshot = prepared.snapshot;
6139
6704
  const limit = args.resolvedLimit;
6140
6705
  const gate = args.sharedGate;
6141
6706
  const original = getIncludeOriginal(input);
6142
6707
  const privateRow = args.virtualPopulateRow ?? (original && typeof original === "object" ? getVirtualPopulateRow(original) : void 0);
6143
6708
  const privateAddress = args.virtualPopulateAddress ?? [];
6144
6709
  const isolated = isolateDocForOutput(input);
6145
- const output = (0, import_utils29.isPlainObject)(isolated) ? isolated : {};
6146
- if (captured && (0, import_utils29.isPlainObject)(input))
6710
+ const output = (0, import_utils30.isPlainObject)(isolated) ? isolated : {};
6711
+ if (captured && (0, import_utils30.isPlainObject)(input))
6147
6712
  for (const key of Object.keys(output)) {
6148
6713
  transferDocumentAuthorizationGraph(input[key], output[key]);
6149
6714
  }
6150
- const baseContext = args.context ?? {};
6715
+ const baseContext = prepared.sharedContext ? deepIsolateValue(prepared.baseContext) : prepared.baseContext;
6151
6716
  const operation = captured?.access.operation ?? baseContext.operation ?? args.operation ?? args.virtualAccess;
6152
6717
  const scopeContext = {
6153
6718
  ...baseContext,
@@ -6165,7 +6730,7 @@ async function finalizeSingleDoc(args, input) {
6165
6730
  if (captured) {
6166
6731
  const projected = args.documentAuthorizationStage ? input : deepIsolateValue(output);
6167
6732
  metadataSource = deepIsolateValue(output);
6168
- documentAuthorization = await resolveOutputDocumentAuthorization({
6733
+ documentAuthorization = await prepared.resolveDocument({
6169
6734
  authorization: plan.authorization,
6170
6735
  binding,
6171
6736
  snapshot: projected,
@@ -6178,13 +6743,10 @@ async function finalizeSingleDoc(args, input) {
6178
6743
  }
6179
6744
  const docGrants = documentAuthorization ? readDocumentAuthorization(documentAuthorization, binding).grants : await resolveDocPermissions(args, output, scopeContext);
6180
6745
  scopeContext.docPermissions = deepIsolateValue(docGrants);
6181
- const globalPerms = captured ? getAuthorizationPermissions(plan.authorization, binding) : resolveGlobalPermissions(args);
6182
- const modelPermissionPrefix = snapshot.modelPermissionPrefix ?? "";
6183
- const documentPermissionField = snapshot.documentPermissionField ?? "_permissions";
6184
- const scopedSchema = getScopedPermissionSchema2(
6185
- snapshot.permissionSchema ?? null,
6186
- scopePath
6187
- );
6746
+ const globalPerms = prepared.permissions ?? resolveGlobalPermissions(args);
6747
+ const modelPermissionPrefix = captured ? "" : deepIsolateValue(snapshot.modelPermissionPrefix ?? "");
6748
+ const documentPermissionField = captured ? "_permissions" : deepIsolateValue(snapshot.documentPermissionField ?? "_permissions");
6749
+ const scopedSchema = deepIsolateValue(prepared.scopedSchema);
6188
6750
  const childPlans = plan.childPlans ?? {};
6189
6751
  for (const [containerName, childPlan] of Object.entries(childPlans)) {
6190
6752
  if (!(containerName in output)) continue;
@@ -6198,17 +6760,18 @@ async function finalizeSingleDoc(args, input) {
6198
6760
  );
6199
6761
  continue;
6200
6762
  }
6201
- if (captured && !(0, import_utils29.isPlainObject)(rawContainer) && !Array.isArray(rawContainer)) {
6763
+ if (captured && !(0, import_utils30.isPlainObject)(rawContainer) && !Array.isArray(rawContainer)) {
6202
6764
  delete output[containerName];
6203
6765
  continue;
6204
6766
  }
6205
6767
  retainRawAssociation(output, containerName, rawContainer);
6206
- const childSnapshot = snapshot;
6207
6768
  const childBase = {
6208
6769
  ...args,
6209
6770
  scopePath: [...childPlan.scopePath ?? [...scopePath, containerName, "sub"]],
6210
6771
  plan: captured ? authorizeEmbeddedOutputPlan(plan, childPlan) : childPlan,
6211
- snapshot: childSnapshot,
6772
+ // Authenticated preparation reads its own authority. Do not clone an
6773
+ // otherwise unused public configuration graph on default traversal.
6774
+ snapshot: args.snapshot,
6212
6775
  // Embedded reuses the owning parent's grants + accesses (VIRT-00A D2).
6213
6776
  docPermissions: docGrants,
6214
6777
  context: scopeContext,
@@ -6219,10 +6782,11 @@ async function finalizeSingleDoc(args, input) {
6219
6782
  related: [],
6220
6783
  virtualPopulateRow: privateRow
6221
6784
  };
6785
+ let childPreparation;
6222
6786
  const finalizeOneChild = async (rawChild, address) => {
6223
6787
  if (captured && Array.isArray(rawChild))
6224
6788
  return mapWithConcurrencyLimit(rawChild, limit, (entry, index) => finalizeOneChild(entry, [...address, index]));
6225
- if (!(0, import_utils29.isPlainObject)(rawChild) && !Array.isArray(rawChild)) return captured ? null : deepIsolateValue(rawChild);
6789
+ if (!(0, import_utils30.isPlainObject)(rawChild) && !Array.isArray(rawChild)) return captured ? null : deepIsolateValue(rawChild);
6226
6790
  if (args.traversal?.finalizeEmbeddedChildren) {
6227
6791
  return args.traversal.finalizeEmbeddedChildren({
6228
6792
  containerName,
@@ -6239,7 +6803,14 @@ async function finalizeSingleDoc(args, input) {
6239
6803
  } : { ...args, virtualPopulateRow: privateRow, virtualPopulateAddress: address }
6240
6804
  });
6241
6805
  }
6242
- return finalizeSingleDoc({ ...childBase, virtualPopulateAddress: address }, rawChild);
6806
+ return finalizeSingleDoc(
6807
+ { ...childBase, virtualPopulateAddress: address },
6808
+ rawChild,
6809
+ childPreparation ??= prepareFinalizer(
6810
+ childBase,
6811
+ Array.isArray(rawContainer) && (rawContainer.length > 1 || Array.isArray(rawContainer[0]))
6812
+ )
6813
+ );
6243
6814
  };
6244
6815
  if (Array.isArray(rawContainer)) {
6245
6816
  const finalized = await mapWithConcurrencyLimit(
@@ -6248,7 +6819,7 @@ async function finalizeSingleDoc(args, input) {
6248
6819
  (entry, index) => finalizeOneChild(entry, [...privateAddress, containerName, index])
6249
6820
  );
6250
6821
  output[containerName] = finalized;
6251
- } else if ((0, import_utils29.isPlainObject)(rawContainer)) {
6822
+ } else if ((0, import_utils30.isPlainObject)(rawContainer)) {
6252
6823
  output[containerName] = await finalizeOneChild(rawContainer, [
6253
6824
  ...privateAddress,
6254
6825
  containerName
@@ -6260,8 +6831,8 @@ async function finalizeSingleDoc(args, input) {
6260
6831
  let rawRelated;
6261
6832
  let originalRelated;
6262
6833
  try {
6263
- rawRelated = target.path.includes(".") ? (0, import_utils29.get)(output, target.path) : output[target.path];
6264
- originalRelated = (0, import_utils29.get)(original, target.path);
6834
+ rawRelated = target.path.includes(".") ? (0, import_utils30.get)(output, target.path) : output[target.path];
6835
+ originalRelated = (0, import_utils30.get)(original, target.path);
6265
6836
  } catch {
6266
6837
  continue;
6267
6838
  }
@@ -6291,8 +6862,9 @@ async function finalizeSingleDoc(args, input) {
6291
6862
  context: scopeContext,
6292
6863
  related: target.plan.relatedPlans?.length ? (args.related ?? []).filter((entry) => entry.path.startsWith(`${target.path}.`)) : []
6293
6864
  };
6865
+ let relatedPreparation;
6294
6866
  const finalizeOneRelated = async (rawChild, originalChild = rawChild) => {
6295
- if (!(0, import_utils29.isPlainObject)(rawChild) && !Array.isArray(rawChild)) return rawChild;
6867
+ if (!(0, import_utils30.isPlainObject)(rawChild) && !Array.isArray(rawChild)) return rawChild;
6296
6868
  if (typeof rawChild?._bsontype === "string") return rawChild;
6297
6869
  const childOriginal = getIncludeOriginal(originalChild);
6298
6870
  const childRow = childOriginal && typeof childOriginal === "object" ? getVirtualPopulateRow(childOriginal) : void 0;
@@ -6304,7 +6876,11 @@ async function finalizeSingleDoc(args, input) {
6304
6876
  parentArgs: { ...args, virtualPopulateRow: childRow, virtualPopulateAddress: [] }
6305
6877
  });
6306
6878
  }
6307
- return finalizeSingleDoc({ ...relatedBase, virtualPopulateRow: childRow }, rawChild);
6879
+ return finalizeSingleDoc(
6880
+ { ...relatedBase, virtualPopulateRow: childRow },
6881
+ rawChild,
6882
+ relatedPreparation ??= prepareFinalizer(relatedBase, Array.isArray(rawRelated) && rawRelated.length > 1)
6883
+ );
6308
6884
  };
6309
6885
  let finalized;
6310
6886
  if (Array.isArray(rawRelated)) {
@@ -6313,29 +6889,35 @@ async function finalizeSingleDoc(args, input) {
6313
6889
  limit,
6314
6890
  (entry, index) => finalizeOneRelated(entry, Array.isArray(originalRelated) ? originalRelated[index] : void 0)
6315
6891
  );
6316
- } else if ((0, import_utils29.isPlainObject)(rawRelated)) {
6892
+ } else if ((0, import_utils30.isPlainObject)(rawRelated)) {
6317
6893
  finalized = await finalizeOneRelated(rawRelated, originalRelated);
6318
6894
  } else {
6319
6895
  continue;
6320
6896
  }
6321
6897
  try {
6322
- if (target.path.includes(".")) (0, import_utils29.set)(output, target.path, finalized);
6898
+ if (target.path.includes(".")) (0, import_utils30.set)(output, target.path, finalized);
6323
6899
  else output[target.path] = finalized;
6324
6900
  } catch {
6325
6901
  }
6326
6902
  }
6327
- const scopeVirtualNames = getScopeVirtualNames(snapshot, scopePath);
6328
- for (const virtualName of scopeVirtualNames) {
6903
+ for (const virtualName of prepared.scopeVirtualNames) {
6329
6904
  if (virtualName in output) delete output[virtualName];
6330
6905
  }
6331
- const stableBase = deepIsolateValue(output);
6332
- const scopeLabel = scopePath.length > 0 ? scopePath.join(".") : "";
6333
6906
  const candidates = plan.candidates ?? [];
6907
+ const needsGetterView = candidates.some((candidate) => {
6908
+ const descriptor = candidate.descriptor;
6909
+ if (typeof descriptor?.get !== "function") return false;
6910
+ if (!privateRow && descriptor.dependsOnPopulate?.length) return false;
6911
+ const dependsOn = Array.isArray(descriptor.dependsOn) ? descriptor.dependsOn : [];
6912
+ return dependsOn.every((dep) => typeof dep === "string" && !isAbsentDependency(output, dep));
6913
+ });
6914
+ let stableBase = needsGetterView ? deepIsolateValue(output) : void 0;
6915
+ const scopeLabel = scopePath.length > 0 ? scopePath.join(".") : "";
6334
6916
  const staged = /* @__PURE__ */ new Map();
6335
6917
  const runCandidate = async (candidate) => {
6336
6918
  const dependsOn = Array.isArray(candidate.descriptor?.dependsOn) ? candidate.descriptor.dependsOn : [];
6337
6919
  for (const dep of dependsOn) {
6338
- if (typeof dep !== "string" || isAbsentDependency(stableBase, dep)) return;
6920
+ if (typeof dep !== "string" || isAbsentDependency(stableBase ?? output, dep)) return;
6339
6921
  }
6340
6922
  const allowed = documentAuthorization ? await evaluateAuthorizedOutputField(documentAuthorization, binding, candidate.name) : await evaluateEffectiveFieldAuthorization({
6341
6923
  req: args.request,
@@ -6350,9 +6932,9 @@ async function finalizeSingleDoc(args, input) {
6350
6932
  if (typeof getter !== "function") return;
6351
6933
  const privateInputs = privateRow ? readVirtualPopulateInputs(privateRow, privateAddress, candidate.name) : candidate.descriptor.dependsOnPopulate?.length ? { available: false } : { available: true, populated: {} };
6352
6934
  if (!privateInputs.available) return;
6353
- const isolatedView = deepIsolateValue(stableBase);
6935
+ const isolatedView = deepIsolateValue(stableBase ??= deepIsolateValue(output));
6354
6936
  const virtualContext = {
6355
- ...scopeContext,
6937
+ ...deepIsolateValue(scopeContext),
6356
6938
  docPermissions: deepIsolateValue(docGrants)
6357
6939
  };
6358
6940
  const outcome = await runVirtualGetter({
@@ -6392,10 +6974,17 @@ async function finalizeSingleDoc(args, input) {
6392
6974
  }
6393
6975
  const eligiblePersisted = new Set(plan.outputPersistedFields ?? []);
6394
6976
  const eligibleVirtuals = new Set(plan.outputVirtualNames ?? []);
6977
+ const staticDecisions = documentAuthorization ? tryStaticOutputFieldDecisions(documentAuthorization, binding, plan, [...eligiblePersisted]) : void 0;
6978
+ if (staticDecisions) {
6979
+ await Promise.resolve();
6980
+ assertFinalizerCall(args, prepared);
6981
+ readDocumentAuthorizationAccess(documentAuthorization, binding);
6982
+ if (!readStaticOutputPlanFields(plan, prepared.authorization)) authorizationError("changed static output plan");
6983
+ }
6395
6984
  const allowedPersisted = [];
6396
6985
  for (const field of eligiblePersisted) {
6397
6986
  if (documentAuthorization) {
6398
- if (plan.childPlans[field] || await evaluateAuthorizedOutputField(documentAuthorization, binding, field))
6987
+ if (plan.childPlans[field] || (staticDecisions ? staticDecisions.get(field) === true : await evaluateAuthorizedOutputField(documentAuthorization, binding, field)))
6399
6988
  allowedPersisted.push(field);
6400
6989
  continue;
6401
6990
  }
@@ -6443,12 +7032,25 @@ async function finalizeSingleDoc(args, input) {
6443
7032
  if (!(key in output)) continue;
6444
7033
  if (captured && !plan.childPlans[key]) {
6445
7034
  const path = [...binding.scopePath ?? [], key].join(".");
6446
- trimmed[key] = captured.configuration.catalog.referencePaths?.some((p) => matchesCatalogPattern(p, path)) ? copyAuthorizedReference(output[key], plan, path) : copyOutputValue(output[key], plan, path);
7035
+ trimmed[key] = captured.catalog.referencePaths?.some((p) => matchesCatalogPattern(p, path)) ? copyAuthorizedReference(output[key], plan, path) : copyOutputValue(output[key], plan, path);
6447
7036
  if (trimmed[key] === void 0) delete trimmed[key];
6448
7037
  } else trimmed[key] = output[key];
6449
7038
  }
6450
7039
  if (documentAuthorization) {
6451
- retainOutputMetadata(trimmed, metadataSource, captured.configuration, binding.scopePath ?? []);
7040
+ retainOutputMetadata(
7041
+ trimmed,
7042
+ metadataSource,
7043
+ copyAuthorizationValue(
7044
+ {
7045
+ documentPermissionField: snapshot.documentPermissionField,
7046
+ stripPermissionsField: snapshot.stripPermissionsField,
7047
+ exposedDocPermissionKeys: snapshot.exposedDocPermissionKeys,
7048
+ disableFieldPermissions: snapshot.disableFieldPermissions
7049
+ },
7050
+ true
7051
+ ),
7052
+ binding.scopePath ?? []
7053
+ );
6452
7054
  associateDocumentAuthorization(documentAuthorization, binding, trimmed);
6453
7055
  args.onFinalized?.(
6454
7056
  trimmed,
@@ -6457,9 +7059,13 @@ async function finalizeSingleDoc(args, input) {
6457
7059
  output: trimmed,
6458
7060
  outputAccess: args.outputAccess,
6459
7061
  authorization: plan.authorization,
6460
- stage: readDocumentAuthorization(documentAuthorization, binding).stage
7062
+ stage: readDocumentAuthorizationAccess(documentAuthorization, binding).stage
6461
7063
  })
6462
7064
  );
7065
+ if (staticDecisions) {
7066
+ assertFinalizerCall(args, prepared);
7067
+ readDocumentAuthorizationAccess(documentAuthorization, binding);
7068
+ }
6463
7069
  }
6464
7070
  void getRetainedAssociations;
6465
7071
  return trimmed;
@@ -6478,7 +7084,7 @@ async function finalizeModelOutput(args) {
6478
7084
  sharedGate: gate,
6479
7085
  resolvedLimit: limit
6480
7086
  };
6481
- return finalizeSingleDoc(internal, args.input);
7087
+ return finalizeSingleDoc(internal, args.input, prepareFinalizer(internal));
6482
7088
  }
6483
7089
  async function finalizeModelOutputs(args) {
6484
7090
  const gate = finalizerGate(args);
@@ -6487,22 +7093,30 @@ async function finalizeModelOutputs(args) {
6487
7093
  if ("documentAuthorizationStage" in args || documentAuthorizationStages && (documentAuthorizationStages.length !== inputs.length || new Set(documentAuthorizationStages).size !== inputs.length)) {
6488
7094
  authorizationError("list finalization requires a distinct document stage per row");
6489
7095
  }
7096
+ if (!inputs.length) return [];
7097
+ const internal = {
7098
+ ...rest,
7099
+ scopePath: [...rest.scopePath ?? rest.plan.scopePath ?? []],
7100
+ sharedGate: gate,
7101
+ resolvedLimit: limit
7102
+ };
7103
+ const prepared = prepareFinalizer(internal, inputs.length > 1);
6490
7104
  return mapWithConcurrencyLimit(inputs, limit, (input, index) => {
6491
- const internal = {
6492
- ...rest,
6493
- scopePath: [...rest.scopePath ?? rest.plan.scopePath ?? []],
6494
- onFinalized: rest.onFinalized ? (output, context) => rest.onFinalized(output, context, index) : void 0,
6495
- documentAuthorizationStage: documentAuthorizationStages?.[index],
6496
- sharedGate: gate,
6497
- resolvedLimit: limit
6498
- };
6499
- return finalizeSingleDoc(internal, input);
7105
+ return finalizeSingleDoc(
7106
+ {
7107
+ ...internal,
7108
+ onFinalized: rest.onFinalized ? (output, context) => rest.onFinalized(output, context, index) : void 0,
7109
+ documentAuthorizationStage: documentAuthorizationStages?.[index]
7110
+ },
7111
+ input,
7112
+ prepared
7113
+ );
6500
7114
  });
6501
7115
  }
6502
- var import_utils29, isVirtualContainerValue3, getScopeVirtualsObject2, getScopeVirtualNames, getScopedPermissionSchema2, resolveGlobalPermissions, resolveDocPermissions, isAbsentDependency, __finalizeInternals;
7116
+ var import_utils30, isVirtualContainerValue3, getScopeVirtualsObject2, getScopeVirtualNames, getScopedPermissionSchema2, resolveGlobalPermissions, resolveDocPermissions, isAbsentDependency, __finalizeInternals;
6503
7117
  var init_finalize_model_output = __esm({
6504
7118
  "src/output/finalize-model-output.ts"() {
6505
- import_utils29 = require("@web-ts-toolkit/utils");
7119
+ import_utils30 = require("@web-ts-toolkit/utils");
6506
7120
  init_document();
6507
7121
  init_concurrency();
6508
7122
  init_request_work();
@@ -6513,22 +7127,23 @@ var init_finalize_model_output = __esm({
6513
7127
  init_output_field_filter();
6514
7128
  init_field_authorization();
6515
7129
  init_field_catalog();
7130
+ init_output_projection();
6516
7131
  init_virtual_populate_execution();
6517
7132
  init_include_output();
6518
- isVirtualContainerValue3 = (value) => (0, import_utils29.isPlainObject)(value) && "sub" in value;
7133
+ isVirtualContainerValue3 = (value) => (0, import_utils30.isPlainObject)(value) && "sub" in value;
6519
7134
  getScopeVirtualsObject2 = (rootVirtuals, scopePath) => {
6520
- if (!rootVirtuals || !(0, import_utils29.isPlainObject)(rootVirtuals)) return null;
7135
+ if (!rootVirtuals || !(0, import_utils30.isPlainObject)(rootVirtuals)) return null;
6521
7136
  if (scopePath.length === 0) return rootVirtuals;
6522
7137
  let current = rootVirtuals;
6523
7138
  for (let i = 0; i < scopePath.length; i += 2) {
6524
7139
  const field = scopePath[i];
6525
7140
  const subMarker = scopePath[i + 1];
6526
7141
  if (!field || subMarker !== "sub") return null;
6527
- if (!(0, import_utils29.isPlainObject)(current)) return null;
7142
+ if (!(0, import_utils30.isPlainObject)(current)) return null;
6528
7143
  const container = current[field];
6529
7144
  if (!isVirtualContainerValue3(container)) return null;
6530
7145
  current = container.sub;
6531
- if (!(0, import_utils29.isPlainObject)(current)) return null;
7146
+ if (!(0, import_utils30.isPlainObject)(current)) return null;
6532
7147
  }
6533
7148
  return current;
6534
7149
  };
@@ -6541,11 +7156,11 @@ var init_finalize_model_output = __esm({
6541
7156
  return Object.entries(scopeVirtuals).filter(([, v]) => v !== void 0 && !isVirtualContainerValue3(v)).map(([k]) => k);
6542
7157
  };
6543
7158
  getScopedPermissionSchema2 = (root, scopePath) => {
6544
- if (!root || !(0, import_utils29.isPlainObject)(root)) return null;
7159
+ if (!root || !(0, import_utils30.isPlainObject)(root)) return null;
6545
7160
  if (scopePath.length === 0) return root;
6546
7161
  try {
6547
- const scoped = (0, import_utils29.get)(root, scopePath.join("."));
6548
- return (0, import_utils29.isPlainObject)(scoped) ? scoped : null;
7162
+ const scoped = (0, import_utils30.get)(root, scopePath.join("."));
7163
+ return (0, import_utils30.isPlainObject)(scoped) ? scoped : null;
6549
7164
  } catch {
6550
7165
  return null;
6551
7166
  }
@@ -6566,7 +7181,7 @@ var init_finalize_model_output = __esm({
6566
7181
  };
6567
7182
  resolveDocPermissions = async (args, isolatedForHook, scopeContext) => {
6568
7183
  if (args.docPermissions != null && typeof args.docPermissions === "object" && !Array.isArray(args.docPermissions)) {
6569
- const grants = args.docPermissions;
7184
+ const grants = deepIsolateValue(args.docPermissions);
6570
7185
  scopeContext.docPermissions = grants;
6571
7186
  return grants;
6572
7187
  }
@@ -6604,7 +7219,7 @@ var init_finalize_model_output = __esm({
6604
7219
  const grants = await args.sharedGate.run(
6605
7220
  () => hook.call(args.request, isolatedForHook, globalPerms, scopeContext)
6606
7221
  );
6607
- const normalized = (0, import_utils29.isPlainObject)(grants) ? grants : {};
7222
+ const normalized = (0, import_utils30.isPlainObject)(grants) ? grants : {};
6608
7223
  scopeContext.docPermissions = normalized;
6609
7224
  return normalized;
6610
7225
  }
@@ -6676,20 +7291,20 @@ __export(index_exports, {
6676
7291
  setModelOptions: () => setModelOptions
6677
7292
  });
6678
7293
  module.exports = __toCommonJS(index_exports);
6679
- var import_utils47 = require("@web-ts-toolkit/utils");
7294
+ var import_utils48 = require("@web-ts-toolkit/utils");
6680
7295
 
6681
7296
  // src/middleware.ts
6682
7297
  var import_express_json_router5 = __toESM(require("@web-ts-toolkit/express-json-router"));
6683
- var import_utils40 = require("@web-ts-toolkit/utils");
7298
+ var import_utils41 = require("@web-ts-toolkit/utils");
6684
7299
 
6685
7300
  // src/core.ts
6686
7301
  init_public_admission();
6687
- var import_utils39 = require("@web-ts-toolkit/utils");
7302
+ var import_utils40 = require("@web-ts-toolkit/utils");
6688
7303
  init_options();
6689
7304
  init_permission();
6690
7305
 
6691
7306
  // src/services/base.ts
6692
- var import_utils24 = require("@web-ts-toolkit/utils");
7307
+ var import_utils25 = require("@web-ts-toolkit/utils");
6693
7308
  init_options();
6694
7309
  init_helpers();
6695
7310
  init_document();
@@ -6815,7 +7430,7 @@ function requestFieldScope(options) {
6815
7430
  init_public_admission();
6816
7431
 
6817
7432
  // src/correlated-includes.ts
6818
- var import_utils20 = require("@web-ts-toolkit/utils");
7433
+ var import_utils22 = require("@web-ts-toolkit/utils");
6819
7434
  init_request_complexity();
6820
7435
  init_sort_policy();
6821
7436
  var PARENT_MARKER_KEY = "$parent";
@@ -6828,10 +7443,10 @@ var FIELD_SEGMENT_PATTERN = /^[A-Za-z_][A-Za-z0-9_$]*$/;
6828
7443
  var ARRAY_INDEX_SEGMENT_PATTERN = /^(0|[1-9]\d*)$/;
6829
7444
  var ownKeys = (value) => Object.keys(value);
6830
7445
  function isParentRefMarker(value) {
6831
- return (0, import_utils20.isPlainObject)(value) && ownKeys(value).length === 1 && ownKeys(value)[0] === PARENT_MARKER_KEY;
7446
+ return (0, import_utils22.isPlainObject)(value) && ownKeys(value).length === 1 && ownKeys(value)[0] === PARENT_MARKER_KEY;
6832
7447
  }
6833
7448
  function isEscapedParentRef(value) {
6834
- return (0, import_utils20.isPlainObject)(value) && ownKeys(value).length === 1 && ownKeys(value)[0] === ESCAPE_WRAPPER_KEY;
7449
+ return (0, import_utils22.isPlainObject)(value) && ownKeys(value).length === 1 && ownKeys(value)[0] === ESCAPE_WRAPPER_KEY;
6835
7450
  }
6836
7451
  function hasMarkerKey(value) {
6837
7452
  return ownKeys(value).includes(PARENT_MARKER_KEY) || ownKeys(value).includes(ESCAPE_WRAPPER_KEY);
@@ -6850,12 +7465,12 @@ function containsParentMarkerShape(value) {
6850
7465
  const seen = /* @__PURE__ */ new Set();
6851
7466
  const visit = (current) => {
6852
7467
  if (isParentRefMarker(current) || isEscapedParentRef(current)) return true;
6853
- if ((0, import_utils20.isArray)(current)) {
7468
+ if ((0, import_utils22.isArray)(current)) {
6854
7469
  if (seen.has(current)) return false;
6855
7470
  seen.add(current);
6856
7471
  return current.some(visit);
6857
7472
  }
6858
- if ((0, import_utils20.isPlainObject)(current)) {
7473
+ if ((0, import_utils22.isPlainObject)(current)) {
6859
7474
  if (seen.has(current)) return false;
6860
7475
  seen.add(current);
6861
7476
  if (hasMarkerKey(current)) return true;
@@ -6885,7 +7500,7 @@ function scanTemplateValueNode(value, path, issues) {
6885
7500
  }
6886
7501
  return;
6887
7502
  }
6888
- if ((0, import_utils20.isPlainObject)(value)) {
7503
+ if ((0, import_utils22.isPlainObject)(value)) {
6889
7504
  if (hasMarkerKey(value)) {
6890
7505
  issues.push({
6891
7506
  message: 'Malformed $parent reference: objects carrying $parent must be exactly { "$parent": "<field>" }',
@@ -6896,7 +7511,7 @@ function scanTemplateValueNode(value, path, issues) {
6896
7511
  scanTemplateObjectEntries(value, path, issues);
6897
7512
  return;
6898
7513
  }
6899
- if ((0, import_utils20.isArray)(value)) {
7514
+ if ((0, import_utils22.isArray)(value)) {
6900
7515
  value.forEach((item, index) => scanTemplateValueNode(item, [...path, index], issues));
6901
7516
  }
6902
7517
  }
@@ -6937,7 +7552,7 @@ function scanTemplateObjectEntries(obj, basePath, issues) {
6937
7552
  continue;
6938
7553
  }
6939
7554
  if (LOGICAL_CLAUSE_KEYS.has(key)) {
6940
- if (!(0, import_utils20.isArray)(child)) {
7555
+ if (!(0, import_utils22.isArray)(child)) {
6941
7556
  scanTemplateValueNode(child, childPath, issues);
6942
7557
  continue;
6943
7558
  }
@@ -6950,7 +7565,7 @@ function scanTemplateObjectEntries(obj, basePath, issues) {
6950
7565
  });
6951
7566
  return;
6952
7567
  }
6953
- if ((0, import_utils20.isPlainObject)(clause)) {
7568
+ if ((0, import_utils22.isPlainObject)(clause)) {
6954
7569
  scanTemplateObjectEntries(clause, clausePath, issues);
6955
7570
  }
6956
7571
  });
@@ -6961,7 +7576,7 @@ function scanTemplateObjectEntries(obj, basePath, issues) {
6961
7576
  }
6962
7577
  function validateCorrelatedFilterTemplate(filter2) {
6963
7578
  const issues = [];
6964
- if (!(0, import_utils20.isPlainObject)(filter2)) {
7579
+ if (!(0, import_utils22.isPlainObject)(filter2)) {
6965
7580
  issues.push({ message: "Correlated include filter must be an object", path: [] });
6966
7581
  return issues;
6967
7582
  }
@@ -7004,13 +7619,13 @@ function collectFilterReferencePaths(filter2) {
7004
7619
  return;
7005
7620
  }
7006
7621
  if (isEscapedParentRef(value)) return;
7007
- if ((0, import_utils20.isArray)(value)) {
7622
+ if ((0, import_utils22.isArray)(value)) {
7008
7623
  if (seen.has(value)) return;
7009
7624
  seen.add(value);
7010
7625
  value.forEach(visitValue);
7011
7626
  return;
7012
7627
  }
7013
- if ((0, import_utils20.isPlainObject)(value)) {
7628
+ if ((0, import_utils22.isPlainObject)(value)) {
7014
7629
  if (seen.has(value)) return;
7015
7630
  seen.add(value);
7016
7631
  for (const [key, child] of Object.entries(value)) {
@@ -7056,7 +7671,7 @@ function getOwnPathValue(parent, path) {
7056
7671
  return current;
7057
7672
  }
7058
7673
  function cloneSubstitutedValue(value) {
7059
- if ((0, import_utils20.isPlainObject)(value) || (0, import_utils20.isArray)(value)) return (0, import_utils20.cloneDeep)(value);
7674
+ if ((0, import_utils22.isPlainObject)(value) || (0, import_utils22.isArray)(value)) return (0, import_utils22.cloneDeep)(value);
7060
7675
  return value;
7061
7676
  }
7062
7677
  function literalParentRefObject(path) {
@@ -7097,7 +7712,7 @@ function resolveObjectEntries(obj, parent) {
7097
7712
  continue;
7098
7713
  }
7099
7714
  if (LOGICAL_CLAUSE_KEYS.has(key)) {
7100
- if (!(0, import_utils20.isArray)(child)) {
7715
+ if (!(0, import_utils22.isArray)(child)) {
7101
7716
  out[key] = resolveValueNode(child, parent, false);
7102
7717
  continue;
7103
7718
  }
@@ -7105,7 +7720,7 @@ function resolveObjectEntries(obj, parent) {
7105
7720
  if (isParentRefMarker(clause) || isEscapedParentRef(clause)) {
7106
7721
  throw new CorrelatedReferenceError(`Unsupported $parent reference as a direct ${key} clause`);
7107
7722
  }
7108
- if (!(0, import_utils20.isPlainObject)(clause)) return cloneSubstitutedValue(clause);
7723
+ if (!(0, import_utils22.isPlainObject)(clause)) return cloneSubstitutedValue(clause);
7109
7724
  return resolveObjectEntries(clause, parent);
7110
7725
  });
7111
7726
  continue;
@@ -7134,10 +7749,10 @@ function resolveValueNode(template, parent, bare) {
7134
7749
  }
7135
7750
  const value = getOwnPathValue(parent, path);
7136
7751
  if (value === void 0 || value === null) throw UNRESOLVABLE;
7137
- if (bare && (0, import_utils20.isPlainObject)(value)) return { $eq: (0, import_utils20.cloneDeep)(value) };
7752
+ if (bare && (0, import_utils22.isPlainObject)(value)) return { $eq: (0, import_utils22.cloneDeep)(value) };
7138
7753
  return cloneSubstitutedValue(value);
7139
7754
  }
7140
- if ((0, import_utils20.isPlainObject)(template)) {
7755
+ if ((0, import_utils22.isPlainObject)(template)) {
7141
7756
  if (hasMarkerKey(template)) {
7142
7757
  throw new CorrelatedReferenceError(
7143
7758
  'Malformed $parent reference: objects carrying $parent must be exactly { "$parent": "<field>" }'
@@ -7145,7 +7760,7 @@ function resolveValueNode(template, parent, bare) {
7145
7760
  }
7146
7761
  return resolveObjectEntries(template, parent);
7147
7762
  }
7148
- if ((0, import_utils20.isArray)(template)) {
7763
+ if ((0, import_utils22.isArray)(template)) {
7149
7764
  return template.map((item) => resolveValueNode(item, parent, false));
7150
7765
  }
7151
7766
  return template;
@@ -7179,7 +7794,7 @@ function resolveCorrelatedIdTemplate(id, parent) {
7179
7794
  }
7180
7795
  function resolveCorrelatedFilterTemplate(filter2, parent) {
7181
7796
  try {
7182
- if (!(0, import_utils20.isPlainObject)(filter2) || isParentRefMarker(filter2) || isEscapedParentRef(filter2)) {
7797
+ if (!(0, import_utils22.isPlainObject)(filter2) || isParentRefMarker(filter2) || isEscapedParentRef(filter2)) {
7183
7798
  throw new CorrelatedReferenceError("Correlated include filter must be an object");
7184
7799
  }
7185
7800
  return { status: "resolved", filter: resolveObjectEntries(filter2, parent) };
@@ -7194,7 +7809,7 @@ function validateExpandedCorrelatedOperands(expanded, limits) {
7194
7809
  var MAX_NESTED_INCLUDE_DEPTH = 10;
7195
7810
  function validateCorrelatedArgsShape(args, op, depth) {
7196
7811
  if (args === void 0) return [];
7197
- if (!(0, import_utils20.isPlainObject)(args)) return ["Correlated include args must be an object"];
7812
+ if (!(0, import_utils22.isPlainObject)(args)) return ["Correlated include args must be an object"];
7198
7813
  const record3 = args;
7199
7814
  const allowed = op === "list" ? /* @__PURE__ */ new Set(["select", "sort", "skip", "limit", "page", "pageSize", "include"]) : /* @__PURE__ */ new Set(["select", "sort", "include"]);
7200
7815
  for (const key of Object.keys(record3)) {
@@ -7216,7 +7831,7 @@ function validateCorrelatedArgsShape(args, op, depth) {
7216
7831
  return [];
7217
7832
  }
7218
7833
  function validateCorrelatedIncludeShape(entry, depth = 0) {
7219
- if (!(0, import_utils20.isPlainObject)(entry)) return ["Correlated include must be an object"];
7834
+ if (!(0, import_utils22.isPlainObject)(entry)) return ["Correlated include must be an object"];
7220
7835
  const record3 = entry;
7221
7836
  if (record3.mode !== "correlated") return ['Correlated include mode must be "correlated"'];
7222
7837
  if (typeof record3.model !== "string" || record3.model.length === 0)
@@ -7229,7 +7844,7 @@ function validateCorrelatedIncludeShape(entry, depth = 0) {
7229
7844
  if ("localField" in record3 || "foreignField" in record3) {
7230
7845
  return ["Correlated includes must not carry localField or foreignField"];
7231
7846
  }
7232
- if (record3.options !== void 0 && !((0, import_utils20.isPlainObject)(record3.options) && Object.keys(record3.options).length === 0)) {
7847
+ if (record3.options !== void 0 && !((0, import_utils22.isPlainObject)(record3.options) && Object.keys(record3.options).length === 0)) {
7233
7848
  return ["Correlated include options must be absent or empty"];
7234
7849
  }
7235
7850
  const hasId = record3.id !== void 0;
@@ -7251,7 +7866,7 @@ function validateCorrelatedIncludeShape(entry, depth = 0) {
7251
7866
  return validateCorrelatedArgsShape(record3.args, record3.op, depth);
7252
7867
  }
7253
7868
  function isCorrelatedInclude(value) {
7254
- return (0, import_utils20.isPlainObject)(value) && value.mode === "correlated";
7869
+ return (0, import_utils22.isPlainObject)(value) && value.mode === "correlated";
7255
7870
  }
7256
7871
 
7257
7872
  // src/services/base.ts
@@ -7537,9 +8152,9 @@ function createServiceExecution(receiver, access, authorization, applicability =
7537
8152
  receiver,
7538
8153
  binding,
7539
8154
  authorization: call,
7540
- access: readServiceAuthorization(call, binding).access,
8155
+ access: readServiceAuthorizationAccess(call, binding),
7541
8156
  family: execution,
7542
- hydration: resolveHydration(readServiceAuthorization(call, binding).configuration, hydration)
8157
+ hydration: resolveHydration(readServiceAuthorizationHydration(call, binding), hydration)
7543
8158
  })
7544
8159
  );
7545
8160
  return execution;
@@ -7550,7 +8165,7 @@ function resolveHydration(configuration, source) {
7550
8165
  }
7551
8166
  function withExecutionHydration(receiver, parent, source) {
7552
8167
  const record3 = readServiceExecution(receiver, parent);
7553
- const { configuration } = readServiceAuthorization(record3.authorization, record3.binding);
8168
+ const configuration = readServiceAuthorizationHydration(record3.authorization, record3.binding);
7554
8169
  const execution = Object.freeze(/* @__PURE__ */ Object.create(null));
7555
8170
  executions.set(execution, Object.freeze({ ...record3, hydration: resolveHydration(configuration, source) }));
7556
8171
  return execution;
@@ -7587,7 +8202,7 @@ function deriveServiceExecution(receiver, parent, access, applicability = "servi
7587
8202
  const execution = Object.freeze(/* @__PURE__ */ Object.create(null));
7588
8203
  executions.set(
7589
8204
  execution,
7590
- Object.freeze({ ...record3, authorization: call, access: readServiceAuthorization(call, record3.binding).access })
8205
+ Object.freeze({ ...record3, authorization: call, access: readServiceAuthorizationAccess(call, record3.binding) })
7591
8206
  );
7592
8207
  return execution;
7593
8208
  }
@@ -7988,20 +8603,20 @@ var copyAuthorizedOutput = (value) => {
7988
8603
  transferDocumentAuthorizationGraph(value, copy);
7989
8604
  return copy;
7990
8605
  };
7991
- var isVirtualContainerValueForGuard = (value) => (0, import_utils24.isPlainObject)(value) && "sub" in value;
8606
+ var isVirtualContainerValueForGuard = (value) => (0, import_utils25.isPlainObject)(value) && "sub" in value;
7992
8607
  var getScopeVirtualsForGuard = (rootVirtuals, scopePath) => {
7993
- if (!rootVirtuals || !(0, import_utils24.isPlainObject)(rootVirtuals)) return null;
8608
+ if (!rootVirtuals || !(0, import_utils25.isPlainObject)(rootVirtuals)) return null;
7994
8609
  if (scopePath.length === 0) return rootVirtuals;
7995
8610
  let current = rootVirtuals;
7996
8611
  for (let i = 0; i < scopePath.length; i += 2) {
7997
8612
  const field = scopePath[i];
7998
8613
  const subMarker = scopePath[i + 1];
7999
8614
  if (!field || subMarker !== "sub") return null;
8000
- if (!(0, import_utils24.isPlainObject)(current)) return null;
8615
+ if (!(0, import_utils25.isPlainObject)(current)) return null;
8001
8616
  const container = current[field];
8002
8617
  if (!isVirtualContainerValueForGuard(container)) return null;
8003
8618
  current = container.sub;
8004
- if (!(0, import_utils24.isPlainObject)(current)) return null;
8619
+ if (!(0, import_utils25.isPlainObject)(current)) return null;
8005
8620
  }
8006
8621
  return current;
8007
8622
  };
@@ -8067,7 +8682,7 @@ var sanitizeSubScopeVirtualKeys = (data, snapshot, sub) => {
8067
8682
  for (const entry of value) stripScope(entry, currentScope);
8068
8683
  return;
8069
8684
  }
8070
- if (!(0, import_utils24.isPlainObject)(value)) return;
8685
+ if (!(0, import_utils25.isPlainObject)(value)) return;
8071
8686
  const record3 = value;
8072
8687
  const leaves = getScopeVirtualLeafNames(snapshot, currentScope);
8073
8688
  for (const leaf of leaves) {
@@ -8080,7 +8695,7 @@ var sanitizeSubScopeVirtualKeys = (data, snapshot, sub) => {
8080
8695
  for (const key of Object.keys(record3)) {
8081
8696
  if (leaves.has(key) || containers.has(key)) continue;
8082
8697
  const child = record3[key];
8083
- if (Array.isArray(child) || (0, import_utils24.isPlainObject)(child)) {
8698
+ if (Array.isArray(child) || (0, import_utils25.isPlainObject)(child)) {
8084
8699
  stripScope(child, currentScope);
8085
8700
  }
8086
8701
  }
@@ -8092,7 +8707,7 @@ var LOGICAL_FILTER_KEYS = /* @__PURE__ */ new Set(["$and", "$or", "$nor"]);
8092
8707
  var isOperatorKey = (key) => key.startsWith("$");
8093
8708
  var REMOVED_VIRTUAL_FILTER = /* @__PURE__ */ Symbol("removed virtual filter clause");
8094
8709
  var rewriteFilterObject = (value, visit) => {
8095
- if (!(0, import_utils24.isPlainObject)(value)) return value;
8710
+ if (!(0, import_utils25.isPlainObject)(value)) return value;
8096
8711
  let changed = false;
8097
8712
  const entries = [];
8098
8713
  for (const [key, child] of Object.entries(value)) {
@@ -8123,7 +8738,7 @@ var resolveVirtualFilterField = (path, scope2) => {
8123
8738
  if (!Object.hasOwn(scope2, segment) || scope2[segment] === void 0) return null;
8124
8739
  const definition = scope2[segment];
8125
8740
  if (!isVirtualContainerValueForGuard(definition)) return REMOVED_VIRTUAL_FILTER;
8126
- scope2 = (0, import_utils24.isPlainObject)(definition.sub) ? definition.sub : null;
8741
+ scope2 = (0, import_utils25.isPlainObject)(definition.sub) ? definition.sub : null;
8127
8742
  inContainer = true;
8128
8743
  }
8129
8744
  return scope2;
@@ -8135,7 +8750,7 @@ var stripVirtualFilterOperator = (key, value, scope2) => {
8135
8750
  }
8136
8751
  if (key === "$all") {
8137
8752
  return rewriteFilterClauses(value, (entry) => {
8138
- if (!(0, import_utils24.isPlainObject)(entry) || Object.keys(entry).length !== 1 || !Object.hasOwn(entry, "$elemMatch")) return entry;
8753
+ if (!(0, import_utils25.isPlainObject)(entry) || Object.keys(entry).length !== 1 || !Object.hasOwn(entry, "$elemMatch")) return entry;
8139
8754
  return rewriteFilterObject(entry, (operator, operand) => stripVirtualFilterOperator(operator, operand, scope2));
8140
8755
  });
8141
8756
  }
@@ -8150,7 +8765,7 @@ var stripVirtualFilterQuery = (value, scope2, element = false) => {
8150
8765
  if (isOperatorKey(key)) return element ? stripVirtualFilterOperator(key, child, scope2) : child;
8151
8766
  const fieldScope = resolveVirtualFilterField(key, scope2);
8152
8767
  if (fieldScope === REMOVED_VIRTUAL_FILTER) return REMOVED_VIRTUAL_FILTER;
8153
- if (!fieldScope || !(0, import_utils24.isPlainObject)(child)) return child;
8768
+ if (!fieldScope || !(0, import_utils25.isPlainObject)(child)) return child;
8154
8769
  if (Object.keys(child).some(isOperatorKey)) {
8155
8770
  return rewriteFilterObject(
8156
8771
  child,
@@ -8172,9 +8787,9 @@ var stripSubVirtualKeysFromFilter = (filter2, snapshot, sub) => {
8172
8787
  function getCorrelatedTemplateDepth(includes) {
8173
8788
  let max = 0;
8174
8789
  const visit = (entries, depth) => {
8175
- const list = (0, import_utils24.castArray)(entries).filter(Boolean);
8790
+ const list = (0, import_utils25.castArray)(entries).filter(Boolean);
8176
8791
  for (const entry of list) {
8177
- if (!(0, import_utils24.isPlainObject)(entry)) continue;
8792
+ if (!(0, import_utils25.isPlainObject)(entry)) continue;
8178
8793
  max = Math.max(max, depth);
8179
8794
  const nested = entry.args?.include;
8180
8795
  if (nested !== void 0) {
@@ -8199,11 +8814,11 @@ function validateClientFilter(filter2) {
8199
8814
  }
8200
8815
  const blockedOperators = /* @__PURE__ */ new Set(["$where", "$expr", "$function", "$accumulator"]);
8201
8816
  const visit = (value, path) => {
8202
- if ((0, import_utils24.isArray)(value)) {
8817
+ if ((0, import_utils25.isArray)(value)) {
8203
8818
  value.forEach((item, index) => visit(item, `${path}[${index}]`));
8204
8819
  return;
8205
8820
  }
8206
- if (!(0, import_utils24.isPlainObject)(value)) return;
8821
+ if (!(0, import_utils25.isPlainObject)(value)) return;
8207
8822
  Object.entries(value).forEach(([key, child]) => {
8208
8823
  const nextPath = path ? `${path}.${key}` : key;
8209
8824
  if (blockedOperators.has(key)) {
@@ -8408,7 +9023,7 @@ var Base = class {
8408
9023
  }
8409
9024
  processInclude(include, authorization) {
8410
9025
  assertPublicAdmission(include, "include");
8411
- const items = (0, import_utils24.compact)((0, import_utils24.castArray)(include));
9026
+ const items = (0, import_utils25.compact)((0, import_utils25.castArray)(include));
8412
9027
  const legacy = [];
8413
9028
  const correlated = [];
8414
9029
  const correlatedReferenceFields = [];
@@ -8444,23 +9059,23 @@ var Base = class {
8444
9059
  else this.assertIncludeOutputPaths([...legacy, ...correlated]);
8445
9060
  let includeLocalFields = [];
8446
9061
  let includePaths = [];
8447
- (0, import_utils24.forEach)(legacy, (inc) => {
9062
+ (0, import_utils25.forEach)(legacy, (inc) => {
8448
9063
  includeLocalFields.push(inc.localField);
8449
9064
  includePaths.push(inc.path);
8450
9065
  });
8451
- includeLocalFields = (0, import_utils24.uniq)((0, import_utils24.compact)(includeLocalFields));
8452
- includePaths = (0, import_utils24.uniq)((0, import_utils24.compact)(includePaths));
9066
+ includeLocalFields = (0, import_utils25.uniq)((0, import_utils25.compact)(includeLocalFields));
9067
+ includePaths = (0, import_utils25.uniq)((0, import_utils25.compact)(includePaths));
8453
9068
  return {
8454
9069
  includes: legacy,
8455
9070
  correlatedIncludes: correlated,
8456
9071
  includeLocalFields,
8457
9072
  includePaths,
8458
- correlatedReferenceFields: (0, import_utils24.uniq)((0, import_utils24.compact)(correlatedReferenceFields))
9073
+ correlatedReferenceFields: (0, import_utils25.uniq)((0, import_utils25.compact)(correlatedReferenceFields))
8459
9074
  };
8460
9075
  }
8461
9076
  validateIncludeOutputPath(path, modelName, configuration) {
8462
9077
  const permissionField = configuration ? configuration.documentPermissionField ?? "_permissions" : getModelOption(modelName, "documentPermissionField");
8463
- if ((0, import_utils24.get)((0, import_utils24.set)({}, path, true), permissionField) !== void 0 || (0, import_utils24.get)((0, import_utils24.set)({}, permissionField, true), path) !== void 0) {
9078
+ if ((0, import_utils25.get)((0, import_utils25.set)({}, path, true), permissionField) !== void 0 || (0, import_utils25.get)((0, import_utils25.set)({}, permissionField, true), path) !== void 0) {
8464
9079
  this.throwClientRequestError(
8465
9080
  "bad_request" /* BadRequest */,
8466
9081
  `Include output path ${path} overlaps document permission field ${permissionField} on model ${modelName}`
@@ -8485,9 +9100,9 @@ var Base = class {
8485
9100
  const walk = (node, prefix) => {
8486
9101
  for (const [key, value] of Object.entries(node)) {
8487
9102
  if (value === void 0) continue;
8488
- if ((0, import_utils24.isPlainObject)(value) && "sub" in value) {
9103
+ if ((0, import_utils25.isPlainObject)(value) && "sub" in value) {
8489
9104
  const sub = value.sub;
8490
- if ((0, import_utils24.isPlainObject)(sub)) walk(sub, prefix ? `${prefix}.${key}` : key);
9105
+ if ((0, import_utils25.isPlainObject)(sub)) walk(sub, prefix ? `${prefix}.${key}` : key);
8491
9106
  continue;
8492
9107
  }
8493
9108
  out.push(prefix ? `${prefix}.${key}` : key);
@@ -8540,7 +9155,7 @@ var Base = class {
8540
9155
  this.throwClientRequestError("bad_request" /* BadRequest */, `Model ${modelName} not found`);
8541
9156
  }
8542
9157
  for (const entry of entries) {
8543
- if (!(0, import_utils24.isPlainObject)(entry)) continue;
9158
+ if (!(0, import_utils25.isPlainObject)(entry)) continue;
8544
9159
  const models = visited.get(entry) ?? /* @__PURE__ */ new Set();
8545
9160
  if (models.has(modelName)) continue;
8546
9161
  models.add(modelName);
@@ -8553,7 +9168,7 @@ var Base = class {
8553
9168
  const target = targets?.find((target2) => target2.path === entry.path);
8554
9169
  if (nested)
8555
9170
  pending.push({
8556
- entries: (0, import_utils24.compact)((0, import_utils24.castArray)(nested)),
9171
+ entries: (0, import_utils25.compact)((0, import_utils25.castArray)(nested)),
8557
9172
  modelName: entry.model,
8558
9173
  configuration: target?.configuration,
8559
9174
  targets: target?.relatedTargets
@@ -8563,7 +9178,7 @@ var Base = class {
8563
9178
  }
8564
9179
  }
8565
9180
  getForeignKeyValues(value) {
8566
- return (0, import_utils24.flatten)((0, import_utils24.castArray)(value));
9181
+ return (0, import_utils25.flatten)((0, import_utils25.castArray)(value));
8567
9182
  }
8568
9183
  getForeignKey(value) {
8569
9184
  return String(value);
@@ -8571,7 +9186,7 @@ var Base = class {
8571
9186
  buildForeignKeyIndex(rows2, foreignField) {
8572
9187
  const index = /* @__PURE__ */ new Map();
8573
9188
  for (const row of rows2) {
8574
- for (const value of this.getForeignKeyValues((0, import_utils24.get)(row, foreignField))) {
9189
+ for (const value of this.getForeignKeyValues((0, import_utils25.get)(row, foreignField))) {
8575
9190
  const key = this.getForeignKey(value);
8576
9191
  const values = index.get(key);
8577
9192
  if (values) values.push(row);
@@ -8607,9 +9222,9 @@ var Base = class {
8607
9222
  async includeDocs(docs, include, parentAuthorization) {
8608
9223
  assertPublicAdmission(include, "include");
8609
9224
  if (!include) return docs;
8610
- const includes = (0, import_utils24.compact)((0, import_utils24.castArray)(include));
9225
+ const includes = (0, import_utils25.compact)((0, import_utils25.castArray)(include));
8611
9226
  if (includes.length === 0) return docs;
8612
- const isSingle = !(0, import_utils24.isArray)(docs);
9227
+ const isSingle = !(0, import_utils25.isArray)(docs);
8613
9228
  let docList = (isSingle ? [docs] : docs).map(prepareIncludeOutput);
8614
9229
  for (let x = 0; x < includes.length; x++) {
8615
9230
  const include2 = includes[x];
@@ -8639,7 +9254,7 @@ var Base = class {
8639
9254
  const svc = await this.getAuthorizedTargetService(model, "read", path, parentAuthorization);
8640
9255
  for (let y = 0; y < docs.length; y++) {
8641
9256
  const doc = docs[y];
8642
- const localValue = (0, import_utils24.get)(doc, localField);
9257
+ const localValue = (0, import_utils25.get)(doc, localField);
8643
9258
  const execution = this.relatedExecution(svc, include, parentAuthorization);
8644
9259
  const prepared = await prepareModelQuery(
8645
9260
  svc,
@@ -8674,15 +9289,15 @@ var Base = class {
8674
9289
  const { model, op, path, localField, foreignField, filter: _filters, args = {}, options = {} } = include;
8675
9290
  const svc = await this.getAuthorizedTargetService(model, op, path, parentAuthorization);
8676
9291
  const includeLocalValues = [];
8677
- (0, import_utils24.forEach)(docs, (doc) => {
8678
- includeLocalValues.push(...this.getForeignKeyValues((0, import_utils24.get)(doc, localField)));
9292
+ (0, import_utils25.forEach)(docs, (doc) => {
9293
+ includeLocalValues.push(...this.getForeignKeyValues((0, import_utils25.get)(doc, localField)));
8679
9294
  });
8680
9295
  const execution = this.relatedExecution(svc, include, parentAuthorization);
8681
9296
  const prepared = await prepareModelQuery(
8682
9297
  svc,
8683
9298
  execution,
8684
9299
  { kind: "client-read", filter: _filters ?? {} },
8685
- { [foreignField]: { $in: (0, import_utils24.flatten)(includeLocalValues) } },
9300
+ { [foreignField]: { $in: (0, import_utils25.flatten)(includeLocalValues) } },
8686
9301
  true
8687
9302
  );
8688
9303
  const trustedArgs = this.sanitizeIncludeArgs(args, "list");
@@ -8725,7 +9340,7 @@ var Base = class {
8725
9340
  }
8726
9341
  for (let y = 0; y < docs.length; y++) {
8727
9342
  const doc = docs[y];
8728
- const matches = this.getIndexedMatches(index, (0, import_utils24.get)(doc, localField));
9343
+ const matches = this.getIndexedMatches(index, (0, import_utils25.get)(doc, localField));
8729
9344
  const isolated = matches.map((m) => copyAuthorizedOutput(m));
8730
9345
  attachIncludeOutput(doc, path, op === "list" ? isolated : isolated[0]);
8731
9346
  }
@@ -8734,7 +9349,7 @@ var Base = class {
8734
9349
  async includeDocsCount(docs, include, parentAuthorization) {
8735
9350
  const { model, path, localField, foreignField, filter: _filters } = include;
8736
9351
  const svc = await this.getAuthorizedTargetService(model, "count", path, parentAuthorization);
8737
- const groups = prepareCountGroups(docs, (doc) => (0, import_utils24.get)(doc, localField));
9352
+ const groups = prepareCountGroups(docs, (doc) => (0, import_utils25.get)(doc, localField));
8738
9353
  const execution = this.relatedExecution(svc, include, parentAuthorization);
8739
9354
  const prepared = await prepareModelQuery(
8740
9355
  svc,
@@ -8788,7 +9403,7 @@ var Base = class {
8788
9403
  }
8789
9404
  const state = this.getCorrelatedExecState();
8790
9405
  docs = docs.map(prepareIncludeOutput);
8791
- const resolvedSnapshots = snapshots2 ?? docs.map((doc) => (0, import_utils24.cloneDeep)(toObject(getIncludeSource(doc))));
9406
+ const resolvedSnapshots = snapshots2 ?? docs.map((doc) => (0, import_utils25.cloneDeep)(toObject(getIncludeSource(doc))));
8792
9407
  for (const include of correlatedIncludes) {
8793
9408
  switch (include.op) {
8794
9409
  case "read":
@@ -9137,10 +9752,10 @@ var Base = class {
9137
9752
  }
9138
9753
  let ret = result2.data;
9139
9754
  if (sqOptions.path) {
9140
- ret = (0, import_utils24.isArray)(ret) ? (0, import_utils24.flatten)(ret.map((v) => (0, import_utils24.get)(v, sqOptions.path))) : (0, import_utils24.get)(ret, sqOptions.path);
9755
+ ret = (0, import_utils25.isArray)(ret) ? (0, import_utils25.flatten)(ret.map((v) => (0, import_utils25.get)(v, sqOptions.path))) : (0, import_utils25.get)(ret, sqOptions.path);
9141
9756
  }
9142
9757
  if (sqOptions.compact) {
9143
- ret = (0, import_utils24.compact)((0, import_utils24.castArray)(ret));
9758
+ ret = (0, import_utils25.compact)((0, import_utils25.castArray)(ret));
9144
9759
  }
9145
9760
  return ret;
9146
9761
  }
@@ -9152,11 +9767,11 @@ var Base = class {
9152
9767
  };
9153
9768
 
9154
9769
  // src/services/service.ts
9155
- var import_utils35 = require("@web-ts-toolkit/utils");
9770
+ var import_utils36 = require("@web-ts-toolkit/utils");
9156
9771
  var import_just_diff = require("just-diff");
9157
9772
 
9158
9773
  // src/model.ts
9159
- var import_utils25 = require("@web-ts-toolkit/utils");
9774
+ var import_utils26 = require("@web-ts-toolkit/utils");
9160
9775
  init_runtime_context();
9161
9776
  init_runtime();
9162
9777
  function admitModelPersistence(adapter, scheduler) {
@@ -9232,7 +9847,7 @@ var Model = class {
9232
9847
  }
9233
9848
  /** Cast a copy using this model's query schema/setters, without executing query middleware or persistence. */
9234
9849
  castFilter(filter2) {
9235
- const query = this.mongooseModel.countDocuments((0, import_utils25.cloneDeep)(filter2));
9850
+ const query = this.mongooseModel.countDocuments((0, import_utils26.cloneDeep)(filter2));
9236
9851
  return query.cast(this.mongooseModel);
9237
9852
  }
9238
9853
  // see https://mongoosejs.com/docs/api.html#model_Model.distinct
@@ -9246,7 +9861,7 @@ var Model = class {
9246
9861
  var model_default = Model;
9247
9862
 
9248
9863
  // src/acl/distinct-field-authorization.ts
9249
- var import_utils26 = require("@web-ts-toolkit/utils");
9864
+ var import_utils27 = require("@web-ts-toolkit/utils");
9250
9865
  init_field_authorization();
9251
9866
  init_field_catalog();
9252
9867
  var schemaVariants = (schema) => Object.values(schema.discriminators ?? {});
@@ -9328,8 +9943,8 @@ function isDistinctFieldAuthorized(args) {
9328
9943
  if (path !== field && !path.startsWith(`${field}.`) && !field.startsWith(`${path}.`)) continue;
9329
9944
  if (path.startsWith(`${field}.`) && (!eligible(path) || !schemaShape(schema, path) || !granted(path)))
9330
9945
  return false;
9331
- if ((0, import_utils26.isPlainObject)(raw) && raw.sub !== void 0) {
9332
- if (!(0, import_utils26.isPlainObject)(raw.sub) || !declaredRulesSafe(raw.sub, path, next)) return false;
9946
+ if ((0, import_utils27.isPlainObject)(raw) && raw.sub !== void 0) {
9947
+ if (!(0, import_utils27.isPlainObject)(raw.sub) || !declaredRulesSafe(raw.sub, path, next)) return false;
9333
9948
  }
9334
9949
  }
9335
9950
  return true;
@@ -9506,7 +10121,7 @@ init_document();
9506
10121
  init_populate_target();
9507
10122
 
9508
10123
  // src/helpers/apply-update.ts
9509
- var import_utils30 = require("@web-ts-toolkit/utils");
10124
+ var import_utils31 = require("@web-ts-toolkit/utils");
9510
10125
  init_lib();
9511
10126
  function applyUpdate(target, data, allowedFields) {
9512
10127
  const wholeFields = /* @__PURE__ */ new Set();
@@ -9522,17 +10137,17 @@ function applyUpdate(target, data, allowedFields) {
9522
10137
  }
9523
10138
  };
9524
10139
  for (const field of allowedFields) {
9525
- collectBoundary((0, import_utils30.set)({}, field, true));
10140
+ collectBoundary((0, import_utils31.set)({}, field, true));
9526
10141
  }
9527
10142
  const apply = (values, prefix = "") => {
9528
10143
  for (const [key, value] of Object.entries(values)) {
9529
10144
  const path = prefix ? `${prefix}.${key}` : key;
9530
- if (partialContainers.has(path) && !wholeFields.has(path) && ((0, import_utils30.isPlainObject)(value) || Array.isArray(value))) {
10145
+ if (partialContainers.has(path) && !wholeFields.has(path) && ((0, import_utils31.isPlainObject)(value) || Array.isArray(value))) {
9531
10146
  apply(value, path);
9532
10147
  } else if (isDocument2(target)) {
9533
10148
  target.set(path, value);
9534
10149
  } else {
9535
- (0, import_utils30.set)(target, path, value);
10150
+ (0, import_utils31.set)(target, path, value);
9536
10151
  }
9537
10152
  }
9538
10153
  };
@@ -9540,7 +10155,7 @@ function applyUpdate(target, data, allowedFields) {
9540
10155
  }
9541
10156
 
9542
10157
  // src/acl/model-input-admission.ts
9543
- var import_utils32 = require("@web-ts-toolkit/utils");
10158
+ var import_utils33 = require("@web-ts-toolkit/utils");
9544
10159
  var import_mongoose8 = require("mongoose");
9545
10160
  init_document();
9546
10161
  init_request_work();
@@ -9548,7 +10163,7 @@ init_logger_helpers();
9548
10163
  init_request_complexity();
9549
10164
 
9550
10165
  // src/acl/select-resolution.ts
9551
- var import_utils31 = require("@web-ts-toolkit/utils");
10166
+ var import_utils32 = require("@web-ts-toolkit/utils");
9552
10167
  init_core_shared();
9553
10168
  init_helpers();
9554
10169
  async function collectAllowedFieldsForRequest({
@@ -9622,15 +10237,15 @@ async function resolveSelectForRequest({
9622
10237
  const excludeall = normalizedSelect.every((v) => v.startsWith("-"));
9623
10238
  if (excludeall) {
9624
10239
  normalizedSelect = normalizedSelect.map((v) => v.substring(1));
9625
- fields = (0, import_utils31.difference)(fields, normalizedSelect);
10240
+ fields = (0, import_utils32.difference)(fields, normalizedSelect);
9626
10241
  if (excludeid) fields.push("-_id");
9627
10242
  } else {
9628
- fields = (0, import_utils31.intersection)(normalizedSelect, fields.concat(excludeid ? "-_id" : "_id"));
10243
+ fields = (0, import_utils32.intersection)(normalizedSelect, fields.concat(excludeid ? "-_id" : "_id"));
9629
10244
  }
9630
10245
  }
9631
10246
  return fields.concat(strippedAlways);
9632
10247
  }
9633
- return (0, import_utils31.intersection)(normalizedSelect, fields);
10248
+ return (0, import_utils32.intersection)(normalizedSelect, fields);
9634
10249
  }
9635
10250
  function stripVirtuals(fields, virtualNames) {
9636
10251
  const set13 = virtualNames instanceof Set ? virtualNames : new Set(virtualNames ?? []);
@@ -9661,7 +10276,7 @@ init_field_catalog();
9661
10276
  init_service_authorization();
9662
10277
  var own = (value, key) => Object.prototype.hasOwnProperty.call(value, key);
9663
10278
  var inside = (path, root) => path === root || path.startsWith(`${root}.`);
9664
- var record2 = (value) => (0, import_utils32.isPlainObject)(value);
10279
+ var record2 = (value) => (0, import_utils33.isPlainObject)(value);
9665
10280
  function inputValue(value) {
9666
10281
  if (typeof value === "function" || typeof value === "symbol") {
9667
10282
  authorizationError("input values must be persisted data, not functions or symbols");
@@ -9730,7 +10345,7 @@ function requestBoundaries(fields) {
9730
10345
  else visit(value, path);
9731
10346
  }
9732
10347
  };
9733
- for (const field of fields) visit((0, import_utils32.set)({}, field, true));
10348
+ for (const field of fields) visit((0, import_utils33.set)({}, field, true));
9734
10349
  return [...new Set(result2)];
9735
10350
  }
9736
10351
  function ownValue(data, parts) {
@@ -9860,7 +10475,7 @@ function admitModelInput(args) {
9860
10475
  if (forbidden(catalog, path, requested)) continue;
9861
10476
  const supplied = ownValue(data, parts);
9862
10477
  if (!supplied) continue;
9863
- (0, import_utils32.set)(allowedData, field, copyInputValue(supplied.value, path, catalog, scopedRequests, logicalPath(field)));
10478
+ (0, import_utils33.set)(allowedData, field, copyInputValue(supplied.value, path, catalog, scopedRequests, logicalPath(field)));
9864
10479
  selected.push(field);
9865
10480
  }
9866
10481
  return { allowedData, allowedFields };
@@ -9872,7 +10487,7 @@ async function requestInputFields(args) {
9872
10487
  const prefix = configuration.modelPermissionPrefix ?? "";
9873
10488
  return collectModelRequestFields({
9874
10489
  req: args.binding.request,
9875
- permissionSchema: args.scopePath ? (0, import_utils32.get)(configuration.permissionSchema, [args.scopePath, "sub"]) : configuration.permissionSchema,
10490
+ permissionSchema: args.scopePath ? (0, import_utils33.get)(configuration.permissionSchema, [args.scopePath, "sub"]) : configuration.permissionSchema,
9876
10491
  access: args.access,
9877
10492
  permissions,
9878
10493
  grants,
@@ -9916,13 +10531,13 @@ init_logger_helpers();
9916
10531
  init_lib();
9917
10532
 
9918
10533
  // src/services/model-subdocument-service.ts
9919
- var import_utils34 = require("@web-ts-toolkit/utils");
10534
+ var import_utils35 = require("@web-ts-toolkit/utils");
9920
10535
  init_helpers();
9921
10536
  init_document();
9922
10537
  init_public_admission();
9923
10538
 
9924
10539
  // src/acl/subdocument-authorization.ts
9925
- var import_utils33 = require("@web-ts-toolkit/utils");
10540
+ var import_utils34 = require("@web-ts-toolkit/utils");
9926
10541
  init_helpers();
9927
10542
  init_document();
9928
10543
  init_core_shared();
@@ -10111,8 +10726,8 @@ async function subdocumentGateAllowed(service, gate) {
10111
10726
  let guard2;
10112
10727
  if (access.startsWith("subs.")) {
10113
10728
  const [, sub, op] = access.split(".");
10114
- guard2 = (0, import_utils33.get)(configuration, `operationAccess.${access}`);
10115
- if (guard2 === void 0) guard2 = (0, import_utils33.get)(configuration, `operationAccess.subs.${sub}`);
10729
+ guard2 = (0, import_utils34.get)(configuration, `operationAccess.${access}`);
10730
+ if (guard2 === void 0) guard2 = (0, import_utils34.get)(configuration, `operationAccess.subs.${sub}`);
10116
10731
  if (guard2 === void 0) guard2 = getCapturedAuthorizationOption(configuration, `operationAccess.${op}`);
10117
10732
  } else guard2 = getCapturedAuthorizationOption(configuration, `operationAccess.${access}`);
10118
10733
  return evaluateRouteGuard(
@@ -10243,7 +10858,7 @@ async function visibleMutationRows(service, call, parentId, rows2) {
10243
10858
  const read = await subdocumentRows(service, visibility.child, selected, selected, call.sub);
10244
10859
  const list = visibility.list ? await subdocumentRows(service, visibility.list, {}, {}, call.sub) : {};
10245
10860
  if (read === false || list === false) return [];
10246
- const visible = filterCollection((0, import_utils34.get)(parent, call.sub), intersectFilters(read, list));
10861
+ const visible = filterCollection((0, import_utils35.get)(parent, call.sub), intersectFilters(read, list));
10247
10862
  return await finalizeSubdocumentRows(service, call.output, parent, visible);
10248
10863
  } catch {
10249
10864
  return [];
@@ -10268,7 +10883,7 @@ async function listSub(service, id, sub, options) {
10268
10883
  populate: []
10269
10884
  });
10270
10885
  if (!parent) return denied2("not_found" /* NotFound */);
10271
- const rows2 = filterCollection((0, import_utils34.get)(parent, sub), childFilter);
10886
+ const rows2 = filterCollection((0, import_utils35.get)(parent, sub), childFilter);
10272
10887
  const data = await finalizeSubdocumentRows(service, call.output, parent, rows2);
10273
10888
  return { success: true, kind: "list", code: "success" /* Success */, data, count: data.length };
10274
10889
  });
@@ -10292,7 +10907,7 @@ async function readSub(service, id, sub, subId, options) {
10292
10907
  });
10293
10908
  if (!parent) return denied2("not_found" /* NotFound */);
10294
10909
  const row = findElement(
10295
- (0, import_utils34.get)(capture ? parent : copySubdocumentParent(parent), sub),
10910
+ (0, import_utils35.get)(capture ? parent : copySubdocumentParent(parent), sub),
10296
10911
  childFilter
10297
10912
  );
10298
10913
  if (!row) return denied2("not_found" /* NotFound */);
@@ -10313,7 +10928,7 @@ async function updateSub(service, persist, id, sub, subId, data, options) {
10313
10928
  const identity = { _id: subId };
10314
10929
  const filter2 = await subdocumentRows(service, call.child, identity, identity, sub);
10315
10930
  if (filter2 === false) return denied2();
10316
- const row = findElement((0, import_utils34.get)(parent, sub), filter2);
10931
+ const row = findElement((0, import_utils35.get)(parent, sub), filter2);
10317
10932
  if (!row) return denied2("not_found" /* NotFound */);
10318
10933
  const original = isolateDocForOutput(row);
10319
10934
  const admit = await inputAdmission(service, call, parent);
@@ -10340,7 +10955,7 @@ async function bulkUpdateSub(service, persist, id, sub, data, options) {
10340
10955
  const selected = { _id: { $in: data.map((row) => row._id) } };
10341
10956
  const filter2 = await subdocumentRows(service, call.child, selected, selected, sub);
10342
10957
  if (filter2 === false) return denied2();
10343
- const rows2 = filterCollection((0, import_utils34.get)(parent, sub), filter2);
10958
+ const rows2 = filterCollection((0, import_utils35.get)(parent, sub), filter2);
10344
10959
  const originals = rows2.map((row) => isolateDocForOutput(row));
10345
10960
  const admit = await inputAdmission(service, call, parent);
10346
10961
  for (const [index, row] of rows2.entries()) {
@@ -10369,7 +10984,7 @@ async function createSub(service, persist, id, sub, data, options) {
10369
10984
  const lookup = await mutationParent(service, id, call);
10370
10985
  if ("error" in lookup) return lookup.error;
10371
10986
  const { parent } = lookup;
10372
- const rows2 = (0, import_utils34.get)(parent, sub);
10987
+ const rows2 = (0, import_utils35.get)(parent, sub);
10373
10988
  const admit = await inputAdmission(service, call, parent);
10374
10989
  const allowed = (Array.isArray(data) ? data : [data]).map((row) => admit(row).allowedData);
10375
10990
  if (addFirst) rows2.unshift(...allowed);
@@ -10390,7 +11005,7 @@ async function deleteSub(service, persist, id, sub, subId, options) {
10390
11005
  const identity = { _id: subId };
10391
11006
  const filter2 = await subdocumentRows(service, call.child, identity, identity, sub);
10392
11007
  if (filter2 === false) return denied2();
10393
- const row = findElement((0, import_utils34.get)(parent, sub), filter2);
11008
+ const row = findElement((0, import_utils35.get)(parent, sub), filter2);
10394
11009
  if (!row) return denied2("not_found" /* NotFound */);
10395
11010
  await ("deleteOne" in row ? row.deleteOne?.() : row.remove?.());
10396
11011
  await persist(() => parent.save());
@@ -10663,7 +11278,8 @@ var Service = class extends Base {
10663
11278
  async finalizeDirectOutput(args) {
10664
11279
  const { plan, context } = args;
10665
11280
  const { authorization, authorizationBinding: binding } = plan;
10666
- const { access, configuration } = readServiceAuthorization(authorization, binding);
11281
+ const access = readServiceAuthorizationAccess(authorization, binding);
11282
+ const configuration = readServiceOutputMetadata(authorization, binding);
10667
11283
  const source = getIncludeSource(args.doc);
10668
11284
  const snapshot = isolateDocForOutput(source);
10669
11285
  for (const key of Object.keys(snapshot))
@@ -10704,20 +11320,20 @@ var Service = class extends Base {
10704
11320
  const field = configuration.documentPermissionField ?? "_permissions";
10705
11321
  unsetDocPath(output, field);
10706
11322
  if (!configuration.stripPermissionsField) {
10707
- (0, import_utils35.set)(output, field, args.includePermissions || args.includeFieldPermissions ? deepIsolateValue(grants) : {});
11323
+ (0, import_utils36.set)(output, field, args.includePermissions || args.includeFieldPermissions ? deepIsolateValue(grants) : {});
10708
11324
  if (args.includeFieldPermissions && !configuration.disableFieldPermissions) {
10709
11325
  const rowAccess = this.asServiceHookContext(context).fieldPermissionAccess ?? await this.getFieldPermissionAccess([snapshot._id]);
10710
11326
  const id = String(snapshot._id);
10711
11327
  const views = rowAccess.readIds?.has(id) ? await requestOutputFieldPaths(handle, binding, "read") : [];
10712
11328
  const edits = rowAccess.updateIds?.has(id) ? await requestOutputFieldPaths(handle, binding, "update") : [];
10713
11329
  const map2 = (paths) => paths.length ? Object.fromEntries(paths.map((path) => [path, true])) : { $: "_" };
10714
- (0, import_utils35.set)(output, `${field}._view`, map2(views));
10715
- (0, import_utils35.set)(output, `${field}._edit`, map2(edits));
10716
- } else if (!args.includePermissions) (0, import_utils35.set)(output, field, { _view: { $: "_" }, _edit: { $: "_" } });
11330
+ (0, import_utils36.set)(output, `${field}._view`, map2(views));
11331
+ (0, import_utils36.set)(output, `${field}._edit`, map2(edits));
11332
+ } else if (!args.includePermissions) (0, import_utils36.set)(output, field, { _view: { $: "_" }, _edit: { $: "_" } });
10717
11333
  const exposed = configuration.exposedDocPermissionKeys;
10718
11334
  if (exposed) {
10719
- const metadata = (0, import_utils35.get)(output, field);
10720
- (0, import_utils35.set)(
11335
+ const metadata = (0, import_utils36.get)(output, field);
11336
+ (0, import_utils36.set)(
10721
11337
  output,
10722
11338
  field,
10723
11339
  Object.fromEntries(
@@ -10978,7 +11594,7 @@ var Service = class extends Base {
10978
11594
  return docs.map((doc) => {
10979
11595
  try {
10980
11596
  const plain = toObject(doc);
10981
- const val = (0, import_utils35.get)(plain, associationField);
11597
+ const val = (0, import_utils36.get)(plain, associationField);
10982
11598
  return deepIsolateValue(val);
10983
11599
  } catch {
10984
11600
  return void 0;
@@ -11087,7 +11703,7 @@ var Service = class extends Base {
11087
11703
  if (this.isScalarPopulateValue(rawTarget)) return rawTarget;
11088
11704
  const isDoc = (() => {
11089
11705
  try {
11090
- if ((0, import_utils35.isPlainObject)(rawTarget)) return true;
11706
+ if ((0, import_utils36.isPlainObject)(rawTarget)) return true;
11091
11707
  const maybe = rawTarget;
11092
11708
  if (maybe && typeof maybe === "object" && "_doc" in maybe) return true;
11093
11709
  if (maybe && typeof maybe.toObject === "function") return true;
@@ -11175,7 +11791,7 @@ var Service = class extends Base {
11175
11791
  child = getDocValue(current, key);
11176
11792
  if (child === void 0) {
11177
11793
  try {
11178
- child = (0, import_utils35.get)(current, key);
11794
+ child = (0, import_utils36.get)(current, key);
11179
11795
  } catch {
11180
11796
  return;
11181
11797
  }
@@ -11410,7 +12026,7 @@ var Service = class extends Base {
11410
12026
  originalDocumentSnapshot: toObject(doc),
11411
12027
  resolvedQuery: query
11412
12028
  };
11413
- const correlatedSnapshots = [(0, import_utils35.cloneDeep)(toObject(doc))];
12029
+ const correlatedSnapshots = [(0, import_utils36.cloneDeep)(toObject(doc))];
11414
12030
  try {
11415
12031
  doc = await this.includeDocs(doc, includes, state.authorization);
11416
12032
  if (correlatedIncludes.length > 0) {
@@ -11592,7 +12208,7 @@ var Service = class extends Base {
11592
12208
  const findAssociationField = this.getAssociationFieldFromOptions(options);
11593
12209
  const withAssocSelect = findAssociationField && !finalSelect.includes(findAssociationField) ? [...finalSelect, findAssociationField] : finalSelect;
11594
12210
  const dbSelect = this.buildDbSelectForAssociation(withAssocSelect, findAssociationField);
11595
- const filteredPopulate = (0, import_utils35.isArray)(withAssocSelect) && (0, import_utils35.isArray)(_populate) ? _populate.filter(
12211
+ const filteredPopulate = (0, import_utils36.isArray)(withAssocSelect) && (0, import_utils36.isArray)(_populate) ? _populate.filter(
11596
12212
  (p) => [
11597
12213
  ...virtualPlan.publicPersistedFetchSelection,
11598
12214
  ...findAssociationField ? [findAssociationField] : []
@@ -11652,7 +12268,7 @@ var Service = class extends Base {
11652
12268
  findAssociationField ? [findAssociationField] : []
11653
12269
  );
11654
12270
  const capturedAssociation = findAssociationField ? this.captureAssociationValues(docs, findAssociationField) : void 0;
11655
- const correlatedSnapshots = docs.map((doc) => (0, import_utils35.cloneDeep)(toObject(doc)));
12271
+ const correlatedSnapshots = docs.map((doc) => (0, import_utils36.cloneDeep)(toObject(doc)));
11656
12272
  try {
11657
12273
  docs = await this.includeDocs(docs, includes, state.authorization);
11658
12274
  if (correlatedIncludes.length > 0) {
@@ -11851,12 +12467,12 @@ var Service = class extends Base {
11851
12467
  context.allowedFields = allowedFields;
11852
12468
  context.allowedData = allowedData;
11853
12469
  const validated = await this.validate(allowedData, "create", context);
11854
- if ((0, import_utils35.isBoolean)(validated)) {
12470
+ if ((0, import_utils36.isBoolean)(validated)) {
11855
12471
  if (!validated) {
11856
12472
  validationErrors.push({ index, errors: [] });
11857
12473
  return void 0;
11858
12474
  }
11859
- } else if ((0, import_utils35.isArray)(validated)) {
12475
+ } else if ((0, import_utils36.isArray)(validated)) {
11860
12476
  if (validated.length > 0) {
11861
12477
  validationErrors.push({
11862
12478
  index,
@@ -12067,7 +12683,7 @@ var Service = class extends Base {
12067
12683
  }
12068
12684
  let doc = await this.model.findOne({
12069
12685
  filter: _filter,
12070
- select: (0, import_utils35.uniq)([...updatePlan.persistedFetchSelection, ...inputFetchPaths(captured.configuration.catalog)]).map(
12686
+ select: (0, import_utils36.uniq)([...updatePlan.persistedFetchSelection, ...inputFetchPaths(captured.configuration.catalog)]).map(
12071
12687
  (path) => `+${path}`
12072
12688
  )
12073
12689
  });
@@ -12106,12 +12722,12 @@ var Service = class extends Base {
12106
12722
  context.allowedFields = allowedFields;
12107
12723
  context.allowedData = allowedData;
12108
12724
  const validated = await this.validate(allowedData, "update", context);
12109
- if ((0, import_utils35.isBoolean)(validated)) {
12725
+ if ((0, import_utils36.isBoolean)(validated)) {
12110
12726
  if (!validated) {
12111
12727
  this.completeOp("updateOne", startedAt, "bad_request" /* BadRequest */, _filter);
12112
12728
  return { success: false, kind: "error", code: "bad_request" /* BadRequest */ };
12113
12729
  }
12114
- } else if ((0, import_utils35.isArray)(validated)) {
12730
+ } else if ((0, import_utils36.isArray)(validated)) {
12115
12731
  if (validated.length > 0) {
12116
12732
  this.completeOp("updateOne", startedAt, "bad_request" /* BadRequest */, _filter);
12117
12733
  return { success: false, kind: "error", code: "bad_request" /* BadRequest */, errors: validated };
@@ -12131,10 +12747,10 @@ var Service = class extends Base {
12131
12747
  const diffExcludeFields = [this.options.documentPermissionField, "__v"];
12132
12748
  this.asServiceHookContext(context).diff = (d) => {
12133
12749
  context.changes = (0, import_just_diff.diff)(
12134
- (0, import_utils35.omit)(context.originalDocumentSnapshot, diffExcludeFields),
12135
- (0, import_utils35.omit)(d.toObject({ virtuals: false }), diffExcludeFields)
12750
+ (0, import_utils36.omit)(context.originalDocumentSnapshot, diffExcludeFields),
12751
+ (0, import_utils36.omit)(d.toObject({ virtuals: false }), diffExcludeFields)
12136
12752
  ) || [];
12137
- context.modifiedPaths = (0, import_utils35.uniq)(context.changes.map((di) => di.path.length > 0 ? String(di.path[0]) : ""));
12753
+ context.modifiedPaths = (0, import_utils36.uniq)(context.changes.map((di) => di.path.length > 0 ? String(di.path[0]) : ""));
12138
12754
  };
12139
12755
  doc = assertModelDocument(await this.afterPersist(doc, "update", context), this.modelName, "afterPersist");
12140
12756
  context.currentDocument = doc;
@@ -12222,7 +12838,7 @@ var Service = class extends Base {
12222
12838
  const upsertOptions = this.resolveUpsertOptions(options);
12223
12839
  const updateIntent = captureModelServiceIntent(this, "updateOne", upsertArgs, upsertOptions);
12224
12840
  const createIntent = captureModelServiceIntent(this, "create", upsertArgs, upsertOptions);
12225
- const related = (0, import_utils35.uniqBy)(
12841
+ const related = (0, import_utils36.uniqBy)(
12226
12842
  [...this.captureRelated(updateIntent.args), ...this.captureRelated(createIntent.args)],
12227
12843
  (target) => target.path
12228
12844
  );
@@ -12663,7 +13279,7 @@ var Service = class extends Base {
12663
13279
  return resolveExistsOptions(this, options);
12664
13280
  }
12665
13281
  async getFieldPermissionAccess(ids) {
12666
- const uniqueIds = (0, import_utils35.compact)((0, import_utils35.uniqBy)(ids, (id) => String(id)).map((id) => String(id)));
13282
+ const uniqueIds = (0, import_utils36.compact)((0, import_utils36.uniqBy)(ids, (id) => String(id)).map((id) => String(id)));
12667
13283
  if (uniqueIds.length === 0) {
12668
13284
  return {
12669
13285
  readIds: /* @__PURE__ */ new Set(),
@@ -12709,7 +13325,7 @@ var Service = class extends Base {
12709
13325
  * (direct/root-entry 200); count measures visible rows, not all updated rows.
12710
13326
  */
12711
13327
  async bulkUpdateSub(id, sub, data, options) {
12712
- return bulkUpdateSub(this, this.persist, id, sub, (0, import_utils35.castArray)(data), options);
13328
+ return bulkUpdateSub(this, this.persist, id, sub, (0, import_utils36.castArray)(data), options);
12713
13329
  }
12714
13330
  /**
12715
13331
  * Append/prepend admitted rows, then return the visible full array (including when
@@ -12733,7 +13349,7 @@ var Service = class extends Base {
12733
13349
  };
12734
13350
 
12735
13351
  // src/services/public-service.ts
12736
- var import_utils36 = require("@web-ts-toolkit/utils");
13352
+ var import_utils37 = require("@web-ts-toolkit/utils");
12737
13353
  init_helpers();
12738
13354
  init_permissions_alias();
12739
13355
  init_document();
@@ -12859,7 +13475,7 @@ var PublicService = class extends Service {
12859
13475
  let d = toObject(doc);
12860
13476
  d = await this.decorate(d, "create", context);
12861
13477
  d = this.runTasks(d, tasks);
12862
- if (select) d = copyPermissionsAlias(d, (0, import_utils36.pick)(d, [...normalizeSelect(select), ...this.baseFieldsExt]));
13478
+ if (select) d = copyPermissionsAlias(d, (0, import_utils37.pick)(d, [...normalizeSelect(select), ...this.baseFieldsExt]));
12863
13479
  return d;
12864
13480
  }
12865
13481
  );
@@ -13078,8 +13694,8 @@ var PublicService = class extends Service {
13078
13694
  let d = toObject(doc);
13079
13695
  d = await this.decorate(d, "update", context);
13080
13696
  d = this.runTasks(d, tasks);
13081
- if (select) d = copyPermissionsAlias(d, (0, import_utils36.pick)(d, [...normalizeSelect(select), ...this.baseFieldsExt]));
13082
- else if (!returningAll) d = copyPermissionsAlias(d, (0, import_utils36.pick)(d, returningKeys));
13697
+ if (select) d = copyPermissionsAlias(d, (0, import_utils37.pick)(d, [...normalizeSelect(select), ...this.baseFieldsExt]));
13698
+ else if (!returningAll) d = copyPermissionsAlias(d, (0, import_utils37.pick)(d, returningKeys));
13083
13699
  return d;
13084
13700
  }
13085
13701
  );
@@ -13162,8 +13778,8 @@ var PublicService = class extends Service {
13162
13778
  let d = toObject(doc);
13163
13779
  d = await this.decorate(d, "update", context);
13164
13780
  d = this.runTasks(d, tasks2);
13165
- if (select) d = copyPermissionsAlias(d, (0, import_utils36.pick)(d, [...normalizeSelect(select), ...this.baseFieldsExt]));
13166
- else if (!returningAll) d = copyPermissionsAlias(d, (0, import_utils36.pick)(d, returningKeys));
13781
+ if (select) d = copyPermissionsAlias(d, (0, import_utils37.pick)(d, [...normalizeSelect(select), ...this.baseFieldsExt]));
13782
+ else if (!returningAll) d = copyPermissionsAlias(d, (0, import_utils37.pick)(d, returningKeys));
13167
13783
  return d;
13168
13784
  }
13169
13785
  );
@@ -13188,7 +13804,7 @@ var PublicService = class extends Service {
13188
13804
  d = await this.decorate(d, "create", context);
13189
13805
  d = this.runTasks(d, tasks);
13190
13806
  if (createSelect)
13191
- d = copyPermissionsAlias(d, (0, import_utils36.pick)(d, [...normalizeSelect(createSelect), ...this.baseFieldsExt]));
13807
+ d = copyPermissionsAlias(d, (0, import_utils37.pick)(d, [...normalizeSelect(createSelect), ...this.baseFieldsExt]));
13192
13808
  return d;
13193
13809
  }
13194
13810
  );
@@ -13333,7 +13949,7 @@ var PublicService = class extends Service {
13333
13949
  init_options();
13334
13950
  init_data_values();
13335
13951
  init_helpers();
13336
- var import_utils37 = require("@web-ts-toolkit/utils");
13952
+ var import_utils38 = require("@web-ts-toolkit/utils");
13337
13953
  init_request_complexity();
13338
13954
  init_runtime_context();
13339
13955
  init_runtime();
@@ -13362,7 +13978,7 @@ var DataService = class {
13362
13978
  let doc = await findElement(this.data, _filter);
13363
13979
  if (!doc) return { success: false, kind: "error", code: "not_found" /* NotFound */, query };
13364
13980
  doc = await this.trimOutputFields(doc, access);
13365
- if (_select.length > 0) doc = (0, import_utils37.pick)(doc, _select);
13981
+ if (_select.length > 0) doc = (0, import_utils38.pick)(doc, _select);
13366
13982
  return {
13367
13983
  success: true,
13368
13984
  kind: "single",
@@ -13408,13 +14024,13 @@ var DataService = class {
13408
14024
  const totalCount = docs.length;
13409
14025
  if (sort) {
13410
14026
  const normalizedSort = normalizeSortForOrderBy(sort);
13411
- docs = (0, import_utils37.orderBy)(docs, normalizedSort.fields, normalizedSort.orders);
14027
+ docs = (0, import_utils38.orderBy)(docs, normalizedSort.fields, normalizedSort.orders);
13412
14028
  }
13413
14029
  const pagedDocs = docs.slice(query.skip, query.limit && query.skip + query.limit);
13414
14030
  const { maxHookConcurrency } = this.getRequestComplexity();
13415
14031
  const trimmed = await mapWithConcurrencyLimit(pagedDocs, maxHookConcurrency, async (doc) => {
13416
14032
  doc = await this.trimOutputFields(doc, "list");
13417
- if (_select.length > 0) doc = (0, import_utils37.pick)(doc, _select);
14033
+ if (_select.length > 0) doc = (0, import_utils38.pick)(doc, _select);
13418
14034
  return copyDataValue(doc);
13419
14035
  });
13420
14036
  if (!hasExplicitLimit && trimmed.length === totalCount) {
@@ -13489,10 +14105,10 @@ var DataService = class {
13489
14105
  init_helpers();
13490
14106
 
13491
14107
  // src/processors.ts
13492
- var import_utils38 = require("@web-ts-toolkit/utils");
14108
+ var import_utils39 = require("@web-ts-toolkit/utils");
13493
14109
  init_permissions_alias();
13494
14110
  function cloneProcessorValue(value) {
13495
- const copy = (0, import_utils38.cloneDeep)(value);
14111
+ const copy = (0, import_utils39.cloneDeep)(value);
13496
14112
  copyPermissionsAliasGraph(value, copy);
13497
14113
  return copy;
13498
14114
  }
@@ -13530,10 +14146,10 @@ function resolveLeafParents(obj, src) {
13530
14146
  for (let ind = 0; ind < segs.length - 1; ind += 1) {
13531
14147
  const seg = segs[ind];
13532
14148
  targets = targets.reduce((ret, target) => {
13533
- if (!(0, import_utils38.isPlainObject)(target)) return ret;
14149
+ if (!(0, import_utils39.isPlainObject)(target)) return ret;
13534
14150
  const targetObject = target;
13535
14151
  const next = targetObject[seg];
13536
- if ((0, import_utils38.isArray)(next)) {
14152
+ if ((0, import_utils39.isArray)(next)) {
13537
14153
  for (const item of next) {
13538
14154
  ret.push(item);
13539
14155
  }
@@ -13543,8 +14159,8 @@ function resolveLeafParents(obj, src) {
13543
14159
  }
13544
14160
  const leaf = segs[segs.length - 1];
13545
14161
  const pairs = [];
13546
- (0, import_utils38.forEach)(targets, (target) => {
13547
- if (!(0, import_utils38.isPlainObject)(target)) return;
14162
+ (0, import_utils39.forEach)(targets, (target) => {
14163
+ if (!(0, import_utils39.isPlainObject)(target)) return;
13548
14164
  pairs.push({ parent: target, leaf });
13549
14165
  });
13550
14166
  return pairs;
@@ -13553,7 +14169,7 @@ var copyAndDepopulate = (docObject, operations, options = { mutable: true, idFie
13553
14169
  const mutable = options.mutable !== false;
13554
14170
  const idField = options.idField ?? "_id";
13555
14171
  const obj = mutable ? docObject : cloneProcessorValue(docObject);
13556
- (0, import_utils38.forEach)(Array.isArray(operations) ? operations : [], (op) => {
14172
+ (0, import_utils39.forEach)(Array.isArray(operations) ? operations : [], (op) => {
13557
14173
  if (!op || typeof op.src !== "string" || typeof op.dest !== "string") return;
13558
14174
  const src = op.src;
13559
14175
  const dest = op.dest;
@@ -13562,19 +14178,19 @@ var copyAndDepopulate = (docObject, operations, options = { mutable: true, idFie
13562
14178
  assertSafePath(dest);
13563
14179
  let targets = [obj];
13564
14180
  const segs = src.split(".");
13565
- (0, import_utils38.forEach)(segs, (seg, ind) => {
14181
+ (0, import_utils39.forEach)(segs, (seg, ind) => {
13566
14182
  if (segs.length === ind + 1) {
13567
- (0, import_utils38.forEach)(targets, (target) => {
13568
- if (!(0, import_utils38.isPlainObject)(target)) return;
14183
+ (0, import_utils39.forEach)(targets, (target) => {
14184
+ if (!(0, import_utils39.isPlainObject)(target)) return;
13569
14185
  const targetObject = target;
13570
14186
  const leaf = targetObject[seg];
13571
14187
  const sourceForDest = leaf;
13572
14188
  let depopulated;
13573
- if ((0, import_utils38.isArray)(leaf)) {
14189
+ if ((0, import_utils39.isArray)(leaf)) {
13574
14190
  if (leaf.length === 0) {
13575
14191
  depopulated = [];
13576
- } else if (leaf.every((item) => (0, import_utils38.isPlainObject)(item))) {
13577
- depopulated = (0, import_utils38.map)(leaf, idField).map((id, i) => {
14192
+ } else if (leaf.every((item) => (0, import_utils39.isPlainObject)(item))) {
14193
+ depopulated = (0, import_utils39.map)(leaf, idField).map((id, i) => {
13578
14194
  if (id === void 0) {
13579
14195
  failMissingId(`${src}[${i}]`);
13580
14196
  }
@@ -13583,8 +14199,8 @@ var copyAndDepopulate = (docObject, operations, options = { mutable: true, idFie
13583
14199
  } else {
13584
14200
  return;
13585
14201
  }
13586
- } else if ((0, import_utils38.isPlainObject)(leaf)) {
13587
- const id = (0, import_utils38.get)(leaf, idField);
14202
+ } else if ((0, import_utils39.isPlainObject)(leaf)) {
14203
+ const id = (0, import_utils39.get)(leaf, idField);
13588
14204
  if (id === void 0) {
13589
14205
  failMissingId(src);
13590
14206
  }
@@ -13592,15 +14208,15 @@ var copyAndDepopulate = (docObject, operations, options = { mutable: true, idFie
13592
14208
  } else {
13593
14209
  return;
13594
14210
  }
13595
- (0, import_utils38.set)(targetObject, dest, sourceForDest);
13596
- (0, import_utils38.set)(targetObject, seg, depopulated);
14211
+ (0, import_utils39.set)(targetObject, dest, sourceForDest);
14212
+ (0, import_utils39.set)(targetObject, seg, depopulated);
13597
14213
  });
13598
14214
  } else {
13599
14215
  targets = targets.reduce((ret, target) => {
13600
- if (!(0, import_utils38.isPlainObject)(target)) return ret;
14216
+ if (!(0, import_utils39.isPlainObject)(target)) return ret;
13601
14217
  const targetObject = target;
13602
14218
  const next = targetObject[seg];
13603
- if ((0, import_utils38.isArray)(next)) {
14219
+ if ((0, import_utils39.isArray)(next)) {
13604
14220
  for (const item of next) {
13605
14221
  ret.push(item);
13606
14222
  }
@@ -13615,7 +14231,7 @@ var copyAndDepopulate = (docObject, operations, options = { mutable: true, idFie
13615
14231
  var copyPaths = (docObject, operations, options = { mutable: true }) => {
13616
14232
  const mutable = options.mutable !== false;
13617
14233
  const obj = mutable ? docObject : cloneProcessorValue(docObject);
13618
- (0, import_utils38.forEach)(Array.isArray(operations) ? operations : [], (op) => {
14234
+ (0, import_utils39.forEach)(Array.isArray(operations) ? operations : [], (op) => {
13619
14235
  if (!op || typeof op.src !== "string" || typeof op.dest !== "string") return;
13620
14236
  const src = op.src;
13621
14237
  const dest = op.dest;
@@ -13623,9 +14239,9 @@ var copyPaths = (docObject, operations, options = { mutable: true }) => {
13623
14239
  assertSafePath(src, "copyPaths");
13624
14240
  assertSafePath(dest, "copyPaths");
13625
14241
  if (src === dest) return;
13626
- (0, import_utils38.forEach)(resolveLeafParents(obj, src), ({ parent, leaf }) => {
13627
- if (!(0, import_utils38.hasOwn)(parent, leaf)) return;
13628
- (0, import_utils38.set)(parent, dest, cloneProcessorValue(parent[leaf]));
14242
+ (0, import_utils39.forEach)(resolveLeafParents(obj, src), ({ parent, leaf }) => {
14243
+ if (!(0, import_utils39.hasOwn)(parent, leaf)) return;
14244
+ (0, import_utils39.set)(parent, dest, cloneProcessorValue(parent[leaf]));
13629
14245
  });
13630
14246
  });
13631
14247
  return obj;
@@ -13633,7 +14249,7 @@ var copyPaths = (docObject, operations, options = { mutable: true }) => {
13633
14249
  var movePaths = (docObject, operations, options = { mutable: true }) => {
13634
14250
  const mutable = options.mutable !== false;
13635
14251
  const obj = mutable ? docObject : cloneProcessorValue(docObject);
13636
- (0, import_utils38.forEach)(Array.isArray(operations) ? operations : [], (op) => {
14252
+ (0, import_utils39.forEach)(Array.isArray(operations) ? operations : [], (op) => {
13637
14253
  if (!op || typeof op.src !== "string" || typeof op.dest !== "string") return;
13638
14254
  const src = op.src;
13639
14255
  const dest = op.dest;
@@ -13641,10 +14257,10 @@ var movePaths = (docObject, operations, options = { mutable: true }) => {
13641
14257
  assertSafePath(src, "movePaths");
13642
14258
  assertSafePath(dest, "movePaths");
13643
14259
  if (src === dest) return;
13644
- (0, import_utils38.forEach)(resolveLeafParents(obj, src), ({ parent, leaf }) => {
13645
- if (!(0, import_utils38.hasOwn)(parent, leaf)) return;
14260
+ (0, import_utils39.forEach)(resolveLeafParents(obj, src), ({ parent, leaf }) => {
14261
+ if (!(0, import_utils39.hasOwn)(parent, leaf)) return;
13646
14262
  const value = cloneProcessorValue(parent[leaf]);
13647
- (0, import_utils38.set)(parent, dest, value);
14263
+ (0, import_utils39.set)(parent, dest, value);
13648
14264
  if (dest === leaf || dest.startsWith(`${leaf}.`)) return;
13649
14265
  delete parent[leaf];
13650
14266
  });
@@ -13656,7 +14272,7 @@ var sliceArrays = (docObject, operations, options = { mutable: true, maxSlice: D
13656
14272
  const maxSlice = options.maxSlice ?? DEFAULT_MAX_SLICE;
13657
14273
  assertNonNegativeSafeInteger(maxSlice, "maxSlice", "sliceArrays");
13658
14274
  const obj = mutable ? docObject : cloneProcessorValue(docObject);
13659
- (0, import_utils38.forEach)(Array.isArray(operations) ? operations : [], (op) => {
14275
+ (0, import_utils39.forEach)(Array.isArray(operations) ? operations : [], (op) => {
13660
14276
  if (!op || typeof op.src !== "string") return;
13661
14277
  const src = op.src;
13662
14278
  if (src.length === 0) return;
@@ -13673,15 +14289,15 @@ var sliceArrays = (docObject, operations, options = { mutable: true, maxSlice: D
13673
14289
  assertNonNegativeSafeInteger(op.limit, "limit", "sliceArrays");
13674
14290
  limit = Math.min(op.limit, maxSlice);
13675
14291
  }
13676
- (0, import_utils38.forEach)(resolveLeafParents(obj, src), ({ parent, leaf }) => {
14292
+ (0, import_utils39.forEach)(resolveLeafParents(obj, src), ({ parent, leaf }) => {
13677
14293
  const leafValue = parent[leaf];
13678
- if (!(0, import_utils38.isArray)(leafValue)) return;
14294
+ if (!(0, import_utils39.isArray)(leafValue)) return;
13679
14295
  const end = typeof limit === "undefined" ? void 0 : skip + limit;
13680
14296
  const window = leafValue.slice(skip, end);
13681
14297
  if (typeof rawDest === "undefined") {
13682
- (0, import_utils38.set)(parent, leaf, window);
14298
+ (0, import_utils39.set)(parent, leaf, window);
13683
14299
  } else {
13684
- (0, import_utils38.set)(parent, rawDest, window);
14300
+ (0, import_utils39.set)(parent, rawDest, window);
13685
14301
  }
13686
14302
  });
13687
14303
  });
@@ -13690,27 +14306,27 @@ var sliceArrays = (docObject, operations, options = { mutable: true, maxSlice: D
13690
14306
  var countPaths = (docObject, operations, options = { mutable: true }) => {
13691
14307
  const mutable = options.mutable !== false;
13692
14308
  const obj = mutable ? docObject : cloneProcessorValue(docObject);
13693
- (0, import_utils38.forEach)(Array.isArray(operations) ? operations : [], (op) => {
14309
+ (0, import_utils39.forEach)(Array.isArray(operations) ? operations : [], (op) => {
13694
14310
  if (!op || typeof op.src !== "string" || typeof op.dest !== "string") return;
13695
14311
  const src = op.src;
13696
14312
  const dest = op.dest;
13697
14313
  if (src.length === 0 || dest.length === 0) return;
13698
14314
  assertSafePath(src, "countPaths");
13699
14315
  assertSafePath(dest, "countPaths");
13700
- (0, import_utils38.forEach)(resolveLeafParents(obj, src), ({ parent, leaf }) => {
13701
- if (!(0, import_utils38.hasOwn)(parent, leaf)) return;
14316
+ (0, import_utils39.forEach)(resolveLeafParents(obj, src), ({ parent, leaf }) => {
14317
+ if (!(0, import_utils39.hasOwn)(parent, leaf)) return;
13702
14318
  const leafValue = parent[leaf];
13703
14319
  let count;
13704
- if ((0, import_utils38.isArray)(leafValue)) {
14320
+ if ((0, import_utils39.isArray)(leafValue)) {
13705
14321
  count = leafValue.length;
13706
- } else if ((0, import_utils38.isPlainObject)(leafValue)) {
14322
+ } else if ((0, import_utils39.isPlainObject)(leafValue)) {
13707
14323
  count = Object.keys(leafValue).length;
13708
14324
  } else if (leafValue === null || typeof leafValue === "undefined") {
13709
14325
  count = 0;
13710
14326
  } else {
13711
14327
  count = 1;
13712
14328
  }
13713
- (0, import_utils38.set)(parent, dest, count);
14329
+ (0, import_utils39.set)(parent, dest, count);
13714
14330
  });
13715
14331
  });
13716
14332
  return obj;
@@ -13718,15 +14334,15 @@ var countPaths = (docObject, operations, options = { mutable: true }) => {
13718
14334
  var maskPaths = (docObject, operations, options = { mutable: true }) => {
13719
14335
  const mutable = options.mutable !== false;
13720
14336
  const obj = mutable ? docObject : cloneProcessorValue(docObject);
13721
- (0, import_utils38.forEach)(Array.isArray(operations) ? operations : [], (op) => {
14337
+ (0, import_utils39.forEach)(Array.isArray(operations) ? operations : [], (op) => {
13722
14338
  if (!op || typeof op.src !== "string") return;
13723
14339
  const src = op.src;
13724
14340
  if (src.length === 0) return;
13725
14341
  assertSafePath(src, "maskPaths");
13726
14342
  const replacement = Object.prototype.hasOwnProperty.call(op, "replacement") ? op.replacement : DEFAULT_MASK_REPLACEMENT;
13727
- (0, import_utils38.forEach)(resolveLeafParents(obj, src), ({ parent, leaf }) => {
13728
- if (!(0, import_utils38.hasOwn)(parent, leaf)) return;
13729
- (0, import_utils38.set)(parent, leaf, replacement);
14343
+ (0, import_utils39.forEach)(resolveLeafParents(obj, src), ({ parent, leaf }) => {
14344
+ if (!(0, import_utils39.hasOwn)(parent, leaf)) return;
14345
+ (0, import_utils39.set)(parent, leaf, replacement);
13730
14346
  });
13731
14347
  });
13732
14348
  return obj;
@@ -13800,10 +14416,10 @@ var Core = class {
13800
14416
  getIdentifier(modelName) {
13801
14417
  const resolveIdFilter = getModelOption(modelName, "resolveIdFilter");
13802
14418
  const idField = getModelOption(modelName, "idField");
13803
- if ((0, import_utils39.isFunction)(resolveIdFilter)) {
14419
+ if ((0, import_utils40.isFunction)(resolveIdFilter)) {
13804
14420
  return null;
13805
14421
  }
13806
- if ((0, import_utils39.isString)(idField)) {
14422
+ if ((0, import_utils40.isString)(idField)) {
13807
14423
  return idField;
13808
14424
  }
13809
14425
  return "_id";
@@ -13895,7 +14511,7 @@ var Core = class {
13895
14511
  /** Persisted request-only populate admission; fetch planning is not field authority. */
13896
14512
  async requestPopulateSelect(configuration, permissions, access, targetFields = null, scopePath = []) {
13897
14513
  const subPaths = scopePath.flatMap((part) => [part, "sub"]);
13898
- const permissionSchema = (0, import_utils39.get)(configuration, ["permissionSchema", ...subPaths]);
14514
+ const permissionSchema = (0, import_utils40.get)(configuration, ["permissionSchema", ...subPaths]);
13899
14515
  const prefix = scopePath.length ? `${scopePath.join(".")}.` : "";
13900
14516
  const virtualNames = (configuration.catalog.virtualPaths ?? []).filter((path) => path.startsWith(prefix)).map((path) => path.slice(prefix.length)).filter((path) => !path.includes("."));
13901
14517
  return resolveSelectForRequest({
@@ -13918,7 +14534,7 @@ var Core = class {
13918
14534
  if (!_populate) return [];
13919
14535
  const descriptors = copyAuthorizationValue(Array.isArray(_populate) ? _populate : [_populate], true);
13920
14536
  for (const p of descriptors) {
13921
- if (!(0, import_utils39.isString)(p)) assertPopulateAccess(p.access);
14537
+ if (!(0, import_utils40.isString)(p)) assertPopulateAccess(p.access);
13922
14538
  }
13923
14539
  const runtime = this.requestRuntime;
13924
14540
  const globalOptions = modelServiceGlobalOptions(this, runtime);
@@ -13928,13 +14544,13 @@ var Core = class {
13928
14544
  const permissions = new permission_default(
13929
14545
  Object.fromEntries(originalPermissions.keys.map((key) => [key, originalPermissions.has(key)]))
13930
14546
  );
13931
- const populate = (0, import_utils39.compact)(
14547
+ const populate = (0, import_utils40.compact)(
13932
14548
  await Promise.all(
13933
14549
  descriptors.map(async (p) => {
13934
- const populateAccess = !(0, import_utils39.isString)(p) && p.access ? p.access : access;
14550
+ const populateAccess = !(0, import_utils40.isString)(p) && p.access ? p.access : access;
13935
14551
  assertPopulateAccess(populateAccess);
13936
- const originalSelect = (0, import_utils39.isString)(p) ? void 0 : p.select;
13937
- const ret = (0, import_utils39.isString)(p) ? { path: p } : {
14552
+ const originalSelect = (0, import_utils40.isString)(p) ? void 0 : p.select;
14553
+ const ret = (0, import_utils40.isString)(p) ? { path: p } : {
13938
14554
  path: p.path,
13939
14555
  select: normalizeSelect(p.select)
13940
14556
  };
@@ -13973,11 +14589,11 @@ var Core = class {
13973
14589
  targetConfiguration.alwaysSelectFields,
13974
14590
  populateAccess
13975
14591
  );
13976
- ret.select = (0, import_utils39.uniq)([
14592
+ ret.select = (0, import_utils40.uniq)([
13977
14593
  ...ret.select,
13978
14594
  ...stripVirtuals(hookInputs, [...targetConfiguration.catalog.virtualPaths ?? []])
13979
14595
  ]);
13980
- const match = (0, import_utils39.isString)(p) ? {} : p.match ?? {};
14596
+ const match = (0, import_utils40.isString)(p) ? {} : p.match ?? {};
13981
14597
  const filter2 = await resolveAccessFilterForRequest({
13982
14598
  req: this.req,
13983
14599
  permissions,
@@ -14008,7 +14624,7 @@ var Core = class {
14008
14624
  internalFetch: { baseFields: ["_id"] },
14009
14625
  globalPermissions: permissions
14010
14626
  });
14011
- const merged = (0, import_utils39.uniq)([...normalizeSelect(ret.select), ...targetPlan.virtualOnlyDeps ?? []]).filter(
14627
+ const merged = (0, import_utils40.uniq)([...normalizeSelect(ret.select), ...targetPlan.virtualOnlyDeps ?? []]).filter(
14012
14628
  (t) => t !== "-_id" && !t.includes(".sub.")
14013
14629
  );
14014
14630
  if (!merged.includes("_id")) merged.push("_id");
@@ -14030,10 +14646,10 @@ var Core = class {
14030
14646
  }
14031
14647
  async validate(modelName, allowedData, access, context) {
14032
14648
  const validate = getModelOption(modelName, `validate.${access}`, null);
14033
- if ((0, import_utils39.isFunction)(validate)) {
14649
+ if ((0, import_utils40.isFunction)(validate)) {
14034
14650
  const permissions = this.getGlobalPermissions();
14035
14651
  return validate.call(this.req, allowedData, permissions, context);
14036
- } else if ((0, import_utils39.isBoolean)(validate) || (0, import_utils39.isArray)(validate)) {
14652
+ } else if ((0, import_utils40.isBoolean)(validate) || (0, import_utils40.isArray)(validate)) {
14037
14653
  return validate;
14038
14654
  } else {
14039
14655
  return true;
@@ -14058,7 +14674,7 @@ var Core = class {
14058
14674
  const changeOptions = getModelOption(modelName, `onChange`, {});
14059
14675
  for (let x = 0; x < context.modifiedPaths.length; x++) {
14060
14676
  const mpath = context.modifiedPaths[x];
14061
- if ((0, import_utils39.isFunction)(changeOptions[mpath])) {
14677
+ if ((0, import_utils40.isFunction)(changeOptions[mpath])) {
14062
14678
  await changeOptions[mpath].call(
14063
14679
  this.req,
14064
14680
  context.originalDocumentSnapshot[mpath],
@@ -14082,7 +14698,7 @@ var Core = class {
14082
14698
  async genDocPermissions(modelName, doc, access, context) {
14083
14699
  const docPermissionsFn = getModelOption(modelName, `docPermissions.${access}`, null);
14084
14700
  let docPermissions = {};
14085
- if ((0, import_utils39.isFunction)(docPermissionsFn)) {
14701
+ if ((0, import_utils40.isFunction)(docPermissionsFn)) {
14086
14702
  const permissions = this.getGlobalPermissions();
14087
14703
  try {
14088
14704
  docPermissions = await getRequestWorkState(this.req, this.requestRuntime).hookGate.run(
@@ -14166,7 +14782,7 @@ var Core = class {
14166
14782
  readExists ? requestFields("read") : [],
14167
14783
  updateExists ? requestFields("update") : []
14168
14784
  ]);
14169
- const viewObj = (0, import_utils39.reduce)(
14785
+ const viewObj = (0, import_utils40.reduce)(
14170
14786
  views,
14171
14787
  (ret, view) => {
14172
14788
  ret[view] = true;
@@ -14174,7 +14790,7 @@ var Core = class {
14174
14790
  },
14175
14791
  {}
14176
14792
  );
14177
- const editObj = (0, import_utils39.reduce)(
14793
+ const editObj = (0, import_utils40.reduce)(
14178
14794
  edits,
14179
14795
  (ret, view) => {
14180
14796
  ret[view] = true;
@@ -14205,9 +14821,9 @@ var Core = class {
14205
14821
  });
14206
14822
  }
14207
14823
  runTasks(modelName, docObject, task) {
14208
- const tasks = (0, import_utils39.compact)((0, import_utils39.castArray)(task));
14824
+ const tasks = (0, import_utils40.compact)((0, import_utils40.castArray)(task));
14209
14825
  if (tasks.length === 0) return docObject;
14210
- (0, import_utils39.forEach)(tasks, (task2) => {
14826
+ (0, import_utils40.forEach)(tasks, (task2) => {
14211
14827
  const { type, args, options } = task2;
14212
14828
  switch (type) {
14213
14829
  case "COPY_AND_DEPOPULATE":
@@ -14277,9 +14893,9 @@ var Core = class {
14277
14893
  }
14278
14894
  const [, field, op] = keys2;
14279
14895
  const subOption = getExactModelOption(modelName, `operationAccess.${access}`);
14280
- if ((0, import_utils39.isUndefined)(subOption)) {
14896
+ if ((0, import_utils40.isUndefined)(subOption)) {
14281
14897
  const subFieldOption = getExactModelOption(modelName, `operationAccess.subs.${field}`);
14282
- if ((0, import_utils39.isUndefined)(subFieldOption)) {
14898
+ if ((0, import_utils40.isUndefined)(subFieldOption)) {
14283
14899
  const opOption = getModelOption(modelName, `operationAccess.${op}`);
14284
14900
  return this.canActivate(opOption);
14285
14901
  }
@@ -14345,25 +14961,25 @@ function guard(condition) {
14345
14961
  const permissions = req[PERMISSIONS];
14346
14962
  let cond = condition;
14347
14963
  let phas = (key) => permissions.has(key);
14348
- if ((0, import_utils40.isPlainObject)(condition)) {
14964
+ if ((0, import_utils41.isPlainObject)(condition)) {
14349
14965
  const { modelName, id, condition: _cond } = condition;
14350
14966
  const svc = req.macl.getPublicService(modelName);
14351
14967
  const select = getModelOption(modelName, `alwaysSelectFields.read`, void 0);
14352
- let _id = (0, import_utils40.isString)(id) ? id : null;
14353
- if ((0, import_utils40.isPlainObject)(id)) {
14968
+ let _id = (0, import_utils41.isString)(id) ? id : null;
14969
+ if ((0, import_utils41.isPlainObject)(id)) {
14354
14970
  const { type = "param", key } = id;
14355
14971
  if (type === "param") {
14356
14972
  const paramValue = req.params[key];
14357
- _id = (0, import_utils40.isArray)(paramValue) ? paramValue[0] ?? null : paramValue ?? null;
14973
+ _id = (0, import_utils41.isArray)(paramValue) ? paramValue[0] ?? null : paramValue ?? null;
14358
14974
  } else if (type === "query") {
14359
14975
  const _qval = req.query[key];
14360
- if ((0, import_utils40.isArray)(_qval)) _id = _qval.length > 0 ? _qval[0] : null;
14976
+ if ((0, import_utils41.isArray)(_qval)) _id = _qval.length > 0 ? _qval[0] : null;
14361
14977
  else _id = _qval;
14362
14978
  } else {
14363
14979
  _id = null;
14364
14980
  }
14365
14981
  }
14366
- if (!(0, import_utils40.isString)(_id) || !_id) {
14982
+ if (!(0, import_utils41.isString)(_id) || !_id) {
14367
14983
  return next(new import_express_json_router5.default.clientErrors.BadRequestError());
14368
14984
  }
14369
14985
  const result2 = await svc._read(_id, { select });
@@ -14375,11 +14991,11 @@ function guard(condition) {
14375
14991
  cond = _cond;
14376
14992
  }
14377
14993
  const { stringHandler, arrayHandler } = createValidator(phas);
14378
- if ((0, import_utils40.isString)(cond)) {
14994
+ if ((0, import_utils41.isString)(cond)) {
14379
14995
  if (stringHandler(cond)) return next();
14380
- } else if ((0, import_utils40.isArray)(cond)) {
14996
+ } else if ((0, import_utils41.isArray)(cond)) {
14381
14997
  if (arrayHandler(cond)) return next();
14382
- } else if ((0, import_utils40.isFunction)(cond)) {
14998
+ } else if ((0, import_utils41.isFunction)(cond)) {
14383
14999
  const result2 = await cond.call(req, permissions);
14384
15000
  if (!!result2) return next();
14385
15001
  }
@@ -14392,7 +15008,7 @@ var import_express2 = __toESM(require("express"));
14392
15008
 
14393
15009
  // src/routers/model-router.ts
14394
15010
  var import_express_json_router8 = __toESM(require("@web-ts-toolkit/express-json-router"));
14395
- var import_utils44 = require("@web-ts-toolkit/utils");
15011
+ var import_utils45 = require("@web-ts-toolkit/utils");
14396
15012
  init_logger_helpers();
14397
15013
  init_runtime();
14398
15014
  init_runtime_context();
@@ -14526,7 +15142,7 @@ init_request_complexity();
14526
15142
 
14527
15143
  // src/validation/common.ts
14528
15144
  var import_zod2 = require("zod");
14529
- var import_utils41 = require("@web-ts-toolkit/utils");
15145
+ var import_utils42 = require("@web-ts-toolkit/utils");
14530
15146
 
14531
15147
  // src/validation/public-admission-schema.ts
14532
15148
  init_public_admission();
@@ -14655,7 +15271,7 @@ var correlatedFilterSchema = import_zod2.z.record(import_zod2.z.string(), import
14655
15271
  }
14656
15272
  });
14657
15273
  var correlatedEmptyOptionsSchema = import_zod2.z.unknown().refine(
14658
- (value) => value === void 0 || (0, import_utils41.isPlainObject)(value) && Object.keys(value).length === 0,
15274
+ (value) => value === void 0 || (0, import_utils42.isPlainObject)(value) && Object.keys(value).length === 0,
14659
15275
  "Correlated include options must be absent or empty"
14660
15276
  ).optional();
14661
15277
  var correlatedPathSchema = import_zod2.z.string().min(1).superRefine((path, ctx) => {
@@ -14692,7 +15308,7 @@ var correlatedListArgsSchema = import_zod2.z.object({
14692
15308
  include: import_zod2.z.lazy(() => correlatedNestedIncludeSchema).optional()
14693
15309
  }).strict().superRefine((args, ctx) => checkArgsMarkers(args.select, args.sort, ctx));
14694
15310
  var correlatedCountArgsSchema = import_zod2.z.unknown().refine(
14695
- (value) => value === void 0 || (0, import_utils41.isPlainObject)(value) && Object.keys(value).length === 0,
15311
+ (value) => value === void 0 || (0, import_utils42.isPlainObject)(value) && Object.keys(value).length === 0,
14696
15312
  "Count includes accept no args"
14697
15313
  ).optional();
14698
15314
  var correlatedReadByIdSchema = import_zod2.z.object({
@@ -14745,7 +15361,7 @@ var correlatedNestedIncludeSchema = import_zod2.z.union([includeItemSchema, impo
14745
15361
  var rejectDuplicateCorrelatedPaths = (items, ctx) => {
14746
15362
  const seen = /* @__PURE__ */ new Set();
14747
15363
  items.forEach((item, index) => {
14748
- if ((0, import_utils41.isPlainObject)(item) && item.mode === "correlated" && typeof item.path === "string") {
15364
+ if ((0, import_utils42.isPlainObject)(item) && item.mode === "correlated" && typeof item.path === "string") {
14749
15365
  if (seen.has(item.path)) {
14750
15366
  ctx.addIssue({
14751
15367
  code: import_zod2.z.ZodIssueCode.custom,
@@ -15718,7 +16334,7 @@ var rootQuerySchema = publicBoundarySchema(
15718
16334
  init_helpers();
15719
16335
 
15720
16336
  // src/routers/shared.ts
15721
- var import_utils42 = require("@web-ts-toolkit/utils");
16337
+ var import_utils43 = require("@web-ts-toolkit/utils");
15722
16338
 
15723
16339
  // src/routers/model-router-collection-routes.ts
15724
16340
  init_schemas();
@@ -15749,15 +16365,15 @@ function setModelCollectionRoutes(context) {
15749
16365
  sort
15750
16366
  } = parseQuery(requestSchemas.listQuery, req.query);
15751
16367
  const svc = context.getPublicService(req);
15752
- const includeCount = (0, import_utils42.parseBooleanString)(include_count);
15753
- const includeExtraHeaders = (0, import_utils42.parseBooleanString)(include_extra_headers);
16368
+ const includeCount = (0, import_utils43.parseBooleanString)(include_count);
16369
+ const includeExtraHeaders = (0, import_utils43.parseBooleanString)(include_extra_headers);
15754
16370
  const result2 = await svc._list(
15755
16371
  {},
15756
16372
  { select: parseSelectParam(select), sort, skip, limit, page, pageSize: page_size },
15757
16373
  {
15758
- skim: (0, import_utils42.parseBooleanString)(skim),
15759
- includePermissions: (0, import_utils42.parseBooleanString)(include_permissions),
15760
- includeFieldPermissions: (0, import_utils42.parseBooleanString)(include_field_permissions),
16374
+ skim: (0, import_utils43.parseBooleanString)(skim),
16375
+ includePermissions: (0, import_utils43.parseBooleanString)(include_permissions),
16376
+ includeFieldPermissions: (0, import_utils43.parseBooleanString)(include_field_permissions),
15761
16377
  includeCount
15762
16378
  }
15763
16379
  );
@@ -15817,8 +16433,8 @@ function setModelCollectionRoutes(context) {
15817
16433
  data,
15818
16434
  {},
15819
16435
  {
15820
- includePermissions: (0, import_utils42.parseBooleanString)(include_permissions),
15821
- includeFieldPermissions: (0, import_utils42.parseBooleanString)(include_field_permissions)
16436
+ includePermissions: (0, import_utils43.parseBooleanString)(include_permissions),
16437
+ includeFieldPermissions: (0, import_utils43.parseBooleanString)(include_field_permissions)
15822
16438
  }
15823
16439
  );
15824
16440
  handleResultError(result2);
@@ -15856,8 +16472,8 @@ function setModelCollectionRoutes(context) {
15856
16472
  finalData,
15857
16473
  { select: finalSelect, populate: finalPopulate, tasks: finalTasks },
15858
16474
  {
15859
- includePermissions: includePermissions ?? (0, import_utils42.parseBooleanString)(include_permissions),
15860
- includeFieldPermissions: includeFieldPermissions ?? (0, import_utils42.parseBooleanString)(include_field_permissions),
16475
+ includePermissions: includePermissions ?? (0, import_utils43.parseBooleanString)(include_permissions),
16476
+ includeFieldPermissions: includeFieldPermissions ?? (0, import_utils43.parseBooleanString)(include_field_permissions),
15861
16477
  populateAccess
15862
16478
  }
15863
16479
  );
@@ -15954,9 +16570,9 @@ function setModelDocumentRoutes(context) {
15954
16570
  id,
15955
16571
  { select: parseSelectParam(select) },
15956
16572
  {
15957
- includePermissions: (0, import_utils42.parseBooleanString)(include_permissions),
15958
- includeFieldPermissions: (0, import_utils42.parseBooleanString)(include_field_permissions),
15959
- tryList: (0, import_utils42.parseBooleanString)(try_list)
16573
+ includePermissions: (0, import_utils43.parseBooleanString)(include_permissions),
16574
+ includeFieldPermissions: (0, import_utils43.parseBooleanString)(include_field_permissions),
16575
+ tryList: (0, import_utils43.parseBooleanString)(try_list)
15960
16576
  }
15961
16577
  );
15962
16578
  handleResultError(result2);
@@ -16056,9 +16672,9 @@ function setModelDocumentRoutes(context) {
16056
16672
  data,
16057
16673
  { select: parseSelectParam(select) },
16058
16674
  {
16059
- returningAll: (0, import_utils42.parseBooleanString)(returning_all),
16060
- includePermissions: (0, import_utils42.parseBooleanString)(include_permissions),
16061
- includeFieldPermissions: (0, import_utils42.parseBooleanString)(include_field_permissions)
16675
+ returningAll: (0, import_utils43.parseBooleanString)(returning_all),
16676
+ includePermissions: (0, import_utils43.parseBooleanString)(include_permissions),
16677
+ includeFieldPermissions: (0, import_utils43.parseBooleanString)(include_field_permissions)
16062
16678
  }
16063
16679
  );
16064
16680
  handleResultError(result2);
@@ -16107,9 +16723,9 @@ function setModelDocumentRoutes(context) {
16107
16723
  finalData,
16108
16724
  { select: finalSelect, populate: finalPopulate, tasks: finalTasks },
16109
16725
  {
16110
- returningAll: returningAll ?? (0, import_utils42.parseBooleanString)(returning_all),
16111
- includePermissions: includePermissions ?? (0, import_utils42.parseBooleanString)(include_permissions),
16112
- includeFieldPermissions: includeFieldPermissions ?? (0, import_utils42.parseBooleanString)(include_field_permissions),
16726
+ returningAll: returningAll ?? (0, import_utils43.parseBooleanString)(returning_all),
16727
+ includePermissions: includePermissions ?? (0, import_utils43.parseBooleanString)(include_permissions),
16728
+ includeFieldPermissions: includeFieldPermissions ?? (0, import_utils43.parseBooleanString)(include_field_permissions),
16113
16729
  populateAccess
16114
16730
  }
16115
16731
  );
@@ -16140,9 +16756,9 @@ function setModelDocumentRoutes(context) {
16140
16756
  body,
16141
16757
  {},
16142
16758
  {
16143
- returningAll: (0, import_utils42.parseBooleanString)(returning_all),
16144
- includePermissions: (0, import_utils42.parseBooleanString)(include_permissions),
16145
- includeFieldPermissions: (0, import_utils42.parseBooleanString)(include_field_permissions)
16759
+ returningAll: (0, import_utils43.parseBooleanString)(returning_all),
16760
+ includePermissions: (0, import_utils43.parseBooleanString)(include_permissions),
16761
+ includeFieldPermissions: (0, import_utils43.parseBooleanString)(include_field_permissions)
16146
16762
  }
16147
16763
  );
16148
16764
  handleResultError(result2);
@@ -16189,9 +16805,9 @@ function setModelDocumentRoutes(context) {
16189
16805
  finalData,
16190
16806
  { select: finalSelect, populate: finalPopulate, tasks: finalTasks },
16191
16807
  {
16192
- returningAll: returningAll ?? (0, import_utils42.parseBooleanString)(returning_all),
16193
- includePermissions: includePermissions ?? (0, import_utils42.parseBooleanString)(include_permissions),
16194
- includeFieldPermissions: includeFieldPermissions ?? (0, import_utils42.parseBooleanString)(include_field_permissions),
16808
+ returningAll: returningAll ?? (0, import_utils43.parseBooleanString)(returning_all),
16809
+ includePermissions: includePermissions ?? (0, import_utils43.parseBooleanString)(include_permissions),
16810
+ includeFieldPermissions: includeFieldPermissions ?? (0, import_utils43.parseBooleanString)(include_field_permissions),
16195
16811
  populateAccess
16196
16812
  }
16197
16813
  );
@@ -16431,11 +17047,11 @@ function setModelSubDocumentRoutes(context) {
16431
17047
  }
16432
17048
 
16433
17049
  // src/openapi/route-registration.ts
16434
- var import_utils43 = require("@web-ts-toolkit/utils");
17050
+ var import_utils44 = require("@web-ts-toolkit/utils");
16435
17051
  function registerOpenApiRoute(runtime, basePath, defaultTag, route) {
16436
17052
  runtime.registerOpenApiRoute({
16437
17053
  ...route,
16438
- path: (0, import_utils43.normalizeUrlPath)(basePath + route.path),
17054
+ path: (0, import_utils44.normalizeUrlPath)(basePath + route.path),
16439
17055
  tags: route.tags ?? [defaultTag]
16440
17056
  });
16441
17057
  }
@@ -16443,8 +17059,8 @@ function registerOpenApiRoute(runtime, basePath, defaultTag, route) {
16443
17059
  // src/routers/model-router.ts
16444
17060
  var clientErrors2 = import_express_json_router8.default.clientErrors;
16445
17061
  function setOption(parentKey, optionKey, option) {
16446
- const key = (0, import_utils44.isUndefined)(option) ? parentKey : `${parentKey}.${optionKey}`;
16447
- const value = (0, import_utils44.isUndefined)(option) ? optionKey : option;
17062
+ const key = (0, import_utils45.isUndefined)(option) ? parentKey : `${parentKey}.${optionKey}`;
17063
+ const value = (0, import_utils45.isUndefined)(option) ? optionKey : option;
16448
17064
  assertMutableRouterOption("model", key);
16449
17065
  this.runtime.setModelOption(
16450
17066
  this.modelName,
@@ -16646,7 +17262,7 @@ var ModelRouter = class _ModelRouter {
16646
17262
  this.runtime = runtime;
16647
17263
  this.runtime.setModelOptions(modelName, initialOptions);
16648
17264
  this.options = this.runtime.getModelOptions(modelName);
16649
- this.fullBasePath = (0, import_utils44.normalizeUrlPath)(this.options.parentPath + this.options.basePath);
17265
+ this.fullBasePath = (0, import_utils45.normalizeUrlPath)(this.options.parentPath + this.options.basePath);
16650
17266
  this.modelName = modelName;
16651
17267
  this.router = new import_express_json_router8.default(this.options.basePath, createSetCore(this.runtime), accessRouterResponseHandler);
16652
17268
  this.model = new model_default(modelName, this.runtime);
@@ -16732,13 +17348,13 @@ var ModelRouter = class _ModelRouter {
16732
17348
  }
16733
17349
  logEndpoints() {
16734
17350
  runWithRuntime(this.runtime, () => {
16735
- (0, import_utils44.forEach)(this.router.getEndpoints(), ({ method, path }) => {
16736
- logInfoMessage(`${(0, import_utils44.padEnd)(method, 6)} ${(0, import_utils44.normalizeUrlPath)(this.options.parentPath + path)}`);
17351
+ (0, import_utils45.forEach)(this.router.getEndpoints(), ({ method, path }) => {
17352
+ logInfoMessage(`${(0, import_utils45.padEnd)(method, 6)} ${(0, import_utils45.normalizeUrlPath)(this.options.parentPath + path)}`);
16737
17353
  });
16738
17354
  });
16739
17355
  }
16740
17356
  set(keyOrOptions, value) {
16741
- if (arguments.length === 2 && (0, import_utils44.isString)(keyOrOptions)) {
17357
+ if (arguments.length === 2 && (0, import_utils45.isString)(keyOrOptions)) {
16742
17358
  assertMutableRouterOption("model", keyOrOptions);
16743
17359
  this.runtime.setModelOption(
16744
17360
  this.modelName,
@@ -16746,7 +17362,7 @@ var ModelRouter = class _ModelRouter {
16746
17362
  value
16747
17363
  );
16748
17364
  }
16749
- if (arguments.length === 1 && (0, import_utils44.isPlainObject)(keyOrOptions)) {
17365
+ if (arguments.length === 1 && (0, import_utils45.isPlainObject)(keyOrOptions)) {
16750
17366
  assertMutableRouterOptions("model", keyOrOptions);
16751
17367
  this.runtime.setModelOptions(
16752
17368
  this.modelName,
@@ -16774,7 +17390,7 @@ var ModelRouter = class _ModelRouter {
16774
17390
 
16775
17391
  // src/routers/root-router.ts
16776
17392
  var import_express_json_router9 = __toESM(require("@web-ts-toolkit/express-json-router"));
16777
- var import_utils45 = require("@web-ts-toolkit/utils");
17393
+ var import_utils46 = require("@web-ts-toolkit/utils");
16778
17394
 
16779
17395
  // src/core-data.ts
16780
17396
  init_options();
@@ -17082,7 +17698,7 @@ var RootRouter = class {
17082
17698
  this.setRoutes();
17083
17699
  }
17084
17700
  registerOpenApiRoute(route) {
17085
- registerOpenApiRoute(this.runtime, (0, import_utils45.normalizeUrlPath)(this.basename), "root", route);
17701
+ registerOpenApiRoute(this.runtime, (0, import_utils46.normalizeUrlPath)(this.basename), "root", route);
17086
17702
  }
17087
17703
  wrapResult(index, item, result2) {
17088
17704
  return {
@@ -17191,7 +17807,7 @@ var RootRouter = class {
17191
17807
  groupItemsByOrder(items) {
17192
17808
  const groups = /* @__PURE__ */ new Map();
17193
17809
  items.forEach((item, index) => {
17194
- const order = (0, import_utils45.isNumber)(item.order) ? item.order : 0;
17810
+ const order = (0, import_utils46.isNumber)(item.order) ? item.order : 0;
17195
17811
  const group = groups.get(order);
17196
17812
  if (group) {
17197
17813
  group.push({ index, item });
@@ -17262,7 +17878,7 @@ var RootRouter = class {
17262
17878
  const arrResult = await this.runGroup(req, groupedItems[x]);
17263
17879
  results.push(...arrResult);
17264
17880
  }
17265
- return (0, import_utils45.orderBy)(results, ["index"], ["asc"]);
17881
+ return (0, import_utils46.orderBy)(results, ["index"], ["asc"]);
17266
17882
  });
17267
17883
  this.registerOpenApiRoute({
17268
17884
  method: "post",
@@ -17280,14 +17896,14 @@ var RootRouter = class {
17280
17896
 
17281
17897
  // src/routers/data-router.ts
17282
17898
  var import_express_json_router10 = __toESM(require("@web-ts-toolkit/express-json-router"));
17283
- var import_utils46 = require("@web-ts-toolkit/utils");
17899
+ var import_utils47 = require("@web-ts-toolkit/utils");
17284
17900
  init_runtime();
17285
17901
  init_helpers();
17286
17902
  init_schemas();
17287
17903
  var clientErrors4 = import_express_json_router10.default.clientErrors;
17288
17904
  function setOption2(parentKey, optionKey, option) {
17289
- const key = (0, import_utils46.isUndefined)(option) ? parentKey : `${parentKey}.${optionKey}`;
17290
- const value = (0, import_utils46.isUndefined)(option) ? optionKey : option;
17905
+ const key = (0, import_utils47.isUndefined)(option) ? parentKey : `${parentKey}.${optionKey}`;
17906
+ const value = (0, import_utils47.isUndefined)(option) ? optionKey : option;
17291
17907
  assertMutableRouterOption("data", key);
17292
17908
  this.runtime.setDataOption(this.dataName, key, value);
17293
17909
  return this;
@@ -17336,7 +17952,7 @@ var DataRouter = class {
17336
17952
  this.runtime = runtime;
17337
17953
  this.runtime.setDataOptions(dataName, initialOptions);
17338
17954
  this.options = this.runtime.getDataOptions(dataName);
17339
- this.fullBasePath = (0, import_utils46.normalizeUrlPath)(this.options.parentPath + this.options.basePath);
17955
+ this.fullBasePath = (0, import_utils47.normalizeUrlPath)(this.options.parentPath + this.options.basePath);
17340
17956
  this.dataName = dataName;
17341
17957
  this.router = new import_express_json_router10.default(this.options.basePath, createSetDataCore(this.runtime), accessRouterResponseHandler);
17342
17958
  this.setCollectionRoutes();
@@ -17369,8 +17985,8 @@ var DataRouter = class {
17369
17985
  req.query
17370
17986
  );
17371
17987
  const svc = this.getService(req);
17372
- const includeCount = (0, import_utils42.parseBooleanString)(include_count);
17373
- const includeExtraHeaders = (0, import_utils42.parseBooleanString)(include_extra_headers);
17988
+ const includeCount = (0, import_utils43.parseBooleanString)(include_count);
17989
+ const includeExtraHeaders = (0, import_utils43.parseBooleanString)(include_extra_headers);
17374
17990
  const result2 = await svc.find(
17375
17991
  {},
17376
17992
  { select: parseSelectParam(select), sort, skip, limit, page, pageSize: page_size },
@@ -17488,7 +18104,7 @@ var DataRouter = class {
17488
18104
  });
17489
18105
  }
17490
18106
  set(keyOrOptions, value) {
17491
- if (arguments.length === 2 && (0, import_utils46.isString)(keyOrOptions)) {
18107
+ if (arguments.length === 2 && (0, import_utils47.isString)(keyOrOptions)) {
17492
18108
  assertMutableRouterOption("data", keyOrOptions);
17493
18109
  this.runtime.setDataOption(
17494
18110
  this.dataName,
@@ -17496,7 +18112,7 @@ var DataRouter = class {
17496
18112
  value
17497
18113
  );
17498
18114
  }
17499
- if (arguments.length === 1 && (0, import_utils46.isPlainObject)(keyOrOptions)) {
18115
+ if (arguments.length === 1 && (0, import_utils47.isPlainObject)(keyOrOptions)) {
17500
18116
  assertMutableRouterOptions("data", keyOrOptions);
17501
18117
  this.runtime.setDataOptions(this.dataName, keyOrOptions);
17502
18118
  }
@@ -17631,7 +18247,7 @@ function createRuntimeApi(runtime) {
17631
18247
  const wtt2 = runtimeMiddleware;
17632
18248
  wtt2.runtime = runtime;
17633
18249
  wtt2.createRouter = function(modelName, options) {
17634
- if ((0, import_utils47.isUndefined)(options)) {
18250
+ if ((0, import_utils48.isUndefined)(options)) {
17635
18251
  return new RootRouter(modelName, runtime);
17636
18252
  }
17637
18253
  if (typeof modelName === "string") {
@@ -17652,10 +18268,10 @@ function createRuntimeApi(runtime) {
17652
18268
  };
17653
18269
  wtt2.combineRoutes = combineRoutes;
17654
18270
  wtt2.set = function(keyOrOptions, value) {
17655
- if (arguments.length === 2 && (0, import_utils47.isString)(keyOrOptions)) {
18271
+ if (arguments.length === 2 && (0, import_utils48.isString)(keyOrOptions)) {
17656
18272
  return runtime.setGlobalOption(keyOrOptions, value);
17657
18273
  }
17658
- if (arguments.length === 1 && (0, import_utils47.isPlainObject)(keyOrOptions)) {
18274
+ if (arguments.length === 1 && (0, import_utils48.isPlainObject)(keyOrOptions)) {
17659
18275
  return runtime.setGlobalOptions(keyOrOptions);
17660
18276
  }
17661
18277
  };