faunadb
Version:
FaunaDB Javascript driver for Node.JS and Browsers
1,680 lines (1,477 loc) • 236 kB
JavaScript
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.faunadb = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
var query = require('./src/query')
var util = require('./src/_util')
var parseJSON = require('./src/_json').parseJSON
module.exports = util.mergeObjects(
{
Client: require('./src/Client'),
Expr: require('./src/Expr'),
PageHelper: require('./src/PageHelper'),
RequestResult: require('./src/RequestResult'),
clientLogger: require('./src/clientLogger'),
errors: require('./src/errors'),
values: require('./src/values'),
query: query,
parseJSON: parseJSON,
},
query
)
},{"./src/Client":11,"./src/Expr":12,"./src/PageHelper":13,"./src/RequestResult":14,"./src/_json":19,"./src/_util":20,"./src/clientLogger":21,"./src/errors":22,"./src/query":23,"./src/values":25}],2:[function(require,module,exports){
'use strict'
exports.byteLength = byteLength
exports.toByteArray = toByteArray
exports.fromByteArray = fromByteArray
var lookup = []
var revLookup = []
var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
for (var i = 0, len = code.length; i < len; ++i) {
lookup[i] = code[i]
revLookup[code.charCodeAt(i)] = i
}
// Support decoding URL-safe base64 strings, as Node.js does.
// See: https://en.wikipedia.org/wiki/Base64#URL_applications
revLookup['-'.charCodeAt(0)] = 62
revLookup['_'.charCodeAt(0)] = 63
function getLens (b64) {
var len = b64.length
if (len % 4 > 0) {
throw new Error('Invalid string. Length must be a multiple of 4')
}
// Trim off extra bytes after placeholder bytes are found
// See: https://github.com/beatgammit/base64-js/issues/42
var validLen = b64.indexOf('=')
if (validLen === -1) validLen = len
var placeHoldersLen = validLen === len
? 0
: 4 - (validLen % 4)
return [validLen, placeHoldersLen]
}
// base64 is 4/3 + up to two characters of the original data
function byteLength (b64) {
var lens = getLens(b64)
var validLen = lens[0]
var placeHoldersLen = lens[1]
return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
}
function _byteLength (b64, validLen, placeHoldersLen) {
return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
}
function toByteArray (b64) {
var tmp
var lens = getLens(b64)
var validLen = lens[0]
var placeHoldersLen = lens[1]
var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))
var curByte = 0
// if there are placeholders, only get up to the last complete 4 chars
var len = placeHoldersLen > 0
? validLen - 4
: validLen
var i
for (i = 0; i < len; i += 4) {
tmp =
(revLookup[b64.charCodeAt(i)] << 18) |
(revLookup[b64.charCodeAt(i + 1)] << 12) |
(revLookup[b64.charCodeAt(i + 2)] << 6) |
revLookup[b64.charCodeAt(i + 3)]
arr[curByte++] = (tmp >> 16) & 0xFF
arr[curByte++] = (tmp >> 8) & 0xFF
arr[curByte++] = tmp & 0xFF
}
if (placeHoldersLen === 2) {
tmp =
(revLookup[b64.charCodeAt(i)] << 2) |
(revLookup[b64.charCodeAt(i + 1)] >> 4)
arr[curByte++] = tmp & 0xFF
}
if (placeHoldersLen === 1) {
tmp =
(revLookup[b64.charCodeAt(i)] << 10) |
(revLookup[b64.charCodeAt(i + 1)] << 4) |
(revLookup[b64.charCodeAt(i + 2)] >> 2)
arr[curByte++] = (tmp >> 8) & 0xFF
arr[curByte++] = tmp & 0xFF
}
return arr
}
function tripletToBase64 (num) {
return lookup[num >> 18 & 0x3F] +
lookup[num >> 12 & 0x3F] +
lookup[num >> 6 & 0x3F] +
lookup[num & 0x3F]
}
function encodeChunk (uint8, start, end) {
var tmp
var output = []
for (var i = start; i < end; i += 3) {
tmp =
((uint8[i] << 16) & 0xFF0000) +
((uint8[i + 1] << 8) & 0xFF00) +
(uint8[i + 2] & 0xFF)
output.push(tripletToBase64(tmp))
}
return output.join('')
}
function fromByteArray (uint8) {
var tmp
var len = uint8.length
var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
var parts = []
var maxChunkLength = 16383 // must be multiple of 3
// go through the array every three bytes, we'll deal with trailing stuff later
for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))
}
// pad the end with zeros, but make sure to not forget the extra bytes
if (extraBytes === 1) {
tmp = uint8[len - 1]
parts.push(
lookup[tmp >> 2] +
lookup[(tmp << 4) & 0x3F] +
'=='
)
} else if (extraBytes === 2) {
tmp = (uint8[len - 2] << 8) + uint8[len - 1]
parts.push(
lookup[tmp >> 10] +
lookup[(tmp >> 4) & 0x3F] +
lookup[(tmp << 2) & 0x3F] +
'='
)
}
return parts.join('')
}
},{}],3:[function(require,module,exports){
},{}],4:[function(require,module,exports){
var global = typeof self !== 'undefined' ? self : this;
var __self__ = (function () {
function F() {
this.fetch = false;
this.DOMException = global.DOMException
}
F.prototype = global;
return new F();
})();
(function(self) {
var irrelevant = (function (exports) {
var support = {
searchParams: 'URLSearchParams' in self,
iterable: 'Symbol' in self && 'iterator' in Symbol,
blob:
'FileReader' in self &&
'Blob' in self &&
(function() {
try {
new Blob();
return true
} catch (e) {
return false
}
})(),
formData: 'FormData' in self,
arrayBuffer: 'ArrayBuffer' in self
};
function isDataView(obj) {
return obj && DataView.prototype.isPrototypeOf(obj)
}
if (support.arrayBuffer) {
var viewClasses = [
'[object Int8Array]',
'[object Uint8Array]',
'[object Uint8ClampedArray]',
'[object Int16Array]',
'[object Uint16Array]',
'[object Int32Array]',
'[object Uint32Array]',
'[object Float32Array]',
'[object Float64Array]'
];
var isArrayBufferView =
ArrayBuffer.isView ||
function(obj) {
return obj && viewClasses.indexOf(Object.prototype.toString.call(obj)) > -1
};
}
function normalizeName(name) {
if (typeof name !== 'string') {
name = String(name);
}
if (/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(name)) {
throw new TypeError('Invalid character in header field name')
}
return name.toLowerCase()
}
function normalizeValue(value) {
if (typeof value !== 'string') {
value = String(value);
}
return value
}
// Build a destructive iterator for the value list
function iteratorFor(items) {
var iterator = {
next: function() {
var value = items.shift();
return {done: value === undefined, value: value}
}
};
if (support.iterable) {
iterator[Symbol.iterator] = function() {
return iterator
};
}
return iterator
}
function Headers(headers) {
this.map = {};
if (headers instanceof Headers) {
headers.forEach(function(value, name) {
this.append(name, value);
}, this);
} else if (Array.isArray(headers)) {
headers.forEach(function(header) {
this.append(header[0], header[1]);
}, this);
} else if (headers) {
Object.getOwnPropertyNames(headers).forEach(function(name) {
this.append(name, headers[name]);
}, this);
}
}
Headers.prototype.append = function(name, value) {
name = normalizeName(name);
value = normalizeValue(value);
var oldValue = this.map[name];
this.map[name] = oldValue ? oldValue + ', ' + value : value;
};
Headers.prototype['delete'] = function(name) {
delete this.map[normalizeName(name)];
};
Headers.prototype.get = function(name) {
name = normalizeName(name);
return this.has(name) ? this.map[name] : null
};
Headers.prototype.has = function(name) {
return this.map.hasOwnProperty(normalizeName(name))
};
Headers.prototype.set = function(name, value) {
this.map[normalizeName(name)] = normalizeValue(value);
};
Headers.prototype.forEach = function(callback, thisArg) {
for (var name in this.map) {
if (this.map.hasOwnProperty(name)) {
callback.call(thisArg, this.map[name], name, this);
}
}
};
Headers.prototype.keys = function() {
var items = [];
this.forEach(function(value, name) {
items.push(name);
});
return iteratorFor(items)
};
Headers.prototype.values = function() {
var items = [];
this.forEach(function(value) {
items.push(value);
});
return iteratorFor(items)
};
Headers.prototype.entries = function() {
var items = [];
this.forEach(function(value, name) {
items.push([name, value]);
});
return iteratorFor(items)
};
if (support.iterable) {
Headers.prototype[Symbol.iterator] = Headers.prototype.entries;
}
function consumed(body) {
if (body.bodyUsed) {
return Promise.reject(new TypeError('Already read'))
}
body.bodyUsed = true;
}
function fileReaderReady(reader) {
return new Promise(function(resolve, reject) {
reader.onload = function() {
resolve(reader.result);
};
reader.onerror = function() {
reject(reader.error);
};
})
}
function readBlobAsArrayBuffer(blob) {
var reader = new FileReader();
var promise = fileReaderReady(reader);
reader.readAsArrayBuffer(blob);
return promise
}
function readBlobAsText(blob) {
var reader = new FileReader();
var promise = fileReaderReady(reader);
reader.readAsText(blob);
return promise
}
function readArrayBufferAsText(buf) {
var view = new Uint8Array(buf);
var chars = new Array(view.length);
for (var i = 0; i < view.length; i++) {
chars[i] = String.fromCharCode(view[i]);
}
return chars.join('')
}
function bufferClone(buf) {
if (buf.slice) {
return buf.slice(0)
} else {
var view = new Uint8Array(buf.byteLength);
view.set(new Uint8Array(buf));
return view.buffer
}
}
function Body() {
this.bodyUsed = false;
this._initBody = function(body) {
this._bodyInit = body;
if (!body) {
this._bodyText = '';
} else if (typeof body === 'string') {
this._bodyText = body;
} else if (support.blob && Blob.prototype.isPrototypeOf(body)) {
this._bodyBlob = body;
} else if (support.formData && FormData.prototype.isPrototypeOf(body)) {
this._bodyFormData = body;
} else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) {
this._bodyText = body.toString();
} else if (support.arrayBuffer && support.blob && isDataView(body)) {
this._bodyArrayBuffer = bufferClone(body.buffer);
// IE 10-11 can't handle a DataView body.
this._bodyInit = new Blob([this._bodyArrayBuffer]);
} else if (support.arrayBuffer && (ArrayBuffer.prototype.isPrototypeOf(body) || isArrayBufferView(body))) {
this._bodyArrayBuffer = bufferClone(body);
} else {
this._bodyText = body = Object.prototype.toString.call(body);
}
if (!this.headers.get('content-type')) {
if (typeof body === 'string') {
this.headers.set('content-type', 'text/plain;charset=UTF-8');
} else if (this._bodyBlob && this._bodyBlob.type) {
this.headers.set('content-type', this._bodyBlob.type);
} else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) {
this.headers.set('content-type', 'application/x-www-form-urlencoded;charset=UTF-8');
}
}
};
if (support.blob) {
this.blob = function() {
var rejected = consumed(this);
if (rejected) {
return rejected
}
if (this._bodyBlob) {
return Promise.resolve(this._bodyBlob)
} else if (this._bodyArrayBuffer) {
return Promise.resolve(new Blob([this._bodyArrayBuffer]))
} else if (this._bodyFormData) {
throw new Error('could not read FormData body as blob')
} else {
return Promise.resolve(new Blob([this._bodyText]))
}
};
this.arrayBuffer = function() {
if (this._bodyArrayBuffer) {
return consumed(this) || Promise.resolve(this._bodyArrayBuffer)
} else {
return this.blob().then(readBlobAsArrayBuffer)
}
};
}
this.text = function() {
var rejected = consumed(this);
if (rejected) {
return rejected
}
if (this._bodyBlob) {
return readBlobAsText(this._bodyBlob)
} else if (this._bodyArrayBuffer) {
return Promise.resolve(readArrayBufferAsText(this._bodyArrayBuffer))
} else if (this._bodyFormData) {
throw new Error('could not read FormData body as text')
} else {
return Promise.resolve(this._bodyText)
}
};
if (support.formData) {
this.formData = function() {
return this.text().then(decode)
};
}
this.json = function() {
return this.text().then(JSON.parse)
};
return this
}
// HTTP methods whose capitalization should be normalized
var methods = ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST', 'PUT'];
function normalizeMethod(method) {
var upcased = method.toUpperCase();
return methods.indexOf(upcased) > -1 ? upcased : method
}
function Request(input, options) {
options = options || {};
var body = options.body;
if (input instanceof Request) {
if (input.bodyUsed) {
throw new TypeError('Already read')
}
this.url = input.url;
this.credentials = input.credentials;
if (!options.headers) {
this.headers = new Headers(input.headers);
}
this.method = input.method;
this.mode = input.mode;
this.signal = input.signal;
if (!body && input._bodyInit != null) {
body = input._bodyInit;
input.bodyUsed = true;
}
} else {
this.url = String(input);
}
this.credentials = options.credentials || this.credentials || 'same-origin';
if (options.headers || !this.headers) {
this.headers = new Headers(options.headers);
}
this.method = normalizeMethod(options.method || this.method || 'GET');
this.mode = options.mode || this.mode || null;
this.signal = options.signal || this.signal;
this.referrer = null;
if ((this.method === 'GET' || this.method === 'HEAD') && body) {
throw new TypeError('Body not allowed for GET or HEAD requests')
}
this._initBody(body);
}
Request.prototype.clone = function() {
return new Request(this, {body: this._bodyInit})
};
function decode(body) {
var form = new FormData();
body
.trim()
.split('&')
.forEach(function(bytes) {
if (bytes) {
var split = bytes.split('=');
var name = split.shift().replace(/\+/g, ' ');
var value = split.join('=').replace(/\+/g, ' ');
form.append(decodeURIComponent(name), decodeURIComponent(value));
}
});
return form
}
function parseHeaders(rawHeaders) {
var headers = new Headers();
// Replace instances of \r\n and \n followed by at least one space or horizontal tab with a space
// https://tools.ietf.org/html/rfc7230#section-3.2
var preProcessedHeaders = rawHeaders.replace(/\r?\n[\t ]+/g, ' ');
preProcessedHeaders.split(/\r?\n/).forEach(function(line) {
var parts = line.split(':');
var key = parts.shift().trim();
if (key) {
var value = parts.join(':').trim();
headers.append(key, value);
}
});
return headers
}
Body.call(Request.prototype);
function Response(bodyInit, options) {
if (!options) {
options = {};
}
this.type = 'default';
this.status = options.status === undefined ? 200 : options.status;
this.ok = this.status >= 200 && this.status < 300;
this.statusText = 'statusText' in options ? options.statusText : 'OK';
this.headers = new Headers(options.headers);
this.url = options.url || '';
this._initBody(bodyInit);
}
Body.call(Response.prototype);
Response.prototype.clone = function() {
return new Response(this._bodyInit, {
status: this.status,
statusText: this.statusText,
headers: new Headers(this.headers),
url: this.url
})
};
Response.error = function() {
var response = new Response(null, {status: 0, statusText: ''});
response.type = 'error';
return response
};
var redirectStatuses = [301, 302, 303, 307, 308];
Response.redirect = function(url, status) {
if (redirectStatuses.indexOf(status) === -1) {
throw new RangeError('Invalid status code')
}
return new Response(null, {status: status, headers: {location: url}})
};
exports.DOMException = self.DOMException;
try {
new exports.DOMException();
} catch (err) {
exports.DOMException = function(message, name) {
this.message = message;
this.name = name;
var error = Error(message);
this.stack = error.stack;
};
exports.DOMException.prototype = Object.create(Error.prototype);
exports.DOMException.prototype.constructor = exports.DOMException;
}
function fetch(input, init) {
return new Promise(function(resolve, reject) {
var request = new Request(input, init);
if (request.signal && request.signal.aborted) {
return reject(new exports.DOMException('Aborted', 'AbortError'))
}
var xhr = new XMLHttpRequest();
function abortXhr() {
xhr.abort();
}
xhr.onload = function() {
var options = {
status: xhr.status,
statusText: xhr.statusText,
headers: parseHeaders(xhr.getAllResponseHeaders() || '')
};
options.url = 'responseURL' in xhr ? xhr.responseURL : options.headers.get('X-Request-URL');
var body = 'response' in xhr ? xhr.response : xhr.responseText;
resolve(new Response(body, options));
};
xhr.onerror = function() {
reject(new TypeError('Network request failed'));
};
xhr.ontimeout = function() {
reject(new TypeError('Network request failed'));
};
xhr.onabort = function() {
reject(new exports.DOMException('Aborted', 'AbortError'));
};
xhr.open(request.method, request.url, true);
if (request.credentials === 'include') {
xhr.withCredentials = true;
} else if (request.credentials === 'omit') {
xhr.withCredentials = false;
}
if ('responseType' in xhr && support.blob) {
xhr.responseType = 'blob';
}
request.headers.forEach(function(value, name) {
xhr.setRequestHeader(name, value);
});
if (request.signal) {
request.signal.addEventListener('abort', abortXhr);
xhr.onreadystatechange = function() {
// DONE (success or failure)
if (xhr.readyState === 4) {
request.signal.removeEventListener('abort', abortXhr);
}
};
}
xhr.send(typeof request._bodyInit === 'undefined' ? null : request._bodyInit);
})
}
fetch.polyfill = true;
if (!self.fetch) {
self.fetch = fetch;
self.Headers = Headers;
self.Request = Request;
self.Response = Response;
}
exports.Headers = Headers;
exports.Request = Request;
exports.Response = Response;
exports.fetch = fetch;
Object.defineProperty(exports, '__esModule', { value: true });
return exports;
})({});
})(__self__);
__self__.fetch.ponyfill = true;
// Remove "polyfill" property added by whatwg-fetch
delete __self__.fetch.polyfill;
// Choose between native implementation (global) or custom implementation (__self__)
// var ctx = global.fetch ? global : __self__;
var ctx = __self__; // this line disable service worker support temporarily
exports = ctx.fetch // To enable: import fetch from 'cross-fetch'
exports.default = ctx.fetch // For TypeScript consumers without esModuleInterop.
exports.fetch = ctx.fetch // To enable: import {fetch} from 'cross-fetch'
exports.Headers = ctx.Headers
exports.Request = ctx.Request
exports.Response = ctx.Response
module.exports = exports
},{}],5:[function(require,module,exports){
'use strict';
module.exports = annotate;
function annotate(fn) {
if (typeof fn !== 'function') {
throw new Error('Could not parse function signature for injection dependencies: Object is not a function');
}
if (!fn.length) return [];
var injects = /^()\(?([^)=]*)\)? *=>/.exec(fn + '') ||
/^[^(]+([^ \(]*) *\(([^\)]*)\)/.exec(fn + '');
if (!injects) {
throw new Error('Could not parse function signature for injection dependencies: ' + fn + '');
}
var argumentString = injects[2]
// Strip multi-line comments:
// Uses the lazy-quantifier (.*?): http://www.rexegg.com/regex-quantifiers.html#lazy_solution
.replace(/\/\*[\S\s]*?\*\//g, ' ')
// Strip single-line comments:
.replace(/\/\/.*/g, ' ');
function groupSubArguments(_, type, keys) {
return type + keys.split(',')
.map(function (arg) {
return arg && arg.trim();
})
.filter(Boolean)
.join('@');
}
argumentString = argumentString.replace(/(\{)([^}]*)\}/g, groupSubArguments);
argumentString = argumentString.replace(/(\[)([^}]*)\]/g, groupSubArguments);
return argumentString.split(',')
.map(function (arg) {
return arg && arg.trim();
})
.map(function (arg) {
if (arg[0] === '{') {
return arg.substring(1).split('@');
}
if (arg[0] === '[') {
return { items: arg.substring(1).split('@') };
}
return arg;
})
.filter(Boolean);
}
},{}],6:[function(require,module,exports){
'use strict'
const _global =
typeof self !== 'undefined'
? self
: typeof window !== 'undefined'
? window
: /* otherwise */ undefined
if (!_global) {
throw new Error(
`Unable to find global scope. Are you sure this is running in the browser?`
)
}
if (!_global.AbortController) {
throw new Error(
`Could not find "AbortController" in the global scope. You need to polyfill it first`
)
}
module.exports.AbortController = _global.AbortController
},{}],7:[function(require,module,exports){
/*
object-assign
(c) Sindre Sorhus
@license MIT
*/
'use strict';
/* eslint-disable no-unused-vars */
var getOwnPropertySymbols = Object.getOwnPropertySymbols;
var hasOwnProperty = Object.prototype.hasOwnProperty;
var propIsEnumerable = Object.prototype.propertyIsEnumerable;
function toObject(val) {
if (val === null || val === undefined) {
throw new TypeError('Object.assign cannot be called with null or undefined');
}
return Object(val);
}
function shouldUseNative() {
try {
if (!Object.assign) {
return false;
}
// Detect buggy property enumeration order in older V8 versions.
// https://bugs.chromium.org/p/v8/issues/detail?id=4118
var test1 = new String('abc'); // eslint-disable-line no-new-wrappers
test1[5] = 'de';
if (Object.getOwnPropertyNames(test1)[0] === '5') {
return false;
}
// https://bugs.chromium.org/p/v8/issues/detail?id=3056
var test2 = {};
for (var i = 0; i < 10; i++) {
test2['_' + String.fromCharCode(i)] = i;
}
var order2 = Object.getOwnPropertyNames(test2).map(function (n) {
return test2[n];
});
if (order2.join('') !== '0123456789') {
return false;
}
// https://bugs.chromium.org/p/v8/issues/detail?id=3056
var test3 = {};
'abcdefghijklmnopqrst'.split('').forEach(function (letter) {
test3[letter] = letter;
});
if (Object.keys(Object.assign({}, test3)).join('') !==
'abcdefghijklmnopqrst') {
return false;
}
return true;
} catch (err) {
// We don't expect any of the above to throw, but better to be safe.
return false;
}
}
module.exports = shouldUseNative() ? Object.assign : function (target, source) {
var from;
var to = toObject(target);
var symbols;
for (var s = 1; s < arguments.length; s++) {
from = Object(arguments[s]);
for (var key in from) {
if (hasOwnProperty.call(from, key)) {
to[key] = from[key];
}
}
if (getOwnPropertySymbols) {
symbols = getOwnPropertySymbols(from);
for (var i = 0; i < symbols.length; i++) {
if (propIsEnumerable.call(from, symbols[i])) {
to[symbols[i]] = from[symbols[i]];
}
}
}
}
return to;
};
},{}],8:[function(require,module,exports){
// shim for using process in browser
var process = module.exports = {};
// cached from whatever global is present so that test runners that stub it
// don't break things. But we need to wrap it in a try catch in case it is
// wrapped in strict mode code which doesn't define any globals. It's inside a
// function because try/catches deoptimize in certain engines.
var cachedSetTimeout;
var cachedClearTimeout;
function defaultSetTimout() {
throw new Error('setTimeout has not been defined');
}
function defaultClearTimeout () {
throw new Error('clearTimeout has not been defined');
}
(function () {
try {
if (typeof setTimeout === 'function') {
cachedSetTimeout = setTimeout;
} else {
cachedSetTimeout = defaultSetTimout;
}
} catch (e) {
cachedSetTimeout = defaultSetTimout;
}
try {
if (typeof clearTimeout === 'function') {
cachedClearTimeout = clearTimeout;
} else {
cachedClearTimeout = defaultClearTimeout;
}
} catch (e) {
cachedClearTimeout = defaultClearTimeout;
}
} ())
function runTimeout(fun) {
if (cachedSetTimeout === setTimeout) {
//normal enviroments in sane situations
return setTimeout(fun, 0);
}
// if setTimeout wasn't available but was latter defined
if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
cachedSetTimeout = setTimeout;
return setTimeout(fun, 0);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedSetTimeout(fun, 0);
} catch(e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedSetTimeout.call(null, fun, 0);
} catch(e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
return cachedSetTimeout.call(this, fun, 0);
}
}
}
function runClearTimeout(marker) {
if (cachedClearTimeout === clearTimeout) {
//normal enviroments in sane situations
return clearTimeout(marker);
}
// if clearTimeout wasn't available but was latter defined
if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
cachedClearTimeout = clearTimeout;
return clearTimeout(marker);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedClearTimeout(marker);
} catch (e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedClearTimeout.call(null, marker);
} catch (e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
// Some versions of I.E. have different rules for clearTimeout vs setTimeout
return cachedClearTimeout.call(this, marker);
}
}
}
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;
function cleanUpNextTick() {
if (!draining || !currentQueue) {
return;
}
draining = false;
if (currentQueue.length) {
queue = currentQueue.concat(queue);
} else {
queueIndex = -1;
}
if (queue.length) {
drainQueue();
}
}
function drainQueue() {
if (draining) {
return;
}
var timeout = runTimeout(cleanUpNextTick);
draining = true;
var len = queue.length;
while(len) {
currentQueue = queue;
queue = [];
while (++queueIndex < len) {
if (currentQueue) {
currentQueue[queueIndex].run();
}
}
queueIndex = -1;
len = queue.length;
}
currentQueue = null;
draining = false;
runClearTimeout(timeout);
}
process.nextTick = function (fun) {
var args = new Array(arguments.length - 1);
if (arguments.length > 1) {
for (var i = 1; i < arguments.length; i++) {
args[i - 1] = arguments[i];
}
}
queue.push(new Item(fun, args));
if (queue.length === 1 && !draining) {
runTimeout(drainQueue);
}
};
// v8 likes predictible objects
function Item(fun, array) {
this.fun = fun;
this.array = array;
}
Item.prototype.run = function () {
this.fun.apply(null, this.array);
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.prependListener = noop;
process.prependOnceListener = noop;
process.listeners = function (name) { return [] }
process.binding = function (name) {
throw new Error('process.binding is not supported');
};
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };
},{}],9:[function(require,module,exports){
(function (global){(function (){
/**
* Module exports.
*/
module.exports = deprecate;
/**
* Mark that a method should not be used.
* Returns a modified function which warns once by default.
*
* If `localStorage.noDeprecation = true` is set, then it is a no-op.
*
* If `localStorage.throwDeprecation = true` is set, then deprecated functions
* will throw an Error when invoked.
*
* If `localStorage.traceDeprecation = true` is set, then deprecated functions
* will invoke `console.trace()` instead of `console.error()`.
*
* @param {Function} fn - the function to deprecate
* @param {String} msg - the string to print to the console when `fn` is invoked
* @returns {Function} a new "deprecated" version of `fn`
* @api public
*/
function deprecate (fn, msg) {
if (config('noDeprecation')) {
return fn;
}
var warned = false;
function deprecated() {
if (!warned) {
if (config('throwDeprecation')) {
throw new Error(msg);
} else if (config('traceDeprecation')) {
console.trace(msg);
} else {
console.warn(msg);
}
warned = true;
}
return fn.apply(this, arguments);
}
return deprecated;
}
/**
* Checks `localStorage` for boolean values for the given `name`.
*
* @param {String} name
* @returns {Boolean}
* @api private
*/
function config (name) {
// accessing global.localStorage can trigger a DOMException in sandboxed iframes
try {
if (!global.localStorage) return false;
} catch (_) {
return false;
}
var val = global.localStorage[name];
if (null == val) return false;
return String(val).toLowerCase() === 'true';
}
}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],10:[function(require,module,exports){
module.exports={
"name": "faunadb",
"version": "4.8.2",
"apiVersion": "4",
"description": "FaunaDB Javascript driver for Node.JS and Browsers",
"homepage": "https://fauna.com",
"repository": "fauna/faunadb-js",
"license": "MPL-2.0",
"keywords": [
"database",
"fauna",
"official",
"driver"
],
"bugs": {
"url": "https://github.com/fauna/faunadb-js/issues"
},
"files": [
"index.d.ts",
"src/",
"dist/",
"tools/printReleaseNotes.js"
],
"main": "index.js",
"scripts": {
"doc": "jsdoc -c ./jsdoc.json",
"browserify": "browserify index.js --standalone faunadb -o dist/faunadb.js",
"browserify-min": "browserify index.js --standalone faunadb | terser -c -m --keep-fnames --keep-classnames -o dist/faunadb-min.js",
"prettify": "prettier --write \"{src,test}/**/*.{js,ts}\"",
"test": "jest --env=node --verbose=true --forceExit --runInBand ./test",
"posttest": "node ./test/afterComplete",
"semantic-release": "semantic-release",
"wp": "webpack",
"postinstall": "node ./tools/printReleaseNotes",
"postupdate": "node ./tools/printReleaseNotes",
"load-test": "node ./tools/loadTest"
},
"types": "index.d.ts",
"dependencies": {
"base64-js": "^1.2.0",
"boxen": "^5.0.1",
"btoa-lite": "^1.0.0",
"chalk": "^4.1.1",
"cross-fetch": "^3.1.5",
"dotenv": "^8.2.0",
"fn-annotate": "^1.1.3",
"node-abort-controller": "^3.0.1",
"object-assign": "^4.1.0",
"util-deprecate": "^1.0.2"
},
"devDependencies": {
"ansi-regex": ">=5.0.1",
"browserify": "^16.2.2",
"eslint": "^5.3.0",
"eslint-config-prettier": "^6.5.0",
"eslint-plugin-prettier": "^3.1.1",
"husky": "^7.0.4",
"jest": "^27.4.7",
"jsdoc": "^3.6.10",
"json-schema": ">=0.4.0",
"lint-staged": ">=8",
"marked": ">=4.0.10",
"prettier": "1.18.2",
"semantic-release": "^19.0.3",
"terser": "^4.3.9",
"webpack": "^5.23.0",
"webpack-cli": "^4.5.0",
"yargs": "^16.2.0"
},
"lint-staged": {
"*.{js,css,json,md}": [
"prettier --write",
"git add"
],
"*.js": [
"eslint --fix",
"git add"
]
},
"release": {
"branches": [
"main"
]
},
"browser": {
"http2": false,
"http": false,
"https": false,
"os": false,
"util": false,
"boxen": false,
"chalk": false
}
}
},{}],11:[function(require,module,exports){
'use strict'
var packageJson = require('../package.json')
var PageHelper = require('./PageHelper')
var RequestResult = require('./RequestResult')
var errors = require('./errors')
var http = require('./_http')
var json = require('./_json')
var query = require('./query')
var stream = require('./stream')
var util = require('./_util')
var values = require('./values')
/**
* The callback that will be executed after every completed request.
*
* @callback Client~observerCallback
* @param {RequestResult} res
*/
/**
* **WARNING: This is an experimental feature. There are no guarantees to
* its API stability and/or service availability. DO NOT USE IT IN
* PRODUCTION**.
*
* Creates a subscription to the result of the given read-only expression. When
* executed, the expression must only perform reads and produce a single
* streamable type, such as a reference or a version. Expressions that attempt
* to perform writes or produce non-streamable types will result in an error.
* Otherwise, any expression can be used to initiate a stream, including
* user-defined function calls.
*
* The subscription returned by this method does not issue any requests until
* the {@link module:stream~Subscription#start} method is called. Make sure to
* subscribe to the events of interest, otherwise the received events are simply
* ignored. For example:
*
* ```
* client.stream(document.ref)
* .on('version', version => console.log(version))
* .on('error', error => console.log(error))
* .start()
* ```
*
* Please note that streams are not temporal, meaning that there is no option to
* configure its starting timestamp. The stream will, however, state its initial
* subscription time via the {@link module:stream~Subscription#event:start}
* event. A common programming mistake is to read a document, then initiate a
* subscription. This approach can miss events that occurred between the initial
* read and the subscription request. To prevent event loss, make sure the
* subscription has started before performing a data load. The following example
* buffer events until the document's data is loaded:
*
* ```
* var buffer = []
* var loaded = false
*
* client.stream(document.ref)
* .on('start', ts => {
* loadData(ts).then(data => {
* processData(data)
* processBuffer(buffer)
* loaded = true
* })
* })
* .on('version', version => {
* if (loaded) {
* processVersion(version)
* } else {
* buffer.push(version)
* }
* })
* .start()
* ```
*
* The reduce boilerplate, the `document` helper implements a similar
* functionality, except it discards events prior to the document's snapshot
* time. The expression given to this helper must be a reference as it
* internally runs a {@link module:query~Get} call with it. The example above
* can be rewritten as:
*
* ```
* client.stream.document(document.ref)
* .on('snapshot', data => processData(data))
* .on('version', version => processVersion(version))
* .start()
* ```
*
* Be aware that streams are not available in all browsers. If the client can't
* initiate a stream, an error event with the {@link
* module:errors~StreamsNotSupported} error will be emmited.
*
* To stop a subscription, call the {@link module:stream~Subscription#close}
* method:
*
* ```
* var subscription = client.stream(document.ref)
* .on('version', version => processVersion(version))
* .start()
*
* // ...
* subscription.close()
* ```
*
* @param {module:query~ExprArg} expression
* The expression to subscribe to. Created from {@link module:query}
* functions.
*
* @param {?module:stream~Options} options
* Object that configures the stream.
*
* @property {function} document
* A document stream helper. See {@link Client#stream} for more information.
*
* @see module:stream~Subscription
*
* @function
* @name Client#stream
* @returns {module:stream~Subscription} A new subscription instance.
*/
/**
* A client for interacting with FaunaDB.
*
* Users will mainly call the {@link Client#query} method to execute queries, or
* the {@link Client#stream} method to subscribe to streams.
*
* See the [FaunaDB Documentation](https://fauna.com/documentation) for detailed examples.
*
* All methods return promises containing a JSON object that represents the FaunaDB response.
* Literal types in the response object will remain as strings, Arrays, and objects.
* FaunaDB types, such as {@link Ref}, {@link SetRef}, {@link FaunaTime}, and {@link FaunaDate} will
* be converted into the appropriate object.
*
* (So if a response contains `{ "@ref": "collections/frogs/123" }`,
* it will be returned as `new Ref("collections/frogs/123")`.)
*
* @constructor
* @param {?Object} options
* Object that configures this FaunaDB client.
* @param {?string} options.endpoint
* Full URL for the FaunaDB server.
* @param {?string} options.domain
* Base URL for the FaunaDB server.
* @param {?('http'|'https')} options.scheme
* HTTP scheme to use.
* @param {?number} options.port
* Port of the FaunaDB server.
* @param {?string} options.secret FaunaDB secret (see [Reference Documentation](https://app.fauna.com/documentation/intro/security))
* @param {?number} options.timeout Read timeout in seconds.
* @param {?Client~observerCallback} options.observer
* Callback that will be called after every completed request.
* @param {?boolean} options.keepAlive
* Configures http/https keepAlive option (ignored in browser environments)
* @param {?{ string: string }} options.headers
* Optional headers to send with requests
* @param {?fetch} options.fetch
* a fetch compatible [API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) for making a request
* @param {?number} options.queryTimeout
* Sets the maximum amount of time (in milliseconds) for query execution on the server
* @param {?number} options.http2SessionIdleTime
* Sets the maximum amount of time (in milliseconds) an HTTP2 session may live
* when there's no activity. Must be a non-negative integer, with a maximum value of 5000.
* If an invalid value is passed a default of 500 ms is applied. If a value
* exceeding 5000 ms is passed (e.g. Infinity) the maximum of 5000 ms is applied.
* Only applicable for NodeJS environment (when http2 module is used).
* can also be configured via the FAUNADB_HTTP2_SESSION_IDLE_TIME environment variable
* which has the highest priority and overrides the option passed into the Client constructor.
* @param {?boolean} options.checkNewVersion
* Enabled by default. Prints a message to the terminal when a newer driver is available.
* @param {?boolean} options.metrics
* Disabled by default. Controls whether or not query metrics are returned.
*/
function Client(options) {
const http2SessionIdleTime = getHttp2SessionIdleTime(
options ? options.http2SessionIdleTime : undefined
)
if (options) options.http2SessionIdleTime = http2SessionIdleTime
options = util.applyDefaults(options, {
endpoint: null,
domain: 'db.fauna.com',
scheme: 'https',
port: null,
secret: null,
timeout: 60,
observer: null,
keepAlive: true,
headers: {},
fetch: undefined,
queryTimeout: null,
http2SessionIdleTime,
checkNewVersion: false,
})
this._observer = options.observer
this._http = new http.HttpClient(options)
this.stream = stream.StreamAPI(this)
}
/**
* Current API version.
*
* @type {string}
*/
Client.apiVersion = packageJson.apiVersion
/**
* Executes a query via the FaunaDB Query API.
* See the [docs](https://app.fauna.com/documentation/reference/queryapi),
* and the query functions in this documentation.
* @param expression {module:query~ExprArg}
* The query to execute. Created from {@link module:query} functions.
* @param {?Object} options
* Object that configures the current query, overriding FaunaDB client options.
* @param {?string} options.secret FaunaDB secret (see [Reference Documentation](https://app.fauna.com/documentation/intro/security))
* @return {external:Promise<Object>} FaunaDB response object.
*/
Client.prototype.query = function(expression, options) {
query.arity.between(1, 2, arguments, 'Client.prototype.query')
options = Object.assign({}, this._globalQueryOptions, options)
return this._execute('POST', '', query.wrap(expression), null, options)
}
/**
* Returns a {@link PageHelper} for the given Query expression.
* This provides a helpful API for paginating over FaunaDB responses.
* @param expression {Expr}
* The Query expression to paginate over.
* @param params {Object}
* Options to be passed to the paginate function. See [paginate](https://app.fauna.com/documentation/reference/queryapi#read-functions).
* @param options {?Object}
* Object that configures the current pagination queries, overriding FaunaDB client options.
* @param {?string} options.secret FaunaDB secret (see [Reference Documentation](https://app.fauna.com/documentation/intro/security))
* @returns {PageHelper} A PageHelper that wraps the provided expression.
*/
Client.prototype.paginate = function(expression, params, options) {
params = util.defaults(params, {})
options = util.defaults(options, {})
return new PageHelper(this, expression, params, options)
}
/**
* Sends a `ping` request to FaunaDB.
* @return {external:Promise<string>} Ping response.
*/
Client.prototype.ping = function(scope, timeout) {
return this._execute('GET', 'ping', null, { scope: scope, timeout: timeout })
}
/**
* Get the freshest timestamp reported to this client.
* @returns {number} the last seen transaction time
*/
Client.prototype.getLastTxnTime = function() {
return this._http.getLastTxnTime()
}
/**
* Sync the freshest timestamp seen by this client.
*
* This has no effect if staler than currently stored timestamp.
* WARNING: This should be used only when coordinating timestamps across
* multiple clients. Moving the timestamp arbitrarily forward into
* the future will cause transactions to stall.
* @param time {number} the last seen transaction time
*/
Client.prototype.syncLastTxnTime = function(time) {
this._http.syncLastTxnTime(time)
}
/**
* Closes the client session and cleans up any held resources.
* By default, it will wait for any ongoing requests to complete on their own;
* streaming requests are terminated forcibly. Any subsequent requests will
* error after the .close method is called.
* Should be used at application termination in order to release any open resources
* and allow the process to terminate e.g. when the custom http2SessionIdleTime parameter is used.
*
* @param {?object} opts Close options.
* @param {?boolean} opts.force Specifying this property will force any ongoing
* requests to terminate instead of gracefully waiting until they complete.
* This may result in an ERR_HTTP2_STREAM_CANCEL error for NodeJS.
* @returns {Promise<void>}
*/
Client.prototype.close = function(opts) {
return this._http.close(opts)
}
/**
* Executes a query via the FaunaDB Query API.
* See the [docs](https://app.fauna.com/documentation/reference/queryapi),
* and the query functions in this documentation.
* @param expression {module:query~ExprArg}
* The query to execute. Created from {@link module:query} functions.
* @param {?Object} options
* Object that configures the current query, overriding FaunaDB client options.
* @param {?string} options.secret FaunaDB secret (see [Reference Documentation](https://app.fauna.com/documentation/intro/security))
* @return {external:Promise<Object>} {value, metrics} An object containing the FaunaDB response object and the list of query metrics incurred by the request.
*/
Client.prototype.queryWithMetrics = function(expression, options) {
query.arity.between(1, 2, arguments, 'Client.prototype.query')
return this._execute('POST', '', query.wrap(expression), null, options, true)
}
Client.prototype._execute = function(
method,
path,
data,
query,
options,
returnMetrics = false
) {
query = util.defaults(query, null)
if (
path instanceof values.Ref ||
util.checkInstanceHasProperty(path, '_isFaunaRef')
) {
path = path.value
}
if (query !== null) {
query = util.removeUndefinedValues(query)
}
var startTime = Date.now()
var self = this
var body =
['GET', 'HEAD'].indexOf(method) >= 0 ? undefined : JSON.stringify(data)
return this._http
.execute(
Object.assign({}, options, {
path: path,
query: query,
method: method,
body: body,
})
)
.then(function(response) {
// Receiving a 200 with no body/content indicates an issue with core router
if (
response.status === 200 &&
(response.body.length === 0 ||
response.headers['content-length'] === '0')
) {
throw new errors.ProtocolError(
'There was an issue communicating with Fauna. Response is empty. Please try again.'
)
}
var endTime = Date.now()
var responseObject = json.parseJSON(response.body)
var result = new RequestResult(
method,
path,
query,
body,
data,
response.body,
responseObject,
response.status,
response.headers,
startTime,
endTime
)
self._handleRequestResult(response, result, options)
const metricsHeaders = [
'x-compute-ops',
'x-byte-read-ops',
'x-byte-write-ops',
'x-query-time',
'x-txn-retries',
]
if (returnMetrics) {
return {
value: responseObject['resource'],
metrics: Object.fromEntries(
Array.from(Object.entries(response.headers))
.filter(([k, v]) => metricsHeaders.includes(k))
.map(([k, v]) => [k, parseInt(v)])
),
}
} else {
return responseObject['resource']
}
})
}
Client.prototype._handleRequestResult = function(response, result, options) {
var txnTimeHeaderKey = 'x-txn-time'
if (response.headers[txnTimeHeaderKey] != null) {
this.syncLastTxnTime(parseInt(response.headers[txnTimeHeaderKey], 10))
}
var observers = [this._observer, options && options.observer]
observers.forEach(observer => {
if (typeof observer == 'function') {
observer(result, this)
}
})
errors.FaunaHTTPError.raiseForStatusCode(result)
}
function getHttp2SessionIdleTime(configuredIdleTime) {
const maxIdleTime = 5000
const defaultIdleTime = 500
const envIdleTime = util.getEnvVariable('FAUNADB_HTTP2_SESSION_IDLE_TIME')
var value = defaultIdleTime
// attemp to set the idle time to the env value and then the configured value
const values = [envIdleTime, configuredIdleTime]
for (const rawValue of values) {
const parsedValue =
r