import {
  AUTH_USER_CONTEXT
} from "./chunk-6XY6ZMMD.js";
import {
  withRequester
} from "./chunk-ZUKFQL6E.js";

// runtime/subsystems/auth/middleware/requester-context.ts
async function resolveRequesterContext(userContext, req) {
  if (typeof userContext.resolveRequester === "function") {
    const ctx = await userContext.resolveRequester(req);
    return ctx?.userId ? ctx : void 0;
  }
  const userId = await userContext.getCurrentUserId(req);
  return userId ? { userId, organizationId: null } : void 0;
}
function makeRequesterContextMiddleware(userContext, options = {}) {
  const onUnresolved = options.onUnresolved ?? "unscoped";
  return (req, _res, next) => {
    resolveRequesterContext(userContext, req).then(
      (ctx) => {
        if (!ctx) {
          next();
          return;
        }
        withRequester(ctx, async () => {
          next();
        });
      },
      (err) => {
        if (onUnresolved === "reject") {
          next(err);
          return;
        }
        next();
      }
    );
  };
}
function installRequesterContext(app, options = {}) {
  const userContext = app.get(AUTH_USER_CONTEXT, {
    strict: false
  });
  if (!userContext) {
    console.warn(
      "[auth] installRequesterContext: AUTH_USER_CONTEXT is not bound \u2014 request scoping NOT installed. Provide an IUserContext under AUTH_USER_CONTEXT in your AppModule to enable ambient tenant scoping."
    );
    return;
  }
  app.use(makeRequesterContextMiddleware(userContext, options));
}

export {
  resolveRequesterContext,
  makeRequesterContextMiddleware,
  installRequesterContext
};
//# sourceMappingURL=chunk-OSQRXVG2.js.map