@prismicio/client 7.19.2 → 7.20.0-alpha.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 (49) 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 +95 -111
  7. package/dist/Client.cjs.map +1 -1
  8. package/dist/Client.d.ts +27 -66
  9. package/dist/Client.js +95 -111
  10. package/dist/Client.js.map +1 -1
  11. package/dist/WriteClient.cjs +100 -151
  12. package/dist/WriteClient.cjs.map +1 -1
  13. package/dist/WriteClient.d.ts +26 -2
  14. package/dist/WriteClient.js +100 -151
  15. package/dist/WriteClient.js.map +1 -1
  16. package/dist/errors/ParsingError.cjs.map +1 -1
  17. package/dist/errors/ParsingError.d.ts +4 -6
  18. package/dist/errors/ParsingError.js.map +1 -1
  19. package/dist/helpers/isFilled.cjs.map +1 -1
  20. package/dist/helpers/isFilled.d.ts +4 -4
  21. package/dist/helpers/isFilled.js.map +1 -1
  22. package/dist/index.cjs.map +1 -1
  23. package/dist/index.d.ts +5 -3
  24. package/dist/index.js.map +1 -1
  25. package/dist/package.json.cjs +1 -1
  26. package/dist/package.json.js +1 -1
  27. package/dist/types/integration.d.ts +28 -0
  28. package/dist/types/value/integration.d.ts +8 -2
  29. package/package.json +1 -1
  30. package/src/BaseClient.ts +330 -0
  31. package/src/Client.ts +171 -201
  32. package/src/WriteClient.ts +157 -214
  33. package/src/errors/ParsingError.ts +4 -6
  34. package/src/helpers/isFilled.ts +5 -4
  35. package/src/index.ts +13 -8
  36. package/src/types/integration.ts +34 -0
  37. package/src/types/value/integration.ts +9 -2
  38. package/dist/errors/InvalidDataError.cjs +0 -7
  39. package/dist/errors/InvalidDataError.cjs.map +0 -1
  40. package/dist/errors/InvalidDataError.d.ts +0 -3
  41. package/dist/errors/InvalidDataError.js +0 -7
  42. package/dist/errors/InvalidDataError.js.map +0 -1
  43. package/dist/lib/request.cjs +0 -43
  44. package/dist/lib/request.cjs.map +0 -1
  45. package/dist/lib/request.d.ts +0 -73
  46. package/dist/lib/request.js +0 -43
  47. package/dist/lib/request.js.map +0 -1
  48. package/src/errors/InvalidDataError.ts +0 -5
  49. package/src/lib/request.ts +0 -166
package/dist/Client.cjs CHANGED
@@ -9,8 +9,7 @@ var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot
9
9
  var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
10
10
  var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
11
11
  var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
12
- var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
13
- var _repositoryName, _Client_instances, request_fn;
12
+ var _repositoryName;
14
13
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
15
14
  const appendFilters = require("./lib/appendFilters.cjs");
16
15
  const castThunk = require("./lib/castThunk.cjs");
@@ -21,7 +20,6 @@ const findRefByID = require("./lib/findRefByID.cjs");
21
20
  const findRefByLabel = require("./lib/findRefByLabel.cjs");
22
21
  const getPreviewCookie = require("./lib/getPreviewCookie.cjs");
23
22
  const minifyGraphQLQuery = require("./lib/minifyGraphQLQuery.cjs");
24
- const request = require("./lib/request.cjs");
25
23
  const someTagsFilter = require("./lib/someTagsFilter.cjs");
26
24
  const throttledLog = require("./lib/throttledLog.cjs");
27
25
  const typeFilter = require("./lib/typeFilter.cjs");
@@ -34,6 +32,7 @@ const RefExpiredError = require("./errors/RefExpiredError.cjs");
34
32
  const RefNotFoundError = require("./errors/RefNotFoundError.cjs");
35
33
  const RepositoryNotFoundError = require("./errors/RepositoryNotFoundError.cjs");
36
34
  const asLink = require("./helpers/asLink.cjs");
35
+ const BaseClient = require("./BaseClient.cjs");
37
36
  const buildQueryURL = require("./buildQueryURL.cjs");
38
37
  const filter = require("./filter.cjs");
39
38
  const getRepositoryEndpoint = require("./getRepositoryEndpoint.cjs");
@@ -42,7 +41,8 @@ const isRepositoryEndpoint = require("./isRepositoryEndpoint.cjs");
42
41
  const MAX_PAGE_SIZE = 100;
43
42
  const REPOSITORY_CACHE_TTL = 5e3;
44
43
  const GET_ALL_QUERY_DELAY = 500;
45
- const MAX_INVALID_REF_RETRY_ATTEMPTS = 3;
44
+ const DEFUALT_RETRY_AFTER_MS = 1e3;
45
+ const MAX_INVALID_REF_RETRY_ATTEMPS = 3;
46
46
  var RefStateMode;
47
47
  (function(RefStateMode2) {
48
48
  RefStateMode2["Master"] = "Master";
@@ -50,7 +50,7 @@ var RefStateMode;
50
50
  RefStateMode2["ReleaseLabel"] = "ReleaseLabel";
51
51
  RefStateMode2["Manual"] = "Manual";
52
52
  })(RefStateMode || (RefStateMode = {}));
53
- class Client {
53
+ class Client extends BaseClient.BaseClient {
54
54
  /**
55
55
  * Creates a Prismic client that can be used to query a repository.
56
56
  *
@@ -66,14 +66,7 @@ class Client {
66
66
  * @returns A client that can query content from the repository.
67
67
  */
68
68
  constructor(repositoryNameOrEndpoint, options = {}) {
69
- __privateAdd(this, _Client_instances);
70
- /**
71
- * The function used to make network requests to the Prismic REST API. In
72
- * environments where a global `fetch` function does not exist, such as
73
- * Node.js, this function must be provided.
74
- */
75
- __publicField(this, "fetchFn");
76
- __publicField(this, "fetchOptions");
69
+ super(options);
77
70
  __privateAdd(this, _repositoryName);
78
71
  /**
79
72
  * The Prismic REST API V2 endpoint for the repository (use
@@ -124,17 +117,6 @@ class Client {
124
117
  * Timestamp at which the cached repository data is considered stale.
125
118
  */
126
119
  __publicField(this, "cachedRepositoryExpiration", 0);
127
- this.fetchOptions = options.fetchOptions;
128
- if (typeof options.fetch === "function") {
129
- this.fetchFn = options.fetch;
130
- } else if (typeof globalThis.fetch === "function") {
131
- this.fetchFn = globalThis.fetch;
132
- } else {
133
- throw new PrismicError.PrismicError("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.", void 0, void 0);
134
- }
135
- if (this.fetchFn === globalThis.fetch) {
136
- this.fetchFn = this.fetchFn.bind(globalThis);
137
- }
138
120
  if ((options.documentAPIEndpoint || isRepositoryEndpoint.isRepositoryEndpoint(repositoryNameOrEndpoint)) && process.env.NODE_ENV === "development") {
139
121
  const documentAPIEndpoint = options.documentAPIEndpoint || repositoryNameOrEndpoint;
140
122
  if (/\.prismic\.io\/(?!api\/v2\/?)/i.test(documentAPIEndpoint)) {
@@ -753,22 +735,7 @@ class Client {
753
735
  if (this.accessToken) {
754
736
  url.searchParams.set("access_token", this.accessToken);
755
737
  }
756
- const response = await __privateMethod(this, _Client_instances, request_fn).call(this, url, params);
757
- switch (response.status) {
758
- case 200: {
759
- return await response.json();
760
- }
761
- case 401: {
762
- const json = await response.json();
763
- throw new ForbiddenError.ForbiddenError(json.error, url.toString(), json);
764
- }
765
- case 404: {
766
- throw new RepositoryNotFoundError.RepositoryNotFoundError(`Prismic repository not found. Check that "${this.documentAPIEndpoint}" is pointing to the correct repository.`, url.toString(), void 0);
767
- }
768
- default: {
769
- throw new PrismicError.PrismicError(void 0, url.toString(), await response.text());
770
- }
771
- }
738
+ return await this.fetch(url.toString(), params);
772
739
  }
773
740
  /**
774
741
  * Returns a list of all refs for the Prismic repository.
@@ -853,20 +820,17 @@ class Client {
853
820
  * @returns A list of all tags used in the repository.
854
821
  */
855
822
  async getTags(params) {
856
- const cachedRepository = await this.getCachedRepository(params);
857
- const form = cachedRepository.forms.tags;
858
- if (form) {
859
- const url = new URL(form.action);
823
+ try {
824
+ const tagsForm = await this.getCachedRepositoryForm("tags", params);
825
+ const url = new URL(tagsForm.action);
860
826
  if (this.accessToken) {
861
827
  url.searchParams.set("access_token", this.accessToken);
862
828
  }
863
- const response = await __privateMethod(this, _Client_instances, request_fn).call(this, url, params);
864
- if (response.ok) {
865
- return await response.json();
866
- }
829
+ return await this.fetch(url.toString(), params);
830
+ } catch {
831
+ const repository = await this.getRepository(params);
832
+ return repository.tags;
867
833
  }
868
- const repository = await this.getRepository(params);
869
- return repository.tags;
870
834
  }
871
835
  /**
872
836
  * Builds a URL used to query content from the Prismic repository.
@@ -1106,11 +1070,29 @@ class Client {
1106
1070
  */
1107
1071
  async getCachedRepository(params) {
1108
1072
  if (!this.cachedRepository || Date.now() >= this.cachedRepositoryExpiration) {
1109
- this.cachedRepository = await this.getRepository(params);
1110
1073
  this.cachedRepositoryExpiration = Date.now() + REPOSITORY_CACHE_TTL;
1074
+ this.cachedRepository = await this.getRepository(params);
1111
1075
  }
1112
1076
  return this.cachedRepository;
1113
1077
  }
1078
+ /**
1079
+ * Returns a cached Prismic repository form. Forms are used to determine API
1080
+ * endpoints for types of repository data.
1081
+ *
1082
+ * @param name - Name of the form.
1083
+ *
1084
+ * @returns The repository form.
1085
+ *
1086
+ * @throws If a matching form cannot be found.
1087
+ */
1088
+ async getCachedRepositoryForm(name, params) {
1089
+ const cachedRepository = await this.getCachedRepository(params);
1090
+ const form = cachedRepository.forms[name];
1091
+ if (!form) {
1092
+ throw new PrismicError.PrismicError(`Form with name "${name}" could not be found`, void 0, void 0);
1093
+ }
1094
+ return form;
1095
+ }
1114
1096
  /**
1115
1097
  * Returns the ref needed to query based on the client's current state. This
1116
1098
  * method may make a network request to fetch a ref or resolve the user's ref
@@ -1189,52 +1171,10 @@ class Client {
1189
1171
  var _a, _b;
1190
1172
  const url = await this.buildQueryURL(params);
1191
1173
  try {
1192
- const response = await __privateMethod(this, _Client_instances, request_fn).call(this, new URL(url), params);
1193
- switch (response.status) {
1194
- case 200: {
1195
- try {
1196
- return {
1197
- data: await response.clone().json(),
1198
- url
1199
- };
1200
- } catch {
1201
- throw new PrismicError.PrismicError(void 0, url, await response.text());
1202
- }
1203
- }
1204
- case 400: {
1205
- const json = await response.json();
1206
- throw new ParsingError.ParsingError(json.message, url, json);
1207
- }
1208
- case 401: {
1209
- const json = await response.json();
1210
- throw new ForbiddenError.ForbiddenError(json.message, url, json);
1211
- }
1212
- case 404: {
1213
- const json = await response.json();
1214
- switch (json.type) {
1215
- case "api_notfound_error": {
1216
- throw new RefNotFoundError.RefNotFoundError(json.message, url, json);
1217
- }
1218
- case "api_security_error": {
1219
- if (/preview token.*expired/i.test(json.message)) {
1220
- throw new PreviewTokenExpired.PreviewTokenExpiredError(json.message, url, json);
1221
- }
1222
- }
1223
- default: {
1224
- throw new NotFoundError.NotFoundError(json.message, url, json);
1225
- }
1226
- }
1227
- }
1228
- case 410: {
1229
- const json = await response.json();
1230
- throw new RefExpiredError.RefExpiredError(json.message, url, json);
1231
- }
1232
- default: {
1233
- throw new PrismicError.PrismicError(void 0, url, await response.text());
1234
- }
1235
- }
1174
+ const data = await this.fetch(url, params);
1175
+ return { data, url };
1236
1176
  } catch (error) {
1237
- if (!(error instanceof RefNotFoundError.RefNotFoundError || error instanceof RefExpiredError.RefExpiredError) || attemptCount >= MAX_INVALID_REF_RETRY_ATTEMPTS - 1) {
1177
+ if (!(error instanceof RefNotFoundError.RefNotFoundError || error instanceof RefExpiredError.RefExpiredError) || attemptCount >= MAX_INVALID_REF_RETRY_ATTEMPS - 1) {
1238
1178
  throw error;
1239
1179
  }
1240
1180
  if (!(params == null ? void 0 : params.ref)) {
@@ -1250,24 +1190,68 @@ class Client {
1250
1190
  return await this._get({ ...params, ref: masterRef }, attemptCount + 1);
1251
1191
  }
1252
1192
  }
1253
- _buildRequestInit(params) {
1254
- var _a, _b, _c, _d;
1255
- return {
1256
- ...this.fetchOptions,
1257
- ...params == null ? void 0 : params.fetchOptions,
1258
- headers: {
1259
- ...(_a = this.fetchOptions) == null ? void 0 : _a.headers,
1260
- ...(_b = params == null ? void 0 : params.fetchOptions) == null ? void 0 : _b.headers
1261
- },
1262
- signal: ((_c = params == null ? void 0 : params.fetchOptions) == null ? void 0 : _c.signal) || (params == null ? void 0 : params.signal) || ((_d = this.fetchOptions) == null ? void 0 : _d.signal)
1263
- };
1193
+ /**
1194
+ * Performs a network request using the configured `fetch` function. It
1195
+ * assumes all successful responses will have a JSON content type. It also
1196
+ * normalizes unsuccessful network requests.
1197
+ *
1198
+ * @typeParam T - The JSON response.
1199
+ *
1200
+ * @param url - URL to the resource to fetch.
1201
+ * @param params - Prismic REST API parameters for the network request.
1202
+ *
1203
+ * @returns The JSON response from the network request.
1204
+ */
1205
+ async fetch(url, params = {}) {
1206
+ const res = await super.fetch(url, params);
1207
+ if (res.status !== 404 && res.status !== 429 && res.json == null) {
1208
+ throw new PrismicError.PrismicError(void 0, url, res.json || res.text);
1209
+ }
1210
+ switch (res.status) {
1211
+ case 200:
1212
+ case 201: {
1213
+ return res.json;
1214
+ }
1215
+ case 400: {
1216
+ throw new ParsingError.ParsingError(res.json.message, url, res.json);
1217
+ }
1218
+ case 401:
1219
+ case 403: {
1220
+ throw new ForbiddenError.ForbiddenError(res.json.error || res.json.message, url, res.json);
1221
+ }
1222
+ case 404: {
1223
+ if (res.json === void 0) {
1224
+ throw new RepositoryNotFoundError.RepositoryNotFoundError(`Prismic repository not found. Check that "${this.documentAPIEndpoint}" is pointing to the correct repository.`, url, url.startsWith(this.documentAPIEndpoint) ? void 0 : res.text);
1225
+ }
1226
+ if (res.json.type === "api_notfound_error") {
1227
+ throw new RefNotFoundError.RefNotFoundError(res.json.message, url, res.json);
1228
+ }
1229
+ if (res.json.type === "api_security_error" && /preview token.*expired/i.test(res.json.message)) {
1230
+ throw new PreviewTokenExpired.PreviewTokenExpiredError(res.json.message, url, res.json);
1231
+ }
1232
+ throw new NotFoundError.NotFoundError(res.json.message, url, res.json);
1233
+ }
1234
+ case 410: {
1235
+ throw new RefExpiredError.RefExpiredError(res.json.message, url, res.json);
1236
+ }
1237
+ case 429: {
1238
+ const parsedRetryAfter = Number(res.headers.get("retry-after"));
1239
+ const delay = Number.isNaN(parsedRetryAfter) ? DEFUALT_RETRY_AFTER_MS : parsedRetryAfter;
1240
+ return await new Promise((resolve, reject) => {
1241
+ setTimeout(async () => {
1242
+ try {
1243
+ resolve(await this.fetch(url, params));
1244
+ } catch (error) {
1245
+ reject(error);
1246
+ }
1247
+ }, delay);
1248
+ });
1249
+ }
1250
+ }
1251
+ throw new PrismicError.PrismicError(void 0, url, res.json);
1264
1252
  }
1265
1253
  }
1266
1254
  _repositoryName = new WeakMap();
1267
- _Client_instances = new WeakSet();
1268
- request_fn = async function(url, params) {
1269
- return await request.request(url, this._buildRequestInit(params), this.fetchFn);
1270
- };
1271
1255
  exports.Client = Client;
1272
1256
  exports.GET_ALL_QUERY_DELAY = GET_ALL_QUERY_DELAY;
1273
1257
  exports.REPOSITORY_CACHE_TTL = REPOSITORY_CACHE_TTL;