@prismicio/client 6.0.0-alpha.9 → 6.0.0-beta.3

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/index.mjs CHANGED
@@ -13,12 +13,8 @@ const castOrderingToString = (ordering) => typeof ordering === "string" ? orderi
13
13
  ].filter(Boolean).join(" ");
14
14
  const buildQueryURL = (endpoint, args) => {
15
15
  var _a;
16
- const { ref, integrationFieldsRef, predicates, ...params } = args;
16
+ const { predicates, ...params } = args;
17
17
  const url = new URL(`documents/search`, `${endpoint}/`);
18
- url.searchParams.set("ref", ref);
19
- if (integrationFieldsRef) {
20
- url.searchParams.set("integrationFieldsRef", integrationFieldsRef);
21
- }
22
18
  if (predicates) {
23
19
  for (const predicate of castArray(predicates)) {
24
20
  url.searchParams.append("q", `[${predicate}]`);
@@ -45,13 +41,46 @@ const buildQueryURL = (endpoint, args) => {
45
41
  return url.toString();
46
42
  };
47
43
 
48
- const appendPredicates = (...predicates) => (objWithPredicates = {}) => ({
49
- ...objWithPredicates,
50
- predicates: [objWithPredicates.predicates || [], ...predicates].flat()
51
- });
44
+ const appendPredicates = (objWithPredicates = {}, predicates) => {
45
+ return {
46
+ ...objWithPredicates,
47
+ predicates: [
48
+ ...objWithPredicates.predicates || [],
49
+ ...castArray(predicates)
50
+ ]
51
+ };
52
+ };
52
53
 
53
54
  const castThunk = (a) => typeof a === "function" ? a : () => a;
54
55
 
56
+ class PrismicError extends Error {
57
+ constructor(message = "An invalid API response was returned", url, response) {
58
+ super(message);
59
+ this.url = url;
60
+ this.response = response;
61
+ }
62
+ }
63
+
64
+ const findRef = (refs, predicate) => {
65
+ const ref = refs.find((ref2) => predicate(ref2));
66
+ if (!ref) {
67
+ throw new PrismicError("Ref could not be found.", void 0, void 0);
68
+ }
69
+ return ref;
70
+ };
71
+
72
+ const findMasterRef = (refs) => {
73
+ return findRef(refs, (ref) => ref.isMasterRef);
74
+ };
75
+
76
+ const findRefByID = (refs, id) => {
77
+ return findRef(refs, (ref) => ref.id === id);
78
+ };
79
+
80
+ const findRefByLabel = (refs, label) => {
81
+ return findRef(refs, (ref) => ref.label === label);
82
+ };
83
+
55
84
  const readValue = (value) => {
56
85
  return value.replace(/%3B/g, ";");
57
86
  };
@@ -69,47 +98,12 @@ const parse = (cookieString) => {
69
98
  const getAll = (cookieStore) => parse(cookieStore);
70
99
  const getCookie = (name, cookieStore) => getAll(cookieStore)[name];
71
100
 
72
- const isForbiddenErrorAPIResponse = (input) => {
73
- return typeof input === "object" && input !== null && ("error" in input || "message" in input) && "oauth_initiate" in input && "oauth_token" in input;
74
- };
75
- class ForbiddenError extends Error {
76
- constructor(message, args) {
77
- super(message);
78
- this.url = args.url;
79
- this.oauth_initiate = args.response.oauth_initiate;
80
- this.oauth_token = args.response.oauth_token;
81
- }
82
- }
83
-
84
- const isParsingErrorAPIResponse = (input) => {
85
- return typeof input === "object" && input !== null && "message" in input && "type" in input;
86
- };
87
- class ParsingError extends Error {
88
- constructor(message, args) {
89
- super(message);
90
- this.url = args.url;
91
- this.line = args.response.line;
92
- this.column = args.response.column;
93
- this.id = args.response.id;
94
- this.location = args.response.location;
95
- }
101
+ class ForbiddenError extends PrismicError {
96
102
  }
97
103
 
98
- class PrismicError extends Error {
99
- constructor(message, args) {
100
- super(message || "An invalid API response was returned");
101
- this.url = args.url;
102
- this.response = args.response;
103
- }
104
+ class ParsingError extends PrismicError {
104
105
  }
105
106
 
106
- const preview = "io.prismic.preview";
107
-
108
- var cookie = /*#__PURE__*/Object.freeze({
109
- __proto__: null,
110
- preview: preview
111
- });
112
-
113
107
  const formatValue = (value) => {
114
108
  if (Array.isArray(value)) {
115
109
  return `[${value.map(formatValue).join(", ")}]`;
@@ -144,114 +138,69 @@ const argsPredicate = (name) => {
144
138
  };
145
139
  return fn;
146
140
  };
147
- const at = pathWithArgsPredicate("at");
148
- const not = pathWithArgsPredicate("not");
149
- const any = pathWithArgsPredicate("any");
150
- const _in = pathWithArgsPredicate("in");
151
- const fulltext = pathWithArgsPredicate("fulltext");
152
- const has = pathPredicate("has");
153
- const missing = pathPredicate("missing");
154
- const similar = argsPredicate("similar");
155
- const geopointNear = pathWithArgsPredicate("geopoint.near");
156
- const numberLessThan = pathWithArgsPredicate("number.lt");
157
- const numberGreaterThan = pathWithArgsPredicate("number.gt");
158
- const numberInRange = pathWithArgsPredicate("number.inRange");
159
- const dateAfter = pathWithArgsPredicate("date.after");
160
- const dateBefore = pathWithArgsPredicate("date.before");
161
- const dateBetween = pathWithArgsPredicate("date.between");
162
- const dateDayOfMonth = pathWithArgsPredicate("date.day-of-month");
163
- const dateDayOfMonthAfter = pathWithArgsPredicate("date.day-of-month-after");
164
- const dateDayOfMonthBefore = pathWithArgsPredicate("date.day-of-month-before");
165
- const dateDayOfWeek = pathWithArgsPredicate("date.day-of-week");
166
- const dateDayOfWeekAfter = pathWithArgsPredicate("date.day-of-week-after");
167
- const dateDayOfWeekBefore = pathWithArgsPredicate("date.day-of-week-before");
168
- const dateMonth = pathWithArgsPredicate("date.month");
169
- const dateMonthAfter = pathWithArgsPredicate("date.month-after");
170
- const dateMonthBefore = pathWithArgsPredicate("date.month-before");
171
- const dateYear = pathWithArgsPredicate("date.year");
172
- const dateHour = pathWithArgsPredicate("date.hour");
173
- const dateHourAfter = pathWithArgsPredicate("date.hour-after");
174
- const dateHourBefore = pathWithArgsPredicate("date.hour-before");
141
+ const predicate = {
142
+ at: pathWithArgsPredicate("at"),
143
+ not: pathWithArgsPredicate("not"),
144
+ any: pathWithArgsPredicate("any"),
145
+ in: pathWithArgsPredicate("in"),
146
+ fulltext: pathWithArgsPredicate("fulltext"),
147
+ has: pathPredicate("has"),
148
+ missing: pathPredicate("missing"),
149
+ similar: argsPredicate("similar"),
150
+ geopointNear: pathWithArgsPredicate("geopoint.near"),
151
+ numberLessThan: pathWithArgsPredicate("number.lt"),
152
+ numberGreaterThan: pathWithArgsPredicate("number.gt"),
153
+ numberInRange: pathWithArgsPredicate("number.inRange"),
154
+ dateAfter: pathWithArgsPredicate("date.after"),
155
+ dateBefore: pathWithArgsPredicate("date.before"),
156
+ dateBetween: pathWithArgsPredicate("date.between"),
157
+ dateDayOfMonth: pathWithArgsPredicate("date.day-of-month"),
158
+ dateDayOfMonthAfter: pathWithArgsPredicate("date.day-of-month-after"),
159
+ dateDayOfMonthBefore: pathWithArgsPredicate("date.day-of-month-before"),
160
+ dateDayOfWeek: pathWithArgsPredicate("date.day-of-week"),
161
+ dateDayOfWeekAfter: pathWithArgsPredicate("date.day-of-week-after"),
162
+ dateDayOfWeekBefore: pathWithArgsPredicate("date.day-of-week-before"),
163
+ dateMonth: pathWithArgsPredicate("date.month"),
164
+ dateMonthAfter: pathWithArgsPredicate("date.month-after"),
165
+ dateMonthBefore: pathWithArgsPredicate("date.month-before"),
166
+ dateYear: pathWithArgsPredicate("date.year"),
167
+ dateHour: pathWithArgsPredicate("date.hour"),
168
+ dateHourAfter: pathWithArgsPredicate("date.hour-after"),
169
+ dateHourBefore: pathWithArgsPredicate("date.hour-before")
170
+ };
171
+
172
+ const preview = "io.prismic.preview";
175
173
 
176
- var predicate = /*#__PURE__*/Object.freeze({
174
+ var cookie = /*#__PURE__*/Object.freeze({
177
175
  __proto__: null,
178
- at: at,
179
- not: not,
180
- any: any,
181
- 'in': _in,
182
- fulltext: fulltext,
183
- has: has,
184
- missing: missing,
185
- similar: similar,
186
- geopointNear: geopointNear,
187
- numberLessThan: numberLessThan,
188
- numberGreaterThan: numberGreaterThan,
189
- numberInRange: numberInRange,
190
- dateAfter: dateAfter,
191
- dateBefore: dateBefore,
192
- dateBetween: dateBetween,
193
- dateDayOfMonth: dateDayOfMonth,
194
- dateDayOfMonthAfter: dateDayOfMonthAfter,
195
- dateDayOfMonthBefore: dateDayOfMonthBefore,
196
- dateDayOfWeek: dateDayOfWeek,
197
- dateDayOfWeekAfter: dateDayOfWeekAfter,
198
- dateDayOfWeekBefore: dateDayOfWeekBefore,
199
- dateMonth: dateMonth,
200
- dateMonthAfter: dateMonthAfter,
201
- dateMonthBefore: dateMonthBefore,
202
- dateYear: dateYear,
203
- dateHour: dateHour,
204
- dateHourAfter: dateHourAfter,
205
- dateHourBefore: dateHourBefore
176
+ preview: preview
206
177
  });
207
178
 
208
- const createSimpleTTLCache = () => {
209
- const cache = new Map();
210
- return {
211
- get(key) {
212
- const cacheValue = cache.get(key);
213
- if (cacheValue) {
214
- if (new Date().getTime() < cacheValue.expiresAt) {
215
- return cacheValue.value;
216
- }
217
- }
218
- },
219
- set(key, value, ttl) {
220
- cache.set(key, { expiresAt: new Date().getTime() + ttl, value });
221
- }
222
- };
223
- };
224
179
  const MAX_PAGE_SIZE = 100;
225
180
  const REPOSITORY_CACHE_TTL = 5e3;
226
- var RefStateType;
227
- (function(RefStateType2) {
228
- RefStateType2[RefStateType2["Master"] = 0] = "Master";
229
- RefStateType2[RefStateType2["ReleaseByID"] = 1] = "ReleaseByID";
230
- RefStateType2[RefStateType2["ReleaseByLabel"] = 2] = "ReleaseByLabel";
231
- RefStateType2[RefStateType2["Manual"] = 3] = "Manual";
232
- })(RefStateType || (RefStateType = {}));
233
- const typePredicate = (documentType) => at("document.type", documentType);
234
- const tagsPredicate = (tags) => at("document.tags", tags);
235
- const findRef = (refs, predicate2) => {
236
- const ref = refs.find((ref2) => predicate2(ref2));
237
- if (!ref) {
238
- throw new Error("Ref could not be found.");
239
- }
240
- return ref;
241
- };
181
+ const GET_ALL_QUERY_DELAY = 500;
182
+ var RefStateMode;
183
+ (function(RefStateMode2) {
184
+ RefStateMode2["Master"] = "Master";
185
+ RefStateMode2["ReleaseID"] = "ReleaseID";
186
+ RefStateMode2["ReleaseLabel"] = "ReleaseLabel";
187
+ RefStateMode2["Manual"] = "Manual";
188
+ })(RefStateMode || (RefStateMode = {}));
189
+ const typePredicate = (documentType) => predicate.at("document.type", documentType);
190
+ const everyTagPredicate = (tags) => predicate.at("document.tags", tags);
191
+ const someTagsPredicate = (tags) => predicate.any("document.tags", tags);
242
192
  const createClient = (...args) => new Client(...args);
243
193
  class Client {
244
194
  constructor(endpoint, options = {}) {
245
- this.query = this.get.bind(this);
195
+ this.refState = {
196
+ mode: RefStateMode.Master,
197
+ autoPreviewsEnabled: true
198
+ };
199
+ this.cachedRepositoryExpiration = 0;
246
200
  this.endpoint = endpoint;
247
201
  this.accessToken = options.accessToken;
248
- this.integrationFieldsRef = options.integrationFieldsRef;
202
+ this.routes = options.routes;
249
203
  this.defaultParams = options.defaultParams;
250
- this.internalCache = createSimpleTTLCache();
251
- this.refMode = {
252
- type: 0,
253
- autoPreviewsEnabled: true
254
- };
255
204
  if (options.ref) {
256
205
  this.queryContentFromRef(options.ref);
257
206
  }
@@ -260,79 +209,110 @@ class Client {
260
209
  } else if (typeof globalThis.fetch === "function") {
261
210
  this.fetchFn = globalThis.fetch;
262
211
  } else {
263
- throw new Error("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.");
212
+ throw new 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);
264
213
  }
265
214
  if (this.fetchFn === globalThis.fetch) {
266
215
  this.fetchFn = this.fetchFn.bind(globalThis);
267
216
  }
268
217
  }
269
218
  enableAutoPreviews() {
270
- this.refMode.autoPreviewsEnabled = true;
219
+ this.refState.autoPreviewsEnabled = true;
271
220
  }
272
221
  enableAutoPreviewsFromReq(req) {
273
- this.refMode.httpRequest = req;
274
- this.refMode.autoPreviewsEnabled = true;
222
+ this.refState.httpRequest = req;
223
+ this.refState.autoPreviewsEnabled = true;
275
224
  }
276
225
  disableAutoPreviews() {
277
- this.refMode.autoPreviewsEnabled = false;
226
+ this.refState.autoPreviewsEnabled = false;
227
+ }
228
+ async query(predicates, params) {
229
+ const url = await this.buildQueryURL({ ...params, predicates });
230
+ return await this.fetch(url, params);
278
231
  }
279
232
  async get(params) {
280
233
  const url = await this.buildQueryURL(params);
281
- return await this.fetch(url);
234
+ return await this.fetch(url, params);
282
235
  }
283
236
  async getFirst(params) {
284
- const result = await this.get(params);
237
+ const url = await this.buildQueryURL(params);
238
+ const result = await this.fetch(url, params);
285
239
  const firstResult = result.results[0];
286
240
  if (firstResult) {
287
241
  return firstResult;
288
242
  }
289
- throw new Error("No documents were returned");
243
+ throw new PrismicError("No documents were returned", url, void 0);
290
244
  }
291
- async getAll(params = {}) {
245
+ async dangerouslyGetAll(params = {}) {
292
246
  const { limit = Infinity, ...actualParams } = params;
293
- const resolvedParams = { pageSize: MAX_PAGE_SIZE, ...actualParams };
294
- const result = await this.get(resolvedParams);
295
- let page = result.page;
296
- let documents = result.results;
297
- while (page < result.total_pages && documents.length < limit) {
298
- page += 1;
299
- const result2 = await this.get({ ...resolvedParams, page });
300
- documents = [...documents, ...result2.results];
247
+ const resolvedParams = {
248
+ ...actualParams,
249
+ pageSize: actualParams.pageSize || MAX_PAGE_SIZE
250
+ };
251
+ const documents = [];
252
+ let latestResult;
253
+ while ((!latestResult || latestResult.next_page) && documents.length < limit) {
254
+ const page = latestResult ? latestResult.page + 1 : void 0;
255
+ latestResult = await this.get({ ...resolvedParams, page });
256
+ documents.push(...latestResult.results);
257
+ if (latestResult.next_page) {
258
+ await new Promise((res) => setTimeout(res, GET_ALL_QUERY_DELAY));
259
+ }
301
260
  }
302
261
  return documents.slice(0, limit);
303
262
  }
304
263
  async getByID(id, params) {
305
- return await this.getFirst(appendPredicates(at("document.id", id))(params));
264
+ return await this.getFirst(appendPredicates(params, predicate.at("document.id", id)));
306
265
  }
307
266
  async getByIDs(ids, params) {
308
- return await this.get(appendPredicates(_in("document.id", ids))(params));
267
+ return await this.get(appendPredicates(params, predicate.in("document.id", ids)));
309
268
  }
310
269
  async getAllByIDs(ids, params) {
311
- return await this.getAll(appendPredicates(_in("document.id", ids))(params));
270
+ return await this.dangerouslyGetAll(appendPredicates(params, predicate.in("document.id", ids)));
312
271
  }
313
272
  async getByUID(documentType, uid, params) {
314
- return await this.getFirst(appendPredicates(typePredicate(documentType), at(`my.${documentType}.uid`, uid))(params));
273
+ return await this.getFirst(appendPredicates(params, [
274
+ typePredicate(documentType),
275
+ predicate.at(`my.${documentType}.uid`, uid)
276
+ ]));
277
+ }
278
+ async getByUIDs(documentType, uids, params) {
279
+ return await this.get(appendPredicates(params, [
280
+ typePredicate(documentType),
281
+ predicate.in(`my.${documentType}.uid`, uids)
282
+ ]));
283
+ }
284
+ async getAllByUIDs(documentType, uids, params) {
285
+ return await this.dangerouslyGetAll(appendPredicates(params, [
286
+ typePredicate(documentType),
287
+ predicate.in(`my.${documentType}.uid`, uids)
288
+ ]));
315
289
  }
316
290
  async getSingle(documentType, params) {
317
- return await this.getFirst(appendPredicates(typePredicate(documentType))(params));
291
+ return await this.getFirst(appendPredicates(params, typePredicate(documentType)));
318
292
  }
319
293
  async getByType(documentType, params) {
320
- return await this.get(appendPredicates(typePredicate(documentType))(params));
294
+ return await this.get(appendPredicates(params, typePredicate(documentType)));
321
295
  }
322
296
  async getAllByType(documentType, params) {
323
- return await this.getAll(appendPredicates(typePredicate(documentType))(params));
297
+ return await this.dangerouslyGetAll(appendPredicates(params, typePredicate(documentType)));
324
298
  }
325
299
  async getByTag(tag, params) {
326
- return await this.get(appendPredicates(tagsPredicate(tag))(params));
300
+ return await this.get(appendPredicates(params, everyTagPredicate(tag)));
327
301
  }
328
302
  async getAllByTag(tag, params) {
329
- return await this.getAll(appendPredicates(tagsPredicate(tag))(params));
303
+ return await this.dangerouslyGetAll(appendPredicates(params, everyTagPredicate(tag)));
304
+ }
305
+ async getByEveryTag(tags, params) {
306
+ return await this.get(appendPredicates(params, everyTagPredicate(tags)));
330
307
  }
331
- async getByTags(tags, params) {
332
- return await this.get(appendPredicates(tagsPredicate(tags))(params));
308
+ async getAllByEveryTag(tags, params) {
309
+ return await this.dangerouslyGetAll(appendPredicates(params, everyTagPredicate(tags)));
333
310
  }
334
- async getAllByTags(tags, params) {
335
- return await this.getAll(appendPredicates(tagsPredicate(tags))(params));
311
+ async getBySomeTags(tags, params) {
312
+ return await this.get(appendPredicates(params, someTagsPredicate(tags)));
313
+ }
314
+ async getAllBySomeTags(tags, params) {
315
+ return await this.dangerouslyGetAll(appendPredicates(params, someTagsPredicate(tags)));
336
316
  }
337
317
  async getRepository() {
338
318
  const url = new URL(this.endpoint);
@@ -342,20 +322,20 @@ class Client {
342
322
  return await this.fetch(url.toString());
343
323
  }
344
324
  async getRefs() {
345
- const res = await this.getRepository();
346
- return res.refs;
325
+ const repository = await this.getRepository();
326
+ return repository.refs;
347
327
  }
348
- async getRefById(id) {
328
+ async getRefByID(id) {
349
329
  const refs = await this.getRefs();
350
- return findRef(refs, (ref) => ref.id === id);
330
+ return findRefByID(refs, id);
351
331
  }
352
332
  async getRefByLabel(label) {
353
333
  const refs = await this.getRefs();
354
- return findRef(refs, (ref) => ref.label === label);
334
+ return findRefByLabel(refs, label);
355
335
  }
356
336
  async getMasterRef() {
357
337
  const refs = await this.getRefs();
358
- return findRef(refs, (ref) => ref.isMasterRef);
338
+ return findMasterRef(refs);
359
339
  }
360
340
  async getReleases() {
361
341
  const refs = await this.getRefs();
@@ -363,195 +343,143 @@ class Client {
363
343
  }
364
344
  async getReleaseByID(id) {
365
345
  const releases = await this.getReleases();
366
- return findRef(releases, (ref) => ref.id === id);
346
+ return findRefByID(releases, id);
367
347
  }
368
348
  async getReleaseByLabel(label) {
369
349
  const releases = await this.getReleases();
370
- return findRef(releases, (ref) => ref.label === label);
350
+ return findRefByLabel(releases, label);
371
351
  }
372
352
  async getTags() {
373
353
  try {
374
354
  const tagsForm = await this.getCachedRepositoryForm("tags");
375
355
  return await this.fetch(tagsForm.action);
376
356
  } catch (e) {
377
- const res = await this.getRepository();
378
- return res.tags;
357
+ const repository = await this.getRepository();
358
+ return repository.tags;
379
359
  }
380
360
  }
381
361
  async buildQueryURL(params = {}) {
382
- const {
383
- ref = await this.getResolvedRefString(),
384
- integrationFieldsRef = await this.getResolvedIntegrationFieldsRef(),
385
- accessToken = this.accessToken,
386
- ...actualParams
387
- } = params;
362
+ const ref = params.ref || await this.getResolvedRefString();
363
+ const integrationFieldsRef = params.integrationFieldsRef || (await this.getCachedRepository()).integrationFieldsRef || void 0;
388
364
  return buildQueryURL(this.endpoint, {
389
365
  ...this.defaultParams,
390
- ...actualParams,
391
- accessToken,
366
+ ...params,
392
367
  ref,
393
- integrationFieldsRef
368
+ integrationFieldsRef,
369
+ routes: params.routes || this.routes,
370
+ accessToken: params.accessToken || this.accessToken
394
371
  });
395
372
  }
396
373
  async resolvePreviewURL(args) {
397
374
  var _a;
398
- let documentId = args.documentId;
375
+ let documentID = args.documentID;
399
376
  let previewToken = args.previewToken;
400
377
  if (typeof globalThis.location !== "undefined") {
401
378
  const searchParams = new URLSearchParams(globalThis.location.search);
402
- documentId = documentId || searchParams.get("documentId") || void 0;
379
+ documentID = documentID || searchParams.get("documentId") || void 0;
403
380
  previewToken = previewToken || searchParams.get("token") || void 0;
404
- } else if ((_a = this.refMode.httpRequest) == null ? void 0 : _a.query) {
405
- if (typeof this.refMode.httpRequest.query.documentId === "string") {
406
- documentId = documentId || this.refMode.httpRequest.query.documentId;
407
- }
408
- if (typeof this.refMode.httpRequest.query.token === "string") {
409
- previewToken = previewToken || this.refMode.httpRequest.query.token;
410
- }
381
+ } else if ((_a = this.refState.httpRequest) == null ? void 0 : _a.query) {
382
+ documentID = documentID || this.refState.httpRequest.query.documentId;
383
+ previewToken = previewToken || this.refState.httpRequest.query.token;
411
384
  }
412
- if (documentId != null) {
413
- const document = await this.getByID(documentId, {
385
+ if (documentID != null) {
386
+ const document = await this.getByID(documentID, {
414
387
  ref: previewToken
415
388
  });
416
- return prismicH.asLink(prismicH.documentToLinkField(document), args.linkResolver);
389
+ return prismicH.asLink(document, args.linkResolver);
417
390
  } else {
418
391
  return args.defaultURL;
419
392
  }
420
393
  }
421
394
  queryLatestContent() {
422
- this.refMode = {
423
- ...this.refMode,
424
- type: 0
425
- };
395
+ this.refState.mode = RefStateMode.Master;
426
396
  }
427
- queryContentFromReleaseByID(releaseId) {
428
- this.refMode = {
429
- ...this.refMode,
430
- type: 1,
431
- payload: { releaseId }
397
+ queryContentFromReleaseByID(releaseID) {
398
+ this.refState = {
399
+ ...this.refState,
400
+ mode: RefStateMode.ReleaseID,
401
+ releaseID
432
402
  };
433
403
  }
434
404
  queryContentFromReleaseByLabel(releaseLabel) {
435
- this.refMode = {
436
- ...this.refMode,
437
- type: 2,
438
- payload: { releaseLabel }
405
+ this.refState = {
406
+ ...this.refState,
407
+ mode: RefStateMode.ReleaseLabel,
408
+ releaseLabel
439
409
  };
440
410
  }
441
411
  queryContentFromRef(ref) {
442
- this.refMode = {
443
- ...this.refMode,
444
- type: 3,
445
- payload: { refStringOrFn: ref }
412
+ this.refState = {
413
+ ...this.refState,
414
+ mode: RefStateMode.Manual,
415
+ ref
446
416
  };
447
417
  }
448
418
  async getCachedRepository() {
449
- const cacheKey = this.endpoint;
450
- const cachedRepository = this.internalCache.get(cacheKey);
451
- if (cachedRepository) {
452
- return cachedRepository;
419
+ if (!this.cachedRepository || Date.now() >= this.cachedRepositoryExpiration) {
420
+ this.cachedRepositoryExpiration = Date.now() + REPOSITORY_CACHE_TTL;
421
+ this.cachedRepository = await this.getRepository();
453
422
  }
454
- const repository = await this.getRepository();
455
- this.internalCache.set(cacheKey, repository, REPOSITORY_CACHE_TTL);
456
- return repository;
423
+ return this.cachedRepository;
457
424
  }
458
425
  async getCachedRepositoryForm(name) {
459
426
  const cachedRepository = await this.getCachedRepository();
460
427
  const form = cachedRepository.forms[name];
461
428
  if (!form) {
462
- throw new Error(`Form with name "${name}" could not be found`);
429
+ throw new PrismicError(`Form with name "${name}" could not be found`, void 0, void 0);
463
430
  }
464
431
  return form;
465
432
  }
466
- getPreviewRefString() {
467
- var _a, _b, _c;
468
- if ((_a = globalThis.document) == null ? void 0 : _a.cookie) {
469
- return getCookie(preview, globalThis.document.cookie);
470
- } else if ((_c = (_b = this.refMode.httpRequest) == null ? void 0 : _b.headers) == null ? void 0 : _c.cookie) {
471
- return getCookie(preview, this.refMode.httpRequest.headers.cookie);
472
- }
473
- }
474
- async getIntegrationFieldsRef() {
475
- const repository = await this.getCachedRepository();
476
- return repository.integrationFieldsRef || void 0;
477
- }
478
- async getResolvedIntegrationFieldsRef() {
479
- const thisIntegrationFieldsRefThunk = castThunk(this.integrationFieldsRef);
480
- const res = await thisIntegrationFieldsRefThunk();
481
- if (typeof res === "string") {
482
- return res;
483
- } else {
484
- return await this.getIntegrationFieldsRef();
485
- }
486
- }
487
433
  async getResolvedRefString() {
488
- if (this.refMode.autoPreviewsEnabled) {
489
- const previewRef = this.getPreviewRefString();
434
+ var _a, _b, _c;
435
+ if (this.refState.autoPreviewsEnabled) {
436
+ let previewRef = void 0;
437
+ if ((_a = globalThis.document) == null ? void 0 : _a.cookie) {
438
+ previewRef = getCookie(preview, globalThis.document.cookie);
439
+ } else if ((_c = (_b = this.refState.httpRequest) == null ? void 0 : _b.headers) == null ? void 0 : _c.cookie) {
440
+ previewRef = getCookie(preview, this.refState.httpRequest.headers.cookie);
441
+ }
490
442
  if (previewRef) {
491
443
  return previewRef;
492
444
  }
493
445
  }
494
- switch (this.refMode.type) {
495
- case 1: {
496
- const releaseId = this.refMode.payload.releaseId;
497
- const repository = await this.getCachedRepository();
498
- const ref = findRef(repository.refs, (ref2) => ref2.id === releaseId);
499
- return ref.ref;
500
- }
501
- case 2: {
502
- const releaseLabel = this.refMode.payload.releaseLabel;
503
- const repository = await this.getCachedRepository();
504
- const ref = findRef(repository.refs, (ref2) => ref2.label === releaseLabel);
505
- return ref.ref;
506
- }
507
- case 3: {
508
- const thisRefThunk = castThunk(this.refMode.payload.refStringOrFn);
509
- const res = await thisRefThunk();
510
- if (typeof res === "string") {
511
- return res;
512
- }
513
- }
514
- case 0:
515
- default: {
516
- const repository = await this.getCachedRepository();
517
- const ref = findRef(repository.refs, (ref2) => ref2.isMasterRef);
518
- return ref.ref;
446
+ const cachedRepository = await this.getCachedRepository();
447
+ const refModeType = this.refState.mode;
448
+ if (refModeType === RefStateMode.ReleaseID) {
449
+ return findRefByID(cachedRepository.refs, this.refState.releaseID).ref;
450
+ } else if (refModeType === RefStateMode.ReleaseLabel) {
451
+ return findRefByLabel(cachedRepository.refs, this.refState.releaseLabel).ref;
452
+ } else if (refModeType === RefStateMode.Manual) {
453
+ const res = await castThunk(this.refState.ref)();
454
+ if (typeof res === "string") {
455
+ return res;
519
456
  }
520
457
  }
458
+ return findMasterRef(cachedRepository.refs).ref;
521
459
  }
522
- async fetch(url) {
460
+ async fetch(url, _params) {
523
461
  const res = await this.fetchFn(url);
524
462
  let json;
525
463
  try {
526
464
  json = await res.json();
527
465
  } catch (e) {
528
- throw new PrismicError(void 0, { url });
466
+ throw new PrismicError(void 0, url, void 0);
529
467
  }
530
468
  switch (res.status) {
531
469
  case 200: {
532
470
  return json;
533
471
  }
534
472
  case 400: {
535
- if (isParsingErrorAPIResponse(json)) {
536
- throw new ParsingError(json.message, {
537
- url,
538
- response: json
539
- });
540
- }
541
- break;
473
+ throw new ParsingError(json.message, url, json);
542
474
  }
543
475
  case 401:
544
476
  case 403: {
545
- if (isForbiddenErrorAPIResponse(json)) {
546
- throw new ForbiddenError("error" in json ? json.error : json.message, {
547
- url,
548
- response: json
549
- });
550
- }
477
+ throw new ForbiddenError("error" in json ? json.error : json.message, url, json);
551
478
  }
552
479
  }
553
- throw new PrismicError(void 0, { url, response: json });
480
+ throw new PrismicError(void 0, url, json);
554
481
  }
555
482
  }
556
483
 
557
484
  export { Client, ForbiddenError, ParsingError, PrismicError, buildQueryURL, cookie, createClient, getEndpoint, predicate };
485
+ //# sourceMappingURL=index.mjs.map