@simpleapps-com/augur-server 2026.11.3 → 2026.11.5

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.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/query-action.ts"],"sourcesContent":["// \"use server\" banner is injected by tsup at build time.\n// Isolated server action for the proxy pattern.\n// This file MUST NOT import from server-actions.ts, server-site-registry.ts,\n// cache/, or any factory. It imports only from lightweight stores with zero\n// deps, the proved pure `rules` (with @atlas/utils' string scans, bundled), plus augur-core\n// and augur-api's `isSiteId` (both external in tsup — not bundled into chunks; every site\n// already loads the SDK on the server).\n// Dynamic imports of next/headers and next-auth/jwt are used for session\n// credential resolution (both are external in tsup).\n\nimport {\n getSdkClientOrNull,\n getSdkCallWrapper,\n getAuthSecret,\n getCrossSite,\n getOrCreateScopedClient,\n getScopedCacheWrapper,\n parseMethodPath,\n type SessionCredentials,\n type ApprovedMethodPath,\n type SdkCallWrapper,\n type ScopedCacheWrapper,\n} from \"./sdk-client-store\";\nimport {\n isReadMethod,\n stripEdgeCacheForNoCachePaths,\n unwrapBaseResponse,\n} from \"@simpleapps-com/augur-core\";\nimport { isSiteId, type BaseResponse, type CallOptions } from \"@simpleapps-com/augur-api\";\nimport {\n clientFor,\n clientIdSiteIdOf,\n mintedCredentials,\n readsSession,\n resolutionOf,\n scopedPrefix,\n sessionCookieName,\n usesCache,\n} from \"./rules\";\n\n/** Auth.js v5's HTTPS session cookie; sessionCookieName (rules.ts) picks it or the plain one. */\nconst SECURE_COOKIE = \"__Secure-authjs.session-token\";\n\n/** Simplified function types for lazy-loaded external deps. */\ntype DecodeFn = (params: {\n token?: string;\n secret: string | string[];\n salt: string;\n}) => Promise<Record<string, unknown> | null>;\ntype CookiesFn = () => Promise<{ get: (name: string) => { value: string } | undefined }>;\ntype DecodeJwtFn = (token: string) => Record<string, unknown>;\n\n/** Cached dynamic imports for next-auth/jwt decode, next/headers cookies, and jose decodeJwt. */\nlet _decode: DecodeFn | null | undefined;\nlet _cookies: CookiesFn | null | undefined;\nlet _decodeJwt: DecodeJwtFn | null | undefined;\n\n/** Lazy-load decode, cookies, and decodeJwt functions from external deps. Cached after first call. */\nasync function ensureImports(): Promise<boolean> {\n if (_decode === undefined) {\n try {\n const mod = await import(\"next-auth/jwt\");\n _decode = mod.decode as unknown as DecodeFn;\n } catch {\n // next-auth is an optional peer: without it there are no session credentials\n _decode = null;\n }\n }\n if (_cookies === undefined) {\n try {\n const mod = await import(\"next/headers\");\n _cookies = mod.cookies as unknown as CookiesFn;\n } catch {\n // outside Next.js there is no request cookie store\n _cookies = null;\n }\n }\n if (_decodeJwt === undefined) {\n try {\n const mod = await import(\"jose\");\n _decodeJwt = mod.decodeJwt as unknown as DecodeJwtFn;\n } catch {\n // jose is an optional peer: without it the bearer cannot be cross-checked\n _decodeJwt = null;\n }\n }\n return !!_decode && !!_cookies && !!_decodeJwt;\n}\n\n/** Read and decode the Auth.js session JWT from request cookies. */\nasync function decodeSessionJwt(secret: string): Promise<Record<string, unknown> | null> {\n const cookieStore = await _cookies!();\n const secureCookie = cookieStore.get(SECURE_COOKIE);\n // The proved rule (rules.ts, AugurServer.SessionCookieName): the HTTPS cookie when present,\n // else the plain one; its name is the salt\n const name = sessionCookieName(Boolean(secureCookie));\n const cookie = secureCookie ?? cookieStore.get(name);\n if (!cookie?.value) return null;\n\n return _decode!({ token: cookie.value, secret, salt: name });\n}\n\n/**\n * Extract the siteId portion of an Augur bearer token's `client_id` claim.\n * Bearer tokens are JWTs whose payload contains `client_id: \"<numeric>|<siteId>\"`.\n * Returns null on any parse failure or unexpected shape.\n *\n * Uses jose.decodeJwt (no signature verification) — we trust the bearer\n * because the *outer* Auth.js cookie's signature was just verified upstream,\n * so the bearer's contents are trusted as session-issued. This check guards\n * against internal inconsistency between the session's `targetSiteId` and the\n * bearer's scope, not against a forged bearer (the auth provider's signature\n * does that).\n */\nfunction parseBearerClientSiteId(bearer: string): string | null {\n try {\n const payload = _decodeJwt!(bearer);\n const clientId = payload[\"client_id\"];\n if (typeof clientId !== \"string\") return null;\n return clientIdSiteIdOf(clientId);\n } catch {\n return null;\n }\n}\n\n/**\n * Resolve session credentials from the Auth.js JWT cookie.\n *\n * Trust-boundary mint point: this is the only function in the package that\n * produces {@link SessionCredentials} values. Bytes from a cookie become\n * typed, paired credentials here and only here. No other production code\n * constructs the branded pair, so a `SessionCredentials` that came through\n * this mint is JWT-validated and internally consistent. The brand is not\n * enforced by the compiler: an `as SessionCredentials` cast compiles (tests\n * do it), so audit casts (see \"Brand strength\" below).\n *\n * Returns null when:\n * - the site did not opt in to cross-site sessions (`createServerSite`'s\n * `auth: { crossSite: true }`, atlas#105): then nothing is imported and no\n * cookie is read, so pages using queryAction can render statically\n * - no AUTH_SECRET is configured\n * - next-auth/jwt, next/headers, or jose cannot be loaded\n * - no session cookie is present\n * - the JWT decode fails or returns null\n * - the decoded payload is missing `targetSiteId` or `token`, or either is\n * not a non-empty string (refuse to mint partial credentials)\n * - `targetSiteId` fails augur-api's `isSiteId` (`[a-z0-9_-]+`): siteIds are\n * lowercase by convention, and the scoped-client key's injectivity proof\n * (`scoped-client-key.ts`) needs a NUL-free siteId\n * - the bearer token's `client_id` siteId portion does not match\n * `targetSiteId` (defense-in-depth: refuses internally inconsistent sessions\n * before they reach the augur-api authority check)\n *\n * ## Verified preconditions for `result = some c`\n *\n * AUTH_SECRET configured\n * next-auth/jwt, next/headers, jose all loadable\n * session cookie present and decodable with the secret\n * typeof jwt.targetSiteId === \"string\" ∧ isSiteId(jwt.targetSiteId) // implies non-empty\n * typeof jwt.token === \"string\" ∧ jwt.token.length > 0\n * bearerClientSiteId(jwt.token) = some jwt.targetSiteId\n *\n * Lean equivalent: each clause becomes a `requires` on the function;\n * `result = none` is the disjunction of any failing.\n * F* equivalent: refinement on the option payload covering the\n * conjunction of these clauses.\n *\n * The bearer cross-check (`bearerClientSiteId(jwt.token) = some jwt.targetSiteId`)\n * is the substantive runtime invariant: it refuses sessions where the bearer's\n * encoded `client_id` siteId disagrees with the session's targetSiteId,\n * catching internal-inconsistency bugs before the call reaches augur-api.\n *\n * ## By construction (not independently verified)\n *\n * c.siteId === jwt.targetSiteId (assigned, not checked)\n * c.token === jwt.token (assigned, not checked)\n *\n * ## Brand strength\n *\n * `SessionCredentials` is a TS-level brand: there is no runtime tag on the\n * value. `value as SessionCredentials` casts compile, so the brand is a\n * code-review signal (audit `as SessionCredentials` usages — there should be\n * exactly one, in this function), not a hard type-system gate.\n */\nasync function getSessionCredentials(): Promise<SessionCredentials | null> {\n const secret = getAuthSecret();\n // Only an opted-in site with a secret looks for a session (rules.readsSession, atlas#105):\n // every other site returns here, before next/headers is imported or cookies() read, so its\n // pages can render statically.\n if (!readsSession(getCrossSite(), Boolean(secret))) return null;\n if (!(await ensureImports())) return null;\n\n try {\n // readsSession held, so the secret is present (Boolean(secret) above).\n const decoded = await decodeSessionJwt(secret as string);\n if (!decoded) return null;\n\n const targetSiteId = decoded[\"targetSiteId\"];\n const token = decoded[\"token\"];\n\n if (typeof targetSiteId !== \"string\" || typeof token !== \"string\") return null;\n\n // An empty or undecodable token has no client_id siteId (\"\").\n const bearerSiteId = parseBearerClientSiteId(token) ?? \"\";\n const mint = mintedCredentials(isSiteId(targetSiteId), targetSiteId, token, bearerSiteId);\n if (mint.kind === \"refused\") return null;\n\n return { siteId: mint.siteId, token: mint.token } as unknown as SessionCredentials;\n } catch {\n // Not in a request context (build time, tests), or decode failed\n }\n\n return null;\n}\n\n/**\n * Discriminated result of client resolution.\n *\n * Encodes two structural invariants at the type level:\n *\n * 1. session credentials exist iff this is the scoped path\n * (only `kind: \"scoped\"` carries `credentials`)\n * 2. a usable client exists iff this is NOT the uninit path\n * (`kind: \"scoped\" | \"global\"` always carry `client: object`)\n *\n * The `client: object` constraint replaces the previous `client: unknown` +\n * runtime null check. Anything narrowed to `kind: \"scoped\"` or `kind: \"global\"`\n * is guaranteed by the type system to have a non-null, traversable client —\n * downstream code that walks the SDK namespace path cannot accidentally\n * dereference null. The runtime check moves into `resolveClient` itself, where\n * `kind: \"uninit\"` is constructed when neither a scoped nor a global client is\n * available.\n *\n * Downstream code that wants to derive a cache prefix can only do so on the\n * scoped variant, and only from the credentials carried by that variant —\n * there is no way to construct a cache prefix from a different source without\n * crossing into the type.\n */\ntype ClientResolution =\n | { kind: \"scoped\"; client: object; credentials: SessionCredentials }\n | { kind: \"global\"; client: object }\n | { kind: \"uninit\" };\n\n/**\n * Resolve the SDK client for this request.\n *\n * - If the session JWT validates and a scoped client can be minted, returns\n * the scoped variant carrying the {@link SessionCredentials} that produced\n * the client. The cache prefix is derived at the use site from\n * `credentials.siteId`, structurally guaranteeing it matches the credentials\n * under which the SDK call is made.\n * - Otherwise returns the global variant. No credentials, no cache prefix.\n *\n * The previous return shape `{ client, cachePrefix: string | null }` made\n * \"cachePrefix exists iff scoped\" a runtime invariant; the tagged union\n * promotes it to a type-level one.\n */\nasync function resolveClient(): Promise<ClientResolution> {\n const creds = await getSessionCredentials();\n const scoped = creds ? getOrCreateScopedClient(creds) : null;\n const globalClient = getSdkClientOrNull();\n const kind = resolutionOf(creds !== null, isObject(scoped), isObject(globalClient));\n if (kind === \"scoped\") return { kind, client: scoped as object, credentials: creds! };\n if (kind === \"global\") return { kind, client: globalClient as object };\n return { kind };\n}\n\n/** A usable client: a non-null object. */\nfunction isObject(value: unknown): boolean {\n return value !== null && typeof value === \"object\";\n}\n\n/** A client offering call options (`AugurAPI.withRequest`, atlas#106). */\ntype BoundableClient = { withRequest: (options: CallOptions) => object };\n\nfunction canBeBounded(client: object): client is BoundableClient {\n return typeof (client as Partial<BoundableClient>).withRequest === \"function\";\n}\n\n/**\n * The client a call runs on (rules.ts `clientFor`, AugurServer.ClientFor): the resolved client\n * with no options; its `withRequest` view with options; and a refusal when it has no\n * `withRequest`, since a call the caller asked to bound must never run unbounded.\n */\nfunction boundClient(client: object, options: CallOptions | undefined): object {\n const choice = clientFor(options !== undefined, canBeBounded(client));\n if (choice === \"client\") return client;\n if (choice === \"refuse\") {\n throw new Error(\n \"queryActionWith: the SDK client has no withRequest; call options need a \" +\n \"@simpleapps-com/augur-api release that has AugurAPI.withRequest.\",\n );\n }\n return (client as BoundableClient).withRequest(options!);\n}\n\n/**\n * Resolve a dot-separated method path on an object, returning the leaf function.\n *\n * Demands {@link ApprovedMethodPath} so callers must have run the path through\n * `parseMethodPath` first — passing an unvalidated string is a compile error.\n */\nfunction resolveMethod(\n client: unknown,\n methodPath: ApprovedMethodPath,\n): (...a: unknown[]) => Promise<unknown> {\n const segments = methodPath.split(\".\");\n\n let current: unknown = client;\n for (const segment of segments) {\n if (current == null || (typeof current !== \"object\" && typeof current !== \"function\")) {\n throw new Error(\n `Cannot resolve \"${methodPath}\": \"${segment}\" is not accessible on ${typeof current}`,\n );\n }\n current = (current as Record<string, unknown>)[segment];\n }\n\n if (typeof current !== \"function\") {\n throw new Error(`\"${methodPath}\" does not resolve to a function (got ${typeof current})`);\n }\n\n return current as (...a: unknown[]) => Promise<unknown>;\n}\n\n/**\n * Bind a scoped cache wrapper to a fixed prefix, producing an `SdkCallWrapper`\n * with the same signature as the global wrapper.\n *\n * On the scoped queryAction path, the cache prefix is derived structurally\n * from the `SessionCredentials` that minted the client (`${credentials.siteId}:`).\n * Capturing that prefix in a closure here lets queryAction's call site treat\n * scoped and global wrappers uniformly — the only thing that differs between\n * them is which prefix gets baked in, and that decision happens in exactly one\n * place per request.\n *\n * Returns null when no scoped wrapper is registered, so the caller falls\n * through to the unwrapped SDK call. The closure preserves the cross-tenant\n * invariant: prefix is captured at bind time from the same credentials value\n * used to mint the scoped client, and cannot be replaced or re-sourced later.\n *\n * ## Property\n *\n * bindScopedPrefix(null, _) = null\n * bindScopedPrefix(w, p)(methodPath, fn, ...args) = w(p, methodPath, fn, ...args)\n *\n * The bound wrapper forwards faithfully — it adds nothing, drops nothing,\n * and reorders nothing. Every effect (cache read, cache write, SDK call)\n * happens inside the underlying scopedWrapper exactly as if queryAction had\n * called it directly with the prefix as the first argument.\n */\nfunction bindScopedPrefix(\n scopedWrapper: ScopedCacheWrapper | null,\n prefix: string,\n): SdkCallWrapper | null {\n if (!scopedWrapper) return null;\n return (methodPath, sdkCall, ...keyArgs) =>\n scopedWrapper(prefix, methodPath, sdkCall, ...keyArgs);\n}\n\n/**\n * The one SDK call behind the two server actions, `queryAction` (the\n * envelope's data) and `queryActionRaw` (the result as returned): routes\n * any SDK method call through the raw SDK client with optional Redis\n * caching. `queryAction` is used internally by `createServerQueryProxy()`\n * to bridge client-side React Query hooks to server-side API calls.\n *\n * For read methods (get, list, lookup, search, suggest), the call is\n * wrapped in the registered cache wrapper (Redis) if one was registered\n * by createServerSite(). Write methods bypass caching.\n *\n * When the request has an active session with targetSiteId + token\n * (from cross-site auth), the call uses a scoped SDK client with those\n * credentials. Redis caching uses targetSiteId as the cache prefix so\n * users managing the same site share cached data.\n *\n * This is the chokepoint: every B2B site without a client-side SDK\n * routes EVERY data access through this one function. The invariants\n * below are load-bearing across every site, every request, every user.\n *\n * ## Preconditions (enforced at runtime via thrown Error)\n *\n * parseMethodPath(methodPath) ≠ null\n * resolveClient().client ≠ null\n *\n * First clause: methodPath is a non-empty string AND — if an allowlist\n * has been registered via `registerAllowedMethodPaths` — methodPath is\n * in the allowlist. Assumes the site opted into surface restriction\n * when narrower-than-augur-api authority is desired; otherwise any\n * non-empty string passes (transparent forwarder default).\n *\n * Second clause: createServerSite() ran during bootstrap OR\n * AUGUR_SITE_ID + AUGUR_JWT env vars are set so the registry can\n * auto-init. Assumes the caller has bootstrapped one of the two paths.\n *\n * Lean equivalent: `requires path : ApprovedMethodPath ∧ client : SDKClient`.\n *\n * ## Cross-tenant cache-prefix invariant (load-bearing)\n *\n * resolution.kind = \"scoped\" ⟹ cachePrefix = `${resolution.credentials.siteId}:`\n *\n * On the scoped path the cache prefix is derived structurally from the\n * same `SessionCredentials` value that minted the scoped client — they\n * cannot be sourced separately. This makes \"siteId from session A\n * combined with token from session B\" or \"siteId X with cache prefix Y\"\n * unrepresentable here. Assumes `getSessionCredentials` performed the\n * bearer/session siteId cross-check at mint time; see the brand-strength\n * caveat on `SessionCredentials`.\n *\n * A regression here would silently leak cached data across tenants.\n * The structural derivation is the only thing standing between the\n * request and that leak — do not reintroduce a separate `cachePrefix`\n * parameter or compute it from anything other than `resolution.credentials`.\n *\n * ### Sibling assumption — bearer is NOT in the cache key\n *\n * The cross-tenant invariant covers cross-SITE leaks. It does NOT cover\n * intra-site cross-USER leaks: the cache key is `(siteId, methodPath, args)`\n * and the bearer token is intentionally absent. Two users with different\n * bearers on the same site share cached data for cacheable namespaces.\n *\n * This is a deliberate design choice. The assumption is:\n *\n * ∀ namespace ∉ NO_CACHE_PATHS, ∀ siteId, ∀ args.\n * augur-api(bearer_A, siteId, args) = augur-api(bearer_B, siteId, args)\n *\n * i.e. for cacheable namespaces, augur-api's response is bearer-independent\n * within a site. augur-api remains the auth authority; `NO_CACHE_PATHS`\n * (commerce.*, payments.*) is the carve-out for namespaces whose responses\n * ARE bearer-coupled. If a future namespace produces bearer-dependent\n * responses (e.g. user-specific permissions affecting query results), it\n * MUST be added to `NO_CACHE_PATHS` or the bearer MUST become part of the\n * cache key — otherwise this assumption silently produces a permission leak.\n *\n * ## No-edge-cache defense-in-depth (load-bearing)\n *\n * ∀ a ∈ safeArgs. methodPath ∈ NO_CACHE_PATHS ⟹ \"edgeCache\" ∉ keys(a)\n *\n * `stripEdgeCacheForNoCachePaths` removes the `edgeCache` key from every\n * first-level object arg when methodPath belongs to a no-cache namespace\n * (currently `commerce.*`, `payments.*`). The augur-api SDK transforms\n * `edgeCache` into a Cloudflare `cacheSiteId{N}` query param; removing\n * it here guarantees no CDN edge-caching of identity-bound responses\n * even if a caller passed one explicitly or a legacy factory injected\n * one. Assumes `NO_CACHE_PATHS` enumerates every namespace whose\n * responses must not cross identity boundaries.\n *\n * ## Postcondition — the SDK's result as returned\n *\n * result = raw (the SDK's result, from the call or the raw cache)\n *\n * Assumes upstream cache wrappers do NOT themselves unwrap — they\n * return whatever the SDK returned (the raw key space, #98), so\n * `queryAction` unwraps exactly once and `queryActionRaw` never does\n * (model: AugurServer.QueryResult).\n *\n * ## Effects\n *\n * @mutates Redis (write-through on read methods when a wrapper is registered)\n * @io augur-api SDK (network request)\n * @throws Error when the allowlist gate fails or no client is initialised\n */\nasync function callSdk(\n methodPath: string,\n args: unknown[],\n options?: CallOptions,\n): Promise<unknown> {\n const approvedPath = parseMethodPath(methodPath);\n if (approvedPath === null) {\n throw new Error(\n `queryAction: methodPath ${JSON.stringify(methodPath)} is not in the registered allowlist. ` +\n `Register it via registerAllowedMethodPaths() in createServerSite() config.`,\n );\n }\n\n const resolution = await resolveClient();\n if (resolution.kind === \"uninit\") {\n throw new Error(\n \"SDK client not initialized. Call createServerSite() or set AUGUR_SITE_ID + AUGUR_JWT env vars.\",\n );\n }\n\n // The options bound the call through the client's view; they are never SDK arguments and\n // never part of the cache key, which stays `safeArgs` (AugurServer.OptionsNeverInTheKey)\n const resolvedMethod = resolveMethod(boundClient(resolution.client, options), approvedPath);\n const leafName = approvedPath.split(\".\").pop()!;\n // Defense in depth: strip `edgeCache` from no-cache paths before the SDK\n // sees it. The augur-api SDK transforms `edgeCache` into a Cloudflare\n // `cacheSiteId{N}` query param; removing it here guarantees no CDN edge\n // caching of identity-bound responses even if a caller explicitly passed\n // one. Also keeps cache keys consistent with what is actually sent.\n const safeArgs = stripEdgeCacheForNoCachePaths(approvedPath, args);\n\n // Pick the wrapper for this resolution's prefix policy. On the scoped path,\n // the prefix is structurally derived from `credentials.siteId` and bound into\n // a closure here — bindScopedPrefix is the only call site that builds it,\n // and the prefix cannot be re-sourced after binding. On the global path, the\n // prefix is closed over by the SdkCallWrapper that createServerSite registered.\n // Both paths now produce a uniform `SdkCallWrapper | null`, so the caching\n // and uncached branches collapse into a single shape below.\n const wrapper: SdkCallWrapper | null =\n resolution.kind === \"scoped\"\n ? bindScopedPrefix(getScopedCacheWrapper(), scopedPrefix(resolution.credentials.siteId))\n : getSdkCallWrapper();\n\n if (usesCache(wrapper !== null, isReadMethod(leafName))) {\n return wrapper!(approvedPath, () => resolvedMethod(...safeArgs), ...safeArgs);\n }\n return resolvedMethod(...safeArgs);\n}\n\n/**\n * The SDK call `callSdk` makes (everything above), answered as its envelope's data.\n *\n * ## Postcondition — BaseResponse pass-through (exactly-once unwrap)\n *\n * result = unwrapBaseResponse(raw)\n * = raw.data when raw is { data, status, message }\n * = raw otherwise\n *\n * Consumers receive `T` directly when the SDK returns\n * `{ data: T, status, message }`, and the original value otherwise.\n * Double-unwrap (caller + queryAction) would silently strip a layer of\n * legitimate `{data, status, message}` user data when that shape happens\n * to round-trip through the API. The envelope's paging (`total`,\n * `totalResults`, `count`) is not in `data`: read it with `queryActionRaw`.\n *\n * @param methodPath Dot-separated SDK method path (e.g. \"items.invMast.doc.get\")\n * @param args Arguments to pass to the resolved method\n * @returns The unwrapped result from the SDK method (possibly from Redis cache)\n */\nexport async function queryAction(methodPath: string, ...args: unknown[]): Promise<unknown> {\n return unwrapBaseResponse(await callSdk(methodPath, args));\n}\n\n/**\n * The same call as `queryAction` (allowlist, client, `edgeCache` strip, Redis), answered as\n * the SDK returned it: augur-api's `BaseResponse<T>` envelope (every SDK method's result) with\n * `data`, `total`, `totalResults` and `count`, so client code can page a list (atlas#107). A\n * method path carries no type, so the caller names `T` (`queryActionRaw<Article[]>(…)`). A\n * `queryAction` and a `queryActionRaw` of one call share one Redis entry.\n *\n * MUST NOT run under a React Query key that also holds `queryAction`'s shape (an options\n * proxy's `queryKey`): give it its own key.\n *\n * @param methodPath Dot-separated SDK method path (e.g. \"joomla.content.list\")\n * @param args Arguments to pass to the resolved method\n * @returns The SDK method's result unchanged (possibly from Redis cache)\n */\nexport async function queryActionRaw<T = unknown>(\n methodPath: string,\n ...args: unknown[]\n): Promise<BaseResponse<T>> {\n return callSdk(methodPath, args) as Promise<BaseResponse<T>>;\n}\n\n/**\n * `queryAction`, bounded (atlas#106): `options.deadline` caps the whole call in milliseconds\n * (every retry and the waits between them), and `options.signal` lets the caller cancel it. At\n * the deadline the call rejects with a `TimeoutError` (the request is cancelled, nothing more is\n * retried, nothing is cached), so a server render can fall back to a client-side fetch.\n *\n * Server code (an SSR render) SHOULD set a deadline: with none, the SDK's retry budget (3 retries\n * at 30 s each, plus backoff) becomes page latency. Called as a server action from the browser,\n * only `deadline` crosses: an `AbortSignal` can't be serialized.\n *\n * The options are not SDK arguments and not part of the cache key, so a bounded call and an\n * unbounded one share one Redis entry. Needs an `@simpleapps-com/augur-api` with\n * `AugurAPI.withRequest`; with an older client the call is refused rather than run unbounded.\n *\n * @example\n * ```ts\n * const items = await queryActionWith({ deadline: 5000 }, \"items.categories.items.list\", uid, params)\n * .catch(() => undefined); // past 5 s: render without them, fetch on the client\n * ```\n */\nexport async function queryActionWith(\n options: CallOptions,\n methodPath: string,\n ...args: unknown[]\n): Promise<unknown> {\n return unwrapBaseResponse(await callSdk(methodPath, args, options));\n}\n\n/** `queryActionRaw`, bounded: the same options as {@link queryActionWith}. */\nexport async function queryActionRawWith<T = unknown>(\n options: CallOptions,\n methodPath: string,\n ...args: unknown[]\n): Promise<BaseResponse<T>> {\n return callSdk(methodPath, args, options) as Promise<BaseResponse<T>>;\n}\n\n/** Reset lazy-loaded imports. Used in tests only. @internal */\nexport function resetSessionImports(): void {\n _decode = undefined;\n _cookies = undefined;\n _decodeJwt = undefined;\n}\n\nexport { unwrapBaseResponse, getSessionCredentials, resolveMethod };\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAuBA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,gBAAqD;AAa9D,IAAM,gBAAgB;AAYtB,IAAI;AACJ,IAAI;AACJ,IAAI;AAGJ,eAAe,gBAAkC;AAC/C,MAAI,YAAY,QAAW;AACzB,QAAI;AACF,YAAM,MAAM,MAAM,OAAO,eAAe;AACxC,gBAAU,IAAI;AAAA,IAChB,QAAQ;AAEN,gBAAU;AAAA,IACZ;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ClB,SAAO,mBAAmB,MAAM,QAAQ,YAAY,MAAM,OAAO,CAAC;AACpE;AAGA,eAAsB,mBACpB,SACA,eACG,MACuB;AAC1B,SAAO,QAAQ,YAAY,MAAM,OAAO;AAC1C;AAGO,SAAS,sBAA4B;AAC1C,YAAU;AACV,aAAW;AACX,eAAa;AACf;","names":[]}
@@ -2,7 +2,7 @@ import {
2
2
  getCrossSite,
3
3
  signInTarget,
4
4
  verifiedFlag
5
- } from "./chunk-RGOLZMU3.js";
5
+ } from "./chunk-6GPKXGPG.js";
6
6
 
7
7
  // src/auth.ts
8
8
  import Credentials from "next-auth/providers/credentials";
@@ -171,4 +171,4 @@ function createAuthConfig(options) {
171
171
  export {
172
172
  createAuthConfig
173
173
  };
174
- //# sourceMappingURL=chunk-22B3WOGA.js.map
174
+ //# sourceMappingURL=chunk-KSGH4DXD.js.map
@@ -18,7 +18,7 @@ import {
18
18
  shouldCache,
19
19
  takesItemId,
20
20
  ttlFor
21
- } from "./chunk-RGOLZMU3.js";
21
+ } from "./chunk-6GPKXGPG.js";
22
22
 
23
23
  // src/environment.ts
24
24
  function getEnvironment() {
@@ -2342,4 +2342,4 @@ export {
2342
2342
  getSiteActions,
2343
2343
  clearSiteActions2 as clearSiteActions
2344
2344
  };
2345
- //# sourceMappingURL=chunk-5I7TBMGU.js.map
2345
+ //# sourceMappingURL=chunk-U54IM6FL.js.map
package/dist/hooks.js CHANGED
@@ -1,8 +1,8 @@
1
1
  "use client";
2
2
  import {
3
3
  queryAction
4
- } from "./chunk-R573MZQL.js";
5
- import "./chunk-RGOLZMU3.js";
4
+ } from "./chunk-FIM6LDMD.js";
5
+ import "./chunk-6GPKXGPG.js";
6
6
 
7
7
  // src/hooks.ts
8
8
  import { createQueryActionProxy } from "@simpleapps-com/augur-core";
package/dist/index.js CHANGED
@@ -21,10 +21,10 @@ import {
21
21
  unwrap,
22
22
  unwrapOr,
23
23
  withServerCache
24
- } from "./chunk-5I7TBMGU.js";
24
+ } from "./chunk-U54IM6FL.js";
25
25
  import {
26
26
  recaptchaOk
27
- } from "./chunk-RGOLZMU3.js";
27
+ } from "./chunk-6GPKXGPG.js";
28
28
 
29
29
  // src/server-query-client.ts
30
30
  import { cache } from "react";
@@ -1,5 +1,6 @@
1
1
  import { type SessionCredentials, type ApprovedMethodPath } from "./sdk-client-store";
2
2
  import { unwrapBaseResponse } from "@simpleapps-com/augur-core";
3
+ import { type BaseResponse, type CallOptions } from "@simpleapps-com/augur-api";
3
4
  /**
4
5
  * Resolve session credentials from the Auth.js JWT cookie.
5
6
  *
@@ -68,93 +69,7 @@ declare function getSessionCredentials(): Promise<SessionCredentials | null>;
68
69
  */
69
70
  declare function resolveMethod(client: unknown, methodPath: ApprovedMethodPath): (...a: unknown[]) => Promise<unknown>;
70
71
  /**
71
- * Generic server action that routes any SDK method call through the raw
72
- * SDK client with optional Redis caching. Used internally by
73
- * `createServerQueryProxy()` to bridge client-side React Query hooks
74
- * to server-side API calls.
75
- *
76
- * For read methods (get, list, lookup, search, suggest), the call is
77
- * wrapped in the registered cache wrapper (Redis) if one was registered
78
- * by createServerSite(). Write methods bypass caching.
79
- *
80
- * When the request has an active session with targetSiteId + token
81
- * (from cross-site auth), the call uses a scoped SDK client with those
82
- * credentials. Redis caching uses targetSiteId as the cache prefix so
83
- * users managing the same site share cached data.
84
- *
85
- * SDK responses wrapped in BaseResponse are automatically unwrapped --
86
- * consumers receive `T` instead of `{ data: T, status, message }`.
87
- *
88
- * This is the chokepoint: every B2B site without a client-side SDK
89
- * routes EVERY data access through this one function. The invariants
90
- * below are load-bearing across every site, every request, every user.
91
- *
92
- * ## Preconditions (enforced at runtime via thrown Error)
93
- *
94
- * parseMethodPath(methodPath) ≠ null
95
- * resolveClient().client ≠ null
96
- *
97
- * First clause: methodPath is a non-empty string AND — if an allowlist
98
- * has been registered via `registerAllowedMethodPaths` — methodPath is
99
- * in the allowlist. Assumes the site opted into surface restriction
100
- * when narrower-than-augur-api authority is desired; otherwise any
101
- * non-empty string passes (transparent forwarder default).
102
- *
103
- * Second clause: createServerSite() ran during bootstrap OR
104
- * AUGUR_SITE_ID + AUGUR_JWT env vars are set so the registry can
105
- * auto-init. Assumes the caller has bootstrapped one of the two paths.
106
- *
107
- * Lean equivalent: `requires path : ApprovedMethodPath ∧ client : SDKClient`.
108
- *
109
- * ## Cross-tenant cache-prefix invariant (load-bearing)
110
- *
111
- * resolution.kind = "scoped" ⟹ cachePrefix = `${resolution.credentials.siteId}:`
112
- *
113
- * On the scoped path the cache prefix is derived structurally from the
114
- * same `SessionCredentials` value that minted the scoped client — they
115
- * cannot be sourced separately. This makes "siteId from session A
116
- * combined with token from session B" or "siteId X with cache prefix Y"
117
- * unrepresentable here. Assumes `getSessionCredentials` performed the
118
- * bearer/session siteId cross-check at mint time; see the brand-strength
119
- * caveat on `SessionCredentials`.
120
- *
121
- * A regression here would silently leak cached data across tenants.
122
- * The structural derivation is the only thing standing between the
123
- * request and that leak — do not reintroduce a separate `cachePrefix`
124
- * parameter or compute it from anything other than `resolution.credentials`.
125
- *
126
- * ### Sibling assumption — bearer is NOT in the cache key
127
- *
128
- * The cross-tenant invariant covers cross-SITE leaks. It does NOT cover
129
- * intra-site cross-USER leaks: the cache key is `(siteId, methodPath, args)`
130
- * and the bearer token is intentionally absent. Two users with different
131
- * bearers on the same site share cached data for cacheable namespaces.
132
- *
133
- * This is a deliberate design choice. The assumption is:
134
- *
135
- * ∀ namespace ∉ NO_CACHE_PATHS, ∀ siteId, ∀ args.
136
- * augur-api(bearer_A, siteId, args) = augur-api(bearer_B, siteId, args)
137
- *
138
- * i.e. for cacheable namespaces, augur-api's response is bearer-independent
139
- * within a site. augur-api remains the auth authority; `NO_CACHE_PATHS`
140
- * (commerce.*, payments.*) is the carve-out for namespaces whose responses
141
- * ARE bearer-coupled. If a future namespace produces bearer-dependent
142
- * responses (e.g. user-specific permissions affecting query results), it
143
- * MUST be added to `NO_CACHE_PATHS` or the bearer MUST become part of the
144
- * cache key — otherwise this assumption silently produces a permission leak.
145
- *
146
- * ## No-edge-cache defense-in-depth (load-bearing)
147
- *
148
- * ∀ a ∈ safeArgs. methodPath ∈ NO_CACHE_PATHS ⟹ "edgeCache" ∉ keys(a)
149
- *
150
- * `stripEdgeCacheForNoCachePaths` removes the `edgeCache` key from every
151
- * first-level object arg when methodPath belongs to a no-cache namespace
152
- * (currently `commerce.*`, `payments.*`). The augur-api SDK transforms
153
- * `edgeCache` into a Cloudflare `cacheSiteId{N}` query param; removing
154
- * it here guarantees no CDN edge-caching of identity-bound responses
155
- * even if a caller passed one explicitly or a legacy factory injected
156
- * one. Assumes `NO_CACHE_PATHS` enumerates every namespace whose
157
- * responses must not cross identity boundaries.
72
+ * The SDK call `callSdk` makes (everything above), answered as its envelope's data.
158
73
  *
159
74
  * ## Postcondition — BaseResponse pass-through (exactly-once unwrap)
160
75
  *
@@ -164,23 +79,54 @@ declare function resolveMethod(client: unknown, methodPath: ApprovedMethodPath):
164
79
  *
165
80
  * Consumers receive `T` directly when the SDK returns
166
81
  * `{ data: T, status, message }`, and the original value otherwise.
167
- * Assumes upstream cache wrappers do NOT themselves unwrap — they
168
- * return whatever the SDK returned, so unwrapping happens exactly
169
- * once, here. Double-unwrap (caller + queryAction) would silently
170
- * strip a layer of legitimate `{data, status, message}` user data
171
- * when that shape happens to round-trip through the API.
172
- *
173
- * ## Effects
174
- *
175
- * @mutates Redis (write-through on read methods when a wrapper is registered)
176
- * @io augur-api SDK (network request)
177
- * @throws Error when the allowlist gate fails or no client is initialised
82
+ * Double-unwrap (caller + queryAction) would silently strip a layer of
83
+ * legitimate `{data, status, message}` user data when that shape happens
84
+ * to round-trip through the API. The envelope's paging (`total`,
85
+ * `totalResults`, `count`) is not in `data`: read it with `queryActionRaw`.
178
86
  *
179
87
  * @param methodPath Dot-separated SDK method path (e.g. "items.invMast.doc.get")
180
88
  * @param args Arguments to pass to the resolved method
181
89
  * @returns The unwrapped result from the SDK method (possibly from Redis cache)
182
90
  */
183
91
  export declare function queryAction(methodPath: string, ...args: unknown[]): Promise<unknown>;
92
+ /**
93
+ * The same call as `queryAction` (allowlist, client, `edgeCache` strip, Redis), answered as
94
+ * the SDK returned it: augur-api's `BaseResponse<T>` envelope (every SDK method's result) with
95
+ * `data`, `total`, `totalResults` and `count`, so client code can page a list (atlas#107). A
96
+ * method path carries no type, so the caller names `T` (`queryActionRaw<Article[]>(…)`). A
97
+ * `queryAction` and a `queryActionRaw` of one call share one Redis entry.
98
+ *
99
+ * MUST NOT run under a React Query key that also holds `queryAction`'s shape (an options
100
+ * proxy's `queryKey`): give it its own key.
101
+ *
102
+ * @param methodPath Dot-separated SDK method path (e.g. "joomla.content.list")
103
+ * @param args Arguments to pass to the resolved method
104
+ * @returns The SDK method's result unchanged (possibly from Redis cache)
105
+ */
106
+ export declare function queryActionRaw<T = unknown>(methodPath: string, ...args: unknown[]): Promise<BaseResponse<T>>;
107
+ /**
108
+ * `queryAction`, bounded (atlas#106): `options.deadline` caps the whole call in milliseconds
109
+ * (every retry and the waits between them), and `options.signal` lets the caller cancel it. At
110
+ * the deadline the call rejects with a `TimeoutError` (the request is cancelled, nothing more is
111
+ * retried, nothing is cached), so a server render can fall back to a client-side fetch.
112
+ *
113
+ * Server code (an SSR render) SHOULD set a deadline: with none, the SDK's retry budget (3 retries
114
+ * at 30 s each, plus backoff) becomes page latency. Called as a server action from the browser,
115
+ * only `deadline` crosses: an `AbortSignal` can't be serialized.
116
+ *
117
+ * The options are not SDK arguments and not part of the cache key, so a bounded call and an
118
+ * unbounded one share one Redis entry. Needs an `@simpleapps-com/augur-api` with
119
+ * `AugurAPI.withRequest`; with an older client the call is refused rather than run unbounded.
120
+ *
121
+ * @example
122
+ * ```ts
123
+ * const items = await queryActionWith({ deadline: 5000 }, "items.categories.items.list", uid, params)
124
+ * .catch(() => undefined); // past 5 s: render without them, fetch on the client
125
+ * ```
126
+ */
127
+ export declare function queryActionWith(options: CallOptions, methodPath: string, ...args: unknown[]): Promise<unknown>;
128
+ /** `queryActionRaw`, bounded: the same options as {@link queryActionWith}. */
129
+ export declare function queryActionRawWith<T = unknown>(options: CallOptions, methodPath: string, ...args: unknown[]): Promise<BaseResponse<T>>;
184
130
  /** Reset lazy-loaded imports. Used in tests only. @internal */
185
131
  export declare function resetSessionImports(): void;
186
132
  export { unwrapBaseResponse, getSessionCredentials, resolveMethod };
@@ -1 +1 @@
1
- {"version":3,"file":"query-action.d.ts","sourceRoot":"","sources":["../src/query-action.ts"],"names":[],"mappings":"AAUA,OAAO,EAQL,KAAK,kBAAkB,EACvB,KAAK,kBAAkB,EAGxB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAGL,kBAAkB,EACnB,MAAM,4BAA4B,CAAC;AAgGpC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA0DG;AACH,iBAAe,qBAAqB,IAAI,OAAO,CAAC,kBAAkB,GAAG,IAAI,CAAC,CA6BzE;AA2DD;;;;;GAKG;AACH,iBAAS,aAAa,CACpB,MAAM,EAAE,OAAO,EACf,UAAU,EAAE,kBAAkB,GAC7B,CAAC,GAAG,CAAC,EAAE,OAAO,EAAE,KAAK,OAAO,CAAC,OAAO,CAAC,CAkBvC;AAqCD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgHG;AACH,wBAAsB,WAAW,CAAC,UAAU,EAAE,MAAM,EAAE,GAAG,IAAI,EAAE,OAAO,EAAE,GAAG,OAAO,CAAC,OAAO,CAAC,CA4C1F;AAED,+DAA+D;AAC/D,wBAAgB,mBAAmB,IAAI,IAAI,CAI1C;AAED,OAAO,EAAE,kBAAkB,EAAE,qBAAqB,EAAE,aAAa,EAAE,CAAC"}
1
+ {"version":3,"file":"query-action.d.ts","sourceRoot":"","sources":["../src/query-action.ts"],"names":[],"mappings":"AAUA,OAAO,EAQL,K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+DAA+D;AAC/D,wBAAgB,mBAAmB,IAAI,IAAI,CAI1C;AAED,OAAO,EAAE,kBAAkB,EAAE,qBAAqB,EAAE,aAAa,EAAE,CAAC"}
@@ -2,14 +2,20 @@
2
2
  import {
3
3
  getSessionCredentials,
4
4
  queryAction,
5
+ queryActionRaw,
6
+ queryActionRawWith,
7
+ queryActionWith,
5
8
  resetSessionImports,
6
9
  resolveMethod,
7
10
  unwrapBaseResponse
8
- } from "./chunk-R573MZQL.js";
9
- import "./chunk-RGOLZMU3.js";
11
+ } from "./chunk-FIM6LDMD.js";
12
+ import "./chunk-6GPKXGPG.js";
10
13
  export {
11
14
  getSessionCredentials,
12
15
  queryAction,
16
+ queryActionRaw,
17
+ queryActionRawWith,
18
+ queryActionWith,
13
19
  resetSessionImports,
14
20
  resolveMethod,
15
21
  unwrapBaseResponse
package/dist/rules.d.ts CHANGED
@@ -56,8 +56,11 @@ export declare function serverEnvOf(nodeEnv: string): Env;
56
56
  * @ensures exactly the model's host rule
57
57
  */
58
58
  export declare function hostEnvOf(host: string): Env;
59
- /** The API route's outcome for a request. */
60
- export type ApiOutcome = "forbidden" | "bad-json" | "bad-method-path" | "bad-args" | "run";
59
+ /**
60
+ * The API route's outcome for a request: "run" answers queryAction's data, "run-full"
61
+ * queryActionRaw's full response (atlas#107).
62
+ */
63
+ export type ApiOutcome = "forbidden" | "bad-json" | "bad-method-path" | "bad-args" | "run" | "run-full";
61
64
  /**
62
65
  * A present, non-empty Sec-Fetch-Site other than same-origin is refused (a missing one, `""`
63
66
  * from the caller, passes).
@@ -66,11 +69,24 @@ export type ApiOutcome = "forbidden" | "bad-json" | "bad-method-path" | "bad-arg
66
69
  */
67
70
  export declare function isCrossOrigin(fetchSite: string): boolean;
68
71
  /**
69
- * The body's outcome: JSON, then a non-empty methodPath string, then an args array.
72
+ * The body's outcome: JSON, then a non-empty methodPath string, then an args array; a valid
73
+ * body with `raw: true` (`full`) runs for the full response, any other for its data.
70
74
  *
71
75
  * @ensures exactly the model's ApiOutcomeOf past the origin check
72
76
  */
73
- export declare function bodyOutcomeOf(jsonOk: boolean, methodPathOk: boolean, argsIsArray: boolean): ApiOutcome;
77
+ export declare function bodyOutcomeOf(jsonOk: boolean, methodPathOk: boolean, argsIsArray: boolean, full: boolean): ApiOutcome;
78
+ /**
79
+ * The route runs the call: either view; any other outcome is a refusal.
80
+ *
81
+ * @ensures exactly the model's Runs
82
+ */
83
+ export declare function runsOf(o: ApiOutcome): boolean;
84
+ /**
85
+ * The route answers the full response (queryActionRaw), not its data.
86
+ *
87
+ * @ensures exactly the model's AnswersFull
88
+ */
89
+ export declare function answersFullOf(o: ApiOutcome): boolean;
74
90
  /**
75
91
  * An outcome's HTTP status: 403, 400 for a bad body, 200 to run.
76
92
  *
@@ -205,6 +221,22 @@ export declare function approvePath(path: string, hasAllowlist: boolean, listed:
205
221
  * @ensures exactly the model's UsesCache
206
222
  */
207
223
  export declare function usesCache(hasWrapper: boolean, isRead: boolean): boolean;
224
+ /**
225
+ * The Auth.js session cookie decodeSessionJwt reads, and the salt it decodes with: the HTTPS
226
+ * cookie when the request has one, else the plain one.
227
+ *
228
+ * @ensures exactly the model's SessionCookieName
229
+ */
230
+ export declare function sessionCookieName(hasSecure: boolean): string;
231
+ /** Which client a bounded call runs on (atlas#106). */
232
+ export type ClientChoice = "client" | "view" | "refuse";
233
+ /**
234
+ * queryActionWith's client: today's client with no options; else the client's `withRequest`
235
+ * view, refused when the client has none (a call asked to be bounded never runs unbounded).
236
+ *
237
+ * @ensures exactly the model's ClientFor
238
+ */
239
+ export declare function clientFor(hasOptions: boolean, hasWithRequest: boolean): ClientChoice;
208
240
  /**
209
241
  * The scoped cache prefix: the session's siteId and ":".
210
242
  *
@@ -1 +1 @@
1
- {"version":3,"file":"rules.d.ts","sourceRoot":"","sources":["../src/rules.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAMlD;;;;;GAKG;AAC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B,UAAU,CAAC,OAAO,EAAE,OAAO,EAAE,GAAG,EAAE,OAAO,GAAG,OAAO,CAIlE;AAED;;;;GAIG;AACH,wBAAgB,QAAQ,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAMxD;AAED;;;;GAIG;AACH,wBAAgB,WAAW,CAAC,GAAG,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO,CAIhE;AAED;;;;GAIG;AACH,wBAAgB,SAAS,CAAC,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO,CAIlE;AAED;;;;GAIG;AACH,wBAAgB,gBAAgB,CAAC,UAAU,EAAE,MAAM,GAAG,SAAS,GAAG,MAAM,CAMvE"}
package/dist/site.js CHANGED
@@ -1,11 +1,11 @@
1
1
  import {
2
2
  createAuthConfig
3
- } from "./chunk-22B3WOGA.js";
3
+ } from "./chunk-KSGH4DXD.js";
4
4
  import {
5
5
  createSiteActions,
6
6
  registerSiteActions,
7
7
  withRawSdkCache
8
- } from "./chunk-5I7TBMGU.js";
8
+ } from "./chunk-U54IM6FL.js";
9
9
  import {
10
10
  crossSiteOf,
11
11
  registerAuthSecret,
@@ -15,7 +15,7 @@ import {
15
15
  registerSdkCallWrapper,
16
16
  registerSdkClient,
17
17
  ttlFor
18
- } from "./chunk-RGOLZMU3.js";
18
+ } from "./chunk-6GPKXGPG.js";
19
19
 
20
20
  // src/server-site.ts
21
21
  import { hours } from "@simpleapps-com/augur-utils";
package/dist/testing.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  clearSiteActions
3
- } from "./chunk-5I7TBMGU.js";
4
- import "./chunk-RGOLZMU3.js";
3
+ } from "./chunk-U54IM6FL.js";
4
+ import "./chunk-6GPKXGPG.js";
5
5
 
6
6
  // src/testing.ts
7
7
  import { createMockClient } from "@simpleapps-com/augur-core/testing";
package/llms.txt CHANGED
@@ -211,14 +211,25 @@ const addToCart = useMutation(q.commerce.cartLine.add.create());
211
211
  ## @simpleapps-com/augur-server/query-action
212
212
 
213
213
  - function: getSessionCredentials - Resolve session credentials from the Auth.js JWT cookie.
214
- - function: queryAction - Generic server action that routes any SDK method call through the raw SDK client with optional Redis caching. Used internally by `createServerQueryProxy()` to bridge client-side React Query hooks to server-side API calls.
214
+ - function: queryAction - The SDK call `callSdk` makes (everything above), answered as its envelope's data.
215
+ - function: queryActionRaw - The same call as `queryAction` (allowlist, client, `edgeCache` strip, Redis), answered as the SDK returned it: augur-api's `BaseResponse<T>` envelope (every SDK method's result) with `data`, `total`, `totalResults` and `count`, so client code can page a list (atlas#107). A method path carries no type, so the caller names `T` (`queryActionRaw<Article[]>(…)`). A `queryAction` and a `queryActionRaw` of one call share one Redis entry.
216
+ - function: queryActionRawWith - `queryActionRaw`, bounded: the same options as {@link queryActionWith}.
217
+ - function: queryActionWith - `queryAction`, bounded (atlas#106): `options.deadline` caps the whole call in milliseconds (every retry and the waits between them), and `options.signal` lets the caller cancel it. At the deadline the call rejects with a `TimeoutError` (the request is cancelled, nothing more is retried, nothing is cached), so a server render can fall back to a client-side fetch.
215
218
  - function: resetSessionImports - Reset lazy-loaded imports. Used in tests only. @internal
216
219
  - function: resolveMethod - Resolve a dot-separated method path on an object, returning the leaf function.
217
220
  - value: unwrapBaseResponse
218
221
 
222
+ ### Examples
223
+
224
+ queryActionWith:
225
+ ```ts
226
+ const items = await queryActionWith({ deadline: 5000 }, "items.categories.items.list", uid, params)
227
+ .catch(() => undefined); // past 5 s: render without them, fetch on the client
228
+ ```
229
+
219
230
  ## @simpleapps-com/augur-server/api
220
231
 
221
- - function: createAugurApiHandler - Creates a Next.js Route Handler that routes method calls through queryAction.
232
+ - function: createAugurApiHandler - Creates a Next.js Route Handler that routes method calls through queryAction, or through queryActionRaw when the body has `raw: true` (augur-core's `createFetchQueryActionRaw`).
222
233
 
223
234
  ### Examples
224
235
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@simpleapps-com/augur-server",
3
- "version": "2026.11.3",
3
+ "version": "2026.11.5",
4
4
  "description": "Server-side utilities for Augur ecommerce sites (Redis caching, SDK helpers, auth)",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -58,12 +58,12 @@
58
58
  "llms.txt"
59
59
  ],
60
60
  "dependencies": {
61
- "@simpleapps-com/augur-core": "^2026.11.2",
61
+ "@simpleapps-com/augur-core": "^2026.11.3",
62
62
  "@simpleapps-com/augur-hooks": "^2026.11.2",
63
63
  "@simpleapps-com/augur-utils": "^2026.11.3"
64
64
  },
65
65
  "peerDependencies": {
66
- "@simpleapps-com/augur-api": "^2026.10.17",
66
+ "@simpleapps-com/augur-api": "^2026.11.4",
67
67
  "@tanstack/react-query": "^5.80.0",
68
68
  "ioredis": "^5.9.0",
69
69
  "jose": "^5.0.0 || ^6.0.0",
@@ -98,10 +98,10 @@
98
98
  "@atlas/eslint-config": "0.0.0",
99
99
  "@atlas/tsconfig": "0.0.0",
100
100
  "@atlas/tsup-config": "0.0.0",
101
- "@atlas/foundation": "0.0.0",
102
101
  "@atlas/utils": "0.0.0",
102
+ "@atlas/foundation": "0.0.0",
103
103
  "@atlas/vitest-config": "0.0.0",
104
- "@simpleapps-com/augur-api": "2026.11.3"
104
+ "@simpleapps-com/augur-api": "2026.11.4"
105
105
  },
106
106
  "engines": {
107
107
  "node": ">=22.0.0"
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/query-action.ts"],"sourcesContent":["// \"use server\" banner is injected by tsup at build time.\n// Isolated server action for the proxy pattern.\n// This file MUST NOT import from server-actions.ts, server-site-registry.ts,\n// cache/, or any factory. It imports only from lightweight stores with zero\n// deps, the proved pure `rules` (with @atlas/utils' string scans, bundled), plus augur-core\n// and augur-api's `isSiteId` (both external in tsup — not bundled into chunks; every site\n// already loads the SDK on the server).\n// Dynamic imports of next/headers and next-auth/jwt are used for session\n// credential resolution (both are external in tsup).\n\nimport {\n getSdkClientOrNull,\n getSdkCallWrapper,\n getAuthSecret,\n getCrossSite,\n getOrCreateScopedClient,\n getScopedCacheWrapper,\n parseMethodPath,\n type SessionCredentials,\n type ApprovedMethodPath,\n type SdkCallWrapper,\n type ScopedCacheWrapper,\n} from \"./sdk-client-store\";\nimport {\n isReadMethod,\n stripEdgeCacheForNoCachePaths,\n unwrapBaseResponse,\n} from \"@simpleapps-com/augur-core\";\nimport { isSiteId } from \"@simpleapps-com/augur-api\";\nimport {\n clientIdSiteIdOf,\n mintedCredentials,\n readsSession,\n resolutionOf,\n scopedPrefix,\n usesCache,\n} from \"./rules\";\n\n/** Auth.js v5 session cookie names (HTTPS secure prefix + HTTP fallback). */\nconst SECURE_COOKIE = \"__Secure-authjs.session-token\";\nconst PLAIN_COOKIE = \"authjs.session-token\";\n\n/** Simplified function types for lazy-loaded external deps. */\ntype DecodeFn = (params: {\n token?: string;\n secret: string | string[];\n salt: string;\n}) => Promise<Record<string, unknown> | null>;\ntype CookiesFn = () => Promise<{ get: (name: string) => { value: string } | undefined }>;\ntype DecodeJwtFn = (token: string) => Record<string, unknown>;\n\n/** Cached dynamic imports for next-auth/jwt decode, next/headers cookies, and jose decodeJwt. */\nlet _decode: DecodeFn | null | undefined;\nlet _cookies: CookiesFn | null | undefined;\nlet _decodeJwt: DecodeJwtFn | null | undefined;\n\n/** Lazy-load decode, cookies, and decodeJwt functions from external deps. Cached after first call. */\nasync function ensureImports(): Promise<boolean> {\n if (_decode === undefined) {\n try {\n const mod = await import(\"next-auth/jwt\");\n _decode = mod.decode as unknown as DecodeFn;\n } catch {\n // next-auth is an optional peer: without it there are no session credentials\n _decode = null;\n }\n }\n if (_cookies === undefined) {\n try {\n const mod = await import(\"next/headers\");\n _cookies = mod.cookies as unknown as CookiesFn;\n } catch {\n // outside Next.js there is no request cookie store\n _cookies = null;\n }\n }\n if (_decodeJwt === undefined) {\n try {\n const mod = await import(\"jose\");\n _decodeJwt = mod.decodeJwt as unknown as DecodeJwtFn;\n } catch {\n // jose is an optional peer: without it the bearer cannot be cross-checked\n _decodeJwt = null;\n }\n }\n return !!_decode && !!_cookies && !!_decodeJwt;\n}\n\n/** Read and decode the Auth.js session JWT from request cookies. */\nasync function decodeSessionJwt(secret: string): Promise<Record<string, unknown> | null> {\n const cookieStore = await _cookies!();\n const secureCookie = cookieStore.get(SECURE_COOKIE);\n const plainCookie = secureCookie ? undefined : cookieStore.get(PLAIN_COOKIE);\n const cookie = secureCookie ?? plainCookie;\n if (!cookie?.value) return null;\n\n const salt = secureCookie ? SECURE_COOKIE : PLAIN_COOKIE;\n return _decode!({ token: cookie.value, secret, salt });\n}\n\n/**\n * Extract the siteId portion of an Augur bearer token's `client_id` claim.\n * Bearer tokens are JWTs whose payload contains `client_id: \"<numeric>|<siteId>\"`.\n * Returns null on any parse failure or unexpected shape.\n *\n * Uses jose.decodeJwt (no signature verification) — we trust the bearer\n * because the *outer* Auth.js cookie's signature was just verified upstream,\n * so the bearer's contents are trusted as session-issued. This check guards\n * against internal inconsistency between the session's `targetSiteId` and the\n * bearer's scope, not against a forged bearer (the auth provider's signature\n * does that).\n */\nfunction parseBearerClientSiteId(bearer: string): string | null {\n try {\n const payload = _decodeJwt!(bearer);\n const clientId = payload[\"client_id\"];\n if (typeof clientId !== \"string\") return null;\n return clientIdSiteIdOf(clientId);\n } catch {\n return null;\n }\n}\n\n/**\n * Resolve session credentials from the Auth.js JWT cookie.\n *\n * Trust-boundary mint point: this is the only function in the package that\n * produces {@link SessionCredentials} values. Bytes from a cookie become\n * typed, paired credentials here and only here. No other production code\n * constructs the branded pair, so a `SessionCredentials` that came through\n * this mint is JWT-validated and internally consistent. The brand is not\n * enforced by the compiler: an `as SessionCredentials` cast compiles (tests\n * do it), so audit casts (see \"Brand strength\" below).\n *\n * Returns null when:\n * - the site did not opt in to cross-site sessions (`createServerSite`'s\n * `auth: { crossSite: true }`, atlas#105): then nothing is imported and no\n * cookie is read, so pages using queryAction can render statically\n * - no AUTH_SECRET is configured\n * - next-auth/jwt, next/headers, or jose cannot be loaded\n * - no session cookie is present\n * - the JWT decode fails or returns null\n * - the decoded payload is missing `targetSiteId` or `token`, or either is\n * not a non-empty string (refuse to mint partial credentials)\n * - `targetSiteId` fails augur-api's `isSiteId` (`[a-z0-9_-]+`): siteIds are\n * lowercase by convention, and the scoped-client key's injectivity proof\n * (`scoped-client-key.ts`) needs a NUL-free siteId\n * - the bearer token's `client_id` siteId portion does not match\n * `targetSiteId` (defense-in-depth: refuses internally inconsistent sessions\n * before they reach the augur-api authority check)\n *\n * ## Verified preconditions for `result = some c`\n *\n * AUTH_SECRET configured\n * next-auth/jwt, next/headers, jose all loadable\n * session cookie present and decodable with the secret\n * typeof jwt.targetSiteId === \"string\" ∧ isSiteId(jwt.targetSiteId) // implies non-empty\n * typeof jwt.token === \"string\" ∧ jwt.token.length > 0\n * bearerClientSiteId(jwt.token) = some jwt.targetSiteId\n *\n * Lean equivalent: each clause becomes a `requires` on the function;\n * `result = none` is the disjunction of any failing.\n * F* equivalent: refinement on the option payload covering the\n * conjunction of these clauses.\n *\n * The bearer cross-check (`bearerClientSiteId(jwt.token) = some jwt.targetSiteId`)\n * is the substantive runtime invariant: it refuses sessions where the bearer's\n * encoded `client_id` siteId disagrees with the session's targetSiteId,\n * catching internal-inconsistency bugs before the call reaches augur-api.\n *\n * ## By construction (not independently verified)\n *\n * c.siteId === jwt.targetSiteId (assigned, not checked)\n * c.token === jwt.token (assigned, not checked)\n *\n * ## Brand strength\n *\n * `SessionCredentials` is a TS-level brand: there is no runtime tag on the\n * value. `value as SessionCredentials` casts compile, so the brand is a\n * code-review signal (audit `as SessionCredentials` usages — there should be\n * exactly one, in this function), not a hard type-system gate.\n */\nasync function getSessionCredentials(): Promise<SessionCredentials | null> {\n const secret = getAuthSecret();\n // Only an opted-in site with a secret looks for a session (rules.readsSession, atlas#105):\n // every other site returns here, before next/headers is imported or cookies() read, so its\n // pages can render statically.\n if (!readsSession(getCrossSite(), Boolean(secret))) return null;\n if (!(await ensureImports())) return null;\n\n try {\n // readsSession held, so the secret is present (Boolean(secret) above).\n const decoded = await decodeSessionJwt(secret as string);\n if (!decoded) return null;\n\n const targetSiteId = decoded[\"targetSiteId\"];\n const token = decoded[\"token\"];\n\n if (typeof targetSiteId !== \"string\" || typeof token !== \"string\") return null;\n\n // An empty or undecodable token has no client_id siteId (\"\").\n const bearerSiteId = parseBearerClientSiteId(token) ?? \"\";\n const mint = mintedCredentials(isSiteId(targetSiteId), targetSiteId, token, bearerSiteId);\n if (mint.kind === \"refused\") return null;\n\n return { siteId: mint.siteId, token: mint.token } as unknown as SessionCredentials;\n } catch {\n // Not in a request context (build time, tests), or decode failed\n }\n\n return null;\n}\n\n/**\n * Discriminated result of client resolution.\n *\n * Encodes two structural invariants at the type level:\n *\n * 1. session credentials exist iff this is the scoped path\n * (only `kind: \"scoped\"` carries `credentials`)\n * 2. a usable client exists iff this is NOT the uninit path\n * (`kind: \"scoped\" | \"global\"` always carry `client: object`)\n *\n * The `client: object` constraint replaces the previous `client: unknown` +\n * runtime null check. Anything narrowed to `kind: \"scoped\"` or `kind: \"global\"`\n * is guaranteed by the type system to have a non-null, traversable client —\n * downstream code that walks the SDK namespace path cannot accidentally\n * dereference null. The runtime check moves into `resolveClient` itself, where\n * `kind: \"uninit\"` is constructed when neither a scoped nor a global client is\n * available.\n *\n * Downstream code that wants to derive a cache prefix can only do so on the\n * scoped variant, and only from the credentials carried by that variant —\n * there is no way to construct a cache prefix from a different source without\n * crossing into the type.\n */\ntype ClientResolution =\n | { kind: \"scoped\"; client: object; credentials: SessionCredentials }\n | { kind: \"global\"; client: object }\n | { kind: \"uninit\" };\n\n/**\n * Resolve the SDK client for this request.\n *\n * - If the session JWT validates and a scoped client can be minted, returns\n * the scoped variant carrying the {@link SessionCredentials} that produced\n * the client. The cache prefix is derived at the use site from\n * `credentials.siteId`, structurally guaranteeing it matches the credentials\n * under which the SDK call is made.\n * - Otherwise returns the global variant. No credentials, no cache prefix.\n *\n * The previous return shape `{ client, cachePrefix: string | null }` made\n * \"cachePrefix exists iff scoped\" a runtime invariant; the tagged union\n * promotes it to a type-level one.\n */\nasync function resolveClient(): Promise<ClientResolution> {\n const creds = await getSessionCredentials();\n const scoped = creds ? getOrCreateScopedClient(creds) : null;\n const globalClient = getSdkClientOrNull();\n const kind = resolutionOf(creds !== null, isObject(scoped), isObject(globalClient));\n if (kind === \"scoped\") return { kind, client: scoped as object, credentials: creds! };\n if (kind === \"global\") return { kind, client: globalClient as object };\n return { kind };\n}\n\n/** A usable client: a non-null object. */\nfunction isObject(value: unknown): boolean {\n return value !== null && typeof value === \"object\";\n}\n\n/**\n * Resolve a dot-separated method path on an object, returning the leaf function.\n *\n * Demands {@link ApprovedMethodPath} so callers must have run the path through\n * `parseMethodPath` first — passing an unvalidated string is a compile error.\n */\nfunction resolveMethod(\n client: unknown,\n methodPath: ApprovedMethodPath,\n): (...a: unknown[]) => Promise<unknown> {\n const segments = methodPath.split(\".\");\n\n let current: unknown = client;\n for (const segment of segments) {\n if (current == null || (typeof current !== \"object\" && typeof current !== \"function\")) {\n throw new Error(\n `Cannot resolve \"${methodPath}\": \"${segment}\" is not accessible on ${typeof current}`,\n );\n }\n current = (current as Record<string, unknown>)[segment];\n }\n\n if (typeof current !== \"function\") {\n throw new Error(`\"${methodPath}\" does not resolve to a function (got ${typeof current})`);\n }\n\n return current as (...a: unknown[]) => Promise<unknown>;\n}\n\n/**\n * Bind a scoped cache wrapper to a fixed prefix, producing an `SdkCallWrapper`\n * with the same signature as the global wrapper.\n *\n * On the scoped queryAction path, the cache prefix is derived structurally\n * from the `SessionCredentials` that minted the client (`${credentials.siteId}:`).\n * Capturing that prefix in a closure here lets queryAction's call site treat\n * scoped and global wrappers uniformly — the only thing that differs between\n * them is which prefix gets baked in, and that decision happens in exactly one\n * place per request.\n *\n * Returns null when no scoped wrapper is registered, so the caller falls\n * through to the unwrapped SDK call. The closure preserves the cross-tenant\n * invariant: prefix is captured at bind time from the same credentials value\n * used to mint the scoped client, and cannot be replaced or re-sourced later.\n *\n * ## Property\n *\n * bindScopedPrefix(null, _) = null\n * bindScopedPrefix(w, p)(methodPath, fn, ...args) = w(p, methodPath, fn, ...args)\n *\n * The bound wrapper forwards faithfully — it adds nothing, drops nothing,\n * and reorders nothing. Every effect (cache read, cache write, SDK call)\n * happens inside the underlying scopedWrapper exactly as if queryAction had\n * called it directly with the prefix as the first argument.\n */\nfunction bindScopedPrefix(\n scopedWrapper: ScopedCacheWrapper | null,\n prefix: string,\n): SdkCallWrapper | null {\n if (!scopedWrapper) return null;\n return (methodPath, sdkCall, ...keyArgs) =>\n scopedWrapper(prefix, methodPath, sdkCall, ...keyArgs);\n}\n\n/**\n * Generic server action that routes any SDK method call through the raw\n * SDK client with optional Redis caching. Used internally by\n * `createServerQueryProxy()` to bridge client-side React Query hooks\n * to server-side API calls.\n *\n * For read methods (get, list, lookup, search, suggest), the call is\n * wrapped in the registered cache wrapper (Redis) if one was registered\n * by createServerSite(). Write methods bypass caching.\n *\n * When the request has an active session with targetSiteId + token\n * (from cross-site auth), the call uses a scoped SDK client with those\n * credentials. Redis caching uses targetSiteId as the cache prefix so\n * users managing the same site share cached data.\n *\n * SDK responses wrapped in BaseResponse are automatically unwrapped --\n * consumers receive `T` instead of `{ data: T, status, message }`.\n *\n * This is the chokepoint: every B2B site without a client-side SDK\n * routes EVERY data access through this one function. The invariants\n * below are load-bearing across every site, every request, every user.\n *\n * ## Preconditions (enforced at runtime via thrown Error)\n *\n * parseMethodPath(methodPath) ≠ null\n * resolveClient().client ≠ null\n *\n * First clause: methodPath is a non-empty string AND — if an allowlist\n * has been registered via `registerAllowedMethodPaths` — methodPath is\n * in the allowlist. Assumes the site opted into surface restriction\n * when narrower-than-augur-api authority is desired; otherwise any\n * non-empty string passes (transparent forwarder default).\n *\n * Second clause: createServerSite() ran during bootstrap OR\n * AUGUR_SITE_ID + AUGUR_JWT env vars are set so the registry can\n * auto-init. Assumes the caller has bootstrapped one of the two paths.\n *\n * Lean equivalent: `requires path : ApprovedMethodPath ∧ client : SDKClient`.\n *\n * ## Cross-tenant cache-prefix invariant (load-bearing)\n *\n * resolution.kind = \"scoped\" ⟹ cachePrefix = `${resolution.credentials.siteId}:`\n *\n * On the scoped path the cache prefix is derived structurally from the\n * same `SessionCredentials` value that minted the scoped client — they\n * cannot be sourced separately. This makes \"siteId from session A\n * combined with token from session B\" or \"siteId X with cache prefix Y\"\n * unrepresentable here. Assumes `getSessionCredentials` performed the\n * bearer/session siteId cross-check at mint time; see the brand-strength\n * caveat on `SessionCredentials`.\n *\n * A regression here would silently leak cached data across tenants.\n * The structural derivation is the only thing standing between the\n * request and that leak — do not reintroduce a separate `cachePrefix`\n * parameter or compute it from anything other than `resolution.credentials`.\n *\n * ### Sibling assumption — bearer is NOT in the cache key\n *\n * The cross-tenant invariant covers cross-SITE leaks. It does NOT cover\n * intra-site cross-USER leaks: the cache key is `(siteId, methodPath, args)`\n * and the bearer token is intentionally absent. Two users with different\n * bearers on the same site share cached data for cacheable namespaces.\n *\n * This is a deliberate design choice. The assumption is:\n *\n * ∀ namespace ∉ NO_CACHE_PATHS, ∀ siteId, ∀ args.\n * augur-api(bearer_A, siteId, args) = augur-api(bearer_B, siteId, args)\n *\n * i.e. for cacheable namespaces, augur-api's response is bearer-independent\n * within a site. augur-api remains the auth authority; `NO_CACHE_PATHS`\n * (commerce.*, payments.*) is the carve-out for namespaces whose responses\n * ARE bearer-coupled. If a future namespace produces bearer-dependent\n * responses (e.g. user-specific permissions affecting query results), it\n * MUST be added to `NO_CACHE_PATHS` or the bearer MUST become part of the\n * cache key — otherwise this assumption silently produces a permission leak.\n *\n * ## No-edge-cache defense-in-depth (load-bearing)\n *\n * ∀ a ∈ safeArgs. methodPath ∈ NO_CACHE_PATHS ⟹ \"edgeCache\" ∉ keys(a)\n *\n * `stripEdgeCacheForNoCachePaths` removes the `edgeCache` key from every\n * first-level object arg when methodPath belongs to a no-cache namespace\n * (currently `commerce.*`, `payments.*`). The augur-api SDK transforms\n * `edgeCache` into a Cloudflare `cacheSiteId{N}` query param; removing\n * it here guarantees no CDN edge-caching of identity-bound responses\n * even if a caller passed one explicitly or a legacy factory injected\n * one. Assumes `NO_CACHE_PATHS` enumerates every namespace whose\n * responses must not cross identity boundaries.\n *\n * ## Postcondition — BaseResponse pass-through (exactly-once unwrap)\n *\n * result = unwrapBaseResponse(raw)\n * = raw.data when raw is { data, status, message }\n * = raw otherwise\n *\n * Consumers receive `T` directly when the SDK returns\n * `{ data: T, status, message }`, and the original value otherwise.\n * Assumes upstream cache wrappers do NOT themselves unwrap — they\n * return whatever the SDK returned, so unwrapping happens exactly\n * once, here. Double-unwrap (caller + queryAction) would silently\n * strip a layer of legitimate `{data, status, message}` user data\n * when that shape happens to round-trip through the API.\n *\n * ## Effects\n *\n * @mutates Redis (write-through on read methods when a wrapper is registered)\n * @io augur-api SDK (network request)\n * @throws Error when the allowlist gate fails or no client is initialised\n *\n * @param methodPath Dot-separated SDK method path (e.g. \"items.invMast.doc.get\")\n * @param args Arguments to pass to the resolved method\n * @returns The unwrapped result from the SDK method (possibly from Redis cache)\n */\nexport async function queryAction(methodPath: string, ...args: unknown[]): Promise<unknown> {\n const approvedPath = parseMethodPath(methodPath);\n if (approvedPath === null) {\n throw new Error(\n `queryAction: methodPath ${JSON.stringify(methodPath)} is not in the registered allowlist. ` +\n `Register it via registerAllowedMethodPaths() in createServerSite() config.`,\n );\n }\n\n const resolution = await resolveClient();\n if (resolution.kind === \"uninit\") {\n throw new Error(\n \"SDK client not initialized. Call createServerSite() or set AUGUR_SITE_ID + AUGUR_JWT env vars.\",\n );\n }\n\n const resolvedMethod = resolveMethod(resolution.client, approvedPath);\n const leafName = approvedPath.split(\".\").pop()!;\n // Defense in depth: strip `edgeCache` from no-cache paths before the SDK\n // sees it. The augur-api SDK transforms `edgeCache` into a Cloudflare\n // `cacheSiteId{N}` query param; removing it here guarantees no CDN edge\n // caching of identity-bound responses even if a caller explicitly passed\n // one. Also keeps cache keys consistent with what is actually sent.\n const safeArgs = stripEdgeCacheForNoCachePaths(approvedPath, args);\n\n // Pick the wrapper for this resolution's prefix policy. On the scoped path,\n // the prefix is structurally derived from `credentials.siteId` and bound into\n // a closure here — bindScopedPrefix is the only call site that builds it,\n // and the prefix cannot be re-sourced after binding. On the global path, the\n // prefix is closed over by the SdkCallWrapper that createServerSite registered.\n // Both paths now produce a uniform `SdkCallWrapper | null`, so the caching\n // and uncached branches collapse into a single shape below.\n const wrapper: SdkCallWrapper | null =\n resolution.kind === \"scoped\"\n ? bindScopedPrefix(getScopedCacheWrapper(), scopedPrefix(resolution.credentials.siteId))\n : getSdkCallWrapper();\n\n if (usesCache(wrapper !== null, isReadMethod(leafName))) {\n const result = await wrapper!(approvedPath, () => resolvedMethod(...safeArgs), ...safeArgs);\n return unwrapBaseResponse(result);\n }\n\n const result = await resolvedMethod(...safeArgs);\n return unwrapBaseResponse(result);\n}\n\n/** Reset lazy-loaded imports. Used in tests only. @internal */\nexport function resetSessionImports(): void {\n _decode = undefined;\n _cookies = undefined;\n _decodeJwt = undefined;\n}\n\nexport { unwrapBaseResponse, getSessionCredentials, resolveMethod };\n"],"mappings":";;;;;;;;;;;;;;;;;AAuBA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,gBAAgB;AAWzB,IAAM,gBAAgB;AACtB,IAAM,eAAe;AAYrB,IAAI;AACJ,IAAI;AACJ,IAAI;AAGJ,eAAe,gBAAkC;AAC/C,MAAI,YAAY,QAAW;AACzB,QAAI;AACF,YAAM,MAAM,MAAM,OAAO,eAAe;AACxC,gBAAU,IAAI;AAAA,IAChB,QAAQ;AAEN,gBAAU;AAAA,IACZ;AAAA,EACF;AACA,MAAI,aAAa,QAAW;AAC1B,QAAI;AACF,YAAM,MAAM,MAAM,OAAO,cAAc;AACvC,iBAAW,IAAI;AAAA,IACjB,QAAQ;AAEN,iBAAW;AAAA,IACb;AAAA,EACF;AACA,MAAI,eAAe,QAAW;AAC5B,QAAI;AACF,YAAM,MAAM,MAAM,OAAO,MAAM;AAC/B,mBAAa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