fauna
Version:
A driver to query Fauna databases in browsers, Node.js, and other Javascript runtimes
1,583 lines (1,565 loc) • 80.3 kB
JavaScript
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __commonJS = (cb, mod) => function __require() {
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var __accessCheck = (obj, member, msg) => {
if (!member.has(obj))
throw TypeError("Cannot " + msg);
};
var __privateGet = (obj, member, getter) => {
__accessCheck(obj, member, "read from private field");
return getter ? getter.call(obj) : member.get(obj);
};
var __privateAdd = (obj, member, value) => {
if (member.has(obj))
throw TypeError("Cannot add the same private member more than once");
member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
};
var __privateSet = (obj, member, value, setter) => {
__accessCheck(obj, member, "write to private field");
setter ? setter.call(obj, value) : member.set(obj, value);
return value;
};
var __privateWrapper = (obj, member, setter, getter) => ({
set _(value) {
__privateSet(obj, member, value, setter);
},
get _() {
return __privateGet(obj, member, getter);
}
});
var __privateMethod = (obj, member, method) => {
__accessCheck(obj, member, "access private method");
return method;
};
// node_modules/base64-js/index.js
var require_base64_js = __commonJS({
"node_modules/base64-js/index.js"(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 (i = 0, len = code.length; i < len; ++i) {
lookup[i] = code[i];
revLookup[code.charCodeAt(i)] = i;
}
var i;
var len;
revLookup["-".charCodeAt(0)] = 62;
revLookup["_".charCodeAt(0)] = 63;
function getLens(b64) {
var len2 = b64.length;
if (len2 % 4 > 0) {
throw new Error("Invalid string. Length must be a multiple of 4");
}
var validLen = b64.indexOf("=");
if (validLen === -1)
validLen = len2;
var placeHoldersLen = validLen === len2 ? 0 : 4 - validLen % 4;
return [validLen, placeHoldersLen];
}
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;
var len2 = placeHoldersLen > 0 ? validLen - 4 : validLen;
var i2;
for (i2 = 0; i2 < len2; i2 += 4) {
tmp = revLookup[b64.charCodeAt(i2)] << 18 | revLookup[b64.charCodeAt(i2 + 1)] << 12 | revLookup[b64.charCodeAt(i2 + 2)] << 6 | revLookup[b64.charCodeAt(i2 + 3)];
arr[curByte++] = tmp >> 16 & 255;
arr[curByte++] = tmp >> 8 & 255;
arr[curByte++] = tmp & 255;
}
if (placeHoldersLen === 2) {
tmp = revLookup[b64.charCodeAt(i2)] << 2 | revLookup[b64.charCodeAt(i2 + 1)] >> 4;
arr[curByte++] = tmp & 255;
}
if (placeHoldersLen === 1) {
tmp = revLookup[b64.charCodeAt(i2)] << 10 | revLookup[b64.charCodeAt(i2 + 1)] << 4 | revLookup[b64.charCodeAt(i2 + 2)] >> 2;
arr[curByte++] = tmp >> 8 & 255;
arr[curByte++] = tmp & 255;
}
return arr;
}
function tripletToBase64(num) {
return lookup[num >> 18 & 63] + lookup[num >> 12 & 63] + lookup[num >> 6 & 63] + lookup[num & 63];
}
function encodeChunk(uint8, start, end) {
var tmp;
var output = [];
for (var i2 = start; i2 < end; i2 += 3) {
tmp = (uint8[i2] << 16 & 16711680) + (uint8[i2 + 1] << 8 & 65280) + (uint8[i2 + 2] & 255);
output.push(tripletToBase64(tmp));
}
return output.join("");
}
function fromByteArray(uint8) {
var tmp;
var len2 = uint8.length;
var extraBytes = len2 % 3;
var parts = [];
var maxChunkLength = 16383;
for (var i2 = 0, len22 = len2 - extraBytes; i2 < len22; i2 += maxChunkLength) {
parts.push(encodeChunk(uint8, i2, i2 + maxChunkLength > len22 ? len22 : i2 + maxChunkLength));
}
if (extraBytes === 1) {
tmp = uint8[len2 - 1];
parts.push(
lookup[tmp >> 2] + lookup[tmp << 4 & 63] + "=="
);
} else if (extraBytes === 2) {
tmp = (uint8[len2 - 2] << 8) + uint8[len2 - 1];
parts.push(
lookup[tmp >> 10] + lookup[tmp >> 4 & 63] + lookup[tmp << 2 & 63] + "="
);
}
return parts.join("");
}
}
});
// src/index.ts
var src_exports = {};
__export(src_exports, {
AbortError: () => AbortError,
AuthenticationError: () => AuthenticationError,
AuthorizationError: () => AuthorizationError,
Client: () => Client,
ClientClosedError: () => ClientClosedError,
ClientError: () => ClientError,
ConsoleLogHandler: () => ConsoleLogHandler,
ConstraintFailureError: () => ConstraintFailureError,
ContendedTransactionError: () => ContendedTransactionError,
DateStub: () => DateStub,
Document: () => Document,
DocumentReference: () => DocumentReference,
EmbeddedSet: () => EmbeddedSet,
FaunaAPIPaths: () => FaunaAPIPaths,
FaunaError: () => FaunaError,
FeedClient: () => FeedClient,
FeedPage: () => FeedPage,
FetchClient: () => FetchClient,
FlattenedSetIterator: () => FlattenedSetIterator,
InvalidRequestError: () => InvalidRequestError,
LOG_LEVELS: () => LOG_LEVELS,
LONG_MAX: () => LONG_MAX,
LONG_MIN: () => LONG_MIN,
Module: () => Module,
NamedDocument: () => NamedDocument,
NamedDocumentReference: () => NamedDocumentReference,
NetworkError: () => NetworkError,
NodeHTTP2Client: () => NodeHTTP2Client,
NullDocument: () => NullDocument,
Page: () => Page,
ProtocolError: () => ProtocolError,
QueryCheckError: () => QueryCheckError,
QueryRuntimeError: () => QueryRuntimeError,
QueryTimeoutError: () => QueryTimeoutError,
ServiceError: () => ServiceError,
ServiceInternalError: () => ServiceInternalError,
SetIterator: () => SetIterator,
StreamClient: () => StreamClient,
StreamToken: () => StreamToken,
TaggedTypeFormat: () => TaggedTypeFormat,
ThrottlingError: () => ThrottlingError,
TimeStub: () => TimeStub,
endpoints: () => endpoints,
fql: () => fql,
getDefaultHTTPClient: () => getDefaultHTTPClient,
isHTTPResponse: () => isHTTPResponse,
isStreamClient: () => isStreamClient,
parseDebugLevel: () => parseDebugLevel
});
module.exports = __toCommonJS(src_exports);
// src/client-configuration.ts
var endpoints = {
default: new URL("https://db.fauna.com"),
local: new URL("http://localhost:8443"),
localhost: new URL("http://localhost:8443")
};
// src/errors.ts
var FaunaError = class extends Error {
constructor(...args) {
super(...args);
}
};
var ServiceError = class extends FaunaError {
httpStatus;
code;
queryInfo;
constraint_failures;
constructor(failure, httpStatus) {
super(failure.error.message);
if (Error.captureStackTrace) {
Error.captureStackTrace(this, ServiceError);
}
this.name = "ServiceError";
this.code = failure.error.code;
this.httpStatus = httpStatus;
const info = {
txn_ts: failure.txn_ts,
summary: failure.summary,
query_tags: failure.query_tags,
stats: failure.stats
};
this.queryInfo = info;
this.constraint_failures = failure.error.constraint_failures;
}
};
var QueryRuntimeError = class extends ServiceError {
constructor(failure, httpStatus) {
super(failure, httpStatus);
if (Error.captureStackTrace) {
Error.captureStackTrace(this, QueryRuntimeError);
}
this.name = "QueryRuntimeError";
}
};
var QueryCheckError = class extends ServiceError {
constructor(failure, httpStatus) {
super(failure, httpStatus);
if (Error.captureStackTrace) {
Error.captureStackTrace(this, QueryCheckError);
}
this.name = "QueryCheckError";
}
};
var InvalidRequestError = class extends ServiceError {
constructor(failure, httpStatus) {
super(failure, httpStatus);
if (Error.captureStackTrace) {
Error.captureStackTrace(this, InvalidRequestError);
}
this.name = "InvalidRequestError";
}
};
var ConstraintFailureError = class extends ServiceError {
constraint_failures;
constructor(failure, httpStatus) {
super(failure, httpStatus);
if (Error.captureStackTrace) {
Error.captureStackTrace(this, QueryCheckError);
}
this.name = "ConstraintFailureError";
this.constraint_failures = failure.error.constraint_failures;
}
};
var AbortError = class extends ServiceError {
abort;
constructor(failure, httpStatus) {
super(failure, httpStatus);
if (Error.captureStackTrace) {
Error.captureStackTrace(this, QueryCheckError);
}
this.name = "AbortError";
this.abort = failure.error.abort;
}
};
var AuthenticationError = class extends ServiceError {
constructor(failure, httpStatus) {
super(failure, httpStatus);
if (Error.captureStackTrace) {
Error.captureStackTrace(this, AuthenticationError);
}
this.name = "AuthenticationError";
}
};
var AuthorizationError = class extends ServiceError {
constructor(failure, httpStatus) {
super(failure, httpStatus);
if (Error.captureStackTrace) {
Error.captureStackTrace(this, AuthorizationError);
}
this.name = "AuthorizationError";
}
};
var ContendedTransactionError = class extends ServiceError {
constructor(failure, httpStatus) {
super(failure, httpStatus);
if (Error.captureStackTrace) {
Error.captureStackTrace(this, InvalidRequestError);
}
this.name = "ContendedTransactionError";
}
};
var ThrottlingError = class extends ServiceError {
constructor(failure, httpStatus) {
super(failure, httpStatus);
if (Error.captureStackTrace) {
Error.captureStackTrace(this, ThrottlingError);
}
this.name = "ThrottlingError";
}
};
var QueryTimeoutError = class extends ServiceError {
stats;
constructor(failure, httpStatus) {
super(failure, httpStatus);
if (Error.captureStackTrace) {
Error.captureStackTrace(this, QueryTimeoutError);
}
this.name = "QueryTimeoutError";
this.stats = failure.stats;
}
};
var ServiceInternalError = class extends ServiceError {
constructor(failure, httpStatus) {
super(failure, httpStatus);
if (Error.captureStackTrace) {
Error.captureStackTrace(this, ServiceInternalError);
}
this.name = "ServiceInternalError";
}
};
var ClientError = class extends FaunaError {
constructor(message, options) {
super(message, options);
if (Error.captureStackTrace) {
Error.captureStackTrace(this, ClientError);
}
this.name = "ClientError";
}
};
var ClientClosedError = class extends FaunaError {
constructor(message, options) {
super(message, options);
if (Error.captureStackTrace) {
Error.captureStackTrace(this, ClientClosedError);
}
this.name = "ClientClosedError";
}
};
var NetworkError = class extends FaunaError {
constructor(message, options) {
super(message, options);
if (Error.captureStackTrace) {
Error.captureStackTrace(this, NetworkError);
}
this.name = "NetworkError";
}
};
var ProtocolError = class extends FaunaError {
httpStatus;
constructor(error) {
super(error.message);
if (Error.captureStackTrace) {
Error.captureStackTrace(this, ProtocolError);
}
this.name = "ProtocolError";
this.httpStatus = error.httpStatus;
}
};
var getServiceError = (failure, httpStatus) => {
const failureCode = failure.error.code;
switch (failureCode) {
case "invalid_query":
return new QueryCheckError(failure, httpStatus);
case "invalid_request":
return new InvalidRequestError(failure, httpStatus);
case "abort":
if (failure.error.abort !== void 0) {
return new AbortError(
failure,
httpStatus
);
}
break;
case "constraint_failure":
if (failure.error.constraint_failures !== void 0) {
return new ConstraintFailureError(
failure,
httpStatus
);
}
break;
case "unauthorized":
return new AuthenticationError(failure, httpStatus);
case "forbidden":
return new AuthorizationError(failure, httpStatus);
case "contended_transaction":
return new ContendedTransactionError(failure, httpStatus);
case "limit_exceeded":
return new ThrottlingError(failure, httpStatus);
case "time_out":
return new QueryTimeoutError(failure, httpStatus);
case "internal_error":
return new ServiceInternalError(failure, httpStatus);
}
return new QueryRuntimeError(failure, httpStatus);
};
// src/http-client/paths.ts
var FaunaAPIPaths = {
QUERY: "/query/1",
STREAM: "/stream/1",
EVENT_FEED: "/feed/1"
};
// src/http-client/fetch-client.ts
var FetchClient = class {
#baseUrl;
#defaultRequestPath = FaunaAPIPaths.QUERY;
#defaultStreamPath = FaunaAPIPaths.STREAM;
#keepalive;
constructor({ url, fetch_keepalive }) {
this.#baseUrl = url;
this.#keepalive = fetch_keepalive;
}
#resolveURL(path) {
return new URL(path, this.#baseUrl).toString();
}
async request({
data,
headers: requestHeaders,
method,
client_timeout_ms,
path = this.#defaultRequestPath
}) {
const signal = AbortSignal.timeout === void 0 ? (() => {
const controller = new AbortController();
const signal2 = controller.signal;
setTimeout(() => controller.abort(), client_timeout_ms);
return signal2;
})() : AbortSignal.timeout(client_timeout_ms);
const response = await fetch(this.#resolveURL(path), {
method,
headers: { ...requestHeaders, "Content-Type": "application/json" },
body: JSON.stringify(data),
signal,
keepalive: this.#keepalive
}).catch((error) => {
throw new NetworkError("The network connection encountered a problem.", {
cause: error
});
});
const status = response.status;
const responseHeaders = {};
response.headers.forEach((value, key) => responseHeaders[key] = value);
const body = await response.text();
return {
status,
body,
headers: responseHeaders
};
}
stream({
data,
headers: requestHeaders,
method,
path = this.#defaultStreamPath
}) {
const request = new Request(this.#resolveURL(path), {
method,
headers: { ...requestHeaders, "Content-Type": "application/json" },
body: JSON.stringify(data),
keepalive: this.#keepalive
});
const abortController = new AbortController();
const options = {
signal: abortController.signal
};
async function* reader() {
const response = await fetch(request, options).catch((error) => {
throw new NetworkError(
"The network connection encountered a problem.",
{
cause: error
}
);
});
const status = response.status;
if (!(status >= 200 && status < 400)) {
const failure = await response.json();
throw getServiceError(failure, status);
}
const body = response.body;
if (!body) {
throw new Error("Response body is undefined.");
}
const reader2 = body.getReader();
try {
for await (const line of readLines(reader2)) {
yield line;
}
} catch (error) {
throw new NetworkError(
"The network connection encountered a problem while streaming events.",
{ cause: error }
);
}
}
return {
read: reader(),
close: () => {
abortController.abort("Stream closed by the client.");
}
};
}
close() {
}
};
async function* readLines(reader) {
const textDecoder = new TextDecoder();
let partOfLine = "";
for await (const chunk of readChunks(reader)) {
const chunkText = textDecoder.decode(chunk);
const chunkLines = (partOfLine + chunkText).split("\n");
for (let i = 0; i < chunkLines.length - 1; i++) {
yield chunkLines[i].trim();
}
partOfLine = chunkLines[chunkLines.length - 1];
}
if (partOfLine.trim() !== "") {
yield partOfLine;
}
}
async function* readChunks(reader) {
let done = false;
do {
const readResult = await reader.read();
if (readResult.value !== void 0) {
yield readResult.value;
}
done = readResult.done;
} while (!done);
}
// src/http-client/node-http2-client.ts
var http2;
try {
http2 = require("node:http2");
} catch (_) {
http2 = void 0;
}
var _clients, _http2_session_idle_ms, _http2_max_streams, _url, _numberOfUsers, _session, _defaultRequestPath, _defaultStreamPath, _getClientKey, getClientKey_fn, _closeForAll, closeForAll_fn, _connect, connect_fn, _doRequest, doRequest_fn, _doStream, doStream_fn;
var _NodeHTTP2Client = class {
constructor({
http2_session_idle_ms,
url,
http2_max_streams
}) {
__privateAdd(this, _closeForAll);
__privateAdd(this, _connect);
__privateAdd(this, _doRequest);
__privateAdd(this, _doStream);
__privateAdd(this, _http2_session_idle_ms, void 0);
__privateAdd(this, _http2_max_streams, void 0);
__privateAdd(this, _url, void 0);
__privateAdd(this, _numberOfUsers, 0);
__privateAdd(this, _session, void 0);
__privateAdd(this, _defaultRequestPath, FaunaAPIPaths.QUERY);
__privateAdd(this, _defaultStreamPath, FaunaAPIPaths.STREAM);
if (http2 === void 0) {
throw new Error("Your platform does not support Node's http2 library");
}
__privateSet(this, _http2_session_idle_ms, http2_session_idle_ms);
__privateSet(this, _http2_max_streams, http2_max_streams);
__privateSet(this, _url, url);
__privateSet(this, _session, null);
}
static getClient(httpClientOptions) {
var _a;
const clientKey = __privateMethod(_a = _NodeHTTP2Client, _getClientKey, getClientKey_fn).call(_a, httpClientOptions);
if (!__privateGet(_NodeHTTP2Client, _clients).has(clientKey)) {
__privateGet(_NodeHTTP2Client, _clients).set(
clientKey,
new _NodeHTTP2Client(httpClientOptions)
);
}
const client = __privateGet(_NodeHTTP2Client, _clients).get(clientKey);
__privateWrapper(client, _numberOfUsers)._++;
return client;
}
async request(req) {
let retryCount = 0;
let memoizedError;
do {
try {
return await __privateMethod(this, _doRequest, doRequest_fn).call(this, req);
} catch (error) {
if (error?.code !== "ERR_HTTP2_GOAWAY_SESSION") {
throw new NetworkError(
"The network connection encountered a problem.",
{
cause: error
}
);
}
memoizedError = error;
retryCount++;
}
} while (retryCount < 3);
throw new NetworkError("The network connection encountered a problem.", {
cause: memoizedError
});
}
stream(req) {
return __privateMethod(this, _doStream, doStream_fn).call(this, req);
}
close() {
if (this.isClosed()) {
return;
}
__privateWrapper(this, _numberOfUsers)._--;
if (__privateGet(this, _numberOfUsers) === 0 && __privateGet(this, _session) && !__privateGet(this, _session).closed) {
__privateGet(this, _session).close();
}
}
isClosed() {
return __privateGet(this, _numberOfUsers) === 0;
}
};
var NodeHTTP2Client = _NodeHTTP2Client;
_clients = new WeakMap();
_http2_session_idle_ms = new WeakMap();
_http2_max_streams = new WeakMap();
_url = new WeakMap();
_numberOfUsers = new WeakMap();
_session = new WeakMap();
_defaultRequestPath = new WeakMap();
_defaultStreamPath = new WeakMap();
_getClientKey = new WeakSet();
getClientKey_fn = function({ http2_session_idle_ms, url }) {
return `${url}|${http2_session_idle_ms}`;
};
_closeForAll = new WeakSet();
closeForAll_fn = function() {
__privateSet(this, _numberOfUsers, 0);
if (__privateGet(this, _session) && !__privateGet(this, _session).closed) {
__privateGet(this, _session).close();
}
};
_connect = new WeakSet();
connect_fn = function() {
if (!__privateGet(this, _session) || __privateGet(this, _session).closed || __privateGet(this, _session).destroyed) {
const newSession = http2.connect(__privateGet(this, _url), {
peerMaxConcurrentStreams: __privateGet(this, _http2_max_streams)
}).once("error", () => __privateMethod(this, _closeForAll, closeForAll_fn).call(this)).once("goaway", () => __privateMethod(this, _closeForAll, closeForAll_fn).call(this));
newSession.setTimeout(__privateGet(this, _http2_session_idle_ms), () => {
__privateMethod(this, _closeForAll, closeForAll_fn).call(this);
});
__privateSet(this, _session, newSession);
}
return __privateGet(this, _session);
};
_doRequest = new WeakSet();
doRequest_fn = function({
client_timeout_ms,
data: requestData,
headers: requestHeaders,
method,
path = __privateGet(this, _defaultRequestPath)
}) {
return new Promise((resolvePromise, rejectPromise) => {
let req;
const onResponse = (http2ResponseHeaders) => {
const status = Number(
http2ResponseHeaders[http2.constants.HTTP2_HEADER_STATUS]
);
let responseData = "";
req.on("data", (chunk) => {
responseData += chunk;
});
req.on("end", () => {
resolvePromise({
status,
body: responseData,
headers: http2ResponseHeaders
});
});
};
try {
const httpRequestHeaders = {
...requestHeaders,
[http2.constants.HTTP2_HEADER_PATH]: path,
[http2.constants.HTTP2_HEADER_METHOD]: method
};
const session = __privateMethod(this, _connect, connect_fn).call(this);
req = session.request(httpRequestHeaders).setEncoding("utf8").on("error", (error) => {
rejectPromise(error);
}).on("response", onResponse);
req.write(JSON.stringify(requestData), "utf8");
req.setTimeout(client_timeout_ms, () => {
req.destroy(new Error(`Client timeout`));
});
req.end();
} catch (error) {
rejectPromise(error);
}
});
};
_doStream = new WeakSet();
doStream_fn = function({
data: requestData,
headers: requestHeaders,
method,
path = __privateGet(this, _defaultStreamPath)
}) {
let resolveChunk;
let rejectChunk;
const setChunkPromise = () => new Promise((res, rej) => {
resolveChunk = res;
rejectChunk = rej;
});
let chunkPromise = setChunkPromise();
let req;
const onResponse = (http2ResponseHeaders) => {
const status = Number(
http2ResponseHeaders[http2.constants.HTTP2_HEADER_STATUS]
);
if (!(status >= 200 && status < 400)) {
let responseData = "";
req.on("data", (chunk) => {
responseData += chunk;
});
req.on("end", () => {
try {
const failure = JSON.parse(responseData);
rejectChunk(getServiceError(failure, status));
} catch (error) {
rejectChunk(
new NetworkError("Could not process query failure.", {
cause: error
})
);
}
});
} else {
let partOfLine = "";
req.on("data", (chunk) => {
const chunkLines = (partOfLine + chunk).split("\n");
resolveChunk(chunkLines.map((s) => s.trim()).slice(0, -1));
chunkPromise = setChunkPromise();
partOfLine = chunkLines[chunkLines.length - 1];
});
req.on("end", () => {
resolveChunk([partOfLine]);
});
}
};
const self2 = this;
async function* reader() {
var _a;
const httpRequestHeaders = {
...requestHeaders,
[http2.constants.HTTP2_HEADER_PATH]: path,
[http2.constants.HTTP2_HEADER_METHOD]: method
};
const session = __privateMethod(_a = self2, _connect, connect_fn).call(_a);
req = session.request(httpRequestHeaders).setEncoding("utf8").on("error", (error) => {
rejectChunk(error);
}).on("response", onResponse);
const body = JSON.stringify(requestData);
req.write(body, "utf8");
req.end();
while (true) {
const chunks = await chunkPromise;
for (const chunk of chunks) {
yield chunk;
}
}
}
return {
read: reader(),
close: () => {
if (req) {
req.close();
}
}
};
};
__privateAdd(NodeHTTP2Client, _getClientKey);
__privateAdd(NodeHTTP2Client, _clients, /* @__PURE__ */ new Map());
// src/http-client/index.ts
var getDefaultHTTPClient = (options) => nodeHttp2IsSupported() ? NodeHTTP2Client.getClient(options) : new FetchClient(options);
var isHTTPResponse = (res) => res instanceof Object && "body" in res && "headers" in res && "status" in res;
var isStreamClient = (client) => {
return "stream" in client && typeof client.stream === "function";
};
var nodeHttp2IsSupported = () => {
if (typeof process !== "undefined" && process && process.release?.name === "node") {
try {
require("node:http2");
return true;
} catch (_) {
return false;
}
}
return false;
};
// src/tagged-type.ts
var import_base64_js = __toESM(require_base64_js());
// src/regex.ts
var yearpart = /(?:\d{4}|[\u2212-]\d{4,}|\+\d{5,})/;
var monthpart = /(?:0[1-9]|1[0-2])/;
var daypart = /(?:0[1-9]|[12]\d|3[01])/;
var hourpart = /(?:[01][0-9]|2[0-3])/;
var minsecpart = /(?:[0-5][0-9])/;
var decimalpart = /(?:\.\d+)/;
var datesplit = new RegExp(
`(${yearpart.source}-(${monthpart.source})-(${daypart.source}))`
);
var timesplit = new RegExp(
`(${hourpart.source}:${minsecpart.source}:${minsecpart.source}${decimalpart.source}?)`
);
var zonesplit = new RegExp(
`([zZ]|[+\u2212-]${hourpart.source}(?::?${minsecpart.source}|:${minsecpart.source}:${minsecpart.source}))`
);
var plaindate = new RegExp(`^${datesplit.source}$`);
var startsWithPlaindate = new RegExp(`^${datesplit.source}`);
var datetime = new RegExp(
`^${datesplit.source}T${timesplit.source}${zonesplit.source}$`
);
// src/values/date-time.ts
var TimeStub = class {
isoString;
constructor(isoString) {
this.isoString = isoString;
}
static from(isoString) {
if (typeof isoString !== "string") {
throw new TypeError(
`Expected string but received ${typeof isoString}: ${isoString}`
);
}
const matches = datetime.exec(isoString);
if (matches === null) {
throw new RangeError(
`(regex) Expected an ISO date string but received '${isoString}'`
);
}
return new TimeStub(isoString);
}
static fromDate(date) {
return new TimeStub(date.toISOString());
}
toDate() {
const date = new Date(this.isoString);
if (date.toString() === "Invalid Date") {
throw new RangeError(
"Fauna Date could not be converted to Javascript Date"
);
}
return date;
}
toString() {
return `TimeStub("${this.isoString}")`;
}
};
var DateStub = class {
dateString;
constructor(dateString) {
this.dateString = dateString;
}
static from(dateString) {
if (typeof dateString !== "string") {
throw new TypeError(
`Expected string but received ${typeof dateString}: ${dateString}`
);
}
const matches = plaindate.exec(dateString);
if (matches === null) {
throw new RangeError(
`Expected a plain date string but received '${dateString}'`
);
}
return new DateStub(matches[0]);
}
static fromDate(date) {
const dateString = date.toISOString();
const matches = startsWithPlaindate.exec(dateString);
if (matches === null) {
throw new ClientError(`Failed to parse date '${date}'`);
}
return new DateStub(matches[0]);
}
toDate() {
const date = new Date(this.dateString + "T00:00:00Z");
if (date.toString() === "Invalid Date") {
throw new RangeError(
"Fauna Date could not be converted to Javascript Date"
);
}
return date;
}
toString() {
return `DateStub("${this.dateString}")`;
}
};
// src/values/doc.ts
var DocumentReference = class {
coll;
id;
constructor({ coll, id }) {
this.id = id;
if (typeof coll === "string") {
this.coll = new Module(coll);
} else {
this.coll = coll;
}
}
};
var Document = class extends DocumentReference {
ts;
ttl;
constructor(obj) {
const { coll, id, ts, ...rest } = obj;
super({ coll, id });
this.ts = ts;
Object.assign(this, rest);
}
toObject() {
return { ...this };
}
};
var NamedDocumentReference = class {
coll;
name;
constructor({ coll, name }) {
this.name = name;
if (typeof coll === "string") {
this.coll = new Module(coll);
} else {
this.coll = coll;
}
}
};
var NamedDocument = class extends NamedDocumentReference {
ts;
data;
constructor(obj) {
const { coll, name, ts, data, ...rest } = obj;
super({ coll, name });
this.ts = ts;
this.data = data || {};
Object.assign(this, rest);
}
toObject() {
return { ...this };
}
};
var Module = class {
name;
constructor(name) {
this.name = name;
}
};
var NullDocument = class {
ref;
cause;
constructor(ref, cause) {
this.ref = ref;
this.cause = cause;
}
};
// src/values/set.ts
var Page = class {
data;
after;
constructor({ data, after }) {
this.data = data;
this.after = after;
}
};
var EmbeddedSet = class {
after;
constructor(after) {
this.after = after;
}
};
var SetIterator = class {
#generator;
constructor(client, initial, options) {
options = options ?? {};
if (initial instanceof Function) {
this.#generator = generateFromThunk(client, initial, options);
} else if (initial instanceof Page || initial instanceof EmbeddedSet) {
this.#generator = generatePages(client, initial, options);
} else {
throw new TypeError(
`Expected 'Page<T> | EmbeddedSet | (() => Promise<T | Page<T> | EmbeddedSet>)', but received ${JSON.stringify(
initial
)}`
);
}
}
static fromQuery(client, query, options) {
return new SetIterator(
client,
async () => {
const response = await client.query(
query,
options
);
return response.data;
},
options
);
}
static fromPageable(client, pageable, options) {
return new SetIterator(client, pageable, options);
}
flatten() {
return new FlattenedSetIterator(this);
}
async next() {
return this.#generator.next();
}
async return() {
return this.#generator.return();
}
async throw(e) {
return this.#generator.throw(e);
}
[Symbol.asyncIterator]() {
return this;
}
};
var FlattenedSetIterator = class {
#generator;
constructor(setIterator) {
this.#generator = generateItems(setIterator);
}
async next() {
return this.#generator.next();
}
async return() {
return this.#generator.return();
}
async throw(e) {
return this.#generator.throw(e);
}
[Symbol.asyncIterator]() {
return this;
}
};
async function* generatePages(client, initial, options) {
let currentPage = initial;
if (currentPage instanceof Page) {
yield currentPage.data;
}
while (currentPage.after) {
const query = fql`Set.paginate(${currentPage.after})`;
const response = await client.query(query, options);
const nextPage = response.data;
currentPage = nextPage;
yield currentPage.data;
}
}
async function* generateFromThunk(client, thunk, options) {
const result = await thunk();
if (result instanceof Page || result instanceof EmbeddedSet) {
for await (const page of generatePages(
client,
result,
options
)) {
yield page;
}
return;
}
yield [result];
}
async function* generateItems(setIterator) {
for await (const page of setIterator) {
for (const item of page) {
yield item;
}
}
}
// src/values/stream.ts
function isEventSource(value) {
if (typeof value.token === "string") {
return true;
}
return false;
}
var StreamToken = class {
token;
constructor(token) {
this.token = token;
}
};
var FeedPage = class {
events;
cursor;
hasNext;
stats;
constructor({ events, cursor, has_next, stats }) {
this.events = this.#toEventIterator(events);
this.cursor = cursor;
this.hasNext = has_next;
this.stats = stats;
}
*#toEventIterator(events) {
for (const event of events) {
if (event.type === "error") {
throw getServiceError(event);
}
yield event;
}
}
};
// src/tagged-type.ts
var TaggedTypeFormat = class {
static encode(input) {
return encode(input);
}
static encodeInterpolation(input) {
return encodeInterpolation(input);
}
static decode(input, decodeOptions) {
return JSON.parse(input, (_, value) => {
if (value == null)
return null;
if (value["@mod"]) {
return new Module(value["@mod"]);
} else if (value["@doc"]) {
if (typeof value["@doc"] === "string") {
const [modName, id] = value["@doc"].split(":");
return new DocumentReference({ coll: modName, id });
}
const obj = value["@doc"];
if (obj.id) {
return new Document(obj);
} else {
return new NamedDocument(obj);
}
} else if (value["@ref"]) {
const obj = value["@ref"];
let ref;
if (obj.id) {
ref = new DocumentReference(obj);
} else {
ref = new NamedDocumentReference(obj);
}
if ("exists" in obj && obj.exists === false) {
return new NullDocument(ref, obj.cause);
}
return ref;
} else if (value["@set"]) {
if (typeof value["@set"] === "string") {
return new EmbeddedSet(value["@set"]);
}
return new Page(value["@set"]);
} else if (value["@int"]) {
return Number(value["@int"]);
} else if (value["@long"]) {
const bigInt = BigInt(value["@long"]);
if (decodeOptions.long_type === "number") {
if (bigInt > Number.MAX_SAFE_INTEGER || bigInt < Number.MIN_SAFE_INTEGER) {
console.warn(`Value is too large to be represented as a number. Returning as Number with loss of precision. Use long_type 'bigint' instead.`);
}
return Number(bigInt);
}
return bigInt;
} else if (value["@double"]) {
return Number(value["@double"]);
} else if (value["@date"]) {
return DateStub.from(value["@date"]);
} else if (value["@time"]) {
return TimeStub.from(value["@time"]);
} else if (value["@object"]) {
return value["@object"];
} else if (value["@stream"]) {
return new StreamToken(value["@stream"]);
} else if (value["@bytes"]) {
return base64toBuffer(value["@bytes"]);
}
return value;
});
}
};
var LONG_MIN = BigInt("-9223372036854775808");
var LONG_MAX = BigInt("9223372036854775807");
var INT_MIN = -(2 ** 31);
var INT_MAX = 2 ** 31 - 1;
var encodeMap = {
bigint: (value) => {
if (value < LONG_MIN || value > LONG_MAX) {
throw new RangeError(
"BigInt value exceeds max magnitude for a 64-bit Fauna long. Use a 'number' to represent doubles beyond that limit."
);
}
if (value >= INT_MIN && value <= INT_MAX) {
return { "@int": value.toString() };
}
return {
"@long": value.toString()
};
},
number: (value) => {
if (value === Number.POSITIVE_INFINITY || value === Number.NEGATIVE_INFINITY) {
throw new RangeError(`Cannot convert ${value} to a Fauna type.`);
}
if (!Number.isInteger(value)) {
return { "@double": value.toString() };
} else {
if (value >= INT_MIN && value <= INT_MAX) {
return { "@int": value.toString() };
} else if (Number.isSafeInteger(value)) {
return {
"@long": value.toString()
};
}
return { "@double": value.toString() };
}
},
string: (value) => {
return value;
},
object: (input) => {
let wrapped = false;
const _out = {};
for (const k in input) {
if (k.startsWith("@")) {
wrapped = true;
}
if (input[k] !== void 0) {
_out[k] = encode(input[k]);
}
}
return wrapped ? { "@object": _out } : _out;
},
array: (input) => input.map(encode),
date: (dateValue) => ({
"@time": dateValue.toISOString()
}),
faunadate: (value) => ({ "@date": value.dateString }),
faunatime: (value) => ({ "@time": value.isoString }),
module: (value) => ({ "@mod": value.name }),
documentReference: (value) => ({
"@ref": { id: value.id, coll: { "@mod": value.coll.name } }
}),
document: (value) => ({
"@ref": { id: value.id, coll: { "@mod": value.coll.name } }
}),
namedDocumentReference: (value) => ({
"@ref": { name: value.name, coll: { "@mod": value.coll.name } }
}),
namedDocument: (value) => ({
"@ref": { name: value.name, coll: { "@mod": value.coll.name } }
}),
set: (value) => {
throw new ClientError(
"Page could not be encoded. Fauna does not accept encoded Set values, yet. Use Page.data and Page.after as arguments, instead."
);
},
streamToken: (value) => value.token,
bytes: (value) => ({
"@bytes": bufferToBase64(value)
})
};
var encode = (input) => {
switch (typeof input) {
case "bigint":
return encodeMap["bigint"](input);
case "string":
return encodeMap["string"](input);
case "number":
return encodeMap["number"](input);
case "boolean":
return input;
case "object":
if (input == null) {
return null;
} else if (Array.isArray(input)) {
return encodeMap["array"](input);
} else if (input instanceof Date) {
return encodeMap["date"](input);
} else if (input instanceof DateStub) {
return encodeMap["faunadate"](input);
} else if (input instanceof TimeStub) {
return encodeMap["faunatime"](input);
} else if (input instanceof Module) {
return encodeMap["module"](input);
} else if (input instanceof Document) {
return encodeMap["document"](input);
} else if (input instanceof DocumentReference) {
return encodeMap["documentReference"](input);
} else if (input instanceof NamedDocument) {
return encodeMap["namedDocument"](input);
} else if (input instanceof NamedDocumentReference) {
return encodeMap["namedDocumentReference"](input);
} else if (input instanceof NullDocument) {
return encode(input.ref);
} else if (input instanceof Page) {
return encodeMap["set"](input);
} else if (input instanceof EmbeddedSet) {
return encodeMap["set"](input);
} else if (input instanceof StreamToken) {
return encodeMap["streamToken"](input);
} else if (input instanceof Uint8Array || input instanceof ArrayBuffer) {
return encodeMap["bytes"](input);
} else if (ArrayBuffer.isView(input)) {
throw new ClientError(
"Error encoding TypedArray to Fauna Bytes. Convert your TypedArray to Uint8Array or ArrayBuffer before passing it to Fauna. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray"
);
} else if (input instanceof Query2) {
throw new TypeError(
"Cannot encode instance of type 'Query'. Try using TaggedTypeFormat.encodeInterpolation instead."
);
} else {
return encodeMap["object"](input);
}
default:
throw new TypeError(
`Passing ${typeof input} as a QueryArgument is not supported`
);
}
};
var encodeInterpolation = (input) => {
switch (typeof input) {
case "bigint":
case "string":
case "number":
case "boolean":
return encodeValueInterpolation(encode(input));
case "object":
if (input == null || input instanceof Date || input instanceof DateStub || input instanceof TimeStub || input instanceof Module || input instanceof DocumentReference || input instanceof NamedDocumentReference || input instanceof Page || input instanceof EmbeddedSet || input instanceof StreamToken || input instanceof Uint8Array || input instanceof ArrayBuffer || ArrayBuffer.isView(input)) {
return encodeValueInterpolation(encode(input));
} else if (input instanceof NullDocument) {
return encodeInterpolation(input.ref);
} else if (input instanceof Query2) {
return encodeQueryInterpolation(input);
} else if (Array.isArray(input)) {
return encodeArrayInterpolation(input);
} else {
return encodeObjectInterpolation(input);
}
default:
throw new TypeError(
`Passing ${typeof input} as a QueryArgument is not supported`
);
}
};
var encodeObjectInterpolation = (input) => {
const _out = {};
for (const k in input) {
if (input[k] !== void 0) {
_out[k] = encodeInterpolation(input[k]);
}
}
return { object: _out };
};
var encodeArrayInterpolation = (input) => {
const encodedItems = input.map(encodeInterpolation);
return { array: encodedItems };
};
var encodeQueryInterpolation = (value) => value.encode();
var encodeValueInterpolation = (value) => ({
value
});
function base64toBuffer(value) {
return import_base64_js.default.toByteArray(value);
}
function bufferToBase64(value) {
const arr = value instanceof Uint8Array ? value : new Uint8Array(value);
return import_base64_js.default.fromByteArray(arr);
}
// src/query-builder.ts
function fql(queryFragments, ...queryArgs) {
return new Query2(queryFragments, ...queryArgs);
}
var Query2 = class {
#queryFragments;
#interpolatedArgs;
#__phantom;
constructor(queryFragments, ...queryArgs) {
if (queryFragments.length === 0 || queryFragments.length !== queryArgs.length + 1) {
throw new Error("invalid query constructed");
}
this.#queryFragments = queryFragments;
this.#interpolatedArgs = queryArgs;
this.#__phantom = void 0;
}
encode() {
if (this.#queryFragments.length === 1) {
return { fql: [this.#queryFragments[0]] };
}
let renderedFragments = this.#queryFragments.flatMap((fragment, i) => {
if (i === this.#queryFragments.length - 1) {
return fragment === "" ? [] : [fragment];
}
const arg = this.#interpolatedArgs[i];
const encoded = TaggedTypeFormat.encodeInterpolation(arg);
return [fragment, encoded];
});
renderedFragments = renderedFragments.filter((x) => x !== "");
return { fql: renderedFragments };
}
};
// src/util/package-version.ts
var packageVersion = "2.4.1";
// src/util/environment.ts
var os;
try {
os = require("node:os");
} catch (_) {
os = void 0;
}
var getDriverEnv = () => {
const driverEnv = {
driver: ["javascript", packageVersion].join("-"),
env: "unknown",
os: "unknown",
runtime: "unknown"
};
try {
const isNode = typeof window === "undefined" && typeof process !== "undefined" && process.versions != null && process.versions.node != null;
const isBrowser = typeof window !== "undefined" && typeof window.document !== "undefined";
const isServiceWorker = typeof self === "object" && self.constructor && self.constructor.name === "DedicatedWorkerGlobalScope";
const isVercelEdgeRuntime = typeof EdgeRuntime !== "string";
if (isNode) {
driverEnv.runtime = ["nodejs", process.version].join("-");
driverEnv.env = getNodeRuntimeEnv();
driverEnv.os = [os.platform(), os.release()].join("-");
} else if (isServiceWorker) {
driverEnv.runtime = getBrowserDetails(navigator);
driverEnv.env = "Service Worker";
driverEnv.os = getBrowserOsDetails(navigator);
} else if (isBrowser) {
driverEnv.runtime = getBrowserDetails(navigator);
driverEnv.env = "browser";
driverEnv.os = getBrowserOsDetails(navigator);
} else if (isVercelEdgeRuntime) {
driverEnv.runtime = "Vercel Edge Runtime";
driverEnv.env = "edge";
}
} catch (e) {
}
return Object.entries(driverEnv).filter(([_, val]) => val !== "unknown").map((entry) => entry.join("=")).join("; ");
};
var getBrowserDetails = (navigator2) => {
let browser = navigator2.appName;
let browserVersion = "" + parseFloat(navigator2.appVersion);
let nameOffset, verOffset, ix;
if ((verOffset = navigator2.userAgent.indexOf("Opera")) != -1) {
browser = "Opera";
browserVersion = navigator2.userAgent.substring(verOffset + 6);
if ((verOffset = navigator2.userAgent.indexOf("Version")) != -1) {
browserVersion = navigator2.userAgent.substring(verOffset + 8);
}
} else if ((verOffset = navigator2.userAgent.indexOf("MSIE")) != -1) {
browser = "Microsoft Internet Explorer";
browserVersion = navigator2.userAgent.substring(verOffset + 5);
} else if (browser == "Netscape" && navigator2.userAgent.indexOf("Trident/") != -1) {
browser = "Microsoft Internet Explorer";
browserVersion = navigator2.userAgent.substring(verOffset + 5);
if ((verOffset = navigator2.userAgent.indexOf("rv:")) != -1) {
browserVersion = navigator2.userAgent.substring(verOffset + 3);
}
} else if ((verOffset = navigator2.userAgent.indexOf("Chrome")) != -1) {
browser = "Chrome";
browserVersion = navigator2.userAgent.substring(verOffset + 7);
} else if ((verOffset = navigator2.userAgent.indexOf("Safari")) != -1) {
browser = "Safari";
browserVersion = navigator2.userAgent.substring(verOffset + 7);
if ((verOffset = navigator2.userAgent.indexOf("Version")) != -1) {
browserVersion = navigator2.userAgent.substring(verOffset + 8);
}
if (navigator2.userAgent.indexOf("CriOS") != -1) {
browser = "Chrome";
}
} else if ((verOffset = navigator2.userAgent.indexOf("Firefox")) != -1) {
browser = "Firefox";
browserVersion = navigator2.userAgent.substring(verOffset + 8);
} else if ((nameOffset = navigator2.userAgent.lastIndexOf(" ") + 1) < (verOffset = navigator2.userAgent.lastIndexOf("/"))) {
browser = navigator2.userAgent.substring(nameOffset, verOffset);
browserVersion = navigator2.userAgent.substring(verOffset + 1);
if (browser.toLowerCase() == browser.toUpperCase()) {
browser = navigator2.appName;
}
}
if ((ix = browserVersion.indexOf(";")) != -1)
browserVersion = browserVersion.substring(0, ix);
if ((ix = browserVersion.indexOf(" ")) != -1)
browserVersion = browserVersion.substring(0, ix);
if ((ix = browserVersion.indexOf(")")) != -1)
browserVersion = browserVersion.substring(0, ix);
return [browser, browserVersion].join("-");
};
var getBrowserOsDetails = (navigator2) => {
let os2 = "unknown";
const clientStrings = [
{ s: "Windows 10", r: /(Windows 10.0|Windows NT 10.0)/ },
{ s: "Windows 8.1", r: /(Windows 8.1|Windows NT 6.3)/ },
{ s: "Windows 8", r: /(Windows 8|Windows NT 6.2)/ },
{ s: "Windows 7", r: /(Windows 7|Windows NT 6.1)/ },
{ s: "Windows Vista", r: /Windows NT 6.0/ },
{ s: "Windows Server 2003", r: /Windows NT 5.2/ },
{ s: "Windows XP", r: /(Windows NT 5.1|Windows XP)/ },
{ s: "Windows 2000", r: /(Windows NT 5.0|Windows 2000)/ },
{ s: "Windows ME", r: /(Win 9x 4.90|Windows ME)/ },
{ s: "Windows 98", r: /(Windows 98|Win98)/ },
{ s: "Windows 95", r: /(Windows 95|Win95|Windows_95)/ },
{ s: "Windows NT 4.0", r: /(Windows NT 4.0|WinNT4.0|WinNT|Windows NT)/ },
{ s: "Windows CE", r: /Windows CE/ },
{ s: "Windows 3.11", r: /Win16/ },
{ s: "Android", r: /Android/ },
{ s: "Open BSD", r: /OpenBSD/ },
{ s: "Sun OS", r: /SunOS/ },
{ s: "Chrome OS", r: /CrOS/ },
{ s: "Linux", r: /(Linux|X11(?!.*CrOS))/ },
{ s: "iOS", r: /(iPhone|iPad|iPod)/ },
{ s: "Mac OS X", r: /Mac OS X/ },
{ s: "Mac OS", r: /(Mac OS|MacPPC|MacIntel|Mac_PowerPC|Macintosh)/ },
{ s: "QNX", r: /QNX/ },
{ s: "UNIX", r: /UNIX/ },
{ s: "BeOS", r: /BeOS/ },
{ s: "OS/2", r: /OS\/2/ },
{
s: "Search Bot",
r: /(nuhk|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask Jeeves\/Teoma|ia_archiver)/
}
];
for (const id in clientStrings) {
const cs = clientStrings[id];
if (cs.r.test(navigator2.userAgent)) {
os2 = cs.s;
break;
}
}
let osVersion = "unknown";
if (/Windows/.test(os2)) {
osVersion;
const matches = /Windows (.*)/.exec(os2);
if (matches) {
osVersion = matches[1];
}
os2 = "Window