@prismicio/client 6.0.0-beta.0 → 6.0.0-beta.1

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,115 +138,68 @@ 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
+ var RefStateMode;
182
+ (function(RefStateMode2) {
183
+ RefStateMode2["Master"] = "Master";
184
+ RefStateMode2["ReleaseID"] = "ReleaseID";
185
+ RefStateMode2["ReleaseLabel"] = "ReleaseLabel";
186
+ RefStateMode2["Manual"] = "Manual";
187
+ })(RefStateMode || (RefStateMode = {}));
188
+ const typePredicate = (documentType) => predicate.at("document.type", documentType);
189
+ const everyTagPredicate = (tags) => predicate.at("document.tags", tags);
190
+ const someTagsPredicate = (tags) => predicate.any("document.tags", tags);
242
191
  const createClient = (...args) => new Client(...args);
243
192
  class Client {
244
193
  constructor(endpoint, options = {}) {
245
- this.query = this.get.bind(this);
194
+ this.refState = {
195
+ mode: RefStateMode.Master,
196
+ autoPreviewsEnabled: true
197
+ };
198
+ this.cachedRepositoryExpiration = 0;
246
199
  this.endpoint = endpoint;
247
200
  this.accessToken = options.accessToken;
248
- this.integrationFieldsRef = options.integrationFieldsRef;
249
201
  this.routes = options.routes;
250
202
  this.defaultParams = options.defaultParams;
251
- this.internalCache = createSimpleTTLCache();
252
- this.refMode = {
253
- type: 0,
254
- autoPreviewsEnabled: true
255
- };
256
203
  if (options.ref) {
257
204
  this.queryContentFromRef(options.ref);
258
205
  }
@@ -261,37 +208,45 @@ class Client {
261
208
  } else if (typeof globalThis.fetch === "function") {
262
209
  this.fetchFn = globalThis.fetch;
263
210
  } else {
264
- 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.");
211
+ 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);
265
212
  }
266
213
  if (this.fetchFn === globalThis.fetch) {
267
214
  this.fetchFn = this.fetchFn.bind(globalThis);
268
215
  }
269
216
  }
270
217
  enableAutoPreviews() {
271
- this.refMode.autoPreviewsEnabled = true;
218
+ this.refState.autoPreviewsEnabled = true;
272
219
  }
273
220
  enableAutoPreviewsFromReq(req) {
274
- this.refMode.httpRequest = req;
275
- this.refMode.autoPreviewsEnabled = true;
221
+ this.refState.httpRequest = req;
222
+ this.refState.autoPreviewsEnabled = true;
276
223
  }
277
224
  disableAutoPreviews() {
278
- this.refMode.autoPreviewsEnabled = false;
225
+ this.refState.autoPreviewsEnabled = false;
226
+ }
227
+ async query(predicates, params) {
228
+ const url = await this.buildQueryURL({ ...params, predicates });
229
+ return await this.fetch(url, params);
279
230
  }
280
231
  async get(params) {
281
232
  const url = await this.buildQueryURL(params);
282
- return await this.fetch(url);
233
+ return await this.fetch(url, params);
283
234
  }
284
235
  async getFirst(params) {
285
- const result = await this.get(params);
236
+ const url = await this.buildQueryURL(params);
237
+ const result = await this.fetch(url, params);
286
238
  const firstResult = result.results[0];
287
239
  if (firstResult) {
288
240
  return firstResult;
289
241
  }
290
- throw new Error("No documents were returned");
242
+ throw new PrismicError("No documents were returned", url, void 0);
291
243
  }
292
244
  async getAll(params = {}) {
293
245
  const { limit = Infinity, ...actualParams } = params;
294
- const resolvedParams = { pageSize: MAX_PAGE_SIZE, ...actualParams };
246
+ const resolvedParams = {
247
+ ...actualParams,
248
+ pageSize: actualParams.pageSize || MAX_PAGE_SIZE
249
+ };
295
250
  const result = await this.get(resolvedParams);
296
251
  let page = result.page;
297
252
  let documents = result.results;
@@ -303,66 +258,77 @@ class Client {
303
258
  return documents.slice(0, limit);
304
259
  }
305
260
  async getByID(id, params) {
306
- return await this.getFirst(appendPredicates(at("document.id", id))(params));
261
+ return await this.getFirst(appendPredicates(params, predicate.at("document.id", id)));
307
262
  }
308
263
  async getByIDs(ids, params) {
309
- return await this.get(appendPredicates(_in("document.id", ids))(params));
264
+ return await this.get(appendPredicates(params, predicate.in("document.id", ids)));
310
265
  }
311
266
  async getAllByIDs(ids, params) {
312
- return await this.getAll(appendPredicates(_in("document.id", ids))(params));
267
+ return await this.getAll(appendPredicates(params, predicate.in("document.id", ids)));
313
268
  }
314
269
  async getByUID(documentType, uid, params) {
315
- return await this.getFirst(appendPredicates(typePredicate(documentType), at(`my.${documentType}.uid`, uid))(params));
270
+ return await this.getFirst(appendPredicates(params, [
271
+ typePredicate(documentType),
272
+ predicate.at(`my.${documentType}.uid`, uid)
273
+ ]));
316
274
  }
317
275
  async getByUIDs(documentType, uids, params) {
318
- return await this.get(appendPredicates(typePredicate(documentType), _in(`my.${documentType}.uid`, uids))(params));
276
+ return await this.get(appendPredicates(params, [
277
+ typePredicate(documentType),
278
+ predicate.in(`my.${documentType}.uid`, uids)
279
+ ]));
319
280
  }
320
281
  async getAllByUIDs(documentType, uids, params) {
321
- return await this.getAll(appendPredicates(typePredicate(documentType), _in(`my.${documentType}.uid`, uids))(params));
282
+ return await this.getAll(appendPredicates(params, [
283
+ typePredicate(documentType),
284
+ predicate.in(`my.${documentType}.uid`, uids)
285
+ ]));
322
286
  }
323
287
  async getSingle(documentType, params) {
324
- return await this.getFirst(appendPredicates(typePredicate(documentType))(params));
288
+ return await this.getFirst(appendPredicates(params, typePredicate(documentType)));
325
289
  }
326
290
  async getByType(documentType, params) {
327
- return await this.get(appendPredicates(typePredicate(documentType))(params));
291
+ return await this.get(appendPredicates(params, typePredicate(documentType)));
328
292
  }
329
293
  async getAllByType(documentType, params) {
330
- return await this.getAll(appendPredicates(typePredicate(documentType))(params));
294
+ return await this.getAll(appendPredicates(params, typePredicate(documentType)));
331
295
  }
332
296
  async getByTag(tag, params) {
333
- return await this.get(appendPredicates(tagsPredicate(tag))(params));
297
+ return await this.get(appendPredicates(params, everyTagPredicate(tag)));
334
298
  }
335
299
  async getAllByTag(tag, params) {
336
- return await this.getAll(appendPredicates(tagsPredicate(tag))(params));
300
+ return await this.getAll(appendPredicates(params, everyTagPredicate(tag)));
301
+ }
302
+ async getByEveryTag(tags, params) {
303
+ return await this.get(appendPredicates(params, everyTagPredicate(tags)));
304
+ }
305
+ async getAllByEveryTag(tags, params) {
306
+ return await this.getAll(appendPredicates(params, everyTagPredicate(tags)));
337
307
  }
338
- async getByTags(tags, params) {
339
- return await this.get(appendPredicates(tagsPredicate(tags))(params));
308
+ async getBySomeTags(tags, params) {
309
+ return await this.get(appendPredicates(params, someTagsPredicate(tags)));
340
310
  }
341
- async getAllByTags(tags, params) {
342
- return await this.getAll(appendPredicates(tagsPredicate(tags))(params));
311
+ async getAllBySomeTags(tags, params) {
312
+ return await this.getAll(appendPredicates(params, someTagsPredicate(tags)));
343
313
  }
344
314
  async getRepository() {
345
- const url = new URL(this.endpoint);
346
- if (this.accessToken) {
347
- url.searchParams.set("access_token", this.accessToken);
348
- }
349
- return await this.fetch(url.toString());
315
+ return await this.fetch(this.endpoint);
350
316
  }
351
317
  async getRefs() {
352
- const res = await this.getRepository();
353
- return res.refs;
318
+ const repository = await this.getRepository();
319
+ return repository.refs;
354
320
  }
355
321
  async getRefByID(id) {
356
322
  const refs = await this.getRefs();
357
- return findRef(refs, (ref) => ref.id === id);
323
+ return findRefByID(refs, id);
358
324
  }
359
325
  async getRefByLabel(label) {
360
326
  const refs = await this.getRefs();
361
- return findRef(refs, (ref) => ref.label === label);
327
+ return findRefByLabel(refs, label);
362
328
  }
363
329
  async getMasterRef() {
364
330
  const refs = await this.getRefs();
365
- return findRef(refs, (ref) => ref.isMasterRef);
331
+ return findMasterRef(refs);
366
332
  }
367
333
  async getReleases() {
368
334
  const refs = await this.getRefs();
@@ -370,36 +336,31 @@ class Client {
370
336
  }
371
337
  async getReleaseByID(id) {
372
338
  const releases = await this.getReleases();
373
- return findRef(releases, (ref) => ref.id === id);
339
+ return findRefByID(releases, id);
374
340
  }
375
341
  async getReleaseByLabel(label) {
376
342
  const releases = await this.getReleases();
377
- return findRef(releases, (ref) => ref.label === label);
343
+ return findRefByLabel(releases, label);
378
344
  }
379
345
  async getTags() {
380
346
  try {
381
347
  const tagsForm = await this.getCachedRepositoryForm("tags");
382
348
  return await this.fetch(tagsForm.action);
383
349
  } catch (e) {
384
- const res = await this.getRepository();
385
- return res.tags;
350
+ const repository = await this.getRepository();
351
+ return repository.tags;
386
352
  }
387
353
  }
388
354
  async buildQueryURL(params = {}) {
389
- const {
390
- ref = await this.getResolvedRefString(),
391
- integrationFieldsRef = await this.getResolvedIntegrationFieldsRef(),
392
- accessToken = this.accessToken,
393
- routes = this.routes,
394
- ...actualParams
395
- } = params;
355
+ const ref = params.ref || await this.getResolvedRefString();
356
+ const integrationFieldsRef = params.integrationFieldsRef || (await this.getCachedRepository()).integrationFieldsRef || void 0;
396
357
  return buildQueryURL(this.endpoint, {
397
358
  ...this.defaultParams,
398
- ...actualParams,
399
- accessToken,
359
+ ...params,
400
360
  ref,
401
361
  integrationFieldsRef,
402
- routes
362
+ routes: params.routes || this.routes,
363
+ accessToken: void 0
403
364
  });
404
365
  }
405
366
  async resolvePreviewURL(args) {
@@ -410,156 +371,108 @@ class Client {
410
371
  const searchParams = new URLSearchParams(globalThis.location.search);
411
372
  documentID = documentID || searchParams.get("documentId") || void 0;
412
373
  previewToken = previewToken || searchParams.get("token") || void 0;
413
- } else if ((_a = this.refMode.httpRequest) == null ? void 0 : _a.query) {
414
- if (typeof this.refMode.httpRequest.query.documentId === "string") {
415
- documentID = documentID || this.refMode.httpRequest.query.documentId;
416
- }
417
- if (typeof this.refMode.httpRequest.query.token === "string") {
418
- previewToken = previewToken || this.refMode.httpRequest.query.token;
419
- }
374
+ } else if ((_a = this.refState.httpRequest) == null ? void 0 : _a.query) {
375
+ documentID = documentID || this.refState.httpRequest.query.documentId;
376
+ previewToken = previewToken || this.refState.httpRequest.query.token;
420
377
  }
421
378
  if (documentID != null) {
422
379
  const document = await this.getByID(documentID, {
423
380
  ref: previewToken
424
381
  });
425
- return prismicH.asLink(prismicH.documentToLinkField(document), args.linkResolver);
382
+ return prismicH.asLink(document, args.linkResolver);
426
383
  } else {
427
384
  return args.defaultURL;
428
385
  }
429
386
  }
430
387
  queryLatestContent() {
431
- this.refMode = {
432
- ...this.refMode,
433
- type: 0
434
- };
388
+ this.refState.mode = RefStateMode.Master;
435
389
  }
436
390
  queryContentFromReleaseByID(releaseID) {
437
- this.refMode = {
438
- ...this.refMode,
439
- type: 1,
440
- payload: { releaseID }
391
+ this.refState = {
392
+ ...this.refState,
393
+ mode: RefStateMode.ReleaseID,
394
+ releaseID
441
395
  };
442
396
  }
443
397
  queryContentFromReleaseByLabel(releaseLabel) {
444
- this.refMode = {
445
- ...this.refMode,
446
- type: 2,
447
- payload: { releaseLabel }
398
+ this.refState = {
399
+ ...this.refState,
400
+ mode: RefStateMode.ReleaseLabel,
401
+ releaseLabel
448
402
  };
449
403
  }
450
404
  queryContentFromRef(ref) {
451
- this.refMode = {
452
- ...this.refMode,
453
- type: 3,
454
- payload: { refStringOrFn: ref }
405
+ this.refState = {
406
+ ...this.refState,
407
+ mode: RefStateMode.Manual,
408
+ ref
455
409
  };
456
410
  }
457
411
  async getCachedRepository() {
458
- const cacheKey = this.endpoint;
459
- const cachedRepository = this.internalCache.get(cacheKey);
460
- if (cachedRepository) {
461
- return cachedRepository;
412
+ if (!this.cachedRepository || Date.now() >= this.cachedRepositoryExpiration) {
413
+ this.cachedRepositoryExpiration = Date.now() + REPOSITORY_CACHE_TTL;
414
+ this.cachedRepository = await this.getRepository();
462
415
  }
463
- const repository = await this.getRepository();
464
- this.internalCache.set(cacheKey, repository, REPOSITORY_CACHE_TTL);
465
- return repository;
416
+ return this.cachedRepository;
466
417
  }
467
418
  async getCachedRepositoryForm(name) {
468
419
  const cachedRepository = await this.getCachedRepository();
469
420
  const form = cachedRepository.forms[name];
470
421
  if (!form) {
471
- throw new Error(`Form with name "${name}" could not be found`);
422
+ throw new PrismicError(`Form with name "${name}" could not be found`, void 0, void 0);
472
423
  }
473
424
  return form;
474
425
  }
475
- getPreviewRefString() {
476
- var _a, _b, _c;
477
- if ((_a = globalThis.document) == null ? void 0 : _a.cookie) {
478
- return getCookie(preview, globalThis.document.cookie);
479
- } else if ((_c = (_b = this.refMode.httpRequest) == null ? void 0 : _b.headers) == null ? void 0 : _c.cookie) {
480
- return getCookie(preview, this.refMode.httpRequest.headers.cookie);
481
- }
482
- }
483
- async getIntegrationFieldsRef() {
484
- const repository = await this.getCachedRepository();
485
- return repository.integrationFieldsRef || void 0;
486
- }
487
- async getResolvedIntegrationFieldsRef() {
488
- const thisIntegrationFieldsRefThunk = castThunk(this.integrationFieldsRef);
489
- const res = await thisIntegrationFieldsRefThunk();
490
- if (typeof res === "string") {
491
- return res;
492
- } else {
493
- return await this.getIntegrationFieldsRef();
494
- }
495
- }
496
426
  async getResolvedRefString() {
497
- if (this.refMode.autoPreviewsEnabled) {
498
- const previewRef = this.getPreviewRefString();
427
+ var _a, _b, _c;
428
+ if (this.refState.autoPreviewsEnabled) {
429
+ let previewRef = void 0;
430
+ if ((_a = globalThis.document) == null ? void 0 : _a.cookie) {
431
+ previewRef = getCookie(preview, globalThis.document.cookie);
432
+ } else if ((_c = (_b = this.refState.httpRequest) == null ? void 0 : _b.headers) == null ? void 0 : _c.cookie) {
433
+ previewRef = getCookie(preview, this.refState.httpRequest.headers.cookie);
434
+ }
499
435
  if (previewRef) {
500
436
  return previewRef;
501
437
  }
502
438
  }
503
- switch (this.refMode.type) {
504
- case 1: {
505
- const releaseID = this.refMode.payload.releaseID;
506
- const repository = await this.getCachedRepository();
507
- const ref = findRef(repository.refs, (ref2) => ref2.id === releaseID);
508
- return ref.ref;
509
- }
510
- case 2: {
511
- const releaseLabel = this.refMode.payload.releaseLabel;
512
- const repository = await this.getCachedRepository();
513
- const ref = findRef(repository.refs, (ref2) => ref2.label === releaseLabel);
514
- return ref.ref;
515
- }
516
- case 3: {
517
- const thisRefThunk = castThunk(this.refMode.payload.refStringOrFn);
518
- const res = await thisRefThunk();
519
- if (typeof res === "string") {
520
- return res;
521
- }
522
- }
523
- case 0:
524
- default: {
525
- const repository = await this.getCachedRepository();
526
- const ref = findRef(repository.refs, (ref2) => ref2.isMasterRef);
527
- return ref.ref;
439
+ const cachedRepository = await this.getCachedRepository();
440
+ const refModeType = this.refState.mode;
441
+ if (refModeType === RefStateMode.ReleaseID) {
442
+ return findRefByID(cachedRepository.refs, this.refState.releaseID).ref;
443
+ } else if (refModeType === RefStateMode.ReleaseLabel) {
444
+ return findRefByLabel(cachedRepository.refs, this.refState.releaseLabel).ref;
445
+ } else if (refModeType === RefStateMode.Manual) {
446
+ const res = await castThunk(this.refState.ref)();
447
+ if (typeof res === "string") {
448
+ return res;
528
449
  }
529
450
  }
451
+ return findMasterRef(cachedRepository.refs).ref;
530
452
  }
531
- async fetch(url) {
532
- const res = await this.fetchFn(url);
453
+ async fetch(url, params) {
454
+ const accessToken = params && params.accessToken || this.accessToken;
455
+ const options = accessToken ? { headers: { Authorization: `Token ${accessToken}` } } : {};
456
+ const res = await this.fetchFn(url, options);
533
457
  let json;
534
458
  try {
535
459
  json = await res.json();
536
460
  } catch (e) {
537
- throw new PrismicError(void 0, { url });
461
+ throw new PrismicError(void 0, url, void 0);
538
462
  }
539
463
  switch (res.status) {
540
464
  case 200: {
541
465
  return json;
542
466
  }
543
467
  case 400: {
544
- if (isParsingErrorAPIResponse(json)) {
545
- throw new ParsingError(json.message, {
546
- url,
547
- response: json
548
- });
549
- }
550
- break;
468
+ throw new ParsingError(json.message, url, json);
551
469
  }
552
470
  case 401:
553
471
  case 403: {
554
- if (isForbiddenErrorAPIResponse(json)) {
555
- throw new ForbiddenError("error" in json ? json.error : json.message, {
556
- url,
557
- response: json
558
- });
559
- }
472
+ throw new ForbiddenError("error" in json ? json.error : json.message, url, json);
560
473
  }
561
474
  }
562
- throw new PrismicError(void 0, { url, response: json });
475
+ throw new PrismicError(void 0, url, json);
563
476
  }
564
477
  }
565
478