@shop-on/theme-server 0.9.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (168) hide show
  1. package/dist/account-state.js +1 -2
  2. package/dist/account.d.ts +1 -3
  3. package/dist/account.js +1 -3
  4. package/dist/activity.d.ts +1 -3
  5. package/dist/activity.js +1 -2
  6. package/dist/analytics-proxy.d.ts +8 -14
  7. package/dist/analytics-proxy.js +111 -28
  8. package/dist/analytics-script-proxy.d.ts +1 -5
  9. package/dist/analytics-script-proxy.js +4 -14
  10. package/dist/api-contract/src/addresses.js +32 -0
  11. package/dist/api-contract/src/areas.js +49 -0
  12. package/dist/api-contract/src/custom-data.d.ts +31 -0
  13. package/dist/api-contract/src/custom-data.js +303 -0
  14. package/dist/api-contract/src/ids.js +110 -0
  15. package/dist/api-contract/src/image.js +65 -0
  16. package/dist/api-contract/src/limits.js +44 -0
  17. package/dist/api-contract/src/media.js +13 -0
  18. package/dist/api-contract/src/pickup.js +11 -0
  19. package/dist/api-contract/src/recommendations.js +4 -0
  20. package/dist/api-contract/src/shops.js +27 -0
  21. package/dist/api-contract/src/storefront/analytics.d.ts +100 -0
  22. package/dist/api-contract/src/storefront/analytics.js +138 -0
  23. package/dist/api-contract/src/storefront/areas.d.ts +2 -0
  24. package/dist/api-contract/src/storefront/cart.d.ts +132 -0
  25. package/dist/api-contract/src/storefront/cart.js +248 -0
  26. package/dist/api-contract/src/storefront/catalog.d.ts +3 -0
  27. package/dist/api-contract/src/storefront/checkout-analytics.d.ts +2 -0
  28. package/dist/api-contract/src/storefront/checkout.d.ts +2 -0
  29. package/dist/api-contract/src/storefront/checkout.js +624 -0
  30. package/dist/api-contract/src/storefront/client.d.ts +3 -0
  31. package/dist/api-contract/src/storefront/client.js +6 -0
  32. package/dist/api-contract/src/storefront/content.d.ts +3 -0
  33. package/dist/api-contract/src/storefront/custom-data.d.ts +2 -0
  34. package/dist/api-contract/src/storefront/custom-data.js +27 -0
  35. package/dist/api-contract/src/storefront/customer.d.ts +2 -0
  36. package/dist/api-contract/src/storefront/customer.js +261 -0
  37. package/dist/api-contract/src/storefront/downloads.d.ts +2 -0
  38. package/dist/api-contract/src/storefront/draft-order-invoice.d.ts +2 -0
  39. package/dist/api-contract/src/storefront/forms.d.ts +2 -0
  40. package/dist/api-contract/src/storefront/forms.js +82 -0
  41. package/dist/api-contract/src/storefront/index.d.ts +20956 -0
  42. package/dist/api-contract/src/storefront/orders.d.ts +2 -0
  43. package/dist/api-contract/src/storefront/policies.d.ts +2 -0
  44. package/dist/api-contract/src/storefront/procedure.d.ts +2 -0
  45. package/dist/api-contract/src/storefront/procedure.js +29 -0
  46. package/dist/api-contract/src/storefront/reviews.d.ts +20 -0
  47. package/dist/api-contract/src/storefront/search.d.ts +3 -0
  48. package/dist/api-contract/src/storefront/seo.d.ts +2 -0
  49. package/dist/api-contract/src/storefront/seo.js +132 -0
  50. package/dist/api-contract/src/storefront/shop.d.ts +2 -0
  51. package/dist/api-contract/src/storefront/shop.js +101 -0
  52. package/dist/api-contract/src/taxonomy.js +5 -0
  53. package/dist/api-contract/src/text.js +15 -0
  54. package/dist/api-contract/src/theme-documents.js +13 -0
  55. package/dist/api-contract/src/theme-translations.d.ts +14 -0
  56. package/dist/api-contract/src/theme-translations.js +30 -0
  57. package/dist/api-contract/src/video.js +19 -0
  58. package/dist/availability.d.ts +6 -3
  59. package/dist/availability.js +11 -5
  60. package/dist/blog.d.ts +53 -59
  61. package/dist/blog.js +197 -497
  62. package/dist/cache.d.ts +5 -6
  63. package/dist/cache.js +1 -2
  64. package/dist/canonical-host.d.ts +4 -6
  65. package/dist/canonical-host.js +5 -6
  66. package/dist/card.js +159 -0
  67. package/dist/cart-customer.d.ts +1 -3
  68. package/dist/cart-customer.js +64 -105
  69. package/dist/cart-mutations.d.ts +43 -77
  70. package/dist/cart-mutations.js +106 -232
  71. package/dist/cart-recommendations.d.ts +1 -3
  72. package/dist/cart-recommendations.js +1 -2
  73. package/dist/cart-session.d.ts +1 -3
  74. package/dist/cart-session.js +1 -2
  75. package/dist/cart.d.ts +63 -224
  76. package/dist/cart.js +70 -197
  77. package/dist/checkout.d.ts +13 -17
  78. package/dist/checkout.js +75 -101
  79. package/dist/coalesce.js +57 -0
  80. package/dist/collection.d.ts +89 -298
  81. package/dist/collection.js +210 -656
  82. package/dist/contact.d.ts +20 -10
  83. package/dist/contact.js +36 -30
  84. package/dist/content-version.d.ts +37 -21
  85. package/dist/content-version.js +64 -42
  86. package/dist/contract-kit/src/client.d.ts +12 -0
  87. package/dist/contract-kit/src/client.js +156 -0
  88. package/dist/contract-kit/src/errors.d.ts +1 -0
  89. package/dist/contract-kit/src/errors.js +81 -0
  90. package/dist/contract-kit/src/ids.d.ts +1 -0
  91. package/dist/contract-kit/src/ids.js +118 -0
  92. package/dist/contract-kit/src/index.d.ts +7 -0
  93. package/dist/contract-kit/src/money.d.ts +1 -0
  94. package/dist/contract-kit/src/money.js +10 -0
  95. package/dist/contract-kit/src/pagination.d.ts +1 -0
  96. package/dist/contract-kit/src/procedure.d.ts +69 -0
  97. package/dist/contract-kit/src/procedure.js +16 -0
  98. package/dist/contract-kit/src/realtime.d.ts +1 -0
  99. package/dist/cookie-secret.js +1 -2
  100. package/dist/csrf.js +1 -2
  101. package/dist/customer-handoff.d.ts +1 -3
  102. package/dist/customer-handoff.js +10 -25
  103. package/dist/customer-session.d.ts +1 -3
  104. package/dist/customer-session.js +1 -2
  105. package/dist/customer.d.ts +2 -3
  106. package/dist/customer.js +27 -44
  107. package/dist/files.d.ts +49 -10
  108. package/dist/files.js +106 -89
  109. package/dist/fonts.d.ts +3 -5
  110. package/dist/fonts.js +16 -35
  111. package/dist/html.d.ts +1 -3
  112. package/dist/html.js +1 -2
  113. package/dist/liquid.d.ts +4 -10
  114. package/dist/liquid.js +25 -32
  115. package/dist/listing.js +79 -0
  116. package/dist/marketing-cookies.d.ts +1 -3
  117. package/dist/marketing-cookies.js +1 -2
  118. package/dist/menu.d.ts +46 -155
  119. package/dist/menu.js +51 -61
  120. package/dist/metafields.d.ts +9 -5
  121. package/dist/metafields.js +10 -38
  122. package/dist/metaobject.d.ts +10 -5
  123. package/dist/metaobject.js +43 -66
  124. package/dist/money.d.ts +7 -0
  125. package/dist/money.js +18 -0
  126. package/dist/newsletter.d.ts +19 -10
  127. package/dist/newsletter.js +31 -25
  128. package/dist/page.d.ts +13 -17
  129. package/dist/page.js +49 -105
  130. package/dist/password-session.d.ts +1 -3
  131. package/dist/password-session.js +1 -2
  132. package/dist/password.d.ts +25 -18
  133. package/dist/password.js +41 -59
  134. package/dist/policy.d.ts +7 -7
  135. package/dist/policy.js +19 -55
  136. package/dist/product.d.ts +42 -67
  137. package/dist/product.js +144 -644
  138. package/dist/read-ahead.d.ts +18 -0
  139. package/dist/read-ahead.js +32 -0
  140. package/dist/recommendations.d.ts +6 -12
  141. package/dist/recommendations.js +36 -60
  142. package/dist/review.d.ts +134 -94
  143. package/dist/review.js +257 -469
  144. package/dist/search.d.ts +59 -64
  145. package/dist/search.js +170 -469
  146. package/dist/seo-context.d.ts +1 -3
  147. package/dist/seo-context.js +4 -5
  148. package/dist/seo-documents.d.ts +50 -0
  149. package/dist/seo-documents.js +149 -0
  150. package/dist/shop-seo.d.ts +3 -5
  151. package/dist/shop-seo.js +7 -26
  152. package/dist/shop.d.ts +38 -42
  153. package/dist/shop.js +37 -51
  154. package/dist/store-availability.d.ts +12 -14
  155. package/dist/store-availability.js +18 -56
  156. package/dist/storefront.js +199 -0
  157. package/dist/structured-data.d.ts +3 -28
  158. package/dist/structured-data.js +19 -49
  159. package/dist/trace.js +1 -2
  160. package/dist/translations.d.ts +26 -31
  161. package/dist/translations.js +55 -28
  162. package/package.json +16 -14
  163. package/dist/graphql-env.d.ts +0 -22778
  164. package/dist/graphql.d.ts +0 -64
  165. package/dist/graphql.js +0 -344
  166. package/dist/schema.storefront.graphql +0 -10483
  167. package/dist/seo-proxy.d.ts +0 -11
  168. package/dist/seo-proxy.js +0 -26
package/dist/graphql.d.ts DELETED
@@ -1,64 +0,0 @@
1
- import { introspection } from "./graphql-env.js";
2
- import { ResultOf, TadaDocumentNode, VariablesOf, initGraphQLTada } from "gql.tada";
3
- //#region src/graphql.d.ts
4
- export declare const graphql: initGraphQLTada<{
5
- introspection: introspection;
6
- scalars: {
7
- ISO8601DateTime: string;
8
- BigInt: string;
9
- HTML: string;
10
- Decimal: string;
11
- };
12
- }>;
13
- interface CachedToken {
14
- accessToken: string;
15
- expiresAtMs: number;
16
- }
17
- export declare const MINT_LEASE_MS = 3000;
18
- export declare class StorefrontConfigError extends Error {
19
- constructor(message: string);
20
- }
21
- export declare function mintToken(): Promise<CachedToken>;
22
- export declare function getStorefrontToken(): Promise<string>;
23
- /**
24
- * `getStorefrontToken`, but gives up once `signal` aborts. For a proxy with its
25
- * own deadline: a Rails that accepts TCP and never answers hangs on the mint,
26
- * not on the proxy's document fetch. The signal can't cancel the mint's own
27
- * fetch (other requests may be waiting on it), only this caller's wait.
28
- */
29
- export declare function getStorefrontTokenWithin(signal: AbortSignal): Promise<string>;
30
- /** The Rails API origin the storefront proxies call. Read per call, as `readConfig` does. */
31
- export declare function storefrontApiUrl(): string;
32
- export interface RequestOptions {
33
- /** Pass a customer session token to populate `X-Customer-Session` on this request. */
34
- customerSessionToken?: string;
35
- /** Forward the buyer's `Accept-Language` for locale-sensitive resolvers (e.g. `pickUpTime`). */
36
- acceptLanguage?: string;
37
- }
38
- /**
39
- * Executes a typed gql.tada document against the Rails storefront endpoint.
40
- * Query documents one request issues in the same tick with identical headers
41
- * are batched into one multiplex POST; mutations, and calls made outside a
42
- * request, go out individually. On a 401 the token that was sent is
43
- * invalidated and the request (or whole batch) is retried once (handles clock
44
- * skew / revocation). GraphQL-level errors surface as `ClientError` to the
45
- * caller either way.
46
- */
47
- export declare function request<TResult, TVariables extends Record<string, unknown>>(document: TadaDocumentNode<TResult, TVariables>, variables?: TVariables, options?: RequestOptions): Promise<TResult>;
48
- /**
49
- * Executes a mutation that carries file `Upload` variables. `graphql-request`
50
- * is JSON-only — it would `JSON.stringify` a `File`/`Blob` to `{}` — so this is
51
- * a purpose-built transport that builds the multipart/form-data body Rails'
52
- * `GraphqlController#extract_graphql_payload` expects (the
53
- * graphql-multipart-request-spec `operations`/`map`/`<key>` shape). Single-shot
54
- * (never batched, mutations always are), same bearer-auth + one-shot 401 retry
55
- * as {@link executeSingle}.
56
- *
57
- * `files` are appended in order; each is spliced into `variables` at
58
- * `${filesPath}.${index}` (so the caller sets that variable to an array of
59
- * `null`s of the same length — the multipart spec's null-placeholder rule). GID
60
- * scalars stay JSON; only the file parts leave the operations blob.
61
- */
62
- export declare function requestUpload<TResult, TVariables extends Record<string, unknown>>(document: TadaDocumentNode<TResult, TVariables>, variables: TVariables, files: readonly Blob[], filesPath: string, options?: RequestOptions): Promise<TResult>;
63
- //#endregion
64
- export type { ResultOf, VariablesOf };
package/dist/graphql.js DELETED
@@ -1,344 +0,0 @@
1
- import { createLease } from "./lease.js";
2
- import { requestSlot } from "./request-scope.js";
3
- import { requestTraceHeaders } from "./trace.js";
4
- import { shardBuyerHeaders } from "@shop-on/customer-runtime/relay";
5
- import { initGraphQLTada } from "gql.tada";
6
- import { Kind, print } from "graphql";
7
- import { ClientError, GraphQLClient } from "graphql-request";
8
- //#region src/graphql.ts
9
- const graphql = initGraphQLTada();
10
- const REFRESH_SKEW_MS = 3e5;
11
- const STALE_TOKEN_MARGIN_MS = 3e4;
12
- let cached = null;
13
- const MINT_LEASE_MS = 3e3;
14
- const mintLease = createLease({ leaseMs: MINT_LEASE_MS });
15
- let mintHoldUntilMs = 0;
16
- let mintHoldError = null;
17
- const MINT_FAILURE_HOLD_MS = 2e3;
18
- const MINT_THROTTLE_FALLBACK_HOLD_MS = 15e3;
19
- const MINT_HOLD_MAX_MS = 6e4;
20
- const GRAPHQL_TIMEOUT_MS = 8e3;
21
- var MintError = class extends Error {
22
- holdMs;
23
- constructor(message, holdMs) {
24
- super(message);
25
- this.holdMs = holdMs;
26
- this.name = "MintError";
27
- }
28
- };
29
- function throttleHoldMs(res, bodyText) {
30
- const header = Number(res.headers.get("Retry-After"));
31
- let seconds = Number.isFinite(header) && header > 0 ? header : 0;
32
- if (!seconds) try {
33
- const body = JSON.parse(bodyText);
34
- if (typeof body.retry_after === "number" && body.retry_after > 0) seconds = body.retry_after;
35
- } catch {}
36
- return seconds ? Math.min(seconds * 1e3, MINT_HOLD_MAX_MS) : MINT_THROTTLE_FALLBACK_HOLD_MS;
37
- }
38
- var StorefrontConfigError = class extends Error {
39
- constructor(message) {
40
- super(message);
41
- this.name = "StorefrontConfigError";
42
- }
43
- };
44
- function assertServerOnly() {
45
- if (typeof window !== "undefined") throw new Error("storefront graphql client is server-only and must not be imported into browser code");
46
- }
47
- function readConfig() {
48
- assertServerOnly();
49
- const clientId = process.env.STOREFRONT_CLIENT_ID || "";
50
- const clientSecret = process.env.STOREFRONT_CLIENT_SECRET || "";
51
- const apiUrl = storefrontApiUrl();
52
- if (!clientId || !clientSecret) throw new StorefrontConfigError("storefront graphql client missing STOREFRONT_CLIENT_ID / STOREFRONT_CLIENT_SECRET env vars");
53
- return {
54
- clientId,
55
- clientSecret,
56
- apiUrl
57
- };
58
- }
59
- async function mintToken() {
60
- const { clientId, clientSecret, apiUrl } = readConfig();
61
- const body = new URLSearchParams({
62
- grant_type: "client_credentials",
63
- client_id: clientId,
64
- client_secret: clientSecret,
65
- scope: "storefront public"
66
- });
67
- const res = await fetch(`${apiUrl}/oauth/token`, {
68
- method: "POST",
69
- headers: { "Content-Type": "application/x-www-form-urlencoded" },
70
- body,
71
- signal: AbortSignal.timeout(2750)
72
- });
73
- if (!res.ok) {
74
- const text = await res.text().catch(() => "");
75
- const holdMs = res.status === 429 ? throttleHoldMs(res, text) : MINT_FAILURE_HOLD_MS;
76
- throw new MintError(`[graphql] token exchange failed (${res.status}): ${text.slice(0, 200)}`, holdMs);
77
- }
78
- const json = await res.json();
79
- const accessToken = json.access_token;
80
- const expiresIn = json.expires_in;
81
- if (typeof accessToken !== "string" || accessToken.length === 0) throw new Error("[graphql] token exchange returned invalid access_token");
82
- if (typeof expiresIn !== "number" || !Number.isFinite(expiresIn) || expiresIn <= 0) throw new Error(`[graphql] token exchange returned invalid expires_in: ${String(expiresIn)}`);
83
- return {
84
- accessToken,
85
- expiresAtMs: Date.now() + expiresIn * 1e3
86
- };
87
- }
88
- async function getStorefrontToken() {
89
- return getToken();
90
- }
91
- /**
92
- * `getStorefrontToken`, but gives up once `signal` aborts. For a proxy with its
93
- * own deadline: a Rails that accepts TCP and never answers hangs on the mint,
94
- * not on the proxy's document fetch. The signal can't cancel the mint's own
95
- * fetch (other requests may be waiting on it), only this caller's wait.
96
- */
97
- function getStorefrontTokenWithin(signal) {
98
- return Promise.race([getToken(), new Promise((_resolve, reject) => {
99
- if (signal.aborted) reject(signal.reason);
100
- signal.addEventListener("abort", () => reject(signal.reason), { once: true });
101
- })]);
102
- }
103
- /** The Rails API origin the storefront proxies call. Read per call, as `readConfig` does. */
104
- function storefrontApiUrl() {
105
- assertServerOnly();
106
- return process.env.STOREFRONT_API_URL || "http://localhost:3003";
107
- }
108
- function activeMintHold() {
109
- return mintHoldError && Date.now() < mintHoldUntilMs ? mintHoldError : null;
110
- }
111
- async function mintUnderLease() {
112
- const held = activeMintHold();
113
- if (held) throw held;
114
- let token;
115
- try {
116
- token = await mintToken();
117
- } catch (err) {
118
- mintHoldError = err;
119
- mintHoldUntilMs = Date.now() + (err instanceof MintError ? err.holdMs : MINT_FAILURE_HOLD_MS);
120
- throw err;
121
- }
122
- cached = token;
123
- mintHoldError = null;
124
- mintHoldUntilMs = 0;
125
- return token;
126
- }
127
- async function getToken() {
128
- const now = Date.now();
129
- if (cached && cached.expiresAtMs - REFRESH_SKEW_MS > now) return cached.accessToken;
130
- const prev = cached && cached.expiresAtMs - STALE_TOKEN_MARGIN_MS > now ? cached.accessToken : null;
131
- const held = activeMintHold();
132
- if (prev && (held || mintLease.heldByOther("t"))) return prev;
133
- if (held) throw held;
134
- try {
135
- return (await mintLease.run("t", mintUnderLease)).accessToken;
136
- } catch (err) {
137
- if (prev && cached?.accessToken === prev) return prev;
138
- throw err;
139
- }
140
- }
141
- function buildClient(headers) {
142
- const { apiUrl } = readConfig();
143
- return new GraphQLClient(`${apiUrl}/graphql`, { headers });
144
- }
145
- function extraHeaders(options) {
146
- const extra = {};
147
- if (options?.customerSessionToken) extra["X-Customer-Session"] = options.customerSessionToken;
148
- if (options?.acceptLanguage) extra["Accept-Language"] = options.acceptLanguage;
149
- return extra;
150
- }
151
- function requestScopedHeaders() {
152
- return {
153
- ...requestTraceHeaders(),
154
- ...shardBuyerHeaders()
155
- };
156
- }
157
- function bearerHeaders(token, options, scoped) {
158
- return {
159
- Authorization: `Bearer ${token}`,
160
- ...extraHeaders(options),
161
- ...scoped
162
- };
163
- }
164
- function invalidateToken(used) {
165
- if (cached?.accessToken === used) cached = null;
166
- }
167
- async function executeSingle(document, variables, options, scoped) {
168
- const send = async (token) => await buildClient(bearerHeaders(token, options, scoped)).request({
169
- document,
170
- variables,
171
- signal: AbortSignal.timeout(GRAPHQL_TIMEOUT_MS)
172
- });
173
- const token = await getToken();
174
- try {
175
- return await send(token);
176
- } catch (err) {
177
- if (err instanceof ClientError && err.response.status === 401) {
178
- invalidateToken(token);
179
- return await send(await getToken());
180
- }
181
- throw err;
182
- }
183
- }
184
- const BATCH_MAX_QUERIES = 20;
185
- const BATCH_QUEUES = Symbol("graphql batch queues");
186
- function isBatchableQuery(document) {
187
- const operations = document.definitions.filter((d) => d.kind === Kind.OPERATION_DEFINITION);
188
- return operations.length > 0 && operations.every((op) => op.operation === "query");
189
- }
190
- function enqueueBatched(queues, query, variables, options) {
191
- const key = `${options?.customerSessionToken ?? ""}\n${options?.acceptLanguage ?? ""}`;
192
- return new Promise((resolve, reject) => {
193
- let queue = queues.get(key);
194
- if (!queue) {
195
- const scheduled = [];
196
- const scoped = requestScopedHeaders();
197
- queue = scheduled;
198
- queues.set(key, scheduled);
199
- setTimeout(() => {
200
- queues.delete(key);
201
- flushBatch(scheduled, options, scoped);
202
- }, 0);
203
- }
204
- queue.push({
205
- query,
206
- variables,
207
- resolve,
208
- reject
209
- });
210
- });
211
- }
212
- async function flushBatch(entries, options, scoped) {
213
- const chunks = [];
214
- for (let i = 0; i < entries.length; i += BATCH_MAX_QUERIES) chunks.push(entries.slice(i, i + BATCH_MAX_QUERIES));
215
- await Promise.all(chunks.map(async (chunk) => {
216
- try {
217
- if (chunk.length === 1) {
218
- const only = chunk[0];
219
- only.resolve(await executeSingle(only.query, only.variables, options, scoped));
220
- } else await executeBatchChunk(chunk, options, scoped);
221
- } catch (err) {
222
- for (const entry of chunk) entry.reject(err);
223
- }
224
- }));
225
- }
226
- function batchClientError(response, request) {
227
- return new ClientError(response, request);
228
- }
229
- async function postWithAuthRetry(buildInit) {
230
- const { apiUrl } = readConfig();
231
- const post = async (token) => await fetch(`${apiUrl}/graphql`, {
232
- method: "POST",
233
- ...buildInit(token)
234
- });
235
- const token = await getToken();
236
- const res = await post(token);
237
- if (res.status !== 401) return res;
238
- invalidateToken(token);
239
- return await post(await getToken());
240
- }
241
- async function executeBatchChunk(chunk, options, scoped) {
242
- const body = JSON.stringify(chunk.map(({ query, variables }) => ({
243
- query,
244
- variables
245
- })));
246
- const res = await postWithAuthRetry((token) => ({
247
- headers: {
248
- "Content-Type": "application/json",
249
- ...bearerHeaders(token, options, scoped)
250
- },
251
- body,
252
- signal: AbortSignal.timeout(GRAPHQL_TIMEOUT_MS)
253
- }));
254
- if (!res.ok) throw batchClientError({
255
- status: res.status,
256
- errors: [{ message: `batch request failed (${res.status})` }]
257
- }, { query: chunk.map((entry) => entry.query) });
258
- const results = await res.json();
259
- if (!Array.isArray(results) || results.length !== chunk.length) throw new Error(`[graphql] batch response shape mismatch (expected ${chunk.length} results)`);
260
- chunk.forEach((entry, i) => {
261
- const result = results[i];
262
- if (result?.errors && result.errors.length > 0) entry.reject(batchClientError({
263
- ...result,
264
- status: res.status
265
- }, {
266
- query: entry.query,
267
- variables: entry.variables
268
- }));
269
- else if (result && result.data !== void 0) entry.resolve(result.data);
270
- else entry.reject(/* @__PURE__ */ new Error("[graphql] batch entry returned neither data nor errors"));
271
- });
272
- }
273
- /**
274
- * Executes a typed gql.tada document against the Rails storefront endpoint.
275
- * Query documents one request issues in the same tick with identical headers
276
- * are batched into one multiplex POST; mutations, and calls made outside a
277
- * request, go out individually. On a 401 the token that was sent is
278
- * invalidated and the request (or whole batch) is retried once (handles clock
279
- * skew / revocation). GraphQL-level errors surface as `ClientError` to the
280
- * caller either way.
281
- */
282
- async function request(document, variables, options) {
283
- assertServerOnly();
284
- const queues = isBatchableQuery(document) ? requestSlot(BATCH_QUEUES, () => /* @__PURE__ */ new Map()) : void 0;
285
- if (!queues) return await executeSingle(document, variables, options, requestScopedHeaders());
286
- return await enqueueBatched(queues, print(document), variables, options);
287
- }
288
- /**
289
- * Executes a mutation that carries file `Upload` variables. `graphql-request`
290
- * is JSON-only — it would `JSON.stringify` a `File`/`Blob` to `{}` — so this is
291
- * a purpose-built transport that builds the multipart/form-data body Rails'
292
- * `GraphqlController#extract_graphql_payload` expects (the
293
- * graphql-multipart-request-spec `operations`/`map`/`<key>` shape). Single-shot
294
- * (never batched, mutations always are), same bearer-auth + one-shot 401 retry
295
- * as {@link executeSingle}.
296
- *
297
- * `files` are appended in order; each is spliced into `variables` at
298
- * `${filesPath}.${index}` (so the caller sets that variable to an array of
299
- * `null`s of the same length — the multipart spec's null-placeholder rule). GID
300
- * scalars stay JSON; only the file parts leave the operations blob.
301
- */
302
- async function requestUpload(document, variables, files, filesPath, options) {
303
- assertServerOnly();
304
- const scoped = requestScopedHeaders();
305
- const query = print(document);
306
- const map = {};
307
- files.forEach((_, i) => {
308
- map[String(i)] = [`${filesPath}.${i}`];
309
- });
310
- const buildBody = () => {
311
- const form = new FormData();
312
- form.append("operations", JSON.stringify({
313
- query,
314
- variables
315
- }));
316
- form.append("map", JSON.stringify(map));
317
- files.forEach((file, i) => {
318
- const named = file;
319
- const filename = typeof named.name === "string" && named.name ? named.name : `upload-${i}`;
320
- form.append(String(i), file, filename);
321
- });
322
- return form;
323
- };
324
- const res = await postWithAuthRetry((token) => ({
325
- headers: bearerHeaders(token, options, scoped),
326
- body: buildBody()
327
- }));
328
- if (!res.ok) throw batchClientError({
329
- status: res.status,
330
- errors: [{ message: `upload request failed (${res.status})` }]
331
- }, { query });
332
- const json = await res.json();
333
- if (json.errors && json.errors.length > 0) throw batchClientError({
334
- status: res.status,
335
- errors: json.errors
336
- }, {
337
- query,
338
- variables
339
- });
340
- if (json.data == null) throw new Error("[graphql] upload response had no data");
341
- return json.data;
342
- }
343
- //#endregion
344
- export { MINT_LEASE_MS, StorefrontConfigError, getStorefrontToken, getStorefrontTokenWithin, graphql, mintToken, request, requestUpload, storefrontApiUrl };