@prismicio/client 7.19.1 → 7.19.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/dist/Client.cjs +109 -93
  2. package/dist/Client.cjs.map +1 -1
  3. package/dist/Client.d.ts +66 -27
  4. package/dist/Client.js +109 -93
  5. package/dist/Client.js.map +1 -1
  6. package/dist/WriteClient.cjs +151 -100
  7. package/dist/WriteClient.cjs.map +1 -1
  8. package/dist/WriteClient.d.ts +2 -26
  9. package/dist/WriteClient.js +151 -100
  10. package/dist/WriteClient.js.map +1 -1
  11. package/dist/errors/InvalidDataError.cjs +7 -0
  12. package/dist/errors/InvalidDataError.cjs.map +1 -0
  13. package/dist/errors/InvalidDataError.d.ts +3 -0
  14. package/dist/errors/InvalidDataError.js +7 -0
  15. package/dist/errors/InvalidDataError.js.map +1 -0
  16. package/dist/errors/ParsingError.cjs.map +1 -1
  17. package/dist/errors/ParsingError.d.ts +6 -4
  18. package/dist/errors/ParsingError.js.map +1 -1
  19. package/dist/index.cjs.map +1 -1
  20. package/dist/index.d.ts +2 -2
  21. package/dist/index.js.map +1 -1
  22. package/dist/lib/request.cjs +43 -0
  23. package/dist/lib/request.cjs.map +1 -0
  24. package/dist/lib/request.d.ts +73 -0
  25. package/dist/lib/request.js +43 -0
  26. package/dist/lib/request.js.map +1 -0
  27. package/dist/package.json.cjs +1 -1
  28. package/dist/package.json.js +1 -1
  29. package/package.json +1 -1
  30. package/src/Client.ts +197 -167
  31. package/src/WriteClient.ts +214 -157
  32. package/src/errors/InvalidDataError.ts +5 -0
  33. package/src/errors/ParsingError.ts +6 -4
  34. package/src/index.ts +7 -8
  35. package/src/lib/request.ts +166 -0
  36. package/dist/BaseClient.cjs +0 -108
  37. package/dist/BaseClient.cjs.map +0 -1
  38. package/dist/BaseClient.d.ts +0 -152
  39. package/dist/BaseClient.js +0 -108
  40. package/dist/BaseClient.js.map +0 -1
  41. package/src/BaseClient.ts +0 -330
package/src/Client.ts CHANGED
@@ -7,13 +7,20 @@ import { findRefByID } from "./lib/findRefByID"
7
7
  import { findRefByLabel } from "./lib/findRefByLabel"
8
8
  import { getPreviewCookie } from "./lib/getPreviewCookie"
9
9
  import { minifyGraphQLQuery } from "./lib/minifyGraphQLQuery"
10
+ import type { ResponseLike } from "./lib/request"
11
+ import {
12
+ type AbortSignalLike,
13
+ type FetchLike,
14
+ type RequestInitLike,
15
+ request,
16
+ } from "./lib/request"
10
17
  import { someTagsFilter } from "./lib/someTagsFilter"
11
18
  import { throttledLog } from "./lib/throttledLog"
12
19
  import { typeFilter } from "./lib/typeFilter"
13
20
 
14
21
  import type { Query } from "./types/api/query"
15
22
  import type { Ref } from "./types/api/ref"
16
- import type { Form, Repository } from "./types/api/repository"
23
+ import type { Repository } from "./types/api/repository"
17
24
  import type { PrismicDocument } from "./types/value/document"
18
25
 
19
26
  import { ForbiddenError } from "./errors/ForbiddenError"
@@ -28,13 +35,6 @@ import { RepositoryNotFoundError } from "./errors/RepositoryNotFoundError"
28
35
  import type { LinkResolverFunction } from "./helpers/asLink"
29
36
  import { asLink } from "./helpers/asLink"
30
37
 
31
- import {
32
- type AbortSignalLike,
33
- BaseClient,
34
- type BaseClientConfig,
35
- type FetchParams,
36
- type HttpRequestLike,
37
- } from "./BaseClient"
38
38
  import type { BuildQueryURLArgs } from "./buildQueryURL"
39
39
  import { buildQueryURL } from "./buildQueryURL"
40
40
  import { filter } from "./filter"
@@ -65,15 +65,6 @@ export const REPOSITORY_CACHE_TTL = 5000
65
65
  */
66
66
  export const GET_ALL_QUERY_DELAY = 500
67
67
 
68
- /**
69
- * The default number of milliseconds to wait before retrying a rate-limited
70
- * `fetch()` request (429 response code). The default value is only used if the
71
- * response does not include a `retry-after` header.
72
- *
73
- * The API allows up to 200 requests per second.
74
- */
75
- const DEFAULT_RETRY_AFTER_MS = 1000
76
-
77
68
  /**
78
69
  * The maximum number of attempts to retry a query with an invalid ref. We allow
79
70
  * multiple attempts since each attempt may use a different (and possibly
@@ -122,6 +113,33 @@ enum RefStateMode {
122
113
  Manual = "Manual",
123
114
  }
124
115
 
116
+ /**
117
+ * The minimum required properties to treat as an HTTP Request for automatic
118
+ * Prismic preview support.
119
+ */
120
+ export type HttpRequestLike =
121
+ | /**
122
+ * Web API Request
123
+ *
124
+ * @see http://developer.mozilla.org/en-US/docs/Web/API/Request
125
+ */
126
+ {
127
+ headers?: {
128
+ get(name: string): string | null
129
+ }
130
+ url?: string
131
+ }
132
+
133
+ /**
134
+ * Express-style Request
135
+ */
136
+ | {
137
+ headers?: {
138
+ cookie?: string
139
+ }
140
+ query?: Record<string, unknown>
141
+ }
142
+
125
143
  /**
126
144
  * An object containing stateful information about a client's ref strategy.
127
145
  */
@@ -163,6 +181,28 @@ type RefStringOrThunk =
163
181
  | string
164
182
  | (() => string | undefined | Promise<string | undefined>)
165
183
 
184
+ /**
185
+ * Parameters for any client method that use `fetch()`.
186
+ */
187
+ export type FetchParams = {
188
+ /**
189
+ * Options provided to the client's `fetch()` on all network requests. These
190
+ * options will be merged with internally required options. They can also be
191
+ * overriden on a per-query basis using the query's `fetchOptions` parameter.
192
+ */
193
+ fetchOptions?: RequestInitLike
194
+
195
+ /**
196
+ * An `AbortSignal` provided by an `AbortController`. This allows the network
197
+ * request to be cancelled if necessary.
198
+ *
199
+ * @deprecated Move the `signal` parameter into `fetchOptions.signal`:
200
+ *
201
+ * @see \<https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal\>
202
+ */
203
+ signal?: AbortSignalLike
204
+ }
205
+
166
206
  /**
167
207
  * Configuration for clients that determine how content is queried.
168
208
  */
@@ -214,7 +254,21 @@ export type ClientConfig = {
214
254
  BuildQueryURLArgs,
215
255
  "ref" | "integrationFieldsRef" | "accessToken" | "routes" | "brokenRoute"
216
256
  >
217
- } & BaseClientConfig
257
+
258
+ /**
259
+ * The function used to make network requests to the Prismic REST API. In
260
+ * environments where a global `fetch` function does not exist, such as
261
+ * Node.js, this function must be provided.
262
+ */
263
+ fetch?: FetchLike
264
+
265
+ /**
266
+ * Options provided to the client's `fetch()` on all network requests. These
267
+ * options will be merged with internally required options. They can also be
268
+ * overriden on a per-query basis using the query's `fetchOptions` parameter.
269
+ */
270
+ fetchOptions?: RequestInitLike
271
+ }
218
272
 
219
273
  /**
220
274
  * Parameters specific to client methods that fetch all documents. These methods
@@ -264,9 +318,16 @@ type ResolvePreviewArgs<LinkResolverReturnType> = {
264
318
  * @typeParam TDocuments - Document types that are registered for the Prismic
265
319
  * repository. Query methods will automatically be typed based on this type.
266
320
  */
267
- export class Client<
268
- TDocuments extends PrismicDocument = PrismicDocument,
269
- > extends BaseClient {
321
+ export class Client<TDocuments extends PrismicDocument = PrismicDocument> {
322
+ /**
323
+ * The function used to make network requests to the Prismic REST API. In
324
+ * environments where a global `fetch` function does not exist, such as
325
+ * Node.js, this function must be provided.
326
+ */
327
+ fetchFn: FetchLike
328
+
329
+ fetchOptions?: RequestInitLike
330
+
270
331
  #repositoryName: string | undefined
271
332
 
272
333
  /**
@@ -388,7 +449,24 @@ export class Client<
388
449
  * @returns A client that can query content from the repository.
389
450
  */
390
451
  constructor(repositoryNameOrEndpoint: string, options: ClientConfig = {}) {
391
- super(options)
452
+ this.fetchOptions = options.fetchOptions
453
+
454
+ if (typeof options.fetch === "function") {
455
+ this.fetchFn = options.fetch
456
+ } else if (typeof globalThis.fetch === "function") {
457
+ this.fetchFn = globalThis.fetch as FetchLike
458
+ } else {
459
+ throw new PrismicError(
460
+ "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.",
461
+ undefined,
462
+ undefined,
463
+ )
464
+ }
465
+
466
+ // If the global fetch function is used, we must bind it to the global scope.
467
+ if (this.fetchFn === globalThis.fetch) {
468
+ this.fetchFn = this.fetchFn.bind(globalThis)
469
+ }
392
470
 
393
471
  if (
394
472
  (options.documentAPIEndpoint ||
@@ -1155,16 +1233,32 @@ export class Client<
1155
1233
  * @returns Repository metadata.
1156
1234
  */
1157
1235
  async getRepository(params?: FetchParams): Promise<Repository> {
1158
- // TODO: Restore when Authorization header support works in browsers with CORS.
1159
- // return await this.fetch<Repository>(this.endpoint);
1160
-
1161
1236
  const url = new URL(this.documentAPIEndpoint)
1162
1237
 
1163
1238
  if (this.accessToken) {
1164
1239
  url.searchParams.set("access_token", this.accessToken)
1165
1240
  }
1166
1241
 
1167
- return await this.fetch<Repository>(url.toString(), params)
1242
+ const response = await this.#request(url, params)
1243
+ switch (response.status) {
1244
+ case 200: {
1245
+ return (await response.json()) as Repository
1246
+ }
1247
+ case 401: {
1248
+ const json = await response.json()
1249
+ throw new ForbiddenError(json.error, url.toString(), json)
1250
+ }
1251
+ case 404: {
1252
+ throw new RepositoryNotFoundError(
1253
+ `Prismic repository not found. Check that "${this.documentAPIEndpoint}" is pointing to the correct repository.`,
1254
+ url.toString(),
1255
+ undefined,
1256
+ )
1257
+ }
1258
+ default: {
1259
+ throw new PrismicError(undefined, url.toString(), await response.text())
1260
+ }
1261
+ }
1168
1262
  }
1169
1263
 
1170
1264
  /**
@@ -1264,21 +1358,23 @@ export class Client<
1264
1358
  * @returns A list of all tags used in the repository.
1265
1359
  */
1266
1360
  async getTags(params?: FetchParams): Promise<string[]> {
1267
- try {
1268
- const tagsForm = await this.getCachedRepositoryForm("tags", params)
1269
-
1270
- const url = new URL(tagsForm.action)
1271
-
1361
+ const cachedRepository = await this.getCachedRepository(params)
1362
+ const form = cachedRepository.forms.tags
1363
+ if (form) {
1364
+ const url = new URL(form.action)
1272
1365
  if (this.accessToken) {
1273
1366
  url.searchParams.set("access_token", this.accessToken)
1274
1367
  }
1275
1368
 
1276
- return await this.fetch<string[]>(url.toString(), params)
1277
- } catch {
1278
- const repository = await this.getRepository(params)
1279
-
1280
- return repository.tags
1369
+ const response = await this.#request(url, params)
1370
+ if (response.ok) {
1371
+ return (await response.json()) as string[]
1372
+ }
1281
1373
  }
1374
+
1375
+ const repository = await this.getRepository(params)
1376
+
1377
+ return repository.tags
1282
1378
  }
1283
1379
 
1284
1380
  /**
@@ -1583,41 +1679,13 @@ export class Client<
1583
1679
  !this.cachedRepository ||
1584
1680
  Date.now() >= this.cachedRepositoryExpiration
1585
1681
  ) {
1586
- this.cachedRepositoryExpiration = Date.now() + REPOSITORY_CACHE_TTL
1587
1682
  this.cachedRepository = await this.getRepository(params)
1683
+ this.cachedRepositoryExpiration = Date.now() + REPOSITORY_CACHE_TTL
1588
1684
  }
1589
1685
 
1590
1686
  return this.cachedRepository
1591
1687
  }
1592
1688
 
1593
- /**
1594
- * Returns a cached Prismic repository form. Forms are used to determine API
1595
- * endpoints for types of repository data.
1596
- *
1597
- * @param name - Name of the form.
1598
- *
1599
- * @returns The repository form.
1600
- *
1601
- * @throws If a matching form cannot be found.
1602
- */
1603
- private async getCachedRepositoryForm(
1604
- name: string,
1605
- params?: FetchParams,
1606
- ): Promise<Form> {
1607
- const cachedRepository = await this.getCachedRepository(params)
1608
- const form = cachedRepository.forms[name]
1609
-
1610
- if (!form) {
1611
- throw new PrismicError(
1612
- `Form with name "${name}" could not be found`,
1613
- undefined,
1614
- undefined,
1615
- )
1616
- }
1617
-
1618
- return form
1619
- }
1620
-
1621
1689
  /**
1622
1690
  * Returns the ref needed to query based on the client's current state. This
1623
1691
  * method may make a network request to fetch a ref or resolve the user's ref
@@ -1713,9 +1781,50 @@ export class Client<
1713
1781
  const url = await this.buildQueryURL(params)
1714
1782
 
1715
1783
  try {
1716
- const data = await this.fetch<Query<TDocument>>(url, params)
1717
-
1718
- return { data, url }
1784
+ const response = await this.#request(new URL(url), params)
1785
+ switch (response.status) {
1786
+ case 200: {
1787
+ try {
1788
+ return {
1789
+ data: (await response.clone().json()) as Query<TDocument>,
1790
+ url,
1791
+ }
1792
+ } catch {
1793
+ throw new PrismicError(undefined, url, await response.text())
1794
+ }
1795
+ }
1796
+ case 400: {
1797
+ const json = await response.json()
1798
+ throw new ParsingError(json.message, url, json)
1799
+ }
1800
+ case 401: {
1801
+ const json = await response.json()
1802
+ throw new ForbiddenError(json.message, url, json)
1803
+ }
1804
+ case 404: {
1805
+ const json = await response.json()
1806
+ switch (json.type) {
1807
+ case "api_notfound_error": {
1808
+ throw new RefNotFoundError(json.message, url, json)
1809
+ }
1810
+ case "api_security_error": {
1811
+ if (/preview token.*expired/i.test(json.message)) {
1812
+ throw new PreviewTokenExpiredError(json.message, url, json)
1813
+ }
1814
+ }
1815
+ default: {
1816
+ throw new NotFoundError(json.message, url, json)
1817
+ }
1818
+ }
1819
+ }
1820
+ case 410: {
1821
+ const json = await response.json()
1822
+ throw new RefExpiredError(json.message, url, json)
1823
+ }
1824
+ default: {
1825
+ throw new PrismicError(undefined, url, await response.text())
1826
+ }
1827
+ }
1719
1828
  } catch (error) {
1720
1829
  if (
1721
1830
  !(
@@ -1752,109 +1861,30 @@ export class Client<
1752
1861
  }
1753
1862
 
1754
1863
  /**
1755
- * Performs a network request using the configured `fetch` function. It
1756
- * assumes all successful responses will have a JSON content type. It also
1757
- * normalizes unsuccessful network requests.
1864
+ * Makes an HTTP request using the client's configured fetch function and
1865
+ * options.
1758
1866
  *
1759
- * @typeParam T - The JSON response.
1867
+ * @param url - The URL to request.
1868
+ * @param params - Fetch options.
1760
1869
  *
1761
- * @param url - URL to the resource to fetch.
1762
- * @param params - Prismic REST API parameters for the network request.
1763
- *
1764
- * @returns The JSON response from the network request.
1870
+ * @returns The response from the fetch request.
1765
1871
  */
1766
- protected async fetch<T = unknown>(
1767
- url: string,
1768
- params: FetchParams = {},
1769
- ): Promise<T> {
1770
- const res = await super.fetch(url, params)
1771
-
1772
- if (res.status !== 404 && res.status !== 429 && res.json == null) {
1773
- throw new PrismicError(undefined, url, res.json || res.text)
1774
- }
1775
-
1776
- switch (res.status) {
1777
- // Successful
1778
- case 200:
1779
- case 201: {
1780
- return res.json
1781
- }
1782
-
1783
- // Bad Request
1784
- // - Invalid filter syntax
1785
- // - Ref not provided (ignored)
1786
- case 400: {
1787
- throw new ParsingError(res.json.message, url, res.json)
1788
- }
1789
-
1790
- // Unauthorized
1791
- // - Missing access token for repository endpoint
1792
- // - Incorrect access token for repository endpoint
1793
- case 401:
1794
- // Forbidden
1795
- // - Missing access token for query endpoint
1796
- // - Incorrect access token for query endpoint
1797
- case 403: {
1798
- throw new ForbiddenError(
1799
- res.json.error || res.json.message,
1800
- url,
1801
- res.json,
1802
- )
1803
- }
1804
-
1805
- // Not Found
1806
- // - Incorrect repository name (this response has an empty body)
1807
- // - Ref does not exist
1808
- // - Preview token is expired
1809
- case 404: {
1810
- if (res.json === undefined) {
1811
- throw new RepositoryNotFoundError(
1812
- `Prismic repository not found. Check that "${this.documentAPIEndpoint}" is pointing to the correct repository.`,
1813
- url,
1814
- url.startsWith(this.documentAPIEndpoint) ? undefined : res.text,
1815
- )
1816
- }
1817
-
1818
- if (res.json.type === "api_notfound_error") {
1819
- throw new RefNotFoundError(res.json.message, url, res.json)
1820
- }
1821
-
1822
- if (
1823
- res.json.type === "api_security_error" &&
1824
- /preview token.*expired/i.test(res.json.message)
1825
- ) {
1826
- throw new PreviewTokenExpiredError(res.json.message, url, res.json)
1827
- }
1828
-
1829
- throw new NotFoundError(res.json.message, url, res.json)
1830
- }
1831
-
1832
- // Gone
1833
- // - Ref is expired
1834
- case 410: {
1835
- throw new RefExpiredError(res.json.message, url, res.json)
1836
- }
1872
+ async #request(url: URL, params?: RequestInitLike): Promise<ResponseLike> {
1873
+ return await request(url, this._buildRequestInit(params), this.fetchFn)
1874
+ }
1837
1875
 
1838
- // Too Many Requests
1839
- // - Exceeded the maximum number of requests per second
1840
- case 429: {
1841
- const parsedRetryAfter = Number(res.headers.get("retry-after"))
1842
- const delay = Number.isNaN(parsedRetryAfter)
1843
- ? DEFAULT_RETRY_AFTER_MS
1844
- : parsedRetryAfter * 1000
1845
-
1846
- return await new Promise((resolve, reject) => {
1847
- setTimeout(async () => {
1848
- try {
1849
- resolve(await this.fetch(url, params))
1850
- } catch (error) {
1851
- reject(error)
1852
- }
1853
- }, delay)
1854
- })
1855
- }
1876
+ protected _buildRequestInit(params?: FetchParams): RequestInitLike {
1877
+ return {
1878
+ ...this.fetchOptions,
1879
+ ...params?.fetchOptions,
1880
+ headers: {
1881
+ ...this.fetchOptions?.headers,
1882
+ ...params?.fetchOptions?.headers,
1883
+ },
1884
+ signal:
1885
+ params?.fetchOptions?.signal ||
1886
+ params?.signal ||
1887
+ this.fetchOptions?.signal,
1856
1888
  }
1857
-
1858
- throw new PrismicError(undefined, url, res.json)
1859
1889
  }
1860
1890
  }