@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
@@ -1,374 +1,7 @@
1
- import { appendFilters } from "./lib/appendFilters"
2
- import { castThunk } from "./lib/castThunk"
3
- import { devMsg } from "./lib/devMsg"
4
- import { everyTagFilter } from "./lib/everyTagFilter"
5
- import { findMasterRef } from "./lib/findMasterRef"
6
- import { findRefByID } from "./lib/findRefByID"
7
- import { findRefByLabel } from "./lib/findRefByLabel"
8
- import { getPreviewCookie } from "./lib/getPreviewCookie"
9
- import { minifyGraphQLQuery } from "./lib/minifyGraphQLQuery"
10
- import { someTagsFilter } from "./lib/someTagsFilter"
11
- import { typeFilter } from "./lib/typeFilter"
12
-
13
- import type { Query } from "./types/api/query"
14
- import type { Ref } from "./types/api/ref"
15
- import type { Form, Repository } from "./types/api/repository"
16
1
  import type { PrismicDocument } from "./types/value/document"
17
2
 
18
- import { ForbiddenError } from "./errors/ForbiddenError"
19
- import { NotFoundError } from "./errors/NotFoundError"
20
- import { ParsingError } from "./errors/ParsingError"
21
- import { PreviewTokenExpiredError } from "./errors/PreviewTokenExpired"
22
- import { PrismicError } from "./errors/PrismicError"
23
- import { RefExpiredError } from "./errors/RefExpiredError"
24
- import { RefNotFoundError } from "./errors/RefNotFoundError"
25
- import { RepositoryNotFoundError } from "./errors/RepositoryNotFoundError"
26
-
27
- import type { LinkResolverFunction } from "./helpers/asLink"
28
- import { asLink } from "./helpers/asLink"
29
-
30
- import type { BuildQueryURLArgs } from "./buildQueryURL"
31
- import { buildQueryURL } from "./buildQueryURL"
32
- import { filter } from "./filter"
33
- import { getRepositoryEndpoint } from "./getRepositoryEndpoint"
34
- import { getRepositoryName } from "./getRepositoryName"
35
- import { isRepositoryEndpoint } from "./isRepositoryEndpoint"
36
-
37
- /**
38
- * The largest page size allowed by the Prismic REST API V2. This value is used
39
- * to minimize the number of requests required to query content.
40
- */
41
- const MAX_PAGE_SIZE = 100
42
-
43
- /**
44
- * The number of milliseconds in which repository metadata is considered valid.
45
- * A ref can be invalidated quickly depending on how frequently content is
46
- * updated in the Prismic repository. As such, repository's metadata can only be
47
- * considered valid for a short amount of time.
48
- */
49
- export const REPOSITORY_CACHE_TTL = 5000
50
-
51
- /**
52
- * The number of milliseconds in which a multi-page `getAll` (e.g. `getAll`,
53
- * `getAllByType`, `getAllByTag`) will wait between individual page requests.
54
- *
55
- * This is done to ensure API performance is sustainable and reduces the chance
56
- * of a failed API request due to overloading.
57
- */
58
- export const GET_ALL_QUERY_DELAY = 500
59
-
60
- /**
61
- * The default number of milliseconds to wait before retrying a rate-limited
62
- * `fetch()` request (429 response code). The default value is only used if the
63
- * response does not include a `retry-after` header.
64
- *
65
- * The API allows up to 200 requests per second.
66
- */
67
- const DEFUALT_RETRY_AFTER_MS = 1000
68
-
69
- /**
70
- * Extracts one or more Prismic document types that match a given Prismic
71
- * document type. If no matches are found, no extraction is performed and the
72
- * union of all provided Prismic document types are returned.
73
- *
74
- * @typeParam TDocuments - Prismic document types from which to extract.
75
- * @typeParam TDocumentType - Type(s) to match `TDocuments` against.
76
- */
77
- type ExtractDocumentType<
78
- TDocuments extends PrismicDocument,
79
- TDocumentType extends TDocuments["type"],
80
- > =
81
- Extract<TDocuments, { type: TDocumentType }> extends never
82
- ? TDocuments
83
- : Extract<TDocuments, { type: TDocumentType }>
84
-
85
- /**
86
- * A universal API to make network requests. A subset of the `fetch()` API.
87
- *
88
- * {@link https://developer.mozilla.org/en-US/docs/Web/API/fetch}
89
- */
90
- export type FetchLike = (
91
- input: string,
92
- init?: RequestInitLike,
93
- ) => Promise<ResponseLike>
94
-
95
- /**
96
- * An object that allows you to abort a `fetch()` request if needed via an
97
- * `AbortController` object
98
- *
99
- * {@link https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal}
100
- */
101
- // `any` is used often here to ensure this type is universally valid among
102
- // different AbortSignal implementations. The types of each property are not
103
- // important to validate since it is blindly passed to a given `fetch()`
104
- // function.
105
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
106
- export type AbortSignalLike = any
107
-
108
- /**
109
- * A subset of RequestInit properties to configure a `fetch()` request.
110
- */
111
- // Only options relevant to the client are included. Extending from the full
112
- // RequestInit would cause issues, such as accepting Header objects.
113
- //
114
- // An interface is used to allow other libraries to augment the type with
115
- // environment-specific types.
116
- export interface RequestInitLike extends Pick<RequestInit, "cache"> {
117
- /**
118
- * An object literal to set the `fetch()` request's headers.
119
- */
120
- headers?: Record<string, string>
121
-
122
- /**
123
- * An AbortSignal to set the `fetch()` request's signal.
124
- *
125
- * See:
126
- * [https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal)
127
- */
128
- // NOTE: `AbortSignalLike` is `any`! It is left as `AbortSignalLike`
129
- // for backwards compatibility (the type is exported) and to signal to
130
- // other readers that this should be an AbortSignal-like object.
131
- signal?: AbortSignalLike
132
- }
133
-
134
- /**
135
- * The minimum required properties from Response.
136
- */
137
- export interface ResponseLike {
138
- status: number
139
- headers: HeadersLike
140
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
141
- json(): Promise<any>
142
- }
143
-
144
- /**
145
- * The minimum required properties from Headers.
146
- */
147
- export interface HeadersLike {
148
- get(name: string): string | null
149
- }
150
-
151
- /**
152
- * The minimum required properties to treat as an HTTP Request for automatic
153
- * Prismic preview support.
154
- */
155
- export type HttpRequestLike =
156
- | /**
157
- * Web API Request
158
- *
159
- * @see http://developer.mozilla.org/en-US/docs/Web/API/Request
160
- */
161
- {
162
- headers?: {
163
- get(name: string): string | null
164
- }
165
- url?: string
166
- }
167
-
168
- /**
169
- * Express-style Request
170
- */
171
- | {
172
- headers?: {
173
- cookie?: string
174
- }
175
- query?: Record<string, unknown>
176
- }
177
-
178
- /**
179
- * Modes for client ref management.
180
- */
181
- enum RefStateMode {
182
- /**
183
- * Use the repository's master ref.
184
- */
185
- Master = "Master",
186
-
187
- /**
188
- * Use a given Release identified by its ID.
189
- */
190
- ReleaseID = "ReleaseID",
191
-
192
- /**
193
- * Use a given Release identified by its label.
194
- */
195
- ReleaseLabel = "ReleaseLabel",
196
-
197
- /**
198
- * Use a given ref.
199
- */
200
- Manual = "Manual",
201
- }
202
-
203
- /**
204
- * An object containing stateful information about a client's ref strategy.
205
- */
206
- type RefState = {
207
- /**
208
- * Determines if automatic preview support is enabled.
209
- */
210
- autoPreviewsEnabled: boolean
211
-
212
- /**
213
- * An optional HTTP server request object used during previews if automatic
214
- * previews are enabled.
215
- */
216
- httpRequest?: HttpRequestLike
217
- } & (
218
- | {
219
- mode: RefStateMode.Master
220
- }
221
- | {
222
- mode: RefStateMode.ReleaseID
223
- releaseID: string
224
- }
225
- | {
226
- mode: RefStateMode.ReleaseLabel
227
- releaseLabel: string
228
- }
229
- | {
230
- mode: RefStateMode.Manual
231
- ref: RefStringOrThunk
232
- }
233
- )
234
-
235
- /**
236
- * A ref or a function that returns a ref. If a static ref is known, one can be
237
- * given. If the ref must be fetched on-demand, a function can be provided. This
238
- * function can optionally be asynchronous.
239
- */
240
- type RefStringOrThunk =
241
- | string
242
- | (() => string | undefined | Promise<string | undefined>)
243
-
244
- /**
245
- * Configuration for clients that determine how content is queried.
246
- */
247
- export type ClientConfig = {
248
- /**
249
- * The secure token for accessing the Prismic repository. This is only
250
- * required if the repository is set to private.
251
- */
252
- accessToken?: string
253
-
254
- /**
255
- * A string representing a version of the Prismic repository's content. This
256
- * may point to the latest version (called the "master ref"), or a preview
257
- * with draft content.
258
- */
259
- ref?: RefStringOrThunk
260
-
261
- /**
262
- * A list of route resolver objects that define how a document's `url`
263
- * property is resolved.
264
- *
265
- * {@link https://prismic.io/docs/route-resolver}
266
- */
267
- routes?: NonNullable<BuildQueryURLArgs["routes"]>
268
-
269
- /**
270
- * The `brokenRoute` option allows you to define the route populated in the
271
- * `url` property for broken link or content relationship fields. A broken
272
- * link is a link or content relationship field whose linked document has been
273
- * unpublished or deleted.
274
- *
275
- * {@link https://prismic.io/docs/route-resolver}
276
- */
277
- brokenRoute?: NonNullable<BuildQueryURLArgs["brokenRoute"]>
278
-
279
- /**
280
- * Default parameters that will be sent with each query. These parameters can
281
- * be overridden on each query if needed.
282
- */
283
- defaultParams?: Omit<
284
- BuildQueryURLArgs,
285
- "ref" | "integrationFieldsRef" | "accessToken" | "routes" | "brokenRoute"
286
- >
287
-
288
- /**
289
- * The function used to make network requests to the Prismic REST API. In
290
- * environments where a global `fetch` function does not exist, such as
291
- * Node.js, this function must be provided.
292
- */
293
- fetch?: FetchLike
294
-
295
- /**
296
- * Options provided to the client's `fetch()` on all network requests. These
297
- * options will be merged with internally required options. They can also be
298
- * overriden on a per-query basis using the query's `fetchOptions` parameter.
299
- */
300
- fetchOptions?: RequestInitLike
301
- }
302
-
303
- /**
304
- * Parameters for any client method that use `fetch()`.
305
- */
306
- type FetchParams = {
307
- /**
308
- * Options provided to the client's `fetch()` on all network requests. These
309
- * options will be merged with internally required options. They can also be
310
- * overriden on a per-query basis using the query's `fetchOptions` parameter.
311
- */
312
- fetchOptions?: RequestInitLike
313
-
314
- /**
315
- * An `AbortSignal` provided by an `AbortController`. This allows the network
316
- * request to be cancelled if necessary.
317
- *
318
- * @deprecated Move the `signal` parameter into `fetchOptions.signal`:
319
- *
320
- * @see \<https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal\>
321
- */
322
- signal?: AbortSignalLike
323
- }
324
-
325
- /**
326
- * Parameters specific to client methods that fetch all documents. These methods
327
- * start with `getAll` (for example, `getAllByType`).
328
- */
329
- type GetAllParams = {
330
- /**
331
- * Limit the number of documents queried. If a number is not provided, there
332
- * will be no limit and all matching documents will be returned.
333
- */
334
- limit?: number
335
- }
336
-
337
- /**
338
- * Arguments to determine how the URL for a preview session is resolved.
339
- */
340
- type ResolvePreviewArgs<LinkResolverReturnType> = {
341
- /**
342
- * A function that maps a Prismic document to a URL within your app.
343
- */
344
- linkResolver?: LinkResolverFunction<LinkResolverReturnType>
345
-
346
- /**
347
- * A fallback URL if the link resolver does not return a value.
348
- */
349
- defaultURL: string
350
-
351
- /**
352
- * The preview token (also known as a ref) that will be used to query preview
353
- * content from the Prismic repository.
354
- */
355
- previewToken?: string
356
-
357
- /**
358
- * The previewed document that will be used to determine the destination URL.
359
- */
360
- documentID?: string
361
- }
362
-
363
- /**
364
- * The result of a `fetch()` job.
365
- */
366
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
367
- type FetchJobResult<TJSON = any> = {
368
- status: number
369
- headers: HeadersLike
370
- json: TJSON
371
- }
3
+ import type { ClientConfig } from "./Client"
4
+ import { Client } from "./Client"
372
5
 
373
6
  /**
374
7
  * Type definitions for the `createClient()` function. May be augmented by
@@ -393,8 +26,7 @@ export interface CreateClient {
393
26
  * createClient("https://qwerty.cdn.prismic.io/api/v2")
394
27
  * ```
395
28
  *
396
- * @typeParam TDocuments - A map of Prismic document type IDs mapped to their
397
- * TypeScript type.
29
+ * @typeParam TDocuments - A union of Prismic document types for the repository.
398
30
  *
399
31
  * @param repositoryNameOrEndpoint - The Prismic repository name or full Rest
400
32
  * API V2 endpoint for the repository.
@@ -407,1563 +39,3 @@ export const createClient: CreateClient = <TDocuments extends PrismicDocument>(
407
39
  repositoryNameOrEndpoint: string,
408
40
  options?: ClientConfig,
409
41
  ) => new Client<TDocuments>(repositoryNameOrEndpoint, options)
410
-
411
- /**
412
- * A client that allows querying content from a Prismic repository.
413
- *
414
- * If used in an environment where a global `fetch` function is unavailable,
415
- * such as Node.js, the `fetch` option must be provided as part of the `options`
416
- * parameter.
417
- *
418
- * @typeParam TDocuments - Document types that are registered for the Prismic
419
- * repository. Query methods will automatically be typed based on this type.
420
- */
421
- export class Client<TDocuments extends PrismicDocument = PrismicDocument> {
422
- /**
423
- * The Prismic REST API V2 endpoint for the repository (use
424
- * `prismic.getRepositoryEndpoint` for the default endpoint).
425
- */
426
- endpoint: string
427
-
428
- /**
429
- * The secure token for accessing the API (only needed if your repository is
430
- * set to private).
431
- *
432
- * {@link https://user-guides.prismic.io/en/articles/1036153-generating-an-access-token}
433
- */
434
- accessToken?: string
435
-
436
- /**
437
- * A list of route resolver objects that define how a document's `url` field
438
- * is resolved.
439
- *
440
- * {@link https://prismic.io/docs/route-resolver}
441
- */
442
- routes?: NonNullable<BuildQueryURLArgs["routes"]>
443
-
444
- /**
445
- * The `brokenRoute` option allows you to define the route populated in the
446
- * `url` property for broken link or content relationship fields. A broken
447
- * link is a link or content relationship field whose linked document has been
448
- * unpublished or deleted.
449
- *
450
- * {@link https://prismic.io/docs/route-resolver}
451
- */
452
- brokenRoute?: NonNullable<BuildQueryURLArgs["brokenRoute"]>
453
-
454
- /**
455
- * The function used to make network requests to the Prismic REST API. In
456
- * environments where a global `fetch` function does not exist, such as
457
- * Node.js, this function must be provided.
458
- */
459
- fetchFn: FetchLike
460
-
461
- fetchOptions?: RequestInitLike
462
-
463
- /**
464
- * Default parameters that will be sent with each query. These parameters can
465
- * be overridden on each query if needed.
466
- */
467
- defaultParams?: Omit<
468
- BuildQueryURLArgs,
469
- "ref" | "integrationFieldsRef" | "accessToken" | "routes"
470
- >
471
-
472
- /**
473
- * The client's ref mode state. This determines which ref is used during
474
- * queries.
475
- */
476
- private refState: RefState = {
477
- mode: RefStateMode.Master,
478
- autoPreviewsEnabled: true,
479
- }
480
-
481
- /**
482
- * Cached repository value.
483
- */
484
- private cachedRepository: Repository | undefined
485
-
486
- /**
487
- * Timestamp at which the cached repository data is considered stale.
488
- */
489
- private cachedRepositoryExpiration = 0
490
-
491
- /**
492
- * Active `fetch()` jobs keyed by URL and AbortSignal (if it exists).
493
- */
494
- private fetchJobs: Record<
495
- string,
496
- Map<AbortSignalLike | undefined, Promise<FetchJobResult>>
497
- > = {}
498
-
499
- /**
500
- * Creates a Prismic client that can be used to query a repository.
501
- *
502
- * If used in an environment where a global `fetch` function is unavailable,
503
- * such as Node.js, the `fetch` option must be provided as part of the
504
- * `options` parameter.
505
- *
506
- * @param repositoryNameOrEndpoint - The Prismic repository name or full Rest
507
- * API V2 endpoint for the repository.
508
- * @param options - Configuration that determines how content will be queried
509
- * from the Prismic repository.
510
- *
511
- * @returns A client that can query content from the repository.
512
- */
513
- constructor(repositoryNameOrEndpoint: string, options: ClientConfig = {}) {
514
- if (isRepositoryEndpoint(repositoryNameOrEndpoint)) {
515
- if (process.env.NODE_ENV === "development") {
516
- // Matches non-API v2 `.prismic.io` endpoints, see: https://regex101.com/r/xRsavu/1
517
- if (/\.prismic\.io\/(?!api\/v2\/?)/i.test(repositoryNameOrEndpoint)) {
518
- throw new PrismicError(
519
- "@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.",
520
- undefined,
521
- undefined,
522
- )
523
- }
524
-
525
- const hostname = new URL(
526
- repositoryNameOrEndpoint,
527
- ).hostname.toLowerCase()
528
-
529
- // Matches non-.cdn `.prismic.io` endpoints
530
- if (
531
- hostname.endsWith(".prismic.io") &&
532
- !hostname.endsWith(".cdn.prismic.io")
533
- ) {
534
- const repositoryName = getRepositoryName(repositoryNameOrEndpoint)
535
- const dotCDNEndpoint = getRepositoryEndpoint(repositoryName)
536
- console.warn(
537
- `[@prismicio/client] A non-.cdn endpoint was provided to create a client with (\`${repositoryNameOrEndpoint}\`). Non-.cdn endpoints can have unexpected side-effects and cause performance issues when querying Prismic. Please convert it to the \`.cdn\` alternative (\`${dotCDNEndpoint}\`) or use the repository name directly instead (\`${repositoryName}\`). For more details, see ${devMsg(
538
- "endpoint-must-use-cdn",
539
- )}`,
540
- )
541
- }
542
- }
543
-
544
- this.endpoint = repositoryNameOrEndpoint
545
- } else {
546
- this.endpoint = getRepositoryEndpoint(repositoryNameOrEndpoint)
547
- }
548
-
549
- this.accessToken = options.accessToken
550
- this.routes = options.routes
551
- this.brokenRoute = options.brokenRoute
552
- this.fetchOptions = options.fetchOptions
553
- this.defaultParams = options.defaultParams
554
-
555
- if (options.ref) {
556
- this.queryContentFromRef(options.ref)
557
- }
558
-
559
- if (typeof options.fetch === "function") {
560
- this.fetchFn = options.fetch
561
- } else if (typeof globalThis.fetch === "function") {
562
- this.fetchFn = globalThis.fetch as FetchLike
563
- } else {
564
- throw new PrismicError(
565
- "A valid fetch implementation was not provided. In environments where fetch is not available (including Node.js), a fetch implementation must be provided via a polyfill or the `fetch` option.",
566
- undefined,
567
- undefined,
568
- )
569
- }
570
-
571
- // If the global fetch function is used, we must bind it to the global scope.
572
- if (this.fetchFn === globalThis.fetch) {
573
- this.fetchFn = this.fetchFn.bind(globalThis)
574
- }
575
-
576
- this.graphQLFetch = this.graphQLFetch.bind(this)
577
- }
578
-
579
- /**
580
- * Enables the client to automatically query content from a preview session if
581
- * one is active in browser environments. This is enabled by default in the
582
- * browser.
583
- *
584
- * For server environments, use `enableAutoPreviewsFromReq`.
585
- *
586
- * @example
587
- *
588
- * ```ts
589
- * client.enableAutoPreviews()
590
- * ```
591
- *
592
- * @see enableAutoPreviewsFromReq
593
- */
594
- enableAutoPreviews(): void {
595
- this.refState.autoPreviewsEnabled = true
596
- }
597
-
598
- /**
599
- * Enables the client to automatically query content from a preview session if
600
- * one is active in server environments. This is disabled by default on the
601
- * server.
602
- *
603
- * For browser environments, use `enableAutoPreviews`.
604
- *
605
- * @example
606
- *
607
- * ```ts
608
- * // In an express app
609
- * app.get("/", function (req, res) {
610
- * client.enableAutoPreviewsFromReq(req)
611
- * })
612
- * ```
613
- *
614
- * @param req - An HTTP server request object containing the request's
615
- * cookies.
616
- */
617
- enableAutoPreviewsFromReq<R extends HttpRequestLike>(req: R): void {
618
- this.refState.httpRequest = req
619
- this.refState.autoPreviewsEnabled = true
620
- }
621
-
622
- /**
623
- * Disables the client from automatically querying content from a preview
624
- * session if one is active.
625
- *
626
- * Automatic preview content querying is enabled by default unless this method
627
- * is called.
628
- *
629
- * @example
630
- *
631
- * ```ts
632
- * client.disableAutoPreviews()
633
- * ```
634
- */
635
- disableAutoPreviews(): void {
636
- this.refState.autoPreviewsEnabled = false
637
- }
638
-
639
- /**
640
- * Queries content from the Prismic repository.
641
- *
642
- * @example
643
- *
644
- * ```ts
645
- * const response = await client.get()
646
- * ```
647
- *
648
- * @typeParam TDocument - Type of Prismic documents returned.
649
- *
650
- * @param params - Parameters to filter, sort, and paginate results.
651
- *
652
- * @returns A paginated response containing the result of the query.
653
- */
654
- async get<TDocument extends TDocuments>(
655
- params?: Partial<BuildQueryURLArgs> & FetchParams,
656
- ): Promise<Query<TDocument>> {
657
- const url = await this.buildQueryURL(params)
658
-
659
- return await this.fetch<Query<TDocument>>(url, params)
660
- }
661
-
662
- /**
663
- * Queries content from the Prismic repository and returns only the first
664
- * result, if any.
665
- *
666
- * @example
667
- *
668
- * ```ts
669
- * const document = await client.getFirst()
670
- * ```
671
- *
672
- * @typeParam TDocument - Type of the Prismic document returned.
673
- *
674
- * @param params - Parameters to filter, sort, and paginate results. @returns
675
- * The first result of the query, if any.
676
- */
677
- async getFirst<TDocument extends TDocuments>(
678
- params?: Partial<BuildQueryURLArgs> & FetchParams,
679
- ): Promise<TDocument> {
680
- const actualParams = { ...params }
681
- if (!(params && params.page) && !params?.pageSize) {
682
- actualParams.pageSize = this.defaultParams?.pageSize ?? 1
683
- }
684
- const url = await this.buildQueryURL(actualParams)
685
- const result = await this.fetch<Query<TDocument>>(url, params)
686
-
687
- const firstResult = result.results[0]
688
-
689
- if (firstResult) {
690
- return firstResult
691
- }
692
-
693
- throw new NotFoundError("No documents were returned", url, undefined)
694
- }
695
-
696
- /**
697
- * **IMPORTANT**: Avoid using `dangerouslyGetAll` as it may be slower and
698
- * require more resources than other methods. Prefer using other methods that
699
- * filter by filters such as `getAllByType`.
700
- *
701
- * Queries content from the Prismic repository and returns all matching
702
- * content. If no filters are provided, all documents will be fetched.
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.dangerouslyGetAll()
711
- * ```
712
- *
713
- * @typeParam TDocument - Type of Prismic documents returned.
714
- *
715
- * @param params - Parameters to filter, sort, and paginate results.
716
- *
717
- * @returns A list of documents matching the query.
718
- */
719
- async dangerouslyGetAll<TDocument extends TDocuments>(
720
- params: Partial<Omit<BuildQueryURLArgs, "page">> &
721
- GetAllParams &
722
- FetchParams = {},
723
- ): Promise<TDocument[]> {
724
- const { limit = Infinity, ...actualParams } = params
725
- const resolvedParams = {
726
- ...actualParams,
727
- pageSize: Math.min(
728
- limit,
729
- actualParams.pageSize || this.defaultParams?.pageSize || MAX_PAGE_SIZE,
730
- ),
731
- }
732
-
733
- const documents: TDocument[] = []
734
- let latestResult: Query<TDocument> | undefined
735
-
736
- while (
737
- (!latestResult || latestResult.next_page) &&
738
- documents.length < limit
739
- ) {
740
- const page = latestResult ? latestResult.page + 1 : undefined
741
-
742
- latestResult = await this.get<TDocument>({ ...resolvedParams, page })
743
- documents.push(...latestResult.results)
744
-
745
- if (latestResult.next_page) {
746
- await new Promise((res) => setTimeout(res, GET_ALL_QUERY_DELAY))
747
- }
748
- }
749
-
750
- return documents.slice(0, limit)
751
- }
752
-
753
- /**
754
- * Queries a document from the Prismic repository with a specific ID.
755
- *
756
- * @remarks
757
- * A document's UID is different from its ID. An ID is automatically generated
758
- * for all documents and is made available on its `id` property. A UID is
759
- * provided in the Prismic editor and is unique among all documents of its
760
- * custom type.
761
- *
762
- * @example
763
- *
764
- * ```ts
765
- * const document = await client.getByID("WW4bKScAAMAqmluX")
766
- * ```
767
- *
768
- * @typeParam TDocument- Type of the Prismic document returned.
769
- *
770
- * @param id - ID of the document.
771
- * @param params - Parameters to filter, sort, and paginate the results.
772
- *
773
- * @returns The document with an ID matching the `id` parameter, if a matching
774
- * document exists.
775
- */
776
- async getByID<TDocument extends TDocuments>(
777
- id: string,
778
- params?: Partial<BuildQueryURLArgs> & FetchParams,
779
- ): Promise<TDocument> {
780
- return await this.getFirst<TDocument>(
781
- appendFilters(params, filter.at("document.id", id)),
782
- )
783
- }
784
-
785
- /**
786
- * Queries documents from the Prismic repository with specific IDs.
787
- *
788
- * @remarks
789
- * A document's UID is different from its ID. An ID is automatically generated
790
- * for all documents and is made available on its `id` property. A UID is
791
- * provided in the Prismic editor and is unique among all documents of its
792
- * custom type.
793
- *
794
- * @example
795
- *
796
- * ```ts
797
- * const response = await client.getByIDs([
798
- * "WW4bKScAAMAqmluX",
799
- * "U1kTRgEAAC8A5ldS",
800
- * ])
801
- * ```
802
- *
803
- * @typeParam TDocument - Type of Prismic documents returned.
804
- *
805
- * @param ids - A list of document IDs.
806
- * @param params - Parameters to filter, sort, and paginate the results.
807
- *
808
- * @returns A paginated response containing documents with IDs matching the
809
- * `ids` parameter.
810
- */
811
- async getByIDs<TDocument extends TDocuments>(
812
- ids: string[],
813
- params?: Partial<BuildQueryURLArgs> & FetchParams,
814
- ): Promise<Query<TDocument>> {
815
- return await this.get<TDocument>(
816
- appendFilters(params, filter.in("document.id", ids)),
817
- )
818
- }
819
-
820
- /**
821
- * Queries all documents from the Prismic repository with specific IDs.
822
- *
823
- * This method may make multiple network requests to query all matching
824
- * content.
825
- *
826
- * @remarks
827
- * A document's UID is different from its ID. An ID is automatically generated
828
- * for all documents and is made available on its `id` property. A UID is
829
- * provided in the Prismic editor and is unique among all documents of its
830
- * custom type.
831
- *
832
- * @example
833
- *
834
- * ```ts
835
- * const response = await client.getAllByIDs([
836
- * "WW4bKScAAMAqmluX",
837
- * "U1kTRgEAAC8A5ldS",
838
- * ])
839
- * ```
840
- *
841
- * @typeParam TDocument - Type of Prismic documents returned.
842
- *
843
- * @param ids - A list of document IDs.
844
- * @param params - Parameters to filter, sort, and paginate the results.
845
- *
846
- * @returns A list of documents with IDs matching the `ids` parameter.
847
- */
848
- async getAllByIDs<TDocument extends TDocuments>(
849
- ids: string[],
850
- params?: Partial<BuildQueryURLArgs> & GetAllParams & FetchParams,
851
- ): Promise<TDocument[]> {
852
- return await this.dangerouslyGetAll<TDocument>(
853
- appendFilters(params, filter.in("document.id", ids)),
854
- )
855
- }
856
-
857
- /**
858
- * Queries a document from the Prismic repository with a specific UID and
859
- * custom type.
860
- *
861
- * @remarks
862
- * A document's UID is different from its ID. An ID is automatically generated
863
- * for all documents and is made available on its `id` property. A UID is
864
- * provided in the Prismic editor and is unique among all documents of its
865
- * custom type.
866
- *
867
- * @example
868
- *
869
- * ```ts
870
- * const document = await client.getByUID("blog_post", "my-first-post")
871
- * ```
872
- *
873
- * @typeParam TDocument - Type of the Prismic document returned.
874
- *
875
- * @param documentType - The API ID of the document's custom type.
876
- * @param uid - UID of the document.
877
- * @param params - Parameters to filter, sort, and paginate the results.
878
- *
879
- * @returns The document with a UID matching the `uid` parameter, if a
880
- * matching document exists.
881
- */
882
- async getByUID<
883
- TDocument extends TDocuments,
884
- TDocumentType extends TDocument["type"] = TDocument["type"],
885
- >(
886
- documentType: TDocumentType,
887
- uid: string,
888
- params?: Partial<BuildQueryURLArgs> & FetchParams,
889
- ): Promise<ExtractDocumentType<TDocument, TDocumentType>> {
890
- return await this.getFirst<ExtractDocumentType<TDocument, TDocumentType>>(
891
- appendFilters(params, [
892
- typeFilter(documentType),
893
- filter.at(`my.${documentType}.uid`, uid),
894
- ]),
895
- )
896
- }
897
-
898
- /**
899
- * Queries document from the Prismic repository with specific UIDs and Custom
900
- * Type.
901
- *
902
- * @remarks
903
- * A document's UID is different from its ID. An ID is automatically generated
904
- * for all documents and is made available on its `id` property. A UID is
905
- * provided in the Prismic editor and is unique among all documents of its
906
- * custom type.
907
- *
908
- * @example
909
- *
910
- * ```ts
911
- * const document = await client.getByUIDs("blog_post", [
912
- * "my-first-post",
913
- * "my-second-post",
914
- * ])
915
- * ```
916
- *
917
- * @typeParam TDocument - Type of the Prismic document returned.
918
- *
919
- * @param documentType - The API ID of the document's custom type.
920
- * @param uids - A list of document UIDs.
921
- * @param params - Parameters to filter, sort, and paginate the results.
922
- *
923
- * @returns A paginated response containing documents with UIDs matching the
924
- * `uids` parameter.
925
- */
926
- async getByUIDs<
927
- TDocument extends TDocuments,
928
- TDocumentType extends TDocument["type"] = TDocument["type"],
929
- >(
930
- documentType: TDocumentType,
931
- uids: string[],
932
- params?: Partial<BuildQueryURLArgs> & FetchParams,
933
- ): Promise<Query<ExtractDocumentType<TDocument, TDocumentType>>> {
934
- return await this.get<ExtractDocumentType<TDocument, TDocumentType>>(
935
- appendFilters(params, [
936
- typeFilter(documentType),
937
- filter.in(`my.${documentType}.uid`, uids),
938
- ]),
939
- )
940
- }
941
-
942
- /**
943
- * Queries all documents from the Prismic repository with specific UIDs and
944
- * custom type.
945
- *
946
- * This method may make multiple network requests to query all matching
947
- * content.
948
- *
949
- * @remarks
950
- * A document's UID is different from its ID. An ID is automatically generated
951
- * for all documents and is made available on its `id` property. A UID is
952
- * provided in the Prismic editor and is unique among all documents of its
953
- * custom type.
954
- *
955
- * @example
956
- *
957
- * ```ts
958
- * const response = await client.getAllByUIDs([
959
- * "my-first-post",
960
- * "my-second-post",
961
- * ])
962
- * ```
963
- *
964
- * @typeParam TDocument - Type of Prismic documents returned.
965
- *
966
- * @param documentType - The API ID of the document's custom type.
967
- * @param uids - A list of document UIDs.
968
- * @param params - Parameters to filter, sort, and paginate the results.
969
- *
970
- * @returns A list of documents with UIDs matching the `uids` parameter.
971
- */
972
- async getAllByUIDs<
973
- TDocument extends TDocuments,
974
- TDocumentType extends TDocument["type"] = TDocument["type"],
975
- >(
976
- documentType: TDocumentType,
977
- uids: string[],
978
- params?: Partial<BuildQueryURLArgs> & GetAllParams & FetchParams,
979
- ): Promise<ExtractDocumentType<TDocument, TDocumentType>[]> {
980
- return await this.dangerouslyGetAll<
981
- ExtractDocumentType<TDocument, TDocumentType>
982
- >(
983
- appendFilters(params, [
984
- typeFilter(documentType),
985
- filter.in(`my.${documentType}.uid`, uids),
986
- ]),
987
- )
988
- }
989
-
990
- /**
991
- * Queries a singleton document from the Prismic repository for a specific
992
- * custom type.
993
- *
994
- * @remarks
995
- * A singleton document is one that is configured in Prismic to only allow one
996
- * instance. For example, a repository may be configured to contain just one
997
- * Settings document. This is in contrast to a repeatable custom type which
998
- * allows multiple instances of itself.
999
- *
1000
- * @example
1001
- *
1002
- * ```ts
1003
- * const document = await client.getSingle("settings")
1004
- * ```
1005
- *
1006
- * @typeParam TDocument - Type of the Prismic document returned.
1007
- *
1008
- * @param documentType - The API ID of the singleton custom type.
1009
- * @param params - Parameters to filter, sort, and paginate the results.
1010
- *
1011
- * @returns The singleton document for the custom type, if a matching document
1012
- * exists.
1013
- */
1014
- async getSingle<
1015
- TDocument extends TDocuments,
1016
- TDocumentType extends TDocument["type"] = TDocument["type"],
1017
- >(
1018
- documentType: TDocumentType,
1019
- params?: Partial<BuildQueryURLArgs> & FetchParams,
1020
- ): Promise<ExtractDocumentType<TDocument, TDocumentType>> {
1021
- return await this.getFirst<ExtractDocumentType<TDocument, TDocumentType>>(
1022
- appendFilters(params, typeFilter(documentType)),
1023
- )
1024
- }
1025
-
1026
- /**
1027
- * Queries documents from the Prismic repository for a specific custom type.
1028
- *
1029
- * Use `getAllByType` instead if you need to query all documents for a
1030
- * specific custom type.
1031
- *
1032
- * @example
1033
- *
1034
- * ```ts
1035
- * const response = await client.getByType("blog_post")
1036
- * ```
1037
- *
1038
- * @typeParam TDocument - Type of Prismic documents returned.
1039
- *
1040
- * @param documentType - The API ID of the custom type.
1041
- * @param params - Parameters to filter, sort, and paginate the results.
1042
- *
1043
- * @returns A paginated response containing documents of the custom type.
1044
- */
1045
- async getByType<
1046
- TDocument extends TDocuments,
1047
- TDocumentType extends TDocument["type"] = TDocument["type"],
1048
- >(
1049
- documentType: TDocumentType,
1050
- params?: Partial<BuildQueryURLArgs> & FetchParams,
1051
- ): Promise<Query<ExtractDocumentType<TDocument, TDocumentType>>> {
1052
- return await this.get<ExtractDocumentType<TDocument, TDocumentType>>(
1053
- appendFilters(params, typeFilter(documentType)),
1054
- )
1055
- }
1056
-
1057
- /**
1058
- * Queries all documents from the Prismic repository for a specific Custom
1059
- * Type.
1060
- *
1061
- * This method may make multiple network requests to query all matching
1062
- * content.
1063
- *
1064
- * @example
1065
- *
1066
- * ```ts
1067
- * const response = await client.getByType("blog_post")
1068
- * ```
1069
- *
1070
- * @typeParam TDocument - Type of Prismic documents returned.
1071
- *
1072
- * @param documentType - The API ID of the custom type.
1073
- * @param params - Parameters to filter, sort, and paginate the results.
1074
- *
1075
- * @returns A list of all documents of the custom type.
1076
- */
1077
- async getAllByType<
1078
- TDocument extends TDocuments,
1079
- TDocumentType extends TDocument["type"] = TDocument["type"],
1080
- >(
1081
- documentType: TDocumentType,
1082
- params?: Partial<Omit<BuildQueryURLArgs, "page">> &
1083
- GetAllParams &
1084
- FetchParams,
1085
- ): Promise<ExtractDocumentType<TDocument, TDocumentType>[]> {
1086
- return await this.dangerouslyGetAll<
1087
- ExtractDocumentType<TDocument, TDocumentType>
1088
- >(appendFilters(params, typeFilter(documentType)))
1089
- }
1090
-
1091
- /**
1092
- * Queries documents from the Prismic repository with a specific tag.
1093
- *
1094
- * Use `getAllByTag` instead if you need to query all documents with a
1095
- * specific tag.
1096
- *
1097
- * @example
1098
- *
1099
- * ```ts
1100
- * const response = await client.getByTag("food")
1101
- * ```
1102
- *
1103
- * @typeParam TDocument - Type of Prismic documents returned.
1104
- *
1105
- * @param tag - The tag that must be included on a document.
1106
- * @param params - Parameters to filter, sort, and paginate the results.
1107
- *
1108
- * @returns A paginated response containing documents with the tag.
1109
- */
1110
- async getByTag<TDocument extends TDocuments>(
1111
- tag: string,
1112
- params?: Partial<BuildQueryURLArgs> & FetchParams,
1113
- ): Promise<Query<TDocument>> {
1114
- return await this.get<TDocument>(appendFilters(params, someTagsFilter(tag)))
1115
- }
1116
-
1117
- /**
1118
- * Queries all documents from the Prismic repository with a specific tag.
1119
- *
1120
- * This method may make multiple network requests to query all matching
1121
- * content.
1122
- *
1123
- * @example
1124
- *
1125
- * ```ts
1126
- * const response = await client.getAllByTag("food")
1127
- * ```
1128
- *
1129
- * @typeParam TDocument - Type of Prismic documents returned.
1130
- *
1131
- * @param tag - The tag that must be included on a document.
1132
- * @param params - Parameters to filter, sort, and paginate the results.
1133
- *
1134
- * @returns A list of all documents with the tag.
1135
- */
1136
- async getAllByTag<TDocument extends TDocuments>(
1137
- tag: string,
1138
- params?: Partial<Omit<BuildQueryURLArgs, "page">> &
1139
- GetAllParams &
1140
- FetchParams,
1141
- ): Promise<TDocument[]> {
1142
- return await this.dangerouslyGetAll<TDocument>(
1143
- appendFilters(params, someTagsFilter(tag)),
1144
- )
1145
- }
1146
-
1147
- /**
1148
- * Queries documents from the Prismic repository with specific tags. A
1149
- * document must be tagged with all of the queried tags to be included.
1150
- *
1151
- * @example
1152
- *
1153
- * ```ts
1154
- * const response = await client.getByEveryTag(["food", "fruit"])
1155
- * ```
1156
- *
1157
- * @typeParam TDocument - Type of Prismic documents returned.
1158
- *
1159
- * @param tags - A list of tags that must be included on a document.
1160
- * @param params - Parameters to filter, sort, and paginate the results.
1161
- *
1162
- * @returns A paginated response containing documents with the tags.
1163
- */
1164
- async getByEveryTag<TDocument extends TDocuments>(
1165
- tags: string[],
1166
- params?: Partial<BuildQueryURLArgs> & FetchParams,
1167
- ): Promise<Query<TDocument>> {
1168
- return await this.get<TDocument>(
1169
- appendFilters(params, everyTagFilter(tags)),
1170
- )
1171
- }
1172
-
1173
- /**
1174
- * Queries documents from the Prismic repository with specific tags. A
1175
- * document must be tagged with all of the queried tags to be included.
1176
- *
1177
- * This method may make multiple network requests to query all matching
1178
- * content.
1179
- *
1180
- * @example
1181
- *
1182
- * ```ts
1183
- * const response = await client.getAllByEveryTag(["food", "fruit"])
1184
- * ```
1185
- *
1186
- * @typeParam TDocument - Type of Prismic documents returned.
1187
- *
1188
- * @param tags - A list of tags that must be included on a document.
1189
- * @param params - Parameters to filter, sort, and paginate the results.
1190
- *
1191
- * @returns A list of all documents with the tags.
1192
- */
1193
- async getAllByEveryTag<TDocument extends TDocuments>(
1194
- tags: string[],
1195
- params?: Partial<Omit<BuildQueryURLArgs, "page">> &
1196
- GetAllParams &
1197
- FetchParams,
1198
- ): Promise<TDocument[]> {
1199
- return await this.dangerouslyGetAll<TDocument>(
1200
- appendFilters(params, everyTagFilter(tags)),
1201
- )
1202
- }
1203
-
1204
- /**
1205
- * Queries documents from the Prismic repository with specific tags. A
1206
- * document must be tagged with at least one of the queried tags to be
1207
- * included.
1208
- *
1209
- * @example
1210
- *
1211
- * ```ts
1212
- * const response = await client.getByEveryTag(["food", "fruit"])
1213
- * ```
1214
- *
1215
- * @typeParam TDocument - Type of Prismic documents returned.
1216
- *
1217
- * @param tags - A list of tags that must be included on a document.
1218
- * @param params - Parameters to filter, sort, and paginate the results.
1219
- *
1220
- * @returns A paginated response containing documents with at least one of the
1221
- * tags.
1222
- */
1223
- async getBySomeTags<TDocument extends TDocuments>(
1224
- tags: string[],
1225
- params?: Partial<BuildQueryURLArgs> & FetchParams,
1226
- ): Promise<Query<TDocument>> {
1227
- return await this.get<TDocument>(
1228
- appendFilters(params, someTagsFilter(tags)),
1229
- )
1230
- }
1231
-
1232
- /**
1233
- * Queries documents from the Prismic repository with specific tags. A
1234
- * document must be tagged with at least one of the queried tags to be
1235
- * included.
1236
- *
1237
- * This method may make multiple network requests to query all matching
1238
- * content.
1239
- *
1240
- * @example
1241
- *
1242
- * ```ts
1243
- * const response = await client.getAllBySomeTags(["food", "fruit"])
1244
- * ```
1245
- *
1246
- * @typeParam TDocument - Type of Prismic documents returned.
1247
- *
1248
- * @param tags - A list of tags that must be included on a document.
1249
- * @param params - Parameters to filter, sort, and paginate the results.
1250
- *
1251
- * @returns A list of all documents with at least one of the tags.
1252
- */
1253
- async getAllBySomeTags<TDocument extends TDocuments>(
1254
- tags: string[],
1255
- params?: Partial<Omit<BuildQueryURLArgs, "page">> &
1256
- GetAllParams &
1257
- FetchParams,
1258
- ): Promise<TDocument[]> {
1259
- return await this.dangerouslyGetAll<TDocument>(
1260
- appendFilters(params, someTagsFilter(tags)),
1261
- )
1262
- }
1263
-
1264
- /**
1265
- * Returns metadata about the Prismic repository, such as its refs, releases,
1266
- * and custom types.
1267
- *
1268
- * @returns Repository metadata.
1269
- */
1270
- async getRepository(params?: FetchParams): Promise<Repository> {
1271
- // TODO: Restore when Authorization header support works in browsers with CORS.
1272
- // return await this.fetch<Repository>(this.endpoint);
1273
-
1274
- const url = new URL(this.endpoint)
1275
-
1276
- if (this.accessToken) {
1277
- url.searchParams.set("access_token", this.accessToken)
1278
- }
1279
-
1280
- return await this.fetch<Repository>(url.toString(), params)
1281
- }
1282
-
1283
- /**
1284
- * Returns a list of all refs for the Prismic repository.
1285
- *
1286
- * Refs are used to identify which version of the repository's content should
1287
- * be queried. All repositories will have at least one ref pointing to the
1288
- * latest published content called the "master ref".
1289
- *
1290
- * @returns A list of all refs for the Prismic repository.
1291
- */
1292
- async getRefs(params?: FetchParams): Promise<Ref[]> {
1293
- const repository = await this.getRepository(params)
1294
-
1295
- return repository.refs
1296
- }
1297
-
1298
- /**
1299
- * Returns a ref for the Prismic repository with a matching ID.
1300
- *
1301
- * @param id - ID of the ref.
1302
- *
1303
- * @returns The ref with a matching ID, if it exists.
1304
- */
1305
- async getRefByID(id: string, params?: FetchParams): Promise<Ref> {
1306
- const refs = await this.getRefs(params)
1307
-
1308
- return findRefByID(refs, id)
1309
- }
1310
-
1311
- /**
1312
- * Returns a ref for the Prismic repository with a matching label.
1313
- *
1314
- * @param label - Label of the ref.
1315
- *
1316
- * @returns The ref with a matching label, if it exists.
1317
- */
1318
- async getRefByLabel(label: string, params?: FetchParams): Promise<Ref> {
1319
- const refs = await this.getRefs(params)
1320
-
1321
- return findRefByLabel(refs, label)
1322
- }
1323
-
1324
- /**
1325
- * Returns the master ref for the Prismic repository. The master ref points to
1326
- * the repository's latest published content.
1327
- *
1328
- * @returns The repository's master ref.
1329
- */
1330
- async getMasterRef(params?: FetchParams): Promise<Ref> {
1331
- const refs = await this.getRefs(params)
1332
-
1333
- return findMasterRef(refs)
1334
- }
1335
-
1336
- /**
1337
- * Returns a list of all Releases for the Prismic repository. Releases are
1338
- * used to group content changes before publishing.
1339
- *
1340
- * @returns A list of all Releases for the Prismic repository.
1341
- */
1342
- async getReleases(params?: FetchParams): Promise<Ref[]> {
1343
- const refs = await this.getRefs(params)
1344
-
1345
- return refs.filter((ref) => !ref.isMasterRef)
1346
- }
1347
-
1348
- /**
1349
- * Returns a Release for the Prismic repository with a matching ID.
1350
- *
1351
- * @param id - ID of the Release.
1352
- *
1353
- * @returns The Release with a matching ID, if it exists.
1354
- */
1355
- async getReleaseByID(id: string, params?: FetchParams): Promise<Ref> {
1356
- const releases = await this.getReleases(params)
1357
-
1358
- return findRefByID(releases, id)
1359
- }
1360
-
1361
- /**
1362
- * Returns a Release for the Prismic repository with a matching label.
1363
- *
1364
- * @param label - Label of the ref.
1365
- *
1366
- * @returns The ref with a matching label, if it exists.
1367
- */
1368
- async getReleaseByLabel(label: string, params?: FetchParams): Promise<Ref> {
1369
- const releases = await this.getReleases(params)
1370
-
1371
- return findRefByLabel(releases, label)
1372
- }
1373
-
1374
- /**
1375
- * Returns a list of all tags used in the Prismic repository.
1376
- *
1377
- * @returns A list of all tags used in the repository.
1378
- */
1379
- async getTags(params?: FetchParams): Promise<string[]> {
1380
- try {
1381
- const tagsForm = await this.getCachedRepositoryForm("tags", params)
1382
-
1383
- const url = new URL(tagsForm.action)
1384
-
1385
- if (this.accessToken) {
1386
- url.searchParams.set("access_token", this.accessToken)
1387
- }
1388
-
1389
- return await this.fetch<string[]>(url.toString(), params)
1390
- } catch {
1391
- const repository = await this.getRepository(params)
1392
-
1393
- return repository.tags
1394
- }
1395
- }
1396
-
1397
- /**
1398
- * Builds a URL used to query content from the Prismic repository.
1399
- *
1400
- * @param params - Parameters to filter, sort, and paginate the results.
1401
- *
1402
- * @returns A URL string that can be requested to query content.
1403
- */
1404
- async buildQueryURL({
1405
- signal,
1406
- fetchOptions,
1407
- ...params
1408
- }: Partial<BuildQueryURLArgs> & FetchParams = {}): Promise<string> {
1409
- const ref =
1410
- params.ref || (await this.getResolvedRefString({ signal, fetchOptions }))
1411
- const integrationFieldsRef =
1412
- params.integrationFieldsRef ||
1413
- (await this.getCachedRepository({ signal, fetchOptions }))
1414
- .integrationFieldsRef ||
1415
- undefined
1416
-
1417
- return buildQueryURL(this.endpoint, {
1418
- ...this.defaultParams,
1419
- ...params,
1420
- ref,
1421
- integrationFieldsRef,
1422
- routes: params.routes || this.routes,
1423
- brokenRoute: params.brokenRoute || this.brokenRoute,
1424
- accessToken: params.accessToken || this.accessToken,
1425
- })
1426
- }
1427
-
1428
- /**
1429
- * Determines the URL for a previewed document during an active preview
1430
- * session. The result of this method should be used to redirect the user to
1431
- * the document's URL.
1432
- *
1433
- * @example
1434
- *
1435
- * ```ts
1436
- * const url = client.resolvePreviewURL({
1437
- * linkResolver: (document) => `/${document.uid}`
1438
- * defaultURL: '/'
1439
- * })
1440
- * ```
1441
- *
1442
- * @param args - Arguments to configure the URL resolving.
1443
- *
1444
- * @returns The URL for the previewed document during an active preview
1445
- * session. The user should be redirected to this URL.
1446
- */
1447
- async resolvePreviewURL<LinkResolverReturnType>(
1448
- args: ResolvePreviewArgs<LinkResolverReturnType> & FetchParams,
1449
- ): Promise<string> {
1450
- let documentID: string | undefined | null = args.documentID
1451
- let previewToken: string | undefined | null = args.previewToken
1452
-
1453
- if (typeof globalThis.location !== "undefined") {
1454
- const searchParams = new URLSearchParams(globalThis.location.search)
1455
-
1456
- documentID = documentID || searchParams.get("documentId")
1457
- previewToken = previewToken || searchParams.get("token")
1458
- } else if (this.refState.httpRequest) {
1459
- if ("query" in this.refState.httpRequest) {
1460
- documentID =
1461
- documentID || (this.refState.httpRequest.query?.documentId as string)
1462
- previewToken =
1463
- previewToken || (this.refState.httpRequest.query?.token as string)
1464
- } else if (
1465
- "url" in this.refState.httpRequest &&
1466
- this.refState.httpRequest.url
1467
- ) {
1468
- // Including "missing-host://" by default
1469
- // handles a case where Next.js Route Handlers
1470
- // only provide the pathname and search
1471
- // parameters in the `url` property
1472
- // (e.g. `/api/preview?foo=bar`).
1473
- const searchParams = new URL(
1474
- this.refState.httpRequest.url,
1475
- "missing-host://",
1476
- ).searchParams
1477
-
1478
- documentID = documentID || searchParams.get("documentId")
1479
- previewToken = previewToken || searchParams.get("token")
1480
- }
1481
- }
1482
-
1483
- if (documentID != null && previewToken != null) {
1484
- const document = await this.getByID(documentID, {
1485
- ref: previewToken,
1486
- lang: "*",
1487
- signal: args.signal,
1488
- fetchOptions: args.fetchOptions,
1489
- })
1490
-
1491
- const url = asLink(document, { linkResolver: args.linkResolver })
1492
-
1493
- if (typeof url === "string") {
1494
- return url
1495
- }
1496
- }
1497
-
1498
- return args.defaultURL
1499
- }
1500
-
1501
- /**
1502
- * Configures the client to query the latest published content for all future
1503
- * queries.
1504
- *
1505
- * If the `ref` parameter is provided during a query, it takes priority for
1506
- * that query.
1507
- *
1508
- * @example
1509
- *
1510
- * ```ts
1511
- * await client.queryLatestContent()
1512
- * const document = await client.getByID("WW4bKScAAMAqmluX")
1513
- * ```
1514
- */
1515
- queryLatestContent(): void {
1516
- this.refState.mode = RefStateMode.Master
1517
- }
1518
-
1519
- /**
1520
- * Configures the client to query content from a specific Release identified
1521
- * by its ID for all future queries.
1522
- *
1523
- * If the `ref` parameter is provided during a query, it takes priority for
1524
- * that query.
1525
- *
1526
- * @example
1527
- *
1528
- * ```ts
1529
- * await client.queryContentFromReleaseByID("YLB7OBAAACMA7Cpa")
1530
- * const document = await client.getByID("WW4bKScAAMAqmluX")
1531
- * ```
1532
- *
1533
- * @param releaseID - The ID of the Release.
1534
- */
1535
- queryContentFromReleaseByID(releaseID: string): void {
1536
- this.refState = {
1537
- ...this.refState,
1538
- mode: RefStateMode.ReleaseID,
1539
- releaseID,
1540
- }
1541
- }
1542
-
1543
- /**
1544
- * Configures the client to query content from a specific Release identified
1545
- * by its label for all future queries.
1546
- *
1547
- * If the `ref` parameter is provided during a query, it takes priority for
1548
- * that query.
1549
- *
1550
- * @example
1551
- *
1552
- * ```ts
1553
- * await client.queryContentFromReleaseByLabel("My Release")
1554
- * const document = await client.getByID("WW4bKScAAMAqmluX")
1555
- * ```
1556
- *
1557
- * @param releaseLabel - The label of the Release.
1558
- */
1559
- queryContentFromReleaseByLabel(releaseLabel: string): void {
1560
- this.refState = {
1561
- ...this.refState,
1562
- mode: RefStateMode.ReleaseLabel,
1563
- releaseLabel,
1564
- }
1565
- }
1566
-
1567
- /**
1568
- * Configures the client to query content from a specific ref. The ref can be
1569
- * provided as a string or a function.
1570
- *
1571
- * If a function is provided, the ref is fetched lazily before each query. The
1572
- * function may also be asynchronous.
1573
- *
1574
- * @example
1575
- *
1576
- * ```ts
1577
- * await client.queryContentFromRef("my-ref")
1578
- * const document = await client.getByID("WW4bKScAAMAqmluX")
1579
- * ```
1580
- *
1581
- * @param ref - The ref or a function that returns the ref from which to query
1582
- * content.
1583
- */
1584
- queryContentFromRef(ref: RefStringOrThunk): void {
1585
- this.refState = {
1586
- ...this.refState,
1587
- mode: RefStateMode.Manual,
1588
- ref,
1589
- }
1590
- }
1591
-
1592
- /**
1593
- * A `fetch()` function to be used with GraphQL clients configured for
1594
- * Prismic's GraphQL API. It automatically applies the necessary `prismic-ref`
1595
- * and Authorization headers. Queries will automatically be minified by
1596
- * removing whitespace where possible.
1597
- *
1598
- * @example
1599
- *
1600
- * ```ts
1601
- * const graphQLClient = new ApolloClient({
1602
- * link: new HttpLink({
1603
- * uri: prismic.getGraphQLEndpoint(repositoryName),
1604
- * // Provide `client.graphQLFetch` as the fetch implementation.
1605
- * fetch: client.graphQLFetch,
1606
- * // Using GET is required.
1607
- * useGETForQueries: true,
1608
- * }),
1609
- * cache: new InMemoryCache(),
1610
- * })
1611
- * ```
1612
- *
1613
- * @param input - The `fetch()` `input` parameter. Only strings are supported.
1614
- * @param init - The `fetch()` `init` parameter. Only plain objects are
1615
- * supported.
1616
- *
1617
- * @returns The `fetch()` Response for the request.
1618
- *
1619
- * @experimental
1620
- */
1621
- async graphQLFetch(
1622
- input: RequestInfo,
1623
- init?: Omit<RequestInit, "signal"> & { signal?: AbortSignalLike },
1624
- ): Promise<Response> {
1625
- const cachedRepository = await this.getCachedRepository()
1626
- const ref = await this.getResolvedRefString()
1627
-
1628
- const unsanitizedHeaders: Record<string, string> = {
1629
- "Prismic-ref": ref,
1630
- Authorization: this.accessToken ? `Token ${this.accessToken}` : "",
1631
- // Asserting `init.headers` is a Record since popular GraphQL
1632
- // libraries pass this as a Record. Header objects as input
1633
- // are unsupported.
1634
- ...(init ? (init.headers as Record<string, string>) : {}),
1635
- }
1636
-
1637
- if (cachedRepository.integrationFieldsRef) {
1638
- unsanitizedHeaders["Prismic-integration-field-ref"] =
1639
- cachedRepository.integrationFieldsRef
1640
- }
1641
-
1642
- // Normalize header keys to lowercase. This prevents header
1643
- // conflicts between the Prismic client and the GraphQL
1644
- // client.
1645
- const headers: Record<string, string> = {}
1646
- for (const key in unsanitizedHeaders) {
1647
- if (unsanitizedHeaders[key]) {
1648
- headers[key.toLowerCase()] =
1649
- unsanitizedHeaders[key as keyof typeof unsanitizedHeaders]
1650
- }
1651
- }
1652
-
1653
- const url = new URL(
1654
- // Asserting `input` is a string since popular GraphQL
1655
- // libraries pass this as a string. Request objects as
1656
- // input are unsupported.
1657
- input as string,
1658
- )
1659
-
1660
- // This prevents the request from being cached unnecessarily.
1661
- // Without adding this `ref` param, re-running a query
1662
- // could return a locally cached response, even if the
1663
- // `ref` changed. This happens because the URL is
1664
- // identical when the `ref` is not included. Caches may ignore
1665
- // headers.
1666
- //
1667
- // The Prismic GraphQL API ignores the `ref` param.
1668
- url.searchParams.set("ref", ref)
1669
-
1670
- const query = url.searchParams.get("query")
1671
- if (query) {
1672
- url.searchParams.set(
1673
- "query",
1674
- // Compress the GraphQL query (if it exists) by
1675
- // removing whitespace. This is done to
1676
- // optimize the query size and avoid
1677
- // hitting the upper limit of GET requests
1678
- // (2048 characters).
1679
- minifyGraphQLQuery(query),
1680
- )
1681
- }
1682
-
1683
- return (await this.fetchFn(url.toString(), {
1684
- ...init,
1685
- headers,
1686
- })) as Response
1687
- }
1688
-
1689
- /**
1690
- * Returns a cached version of `getRepository` with a TTL.
1691
- *
1692
- * @returns Cached repository metadata.
1693
- */
1694
- private async getCachedRepository(params?: FetchParams): Promise<Repository> {
1695
- if (
1696
- !this.cachedRepository ||
1697
- Date.now() >= this.cachedRepositoryExpiration
1698
- ) {
1699
- this.cachedRepositoryExpiration = Date.now() + REPOSITORY_CACHE_TTL
1700
- this.cachedRepository = await this.getRepository(params)
1701
- }
1702
-
1703
- return this.cachedRepository
1704
- }
1705
-
1706
- /**
1707
- * Returns a cached Prismic repository form. Forms are used to determine API
1708
- * endpoints for types of repository data.
1709
- *
1710
- * @param name - Name of the form.
1711
- *
1712
- * @returns The repository form.
1713
- *
1714
- * @throws If a matching form cannot be found.
1715
- */
1716
- private async getCachedRepositoryForm(
1717
- name: string,
1718
- params?: FetchParams,
1719
- ): Promise<Form> {
1720
- const cachedRepository = await this.getCachedRepository(params)
1721
- const form = cachedRepository.forms[name]
1722
-
1723
- if (!form) {
1724
- throw new PrismicError(
1725
- `Form with name "${name}" could not be found`,
1726
- undefined,
1727
- undefined,
1728
- )
1729
- }
1730
-
1731
- return form
1732
- }
1733
-
1734
- /**
1735
- * Returns the ref needed to query based on the client's current state. This
1736
- * method may make a network request to fetch a ref or resolve the user's ref
1737
- * thunk.
1738
- *
1739
- * If auto previews are enabled, the preview ref takes priority if available.
1740
- *
1741
- * The following strategies are used depending on the client's state:
1742
- *
1743
- * - If the user called `queryLatestContent`: Use the repository's master ref.
1744
- * The ref is cached for 5 seconds. After 5 seconds, a new master ref is
1745
- * fetched.
1746
- * - If the user called `queryContentFromReleaseByID`: Use the release's ref.
1747
- * The ref is cached for 5 seconds. After 5 seconds, a new ref for the
1748
- * release is fetched.
1749
- * - If the user called `queryContentFromReleaseByLabel`: Use the release's ref.
1750
- * The ref is cached for 5 seconds. After 5 seconds, a new ref for the
1751
- * release is fetched.
1752
- * - If the user called `queryContentFromRef`: Use the provided ref. Fall back
1753
- * to the master ref if the ref is not a string.
1754
- *
1755
- * @returns The ref to use during a query.
1756
- */
1757
- private async getResolvedRefString(params?: FetchParams): Promise<string> {
1758
- if (this.refState.autoPreviewsEnabled) {
1759
- let previewRef: string | undefined
1760
-
1761
- let cookieJar: string | null | undefined
1762
-
1763
- if (this.refState.httpRequest?.headers) {
1764
- if (
1765
- "get" in this.refState.httpRequest.headers &&
1766
- typeof this.refState.httpRequest.headers.get === "function"
1767
- ) {
1768
- // Web API Headers
1769
- cookieJar = this.refState.httpRequest.headers.get("cookie")
1770
- } else if ("cookie" in this.refState.httpRequest.headers) {
1771
- // Express-style headers
1772
- cookieJar = this.refState.httpRequest.headers.cookie
1773
- }
1774
- } else if (globalThis.document?.cookie) {
1775
- cookieJar = globalThis.document.cookie
1776
- }
1777
-
1778
- if (cookieJar) {
1779
- previewRef = getPreviewCookie(cookieJar)
1780
- }
1781
-
1782
- if (previewRef) {
1783
- return previewRef
1784
- }
1785
- }
1786
-
1787
- const cachedRepository = await this.getCachedRepository(params)
1788
-
1789
- const refModeType = this.refState.mode
1790
- if (refModeType === RefStateMode.ReleaseID) {
1791
- return findRefByID(cachedRepository.refs, this.refState.releaseID).ref
1792
- } else if (refModeType === RefStateMode.ReleaseLabel) {
1793
- return findRefByLabel(cachedRepository.refs, this.refState.releaseLabel)
1794
- .ref
1795
- } else if (refModeType === RefStateMode.Manual) {
1796
- const res = await castThunk(this.refState.ref)()
1797
-
1798
- if (typeof res === "string") {
1799
- return res
1800
- }
1801
- }
1802
-
1803
- return findMasterRef(cachedRepository.refs).ref
1804
- }
1805
-
1806
- /**
1807
- * Performs a network request using the configured `fetch` function. It
1808
- * assumes all successful responses will have a JSON content type. It also
1809
- * normalizes unsuccessful network requests.
1810
- *
1811
- * @typeParam T - The JSON response.
1812
- *
1813
- * @param url - URL to the resource to fetch.
1814
- * @param params - Prismic REST API parameters for the network request.
1815
- *
1816
- * @returns The JSON response from the network request.
1817
- */
1818
- private async fetch<T = unknown>(
1819
- url: string,
1820
- params: FetchParams = {},
1821
- ): Promise<T> {
1822
- const requestInit: RequestInitLike = {
1823
- ...this.fetchOptions,
1824
- ...params.fetchOptions,
1825
- headers: {
1826
- ...this.fetchOptions?.headers,
1827
- ...params.fetchOptions?.headers,
1828
- },
1829
- signal:
1830
- params.fetchOptions?.signal ||
1831
- params.signal ||
1832
- this.fetchOptions?.signal,
1833
- }
1834
-
1835
- let job: Promise<FetchJobResult>
1836
-
1837
- // `fetchJobs` is keyed twice: first by the URL and again by is
1838
- // signal, if one exists.
1839
- //
1840
- // Using two keys allows us to reuse fetch requests for
1841
- // equivalent URLs, but eject when we detect unique signals.
1842
- if (this.fetchJobs[url] && this.fetchJobs[url].has(requestInit.signal)) {
1843
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1844
- job = this.fetchJobs[url].get(requestInit.signal)!
1845
- } else {
1846
- this.fetchJobs[url] = this.fetchJobs[url] || new Map()
1847
-
1848
- job = this.fetchFn(url, requestInit)
1849
- .then(async (res) => {
1850
- // We can assume Prismic REST API responses
1851
- // will have a `application/json`
1852
- // Content Type. If not, this will
1853
- // throw, signaling an invalid
1854
- // response.
1855
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1856
- let json: any = undefined
1857
- try {
1858
- json = await res.json()
1859
- } catch {
1860
- // noop
1861
- }
1862
-
1863
- return {
1864
- status: res.status,
1865
- headers: res.headers,
1866
- json,
1867
- }
1868
- })
1869
- .finally(() => {
1870
- this.fetchJobs[url].delete(requestInit.signal)
1871
-
1872
- if (this.fetchJobs[url].size === 0) {
1873
- delete this.fetchJobs[url]
1874
- }
1875
- })
1876
-
1877
- this.fetchJobs[url].set(requestInit.signal, job)
1878
- }
1879
-
1880
- const res = await job
1881
-
1882
- if (res.status !== 404 && res.json == null) {
1883
- throw new PrismicError(undefined, url, res.json)
1884
- }
1885
-
1886
- switch (res.status) {
1887
- // Successful
1888
- case 200: {
1889
- return res.json
1890
- }
1891
-
1892
- // Bad Request
1893
- // - Invalid filter syntax
1894
- // - Ref not provided (ignored)
1895
- case 400: {
1896
- throw new ParsingError(res.json.message, url, res.json)
1897
- }
1898
-
1899
- // Unauthorized
1900
- // - Missing access token for repository endpoint
1901
- // - Incorrect access token for repository endpoint
1902
- case 401:
1903
- // Forbidden
1904
- // - Missing access token for query endpoint
1905
- // - Incorrect access token for query endpoint
1906
- case 403: {
1907
- throw new ForbiddenError(
1908
- res.json.error || res.json.message,
1909
- url,
1910
- res.json,
1911
- )
1912
- }
1913
-
1914
- // Not Found
1915
- // - Incorrect repository name (this response has an empty body)
1916
- // - Ref does not exist
1917
- // - Preview token is expired
1918
- case 404: {
1919
- if (res.json === undefined) {
1920
- throw new RepositoryNotFoundError(
1921
- `Prismic repository not found. Check that "${this.endpoint}" is pointing to the correct repository.`,
1922
- url,
1923
- undefined,
1924
- )
1925
- }
1926
-
1927
- if (res.json.type === "api_notfound_error") {
1928
- throw new RefNotFoundError(res.json.message, url, res.json)
1929
- }
1930
-
1931
- if (
1932
- res.json.type === "api_security_error" &&
1933
- /preview token.*expired/i.test(res.json.message)
1934
- ) {
1935
- throw new PreviewTokenExpiredError(res.json.message, url, res.json)
1936
- }
1937
-
1938
- throw new NotFoundError(res.json.message, url, res.json)
1939
- }
1940
-
1941
- // Gone
1942
- // - Ref is expired
1943
- case 410: {
1944
- throw new RefExpiredError(res.json.message, url, res.json)
1945
- }
1946
-
1947
- // Too Many Requests
1948
- // - Exceeded the maximum number of requests per second
1949
- case 429: {
1950
- const parsedRetryAfter = Number(res.headers.get("retry-after"))
1951
- const delay = Number.isNaN(parsedRetryAfter)
1952
- ? DEFUALT_RETRY_AFTER_MS
1953
- : parsedRetryAfter
1954
-
1955
- return await new Promise((resolve, reject) => {
1956
- setTimeout(async () => {
1957
- try {
1958
- resolve(await this.fetch(url, params))
1959
- } catch (error) {
1960
- reject(error)
1961
- }
1962
- }, delay)
1963
- })
1964
- }
1965
- }
1966
-
1967
- throw new PrismicError(undefined, url, res.json)
1968
- }
1969
- }