@makeswift/runtime 0.24.7-canary.1 → 0.24.7-canary.2

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 (73) hide show
  1. package/client/package.json +5 -0
  2. package/dist/cjs/client/index.js +686 -0
  3. package/dist/cjs/client/index.js.map +1 -0
  4. package/dist/cjs/next/api-handler/handlers/manifest.js +1 -1
  5. package/dist/cjs/next/client.js +8 -654
  6. package/dist/cjs/next/client.js.map +1 -1
  7. package/dist/cjs/next/components/MakeswiftComponent.js +1 -1
  8. package/dist/cjs/next/components/MakeswiftComponent.js.map +1 -1
  9. package/dist/cjs/next/components/Slot.js.map +1 -1
  10. package/dist/cjs/next/components/page.js +1 -1
  11. package/dist/cjs/next/components/page.js.map +1 -1
  12. package/dist/cjs/next/index.js.map +1 -1
  13. package/dist/cjs/runtimes/react/testing/element-data.js.map +1 -1
  14. package/dist/cjs/utils/async-iterable.js.map +1 -0
  15. package/dist/cjs/utils/pagination.js.map +1 -0
  16. package/dist/esm/client/index.js +671 -0
  17. package/dist/esm/client/index.js.map +1 -0
  18. package/dist/esm/next/api-handler/handlers/manifest.js +1 -1
  19. package/dist/esm/next/client.js +7 -662
  20. package/dist/esm/next/client.js.map +1 -1
  21. package/dist/esm/next/components/MakeswiftComponent.js +1 -1
  22. package/dist/esm/next/components/MakeswiftComponent.js.map +1 -1
  23. package/dist/esm/next/components/Slot.js.map +1 -1
  24. package/dist/esm/next/components/page.js +1 -1
  25. package/dist/esm/next/components/page.js.map +1 -1
  26. package/dist/esm/next/index.js.map +1 -1
  27. package/dist/esm/runtimes/react/testing/element-data.js.map +1 -1
  28. package/dist/esm/utils/async-iterable.js.map +1 -0
  29. package/dist/esm/utils/pagination.js.map +1 -0
  30. package/dist/types/client/index.d.ts +697 -0
  31. package/dist/types/client/index.d.ts.map +1 -0
  32. package/dist/types/client/tests/client.error-handling.test.d.ts.map +1 -0
  33. package/dist/types/client/tests/client.get-component-snapshot.test.d.ts.map +1 -0
  34. package/dist/types/client/tests/client.get-page-snapshot.test.d.ts.map +1 -0
  35. package/dist/types/client/tests/client.get-pages.test.d.ts.map +1 -0
  36. package/dist/types/client/tests/client.get-resources.test.d.ts.map +1 -0
  37. package/dist/types/next/client.d.ts +3 -690
  38. package/dist/types/next/client.d.ts.map +1 -1
  39. package/dist/types/next/components/MakeswiftComponent.d.ts +1 -1
  40. package/dist/types/next/components/MakeswiftComponent.d.ts.map +1 -1
  41. package/dist/types/next/components/Slot.d.ts +1 -1
  42. package/dist/types/next/components/Slot.d.ts.map +1 -1
  43. package/dist/types/next/components/page.d.ts +1 -1
  44. package/dist/types/next/components/page.d.ts.map +1 -1
  45. package/dist/types/next/index.d.ts +1 -1
  46. package/dist/types/next/index.d.ts.map +1 -1
  47. package/dist/types/runtimes/react/testing/element-data.d.ts +1 -1
  48. package/dist/types/runtimes/react/testing/element-data.d.ts.map +1 -1
  49. package/dist/types/utils/async-iterable.d.ts.map +1 -0
  50. package/dist/types/utils/pagination.d.ts.map +1 -0
  51. package/package.json +7 -1
  52. package/dist/cjs/next/utils/async-iterable.js.map +0 -1
  53. package/dist/cjs/next/utils/pagination.js.map +0 -1
  54. package/dist/esm/next/utils/async-iterable.js.map +0 -1
  55. package/dist/esm/next/utils/pagination.js.map +0 -1
  56. package/dist/types/next/tests/client.error-handling.test.d.ts.map +0 -1
  57. package/dist/types/next/tests/client.get-component-snapshot.test.d.ts.map +0 -1
  58. package/dist/types/next/tests/client.get-page-snapshot.test.d.ts.map +0 -1
  59. package/dist/types/next/tests/client.get-pages.test.d.ts.map +0 -1
  60. package/dist/types/next/tests/client.get-resources.test.d.ts.map +0 -1
  61. package/dist/types/next/utils/async-iterable.d.ts.map +0 -1
  62. package/dist/types/next/utils/pagination.d.ts.map +0 -1
  63. /package/dist/cjs/{next/utils → utils}/async-iterable.js +0 -0
  64. /package/dist/cjs/{next/utils → utils}/pagination.js +0 -0
  65. /package/dist/esm/{next/utils → utils}/async-iterable.js +0 -0
  66. /package/dist/esm/{next/utils → utils}/pagination.js +0 -0
  67. /package/dist/types/{next → client}/tests/client.error-handling.test.d.ts +0 -0
  68. /package/dist/types/{next → client}/tests/client.get-component-snapshot.test.d.ts +0 -0
  69. /package/dist/types/{next → client}/tests/client.get-page-snapshot.test.d.ts +0 -0
  70. /package/dist/types/{next → client}/tests/client.get-pages.test.d.ts +0 -0
  71. /package/dist/types/{next → client}/tests/client.get-resources.test.d.ts +0 -0
  72. /package/dist/types/{next/utils → utils}/async-iterable.d.ts +0 -0
  73. /package/dist/types/{next/utils → utils}/pagination.d.ts +0 -0
@@ -1,678 +1,23 @@
1
- import { z } from "zod";
2
- import {
3
- APIResourceType
4
- } from "../api";
5
- import { GraphQLClient } from "../api/graphql/client";
6
- import { FileQuery, IntrospectedResourcesQuery, TableQuery } from "../api/graphql/documents";
7
- import { CacheData } from "../api/react";
8
- import {
9
- getElementChildren,
10
- getSwatchIds,
11
- getFileIds,
12
- getPageIds,
13
- getTableIds,
14
- getTypographyIds
15
- } from "../prop-controllers/introspection";
16
- import {
17
- getPropControllerDescriptors,
18
- isElementReference
19
- } from "../state/react-page";
20
- import { getMakeswiftSiteVersion } from "./preview-mode";
21
1
  import { MakeswiftSiteVersion } from "../api/site-version";
22
- import { toIterablePaginationResult } from "./utils/pagination";
23
- import { deterministicUUID } from "../utils/deterministic-uuid";
24
- import { Schema } from "@makeswift/controls";
25
- import { EMBEDDED_DOCUMENT_TYPE } from "../state/modules/read-only-documents";
2
+ import { getMakeswiftSiteVersion } from "./preview-mode";
3
+ import { MakeswiftClient } from "../client";
26
4
  import { MAKESWIFT_CACHE_TAG } from "./cache";
27
- const makeswiftPageResultSchema = z.object({
28
- id: z.string(),
29
- path: z.string(),
30
- title: z.string().nullable(),
31
- description: z.string().nullable(),
32
- canonicalUrl: z.string().nullable(),
33
- socialImageUrl: z.string().nullable(),
34
- sitemapPriority: z.number().nullable(),
35
- sitemapFrequency: z.enum(["always", "hourly", "daily", "weekly", "monthly", "yearly", "never"]).nullable(),
36
- createdAt: z.string(),
37
- updatedAt: z.string(),
38
- publishedAt: z.string().nullable(),
39
- isOnline: z.boolean().nullable(),
40
- excludedFromSearch: z.boolean().nullable(),
41
- locale: z.string(),
42
- localizedVariants: z.array(
43
- z.object({
44
- locale: z.string(),
45
- path: z.string()
46
- })
47
- )
48
- });
49
- const makeswiftGetPagesResultAPISchema = z.object({
50
- data: z.array(makeswiftPageResultSchema),
51
- hasMore: z.boolean()
52
- });
53
- const makeswiftGetPagesParamsSchema = z.object({
54
- limit: z.number().optional(),
55
- after: z.string().optional(),
56
- sortBy: z.enum(["title", "path", "description", "createdAt", "updatedAt"]).optional(),
57
- sortDirection: z.enum(["asc", "desc"]).optional(),
58
- includeOffline: z.boolean().optional(),
59
- pathPrefix: z.string().optional(),
60
- locale: z.string().optional()
61
- });
62
- function getPagesQueryParams({
63
- limit = 20,
64
- after,
65
- sortBy,
66
- sortDirection,
67
- includeOffline,
68
- pathPrefix,
69
- locale
70
- }) {
71
- const params = new URLSearchParams();
72
- if (limit != null)
73
- params.set("limit", limit.toString());
74
- if (after != null)
75
- params.set("after", after);
76
- if (sortBy != null)
77
- params.set("sortBy", sortBy);
78
- if (sortDirection != null)
79
- params.set("sortDirection", sortDirection);
80
- if (includeOffline != null)
81
- params.set("includeOffline", includeOffline.toString());
82
- if (pathPrefix != null)
83
- params.set("pathPrefix", pathPrefix);
84
- if (locale != null)
85
- params.set("locale", locale);
86
- return params;
87
- }
88
- function pageToRootDocument(pageDocument) {
89
- const { locale, localizedPages, id, data } = pageDocument;
90
- const localizedPage = localizedPages.find(({ parentId }) => parentId == null);
91
- return localizedPage ? { key: localizedPage.elementTreeId, rootElement: localizedPage.data, locale } : { key: id, rootElement: data, locale };
92
- }
93
- const makeswiftComponentDocumentSchema = z.object({
94
- id: z.string(),
95
- name: z.string().nullable(),
96
- locale: z.string().nullable(),
97
- data: Schema.element,
98
- siteId: z.string(),
99
- inheritsFromParent: z.boolean()
100
- });
101
- const makeswiftComponentDocumentFallbackSchema = z.object({
102
- id: z.string(),
103
- locale: z.string().nullable(),
104
- data: z.null()
105
- });
106
- function componentDocumentToRootEmbeddedDocument({
107
- document,
108
- documentKey,
109
- name,
110
- type,
111
- meta
112
- }) {
113
- const { data: rootElement, locale, id } = document;
114
- if (rootElement != null && rootElement.type !== type) {
115
- throw new Error(
116
- `Type "${rootElement.type}" does not match the expected type "${type}" from the snapshot`
117
- );
118
- }
119
- const rootDocument = {
120
- key: documentKey,
121
- rootElement: rootElement ?? {
122
- // Fallback rootElement
123
- // Create a stable uuid so two different clients will have the same empty element data.
124
- // This is needed to make presence feature work for an element that is not yet created.
125
- key: deterministicUUID({ id, locale, seed: documentKey }),
126
- type,
127
- props: {}
128
- },
129
- locale,
130
- id,
131
- type,
132
- name,
133
- meta,
134
- __type: EMBEDDED_DOCUMENT_TYPE
135
- };
136
- return rootDocument;
137
- }
138
- async function failedResponseBody(response) {
139
- try {
140
- const text = await response.text();
141
- try {
142
- return JSON.parse(text);
143
- } catch {
144
- return text;
145
- }
146
- } catch (e) {
147
- return `Failed to extract response body: ${e}`;
148
- }
149
- }
150
- function responseError(response) {
151
- return `${response.status} ${response.statusText}`;
152
- }
153
- const pagePathnameSlicesAPISchema = z.array(
154
- z.object({
155
- id: z.string(),
156
- basePageId: z.string(),
157
- pathname: z.string(),
158
- localizedPathname: z.string().optional(),
159
- __typename: z.literal("PagePathnameSlice")
160
- }).nullable()
161
- );
162
- const getPageAPISchema = z.object({
163
- pathname: z.string(),
164
- locale: z.string(),
165
- alternate: z.array(
166
- z.object({
167
- pathname: z.string(),
168
- locale: z.string()
169
- })
170
- )
171
- });
172
- class Makeswift {
173
- apiKey;
174
- apiOrigin;
175
- graphqlClient;
176
- runtime;
5
+ class Makeswift extends MakeswiftClient {
177
6
  static getSiteVersion(previewData) {
178
7
  return getMakeswiftSiteVersion(previewData) ?? MakeswiftSiteVersion.Live;
179
8
  }
180
9
  static getPreviewMode(previewData) {
181
10
  return getMakeswiftSiteVersion(previewData) === MakeswiftSiteVersion.Working;
182
11
  }
183
- constructor(apiKey, { apiOrigin = "https://api.makeswift.com", runtime }) {
184
- if (typeof apiKey !== "string") {
185
- throw new Error(
186
- `The Makeswift client must be passed a valid Makeswift site API key: \`new Makeswift('<makeswift_site_api_key>')\`
187
- Received "${apiKey}" instead.`
188
- );
189
- }
190
- this.apiKey = apiKey;
191
- try {
192
- this.apiOrigin = new URL(apiOrigin);
193
- } catch {
194
- throw new Error(
195
- `The Makeswift client received an invalid \`apiOrigin\` parameter: "${apiOrigin}".`
196
- );
197
- }
198
- this.graphqlClient = new GraphQLClient(new URL("graphql", apiOrigin).href);
199
- this.runtime = runtime;
200
- }
201
- async fetch(path, siteVersion = MakeswiftSiteVersion.Live, init) {
202
- const response = await fetch(new URL(path, this.apiOrigin).toString(), {
203
- ...init,
204
- headers: {
205
- ["X-API-Key"]: this.apiKey,
206
- "Makeswift-Site-API-Key": this.apiKey,
207
- "Makeswift-Site-Version": siteVersion,
208
- ...init?.headers
209
- },
210
- ...siteVersion === MakeswiftSiteVersion.Working ? { cache: "no-store" } : {},
211
- next: {
212
- ...init?.next,
213
- tags: [...init?.next?.tags ?? [], MAKESWIFT_CACHE_TAG]
214
- }
215
- });
216
- return response;
217
- }
218
- getPagesInternal = async ({
219
- siteVersion = MakeswiftSiteVersion.Live,
220
- ...params
221
- } = {}) => {
222
- const queryParams = getPagesQueryParams(params);
223
- const response = await this.fetch(`v4/pages?${queryParams.toString()}`, siteVersion);
224
- if (!response.ok) {
225
- console.error("Failed to get pages", {
226
- response: await failedResponseBody(response),
227
- siteVersion,
228
- params
229
- });
230
- throw new Error(`Failed to get pages: ${responseError(response)}`);
231
- }
232
- const result = await response.json();
233
- const parsedResponse = makeswiftGetPagesResultAPISchema.safeParse(result);
234
- if (!parsedResponse.success) {
235
- throw new Error(
236
- `Failed to parse 'getPages' response: ${parsedResponse.error.errors.map((e) => e.message).join("; ")}`
237
- );
238
- }
239
- return parsedResponse.data;
240
- };
241
- getPages = toIterablePaginationResult(this.getPagesInternal);
242
- async getPage(pathname, {
243
- siteVersion = MakeswiftSiteVersion.Live,
244
- locale
245
- } = {}) {
246
- const url = new URL(`v2/pages/${encodeURIComponent(pathname)}`, this.apiOrigin);
247
- if (locale)
248
- url.searchParams.set("locale", locale);
249
- const response = await this.fetch(url.pathname + url.search, siteVersion);
250
- if (!response.ok) {
251
- if (response.status === 404)
252
- return null;
253
- console.error(`Failed to get page snapshot for '${pathname}'`, {
254
- response: await failedResponseBody(response),
255
- siteVersion,
256
- locale
257
- });
258
- throw new Error(`Failed to get page snapshot for '${pathname}': ${responseError(response)}`);
259
- }
260
- const json = await response.json();
261
- return getPageAPISchema.parse(json);
262
- }
263
- async getTypographies(typographyIds, siteVersion) {
264
- if (typographyIds.length === 0)
265
- return [];
266
- const url = new URL(`v2/typographies/bulk`, this.apiOrigin);
267
- typographyIds.forEach((id) => {
268
- url.searchParams.append("ids", id);
269
- });
270
- const response = await this.fetch(url.pathname + url.search, siteVersion);
271
- if (!response.ok) {
272
- console.error(`Failed to get typographies for [${typographyIds.join(", ")}]`, {
273
- response: await failedResponseBody(response),
274
- siteVersion
275
- });
276
- return [];
277
- }
278
- const body = await response.json();
279
- return body;
280
- }
281
- async getSwatches(ids, siteVersion) {
282
- if (ids.length === 0)
283
- return [];
284
- const url = new URL(`v2/swatches/bulk`, this.apiOrigin);
285
- ids.forEach((id) => {
286
- url.searchParams.append("ids", id);
287
- });
288
- const response = await this.fetch(url.pathname + url.search, siteVersion);
289
- if (!response.ok) {
290
- console.error(`Failed to get swatches for ${ids.join(", ")}`, {
291
- response: await failedResponseBody(response),
292
- siteVersion
293
- });
294
- return [];
295
- }
296
- return await response.json();
297
- }
298
- async getIntrospectedResources({
299
- swatchIds,
300
- ...introspectedResourceIds
301
- }, siteVersion) {
302
- const result = await this.graphqlClient.request(IntrospectedResourcesQuery, introspectedResourceIds);
303
- const swatches = await this.getSwatches(swatchIds, siteVersion);
304
- return { ...result, swatches };
305
- }
306
- async introspect(element, siteVersion, locale) {
307
- const runtime = this.runtime;
308
- const descriptors = getPropControllerDescriptors(runtime.store.getState());
309
- const swatchIds = /* @__PURE__ */ new Set();
310
- const fileIds = /* @__PURE__ */ new Set();
311
- const typographyIds = /* @__PURE__ */ new Set();
312
- const tableIds = /* @__PURE__ */ new Set();
313
- const pageIds = /* @__PURE__ */ new Set();
314
- const globalElements = /* @__PURE__ */ new Map();
315
- const localizedGlobalElements = /* @__PURE__ */ new Map();
316
- const localizedResourcesMap = /* @__PURE__ */ new Map();
317
- const remaining = [element];
318
- const seen = /* @__PURE__ */ new Set();
319
- let current;
320
- while (current = remaining.pop()) {
321
- let getResourcesFromElementDescriptors2 = function(elementDescriptors2, props) {
322
- Object.entries(elementDescriptors2).forEach(([propName, descriptor]) => {
323
- getSwatchIds(descriptor, props[propName]).forEach((swatchId) => {
324
- swatchIds.add(swatchId);
325
- });
326
- getFileIds(descriptor, props[propName]).forEach((fileId) => fileIds.add(fileId));
327
- getTypographyIds(descriptor, props[propName]).forEach(
328
- (typographyId) => typographyIds.add(typographyId)
329
- );
330
- getTableIds(descriptor, props[propName]).forEach((tableId) => tableIds.add(tableId));
331
- getPageIds(descriptor, props[propName]).forEach((pageId) => pageIds.add(pageId));
332
- getElementChildren(descriptor, props[propName]).forEach((child) => {
333
- if (!seen.has(child.key)) {
334
- seen.add(child.key);
335
- remaining.push(child);
336
- }
337
- });
338
- });
339
- };
340
- var getResourcesFromElementDescriptors = getResourcesFromElementDescriptors2;
341
- let element2;
342
- if (isElementReference(current)) {
343
- const globalElementId = current.value;
344
- const globalElement = await this.getGlobalElement(globalElementId, siteVersion);
345
- let elementData = globalElement?.data;
346
- if (locale) {
347
- const localizedGlobalElement = await this.getLocalizedGlobalElement(
348
- globalElementId,
349
- locale,
350
- siteVersion
351
- );
352
- if (localizedGlobalElement) {
353
- elementData = localizedGlobalElement.data;
354
- localizedResourcesMap.set(globalElementId, localizedGlobalElement.id);
355
- localizedGlobalElements.set(localizedGlobalElement.id, localizedGlobalElement);
356
- }
357
- }
358
- globalElements.set(globalElementId, globalElement);
359
- if (elementData == null)
360
- continue;
361
- element2 = elementData;
362
- } else {
363
- element2 = current;
364
- }
365
- const elementDescriptors = descriptors.get(element2.type);
366
- if (elementDescriptors == null)
367
- continue;
368
- getResourcesFromElementDescriptors2(elementDescriptors, element2.props);
369
- }
370
- const typographies = await this.getTypographies([...typographyIds], siteVersion);
371
- typographies.forEach((typography) => {
372
- typography?.style.forEach((style) => {
373
- const swatchId = style.value.color?.swatchId;
374
- if (swatchId != null)
375
- swatchIds.add(swatchId);
376
- });
377
- });
378
- const pagePathnames = await this.getPagePathnameSlices([...pageIds], siteVersion, { locale });
379
- const { swatches, files, tables } = await this.getIntrospectedResources(
380
- {
381
- swatchIds: [...swatchIds],
382
- fileIds: [...fileIds],
383
- tableIds: [...tableIds]
384
- },
385
- siteVersion
386
- );
387
- const apiResources = {
388
- [APIResourceType.Swatch]: [...swatchIds].map((id) => ({
389
- id,
390
- value: swatches.find((swatch) => swatch?.id === id) ?? null
391
- })),
392
- [APIResourceType.File]: [...fileIds].map((id) => ({
393
- id,
394
- value: files.find((file) => file?.id === id) ?? null
395
- })),
396
- [APIResourceType.Typography]: [...typographyIds].map((id) => ({
397
- id,
398
- value: typographies.find((typography) => typography?.id === id) ?? null
399
- })),
400
- [APIResourceType.Table]: [...tableIds].map((id) => ({
401
- id,
402
- value: tables.find((table) => table?.id === id) ?? null
403
- })),
404
- [APIResourceType.PagePathnameSlice]: [...pageIds].map((id) => ({
405
- id,
406
- value: pagePathnames.find((pagePathnameSlice) => pagePathnameSlice?.id === id) ?? null,
407
- locale
408
- })),
409
- [APIResourceType.GlobalElement]: [...globalElements.entries()].map(([id, value]) => ({
410
- id,
411
- value
412
- })),
413
- [APIResourceType.LocalizedGlobalElement]: [...localizedGlobalElements.entries()].map(
414
- ([id, value]) => ({
415
- id,
416
- value,
417
- locale
418
- })
419
- )
420
- };
12
+ fetchOptions(_siteVersion) {
421
13
  return {
422
- apiResources,
423
- localizedResourcesMap: locale != null ? { [locale]: Object.fromEntries(localizedResourcesMap.entries()) } : {}
424
- };
425
- }
426
- async getPageSnapshot(pathname, {
427
- siteVersion: siteVersionPromise,
428
- locale,
429
- allowLocaleFallback = true
430
- }) {
431
- const queryParams = () => {
432
- const params = new URLSearchParams();
433
- if (locale)
434
- params.set("locale", locale);
435
- if (allowLocaleFallback != null)
436
- params.set("allowLocaleFallback", `${allowLocaleFallback}`);
437
- return params.toString();
438
- };
439
- const siteVersion = await siteVersionPromise;
440
- const response = await this.fetch(
441
- `v3/pages/${encodeURIComponent(pathname)}/document?${queryParams()}`,
442
- siteVersion
443
- );
444
- if (!response.ok) {
445
- if (response.status === 404)
446
- return null;
447
- console.error(`Failed to get page snapshot for '${pathname}'`, {
448
- response: await failedResponseBody(response),
449
- siteVersion,
450
- locale
451
- });
452
- throw new Error(`Failed to get page snapshot for '${pathname}': ${responseError(response)}`);
453
- }
454
- const document = await response.json();
455
- const baseLocalizedPage = document.localizedPages.find(({ parentId }) => parentId == null);
456
- const cacheData = await this.introspect(
457
- baseLocalizedPage?.data ?? document.data,
458
- siteVersion,
459
- // The /v3/pages endpoint returns null for document.locale when the requested locale is the default.
460
- // This legacy behavior is set to change with the upcoming /v4/pages endpoint.
461
- // We rely on document.locale when reading from the API cache, so ensure the cache is built during
462
- // introspection using the same value.
463
- document.locale
464
- );
465
- return {
466
- document,
467
- cacheData
468
- };
469
- }
470
- async getComponentSnapshot(id, {
471
- siteVersion: siteVersionPromise,
472
- locale,
473
- allowLocaleFallback = true
474
- }) {
475
- const searchParams = new URLSearchParams();
476
- if (locale)
477
- searchParams.set("locale", locale);
478
- const siteVersion = await siteVersionPromise;
479
- const key = deterministicUUID({ id, locale, seed: this.apiKey.split("-").at(0) });
480
- const baseLocaleWasRequested = locale == null;
481
- const canAttemptLocaleFallback = !baseLocaleWasRequested && allowLocaleFallback;
482
- let response;
483
- const responseForRequestedLocale = await this.fetch(
484
- `v1/element-trees/${encodeURIComponent(id)}?${searchParams.toString()}`,
485
- siteVersion
486
- );
487
- if (responseForRequestedLocale.status === 404 && canAttemptLocaleFallback) {
488
- response = await this.fetch(`v1/element-trees/${encodeURIComponent(id)}`, siteVersion);
489
- } else {
490
- response = responseForRequestedLocale;
491
- }
492
- if (!response.ok) {
493
- if (response.status === 404) {
494
- return {
495
- document: {
496
- id,
497
- locale: locale ?? null,
498
- data: null
499
- },
500
- key,
501
- cacheData: CacheData.empty(),
502
- meta: {
503
- allowLocaleFallback,
504
- requestedLocale: locale ?? null
505
- }
506
- };
507
- }
508
- console.error(`Failed to get component snapshot for '${id}':`, {
509
- response: await failedResponseBody(response),
510
- siteVersion,
511
- locale
512
- });
513
- throw new Error(`Failed to get component snapshot for '${id}': ${responseError(response)}`);
514
- }
515
- const document = makeswiftComponentDocumentSchema.parse(await response.json());
516
- const cacheData = await this.introspect(document.data, siteVersion, locale ?? null);
517
- return {
518
- document,
519
- cacheData,
520
- key,
521
- meta: {
522
- allowLocaleFallback,
523
- requestedLocale: locale ?? null
14
+ next: {
15
+ tags: [MAKESWIFT_CACHE_TAG]
524
16
  }
525
17
  };
526
18
  }
527
- async getSwatch(swatchId, siteVersion) {
528
- const response = await this.fetch(`v2/swatches/${swatchId}`, siteVersion);
529
- if (!response.ok) {
530
- if (response.status !== 404) {
531
- console.error(`Failed to get swatch '${swatchId}'`, {
532
- response: await failedResponseBody(response),
533
- siteVersion
534
- });
535
- }
536
- return null;
537
- }
538
- const swatch = await response.json();
539
- return swatch;
540
- }
541
- async getFile(fileId) {
542
- const result = await this.graphqlClient.request(
543
- FileQuery,
544
- { fileId }
545
- );
546
- return result.file;
547
- }
548
- async getTypography(typographyId, siteVersion) {
549
- const response = await this.fetch(`v2/typographies/${typographyId}`, siteVersion);
550
- if (!response.ok) {
551
- if (response.status !== 404) {
552
- console.error(`Failed to get typography '${typographyId}'`, {
553
- response: await failedResponseBody(response),
554
- siteVersion
555
- });
556
- }
557
- return null;
558
- }
559
- const typography = await response.json();
560
- return typography;
561
- }
562
- async getGlobalElement(globalElementId, siteVersion) {
563
- const response = await this.fetch(`v2/global-elements/${globalElementId}`, siteVersion);
564
- if (!response.ok) {
565
- if (response.status !== 404) {
566
- console.error(`Failed to get global element '${globalElementId}'`, {
567
- response: await failedResponseBody(response),
568
- siteVersion
569
- });
570
- }
571
- return null;
572
- }
573
- const globalElement = await response.json();
574
- return globalElement;
575
- }
576
- async getLocalizedGlobalElement(globalElementId, locale, siteVersion) {
577
- const response = await this.fetch(
578
- `v2/localized-global-elements/${globalElementId}?locale=${locale}`,
579
- siteVersion
580
- );
581
- if (!response.ok) {
582
- if (response.status !== 404) {
583
- console.error(`Failed to get localized global element '${globalElementId}'`, {
584
- response: await failedResponseBody(response),
585
- siteVersion,
586
- locale
587
- });
588
- }
589
- return null;
590
- }
591
- const localizedGlobalElement = await response.json();
592
- return localizedGlobalElement;
593
- }
594
- async getPagePathnameSlices(pageIds, siteVersion, { locale }) {
595
- if (pageIds.length === 0)
596
- return [];
597
- const url = new URL(`v2/page-pathname-slices/bulk`, this.apiOrigin);
598
- pageIds.forEach((id) => url.searchParams.append("ids", id));
599
- if (locale != null)
600
- url.searchParams.set("locale", locale);
601
- const response = await this.fetch(url.pathname + url.search, siteVersion);
602
- if (!response.ok) {
603
- console.error(`Failed to get page pathname slice(s) for ${pageIds.join(", ")}`, {
604
- response: await failedResponseBody(response),
605
- siteVersion,
606
- locale
607
- });
608
- return [];
609
- }
610
- const json = await response.json();
611
- const pagePathnameSlices = pagePathnameSlicesAPISchema.parse(json);
612
- return pagePathnameSlices.map((pagePathnameSlice) => {
613
- if (pagePathnameSlice == null)
614
- return null;
615
- return {
616
- ...pagePathnameSlice,
617
- id: pagePathnameSlice.basePageId,
618
- localizedPathname: pagePathnameSlice.localizedPathname ?? null
619
- };
620
- });
621
- }
622
- async getPagePathnameSlice(pageId, siteVersion, { locale } = {}) {
623
- const pagePathnameSlices = await this.getPagePathnameSlices([pageId], siteVersion, { locale });
624
- return pagePathnameSlices.at(0) ?? null;
625
- }
626
- async getTable(tableId) {
627
- const result = await this.graphqlClient.request(
628
- TableQuery,
629
- { tableId }
630
- );
631
- return result.table;
632
- }
633
- /**
634
- * @deprecated `getSitemap` is deprecated. We recommend constructing a sitemap
635
- * using data from `getPages` instead.
636
- */
637
- async getSitemap({
638
- limit = 50,
639
- after,
640
- pathnamePrefix,
641
- locale
642
- } = {}) {
643
- const url = new URL("v1/sitemap", this.apiOrigin);
644
- url.searchParams.set("limit", limit.toString());
645
- if (after != null)
646
- url.searchParams.set("after", after);
647
- if (pathnamePrefix != null)
648
- url.searchParams.set("pathnamePrefix", pathnamePrefix);
649
- if (locale != null)
650
- url.searchParams.set("locale", locale);
651
- const response = await this.fetch(url.pathname + url.search);
652
- if (!response.ok) {
653
- console.error("Failed to get sitemap ", {
654
- response: await failedResponseBody(response),
655
- limit,
656
- after,
657
- pathnamePrefix,
658
- locale
659
- });
660
- throw new Error(`Failed to get sitemap with error: ${responseError(response)}`);
661
- }
662
- const sitemap = await response.json();
663
- return sitemap;
664
- }
665
- getTranslatableData(elementTree) {
666
- return this.runtime.getTranslatableData(elementTree);
667
- }
668
- mergeTranslatedData(elementTree, translatedData) {
669
- return this.runtime.mergeTranslatedData(elementTree, translatedData);
670
- }
671
19
  }
672
20
  export {
673
- Makeswift,
674
- componentDocumentToRootEmbeddedDocument,
675
- failedResponseBody,
676
- pageToRootDocument
21
+ Makeswift
677
22
  };
678
23
  //# sourceMappingURL=client.js.map