@prismicio/client 7.10.0-alpha.0 → 7.10.1

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 (121) hide show
  1. package/dist/BaseClient.cjs +108 -0
  2. package/dist/BaseClient.cjs.map +1 -0
  3. package/dist/BaseClient.d.ts +152 -0
  4. package/dist/BaseClient.js +108 -0
  5. package/dist/BaseClient.js.map +1 -0
  6. package/dist/Client.cjs +1217 -0
  7. package/dist/Client.cjs.map +1 -0
  8. package/dist/Client.d.ts +924 -0
  9. package/dist/Client.js +1217 -0
  10. package/dist/Client.js.map +1 -0
  11. package/dist/Migration.cjs +318 -0
  12. package/dist/Migration.cjs.map +1 -0
  13. package/dist/Migration.d.ts +213 -0
  14. package/dist/Migration.js +318 -0
  15. package/dist/Migration.js.map +1 -0
  16. package/dist/WriteClient.cjs +515 -0
  17. package/dist/WriteClient.cjs.map +1 -0
  18. package/dist/WriteClient.d.ts +314 -0
  19. package/dist/WriteClient.js +515 -0
  20. package/dist/WriteClient.js.map +1 -0
  21. package/dist/createClient.cjs +2 -1215
  22. package/dist/createClient.cjs.map +1 -1
  23. package/dist/createClient.d.ts +2 -1003
  24. package/dist/createClient.js +1 -1214
  25. package/dist/createClient.js.map +1 -1
  26. package/dist/createMigration.cjs +6 -0
  27. package/dist/createMigration.cjs.map +1 -0
  28. package/dist/createMigration.d.ts +24 -0
  29. package/dist/createMigration.js +6 -0
  30. package/dist/createMigration.js.map +1 -0
  31. package/dist/createWriteClient.cjs +6 -0
  32. package/dist/createWriteClient.cjs.map +1 -0
  33. package/dist/createWriteClient.d.ts +32 -0
  34. package/dist/createWriteClient.js +6 -0
  35. package/dist/createWriteClient.js.map +1 -0
  36. package/dist/getRepositoryName.cjs +7 -2
  37. package/dist/getRepositoryName.cjs.map +1 -1
  38. package/dist/getRepositoryName.d.ts +3 -6
  39. package/dist/getRepositoryName.js +7 -2
  40. package/dist/getRepositoryName.js.map +1 -1
  41. package/dist/index.cjs +14 -1
  42. package/dist/index.cjs.map +1 -1
  43. package/dist/index.d.ts +17 -2
  44. package/dist/index.js +14 -1
  45. package/dist/index.js.map +1 -1
  46. package/dist/lib/isMigrationValue.cjs +24 -0
  47. package/dist/lib/isMigrationValue.cjs.map +1 -0
  48. package/dist/lib/isMigrationValue.d.ts +62 -0
  49. package/dist/lib/isMigrationValue.js +24 -0
  50. package/dist/lib/isMigrationValue.js.map +1 -0
  51. package/dist/lib/isValue.cjs +53 -0
  52. package/dist/lib/isValue.cjs.map +1 -0
  53. package/dist/lib/isValue.d.ts +72 -0
  54. package/dist/lib/isValue.js +53 -0
  55. package/dist/lib/isValue.js.map +1 -0
  56. package/dist/lib/pLimit.cjs +49 -0
  57. package/dist/lib/pLimit.cjs.map +1 -0
  58. package/dist/lib/pLimit.d.ts +22 -0
  59. package/dist/lib/pLimit.js +49 -0
  60. package/dist/lib/pLimit.js.map +1 -0
  61. package/dist/lib/resolveMigrationDocumentData.cjs +123 -0
  62. package/dist/lib/resolveMigrationDocumentData.cjs.map +1 -0
  63. package/dist/lib/resolveMigrationDocumentData.d.ts +52 -0
  64. package/dist/lib/resolveMigrationDocumentData.js +123 -0
  65. package/dist/lib/resolveMigrationDocumentData.js.map +1 -0
  66. package/dist/lib/validateAssetMetadata.cjs +28 -0
  67. package/dist/lib/validateAssetMetadata.cjs.map +1 -0
  68. package/dist/lib/validateAssetMetadata.d.ts +10 -0
  69. package/dist/lib/validateAssetMetadata.js +28 -0
  70. package/dist/lib/validateAssetMetadata.js.map +1 -0
  71. package/dist/package.json.cjs +1 -1
  72. package/dist/package.json.js +1 -1
  73. package/dist/types/api/asset/asset.d.ts +177 -0
  74. package/dist/types/api/asset/tag.d.ts +53 -0
  75. package/dist/types/api/migration/document.d.ts +60 -0
  76. package/dist/types/migration/Asset.cjs +33 -0
  77. package/dist/types/migration/Asset.cjs.map +1 -0
  78. package/dist/types/migration/Asset.d.ts +109 -0
  79. package/dist/types/migration/Asset.js +33 -0
  80. package/dist/types/migration/Asset.js.map +1 -0
  81. package/dist/types/migration/ContentRelationship.d.ts +17 -0
  82. package/dist/types/migration/Document.cjs +47 -0
  83. package/dist/types/migration/Document.cjs.map +1 -0
  84. package/dist/types/migration/Document.d.ts +94 -0
  85. package/dist/types/migration/Document.js +47 -0
  86. package/dist/types/migration/Document.js.map +1 -0
  87. package/dist/types/model/link.cjs.map +1 -1
  88. package/dist/types/model/link.d.ts +0 -1
  89. package/dist/types/model/link.js.map +1 -1
  90. package/dist/types/model/linkToMedia.d.ts +0 -1
  91. package/dist/types/value/contentRelationship.d.ts +0 -1
  92. package/dist/types/value/link.cjs.map +1 -1
  93. package/dist/types/value/link.d.ts +0 -2
  94. package/dist/types/value/link.js.map +1 -1
  95. package/dist/types/value/linkToMedia.d.ts +0 -1
  96. package/package.json +2 -2
  97. package/src/BaseClient.ts +330 -0
  98. package/src/Client.ts +1787 -0
  99. package/src/Migration.ts +531 -0
  100. package/src/WriteClient.ts +916 -0
  101. package/src/createClient.ts +3 -1931
  102. package/src/createMigration.ts +31 -0
  103. package/src/createWriteClient.ts +43 -0
  104. package/src/getRepositoryName.ts +19 -14
  105. package/src/index.ts +32 -4
  106. package/src/lib/isMigrationValue.ts +126 -0
  107. package/src/lib/isValue.ts +196 -0
  108. package/src/lib/pLimit.ts +106 -0
  109. package/src/lib/resolveMigrationDocumentData.ts +233 -0
  110. package/src/lib/validateAssetMetadata.ts +82 -0
  111. package/src/types/api/asset/asset.ts +211 -0
  112. package/src/types/api/asset/tag.ts +59 -0
  113. package/src/types/api/migration/document.ts +84 -0
  114. package/src/types/migration/Asset.ts +156 -0
  115. package/src/types/migration/ContentRelationship.ts +36 -0
  116. package/src/types/migration/Document.ts +157 -0
  117. package/src/types/model/link.ts +0 -1
  118. package/src/types/model/linkToMedia.ts +0 -1
  119. package/src/types/value/contentRelationship.ts +0 -1
  120. package/src/types/value/link.ts +0 -2
  121. package/src/types/value/linkToMedia.ts +0 -1
package/dist/Client.js ADDED
@@ -0,0 +1,1217 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __typeError = (msg) => {
3
+ throw TypeError(msg);
4
+ };
5
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
6
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
7
+ var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
8
+ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
9
+ var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
10
+ var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
11
+ var _repositoryName;
12
+ import { appendFilters } from "./lib/appendFilters.js";
13
+ import { castThunk } from "./lib/castThunk.js";
14
+ import { devMsg } from "./lib/devMsg.js";
15
+ import { everyTagFilter } from "./lib/everyTagFilter.js";
16
+ import { findMasterRef } from "./lib/findMasterRef.js";
17
+ import { findRefByID } from "./lib/findRefByID.js";
18
+ import { findRefByLabel } from "./lib/findRefByLabel.js";
19
+ import { getPreviewCookie } from "./lib/getPreviewCookie.js";
20
+ import { minifyGraphQLQuery } from "./lib/minifyGraphQLQuery.js";
21
+ import { someTagsFilter } from "./lib/someTagsFilter.js";
22
+ import { typeFilter } from "./lib/typeFilter.js";
23
+ import { ForbiddenError } from "./errors/ForbiddenError.js";
24
+ import { NotFoundError } from "./errors/NotFoundError.js";
25
+ import { ParsingError } from "./errors/ParsingError.js";
26
+ import { PreviewTokenExpiredError } from "./errors/PreviewTokenExpired.js";
27
+ import { PrismicError } from "./errors/PrismicError.js";
28
+ import { RefExpiredError } from "./errors/RefExpiredError.js";
29
+ import { RefNotFoundError } from "./errors/RefNotFoundError.js";
30
+ import { RepositoryNotFoundError } from "./errors/RepositoryNotFoundError.js";
31
+ import { asLink } from "./helpers/asLink.js";
32
+ import { BaseClient } from "./BaseClient.js";
33
+ import { buildQueryURL } from "./buildQueryURL.js";
34
+ import { filter } from "./filter.js";
35
+ import { getRepositoryEndpoint } from "./getRepositoryEndpoint.js";
36
+ import { getRepositoryName } from "./getRepositoryName.js";
37
+ import { isRepositoryEndpoint } from "./isRepositoryEndpoint.js";
38
+ const MAX_PAGE_SIZE = 100;
39
+ const REPOSITORY_CACHE_TTL = 5e3;
40
+ const GET_ALL_QUERY_DELAY = 500;
41
+ const DEFUALT_RETRY_AFTER_MS = 1e3;
42
+ var RefStateMode;
43
+ (function(RefStateMode2) {
44
+ RefStateMode2["Master"] = "Master";
45
+ RefStateMode2["ReleaseID"] = "ReleaseID";
46
+ RefStateMode2["ReleaseLabel"] = "ReleaseLabel";
47
+ RefStateMode2["Manual"] = "Manual";
48
+ })(RefStateMode || (RefStateMode = {}));
49
+ class Client extends BaseClient {
50
+ /**
51
+ * Creates a Prismic client that can be used to query a repository.
52
+ *
53
+ * If used in an environment where a global `fetch` function is unavailable,
54
+ * such as in some Node.js versions, the `fetch` option must be provided as
55
+ * part of the `options` parameter.
56
+ *
57
+ * @param repositoryNameOrEndpoint - The Prismic repository name or full Rest
58
+ * API V2 endpoint for the repository.
59
+ * @param options - Configuration that determines how content will be queried
60
+ * from the Prismic repository.
61
+ *
62
+ * @returns A client that can query content from the repository.
63
+ */
64
+ constructor(repositoryNameOrEndpoint, options = {}) {
65
+ super(options);
66
+ __privateAdd(this, _repositoryName);
67
+ /**
68
+ * The Prismic REST API V2 endpoint for the repository (use
69
+ * `prismic.getRepositoryEndpoint` for the default endpoint).
70
+ */
71
+ __publicField(this, "documentAPIEndpoint");
72
+ /**
73
+ * The secure token for accessing the API (only needed if your repository is
74
+ * set to private).
75
+ *
76
+ * {@link https://user-guides.prismic.io/en/articles/1036153-generating-an-access-token}
77
+ */
78
+ __publicField(this, "accessToken");
79
+ /**
80
+ * A list of route resolver objects that define how a document's `url` field
81
+ * is resolved.
82
+ *
83
+ * {@link https://prismic.io/docs/route-resolver}
84
+ */
85
+ __publicField(this, "routes");
86
+ /**
87
+ * The `brokenRoute` option allows you to define the route populated in the
88
+ * `url` property for broken link or content relationship fields. A broken
89
+ * link is a link or content relationship field whose linked document has been
90
+ * unpublished or deleted.
91
+ *
92
+ * {@link https://prismic.io/docs/route-resolver}
93
+ */
94
+ __publicField(this, "brokenRoute");
95
+ /**
96
+ * Default parameters that will be sent with each query. These parameters can
97
+ * be overridden on each query if needed.
98
+ */
99
+ __publicField(this, "defaultParams");
100
+ /**
101
+ * The client's ref mode state. This determines which ref is used during
102
+ * queries.
103
+ */
104
+ __publicField(this, "refState", {
105
+ mode: RefStateMode.Master,
106
+ autoPreviewsEnabled: true
107
+ });
108
+ /**
109
+ * Cached repository value.
110
+ */
111
+ __publicField(this, "cachedRepository");
112
+ /**
113
+ * Timestamp at which the cached repository data is considered stale.
114
+ */
115
+ __publicField(this, "cachedRepositoryExpiration", 0);
116
+ if ((options.documentAPIEndpoint || isRepositoryEndpoint(repositoryNameOrEndpoint)) && process.env.NODE_ENV === "development") {
117
+ const documentAPIEndpoint = options.documentAPIEndpoint || repositoryNameOrEndpoint;
118
+ if (/\.prismic\.io\/(?!api\/v2\/?)/i.test(documentAPIEndpoint)) {
119
+ throw new PrismicError("@prismicio/client only supports Prismic Rest API V2. Please provide only the repository name to the first createClient() parameter or use the getRepositoryEndpoint() helper to generate a valid Rest API V2 endpoint URL.", void 0, void 0);
120
+ }
121
+ const hostname = new URL(documentAPIEndpoint).hostname.toLowerCase();
122
+ if (hostname.endsWith(".prismic.io") && !hostname.endsWith(".cdn.prismic.io")) {
123
+ console.warn(`[@prismicio/client] The client was created with a non-CDN endpoint. Convert it to the CDN endpoint for better performance. For more details, see ${devMsg("endpoint-must-use-cdn")}`);
124
+ }
125
+ if (options.documentAPIEndpoint && isRepositoryEndpoint(repositoryNameOrEndpoint) && repositoryNameOrEndpoint !== options.documentAPIEndpoint) {
126
+ console.warn(`[@prismicio/client] Multiple incompatible endpoints were provided. Create the client using a repository name to prevent this error. For more details, see ${devMsg("prefer-repository-name")}`);
127
+ }
128
+ }
129
+ if (isRepositoryEndpoint(repositoryNameOrEndpoint)) {
130
+ this.documentAPIEndpoint = repositoryNameOrEndpoint;
131
+ try {
132
+ this.repositoryName = getRepositoryName(repositoryNameOrEndpoint);
133
+ } catch (error) {
134
+ console.warn(`[@prismicio/client] A repository name could not be inferred from the provided endpoint (\`${repositoryNameOrEndpoint}\`). Some methods will be disabled. Create the client using a repository name to prevent this warning. For more details, see ${devMsg("prefer-repository-name")}`);
135
+ }
136
+ } else {
137
+ this.documentAPIEndpoint = options.documentAPIEndpoint || getRepositoryEndpoint(repositoryNameOrEndpoint);
138
+ this.repositoryName = repositoryNameOrEndpoint;
139
+ }
140
+ this.accessToken = options.accessToken;
141
+ this.routes = options.routes;
142
+ this.brokenRoute = options.brokenRoute;
143
+ this.defaultParams = options.defaultParams;
144
+ if (options.ref) {
145
+ this.queryContentFromRef(options.ref);
146
+ }
147
+ this.graphQLFetch = this.graphQLFetch.bind(this);
148
+ }
149
+ /**
150
+ * The Prismic repository's name.
151
+ */
152
+ set repositoryName(value) {
153
+ __privateSet(this, _repositoryName, value);
154
+ }
155
+ /**
156
+ * The Prismic repository's name.
157
+ */
158
+ get repositoryName() {
159
+ if (!__privateGet(this, _repositoryName)) {
160
+ throw new PrismicError(`A repository name is required for this method but one could not be inferred from the provided API endpoint (\`${this.documentAPIEndpoint}\`). To fix this error, provide a repository name when creating the client. For more details, see ${devMsg("prefer-repository-name")}`, void 0, void 0);
161
+ }
162
+ return __privateGet(this, _repositoryName);
163
+ }
164
+ /**
165
+ * The Prismic REST API V2 endpoint for the repository (use
166
+ * `prismic.getRepositoryEndpoint` for the default endpoint).
167
+ *
168
+ * @deprecated Use `documentAPIEndpoint` instead.
169
+ */
170
+ // TODO: Remove in v8.
171
+ set endpoint(value) {
172
+ this.documentAPIEndpoint = value;
173
+ }
174
+ /**
175
+ * The Prismic REST API V2 endpoint for the repository (use
176
+ * `prismic.getRepositoryEndpoint` for the default endpoint).
177
+ *
178
+ * @deprecated Use `documentAPIEndpoint` instead.
179
+ */
180
+ // TODO: Remove in v8.
181
+ get endpoint() {
182
+ return this.documentAPIEndpoint;
183
+ }
184
+ /**
185
+ * Enables the client to automatically query content from a preview session if
186
+ * one is active in browser environments. This is enabled by default in the
187
+ * browser.
188
+ *
189
+ * For server environments, use `enableAutoPreviewsFromReq`.
190
+ *
191
+ * @example
192
+ *
193
+ * ```ts
194
+ * client.enableAutoPreviews()
195
+ * ```
196
+ *
197
+ * @see enableAutoPreviewsFromReq
198
+ */
199
+ enableAutoPreviews() {
200
+ this.refState.autoPreviewsEnabled = true;
201
+ }
202
+ /**
203
+ * Enables the client to automatically query content from a preview session if
204
+ * one is active in server environments. This is disabled by default on the
205
+ * server.
206
+ *
207
+ * For browser environments, use `enableAutoPreviews`.
208
+ *
209
+ * @example
210
+ *
211
+ * ```ts
212
+ * // In an express app
213
+ * app.get("/", function (req, res) {
214
+ * client.enableAutoPreviewsFromReq(req)
215
+ * })
216
+ * ```
217
+ *
218
+ * @param req - An HTTP server request object containing the request's
219
+ * cookies.
220
+ */
221
+ enableAutoPreviewsFromReq(req) {
222
+ this.refState.httpRequest = req;
223
+ this.refState.autoPreviewsEnabled = true;
224
+ }
225
+ /**
226
+ * Disables the client from automatically querying content from a preview
227
+ * session if one is active.
228
+ *
229
+ * Automatic preview content querying is enabled by default unless this method
230
+ * is called.
231
+ *
232
+ * @example
233
+ *
234
+ * ```ts
235
+ * client.disableAutoPreviews()
236
+ * ```
237
+ */
238
+ disableAutoPreviews() {
239
+ this.refState.autoPreviewsEnabled = false;
240
+ }
241
+ /**
242
+ * Queries content from the Prismic repository.
243
+ *
244
+ * @example
245
+ *
246
+ * ```ts
247
+ * const response = await client.get()
248
+ * ```
249
+ *
250
+ * @typeParam TDocument - Type of Prismic documents returned.
251
+ *
252
+ * @param params - Parameters to filter, sort, and paginate results.
253
+ *
254
+ * @returns A paginated response containing the result of the query.
255
+ */
256
+ async get(params) {
257
+ const url = await this.buildQueryURL(params);
258
+ return await this.fetch(url, params);
259
+ }
260
+ /**
261
+ * Queries content from the Prismic repository and returns only the first
262
+ * result, if any.
263
+ *
264
+ * @example
265
+ *
266
+ * ```ts
267
+ * const document = await client.getFirst()
268
+ * ```
269
+ *
270
+ * @typeParam TDocument - Type of the Prismic document returned.
271
+ *
272
+ * @param params - Parameters to filter, sort, and paginate results. @returns
273
+ * The first result of the query, if any.
274
+ */
275
+ async getFirst(params) {
276
+ var _a;
277
+ const actualParams = { ...params };
278
+ if (!(params && params.page) && !(params == null ? void 0 : params.pageSize)) {
279
+ actualParams.pageSize = ((_a = this.defaultParams) == null ? void 0 : _a.pageSize) ?? 1;
280
+ }
281
+ const url = await this.buildQueryURL(actualParams);
282
+ const result = await this.fetch(url, params);
283
+ const firstResult = result.results[0];
284
+ if (firstResult) {
285
+ return firstResult;
286
+ }
287
+ throw new NotFoundError("No documents were returned", url, void 0);
288
+ }
289
+ /**
290
+ * **IMPORTANT**: Avoid using `dangerouslyGetAll` as it may be slower and
291
+ * require more resources than other methods. Prefer using other methods that
292
+ * filter by filters such as `getAllByType`.
293
+ *
294
+ * Queries content from the Prismic repository and returns all matching
295
+ * content. If no filters are provided, all documents will be fetched.
296
+ *
297
+ * This method may make multiple network requests to query all matching
298
+ * content.
299
+ *
300
+ * @example
301
+ *
302
+ * ```ts
303
+ * const response = await client.dangerouslyGetAll()
304
+ * ```
305
+ *
306
+ * @typeParam TDocument - Type of Prismic documents returned.
307
+ *
308
+ * @param params - Parameters to filter, sort, and paginate results.
309
+ *
310
+ * @returns A list of documents matching the query.
311
+ */
312
+ async dangerouslyGetAll(params = {}) {
313
+ var _a;
314
+ const { limit = Infinity, ...actualParams } = params;
315
+ const resolvedParams = {
316
+ ...actualParams,
317
+ pageSize: Math.min(limit, actualParams.pageSize || ((_a = this.defaultParams) == null ? void 0 : _a.pageSize) || MAX_PAGE_SIZE)
318
+ };
319
+ const documents = [];
320
+ let latestResult;
321
+ while ((!latestResult || latestResult.next_page) && documents.length < limit) {
322
+ const page = latestResult ? latestResult.page + 1 : void 0;
323
+ latestResult = await this.get({ ...resolvedParams, page });
324
+ documents.push(...latestResult.results);
325
+ if (latestResult.next_page) {
326
+ await new Promise((res) => setTimeout(res, GET_ALL_QUERY_DELAY));
327
+ }
328
+ }
329
+ return documents.slice(0, limit);
330
+ }
331
+ /**
332
+ * Queries a document from the Prismic repository with a specific ID.
333
+ *
334
+ * @remarks
335
+ * A document's UID is different from its ID. An ID is automatically generated
336
+ * for all documents and is made available on its `id` property. A UID is
337
+ * provided in the Prismic editor and is unique among all documents of its
338
+ * custom type.
339
+ *
340
+ * @example
341
+ *
342
+ * ```ts
343
+ * const document = await client.getByID("WW4bKScAAMAqmluX")
344
+ * ```
345
+ *
346
+ * @typeParam TDocument- Type of the Prismic document returned.
347
+ *
348
+ * @param id - ID of the document.
349
+ * @param params - Parameters to filter, sort, and paginate the results.
350
+ *
351
+ * @returns The document with an ID matching the `id` parameter, if a matching
352
+ * document exists.
353
+ */
354
+ async getByID(id, params) {
355
+ return await this.getFirst(appendFilters(params, filter.at("document.id", id)));
356
+ }
357
+ /**
358
+ * Queries documents from the Prismic repository with specific IDs.
359
+ *
360
+ * @remarks
361
+ * A document's UID is different from its ID. An ID is automatically generated
362
+ * for all documents and is made available on its `id` property. A UID is
363
+ * provided in the Prismic editor and is unique among all documents of its
364
+ * custom type.
365
+ *
366
+ * @example
367
+ *
368
+ * ```ts
369
+ * const response = await client.getByIDs([
370
+ * "WW4bKScAAMAqmluX",
371
+ * "U1kTRgEAAC8A5ldS",
372
+ * ])
373
+ * ```
374
+ *
375
+ * @typeParam TDocument - Type of Prismic documents returned.
376
+ *
377
+ * @param ids - A list of document IDs.
378
+ * @param params - Parameters to filter, sort, and paginate the results.
379
+ *
380
+ * @returns A paginated response containing documents with IDs matching the
381
+ * `ids` parameter.
382
+ */
383
+ async getByIDs(ids, params) {
384
+ return await this.get(appendFilters(params, filter.in("document.id", ids)));
385
+ }
386
+ /**
387
+ * Queries all documents from the Prismic repository with specific IDs.
388
+ *
389
+ * This method may make multiple network requests to query all matching
390
+ * content.
391
+ *
392
+ * @remarks
393
+ * A document's UID is different from its ID. An ID is automatically generated
394
+ * for all documents and is made available on its `id` property. A UID is
395
+ * provided in the Prismic editor and is unique among all documents of its
396
+ * custom type.
397
+ *
398
+ * @example
399
+ *
400
+ * ```ts
401
+ * const response = await client.getAllByIDs([
402
+ * "WW4bKScAAMAqmluX",
403
+ * "U1kTRgEAAC8A5ldS",
404
+ * ])
405
+ * ```
406
+ *
407
+ * @typeParam TDocument - Type of Prismic documents returned.
408
+ *
409
+ * @param ids - A list of document IDs.
410
+ * @param params - Parameters to filter, sort, and paginate the results.
411
+ *
412
+ * @returns A list of documents with IDs matching the `ids` parameter.
413
+ */
414
+ async getAllByIDs(ids, params) {
415
+ return await this.dangerouslyGetAll(appendFilters(params, filter.in("document.id", ids)));
416
+ }
417
+ /**
418
+ * Queries a document from the Prismic repository with a specific UID and
419
+ * custom type.
420
+ *
421
+ * @remarks
422
+ * A document's UID is different from its ID. An ID is automatically generated
423
+ * for all documents and is made available on its `id` property. A UID is
424
+ * provided in the Prismic editor and is unique among all documents of its
425
+ * custom type.
426
+ *
427
+ * @example
428
+ *
429
+ * ```ts
430
+ * const document = await client.getByUID("blog_post", "my-first-post")
431
+ * ```
432
+ *
433
+ * @typeParam TDocument - Type of the Prismic document returned.
434
+ *
435
+ * @param documentType - The API ID of the document's custom type.
436
+ * @param uid - UID of the document.
437
+ * @param params - Parameters to filter, sort, and paginate the results.
438
+ *
439
+ * @returns The document with a UID matching the `uid` parameter, if a
440
+ * matching document exists.
441
+ */
442
+ async getByUID(documentType, uid, params) {
443
+ return await this.getFirst(appendFilters(params, [
444
+ typeFilter(documentType),
445
+ filter.at(`my.${documentType}.uid`, uid)
446
+ ]));
447
+ }
448
+ /**
449
+ * Queries document from the Prismic repository with specific UIDs and Custom
450
+ * Type.
451
+ *
452
+ * @remarks
453
+ * A document's UID is different from its ID. An ID is automatically generated
454
+ * for all documents and is made available on its `id` property. A UID is
455
+ * provided in the Prismic editor and is unique among all documents of its
456
+ * custom type.
457
+ *
458
+ * @example
459
+ *
460
+ * ```ts
461
+ * const document = await client.getByUIDs("blog_post", [
462
+ * "my-first-post",
463
+ * "my-second-post",
464
+ * ])
465
+ * ```
466
+ *
467
+ * @typeParam TDocument - Type of the Prismic document returned.
468
+ *
469
+ * @param documentType - The API ID of the document's custom type.
470
+ * @param uids - A list of document UIDs.
471
+ * @param params - Parameters to filter, sort, and paginate the results.
472
+ *
473
+ * @returns A paginated response containing documents with UIDs matching the
474
+ * `uids` parameter.
475
+ */
476
+ async getByUIDs(documentType, uids, params) {
477
+ return await this.get(appendFilters(params, [
478
+ typeFilter(documentType),
479
+ filter.in(`my.${documentType}.uid`, uids)
480
+ ]));
481
+ }
482
+ /**
483
+ * Queries all documents from the Prismic repository with specific UIDs and
484
+ * custom type.
485
+ *
486
+ * This method may make multiple network requests to query all matching
487
+ * content.
488
+ *
489
+ * @remarks
490
+ * A document's UID is different from its ID. An ID is automatically generated
491
+ * for all documents and is made available on its `id` property. A UID is
492
+ * provided in the Prismic editor and is unique among all documents of its
493
+ * custom type.
494
+ *
495
+ * @example
496
+ *
497
+ * ```ts
498
+ * const response = await client.getAllByUIDs([
499
+ * "my-first-post",
500
+ * "my-second-post",
501
+ * ])
502
+ * ```
503
+ *
504
+ * @typeParam TDocument - Type of Prismic documents returned.
505
+ *
506
+ * @param documentType - The API ID of the document's custom type.
507
+ * @param uids - A list of document UIDs.
508
+ * @param params - Parameters to filter, sort, and paginate the results.
509
+ *
510
+ * @returns A list of documents with UIDs matching the `uids` parameter.
511
+ */
512
+ async getAllByUIDs(documentType, uids, params) {
513
+ return await this.dangerouslyGetAll(appendFilters(params, [
514
+ typeFilter(documentType),
515
+ filter.in(`my.${documentType}.uid`, uids)
516
+ ]));
517
+ }
518
+ /**
519
+ * Queries a singleton document from the Prismic repository for a specific
520
+ * custom type.
521
+ *
522
+ * @remarks
523
+ * A singleton document is one that is configured in Prismic to only allow one
524
+ * instance. For example, a repository may be configured to contain just one
525
+ * Settings document. This is in contrast to a repeatable custom type which
526
+ * allows multiple instances of itself.
527
+ *
528
+ * @example
529
+ *
530
+ * ```ts
531
+ * const document = await client.getSingle("settings")
532
+ * ```
533
+ *
534
+ * @typeParam TDocument - Type of the Prismic document returned.
535
+ *
536
+ * @param documentType - The API ID of the singleton custom type.
537
+ * @param params - Parameters to filter, sort, and paginate the results.
538
+ *
539
+ * @returns The singleton document for the custom type, if a matching document
540
+ * exists.
541
+ */
542
+ async getSingle(documentType, params) {
543
+ return await this.getFirst(appendFilters(params, typeFilter(documentType)));
544
+ }
545
+ /**
546
+ * Queries documents from the Prismic repository for a specific custom type.
547
+ *
548
+ * Use `getAllByType` instead if you need to query all documents for a
549
+ * specific custom type.
550
+ *
551
+ * @example
552
+ *
553
+ * ```ts
554
+ * const response = await client.getByType("blog_post")
555
+ * ```
556
+ *
557
+ * @typeParam TDocument - Type of Prismic documents returned.
558
+ *
559
+ * @param documentType - The API ID of the custom type.
560
+ * @param params - Parameters to filter, sort, and paginate the results.
561
+ *
562
+ * @returns A paginated response containing documents of the custom type.
563
+ */
564
+ async getByType(documentType, params) {
565
+ return await this.get(appendFilters(params, typeFilter(documentType)));
566
+ }
567
+ /**
568
+ * Queries all documents from the Prismic repository for a specific Custom
569
+ * Type.
570
+ *
571
+ * This method may make multiple network requests to query all matching
572
+ * content.
573
+ *
574
+ * @example
575
+ *
576
+ * ```ts
577
+ * const response = await client.getByType("blog_post")
578
+ * ```
579
+ *
580
+ * @typeParam TDocument - Type of Prismic documents returned.
581
+ *
582
+ * @param documentType - The API ID of the custom type.
583
+ * @param params - Parameters to filter, sort, and paginate the results.
584
+ *
585
+ * @returns A list of all documents of the custom type.
586
+ */
587
+ async getAllByType(documentType, params) {
588
+ return await this.dangerouslyGetAll(appendFilters(params, typeFilter(documentType)));
589
+ }
590
+ /**
591
+ * Queries documents from the Prismic repository with a specific tag.
592
+ *
593
+ * Use `getAllByTag` instead if you need to query all documents with a
594
+ * specific tag.
595
+ *
596
+ * @example
597
+ *
598
+ * ```ts
599
+ * const response = await client.getByTag("food")
600
+ * ```
601
+ *
602
+ * @typeParam TDocument - Type of Prismic documents returned.
603
+ *
604
+ * @param tag - The tag that must be included on a document.
605
+ * @param params - Parameters to filter, sort, and paginate the results.
606
+ *
607
+ * @returns A paginated response containing documents with the tag.
608
+ */
609
+ async getByTag(tag, params) {
610
+ return await this.get(appendFilters(params, someTagsFilter(tag)));
611
+ }
612
+ /**
613
+ * Queries all documents from the Prismic repository with a specific tag.
614
+ *
615
+ * This method may make multiple network requests to query all matching
616
+ * content.
617
+ *
618
+ * @example
619
+ *
620
+ * ```ts
621
+ * const response = await client.getAllByTag("food")
622
+ * ```
623
+ *
624
+ * @typeParam TDocument - Type of Prismic documents returned.
625
+ *
626
+ * @param tag - The tag that must be included on a document.
627
+ * @param params - Parameters to filter, sort, and paginate the results.
628
+ *
629
+ * @returns A list of all documents with the tag.
630
+ */
631
+ async getAllByTag(tag, params) {
632
+ return await this.dangerouslyGetAll(appendFilters(params, someTagsFilter(tag)));
633
+ }
634
+ /**
635
+ * Queries documents from the Prismic repository with specific tags. A
636
+ * document must be tagged with all of the queried tags to be included.
637
+ *
638
+ * @example
639
+ *
640
+ * ```ts
641
+ * const response = await client.getByEveryTag(["food", "fruit"])
642
+ * ```
643
+ *
644
+ * @typeParam TDocument - Type of Prismic documents returned.
645
+ *
646
+ * @param tags - A list of tags that must be included on a document.
647
+ * @param params - Parameters to filter, sort, and paginate the results.
648
+ *
649
+ * @returns A paginated response containing documents with the tags.
650
+ */
651
+ async getByEveryTag(tags, params) {
652
+ return await this.get(appendFilters(params, everyTagFilter(tags)));
653
+ }
654
+ /**
655
+ * Queries documents from the Prismic repository with specific tags. A
656
+ * document must be tagged with all of the queried tags to be included.
657
+ *
658
+ * This method may make multiple network requests to query all matching
659
+ * content.
660
+ *
661
+ * @example
662
+ *
663
+ * ```ts
664
+ * const response = await client.getAllByEveryTag(["food", "fruit"])
665
+ * ```
666
+ *
667
+ * @typeParam TDocument - Type of Prismic documents returned.
668
+ *
669
+ * @param tags - A list of tags that must be included on a document.
670
+ * @param params - Parameters to filter, sort, and paginate the results.
671
+ *
672
+ * @returns A list of all documents with the tags.
673
+ */
674
+ async getAllByEveryTag(tags, params) {
675
+ return await this.dangerouslyGetAll(appendFilters(params, everyTagFilter(tags)));
676
+ }
677
+ /**
678
+ * Queries documents from the Prismic repository with specific tags. A
679
+ * document must be tagged with at least one of the queried tags to be
680
+ * included.
681
+ *
682
+ * @example
683
+ *
684
+ * ```ts
685
+ * const response = await client.getByEveryTag(["food", "fruit"])
686
+ * ```
687
+ *
688
+ * @typeParam TDocument - Type of Prismic documents returned.
689
+ *
690
+ * @param tags - A list of tags that must be included on a document.
691
+ * @param params - Parameters to filter, sort, and paginate the results.
692
+ *
693
+ * @returns A paginated response containing documents with at least one of the
694
+ * tags.
695
+ */
696
+ async getBySomeTags(tags, params) {
697
+ return await this.get(appendFilters(params, someTagsFilter(tags)));
698
+ }
699
+ /**
700
+ * Queries documents from the Prismic repository with specific tags. A
701
+ * document must be tagged with at least one of the queried tags to be
702
+ * included.
703
+ *
704
+ * This method may make multiple network requests to query all matching
705
+ * content.
706
+ *
707
+ * @example
708
+ *
709
+ * ```ts
710
+ * const response = await client.getAllBySomeTags(["food", "fruit"])
711
+ * ```
712
+ *
713
+ * @typeParam TDocument - Type of Prismic documents returned.
714
+ *
715
+ * @param tags - A list of tags that must be included on a document.
716
+ * @param params - Parameters to filter, sort, and paginate the results.
717
+ *
718
+ * @returns A list of all documents with at least one of the tags.
719
+ */
720
+ async getAllBySomeTags(tags, params) {
721
+ return await this.dangerouslyGetAll(appendFilters(params, someTagsFilter(tags)));
722
+ }
723
+ /**
724
+ * Returns metadata about the Prismic repository, such as its refs, releases,
725
+ * and custom types.
726
+ *
727
+ * @returns Repository metadata.
728
+ */
729
+ async getRepository(params) {
730
+ const url = new URL(this.documentAPIEndpoint);
731
+ if (this.accessToken) {
732
+ url.searchParams.set("access_token", this.accessToken);
733
+ }
734
+ return await this.fetch(url.toString(), params);
735
+ }
736
+ /**
737
+ * Returns a list of all refs for the Prismic repository.
738
+ *
739
+ * Refs are used to identify which version of the repository's content should
740
+ * be queried. All repositories will have at least one ref pointing to the
741
+ * latest published content called the "master ref".
742
+ *
743
+ * @returns A list of all refs for the Prismic repository.
744
+ */
745
+ async getRefs(params) {
746
+ const repository = await this.getRepository(params);
747
+ return repository.refs;
748
+ }
749
+ /**
750
+ * Returns a ref for the Prismic repository with a matching ID.
751
+ *
752
+ * @param id - ID of the ref.
753
+ *
754
+ * @returns The ref with a matching ID, if it exists.
755
+ */
756
+ async getRefByID(id, params) {
757
+ const refs = await this.getRefs(params);
758
+ return findRefByID(refs, id);
759
+ }
760
+ /**
761
+ * Returns a ref for the Prismic repository with a matching label.
762
+ *
763
+ * @param label - Label of the ref.
764
+ *
765
+ * @returns The ref with a matching label, if it exists.
766
+ */
767
+ async getRefByLabel(label, params) {
768
+ const refs = await this.getRefs(params);
769
+ return findRefByLabel(refs, label);
770
+ }
771
+ /**
772
+ * Returns the master ref for the Prismic repository. The master ref points to
773
+ * the repository's latest published content.
774
+ *
775
+ * @returns The repository's master ref.
776
+ */
777
+ async getMasterRef(params) {
778
+ const refs = await this.getRefs(params);
779
+ return findMasterRef(refs);
780
+ }
781
+ /**
782
+ * Returns a list of all Releases for the Prismic repository. Releases are
783
+ * used to group content changes before publishing.
784
+ *
785
+ * @returns A list of all Releases for the Prismic repository.
786
+ */
787
+ async getReleases(params) {
788
+ const refs = await this.getRefs(params);
789
+ return refs.filter((ref) => !ref.isMasterRef);
790
+ }
791
+ /**
792
+ * Returns a Release for the Prismic repository with a matching ID.
793
+ *
794
+ * @param id - ID of the Release.
795
+ *
796
+ * @returns The Release with a matching ID, if it exists.
797
+ */
798
+ async getReleaseByID(id, params) {
799
+ const releases = await this.getReleases(params);
800
+ return findRefByID(releases, id);
801
+ }
802
+ /**
803
+ * Returns a Release for the Prismic repository with a matching label.
804
+ *
805
+ * @param label - Label of the ref.
806
+ *
807
+ * @returns The ref with a matching label, if it exists.
808
+ */
809
+ async getReleaseByLabel(label, params) {
810
+ const releases = await this.getReleases(params);
811
+ return findRefByLabel(releases, label);
812
+ }
813
+ /**
814
+ * Returns a list of all tags used in the Prismic repository.
815
+ *
816
+ * @returns A list of all tags used in the repository.
817
+ */
818
+ async getTags(params) {
819
+ try {
820
+ const tagsForm = await this.getCachedRepositoryForm("tags", params);
821
+ const url = new URL(tagsForm.action);
822
+ if (this.accessToken) {
823
+ url.searchParams.set("access_token", this.accessToken);
824
+ }
825
+ return await this.fetch(url.toString(), params);
826
+ } catch {
827
+ const repository = await this.getRepository(params);
828
+ return repository.tags;
829
+ }
830
+ }
831
+ /**
832
+ * Builds a URL used to query content from the Prismic repository.
833
+ *
834
+ * @param params - Parameters to filter, sort, and paginate the results.
835
+ *
836
+ * @returns A URL string that can be requested to query content.
837
+ */
838
+ async buildQueryURL({ signal, fetchOptions, ...params } = {}) {
839
+ const ref = params.ref || await this.getResolvedRefString({ signal, fetchOptions });
840
+ const integrationFieldsRef = params.integrationFieldsRef || (await this.getCachedRepository({ signal, fetchOptions })).integrationFieldsRef || void 0;
841
+ return buildQueryURL(this.documentAPIEndpoint, {
842
+ ...this.defaultParams,
843
+ ...params,
844
+ ref,
845
+ integrationFieldsRef,
846
+ routes: params.routes || this.routes,
847
+ brokenRoute: params.brokenRoute || this.brokenRoute,
848
+ accessToken: params.accessToken || this.accessToken
849
+ });
850
+ }
851
+ /**
852
+ * Determines the URL for a previewed document during an active preview
853
+ * session. The result of this method should be used to redirect the user to
854
+ * the document's URL.
855
+ *
856
+ * @example
857
+ *
858
+ * ```ts
859
+ * const url = client.resolvePreviewURL({
860
+ * linkResolver: (document) => `/${document.uid}`
861
+ * defaultURL: '/'
862
+ * })
863
+ * ```
864
+ *
865
+ * @param args - Arguments to configure the URL resolving.
866
+ *
867
+ * @returns The URL for the previewed document during an active preview
868
+ * session. The user should be redirected to this URL.
869
+ */
870
+ async resolvePreviewURL(args) {
871
+ var _a, _b;
872
+ let documentID = args.documentID;
873
+ let previewToken = args.previewToken;
874
+ if (typeof globalThis.location !== "undefined") {
875
+ const searchParams = new URLSearchParams(globalThis.location.search);
876
+ documentID = documentID || searchParams.get("documentId");
877
+ previewToken = previewToken || searchParams.get("token");
878
+ } else if (this.refState.httpRequest) {
879
+ if ("query" in this.refState.httpRequest) {
880
+ documentID = documentID || ((_a = this.refState.httpRequest.query) == null ? void 0 : _a.documentId);
881
+ previewToken = previewToken || ((_b = this.refState.httpRequest.query) == null ? void 0 : _b.token);
882
+ } else if ("url" in this.refState.httpRequest && this.refState.httpRequest.url) {
883
+ const searchParams = new URL(this.refState.httpRequest.url, "missing-host://").searchParams;
884
+ documentID = documentID || searchParams.get("documentId");
885
+ previewToken = previewToken || searchParams.get("token");
886
+ }
887
+ }
888
+ if (documentID != null && previewToken != null) {
889
+ const document = await this.getByID(documentID, {
890
+ ref: previewToken,
891
+ lang: "*",
892
+ signal: args.signal,
893
+ fetchOptions: args.fetchOptions
894
+ });
895
+ const url = asLink(document, { linkResolver: args.linkResolver });
896
+ if (typeof url === "string") {
897
+ return url;
898
+ }
899
+ }
900
+ return args.defaultURL;
901
+ }
902
+ /**
903
+ * Configures the client to query the latest published content for all future
904
+ * queries.
905
+ *
906
+ * If the `ref` parameter is provided during a query, it takes priority for
907
+ * that query.
908
+ *
909
+ * @example
910
+ *
911
+ * ```ts
912
+ * await client.queryLatestContent()
913
+ * const document = await client.getByID("WW4bKScAAMAqmluX")
914
+ * ```
915
+ */
916
+ queryLatestContent() {
917
+ this.refState.mode = RefStateMode.Master;
918
+ }
919
+ /**
920
+ * Configures the client to query content from a specific Release identified
921
+ * by its ID for all future queries.
922
+ *
923
+ * If the `ref` parameter is provided during a query, it takes priority for
924
+ * that query.
925
+ *
926
+ * @example
927
+ *
928
+ * ```ts
929
+ * await client.queryContentFromReleaseByID("YLB7OBAAACMA7Cpa")
930
+ * const document = await client.getByID("WW4bKScAAMAqmluX")
931
+ * ```
932
+ *
933
+ * @param releaseID - The ID of the Release.
934
+ */
935
+ queryContentFromReleaseByID(releaseID) {
936
+ this.refState = {
937
+ ...this.refState,
938
+ mode: RefStateMode.ReleaseID,
939
+ releaseID
940
+ };
941
+ }
942
+ /**
943
+ * Configures the client to query content from a specific Release identified
944
+ * by its label for all future queries.
945
+ *
946
+ * If the `ref` parameter is provided during a query, it takes priority for
947
+ * that query.
948
+ *
949
+ * @example
950
+ *
951
+ * ```ts
952
+ * await client.queryContentFromReleaseByLabel("My Release")
953
+ * const document = await client.getByID("WW4bKScAAMAqmluX")
954
+ * ```
955
+ *
956
+ * @param releaseLabel - The label of the Release.
957
+ */
958
+ queryContentFromReleaseByLabel(releaseLabel) {
959
+ this.refState = {
960
+ ...this.refState,
961
+ mode: RefStateMode.ReleaseLabel,
962
+ releaseLabel
963
+ };
964
+ }
965
+ /**
966
+ * Configures the client to query content from a specific ref. The ref can be
967
+ * provided as a string or a function.
968
+ *
969
+ * If a function is provided, the ref is fetched lazily before each query. The
970
+ * function may also be asynchronous.
971
+ *
972
+ * @example
973
+ *
974
+ * ```ts
975
+ * await client.queryContentFromRef("my-ref")
976
+ * const document = await client.getByID("WW4bKScAAMAqmluX")
977
+ * ```
978
+ *
979
+ * @param ref - The ref or a function that returns the ref from which to query
980
+ * content.
981
+ */
982
+ queryContentFromRef(ref) {
983
+ this.refState = {
984
+ ...this.refState,
985
+ mode: RefStateMode.Manual,
986
+ ref
987
+ };
988
+ }
989
+ /**
990
+ * A `fetch()` function to be used with GraphQL clients configured for
991
+ * Prismic's GraphQL API. It automatically applies the necessary `prismic-ref`
992
+ * and Authorization headers. Queries will automatically be minified by
993
+ * removing whitespace where possible.
994
+ *
995
+ * @example
996
+ *
997
+ * ```ts
998
+ * const graphQLClient = new ApolloClient({
999
+ * link: new HttpLink({
1000
+ * uri: prismic.getGraphQLEndpoint(repositoryName),
1001
+ * // Provide `client.graphQLFetch` as the fetch implementation.
1002
+ * fetch: client.graphQLFetch,
1003
+ * // Using GET is required.
1004
+ * useGETForQueries: true,
1005
+ * }),
1006
+ * cache: new InMemoryCache(),
1007
+ * })
1008
+ * ```
1009
+ *
1010
+ * @param input - The `fetch()` `input` parameter. Only strings are supported.
1011
+ * @param init - The `fetch()` `init` parameter. Only plain objects are
1012
+ * supported.
1013
+ *
1014
+ * @returns The `fetch()` Response for the request.
1015
+ *
1016
+ * @experimental
1017
+ */
1018
+ async graphQLFetch(input, init) {
1019
+ const cachedRepository = await this.getCachedRepository();
1020
+ const ref = await this.getResolvedRefString();
1021
+ const unsanitizedHeaders = {
1022
+ "Prismic-ref": ref,
1023
+ Authorization: this.accessToken ? `Token ${this.accessToken}` : "",
1024
+ // Asserting `init.headers` is a Record since popular GraphQL
1025
+ // libraries pass this as a Record. Header objects as input
1026
+ // are unsupported.
1027
+ ...init ? init.headers : {}
1028
+ };
1029
+ if (cachedRepository.integrationFieldsRef) {
1030
+ unsanitizedHeaders["Prismic-integration-field-ref"] = cachedRepository.integrationFieldsRef;
1031
+ }
1032
+ const headers = {};
1033
+ for (const key in unsanitizedHeaders) {
1034
+ if (unsanitizedHeaders[key]) {
1035
+ headers[key.toLowerCase()] = unsanitizedHeaders[key];
1036
+ }
1037
+ }
1038
+ const url = new URL(
1039
+ // Asserting `input` is a string since popular GraphQL
1040
+ // libraries pass this as a string. Request objects as
1041
+ // input are unsupported.
1042
+ input
1043
+ );
1044
+ url.searchParams.set("ref", ref);
1045
+ const query = url.searchParams.get("query");
1046
+ if (query) {
1047
+ url.searchParams.set(
1048
+ "query",
1049
+ // Compress the GraphQL query (if it exists) by
1050
+ // removing whitespace. This is done to
1051
+ // optimize the query size and avoid
1052
+ // hitting the upper limit of GET requests
1053
+ // (2048 characters).
1054
+ minifyGraphQLQuery(query)
1055
+ );
1056
+ }
1057
+ return await this.fetchFn(url.toString(), {
1058
+ ...init,
1059
+ headers
1060
+ });
1061
+ }
1062
+ /**
1063
+ * Returns a cached version of `getRepository` with a TTL.
1064
+ *
1065
+ * @returns Cached repository metadata.
1066
+ */
1067
+ async getCachedRepository(params) {
1068
+ if (!this.cachedRepository || Date.now() >= this.cachedRepositoryExpiration) {
1069
+ this.cachedRepositoryExpiration = Date.now() + REPOSITORY_CACHE_TTL;
1070
+ this.cachedRepository = await this.getRepository(params);
1071
+ }
1072
+ return this.cachedRepository;
1073
+ }
1074
+ /**
1075
+ * Returns a cached Prismic repository form. Forms are used to determine API
1076
+ * endpoints for types of repository data.
1077
+ *
1078
+ * @param name - Name of the form.
1079
+ *
1080
+ * @returns The repository form.
1081
+ *
1082
+ * @throws If a matching form cannot be found.
1083
+ */
1084
+ async getCachedRepositoryForm(name, params) {
1085
+ const cachedRepository = await this.getCachedRepository(params);
1086
+ const form = cachedRepository.forms[name];
1087
+ if (!form) {
1088
+ throw new PrismicError(`Form with name "${name}" could not be found`, void 0, void 0);
1089
+ }
1090
+ return form;
1091
+ }
1092
+ /**
1093
+ * Returns the ref needed to query based on the client's current state. This
1094
+ * method may make a network request to fetch a ref or resolve the user's ref
1095
+ * thunk.
1096
+ *
1097
+ * If auto previews are enabled, the preview ref takes priority if available.
1098
+ *
1099
+ * The following strategies are used depending on the client's state:
1100
+ *
1101
+ * - If the user called `queryLatestContent`: Use the repository's master ref.
1102
+ * The ref is cached for 5 seconds. After 5 seconds, a new master ref is
1103
+ * fetched.
1104
+ * - If the user called `queryContentFromReleaseByID`: Use the release's ref.
1105
+ * The ref is cached for 5 seconds. After 5 seconds, a new ref for the
1106
+ * release is fetched.
1107
+ * - If the user called `queryContentFromReleaseByLabel`: Use the release's ref.
1108
+ * The ref is cached for 5 seconds. After 5 seconds, a new ref for the
1109
+ * release is fetched.
1110
+ * - If the user called `queryContentFromRef`: Use the provided ref. Fall back
1111
+ * to the master ref if the ref is not a string.
1112
+ *
1113
+ * @returns The ref to use during a query.
1114
+ */
1115
+ async getResolvedRefString(params) {
1116
+ var _a, _b;
1117
+ if (this.refState.autoPreviewsEnabled) {
1118
+ let previewRef;
1119
+ let cookieJar;
1120
+ if ((_a = this.refState.httpRequest) == null ? void 0 : _a.headers) {
1121
+ if ("get" in this.refState.httpRequest.headers && typeof this.refState.httpRequest.headers.get === "function") {
1122
+ cookieJar = this.refState.httpRequest.headers.get("cookie");
1123
+ } else if ("cookie" in this.refState.httpRequest.headers) {
1124
+ cookieJar = this.refState.httpRequest.headers.cookie;
1125
+ }
1126
+ } else if ((_b = globalThis.document) == null ? void 0 : _b.cookie) {
1127
+ cookieJar = globalThis.document.cookie;
1128
+ }
1129
+ if (cookieJar) {
1130
+ previewRef = getPreviewCookie(cookieJar);
1131
+ }
1132
+ if (previewRef) {
1133
+ return previewRef;
1134
+ }
1135
+ }
1136
+ const cachedRepository = await this.getCachedRepository(params);
1137
+ const refModeType = this.refState.mode;
1138
+ if (refModeType === RefStateMode.ReleaseID) {
1139
+ return findRefByID(cachedRepository.refs, this.refState.releaseID).ref;
1140
+ } else if (refModeType === RefStateMode.ReleaseLabel) {
1141
+ return findRefByLabel(cachedRepository.refs, this.refState.releaseLabel).ref;
1142
+ } else if (refModeType === RefStateMode.Manual) {
1143
+ const res = await castThunk(this.refState.ref)();
1144
+ if (typeof res === "string") {
1145
+ return res;
1146
+ }
1147
+ }
1148
+ return findMasterRef(cachedRepository.refs).ref;
1149
+ }
1150
+ /**
1151
+ * Performs a network request using the configured `fetch` function. It
1152
+ * assumes all successful responses will have a JSON content type. It also
1153
+ * normalizes unsuccessful network requests.
1154
+ *
1155
+ * @typeParam T - The JSON response.
1156
+ *
1157
+ * @param url - URL to the resource to fetch.
1158
+ * @param params - Prismic REST API parameters for the network request.
1159
+ *
1160
+ * @returns The JSON response from the network request.
1161
+ */
1162
+ async fetch(url, params = {}) {
1163
+ const res = await super.fetch(url, params);
1164
+ if (res.status !== 404 && res.status !== 429 && res.json == null) {
1165
+ throw new PrismicError(void 0, url, res.json || res.text);
1166
+ }
1167
+ switch (res.status) {
1168
+ case 200:
1169
+ case 201: {
1170
+ return res.json;
1171
+ }
1172
+ case 400: {
1173
+ throw new ParsingError(res.json.message, url, res.json);
1174
+ }
1175
+ case 401:
1176
+ case 403: {
1177
+ throw new ForbiddenError(res.json.error || res.json.message, url, res.json);
1178
+ }
1179
+ case 404: {
1180
+ if (res.json === void 0) {
1181
+ throw new RepositoryNotFoundError(`Prismic repository not found. Check that "${this.documentAPIEndpoint}" is pointing to the correct repository.`, url, url.startsWith(this.documentAPIEndpoint) ? void 0 : res.text);
1182
+ }
1183
+ if (res.json.type === "api_notfound_error") {
1184
+ throw new RefNotFoundError(res.json.message, url, res.json);
1185
+ }
1186
+ if (res.json.type === "api_security_error" && /preview token.*expired/i.test(res.json.message)) {
1187
+ throw new PreviewTokenExpiredError(res.json.message, url, res.json);
1188
+ }
1189
+ throw new NotFoundError(res.json.message, url, res.json);
1190
+ }
1191
+ case 410: {
1192
+ throw new RefExpiredError(res.json.message, url, res.json);
1193
+ }
1194
+ case 429: {
1195
+ const parsedRetryAfter = Number(res.headers.get("retry-after"));
1196
+ const delay = Number.isNaN(parsedRetryAfter) ? DEFUALT_RETRY_AFTER_MS : parsedRetryAfter;
1197
+ return await new Promise((resolve, reject) => {
1198
+ setTimeout(async () => {
1199
+ try {
1200
+ resolve(await this.fetch(url, params));
1201
+ } catch (error) {
1202
+ reject(error);
1203
+ }
1204
+ }, delay);
1205
+ });
1206
+ }
1207
+ }
1208
+ throw new PrismicError(void 0, url, res.json);
1209
+ }
1210
+ }
1211
+ _repositoryName = new WeakMap();
1212
+ export {
1213
+ Client,
1214
+ GET_ALL_QUERY_DELAY,
1215
+ REPOSITORY_CACHE_TTL
1216
+ };
1217
+ //# sourceMappingURL=Client.js.map