@prismicio/client 7.21.0-pr.418.8bcf835 → 7.21.0-pr.419.fc46a04

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.
package/dist/Client.cjs CHANGED
@@ -1,5 +1,6 @@
1
1
  const require_filter = require('./filter.cjs');
2
2
  const require_appendFilters = require('./lib/appendFilters.cjs');
3
+ const require_castThunk = require('./lib/castThunk.cjs');
3
4
  const require_devMsg = require('./lib/devMsg.cjs');
4
5
  const require_everyTagFilter = require('./lib/everyTagFilter.cjs');
5
6
  const require_PrismicError = require('./errors/PrismicError.cjs');
@@ -53,6 +54,28 @@ const GET_ALL_QUERY_DELAY = 500;
53
54
  */
54
55
  const MAX_INVALID_REF_RETRY_ATTEMPTS = 3;
55
56
  /**
57
+ * Modes for client ref management.
58
+ */
59
+ var RefStateMode = /* @__PURE__ */ function(RefStateMode$1) {
60
+ /**
61
+ * Use the repository's master ref.
62
+ */
63
+ RefStateMode$1["Master"] = "Master";
64
+ /**
65
+ * Use a given Release identified by its ID.
66
+ */
67
+ RefStateMode$1["ReleaseID"] = "ReleaseID";
68
+ /**
69
+ * Use a given Release identified by its label.
70
+ */
71
+ RefStateMode$1["ReleaseLabel"] = "ReleaseLabel";
72
+ /**
73
+ * Use a given ref.
74
+ */
75
+ RefStateMode$1["Manual"] = "Manual";
76
+ return RefStateMode$1;
77
+ }(RefStateMode || {});
78
+ /**
56
79
  * A client that allows querying content from a Prismic repository.
57
80
  *
58
81
  * If used in an environment where a global `fetch` function is unavailable,
@@ -135,9 +158,14 @@ var Client = class {
135
158
  * be overridden on each query if needed.
136
159
  */
137
160
  defaultParams;
138
- #getRef;
139
- #autoPreviews = true;
140
- #autoPreviewsRequest;
161
+ /**
162
+ * The client's ref mode state. This determines which ref is used during
163
+ * queries.
164
+ */
165
+ refState = {
166
+ mode: RefStateMode.Master,
167
+ autoPreviewsEnabled: true
168
+ };
141
169
  #cachedRepository;
142
170
  #cachedRepositoryExpiration = 0;
143
171
  /**
@@ -201,7 +229,7 @@ var Client = class {
201
229
  * @see enableAutoPreviewsFromReq
202
230
  */
203
231
  enableAutoPreviews() {
204
- this.#autoPreviews = true;
232
+ this.refState.autoPreviewsEnabled = true;
205
233
  }
206
234
  /**
207
235
  * Enables the client to automatically query content from a preview session if
@@ -222,9 +250,9 @@ var Client = class {
222
250
  * @param req - An HTTP server request object containing the request's
223
251
  * cookies.
224
252
  */
225
- enableAutoPreviewsFromReq(request$1) {
226
- this.enableAutoPreviews();
227
- this.#autoPreviewsRequest = request$1;
253
+ enableAutoPreviewsFromReq(req) {
254
+ this.refState.httpRequest = req;
255
+ this.refState.autoPreviewsEnabled = true;
228
256
  }
229
257
  /**
230
258
  * Disables the client from automatically querying content from a preview
@@ -240,8 +268,7 @@ var Client = class {
240
268
  * ```
241
269
  */
242
270
  disableAutoPreviews() {
243
- this.#autoPreviews = false;
244
- this.#autoPreviewsRequest = void 0;
271
+ this.refState.autoPreviewsEnabled = false;
245
272
  }
246
273
  /**
247
274
  * Queries content from the Prismic repository.
@@ -259,8 +286,7 @@ var Client = class {
259
286
  * @returns A paginated response containing the result of the query.
260
287
  */
261
288
  async get(params) {
262
- const { data } = await this._get(params);
263
- return data;
289
+ return await (await this.#internalGet(params)).json();
264
290
  }
265
291
  /**
266
292
  * Queries content from the Prismic repository and returns only the first
@@ -279,15 +305,14 @@ var Client = class {
279
305
  * @returns The first result of the query, if any.
280
306
  */
281
307
  async getFirst(params) {
282
- const actualParams = { ...params };
283
- if (!(params && params.page) && !(params === null || params === void 0 ? void 0 : params.pageSize)) {
284
- var _this$defaultParams;
285
- actualParams.pageSize = ((_this$defaultParams = this.defaultParams) === null || _this$defaultParams === void 0 ? void 0 : _this$defaultParams.pageSize) ?? 1;
286
- }
287
- const { data, url } = await this._get(actualParams);
288
- const firstResult = data.results[0];
289
- if (firstResult) return firstResult;
290
- throw new require_NotFoundError.NotFoundError("No documents were returned", url, void 0);
308
+ const actualParams = (params === null || params === void 0 ? void 0 : params.page) || (params === null || params === void 0 ? void 0 : params.pageSize) ? params : {
309
+ ...params,
310
+ pageSize: 1
311
+ };
312
+ const response = await this.#internalGet(actualParams);
313
+ const { results } = await response.clone().json();
314
+ if (results[0]) return results[0];
315
+ throw new require_NotFoundError.NotFoundError("No documents were returned", response.url, void 0);
291
316
  }
292
317
  /**
293
318
  * **IMPORTANT**: Avoid using `dangerouslyGetAll` as it may be slower and
@@ -313,11 +338,11 @@ var Client = class {
313
338
  * @returns A list of documents matching the query.
314
339
  */
315
340
  async dangerouslyGetAll(params = {}) {
316
- var _this$defaultParams2;
341
+ var _this$defaultParams;
317
342
  const { limit = Infinity,...actualParams } = params;
318
343
  const resolvedParams = {
319
344
  ...actualParams,
320
- pageSize: Math.min(limit, actualParams.pageSize || ((_this$defaultParams2 = this.defaultParams) === null || _this$defaultParams2 === void 0 ? void 0 : _this$defaultParams2.pageSize) || MAX_PAGE_SIZE)
345
+ pageSize: Math.min(limit, actualParams.pageSize || ((_this$defaultParams = this.defaultParams) === null || _this$defaultParams === void 0 ? void 0 : _this$defaultParams.pageSize) || MAX_PAGE_SIZE)
321
346
  };
322
347
  const documents = [];
323
348
  let latestResult;
@@ -727,18 +752,13 @@ var Client = class {
727
752
  const accessToken = (params === null || params === void 0 ? void 0 : params.accessToken) || this.accessToken;
728
753
  if (accessToken) url.searchParams.set("access_token", accessToken);
729
754
  const response = await this.#request(url, params);
730
- switch (response.status) {
731
- case 200:
732
- this.#cachedRepository = await response.json();
733
- this.#cachedRepositoryExpiration = Date.now() + REPOSITORY_CACHE_TTL;
734
- return this.#cachedRepository;
735
- case 401: {
736
- const json = await response.json();
737
- throw new require_ForbiddenError.ForbiddenError(json.error, url.toString(), json);
738
- }
739
- case 404: throw new require_RepositoryNotFoundError.RepositoryNotFoundError(`Prismic repository not found. Check that "${this.documentAPIEndpoint}" is pointing to the correct repository.`, url.toString(), void 0);
740
- default: throw new require_PrismicError.PrismicError(void 0, url.toString(), await response.text());
755
+ if (response.ok) {
756
+ this.#cachedRepository = await response.json();
757
+ this.#cachedRepositoryExpiration = Date.now() + REPOSITORY_CACHE_TTL;
758
+ return this.#cachedRepository;
741
759
  }
760
+ if (response.status === 404) throw new require_RepositoryNotFoundError.RepositoryNotFoundError(`Prismic repository not found. Check that "${this.documentAPIEndpoint}" is pointing to the correct repository.`, url.toString(), void 0);
761
+ return await this.#throwContentAPIError(response, url.toString());
742
762
  }
743
763
  /**
744
764
  * Returns a list of all refs for the Prismic repository.
@@ -834,7 +854,7 @@ var Client = class {
834
854
  * @returns A URL string that can be requested to query content.
835
855
  */
836
856
  async buildQueryURL({ signal, fetchOptions,...params } = {}) {
837
- const ref = params.ref || await this.#getResolvedRef({
857
+ const ref = params.ref || await this.getResolvedRefString({
838
858
  accessToken: params.accessToken,
839
859
  signal,
840
860
  fetchOptions
@@ -880,13 +900,13 @@ var Client = class {
880
900
  const searchParams = new URLSearchParams(globalThis.location.search);
881
901
  documentID = documentID || searchParams.get("documentId");
882
902
  previewToken = previewToken || searchParams.get("token");
883
- } else if (this.#autoPreviewsRequest) {
884
- if ("query" in this.#autoPreviewsRequest) {
885
- var _this$autoPreviewsReq, _this$autoPreviewsReq2;
886
- documentID = documentID || ((_this$autoPreviewsReq = this.#autoPreviewsRequest.query) === null || _this$autoPreviewsReq === void 0 ? void 0 : _this$autoPreviewsReq.documentId);
887
- previewToken = previewToken || ((_this$autoPreviewsReq2 = this.#autoPreviewsRequest.query) === null || _this$autoPreviewsReq2 === void 0 ? void 0 : _this$autoPreviewsReq2.token);
888
- } else if ("url" in this.#autoPreviewsRequest && this.#autoPreviewsRequest.url) {
889
- const searchParams = new URL(this.#autoPreviewsRequest.url, "missing-host://").searchParams;
903
+ } else if (this.refState.httpRequest) {
904
+ if ("query" in this.refState.httpRequest) {
905
+ var _this$refState$httpRe, _this$refState$httpRe2;
906
+ documentID = documentID || ((_this$refState$httpRe = this.refState.httpRequest.query) === null || _this$refState$httpRe === void 0 ? void 0 : _this$refState$httpRe.documentId);
907
+ previewToken = previewToken || ((_this$refState$httpRe2 = this.refState.httpRequest.query) === null || _this$refState$httpRe2 === void 0 ? void 0 : _this$refState$httpRe2.token);
908
+ } else if ("url" in this.refState.httpRequest && this.refState.httpRequest.url) {
909
+ const searchParams = new URL(this.refState.httpRequest.url, "missing-host://").searchParams;
890
910
  documentID = documentID || searchParams.get("documentId");
891
911
  previewToken = previewToken || searchParams.get("token");
892
912
  }
@@ -917,7 +937,7 @@ var Client = class {
917
937
  * ```
918
938
  */
919
939
  queryLatestContent() {
920
- this.#getRef = void 0;
940
+ this.refState.mode = RefStateMode.Master;
921
941
  }
922
942
  /**
923
943
  * Configures the client to query content from a specific Release identified
@@ -935,9 +955,11 @@ var Client = class {
935
955
  *
936
956
  * @param releaseID - The ID of the Release.
937
957
  */
938
- queryContentFromReleaseByID(id) {
939
- this.#getRef = async (params) => {
940
- return (await this.getReleaseByID(id, params)).ref;
958
+ queryContentFromReleaseByID(releaseID) {
959
+ this.refState = {
960
+ ...this.refState,
961
+ mode: RefStateMode.ReleaseID,
962
+ releaseID
941
963
  };
942
964
  }
943
965
  /**
@@ -956,9 +978,11 @@ var Client = class {
956
978
  *
957
979
  * @param releaseLabel - The label of the Release.
958
980
  */
959
- queryContentFromReleaseByLabel(label) {
960
- this.#getRef = async (params) => {
961
- return (await this.getReleaseByLabel(label, params)).ref;
981
+ queryContentFromReleaseByLabel(releaseLabel) {
982
+ this.refState = {
983
+ ...this.refState,
984
+ mode: RefStateMode.ReleaseLabel,
985
+ releaseLabel
962
986
  };
963
987
  }
964
988
  /**
@@ -979,7 +1003,11 @@ var Client = class {
979
1003
  * content.
980
1004
  */
981
1005
  queryContentFromRef(ref) {
982
- this.#getRef = typeof ref === "string" ? () => ref : ref;
1006
+ this.refState = {
1007
+ ...this.refState,
1008
+ mode: RefStateMode.Manual,
1009
+ ref
1010
+ };
983
1011
  }
984
1012
  /**
985
1013
  * A `fetch()` function to be used with GraphQL clients configured for
@@ -1012,7 +1040,7 @@ var Client = class {
1012
1040
  */
1013
1041
  async graphQLFetch(input, init) {
1014
1042
  const repository = await this.getRepository();
1015
- const ref = await this.#getResolvedRef();
1043
+ const ref = await this.getResolvedRefString();
1016
1044
  const unsanitizedHeaders = {
1017
1045
  "Prismic-ref": ref,
1018
1046
  Authorization: this.accessToken ? `Token ${this.accessToken}` : "",
@@ -1053,79 +1081,72 @@ var Client = class {
1053
1081
  *
1054
1082
  * @returns The ref to use during a query.
1055
1083
  */
1056
- async #getResolvedRef(params) {
1057
- var _this$getRef;
1058
- if (this.#autoPreviews) {
1059
- var _this$autoPreviewsReq3, _globalThis$document;
1060
- const previewRef = require_getPreviewCookie.getPreviewCookie((((_this$autoPreviewsReq3 = this.#autoPreviewsRequest) === null || _this$autoPreviewsReq3 === void 0 ? void 0 : _this$autoPreviewsReq3.headers) ? "get" in this.#autoPreviewsRequest.headers ? this.#autoPreviewsRequest.headers.get("cookie") : this.#autoPreviewsRequest.headers.cookie : (_globalThis$document = globalThis.document) === null || _globalThis$document === void 0 ? void 0 : _globalThis$document.cookie) ?? "");
1084
+ async getResolvedRefString(params) {
1085
+ if (this.refState.autoPreviewsEnabled) {
1086
+ var _this$refState$httpRe3, _globalThis$document;
1087
+ let previewRef;
1088
+ let cookieJar;
1089
+ if ((_this$refState$httpRe3 = this.refState.httpRequest) === null || _this$refState$httpRe3 === void 0 ? void 0 : _this$refState$httpRe3.headers) {
1090
+ if ("get" in this.refState.httpRequest.headers && typeof this.refState.httpRequest.headers.get === "function") cookieJar = this.refState.httpRequest.headers.get("cookie");
1091
+ else if ("cookie" in this.refState.httpRequest.headers) cookieJar = this.refState.httpRequest.headers.cookie;
1092
+ } else if ((_globalThis$document = globalThis.document) === null || _globalThis$document === void 0 ? void 0 : _globalThis$document.cookie) cookieJar = globalThis.document.cookie;
1093
+ if (cookieJar) previewRef = require_getPreviewCookie.getPreviewCookie(cookieJar);
1061
1094
  if (previewRef) return previewRef;
1062
1095
  }
1063
- const ref = await ((_this$getRef = this.#getRef) === null || _this$getRef === void 0 ? void 0 : _this$getRef.call(this, params));
1064
- if (ref) return ref;
1065
- return (await this.getMasterRef(params)).ref;
1096
+ const repository = await this.getRepository(params);
1097
+ const refModeType = this.refState.mode;
1098
+ if (refModeType === RefStateMode.ReleaseID) return require_findRefByID.findRefByID(repository.refs, this.refState.releaseID).ref;
1099
+ else if (refModeType === RefStateMode.ReleaseLabel) return require_findRefByLabel.findRefByLabel(repository.refs, this.refState.releaseLabel).ref;
1100
+ else if (refModeType === RefStateMode.Manual) {
1101
+ const res = await require_castThunk.castThunk(this.refState.ref)();
1102
+ if (typeof res === "string") return res;
1103
+ }
1104
+ return require_findMasterRef.findMasterRef(repository.refs).ref;
1066
1105
  }
1067
- /**
1068
- * The private implementation of `this.get`. It returns the API response and
1069
- * the URL used to make the request. The URL is sometimes used in the public
1070
- * method to include in thrown errors.
1071
- *
1072
- * This method retries requests that throw `RefNotFoundError` or
1073
- * `RefExpiredError`. It contains special logic to retry with the latest
1074
- * master ref, provided in the API's error message.
1075
- *
1076
- * @typeParam TDocument - Type of Prismic documents returned.
1077
- *
1078
- * @param params - Parameters to filter, sort, and paginate results.
1079
- *
1080
- * @returns An object containing the paginated response containing the result
1081
- * of the query and the URL used to make the API request.
1082
- */
1083
- async _get(params, attemptCount = 0) {
1106
+ async #internalGet(params, attempt = 1) {
1084
1107
  const url = await this.buildQueryURL(params);
1108
+ const response = await this.#request(new URL(url), params);
1109
+ if (response.ok) return response;
1085
1110
  try {
1086
- const response = await this.#request(new URL(url), params);
1087
- switch (response.status) {
1088
- case 200: try {
1089
- return {
1090
- data: await response.clone().json(),
1091
- url
1092
- };
1093
- } catch {
1094
- throw new require_PrismicError.PrismicError(void 0, url, await response.text());
1095
- }
1096
- case 400: {
1097
- const json = await response.json();
1098
- throw new require_ParsingError.ParsingError(json.message, url, json);
1099
- }
1100
- case 401: {
1101
- const json = await response.json();
1102
- throw new require_ForbiddenError.ForbiddenError(json.message, url, json);
1103
- }
1104
- case 404: {
1105
- const json = await response.json();
1106
- switch (json.type) {
1107
- case "api_notfound_error": throw new require_RefNotFoundError.RefNotFoundError(json.message, url, json);
1108
- case "api_security_error": if (/preview token.*expired/i.test(json.message)) throw new require_PreviewTokenExpired.PreviewTokenExpiredError(json.message, url, json);
1109
- default: throw new require_NotFoundError.NotFoundError(json.message, url, json);
1110
- }
1111
- }
1112
- case 410: {
1113
- const json = await response.json();
1114
- throw new require_RefExpiredError.RefExpiredError(json.message, url, json);
1111
+ return await this.#throwContentAPIError(response, url);
1112
+ } catch (error) {
1113
+ if ((error instanceof require_RefNotFoundError.RefNotFoundError || error instanceof require_RefExpiredError.RefExpiredError) && attempt < MAX_INVALID_REF_RETRY_ATTEMPTS) {
1114
+ var _error$message$match;
1115
+ if (!(params === null || params === void 0 ? void 0 : params.ref)) this.#cachedRepository = void 0;
1116
+ const masterRef = (_error$message$match = error.message.match(/master ref is: (?<ref>.*)$/i)) === null || _error$message$match === void 0 || (_error$message$match = _error$message$match.groups) === null || _error$message$match === void 0 ? void 0 : _error$message$match.ref;
1117
+ if (!masterRef) throw error;
1118
+ require_throttledLog.throttledLog(`[@prismicio/client] The ref (${new URL(url).searchParams.get("ref")}) was ${error instanceof require_RefNotFoundError.RefNotFoundError ? "invalid" : "expired"}. Now retrying with the latest master ref (${masterRef}). If you were previewing content, the response will not include draft content.`, { level: "warn" });
1119
+ return await this.#internalGet({
1120
+ ...params,
1121
+ ref: masterRef
1122
+ }, attempt + 1);
1123
+ }
1124
+ throw error;
1125
+ }
1126
+ }
1127
+ async #throwContentAPIError(response, url) {
1128
+ switch (response.status) {
1129
+ case 400: {
1130
+ const json = await response.clone().json();
1131
+ throw new require_ParsingError.ParsingError(json.message, url, json);
1132
+ }
1133
+ case 401: {
1134
+ const json = await response.clone().json();
1135
+ throw new require_ForbiddenError.ForbiddenError(json.message, url, json);
1136
+ }
1137
+ case 404: {
1138
+ const json = await response.clone().json();
1139
+ switch (json.type) {
1140
+ case "api_notfound_error": throw new require_RefNotFoundError.RefNotFoundError(json.message, url, json);
1141
+ case "api_security_error": if (/preview token.*expired/i.test(json.message)) throw new require_PreviewTokenExpired.PreviewTokenExpiredError(json.message, url, json);
1142
+ default: throw new require_NotFoundError.NotFoundError(json.message, url, json);
1115
1143
  }
1116
- default: throw new require_PrismicError.PrismicError(void 0, url, await response.text());
1117
1144
  }
1118
- } catch (error) {
1119
- var _error$message$match;
1120
- if (!(error instanceof require_RefNotFoundError.RefNotFoundError || error instanceof require_RefExpiredError.RefExpiredError) || attemptCount >= MAX_INVALID_REF_RETRY_ATTEMPTS - 1) throw error;
1121
- if (!(params === null || params === void 0 ? void 0 : params.ref)) this.#cachedRepository = void 0;
1122
- const masterRef = (_error$message$match = error.message.match(/master ref is: (?<ref>.*)$/i)) === null || _error$message$match === void 0 || (_error$message$match = _error$message$match.groups) === null || _error$message$match === void 0 ? void 0 : _error$message$match.ref;
1123
- if (!masterRef) throw error;
1124
- require_throttledLog.throttledLog(`[@prismicio/client] The ref (${new URL(url).searchParams.get("ref")}) was ${error instanceof require_RefNotFoundError.RefNotFoundError ? "invalid" : "expired"}. Now retrying with the latest master ref (${masterRef}). If you were previewing content, the response will not include draft content.`, { level: "warn" });
1125
- return await this._get({
1126
- ...params,
1127
- ref: masterRef
1128
- }, attemptCount + 1);
1145
+ case 410: {
1146
+ const json = await response.clone().json();
1147
+ throw new require_RefExpiredError.RefExpiredError(json.message, url, json);
1148
+ }
1149
+ default: throw new require_PrismicError.PrismicError(void 0, url, await response.text());
1129
1150
  }
1130
1151
  }
1131
1152
  /**