@simpleapps-com/augur-server 2.3.1 → 2.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,21 +1,171 @@
1
+ declare const SessionSiteIdBrand: unique symbol;
2
+ declare const SessionBearerTokenBrand: unique symbol;
3
+ declare const SessionCredentialsBrand: unique symbol;
4
+ declare const ApprovedMethodPathBrand: unique symbol;
5
+ /**
6
+ * Site identifier extracted from a validated Auth.js session JWT cookie.
7
+ *
8
+ * Intended to be minted only by `getSessionCredentials` in query-action.ts.
9
+ *
10
+ * Brand strength: code-review signal, not type-system enforcement. TypeScript
11
+ * allows `value as SessionSiteId` casts, so audit `as SessionSiteId` usages
12
+ * to catch unintended mints — there should be exactly one, at the JWT mint
13
+ * point.
14
+ */
15
+ type SessionSiteId = string & {
16
+ readonly [SessionSiteIdBrand]: true;
17
+ };
18
+ /**
19
+ * Bearer token extracted from a validated Auth.js session JWT cookie.
20
+ * Same intended-mint and brand-strength caveat as {@link SessionSiteId}.
21
+ */
22
+ type SessionBearerToken = string & {
23
+ readonly [SessionBearerTokenBrand]: true;
24
+ };
25
+ /**
26
+ * Paired session credentials. Bundles `siteId` and `token` from the same
27
+ * validated session into one value so downstream functions can accept the
28
+ * pair as a unit, instead of two separate parameters that callers might
29
+ * accidentally mix across sessions.
30
+ *
31
+ * Intended to be minted only by `getSessionCredentials` in query-action.ts,
32
+ * which performs the cross-check that the bearer's `client_id` siteId
33
+ * matches `targetSiteId`. Anything that holds a `SessionCredentials` *was*
34
+ * cross-checked at mint time — provided the value came through that mint
35
+ * and not via a cast.
36
+ *
37
+ * Brand strength: same code-review signal as the field brands. `value as
38
+ * SessionCredentials` compiles. Audit `as SessionCredentials` usages — there
39
+ * should be exactly one, in `getSessionCredentials`.
40
+ */
41
+ type SessionCredentials = {
42
+ readonly siteId: SessionSiteId;
43
+ readonly token: SessionBearerToken;
44
+ readonly [SessionCredentialsBrand]: true;
45
+ };
46
+ /**
47
+ * SDK method path validated against the registered allowlist.
48
+ *
49
+ * Intended to be minted only by `parseMethodPath` below. Functions that walk
50
+ * the path into the SDK client (notably `resolveMethod`) demand this type
51
+ * so that an unvalidated string flowing into the walker is a compile error
52
+ * for code that respects the convention.
53
+ *
54
+ * Brand strength: code-review signal. `value as ApprovedMethodPath` compiles.
55
+ * Audit `as ApprovedMethodPath` usages — there should be one, in
56
+ * `parseMethodPath`.
57
+ *
58
+ * Scope of validation: this is a *site-level surface restriction*, not a
59
+ * security boundary. augur-api is the auth authority; the allowlist limits
60
+ * what the application's proxy will forward to the SDK, not what tokens are
61
+ * permitted to do. Useful for narrowing same-origin attack surface (XSS,
62
+ * malicious bundled deps); not a substitute for API-level authorization.
63
+ */
64
+ type ApprovedMethodPath = string & {
65
+ readonly [ApprovedMethodPathBrand]: true;
66
+ };
67
+
1
68
  /**
2
69
  * Resolve session credentials from the Auth.js JWT cookie.
3
- * Returns the targetSiteId and token if present, or null.
4
- * Falls back to null on any error (no cookie, no secret, not in request context).
70
+ *
71
+ * Trust-boundary mint point: this is the only function in the package that
72
+ * produces {@link SessionCredentials} values. Bytes from a cookie become
73
+ * typed, paired credentials here and only here. The branded pair cannot be
74
+ * constructed elsewhere, so any function consuming `SessionCredentials` is
75
+ * guaranteed to receive a JWT-validated, internally-consistent session.
76
+ *
77
+ * Returns null when:
78
+ * - no AUTH_SECRET is configured
79
+ * - next-auth/jwt, next/headers, or jose cannot be loaded
80
+ * - no session cookie is present
81
+ * - the JWT decode fails or returns null
82
+ * - the decoded payload is missing `targetSiteId` or `token`, or either is
83
+ * not a non-empty string (refuse to mint partial credentials)
84
+ * - the bearer token's `client_id` siteId portion does not match
85
+ * `targetSiteId` (defense-in-depth: refuses internally inconsistent sessions
86
+ * before they reach the augur-api authority check)
87
+ *
88
+ * ## Verified preconditions for `result = some c`
89
+ *
90
+ * AUTH_SECRET configured
91
+ * next-auth/jwt, next/headers, jose all loadable
92
+ * session cookie present and decodable with the secret
93
+ * typeof jwt.targetSiteId === "string" ∧ jwt.targetSiteId.length > 0
94
+ * typeof jwt.token === "string" ∧ jwt.token.length > 0
95
+ * bearerClientSiteId(jwt.token) = some jwt.targetSiteId
96
+ *
97
+ * Lean equivalent: each clause becomes a `requires` on the function;
98
+ * `result = none` is the disjunction of any failing.
99
+ * F* equivalent: refinement on the option payload covering the
100
+ * conjunction of these clauses.
101
+ *
102
+ * The bearer cross-check (`bearerClientSiteId(jwt.token) = some jwt.targetSiteId`)
103
+ * is the substantive runtime invariant: it refuses sessions where the bearer's
104
+ * encoded `client_id` siteId disagrees with the session's targetSiteId,
105
+ * catching internal-inconsistency bugs before the call reaches augur-api.
106
+ *
107
+ * ## By construction (not independently verified)
108
+ *
109
+ * c.siteId === jwt.targetSiteId (assigned, not checked)
110
+ * c.token === jwt.token (assigned, not checked)
111
+ *
112
+ * ## Brand strength
113
+ *
114
+ * `SessionCredentials` is a TS-level brand: there is no runtime tag on the
115
+ * value. `value as SessionCredentials` casts compile, so the brand is a
116
+ * code-review signal (audit `as SessionCredentials` usages — there should be
117
+ * exactly one, in this function), not a hard type-system gate.
5
118
  */
6
- declare function getSessionCredentials(): Promise<{
7
- siteId: string;
8
- token: string;
9
- } | null>;
119
+ declare function getSessionCredentials(): Promise<SessionCredentials | null>;
10
120
  /**
11
121
  * Unwrap SDK BaseResponse if the result matches the standard shape.
12
122
  * The SDK wraps all responses in `{ data: T, status: number, message: string }`.
13
123
  * SiteActions previously unwrapped this; queryAction now does it automatically
14
124
  * so consumers receive `T` directly.
125
+ *
126
+ * ## Property
127
+ *
128
+ * ∀ raw. result(raw) ∈ {raw.data, raw}
129
+ * BaseResponse?(raw) ⟺ raw is non-null object ∧ "data" ∈ keys(raw)
130
+ * ∧ "status" ∈ keys(raw)
131
+ * ∧ "message" ∈ keys(raw)
132
+ *
133
+ * Two possible outcomes; never throws, never reshapes. The structural
134
+ * test checks key presence only — it does NOT validate field types or
135
+ * values. Assumes upstream code does not produce `{data, status, message}`
136
+ * shapes that aren't actually BaseResponses; if it does, those will be
137
+ * incorrectly unwrapped (false positive). In practice the augur-api SDK
138
+ * is the only producer of this shape on the server path.
139
+ *
140
+ * This property is what lets queryAction call this exactly once per
141
+ * request without double-unwrap risk: applying unwrapBaseResponse to
142
+ * an already-unwrapped value is a no-op (the second branch of the
143
+ * property fires).
144
+ *
145
+ * ## SDK envelope coupling — forward-compat additive, brittle to renames
146
+ *
147
+ * The structural test checks for `data ∧ status ∧ message`. Three implications:
148
+ *
149
+ * - Additive SDK changes (envelope grows new fields, e.g. `pagination`,
150
+ * `requestId`) are forward-compatible — the predicate still matches and
151
+ * this function still unwraps correctly.
152
+ * - Renames are brittle: if the augur-api SDK ever changes the envelope
153
+ * to `{ result, status, message }` (or any rename of `data`), this
154
+ * function silently STOPS unwrapping. Consumers receive the envelope
155
+ * as `T` and downstream code breaks far from the cause. The fix is
156
+ * mechanical (update the predicate) but the failure mode is silent —
157
+ * audit this function whenever the SDK envelope contract changes.
158
+ * - This predicate MUST stay in sync with augur-api's BaseResponse type.
159
+ * Treat the envelope shape as a coupled contract, not as inferred behaviour.
15
160
  */
16
161
  declare function unwrapBaseResponse(raw: unknown): unknown;
17
- /** Resolve a dot-separated method path on an object, returning the leaf function. */
18
- declare function resolveMethod(client: unknown, methodPath: string): (...a: unknown[]) => Promise<unknown>;
162
+ /**
163
+ * Resolve a dot-separated method path on an object, returning the leaf function.
164
+ *
165
+ * Demands {@link ApprovedMethodPath} so callers must have run the path through
166
+ * `parseMethodPath` first — passing an unvalidated string is a compile error.
167
+ */
168
+ declare function resolveMethod(client: unknown, methodPath: ApprovedMethodPath): (...a: unknown[]) => Promise<unknown>;
19
169
  /**
20
170
  * Generic server action that routes any SDK method call through the raw
21
171
  * SDK client with optional Redis caching. Used internally by
@@ -34,6 +184,97 @@ declare function resolveMethod(client: unknown, methodPath: string): (...a: unkn
34
184
  * SDK responses wrapped in BaseResponse are automatically unwrapped --
35
185
  * consumers receive `T` instead of `{ data: T, status, message }`.
36
186
  *
187
+ * This is the chokepoint: every B2B site without a client-side SDK
188
+ * routes EVERY data access through this one function. The invariants
189
+ * below are load-bearing across every site, every request, every user.
190
+ *
191
+ * ## Preconditions (enforced at runtime via thrown Error)
192
+ *
193
+ * parseMethodPath(methodPath) ≠ null
194
+ * resolveClient().client ≠ null
195
+ *
196
+ * First clause: methodPath is a non-empty string AND — if an allowlist
197
+ * has been registered via `registerAllowedMethodPaths` — methodPath is
198
+ * in the allowlist. Assumes the site opted into surface restriction
199
+ * when narrower-than-augur-api authority is desired; otherwise any
200
+ * non-empty string passes (transparent forwarder default).
201
+ *
202
+ * Second clause: createServerSite() ran during bootstrap OR
203
+ * AUGUR_SITE_ID + AUGUR_JWT env vars are set so the registry can
204
+ * auto-init. Assumes the caller has bootstrapped one of the two paths.
205
+ *
206
+ * Lean equivalent: `requires path : ApprovedMethodPath ∧ client : SDKClient`.
207
+ *
208
+ * ## Cross-tenant cache-prefix invariant (load-bearing)
209
+ *
210
+ * resolution.kind = "scoped" ⟹ cachePrefix = `${resolution.credentials.siteId}:`
211
+ *
212
+ * On the scoped path the cache prefix is derived structurally from the
213
+ * same `SessionCredentials` value that minted the scoped client — they
214
+ * cannot be sourced separately. This makes "siteId from session A
215
+ * combined with token from session B" or "siteId X with cache prefix Y"
216
+ * unrepresentable here. Assumes `getSessionCredentials` performed the
217
+ * bearer/session siteId cross-check at mint time; see the brand-strength
218
+ * caveat on `SessionCredentials`.
219
+ *
220
+ * A regression here would silently leak cached data across tenants.
221
+ * The structural derivation is the only thing standing between the
222
+ * request and that leak — do not reintroduce a separate `cachePrefix`
223
+ * parameter or compute it from anything other than `resolution.credentials`.
224
+ *
225
+ * ### Sibling assumption — bearer is NOT in the cache key
226
+ *
227
+ * The cross-tenant invariant covers cross-SITE leaks. It does NOT cover
228
+ * intra-site cross-USER leaks: the cache key is `(siteId, methodPath, args)`
229
+ * and the bearer token is intentionally absent. Two users with different
230
+ * bearers on the same site share cached data for cacheable namespaces.
231
+ *
232
+ * This is a deliberate design choice. The assumption is:
233
+ *
234
+ * ∀ namespace ∉ NO_CACHE_PATHS, ∀ siteId, ∀ args.
235
+ * augur-api(bearer_A, siteId, args) = augur-api(bearer_B, siteId, args)
236
+ *
237
+ * i.e. for cacheable namespaces, augur-api's response is bearer-independent
238
+ * within a site. augur-api remains the auth authority; `NO_CACHE_PATHS`
239
+ * (commerce.*, payments.*) is the carve-out for namespaces whose responses
240
+ * ARE bearer-coupled. If a future namespace produces bearer-dependent
241
+ * responses (e.g. user-specific permissions affecting query results), it
242
+ * MUST be added to `NO_CACHE_PATHS` or the bearer MUST become part of the
243
+ * cache key — otherwise this assumption silently produces a permission leak.
244
+ *
245
+ * ## No-edge-cache defense-in-depth (load-bearing)
246
+ *
247
+ * ∀ a ∈ safeArgs. methodPath ∈ NO_CACHE_PATHS ⟹ "edgeCache" ∉ keys(a)
248
+ *
249
+ * `stripEdgeCacheForNoCachePaths` removes the `edgeCache` key from every
250
+ * first-level object arg when methodPath belongs to a no-cache namespace
251
+ * (currently `commerce.*`, `payments.*`). The augur-api SDK transforms
252
+ * `edgeCache` into a Cloudflare `cacheSiteId{N}` query param; removing
253
+ * it here guarantees no CDN edge-caching of identity-bound responses
254
+ * even if a caller passed one explicitly or a legacy factory injected
255
+ * one. Assumes `NO_CACHE_PATHS` enumerates every namespace whose
256
+ * responses must not cross identity boundaries.
257
+ *
258
+ * ## Postcondition — BaseResponse pass-through (exactly-once unwrap)
259
+ *
260
+ * result = unwrapBaseResponse(raw)
261
+ * = raw.data when raw is { data, status, message }
262
+ * = raw otherwise
263
+ *
264
+ * Consumers receive `T` directly when the SDK returns
265
+ * `{ data: T, status, message }`, and the original value otherwise.
266
+ * Assumes upstream cache wrappers do NOT themselves unwrap — they
267
+ * return whatever the SDK returned, so unwrapping happens exactly
268
+ * once, here. Double-unwrap (caller + queryAction) would silently
269
+ * strip a layer of legitimate `{data, status, message}` user data
270
+ * when that shape happens to round-trip through the API.
271
+ *
272
+ * ## Effects
273
+ *
274
+ * @mutates Redis (write-through on read methods when a wrapper is registered)
275
+ * @io augur-api SDK (network request)
276
+ * @throws Error when the allowlist gate fails or no client is initialised
277
+ *
37
278
  * @param methodPath Dot-separated SDK method path (e.g. "items.invMast.doc.get")
38
279
  * @param args Arguments to pass to the resolved method
39
280
  * @returns The unwrapped result from the SDK method (possibly from Redis cache)
@@ -5,8 +5,8 @@ import {
5
5
  resetSessionImports,
6
6
  resolveMethod,
7
7
  unwrapBaseResponse
8
- } from "./chunk-ZUJZDRTP.js";
9
- import "./chunk-HPQQYROJ.js";
8
+ } from "./chunk-2NL4QKJN.js";
9
+ import "./chunk-ALTIINP6.js";
10
10
  import "./chunk-DGUM43GV.js";
11
11
  export {
12
12
  getSessionCredentials,
package/dist/query.d.ts CHANGED
@@ -11,7 +11,11 @@ interface QueryOptionsConfig<TParams, TData> {
11
11
  enabledFn?: (params: TParams) => boolean;
12
12
  /** Custom stale time in milliseconds (default: SEMI_STATIC) */
13
13
  staleTime?: number;
14
- /** Custom garbage collection time in milliseconds (default: SEMI_STATIC) */
14
+ /**
15
+ * Custom garbage collection time in milliseconds (default: SEMI_STATIC).
16
+ * Browser only: on the server the returned gcTime is always `Infinity`
17
+ * (no GC timer), so the per-request cache is freed with the request (#481).
18
+ */
15
19
  gcTime?: number;
16
20
  /** Key to exclude from query key generation */
17
21
  excludeFromKey?: keyof TParams;
package/dist/query.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  createQueryOptions,
3
3
  createSuspenseQueryOptions
4
- } from "./chunk-TQP67TGL.js";
4
+ } from "./chunk-PIYHMA6F.js";
5
5
  import "./chunk-DGUM43GV.js";
6
6
  export {
7
7
  createQueryOptions,
package/dist/site.js CHANGED
@@ -5,14 +5,14 @@ import {
5
5
  createSiteActions,
6
6
  registerSiteActions,
7
7
  withServerCache
8
- } from "./chunk-WOHZDFJF.js";
8
+ } from "./chunk-26WZBC4F.js";
9
9
  import {
10
10
  registerAuthSecret,
11
11
  registerClientFactory,
12
12
  registerScopedCacheWrapper,
13
13
  registerSdkCallWrapper,
14
14
  registerSdkClient
15
- } from "./chunk-HPQQYROJ.js";
15
+ } from "./chunk-ALTIINP6.js";
16
16
  import "./chunk-DGUM43GV.js";
17
17
 
18
18
  // src/server-site.ts
package/dist/testing.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  clearSiteActions
3
- } from "./chunk-WOHZDFJF.js";
4
- import "./chunk-HPQQYROJ.js";
3
+ } from "./chunk-26WZBC4F.js";
4
+ import "./chunk-ALTIINP6.js";
5
5
  import "./chunk-DGUM43GV.js";
6
6
 
7
7
  // src/testing.ts
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@simpleapps-com/augur-server",
3
- "version": "2.3.1",
3
+ "version": "2.4.0",
4
4
  "description": "Server-side utilities for Augur ecommerce sites (Redis caching, SDK helpers, auth)",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -58,14 +58,15 @@
58
58
  "llms.txt"
59
59
  ],
60
60
  "dependencies": {
61
- "@simpleapps-com/augur-core": "2.3.1",
62
- "@simpleapps-com/augur-hooks": "2.3.1",
63
- "@simpleapps-com/augur-utils": "2.3.1"
61
+ "@simpleapps-com/augur-core": "2.4.0",
62
+ "@simpleapps-com/augur-hooks": "2.4.0",
63
+ "@simpleapps-com/augur-utils": "2.4.0"
64
64
  },
65
65
  "peerDependencies": {
66
- "@simpleapps-com/augur-api": "^2026.4.6",
66
+ "@simpleapps-com/augur-api": "^2026.4.7",
67
67
  "@tanstack/react-query": "^5.80.0",
68
68
  "ioredis": "^5.9.0",
69
+ "jose": "^5.0.0 || ^6.0.0",
69
70
  "next": "^16.1.6",
70
71
  "next-auth": ">=5.0.0-beta.30",
71
72
  "react": "^19.0.0"
@@ -74,6 +75,9 @@
74
75
  "ioredis": {
75
76
  "optional": true
76
77
  },
78
+ "jose": {
79
+ "optional": true
80
+ },
77
81
  "next-auth": {
78
82
  "optional": true
79
83
  }
@@ -84,11 +88,12 @@
84
88
  "@types/react": "^19.0.0",
85
89
  "@vitest/coverage-v8": "^3.2.4",
86
90
  "ioredis": "^5.9.0",
91
+ "jose": "^5.0.0",
87
92
  "react": "^19.0.0",
88
93
  "tsup": "^8.5.0",
89
94
  "vitest": "^3.2.0",
90
95
  "@augur-packages/tsconfig": "0.0.0",
91
- "@simpleapps-com/augur-hooks": "2.3.1"
96
+ "@simpleapps-com/augur-hooks": "2.4.0"
92
97
  },
93
98
  "scripts": {
94
99
  "build": "tsup",
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/sdk-client-store.ts"],"sourcesContent":["/**\n * Lightweight getter/setter for the raw SDK client instance, cache wrapper,\n * auth secret, client factory, and scoped client cache.\n *\n * queryAction resolves method paths on the SDK client directly (not on\n * SiteActions). This ensures the proxy pattern works end-to-end: the\n * proxy generates SDK namespace paths (e.g. \"pricing.priceEngine.get\")\n * which match the SDK client structure.\n *\n * The cache wrapper is a function registered by createServerSite() that\n * wraps SDK calls with Redis caching. It captures withServerCache + config\n * in its closure, so queryAction can use it without importing heavy deps.\n *\n * The auth secret, client factory, and scoped cache wrapper support\n * per-request session credentials for multi-tenant apps. queryAction\n * decodes the JWT from request cookies and creates scoped SDK clients\n * when the session contains a targetSiteId + token.\n *\n * This module has ZERO imports from actions/site, cache/, or any factory.\n * Same isolation constraints as site-actions-store.ts.\n */\n\n/** Function that wraps an SDK call with server-side caching. */\nexport type SdkCallWrapper = (\n methodPath: string,\n sdkCall: () => Promise<unknown>,\n ...keyArgs: unknown[]\n) => Promise<unknown>;\n\n/** Function that wraps an SDK call with server-side caching using a specific prefix. */\nexport type ScopedCacheWrapper = (\n prefix: string,\n methodPath: string,\n sdkCall: () => Promise<unknown>,\n ...keyArgs: unknown[]\n) => Promise<unknown>;\n\n/** Function that creates a scoped SDK client with different credentials. */\nexport type ClientFactory = (siteId: string, bearerToken: string) => unknown;\n\nconst g = globalThis as unknown as {\n __augur_sdk_client?: unknown;\n __augur_sdk_call_wrapper?: SdkCallWrapper;\n __augur_auth_secret?: string;\n __augur_client_factory?: ClientFactory;\n __augur_scoped_cache_wrapper?: ScopedCacheWrapper;\n};\n\nlet _cachedClient: unknown = null;\nlet _cachedWrapper: SdkCallWrapper | null = null;\nlet _cachedAuthSecret: string | null = null;\nlet _cachedClientFactory: ClientFactory | null = null;\nlet _cachedScopedCacheWrapper: ScopedCacheWrapper | null = null;\nlet _scopedClient: { key: string; client: unknown } | null = null;\n\n/** Register the raw SDK client instance. Called by createServerSite(). */\nexport function registerSdkClient(client: unknown): void {\n _cachedClient = client;\n g.__augur_sdk_client = client;\n}\n\n/** Returns the registered SDK client, or null if not yet registered. */\nexport function getSdkClientOrNull(): unknown {\n const client = g.__augur_sdk_client ?? _cachedClient;\n if (client) {\n if (!g.__augur_sdk_client) {\n g.__augur_sdk_client = client;\n }\n return client;\n }\n return null;\n}\n\n/**\n * Register a cache wrapper for SDK calls. Called by createServerSite().\n * The wrapper captures withServerCache + config in its closure so that\n * queryAction can use Redis caching without importing heavy deps.\n */\nexport function registerSdkCallWrapper(wrapper: SdkCallWrapper): void {\n _cachedWrapper = wrapper;\n g.__augur_sdk_call_wrapper = wrapper;\n}\n\n/** Returns the registered cache wrapper, or null if not registered. */\nexport function getSdkCallWrapper(): SdkCallWrapper | null {\n return g.__augur_sdk_call_wrapper ?? _cachedWrapper ?? null;\n}\n\n/** Register the auth secret for JWT decoding. Called by createServerSite(). */\nexport function registerAuthSecret(secret: string): void {\n _cachedAuthSecret = secret;\n g.__augur_auth_secret = secret;\n}\n\n/** Returns the registered auth secret, or null if not registered. */\nexport function getAuthSecret(): string | null {\n return g.__augur_auth_secret ?? _cachedAuthSecret ?? null;\n}\n\n/** Register a factory that creates scoped SDK clients. Called by createServerSite(). */\nexport function registerClientFactory(factory: ClientFactory): void {\n _cachedClientFactory = factory;\n g.__augur_client_factory = factory;\n}\n\n/** Returns the registered client factory, or null if not registered. */\nexport function getClientFactory(): ClientFactory | null {\n return g.__augur_client_factory ?? _cachedClientFactory ?? null;\n}\n\n/** Register a scoped cache wrapper that accepts a prefix. Called by createServerSite(). */\nexport function registerScopedCacheWrapper(wrapper: ScopedCacheWrapper): void {\n _cachedScopedCacheWrapper = wrapper;\n g.__augur_scoped_cache_wrapper = wrapper;\n}\n\n/** Returns the registered scoped cache wrapper, or null if not registered. */\nexport function getScopedCacheWrapper(): ScopedCacheWrapper | null {\n return g.__augur_scoped_cache_wrapper ?? _cachedScopedCacheWrapper ?? null;\n}\n\n/**\n * Returns a cached scoped client for the given credentials, or creates one\n * via the registered factory. Caches the last (siteId, token) pair so that\n * multiple queryAction calls in the same request reuse the same client.\n */\nexport function getOrCreateScopedClient(siteId: string, bearerToken: string): unknown {\n const key = `${siteId}\\0${bearerToken}`;\n if (_scopedClient?.key === key) return _scopedClient.client;\n\n const factory = g.__augur_client_factory ?? _cachedClientFactory;\n if (!factory) return null;\n\n const client = factory(siteId, bearerToken);\n _scopedClient = { key, client };\n return client;\n}\n\n/** Clears the registered SDK client, wrapper, and session stores. Used in tests only. @internal */\nexport function clearSdkClient(): void {\n _cachedClient = null;\n _cachedWrapper = null;\n _cachedAuthSecret = null;\n _cachedClientFactory = null;\n _cachedScopedCacheWrapper = null;\n _scopedClient = null;\n g.__augur_sdk_client = undefined;\n g.__augur_sdk_call_wrapper = undefined;\n g.__augur_auth_secret = undefined;\n g.__augur_client_factory = undefined;\n g.__augur_scoped_cache_wrapper = undefined;\n}\n"],"mappings":";AAwCA,IAAM,IAAI;AAQV,IAAI,gBAAyB;AAC7B,IAAI,iBAAwC;AAC5C,IAAI,oBAAmC;AACvC,IAAI,uBAA6C;AACjD,IAAI,4BAAuD;AAC3D,IAAI,gBAAyD;AAGtD,SAAS,kBAAkB,QAAuB;AACvD,kBAAgB;AAChB,IAAE,qBAAqB;AACzB;AAGO,SAAS,qBAA8B;AAC5C,QAAM,SAAS,EAAE,sBAAsB;AACvC,MAAI,QAAQ;AACV,QAAI,CAAC,EAAE,oBAAoB;AACzB,QAAE,qBAAqB;AAAA,IACzB;AACA,WAAO;AAAA,EACT;AACA,SAAO;AACT;AAOO,SAAS,uBAAuB,SAA+B;AACpE,mBAAiB;AACjB,IAAE,2BAA2B;AAC/B;AAGO,SAAS,oBAA2C;AACzD,SAAO,EAAE,4BAA4B,kBAAkB;AACzD;AAGO,SAAS,mBAAmB,QAAsB;AACvD,sBAAoB;AACpB,IAAE,sBAAsB;AAC1B;AAGO,SAAS,gBAA+B;AAC7C,SAAO,EAAE,uBAAuB,qBAAqB;AACvD;AAGO,SAAS,sBAAsB,SAA8B;AAClE,yBAAuB;AACvB,IAAE,yBAAyB;AAC7B;AAQO,SAAS,2BAA2B,SAAmC;AAC5E,8BAA4B;AAC5B,IAAE,+BAA+B;AACnC;AAGO,SAAS,wBAAmD;AACjE,SAAO,EAAE,gCAAgC,6BAA6B;AACxE;AAOO,SAAS,wBAAwB,QAAgB,aAA8B;AACpF,QAAM,MAAM,GAAG,MAAM,KAAK,WAAW;AACrC,MAAI,eAAe,QAAQ,IAAK,QAAO,cAAc;AAErD,QAAM,UAAU,EAAE,0BAA0B;AAC5C,MAAI,CAAC,QAAS,QAAO;AAErB,QAAM,SAAS,QAAQ,QAAQ,WAAW;AAC1C,kBAAgB,EAAE,KAAK,OAAO;AAC9B,SAAO;AACT;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/query-options-helper.ts"],"sourcesContent":["import type { UseQueryOptions, UseSuspenseQueryOptions } from \"@tanstack/react-query\";\nimport { CACHE_CONFIG } from \"@simpleapps-com/augur-utils\";\n\nexport interface QueryOptionsConfig<TParams, TData> {\n /** Base query key (e.g., \"customer-orders\") */\n baseKey: string;\n /** Parameters object */\n params: TParams;\n /** Function that returns the data */\n queryFn: (params: TParams) => Promise<TData>;\n /** Function to determine if query should be enabled */\n enabledFn?: (params: TParams) => boolean;\n /** Custom stale time in milliseconds (default: SEMI_STATIC) */\n staleTime?: number;\n /** Custom garbage collection time in milliseconds (default: SEMI_STATIC) */\n gcTime?: number;\n /** Key to exclude from query key generation */\n excludeFromKey?: keyof TParams;\n}\n\n/**\n * Creates useQuery options with consistent key generation.\n * Filters out undefined/null/empty params from the query key.\n */\nexport const createQueryOptions = <TParams extends Record<string, unknown>, TData>({\n baseKey,\n params,\n queryFn,\n enabledFn,\n staleTime = CACHE_CONFIG.SEMI_STATIC.staleTime,\n gcTime = CACHE_CONFIG.SEMI_STATIC.gcTime,\n excludeFromKey,\n}: QueryOptionsConfig<TParams, TData>): UseQueryOptions<TData> => {\n const paramEntries = Object.entries(params)\n .filter(([key, value]) => {\n if (excludeFromKey && key === excludeFromKey) return false;\n return value !== undefined && value !== null && value !== \"\";\n })\n .map(([key, value]) => `${key}:${value}`)\n .sort();\n\n const queryKey = [baseKey, ...paramEntries];\n\n return {\n queryKey,\n queryFn: () => queryFn(params),\n enabled: enabledFn ? enabledFn(params) : true,\n staleTime,\n gcTime,\n };\n};\n\n/**\n * Creates useSuspenseQuery options with consistent key generation.\n * Same as createQueryOptions but without enabledFn (suspense queries\n * cannot be disabled).\n */\nexport const createSuspenseQueryOptions = <TParams extends Record<string, unknown>, TData>({\n baseKey,\n params,\n queryFn,\n staleTime = CACHE_CONFIG.SEMI_STATIC.staleTime,\n gcTime = CACHE_CONFIG.SEMI_STATIC.gcTime,\n excludeFromKey,\n}: Omit<QueryOptionsConfig<TParams, TData>, \"enabledFn\">): UseSuspenseQueryOptions<TData> => {\n const paramEntries = Object.entries(params)\n .filter(([key, value]) => {\n if (excludeFromKey && key === excludeFromKey) return false;\n return value !== undefined && value !== null && value !== \"\";\n })\n .map(([key, value]) => `${key}:${value}`)\n .sort();\n\n const queryKey = [baseKey, ...paramEntries];\n\n return {\n queryKey,\n queryFn: () => queryFn(params),\n staleTime,\n gcTime,\n };\n};\n"],"mappings":";AACA,SAAS,oBAAoB;AAuBtB,IAAM,qBAAqB,CAAiD;AAAA,EACjF;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,YAAY,aAAa,YAAY;AAAA,EACrC,SAAS,aAAa,YAAY;AAAA,EAClC;AACF,MAAkE;AAChE,QAAM,eAAe,OAAO,QAAQ,MAAM,EACvC,OAAO,CAAC,CAAC,KAAK,KAAK,MAAM;AACxB,QAAI,kBAAkB,QAAQ,eAAgB,QAAO;AACrD,WAAO,UAAU,UAAa,UAAU,QAAQ,UAAU;AAAA,EAC5D,CAAC,EACA,IAAI,CAAC,CAAC,KAAK,KAAK,MAAM,GAAG,GAAG,IAAI,KAAK,EAAE,EACvC,KAAK;AAER,QAAM,WAAW,CAAC,SAAS,GAAG,YAAY;AAE1C,SAAO;AAAA,IACL;AAAA,IACA,SAAS,MAAM,QAAQ,MAAM;AAAA,IAC7B,SAAS,YAAY,UAAU,MAAM,IAAI;AAAA,IACzC;AAAA,IACA;AAAA,EACF;AACF;AAOO,IAAM,6BAA6B,CAAiD;AAAA,EACzF;AAAA,EACA;AAAA,EACA;AAAA,EACA,YAAY,aAAa,YAAY;AAAA,EACrC,SAAS,aAAa,YAAY;AAAA,EAClC;AACF,MAA6F;AAC3F,QAAM,eAAe,OAAO,QAAQ,MAAM,EACvC,OAAO,CAAC,CAAC,KAAK,KAAK,MAAM;AACxB,QAAI,kBAAkB,QAAQ,eAAgB,QAAO;AACrD,WAAO,UAAU,UAAa,UAAU,QAAQ,UAAU;AAAA,EAC5D,CAAC,EACA,IAAI,CAAC,CAAC,KAAK,KAAK,MAAM,GAAG,GAAG,IAAI,KAAK,EAAE,EACvC,KAAK;AAER,QAAM,WAAW,CAAC,SAAS,GAAG,YAAY;AAE1C,SAAO;AAAA,IACL;AAAA,IACA,SAAS,MAAM,QAAQ,MAAM;AAAA,IAC7B;AAAA,IACA;AAAA,EACF;AACF;","names":[]}