prismic-ts-codegen 0.1.21 → 0.1.22

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