@shopkit/data-layer 1.3.0 → 1.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.
package/dist/index.js CHANGED
@@ -1,659 +1,12 @@
1
1
  'use strict';
2
2
 
3
- // ../../node_modules/.bun/@shopify+graphql-client@1.4.2/node_modules/@shopify/graphql-client/dist/graphql-client/constants.mjs
4
- var CLIENT = "GraphQL Client";
5
- var MIN_RETRIES = 0;
6
- var MAX_RETRIES = 3;
7
- var GQL_API_ERROR = "An error occurred while fetching from the API. Review 'graphQLErrors' for details.";
8
- var UNEXPECTED_CONTENT_TYPE_ERROR = "Response returned unexpected Content-Type:";
9
- var NO_DATA_OR_ERRORS_ERROR = "An unknown error has occurred. The API did not return a data object or any errors in its response.";
10
- var CONTENT_TYPES = {
11
- json: "application/json",
12
- multipart: "multipart/mixed"
13
- };
14
- var SDK_VARIANT_HEADER = "X-SDK-Variant";
15
- var SDK_VERSION_HEADER = "X-SDK-Version";
16
- var DEFAULT_SDK_VARIANT = "shopify-graphql-client";
17
- var DEFAULT_CLIENT_VERSION = "1.4.2";
18
- var RETRY_WAIT_TIME = 1e3;
19
- var RETRIABLE_STATUS_CODES = [429, 503];
20
- var DEFER_OPERATION_REGEX = /@(defer)\b/i;
21
- var NEWLINE_SEPARATOR = "\r\n";
22
- var BOUNDARY_HEADER_REGEX = /boundary="?([^=";]+)"?/i;
23
- var HEADER_SEPARATOR = NEWLINE_SEPARATOR + NEWLINE_SEPARATOR;
24
-
25
- // ../../node_modules/.bun/@shopify+graphql-client@1.4.2/node_modules/@shopify/graphql-client/dist/graphql-client/utilities.mjs
26
- function formatErrorMessage(message, client = CLIENT) {
27
- return message.startsWith(`${client}`) ? message : `${client}: ${message}`;
28
- }
29
- function getErrorMessage(error) {
30
- return error instanceof Error ? error.message : JSON.stringify(error);
31
- }
32
- function getErrorCause(error) {
33
- return error instanceof Error && error.cause ? error.cause : void 0;
34
- }
35
- function combineErrors(dataArray) {
36
- return dataArray.flatMap(({ errors }) => {
37
- return errors ?? [];
38
- });
39
- }
40
- function validateRetries({ client, retries }) {
41
- if (retries !== void 0 && (typeof retries !== "number" || retries < MIN_RETRIES || retries > MAX_RETRIES)) {
42
- throw new Error(`${client}: The provided "retries" value (${retries}) is invalid - it cannot be less than ${MIN_RETRIES} or greater than ${MAX_RETRIES}`);
43
- }
44
- }
45
- function getKeyValueIfValid(key, value) {
46
- return value && (typeof value !== "object" || Array.isArray(value) || typeof value === "object" && Object.keys(value).length > 0) ? { [key]: value } : {};
47
- }
48
- function buildDataObjectByPath(path, data) {
49
- if (path.length === 0) {
50
- return data;
51
- }
52
- const key = path.pop();
53
- const newData = {
54
- [key]: data
55
- };
56
- if (path.length === 0) {
57
- return newData;
58
- }
59
- return buildDataObjectByPath(path, newData);
60
- }
61
- function combineObjects(baseObject, newObject) {
62
- return Object.keys(newObject || {}).reduce((acc, key) => {
63
- if ((typeof newObject[key] === "object" || Array.isArray(newObject[key])) && baseObject[key]) {
64
- acc[key] = combineObjects(baseObject[key], newObject[key]);
65
- return acc;
66
- }
67
- acc[key] = newObject[key];
68
- return acc;
69
- }, Array.isArray(baseObject) ? [...baseObject] : { ...baseObject });
70
- }
71
- function buildCombinedDataObject([initialDatum, ...remainingData]) {
72
- return remainingData.reduce(combineObjects, { ...initialDatum });
73
- }
74
-
75
- // ../../node_modules/.bun/@shopify+graphql-client@1.4.2/node_modules/@shopify/graphql-client/dist/graphql-client/http-fetch.mjs
76
- function generateHttpFetch({ clientLogger, customFetchApi = fetch, client = CLIENT, defaultRetryWaitTime = RETRY_WAIT_TIME, retriableCodes = RETRIABLE_STATUS_CODES }) {
77
- const httpFetch = async (requestParams, count, maxRetries) => {
78
- const nextCount = count + 1;
79
- const maxTries = maxRetries + 1;
80
- let response;
81
- try {
82
- response = await customFetchApi(...requestParams);
83
- clientLogger({
84
- type: "HTTP-Response",
85
- content: {
86
- requestParams,
87
- response
88
- }
89
- });
90
- if (!response.ok && retriableCodes.includes(response.status) && nextCount <= maxTries) {
91
- throw new Error();
92
- }
93
- const deprecationNotice = response?.headers.get("X-Shopify-API-Deprecated-Reason") || "";
94
- if (deprecationNotice) {
95
- clientLogger({
96
- type: "HTTP-Response-GraphQL-Deprecation-Notice",
97
- content: {
98
- requestParams,
99
- deprecationNotice
100
- }
101
- });
102
- }
103
- return response;
104
- } catch (error) {
105
- if (nextCount <= maxTries) {
106
- const retryAfter = response?.headers.get("Retry-After");
107
- await sleep(retryAfter ? parseInt(retryAfter, 10) : defaultRetryWaitTime);
108
- clientLogger({
109
- type: "HTTP-Retry",
110
- content: {
111
- requestParams,
112
- lastResponse: response,
113
- retryAttempt: count,
114
- maxRetries
115
- }
116
- });
117
- return httpFetch(requestParams, nextCount, maxRetries);
118
- }
119
- throw new Error(formatErrorMessage(`${maxRetries > 0 ? `Attempted maximum number of ${maxRetries} network retries. Last message - ` : ""}${getErrorMessage(error)}`, client));
120
- }
121
- };
122
- return httpFetch;
123
- }
124
- async function sleep(waitTime) {
125
- return new Promise((resolve) => setTimeout(resolve, waitTime));
126
- }
127
-
128
- // ../../node_modules/.bun/@shopify+graphql-client@1.4.2/node_modules/@shopify/graphql-client/dist/graphql-client/graphql-client.mjs
129
- function createGraphQLClient({ headers, url, customFetchApi = fetch, retries = 0, logger: logger2 }) {
130
- validateRetries({ client: CLIENT, retries });
131
- const config = {
132
- headers,
133
- url,
134
- retries
135
- };
136
- const clientLogger = generateClientLogger(logger2);
137
- const httpFetch = generateHttpFetch({
138
- customFetchApi,
139
- clientLogger,
140
- defaultRetryWaitTime: RETRY_WAIT_TIME
141
- });
142
- const fetchFn = generateFetch(httpFetch, config);
143
- const request = generateRequest(fetchFn);
144
- const requestStream = generateRequestStream(fetchFn);
145
- return {
146
- config,
147
- fetch: fetchFn,
148
- request,
149
- requestStream
150
- };
151
- }
152
- function generateClientLogger(logger2) {
153
- return (logContent) => {
154
- if (logger2) {
155
- logger2(logContent);
156
- }
157
- };
158
- }
159
- async function processJSONResponse(response) {
160
- const { errors, data, extensions } = await response.json();
161
- return {
162
- ...getKeyValueIfValid("data", data),
163
- ...getKeyValueIfValid("extensions", extensions),
164
- headers: response.headers,
165
- ...errors || !data ? {
166
- errors: {
167
- networkStatusCode: response.status,
168
- message: formatErrorMessage(errors ? GQL_API_ERROR : NO_DATA_OR_ERRORS_ERROR),
169
- ...getKeyValueIfValid("graphQLErrors", errors),
170
- response
171
- }
172
- } : {}
173
- };
174
- }
175
- function generateFetch(httpFetch, { url, headers, retries }) {
176
- return async (operation, options = {}) => {
177
- const { variables, headers: overrideHeaders, url: overrideUrl, retries: overrideRetries, keepalive, signal } = options;
178
- const body = JSON.stringify({
179
- query: operation,
180
- variables
181
- });
182
- validateRetries({ client: CLIENT, retries: overrideRetries });
183
- const flatHeaders = Object.entries({
184
- ...headers,
185
- ...overrideHeaders
186
- }).reduce((headers2, [key, value]) => {
187
- headers2[key] = Array.isArray(value) ? value.join(", ") : value.toString();
188
- return headers2;
189
- }, {});
190
- if (!flatHeaders[SDK_VARIANT_HEADER] && !flatHeaders[SDK_VERSION_HEADER]) {
191
- flatHeaders[SDK_VARIANT_HEADER] = DEFAULT_SDK_VARIANT;
192
- flatHeaders[SDK_VERSION_HEADER] = DEFAULT_CLIENT_VERSION;
193
- }
194
- const fetchParams = [
195
- overrideUrl ?? url,
196
- {
197
- method: "POST",
198
- headers: flatHeaders,
199
- body,
200
- signal,
201
- keepalive
202
- }
203
- ];
204
- return httpFetch(fetchParams, 1, overrideRetries ?? retries);
205
- };
206
- }
207
- function generateRequest(fetchFn) {
208
- return async (...props) => {
209
- if (DEFER_OPERATION_REGEX.test(props[0])) {
210
- throw new Error(formatErrorMessage("This operation will result in a streamable response - use requestStream() instead."));
211
- }
212
- let response = null;
213
- try {
214
- response = await fetchFn(...props);
215
- const { status, statusText } = response;
216
- const contentType = response.headers.get("content-type") || "";
217
- if (!response.ok) {
218
- return {
219
- errors: {
220
- networkStatusCode: status,
221
- message: formatErrorMessage(statusText),
222
- response
223
- }
224
- };
225
- }
226
- if (!contentType.includes(CONTENT_TYPES.json)) {
227
- return {
228
- errors: {
229
- networkStatusCode: status,
230
- message: formatErrorMessage(`${UNEXPECTED_CONTENT_TYPE_ERROR} ${contentType}`),
231
- response
232
- }
233
- };
234
- }
235
- return await processJSONResponse(response);
236
- } catch (error) {
237
- return {
238
- errors: {
239
- message: getErrorMessage(error),
240
- ...response == null ? {} : {
241
- networkStatusCode: response.status,
242
- response
243
- }
244
- }
245
- };
246
- }
247
- };
248
- }
249
- async function* getStreamBodyIterator(response) {
250
- const decoder = new TextDecoder();
251
- if (response.body[Symbol.asyncIterator]) {
252
- for await (const chunk of response.body) {
253
- yield decoder.decode(chunk);
254
- }
255
- } else {
256
- const reader = response.body.getReader();
257
- let readResult;
258
- try {
259
- while (!(readResult = await reader.read()).done) {
260
- yield decoder.decode(readResult.value);
261
- }
262
- } finally {
263
- reader.cancel();
264
- }
265
- }
266
- }
267
- function readStreamChunk(streamBodyIterator, boundary) {
268
- return {
269
- async *[Symbol.asyncIterator]() {
270
- try {
271
- let buffer = "";
272
- for await (const textChunk of streamBodyIterator) {
273
- buffer += textChunk;
274
- if (buffer.indexOf(boundary) > -1) {
275
- const lastBoundaryIndex = buffer.lastIndexOf(boundary);
276
- const fullResponses = buffer.slice(0, lastBoundaryIndex);
277
- const chunkBodies = fullResponses.split(boundary).filter((chunk) => chunk.trim().length > 0).map((chunk) => {
278
- const body = chunk.slice(chunk.indexOf(HEADER_SEPARATOR) + HEADER_SEPARATOR.length).trim();
279
- return body;
280
- });
281
- if (chunkBodies.length > 0) {
282
- yield chunkBodies;
283
- }
284
- buffer = buffer.slice(lastBoundaryIndex + boundary.length);
285
- if (buffer.trim() === `--`) {
286
- buffer = "";
287
- }
288
- }
289
- }
290
- } catch (error) {
291
- throw new Error(`Error occured while processing stream payload - ${getErrorMessage(error)}`);
292
- }
293
- }
294
- };
295
- }
296
- function createJsonResponseAsyncIterator(response) {
297
- return {
298
- async *[Symbol.asyncIterator]() {
299
- try {
300
- const processedResponse = await processJSONResponse(response);
301
- yield {
302
- ...processedResponse,
303
- hasNext: false
304
- };
305
- } catch (error) {
306
- yield {
307
- errors: {
308
- message: formatErrorMessage(getErrorMessage(error)),
309
- networkStatusCode: response.status,
310
- response
311
- },
312
- hasNext: false
313
- };
314
- }
315
- }
316
- };
317
- }
318
- function getResponseDataFromChunkBodies(chunkBodies) {
319
- return chunkBodies.map((value) => {
320
- try {
321
- return JSON.parse(value);
322
- } catch (error) {
323
- throw new Error(`Error in parsing multipart response - ${getErrorMessage(error)}`);
324
- }
325
- }).map((payload) => {
326
- const { data, incremental, hasNext, extensions, errors } = payload;
327
- if (!incremental) {
328
- return {
329
- data: data || {},
330
- ...getKeyValueIfValid("errors", errors),
331
- ...getKeyValueIfValid("extensions", extensions),
332
- hasNext
333
- };
334
- }
335
- const incrementalArray = incremental.map(({ data: data2, path, errors: errors2 }) => {
336
- return {
337
- data: data2 && path ? buildDataObjectByPath(path, data2) : {},
338
- ...getKeyValueIfValid("errors", errors2)
339
- };
340
- });
341
- return {
342
- data: incrementalArray.length === 1 ? incrementalArray[0].data : buildCombinedDataObject([
343
- ...incrementalArray.map(({ data: data2 }) => data2)
344
- ]),
345
- ...getKeyValueIfValid("errors", combineErrors(incrementalArray)),
346
- hasNext
347
- };
348
- });
349
- }
350
- function validateResponseData(responseErrors, combinedData) {
351
- if (responseErrors.length > 0) {
352
- throw new Error(GQL_API_ERROR, {
353
- cause: {
354
- graphQLErrors: responseErrors
355
- }
356
- });
357
- }
358
- if (Object.keys(combinedData).length === 0) {
359
- throw new Error(NO_DATA_OR_ERRORS_ERROR);
360
- }
361
- }
362
- function createMultipartResponseAsyncInterator(response, responseContentType) {
363
- const boundaryHeader = (responseContentType ?? "").match(BOUNDARY_HEADER_REGEX);
364
- const boundary = `--${boundaryHeader ? boundaryHeader[1] : "-"}`;
365
- if (!response.body?.getReader && !response.body?.[Symbol.asyncIterator]) {
366
- throw new Error("API multipart response did not return an iterable body", {
367
- cause: response
368
- });
369
- }
370
- const streamBodyIterator = getStreamBodyIterator(response);
371
- let combinedData = {};
372
- let responseExtensions;
373
- return {
374
- async *[Symbol.asyncIterator]() {
375
- try {
376
- let streamHasNext = true;
377
- for await (const chunkBodies of readStreamChunk(streamBodyIterator, boundary)) {
378
- const responseData = getResponseDataFromChunkBodies(chunkBodies);
379
- responseExtensions = responseData.find((datum) => datum.extensions)?.extensions ?? responseExtensions;
380
- const responseErrors = combineErrors(responseData);
381
- combinedData = buildCombinedDataObject([
382
- combinedData,
383
- ...responseData.map(({ data }) => data)
384
- ]);
385
- streamHasNext = responseData.slice(-1)[0].hasNext;
386
- validateResponseData(responseErrors, combinedData);
387
- yield {
388
- ...getKeyValueIfValid("data", combinedData),
389
- ...getKeyValueIfValid("extensions", responseExtensions),
390
- hasNext: streamHasNext
391
- };
392
- }
393
- if (streamHasNext) {
394
- throw new Error(`Response stream terminated unexpectedly`);
395
- }
396
- } catch (error) {
397
- const cause = getErrorCause(error);
398
- yield {
399
- ...getKeyValueIfValid("data", combinedData),
400
- ...getKeyValueIfValid("extensions", responseExtensions),
401
- errors: {
402
- message: formatErrorMessage(getErrorMessage(error)),
403
- networkStatusCode: response.status,
404
- ...getKeyValueIfValid("graphQLErrors", cause?.graphQLErrors),
405
- response
406
- },
407
- hasNext: false
408
- };
409
- }
410
- }
411
- };
412
- }
413
- function generateRequestStream(fetchFn) {
414
- return async (...props) => {
415
- if (!DEFER_OPERATION_REGEX.test(props[0])) {
416
- throw new Error(formatErrorMessage("This operation does not result in a streamable response - use request() instead."));
417
- }
418
- try {
419
- const response = await fetchFn(...props);
420
- const { statusText } = response;
421
- if (!response.ok) {
422
- throw new Error(statusText, { cause: response });
423
- }
424
- const responseContentType = response.headers.get("content-type") || "";
425
- switch (true) {
426
- case responseContentType.includes(CONTENT_TYPES.json):
427
- return createJsonResponseAsyncIterator(response);
428
- case responseContentType.includes(CONTENT_TYPES.multipart):
429
- return createMultipartResponseAsyncInterator(response, responseContentType);
430
- default:
431
- throw new Error(`${UNEXPECTED_CONTENT_TYPE_ERROR} ${responseContentType}`, { cause: response });
432
- }
433
- } catch (error) {
434
- return {
435
- async *[Symbol.asyncIterator]() {
436
- const response = getErrorCause(error);
437
- yield {
438
- errors: {
439
- message: formatErrorMessage(getErrorMessage(error)),
440
- ...getKeyValueIfValid("networkStatusCode", response?.status),
441
- ...getKeyValueIfValid("response", response)
442
- },
443
- hasNext: false
444
- };
445
- }
446
- };
447
- }
448
- };
449
- }
450
-
451
- // ../../node_modules/.bun/@shopify+graphql-client@1.4.2/node_modules/@shopify/graphql-client/dist/api-client-utilities/validations.mjs
452
- function validateDomainAndGetStoreUrl({ client, storeDomain }) {
453
- try {
454
- if (!storeDomain || typeof storeDomain !== "string") {
455
- throw new Error();
456
- }
457
- const trimmedDomain = storeDomain.trim();
458
- const protocolUrl = trimmedDomain.match(/^https?:/) ? trimmedDomain : `https://${trimmedDomain}`;
459
- const url = new URL(protocolUrl);
460
- url.protocol = "https";
461
- return url.origin;
462
- } catch (error) {
463
- throw new Error(`${client}: a valid store domain ("${storeDomain}") must be provided`, { cause: error });
464
- }
465
- }
466
- function validateApiVersion({ client, currentSupportedApiVersions, apiVersion, logger: logger2 }) {
467
- const versionError = `${client}: the provided apiVersion ("${apiVersion}")`;
468
- const supportedVersion = `Currently supported API versions: ${currentSupportedApiVersions.join(", ")}`;
469
- if (!apiVersion || typeof apiVersion !== "string") {
470
- throw new Error(`${versionError} is invalid. ${supportedVersion}`);
471
- }
472
- const trimmedApiVersion = apiVersion.trim();
473
- if (!currentSupportedApiVersions.includes(trimmedApiVersion)) {
474
- if (logger2) {
475
- logger2({
476
- type: "Unsupported_Api_Version",
477
- content: {
478
- apiVersion,
479
- supportedApiVersions: currentSupportedApiVersions
480
- }
481
- });
482
- } else {
483
- console.warn(`${versionError} is likely deprecated or not supported. ${supportedVersion}`);
484
- }
485
- }
486
- }
487
-
488
- // ../../node_modules/.bun/@shopify+graphql-client@1.4.2/node_modules/@shopify/graphql-client/dist/api-client-utilities/api-versions.mjs
489
- function getQuarterMonth(quarter) {
490
- const month = quarter * 3 - 2;
491
- return month === 10 ? month : `0${month}`;
492
- }
493
- function getPrevousVersion(year, quarter, nQuarter) {
494
- const versionQuarter = quarter - nQuarter;
495
- if (versionQuarter <= 0) {
496
- return `${year - 1}-${getQuarterMonth(versionQuarter + 4)}`;
497
- }
498
- return `${year}-${getQuarterMonth(versionQuarter)}`;
499
- }
500
- function getCurrentApiVersion() {
501
- const date = /* @__PURE__ */ new Date();
502
- const month = date.getUTCMonth();
503
- const year = date.getUTCFullYear();
504
- const quarter = Math.floor(month / 3 + 1);
505
- return {
506
- year,
507
- quarter,
508
- version: `${year}-${getQuarterMonth(quarter)}`
509
- };
510
- }
511
- function getCurrentSupportedApiVersions() {
512
- const { year, quarter, version: currentVersion } = getCurrentApiVersion();
513
- const nextVersion = quarter === 4 ? `${year + 1}-01` : `${year}-${getQuarterMonth(quarter + 1)}`;
514
- return [
515
- getPrevousVersion(year, quarter, 3),
516
- getPrevousVersion(year, quarter, 2),
517
- getPrevousVersion(year, quarter, 1),
518
- currentVersion,
519
- nextVersion,
520
- "unstable"
521
- ];
522
- }
523
-
524
- // ../../node_modules/.bun/@shopify+graphql-client@1.4.2/node_modules/@shopify/graphql-client/dist/api-client-utilities/utilities.mjs
525
- function generateGetHeaders(config) {
526
- return (customHeaders) => {
527
- return { ...customHeaders ?? {}, ...config.headers };
528
- };
529
- }
530
- function generateGetGQLClientParams({ getHeaders, getApiUrl }) {
531
- return (operation, options) => {
532
- const props = [operation];
533
- if (options && Object.keys(options).length > 0) {
534
- const { variables, apiVersion: propApiVersion, headers, retries, signal } = options;
535
- props.push({
536
- ...variables ? { variables } : {},
537
- ...headers ? { headers: getHeaders(headers) } : {},
538
- ...propApiVersion ? { url: getApiUrl(propApiVersion) } : {},
539
- ...retries ? { retries } : {},
540
- ...signal ? { signal } : {}
541
- });
542
- }
543
- return props;
544
- };
545
- }
546
-
547
- // ../../node_modules/.bun/@shopify+storefront-api-client@1.0.10/node_modules/@shopify/storefront-api-client/dist/constants.mjs
548
- var DEFAULT_CONTENT_TYPE = "application/json";
549
- var DEFAULT_SDK_VARIANT2 = "storefront-api-client";
550
- var DEFAULT_CLIENT_VERSION2 = "1.0.10";
551
- var PUBLIC_ACCESS_TOKEN_HEADER = "X-Shopify-Storefront-Access-Token";
552
- var PRIVATE_ACCESS_TOKEN_HEADER = "Shopify-Storefront-Private-Token";
553
- var SDK_VARIANT_HEADER2 = "X-SDK-Variant";
554
- var SDK_VERSION_HEADER2 = "X-SDK-Version";
555
- var SDK_VARIANT_SOURCE_HEADER = "X-SDK-Variant-Source";
556
- var CLIENT2 = "Storefront API Client";
557
-
558
- // ../../node_modules/.bun/@shopify+storefront-api-client@1.0.10/node_modules/@shopify/storefront-api-client/dist/validations.mjs
559
- function validatePrivateAccessTokenUsage(privateAccessToken) {
560
- if (privateAccessToken && typeof window !== "undefined") {
561
- throw new Error(`${CLIENT2}: private access tokens and headers should only be used in a server-to-server implementation. Use the public API access token in nonserver environments.`);
562
- }
563
- }
564
- function validateRequiredAccessTokens(publicAccessToken, privateAccessToken) {
565
- if (!publicAccessToken && !privateAccessToken) {
566
- throw new Error(`${CLIENT2}: a public or private access token must be provided`);
567
- }
568
- if (publicAccessToken && privateAccessToken) {
569
- throw new Error(`${CLIENT2}: only provide either a public or private access token`);
570
- }
571
- }
572
-
573
- // ../../node_modules/.bun/@shopify+storefront-api-client@1.0.10/node_modules/@shopify/storefront-api-client/dist/storefront-api-client.mjs
574
- function createStorefrontApiClient({ storeDomain, apiVersion, publicAccessToken, privateAccessToken, clientName, retries = 0, customFetchApi, logger: logger2 }) {
575
- const currentSupportedApiVersions = getCurrentSupportedApiVersions();
576
- const storeUrl = validateDomainAndGetStoreUrl({
577
- client: CLIENT2,
578
- storeDomain
579
- });
580
- const baseApiVersionValidationParams = {
581
- client: CLIENT2,
582
- currentSupportedApiVersions,
583
- logger: logger2
584
- };
585
- validateApiVersion({ ...baseApiVersionValidationParams, apiVersion });
586
- validateRequiredAccessTokens(publicAccessToken, privateAccessToken);
587
- validatePrivateAccessTokenUsage(privateAccessToken);
588
- const apiUrlFormatter = generateApiUrlFormatter(storeUrl, apiVersion, baseApiVersionValidationParams);
589
- const config = {
590
- storeDomain: storeUrl,
591
- apiVersion,
592
- ...publicAccessToken ? { publicAccessToken } : {
593
- privateAccessToken
594
- },
595
- headers: {
596
- "Content-Type": DEFAULT_CONTENT_TYPE,
597
- Accept: DEFAULT_CONTENT_TYPE,
598
- [SDK_VARIANT_HEADER2]: DEFAULT_SDK_VARIANT2,
599
- [SDK_VERSION_HEADER2]: DEFAULT_CLIENT_VERSION2,
600
- ...clientName ? { [SDK_VARIANT_SOURCE_HEADER]: clientName } : {},
601
- ...publicAccessToken ? { [PUBLIC_ACCESS_TOKEN_HEADER]: publicAccessToken } : { [PRIVATE_ACCESS_TOKEN_HEADER]: privateAccessToken }
602
- },
603
- apiUrl: apiUrlFormatter(),
604
- clientName
605
- };
606
- const graphqlClient = createGraphQLClient({
607
- headers: config.headers,
608
- url: config.apiUrl,
609
- retries,
610
- customFetchApi,
611
- logger: logger2
612
- });
613
- const getHeaders = generateGetHeaders(config);
614
- const getApiUrl = generateGetApiUrl(config, apiUrlFormatter);
615
- const getGQLClientParams = generateGetGQLClientParams({
616
- getHeaders,
617
- getApiUrl
618
- });
619
- const client = {
620
- config,
621
- getHeaders,
622
- getApiUrl,
623
- fetch: (...props) => {
624
- return graphqlClient.fetch(...getGQLClientParams(...props));
625
- },
626
- request: (...props) => {
627
- return graphqlClient.request(...getGQLClientParams(...props));
628
- },
629
- requestStream: (...props) => {
630
- return graphqlClient.requestStream(...getGQLClientParams(...props));
631
- }
632
- };
633
- return Object.freeze(client);
634
- }
635
- function generateApiUrlFormatter(storeUrl, defaultApiVersion, baseApiVersionValidationParams) {
636
- return (apiVersion) => {
637
- if (apiVersion) {
638
- validateApiVersion({
639
- ...baseApiVersionValidationParams,
640
- apiVersion
641
- });
642
- }
643
- const urlApiVersion = (apiVersion ?? defaultApiVersion).trim();
644
- return `${storeUrl}/api/${urlApiVersion}/graphql.json`;
645
- };
646
- }
647
- function generateGetApiUrl(config, apiUrlFormatter) {
648
- return (propApiVersion) => {
649
- return propApiVersion ? apiUrlFormatter(propApiVersion) : config.apiUrl;
650
- };
651
- }
3
+ var storefrontApiClient = require('@shopify/storefront-api-client');
4
+ var cacheTags = require('@shopkit/core/cache-tags');
652
5
 
653
6
  // src/adapters/shopify/client.ts
654
7
  function createShopifyStorefrontClient(config) {
655
8
  const { domain, storefrontAccessToken, apiVersion = "2025-04" } = config;
656
- const nativeClient = createStorefrontApiClient({
9
+ const nativeClient = storefrontApiClient.createStorefrontApiClient({
657
10
  storeDomain: domain,
658
11
  apiVersion,
659
12
  publicAccessToken: storefrontAccessToken
@@ -4344,8 +3697,12 @@ var BaseCustomService = class {
4344
3697
  headers,
4345
3698
  // Bound the upstream wait — see core/request-timeout.ts for the policy and
4346
3699
  // rationale (Bblunt prod memory-leak postmortem, Jun 2026).
4347
- signal: resolveRequestSignal(options, this.timeout)
3700
+ signal: resolveRequestSignal(options, this.timeout),
3701
+ ...options?.cache ? { cache: options.cache } : {}
4348
3702
  };
3703
+ if (options?.next) {
3704
+ requestOptions.next = options.next;
3705
+ }
4349
3706
  if (data && method !== "GET") {
4350
3707
  requestOptions.body = JSON.stringify(data);
4351
3708
  }
@@ -4613,7 +3970,15 @@ var ProductService2 = class extends BaseCustomService {
4613
3970
  PRODUCT_ENDPOINTS.getCollections(options?.version),
4614
3971
  "GET",
4615
3972
  void 0,
4616
- { params: queryParams, ...options || {} }
3973
+ {
3974
+ params: queryParams,
3975
+ ...options || {},
3976
+ // Broad collections tag so a catalog-wide change can revalidate the list.
3977
+ next: {
3978
+ ...options?.next || {},
3979
+ tags: [cacheTags.CacheTags.collections(), ...options?.next?.tags || []]
3980
+ }
3981
+ }
4617
3982
  );
4618
3983
  if (!result || !result.collections) {
4619
3984
  return formatResponse({
@@ -4663,7 +4028,18 @@ var ProductService2 = class extends BaseCustomService {
4663
4028
  const apiUrl = handle ? PRODUCT_ENDPOINTS.getCollectionByHandle(options?.version, handle) : PRODUCT_ENDPOINTS.getCollectionById(options?.version, id);
4664
4029
  const result = await this.request(apiUrl, "GET", void 0, {
4665
4030
  params: queryParams,
4666
- ...options || {}
4031
+ ...options || {},
4032
+ // Tag the collection read so a webhook can revalidateTag() it, refreshing
4033
+ // the collection page AND every grid built from it. GET only — Next caches
4034
+ // GET; the handle keys the entity. See @shopkit/core/cache-tags.
4035
+ next: {
4036
+ ...options?.next || {},
4037
+ tags: [
4038
+ cacheTags.CacheTags.collections(),
4039
+ ...handle ? [cacheTags.CacheTags.collection(handle)] : [],
4040
+ ...options?.next?.tags || []
4041
+ ]
4042
+ }
4667
4043
  });
4668
4044
  if (!result) {
4669
4045
  return formatResponse({