@hpcc-js/wasm-duckdb 1.6.0 → 1.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -8,3 +8,4 @@ return true;`)}function Fd(i){return typeof i!="bigint"?ie(i):`${ie(i)}n`}functi
8
8
  ${this.toArray().join(`,
9
9
  `)}
10
10
  ]`}concat(...t){let e=this.schema,r=this.data.concat(t.flatMap(({data:n})=>n));return new i(e,r.map(n=>new rt(e,n)))}slice(t,e){let r=this.schema;[t,e]=Gr({length:this.numRows},t,e);let n=yo(this.data,this._offsets,t,e);return new i(r,n.map(o=>new rt(r,o)))}getChild(t){return this.getChildAt(this.schema.fields.findIndex(e=>e.name===t))}getChildAt(t){if(t>-1&&t<this.schema.fields.length){let e=this.data.map(r=>r.children[t]);if(e.length===0){let{type:r}=this.schema.fields[t],n=H({type:r,length:0,nullCount:0});e.push(n._changeLengthAndBackfillNullBitmap(this.numRows))}return new _(e)}return null}setChild(t,e){var r;return this.setChildAt((r=this.schema.fields)===null||r===void 0?void 0:r.findIndex(n=>n.name===t),e)}setChildAt(t,e){let r=this.schema,n=[...this.batches];if(t>-1&&t<this.numCols){e||(e=new _([H({type:new Ot,length:this.numRows})]));let o=r.fields.slice(),s=o[t].clone({type:e.type}),a=this.schema.fields.map((u,B)=>this.getChildAt(B));[o[t],a[t]]=[s,e],[r,n]=Jo(r,a)}return new i(r,n)}select(t){let e=this.schema.fields.reduce((r,n,o)=>r.set(n.name,o),new Map);return this.selectAt(t.map(r=>e.get(r)).filter(r=>r>-1))}selectAt(t){let e=this.schema.selectAt(t),r=this.batches.map(n=>n.selectAt(t));return new i(e,r)}assign(t){let e=this.schema.fields,[r,n]=t.schema.fields.reduce((a,u,B)=>{let[d,l]=a,m=e.findIndex(F=>F.name===u.name);return~m?l[m]=B:d.push(B),a},[[],[]]),o=this.schema.assign(t.schema),s=[...e.map((a,u)=>[u,n[u]]).map(([a,u])=>u===void 0?this.getChildAt(a):t.getChildAt(u)),...r.map(a=>t.getChildAt(a))].filter(Boolean);return new i(...Jo(o,s))}};Uu=Symbol.toStringTag;Mt[Uu]=(i=>(i.schema=null,i.batches=[],i._offsets=new Uint32Array([0]),i._nullCount=-1,i[Symbol.isConcatSpreadable]=!0,i.isValid=ki(pr),i.get=ki(st.getVisitFn(c.Struct)),i.set=ho(Ft.getVisitFn(c.Struct)),i.indexOf=Lo(vi.getVisitFn(c.Struct)),"Table"))(Mt.prototype);var ku,rt=class i{constructor(...t){switch(t.length){case 2:{if([this.schema]=t,!(this.schema instanceof P))throw new TypeError("RecordBatch constructor expects a [Schema, Data] pair.");if([,this.data=H({nullCount:0,type:new q(this.schema.fields),children:this.schema.fields.map(e=>H({type:e.type,nullCount:0}))})]=t,!(this.data instanceof J))throw new TypeError("RecordBatch constructor expects a [Schema, Data] pair.");[this.schema,this.data]=Ku(this.schema,this.data.children);break}case 1:{let[e]=t,{fields:r,children:n,length:o}=Object.keys(e).reduce((u,B,d)=>(u.children[d]=e[B],u.length=Math.max(u.length,e[B].length),u.fields[d]=W.new({name:B,type:e[B].type,nullable:!0}),u),{length:0,fields:new Array,children:new Array}),s=new P(r),a=H({type:new q(r),length:o,children:n,nullCount:0});[this.schema,this.data]=Ku(s,a.children,o);break}default:throw new TypeError("RecordBatch constructor expects an Object mapping names to child Data, or a [Schema, Data] pair.")}}get dictionaries(){return this._dictionaries||(this._dictionaries=Qu(this.schema.fields,this.data.children))}get numCols(){return this.schema.fields.length}get numRows(){return this.data.length}get nullCount(){return this.data.nullCount}isValid(t){return this.data.getValid(t)}get(t){return st.visit(this.data,t)}at(t){return this.get(Ii(t,this.numRows))}set(t,e){return Ft.visit(this.data,t,e)}indexOf(t,e){return vi.visit(this.data,t,e)}[Symbol.iterator](){return Qi.visit(new _([this.data]))}toArray(){return[...this]}concat(...t){return new Mt(this.schema,[this,...t])}slice(t,e){let[r]=new _([this.data]).slice(t,e).data;return new i(this.schema,r)}getChild(t){var e;return this.getChildAt((e=this.schema.fields)===null||e===void 0?void 0:e.findIndex(r=>r.name===t))}getChildAt(t){return t>-1&&t<this.schema.fields.length?new _([this.data.children[t]]):null}setChild(t,e){var r;return this.setChildAt((r=this.schema.fields)===null||r===void 0?void 0:r.findIndex(n=>n.name===t),e)}setChildAt(t,e){let r=this.schema,n=this.data;if(t>-1&&t<this.numCols){e||(e=new _([H({type:new Ot,length:this.numRows})]));let o=r.fields.slice(),s=n.children.slice(),a=o[t].clone({type:e.type});[o[t],s[t]]=[a,e.data[0]],r=new P(o,new Map(this.schema.metadata)),n=H({type:new q(o),children:s})}return new i(r,n)}select(t){let e=this.schema.select(t),r=new q(e.fields),n=[];for(let o of t){let s=this.schema.fields.findIndex(a=>a.name===o);~s&&(n[s]=this.data.children[s])}return new i(e,H({type:r,length:this.numRows,children:n}))}selectAt(t){let e=this.schema.selectAt(t),r=t.map(o=>this.data.children[o]).filter(Boolean),n=H({type:new q(e.fields),length:this.numRows,children:r});return new i(e,n)}};ku=Symbol.toStringTag;rt[ku]=(i=>(i._nullCount=-1,i[Symbol.isConcatSpreadable]=!0,"RecordBatch"))(rt.prototype);function Ku(i,t,e=t.reduce((r,n)=>Math.max(r,n.length),0)){var r;let n=[...i.fields],o=[...t],s=(e+63&-64)>>3;for(let[a,u]of i.fields.entries()){let B=t[a];(!B||B.length!==e)&&(n[a]=u.clone({nullable:!0}),o[a]=(r=B?._changeLengthAndBackfillNullBitmap(e))!==null&&r!==void 0?r:H({type:u.type,length:e,nullCount:e,nullBitmap:new Uint8Array(s)}))}return[i.assign(n),H({type:new q(n),length:e,children:o})]}function Qu(i,t,e=new Map){var r,n;if(((r=i?.length)!==null&&r!==void 0?r:0)>0&&i?.length===t?.length)for(let o=-1,s=i.length;++o<s;){let{type:a}=i[o],u=t[o];for(let B of[u,...((n=u?.dictionary)===null||n===void 0?void 0:n.data)||[]])Qu(a.children,B?.children,e);if(y.isDictionary(a)){let{id:B}=a;if(!e.has(B))u?.dictionary&&e.set(B,u.dictionary);else if(e.get(B)!==u.dictionary)throw new Error("Cannot create Schema containing two different dictionaries with the same Id")}}return e}var Gi=class extends rt{constructor(t){let e=t.fields.map(n=>H({type:n.type})),r=H({type:new q(t.fields),nullCount:0,children:e});super(t,r)}};var Be=class i{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsMessage(t,e){return(e||new i).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsMessage(t,e){return t.setPosition(t.position()+4),(e||new i).__init(t.readInt32(t.position())+t.position(),t)}version(){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.readInt16(this.bb_pos+t):j.V1}headerType(){let t=this.bb.__offset(this.bb_pos,6);return t?this.bb.readUint8(this.bb_pos+t):p.NONE}header(t){let e=this.bb.__offset(this.bb_pos,8);return e?this.bb.__union(t,this.bb_pos+e):null}bodyLength(){let t=this.bb.__offset(this.bb_pos,10);return t?this.bb.readInt64(this.bb_pos+t):BigInt("0")}customMetadata(t,e){let r=this.bb.__offset(this.bb_pos,12);return r?(e||new dt).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+t*4),this.bb):null}customMetadataLength(){let t=this.bb.__offset(this.bb_pos,12);return t?this.bb.__vector_len(this.bb_pos+t):0}static startMessage(t){t.startObject(5)}static addVersion(t,e){t.addFieldInt16(0,e,j.V1)}static addHeaderType(t,e){t.addFieldInt8(1,e,p.NONE)}static addHeader(t,e){t.addFieldOffset(2,e,0)}static addBodyLength(t,e){t.addFieldInt64(3,e,BigInt("0"))}static addCustomMetadata(t,e){t.addFieldOffset(4,e,0)}static createCustomMetadataVector(t,e){t.startVector(4,e.length,4);for(let r=e.length-1;r>=0;r--)t.addOffset(e[r]);return t.endVector()}static startCustomMetadataVector(t,e){t.startVector(4,e,4)}static endMessage(t){return t.endObject()}static finishMessageBuffer(t,e){t.finish(e)}static finishSizePrefixedMessageBuffer(t,e){t.finish(e,void 0,!0)}static createMessage(t,e,r,n,o,s){return i.startMessage(t),i.addVersion(t,e),i.addHeaderType(t,r),i.addHeader(t,n),i.addBodyLength(t,o),i.addCustomMetadata(t,s),i.endMessage(t)}};var Vs=class extends C{visit(t,e){return t==null||e==null?void 0:super.visit(t,e)}visitNull(t,e){return Xr.startNull(e),Xr.endNull(e)}visitInt(t,e){return te.startInt(e),te.addBitWidth(e,t.bitWidth),te.addIsSigned(e,t.isSigned),te.endInt(e)}visitFloat(t,e){return ni.startFloatingPoint(e),ni.addPrecision(e,t.precision),ni.endFloatingPoint(e)}visitBinary(t,e){return Rr.startBinary(e),Rr.endBinary(e)}visitLargeBinary(t,e){return vr.startLargeBinary(e),vr.endLargeBinary(e)}visitBool(t,e){return Or.startBool(e),Or.endBool(e)}visitUtf8(t,e){return mr.startUtf8(e),mr.endUtf8(e)}visitLargeUtf8(t,e){return Mr.startLargeUtf8(e),Mr.endLargeUtf8(e)}visitDecimal(t,e){return Ie.startDecimal(e),Ie.addScale(e,t.scale),Ie.addPrecision(e,t.precision),Ie.addBitWidth(e,t.bitWidth),Ie.endDecimal(e)}visitDate(t,e){return ti.startDate(e),ti.addUnit(e,t.unit),ti.endDate(e)}visitTime(t,e){return De.startTime(e),De.addUnit(e,t.unit),De.addBitWidth(e,t.bitWidth),De.endTime(e)}visitTimestamp(t,e){let r=t.timezone&&e.createString(t.timezone)||void 0;return me.startTimestamp(e),me.addUnit(e,t.unit),r!==void 0&&me.addTimezone(e,r),me.endTimestamp(e)}visitInterval(t,e){return oi.startInterval(e),oi.addUnit(e,t.unit),oi.endInterval(e)}visitDuration(t,e){return ei.startDuration(e),ei.addUnit(e,t.unit),ei.endDuration(e)}visitList(t,e){return Er.startList(e),Er.endList(e)}visitStruct(t,e){return Dr.startStruct_(e),Dr.endStruct_(e)}visitUnion(t,e){ee.startTypeIdsVector(e,t.typeIds.length);let r=ee.createTypeIdsVector(e,t.typeIds);return ee.startUnion(e),ee.addMode(e,t.mode),ee.addTypeIds(e,r),ee.endUnion(e)}visitDictionary(t,e){let r=this.visit(t.indices,e);return Ce.startDictionaryEncoding(e),Ce.addId(e,BigInt(t.id)),Ce.addIsOrdered(e,t.isOrdered),r!==void 0&&Ce.addIndexType(e,r),Ce.endDictionaryEncoding(e)}visitFixedSizeBinary(t,e){return ii.startFixedSizeBinary(e),ii.addByteWidth(e,t.byteWidth),ii.endFixedSizeBinary(e)}visitFixedSizeList(t,e){return ri.startFixedSizeList(e),ri.addListSize(e,t.listSize),ri.endFixedSizeList(e)}visitMap(t,e){return si.startMap(e),si.addKeysSorted(e,t.keysSorted),si.endMap(e)}},jo=new Vs;function Au(i,t=new Map){return new P(bd(i,t),zo(i.metadata),t)}function qs(i){return new Ct(i.count,ec(i.columns),ic(i.columns))}function tc(i){return new Yt(qs(i.data),i.id,i.isDelta)}function bd(i,t){return(i.fields||[]).filter(Boolean).map(e=>W.fromJSON(e,t))}function Vu(i,t){return(i.children||[]).filter(Boolean).map(e=>W.fromJSON(e,t))}function ec(i){return(i||[]).reduce((t,e)=>[...t,new Kt(e.count,Yd(e.VALIDITY)),...ec(e.children)],[])}function ic(i,t=[]){for(let e=-1,r=(i||[]).length;++e<r;){let n=i[e];n.VALIDITY&&t.push(new bt(t.length,n.VALIDITY.length)),n.TYPE_ID&&t.push(new bt(t.length,n.TYPE_ID.length)),n.OFFSET&&t.push(new bt(t.length,n.OFFSET.length)),n.DATA&&t.push(new bt(t.length,n.DATA.length)),t=ic(n.children,t)}return t}function Yd(i){return(i||[]).reduce((t,e)=>t+ +(e===0),0)}function rc(i,t){let e,r,n,o,s,a;return!t||!(o=i.dictionary)?(s=$u(i,Vu(i,t)),n=new W(i.name,s,i.nullable,zo(i.metadata))):t.has(e=o.id)?(r=(r=o.indexType)?qu(r):new we,a=new _t(t.get(e),r,e,o.isOrdered),n=new W(i.name,a,i.nullable,zo(i.metadata))):(r=(r=o.indexType)?qu(r):new we,t.set(e,s=$u(i,Vu(i,t))),a=new _t(s,r,e,o.isOrdered),n=new W(i.name,a,i.nullable,zo(i.metadata))),n||null}function zo(i=[]){return new Map(i.map(({key:t,value:e})=>[t,e]))}function qu(i){return new lt(i.isSigned,i.bitWidth)}function $u(i,t){let e=i.type.name;switch(e){case"NONE":return new Ot;case"null":return new Ot;case"binary":return new He;case"largebinary":return new be;case"utf8":return new Ye;case"largeutf8":return new Ge;case"bool":return new xe;case"list":return new ne((t||[])[0]);case"struct":return new q(t||[]);case"struct_":return new q(t||[])}switch(e){case"int":{let r=i.type;return new lt(r.isSigned,r.bitWidth)}case"floatingpoint":{let r=i.type;return new zt(U[r.precision])}case"decimal":{let r=i.type;return new We(r.scale,r.precision,r.bitWidth)}case"date":{let r=i.type;return new pe(it[r.unit])}case"time":{let r=i.type;return new Ne(h[r.unit],r.bitWidth)}case"timestamp":{let r=i.type;return new _e(h[r.unit],r.timezone)}case"interval":{let r=i.type;return new Se(Bt[r.unit])}case"duration":{let r=i.type;return new Ze(h[r.unit])}case"union":{let r=i.type,[n,...o]=(r.mode+"").toLowerCase(),s=n.toUpperCase()+o.join("");return new oe(K[s],r.typeIds||[],t||[])}case"fixedsizebinary":{let r=i.type;return new ge(r.byteWidth)}case"fixedsizelist":{let r=i.type;return new se(r.listSize,(t||[])[0])}case"map":{let r=i.type;return new ae((t||[])[0],r.keysSorted)}}throw new Error(`Unrecognized type: "${e}"`)}var Gd=Ci,xd=pt,Gt=class i{static fromJSON(t,e){let r=new i(0,j.V5,e);return r._createHeader=Wd(t,e),r}static decode(t){t=new xd(M(t));let e=Be.getRootAsMessage(t),r=e.bodyLength(),n=e.version(),o=e.headerType(),s=new i(r,n,o);return s._createHeader=pd(e,o),s}static encode(t){let e=new Gd,r=-1;return t.isSchema()?r=P.encode(e,t.header()):t.isRecordBatch()?r=Ct.encode(e,t.header()):t.isDictionaryBatch()&&(r=Yt.encode(e,t.header())),Be.startMessage(e),Be.addVersion(e,j.V5),Be.addHeader(e,r),Be.addHeaderType(e,t.headerType),Be.addBodyLength(e,BigInt(t.bodyLength)),Be.finishMessageBuffer(e,Be.endMessage(e)),e.asUint8Array()}static from(t,e=0){if(t instanceof P)return new i(0,j.V5,p.Schema,t);if(t instanceof Ct)return new i(e,j.V5,p.RecordBatch,t);if(t instanceof Yt)return new i(e,j.V5,p.DictionaryBatch,t);throw new Error(`Unrecognized Message header: ${t}`)}get type(){return this.headerType}get version(){return this._version}get headerType(){return this._headerType}get bodyLength(){return this._bodyLength}header(){return this._createHeader()}isSchema(){return this.headerType===p.Schema}isRecordBatch(){return this.headerType===p.RecordBatch}isDictionaryBatch(){return this.headerType===p.DictionaryBatch}constructor(t,e,r,n){this._version=e,this._headerType=r,this.body=new Uint8Array(0),n&&(this._createHeader=()=>n),this._bodyLength=Z(t)}},Ct=class{get nodes(){return this._nodes}get length(){return this._length}get buffers(){return this._buffers}constructor(t,e,r){this._nodes=e,this._buffers=r,this._length=Z(t)}},Yt=class{get id(){return this._id}get data(){return this._data}get isDelta(){return this._isDelta}get length(){return this.data.length}get nodes(){return this.data.nodes}get buffers(){return this.data.buffers}constructor(t,e,r=!1){this._data=t,this._isDelta=r,this._id=Z(e)}},bt=class{constructor(t,e){this.offset=Z(t),this.length=Z(e)}},Kt=class{constructor(t,e){this.length=Z(t),this.nullCount=Z(e)}};function Wd(i,t){return()=>{switch(t){case p.Schema:return P.fromJSON(i);case p.RecordBatch:return Ct.fromJSON(i);case p.DictionaryBatch:return Yt.fromJSON(i)}throw new Error(`Unrecognized Message type: { name: ${p[t]}, type: ${t} }`)}}function pd(i,t){return()=>{switch(t){case p.Schema:return P.decode(i.header(new mt),new Map,i.version());case p.RecordBatch:return Ct.decode(i.header(new Nt),i.version());case p.DictionaryBatch:return Yt.decode(i.header(new Xe),i.version())}throw new Error(`Unrecognized Message type: { name: ${p[t]}, type: ${t} }`)}}W.encode=Ud;W.decode=zd;W.fromJSON=rc;P.encode=Pd;P.decode=Nd;P.fromJSON=Au;Ct.encode=Kd;Ct.decode=_d;Ct.fromJSON=qs;Yt.encode=kd;Yt.decode=Sd;Yt.fromJSON=tc;Kt.encode=Qd;Kt.decode=gd;bt.encode=Vd;bt.decode=Zd;function Nd(i,t=new Map,e=j.V5){let r=jd(i,t);return new P(r,Po(i),t,e)}function _d(i,t=j.V5){if(i.compression()!==null)throw new Error("Record batch compression not implemented");return new Ct(i.length(),Td(i),Jd(i,t))}function Sd(i,t=j.V5){return new Yt(Ct.decode(i.data(),t),i.id(),i.isDelta())}function Zd(i){return new bt(i.offset(),i.length())}function gd(i){return new Kt(i.length(),i.nullCount())}function Td(i){let t=[];for(let e,r=-1,n=-1,o=i.nodesLength();++r<o;)(e=i.nodes(r))&&(t[++n]=Kt.decode(e));return t}function Jd(i,t){let e=[];for(let r,n=-1,o=-1,s=i.buffersLength();++n<s;)(r=i.buffers(n))&&(t<j.V4&&(r.bb_pos+=8*(n+1)),e[++o]=bt.decode(r));return e}function jd(i,t){let e=[];for(let r,n=-1,o=-1,s=i.fieldsLength();++n<s;)(r=i.fields(n))&&(e[++o]=W.decode(r,t));return e}function nc(i,t){let e=[];for(let r,n=-1,o=-1,s=i.childrenLength();++n<s;)(r=i.children(n))&&(e[++o]=W.decode(r,t));return e}function zd(i,t){let e,r,n,o,s,a;return!t||!(a=i.dictionary())?(n=sc(i,nc(i,t)),r=new W(i.name(),n,i.nullable(),Po(i))):t.has(e=Z(a.id()))?(o=(o=a.indexType())?oc(o):new we,s=new _t(t.get(e),o,e,a.isOrdered()),r=new W(i.name(),s,i.nullable(),Po(i))):(o=(o=a.indexType())?oc(o):new we,t.set(e,n=sc(i,nc(i,t))),s=new _t(n,o,e,a.isOrdered()),r=new W(i.name(),s,i.nullable(),Po(i))),r||null}function Po(i){let t=new Map;if(i)for(let e,r,n=-1,o=Math.trunc(i.customMetadataLength());++n<o;)(e=i.customMetadata(n))&&(r=e.key())!=null&&t.set(r,e.value());return t}function oc(i){return new lt(i.isSigned(),i.bitWidth())}function sc(i,t){let e=i.typeType();switch(e){case k.NONE:return new Ot;case k.Null:return new Ot;case k.Binary:return new He;case k.LargeBinary:return new be;case k.Utf8:return new Ye;case k.LargeUtf8:return new Ge;case k.Bool:return new xe;case k.List:return new ne((t||[])[0]);case k.Struct_:return new q(t||[])}switch(e){case k.Int:{let r=i.type(new te);return new lt(r.isSigned(),r.bitWidth())}case k.FloatingPoint:{let r=i.type(new ni);return new zt(r.precision())}case k.Decimal:{let r=i.type(new Ie);return new We(r.scale(),r.precision(),r.bitWidth())}case k.Date:{let r=i.type(new ti);return new pe(r.unit())}case k.Time:{let r=i.type(new De);return new Ne(r.unit(),r.bitWidth())}case k.Timestamp:{let r=i.type(new me);return new _e(r.unit(),r.timezone())}case k.Interval:{let r=i.type(new oi);return new Se(r.unit())}case k.Duration:{let r=i.type(new ei);return new Ze(r.unit())}case k.Union:{let r=i.type(new ee);return new oe(r.mode(),r.typeIdsArray()||[],t||[])}case k.FixedSizeBinary:{let r=i.type(new ii);return new ge(r.byteWidth())}case k.FixedSizeList:{let r=i.type(new ri);return new se(r.listSize(),(t||[])[0])}case k.Map:{let r=i.type(new si);return new ae((t||[])[0],r.keysSorted())}}throw new Error(`Unrecognized type: "${k[e]}" (${e})`)}function Pd(i,t){let e=t.fields.map(o=>W.encode(i,o));mt.startFieldsVector(i,e.length);let r=mt.createFieldsVector(i,e),n=t.metadata&&t.metadata.size>0?mt.createCustomMetadataVector(i,[...t.metadata].map(([o,s])=>{let a=i.createString(`${o}`),u=i.createString(`${s}`);return dt.startKeyValue(i),dt.addKey(i,a),dt.addValue(i,u),dt.endKeyValue(i)})):-1;return mt.startSchema(i),mt.addFields(i,r),mt.addEndianness(i,qd?Ae.Little:Ae.Big),n!==-1&&mt.addCustomMetadata(i,n),mt.endSchema(i)}function Ud(i,t){let e=-1,r=-1,n=-1,o=t.type,s=t.typeId;y.isDictionary(o)?(s=o.dictionary.typeId,n=jo.visit(o,i),r=jo.visit(o.dictionary,i)):r=jo.visit(o,i);let a=(o.children||[]).map(d=>W.encode(i,d)),u=wt.createChildrenVector(i,a),B=t.metadata&&t.metadata.size>0?wt.createCustomMetadataVector(i,[...t.metadata].map(([d,l])=>{let m=i.createString(`${d}`),F=i.createString(`${l}`);return dt.startKeyValue(i),dt.addKey(i,m),dt.addValue(i,F),dt.endKeyValue(i)})):-1;return t.name&&(e=i.createString(t.name)),wt.startField(i),wt.addType(i,r),wt.addTypeType(i,s),wt.addChildren(i,u),wt.addNullable(i,!!t.nullable),e!==-1&&wt.addName(i,e),n!==-1&&wt.addDictionary(i,n),B!==-1&&wt.addCustomMetadata(i,B),wt.endField(i)}function Kd(i,t){let e=t.nodes||[],r=t.buffers||[];Nt.startNodesVector(i,e.length);for(let s of e.slice().reverse())Kt.encode(i,s);let n=i.endVector();Nt.startBuffersVector(i,r.length);for(let s of r.slice().reverse())bt.encode(i,s);let o=i.endVector();return Nt.startRecordBatch(i),Nt.addLength(i,BigInt(t.length)),Nt.addNodes(i,n),Nt.addBuffers(i,o),Nt.endRecordBatch(i)}function kd(i,t){let e=Ct.encode(i,t.data);return Xe.startDictionaryBatch(i),Xe.addId(i,BigInt(t.id)),Xe.addIsDelta(i,t.isDelta),Xe.addData(i,e),Xe.endDictionaryBatch(i)}function Qd(i,t){return Zi.createFieldNode(i,BigInt(t.length),BigInt(t.nullCount))}function Vd(i,t){return Si.createBuffer(i,BigInt(t.offset),BigInt(t.length))}var qd=(()=>{let i=new ArrayBuffer(2);return new DataView(i).setInt16(0,256,!0),new Int16Array(i)[0]===256})();var As=i=>`Expected ${p[i]} Message in stream, but was null or length 0.`,ta=i=>`Header pointer of flatbuffer-encoded ${p[i]} Message is null or length 0.`,ac=(i,t)=>`Expected to read ${i} metadata bytes, but only read ${t}.`,uc=(i,t)=>`Expected to read ${i} bytes for message body, but only read ${t}.`,rr=class{constructor(t){this.source=t instanceof ve?t:new ve(t)}[Symbol.iterator](){return this}next(){let t;return(t=this.readMetadataLength()).done?$:t.value===-1&&(t=this.readMetadataLength()).done?$:(t=this.readMetadata(t.value)).done?$:t}throw(t){return this.source.throw(t)}return(t){return this.source.return(t)}readMessage(t){let e;if((e=this.next()).done)return null;if(t!=null&&e.value.headerType!==t)throw new Error(As(t));return e.value}readMessageBody(t){if(t<=0)return new Uint8Array(0);let e=M(this.source.read(t));if(e.byteLength<t)throw new Error(uc(t,e.byteLength));return e.byteOffset%8===0&&e.byteOffset+e.byteLength<=e.buffer.byteLength?e:e.slice()}readSchema(t=!1){let e=p.Schema,r=this.readMessage(e),n=r?.header();if(t&&!n)throw new Error(ta(e));return n}readMetadataLength(){let t=this.source.read(Uo),e=t&&new pt(t),r=e?.readInt32(0)||0;return{done:r===0,value:r}}readMetadata(t){let e=this.source.read(t);if(!e)return $;if(e.byteLength<t)throw new Error(ac(t,e.byteLength));return{done:!1,value:Gt.decode(e)}}},dn=class{constructor(t,e){this.source=t instanceof Pt?t:Mn(t)?new di(t,e):new Pt(t)}[Symbol.asyncIterator](){return this}next(){return f(this,void 0,void 0,function*(){let t;return(t=yield this.readMetadataLength()).done?$:t.value===-1&&(t=yield this.readMetadataLength()).done?$:(t=yield this.readMetadata(t.value)).done?$:t})}throw(t){return f(this,void 0,void 0,function*(){return yield this.source.throw(t)})}return(t){return f(this,void 0,void 0,function*(){return yield this.source.return(t)})}readMessage(t){return f(this,void 0,void 0,function*(){let e;if((e=yield this.next()).done)return null;if(t!=null&&e.value.headerType!==t)throw new Error(As(t));return e.value})}readMessageBody(t){return f(this,void 0,void 0,function*(){if(t<=0)return new Uint8Array(0);let e=M(yield this.source.read(t));if(e.byteLength<t)throw new Error(uc(t,e.byteLength));return e.byteOffset%8===0&&e.byteOffset+e.byteLength<=e.buffer.byteLength?e:e.slice()})}readSchema(){return f(this,arguments,void 0,function*(t=!1){let e=p.Schema,r=yield this.readMessage(e),n=r?.header();if(t&&!n)throw new Error(ta(e));return n})}readMetadataLength(){return f(this,void 0,void 0,function*(){let t=yield this.source.read(Uo),e=t&&new pt(t),r=e?.readInt32(0)||0;return{done:r===0,value:r}})}readMetadata(t){return f(this,void 0,void 0,function*(){let e=yield this.source.read(t);if(!e)return $;if(e.byteLength<t)throw new Error(ac(t,e.byteLength));return{done:!1,value:Gt.decode(e)}})}},ln=class extends rr{constructor(t){super(new Uint8Array(0)),this._schema=!1,this._body=[],this._batchIndex=0,this._dictionaryIndex=0,this._json=t instanceof Nr?t:new Nr(t)}next(){let{_json:t}=this;if(!this._schema)return this._schema=!0,{done:!1,value:Gt.fromJSON(t.schema,p.Schema)};if(this._dictionaryIndex<t.dictionaries.length){let e=t.dictionaries[this._dictionaryIndex++];return this._body=e.data.columns,{done:!1,value:Gt.fromJSON(e,p.DictionaryBatch)}}if(this._batchIndex<t.batches.length){let e=t.batches[this._batchIndex++];return this._body=e.columns,{done:!1,value:Gt.fromJSON(e,p.RecordBatch)}}return this._body=[],$}readMessageBody(t){return e(this._body);function e(r){return(r||[]).reduce((n,o)=>[...n,...o.VALIDITY&&[o.VALIDITY]||[],...o.TYPE_ID&&[o.TYPE_ID]||[],...o.OFFSET&&[o.OFFSET]||[],...o.DATA&&[o.DATA]||[],...e(o.children)],[])}}readMessage(t){let e;if((e=this.next()).done)return null;if(t!=null&&e.value.headerType!==t)throw new Error(As(t));return e.value}readSchema(){let t=p.Schema,e=this.readMessage(t),r=e?.header();if(!e||!r)throw new Error(ta(t));return r}},Uo=4,$s="ARROW1",nr=new Uint8Array($s.length);for(let i=0;i<$s.length;i+=1)nr[i]=$s.codePointAt(i);function Ko(i,t=0){for(let e=-1,r=nr.length;++e<r;)if(nr[e]!==i[t+e])return!1;return!0}var or=nr.length,ea=or+Uo,cc=or*2+Uo;var It=class i extends Ei{constructor(t){super(),this._impl=t}get closed(){return this._impl.closed}get schema(){return this._impl.schema}get autoDestroy(){return this._impl.autoDestroy}get dictionaries(){return this._impl.dictionaries}get numDictionaries(){return this._impl.numDictionaries}get numRecordBatches(){return this._impl.numRecordBatches}get footer(){return this._impl.isFile()?this._impl.footer:null}isSync(){return this._impl.isSync()}isAsync(){return this._impl.isAsync()}isFile(){return this._impl.isFile()}isStream(){return this._impl.isStream()}next(){return this._impl.next()}throw(t){return this._impl.throw(t)}return(t){return this._impl.return(t)}cancel(){return this._impl.cancel()}reset(t){return this._impl.reset(t),this._DOMStream=void 0,this._nodeStream=void 0,this}open(t){let e=this._impl.open(t);return Vt(e)?e.then(()=>this):this}readRecordBatch(t){return this._impl.isFile()?this._impl.readRecordBatch(t):null}[Symbol.iterator](){return this._impl[Symbol.iterator]()}[Symbol.asyncIterator](){return this._impl[Symbol.asyncIterator]()}toDOMStream(){return Lt.toDOMStream(this.isSync()?{[Symbol.iterator]:()=>this}:{[Symbol.asyncIterator]:()=>this})}toNodeStream(){return Lt.toNodeStream(this.isSync()?{[Symbol.iterator]:()=>this}:{[Symbol.asyncIterator]:()=>this},{objectMode:!0})}static throughNode(t){throw new Error('"throughNode" not available in this environment')}static throughDOM(t,e){throw new Error('"throughDOM" not available in this environment')}static from(t){return t instanceof i?t:On(t)?Ad(t):Mn(t)?il(t):Vt(t)?f(this,void 0,void 0,function*(){return yield i.from(yield t)}):En(t)||hr(t)||Dn(t)||Tt(t)?el(new Pt(t)):tl(new ve(t))}static readAll(t){return t instanceof i?t.isSync()?Bc(t):dc(t):On(t)||ArrayBuffer.isView(t)||qt(t)||vn(t)?Bc(t):dc(t)}},Ee=class extends It{constructor(t){super(t),this._impl=t}readAll(){return[...this]}[Symbol.iterator](){return this._impl[Symbol.iterator]()}[Symbol.asyncIterator](){return xt(this,arguments,function*(){yield Y(yield*Ni(Qt(this[Symbol.iterator]())))})}},li=class extends It{constructor(t){super(t),this._impl=t}readAll(){return f(this,void 0,void 0,function*(){var t,e,r,n;let o=new Array;try{for(var s=!0,a=Qt(this),u;u=yield a.next(),t=u.done,!t;s=!0){n=u.value,s=!1;let B=n;o.push(B)}}catch(B){e={error:B}}finally{try{!s&&!t&&(r=a.return)&&(yield r.call(a))}finally{if(e)throw e.error}}return o})}[Symbol.iterator](){throw new Error("AsyncRecordBatchStreamReader is not Iterable")}[Symbol.asyncIterator](){return this._impl[Symbol.asyncIterator]()}},fi=class extends Ee{constructor(t){super(t),this._impl=t}},fn=class extends li{constructor(t){super(t),this._impl=t}},ko=class{get numDictionaries(){return this._dictionaryIndex}get numRecordBatches(){return this._recordBatchIndex}constructor(t=new Map){this.closed=!1,this.autoDestroy=!0,this._dictionaryIndex=0,this._recordBatchIndex=0,this.dictionaries=t}isSync(){return!1}isAsync(){return!1}isFile(){return!1}isStream(){return!1}reset(t){return this._dictionaryIndex=0,this._recordBatchIndex=0,this.schema=t,this.dictionaries=new Map,this}_loadRecordBatch(t,e){let r=this._loadVectors(t,e,this.schema.fields),n=H({type:new q(this.schema.fields),length:t.length,children:r});return new rt(this.schema,n)}_loadDictionaryBatch(t,e){let{id:r,isDelta:n}=t,{dictionaries:o,schema:s}=this,a=o.get(r),u=s.dictionaries.get(r),B=this._loadVectors(t.data,e,[u]);return(a&&n?a.concat(new _(B)):new _(B)).memoize()}_loadVectors(t,e,r){return new gr(e,t.nodes,t.buffers,this.dictionaries,this.schema.metadataVersion).visitMany(r)}},sr=class extends ko{constructor(t,e){super(e),this._reader=On(t)?new ln(this._handle=t):new rr(this._handle=t)}isSync(){return!0}isStream(){return!0}[Symbol.iterator](){return this}cancel(){!this.closed&&(this.closed=!0)&&(this.reset()._reader.return(),this._reader=null,this.dictionaries=null)}open(t){return this.closed||(this.autoDestroy=lc(this,t),this.schema||(this.schema=this._reader.readSchema())||this.cancel()),this}throw(t){return!this.closed&&this.autoDestroy&&(this.closed=!0)?this.reset()._reader.throw(t):$}return(t){return!this.closed&&this.autoDestroy&&(this.closed=!0)?this.reset()._reader.return(t):$}next(){if(this.closed)return $;let t,{_reader:e}=this;for(;t=this._readNextMessageAndValidate();)if(t.isSchema())this.reset(t.header());else if(t.isRecordBatch()){this._recordBatchIndex++;let r=t.header(),n=e.readMessageBody(t.bodyLength);return{done:!1,value:this._loadRecordBatch(r,n)}}else if(t.isDictionaryBatch()){this._dictionaryIndex++;let r=t.header(),n=e.readMessageBody(t.bodyLength),o=this._loadDictionaryBatch(r,n);this.dictionaries.set(r.id,o)}return this.schema&&this._recordBatchIndex===0?(this._recordBatchIndex++,{done:!1,value:new Gi(this.schema)}):this.return()}_readNextMessageAndValidate(t){return this._reader.readMessage(t)}},ar=class extends ko{constructor(t,e){super(e),this._reader=new dn(this._handle=t)}isAsync(){return!0}isStream(){return!0}[Symbol.asyncIterator](){return this}cancel(){return f(this,void 0,void 0,function*(){!this.closed&&(this.closed=!0)&&(yield this.reset()._reader.return(),this._reader=null,this.dictionaries=null)})}open(t){return f(this,void 0,void 0,function*(){return this.closed||(this.autoDestroy=lc(this,t),this.schema||(this.schema=yield this._reader.readSchema())||(yield this.cancel())),this})}throw(t){return f(this,void 0,void 0,function*(){return!this.closed&&this.autoDestroy&&(this.closed=!0)?yield this.reset()._reader.throw(t):$})}return(t){return f(this,void 0,void 0,function*(){return!this.closed&&this.autoDestroy&&(this.closed=!0)?yield this.reset()._reader.return(t):$})}next(){return f(this,void 0,void 0,function*(){if(this.closed)return $;let t,{_reader:e}=this;for(;t=yield this._readNextMessageAndValidate();)if(t.isSchema())yield this.reset(t.header());else if(t.isRecordBatch()){this._recordBatchIndex++;let r=t.header(),n=yield e.readMessageBody(t.bodyLength);return{done:!1,value:this._loadRecordBatch(r,n)}}else if(t.isDictionaryBatch()){this._dictionaryIndex++;let r=t.header(),n=yield e.readMessageBody(t.bodyLength),o=this._loadDictionaryBatch(r,n);this.dictionaries.set(r.id,o)}return this.schema&&this._recordBatchIndex===0?(this._recordBatchIndex++,{done:!1,value:new Gi(this.schema)}):yield this.return()})}_readNextMessageAndValidate(t){return f(this,void 0,void 0,function*(){return yield this._reader.readMessage(t)})}},Qo=class extends sr{get footer(){return this._footer}get numDictionaries(){return this._footer?this._footer.numDictionaries:0}get numRecordBatches(){return this._footer?this._footer.numRecordBatches:0}constructor(t,e){super(t instanceof _r?t:new _r(t),e)}isSync(){return!0}isFile(){return!0}open(t){if(!this.closed&&!this._footer){this.schema=(this._footer=this._readFooter()).schema;for(let e of this._footer.dictionaryBatches())e&&this._readDictionaryBatch(this._dictionaryIndex++)}return super.open(t)}readRecordBatch(t){var e;if(this.closed)return null;this._footer||this.open();let r=(e=this._footer)===null||e===void 0?void 0:e.getRecordBatch(t);if(r&&this._handle.seek(r.offset)){let n=this._reader.readMessage(p.RecordBatch);if(n?.isRecordBatch()){let o=n.header(),s=this._reader.readMessageBody(n.bodyLength);return this._loadRecordBatch(o,s)}}return null}_readDictionaryBatch(t){var e;let r=(e=this._footer)===null||e===void 0?void 0:e.getDictionaryBatch(t);if(r&&this._handle.seek(r.offset)){let n=this._reader.readMessage(p.DictionaryBatch);if(n?.isDictionaryBatch()){let o=n.header(),s=this._reader.readMessageBody(n.bodyLength),a=this._loadDictionaryBatch(o,s);this.dictionaries.set(o.id,a)}}}_readFooter(){let{_handle:t}=this,e=t.size-ea,r=t.readInt32(e),n=t.readAt(e-r,r);return je.decode(n)}_readNextMessageAndValidate(t){var e;if(this._footer||this.open(),this._footer&&this._recordBatchIndex<this.numRecordBatches){let r=(e=this._footer)===null||e===void 0?void 0:e.getRecordBatch(this._recordBatchIndex);if(r&&this._handle.seek(r.offset))return this._reader.readMessage(t)}return null}},ia=class extends ar{get footer(){return this._footer}get numDictionaries(){return this._footer?this._footer.numDictionaries:0}get numRecordBatches(){return this._footer?this._footer.numRecordBatches:0}constructor(t,...e){let r=typeof e[0]!="number"?e.shift():void 0,n=e[0]instanceof Map?e.shift():void 0;super(t instanceof di?t:new di(t,r),n)}isFile(){return!0}isAsync(){return!0}open(t){let e=Object.create(null,{open:{get:()=>super.open}});return f(this,void 0,void 0,function*(){if(!this.closed&&!this._footer){this.schema=(this._footer=yield this._readFooter()).schema;for(let r of this._footer.dictionaryBatches())r&&(yield this._readDictionaryBatch(this._dictionaryIndex++))}return yield e.open.call(this,t)})}readRecordBatch(t){return f(this,void 0,void 0,function*(){var e;if(this.closed)return null;this._footer||(yield this.open());let r=(e=this._footer)===null||e===void 0?void 0:e.getRecordBatch(t);if(r&&(yield this._handle.seek(r.offset))){let n=yield this._reader.readMessage(p.RecordBatch);if(n?.isRecordBatch()){let o=n.header(),s=yield this._reader.readMessageBody(n.bodyLength);return this._loadRecordBatch(o,s)}}return null})}_readDictionaryBatch(t){return f(this,void 0,void 0,function*(){var e;let r=(e=this._footer)===null||e===void 0?void 0:e.getDictionaryBatch(t);if(r&&(yield this._handle.seek(r.offset))){let n=yield this._reader.readMessage(p.DictionaryBatch);if(n?.isDictionaryBatch()){let o=n.header(),s=yield this._reader.readMessageBody(n.bodyLength),a=this._loadDictionaryBatch(o,s);this.dictionaries.set(o.id,a)}}})}_readFooter(){return f(this,void 0,void 0,function*(){let{_handle:t}=this;t._pending&&(yield t._pending);let e=t.size-ea,r=yield t.readInt32(e),n=yield t.readAt(e-r,r);return je.decode(n)})}_readNextMessageAndValidate(t){return f(this,void 0,void 0,function*(){if(this._footer||(yield this.open()),this._footer&&this._recordBatchIndex<this.numRecordBatches){let e=this._footer.getRecordBatch(this._recordBatchIndex);if(e&&(yield this._handle.seek(e.offset)))return yield this._reader.readMessage(t)}return null})}},ra=class extends sr{constructor(t,e){super(t,e)}_loadVectors(t,e,r){return new wo(e,t.nodes,t.buffers,this.dictionaries,this.schema.metadataVersion).visitMany(r)}};function lc(i,t){return t&&typeof t.autoDestroy=="boolean"?t.autoDestroy:i.autoDestroy}function*Bc(i){let t=It.from(i);try{if(!t.open({autoDestroy:!1}).closed)do yield t;while(!t.reset().open().closed)}finally{t.cancel()}}function dc(i){return xt(this,arguments,function*(){let e=yield Y(It.from(i));try{if(!(yield Y(e.open({autoDestroy:!1}))).closed)do yield yield Y(e);while(!(yield Y(e.reset().open())).closed)}finally{yield Y(e.cancel())}})}function Ad(i){return new Ee(new ra(i))}function tl(i){let t=i.peek(or+7&-8);return t&&t.byteLength>=4?Ko(t)?new fi(new Qo(i.read())):new Ee(new sr(i)):new Ee(new sr(function*(){}()))}function el(i){return f(this,void 0,void 0,function*(){let t=yield i.peek(or+7&-8);return t&&t.byteLength>=4?Ko(t)?new fi(new Qo(yield i.read())):new li(new ar(i)):new li(new ar(function(){return xt(this,arguments,function*(){})}()))})}function il(i){return f(this,void 0,void 0,function*(){let{size:t}=yield i.stat(),e=new di(i,t);return t>=cc&&Ko(yield e.readAt(0,or+7&-8))?new fn(new ia(e)):new li(new ar(e))})}var tt=class i extends C{static assemble(...t){let e=n=>n.flatMap(o=>Array.isArray(o)?e(o):o instanceof rt?o.data.children:o.data),r=new i;return r.visitMany(e(t)),r}constructor(){super(),this._byteLength=0,this._nodes=[],this._buffers=[],this._bufferRegions=[]}visit(t){if(t instanceof _)return this.visitMany(t.data),this;let{type:e}=t;if(!y.isDictionary(e)){let{length:r}=t;if(r>2147483647)throw new RangeError("Cannot write arrays larger than 2^31 - 1 in length");if(y.isUnion(e))this.nodes.push(new Kt(r,0));else{let{nullCount:n}=t;y.isNull(e)||de.call(this,n<=0?new Uint8Array(0):Ri(t.offset,r,t.nullBitmap)),this.nodes.push(new Kt(r,n))}}return super.visit(t)}visitNull(t){return this}visitDictionary(t){return this.visit(t.clone(t.type.indices))}get nodes(){return this._nodes}get buffers(){return this._buffers}get byteLength(){return this._byteLength}get bufferRegions(){return this._bufferRegions}};function de(i){let t=i.byteLength+7&-8;return this.buffers.push(i),this.bufferRegions.push(new bt(this._byteLength,t)),this._byteLength+=t,this}function rl(i){var t;let{type:e,length:r,typeIds:n,valueOffsets:o}=i;if(de.call(this,n),e.mode===K.Sparse)return na.call(this,i);if(e.mode===K.Dense){if(i.offset<=0)return de.call(this,o),na.call(this,i);{let s=new Int32Array(r),a=Object.create(null),u=Object.create(null);for(let B,d,l=-1;++l<r;)(B=n[l])!==void 0&&((d=a[B])===void 0&&(d=a[B]=o[l]),s[l]=o[l]-d,u[B]=((t=u[B])!==null&&t!==void 0?t:0)+1);de.call(this,s),this.visitMany(i.children.map((B,d)=>{let l=e.typeIds[d],m=a[l],F=u[l];return B.slice(m,Math.min(r,F))}))}}return this}function nl(i){let t;return i.nullCount>=i.length?de.call(this,new Uint8Array(0)):(t=i.values)instanceof Uint8Array?de.call(this,Ri(i.offset,i.length,t)):de.call(this,Oi(i.values))}function qe(i){return de.call(this,i.values.subarray(0,i.length*i.stride))}function Vo(i){let{length:t,values:e,valueOffsets:r}=i,n=Z(r[0]),o=Z(r[t]),s=Math.min(o-n,e.byteLength-n);return de.call(this,Hn(-n,t+1,r)),de.call(this,e.subarray(n,n+s)),this}function oa(i){let{length:t,valueOffsets:e}=i;if(e){let{[0]:r,[t]:n}=e;return de.call(this,Hn(-r,t+1,e)),this.visit(i.children[0].slice(r,n-r))}return this.visit(i.children[0])}function na(i){return this.visitMany(i.type.children.map((t,e)=>i.children[e]).filter(Boolean))[0]}tt.prototype.visitBool=nl;tt.prototype.visitInt=qe;tt.prototype.visitFloat=qe;tt.prototype.visitUtf8=Vo;tt.prototype.visitLargeUtf8=Vo;tt.prototype.visitBinary=Vo;tt.prototype.visitLargeBinary=Vo;tt.prototype.visitFixedSizeBinary=qe;tt.prototype.visitDate=qe;tt.prototype.visitTimestamp=qe;tt.prototype.visitTime=qe;tt.prototype.visitDecimal=qe;tt.prototype.visitList=oa;tt.prototype.visitStruct=na;tt.prototype.visitUnion=rl;tt.prototype.visitInterval=qe;tt.prototype.visitDuration=qe;tt.prototype.visitFixedSizeList=oa;tt.prototype.visitMap=oa;var xi=class extends Ei{static throughNode(t){throw new Error('"throughNode" not available in this environment')}static throughDOM(t,e){throw new Error('"throughDOM" not available in this environment')}constructor(t){super(),this._position=0,this._started=!1,this._sink=new Oe,this._schema=null,this._dictionaryBlocks=[],this._recordBatchBlocks=[],this._seenDictionaries=new Map,this._dictionaryDeltaOffsets=new Map,Rt(t)||(t={autoDestroy:!0,writeLegacyIpcFormat:!1}),this._autoDestroy=typeof t.autoDestroy=="boolean"?t.autoDestroy:!0,this._writeLegacyIpcFormat=typeof t.writeLegacyIpcFormat=="boolean"?t.writeLegacyIpcFormat:!1}toString(t=!1){return this._sink.toString(t)}toUint8Array(t=!1){return this._sink.toUint8Array(t)}writeAll(t){return Vt(t)?t.then(e=>this.writeAll(e)):Tt(t)?aa(this,t):sa(this,t)}get closed(){return this._sink.closed}[Symbol.asyncIterator](){return this._sink[Symbol.asyncIterator]()}toDOMStream(t){return this._sink.toDOMStream(t)}toNodeStream(t){return this._sink.toNodeStream(t)}close(){return this.reset()._sink.close()}abort(t){return this.reset()._sink.abort(t)}finish(){return this._autoDestroy?this.close():this.reset(this._sink,this._schema),this}reset(t=this._sink,e=null){return t===this._sink||t instanceof Oe?this._sink=t:(this._sink=new Oe,t&&ma(t)?this.toDOMStream({type:"bytes"}).pipeTo(t):t&&Ha(t)&&this.toNodeStream({objectMode:!1}).pipe(t)),this._started&&this._schema&&this._writeFooter(this._schema),this._started=!1,this._dictionaryBlocks=[],this._recordBatchBlocks=[],this._seenDictionaries=new Map,this._dictionaryDeltaOffsets=new Map,(!e||!Yi(e,this._schema))&&(e==null?(this._position=0,this._schema=null):(this._started=!0,this._schema=e,this._writeSchema(e))),this}write(t){let e=null;if(this._sink){if(t==null)return this.finish()&&void 0;if(t instanceof Mt&&!(e=t.schema))return this.finish()&&void 0;if(t instanceof rt&&!(e=t.schema))return this.finish()&&void 0}else throw new Error("RecordBatchWriter is closed");if(e&&!Yi(e,this._schema)){if(this._started&&this._autoDestroy)return this.close();this.reset(this._sink,e)}t instanceof rt?t instanceof Gi||this._writeRecordBatch(t):t instanceof Mt?this.writeAll(t.batches):qt(t)&&this.writeAll(t)}_writeMessage(t,e=8){let r=e-1,n=Gt.encode(t),o=n.byteLength,s=this._writeLegacyIpcFormat?4:8,a=o+s+r&~r,u=a-o-s;return t.headerType===p.RecordBatch?this._recordBatchBlocks.push(new ze(a,t.bodyLength,this._position)):t.headerType===p.DictionaryBatch&&this._dictionaryBlocks.push(new ze(a,t.bodyLength,this._position)),this._writeLegacyIpcFormat||this._write(Int32Array.of(-1)),this._write(Int32Array.of(a-s)),o>0&&this._write(n),this._writePadding(u)}_write(t){if(this._started){let e=M(t);e&&e.byteLength>0&&(this._sink.write(e),this._position+=e.byteLength)}return this}_writeSchema(t){return this._writeMessage(Gt.from(t))}_writeFooter(t){return this._writeLegacyIpcFormat?this._write(Int32Array.of(0)):this._write(Int32Array.of(-1,0))}_writeMagic(){return this._write(nr)}_writePadding(t){return t>0?this._write(new Uint8Array(t)):this}_writeRecordBatch(t){let{byteLength:e,nodes:r,bufferRegions:n,buffers:o}=tt.assemble(t),s=new Ct(t.numRows,r,n),a=Gt.from(s,e);return this._writeDictionaries(t)._writeMessage(a)._writeBodyBuffers(o)}_writeDictionaryBatch(t,e,r=!1){let{byteLength:n,nodes:o,bufferRegions:s,buffers:a}=tt.assemble(new _([t])),u=new Ct(t.length,o,s),B=new Yt(u,e,r),d=Gt.from(B,n);return this._writeMessage(d)._writeBodyBuffers(a)}_writeBodyBuffers(t){let e,r,n;for(let o=-1,s=t.length;++o<s;)(e=t[o])&&(r=e.byteLength)>0&&(this._write(e),(n=(r+7&-8)-r)>0&&this._writePadding(n));return this}_writeDictionaries(t){var e,r;for(let[n,o]of t.dictionaries){let s=(e=o?.data)!==null&&e!==void 0?e:[],a=this._seenDictionaries.get(n),u=(r=this._dictionaryDeltaOffsets.get(n))!==null&&r!==void 0?r:0;if(!a||a.data[0]!==s[0])for(let[B,d]of s.entries())this._writeDictionaryBatch(d,n,B>0);else if(u<s.length)for(let B of s.slice(u))this._writeDictionaryBatch(B,n,!0);this._seenDictionaries.set(n,o),this._dictionaryDeltaOffsets.set(n,s.length)}return this}},Wi=class i extends xi{static writeAll(t,e){let r=new i(e);return Vt(t)?t.then(n=>r.writeAll(n)):Tt(t)?aa(r,t):sa(r,t)}},pi=class i extends xi{static writeAll(t){let e=new i;return Vt(t)?t.then(r=>e.writeAll(r)):Tt(t)?aa(e,t):sa(e,t)}constructor(){super(),this._autoDestroy=!0}_writeSchema(t){return this._writeMagic()._writePadding(2)}_writeDictionaryBatch(t,e,r=!1){if(!r&&this._seenDictionaries.has(e))throw new Error("The Arrow File format does not support replacement dictionaries. ");return super._writeDictionaryBatch(t,e,r)}_writeFooter(t){let e=je.encode(new je(t,j.V5,this._recordBatchBlocks,this._dictionaryBlocks));return super._writeFooter(t)._write(e)._write(Int32Array.of(e.byteLength))._writeMagic()}};function sa(i,t){let e=t;t instanceof Mt&&(e=t.batches,i.reset(void 0,t.schema));for(let r of e)i.write(r);return i.finish()}function aa(i,t){return f(this,void 0,void 0,function*(){var e,r,n,o,s,a,u;try{for(e=!0,r=Qt(t);n=yield r.next(),o=n.done,!o;e=!0){u=n.value,e=!1;let B=u;i.write(B)}}catch(B){s={error:B}}finally{try{!e&&!o&&(a=r.return)&&(yield a.call(r))}finally{if(s)throw s.error}}return i.finish()})}function fc(i,t){if(Tt(i))return sl(i,t);if(qt(i))return ol(i,t);throw new Error("toDOMStream() must be called with an Iterable or AsyncIterable")}function ol(i,t){let e=null,r=t?.type==="bytes"||!1,n=t?.highWaterMark||Math.pow(2,24);return new ReadableStream(Object.assign(Object.assign({},t),{start(s){o(s,e||(e=i[Symbol.iterator]()))},pull(s){e?o(s,e):s.close()},cancel(){(e?.return&&e.return()||!0)&&(e=null)}}),Object.assign({highWaterMark:r?n:void 0},t));function o(s,a){let u,B=null,d=s.desiredSize||null;for(;!(B=a.next(r?d:null)).done;)if(ArrayBuffer.isView(B.value)&&(u=M(B.value))&&(d!=null&&r&&(d=d-u.byteLength+1),B.value=u),s.enqueue(B.value),d!=null&&--d<=0)return;s.close()}}function sl(i,t){let e=null,r=t?.type==="bytes"||!1,n=t?.highWaterMark||Math.pow(2,24);return new ReadableStream(Object.assign(Object.assign({},t),{start(s){return f(this,void 0,void 0,function*(){yield o(s,e||(e=i[Symbol.asyncIterator]()))})},pull(s){return f(this,void 0,void 0,function*(){e?yield o(s,e):s.close()})},cancel(){return f(this,void 0,void 0,function*(){(e?.return&&(yield e.return())||!0)&&(e=null)})}}),Object.assign({highWaterMark:r?n:void 0},t));function o(s,a){return f(this,void 0,void 0,function*(){let u,B=null,d=s.desiredSize||null;for(;!(B=yield a.next(r?d:null)).done;)if(ArrayBuffer.isView(B.value)&&(u=M(B.value))&&(d!=null&&r&&(d=d-u.byteLength+1),B.value=u),s.enqueue(B.value),d!=null&&--d<=0)return;s.close()})}}function Lc(i){return new ua(i)}var ua=class{constructor(t){this._numChunks=0,this._finished=!1,this._bufferedSize=0;let{["readableStrategy"]:e,["writableStrategy"]:r,["queueingStrategy"]:n="count"}=t,o=Xa(t,["readableStrategy","writableStrategy","queueingStrategy"]);this._controller=null,this._builder=Di(o),this._getSize=n!=="bytes"?yc:hc;let{["highWaterMark"]:s=n==="bytes"?Math.pow(2,14):1e3}=Object.assign({},e),{["highWaterMark"]:a=n==="bytes"?Math.pow(2,14):1e3}=Object.assign({},r);this.readable=new ReadableStream({cancel:()=>{this._builder.clear()},pull:u=>{this._maybeFlush(this._builder,this._controller=u)},start:u=>{this._maybeFlush(this._builder,this._controller=u)}},{highWaterMark:s,size:n!=="bytes"?yc:hc}),this.writable=new WritableStream({abort:()=>{this._builder.clear()},write:()=>{this._maybeFlush(this._builder,this._controller)},close:()=>{this._maybeFlush(this._builder.finish(),this._controller)}},{highWaterMark:a,size:u=>this._writeValueAndReturnChunkSize(u)})}_writeValueAndReturnChunkSize(t){let e=this._bufferedSize;return this._bufferedSize=this._getSize(this._builder.append(t)),this._bufferedSize-e}_maybeFlush(t,e){e!=null&&(this._bufferedSize>=e.desiredSize&&++this._numChunks&&this._enqueue(e,t.toVector()),t.finished&&((t.length>0||this._numChunks===0)&&++this._numChunks&&this._enqueue(e,t.toVector()),!this._finished&&(this._finished=!0)&&this._enqueue(e,null)))}_enqueue(t,e){this._bufferedSize=0,this._controller=null,e==null?t.close():t.enqueue(e)}},yc=i=>{var t;return(t=i?.length)!==null&&t!==void 0?t:0},hc=i=>{var t;return(t=i?.byteLength)!==null&&t!==void 0?t:0};function qo(i,t){let e=new Oe,r=null,n=new ReadableStream({cancel(){return f(this,void 0,void 0,function*(){yield e.close()})},start(a){return f(this,void 0,void 0,function*(){yield s(a,r||(r=yield o()))})},pull(a){return f(this,void 0,void 0,function*(){r?yield s(a,r):a.close()})}});return{writable:new WritableStream(e,Object.assign({highWaterMark:Math.pow(2,14)},i)),readable:n};function o(){return f(this,void 0,void 0,function*(){return yield(yield It.from(e)).open(t)})}function s(a,u){return f(this,void 0,void 0,function*(){let B=a.desiredSize,d=null;for(;!(d=yield u.next()).done;)if(a.enqueue(d.value),B!=null&&--B<=0)return;a.close()})}}function $o(i,t){let e=new this(i),r=new Pt(e),n=new ReadableStream({cancel(){return f(this,void 0,void 0,function*(){yield r.cancel()})},pull(s){return f(this,void 0,void 0,function*(){yield o(s)})},start(s){return f(this,void 0,void 0,function*(){yield o(s)})}},Object.assign({highWaterMark:Math.pow(2,14)},t));return{writable:new WritableStream(e,i),readable:n};function o(s){return f(this,void 0,void 0,function*(){let a=null,u=s.desiredSize;for(;a=yield r.read(u||null);)if(s.enqueue(a),u!=null&&(u-=a.byteLength)<=0)return;s.close()})}}function Ao(i,t="stream"){return(t==="stream"?Wi:pi).writeAll(i).toUint8Array(!0)}var Bl=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},ws),Ps),Ns),Rs),fs),ps),Ls),{compareSchemas:Yi,compareFields:zu,compareTypes:Pu});Lt.toDOMStream=fc;A.throughDOM=Lc;It.throughDOM=qo;fi.throughDOM=qo;Ee.throughDOM=qo;xi.throughDOM=$o;pi.throughDOM=$o;Wi.throughDOM=$o;var dl=Object.create,Cc=Object.defineProperty,ll=Object.getOwnPropertyDescriptor,fl=Object.getOwnPropertyNames,yl=Object.getPrototypeOf,hl=Object.prototype.hasOwnProperty,Ll=(i,t)=>()=>(t||i((t={exports:{}}).exports,t),t.exports),Fl=(i,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of fl(t))!hl.call(i,n)&&n!==e&&Cc(i,n,{get:()=>t[n],enumerable:!(r=ll(t,n))||r.enumerable});return i},Cl=(i,t,e)=>(e=i!=null?dl(yl(i)):{},Fl(t||!i||!i.__esModule?Cc(e,"default",{value:i,enumerable:!0}):e,i)),Il=Ll((i,t)=>{t.exports=Worker}),wl=(i=>(i[i.UNDEFINED=0]="UNDEFINED",i[i.AUTOMATIC=1]="AUTOMATIC",i[i.READ_ONLY=2]="READ_ONLY",i[i.READ_WRITE=3]="READ_WRITE",i))(wl||{}),Rl=(i=>(i[i.IDENTIFIER=0]="IDENTIFIER",i[i.NUMERIC_CONSTANT=1]="NUMERIC_CONSTANT",i[i.STRING_CONSTANT=2]="STRING_CONSTANT",i[i.OPERATOR=3]="OPERATOR",i[i.KEYWORD=4]="KEYWORD",i[i.COMMENT=5]="COMMENT",i))(Rl||{}),Ol=(i=>(i[i.NONE=0]="NONE",i[i.DEBUG=1]="DEBUG",i[i.INFO=2]="INFO",i[i.WARNING=3]="WARNING",i[i.ERROR=4]="ERROR",i))(Ol||{}),vl=(i=>(i[i.NONE=0]="NONE",i[i.CONNECT=1]="CONNECT",i[i.DISCONNECT=2]="DISCONNECT",i[i.OPEN=3]="OPEN",i[i.QUERY=4]="QUERY",i[i.INSTANTIATE=5]="INSTANTIATE",i))(vl||{}),Ml=(i=>(i[i.NONE=0]="NONE",i[i.OK=1]="OK",i[i.ERROR=2]="ERROR",i[i.START=3]="START",i[i.RUN=4]="RUN",i[i.CAPTURE=5]="CAPTURE",i))(Ml||{}),El=(i=>(i[i.NONE=0]="NONE",i[i.WEB_WORKER=1]="WEB_WORKER",i[i.NODE_WORKER=2]="NODE_WORKER",i[i.BINDINGS=3]="BINDINGS",i[i.ASYNC_DUCKDB=4]="ASYNC_DUCKDB",i))(El||{});var Ic=class{constructor(i=2){this.level=i}log(i){i.level>=this.level&&console.log(i)}};var Xl=(i=>(i[i.SUCCESS=0]="SUCCESS",i))(Xl||{}),Dl=class{constructor(i,t){this._bindings=i,this._conn=t}get bindings(){return this._bindings}async close(){return this._bindings.disconnect(this._conn)}useUnsafe(i){return i(this._bindings,this._conn)}async query(i){this._bindings.logger.log({timestamp:new Date,level:2,origin:4,topic:4,event:4,value:i});let t=await this._bindings.runQuery(this._conn,i),e=It.from(t);return console.assert(e.isSync(),"Reader is not sync"),console.assert(e.isFile(),"Reader is not file"),new Mt(e)}async send(i){this._bindings.logger.log({timestamp:new Date,level:2,origin:4,topic:4,event:4,value:i});let t=await this._bindings.startPendingQuery(this._conn,i);for(;t==null;)t=await this._bindings.pollPendingQuery(this._conn);let e=new wc(this._bindings,this._conn,t),r=await It.from(e);return console.assert(r.isAsync()),console.assert(r.isStream()),r}async cancelSent(){return await this._bindings.cancelPendingQuery(this._conn)}async getTableNames(i){return await this._bindings.getTableNames(this._conn,i)}async prepare(i){let t=await this._bindings.createPrepared(this._conn,i);return new ml(this._bindings,this._conn,t)}async insertArrowTable(i,t){let e=Ao(i,"stream");await this.insertArrowFromIPCStream(e,t)}async insertArrowFromIPCStream(i,t){await this._bindings.insertArrowFromIPCStream(this._conn,i,t)}async insertCSVFromPath(i,t){await this._bindings.insertCSVFromPath(this._conn,i,t)}async insertJSONFromPath(i,t){await this._bindings.insertJSONFromPath(this._conn,i,t)}},wc=class{constructor(i,t,e){this.db=i,this.conn=t,this.header=e,this._first=!0,this._depleted=!1,this._inFlight=null}async next(){if(this._first)return this._first=!1,{done:!1,value:this.header};if(this._depleted)return{done:!0,value:null};let i;return this._inFlight!=null?(i=await this._inFlight,this._inFlight=null):i=await this.db.fetchQueryResults(this.conn),this._depleted=i.length==0,this._depleted||(this._inFlight=this.db.fetchQueryResults(this.conn)),{done:this._depleted,value:i}}[Symbol.asyncIterator](){return this}},ml=class{constructor(i,t,e){this.bindings=i,this.connectionId=t,this.statementId=e}async close(){await this.bindings.closePrepared(this.connectionId,this.statementId)}async query(...i){let t=await this.bindings.runPrepared(this.connectionId,this.statementId,i),e=It.from(t);return console.assert(e.isSync()),console.assert(e.isFile()),new Mt(e)}async send(...i){let t=await this.bindings.sendPrepared(this.connectionId,this.statementId,i),e=new wc(this.bindings,this.connectionId,t),r=await It.from(e);return console.assert(r.isAsync()),console.assert(r.isStream()),r}},Hl=(i=>(i.CANCEL_PENDING_QUERY="CANCEL_PENDING_QUERY",i.CLOSE_PREPARED="CLOSE_PREPARED",i.COLLECT_FILE_STATISTICS="COLLECT_FILE_STATISTICS",i.CONNECT="CONNECT",i.COPY_FILE_TO_BUFFER="COPY_FILE_TO_BUFFER",i.COPY_FILE_TO_PATH="COPY_FILE_TO_PATH",i.CREATE_PREPARED="CREATE_PREPARED",i.DISCONNECT="DISCONNECT",i.DROP_FILE="DROP_FILE",i.DROP_FILES="DROP_FILES",i.EXPORT_FILE_STATISTICS="EXPORT_FILE_STATISTICS",i.FETCH_QUERY_RESULTS="FETCH_QUERY_RESULTS",i.FLUSH_FILES="FLUSH_FILES",i.GET_FEATURE_FLAGS="GET_FEATURE_FLAGS",i.GET_TABLE_NAMES="GET_TABLE_NAMES",i.GET_VERSION="GET_VERSION",i.GLOB_FILE_INFOS="GLOB_FILE_INFOS",i.INSERT_ARROW_FROM_IPC_STREAM="INSERT_ARROW_FROM_IPC_STREAM",i.INSERT_CSV_FROM_PATH="IMPORT_CSV_FROM_PATH",i.INSERT_JSON_FROM_PATH="IMPORT_JSON_FROM_PATH",i.INSTANTIATE="INSTANTIATE",i.OPEN="OPEN",i.PING="PING",i.POLL_PENDING_QUERY="POLL_PENDING_QUERY",i.REGISTER_FILE_BUFFER="REGISTER_FILE_BUFFER",i.REGISTER_FILE_HANDLE="REGISTER_FILE_HANDLE",i.REGISTER_FILE_URL="REGISTER_FILE_URL",i.RESET="RESET",i.RUN_PREPARED="RUN_PREPARED",i.RUN_QUERY="RUN_QUERY",i.SEND_PREPARED="SEND_PREPARED",i.START_PENDING_QUERY="START_PENDING_QUERY",i.TOKENIZE="TOKENIZE",i))(Hl||{}),bl=(i=>(i.CONNECTION_INFO="CONNECTION_INFO",i.ERROR="ERROR",i.FEATURE_FLAGS="FEATURE_FLAGS",i.FILE_BUFFER="FILE_BUFFER",i.FILE_INFOS="FILE_INFOS",i.FILE_SIZE="FILE_SIZE",i.FILE_STATISTICS="FILE_STATISTICS",i.INSTANTIATE_PROGRESS="INSTANTIATE_PROGRESS",i.LOG="LOG",i.OK="OK",i.PREPARED_STATEMENT_ID="PREPARED_STATEMENT_ID",i.QUERY_PLAN="QUERY_PLAN",i.QUERY_RESULT="QUERY_RESULT",i.QUERY_RESULT_CHUNK="QUERY_RESULT_CHUNK",i.QUERY_RESULT_HEADER="QUERY_RESULT_HEADER",i.QUERY_RESULT_HEADER_OR_NULL="QUERY_RESULT_HEADER_OR_NULL",i.REGISTERED_FILE="REGISTERED_FILE",i.SCRIPT_TOKENS="SCRIPT_TOKENS",i.SUCCESS="SUCCESS",i.TABLE_NAMES="TABLE_NAMES",i.VERSION_STRING="VERSION_STRING",i))(bl||{}),T=class{constructor(i,t){this.promiseResolver=()=>{},this.promiseRejecter=()=>{},this.type=i,this.data=t,this.promise=new Promise((e,r)=>{this.promiseResolver=e,this.promiseRejecter=r})}};function ts(i){switch(i.typeId){case c.Binary:return{sqlType:"binary"};case c.Bool:return{sqlType:"bool"};case c.Date:return{sqlType:"date"};case c.DateDay:return{sqlType:"date32[d]"};case c.DateMillisecond:return{sqlType:"date64[ms]"};case c.Decimal:{let t=i;return{sqlType:"decimal",precision:t.precision,scale:t.scale}}case c.Float:return{sqlType:"float"};case c.Float16:return{sqlType:"float16"};case c.Float32:return{sqlType:"float32"};case c.Float64:return{sqlType:"float64"};case c.Int:return{sqlType:"int32"};case c.Int16:return{sqlType:"int16"};case c.Int32:return{sqlType:"int32"};case c.Int64:return{sqlType:"int64"};case c.Uint16:return{sqlType:"uint16"};case c.Uint32:return{sqlType:"uint32"};case c.Uint64:return{sqlType:"uint64"};case c.Uint8:return{sqlType:"uint8"};case c.IntervalDayTime:return{sqlType:"interval[dt]"};case c.IntervalYearMonth:return{sqlType:"interval[m]"};case c.List:return{sqlType:"list",valueType:ts(i.valueType)};case c.FixedSizeBinary:return{sqlType:"fixedsizebinary",byteWidth:i.byteWidth};case c.Null:return{sqlType:"null"};case c.Utf8:return{sqlType:"utf8"};case c.Struct:return{sqlType:"struct",fields:i.children.map(t=>ca(t.name,t.type))};case c.Map:{let t=i;return{sqlType:"map",keyType:ts(t.keyType),valueType:ts(t.valueType)}}case c.Time:return{sqlType:"time[s]"};case c.TimeMicrosecond:return{sqlType:"time[us]"};case c.TimeMillisecond:return{sqlType:"time[ms]"};case c.TimeNanosecond:return{sqlType:"time[ns]"};case c.TimeSecond:return{sqlType:"time[s]"};case c.Timestamp:return{sqlType:"timestamp",timezone:i.timezone||void 0};case c.TimestampSecond:return{sqlType:"timestamp[s]",timezone:i.timezone||void 0};case c.TimestampMicrosecond:return{sqlType:"timestamp[us]",timezone:i.timezone||void 0};case c.TimestampNanosecond:return{sqlType:"timestamp[ns]",timezone:i.timezone||void 0};case c.TimestampMillisecond:return{sqlType:"timestamp[ms]",timezone:i.timezone||void 0}}throw new Error("unsupported arrow type: ".concat(i.toString()))}function ca(i,t){let e=ts(t);return e.name=i,e}var Yl=new TextEncoder,Rc=class{constructor(i,t=null){this._onInstantiationProgress=[],this._worker=null,this._workerShutdownPromise=null,this._workerShutdownResolver=()=>{},this._nextMessageId=0,this._pendingRequests=new Map,this._logger=i,this._onMessageHandler=this.onMessage.bind(this),this._onErrorHandler=this.onError.bind(this),this._onCloseHandler=this.onClose.bind(this),t!=null&&this.attach(t)}get logger(){return this._logger}attach(i){this._worker=i,this._worker.addEventListener("message",this._onMessageHandler),this._worker.addEventListener("error",this._onErrorHandler),this._worker.addEventListener("close",this._onCloseHandler),this._workerShutdownPromise=new Promise((t,e)=>{this._workerShutdownResolver=t})}detach(){this._worker&&(this._worker.removeEventListener("message",this._onMessageHandler),this._worker.removeEventListener("error",this._onErrorHandler),this._worker.removeEventListener("close",this._onCloseHandler),this._worker=null,this._workerShutdownResolver(null),this._workerShutdownPromise=null,this._workerShutdownResolver=()=>{})}async terminate(){this._worker&&(this._worker.terminate(),this._worker=null,this._workerShutdownPromise=null,this._workerShutdownResolver=()=>{})}async postTask(i,t=[]){if(!this._worker){console.error("cannot send a message since the worker is not set!");return}let e=this._nextMessageId++;return this._pendingRequests.set(e,i),this._worker.postMessage({messageId:e,type:i.type,data:i.data},t),await i.promise}onMessage(i){var t;let e=i.data;switch(e.type){case"LOG":{this._logger.log(e.data);return}case"INSTANTIATE_PROGRESS":{for(let n of this._onInstantiationProgress)n(e.data);return}}let r=this._pendingRequests.get(e.requestId);if(!r){console.warn("unassociated response: [".concat(e.requestId,", ").concat(e.type.toString(),"]"));return}if(this._pendingRequests.delete(e.requestId),e.type=="ERROR"){let n=new Error(e.data.message);n.name=e.data.name,(t=Object.getOwnPropertyDescriptor(n,"stack"))!=null&&t.writable&&(n.stack=e.data.stack),r.promiseRejecter(n);return}switch(r.type){case"CLOSE_PREPARED":case"COLLECT_FILE_STATISTICS":case"COPY_FILE_TO_PATH":case"DISCONNECT":case"DROP_FILE":case"DROP_FILES":case"FLUSH_FILES":case"INSERT_ARROW_FROM_IPC_STREAM":case"IMPORT_CSV_FROM_PATH":case"IMPORT_JSON_FROM_PATH":case"OPEN":case"PING":case"REGISTER_FILE_BUFFER":case"REGISTER_FILE_HANDLE":case"REGISTER_FILE_URL":case"RESET":if(e.type=="OK"){r.promiseResolver(e.data);return}break;case"INSTANTIATE":if(this._onInstantiationProgress=[],e.type=="OK"){r.promiseResolver(e.data);return}break;case"GLOB_FILE_INFOS":if(e.type=="FILE_INFOS"){r.promiseResolver(e.data);return}break;case"GET_VERSION":if(e.type=="VERSION_STRING"){r.promiseResolver(e.data);return}break;case"GET_FEATURE_FLAGS":if(e.type=="FEATURE_FLAGS"){r.promiseResolver(e.data);return}break;case"GET_TABLE_NAMES":if(e.type=="TABLE_NAMES"){r.promiseResolver(e.data);return}break;case"TOKENIZE":if(e.type=="SCRIPT_TOKENS"){r.promiseResolver(e.data);return}break;case"COPY_FILE_TO_BUFFER":if(e.type=="FILE_BUFFER"){r.promiseResolver(e.data);return}break;case"EXPORT_FILE_STATISTICS":if(e.type=="FILE_STATISTICS"){r.promiseResolver(e.data);return}break;case"CONNECT":if(e.type=="CONNECTION_INFO"){r.promiseResolver(e.data);return}break;case"RUN_PREPARED":case"RUN_QUERY":if(e.type=="QUERY_RESULT"){r.promiseResolver(e.data);return}break;case"SEND_PREPARED":if(e.type=="QUERY_RESULT_HEADER"){r.promiseResolver(e.data);return}break;case"START_PENDING_QUERY":if(e.type=="QUERY_RESULT_HEADER_OR_NULL"){r.promiseResolver(e.data);return}break;case"POLL_PENDING_QUERY":if(e.type=="QUERY_RESULT_HEADER_OR_NULL"){r.promiseResolver(e.data);return}break;case"CANCEL_PENDING_QUERY":if(this._onInstantiationProgress=[],e.type=="SUCCESS"){r.promiseResolver(e.data);return}break;case"FETCH_QUERY_RESULTS":if(e.type=="QUERY_RESULT_CHUNK"){r.promiseResolver(e.data);return}break;case"CREATE_PREPARED":if(e.type=="PREPARED_STATEMENT_ID"){r.promiseResolver(e.data);return}break}r.promiseRejecter(new Error("unexpected response type: ".concat(e.type.toString())))}onError(i){console.error(i),console.error("error in duckdb worker: ".concat(i.message)),this._pendingRequests.clear()}onClose(){if(this._workerShutdownResolver(null),this._pendingRequests.size!=0){console.warn("worker terminated with ".concat(this._pendingRequests.size," pending requests"));return}this._pendingRequests.clear()}async reset(){let i=new T("RESET",null);return await this.postTask(i)}async ping(){let i=new T("PING",null);await this.postTask(i)}async dropFile(i){let t=new T("DROP_FILE",i);return await this.postTask(t)}async dropFiles(){let i=new T("DROP_FILES",null);return await this.postTask(i)}async flushFiles(){let i=new T("FLUSH_FILES",null);return await this.postTask(i)}async instantiate(i,t=null,e=r=>{}){this._onInstantiationProgress.push(e);let r=new T("INSTANTIATE",[i,t]);return await this.postTask(r)}async getVersion(){let i=new T("GET_VERSION",null);return await this.postTask(i)}async getFeatureFlags(){let i=new T("GET_FEATURE_FLAGS",null);return await this.postTask(i)}async open(i){let t=new T("OPEN",i);await this.postTask(t)}async tokenize(i){let t=new T("TOKENIZE",i);return await this.postTask(t)}async connectInternal(){let i=new T("CONNECT",null);return await this.postTask(i)}async connect(){let i=await this.connectInternal();return new Dl(this,i)}async disconnect(i){let t=new T("DISCONNECT",i);await this.postTask(t)}async runQuery(i,t){let e=new T("RUN_QUERY",[i,t]);return await this.postTask(e)}async startPendingQuery(i,t){let e=new T("START_PENDING_QUERY",[i,t]);return await this.postTask(e)}async pollPendingQuery(i){let t=new T("POLL_PENDING_QUERY",i);return await this.postTask(t)}async cancelPendingQuery(i){let t=new T("CANCEL_PENDING_QUERY",i);return await this.postTask(t)}async fetchQueryResults(i){let t=new T("FETCH_QUERY_RESULTS",i);return await this.postTask(t)}async getTableNames(i,t){let e=new T("GET_TABLE_NAMES",[i,t]);return await this.postTask(e)}async createPrepared(i,t){let e=new T("CREATE_PREPARED",[i,t]);return await this.postTask(e)}async closePrepared(i,t){let e=new T("CLOSE_PREPARED",[i,t]);await this.postTask(e)}async runPrepared(i,t,e){let r=new T("RUN_PREPARED",[i,t,e]);return await this.postTask(r)}async sendPrepared(i,t,e){let r=new T("SEND_PREPARED",[i,t,e]);return await this.postTask(r)}async globFiles(i){let t=new T("GLOB_FILE_INFOS",i);return await this.postTask(t)}async registerFileText(i,t){let e=Yl.encode(t);await this.registerFileBuffer(i,e)}async registerFileURL(i,t,e,r){t===void 0&&(t=i);let n=new T("REGISTER_FILE_URL",[i,t,e,r]);await this.postTask(n)}async registerEmptyFileBuffer(i){}async registerFileBuffer(i,t){let e=new T("REGISTER_FILE_BUFFER",[i,t]);await this.postTask(e,[t.buffer])}async registerFileHandle(i,t,e,r){let n=new T("REGISTER_FILE_HANDLE",[i,t,e,r]);await this.postTask(n,[])}async collectFileStatistics(i,t){let e=new T("COLLECT_FILE_STATISTICS",[i,t]);await this.postTask(e,[])}async exportFileStatistics(i){let t=new T("EXPORT_FILE_STATISTICS",i);return await this.postTask(t,[])}async copyFileToBuffer(i){let t=new T("COPY_FILE_TO_BUFFER",i);return await this.postTask(t)}async copyFileToPath(i,t){let e=new T("COPY_FILE_TO_PATH",[i,t]);await this.postTask(e)}async insertArrowFromIPCStream(i,t,e){if(t.length==0)return;let r=new T("INSERT_ARROW_FROM_IPC_STREAM",[i,t,e]);await this.postTask(r,[t.buffer])}async insertCSVFromPath(i,t,e){if(e.columns!==void 0){let n=[];for(let o in e.columns){let s=e.columns[o];n.push(ca(o,s))}e.columnsFlat=n,delete e.columns}let r=new T("IMPORT_CSV_FROM_PATH",[i,t,e]);await this.postTask(r)}async insertJSONFromPath(i,t,e){if(e.columns!==void 0){let n=[];for(let o in e.columns){let s=e.columns[o];n.push(ca(o,s))}e.columnsFlat=n,delete e.columns}let r=new T("IMPORT_JSON_FROM_PATH",[i,t,e]);await this.postTask(r)}};var Ba={name:"@duckdb/duckdb-wasm",version:"1.29.0",description:"DuckDB powered by WebAssembly",license:"MIT",repository:{type:"git",url:"https://github.com/duckdb/duckdb-wasm.git"},keywords:["sql","duckdb","relational","database","data","query","wasm","analytics","olap","arrow","parquet","json","csv"],dependencies:{"apache-arrow":"^17.0.0"},devDependencies:{"@types/emscripten":"^1.39.10","@types/jasmine":"^5.1.4","@typescript-eslint/eslint-plugin":"^6.21.0","@typescript-eslint/parser":"^6.21.0",esbuild:"^0.20.2",eslint:"^8.57.0","eslint-plugin-jasmine":"^4.1.3","eslint-plugin-react":"^7.34.0","fast-glob":"^3.3.2",jasmine:"^5.1.0","jasmine-core":"^5.1.2","jasmine-spec-reporter":"^7.0.0","js-sha256":"^0.11.0",karma:"^6.4.2","karma-chrome-launcher":"^3.2.0","karma-coverage":"^2.2.1","karma-firefox-launcher":"^2.1.3","karma-jasmine":"^5.1.0","karma-jasmine-html-reporter":"^2.1.0","karma-sourcemap-loader":"^0.4.0","karma-spec-reporter":"^0.0.36","make-dir":"^4.0.0",nyc:"^15.1.0",prettier:"^3.2.5",puppeteer:"^22.8.0",rimraf:"^5.0.5",s3rver:"^3.7.1",typedoc:"^0.25.13",typescript:"^5.3.3","wasm-feature-detect":"^1.6.1","web-worker":"^1.2.0"},scripts:{"build:debug":"node bundle.mjs debug && tsc --emitDeclarationOnly","build:release":"node bundle.mjs release && tsc --emitDeclarationOnly",docs:"typedoc",report:"node ./coverage.mjs","test:node":"node --enable-source-maps ../../node_modules/jasmine/bin/jasmine ./dist/tests-node.cjs","test:node:debug":"node --inspect-brk --enable-source-maps ../../node_modules/jasmine/bin/jasmine ./dist/tests-node.cjs","test:node:coverage":"nyc -r json --report-dir ./coverage/node node ../../node_modules/jasmine/bin/jasmine ./dist/tests-node.cjs","test:firefox":"karma start ./karma/tests-firefox.cjs","test:chrome":"karma start ./karma/tests-chrome.cjs","test:chrome:eh":"karma start ./karma/tests-chrome-eh.cjs","test:chrome:coverage":"karma start ./karma/tests-chrome-coverage.cjs","test:browser":"karma start ./karma/tests-all.cjs","test:browser:debug":"karma start ./karma/tests-debug.cjs",test:"npm run test:chrome && npm run test:node","test:coverage":"npm run test:chrome:coverage && npm run test:node:coverage && npm run report",lint:"eslint src test"},files:["dist","!dist/tests-*","!dist/duckdb-browser-mvp.worker.js.map","!dist/types/test"],main:"dist/duckdb-browser.cjs",module:"dist/duckdb-browser.mjs",types:"dist/duckdb-browser.d.ts",jsdelivr:"dist/duckdb-browser.cjs",unpkg:"dist/duckdb-browser.mjs",sideEffects:!1,browser:{fs:!1,path:!1,perf_hooks:!1,os:!1,worker_threads:!1},exports:{"./dist/duckdb-mvp.wasm":"./dist/duckdb-mvp.wasm","./dist/duckdb-eh.wasm":"./dist/duckdb-eh.wasm","./dist/duckdb-coi.wasm":"./dist/duckdb-coi.wasm","./dist/duckdb-browser":"./dist/duckdb-browser.mjs","./dist/duckdb-browser.cjs":"./dist/duckdb-browser.cjs","./dist/duckdb-browser.mjs":"./dist/duckdb-browser.mjs","./dist/duckdb-browser-coi.pthread.worker.js":"./dist/duckdb-browser-coi.pthread.worker.js","./dist/duckdb-browser-coi.worker.js":"./dist/duckdb-browser-coi.worker.js","./dist/duckdb-browser-eh.worker.js":"./dist/duckdb-browser-eh.worker.js","./dist/duckdb-browser-mvp.worker.js":"./dist/duckdb-browser-mvp.worker.js","./dist/duckdb-node":"./dist/duckdb-node.cjs","./dist/duckdb-node.cjs":"./dist/duckdb-node.cjs","./dist/duckdb-node-blocking":"./dist/duckdb-node-blocking.cjs","./dist/duckdb-node-blocking.cjs":"./dist/duckdb-node-blocking.cjs","./dist/duckdb-node-eh.worker.cjs":"./dist/duckdb-node-eh.worker.cjs","./dist/duckdb-node-mvp.worker.cjs":"./dist/duckdb-node-mvp.worker.cjs","./blocking":{node:{types:"./dist/duckdb-node-blocking.d.ts",require:"./dist/duckdb-node-blocking.cjs",import:"./dist/duckdb-node-blocking.cjs"},types:"./dist/duckdb-node-blocking.d.ts",import:"./dist/duckdb-node-blocking.mjs",require:"./dist/duckdb-node-blocking.cjs"},".":{browser:{types:"./dist/duckdb-browser.d.ts",import:"./dist/duckdb-browser.mjs",require:"./dist/duckdb-browser.cjs"},node:{types:"./dist/duckdb-node.d.ts",import:"./dist/duckdb-node.cjs",require:"./dist/duckdb-node.cjs"},types:"./dist/duckdb-browser.d.ts",import:"./dist/duckdb-browser.mjs",require:"./dist/duckdb-browser.cjs"}}},yO=Ba.name,hO=Ba.version,da=Ba.version.split("."),LO=da[0],FO=da[1],CO=da[2];var IO=Cl(Il());function Gl(){let i=new TextDecoder;return t=>(typeof SharedArrayBuffer<"u"&&t.buffer instanceof SharedArrayBuffer&&(t=new Uint8Array(t)),i.decode(t))}var wO=Gl(),xl=(i=>(i[i.BUFFER=0]="BUFFER",i[i.NODE_FS=1]="NODE_FS",i[i.BROWSER_FILEREADER=2]="BROWSER_FILEREADER",i[i.BROWSER_FSACCESS=3]="BROWSER_FSACCESS",i[i.HTTP=4]="HTTP",i[i.S3=5]="S3",i))(xl||{});var Oc=class i{constructor(t,e){this._version=e;this.db=t}db;static load(){let t=URL.createObjectURL(new Blob([va()],{type:"text/javascript"})),e=new Worker(t);URL.revokeObjectURL(t);let r=new Ic,n=new Rc(r,e),o=URL.createObjectURL(new Blob([wa()],{type:"application/wasm"}));return n.instantiate(o,null).then(async()=>(URL.revokeObjectURL(o),new i(n,await n.getVersion())))}static unload(){Ma(),Ra()}version(){return this._version}};export{Oc as DuckDB};
11
+ //# sourceMappingURL=index.js.map