@prismicio/client 7.19.1-alpha.0 → 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
@@ -1,5 +1,7 @@
1
1
  import { devMsg } from "./lib/devMsg"
2
2
  import { pLimit } from "./lib/pLimit"
3
+ import type { ResponseLike } from "./lib/request"
4
+ import { type RequestInitLike, request } from "./lib/request"
3
5
  import {
4
6
  resolveMigrationContentRelationship,
5
7
  resolveMigrationDocumentData,
@@ -8,22 +10,15 @@ import {
8
10
  import type {
9
11
  Asset,
10
12
  PatchAssetParams,
11
- PatchAssetResult,
12
13
  PostAssetParams,
13
14
  PostAssetResult,
14
15
  } from "./types/api/asset/asset"
15
16
  import type {
16
17
  AssetTag,
17
18
  GetAssetTagsResult,
18
- PostAssetTagParams,
19
19
  PostAssetTagResult,
20
20
  } from "./types/api/asset/tag"
21
- import type { PutDocumentResult } from "./types/api/migration/document"
22
- import {
23
- type PostDocumentParams,
24
- type PostDocumentResult,
25
- type PutDocumentParams,
26
- } from "./types/api/migration/document"
21
+ import { type PostDocumentResult } from "./types/api/migration/document"
27
22
  import type { PrismicMigrationAsset } from "./types/migration/Asset"
28
23
  import type {
29
24
  MigrationDocument,
@@ -32,11 +27,13 @@ import type {
32
27
  } from "./types/migration/Document"
33
28
  import type { PrismicDocument } from "./types/value/document"
34
29
 
30
+ import { ForbiddenError } from "./errors/ForbiddenError"
31
+ import { InvalidDataError } from "./errors/InvalidDataError"
32
+ import { NotFoundError } from "./errors/NotFoundError"
35
33
  import { PrismicError } from "./errors/PrismicError"
36
34
 
37
- import type { FetchParams, RequestInitLike } from "./BaseClient"
38
35
  import { Client } from "./Client"
39
- import type { ClientConfig } from "./Client"
36
+ import type { ClientConfig, FetchParams } from "./Client"
40
37
  import type { Migration } from "./Migration"
41
38
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
42
39
  import type { createMigration } from "./createMigration"
@@ -537,20 +534,24 @@ export class WriteClient<
537
534
  formData.append("alt", alt)
538
535
  }
539
536
 
540
- const asset = await this.fetch<PostAssetResult>(
541
- url.toString(),
542
- this.buildAssetAPIQueryParams({
543
- method: "POST",
544
- body: formData,
545
- params,
546
- }),
547
- )
537
+ const response = await this.#request(url, params, {
538
+ method: "POST",
539
+ body: formData,
540
+ })
541
+ switch (response.status) {
542
+ case 200: {
543
+ const asset = (await response.json()) as PostAssetResult
548
544
 
549
- if (tags && tags.length) {
550
- return this.updateAsset(asset.id, { tags })
551
- }
545
+ if (tags && tags.length) {
546
+ return this.updateAsset(asset.id, { tags })
547
+ }
552
548
 
553
- return asset
549
+ return asset
550
+ }
551
+ default: {
552
+ return await this.#handleAssetAPIError(response)
553
+ }
554
+ }
554
555
  }
555
556
 
556
557
  /**
@@ -582,20 +583,27 @@ export class WriteClient<
582
583
  })
583
584
  }
584
585
 
585
- return this.fetch<PatchAssetResult>(
586
- url.toString(),
587
- this.buildAssetAPIQueryParams<PatchAssetParams>({
588
- method: "PATCH",
589
- body: {
590
- notes,
591
- credits,
592
- alt,
593
- filename,
594
- tags,
595
- },
596
- params,
586
+ const response = await this.#request(url, params, {
587
+ method: "PATCH",
588
+ body: JSON.stringify({
589
+ notes,
590
+ credits,
591
+ alt,
592
+ filename,
593
+ tags,
597
594
  }),
598
- )
595
+ headers: {
596
+ "content-type": "application/json",
597
+ },
598
+ })
599
+ switch (response.status) {
600
+ case 200: {
601
+ return (await response.json()) as Asset
602
+ }
603
+ default: {
604
+ return await this.#handleAssetAPIError(response)
605
+ }
606
+ }
599
607
  }
600
608
 
601
609
  /**
@@ -610,20 +618,7 @@ export class WriteClient<
610
618
  url: string,
611
619
  params: FetchParams = {},
612
620
  ): Promise<Blob> {
613
- const requestInit: RequestInitLike = {
614
- ...this.fetchOptions,
615
- ...params.fetchOptions,
616
- headers: {
617
- ...this.fetchOptions?.headers,
618
- ...params.fetchOptions?.headers,
619
- },
620
- signal:
621
- params.fetchOptions?.signal ||
622
- params.signal ||
623
- this.fetchOptions?.signal,
624
- }
625
-
626
- const res = await this.fetchFn(url, requestInit)
621
+ const res = await this.fetchFn(url, this._buildRequestInit(params))
627
622
 
628
623
  if (!res.ok) {
629
624
  throw new PrismicError("Could not fetch foreign asset", url, undefined)
@@ -696,14 +691,21 @@ export class WriteClient<
696
691
  ): Promise<AssetTag> {
697
692
  const url = new URL("tags", this.assetAPIEndpoint)
698
693
 
699
- return this.fetch<PostAssetTagResult>(
700
- url.toString(),
701
- this.buildAssetAPIQueryParams<PostAssetTagParams>({
702
- method: "POST",
703
- body: { name },
704
- params,
705
- }),
706
- )
694
+ const response = await this.#request(url, params, {
695
+ method: "POST",
696
+ body: JSON.stringify({ name }),
697
+ headers: {
698
+ "content-type": "application/json",
699
+ },
700
+ })
701
+ switch (response.status) {
702
+ case 201: {
703
+ return (await response.json()) as PostAssetTagResult
704
+ }
705
+ default: {
706
+ return await this.#handleAssetAPIError(response)
707
+ }
708
+ }
707
709
  }
708
710
 
709
711
  /**
@@ -716,12 +718,17 @@ export class WriteClient<
716
718
  private async getAssetTags(params?: FetchParams): Promise<AssetTag[]> {
717
719
  const url = new URL("tags", this.assetAPIEndpoint)
718
720
 
719
- const { items } = await this.fetch<GetAssetTagsResult>(
720
- url.toString(),
721
- this.buildAssetAPIQueryParams({ params }),
722
- )
721
+ const response = await this.#request(url, params)
722
+ switch (response.status) {
723
+ case 200: {
724
+ const json = (await response.json()) as GetAssetTagsResult
723
725
 
724
- return items
726
+ return json.items
727
+ }
728
+ default: {
729
+ return await this.#handleAssetAPIError(response)
730
+ }
731
+ }
725
732
  }
726
733
 
727
734
  /**
@@ -749,24 +756,31 @@ export class WriteClient<
749
756
  ): Promise<{ id: string }> {
750
757
  const url = new URL("documents", this.migrationAPIEndpoint)
751
758
 
752
- const result = await this.fetch<PostDocumentResult>(
753
- url.toString(),
754
- this.buildMigrationAPIQueryParams<PostDocumentParams>({
755
- method: "POST",
756
- body: {
757
- title: documentTitle,
758
- type: document.type,
759
- uid: document.uid || undefined,
760
- lang: document.lang,
761
- alternate_language_id: masterLanguageDocumentID,
762
- tags: document.tags,
763
- data: document.data,
764
- },
765
- params,
759
+ const response = await this.#request(url, params, {
760
+ method: "POST",
761
+ body: JSON.stringify({
762
+ title: documentTitle,
763
+ type: document.type,
764
+ uid: document.uid || undefined,
765
+ lang: document.lang,
766
+ alternate_language_id: masterLanguageDocumentID,
767
+ tags: document.tags,
768
+ data: document.data,
766
769
  }),
767
- )
770
+ headers: {
771
+ "content-type": "application/json",
772
+ },
773
+ })
774
+ switch (response.status) {
775
+ case 201: {
776
+ const json = (await response.json()) as PostDocumentResult
768
777
 
769
- return { id: result.id }
778
+ return { id: json.id }
779
+ }
780
+ default: {
781
+ return await this.#handleMigrationAPIError(response)
782
+ }
783
+ }
770
784
  }
771
785
 
772
786
  /**
@@ -789,101 +803,144 @@ export class WriteClient<
789
803
  ): Promise<void> {
790
804
  const url = new URL(`documents/${id}`, this.migrationAPIEndpoint)
791
805
 
792
- await this.fetch<PutDocumentResult>(
793
- url.toString(),
794
- this.buildMigrationAPIQueryParams({
795
- method: "PUT",
796
- body: {
797
- title: document.documentTitle,
798
- uid: document.uid || undefined,
799
- tags: document.tags,
800
- data: document.data,
801
- },
802
- params,
806
+ const response = await this.#request(url, params, {
807
+ method: "PUT",
808
+ body: JSON.stringify({
809
+ title: document.documentTitle,
810
+ uid: document.uid || undefined,
811
+ tags: document.tags,
812
+ data: document.data,
803
813
  }),
804
- )
814
+ headers: {
815
+ "content-type": "application/json",
816
+ },
817
+ })
818
+ switch (response.status) {
819
+ case 200: {
820
+ return
821
+ }
822
+ default: {
823
+ await this.#handleMigrationAPIError(response)
824
+ }
825
+ }
805
826
  }
806
827
 
807
828
  /**
808
- * Builds fetch parameters for the Asset API.
809
- *
810
- * @typeParam TBody - Type of the body to send in the fetch request.
829
+ * Makes an authenticated HTTP request for write operations using the client's
830
+ * configured fetch function and options.
811
831
  *
812
- * @param params - Method, body, and additional fetch parameters.
832
+ * @param url - The URL to request.
833
+ * @param params - Fetch options from the user.
834
+ * @param init - Additional fetch options to merge with the user-provided
835
+ * options.
813
836
  *
814
- * @returns An object that can be fetched to interact with the Asset API.
815
- *
816
- * @see Prismic Asset API technical reference: {@link https://prismic.io/docs/asset-api-technical-reference}
837
+ * @returns The response from the fetch request.
817
838
  */
818
- private buildAssetAPIQueryParams<TBody = FormData | Record<string, unknown>>({
819
- method,
820
- body,
821
- params,
822
- }: {
823
- method?: string
824
- body?: TBody
825
- params?: FetchParams
826
- }): FetchParams {
827
- const headers: Record<string, string> = {
828
- ...params?.fetchOptions?.headers,
829
- authorization: `Bearer ${this.writeToken}`,
830
- repository: this.repositoryName,
831
- }
832
-
833
- let _body: FormData | string | undefined
834
- if (body instanceof FormData) {
835
- _body = body
836
- } else if (body) {
837
- _body = JSON.stringify(body)
838
- headers["content-type"] = "application/json"
839
- }
840
-
841
- return {
842
- ...params,
843
- fetchOptions: {
844
- ...params?.fetchOptions,
845
- method,
846
- body: _body,
847
- headers,
839
+ async #request(
840
+ url: URL,
841
+ params?: RequestInitLike,
842
+ init?: RequestInitLike,
843
+ ): Promise<ResponseLike> {
844
+ const baseInit = this._buildRequestInit(params)
845
+
846
+ return await request(
847
+ url,
848
+ {
849
+ ...baseInit,
850
+ ...init,
851
+ headers: {
852
+ ...baseInit.headers,
853
+ ...init?.headers,
854
+ repository: this.repositoryName,
855
+ authorization: `Bearer ${this.writeToken}`,
856
+ },
848
857
  },
849
- }
858
+ this.fetchFn,
859
+ )
850
860
  }
851
861
 
852
862
  /**
853
- * Builds fetch parameters for the Migration API.
863
+ * Handles error responses from the Asset API with comprehensive error
864
+ * parsing.
854
865
  *
855
- * @typeParam TBody - Type of the body to send in the fetch request.
866
+ * @param response - The HTTP response from the Asset API.
856
867
  *
857
- * @param params - Method, body, and additional fetch options.
868
+ * @throws {@link InvalidDataError} For 400 errors.
869
+ * @throws {@link ForbiddenError} For 401 and 403 errors.
870
+ * @throws {@link NotFoundError} For 404 errors.
871
+ * @throws {@link PrismicError} For 500, 503, and other unexpected errors.
872
+ */
873
+ async #handleAssetAPIError(response: ResponseLike): Promise<never> {
874
+ const json = await response.json()
875
+ switch (response.status) {
876
+ case 401:
877
+ case 403:
878
+ throw new ForbiddenError(json.error, response.url, json)
879
+
880
+ case 404:
881
+ throw new NotFoundError(json.error, response.url, json)
882
+
883
+ case 400:
884
+ throw new InvalidDataError(json.error, response.url, json)
885
+
886
+ case 500:
887
+ case 503:
888
+ default:
889
+ throw new PrismicError(json.error, response.url, json)
890
+ }
891
+ }
892
+
893
+ /**
894
+ * Handles error responses from the Migration API with comprehensive error
895
+ * parsing.
858
896
  *
859
- * @returns An object that can be fetched to interact with the Migration API.
897
+ * @param response - The HTTP response from the Migration API.
860
898
  *
861
- * @see Prismic Migration API technical reference: {@link https://prismic.io/docs/migration-api-technical-reference}
899
+ * @throws {@link InvalidDataError} For 400 errors.
900
+ * @throws {@link ForbiddenError} For 401 and 403 errors.
901
+ * @throws {@link NotFoundError} For 404 errors.
902
+ * @throws {@link PrismicError} For 500, and other unexpected errors.
862
903
  */
863
- private buildMigrationAPIQueryParams<
864
- TBody extends PostDocumentParams | PutDocumentParams,
865
- >({
866
- method,
867
- body,
868
- params,
869
- }: {
870
- method?: string
871
- body: TBody
872
- params?: FetchParams
873
- }): FetchParams {
874
- return {
875
- ...params,
876
- fetchOptions: {
877
- ...params?.fetchOptions,
878
- method,
879
- body: JSON.stringify(body),
880
- headers: {
881
- ...params?.fetchOptions?.headers,
882
- "content-type": "application/json",
883
- repository: this.repositoryName,
884
- authorization: `Bearer ${this.writeToken}`,
885
- },
886
- },
904
+ async #handleMigrationAPIError(response: ResponseLike): Promise<never> {
905
+ // Some responses come with a JSON body, some with a text body.
906
+ const text = await response.text()
907
+ let json: unknown
908
+ try {
909
+ json = JSON.parse(text)
910
+ } catch {
911
+ // no-op
912
+ }
913
+
914
+ switch (response.status) {
915
+ case 400:
916
+ if (json) {
917
+ throw new InvalidDataError(
918
+ "Validation failed, check the response property of the error for details",
919
+ response.url,
920
+ json, // `json` has the shape Array<{ property: string, value: unknown, error: string }>
921
+ )
922
+ }
923
+ throw new InvalidDataError(text, response.url, text)
924
+
925
+ case 401:
926
+ throw new ForbiddenError(text, response.url, text)
927
+
928
+ case 403:
929
+ if (json) {
930
+ throw new ForbiddenError(
931
+ (json as { Message: string }).Message,
932
+ response.url,
933
+ json,
934
+ )
935
+ }
936
+ throw new ForbiddenError(text, response.url, text)
937
+
938
+ case 404:
939
+ throw new NotFoundError(text, response.url, text)
940
+
941
+ case 500:
942
+ default:
943
+ throw new PrismicError(text, response.url, text)
887
944
  }
888
945
  }
889
946
  }
@@ -0,0 +1,5 @@
1
+ import { PrismicError } from "./PrismicError"
2
+
3
+ export class InvalidDataError<
4
+ TResponse = undefined,
5
+ > extends PrismicError<TResponse> {}
@@ -3,10 +3,12 @@ import { PrismicError } from "./PrismicError"
3
3
  type ParsingErrorAPIResponse = {
4
4
  type: "parsing-error"
5
5
  message: string
6
- line: number
7
- column: number
8
- id: number
9
- location: string
6
+ pos: {
7
+ line: number
8
+ column: number
9
+ id: number
10
+ location: string
11
+ }
10
12
  }
11
13
 
12
14
  export class ParsingError<
package/src/index.ts CHANGED
@@ -51,16 +51,9 @@ export * as cookie from "./cookie"
51
51
 
52
52
  // General types used to query content from Prismic. These are made public to allow users to better type their projects.
53
53
  export type { CreateClient } from "./createClient"
54
- export type { ClientConfig } from "./Client"
54
+ export type { ClientConfig, HttpRequestLike } from "./Client"
55
55
  export type { CreateWriteClient } from "./createWriteClient"
56
56
  export type { WriteClientConfig, MigrateReporterEvents } from "./WriteClient"
57
- export type {
58
- AbortSignalLike,
59
- FetchLike,
60
- HttpRequestLike,
61
- RequestInitLike,
62
- ResponseLike,
63
- } from "./BaseClient"
64
57
  export type {
65
58
  BuildQueryURLArgs,
66
59
  Ordering,
@@ -68,6 +61,12 @@ export type {
68
61
  Route,
69
62
  } from "./buildQueryURL"
70
63
  export type { CreateMigration } from "./createMigration"
64
+ export type {
65
+ AbortSignalLike,
66
+ FetchLike,
67
+ RequestInitLike,
68
+ ResponseLike,
69
+ } from "./lib/request"
71
70
 
72
71
  //=============================================================================
73
72
  // Helpers - Manipulate content from Prismic.
@@ -0,0 +1,166 @@
1
+ import { type LimitFunction, pLimit } from "./pLimit"
2
+
3
+ /**
4
+ * The default number of milliseconds to wait before retrying a rate-limited
5
+ * `fetch()` request (429 response code). The default value is only used if the
6
+ * response does not include a `retry-after` header.
7
+ */
8
+ export const DEFAULT_RETRY_AFTER = 1500 // ms
9
+
10
+ /**
11
+ * A record of URLs mapped to throttled task runners.
12
+ */
13
+ const THROTTLED_RUNNERS: Partial<Record<string, LimitFunction>> = {}
14
+
15
+ /**
16
+ * A record of URLs mapped to active deduplicated jobs. Jobs are keyed by their
17
+ * optional signal.
18
+ */
19
+ const DEDUPLICATED_JOBS: Partial<
20
+ Record<string, Map<AbortSignalLike | undefined, Promise<ResponseLike>>>
21
+ > = {}
22
+
23
+ /**
24
+ * A universal API to make network requests. A subset of the `fetch()` API.
25
+ *
26
+ * {@link https://developer.mozilla.org/en-US/docs/Web/API/fetch}
27
+ */
28
+ export type FetchLike = (
29
+ input: string,
30
+ init?: RequestInitLike,
31
+ ) => Promise<ResponseLike>
32
+
33
+ /**
34
+ * An object that allows you to abort a `fetch()` request if needed via an
35
+ * `AbortController` object
36
+ *
37
+ * {@link https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal}
38
+ */
39
+ // `any` is used often here to ensure this type is universally valid among
40
+ // different AbortSignal implementations. The types of each property are not
41
+ // important to validate since it is blindly passed to a given `fetch()`
42
+ // function.
43
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
44
+ export type AbortSignalLike = any
45
+
46
+ /**
47
+ * A subset of RequestInit properties to configure a `fetch()` request.
48
+ */
49
+ // Only options relevant to the client are included. Extending from the full
50
+ // RequestInit would cause issues, such as accepting Header objects.
51
+ //
52
+ // An interface is used to allow other libraries to augment the type with
53
+ // environment-specific types.
54
+ export interface RequestInitLike extends Pick<RequestInit, "cache"> {
55
+ /**
56
+ * The HTTP method to use for the request.
57
+ */
58
+ method?: string
59
+
60
+ /**
61
+ * The request body to send with the request.
62
+ */
63
+ // We want to keep the body type as compatible as possible, so
64
+ // we only declare the type we need and accept anything else.
65
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
66
+ body?: any | FormData | string
67
+
68
+ /**
69
+ * An object literal to set the `fetch()` request's headers.
70
+ */
71
+ headers?: Record<string, string>
72
+
73
+ /**
74
+ * An AbortSignal to set the `fetch()` request's signal.
75
+ *
76
+ * See:
77
+ * [https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal)
78
+ */
79
+ // NOTE: `AbortSignalLike` is `any`! It is left as `AbortSignalLike`
80
+ // for backwards compatibility (the type is exported) and to signal to
81
+ // other readers that this should be an AbortSignal-like object.
82
+ signal?: AbortSignalLike
83
+ }
84
+
85
+ /**
86
+ * The minimum required properties from Response.
87
+ */
88
+ export interface ResponseLike {
89
+ ok: boolean
90
+ status: number
91
+ headers: HeadersLike
92
+ url: string
93
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
94
+ json(): Promise<any>
95
+ text(): Promise<string>
96
+ blob(): Promise<Blob>
97
+ clone(): ResponseLike
98
+ }
99
+
100
+ /**
101
+ * The minimum required properties from Headers.
102
+ */
103
+ export interface HeadersLike {
104
+ get(name: string): string | null
105
+ }
106
+
107
+ /**
108
+ * Makes an HTTP request with automatic retry for rate limits and request
109
+ * deduplication.
110
+ *
111
+ * @param url - The URL to request.
112
+ * @param init - Fetch options.
113
+ * @param fetchFn - The fetch function to use.
114
+ *
115
+ * @returns The response from the fetch request.
116
+ */
117
+ export async function request(
118
+ url: URL,
119
+ init: RequestInitLike | undefined,
120
+ fetchFn: FetchLike,
121
+ ): Promise<ResponseLike> {
122
+ const stringURL = url.toString()
123
+
124
+ let job: Promise<ResponseLike>
125
+
126
+ // Throttle requests with a body.
127
+ if (init?.body) {
128
+ // Rate limiting is done per hostname.
129
+ const runner = (THROTTLED_RUNNERS[url.hostname] ||= pLimit({
130
+ interval: DEFAULT_RETRY_AFTER,
131
+ }))
132
+
133
+ job = runner(() => fetchFn(stringURL, init))
134
+ } else {
135
+ // Deduplicate all other requests.
136
+ const existingJob = DEDUPLICATED_JOBS[stringURL]?.get(init?.signal)
137
+ if (existingJob) {
138
+ job = existingJob
139
+ } else {
140
+ job = fetchFn(stringURL, init).finally(() => {
141
+ DEDUPLICATED_JOBS[stringURL]?.delete(init?.signal)
142
+ if (DEDUPLICATED_JOBS[stringURL]?.size === 0) {
143
+ delete DEDUPLICATED_JOBS[stringURL]
144
+ }
145
+ })
146
+ const map = (DEDUPLICATED_JOBS[stringURL] ||= new Map())
147
+ map.set(init?.signal, job)
148
+ }
149
+ }
150
+
151
+ const response = await job
152
+
153
+ // Retry rate limited requests.
154
+ if (response.status === 429) {
155
+ const retryAfter = Number(response.headers.get("retry-after"))
156
+ const resolvedRetryAfter = Number.isNaN(retryAfter)
157
+ ? DEFAULT_RETRY_AFTER
158
+ : retryAfter * 1000
159
+
160
+ await new Promise((resolve) => setTimeout(resolve, resolvedRetryAfter))
161
+
162
+ return request(url, init, fetchFn)
163
+ }
164
+
165
+ return response.clone()
166
+ }