@simpleapps-com/augur-server 2026.11.11 → 2026.11.12

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 (50) hide show
  1. package/EXPORTS.md +2 -2
  2. package/README.md +37 -7
  3. package/dist/api-handler.d.ts.map +1 -1
  4. package/dist/api.js +7 -5
  5. package/dist/api.js.map +1 -1
  6. package/dist/auth.d.ts +38 -4
  7. package/dist/auth.d.ts.map +1 -1
  8. package/dist/auth.js +4 -3
  9. package/dist/{chunk-5X2QWOTO.js → chunk-5DBFTSWY.js} +4 -11
  10. package/dist/chunk-5DBFTSWY.js.map +1 -0
  11. package/dist/{chunk-4CU4UNBH.js → chunk-GKT4MAWC.js} +4 -4
  12. package/dist/{chunk-BG4G5QUQ.js → chunk-HGJF667G.js} +8 -1
  13. package/dist/{chunk-BG4G5QUQ.js.map → chunk-HGJF667G.js.map} +1 -1
  14. package/dist/chunk-ILXNFJVM.js +86 -0
  15. package/dist/chunk-ILXNFJVM.js.map +1 -0
  16. package/dist/{chunk-JIYVQWXK.js → chunk-IM7FDRER.js} +1 -1
  17. package/dist/chunk-IM7FDRER.js.map +1 -0
  18. package/dist/chunk-M35O5JDZ.js +257 -0
  19. package/dist/chunk-M35O5JDZ.js.map +1 -0
  20. package/dist/{chunk-OTZUEADV.js → chunk-Y54RGILF.js} +35 -3
  21. package/dist/chunk-Y54RGILF.js.map +1 -0
  22. package/dist/hooks.js +4 -3
  23. package/dist/hooks.js.map +1 -1
  24. package/dist/index.js +6 -5
  25. package/dist/index.js.map +1 -1
  26. package/dist/query-action.d.ts +2 -8
  27. package/dist/query-action.d.ts.map +1 -1
  28. package/dist/query-action.js +4 -3
  29. package/dist/recaptcha.d.ts.map +1 -1
  30. package/dist/rules.d.ts +2 -14
  31. package/dist/rules.d.ts.map +1 -1
  32. package/dist/sdk-client-store.d.ts +4 -3
  33. package/dist/sdk-client-store.d.ts.map +1 -1
  34. package/dist/server-site.d.ts +6 -8
  35. package/dist/server-site.d.ts.map +1 -1
  36. package/dist/session-rules.d.ts +118 -0
  37. package/dist/session-rules.d.ts.map +1 -0
  38. package/dist/site.js +14 -9
  39. package/dist/site.js.map +1 -1
  40. package/dist/sitemap.js +2 -2
  41. package/dist/testing.js +4 -4
  42. package/llms.txt +4 -2
  43. package/next-auth.d.ts +2 -2
  44. package/package.json +7 -6
  45. package/dist/chunk-5X2QWOTO.js.map +0 -1
  46. package/dist/chunk-AEFUT3MB.js +0 -183
  47. package/dist/chunk-AEFUT3MB.js.map +0 -1
  48. package/dist/chunk-JIYVQWXK.js.map +0 -1
  49. package/dist/chunk-OTZUEADV.js.map +0 -1
  50. /package/dist/{chunk-4CU4UNBH.js.map → chunk-GKT4MAWC.js.map} +0 -0
@@ -1,183 +0,0 @@
1
- import {
2
- cartLookupRuns,
3
- getCrossSite,
4
- signInTarget,
5
- verifiedFlag
6
- } from "./chunk-5X2QWOTO.js";
7
-
8
- // src/auth.ts
9
- import { addressIdOf, resolveAddressId } from "@simpleapps-com/augur-utils";
10
- import Credentials from "next-auth/providers/credentials";
11
- function buildInternalCallbacks(augurClient) {
12
- return {
13
- async getUserProfile(userId) {
14
- if (!userId) return null;
15
- const uid = parseInt(userId, 10);
16
- if (isNaN(uid)) return null;
17
- const result = await augurClient.joomla.users.doc.get(uid, {
18
- edgeCache: 1
19
- });
20
- const data = result.data;
21
- if (!data) return null;
22
- return {
23
- id: String(data["id"]),
24
- name: data["name"],
25
- username: data["username"],
26
- email: data["email"],
27
- isVerified: true,
28
- // Joomla holds it as text; "" and "0" are no customer, so none reaches the session (atlas#95).
29
- customerId: addressIdOf(data["customerId"]) ?? void 0,
30
- contactId: data["contactId"]
31
- };
32
- },
33
- async cartHdrLookup(userId, _token, contactId, customerId) {
34
- const result = await augurClient.commerce.cartHdr.lookup.get({
35
- userId: Number(userId) || 0,
36
- // Always a usable id: lookupCartHdr looks up no cart without one (atlas#95).
37
- customerId,
38
- contactId: Number(contactId) || 0
39
- });
40
- return result.data || null;
41
- }
42
- };
43
- }
44
- function resolveCallbacks(options) {
45
- const { augurClient, callbacks } = options;
46
- if (augurClient) {
47
- const internal = buildInternalCallbacks(augurClient);
48
- return {
49
- getUserProfile: callbacks?.getUserProfile ?? internal.getUserProfile,
50
- cartHdrLookup: callbacks?.cartHdrLookup ?? internal.cartHdrLookup
51
- };
52
- }
53
- if (!callbacks?.getUserProfile) {
54
- throw new Error("createAuthConfig requires either `augurClient` or `callbacks.getUserProfile`");
55
- }
56
- return {
57
- getUserProfile: callbacks.getUserProfile,
58
- cartHdrLookup: callbacks.cartHdrLookup
59
- };
60
- }
61
- async function lookupCartHdr(siteCallbacks, profile, defaultCustomerId, defaultContactId) {
62
- const customerId = resolveAddressId(profile.customerId, defaultCustomerId);
63
- const lookup = siteCallbacks.cartHdrLookup;
64
- if (!cartLookupRuns(lookup !== void 0, !!profile.id, customerId)) {
65
- return void 0;
66
- }
67
- const cartHdr = await lookup(
68
- profile.id,
69
- "",
70
- profile.contactId ?? defaultContactId ?? "",
71
- customerId
72
- );
73
- return cartHdr?.cartHdrUid;
74
- }
75
- function baseUserOf(token) {
76
- return {
77
- id: token["id"] || "",
78
- username: token["username"] || "",
79
- isVerified: token["isVerified"] || false
80
- };
81
- }
82
- function createAuthConfig(options) {
83
- const {
84
- secret = process.env["AUTH_SECRET"],
85
- maxAge = 4 * 60 * 60,
86
- defaultCustomerId,
87
- defaultContactId,
88
- debug = process.env["NODE_ENV"] === "development"
89
- } = options;
90
- const siteCallbacks = resolveCallbacks(options);
91
- return {
92
- providers: [
93
- Credentials({
94
- name: "Credentials",
95
- credentials: {
96
- username: { label: "Username", type: "text" },
97
- password: { label: "Password", type: "password" },
98
- id: { label: "ID", type: "text" },
99
- isVerified: { label: "Is Verified", type: "text" },
100
- token: { label: "Token", type: "text" },
101
- siteId: { label: "Site ID", type: "text" }
102
- },
103
- async authorize(credentials) {
104
- if (!credentials) return null;
105
- const { id, isVerified, username, token, siteId } = credentials;
106
- return {
107
- id,
108
- isVerified: verifiedFlag(isVerified),
109
- username,
110
- token,
111
- // Kept only on a site that opted in (createServerSite's auth.crossSite), read from
112
- // the same store queryAction reads, at sign-in time (rules.signInTarget, atlas#105).
113
- targetSiteId: signInTarget(getCrossSite(), siteId)
114
- };
115
- }
116
- })
117
- ],
118
- callbacks: {
119
- async signIn() {
120
- return true;
121
- },
122
- async redirect({ baseUrl }) {
123
- return baseUrl;
124
- },
125
- async session({ session, token }) {
126
- const baseUser = baseUserOf(token);
127
- const targetSiteId = token["targetSiteId"];
128
- const buildSession = (userOverrides = {}) => ({
129
- ...session,
130
- user: { ...session.user, ...baseUser, ...userOverrides, targetSiteId },
131
- token: token["token"],
132
- targetSiteId
133
- });
134
- try {
135
- const userProfile = await siteCallbacks.getUserProfile(baseUser.id);
136
- if (!userProfile) return buildSession();
137
- const cartHdrUid = await lookupCartHdr(
138
- siteCallbacks,
139
- userProfile,
140
- defaultCustomerId,
141
- defaultContactId
142
- );
143
- return buildSession({
144
- name: userProfile.name ?? session.user?.name,
145
- email: userProfile.email ?? session.user?.email,
146
- // Never "" or "0": the profile's usable id, else the default's, else none (atlas#95).
147
- customerId: resolveAddressId(userProfile.customerId, defaultCustomerId) ?? void 0,
148
- contactId: userProfile.contactId,
149
- cartHdrUid
150
- });
151
- } catch {
152
- return buildSession();
153
- }
154
- },
155
- async jwt({ token, user }) {
156
- if (user) {
157
- const typedUser = user;
158
- return {
159
- ...token,
160
- id: typedUser.id,
161
- isVerified: typedUser.isVerified,
162
- username: typedUser.username,
163
- token: typedUser.token,
164
- targetSiteId: typedUser.targetSiteId
165
- };
166
- }
167
- return token;
168
- }
169
- },
170
- secret,
171
- debug,
172
- session: {
173
- strategy: "jwt",
174
- maxAge
175
- },
176
- trustHost: true
177
- };
178
- }
179
-
180
- export {
181
- createAuthConfig
182
- };
183
- //# sourceMappingURL=chunk-AEFUT3MB.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/auth.ts"],"sourcesContent":["// @simpleapps-com/augur-server/auth\n// NextAuth 5 configuration factory for Augur ecommerce sites.\n\nimport type { AugurAPI } from \"@simpleapps-com/augur-api\";\nimport { addressIdOf, resolveAddressId } from \"@simpleapps-com/augur-utils\";\nimport type { NextAuthConfig } from \"next-auth\";\nimport Credentials from \"next-auth/providers/credentials\";\nimport type { AddressId } from \"./address-id\";\nimport { cartLookupRuns, signInTarget, verifiedFlag } from \"./rules\";\nimport { getCrossSite } from \"./sdk-client-store\";\n\n/** Base user fields shared across all Augur sites. */\nexport interface AugurUser {\n id: string;\n username: string;\n isVerified: boolean;\n name?: string;\n email?: string;\n customerId?: string | number;\n contactId?: string | number;\n cartHdrUid?: number;\n token?: string;\n /** Target site ID for cross-site auth sessions (augur_info + body siteId). */\n targetSiteId?: string;\n}\n\n/** Session shape returned by all Augur sites. */\nexport interface AugurSession {\n user: AugurUser;\n token?: string;\n targetSiteId?: string;\n expires: string;\n}\n\n/** JWT token shape used by Augur auth. */\nexport interface AugurJWT {\n id: string;\n username: string;\n isVerified: boolean;\n token?: string;\n targetSiteId?: string;\n}\n\n/** Site-specific callbacks the consumer can provide. */\nexport interface AugurAuthCallbacks {\n /** Fetch user profile from the Augur API given the user's Joomla ID. */\n getUserProfile: (userId: string) => Promise<AugurUser | null>;\n /**\n * Look up or create a cart header for the authenticated user. `customerId` is always a usable\n * P21 customer id (resolved by augur-utils `resolveAddressId`): without one no lookup is made\n * (atlas#95).\n */\n cartHdrLookup?: (\n userId: string | number,\n token: string,\n contactId: string | number,\n customerId: number,\n ) => Promise<{ cartHdrUid?: number } | null>;\n}\n\n/** Derived from augur-api SDK — keeps types in sync automatically. */\nexport type AugurAuthClient = Pick<AugurAPI, \"joomla\" | \"commerce\">;\n\nexport interface CreateAuthConfigOptions {\n /** Augur SDK client. When provided, auth SDK calls are handled internally. */\n augurClient?: AugurAuthClient;\n /** Site-specific callbacks. Override internal SDK calls when custom behavior is needed. */\n callbacks?: Partial<AugurAuthCallbacks>;\n /** NextAuth secret (defaults to AUTH_SECRET env var). */\n secret?: string;\n /** Session max age in seconds (defaults to 4 hours). */\n maxAge?: number;\n /** Default customer ID when profile doesn't provide one. */\n defaultCustomerId?: string | number;\n /** Default contact ID for cart header lookups. */\n defaultContactId?: string | number;\n /** Enable NextAuth debug logging (defaults to NODE_ENV === \"development\"). */\n debug?: boolean;\n}\n\n/** Build internal callbacks that call the Augur SDK directly. */\nfunction buildInternalCallbacks(augurClient: AugurAuthClient): AugurAuthCallbacks {\n return {\n async getUserProfile(userId: string): Promise<AugurUser | null> {\n if (!userId) return null;\n const uid = parseInt(userId, 10);\n if (isNaN(uid)) return null;\n const result = await augurClient.joomla.users.doc.get(uid, {\n edgeCache: 1,\n });\n const data = result.data as Record<string, unknown>;\n if (!data) return null;\n return {\n id: String(data[\"id\"]),\n name: data[\"name\"] as string | undefined,\n username: data[\"username\"] as string,\n email: data[\"email\"] as string | undefined,\n isVerified: true,\n // Joomla holds it as text; \"\" and \"0\" are no customer, so none reaches the session (atlas#95).\n customerId: addressIdOf(data[\"customerId\"] as string | number | undefined) ?? undefined,\n contactId: data[\"contactId\"] as string | number | undefined,\n };\n },\n async cartHdrLookup(\n userId: string | number,\n _token: string,\n contactId: string | number,\n customerId: number,\n ): Promise<{ cartHdrUid?: number } | null> {\n const result = await augurClient.commerce.cartHdr.lookup.get({\n userId: Number(userId) || 0,\n // Always a usable id: lookupCartHdr looks up no cart without one (atlas#95).\n customerId,\n contactId: Number(contactId) || 0,\n });\n // The SDK returns `false` when no cart header exists.\n return result.data || null;\n },\n };\n}\n\n/** Resolve final callbacks: callback overrides take priority over internal SDK calls. */\nfunction resolveCallbacks(options: CreateAuthConfigOptions): AugurAuthCallbacks {\n const { augurClient, callbacks } = options;\n\n if (augurClient) {\n const internal = buildInternalCallbacks(augurClient);\n return {\n getUserProfile: callbacks?.getUserProfile ?? internal.getUserProfile,\n cartHdrLookup: callbacks?.cartHdrLookup ?? internal.cartHdrLookup,\n };\n }\n\n if (!callbacks?.getUserProfile) {\n throw new Error(\"createAuthConfig requires either `augurClient` or `callbacks.getUserProfile`\");\n }\n\n return {\n getUserProfile: callbacks.getUserProfile,\n cartHdrLookup: callbacks.cartHdrLookup,\n };\n}\n\n/**\n * Create a NextAuth 5 configuration for an Augur ecommerce site.\n *\n * Accepts either an `augurClient` (recommended) for zero-boilerplate auth,\n * or explicit `callbacks` for custom behavior. Callback overrides take\n * priority when both are provided.\n *\n * For cross-site auth (augur-support pattern): use an augur_info API client,\n * opt in with `createServerSite(client, { auth: { crossSite: true } })`, and\n * pass `siteId` in the signIn credentials. The API uses augur_info as the\n * header siteId and the body siteId as the target. The session stores the\n * targetSiteId and user-scoped token for later API calls. Without the opt-in\n * the `siteId` is ignored and queryAction never reads the session (atlas#105).\n *\n * @example\n * ```ts\n * // Single-site (recommended)\n * export const { handlers, signIn, signOut, auth } = NextAuth(\n * createAuthConfig({ augurClient }),\n * );\n * ```\n *\n * @example\n * ```ts\n * // Cross-site: site passes siteId in signIn credentials\n * await signIn(\"credentials\", { id, username, isVerified: \"true\", token, siteId: targetSiteId });\n * ```\n */\nasync function lookupCartHdr(\n siteCallbacks: AugurAuthCallbacks,\n profile: AugurUser,\n defaultCustomerId?: string | number,\n defaultContactId?: string | number,\n): Promise<number | undefined> {\n // The profile's customer when usable, else the default. With neither there is no cart to look\n // up: never one for customer 0 (atlas#95; commerce's cartHdrLookup refuses the same case).\n const customerId = resolveAddressId(profile.customerId, defaultCustomerId);\n const lookup = siteCallbacks.cartHdrLookup;\n if (!cartLookupRuns(lookup !== undefined, !!profile.id, customerId)) {\n return undefined;\n }\n // Both set: cartLookupRuns refused the lookup above without either.\n const cartHdr = await (lookup as NonNullable<typeof lookup>)(\n profile.id,\n \"\",\n profile.contactId ?? defaultContactId ?? \"\",\n customerId as AddressId,\n );\n return cartHdr?.cartHdrUid;\n}\n\n/** The user fields the JWT carries, each defaulted when absent (\"\", \"\", false). */\nfunction baseUserOf(token: Record<string, unknown>): {\n id: string;\n username: string;\n isVerified: boolean;\n} {\n return {\n id: (token[\"id\"] as string) || \"\",\n username: (token[\"username\"] as string) || \"\",\n isVerified: (token[\"isVerified\"] as boolean) || false,\n };\n}\n\n/** Creates a NextAuth configuration with Joomla credential provider, session callbacks, and automatic cart initialization. */\nexport function createAuthConfig(options: CreateAuthConfigOptions): NextAuthConfig {\n const {\n secret = process.env[\"AUTH_SECRET\"],\n maxAge = 4 * 60 * 60,\n defaultCustomerId,\n defaultContactId,\n debug = process.env[\"NODE_ENV\"] === \"development\",\n } = options;\n\n const siteCallbacks = resolveCallbacks(options);\n\n return {\n providers: [\n Credentials({\n name: \"Credentials\",\n credentials: {\n username: { label: \"Username\", type: \"text\" },\n password: { label: \"Password\", type: \"password\" },\n id: { label: \"ID\", type: \"text\" },\n isVerified: { label: \"Is Verified\", type: \"text\" },\n token: { label: \"Token\", type: \"text\" },\n siteId: { label: \"Site ID\", type: \"text\" },\n },\n async authorize(credentials) {\n if (!credentials) return null;\n\n const { id, isVerified, username, token, siteId } = credentials as {\n id: string;\n isVerified: string;\n username: string;\n token: string;\n siteId?: string;\n };\n\n return {\n id,\n isVerified: verifiedFlag(isVerified),\n username,\n token,\n // Kept only on a site that opted in (createServerSite's auth.crossSite), read from\n // the same store queryAction reads, at sign-in time (rules.signInTarget, atlas#105).\n targetSiteId: signInTarget(getCrossSite(), siteId),\n };\n },\n }),\n ],\n callbacks: {\n async signIn() {\n return true;\n },\n async redirect({ baseUrl }) {\n return baseUrl;\n },\n async session({ session, token }) {\n const baseUser = baseUserOf(token);\n\n const targetSiteId = token[\"targetSiteId\"] as string | undefined;\n\n const buildSession = (userOverrides = {}) => ({\n ...session,\n user: { ...session.user, ...baseUser, ...userOverrides, targetSiteId },\n token: token[\"token\"] as string | undefined,\n targetSiteId,\n });\n\n try {\n const userProfile = await siteCallbacks.getUserProfile(baseUser.id);\n if (!userProfile) return buildSession();\n\n const cartHdrUid = await lookupCartHdr(\n siteCallbacks,\n userProfile,\n defaultCustomerId,\n defaultContactId,\n );\n\n return buildSession({\n name: userProfile.name ?? session.user?.name,\n email: userProfile.email ?? session.user?.email,\n // Never \"\" or \"0\": the profile's usable id, else the default's, else none (atlas#95).\n customerId: resolveAddressId(userProfile.customerId, defaultCustomerId) ?? undefined,\n contactId: userProfile.contactId,\n cartHdrUid,\n });\n } catch {\n return buildSession();\n }\n },\n async jwt({ token, user }) {\n if (user) {\n const typedUser = user as {\n id: string;\n isVerified: boolean;\n username: string;\n token?: string;\n targetSiteId?: string;\n };\n\n return {\n ...token,\n id: typedUser.id,\n isVerified: typedUser.isVerified,\n username: typedUser.username,\n token: typedUser.token,\n targetSiteId: typedUser.targetSiteId,\n };\n }\n return token;\n },\n },\n secret,\n debug,\n session: {\n strategy: \"jwt\",\n maxAge,\n },\n trustHost: true,\n };\n}\n"],"mappings":";;;;;;;;AAIA,SAAS,aAAa,wBAAwB;AAE9C,OAAO,iBAAiB;AA2ExB,SAAS,uBAAuB,aAAkD;AAChF,SAAO;AAAA,IACL,MAAM,eAAe,QAA2C;AAC9D,UAAI,CAAC,OAAQ,QAAO;AACpB,YAAM,MAAM,SAAS,QAAQ,EAAE;AAC/B,UAAI,MAAM,GAAG,EAAG,QAAO;AACvB,YAAM,SAAS,MAAM,YAAY,OAAO,MAAM,IAAI,IAAI,KAAK;AAAA,QACzD,WAAW;AAAA,MACb,CAAC;AACD,YAAM,OAAO,OAAO;AACpB,UAAI,CAAC,KAAM,QAAO;AAClB,aAAO;AAAA,QACL,IAAI,OAAO,KAAK,IAAI,CAAC;AAAA,QACrB,MAAM,KAAK,MAAM;AAAA,QACjB,UAAU,KAAK,UAAU;AAAA,QACzB,OAAO,KAAK,OAAO;AAAA,QACnB,YAAY;AAAA;AAAA,QAEZ,YAAY,YAAY,KAAK,YAAY,CAAgC,KAAK;AAAA,QAC9E,WAAW,KAAK,WAAW;AAAA,MAC7B;AAAA,IACF;AAAA,IACA,MAAM,cACJ,QACA,QACA,WACA,YACyC;AACzC,YAAM,SAAS,MAAM,YAAY,SA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AAe,SAAS,EAAE;AAClE,cAAI,CAAC,YAAa,QAAO,aAAa;AAEtC,gBAAM,aAAa,MAAM;AAAA,YACvB;AAAA,YACA;AAAA,YACA;AAAA,YACA;AAAA,UACF;AAEA,iBAAO,aAAa;AAAA,YAClB,MAAM,YAAY,QAAQ,QAAQ,MAAM;AAAA,YACxC,OAAO,YAAY,SAAS,QAAQ,MAAM;AAAA;AAAA,YAE1C,YAAY,iBAAiB,YAAY,YAAY,iBAAiB,KAAK;AAAA,YAC3E,WAAW,YAAY;AAAA,YACvB;AAAA,UACF,CAAC;AAAA,QACH,QAAQ;AACN,iBAAO,aAAa;AAAA,QACtB;AAAA,MACF;AAAA,MACA,MAAM,IAAI,EAAE,OAAO,KAAK,GAAG;AACzB,YAAI,MAAM;AACR,gBAAM,YAAY;AAQlB,iBAAO;AAAA,YACL,GAAG;AAAA,YACH,IAAI,UAAU;AAAA,YACd,YAAY,UAAU;AAAA,YACtB,UAAU,UAAU;AAAA,YACpB,OAAO,UAAU;AAAA,YACjB,cAAc,UAAU;AAAA,UAC1B;AAAA,QACF;AACA,eAAO;AAAA,MACT;AAAA,IACF;AAAA,IACA;AAAA,IACA;AAAA,IACA,SAAS;AAAA,MACP,UAAU;AAAA,MACV;AAAA,IACF;AAAA,IACA,WAAW;AAAA,EACb;AACF;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../foundation/src/decimal.ts"],"sourcesContent":["//@ backend dafny\n\n/* Verified with LemmaScript → Dafny (`pnpm proofs`; hand lemmas in decimal.dfy; model:\n models/Platform.dfy Decimal; link: models/links/foundation-decimal.dfy): how every app\n writes an id as text. Used by services/agr-int-mcp (customer grant ids `<site>|<usersUid>`) and\n packages/joomla-auth (staff grant ids `staff-<Joomla user id>`), so both are one-to-one\n by the same proof. */\n\n/**\n * The decimal digits of `n`, exactly what `String(n)` gives for a non-negative integer\n * (tests pin the two together). Recursive so specs can use it. Injective: different numbers\n * are written differently (lemma DecimalInjective, decimal.dfy; Platform.DecimalInjective).\n *\n * @ensures |result| ≥ 1 ∧ ∀ k < |result|. result[k] ∈ '0'..'9'\n */\nexport function decimal(n: number): string {\n //@ verify\n //@ type n nat\n //@ requires n >= 0\n //@ decreases n\n //@ ensures \\result.length > 0\n //@ ensures forall(k: nat, k < \\result.length ==> (\\result.charCodeAt(k) >= 48 && \\result.charCodeAt(k) <= 57))\n const last = \"0123456789\".slice(n % 10, (n % 10) + 1);\n return n < 10 ? last : decimal(Math.floor(n / 10)) + last;\n}\n\n/**\n * Any integer as `String(n)` writes it: a minus for a negative, then `decimal`'s digits\n * (tests pin it to `String` for safe integers). An id written this way can't change a path.\n *\n * @ensures result is digits, after a \"-\" exactly when n < 0 — never empty, so an id written\n * this way can't change a path; exactly the model's Platform.IntText in the link (a contract\n * naming `decimal` couldn't be resolved by an importer, models/LSC-GAPS.md, so importers that\n * need the exact text take the link's equality as a premise)\n */\nexport function intText(n: number): string {\n //@ verify\n //@ type n int\n //@ ensures \\result.length > 0\n //@ ensures n >= 0 ==> forall(k: nat, k < \\result.length ==> (\\result.charCodeAt(k) >= 48 && \\result.charCodeAt(k) <= 57))\n //@ ensures n < 0 ==> (\\result.length > 1 && \\result.charCodeAt(0) === 45 && forall(k: nat, (1 <= k && k < \\result.length) ==> (\\result.charCodeAt(k) >= 48 && \\result.charCodeAt(k) <= 57)))\n return n < 0 ? \"-\" + decimal(-n) : decimal(n);\n}\n"],"mappings":";AAeO,SAAS,QAAQ,GAAmB;AAOzC,QAAM,OAAO,aAAa,MAAM,IAAI,IAAK,IAAI,KAAM,CAAC;AACpD,SAAO,IAAI,KAAK,OAAO,QAAQ,KAAK,MAAM,IAAI,EAAE,CAAC,IAAI;AACvD;","names":[]}
@@ -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 type MethodArgs,\n type MethodData,\n type MethodPath,\n} from \"@simpleapps-com/augur-core\";\nimport {\n isSiteId,\n type AugurAPI,\n type BaseResponse,\n type CallOptions,\n} 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 * ## Typed by path (atlas#103)\n *\n * The path is one of the SDK's method paths, the arguments that method's own, the result the\n * envelope's data (model AugurQueryTypes: `IsTypedPath`, `TypedArgs`, `TypedResult`), so an\n * unknown path or arguments that no longer match an upgraded SDK fail `tsc` instead of a live\n * request. The runtime is unchanged: the allowlist still checks every path.\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<P extends MethodPath<AugurAPI>>(\n methodPath: P,\n ...args: MethodArgs<AugurAPI, P>\n): Promise<MethodData<AugurAPI, P>> {\n // The value is what unwrapBaseResponse gives; its type is the model's TypedResult\n return unwrapBaseResponse(await callSdk(methodPath, args)) as MethodData<AugurAPI, P>;\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<P extends MethodPath<AugurAPI>>(\n options: CallOptions,\n methodPath: P,\n ...args: MethodArgs<AugurAPI, P>\n): Promise<MethodData<AugurAPI, P>> {\n // Typed as queryAction (atlas#103); the value is what unwrapBaseResponse gives\n return unwrapBaseResponse(await callSdk(methodPath, args, options)) as MethodData<AugurAPI, P>;\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,OAIK;AACP;AAAA,EACE;AAAA,OAIK;AAaP,IAAM,gBAAgB;AAYtB,IA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