@prismicio/client 5.1.0 → 5.2.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.
@@ -1,1278 +0,0 @@
1
- import crossFetch from 'cross-fetch';
2
-
3
- /*! *****************************************************************************
4
- Copyright (c) Microsoft Corporation. All rights reserved.
5
- Licensed under the Apache License, Version 2.0 (the "License"); you may not use
6
- this file except in compliance with the License. You may obtain a copy of the
7
- License at http://www.apache.org/licenses/LICENSE-2.0
8
-
9
- THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
10
- KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
11
- WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
12
- MERCHANTABLITY OR NON-INFRINGEMENT.
13
-
14
- See the Apache Version 2.0 License for specific language governing permissions
15
- and limitations under the License.
16
- ***************************************************************************** */
17
-
18
- var __assign = function() {
19
- __assign = Object.assign || function __assign(t) {
20
- for (var s, i = 1, n = arguments.length; i < n; i++) {
21
- s = arguments[i];
22
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
23
- }
24
- return t;
25
- };
26
- return __assign.apply(this, arguments);
27
- };
28
-
29
- var Variation = /** @class */ (function () {
30
- function Variation(data) {
31
- this.data = {};
32
- this.data = data;
33
- }
34
- Variation.prototype.id = function () {
35
- return this.data.id;
36
- };
37
- Variation.prototype.ref = function () {
38
- return this.data.ref;
39
- };
40
- Variation.prototype.label = function () {
41
- return this.data.label;
42
- };
43
- return Variation;
44
- }());
45
- var Experiment = /** @class */ (function () {
46
- function Experiment(data) {
47
- this.data = {};
48
- this.data = data;
49
- this.variations = (data.variations || []).map(function (v) {
50
- return new Variation(v);
51
- });
52
- }
53
- Experiment.prototype.id = function () {
54
- return this.data.id;
55
- };
56
- Experiment.prototype.googleId = function () {
57
- return this.data.googleId;
58
- };
59
- Experiment.prototype.name = function () {
60
- return this.data.name;
61
- };
62
- return Experiment;
63
- }());
64
- var Experiments = /** @class */ (function () {
65
- function Experiments(data) {
66
- if (data) {
67
- this.drafts = (data.drafts || []).map(function (exp) {
68
- return new Experiment(exp);
69
- });
70
- this.running = (data.running || []).map(function (exp) {
71
- return new Experiment(exp);
72
- });
73
- }
74
- }
75
- Experiments.prototype.current = function () {
76
- if (this.running.length > 0) {
77
- return this.running[0];
78
- }
79
- else {
80
- return null;
81
- }
82
- };
83
- Experiments.prototype.refFromCookie = function (cookie) {
84
- if (!cookie || cookie.trim() === '')
85
- return null;
86
- var splitted = cookie.trim().split(' ');
87
- if (splitted.length < 2)
88
- return null;
89
- var expId = splitted[0];
90
- var varIndex = parseInt(splitted[1], 10);
91
- var exp = this.running.filter(function (exp) {
92
- return exp.googleId() === expId && exp.variations.length > varIndex;
93
- })[0];
94
- return exp ? exp.variations[varIndex].ref() : null;
95
- };
96
- return Experiments;
97
- }());
98
-
99
- var LazySearchForm = /** @class */ (function () {
100
- function LazySearchForm(id, api) {
101
- this.id = id;
102
- this.api = api;
103
- this.fields = {};
104
- }
105
- LazySearchForm.prototype.set = function (key, value) {
106
- this.fields[key] = value;
107
- return this;
108
- };
109
- LazySearchForm.prototype.ref = function (ref) {
110
- return this.set('ref', ref);
111
- };
112
- LazySearchForm.prototype.query = function (query) {
113
- return this.set('q', query);
114
- };
115
- LazySearchForm.prototype.pageSize = function (size) {
116
- return this.set('pageSize', size);
117
- };
118
- LazySearchForm.prototype.fetch = function (fields) {
119
- console.warn('Warning: Using Fetch is deprecated. Use the property `graphQuery` instead.');
120
- return this.set('fetch', fields);
121
- };
122
- LazySearchForm.prototype.fetchLinks = function (fields) {
123
- console.warn('Warning: Using FetchLinks is deprecated. Use the property `graphQuery` instead.');
124
- return this.set('fetchLinks', fields);
125
- };
126
- LazySearchForm.prototype.graphQuery = function (query) {
127
- return this.set('graphQuery', query);
128
- };
129
- LazySearchForm.prototype.lang = function (langCode) {
130
- return this.set('lang', langCode);
131
- };
132
- LazySearchForm.prototype.page = function (p) {
133
- return this.set('page', p);
134
- };
135
- LazySearchForm.prototype.after = function (documentId) {
136
- return this.set('after', documentId);
137
- };
138
- LazySearchForm.prototype.orderings = function (orderings) {
139
- return this.set('orderings', orderings);
140
- };
141
- LazySearchForm.prototype.url = function () {
142
- var _this = this;
143
- return this.api.get().then(function (api) {
144
- return LazySearchForm.toSearchForm(_this, api).url();
145
- });
146
- };
147
- LazySearchForm.prototype.submit = function (cb) {
148
- var _this = this;
149
- return this.api.get().then(function (api) {
150
- return LazySearchForm.toSearchForm(_this, api).submit(cb);
151
- });
152
- };
153
- LazySearchForm.toSearchForm = function (lazyForm, api) {
154
- var form = api.form(lazyForm.id);
155
- if (form) {
156
- return Object.keys(lazyForm.fields).reduce(function (form, fieldKey) {
157
- var fieldValue = lazyForm.fields[fieldKey];
158
- if (fieldKey === 'q') {
159
- return form.query(fieldValue);
160
- }
161
- else if (fieldKey === 'pageSize') {
162
- return form.pageSize(fieldValue);
163
- }
164
- else if (fieldKey === 'fetch') {
165
- return form.fetch(fieldValue);
166
- }
167
- else if (fieldKey === 'fetchLinks') {
168
- return form.fetchLinks(fieldValue);
169
- }
170
- else if (fieldKey === 'graphQuery') {
171
- return form.graphQuery(fieldValue);
172
- }
173
- else if (fieldKey === 'lang') {
174
- return form.lang(fieldValue);
175
- }
176
- else if (fieldKey === 'page') {
177
- return form.page(fieldValue);
178
- }
179
- else if (fieldKey === 'after') {
180
- return form.after(fieldValue);
181
- }
182
- else if (fieldKey === 'orderings') {
183
- return form.orderings(fieldValue);
184
- }
185
- else {
186
- return form.set(fieldKey, fieldValue);
187
- }
188
- }, form);
189
- }
190
- else {
191
- throw new Error("Unable to access to form " + lazyForm.id);
192
- }
193
- };
194
- return LazySearchForm;
195
- }());
196
- var SearchForm = /** @class */ (function () {
197
- function SearchForm(form, httpClient) {
198
- this.httpClient = httpClient;
199
- this.form = form;
200
- this.data = {};
201
- for (var field in form.fields) {
202
- if (form.fields[field]['default']) {
203
- this.data[field] = [form.fields[field]['default']];
204
- }
205
- }
206
- }
207
- SearchForm.prototype.set = function (field, value) {
208
- var fieldDesc = this.form.fields[field];
209
- if (!fieldDesc)
210
- throw new Error('Unknown field ' + field);
211
- var checkedValue = value === '' || value === undefined ? null : value;
212
- var values = this.data[field] || [];
213
- if (fieldDesc.multiple) {
214
- values = checkedValue ? values.concat([checkedValue]) : values;
215
- }
216
- else {
217
- values = checkedValue ? [checkedValue] : values;
218
- }
219
- this.data[field] = values;
220
- return this;
221
- };
222
- /**
223
- * Sets a ref to query on for this SearchForm. This is a mandatory
224
- * method to call before calling submit(), and api.form('everything').submit()
225
- * will not work.
226
- */
227
- SearchForm.prototype.ref = function (ref) {
228
- return this.set('ref', ref);
229
- };
230
- /**
231
- * Sets a predicate-based query for this SearchForm. This is where you
232
- * paste what you compose in your prismic.io API browser.
233
- */
234
- SearchForm.prototype.query = function (query) {
235
- if (typeof query === 'string') {
236
- return this.query([query]);
237
- }
238
- else if (Array.isArray(query)) {
239
- return this.set('q', "[" + query.join('') + "]");
240
- }
241
- else {
242
- throw new Error("Invalid query : " + query);
243
- }
244
- };
245
- /**
246
- * Sets a page size to query for this SearchForm. This is an optional method.
247
- *
248
- * @param {number} size - The page size
249
- * @returns {SearchForm} - The SearchForm itself
250
- */
251
- SearchForm.prototype.pageSize = function (size) {
252
- return this.set('pageSize', size);
253
- };
254
- /**
255
- * Restrict the results document to the specified fields
256
- */
257
- SearchForm.prototype.fetch = function (fields) {
258
- console.warn('Warning: Using Fetch is deprecated. Use the property `graphQuery` instead.');
259
- var strFields = Array.isArray(fields) ? fields.join(',') : fields;
260
- return this.set('fetch', strFields);
261
- };
262
- /**
263
- * Include the requested fields in the DocumentLink instances in the result
264
- */
265
- SearchForm.prototype.fetchLinks = function (fields) {
266
- console.warn('Warning: Using FetchLinks is deprecated. Use the property `graphQuery` instead.');
267
- var strFields = Array.isArray(fields) ? fields.join(',') : fields;
268
- return this.set('fetchLinks', strFields);
269
- };
270
- /**
271
- * Sets the graphquery to query for this SearchForm. This is an optional method.
272
- */
273
- SearchForm.prototype.graphQuery = function (query) {
274
- return this.set('graphQuery', query);
275
- };
276
- /**
277
- * Sets the language to query for this SearchForm. This is an optional method.
278
- */
279
- SearchForm.prototype.lang = function (langCode) {
280
- return this.set('lang', langCode);
281
- };
282
- /**
283
- * Sets the page number to query for this SearchForm. This is an optional method.
284
- */
285
- SearchForm.prototype.page = function (p) {
286
- return this.set('page', p);
287
- };
288
- /**
289
- * Remove all the documents except for those after the specified document in the list. This is an optional method.
290
- */
291
- SearchForm.prototype.after = function (documentId) {
292
- return this.set('after', documentId);
293
- };
294
- /**
295
- * Sets the orderings to query for this SearchForm. This is an optional method.
296
- */
297
- SearchForm.prototype.orderings = function (orderings) {
298
- if (!orderings) {
299
- return this;
300
- }
301
- else {
302
- return this.set('orderings', "[" + orderings.join(',') + "]");
303
- }
304
- };
305
- /**
306
- * Build the URL to query
307
- */
308
- SearchForm.prototype.url = function () {
309
- var url = this.form.action;
310
- if (this.data) {
311
- var sep = (url.indexOf('?') > -1 ? '&' : '?');
312
- for (var key in this.data) {
313
- if (Object.prototype.hasOwnProperty.call(this.data, key)) {
314
- var values = this.data[key];
315
- if (values) {
316
- for (var i = 0; i < values.length; i++) {
317
- url += sep + key + '=' + encodeURIComponent(values[i]);
318
- sep = '&';
319
- }
320
- }
321
- }
322
- }
323
- }
324
- return url;
325
- };
326
- /**
327
- * Submits the query, and calls the callback function.
328
- */
329
- SearchForm.prototype.submit = function (cb) {
330
- return this.httpClient.cachedRequest(this.url()).then(function (response) {
331
- cb && cb(null, response);
332
- return response;
333
- }).catch(function (error) {
334
- cb && cb(error);
335
- throw error;
336
- });
337
- };
338
- return SearchForm;
339
- }());
340
-
341
- var OPERATOR = {
342
- at: 'at',
343
- not: 'not',
344
- missing: 'missing',
345
- has: 'has',
346
- any: 'any',
347
- in: 'in',
348
- fulltext: 'fulltext',
349
- similar: 'similar',
350
- numberGt: 'number.gt',
351
- numberLt: 'number.lt',
352
- numberInRange: 'number.inRange',
353
- dateBefore: 'date.before',
354
- dateAfter: 'date.after',
355
- dateBetween: 'date.between',
356
- dateDayOfMonth: 'date.day-of-month',
357
- dateDayOfMonthAfter: 'date.day-of-month-after',
358
- dateDayOfMonthBefore: 'date.day-of-month-before',
359
- dateDayOfWeek: 'date.day-of-week',
360
- dateDayOfWeekAfter: 'date.day-of-week-after',
361
- dateDayOfWeekBefore: 'date.day-of-week-before',
362
- dateMonth: 'date.month',
363
- dateMonthBefore: 'date.month-before',
364
- dateMonthAfter: 'date.month-after',
365
- dateYear: 'date.year',
366
- dateHour: 'date.hour',
367
- dateHourBefore: 'date.hour-before',
368
- dateHourAfter: 'date.hour-after',
369
- GeopointNear: 'geopoint.near',
370
- };
371
- function encode(value) {
372
- if (typeof value === 'string') {
373
- return "\"" + value + "\"";
374
- }
375
- else if (typeof value === 'number') {
376
- return value.toString();
377
- }
378
- else if (value instanceof Date) {
379
- return value.getTime().toString();
380
- }
381
- else if (Array.isArray(value)) {
382
- return "[" + value.map(function (v) { return encode(v); }).join(',') + "]";
383
- }
384
- else if (typeof value === "boolean") {
385
- return value.toString();
386
- }
387
- else {
388
- throw new Error("Unable to encode " + value + " of type " + typeof value);
389
- }
390
- }
391
- var geopoint = {
392
- near: function (fragment, latitude, longitude, radius) {
393
- return "[" + OPERATOR.GeopointNear + "(" + fragment + ", " + latitude + ", " + longitude + ", " + radius + ")]";
394
- },
395
- };
396
- var date = {
397
- before: function (fragment, before) {
398
- return "[" + OPERATOR.dateBefore + "(" + fragment + ", " + encode(before) + ")]";
399
- },
400
- after: function (fragment, after) {
401
- return "[" + OPERATOR.dateAfter + "(" + fragment + ", " + encode(after) + ")]";
402
- },
403
- between: function (fragment, before, after) {
404
- return "[" + OPERATOR.dateBetween + "(" + fragment + ", " + encode(before) + ", " + encode(after) + ")]";
405
- },
406
- dayOfMonth: function (fragment, day) {
407
- return "[" + OPERATOR.dateDayOfMonth + "(" + fragment + ", " + day + ")]";
408
- },
409
- dayOfMonthAfter: function (fragment, day) {
410
- return "[" + OPERATOR.dateDayOfMonthAfter + "(" + fragment + ", " + day + ")]";
411
- },
412
- dayOfMonthBefore: function (fragment, day) {
413
- return "[" + OPERATOR.dateDayOfMonthBefore + "(" + fragment + ", " + day + ")]";
414
- },
415
- dayOfWeek: function (fragment, day) {
416
- return "[" + OPERATOR.dateDayOfWeek + "(" + fragment + ", " + encode(day) + ")]";
417
- },
418
- dayOfWeekAfter: function (fragment, day) {
419
- return "[" + OPERATOR.dateDayOfWeekAfter + "(" + fragment + ", " + encode(day) + ")]";
420
- },
421
- dayOfWeekBefore: function (fragment, day) {
422
- return "[" + OPERATOR.dateDayOfWeekBefore + "(" + fragment + ", " + encode(day) + ")]";
423
- },
424
- month: function (fragment, month) {
425
- return "[" + OPERATOR.dateMonth + "(" + fragment + ", " + encode(month) + ")]";
426
- },
427
- monthBefore: function (fragment, month) {
428
- return "[" + OPERATOR.dateMonthBefore + "(" + fragment + ", " + encode(month) + ")]";
429
- },
430
- monthAfter: function (fragment, month) {
431
- return "[" + OPERATOR.dateMonthAfter + "(" + fragment + ", " + encode(month) + ")]";
432
- },
433
- year: function (fragment, year) {
434
- return "[" + OPERATOR.dateYear + "(" + fragment + ", " + year + ")]";
435
- },
436
- hour: function (fragment, hour) {
437
- return "[" + OPERATOR.dateHour + "(" + fragment + ", " + hour + ")]";
438
- },
439
- hourBefore: function (fragment, hour) {
440
- return "[" + OPERATOR.dateHourBefore + "(" + fragment + ", " + hour + ")]";
441
- },
442
- hourAfter: function (fragment, hour) {
443
- return "[" + OPERATOR.dateHourAfter + "(" + fragment + ", " + hour + ")]";
444
- },
445
- };
446
- var number = {
447
- gt: function (fragment, value) {
448
- return "[" + OPERATOR.numberGt + "(" + fragment + ", " + value + ")]";
449
- },
450
- lt: function (fragment, value) {
451
- return "[" + OPERATOR.numberLt + "(" + fragment + ", " + value + ")]";
452
- },
453
- inRange: function (fragment, before, after) {
454
- return "[" + OPERATOR.numberInRange + "(" + fragment + ", " + before + ", " + after + ")]";
455
- },
456
- };
457
- var Predicates = {
458
- at: function (fragment, value) {
459
- return "[" + OPERATOR.at + "(" + fragment + ", " + encode(value) + ")]";
460
- },
461
- not: function (fragment, value) {
462
- return "[" + OPERATOR.not + "(" + fragment + ", " + encode(value) + ")]";
463
- },
464
- missing: function (fragment) {
465
- return "[" + OPERATOR.missing + "(" + fragment + ")]";
466
- },
467
- has: function (fragment) {
468
- return "[" + OPERATOR.has + "(" + fragment + ")]";
469
- },
470
- any: function (fragment, values) {
471
- return "[" + OPERATOR.any + "(" + fragment + ", " + encode(values) + ")]";
472
- },
473
- in: function (fragment, values) {
474
- return "[" + OPERATOR.in + "(" + fragment + ", " + encode(values) + ")]";
475
- },
476
- fulltext: function (fragment, value) {
477
- return "[" + OPERATOR.fulltext + "(" + fragment + ", " + encode(value) + ")]";
478
- },
479
- similar: function (documentId, maxResults) {
480
- return "[" + OPERATOR.similar + "(\"" + documentId + "\", " + maxResults + ")]";
481
- },
482
- date: date,
483
- dateBefore: date.before,
484
- dateAfter: date.after,
485
- dateBetween: date.between,
486
- dayOfMonth: date.dayOfMonth,
487
- dayOfMonthAfter: date.dayOfMonthAfter,
488
- dayOfMonthBefore: date.dayOfMonthBefore,
489
- dayOfWeek: date.dayOfWeek,
490
- dayOfWeekAfter: date.dayOfWeekAfter,
491
- dayOfWeekBefore: date.dayOfWeekBefore,
492
- month: date.month,
493
- monthBefore: date.monthBefore,
494
- monthAfter: date.monthAfter,
495
- year: date.year,
496
- hour: date.hour,
497
- hourBefore: date.hourBefore,
498
- hourAfter: date.hourAfter,
499
- number: number,
500
- gt: number.gt,
501
- lt: number.lt,
502
- inRange: number.inRange,
503
- near: geopoint.near,
504
- geopoint: geopoint,
505
- };
506
-
507
- /* eslint-disable */
508
- // Some portions of code from https://github.com/jshttp/cookie
509
- var decode = decodeURIComponent;
510
- function tryDecode(str, decode) {
511
- try {
512
- return decode(str);
513
- }
514
- catch (e) {
515
- return str;
516
- }
517
- }
518
- function parse(str, options) {
519
- if (typeof str !== 'string') {
520
- throw new TypeError('argument str must be a string');
521
- }
522
- var obj = {};
523
- var opt = options || {};
524
- var pairs = str.split(/; */);
525
- var dec = opt.decode || decode;
526
- pairs.forEach(function (pair) {
527
- var eq_idx = pair.indexOf('=');
528
- // skip things that don't look like key=value
529
- if (eq_idx < 0) {
530
- return;
531
- }
532
- var key = pair.substr(0, eq_idx).trim();
533
- var val = pair.substr(++eq_idx, pair.length).trim();
534
- // quoted values
535
- if ('"' == val[0]) {
536
- val = val.slice(1, -1);
537
- }
538
- // only assign once
539
- if (undefined == obj[key]) {
540
- obj[key] = tryDecode(val, dec);
541
- }
542
- });
543
- return obj;
544
- }
545
- var Cookies = { parse: parse };
546
-
547
- function createPreviewResolver(token, documentId, getDocByID) {
548
- var resolve = function (linkResolver, defaultUrl, cb) {
549
- if (documentId && getDocByID) {
550
- return getDocByID(documentId, { ref: token }).then(function (document) {
551
- if (!document) {
552
- cb && cb(null, defaultUrl);
553
- return defaultUrl;
554
- }
555
- else {
556
- var url = (linkResolver && linkResolver(document)) || document.url || defaultUrl;
557
- cb && cb(null, url);
558
- return url;
559
- }
560
- });
561
- }
562
- else {
563
- return Promise.resolve(defaultUrl);
564
- }
565
- };
566
- return { token: token, documentId: documentId, resolve: resolve };
567
- }
568
-
569
- var PREVIEW_COOKIE = 'io.prismic.preview';
570
- var EXPERIMENT_COOKIE = 'io.prismic.experiment';
571
- var ResolvedApi = /** @class */ (function () {
572
- function ResolvedApi(data, httpClient, options) {
573
- this.data = data;
574
- this.masterRef = data.refs.filter(function (ref) { return ref.isMasterRef; })[0];
575
- this.experiments = new Experiments(data.experiments);
576
- this.bookmarks = data.bookmarks;
577
- this.httpClient = httpClient;
578
- this.options = options;
579
- this.refs = data.refs;
580
- this.tags = data.tags;
581
- this.types = data.types;
582
- this.languages = data.languages;
583
- }
584
- /**
585
- * Returns a useable form from its id, as described in the RESTful description of the API.
586
- * For instance: api.form("everything") works on every repository (as "everything" exists by default)
587
- * You can then chain the calls: api.form("everything").query('[[:d = at(document.id, "UkL0gMuvzYUANCpf")]]').ref(ref).submit()
588
- */
589
- ResolvedApi.prototype.form = function (formId) {
590
- var form = this.data.forms[formId];
591
- if (form) {
592
- return new SearchForm(form, this.httpClient);
593
- }
594
- return null;
595
- };
596
- ResolvedApi.prototype.everything = function () {
597
- var f = this.form('everything');
598
- if (!f)
599
- throw new Error('Missing everything form');
600
- return f;
601
- };
602
- /**
603
- * The ID of the master ref on this prismic.io API.
604
- * Do not use like this: searchForm.ref(api.master()).
605
- * Instead, set your ref once in a variable, and call it when you need it; this will allow to change the ref you're viewing easily for your entire page.
606
- */
607
- ResolvedApi.prototype.master = function () {
608
- return this.masterRef.ref;
609
- };
610
- /**
611
- * Returns the ref ID for a given ref's label.
612
- * Do not use like this: searchForm.ref(api.ref("Future release label")).
613
- * Instead, set your ref once in a variable, and call it when you need it; this will allow to change the ref you're viewing easily for your entire page.
614
- */
615
- ResolvedApi.prototype.ref = function (label) {
616
- var ref = this.data.refs.filter(function (ref) { return ref.label === label; })[0];
617
- return ref ? ref.ref : null;
618
- };
619
- ResolvedApi.prototype.currentExperiment = function () {
620
- return this.experiments.current();
621
- };
622
- /**
623
- * Query the repository
624
- */
625
- ResolvedApi.prototype.query = function (q, optionsOrCallback, cb) {
626
- if (cb === void 0) { cb = function () { }; }
627
- var _a = typeof optionsOrCallback === 'function'
628
- ? { options: {}, callback: optionsOrCallback }
629
- : { options: optionsOrCallback || {}, callback: cb }, options = _a.options, callback = _a.callback;
630
- var form = this.everything();
631
- for (var key in options) {
632
- form = form.set(key, options[key]);
633
- }
634
- if (!options.ref) {
635
- // Look in cookies if we have a ref (preview or experiment)
636
- var cookieString = '';
637
- if (this.options.req) { // NodeJS
638
- cookieString = this.options.req.headers['cookie'] || '';
639
- }
640
- else if (typeof window !== 'undefined' && window.document) { // Browser
641
- cookieString = window.document.cookie || '';
642
- }
643
- var cookies = Cookies.parse(cookieString);
644
- var previewRef = cookies[PREVIEW_COOKIE];
645
- var experimentRef = this.experiments.refFromCookie(cookies[EXPERIMENT_COOKIE]);
646
- form = form.ref(previewRef || experimentRef || this.masterRef.ref);
647
- }
648
- if (q) {
649
- form.query(q);
650
- }
651
- return form.submit(callback);
652
- };
653
- /**
654
- * Retrieve the document returned by the given query
655
- * @param {string|array|Predicate} the query
656
- * @param {object} additional parameters. In NodeJS, pass the request as 'req'.
657
- * @param {function} callback(err, doc)
658
- */
659
- ResolvedApi.prototype.queryFirst = function (q, optionsOrCallback, cb) {
660
- var _a = typeof optionsOrCallback === 'function'
661
- ? { options: {}, callback: optionsOrCallback }
662
- : { options: optionsOrCallback || {}, callback: cb || (function () { }) }, options = _a.options, callback = _a.callback;
663
- options.page = 1;
664
- options.pageSize = 1;
665
- return this.query(q, options).then(function (response) {
666
- var document = response && response.results && response.results[0];
667
- callback(null, document);
668
- return document;
669
- }).catch(function (error) {
670
- callback(error);
671
- throw error;
672
- });
673
- };
674
- /**
675
- * Retrieve the document with the given id
676
- */
677
- ResolvedApi.prototype.getByID = function (id, maybeOptions, cb) {
678
- var options = maybeOptions ? __assign({}, maybeOptions) : {};
679
- if (!options.lang)
680
- options.lang = '*';
681
- return this.queryFirst(Predicates.at('document.id', id), options, cb);
682
- };
683
- /**
684
- * Retrieve multiple documents from an array of id
685
- */
686
- ResolvedApi.prototype.getByIDs = function (ids, maybeOptions, cb) {
687
- var options = maybeOptions ? __assign({}, maybeOptions) : {};
688
- if (!options.lang)
689
- options.lang = '*';
690
- return this.query(Predicates.in('document.id', ids), options, cb);
691
- };
692
- /**
693
- * Retrieve the document with the given uid
694
- */
695
- ResolvedApi.prototype.getByUID = function (type, uid, maybeOptions, cb) {
696
- var options = maybeOptions ? __assign({}, maybeOptions) : {};
697
- if (options.lang === '*')
698
- throw new Error("FORBIDDEN. You can't use getByUID with *, use the predicates instead.");
699
- if (!options.page)
700
- options.page = 1;
701
- return this.queryFirst(Predicates.at("my." + type + ".uid", uid), options, cb);
702
- };
703
- /**
704
- * Retrieve the singleton document with the given type
705
- */
706
- ResolvedApi.prototype.getSingle = function (type, maybeOptions, cb) {
707
- var options = maybeOptions ? __assign({}, maybeOptions) : {};
708
- return this.queryFirst(Predicates.at('document.type', type), options, cb);
709
- };
710
- /**
711
- * Retrieve the document with the given bookmark
712
- */
713
- ResolvedApi.prototype.getBookmark = function (bookmark, maybeOptions, cb) {
714
- var id = this.data.bookmarks[bookmark];
715
- if (id) {
716
- return this.getByID(id, maybeOptions, cb);
717
- }
718
- else {
719
- return Promise.reject('Error retrieving bookmarked id');
720
- }
721
- };
722
- ResolvedApi.prototype.getPreviewResolver = function (token, documentId) {
723
- return createPreviewResolver(token, documentId, this.getByID.bind(this));
724
- };
725
- ResolvedApi.prototype.previewSession = function (token, linkResolver, defaultUrl, cb) {
726
- var _this = this;
727
- console.warn('previewSession function is deprecated in favor of getPreviewResolver function.');
728
- return new Promise(function (resolve, reject) {
729
- _this.httpClient.request(token, function (e, result) {
730
- if (e) {
731
- cb && cb(e);
732
- reject(e);
733
- }
734
- else if (result) {
735
- if (!result.mainDocument) {
736
- cb && cb(null, defaultUrl);
737
- resolve(defaultUrl);
738
- }
739
- else {
740
- return _this.getByID(result.mainDocument, { ref: token }).then(function (document) {
741
- if (!document) {
742
- cb && cb(null, defaultUrl);
743
- resolve(defaultUrl);
744
- }
745
- else {
746
- var url = (linkResolver && linkResolver(document)) || document.url || defaultUrl;
747
- cb && cb(null, url);
748
- resolve(url);
749
- }
750
- }).catch(reject);
751
- }
752
- }
753
- });
754
- });
755
- };
756
- return ResolvedApi;
757
- }());
758
-
759
- /* eslint-disable */
760
- /**
761
- * A doubly linked list-based Least Recently Used (LRU) cache. Will keep most
762
- * recently used items while discarding least recently used items when its limit
763
- * is reached.
764
- *
765
- * Licensed under MIT. Copyright (c) 2010 Rasmus Andersson <http://hunch.se/>
766
- * Typescript-ified by Oleksandr Nikitin <https://tvori.info>
767
- *
768
- * Illustration of the design:
769
- *
770
- * entry entry entry entry
771
- * ______ ______ ______ ______
772
- * | head |.newer => | |.newer => | |.newer => | tail |
773
- * | A | | B | | C | | D |
774
- * |______| <= older.|______| <= older.|______| <= older.|______|
775
- *
776
- * removed <-- <-- <-- <-- <-- <-- <-- <-- <-- <-- <-- added
777
- */
778
- function MakeLRUCache(limit) {
779
- return new LRUCache(limit);
780
- }
781
- function LRUCache(limit) {
782
- // Current size of the cache. (Read-only).
783
- this.size = 0;
784
- // Maximum number of items this cache can hold.
785
- this.limit = limit;
786
- this._keymap = {};
787
- }
788
- /**
789
- * Put <value> into the cache associated with <key>. Returns the entry which was
790
- * removed to make room for the new entry. Otherwise undefined is returned
791
- * (i.e. if there was enough room already).
792
- */
793
- LRUCache.prototype.put = function (key, value) {
794
- var entry = { key: key, value: value };
795
- // Note: No protection agains replacing, and thus orphan entries. By design.
796
- this._keymap[key] = entry;
797
- if (this.tail) {
798
- // link previous tail to the new tail (entry)
799
- this.tail.newer = entry;
800
- entry.older = this.tail;
801
- }
802
- else {
803
- // we're first in -- yay
804
- this.head = entry;
805
- }
806
- // add new entry to the end of the linked list -- it's now the freshest entry.
807
- this.tail = entry;
808
- if (this.size === this.limit) {
809
- // we hit the limit -- remove the head
810
- return this.shift();
811
- }
812
- else {
813
- // increase the size counter
814
- this.size++;
815
- }
816
- };
817
- /**
818
- * Purge the least recently used (oldest) entry from the cache. Returns the
819
- * removed entry or undefined if the cache was empty.
820
- *
821
- * If you need to perform any form of finalization of purged items, this is a
822
- * good place to do it. Simply override/replace this function:
823
- *
824
- * var c = new LRUCache(123);
825
- * c.shift = function() {
826
- * var entry = LRUCache.prototype.shift.call(this);
827
- * doSomethingWith(entry);
828
- * return entry;
829
- * }
830
- */
831
- LRUCache.prototype.shift = function () {
832
- // todo: handle special case when limit == 1
833
- var entry = this.head;
834
- if (entry) {
835
- if (this.head.newer) {
836
- this.head = this.head.newer;
837
- this.head.older = undefined;
838
- }
839
- else {
840
- this.head = undefined;
841
- }
842
- // Remove last strong reference to <entry> and remove links from the purged
843
- // entry being returned:
844
- entry.newer = entry.older = undefined;
845
- // delete is slow, but we need to do this to avoid uncontrollable growth:
846
- delete this._keymap[entry.key];
847
- }
848
- console.log('purging ', entry.key);
849
- return entry;
850
- };
851
- /**
852
- * Get and register recent use of <key>. Returns the value associated with <key>
853
- * or undefined if not in cache.
854
- */
855
- LRUCache.prototype.get = function (key, returnEntry) {
856
- // First, find our cache entry
857
- var entry = this._keymap[key];
858
- if (entry === undefined)
859
- return; // Not cached. Sorry.
860
- // As <key> was found in the cache, register it as being requested recently
861
- if (entry === this.tail) {
862
- // Already the most recently used entry, so no need to update the list
863
- return returnEntry ? entry : entry.value;
864
- }
865
- // HEAD--------------TAIL
866
- // <.older .newer>
867
- // <--- add direction --
868
- // A B C <D> E
869
- if (entry.newer) {
870
- if (entry === this.head)
871
- this.head = entry.newer;
872
- entry.newer.older = entry.older; // C <-- E.
873
- }
874
- if (entry.older)
875
- entry.older.newer = entry.newer; // C. --> E
876
- entry.newer = undefined; // D --x
877
- entry.older = this.tail; // D. --> E
878
- if (this.tail)
879
- this.tail.newer = entry; // E. <-- D
880
- this.tail = entry;
881
- return returnEntry ? entry : entry.value;
882
- };
883
- // ----------------------------------------------------------------------------
884
- // Following code is optional and can be removed without breaking the core
885
- // functionality.
886
- /**
887
- * Check if <key> is in the cache without registering recent use. Feasible if
888
- * you do not want to chage the state of the cache, but only "peek" at it.
889
- * Returns the entry associated with <key> if found, or undefined if not found.
890
- */
891
- LRUCache.prototype.find = function (key) {
892
- return this._keymap[key];
893
- };
894
- /**
895
- * Update the value of entry with <key>. Returns the old value, or undefined if
896
- * entry was not in the cache.
897
- */
898
- LRUCache.prototype.set = function (key, value) {
899
- var oldvalue;
900
- var entry = this.get(key, true);
901
- if (entry) {
902
- oldvalue = entry.value;
903
- entry.value = value;
904
- }
905
- else {
906
- oldvalue = this.put(key, value);
907
- if (oldvalue)
908
- oldvalue = oldvalue.value;
909
- }
910
- return oldvalue;
911
- };
912
- /**
913
- * Remove entry <key> from cache and return its value. Returns undefined if not
914
- * found.
915
- */
916
- LRUCache.prototype.remove = function (key) {
917
- var entry = this._keymap[key];
918
- if (!entry)
919
- return;
920
- delete this._keymap[entry.key]; // need to do delete unfortunately
921
- if (entry.newer && entry.older) {
922
- // relink the older entry with the newer entry
923
- entry.older.newer = entry.newer;
924
- entry.newer.older = entry.older;
925
- }
926
- else if (entry.newer) {
927
- // remove the link to us
928
- entry.newer.older = undefined;
929
- // link the newer entry to head
930
- this.head = entry.newer;
931
- }
932
- else if (entry.older) {
933
- // remove the link to us
934
- entry.older.newer = undefined;
935
- // link the newer entry to head
936
- this.tail = entry.older;
937
- }
938
- else { // if(entry.older === undefined && entry.newer === undefined) {
939
- this.head = this.tail = undefined;
940
- }
941
- this.size--;
942
- return entry.value;
943
- };
944
- /** Removes all entries */
945
- LRUCache.prototype.removeAll = function () {
946
- // This should be safe, as we never expose strong refrences to the outside
947
- this.head = this.tail = undefined;
948
- this.size = 0;
949
- this._keymap = {};
950
- };
951
- /**
952
- * Return an array containing all keys of entries stored in the cache object, in
953
- * arbitrary order.
954
- */
955
- if (typeof Object.keys === 'function') {
956
- LRUCache.prototype.keys = function () { return Object.keys(this._keymap); };
957
- }
958
- else {
959
- LRUCache.prototype.keys = function () {
960
- var keys = [];
961
- for (var k in this._keymap)
962
- keys.push(k);
963
- return keys;
964
- };
965
- }
966
- /**
967
- * Call `fun` for each entry. Starting with the newest entry if `desc` is a true
968
- * value, otherwise starts with the oldest (head) enrty and moves towards the
969
- * tail.
970
- *
971
- * `fun` is called with 3 arguments in the context `context`:
972
- * `fun.call(context, Object key, Object value, LRUCache self)`
973
- */
974
- LRUCache.prototype.forEach = function (fun, context, desc) {
975
- var entry;
976
- if (context === true) {
977
- desc = true;
978
- context = undefined;
979
- }
980
- else if (typeof context !== 'object')
981
- context = this;
982
- if (desc) {
983
- entry = this.tail;
984
- while (entry) {
985
- fun.call(context, entry.key, entry.value, this);
986
- entry = entry.older;
987
- }
988
- }
989
- else {
990
- entry = this.head;
991
- while (entry) {
992
- fun.call(context, entry.key, entry.value, this);
993
- entry = entry.newer;
994
- }
995
- }
996
- };
997
- /** Returns a JSON (array) representation */
998
- //LRUCache.prototype.toJSON = function () {
999
- // var s: IEntry[] = [], entry = this.head;
1000
- // while (entry) {
1001
- // s.push({ key: entry.key.toJSON(), value: entry.value.toJSON() });
1002
- // entry = entry.newer;
1003
- // }
1004
- // return s;
1005
- //};
1006
- /** Returns a String representation */
1007
- LRUCache.prototype.toString = function () {
1008
- var s = '', entry = this.head;
1009
- while (entry) {
1010
- s += String(entry.key) + ':' + entry.value;
1011
- entry = entry.newer;
1012
- if (entry)
1013
- s += ' < ';
1014
- }
1015
- return s;
1016
- };
1017
- // Export ourselves
1018
- //if (typeof this === 'object') this.LRUCache = LRUCache;
1019
-
1020
- var DefaultApiCache = /** @class */ (function () {
1021
- function DefaultApiCache(limit) {
1022
- if (limit === void 0) { limit = 1000; }
1023
- this.lru = MakeLRUCache(limit);
1024
- }
1025
- DefaultApiCache.prototype.isExpired = function (key) {
1026
- var value = this.lru.get(key, false);
1027
- if (value) {
1028
- return value.expiredIn !== 0 && value.expiredIn < Date.now();
1029
- }
1030
- else {
1031
- return false;
1032
- }
1033
- };
1034
- DefaultApiCache.prototype.get = function (key, cb) {
1035
- var value = this.lru.get(key, false);
1036
- if (value && !this.isExpired(key)) {
1037
- cb(null, value.data);
1038
- }
1039
- else {
1040
- cb && cb(null);
1041
- }
1042
- };
1043
- DefaultApiCache.prototype.set = function (key, value, ttl, cb) {
1044
- this.lru.remove(key);
1045
- this.lru.put(key, {
1046
- data: value,
1047
- expiredIn: ttl ? (Date.now() + (ttl * 1000)) : 0,
1048
- });
1049
- cb && cb(null);
1050
- };
1051
- DefaultApiCache.prototype.remove = function (key, cb) {
1052
- this.lru.remove(key);
1053
- cb && cb(null);
1054
- };
1055
- DefaultApiCache.prototype.clear = function (cb) {
1056
- this.lru.removeAll();
1057
- cb && cb(null);
1058
- };
1059
- return DefaultApiCache;
1060
- }());
1061
-
1062
- function fetchRequest(url, options, callback) {
1063
- var fetchOptions = {
1064
- headers: {
1065
- Accept: 'application/json',
1066
- },
1067
- };
1068
- if (options && options.proxyAgent) {
1069
- fetchOptions.agent = options.proxyAgent;
1070
- }
1071
- // can't use number because of NodeJS globals included
1072
- var timeoutId;
1073
- var fetchPromise = crossFetch(url, fetchOptions);
1074
- var promise = options.timeoutInMs ? Promise.race([
1075
- fetchPromise,
1076
- new Promise(function (_, reject) {
1077
- timeoutId = setTimeout(function () { return reject(new Error(url + " response timeout")); }, options.timeoutInMs);
1078
- })
1079
- ]) : fetchPromise;
1080
- promise.then(function (resp) {
1081
- clearTimeout(timeoutId);
1082
- if (~~(resp.status / 100 !== 2)) {
1083
- /**
1084
- * @description
1085
- * drain the resp before throwing an error to prevent memory leaks
1086
- * @link https://github.com/bitinn/node-fetch/issues/83
1087
- */
1088
- return resp.text().then(function () {
1089
- var e = new Error("Unexpected status code [" + resp.status + "] on URL " + url);
1090
- e.status = resp.status;
1091
- throw e;
1092
- });
1093
- }
1094
- return resp.json().then(function (result) {
1095
- var cacheControl = resp.headers.get('cache-control');
1096
- var parsedCacheControl = cacheControl ? /max-age=(\d+)/.exec(cacheControl) : null;
1097
- var ttl = parsedCacheControl ? parseInt(parsedCacheControl[1], 10) : undefined;
1098
- callback(null, result, resp, ttl);
1099
- });
1100
- }).catch(function (err) {
1101
- clearTimeout(timeoutId);
1102
- callback(err);
1103
- });
1104
- }
1105
- var DefaultRequestHandler = /** @class */ (function () {
1106
- function DefaultRequestHandler(options) {
1107
- this.options = options || {};
1108
- }
1109
- DefaultRequestHandler.prototype.request = function (url, callback) {
1110
- fetchRequest(url, this.options, callback);
1111
- };
1112
- return DefaultRequestHandler;
1113
- }());
1114
-
1115
- var HttpClient = /** @class */ (function () {
1116
- function HttpClient(requestHandler, cache, proxyAgent, timeoutInMs) {
1117
- this.requestHandler = requestHandler || new DefaultRequestHandler({ proxyAgent: proxyAgent, timeoutInMs: timeoutInMs });
1118
- this.cache = cache || new DefaultApiCache();
1119
- }
1120
- HttpClient.prototype.request = function (url, callback) {
1121
- this.requestHandler.request(url, function (err, result, xhr, ttl) {
1122
- if (err) {
1123
- callback && callback(err, null, xhr, ttl);
1124
- }
1125
- else if (result) {
1126
- callback && callback(null, result, xhr, ttl);
1127
- }
1128
- });
1129
- };
1130
- /**
1131
- * Fetch a URL corresponding to a query, and parse the response as a Response object
1132
- */
1133
- HttpClient.prototype.cachedRequest = function (url, maybeOptions) {
1134
- var _this = this;
1135
- var options = maybeOptions || {};
1136
- var run = function (cb) {
1137
- var cacheKey = options.cacheKey || url;
1138
- _this.cache.get(cacheKey, function (cacheGetError, cacheGetValue) {
1139
- if (cacheGetError || cacheGetValue) {
1140
- cb(cacheGetError, cacheGetValue);
1141
- }
1142
- else {
1143
- _this.request(url, function (fetchError, fetchValue, _, ttlReq) {
1144
- if (fetchError) {
1145
- cb(fetchError, null);
1146
- }
1147
- else {
1148
- var ttl = ttlReq || options.ttl;
1149
- if (ttl) {
1150
- _this.cache.set(cacheKey, fetchValue, ttl, cb);
1151
- }
1152
- cb(null, fetchValue);
1153
- }
1154
- });
1155
- }
1156
- });
1157
- };
1158
- return new Promise(function (resolve, reject) {
1159
- run(function (err, value) {
1160
- if (err)
1161
- reject(err);
1162
- if (value)
1163
- resolve(value);
1164
- });
1165
- });
1166
- };
1167
- return HttpClient;
1168
- }());
1169
-
1170
- function separator(url) {
1171
- return url.indexOf('?') > -1 ? '&' : '?';
1172
- }
1173
- var Api = /** @class */ (function () {
1174
- function Api(url, options) {
1175
- this.options = options || {};
1176
- this.url = url;
1177
- if (this.options.accessToken) {
1178
- var accessTokenParam = "access_token=" + this.options.accessToken;
1179
- this.url += separator(url) + accessTokenParam;
1180
- }
1181
- if (this.options.routes) {
1182
- this.url += separator(url) + ("routes=" + encodeURIComponent(JSON.stringify(this.options.routes)));
1183
- }
1184
- this.apiDataTTL = this.options.apiDataTTL || 5;
1185
- this.httpClient = new HttpClient(this.options.requestHandler, this.options.apiCache, this.options.proxyAgent, this.options.timeoutInMs);
1186
- }
1187
- /**
1188
- * Fetches data used to construct the api client, from cache if it's
1189
- * present, otherwise from calling the prismic api endpoint (which is
1190
- * then cached).
1191
- */
1192
- Api.prototype.get = function (cb) {
1193
- var _this = this;
1194
- return this.httpClient.cachedRequest(this.url, { ttl: this.apiDataTTL }).then(function (data) {
1195
- var resolvedApi = new ResolvedApi(data, _this.httpClient, _this.options);
1196
- cb && cb(null, resolvedApi);
1197
- return resolvedApi;
1198
- }).catch(function (error) {
1199
- cb && cb(error);
1200
- throw error;
1201
- });
1202
- };
1203
- return Api;
1204
- }());
1205
-
1206
- var DefaultClient = /** @class */ (function () {
1207
- function DefaultClient(url, options) {
1208
- this.api = new Api(url, options);
1209
- }
1210
- DefaultClient.prototype.getApi = function () {
1211
- return this.api.get();
1212
- };
1213
- DefaultClient.prototype.everything = function () {
1214
- return this.form('everything');
1215
- };
1216
- DefaultClient.prototype.form = function (formId) {
1217
- return new LazySearchForm(formId, this.api);
1218
- };
1219
- DefaultClient.prototype.query = function (q, optionsOrCallback, cb) {
1220
- return this.getApi().then(function (api) { return api.query(q, optionsOrCallback, cb); });
1221
- };
1222
- DefaultClient.prototype.queryFirst = function (q, optionsOrCallback, cb) {
1223
- return this.getApi().then(function (api) { return api.queryFirst(q, optionsOrCallback, cb); });
1224
- };
1225
- DefaultClient.prototype.getByID = function (id, options, cb) {
1226
- return this.getApi().then(function (api) { return api.getByID(id, options, cb); });
1227
- };
1228
- DefaultClient.prototype.getByIDs = function (ids, options, cb) {
1229
- return this.getApi().then(function (api) { return api.getByIDs(ids, options, cb); });
1230
- };
1231
- DefaultClient.prototype.getByUID = function (type, uid, options, cb) {
1232
- return this.getApi().then(function (api) { return api.getByUID(type, uid, options, cb); });
1233
- };
1234
- DefaultClient.prototype.getSingle = function (type, options, cb) {
1235
- return this.getApi().then(function (api) { return api.getSingle(type, options, cb); });
1236
- };
1237
- DefaultClient.prototype.getBookmark = function (bookmark, options, cb) {
1238
- return this.getApi().then(function (api) { return api.getBookmark(bookmark, options, cb); });
1239
- };
1240
- DefaultClient.prototype.previewSession = function (token, linkResolver, defaultUrl, cb) {
1241
- return this.getApi().then(function (api) { return api.previewSession(token, linkResolver, defaultUrl, cb); });
1242
- };
1243
- DefaultClient.prototype.getPreviewResolver = function (token, documentId) {
1244
- var _this = this;
1245
- var getDocById = function (documentId, maybeOptions) { return _this.getApi().then(function (api) {
1246
- return api.getByID(documentId, maybeOptions);
1247
- }); };
1248
- return createPreviewResolver(token, documentId, getDocById);
1249
- };
1250
- DefaultClient.getApi = function (url, options) {
1251
- var api = new Api(url, options);
1252
- return api.get();
1253
- };
1254
- return DefaultClient;
1255
- }());
1256
-
1257
- var index = {
1258
- experimentCookie: EXPERIMENT_COOKIE,
1259
- previewCookie: PREVIEW_COOKIE,
1260
- Predicates: Predicates,
1261
- Experiments: Experiments,
1262
- Api: Api,
1263
- client: client,
1264
- getApi: getApi,
1265
- api: api,
1266
- };
1267
- function client(url, options) {
1268
- return new DefaultClient(url, options);
1269
- }
1270
- function getApi(url, options) {
1271
- return DefaultClient.getApi(url, options);
1272
- }
1273
- function api(url, options) {
1274
- return getApi(url, options);
1275
- }
1276
-
1277
- export default index;
1278
- //# sourceMappingURL=prismic-javascript.mjs.map