@prismicio/client 7.20.0-alpha.0 → 7.20.0

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 (43) hide show
  1. package/dist/Client.cjs +111 -95
  2. package/dist/Client.cjs.map +1 -1
  3. package/dist/Client.d.ts +66 -27
  4. package/dist/Client.js +111 -95
  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 +3 -3
  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/dist/types/{integration.d.ts → api/integration.d.ts} +1 -1
  30. package/package.json +1 -1
  31. package/src/Client.ts +201 -171
  32. package/src/WriteClient.ts +214 -157
  33. package/src/errors/InvalidDataError.ts +5 -0
  34. package/src/errors/ParsingError.ts +6 -4
  35. package/src/index.ts +13 -11
  36. package/src/lib/request.ts +166 -0
  37. package/src/types/{integration.ts → api/integration.ts} +1 -1
  38. package/dist/BaseClient.cjs +0 -108
  39. package/dist/BaseClient.cjs.map +0 -1
  40. package/dist/BaseClient.d.ts +0 -152
  41. package/dist/BaseClient.js +0 -108
  42. package/dist/BaseClient.js.map +0 -1
  43. 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.
@@ -377,6 +376,12 @@ export type {
377
376
 
378
377
  export type { Tags } from "./types/api/tags"
379
378
 
379
+ // Integration - Types representing Prismic's integration API.
380
+ export {
381
+ IntegrationAPIItem,
382
+ IntegrationAPIResults,
383
+ } from "./types/api/integration"
384
+
380
385
  // Webhook - Types representing Prismic webhooks.
381
386
  export { WebhookType } from "./types/webhook/types"
382
387
 
@@ -385,6 +390,3 @@ export type { WebhookBody } from "./types/webhook/types"
385
390
  export type { WebhookBodyAPIUpdate } from "./types/webhook/apiUpdate"
386
391
 
387
392
  export type { WebhookBodyTestTrigger } from "./types/webhook/testTrigger"
388
-
389
- // Integration - Types representing integration catalogs.
390
- export { IntegrationAPIItem, IntegrationAPIResults } from "./types/integration"