Comparing version 1.4.0-beta.0 to 2.0.0-beta.0
@@ -1,5 +0,5 @@ | ||
var Ie=(r=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(r,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):r)(function(r){if(typeof require<"u")return require.apply(this,arguments);throw new Error('Dynamic require of "'+r+'" is not supported')});var De=(r,e,t)=>{if(!e.has(r))throw TypeError("Cannot "+t)};var a=(r,e,t)=>(De(r,e,"read from private field"),t?t.call(r):e.get(r)),u=(r,e,t)=>{if(e.has(r))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(r):e.set(r,t)},T=(r,e,t,s)=>(De(r,e,"write to private field"),s?s.call(r,t):e.set(r,t),t),ve=(r,e,t,s)=>({set _(n){T(r,e,n,t)},get _(){return a(r,e,s)}}),p=(r,e,t)=>(De(r,e,"access private method"),t);var qe={default:new URL("https://db.fauna.com"),local:new URL("http://localhost:8443"),localhost:new URL("http://localhost:8443")};var R=class extends Error{constructor(...e){super(...e)}},l=class extends R{httpStatus;code;queryInfo;constraint_failures;constructor(e,t){super(e.error.message),Error.captureStackTrace&&Error.captureStackTrace(this,l),this.name="ServiceError",this.code=e.error.code,this.httpStatus=t;let s={txn_ts:e.txn_ts,summary:e.summary,query_tags:e.query_tags,stats:e.stats};this.queryInfo=s,this.constraint_failures=e.error.constraint_failures}},B=class extends l{constructor(e,t){super(e,t),Error.captureStackTrace&&Error.captureStackTrace(this,B),this.name="QueryRuntimeError"}},q=class extends l{constructor(e,t){super(e,t),Error.captureStackTrace&&Error.captureStackTrace(this,q),this.name="QueryCheckError"}},V=class extends l{constructor(e,t){super(e,t),Error.captureStackTrace&&Error.captureStackTrace(this,V),this.name="InvalidRequestError"}},ce=class extends l{abort;constructor(e,t){super(e,t),Error.captureStackTrace&&Error.captureStackTrace(this,q),this.name="AbortError",this.abort=e.error.abort}},z=class extends l{constructor(e,t){super(e,t),Error.captureStackTrace&&Error.captureStackTrace(this,z),this.name="AuthenticationError"}},X=class extends l{constructor(e,t){super(e,t),Error.captureStackTrace&&Error.captureStackTrace(this,X),this.name="AuthorizationError"}},ue=class extends l{constructor(e,t){super(e,t),Error.captureStackTrace&&Error.captureStackTrace(this,V),this.name="ContendedTransactionError"}},F=class extends l{constructor(e,t){super(e,t),Error.captureStackTrace&&Error.captureStackTrace(this,F),this.name="ThrottlingError"}},Y=class extends l{stats;constructor(e,t){super(e,t),Error.captureStackTrace&&Error.captureStackTrace(this,Y),this.name="QueryTimeoutError",this.stats=e.stats}},J=class extends l{constructor(e,t){super(e,t),Error.captureStackTrace&&Error.captureStackTrace(this,J),this.name="ServiceInternalError"}},K=class extends l{constructor(e,t){super(e,t),Error.captureStackTrace&&Error.captureStackTrace(this,K),this.name="ServiceTimeoutError"}},b=class extends R{constructor(e,t){super(e,t),Error.captureStackTrace&&Error.captureStackTrace(this,b),this.name="ClientError"}},P=class extends R{constructor(e,t){super(e,t),Error.captureStackTrace&&Error.captureStackTrace(this,P),this.name="ClientClosedError"}},w=class extends R{constructor(e,t){super(e,t),Error.captureStackTrace&&Error.captureStackTrace(this,w),this.name="NetworkError"}},k=class extends R{httpStatus;constructor(e){super(e.message),Error.captureStackTrace&&Error.captureStackTrace(this,k),this.name="ProtocolError",this.httpStatus=e.httpStatus}};var de=class{#e;#t;#r;constructor({url:e,fetch_keepalive:t}){this.#e=new URL("/query/1",e).toString(),this.#t=new URL("/stream/1",e).toString(),this.#r=t}async request({data:e,headers:t,method:s,client_timeout_ms:n}){let o=AbortSignal.timeout===void 0?(()=>{let f=new AbortController,m=f.signal;return setTimeout(()=>f.abort(),n),m})():AbortSignal.timeout(n),i=await fetch(this.#e,{method:s,headers:{...t,"Content-Type":"application/json"},body:JSON.stringify(e),signal:o,keepalive:this.#r}).catch(f=>{throw new w("The network connection encountered a problem.",{cause:f})}),c=i.status,d={};i.headers.forEach((f,m)=>d[m]=f);let g=await i.text();return{status:c,body:g,headers:d}}stream({data:e,headers:t,method:s}){let n=new Request(this.#t,{method:s,headers:{...t,"Content-Type":"application/json"},body:JSON.stringify(e),keepalive:this.#r}),o=new AbortController,i={signal:o.signal};async function*c(){let d=await fetch(n,i).catch(y=>{throw new w("The network connection encountered a problem.",{cause:y})}),g=d.status;if(!(g>=200&&g<400)){let y=await d.json();throw new l(y,g)}let f=d.body;if(!f)throw new Error("Response body is undefined.");let m=f.getReader();for await(let y of St(m))yield y}return{read:c(),close:()=>{o.abort("Stream closed by the client.")}}}close(){}};async function*St(r){let e=new TextDecoder,t="";for await(let s of wt(r)){let n=e.decode(s),o=(t+n).split(` | ||
`);for(let i=0;i<o.length-1;i++)yield o[i].trim();t=o[o.length-1]}t.trim()!==""&&(yield t)}async function*wt(r){let e=!1;do{let t=await r.read();t.value!==void 0&&(yield t.value),e=t.done}while(!e)}var Q;try{Q=Ie("node:http2")}catch{Q=void 0}var ne,le,me,pe,M,S,be,Xe,se,Te,fe,Ve,Se,Ye,we,Je,Z=class{constructor({http2_session_idle_ms:e,url:t,http2_max_streams:s}){u(this,se);u(this,fe);u(this,Se);u(this,we);u(this,le,void 0);u(this,me,void 0);u(this,pe,void 0);u(this,M,0);u(this,S,void 0);if(Q===void 0)throw new Error("Your platform does not support Node's http2 library");T(this,le,e),T(this,me,s),T(this,pe,t),T(this,S,null)}static getClient(e){var n;let t=p(n=Z,be,Xe).call(n,e);a(Z,ne).has(t)||a(Z,ne).set(t,new Z(e));let s=a(Z,ne).get(t);return ve(s,M)._++,s}async request(e){let t=0,s;do try{return await p(this,Se,Ye).call(this,e)}catch(n){if(n?.code!=="ERR_HTTP2_GOAWAY_SESSION")throw new w("The network connection encountered a problem.",{cause:n});s=n,t++}while(t<3);throw new w("The network connection encountered a problem.",{cause:s})}stream(e){return p(this,we,Je).call(this,e)}close(){this.isClosed()||(ve(this,M)._--,a(this,M)===0&&a(this,S)&&!a(this,S).closed&&a(this,S).close())}isClosed(){return a(this,M)===0}},ee=Z;ne=new WeakMap,le=new WeakMap,me=new WeakMap,pe=new WeakMap,M=new WeakMap,S=new WeakMap,be=new WeakSet,Xe=function({http2_session_idle_ms:e,url:t}){return`${t}|${e}`},se=new WeakSet,Te=function(){T(this,M,0),a(this,S)&&!a(this,S).closed&&a(this,S).close()},fe=new WeakSet,Ve=function(){if(!a(this,S)||a(this,S).closed||a(this,S).destroyed){let e=Q.connect(a(this,pe),{peerMaxConcurrentStreams:a(this,me)}).once("error",()=>p(this,se,Te).call(this)).once("goaway",()=>p(this,se,Te).call(this));e.setTimeout(a(this,le),()=>{p(this,se,Te).call(this)}),T(this,S,e)}return a(this,S)},Se=new WeakSet,Ye=function({client_timeout_ms:e,data:t,headers:s,method:n}){return new Promise((o,i)=>{let c,d=g=>{let f=Number(g[Q.constants.HTTP2_HEADER_STATUS]),m="";c.on("data",y=>{m+=y}),c.on("end",()=>{o({status:f,body:m,headers:g})})};try{let g={...s,[Q.constants.HTTP2_HEADER_PATH]:"/query/1",[Q.constants.HTTP2_HEADER_METHOD]:n};c=p(this,fe,Ve).call(this).request(g).setEncoding("utf8").on("error",m=>{i(m)}).on("response",d),c.write(JSON.stringify(t),"utf8"),c.setTimeout(e,()=>{c.destroy(new Error("Client timeout"))}),c.end()}catch(g){i(g)}})},we=new WeakSet,Je=function({data:e,headers:t,method:s}){let n,o,i=()=>new Promise((y,C)=>{n=y,o=C}),c=i(),d,g=y=>{let C=Number(y[Q.constants.HTTP2_HEADER_STATUS]);if(C>=200&&C<400){let E="";d.on("data",v=>{let G=(E+v).split(` | ||
`);n(G.map(He=>He.trim()).slice(0,-1)),c=i(),E=G[G.length-1]}),d.on("end",()=>{n([E])})}else{let E="";d.on("data",v=>{E+=v}),d.on("end",()=>{o(new l(JSON.parse(E),C))})}},f=this;async function*m(){var v;let y={...t,[Q.constants.HTTP2_HEADER_PATH]:"/stream/1",[Q.constants.HTTP2_HEADER_METHOD]:s};d=p(v=f,fe,Ve).call(v).request(y).setEncoding("utf8").on("error",G=>{o(G)}).on("response",g);let E=JSON.stringify(e);for(d.write(E,"utf8"),d.end();;){let G=await c;for(let He of G)yield He}}return{read:m(),close:()=>{d&&d.close()}}},u(ee,be),u(ee,ne,new Map);var Fe=r=>xt()?ee.getClient(r):new de(r),Me=r=>r instanceof Object&&"body"in r&&"headers"in r&&"status"in r,We=r=>"stream"in r&&typeof r.stream=="function",xt=()=>{if(typeof process<"u"&&process&&process.release?.name==="node")try{return Ie("node:http2"),!0}catch{return!1}return!1};var Et=/(?:\d{4}|[\u2212-]\d{4,}|\+\d{5,})/,_t=/(?:0[1-9]|1[0-2])/,Ct=/(?:0[1-9]|[12]\d|3[01])/,Ke=/(?:[01][0-9]|2[0-3])/,ye=/(?:[0-5][0-9])/,Rt=/(?:\.\d+)/,je=new RegExp(`(${Et.source}-(${_t.source})-(${Ct.source}))`),Qt=new RegExp(`(${Ke.source}:${ye.source}:${ye.source}${Rt.source}?)`),Pt=new RegExp(`([zZ]|[+\u2212-]${Ke.source}(?::?${ye.source}|:${ye.source}:${ye.source}))`),Ze=new RegExp(`^${je.source}$`),et=new RegExp(`^${je.source}`),tt=new RegExp(`^${je.source}T${Qt.source}${Pt.source}$`);var O=class{isoString;constructor(e){this.isoString=e}static from(e){if(typeof e!="string")throw new TypeError(`Expected string but received ${typeof e}: ${e}`);if(tt.exec(e)===null)throw new RangeError(`(regex) Expected an ISO date string but received '${e}'`);return new O(e)}static fromDate(e){return new O(e.toISOString())}toDate(){let e=new Date(this.isoString);if(e.toString()==="Invalid Date")throw new RangeError("Fauna Date could not be converted to Javascript Date");return e}toString(){return`TimeStub("${this.isoString}")`}},A=class{dateString;constructor(e){this.dateString=e}static from(e){if(typeof e!="string")throw new TypeError(`Expected string but received ${typeof e}: ${e}`);let t=Ze.exec(e);if(t===null)throw new RangeError(`Expected a plain date string but received '${e}'`);return new A(t[0])}static fromDate(e){let t=e.toISOString(),s=et.exec(t);if(s===null)throw new b(`Failed to parse date '${e}'`);return new A(s[0])}toDate(){let e=new Date(this.dateString+"T00:00:00Z");if(e.toString()==="Invalid Date")throw new RangeError("Fauna Date could not be converted to Javascript Date");return e}toString(){return`DateStub("${this.dateString}")`}};var W=class{coll;id;constructor({coll:e,id:t}){this.id=t,typeof e=="string"?this.coll=new j(e):this.coll=e}},oe=class extends W{ts;constructor(e){let{coll:t,id:s,ts:n,...o}=e;super({coll:t,id:s}),this.ts=n,Object.assign(this,o)}toObject(){return{...this}}},te=class{coll;name;constructor({coll:e,name:t}){this.name=t,typeof e=="string"?this.coll=new j(e):this.coll=e}},ie=class extends te{ts;data;constructor(e){let{coll:t,name:s,ts:n,data:o,...i}=e;super({coll:t,name:s}),this.ts=n,this.data=o||{},Object.assign(this,i)}toObject(){return{...this}}},j=class{name;constructor(e){this.name=e}},ae=class{ref;cause;constructor(e,t){this.ref=e,this.cause=t}};var N=class{data;after;constructor({data:e,after:t}){this.data=e,this.after=t}},$=class{after;constructor(e){this.after=e}},H=class{#e;constructor(e,t,s){if(s=s??{},t instanceof Function)this.#e=Ot(e,t,s);else if(t instanceof N||t instanceof $)this.#e=rt(e,t,s);else throw new TypeError(`Expected 'Page<T> | EmbeddedSet | (() => Promise<T | Page<T> | EmbeddedSet>)', but received ${JSON.stringify(t)}`)}static fromQuery(e,t,s){return new H(e,async()=>(await e.query(t,s)).data,s)}static fromPageable(e,t,s){return new H(e,t,s)}flatten(){return new $e(this)}async next(){return this.#e.next()}async return(){return this.#e.return()}async throw(e){return this.#e.throw(e)}[Symbol.asyncIterator](){return this}},$e=class{#e;constructor(e){this.#e=At(e)}async next(){return this.#e.next()}async return(){return this.#e.return()}async throw(e){return this.#e.throw(e)}[Symbol.asyncIterator](){return this}};async function*rt(r,e,t){let s=e;for(s instanceof N&&(yield s.data);s.after;){let n=Le`Set.paginate(${s.after})`;s=(await r.query(n,t)).data,yield s.data}}async function*Ot(r,e,t){let s=await e();if(s instanceof N||s instanceof $){for await(let n of rt(r,s,t))yield n;return}yield[s]}async function*At(r){for await(let e of r)for(let t of e)yield t}var I=class{token;constructor(e){this.token=e}};var D=class{static encode(e){return xe(e)}static decode(e,t){return JSON.parse(e,(s,n)=>{if(n==null)return null;if(n["@mod"])return new j(n["@mod"]);if(n["@doc"]){if(typeof n["@doc"]=="string"){let[i,c]=n["@doc"].split(":");return new W({coll:i,id:c})}let o=n["@doc"];return o.id?new oe(o):new ie(o)}else if(n["@ref"]){let o=n["@ref"],i;return o.id?i=new W(o):i=new te(o),"exists"in o&&o.exists===!1?new ae(i,o.cause):i}else{if(n["@set"])return typeof n["@set"]=="string"?new $(n["@set"]):new N(n["@set"]);if(n["@int"])return Number(n["@int"]);if(n["@long"]){let o=BigInt(n["@long"]);return t.long_type==="number"?((o>Number.MAX_SAFE_INTEGER||o<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."),Number(o)):o}else{if(n["@double"])return Number(n["@double"]);if(n["@date"])return A.from(n["@date"]);if(n["@time"])return O.from(n["@time"]);if(n["@object"])return n["@object"];if(n["@stream"])return new I(n["@stream"])}}return n})}},ot=BigInt("-9223372036854775808"),it=BigInt("9223372036854775807"),nt=-(2**31),st=2**31-1,h={bigint:r=>{if(r<ot||r>it)throw new RangeError("BigInt value exceeds max magnitude for a 64-bit Fauna long. Use a 'number' to represent doubles beyond that limit.");return r>=nt&&r<=st?{"@int":r.toString()}:{"@long":r.toString()}},number:r=>{if(r===Number.POSITIVE_INFINITY||r===Number.NEGATIVE_INFINITY)throw new RangeError(`Cannot convert ${r} to a Fauna type.`);return Number.isInteger(r)?r>=nt&&r<=st?{"@int":r.toString()}:Number.isSafeInteger(r)?{"@long":r.toString()}:{"@double":r.toString()}:{"@double":r.toString()}},string:r=>r,object:r=>{let e=!1,t={};for(let s in r)s.startsWith("@")&&(e=!0),r[s]!==void 0&&(t[s]=xe(r[s]));return e?{"@object":t}:t},array:r=>{let e=[];for(let t in r)e.push(xe(r[t]));return e},date:r=>({"@time":r.toISOString()}),faunadate:r=>({"@date":r.dateString}),faunatime:r=>({"@time":r.isoString}),module:r=>({"@mod":r.name}),documentReference:r=>({"@ref":{id:r.id,coll:{"@mod":r.coll.name}}}),document:r=>({"@ref":{id:r.id,coll:{"@mod":r.coll.name}}}),namedDocumentReference:r=>({"@ref":{name:r.name,coll:{"@mod":r.coll.name}}}),namedDocument:r=>({"@ref":{name:r.name,coll:{"@mod":r.coll.name}}}),set:r=>{throw new b("Page could not be encoded. Fauna does not accept encoded Set values, yet. Use Page.data and Page.after as arguments, instead.")},streamToken:r=>r.token},xe=r=>{if(r===void 0)throw new TypeError("Passing undefined as a QueryValue is not supported");switch(typeof r){case"bigint":return h.bigint(r);case"string":return h.string(r);case"number":return h.number(r);case"boolean":return r;case"object":return r==null?null:Array.isArray(r)?h.array(r):r instanceof Date?h.date(r):r instanceof A?h.faunadate(r):r instanceof O?h.faunatime(r):r instanceof j?h.module(r):r instanceof oe?h.document(r):r instanceof W?h.documentReference(r):r instanceof ie?h.namedDocument(r):r instanceof te?h.namedDocumentReference(r):r instanceof ae?xe(r.ref):r instanceof N||r instanceof $?h.set(r):r instanceof I?h.streamToken(r):h.object(r)}};function Le(r,...e){return new L(r,...e)}var L=class{#e;#t;constructor(e,...t){if(e.length===0||e.length!==t.length+1)throw new Error("invalid query constructed");this.#e=e,this.#t=t}toQuery(e={}){return{...this.#r(e),...e}}#r(e){if(this.#e.length===1)return{query:{fql:[this.#e[0]]},arguments:{}};let t={};return{query:{fql:this.#e.flatMap((n,o)=>{if(o===this.#e.length-1)return n===""?[]:[n];let i=this.#t[o],c;if(i instanceof L){let d=i.toQuery(e);c=d.query,t={...t,...d.arguments}}else c={value:D.encode(i)};return[n,c].filter(d=>d!=="")})},arguments:t}}};var at="1.4.0-beta.0";var Ee;try{Ee=Ie("node:os")}catch{Ee=void 0}var dt=()=>{let r={driver:["javascript",at].join("-"),env:"unknown",os:"unknown",runtime:"unknown"};try{let e=typeof window>"u"&&typeof process<"u"&&process.versions!=null&&process.versions.node!=null,t=typeof window<"u"&&typeof window.document<"u",s=typeof self=="object"&&self.constructor&&self.constructor.name==="DedicatedWorkerGlobalScope";e?(r.runtime=["nodejs",process.version].join("-"),r.env=Ht(),r.os=[Ee.platform(),Ee.release()].join("-")):s?(r.runtime=ct(navigator),r.env="Service Worker",r.os=ut(navigator)):t?(r.runtime=ct(navigator),r.env="browser",r.os=ut(navigator)):typeof EdgeRuntime!="string"&&(r.runtime="Vercel Edge Runtime",r.env="edge")}catch{}return Object.entries(r).filter(([e,t])=>t!=="unknown").map(e=>e.join("=")).join("; ")},ct=r=>{let e=r.appName,t=""+parseFloat(r.appVersion),s,n,o;return(n=r.userAgent.indexOf("Opera"))!=-1?(e="Opera",t=r.userAgent.substring(n+6),(n=r.userAgent.indexOf("Version"))!=-1&&(t=r.userAgent.substring(n+8))):(n=r.userAgent.indexOf("MSIE"))!=-1?(e="Microsoft Internet Explorer",t=r.userAgent.substring(n+5)):e=="Netscape"&&r.userAgent.indexOf("Trident/")!=-1?(e="Microsoft Internet Explorer",t=r.userAgent.substring(n+5),(n=r.userAgent.indexOf("rv:"))!=-1&&(t=r.userAgent.substring(n+3))):(n=r.userAgent.indexOf("Chrome"))!=-1?(e="Chrome",t=r.userAgent.substring(n+7)):(n=r.userAgent.indexOf("Safari"))!=-1?(e="Safari",t=r.userAgent.substring(n+7),(n=r.userAgent.indexOf("Version"))!=-1&&(t=r.userAgent.substring(n+8)),r.userAgent.indexOf("CriOS")!=-1&&(e="Chrome")):(n=r.userAgent.indexOf("Firefox"))!=-1?(e="Firefox",t=r.userAgent.substring(n+8)):(s=r.userAgent.lastIndexOf(" ")+1)<(n=r.userAgent.lastIndexOf("/"))&&(e=r.userAgent.substring(s,n),t=r.userAgent.substring(n+1),e.toLowerCase()==e.toUpperCase()&&(e=r.appName)),(o=t.indexOf(";"))!=-1&&(t=t.substring(0,o)),(o=t.indexOf(" "))!=-1&&(t=t.substring(0,o)),(o=t.indexOf(")"))!=-1&&(t=t.substring(0,o)),[e,t].join("-")},ut=r=>{let e="unknown",t=[{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(let n in t){let o=t[n];if(o.r.test(r.userAgent)){e=o.s;break}}let s="unknown";if(/Windows/.test(e)){let n=/Windows (.*)/.exec(e);n&&(s=n[1]),e="Windows"}switch(e){case"Mac OS":case"Mac OS X":case"Android":{let n=/(?:Android|Mac OS|Mac OS X|MacPPC|MacIntel|Mac_PowerPC|Macintosh) ([._\d]+)/.exec(r.userAgent);n&&(s=n[1]);break}case"iOS":{let n=/OS (\d+)_(\d+)_?(\d+)?/.exec(r.appVersion);n&&(s=n[1]+"."+n[2]+"."+(n[3]??0));break}}return[e,s].join("-")},Nt=typeof window<"u"?window:typeof globalThis<"u"?globalThis:typeof global<"u"?global:self,Ht=()=>{if(!(typeof process<"u"&&process&&process.env&&typeof process.env=="object"))return"unknown";let e=[{name:"Netlify",check:function(){return!!process.env.NETLIFY_IMAGES_CDN_DOMAIN}},{name:"Vercel",check:function(){return!!process.env.VERCEL}},{name:"Heroku",check:function(){return!!process.env.PATH&&process.env.PATH.indexOf(".heroku")!==-1}},{name:"AWS Lambda",check:function(){return!!process.env.AWS_LAMBDA_FUNCTION_VERSION}},{name:"GCP Cloud Functions",check:function(){return!!process.env._&&process.env._.indexOf("google")!==-1}},{name:"GCP Compute Instances",check:function(){return!!process.env.GOOGLE_CLOUD_PROJECT}},{name:"Azure Cloud Functions",check:function(){return!!process.env.WEBSITE_FUNCTIONS_AZUREMONITOR_CATEGORIES}},{name:"Azure Compute",check:function(){return!!process.env.ORYX_ENV_TYPE&&!!process.env.WEBSITE_INSTANCE_ID&&process.env.ORYX_ENV_TYPE==="AppService"}},{name:"Mongo Stitch",check:function(){return typeof Nt?.StitchError=="function"}},{name:"Render",check:function(){return!!process.env.RENDER_SERVICE_ID}},{name:"Begin",check:function(){return!!process.env.BEGIN_DATA_SCOPE_ID}}].find(t=>t.check());return e?e.name:"unknown"};var lt=r=>r instanceof Object&&"data"in r,mt=r=>r instanceof Object&&"error"in r&&r.error instanceof Object&&"code"in r.error&&"message"in r.error;var Ue={client_timeout_buffer_ms:5e3,format:"tagged",http2_session_idle_ms:5e3,http2_max_streams:100,long_type:"number",fetch_keepalive:!1,query_timeout_ms:5e3,max_attempts:3,max_backoff:20},Re,x,U,_,re,ge,Ge,he,Be,Qe,pt,Pe,ft,ke,yt,Oe,gt,Ae,ht,Ne,Tt,ze=class{constructor(e,t){u(this,ge);u(this,he);u(this,Qe);u(this,Pe);u(this,ke);u(this,Oe);u(this,Ae);u(this,Ne);u(this,x,void 0);u(this,U,void 0);u(this,_,void 0);u(this,re,!1);T(this,x,{...Ue,...e,secret:p(this,Qe,pt).call(this,e),endpoint:p(this,Pe,ft).call(this,e)}),p(this,Ne,Tt).call(this),t?T(this,U,t):T(this,U,Fe({url:a(this,x).endpoint.toString(),http2_session_idle_ms:a(this,x).http2_session_idle_ms,http2_max_streams:a(this,x).http2_max_streams,fetch_keepalive:a(this,x).fetch_keepalive}))}get lastTxnTs(){return a(this,_)}set lastTxnTs(e){e!==void 0&&T(this,_,a(this,_)?Math.max(e,a(this,_)):e)}get clientConfiguration(){let{...e}=a(this,x);return e}close(){if(a(this,re))throw new P("Your client is closed. You cannot close it again.");a(this,U).close(),T(this,re,!0)}paginate(e,t){return e instanceof L?H.fromQuery(this,e,t):H.fromPageable(this,e,t)}async query(e,t){if(a(this,re))throw new P("Your client is closed. No further requests can be issued.");let s=e.toQuery(t).query;return p(this,ge,Ge).call(this,s,t)}stream(e,t){if(a(this,re))throw new P("Your client is closed. No further requests can be issued.");let s=a(this,U);if(We(s)){let n={...a(this,x),httpStreamClient:s,...t},o=e instanceof L?()=>this.query(e).then(i=>i.data):e;return new Ce(o,n)}else throw new b("Streaming is not supported by this client.")}},_e=ze;Re=new WeakMap,x=new WeakMap,U=new WeakMap,_=new WeakMap,re=new WeakMap,ge=new WeakSet,Ge=async function(e,t,s=0){let n=this.clientConfiguration.max_backoff??Ue.max_backoff,o=this.clientConfiguration.max_attempts??Ue.max_attempts,i=Math.min(Math.random()*2**s,n)*1e3;s+=1;try{return await p(this,Oe,gt).call(this,e,t,s)}catch(c){if(c instanceof F&&s<o)return await bt(i),p(this,ge,Ge).call(this,e,t,s);throw c}},he=new WeakSet,Be=function(e){if(e instanceof b||e instanceof w||e instanceof k||e instanceof l)return e;if(Me(e)){if(mt(e.body)){let t=e.body,s=e.status;return p(this,ke,yt).call(this,t,s)}return new k({message:`Response is in an unkown format: ${e.body}`,httpStatus:e.status})}return new b("A client level error occurred. Fauna was not called.",{cause:e})},Qe=new WeakSet,pt=function(e){let t;typeof process<"u"&&process&&typeof process=="object"&&process.env&&typeof process.env=="object"&&(t=process.env.FAUNA_SECRET);let s=e?.secret??t;if(s===void 0)throw new TypeError("You must provide a secret to the driver. Set it in an environmental variable named FAUNA_SECRET or pass it to the Client constructor.");return s},Pe=new WeakSet,ft=function(e){if(e&&"endpoint"in e&&e.endpoint===void 0)throw new TypeError("ClientConfiguration option endpoint must be defined.");let t;return typeof process<"u"&&process&&typeof process=="object"&&process.env&&typeof process.env=="object"&&(t=process.env.FAUNA_ENDPOINT?new URL(process.env.FAUNA_ENDPOINT):void 0),e?.endpoint??t??qe.default},ke=new WeakSet,yt=function(e,t){switch(t){case 400:return It.includes(e.error.code)?new q(e,t):e.error.code==="invalid_request"?new V(e,t):e.error.code==="abort"&&e.error.abort!==void 0?new ce(e,t):new B(e,t);case 401:return new z(e,t);case 403:return new X(e,t);case 409:return new ue(e,t);case 429:return new F(e,t);case 440:return new Y(e,t);case 500:return new J(e,t);case 503:return new K(e,t);default:return new l(e,t)}},Oe=new WeakSet,gt=async function(e,t,s=0){try{let n={...a(this,x),...t},o={Authorization:`Bearer ${n.secret}`};p(this,Ae,ht).call(this,n,o);let i=n.format==="tagged",c=n.arguments?i?D.encode(n.arguments):n.arguments:void 0,d={query:e,arguments:c},g=n.query_timeout_ms+a(this,x).client_timeout_buffer_ms,f=await a(this,U).request({client_timeout_ms:g,data:d,headers:o,method:"POST"}),m;try{if(m={...f,body:i?D.decode(f.body,{long_type:n.long_type}):JSON.parse(f.body)},m.body.query_tags){let E=m.body.query_tags.split(",").map(v=>v.split("="));m.body.query_tags=Object.fromEntries(E)}}catch(E){throw new k({message:`Error parsing response as JSON: ${E}`,httpStatus:f.status})}if(!lt(m.body))throw p(this,he,Be).call(this,m);let y=m.body.txn_ts;(a(this,_)===void 0&&y!==void 0||y!==void 0&&a(this,_)!==void 0&&a(this,_)<y)&&T(this,_,y);let C=m.body;return C.stats&&(C.stats.attempts=s),C}catch(n){throw p(this,he,Be).call(this,n)}},Ae=new WeakSet,ht=function(e,t){let s=(n,o,i=c=>String(c))=>{o!==void 0&&(t[n]=i(o))};s("x-format",e.format),s("x-typecheck",e.typecheck),s("x-query-timeout-ms",e.query_timeout_ms),s("x-linearized",e.linearized),s("x-max-contention-retries",e.max_contention_retries),s("traceparent",e.traceparent),s("x-query-tags",e.query_tags,n=>Object.entries(n).map(o=>o.join("=")).join(",")),s("x-last-txn-ts",a(this,_),n=>n),s("x-driver-env",a(ze,Re))},Ne=new WeakSet,Tt=function(){let e=a(this,x);if(["client_timeout_buffer_ms","endpoint","format","http2_session_idle_ms","long_type","query_timeout_ms","fetch_keepalive","http2_max_streams","max_backoff","max_attempts"].forEach(s=>{if(e[s]===void 0)throw new TypeError(`ClientConfiguration option '${s}' must be defined.`)}),e.http2_max_streams<=0)throw new RangeError("'http2_max_streams' must be greater than zero.");if(e.client_timeout_buffer_ms<=0)throw new RangeError("'client_timeout_buffer_ms' must be greater than zero.");if(e.query_timeout_ms<=0)throw new RangeError("'query_timeout_ms' must be greater than zero.");if(e.max_backoff<=0)throw new RangeError("'max_backoff' must be greater than zero.");if(e.max_attempts<=0)throw new RangeError("'max_attempts' must be greater than zero.")},u(_e,Re,dt());var Ce=class{closed=!1;#e;#t=0;#r;#s;#n;#o;constructor(e,t){e instanceof I?this.#r=()=>Promise.resolve(e):this.#r=e,this.#e=t,this.#a()}start(e,t){if(typeof e!="function")throw new TypeError(`Expected a function as the 'onEvent' argument, but received ${typeof e}. Please provide a valid function.`);if(t&&typeof t!="function")throw new TypeError(`Expected a function as the 'onError' argument, but received ${typeof t}. Please provide a valid function.`);(async()=>{try{for await(let n of this)e(n)}catch(n){t&&t(n)}})()}async*[Symbol.asyncIterator](){if(this.closed)throw new b("The stream has been closed and cannot be reused.");for(this.#o||(this.#o=await this.#r().then(e=>{if(!(e instanceof I))throw new b(`Error requesting a stream token. Expected a StreamToken as the query result, but received ${typeof e}. Your query must return the result of '<Set>.toStream' or '<Set>.changesOn') | ||
Query result: ${JSON.stringify(e,null)}`);return e})),this.#t=1;!this.closed;){let e=Math.min(Math.random()*2**this.#t,this.#e.max_backoff)*1e3;try{for await(let t of this.#i(this.#s))yield t}catch(t){if(t instanceof R||this.#t>=this.#e.max_attempts)throw this.close(),t;this.#t+=1,await bt(e)}}}close(){this.#n&&(this.#n.close(),this.#n=void 0),this.closed=!0}get last_ts(){return this.#s}async*#i(e){let t=this.#o,s={Authorization:`Bearer ${this.#e.secret}`},n=this.#e.httpStreamClient.stream({data:{token:t.token,start_ts:e},headers:s,method:"POST"});this.#n=n;for await(let o of n.read){let i=D.decode(o,{long_type:this.#e.long_type});if(i.type==="error")throw this.close(),new l(i,400);this.#s=i.txn_ts,i.type==="start"&&(i.type="status"),!(!this.#e.status_events&&i.type==="status")&&(yield i)}}#a(){let e=this.#e;if(["long_type","httpStreamClient","max_backoff","max_attempts","secret"].forEach(s=>{if(e[s]===void 0)throw new TypeError(`ClientConfiguration option '${s}' must be defined.`)}),e.max_backoff<=0)throw new RangeError("'max_backoff' must be greater than zero.");if(e.max_attempts<=0)throw new RangeError("'max_attempts' must be greater than zero.")}},It=["invalid_function_definition","invalid_identifier","invalid_query","invalid_syntax","invalid_type"];function bt(r){return new Promise(e=>setTimeout(e,r))}export{ce as AbortError,z as AuthenticationError,X as AuthorizationError,_e as Client,P as ClientClosedError,b as ClientError,ue as ContendedTransactionError,A as DateStub,oe as Document,W as DocumentReference,$ as EmbeddedSet,R as FaunaError,de as FetchClient,V as InvalidRequestError,it as LONG_MAX,ot as LONG_MIN,j as Module,ie as NamedDocument,te as NamedDocumentReference,w as NetworkError,ee as NodeHTTP2Client,ae as NullDocument,N as Page,k as ProtocolError,q as QueryCheckError,B as QueryRuntimeError,Y as QueryTimeoutError,l as ServiceError,J as ServiceInternalError,K as ServiceTimeoutError,H as SetIterator,Ce as StreamClient,I as StreamToken,D as TaggedTypeFormat,F as ThrottlingError,O as TimeStub,qe as endpoints,Le as fql,Fe as getDefaultHTTPClient,Me as isHTTPResponse,We as isStreamClient}; | ||
var Rt=Object.create;var tt=Object.defineProperty;var Pt=Object.getOwnPropertyDescriptor;var Ot=Object.getOwnPropertyNames;var vt=Object.getPrototypeOf,Nt=Object.prototype.hasOwnProperty;var qe=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw new Error('Dynamic require of "'+t+'" is not supported')});var Ht=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var Ft=(t,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Ot(e))!Nt.call(t,n)&&n!==r&&tt(t,n,{get:()=>e[n],enumerable:!(s=Pt(e,n))||s.enumerable});return t};var It=(t,e,r)=>(r=t!=null?Rt(vt(t)):{},Ft(e||!t||!t.__esModule?tt(r,"default",{value:t,enumerable:!0}):r,t));var Ve=(t,e,r)=>{if(!e.has(t))throw TypeError("Cannot "+r)};var i=(t,e,r)=>(Ve(t,e,"read from private field"),r?r.call(t):e.get(t)),d=(t,e,r)=>{if(e.has(t))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(t):e.set(t,r)},S=(t,e,r,s)=>(Ve(t,e,"write to private field"),s?s.call(t,r):e.set(t,r),r),Me=(t,e,r,s)=>({set _(n){S(t,e,n,r)},get _(){return i(t,e,s)}}),p=(t,e,r)=>(Ve(t,e,"access private method"),r);var it=Ht(Ae=>{"use strict";Ae.byteLength=Wt;Ae.toByteArray=Lt;Ae.fromByteArray=$t;var P=[],C=[],Mt=typeof Uint8Array<"u"?Uint8Array:Array,$e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(Z=0,ot=$e.length;Z<ot;++Z)P[Z]=$e[Z],C[$e.charCodeAt(Z)]=Z;var Z,ot;C["-".charCodeAt(0)]=62;C["_".charCodeAt(0)]=63;function at(t){var e=t.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=t.indexOf("=");r===-1&&(r=e);var s=r===e?0:4-r%4;return[r,s]}function Wt(t){var e=at(t),r=e[0],s=e[1];return(r+s)*3/4-s}function jt(t,e,r){return(e+r)*3/4-r}function Lt(t){var e,r=at(t),s=r[0],n=r[1],o=new Mt(jt(t,s,n)),a=0,c=n>0?s-4:s,u;for(u=0;u<c;u+=4)e=C[t.charCodeAt(u)]<<18|C[t.charCodeAt(u+1)]<<12|C[t.charCodeAt(u+2)]<<6|C[t.charCodeAt(u+3)],o[a++]=e>>16&255,o[a++]=e>>8&255,o[a++]=e&255;return n===2&&(e=C[t.charCodeAt(u)]<<2|C[t.charCodeAt(u+1)]>>4,o[a++]=e&255),n===1&&(e=C[t.charCodeAt(u)]<<10|C[t.charCodeAt(u+1)]<<4|C[t.charCodeAt(u+2)]>>2,o[a++]=e>>8&255,o[a++]=e&255),o}function Ut(t){return P[t>>18&63]+P[t>>12&63]+P[t>>6&63]+P[t&63]}function Bt(t,e,r){for(var s,n=[],o=e;o<r;o+=3)s=(t[o]<<16&16711680)+(t[o+1]<<8&65280)+(t[o+2]&255),n.push(Ut(s));return n.join("")}function $t(t){for(var e,r=t.length,s=r%3,n=[],o=16383,a=0,c=r-s;a<c;a+=o)n.push(Bt(t,a,a+o>c?c:a+o));return s===1?(e=t[r-1],n.push(P[e>>2]+P[e<<4&63]+"==")):s===2&&(e=(t[r-2]<<8)+t[r-1],n.push(P[e>>10]+P[e>>4&63]+P[e<<2&63]+"=")),n.join("")}});var We={default:new URL("https://db.fauna.com"),local:new URL("http://localhost:8443"),localhost:new URL("http://localhost:8443")};var Q=class extends Error{constructor(...e){super(...e)}},y=class extends Q{httpStatus;code;queryInfo;constraint_failures;constructor(e,r){super(e.error.message),Error.captureStackTrace&&Error.captureStackTrace(this,y),this.name="ServiceError",this.code=e.error.code,this.httpStatus=r;let s={txn_ts:e.txn_ts,summary:e.summary,query_tags:e.query_tags,stats:e.stats};this.queryInfo=s,this.constraint_failures=e.error.constraint_failures}},te=class extends y{constructor(e,r){super(e,r),Error.captureStackTrace&&Error.captureStackTrace(this,te),this.name="QueryRuntimeError"}},V=class extends y{constructor(e,r){super(e,r),Error.captureStackTrace&&Error.captureStackTrace(this,V),this.name="QueryCheckError"}},z=class extends y{constructor(e,r){super(e,r),Error.captureStackTrace&&Error.captureStackTrace(this,z),this.name="InvalidRequestError"}},be=class extends y{constraint_failures;constructor(e,r){super(e,r),Error.captureStackTrace&&Error.captureStackTrace(this,V),this.name="ConstraintFailureError",this.constraint_failures=e.error.constraint_failures}},Se=class extends y{abort;constructor(e,r){super(e,r),Error.captureStackTrace&&Error.captureStackTrace(this,V),this.name="AbortError",this.abort=e.error.abort}},re=class extends y{constructor(e,r){super(e,r),Error.captureStackTrace&&Error.captureStackTrace(this,re),this.name="AuthenticationError"}},ne=class extends y{constructor(e,r){super(e,r),Error.captureStackTrace&&Error.captureStackTrace(this,ne),this.name="AuthorizationError"}},we=class extends y{constructor(e,r){super(e,r),Error.captureStackTrace&&Error.captureStackTrace(this,z),this.name="ContendedTransactionError"}},M=class extends y{constructor(e,r){super(e,r),Error.captureStackTrace&&Error.captureStackTrace(this,M),this.name="ThrottlingError"}},se=class extends y{stats;constructor(e,r){super(e,r),Error.captureStackTrace&&Error.captureStackTrace(this,se),this.name="QueryTimeoutError",this.stats=e.stats}},oe=class extends y{constructor(e,r){super(e,r),Error.captureStackTrace&&Error.captureStackTrace(this,oe),this.name="ServiceInternalError"}},b=class extends Q{constructor(e,r){super(e,r),Error.captureStackTrace&&Error.captureStackTrace(this,b),this.name="ClientError"}},O=class extends Q{constructor(e,r){super(e,r),Error.captureStackTrace&&Error.captureStackTrace(this,O),this.name="ClientClosedError"}},g=class extends Q{constructor(e,r){super(e,r),Error.captureStackTrace&&Error.captureStackTrace(this,g),this.name="NetworkError"}},v=class extends Q{httpStatus;constructor(e){super(e.message),Error.captureStackTrace&&Error.captureStackTrace(this,v),this.name="ProtocolError",this.httpStatus=e.httpStatus}},X=(t,e)=>{switch(t.error.code){case"invalid_query":return new V(t,e);case"invalid_request":return new z(t,e);case"abort":if(t.error.abort!==void 0)return new Se(t,e);break;case"constraint_failure":if(t.error.constraint_failures!==void 0)return new be(t,e);break;case"unauthorized":return new re(t,e);case"forbidden":return new ne(t,e);case"contended_transaction":return new we(t,e);case"throttle":return new M(t,e);case"time_out":return new se(t,e);case"internal_error":return new oe(t,e)}return new te(t,e)};var le=class{#e;#t;#r;constructor({url:e,fetch_keepalive:r}){this.#e=new URL("/query/1",e).toString(),this.#t=new URL("/stream/1",e).toString(),this.#r=r}async request({data:e,headers:r,method:s,client_timeout_ms:n}){let o=AbortSignal.timeout===void 0?(()=>{let f=new AbortController,l=f.signal;return setTimeout(()=>f.abort(),n),l})():AbortSignal.timeout(n),a=await fetch(this.#e,{method:s,headers:{...r,"Content-Type":"application/json"},body:JSON.stringify(e),signal:o,keepalive:this.#r}).catch(f=>{throw new g("The network connection encountered a problem.",{cause:f})}),c=a.status,u={};a.headers.forEach((f,l)=>u[l]=f);let T=await a.text();return{status:c,body:T,headers:u}}stream({data:e,headers:r,method:s}){let n=new Request(this.#t,{method:s,headers:{...r,"Content-Type":"application/json"},body:JSON.stringify(e),keepalive:this.#r}),o=new AbortController,a={signal:o.signal};async function*c(){let u=await fetch(n,a).catch(m=>{throw new g("The network connection encountered a problem.",{cause:m})}),T=u.status;if(!(T>=200&&T<400)){let m=await u.json();throw X(m,T)}let f=u.body;if(!f)throw new Error("Response body is undefined.");let l=f.getReader();try{for await(let m of Dt(l))yield m}catch(m){throw new g("The network connection encountered a problem while streaming events.",{cause:m})}}return{read:c(),close:()=>{o.abort("Stream closed by the client.")}}}close(){}};async function*Dt(t){let e=new TextDecoder,r="";for await(let s of qt(t)){let n=e.decode(s),o=(r+n).split(` | ||
`);for(let a=0;a<o.length-1;a++)yield o[a].trim();r=o[o.length-1]}r.trim()!==""&&(yield r)}async function*qt(t){let e=!1;do{let r=await t.read();r.value!==void 0&&(yield r.value),e=r.done}while(!e)}var R;try{R=qe("node:http2")}catch{R=void 0}var ae,me,fe,pe,W,w,_e,rt,ie,xe,ye,je,Ee,nt,Ce,st,Y=class{constructor({http2_session_idle_ms:e,url:r,http2_max_streams:s}){d(this,ie);d(this,ye);d(this,Ee);d(this,Ce);d(this,me,void 0);d(this,fe,void 0);d(this,pe,void 0);d(this,W,0);d(this,w,void 0);if(R===void 0)throw new Error("Your platform does not support Node's http2 library");S(this,me,e),S(this,fe,s),S(this,pe,r),S(this,w,null)}static getClient(e){var n;let r=p(n=Y,_e,rt).call(n,e);i(Y,ae).has(r)||i(Y,ae).set(r,new Y(e));let s=i(Y,ae).get(r);return Me(s,W)._++,s}async request(e){let r=0,s;do try{return await p(this,Ee,nt).call(this,e)}catch(n){if(n?.code!=="ERR_HTTP2_GOAWAY_SESSION")throw new g("The network connection encountered a problem.",{cause:n});s=n,r++}while(r<3);throw new g("The network connection encountered a problem.",{cause:s})}stream(e){return p(this,Ce,st).call(this,e)}close(){this.isClosed()||(Me(this,W)._--,i(this,W)===0&&i(this,w)&&!i(this,w).closed&&i(this,w).close())}isClosed(){return i(this,W)===0}},J=Y;ae=new WeakMap,me=new WeakMap,fe=new WeakMap,pe=new WeakMap,W=new WeakMap,w=new WeakMap,_e=new WeakSet,rt=function({http2_session_idle_ms:e,url:r}){return`${r}|${e}`},ie=new WeakSet,xe=function(){S(this,W,0),i(this,w)&&!i(this,w).closed&&i(this,w).close()},ye=new WeakSet,je=function(){if(!i(this,w)||i(this,w).closed||i(this,w).destroyed){let e=R.connect(i(this,pe),{peerMaxConcurrentStreams:i(this,fe)}).once("error",()=>p(this,ie,xe).call(this)).once("goaway",()=>p(this,ie,xe).call(this));e.setTimeout(i(this,me),()=>{p(this,ie,xe).call(this)}),S(this,w,e)}return i(this,w)},Ee=new WeakSet,nt=function({client_timeout_ms:e,data:r,headers:s,method:n}){return new Promise((o,a)=>{let c,u=T=>{let f=Number(T[R.constants.HTTP2_HEADER_STATUS]),l="";c.on("data",m=>{l+=m}),c.on("end",()=>{o({status:f,body:l,headers:T})})};try{let T={...s,[R.constants.HTTP2_HEADER_PATH]:"/query/1",[R.constants.HTTP2_HEADER_METHOD]:n};c=p(this,ye,je).call(this).request(T).setEncoding("utf8").on("error",l=>{a(new g("The network connection encountered a problem while streaming events.",{cause:l}))}).on("response",u),c.write(JSON.stringify(r),"utf8"),c.setTimeout(e,()=>{c.destroy(new Error("Client timeout"))}),c.end()}catch(T){a(new g("The network connection encountered a problem while streaming events.",{cause:T}))}})},Ce=new WeakSet,st=function({data:e,headers:r,method:s}){let n,o,a=()=>new Promise((m,k)=>{n=m,o=k}),c=a(),u,T=m=>{let k=Number(m[R.constants.HTTP2_HEADER_STATUS]);if(k>=200&&k<400){let _="";u.on("data",E=>{let G=(_+E).split(` | ||
`);n(G.map(De=>De.trim()).slice(0,-1)),c=a(),_=G[G.length-1]}),u.on("end",()=>{n([_])})}else{let _="";u.on("data",E=>{_+=E}),u.on("end",()=>{try{let E=JSON.parse(_);o(X(E,k))}catch(E){o(new g("Could not process query failure.",{cause:E}))}})}},f=this;async function*l(){var E;let m={...r,[R.constants.HTTP2_HEADER_PATH]:"/stream/1",[R.constants.HTTP2_HEADER_METHOD]:s};u=p(E=f,ye,je).call(E).request(m).setEncoding("utf8").on("error",G=>{o(G)}).on("response",T);let _=JSON.stringify(e);for(u.write(_,"utf8"),u.end();;){let G=await c;for(let De of G)yield De}}return{read:l(),close:()=>{u&&u.close()}}},d(J,_e),d(J,ae,new Map);var Le=t=>Vt()?J.getClient(t):new le(t),Ue=t=>t instanceof Object&&"body"in t&&"headers"in t&&"status"in t,Be=t=>"stream"in t&&typeof t.stream=="function",Vt=()=>{if(typeof process<"u"&&process&&process.release?.name==="node")try{return qe("node:http2"),!0}catch{return!1}return!1};var Ye=It(it());var Gt=/(?:\d{4}|[\u2212-]\d{4,}|\+\d{5,})/,zt=/(?:0[1-9]|1[0-2])/,Xt=/(?:0[1-9]|[12]\d|3[01])/,ut=/(?:[01][0-9]|2[0-3])/,ge=/(?:[0-5][0-9])/,Yt=/(?:\.\d+)/,Ge=new RegExp(`(${Gt.source}-(${zt.source})-(${Xt.source}))`),Jt=new RegExp(`(${ut.source}:${ge.source}:${ge.source}${Yt.source}?)`),Zt=new RegExp(`([zZ]|[+\u2212-]${ut.source}(?::?${ge.source}|:${ge.source}:${ge.source}))`),ct=new RegExp(`^${Ge.source}$`),dt=new RegExp(`^${Ge.source}`),lt=new RegExp(`^${Ge.source}T${Jt.source}${Zt.source}$`);var N=class{isoString;constructor(e){this.isoString=e}static from(e){if(typeof e!="string")throw new TypeError(`Expected string but received ${typeof e}: ${e}`);if(lt.exec(e)===null)throw new RangeError(`(regex) Expected an ISO date string but received '${e}'`);return new N(e)}static fromDate(e){return new N(e.toISOString())}toDate(){let e=new Date(this.isoString);if(e.toString()==="Invalid Date")throw new RangeError("Fauna Date could not be converted to Javascript Date");return e}toString(){return`TimeStub("${this.isoString}")`}},H=class{dateString;constructor(e){this.dateString=e}static from(e){if(typeof e!="string")throw new TypeError(`Expected string but received ${typeof e}: ${e}`);let r=ct.exec(e);if(r===null)throw new RangeError(`Expected a plain date string but received '${e}'`);return new H(r[0])}static fromDate(e){let r=e.toISOString(),s=dt.exec(r);if(s===null)throw new b(`Failed to parse date '${e}'`);return new H(s[0])}toDate(){let e=new Date(this.dateString+"T00:00:00Z");if(e.toString()==="Invalid Date")throw new RangeError("Fauna Date could not be converted to Javascript Date");return e}toString(){return`DateStub("${this.dateString}")`}};var j=class{coll;id;constructor({coll:e,id:r}){this.id=r,typeof e=="string"?this.coll=new L(e):this.coll=e}},ue=class extends j{ts;ttl;constructor(e){let{coll:r,id:s,ts:n,...o}=e;super({coll:r,id:s}),this.ts=n,Object.assign(this,o)}toObject(){return{...this}}},K=class{coll;name;constructor({coll:e,name:r}){this.name=r,typeof e=="string"?this.coll=new L(e):this.coll=e}},ce=class extends K{ts;data;constructor(e){let{coll:r,name:s,ts:n,data:o,...a}=e;super({coll:r,name:s}),this.ts=n,this.data=o||{},Object.assign(this,a)}toObject(){return{...this}}},L=class{name;constructor(e){this.name=e}},de=class{ref;cause;constructor(e,r){this.ref=e,this.cause=r}};var F=class{data;after;constructor({data:e,after:r}){this.data=e,this.after=r}},U=class{after;constructor(e){this.after=e}},I=class{#e;constructor(e,r,s){if(s=s??{},r instanceof Function)this.#e=er(e,r,s);else if(r instanceof F||r instanceof U)this.#e=mt(e,r,s);else throw new TypeError(`Expected 'Page<T> | EmbeddedSet | (() => Promise<T | Page<T> | EmbeddedSet>)', but received ${JSON.stringify(r)}`)}static fromQuery(e,r,s){return new I(e,async()=>(await e.query(r,s)).data,s)}static fromPageable(e,r,s){return new I(e,r,s)}flatten(){return new ze(this)}async next(){return this.#e.next()}async return(){return this.#e.return()}async throw(e){return this.#e.throw(e)}[Symbol.asyncIterator](){return this}},ze=class{#e;constructor(e){this.#e=tr(e)}async next(){return this.#e.next()}async return(){return this.#e.return()}async throw(e){return this.#e.throw(e)}[Symbol.asyncIterator](){return this}};async function*mt(t,e,r){let s=e;for(s instanceof F&&(yield s.data);s.after;){let n=Xe`Set.paginate(${s.after})`;s=(await t.query(n,r)).data,yield s.data}}async function*er(t,e,r){let s=await e();if(s instanceof F||s instanceof U){for await(let n of mt(t,s,r))yield n;return}yield[s]}async function*tr(t){for await(let e of t)for(let r of e)yield r}var D=class{token;constructor(e){this.token=e}};var q=class{static encode(e){return ke(e)}static decode(e,r){return JSON.parse(e,(s,n)=>{if(n==null)return null;if(n["@mod"])return new L(n["@mod"]);if(n["@doc"]){if(typeof n["@doc"]=="string"){let[a,c]=n["@doc"].split(":");return new j({coll:a,id:c})}let o=n["@doc"];return o.id?new ue(o):new ce(o)}else if(n["@ref"]){let o=n["@ref"],a;return o.id?a=new j(o):a=new K(o),"exists"in o&&o.exists===!1?new de(a,o.cause):a}else{if(n["@set"])return typeof n["@set"]=="string"?new U(n["@set"]):new F(n["@set"]);if(n["@int"])return Number(n["@int"]);if(n["@long"]){let o=BigInt(n["@long"]);return r.long_type==="number"?((o>Number.MAX_SAFE_INTEGER||o<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."),Number(o)):o}else{if(n["@double"])return Number(n["@double"]);if(n["@date"])return H.from(n["@date"]);if(n["@time"])return N.from(n["@time"]);if(n["@object"])return n["@object"];if(n["@stream"])return new D(n["@stream"]);if(n["@bytes"])return rr(n["@bytes"])}}return n})}},yt=BigInt("-9223372036854775808"),gt=BigInt("9223372036854775807"),ft=-(2**31),pt=2**31-1,h={bigint:t=>{if(t<yt||t>gt)throw new RangeError("BigInt value exceeds max magnitude for a 64-bit Fauna long. Use a 'number' to represent doubles beyond that limit.");return t>=ft&&t<=pt?{"@int":t.toString()}:{"@long":t.toString()}},number:t=>{if(t===Number.POSITIVE_INFINITY||t===Number.NEGATIVE_INFINITY)throw new RangeError(`Cannot convert ${t} to a Fauna type.`);return Number.isInteger(t)?t>=ft&&t<=pt?{"@int":t.toString()}:Number.isSafeInteger(t)?{"@long":t.toString()}:{"@double":t.toString()}:{"@double":t.toString()}},string:t=>t,object:t=>{let e=!1,r={};for(let s in t)s.startsWith("@")&&(e=!0),t[s]!==void 0&&(r[s]=ke(t[s]));return e?{"@object":r}:r},array:t=>{let e=[];for(let r in t)e.push(ke(t[r]));return e},date:t=>({"@time":t.toISOString()}),faunadate:t=>({"@date":t.dateString}),faunatime:t=>({"@time":t.isoString}),module:t=>({"@mod":t.name}),documentReference:t=>({"@ref":{id:t.id,coll:{"@mod":t.coll.name}}}),document:t=>({"@ref":{id:t.id,coll:{"@mod":t.coll.name}}}),namedDocumentReference:t=>({"@ref":{name:t.name,coll:{"@mod":t.coll.name}}}),namedDocument:t=>({"@ref":{name:t.name,coll:{"@mod":t.coll.name}}}),set:t=>{throw new b("Page could not be encoded. Fauna does not accept encoded Set values, yet. Use Page.data and Page.after as arguments, instead.")},streamToken:t=>t.token,bytes:t=>({"@bytes":nr(t)})},ke=t=>{if(t===void 0)throw new TypeError("Passing undefined as a QueryValue is not supported");switch(typeof t){case"bigint":return h.bigint(t);case"string":return h.string(t);case"number":return h.number(t);case"boolean":return t;case"object":if(t==null)return null;if(Array.isArray(t))return h.array(t);if(t instanceof Date)return h.date(t);if(t instanceof H)return h.faunadate(t);if(t instanceof N)return h.faunatime(t);if(t instanceof L)return h.module(t);if(t instanceof ue)return h.document(t);if(t instanceof j)return h.documentReference(t);if(t instanceof ce)return h.namedDocument(t);if(t instanceof K)return h.namedDocumentReference(t);if(t instanceof de)return ke(t.ref);if(t instanceof F)return h.set(t);if(t instanceof U)return h.set(t);if(t instanceof D)return h.streamToken(t);if(t instanceof Uint8Array||t instanceof ArrayBuffer)return h.bytes(t);if(ArrayBuffer.isView(t))throw new b("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");return h.object(t)}};function rr(t){return Ye.default.toByteArray(t)}function nr(t){let e=t instanceof Uint8Array?t:new Uint8Array(t);return Ye.default.fromByteArray(e)}function Xe(t,...e){return new B(t,...e)}var B=class{#e;#t;constructor(e,...r){if(e.length===0||e.length!==r.length+1)throw new Error("invalid query constructed");this.#e=e,this.#t=r}toQuery(e={}){return{...this.#r(e),...e}}#r(e){if(this.#e.length===1)return{query:{fql:[this.#e[0]]},arguments:{}};let r={};return{query:{fql:this.#e.flatMap((n,o)=>{if(o===this.#e.length-1)return n===""?[]:[n];let a=this.#t[o],c;if(a instanceof B){let u=a.toQuery(e);c=u.query,r={...r,...u.arguments}}else c={value:q.encode(a)};return[n,c].filter(u=>u!=="")})},arguments:r}}};var ht="2.0.0-beta.0";var Qe;try{Qe=qe("node:os")}catch{Qe=void 0}var St=()=>{let t={driver:["javascript",ht].join("-"),env:"unknown",os:"unknown",runtime:"unknown"};try{let e=typeof window>"u"&&typeof process<"u"&&process.versions!=null&&process.versions.node!=null,r=typeof window<"u"&&typeof window.document<"u",s=typeof self=="object"&&self.constructor&&self.constructor.name==="DedicatedWorkerGlobalScope";e?(t.runtime=["nodejs",process.version].join("-"),t.env=or(),t.os=[Qe.platform(),Qe.release()].join("-")):s?(t.runtime=Tt(navigator),t.env="Service Worker",t.os=bt(navigator)):r?(t.runtime=Tt(navigator),t.env="browser",t.os=bt(navigator)):typeof EdgeRuntime!="string"&&(t.runtime="Vercel Edge Runtime",t.env="edge")}catch{}return Object.entries(t).filter(([e,r])=>r!=="unknown").map(e=>e.join("=")).join("; ")},Tt=t=>{let e=t.appName,r=""+parseFloat(t.appVersion),s,n,o;return(n=t.userAgent.indexOf("Opera"))!=-1?(e="Opera",r=t.userAgent.substring(n+6),(n=t.userAgent.indexOf("Version"))!=-1&&(r=t.userAgent.substring(n+8))):(n=t.userAgent.indexOf("MSIE"))!=-1?(e="Microsoft Internet Explorer",r=t.userAgent.substring(n+5)):e=="Netscape"&&t.userAgent.indexOf("Trident/")!=-1?(e="Microsoft Internet Explorer",r=t.userAgent.substring(n+5),(n=t.userAgent.indexOf("rv:"))!=-1&&(r=t.userAgent.substring(n+3))):(n=t.userAgent.indexOf("Chrome"))!=-1?(e="Chrome",r=t.userAgent.substring(n+7)):(n=t.userAgent.indexOf("Safari"))!=-1?(e="Safari",r=t.userAgent.substring(n+7),(n=t.userAgent.indexOf("Version"))!=-1&&(r=t.userAgent.substring(n+8)),t.userAgent.indexOf("CriOS")!=-1&&(e="Chrome")):(n=t.userAgent.indexOf("Firefox"))!=-1?(e="Firefox",r=t.userAgent.substring(n+8)):(s=t.userAgent.lastIndexOf(" ")+1)<(n=t.userAgent.lastIndexOf("/"))&&(e=t.userAgent.substring(s,n),r=t.userAgent.substring(n+1),e.toLowerCase()==e.toUpperCase()&&(e=t.appName)),(o=r.indexOf(";"))!=-1&&(r=r.substring(0,o)),(o=r.indexOf(" "))!=-1&&(r=r.substring(0,o)),(o=r.indexOf(")"))!=-1&&(r=r.substring(0,o)),[e,r].join("-")},bt=t=>{let e="unknown",r=[{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(let n in r){let o=r[n];if(o.r.test(t.userAgent)){e=o.s;break}}let s="unknown";if(/Windows/.test(e)){let n=/Windows (.*)/.exec(e);n&&(s=n[1]),e="Windows"}switch(e){case"Mac OS":case"Mac OS X":case"Android":{let n=/(?:Android|Mac OS|Mac OS X|MacPPC|MacIntel|Mac_PowerPC|Macintosh) ([._\d]+)/.exec(t.userAgent);n&&(s=n[1]);break}case"iOS":{let n=/OS (\d+)_(\d+)_?(\d+)?/.exec(t.appVersion);n&&(s=n[1]+"."+n[2]+"."+(n[3]??0));break}}return[e,s].join("-")},sr=typeof window<"u"?window:typeof globalThis<"u"?globalThis:typeof global<"u"?global:self,or=()=>{if(!(typeof process<"u"&&process&&process.env&&typeof process.env=="object"))return"unknown";let e=[{name:"Netlify",check:function(){return!!process.env.NETLIFY_IMAGES_CDN_DOMAIN}},{name:"Vercel",check:function(){return!!process.env.VERCEL}},{name:"Heroku",check:function(){return!!process.env.PATH&&process.env.PATH.indexOf(".heroku")!==-1}},{name:"AWS Lambda",check:function(){return!!process.env.AWS_LAMBDA_FUNCTION_VERSION}},{name:"GCP Cloud Functions",check:function(){return!!process.env._&&process.env._.indexOf("google")!==-1}},{name:"GCP Compute Instances",check:function(){return!!process.env.GOOGLE_CLOUD_PROJECT}},{name:"Azure Cloud Functions",check:function(){return!!process.env.WEBSITE_FUNCTIONS_AZUREMONITOR_CATEGORIES}},{name:"Azure Compute",check:function(){return!!process.env.ORYX_ENV_TYPE&&!!process.env.WEBSITE_INSTANCE_ID&&process.env.ORYX_ENV_TYPE==="AppService"}},{name:"Mongo Stitch",check:function(){return typeof sr?.StitchError=="function"}},{name:"Render",check:function(){return!!process.env.RENDER_SERVICE_ID}},{name:"Begin",check:function(){return!!process.env.BEGIN_DATA_SCOPE_ID}}].find(r=>r.check());return e?e.name:"unknown"};var wt=t=>t instanceof Object&&"data"in t,xt=t=>t instanceof Object&&"error"in t&&t.error instanceof Object&&"code"in t.error&&"message"in t.error;var Je={client_timeout_buffer_ms:5e3,format:"tagged",http2_session_idle_ms:5e3,http2_max_streams:100,long_type:"number",fetch_keepalive:!1,query_timeout_ms:5e3,max_attempts:3,max_backoff:20},Oe,x,$,A,ee,he,Ze,Te,Ke,ve,_t,Ne,Et,He,Ct,Fe,At,Ie,kt,et=class{constructor(e,r){d(this,he);d(this,Te);d(this,ve);d(this,Ne);d(this,He);d(this,Fe);d(this,Ie);d(this,x,void 0);d(this,$,void 0);d(this,A,void 0);d(this,ee,!1);S(this,x,{...Je,...e,secret:p(this,ve,_t).call(this,e),endpoint:p(this,Ne,Et).call(this,e)}),p(this,Ie,kt).call(this),r?S(this,$,r):S(this,$,Le({url:i(this,x).endpoint.toString(),http2_session_idle_ms:i(this,x).http2_session_idle_ms,http2_max_streams:i(this,x).http2_max_streams,fetch_keepalive:i(this,x).fetch_keepalive}))}get lastTxnTs(){return i(this,A)}set lastTxnTs(e){e!==void 0&&S(this,A,i(this,A)?Math.max(e,i(this,A)):e)}get clientConfiguration(){let{...e}=i(this,x);return e}close(){if(i(this,ee))throw new O("Your client is closed. You cannot close it again.");i(this,$).close(),S(this,ee,!0)}paginate(e,r){return e instanceof B?I.fromQuery(this,e,r):I.fromPageable(this,e,r)}async query(e,r){if(i(this,ee))throw new O("Your client is closed. No further requests can be issued.");let s=e.toQuery(r).query;return p(this,he,Ze).call(this,s,r)}stream(e,r){if(i(this,ee))throw new O("Your client is closed. No further requests can be issued.");let s=i(this,$);if(Be(s)){let n={...i(this,x),httpStreamClient:s,...r},o=e instanceof B?()=>this.query(e).then(a=>a.data):e;return new Pe(o,n)}else throw new b("Streaming is not supported by this client.")}},Re=et;Oe=new WeakMap,x=new WeakMap,$=new WeakMap,A=new WeakMap,ee=new WeakMap,he=new WeakSet,Ze=async function(e,r,s=0){let n=this.clientConfiguration.max_backoff??Je.max_backoff,o=this.clientConfiguration.max_attempts??Je.max_attempts,a=Math.min(Math.random()*2**s,n)*1e3;s+=1;try{return await p(this,He,Ct).call(this,e,r,s)}catch(c){if(c instanceof M&&s<o)return await Qt(a),p(this,he,Ze).call(this,e,r,s);throw c}},Te=new WeakSet,Ke=function(e){if(e instanceof b||e instanceof g||e instanceof v||e instanceof y)return e;if(Ue(e)){if(xt(e.body)){let r=e.body,s=e.status;return X(r,s)}return new v({message:`Response is in an unkown format: ${e.body}`,httpStatus:e.status})}return new b("A client level error occurred. Fauna was not called.",{cause:e})},ve=new WeakSet,_t=function(e){let r;typeof process<"u"&&process&&typeof process=="object"&&process.env&&typeof process.env=="object"&&(r=process.env.FAUNA_SECRET);let s=e?.secret??r;if(s===void 0)throw new TypeError("You must provide a secret to the driver. Set it in an environmental variable named FAUNA_SECRET or pass it to the Client constructor.");return s},Ne=new WeakSet,Et=function(e){if(e&&"endpoint"in e&&e.endpoint===void 0)throw new TypeError("ClientConfiguration option endpoint must be defined.");let r;return typeof process<"u"&&process&&typeof process=="object"&&process.env&&typeof process.env=="object"&&(r=process.env.FAUNA_ENDPOINT?new URL(process.env.FAUNA_ENDPOINT):void 0),e?.endpoint??r??We.default},He=new WeakSet,Ct=async function(e,r,s=0){try{let n={...i(this,x),...r},o={Authorization:`Bearer ${n.secret}`};p(this,Fe,At).call(this,n,o);let a=n.format==="tagged",c=n.arguments?a?q.encode(n.arguments):n.arguments:void 0,u={query:e,arguments:c},T=n.query_timeout_ms+i(this,x).client_timeout_buffer_ms,f=await i(this,$).request({client_timeout_ms:T,data:u,headers:o,method:"POST"}),l;try{if(l={...f,body:a?q.decode(f.body,{long_type:n.long_type}):JSON.parse(f.body)},l.body.query_tags){let _=l.body.query_tags.split(",").map(E=>E.split("="));l.body.query_tags=Object.fromEntries(_)}}catch(_){throw new v({message:`Error parsing response as JSON: ${_}`,httpStatus:f.status})}if(!wt(l.body))throw p(this,Te,Ke).call(this,l);let m=l.body.txn_ts;(i(this,A)===void 0&&m!==void 0||m!==void 0&&i(this,A)!==void 0&&i(this,A)<m)&&S(this,A,m);let k=l.body;return k.stats&&(k.stats.attempts=s),k}catch(n){throw p(this,Te,Ke).call(this,n)}},Fe=new WeakSet,At=function(e,r){let s=(n,o,a=c=>String(c))=>{o!==void 0&&(r[n]=a(o))};s("x-format",e.format),s("x-typecheck",e.typecheck),s("x-query-timeout-ms",e.query_timeout_ms),s("x-linearized",e.linearized),s("x-max-contention-retries",e.max_contention_retries),s("traceparent",e.traceparent),s("x-query-tags",e.query_tags,n=>Object.entries(n).map(o=>o.join("=")).join(",")),s("x-last-txn-ts",i(this,A),n=>n),s("x-driver-env",i(et,Oe))},Ie=new WeakSet,kt=function(){let e=i(this,x);if(["client_timeout_buffer_ms","endpoint","format","http2_session_idle_ms","long_type","query_timeout_ms","fetch_keepalive","http2_max_streams","max_backoff","max_attempts"].forEach(s=>{if(e[s]===void 0)throw new TypeError(`ClientConfiguration option '${s}' must be defined.`)}),e.http2_max_streams<=0)throw new RangeError("'http2_max_streams' must be greater than zero.");if(e.client_timeout_buffer_ms<=0)throw new RangeError("'client_timeout_buffer_ms' must be greater than zero.");if(e.query_timeout_ms<=0)throw new RangeError("'query_timeout_ms' must be greater than zero.");if(e.max_backoff<=0)throw new RangeError("'max_backoff' must be greater than zero.");if(e.max_attempts<=0)throw new RangeError("'max_attempts' must be greater than zero.")},d(Re,Oe,St());var Pe=class{closed=!1;#e;#t=0;#r;#s;#n;#o;constructor(e,r){e instanceof D?this.#r=()=>Promise.resolve(e):this.#r=e,this.#e=r,this.#i()}start(e,r){if(typeof e!="function")throw new TypeError(`Expected a function as the 'onEvent' argument, but received ${typeof e}. Please provide a valid function.`);if(r&&typeof r!="function")throw new TypeError(`Expected a function as the 'onError' argument, but received ${typeof r}. Please provide a valid function.`);(async()=>{try{for await(let n of this)e(n)}catch(n){r&&r(n)}})()}async*[Symbol.asyncIterator](){if(this.closed)throw new b("The stream has been closed and cannot be reused.");for(this.#o||(this.#o=await this.#r().then(e=>{if(!(e instanceof D))throw new b(`Error requesting a stream token. Expected a StreamToken as the query result, but received ${typeof e}. Your query must return the result of '<Set>.toStream' or '<Set>.changesOn') | ||
Query result: ${JSON.stringify(e,null)}`);return e})),this.#t=1;!this.closed;){let e=Math.min(Math.random()*2**this.#t,this.#e.max_backoff)*1e3;try{for await(let r of this.#a(this.#s))yield r}catch(r){if(r instanceof Q||this.#t>=this.#e.max_attempts)throw this.close(),r;this.#t+=1,await Qt(e)}}}close(){this.#n&&(this.#n.close(),this.#n=void 0),this.closed=!0}get last_ts(){return this.#s}async*#a(e){let r=this.#o,s={Authorization:`Bearer ${this.#e.secret}`},n=this.#e.httpStreamClient.stream({data:{token:r.token,start_ts:e},headers:s,method:"POST"});this.#n=n;for await(let o of n.read){let a=q.decode(o,{long_type:this.#e.long_type});if(a.type==="error")throw this.close(),X(a);this.#s=a.txn_ts,a.type==="start"&&(a.type="status"),!(!this.#e.status_events&&a.type==="status")&&(yield a)}}#i(){let e=this.#e;if(["long_type","httpStreamClient","max_backoff","max_attempts","secret"].forEach(s=>{if(e[s]===void 0)throw new TypeError(`ClientConfiguration option '${s}' must be defined.`)}),e.max_backoff<=0)throw new RangeError("'max_backoff' must be greater than zero.");if(e.max_attempts<=0)throw new RangeError("'max_attempts' must be greater than zero.")}};function Qt(t){return new Promise(e=>setTimeout(e,t))}export{Se as AbortError,re as AuthenticationError,ne as AuthorizationError,Re as Client,O as ClientClosedError,b as ClientError,be as ConstraintFailureError,we as ContendedTransactionError,H as DateStub,ue as Document,j as DocumentReference,U as EmbeddedSet,Q as FaunaError,le as FetchClient,z as InvalidRequestError,gt as LONG_MAX,yt as LONG_MIN,L as Module,ce as NamedDocument,K as NamedDocumentReference,g as NetworkError,J as NodeHTTP2Client,de as NullDocument,F as Page,v as ProtocolError,V as QueryCheckError,te as QueryRuntimeError,se as QueryTimeoutError,y as ServiceError,oe as ServiceInternalError,I as SetIterator,Pe as StreamClient,D as StreamToken,q as TaggedTypeFormat,M as ThrottlingError,N as TimeStub,We as endpoints,Xe as fql,Le as getDefaultHTTPClient,Ue as isHTTPResponse,Be as isStreamClient}; | ||
//# sourceMappingURL=index.js.map |
@@ -79,3 +79,3 @@ import { HTTPStreamClient } from "./http-client"; | ||
/** | ||
* Controls what Javascript type to deserialize {@link https://fqlx-beta--fauna-docs.netlify.app/fqlx/beta/reference/language/types#long | Fauna longs} to. | ||
* Controls what Javascript type to deserialize {@link https://docs.fauna.com/fauna/current/reference/fql_reference/types#long | Fauna longs} to. | ||
* Use 'number' to deserialize longs to number. Use 'bigint' to deserialize to bigint. Defaults to 'number'. | ||
@@ -149,3 +149,4 @@ * Note, for extremely large maginitude numbers Javascript's number will lose precision; as Javascript's | ||
/** | ||
* Controls what Javascript type to deserialize {@link https://fqlx-beta--fauna-docs.netlify.app/fqlx/beta/reference/language/types#long | Fauna longs} to. | ||
* Controls what Javascript type to deserialize {@link https://docs.fauna.com/fauna/current/reference/fql_reference/types#long | Fauna longs} to. | ||
* | ||
* @see {@link ClientConfiguration.long_type} | ||
@@ -152,0 +153,0 @@ */ |
@@ -104,6 +104,3 @@ import { ClientConfiguration, StreamClientConfiguration } from "./client-configuration"; | ||
* one of ServiceError's child classes if the error can be further categorized, | ||
* or a concrete ServiceError if it cannot. ServiceError child types are | ||
* {@link AuthenticaionError}, {@link AuthorizationError}, {@link QueryCheckError} | ||
* {@link QueryRuntimeError}, {@link QueryTimeoutError}, {@link ServiceInternalError} | ||
* {@link ServiceTimeoutError}, {@link ThrottlingError}. | ||
* or a concrete ServiceError if it cannot. | ||
* You can use either the type, or the underlying httpStatus + code to determine | ||
@@ -110,0 +107,0 @@ * the root cause. |
@@ -15,3 +15,3 @@ import type { ConstraintFailure, QueryFailure, QueryInfo, QueryValue } from "./wire-protocol"; | ||
*/ | ||
readonly httpStatus: number; | ||
readonly httpStatus?: number; | ||
/** | ||
@@ -32,3 +32,3 @@ * A code for the error. Codes indicate the cause of the error. | ||
readonly constraint_failures?: Array<ConstraintFailure>; | ||
constructor(failure: QueryFailure, httpStatus: number); | ||
constructor(failure: QueryFailure, httpStatus?: number); | ||
} | ||
@@ -40,7 +40,5 @@ /** | ||
* The 'code' field will vary based on the specific error cause. | ||
* | ||
* @see {@link https://fqlx-beta--fauna-docs.netlify.app/fqlx/beta/reference/language/errors#runtime-errors} | ||
*/ | ||
export declare class QueryRuntimeError extends ServiceError { | ||
constructor(failure: QueryFailure, httpStatus: 400); | ||
constructor(failure: QueryFailure, httpStatus?: number); | ||
} | ||
@@ -50,7 +48,5 @@ /** | ||
* failing. | ||
* | ||
* @see {@link https://fqlx-beta--fauna-docs.netlify.app/fqlx/beta/reference/language/errors#runtime-errors} | ||
*/ | ||
export declare class QueryCheckError extends ServiceError { | ||
constructor(failure: QueryFailure, httpStatus: 400); | ||
constructor(failure: QueryFailure, httpStatus?: number); | ||
} | ||
@@ -60,12 +56,22 @@ /** | ||
* valid JSON or did not conform to the API specification | ||
* | ||
* @see {@link https://fqlx-beta--fauna-docs.netlify.app/fqlx/beta/reference/language/errors#runtime-errors} | ||
*/ | ||
export declare class InvalidRequestError extends ServiceError { | ||
constructor(failure: QueryFailure, httpStatus: 400); | ||
constructor(failure: QueryFailure, httpStatus?: number); | ||
} | ||
/** | ||
* A runtime error due to failing schema constraints. | ||
*/ | ||
export declare class ConstraintFailureError extends ServiceError { | ||
/** | ||
* The list of constraints that failed. | ||
*/ | ||
readonly constraint_failures: Array<ConstraintFailure>; | ||
constructor(failure: QueryFailure & { | ||
error: { | ||
constraint_failures: Array<ConstraintFailure>; | ||
}; | ||
}, httpStatus?: number); | ||
} | ||
/** | ||
* An error due to calling the FQL `abort` function. | ||
* | ||
* @see {@link https://fqlx-beta--fauna-docs.netlify.app/fqlx/beta/reference/language/errors#runtime-errors} | ||
*/ | ||
@@ -83,3 +89,3 @@ export declare class AbortError extends ServiceError { | ||
}; | ||
}, httpStatus: 400); | ||
}, httpStatus?: number); | ||
} | ||
@@ -91,3 +97,3 @@ /** | ||
export declare class AuthenticationError extends ServiceError { | ||
constructor(failure: QueryFailure, httpStatus: 401); | ||
constructor(failure: QueryFailure, httpStatus?: number); | ||
} | ||
@@ -99,3 +105,3 @@ /** | ||
export declare class AuthorizationError extends ServiceError { | ||
constructor(failure: QueryFailure, httpStatus: 403); | ||
constructor(failure: QueryFailure, httpStatus?: number); | ||
} | ||
@@ -106,3 +112,3 @@ /** | ||
export declare class ContendedTransactionError extends ServiceError { | ||
constructor(failure: QueryFailure, httpStatus: 409); | ||
constructor(failure: QueryFailure, httpStatus?: number); | ||
} | ||
@@ -114,10 +120,15 @@ /** | ||
export declare class ThrottlingError extends ServiceError { | ||
constructor(failure: QueryFailure, httpStatus: 429); | ||
constructor(failure: QueryFailure, httpStatus?: number); | ||
} | ||
/** | ||
* A failure due to the timeout being exceeded, but the timeout | ||
* was set lower than the query's expected processing time. | ||
* This response is distinguished from a ServiceTimeoutException | ||
* in that a QueryTimeoutError shows Fauna behaving in an expected | ||
* manner. | ||
* A failure due to the query timeout being exceeded. | ||
* | ||
* This error can have one of two sources: | ||
* 1. Fauna is behaving expectedly, but the query timeout provided was too | ||
* aggressive and lower than the query's expected processing time. | ||
* 2. Fauna was not available to service the request before the timeout was | ||
* reached. | ||
* | ||
* In either case, consider increasing the `query_timeout_ms` configuration for | ||
* your client. | ||
*/ | ||
@@ -131,3 +142,3 @@ export declare class QueryTimeoutError extends ServiceError { | ||
}; | ||
constructor(failure: QueryFailure, httpStatus: 440); | ||
constructor(failure: QueryFailure, httpStatus?: number); | ||
} | ||
@@ -138,12 +149,5 @@ /** | ||
export declare class ServiceInternalError extends ServiceError { | ||
constructor(failure: QueryFailure, httpStatus: 500); | ||
constructor(failure: QueryFailure, httpStatus?: number); | ||
} | ||
/** | ||
* ServiceTimeoutError indicates Fauna was not available to servce | ||
* the request before the timeout was reached. | ||
*/ | ||
export declare class ServiceTimeoutError extends ServiceError { | ||
constructor(failure: QueryFailure, httpStatus: 503); | ||
} | ||
/** | ||
* An error representing a failure internal to the client, itself. | ||
@@ -189,1 +193,2 @@ * This indicates Fauna was never called - the client failed internally | ||
} | ||
export declare const getServiceError: (failure: QueryFailure, httpStatus?: number) => ServiceError; |
export { Client, StreamClient } from "./client"; | ||
export { endpoints, type ClientConfiguration, type Endpoints, type StreamClientConfiguration, } from "./client-configuration"; | ||
export { AbortError, AuthenticationError, AuthorizationError, ClientError, ClientClosedError, ContendedTransactionError, FaunaError, InvalidRequestError, NetworkError, ProtocolError, QueryCheckError, QueryRuntimeError, QueryTimeoutError, ServiceError, ServiceInternalError, ServiceTimeoutError, ThrottlingError, } from "./errors"; | ||
export { type Query, fql } from "./query-builder"; | ||
export { AbortError, AuthenticationError, AuthorizationError, ClientError, ClientClosedError, ConstraintFailureError, ContendedTransactionError, FaunaError, InvalidRequestError, NetworkError, ProtocolError, QueryCheckError, QueryRuntimeError, QueryTimeoutError, ServiceError, ServiceInternalError, ThrottlingError, } from "./errors"; | ||
export { type Query, type QueryArgument, fql } from "./query-builder"; | ||
export { LONG_MAX, LONG_MIN, TaggedTypeFormat } from "./tagged-type"; | ||
@@ -6,0 +6,0 @@ export { type QueryValueObject, type QueryValue, type QueryFailure, type QueryInfo, type QueryInterpolation, type QueryOptions, type QueryRequest, type QueryStats, type QuerySuccess, type Span, type ValueFragment, } from "./wire-protocol"; |
import type { QueryValue, QueryRequest, QueryOptions } from "./wire-protocol"; | ||
export type QueryArgument = QueryValue | Query | Date | ArrayBuffer | Uint8Array; | ||
/** | ||
@@ -18,3 +19,3 @@ * Creates a new Query. Accepts template literal inputs. | ||
*/ | ||
export declare function fql(queryFragments: ReadonlyArray<string>, ...queryArgs: (QueryValue | Query)[]): Query; | ||
export declare function fql(queryFragments: ReadonlyArray<string>, ...queryArgs: QueryArgument[]): Query; | ||
/** | ||
@@ -27,3 +28,3 @@ * Internal class. | ||
#private; | ||
constructor(queryFragments: ReadonlyArray<string>, ...queryArgs: (QueryValue | Query)[]); | ||
constructor(queryFragments: ReadonlyArray<string>, ...queryArgs: QueryArgument[]); | ||
/** | ||
@@ -30,0 +31,0 @@ * Converts this Query to a {@link QueryRequest} you can send |
/** The current package version. */ | ||
export declare const packageVersion = "1.4.0-beta.0"; | ||
export declare const packageVersion = "2.0.0-beta.0"; |
@@ -17,3 +17,3 @@ /** | ||
* | ||
* @see {@link https://fqlx-beta--fauna-docs.netlify.app/fqlx/beta/reference/builtin_functions/time/time} | ||
* @see {@link https://docs.fauna.com/fauna/current/reference/fql_reference/types#time} | ||
*/ | ||
@@ -68,3 +68,3 @@ export declare class TimeStub { | ||
* | ||
* @see {@link https://fqlx-beta--fauna-docs.netlify.app/fqlx/beta/reference/builtin_functions/date/date} | ||
* @see {@link https://docs.fauna.com/fauna/current/reference/fql_reference/types#date} | ||
*/ | ||
@@ -71,0 +71,0 @@ export declare class DateStub { |
@@ -21,2 +21,4 @@ import { QueryValueObject } from "../wire-protocol"; | ||
* ``` | ||
* | ||
* @see {@link https://docs.fauna.com/fauna/current/reference/fql_reference/types#special} | ||
*/ | ||
@@ -53,5 +55,8 @@ export declare class DocumentReference { | ||
* extend generic type arguments. | ||
* | ||
* @see {@link https://docs.fauna.com/fauna/current/reference/fql_reference/types#special} | ||
*/ | ||
export declare class Document extends DocumentReference { | ||
readonly ts: TimeStub; | ||
readonly ttl?: TimeStub; | ||
constructor(obj: { | ||
@@ -67,2 +72,3 @@ coll: Module | string; | ||
ts: TimeStub; | ||
ttl?: TimeStub; | ||
}; | ||
@@ -88,2 +94,4 @@ } | ||
* ``` | ||
* | ||
* @see {@link https://docs.fauna.com/fauna/current/reference/fql_reference/types#special} | ||
*/ | ||
@@ -130,2 +138,4 @@ export declare class NamedDocumentReference { | ||
* ``` | ||
* | ||
* @see {@link https://docs.fauna.com/fauna/current/reference/fql_reference/types#special} | ||
*/ | ||
@@ -165,2 +175,4 @@ export declare class NamedDocument<T extends QueryValueObject = Record<string, never>> extends NamedDocumentReference { | ||
* ``` | ||
* | ||
* @see {@link https://docs.fauna.com/fauna/current/reference/fql_reference/types#module} | ||
*/ | ||
@@ -196,2 +208,4 @@ export declare class Module { | ||
* ``` | ||
* | ||
* @see {@link https://docs.fauna.com/fauna/current/reference/fql_reference/types#nulldoc} | ||
*/ | ||
@@ -198,0 +212,0 @@ export declare class NullDocument { |
@@ -6,3 +6,3 @@ import { Client } from "../client"; | ||
* A materialized view of a Set. | ||
* @see {@link https://fqlx-beta--fauna-docs.netlify.app/fqlx/beta/reference/language/types#set} | ||
* @see {@link https://docs.fauna.com/fauna/current/reference/fql_reference/types#set} | ||
*/ | ||
@@ -27,3 +27,3 @@ export declare class Page<T extends QueryValue> { | ||
* issues such as self-reference and infinite recursion | ||
* @see {@link https://fqlx-beta--fauna-docs.netlify.app/fqlx/beta/reference/language/types#set} | ||
* @see {@link https://docs.fauna.com/fauna/current/reference/fql_reference/types#set} | ||
*/ | ||
@@ -30,0 +30,0 @@ export declare class EmbeddedSet { |
@@ -36,3 +36,3 @@ import { DateStub, Document, DocumentReference, EmbeddedSet, Module, NamedDocument, NamedDocumentReference, NullDocument, Page, StreamToken, TimeStub } from "./values"; | ||
/** | ||
* Controls what Javascript type to deserialize {@link https://fqlx-beta--fauna-docs.netlify.app/fqlx/beta/reference/language/types#long | Fauna longs} to. | ||
* Controls what Javascript type to deserialize {@link https://docs.fauna.com/fauna/current/reference/fql_reference/types#long | Fauna longs} to. | ||
* Use 'number' to deserialize longs to number. Use 'bigint' to deserialize to bigint. Defaults to 'number'. | ||
@@ -257,3 +257,3 @@ * Note, for extremely large maginitude numbers Javascript's number will lose precision; as Javascript's | ||
*/ | ||
export type QueryValue = null | string | number | bigint | boolean | QueryValueObject | Array<QueryValue> | DateStub | TimeStub | Module | Document | DocumentReference | NamedDocument | NamedDocumentReference | NullDocument | Page<QueryValue> | EmbeddedSet | StreamToken; | ||
export type QueryValue = null | string | number | bigint | boolean | QueryValueObject | Array<QueryValue> | DateStub | TimeStub | Module | Document | DocumentReference | NamedDocument | NamedDocumentReference | NullDocument | Page<QueryValue> | EmbeddedSet | StreamToken | Uint8Array; | ||
export type StreamRequest = { | ||
@@ -260,0 +260,0 @@ token: string; |
{ | ||
"name": "fauna", | ||
"version": "1.4.0-beta.0", | ||
"version": "2.0.0-beta.0", | ||
"description": "A driver to query Fauna databases in browsers, Node.js, and other Javascript runtimes", | ||
@@ -21,19 +21,19 @@ "homepage": "https://fauna.com", | ||
"@tsconfig/node18": "^1.0.1", | ||
"@types/jest": "^29.4.0", | ||
"@types/jest": "^29.5.12", | ||
"@types/node": "^18.13.0", | ||
"@types/serviceworker": "^0.0.67", | ||
"@typescript-eslint/eslint-plugin": "^5.52.0", | ||
"@typescript-eslint/parser": "^5.52.0", | ||
"@typescript-eslint/eslint-plugin": "^7.5.0", | ||
"@typescript-eslint/parser": "^7.5.0", | ||
"esbuild": "^0.15.12", | ||
"eslint": "^8.25.0", | ||
"eslint": "^8.57.0", | ||
"eslint-plugin-tsdoc": "^0.2.17", | ||
"husky": "^8.0.1", | ||
"jest": "^29.4.2", | ||
"jest": "^29.7.0", | ||
"jest-fetch-mock": "^3.0.3", | ||
"jest-junit": "^12.0.0", | ||
"prettier": "^2.7.1", | ||
"pretty-quick": "^3.1.3", | ||
"ts-jest": "^29.0.3", | ||
"ts-node": "^10.9.1", | ||
"typescript": "^4.8.4" | ||
"jest-junit": "^16.0.0", | ||
"prettier": "^3.2.5", | ||
"pretty-quick": "^4.0.0", | ||
"ts-jest": "^29.1.2", | ||
"ts-node": "^10.9.2", | ||
"typescript": "^5.4.3" | ||
}, | ||
@@ -46,3 +46,3 @@ "scripts": { | ||
"lint": "eslint -f unix \"src/**/*.{ts,tsx}\"", | ||
"fauna-local": "docker start faunadb-local || docker run --rm -d --name faunadb-local -p 8443:8443 -p 8084:8084 --mount type=bind,source=\"$(pwd)\"/docker/feature-flags.json,target=/etc/feature-flag-periodic.d/feature-flags.json fauna/faunadb", | ||
"fauna-local": "docker start faunadb-local || docker run --rm -d --name faunadb-local -p 8443:8443 -p 8084:8084 fauna/faunadb", | ||
"fauna-local-alt-port": "docker start faunadb-local-alt-port || docker run --rm -d --name faunadb-local-alt-port -p 7443:8443 -p 7084:8084 fauna/faunadb", | ||
@@ -63,3 +63,6 @@ "prepare": "husky install", | ||
"titleTemplate": "{title}" | ||
}, | ||
"dependencies": { | ||
"base64-js": "^1.5.1" | ||
} | ||
} |
@@ -108,3 +108,3 @@ # The Official Javascript Driver for [Fauna](https://fauna.com). | ||
```shell | ||
npm install fauna | ||
npm install fauna@beta | ||
``` | ||
@@ -115,3 +115,3 @@ | ||
```shell | ||
yarn add fauna | ||
yarn add fauna@beta | ||
``` | ||
@@ -490,2 +490,29 @@ | ||
_Close a stream_ | ||
Use the `<stream>.close()` method to close a stream. | ||
```javascript | ||
import { Client, fql } from "fauna" | ||
const client = new Client() | ||
const stream = await client.stream(fql`Product.all().toStream()`) | ||
let count = 0; | ||
for await (const event of stream) { | ||
console.log(event.type) | ||
console.log(event.data) | ||
count++; | ||
// Close the stream after 2 events | ||
if (count === 2) { | ||
console.log("Closing the stream ...") | ||
stream.close() | ||
break; | ||
} | ||
} | ||
client.close(); | ||
``` | ||
# Contributing | ||
@@ -492,0 +519,0 @@ |
@@ -91,3 +91,3 @@ import { HTTPStreamClient } from "./http-client"; | ||
/** | ||
* Controls what Javascript type to deserialize {@link https://fqlx-beta--fauna-docs.netlify.app/fqlx/beta/reference/language/types#long | Fauna longs} to. | ||
* Controls what Javascript type to deserialize {@link https://docs.fauna.com/fauna/current/reference/fql_reference/types#long | Fauna longs} to. | ||
* Use 'number' to deserialize longs to number. Use 'bigint' to deserialize to bigint. Defaults to 'number'. | ||
@@ -171,3 +171,4 @@ * Note, for extremely large maginitude numbers Javascript's number will lose precision; as Javascript's | ||
/** | ||
* Controls what Javascript type to deserialize {@link https://fqlx-beta--fauna-docs.netlify.app/fqlx/beta/reference/language/types#long | Fauna longs} to. | ||
* Controls what Javascript type to deserialize {@link https://docs.fauna.com/fauna/current/reference/fql_reference/types#long | Fauna longs} to. | ||
* | ||
* @see {@link ClientConfiguration.long_type} | ||
@@ -174,0 +175,0 @@ */ |
@@ -7,19 +7,10 @@ import { | ||
import { | ||
AuthenticationError, | ||
AuthorizationError, | ||
ClientClosedError, | ||
ClientError, | ||
FaunaError, | ||
NetworkError, | ||
ProtocolError, | ||
AbortError, | ||
QueryCheckError, | ||
QueryRuntimeError, | ||
QueryTimeoutError, | ||
ServiceError, | ||
ServiceInternalError, | ||
ServiceTimeoutError, | ||
ThrottlingError, | ||
ContendedTransactionError, | ||
InvalidRequestError, | ||
FaunaError, | ||
getServiceError, | ||
} from "./errors"; | ||
@@ -45,3 +36,2 @@ import { | ||
StreamEventStatus, | ||
type QueryFailure, | ||
type QueryOptions, | ||
@@ -119,3 +109,3 @@ type QuerySuccess, | ||
clientConfiguration?: ClientConfiguration, | ||
httpClient?: HTTPClient | ||
httpClient?: HTTPClient, | ||
) { | ||
@@ -176,3 +166,3 @@ this.#clientConfiguration = { | ||
throw new ClientClosedError( | ||
"Your client is closed. You cannot close it again." | ||
"Your client is closed. You cannot close it again.", | ||
); | ||
@@ -228,3 +218,3 @@ } | ||
iterable: Page<T> | EmbeddedSet | Query, | ||
options?: QueryOptions | ||
options?: QueryOptions, | ||
): SetIterator<T> { | ||
@@ -251,6 +241,3 @@ if (iterable instanceof Query) { | ||
* one of ServiceError's child classes if the error can be further categorized, | ||
* or a concrete ServiceError if it cannot. ServiceError child types are | ||
* {@link AuthenticaionError}, {@link AuthorizationError}, {@link QueryCheckError} | ||
* {@link QueryRuntimeError}, {@link QueryTimeoutError}, {@link ServiceInternalError} | ||
* {@link ServiceTimeoutError}, {@link ThrottlingError}. | ||
* or a concrete ServiceError if it cannot. | ||
* You can use either the type, or the underlying httpStatus + code to determine | ||
@@ -267,7 +254,7 @@ * the root cause. | ||
query: Query, | ||
options?: QueryOptions | ||
options?: QueryOptions, | ||
): Promise<QuerySuccess<T>> { | ||
if (this.#isClosed) { | ||
throw new ClientClosedError( | ||
"Your client is closed. No further requests can be issued." | ||
"Your client is closed. No further requests can be issued.", | ||
); | ||
@@ -340,10 +327,9 @@ } | ||
*/ | ||
// TODO: implement options | ||
stream<T extends QueryValue>( | ||
tokenOrQuery: StreamToken | Query, | ||
options?: Partial<StreamClientConfiguration> | ||
options?: Partial<StreamClientConfiguration>, | ||
): StreamClient<T> { | ||
if (this.#isClosed) { | ||
throw new ClientClosedError( | ||
"Your client is closed. No further requests can be issued." | ||
"Your client is closed. No further requests can be issued.", | ||
); | ||
@@ -375,3 +361,3 @@ } | ||
options?: QueryOptions, | ||
attempt = 0 | ||
attempt = 0, | ||
): Promise<QuerySuccess<T>> { | ||
@@ -416,3 +402,3 @@ const maxBackoff = | ||
const status = e.status; | ||
return this.#getServiceError(failure, status); | ||
return getServiceError(failure, status); | ||
} | ||
@@ -432,3 +418,3 @@ | ||
cause: e, | ||
} | ||
}, | ||
); | ||
@@ -454,3 +440,3 @@ } | ||
in an environmental variable named FAUNA_SECRET or pass it to the Client\ | ||
constructor." | ||
constructor.", | ||
); | ||
@@ -470,3 +456,3 @@ } | ||
throw new TypeError( | ||
`ClientConfiguration option endpoint must be defined.` | ||
`ClientConfiguration option endpoint must be defined.`, | ||
); | ||
@@ -491,44 +477,6 @@ } | ||
#getServiceError(failure: QueryFailure, httpStatus: number): ServiceError { | ||
switch (httpStatus) { | ||
case 400: | ||
if (QUERY_CHECK_FAILURE_CODES.includes(failure.error.code)) { | ||
return new QueryCheckError(failure, httpStatus); | ||
} | ||
if (failure.error.code === "invalid_request") { | ||
return new InvalidRequestError(failure, httpStatus); | ||
} | ||
if ( | ||
failure.error.code === "abort" && | ||
failure.error.abort !== undefined | ||
) { | ||
return new AbortError( | ||
failure as QueryFailure & { error: { abort: QueryValue } }, | ||
httpStatus | ||
); | ||
} | ||
return new QueryRuntimeError(failure, httpStatus); | ||
case 401: | ||
return new AuthenticationError(failure, httpStatus); | ||
case 403: | ||
return new AuthorizationError(failure, httpStatus); | ||
case 409: | ||
return new ContendedTransactionError(failure, httpStatus); | ||
case 429: | ||
return new ThrottlingError(failure, httpStatus); | ||
case 440: | ||
return new QueryTimeoutError(failure, httpStatus); | ||
case 500: | ||
return new ServiceInternalError(failure, httpStatus); | ||
case 503: | ||
return new ServiceTimeoutError(failure, httpStatus); | ||
default: | ||
return new ServiceError(failure, httpStatus); | ||
} | ||
} | ||
async #query<T extends QueryValue>( | ||
queryInterpolation: string | QueryInterpolation, | ||
options?: QueryOptions, | ||
attempt = 0 | ||
attempt = 0, | ||
): Promise<QuerySuccess<T>> { | ||
@@ -620,3 +568,3 @@ try { | ||
fromObject: QueryOptions, | ||
headerObject: Record<string, string | number> | ||
headerObject: Record<string, string | number>, | ||
): void { | ||
@@ -626,3 +574,3 @@ const setHeader = <V>( | ||
value: V | undefined, | ||
transform: (v: V) => string | number = (v) => String(v) | ||
transform: (v: V) => string | number = (v) => String(v), | ||
) => { | ||
@@ -643,3 +591,3 @@ if (value !== undefined) { | ||
.map((tag) => tag.join("=")) | ||
.join(",") | ||
.join(","), | ||
); | ||
@@ -668,3 +616,3 @@ setHeader("x-last-txn-ts", this.#lastTxnTs, (v) => v); // x-last-txn-ts doesn't get stringified | ||
throw new TypeError( | ||
`ClientConfiguration option '${option}' must be defined.` | ||
`ClientConfiguration option '${option}' must be defined.`, | ||
); | ||
@@ -680,3 +628,3 @@ } | ||
throw new RangeError( | ||
`'client_timeout_buffer_ms' must be greater than zero.` | ||
`'client_timeout_buffer_ms' must be greater than zero.`, | ||
); | ||
@@ -729,6 +677,5 @@ } | ||
*/ | ||
// TODO: implement stream-specific options | ||
constructor( | ||
token: StreamToken | (() => Promise<StreamToken>), | ||
clientConfiguration: StreamClientConfiguration | ||
clientConfiguration: StreamClientConfiguration, | ||
) { | ||
@@ -755,7 +702,7 @@ if (token instanceof StreamToken) { | ||
onEvent: (event: StreamEventData<T> | StreamEventStatus) => void, | ||
onError?: (error: Error) => void | ||
onError?: (error: Error) => void, | ||
) { | ||
if (typeof onEvent !== "function") { | ||
throw new TypeError( | ||
`Expected a function as the 'onEvent' argument, but received ${typeof onEvent}. Please provide a valid function.` | ||
`Expected a function as the 'onEvent' argument, but received ${typeof onEvent}. Please provide a valid function.`, | ||
); | ||
@@ -765,3 +712,3 @@ } | ||
throw new TypeError( | ||
`Expected a function as the 'onError' argument, but received ${typeof onError}. Please provide a valid function.` | ||
`Expected a function as the 'onError' argument, but received ${typeof onError}. Please provide a valid function.`, | ||
); | ||
@@ -795,3 +742,3 @@ } | ||
`Error requesting a stream token. Expected a StreamToken as the query result, but received ${typeof maybeStreamToken}. Your query must return the result of '<Set>.toStream' or '<Set>.changesOn')\n` + | ||
`Query result: ${JSON.stringify(maybeStreamToken, null)}` | ||
`Query result: ${JSON.stringify(maybeStreamToken, null)}`, | ||
); | ||
@@ -808,3 +755,3 @@ } | ||
Math.random() * 2 ** this.#connectionAttempts, | ||
this.#clientConfiguration.max_backoff | ||
this.#clientConfiguration.max_backoff, | ||
) * 1_000; | ||
@@ -845,3 +792,3 @@ | ||
async *#startStream( | ||
start_ts?: number | ||
start_ts?: number, | ||
): AsyncGenerator<StreamEventData<T> | StreamEventStatus> { | ||
@@ -872,4 +819,3 @@ // Safety: This method must only be called after a stream token has been acquired | ||
this.close(); | ||
// TODO: replace with appropriate class from existing error heirarchy | ||
throw new ServiceError(deserializedEvent, 400); | ||
throw getServiceError(deserializedEvent); | ||
} | ||
@@ -908,3 +854,3 @@ | ||
throw new TypeError( | ||
`ClientConfiguration option '${option}' must be defined.` | ||
`ClientConfiguration option '${option}' must be defined.`, | ||
); | ||
@@ -926,12 +872,4 @@ } | ||
const QUERY_CHECK_FAILURE_CODES = [ | ||
"invalid_function_definition", | ||
"invalid_identifier", | ||
"invalid_query", | ||
"invalid_syntax", | ||
"invalid_type", | ||
]; | ||
function wait(ms: number) { | ||
return new Promise((r) => setTimeout(r, ms)); | ||
} |
@@ -24,3 +24,3 @@ import type { | ||
*/ | ||
readonly httpStatus: number; | ||
readonly httpStatus?: number; | ||
/** | ||
@@ -42,3 +42,3 @@ * A code for the error. Codes indicate the cause of the error. | ||
constructor(failure: QueryFailure, httpStatus: number) { | ||
constructor(failure: QueryFailure, httpStatus?: number) { | ||
super(failure.error.message); | ||
@@ -72,7 +72,5 @@ | ||
* The 'code' field will vary based on the specific error cause. | ||
* | ||
* @see {@link https://fqlx-beta--fauna-docs.netlify.app/fqlx/beta/reference/language/errors#runtime-errors} | ||
*/ | ||
export class QueryRuntimeError extends ServiceError { | ||
constructor(failure: QueryFailure, httpStatus: 400) { | ||
constructor(failure: QueryFailure, httpStatus?: number) { | ||
super(failure, httpStatus); | ||
@@ -91,7 +89,5 @@ if (Error.captureStackTrace) { | ||
* failing. | ||
* | ||
* @see {@link https://fqlx-beta--fauna-docs.netlify.app/fqlx/beta/reference/language/errors#runtime-errors} | ||
*/ | ||
export class QueryCheckError extends ServiceError { | ||
constructor(failure: QueryFailure, httpStatus: 400) { | ||
constructor(failure: QueryFailure, httpStatus?: number) { | ||
super(failure, httpStatus); | ||
@@ -108,7 +104,5 @@ if (Error.captureStackTrace) { | ||
* valid JSON or did not conform to the API specification | ||
* | ||
* @see {@link https://fqlx-beta--fauna-docs.netlify.app/fqlx/beta/reference/language/errors#runtime-errors} | ||
*/ | ||
export class InvalidRequestError extends ServiceError { | ||
constructor(failure: QueryFailure, httpStatus: 400) { | ||
constructor(failure: QueryFailure, httpStatus?: number) { | ||
super(failure, httpStatus); | ||
@@ -123,5 +117,27 @@ if (Error.captureStackTrace) { | ||
/** | ||
* A runtime error due to failing schema constraints. | ||
*/ | ||
export class ConstraintFailureError extends ServiceError { | ||
/** | ||
* The list of constraints that failed. | ||
*/ | ||
readonly constraint_failures: Array<ConstraintFailure>; | ||
constructor( | ||
failure: QueryFailure & { | ||
error: { constraint_failures: Array<ConstraintFailure> }; | ||
}, | ||
httpStatus?: number, | ||
) { | ||
super(failure, httpStatus); | ||
if (Error.captureStackTrace) { | ||
Error.captureStackTrace(this, QueryCheckError); | ||
} | ||
this.name = "ConstraintFailureError"; | ||
this.constraint_failures = failure.error.constraint_failures; | ||
} | ||
} | ||
/** | ||
* An error due to calling the FQL `abort` function. | ||
* | ||
* @see {@link https://fqlx-beta--fauna-docs.netlify.app/fqlx/beta/reference/language/errors#runtime-errors} | ||
*/ | ||
@@ -138,3 +154,3 @@ export class AbortError extends ServiceError { | ||
failure: QueryFailure & { error: { abort: QueryValue } }, | ||
httpStatus: 400 | ||
httpStatus?: number, | ||
) { | ||
@@ -155,3 +171,3 @@ super(failure, httpStatus); | ||
export class AuthenticationError extends ServiceError { | ||
constructor(failure: QueryFailure, httpStatus: 401) { | ||
constructor(failure: QueryFailure, httpStatus?: number) { | ||
super(failure, httpStatus); | ||
@@ -170,3 +186,3 @@ if (Error.captureStackTrace) { | ||
export class AuthorizationError extends ServiceError { | ||
constructor(failure: QueryFailure, httpStatus: 403) { | ||
constructor(failure: QueryFailure, httpStatus?: number) { | ||
super(failure, httpStatus); | ||
@@ -184,3 +200,3 @@ if (Error.captureStackTrace) { | ||
export class ContendedTransactionError extends ServiceError { | ||
constructor(failure: QueryFailure, httpStatus: 409) { | ||
constructor(failure: QueryFailure, httpStatus?: number) { | ||
super(failure, httpStatus); | ||
@@ -199,3 +215,3 @@ if (Error.captureStackTrace) { | ||
export class ThrottlingError extends ServiceError { | ||
constructor(failure: QueryFailure, httpStatus: 429) { | ||
constructor(failure: QueryFailure, httpStatus?: number) { | ||
super(failure, httpStatus); | ||
@@ -210,7 +226,12 @@ if (Error.captureStackTrace) { | ||
/** | ||
* A failure due to the timeout being exceeded, but the timeout | ||
* was set lower than the query's expected processing time. | ||
* This response is distinguished from a ServiceTimeoutException | ||
* in that a QueryTimeoutError shows Fauna behaving in an expected | ||
* manner. | ||
* A failure due to the query timeout being exceeded. | ||
* | ||
* This error can have one of two sources: | ||
* 1. Fauna is behaving expectedly, but the query timeout provided was too | ||
* aggressive and lower than the query's expected processing time. | ||
* 2. Fauna was not available to service the request before the timeout was | ||
* reached. | ||
* | ||
* In either case, consider increasing the `query_timeout_ms` configuration for | ||
* your client. | ||
*/ | ||
@@ -223,3 +244,3 @@ export class QueryTimeoutError extends ServiceError { | ||
constructor(failure: QueryFailure, httpStatus: 440) { | ||
constructor(failure: QueryFailure, httpStatus?: number) { | ||
super(failure, httpStatus); | ||
@@ -238,3 +259,3 @@ if (Error.captureStackTrace) { | ||
export class ServiceInternalError extends ServiceError { | ||
constructor(failure: QueryFailure, httpStatus: 500) { | ||
constructor(failure: QueryFailure, httpStatus?: number) { | ||
super(failure, httpStatus); | ||
@@ -249,16 +270,2 @@ if (Error.captureStackTrace) { | ||
/** | ||
* ServiceTimeoutError indicates Fauna was not available to servce | ||
* the request before the timeout was reached. | ||
*/ | ||
export class ServiceTimeoutError extends ServiceError { | ||
constructor(failure: QueryFailure, httpStatus: 503) { | ||
super(failure, httpStatus); | ||
if (Error.captureStackTrace) { | ||
Error.captureStackTrace(this, ServiceTimeoutError); | ||
} | ||
this.name = "ServiceTimeoutError"; | ||
} | ||
} | ||
/** | ||
* An error representing a failure internal to the client, itself. | ||
@@ -330,1 +337,56 @@ * This indicates Fauna was never called - the client failed internally | ||
} | ||
export const getServiceError = ( | ||
failure: QueryFailure, | ||
httpStatus?: number, | ||
): ServiceError => { | ||
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 !== undefined) { | ||
return new AbortError( | ||
failure as QueryFailure & { error: { abort: QueryValue } }, | ||
httpStatus, | ||
); | ||
} | ||
break; | ||
case "constraint_failure": | ||
if (failure.error.constraint_failures !== undefined) { | ||
return new ConstraintFailureError( | ||
failure as QueryFailure & { | ||
error: { constraint_failures: Array<ConstraintFailure> }; | ||
}, | ||
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 "throttle": | ||
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); | ||
}; |
/** following reference needed to include types for experimental fetch API in Node */ | ||
/// <reference lib="dom" /> | ||
import { NetworkError, ServiceError } from "../errors"; | ||
import { getServiceError, NetworkError } from "../errors"; | ||
import { QueryFailure } from "../wire-protocol"; | ||
import { | ||
@@ -97,3 +98,3 @@ HTTPClient, | ||
cause: error, | ||
} | ||
}, | ||
); | ||
@@ -103,4 +104,4 @@ }); | ||
if (!(status >= 200 && status < 400)) { | ||
const body = await response.json(); | ||
throw new ServiceError(body, status); | ||
const failure: QueryFailure = await response.json(); | ||
throw getServiceError(failure, status); | ||
} | ||
@@ -114,4 +115,11 @@ | ||
for await (const line of readLines(reader)) { | ||
yield line; | ||
try { | ||
for await (const line of readLines(reader)) { | ||
yield line; | ||
} | ||
} catch (error) { | ||
throw new NetworkError( | ||
"The network connection encountered a problem while streaming events.", | ||
{ cause: error }, | ||
); | ||
} | ||
@@ -118,0 +126,0 @@ } |
@@ -16,3 +16,4 @@ let http2: any; | ||
} from "./http-client"; | ||
import { ServiceError, NetworkError } from "../errors"; | ||
import { NetworkError, getServiceError } from "../errors"; | ||
import { QueryFailure } from "../wire-protocol"; | ||
@@ -63,3 +64,3 @@ // alias http2 types | ||
clientKey, | ||
new NodeHTTP2Client(httpClientOptions) | ||
new NodeHTTP2Client(httpClientOptions), | ||
); | ||
@@ -103,3 +104,3 @@ } | ||
cause: error, | ||
} | ||
}, | ||
); | ||
@@ -175,6 +176,6 @@ } | ||
const onResponse = ( | ||
http2ResponseHeaders: IncomingHttpHeaders & IncomingHttpStatusHeader | ||
http2ResponseHeaders: IncomingHttpHeaders & IncomingHttpStatusHeader, | ||
) => { | ||
const status = Number( | ||
http2ResponseHeaders[http2.constants.HTTP2_HEADER_STATUS] | ||
http2ResponseHeaders[http2.constants.HTTP2_HEADER_STATUS], | ||
); | ||
@@ -211,3 +212,8 @@ let responseData = ""; | ||
.on("error", (error: any) => { | ||
rejectPromise(error); | ||
rejectPromise( | ||
new NetworkError( | ||
"The network connection encountered a problem while streaming events.", | ||
{ cause: error }, | ||
), | ||
); | ||
}) | ||
@@ -225,3 +231,8 @@ .on("response", onResponse); | ||
} catch (error) { | ||
rejectPromise(error); | ||
rejectPromise( | ||
new NetworkError( | ||
"The network connection encountered a problem while streaming events.", | ||
{ cause: error }, | ||
), | ||
); | ||
} | ||
@@ -250,6 +261,6 @@ }); | ||
const onResponse = ( | ||
http2ResponseHeaders: IncomingHttpHeaders & IncomingHttpStatusHeader | ||
http2ResponseHeaders: IncomingHttpHeaders & IncomingHttpStatusHeader, | ||
) => { | ||
const status = Number( | ||
http2ResponseHeaders[http2.constants.HTTP2_HEADER_STATUS] | ||
http2ResponseHeaders[http2.constants.HTTP2_HEADER_STATUS], | ||
); | ||
@@ -267,6 +278,13 @@ if (!(status >= 200 && status < 400)) { | ||
// Once the response is finished, resolve the promise | ||
// TODO: The Client contains the information for how to parse an error | ||
// into the appropriate class, so lift this logic out of the HTTPClient. | ||
req.on("end", () => { | ||
rejectChunk(new ServiceError(JSON.parse(responseData), status)); | ||
try { | ||
const failure: QueryFailure = JSON.parse(responseData); | ||
rejectChunk(getServiceError(failure, status)); | ||
} catch (error) { | ||
rejectChunk( | ||
new NetworkError("Could not process query failure.", { | ||
cause: error, | ||
}), | ||
); | ||
} | ||
}); | ||
@@ -273,0 +291,0 @@ } else { |
@@ -14,2 +14,3 @@ export { Client, StreamClient } from "./client"; | ||
ClientClosedError, | ||
ConstraintFailureError, | ||
ContendedTransactionError, | ||
@@ -25,6 +26,5 @@ FaunaError, | ||
ServiceInternalError, | ||
ServiceTimeoutError, | ||
ThrottlingError, | ||
} from "./errors"; | ||
export { type Query, fql } from "./query-builder"; | ||
export { type Query, type QueryArgument, fql } from "./query-builder"; | ||
export { LONG_MAX, LONG_MIN, TaggedTypeFormat } from "./tagged-type"; | ||
@@ -31,0 +31,0 @@ export { |
@@ -10,2 +10,9 @@ import { TaggedTypeFormat } from "./tagged-type"; | ||
export type QueryArgument = | ||
| QueryValue | ||
| Query | ||
| Date | ||
| ArrayBuffer | ||
| Uint8Array; | ||
/** | ||
@@ -29,3 +36,3 @@ * Creates a new Query. Accepts template literal inputs. | ||
queryFragments: ReadonlyArray<string>, | ||
...queryArgs: (QueryValue | Query)[] | ||
...queryArgs: QueryArgument[] | ||
): Query { | ||
@@ -42,7 +49,7 @@ return new Query(queryFragments, ...queryArgs); | ||
readonly #queryFragments: ReadonlyArray<string>; | ||
readonly #queryArgs: (QueryValue | Query)[]; | ||
readonly #queryArgs: QueryArgument[]; | ||
constructor( | ||
queryFragments: ReadonlyArray<string>, | ||
...queryArgs: (QueryValue | Query)[] | ||
...queryArgs: QueryArgument[] | ||
) { | ||
@@ -49,0 +56,0 @@ if ( |
@@ -0,1 +1,3 @@ | ||
import base64 from "base64-js"; | ||
import { ClientError } from "./errors"; | ||
@@ -101,2 +103,4 @@ import { | ||
return new StreamToken(value["@stream"]); | ||
} else if (value["@bytes"]) { | ||
return base64toBuffer(value["@bytes"]); | ||
} | ||
@@ -109,2 +113,3 @@ | ||
type TaggedBytes = { "@bytes": string }; | ||
type TaggedDate = { "@date": string }; | ||
@@ -132,3 +137,3 @@ type TaggedDouble = { "@double": string }; | ||
throw new RangeError( | ||
"BigInt value exceeds max magnitude for a 64-bit Fauna long. Use a 'number' to represent doubles beyond that limit." | ||
"BigInt value exceeds max magnitude for a 64-bit Fauna long. Use a 'number' to represent doubles beyond that limit.", | ||
); | ||
@@ -204,6 +209,6 @@ } | ||
}), | ||
// es-lint-disable-next-line @typescript-eslint/no-unused-vars | ||
// eslint-disable-next-line @typescript-eslint/no-unused-vars | ||
set: (value: Page<QueryValue> | EmbeddedSet) => { | ||
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." | ||
"Page could not be encoded. Fauna does not accept encoded Set values, yet. Use Page.data and Page.after as arguments, instead.", | ||
); | ||
@@ -222,2 +227,5 @@ // TODO: uncomment to encode Pages once core starts accepting `@set` tagged values | ||
streamToken: (value: StreamToken): string => value.token, | ||
bytes: (value: ArrayBuffer | Uint8Array): TaggedBytes => ({ | ||
"@bytes": bufferToBase64(value), | ||
}), | ||
}; | ||
@@ -269,2 +277,8 @@ | ||
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 { | ||
@@ -276,1 +290,12 @@ return encodeMap["object"](input); | ||
}; | ||
function base64toBuffer(value: string): Uint8Array { | ||
return base64.toByteArray(value); | ||
} | ||
function bufferToBase64(value: ArrayBuffer | Uint8Array): string { | ||
const arr: Uint8Array = | ||
value instanceof Uint8Array ? value : new Uint8Array(value); | ||
return base64.fromByteArray(arr); | ||
} |
//THIS FILE IS AUTOGENERATED. DO NOT EDIT. SEE .husky/pre-commit | ||
/** The current package version. */ | ||
export const packageVersion = "1.4.0-beta.0"; | ||
export const packageVersion = "2.0.0-beta.0"; |
@@ -20,3 +20,3 @@ import { ClientError } from "../errors"; | ||
* | ||
* @see {@link https://fqlx-beta--fauna-docs.netlify.app/fqlx/beta/reference/builtin_functions/time/time} | ||
* @see {@link https://docs.fauna.com/fauna/current/reference/fql_reference/types#time} | ||
*/ | ||
@@ -108,3 +108,3 @@ export class TimeStub { | ||
* | ||
* @see {@link https://fqlx-beta--fauna-docs.netlify.app/fqlx/beta/reference/builtin_functions/date/date} | ||
* @see {@link https://docs.fauna.com/fauna/current/reference/fql_reference/types#date} | ||
*/ | ||
@@ -111,0 +111,0 @@ export class DateStub { |
@@ -22,2 +22,4 @@ import { QueryValueObject } from "../wire-protocol"; | ||
* ``` | ||
* | ||
* @see {@link https://docs.fauna.com/fauna/current/reference/fql_reference/types#special} | ||
*/ | ||
@@ -61,5 +63,8 @@ export class DocumentReference { | ||
* extend generic type arguments. | ||
* | ||
* @see {@link https://docs.fauna.com/fauna/current/reference/fql_reference/types#special} | ||
*/ | ||
export class Document extends DocumentReference { | ||
readonly ts: TimeStub; | ||
readonly ttl?: TimeStub; | ||
@@ -78,4 +83,4 @@ constructor(obj: { | ||
toObject(): { coll: Module; id: string; ts: TimeStub } { | ||
return { ...this } as { coll: Module; id: string; ts: TimeStub }; | ||
toObject(): { coll: Module; id: string; ts: TimeStub; ttl?: TimeStub } { | ||
return { ...this }; | ||
} | ||
@@ -102,2 +107,4 @@ } | ||
* ``` | ||
* | ||
* @see {@link https://docs.fauna.com/fauna/current/reference/fql_reference/types#special} | ||
*/ | ||
@@ -151,5 +158,7 @@ export class NamedDocumentReference { | ||
* ``` | ||
* | ||
* @see {@link https://docs.fauna.com/fauna/current/reference/fql_reference/types#special} | ||
*/ | ||
export class NamedDocument< | ||
T extends QueryValueObject = Record<string, never> | ||
T extends QueryValueObject = Record<string, never>, | ||
> extends NamedDocumentReference { | ||
@@ -194,2 +203,4 @@ readonly ts: TimeStub; | ||
* ``` | ||
* | ||
* @see {@link https://docs.fauna.com/fauna/current/reference/fql_reference/types#module} | ||
*/ | ||
@@ -229,2 +240,4 @@ export class Module { | ||
* ``` | ||
* | ||
* @see {@link https://docs.fauna.com/fauna/current/reference/fql_reference/types#nulldoc} | ||
*/ | ||
@@ -231,0 +244,0 @@ export class NullDocument { |
@@ -7,3 +7,3 @@ import { Client } from "../client"; | ||
* A materialized view of a Set. | ||
* @see {@link https://fqlx-beta--fauna-docs.netlify.app/fqlx/beta/reference/language/types#set} | ||
* @see {@link https://docs.fauna.com/fauna/current/reference/fql_reference/types#set} | ||
*/ | ||
@@ -30,3 +30,3 @@ export class Page<T extends QueryValue> { | ||
* issues such as self-reference and infinite recursion | ||
* @see {@link https://fqlx-beta--fauna-docs.netlify.app/fqlx/beta/reference/language/types#set} | ||
* @see {@link https://docs.fauna.com/fauna/current/reference/fql_reference/types#set} | ||
*/ | ||
@@ -33,0 +33,0 @@ export class EmbeddedSet { |
@@ -56,3 +56,3 @@ // eslint-disable-next-line @typescript-eslint/no-unused-vars | ||
/** | ||
* Controls what Javascript type to deserialize {@link https://fqlx-beta--fauna-docs.netlify.app/fqlx/beta/reference/language/types#long | Fauna longs} to. | ||
* Controls what Javascript type to deserialize {@link https://docs.fauna.com/fauna/current/reference/fql_reference/types#long | Fauna longs} to. | ||
* Use 'number' to deserialize longs to number. Use 'bigint' to deserialize to bigint. Defaults to 'number'. | ||
@@ -322,3 +322,4 @@ * Note, for extremely large maginitude numbers Javascript's number will lose precision; as Javascript's | ||
| EmbeddedSet | ||
| StreamToken; | ||
| StreamToken | ||
| Uint8Array; | ||
@@ -325,0 +326,0 @@ export type StreamRequest = { |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
637396
7469
542
1
+ Addedbase64-js@^1.5.1
+ Addedbase64-js@1.5.1(transitive)