Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@electric-sql/pglite

Package Overview
Dependencies
Maintainers
3
Versions
40
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@electric-sql/pglite - npm Package Compare versions

Comparing version 0.2.5 to 0.2.6

dist/autoinc.tar.gz

4

dist/contrib/adminpack.d.ts

@@ -1,4 +0,4 @@

import { P as PGliteInterface } from '../interface-Db0XLAWB.js';
import { a as PGliteInterface } from '../interface-BChI4DHV.js';
import '@electric-sql/pg-protocol/messages';
import '../types-CQTnnKLt.js';
import '../types-XE-2t5ub.js';

@@ -5,0 +5,0 @@ declare const adminpack: {

@@ -1,4 +0,4 @@

import { P as PGliteInterface } from '../interface-Db0XLAWB.js';
import { a as PGliteInterface } from '../interface-BChI4DHV.js';
import '@electric-sql/pg-protocol/messages';
import '../types-CQTnnKLt.js';
import '../types-XE-2t5ub.js';

@@ -5,0 +5,0 @@ declare const amcheck: {

@@ -1,4 +0,4 @@

import { P as PGliteInterface } from '../interface-Db0XLAWB.js';
import { a as PGliteInterface } from '../interface-BChI4DHV.js';
import '@electric-sql/pg-protocol/messages';
import '../types-CQTnnKLt.js';
import '../types-XE-2t5ub.js';

@@ -5,0 +5,0 @@ declare const auto_explain: {

@@ -1,4 +0,4 @@

import { P as PGliteInterface } from '../interface-Db0XLAWB.js';
import { a as PGliteInterface } from '../interface-BChI4DHV.js';
import '@electric-sql/pg-protocol/messages';
import '../types-CQTnnKLt.js';
import '../types-XE-2t5ub.js';

@@ -5,0 +5,0 @@ declare const bloom: {

@@ -1,4 +0,4 @@

import { P as PGliteInterface } from '../interface-Db0XLAWB.js';
import { a as PGliteInterface } from '../interface-BChI4DHV.js';
import '@electric-sql/pg-protocol/messages';
import '../types-CQTnnKLt.js';
import '../types-XE-2t5ub.js';

@@ -5,0 +5,0 @@ declare const btree_gin: {

@@ -1,4 +0,4 @@

import { P as PGliteInterface } from '../interface-Db0XLAWB.js';
import { a as PGliteInterface } from '../interface-BChI4DHV.js';
import '@electric-sql/pg-protocol/messages';
import '../types-CQTnnKLt.js';
import '../types-XE-2t5ub.js';

@@ -5,0 +5,0 @@ declare const btree_gist: {

@@ -1,4 +0,4 @@

import { P as PGliteInterface } from '../interface-Db0XLAWB.js';
import { a as PGliteInterface } from '../interface-BChI4DHV.js';
import '@electric-sql/pg-protocol/messages';
import '../types-CQTnnKLt.js';
import '../types-XE-2t5ub.js';

@@ -5,0 +5,0 @@ declare const citext: {

@@ -1,4 +0,4 @@

import { P as PGliteInterface } from '../interface-Db0XLAWB.js';
import { a as PGliteInterface } from '../interface-BChI4DHV.js';
import '@electric-sql/pg-protocol/messages';
import '../types-CQTnnKLt.js';
import '../types-XE-2t5ub.js';

@@ -5,0 +5,0 @@ declare const cube: {

@@ -1,4 +0,4 @@

import { P as PGliteInterface } from '../interface-Db0XLAWB.js';
import { a as PGliteInterface } from '../interface-BChI4DHV.js';
import '@electric-sql/pg-protocol/messages';
import '../types-CQTnnKLt.js';
import '../types-XE-2t5ub.js';

@@ -5,0 +5,0 @@ declare const earthdistance: {

@@ -1,4 +0,4 @@

import { P as PGliteInterface } from '../interface-Db0XLAWB.js';
import { a as PGliteInterface } from '../interface-BChI4DHV.js';
import '@electric-sql/pg-protocol/messages';
import '../types-CQTnnKLt.js';
import '../types-XE-2t5ub.js';

@@ -5,0 +5,0 @@ declare const fuzzystrmatch: {

@@ -1,4 +0,4 @@

import { P as PGliteInterface } from '../interface-Db0XLAWB.js';
import { a as PGliteInterface } from '../interface-BChI4DHV.js';
import '@electric-sql/pg-protocol/messages';
import '../types-CQTnnKLt.js';
import '../types-XE-2t5ub.js';

@@ -5,0 +5,0 @@ declare const hstore: {

@@ -1,4 +0,4 @@

import { P as PGliteInterface } from '../interface-Db0XLAWB.js';
import { a as PGliteInterface } from '../interface-BChI4DHV.js';
import '@electric-sql/pg-protocol/messages';
import '../types-CQTnnKLt.js';
import '../types-XE-2t5ub.js';

@@ -5,0 +5,0 @@ declare const isn: {

@@ -1,4 +0,4 @@

import { P as PGliteInterface } from '../interface-Db0XLAWB.js';
import { a as PGliteInterface } from '../interface-BChI4DHV.js';
import '@electric-sql/pg-protocol/messages';
import '../types-CQTnnKLt.js';
import '../types-XE-2t5ub.js';

@@ -5,0 +5,0 @@ declare const lo: {

@@ -1,4 +0,4 @@

import { P as PGliteInterface } from '../interface-Db0XLAWB.js';
import { a as PGliteInterface } from '../interface-BChI4DHV.js';
import '@electric-sql/pg-protocol/messages';
import '../types-CQTnnKLt.js';
import '../types-XE-2t5ub.js';

@@ -5,0 +5,0 @@ declare const ltree: {

@@ -1,4 +0,4 @@

import { P as PGliteInterface } from '../interface-Db0XLAWB.js';
import { a as PGliteInterface } from '../interface-BChI4DHV.js';
import '@electric-sql/pg-protocol/messages';
import '../types-CQTnnKLt.js';
import '../types-XE-2t5ub.js';

@@ -5,0 +5,0 @@ declare const pg_trgm: {

@@ -1,4 +0,4 @@

import { P as PGliteInterface } from '../interface-Db0XLAWB.js';
import { a as PGliteInterface } from '../interface-BChI4DHV.js';
import '@electric-sql/pg-protocol/messages';
import '../types-CQTnnKLt.js';
import '../types-XE-2t5ub.js';

@@ -5,0 +5,0 @@ declare const seg: {

@@ -1,4 +0,4 @@

import { P as PGliteInterface } from '../interface-Db0XLAWB.js';
import { a as PGliteInterface } from '../interface-BChI4DHV.js';
import '@electric-sql/pg-protocol/messages';
import '../types-CQTnnKLt.js';
import '../types-XE-2t5ub.js';

@@ -5,0 +5,0 @@ declare const tablefunc: {

@@ -1,4 +0,4 @@

import { P as PGliteInterface } from '../interface-Db0XLAWB.js';
import { a as PGliteInterface } from '../interface-BChI4DHV.js';
import '@electric-sql/pg-protocol/messages';
import '../types-CQTnnKLt.js';
import '../types-XE-2t5ub.js';

@@ -5,0 +5,0 @@ declare const tcn: {

@@ -1,4 +0,4 @@

import { P as PGliteInterface } from '../interface-Db0XLAWB.js';
import { a as PGliteInterface } from '../interface-BChI4DHV.js';
import '@electric-sql/pg-protocol/messages';
import '../types-CQTnnKLt.js';
import '../types-XE-2t5ub.js';

@@ -5,0 +5,0 @@ declare const tsm_system_rows: {

@@ -1,4 +0,4 @@

import { P as PGliteInterface } from '../interface-Db0XLAWB.js';
import { a as PGliteInterface } from '../interface-BChI4DHV.js';
import '@electric-sql/pg-protocol/messages';
import '../types-CQTnnKLt.js';
import '../types-XE-2t5ub.js';

@@ -5,0 +5,0 @@ declare const tsm_system_time: {

@@ -1,4 +0,4 @@

import { P as PGliteInterface } from '../interface-Db0XLAWB.js';
import { a as PGliteInterface } from '../interface-BChI4DHV.js';
import '@electric-sql/pg-protocol/messages';
import '../types-CQTnnKLt.js';
import '../types-XE-2t5ub.js';

@@ -5,0 +5,0 @@ declare const uuid_ossp: {

@@ -1,2 +0,2 @@

import { a as FilesystemBase, P as PostgresMod, b as FS, D as DumpTarCompressionOptions } from '../types-CQTnnKLt.js';
import { F as FilesystemBase, P as PostgresMod, a as FS, D as DumpTarCompressionOptions } from '../types-XE-2t5ub.js';

@@ -3,0 +3,0 @@ declare class NodeFS extends FilesystemBase {

@@ -1,2 +0,2 @@

import { a as FilesystemBase, P as PostgresMod, b as FS, D as DumpTarCompressionOptions } from '../../types-CQTnnKLt.js';
import { F as FilesystemBase, P as PostgresMod, a as FS, D as DumpTarCompressionOptions } from '../../types-XE-2t5ub.js';

@@ -3,0 +3,0 @@ type FsStats = {

@@ -1,4 +0,4 @@

import { F as Filesystem, P as PostgresMod, D as DumpTarCompressionOptions, a as FilesystemBase, b as FS } from './types-CQTnnKLt.js';
import { P as PGliteInterface, D as DebugLevel, a as PGliteOptions, b as PGliteInterfaceExtensions, Q as QueryOptions, R as Results, T as Transaction, E as ExecProtocolOptions, c as ParserOptions } from './interface-Db0XLAWB.js';
export { i as DumpDataDirResult, g as Extension, f as ExtensionSetup, e as ExtensionSetupResult, h as Extensions, F as FilesystemType, j as Row, d as RowMode } from './interface-Db0XLAWB.js';
export { P as PGlite } from './pglite-Dh_uQEOE.js';
import { P as ParserOptions, Q as QueryOptions, R as Results, a as PGliteInterface, T as Transaction } from './interface-BChI4DHV.js';
export { D as DebugLevel, g as DumpDataDirResult, E as ExecProtocolOptions, e as Extension, d as ExtensionSetup, c as ExtensionSetupResult, f as Extensions, F as FilesystemType, i as PGliteInterfaceExtensions, h as PGliteOptions, j as Row, b as RowMode } from './interface-BChI4DHV.js';
import { BackendMessage } from '@electric-sql/pg-protocol/messages';

@@ -8,152 +8,4 @@ import * as messages from '@electric-sql/pg-protocol/messages';

import { B, a, m } from './messages-CaXcfh5Z.js';
import { F as FilesystemBase, P as PostgresMod, a as FS, D as DumpTarCompressionOptions } from './types-XE-2t5ub.js';
declare class PGlite implements PGliteInterface, AsyncDisposable {
#private;
fs?: Filesystem;
protected mod?: PostgresMod;
readonly dataDir?: string;
readonly waitReady: Promise<void>;
readonly debug: DebugLevel;
/**
* Create a new PGlite instance
* @param dataDir The directory to store the database files
* Prefix with idb:// to use indexeddb filesystem in the browser
* Use memory:// to use in-memory filesystem
* @param options PGlite options
*/
constructor(dataDir?: string, options?: PGliteOptions);
/**
* Create a new PGlite instance
* @param options PGlite options including the data directory
*/
constructor(options?: PGliteOptions);
/**
* Create a new PGlite instance with extensions on the Typescript interface
* (The main constructor does enable extensions, however due to the limitations
* of Typescript, the extensions are not available on the instance interface)
* @param options PGlite options including the data directory
* @returns A promise that resolves to the PGlite instance when it's ready.
*/
static create<O extends PGliteOptions>(options?: O): Promise<PGlite & PGliteInterfaceExtensions<O['extensions']>>;
/**
* Create a new PGlite instance with extensions on the Typescript interface
* (The main constructor does enable extensions, however due to the limitations
* of Typescript, the extensions are not available on the instance interface)
* @param dataDir The directory to store the database files
* Prefix with idb:// to use indexeddb filesystem in the browser
* Use memory:// to use in-memory filesystem
* @param options PGlite options
* @returns A promise that resolves to the PGlite instance when it's ready.
*/
static create<O extends PGliteOptions>(dataDir?: string, options?: O): Promise<PGlite & PGliteInterfaceExtensions<O['extensions']>>;
/**
* The Postgres Emscripten Module
*/
get Module(): PostgresMod;
/**
* The ready state of the database
*/
get ready(): boolean;
/**
* The closed state of the database
*/
get closed(): boolean;
/**
* Close the database
* @returns A promise that resolves when the database is closed
*/
close(): Promise<void>;
/**
* Close the database when the object exits scope
* Stage 3 ECMAScript Explicit Resource Management
* https://www.typescriptlang.org/docs/handbook/release-notes/typescript-5-2.html#using-declarations-and-explicit-resource-management
*/
[Symbol.asyncDispose](): Promise<void>;
/**
* Execute a single SQL statement
* This uses the "Extended Query" postgres wire protocol message.
* @param query The query to execute
* @param params Optional parameters for the query
* @returns The result of the query
*/
query<T>(query: string, params?: any[], options?: QueryOptions): Promise<Results<T>>;
/**
* Execute a single SQL statement like with {@link PGlite.query}, but with a
* templated statement where template values will be treated as parameters.
*
* You can use helpers from `/template` to further format the query with
* identifiers, raw SQL, and nested statements.
*
* This uses the "Extended Query" postgres wire protocol message.
*
* @param query The query to execute with parameters as template values
* @returns The result of the query
*
* @example
* ```ts
* const results = await db.sql`SELECT * FROM ${identifier`foo`} WHERE id = ${id}`
* ```
*/
sql<T>(sqlStrings: TemplateStringsArray, ...params: any[]): Promise<Results<T>>;
/**
* Execute a SQL query, this can have multiple statements.
* This uses the "Simple Query" postgres wire protocol message.
* @param query The query to execute
* @returns The result of the query
*/
exec(query: string, options?: QueryOptions): Promise<Array<Results>>;
/**
* Execute a transaction
* @param callback A callback function that takes a transaction object
* @returns The result of the transaction
*/
transaction<T>(callback: (tx: Transaction) => Promise<T>): Promise<T | undefined>;
/**
* Execute a postgres wire protocol message directly without wrapping the response.
* Only use if `execProtocol()` doesn't suite your needs.
*
* **Warning:** This bypasses PGlite's protocol wrappers that manage error/notice messages,
* transactions, and notification listeners. Only use if you need to bypass these wrappers and
* don't intend to use the above features.
*
* @param message The postgres wire protocol message to execute
* @returns The direct message data response produced by Postgres
*/
execProtocolRaw(message: Uint8Array, { syncToFs }?: ExecProtocolOptions): Promise<Uint8Array>;
/**
* Execute a postgres wire protocol message
* @param message The postgres wire protocol message to execute
* @returns The result of the query
*/
execProtocol(message: Uint8Array, { syncToFs, onNotice }?: ExecProtocolOptions): Promise<Array<[BackendMessage, Uint8Array]>>;
/**
* Listen for a notification
* @param channel The channel to listen on
* @param callback The callback to call when a notification is received
*/
listen(channel: string, callback: (payload: string) => void): Promise<() => Promise<void>>;
/**
* Stop listening for a notification
* @param channel The channel to stop listening on
* @param callback The callback to remove
*/
unlisten(channel: string, callback?: (payload: string) => void): Promise<void>;
/**
* Listen to notifications
* @param callback The callback to call when a notification is received
*/
onNotification(callback: (channel: string, payload: string) => void): () => void;
/**
* Stop listening to notifications
* @param callback The callback to remove
*/
offNotification(callback: (channel: string, payload: string) => void): void;
/**
* Dump the PGDATA dir from the filesystem to a gziped tarball.
* @param compression The compression options to use - 'gzip', 'auto', 'none'
* @returns The tarball as a File object where available, and fallback to a Blob
*/
dumpDataDir(compression?: DumpTarCompressionOptions): Promise<File | Blob>;
}
declare const BOOL = 16;

@@ -505,2 +357,2 @@ declare const BYTEA = 17;

export { DebugLevel, ExecProtocolOptions, IdbFs, MemoryFS, Mutex, PGlite, PGliteInterface, PGliteInterfaceExtensions, PGliteOptions, ParserOptions, QueryOptions, Results, Transaction, formatQuery, parse, index_d as protocol, types$1 as types, uuid };
export { IdbFs, MemoryFS, Mutex, PGliteInterface, ParserOptions, QueryOptions, Results, Transaction, formatQuery, parse, index_d as protocol, types$1 as types, uuid };

@@ -1,2 +0,2 @@

import{b as xs,d as kt,e as Ss,f as Ps,g as at,h as Ge,i as Ut,j as Lt}from"./chunk-SJVDOE3S.js";import{d as ot}from"./chunk-TAZBUB4Z.js";import{a as Nt,b as Gt,c as vs,d as Rs}from"./chunk-3BCYDNSE.js";import{b as Ne,c as Ts,d as f,e as x,f as P,g as p,i as b}from"./chunk-Y3AVQXKT.js";b();b();b();var ri=new Error("timeout while waiting for mutex to become available"),ii=new Error("mutex already locked"),Ds=new Error("request for lock canceled"),Is=function(t,e,s,r){function i(a){return a instanceof s?a:new s(function(l){l(a)})}return new(s||(s=Promise))(function(a,l){function o(d){try{c(r.next(d))}catch(A){l(A)}}function y(d){try{c(r.throw(d))}catch(A){l(A)}}function c(d){d.done?a(d.value):i(d.value).then(o,y)}c((r=r.apply(t,e||[])).next())})},lt=class{constructor(e,s=Ds){this._value=e,this._cancelError=s,this._weightedQueues=[],this._weightedWaiters=[]}acquire(e=1){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);return new Promise((s,r)=>{this._weightedQueues[e-1]||(this._weightedQueues[e-1]=[]),this._weightedQueues[e-1].push({resolve:s,reject:r}),this._dispatch()})}runExclusive(e,s=1){return Is(this,void 0,void 0,function*(){let[r,i]=yield this.acquire(s);try{return yield e(r)}finally{i()}})}waitForUnlock(e=1){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);return new Promise(s=>{this._weightedWaiters[e-1]||(this._weightedWaiters[e-1]=[]),this._weightedWaiters[e-1].push(s),this._dispatch()})}isLocked(){return this._value<=0}getValue(){return this._value}setValue(e){this._value=e,this._dispatch()}release(e=1){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);this._value+=e,this._dispatch()}cancel(){this._weightedQueues.forEach(e=>e.forEach(s=>s.reject(this._cancelError))),this._weightedQueues=[]}_dispatch(){var e;for(let s=this._value;s>0;s--){let r=(e=this._weightedQueues[s-1])===null||e===void 0?void 0:e.shift();if(!r)continue;let i=this._value,a=s;this._value-=s,s=this._value+1,r.resolve([i,this._newReleaser(a)])}this._drainUnlockWaiters()}_newReleaser(e){let s=!1;return()=>{s||(s=!0,this.release(e))}}_drainUnlockWaiters(){for(let e=this._value;e>0;e--)this._weightedWaiters[e-1]&&(this._weightedWaiters[e-1].forEach(s=>s()),this._weightedWaiters[e-1]=[])}},Ms=function(t,e,s,r){function i(a){return a instanceof s?a:new s(function(l){l(a)})}return new(s||(s=Promise))(function(a,l){function o(d){try{c(r.next(d))}catch(A){l(A)}}function y(d){try{c(r.throw(d))}catch(A){l(A)}}function c(d){d.done?a(d.value):i(d.value).then(o,y)}c((r=r.apply(t,e||[])).next())})},$=class{constructor(e){this._semaphore=new lt(1,e)}acquire(){return Ms(this,void 0,void 0,function*(){let[,e]=yield this._semaphore.acquire();return e})}runExclusive(e){return this._semaphore.runExclusive(()=>e())}isLocked(){return this._semaphore.isLocked()}waitForUnlock(){return this._semaphore.waitForUnlock()}release(){this._semaphore.isLocked()&&this._semaphore.release()}cancel(){return this._semaphore.cancel()}};b();import Os from"./postgres.js";var qt=Os;var Xt={};Ne(Xt,{parseResults:()=>Ye});b();var Wt={};Ne(Wt,{AuthenticationCleartextPassword:()=>ge,AuthenticationMD5Password:()=>we,AuthenticationOk:()=>me,AuthenticationSASL:()=>be,AuthenticationSASLContinue:()=>Ee,AuthenticationSASLFinal:()=>Ae,BackendKeyDataMessage:()=>Re,CommandCompleteMessage:()=>k,CopyDataMessage:()=>Te,CopyResponse:()=>xe,DataRowMessage:()=>z,DatabaseError:()=>G,Field:()=>Se,NoticeMessage:()=>K,NotificationResponseMessage:()=>H,ParameterDescriptionMessage:()=>Pe,ParameterStatusMessage:()=>ve,ReadyForQueryMessage:()=>De,RowDescriptionMessage:()=>q,bindComplete:()=>ce,closeComplete:()=>ue,copyDone:()=>ye,emptyQuery:()=>pe,noData:()=>he,parseComplete:()=>le,portalSuspended:()=>fe,replicationStart:()=>de});b();b();var _s=Object.defineProperty,zt=t=>{throw TypeError(t)},Cs=(t,e)=>{for(var s in e)_s(t,s,{get:e[s],enumerable:!0})},ct=(t,e,s)=>e.has(t)||zt("Cannot "+s),n=(t,e,s)=>(ct(t,e,"read from private field"),s?s.call(t):e.get(t)),v=(t,e,s)=>e.has(t)?zt("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,s),g=(t,e,s,r)=>(ct(t,e,"write to private field"),r?r.call(t,s):e.set(t,s),s),m=(t,e,s)=>(ct(t,e,"access private method"),s),ut=(t,e,s,r)=>({set _(i){g(t,e,i,s)},get _(){return n(t,e,r)}}),ht={};Cs(ht,{AuthenticationCleartextPassword:()=>ge,AuthenticationMD5Password:()=>we,AuthenticationOk:()=>me,AuthenticationSASL:()=>be,AuthenticationSASLContinue:()=>Ee,AuthenticationSASLFinal:()=>Ae,BackendKeyDataMessage:()=>Re,CommandCompleteMessage:()=>k,CopyDataMessage:()=>Te,CopyResponse:()=>xe,DataRowMessage:()=>z,DatabaseError:()=>G,Field:()=>Se,NoticeMessage:()=>K,NotificationResponseMessage:()=>H,ParameterDescriptionMessage:()=>Pe,ParameterStatusMessage:()=>ve,ReadyForQueryMessage:()=>De,RowDescriptionMessage:()=>q,bindComplete:()=>ce,closeComplete:()=>ue,copyDone:()=>ye,emptyQuery:()=>pe,noData:()=>he,parseComplete:()=>le,portalSuspended:()=>fe,replicationStart:()=>de});var le={name:"parseComplete",length:5},ce={name:"bindComplete",length:5},ue={name:"closeComplete",length:5},he={name:"noData",length:5},fe={name:"portalSuspended",length:5},de={name:"replicationStart",length:4},pe={name:"emptyQuery",length:4},ye={name:"copyDone",length:4},me=class{constructor(t){this.length=t,this.name="authenticationOk"}},ge=class{constructor(t){this.length=t,this.name="authenticationCleartextPassword"}},we=class{constructor(t,e){this.length=t,this.salt=e,this.name="authenticationMD5Password"}},be=class{constructor(t,e){this.length=t,this.mechanisms=e,this.name="authenticationSASL"}},Ee=class{constructor(t,e){this.length=t,this.data=e,this.name="authenticationSASLContinue"}},Ae=class{constructor(t,e){this.length=t,this.data=e,this.name="authenticationSASLFinal"}},G=class extends Error{constructor(t,e,s){super(t),this.length=e,this.name=s}},Te=class{constructor(t,e){this.length=t,this.chunk=e,this.name="copyData"}},xe=class{constructor(t,e,s,r){this.length=t,this.name=e,this.binary=s,this.columnTypes=new Array(r)}},Se=class{constructor(t,e,s,r,i,a,l){this.name=t,this.tableID=e,this.columnID=s,this.dataTypeID=r,this.dataTypeSize=i,this.dataTypeModifier=a,this.format=l}},q=class{constructor(t,e){this.length=t,this.fieldCount=e,this.name="rowDescription",this.fields=new Array(this.fieldCount)}},Pe=class{constructor(t,e){this.length=t,this.parameterCount=e,this.name="parameterDescription",this.dataTypeIDs=new Array(this.parameterCount)}},ve=class{constructor(t,e,s){this.length=t,this.parameterName=e,this.parameterValue=s,this.name="parameterStatus"}},Re=class{constructor(t,e,s){this.length=t,this.processID=e,this.secretKey=s,this.name="backendKeyData"}},H=class{constructor(t,e,s,r){this.length=t,this.processId=e,this.channel=s,this.payload=r,this.name="notification"}},De=class{constructor(t,e){this.length=t,this.status=e,this.name="readyForQuery"}},k=class{constructor(t,e){this.length=t,this.text=e,this.name="commandComplete"}},z=class{constructor(t,e){this.length=t,this.fields=e,this.name="dataRow",this.fieldCount=e.length}},K=class{constructor(t,e){this.length=t,this.message=e,this.name="notice"}};var Yt={};Ne(Yt,{ABSTIME:()=>js,ACLITEM:()=>er,BIT:()=>nr,BOOL:()=>ft,BPCHAR:()=>tr,BYTEA:()=>We,CHAR:()=>Qt,CID:()=>Ns,CIDR:()=>Vs,CIRCLE:()=>Ks,DATE:()=>wt,FLOAT4:()=>mt,FLOAT8:()=>je,GTSVECTOR:()=>Ar,INET:()=>Zs,INT2:()=>dt,INT4:()=>pt,INT8:()=>Ie,INTERVAL:()=>rr,JSON:()=>Ve,JSONB:()=>At,MACADDR:()=>Js,MACADDR8:()=>Ys,MONEY:()=>Xs,NUMERIC:()=>or,OID:()=>yt,PATH:()=>Ws,PG_DEPENDENCIES:()=>wr,PG_LSN:()=>mr,PG_NDISTINCT:()=>gr,PG_NODE_TREE:()=>qs,POLYGON:()=>Qs,REFCURSOR:()=>lr,REGCLASS:()=>fr,REGCONFIG:()=>Tr,REGDICTIONARY:()=>xr,REGNAMESPACE:()=>Sr,REGOPER:()=>ur,REGOPERATOR:()=>hr,REGPROC:()=>ks,REGPROCEDURE:()=>cr,REGROLE:()=>Pr,REGTYPE:()=>dr,RELTIME:()=>$s,SMGR:()=>zs,TEXT:()=>Qe,TID:()=>Us,TIME:()=>sr,TIMESTAMP:()=>bt,TIMESTAMPTZ:()=>Et,TIMETZ:()=>ir,TINTERVAL:()=>Hs,TSQUERY:()=>Er,TSVECTOR:()=>br,TXID_SNAPSHOT:()=>yr,UUID:()=>pr,VARBIT:()=>ar,VARCHAR:()=>gt,XID:()=>Ls,XML:()=>Gs,arrayTypes:()=>qe,parseArray:()=>Kt,parseType:()=>Ke,parsers:()=>Vt,serializeType:()=>He,serializerFor:()=>$t,serializerInstanceof:()=>jt,serializers:()=>ze,types:()=>Tt});b();var Fs=globalThis.JSON.parse,Bs=globalThis.JSON.stringify,ft=16,We=17,Qt=18,Ie=20,dt=21,pt=23,ks=24,Qe=25,yt=26,Us=27,Ls=28,Ns=29,Ve=114,Gs=142,qs=194,zs=210,Ws=602,Qs=604,Vs=650,mt=700,je=701,js=702,$s=703,Hs=704,Ks=718,Ys=774,Xs=790,Js=829,Zs=869,er=1033,tr=1042,gt=1043,wt=1082,sr=1083,bt=1114,Et=1184,rr=1186,ir=1266,nr=1560,ar=1562,or=1700,lr=1790,cr=2202,ur=2203,hr=2204,fr=2205,dr=2206,pr=2950,yr=2970,mr=3220,gr=3361,wr=3402,br=3614,Er=3615,Ar=3642,Tr=3734,xr=3769,At=3802,Sr=4089,Pr=4096,qe={1001:We,1002:Qt,1016:Ie,1005:dt,1007:pt,1009:Qe,1028:yt,199:Ve,1021:mt,1022:je,1015:gt,3807:At,1182:wt,1115:bt,1116:Et},Tt={string:{to:0,from:[Qe,gt],serialize:t=>t,parse:t=>t,forceTo:Qe},number:{to:0,from:[dt,pt,yt,mt,je],serialize:t=>t.toString(),parse:t=>+t,forceTo:t=>Number.isInteger(t)?Ie:je},bigint:{to:Ie,from:[Ie],js:[BigInt],serialize:t=>t.toString(),parse:t=>{let e=BigInt(t);return e<Number.MIN_SAFE_INTEGER||e>Number.MAX_SAFE_INTEGER?e:Number(e)}},json:{to:Ve,from:[Ve,At],serialize:t=>Bs(t),parse:t=>Fs(t)},boolean:{to:ft,from:[ft],serialize:t=>t===!0?"t":"f",parse:t=>t==="t"},date:{to:1184,from:[wt,bt,Et],js:[Date],serialize:t=>(t instanceof Date?t:new Date(t)).toISOString(),parse:t=>new Date(t)},bytea:{to:We,from:[We],js:[Uint8Array],serialize:t=>"\\x"+Array.from(t).map(e=>e.toString(16).padStart(2,"0")).join(""),parse:t=>{let e=t.slice(2);return Uint8Array.from({length:e.length/2},(s,r)=>parseInt(e.substring(r*2,(r+1)*2),16))}},array:{to:0,from:Object.keys(qe).map(t=>+t),serialize:t=>Ht(t),parse:(t,e)=>{let s;return e&&e in qe&&(s=Vt[qe[e]]),Kt(t,s)}}},$e=Rr(Tt),Vt=$e.parsers,ze=$e.serializers,jt=$e.serializerInstanceof;function $t(t){if(Array.isArray(t))return ze.array;let e=ze[typeof t];if(e)return e;for(let[s,r]of jt)if(t instanceof s)return r;return ze.json}function He(t,e=!1){return t==null?[null,0]:$t(t)(t,e)}function vr(t){return'"'+t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')+'"'}function Ht(t){let e="{";for(let s=0;s<t.length;s++)if(s>0&&(e=e+","),t[s]===null||typeof t[s]>"u")e=e+"NULL";else if(Array.isArray(t[s]))e=e+Ht(t[s]);else if(ArrayBuffer.isView(t[s])||t[s]instanceof ArrayBuffer){let r=ArrayBuffer.isView(t[s])?new Uint8Array(t[s].buffer,t[s].byteOffset,t[s].byteLength):new Uint8Array(t[s]);e+="\\"+Tt.bytea.serialize(r)}else e+=vr(He(t[s])[0]);return e=e+"}",e}function Kt(t,e){let s=0,r=null,i="",a=!1,l=0,o;function y(c){let d=[];for(;s<c.length;s++){if(r=c[s],a)r==="\\"?i+=c[++s]:r==='"'?(d.push(e?e(i):i),i="",a=c[s+1]==='"',l=s+2):i+=r;else if(r==='"')a=!0;else if(r==="{")l=++s,d.push(y(c));else if(r==="}"){a=!1,l<s&&d.push(e?e(c.slice(l,s)):c.slice(l,s)),l=s+1;break}else r===","&&o!=="}"&&o!=='"'&&(d.push(e?e(c.slice(l,s)):c.slice(l,s)),l=s+1);o=r}return l<s&&d.push(e?e(c.slice(l,s+1)):c.slice(l,s+1)),d}return y(t)[0]}function Ke(t,e,s){if(t===null)return null;let r=s?.[e]??$e.parsers[e];return r?r(t,e):t}function Rr(t){return Object.keys(t).reduce(({parsers:e,serializers:s,serializerInstanceof:r},i)=>{let{to:a,from:l,serialize:o,parse:y=null,forceTo:c}=t[i],d=(A,L=!1)=>[o(A),L&&c?typeof c=="function"?c(A):c:a];return s[a]=d,s[i]=d,t[i].js&&t[i].js.forEach(A=>r.push([A,d])),y&&(Array.isArray(l)?l.forEach(A=>e[A]=y):e[l]=y,e[i]=y),{parsers:e,serializers:s,serializerInstanceof:r}},{parsers:{},serializers:{},serializerInstanceof:[]})}function Ye(t,e,s){let r=[],i={rows:[],fields:[]},a=0,l=t.filter(o=>o instanceof q||o instanceof z||o instanceof k);return l.forEach((o,y)=>{o instanceof q?i.fields=o.fields.map(c=>({name:c.name,dataTypeID:c.dataTypeID})):o instanceof z&&i?e?.rowMode==="array"?i.rows.push(o.fields.map((c,d)=>Ke(c,i.fields[d].dataTypeID,e?.parsers))):i.rows.push(Object.fromEntries(o.fields.map((c,d)=>[i.fields[d].name,Ke(c,i.fields[d].dataTypeID,e?.parsers)]))):o instanceof k&&(a+=Dr(o),y===l.length-1?r.push({...i,affectedRows:a,...s?{blob:s}:{}}):r.push(i),i={rows:[],fields:[]})}),r.length===0&&r.push({rows:[],fields:[]}),r}function Dr(t){let e=t.text.split(" ");switch(e[0]){case"INSERT":return parseInt(e[2],10);case"UPDATE":case"DELETE":return parseInt(e[1],10);default:return 0}}b();var Jt=Ts(xs(),1);async function xt(t){if(Nt){let e=await import("fs"),s=await import("zlib"),{Writable:r}=await import("stream"),{pipeline:i}=await import("stream/promises");if(!e.existsSync(t))throw new Error(`Extension bundle not found: ${t}`);let a=s.createGunzip(),l=[];return await i(e.createReadStream(t),a,new r({write(o,y,c){l.push(o),c()}})),new Blob(l)}else{let e=await fetch(t.toString());if(!e.ok||!e.body)return null;if(e.headers.get("Content-Encoding")==="gzip")return e.blob();{let s=new DecompressionStream("gzip");return new Response(e.body.pipeThrough(s)).blob()}}}async function Zt(t,e){for(let s in t.pg_extensions){let r;try{r=await t.pg_extensions[s]}catch(i){console.error("Failed to fetch extension:",s,i);continue}if(r){let i=new Uint8Array(await r.arrayBuffer());Ir(t,s,i,e)}else console.error("Could not get binary data for extension:",s)}}function Ir(t,e,s,r){Jt.default.untar(s).forEach(a=>{if(!a.name.startsWith(".")){let l=t.WASM_PREFIX+"/"+a.name;if(a.name.endsWith(".so")){let o=(...c)=>{r("pgfs:ext OK",l,c)},y=(...c)=>{r("pgfs:ext FAIL",l,c)};t.FS.createPreloadedFile(Mr(l),a.name.split("/").pop().slice(0,-3),a.data,!0,!0,o,y,!1)}else t.FS.writeFile(l,a.data)}})}function Mr(t){let e=t.lastIndexOf("/");return e>0?t.slice(0,e):t}var bs={};Ne(bs,{Parser:()=>st,messages:()=>ht,serialize:()=>U});b();function Ze(t){let e=t.length;for(let s=t.length-1;s>=0;s--){let r=t.charCodeAt(s);r>127&&r<=2047?e++:r>2047&&r<=65535&&(e+=2),r>=56320&&r<=57343&&s--}return e}var R,T,Oe,vt,Me,O,Je,se,ms,et=class{constructor(t=256){this.size=t,v(this,O),v(this,R),v(this,T,5),v(this,Oe,!1),v(this,vt,new TextEncoder),v(this,Me,0),g(this,R,m(this,O,Je).call(this,t))}addInt32(t){return m(this,O,se).call(this,4),n(this,R).setInt32(n(this,T),t,n(this,Oe)),g(this,T,n(this,T)+4),this}addInt16(t){return m(this,O,se).call(this,2),n(this,R).setInt16(n(this,T),t,n(this,Oe)),g(this,T,n(this,T)+2),this}addCString(t){return t&&this.addString(t),m(this,O,se).call(this,1),n(this,R).setUint8(n(this,T),0),ut(this,T)._++,this}addString(t=""){let e=Ze(t);return m(this,O,se).call(this,e),n(this,vt).encodeInto(t,new Uint8Array(n(this,R).buffer,n(this,T))),g(this,T,n(this,T)+e),this}add(t){return m(this,O,se).call(this,t.byteLength),new Uint8Array(n(this,R).buffer).set(new Uint8Array(t),n(this,T)),g(this,T,n(this,T)+t.byteLength),this}flush(t){let e=m(this,O,ms).call(this,t);return g(this,T,5),g(this,R,m(this,O,Je).call(this,this.size)),new Uint8Array(e)}};R=new WeakMap,T=new WeakMap,Oe=new WeakMap,vt=new WeakMap,Me=new WeakMap,O=new WeakSet,Je=function(t){return new DataView(new ArrayBuffer(t))},se=function(t){if(n(this,R).byteLength-n(this,T)<t){let e=n(this,R).buffer,s=e.byteLength+(e.byteLength>>1)+t;g(this,R,m(this,O,Je).call(this,s)),new Uint8Array(n(this,R).buffer).set(new Uint8Array(e))}},ms=function(t){if(t){n(this,R).setUint8(n(this,Me),t);let e=n(this,T)-(n(this,Me)+1);n(this,R).setInt32(n(this,Me)+1,e,n(this,Oe))}return n(this,R).buffer.slice(t?0:5,n(this,T))};var w=new et,Or=t=>{w.addInt16(3).addInt16(0);for(let r of Object.keys(t))w.addCString(r).addCString(t[r]);w.addCString("client_encoding").addCString("UTF8");let e=w.addCString("").flush(),s=e.byteLength+4;return new et().addInt32(s).add(e).flush()},_r=()=>{let t=new DataView(new ArrayBuffer(8));return t.setInt32(0,8,!1),t.setInt32(4,80877103,!1),new Uint8Array(t.buffer)},Cr=t=>w.addCString(t).flush(112),Fr=(t,e)=>(w.addCString(t).addInt32(Ze(e)).addString(e),w.flush(112)),Br=t=>w.addString(t).flush(112),kr=t=>w.addCString(t).flush(81),Ur=[],Lr=t=>{let e=t.name??"";e.length>63&&(console.error("Warning! Postgres only supports 63 characters for query names."),console.error("You supplied %s (%s)",e,e.length),console.error("This can cause conflicts and silent errors executing queries"));let s=w.addCString(e).addCString(t.text).addInt16(t.types?.length??0);return t.types?.forEach(r=>s.addInt32(r)),w.flush(80)},re=new et,Nr=(t,e)=>{for(let s=0;s<t.length;s++){let r=e?e(t[s],s):t[s];if(r===null)w.addInt16(0),re.addInt32(-1);else if(r instanceof ArrayBuffer||ArrayBuffer.isView(r)){let i=ArrayBuffer.isView(r)?r.buffer.slice(r.byteOffset,r.byteOffset+r.byteLength):r;w.addInt16(1),re.addInt32(i.byteLength),re.add(i)}else w.addInt16(0),re.addInt32(Ze(r)),re.addString(r)}},Gr=(t={})=>{let e=t.portal??"",s=t.statement??"",r=t.binary??!1,i=t.values??Ur,a=i.length;return w.addCString(e).addCString(s),w.addInt16(a),Nr(i,t.valueMapper),w.addInt16(a),w.add(re.flush()),w.addInt16(r?1:0),w.flush(66)},qr=new Uint8Array([69,0,0,0,9,0,0,0,0,0]),zr=t=>{if(!t||!t.portal&&!t.rows)return qr;let e=t.portal??"",s=t.rows??0,r=Ze(e),i=4+r+1+4,a=new DataView(new ArrayBuffer(1+i));return a.setUint8(0,69),a.setInt32(1,i,!1),new TextEncoder().encodeInto(e,new Uint8Array(a.buffer,5)),a.setUint8(r+5,0),a.setUint32(a.byteLength-4,s,!1),new Uint8Array(a.buffer)},Wr=(t,e)=>{let s=new DataView(new ArrayBuffer(16));return s.setInt32(0,16,!1),s.setInt16(4,1234,!1),s.setInt16(6,5678,!1),s.setInt32(8,t,!1),s.setInt32(12,e,!1),new Uint8Array(s.buffer)},Mt=(t,e)=>{let s=new et;return s.addCString(e),s.flush(t)},Qr=w.addCString("P").flush(68),Vr=w.addCString("S").flush(68),jr=t=>t.name?Mt(68,`${t.type}${t.name??""}`):t.type==="P"?Qr:Vr,$r=t=>{let e=`${t.type}${t.name??""}`;return Mt(67,e)},Hr=t=>w.add(t).flush(100),Kr=t=>Mt(102,t),tt=t=>new Uint8Array([t,0,0,0,4]),Yr=tt(72),Xr=tt(83),Jr=tt(88),Zr=tt(99),U={startup:Or,password:Cr,requestSsl:_r,sendSASLInitialResponseMessage:Fr,sendSCRAMClientFinalMessage:Br,query:kr,parse:Lr,bind:Gr,execute:zr,describe:jr,close:$r,flush:()=>Yr,sync:()=>Xr,end:()=>Jr,copyData:Hr,copyDone:()=>Zr,copyFail:Kr,cancel:Wr},es={text:0,binary:1},ei=new ArrayBuffer(0),W,S,Rt,Dt,Xe,ti=class{constructor(t=0){v(this,W,new DataView(ei)),v(this,S),v(this,Rt,"utf-8"),v(this,Dt,new TextDecoder(n(this,Rt))),v(this,Xe,!1),g(this,S,t)}setBuffer(t,e){g(this,S,t),g(this,W,new DataView(e))}int16(){let t=n(this,W).getInt16(n(this,S),n(this,Xe));return g(this,S,n(this,S)+2),t}byte(){let t=n(this,W).getUint8(n(this,S));return ut(this,S)._++,t}int32(){let t=n(this,W).getInt32(n(this,S),n(this,Xe));return g(this,S,n(this,S)+4),t}string(t){return n(this,Dt).decode(this.bytes(t))}cstring(){let t=n(this,S),e=t;for(;n(this,W).getUint8(e++)!==0;);let s=this.string(e-t-1);return g(this,S,e),s}bytes(t){let e=n(this,W).buffer.slice(n(this,S),n(this,S)+t);return g(this,S,n(this,S)+t),new Uint8Array(e)}};W=new WeakMap,S=new WeakMap,Rt=new WeakMap,Dt=new WeakMap,Xe=new WeakMap;var It=1,si=4,ts=It+si,ss=new ArrayBuffer(0),D,I,M,h,E,gs,ws,rs,is,ns,as,os,St,ls,cs,us,hs,fs,ds,ps,ys,Pt,st=class{constructor(){v(this,E),v(this,D,new DataView(ss)),v(this,I,0),v(this,M,0),v(this,h,new ti)}parse(t,e){m(this,E,gs).call(this,ArrayBuffer.isView(t)?t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength):t);let s=n(this,M)+n(this,I),r=n(this,M);for(;r+ts<=s;){let i=n(this,D).getUint8(r),a=n(this,D).getUint32(r+It,!1),l=It+a;if(l+r<=s){let o=m(this,E,ws).call(this,r+ts,i,a,n(this,D).buffer);e(o),r+=l}else break}r===s?(g(this,D,new DataView(ss)),g(this,I,0),g(this,M,0)):(g(this,I,s-r),g(this,M,r))}};D=new WeakMap,I=new WeakMap,M=new WeakMap,h=new WeakMap,E=new WeakSet,gs=function(t){if(n(this,I)>0){let e=n(this,I)+t.byteLength;if(e+n(this,M)>n(this,D).byteLength){let s;if(e<=n(this,D).byteLength&&n(this,M)>=n(this,I))s=n(this,D).buffer;else{let r=n(this,D).byteLength*2;for(;e>=r;)r*=2;s=new ArrayBuffer(r)}new Uint8Array(s).set(new Uint8Array(n(this,D).buffer,n(this,M),n(this,I))),g(this,D,new DataView(s)),g(this,M,0)}new Uint8Array(n(this,D).buffer).set(new Uint8Array(t),n(this,M)+n(this,I)),g(this,I,e)}else g(this,D,new DataView(t)),g(this,M,0),g(this,I,t.byteLength)},ws=function(t,e,s,r){switch(e){case 50:return ce;case 49:return le;case 51:return ue;case 110:return he;case 115:return fe;case 99:return ye;case 87:return de;case 73:return pe;case 68:return m(this,E,fs).call(this,t,s,r);case 67:return m(this,E,is).call(this,t,s,r);case 90:return m(this,E,rs).call(this,t,s,r);case 65:return m(this,E,ls).call(this,t,s,r);case 82:return m(this,E,ys).call(this,t,s,r);case 83:return m(this,E,ds).call(this,t,s,r);case 75:return m(this,E,ps).call(this,t,s,r);case 69:return m(this,E,Pt).call(this,t,s,r,"error");case 78:return m(this,E,Pt).call(this,t,s,r,"notice");case 84:return m(this,E,cs).call(this,t,s,r);case 116:return m(this,E,hs).call(this,t,s,r);case 71:return m(this,E,as).call(this,t,s,r);case 72:return m(this,E,os).call(this,t,s,r);case 100:return m(this,E,ns).call(this,t,s,r);default:return new G("received invalid response: "+e.toString(16),s,"error")}},rs=function(t,e,s){n(this,h).setBuffer(t,s);let r=n(this,h).string(1);return new De(e,r)},is=function(t,e,s){n(this,h).setBuffer(t,s);let r=n(this,h).cstring();return new k(e,r)},ns=function(t,e,s){let r=s.slice(t,t+(e-4));return new Te(e,new Uint8Array(r))},as=function(t,e,s){return m(this,E,St).call(this,t,e,s,"copyInResponse")},os=function(t,e,s){return m(this,E,St).call(this,t,e,s,"copyOutResponse")},St=function(t,e,s,r){n(this,h).setBuffer(t,s);let i=n(this,h).byte()!==0,a=n(this,h).int16(),l=new xe(e,r,i,a);for(let o=0;o<a;o++)l.columnTypes[o]=n(this,h).int16();return l},ls=function(t,e,s){n(this,h).setBuffer(t,s);let r=n(this,h).int32(),i=n(this,h).cstring(),a=n(this,h).cstring();return new H(e,r,i,a)},cs=function(t,e,s){n(this,h).setBuffer(t,s);let r=n(this,h).int16(),i=new q(e,r);for(let a=0;a<r;a++)i.fields[a]=m(this,E,us).call(this);return i},us=function(){let t=n(this,h).cstring(),e=n(this,h).int32(),s=n(this,h).int16(),r=n(this,h).int32(),i=n(this,h).int16(),a=n(this,h).int32(),l=n(this,h).int16()===0?es.text:es.binary;return new Se(t,e,s,r,i,a,l)},hs=function(t,e,s){n(this,h).setBuffer(t,s);let r=n(this,h).int16(),i=new Pe(e,r);for(let a=0;a<r;a++)i.dataTypeIDs[a]=n(this,h).int32();return i},fs=function(t,e,s){n(this,h).setBuffer(t,s);let r=n(this,h).int16(),i=new Array(r);for(let a=0;a<r;a++){let l=n(this,h).int32();i[a]=l===-1?null:n(this,h).string(l)}return new z(e,i)},ds=function(t,e,s){n(this,h).setBuffer(t,s);let r=n(this,h).cstring(),i=n(this,h).cstring();return new ve(e,r,i)},ps=function(t,e,s){n(this,h).setBuffer(t,s);let r=n(this,h).int32(),i=n(this,h).int32();return new Re(e,r,i)},ys=function(t,e,s){n(this,h).setBuffer(t,s);let r=n(this,h).int32();switch(r){case 0:return new me(e);case 3:return new ge(e);case 5:return new we(e,n(this,h).bytes(4));case 10:{let i=[];for(;;){let a=n(this,h).cstring();if(a.length===0)return new be(e,i);i.push(a)}}case 11:return new Ee(e,n(this,h).string(e-8));case 12:return new Ae(e,n(this,h).string(e-8));default:throw new Error("Unknown authenticationOk message type "+r)}},Pt=function(t,e,s,r){n(this,h).setBuffer(t,s);let i={},a=n(this,h).string(1);for(;a!=="\0";)i[a]=n(this,h).cstring(),a=n(this,h).string(1);let l=i.M,o=r==="notice"?new K(e,l):new G(l,e,r);return o.severity=i.S,o.code=i.C,o.detail=i.D,o.hint=i.H,o.position=i.P,o.internalPosition=i.p,o.internalQuery=i.q,o.where=i.W,o.schema=i.s,o.table=i.t,o.column=i.c,o.dataType=i.d,o.constraint=i.n,o.file=i.F,o.line=i.L,o.routine=i.R,o};var ie,X,J,Z,ne,Fe,ae,it,oe,Be,ke,Ue,ee,_,C,te,u,As,rt,Q,Ot,_t,_e,V,Ce,Y,Ct=class Ct{constructor(e={},s={}){x(this,u);x(this,ie,!1);x(this,X,!1);x(this,J,!1);x(this,Z,!1);x(this,ne,!1);x(this,Fe,new $);x(this,ae,new $);x(this,it,new $);x(this,oe,!1);this.debug=0;x(this,Be);x(this,ke,[]);x(this,Ue,new st);x(this,ee);x(this,_);x(this,C,new Map);x(this,te,new Set);typeof e=="string"?s={dataDir:e,...s}:s=e,this.dataDir=s.dataDir,s?.debug!==void 0&&(this.debug=s.debug),s?.relaxedDurability!==void 0&&P(this,ne,s.relaxedDurability),P(this,Be,s.extensions??{}),this.waitReady=p(this,u,As).call(this,s??{})}static async create(e,s){let r=typeof e=="string"?{dataDir:e,...s??{}}:e??{},i=new Ct(r);return await i.waitReady,i}get Module(){return this.mod}get ready(){return f(this,ie)&&!f(this,X)&&!f(this,J)}get closed(){return f(this,J)}async close(){await p(this,u,_e).call(this),P(this,X,!0);for(let e of f(this,ke))await e();try{await this.execProtocol(U.end())}catch(e){let s=e;if(!(s.name==="ExitStatus"&&s.status===0))throw e}await this.fs.close(this.mod.FS),P(this,J,!0),P(this,X,!1)}async[Symbol.asyncDispose](){await this.close()}async query(e,s,r){return await p(this,u,_e).call(this),await f(this,ae).runExclusive(async()=>await p(this,u,rt).call(this,e,s,r))}async sql(e,...s){let{query:r,params:i}=ot(e,...s);return await this.query(r,i)}async exec(e,s){return await p(this,u,_e).call(this),await f(this,ae).runExclusive(async()=>await p(this,u,Q).call(this,e,s))}async transaction(e){return await p(this,u,_e).call(this),await f(this,ae).runExclusive(async()=>{await p(this,u,Q).call(this,"BEGIN");let s=!1,r=()=>{if(s)throw new Error("Transaction is closed")};try{let a=await e({query:async(l,o,y)=>(r(),await p(this,u,rt).call(this,l,o,y)),sql:async(l,...o)=>{let{query:y,params:c}=ot(l,...o);return await p(this,u,rt).call(this,y,c)},exec:async(l,o)=>(r(),await p(this,u,Q).call(this,l,o)),rollback:async()=>{r(),await p(this,u,Q).call(this,"ROLLBACK"),s=!0},get closed(){return s}});return s||(s=!0,await p(this,u,Q).call(this,"COMMIT")),a}catch(i){throw s||await p(this,u,Q).call(this,"ROLLBACK"),i}})}async execProtocolRaw(e,{syncToFs:s=!0}={}){let r=e.length,i=this.mod;i._interactive_write(r),i.HEAPU8.set(e,1),i._interactive_one();let a=r+2,l=a+i._interactive_read(),o=i.HEAPU8.subarray(a,l);return s&&await p(this,u,Ce).call(this),o}async execProtocol(e,{syncToFs:s=!0,onNotice:r}={}){let i=await this.execProtocolRaw(e,{syncToFs:s}),a=[];return f(this,Ue).parse(i,l=>{if(l instanceof G)throw P(this,Ue,new st),l;if(l instanceof K)this.debug>0&&console.warn(l),r&&r(l);else if(l instanceof k)switch(l.text){case"BEGIN":P(this,Z,!0);break;case"COMMIT":case"ROLLBACK":P(this,Z,!1);break}else if(l instanceof H){let o=f(this,C).get(l.channel);o&&o.forEach(y=>{queueMicrotask(()=>y(l.payload))}),f(this,te).forEach(y=>{queueMicrotask(()=>y(l.channel,l.payload))})}a.push([l,i])}),a}async listen(e,s){return f(this,C).has(e)||f(this,C).set(e,new Set),f(this,C).get(e).add(s),await this.exec(`LISTEN ${e}`),async()=>{await this.unlisten(e,s)}}async unlisten(e,s){s?(f(this,C).get(e)?.delete(s),f(this,C).get(e)?.size===0&&(await this.exec(`UNLISTEN ${e}`),f(this,C).delete(e))):(await this.exec(`UNLISTEN ${e}`),f(this,C).delete(e))}onNotification(e){return f(this,te).add(e),()=>{f(this,te).delete(e)}}offNotification(e){f(this,te).delete(e)}async dumpDataDir(e){let s=this.dataDir?.split("/").pop()??"pgdata";return this.fs.dumpTar(this.mod.FS,s,e)}};ie=new WeakMap,X=new WeakMap,J=new WeakMap,Z=new WeakMap,ne=new WeakMap,Fe=new WeakMap,ae=new WeakMap,it=new WeakMap,oe=new WeakMap,Be=new WeakMap,ke=new WeakMap,Ue=new WeakMap,ee=new WeakMap,_=new WeakMap,C=new WeakMap,te=new WeakMap,u=new WeakSet,As=async function(e){if(e.fs)this.fs=e.fs;else{let{dataDir:o,fsType:y}=Ut(e.dataDir);this.fs=await Lt(o,y)}let s={},r=[],i=[`PGDATA=${Ge}`,`PREFIX=${at}`,`PGUSER=${e.username??"postgres"}`,`PGDATABASE=${e.database??"template1"}`,"MODE=REACT","REPL=N",...this.debug?["-d",this.debug.toString()]:[]],a={WASM_PREFIX:at,arguments:i,INITIAL_MEMORY:e.initialMemory,noExitRuntime:!0,...this.debug>0?{print:console.info,printErr:console.error}:{print:()=>{},printErr:()=>{}},locateFile:await Gt(),preRun:[o=>{let y=o.FS.makedev(64,0),c={open:d=>{},close:d=>{},read:(d,A,L,j,N)=>{let Ft=f(this,ee);if(!Ft)throw new Error("No /dev/blob File or Blob provided to read from");let nt=new Uint8Array(Ft);if(N>=nt.length)return 0;let Bt=Math.min(nt.length-N,j);for(let Le=0;Le<Bt;Le++)A[L+Le]=nt[N+Le];return Bt},write:(d,A,L,j,N)=>(f(this,_)??P(this,_,[]),f(this,_).push(A.slice(L,L+j)),j),llseek:(d,A,L)=>{let j=f(this,ee);if(!j)throw new Error("No /dev/blob File or Blob provided to llseek");let N=A;if(L===1?N+=d.position:L===2&&(N=new Uint8Array(j).length),N<0)throw new o.FS.ErrnoError(28);return N}};o.FS.registerDevice(y,c),o.FS.mkdev("/dev/blob",y)}]};a=await this.fs.emscriptenOpts(a);for(let[o,y]of Object.entries(f(this,Be)))if(y instanceof URL)s[o]=xt(y);else{let c=await y.setup(this,a);if(c.emscriptenOpts&&(a=c.emscriptenOpts),c.namespaceObj){let d=this;d[o]=c.namespaceObj}c.bundlePath&&(s[o]=xt(c.bundlePath)),c.init&&r.push(c.init),c.close&&f(this,ke).push(c.close)}if(a.pg_extensions=s,this.mod=await qt(a),await this.fs.initialSyncFs(this.mod.FS),e.loadDataDir){if(this.mod.FS.analyzePath(Ge+"/PG_VERSION").exists)throw new Error("Database already exists, cannot load from tarball");p(this,u,Y).call(this,"pglite: loading data from tarball"),await kt(this.mod.FS,e.loadDataDir)}this.mod.FS.analyzePath(Ge+"/PG_VERSION").exists?p(this,u,Y).call(this,"pglite: found DB, resuming"):p(this,u,Y).call(this,"pglite: no db"),await Zt(this.mod,(...o)=>p(this,u,Y).call(this,...o));let l=this.mod._pg_initdb();if(!l)throw new Error("INITDB failed to return value");if(l&1)throw new Error("INITDB failed");if(l&2){let o=e.username??"postgres",y=e.database??"template1";if(l&4){if(!(l&12))throw new Error("Invalid db/user combination")}else if(y!=="template1"&&o!=="postgres")throw new Error("INITDB created a new datadir, but an alternative db/user was requested")}await p(this,u,Ce).call(this),await p(this,u,Q).call(this,"SET search_path TO public;"),P(this,ie,!0);for(let o of r)await o()},rt=async function(e,s,r){return await f(this,Fe).runExclusive(async()=>{p(this,u,Y).call(this,"runQuery",e,s,r),await p(this,u,Ot).call(this,r?.blob);let i=s?.map(o=>He(o,r?.setAllTypes))||[],a;try{a=[...await p(this,u,V).call(this,U.parse({text:e,types:i.map(([,o])=>o)}),r),...await p(this,u,V).call(this,U.bind({values:i.map(([o])=>o)}),r),...await p(this,u,V).call(this,U.describe({type:"P"}),r),...await p(this,u,V).call(this,U.execute({}),r)]}finally{await p(this,u,V).call(this,U.sync(),r)}p(this,u,_t).call(this),f(this,Z)||await p(this,u,Ce).call(this);let l;return f(this,_)&&(l=new Blob(f(this,_)),P(this,_,void 0)),Ye(a.map(([o])=>o),r,l)[0]})},Q=async function(e,s){return await f(this,Fe).runExclusive(async()=>{p(this,u,Y).call(this,"runExec",e,s),await p(this,u,Ot).call(this,s?.blob);let r;try{r=await p(this,u,V).call(this,U.query(e),s)}finally{await p(this,u,V).call(this,U.sync(),s)}p(this,u,_t).call(this),f(this,Z)||await p(this,u,Ce).call(this);let i;return f(this,_)&&(i=new Blob(f(this,_)),P(this,_,void 0)),Ye(r.map(([a])=>a),s,i)})},Ot=async function(e){P(this,ee,e?await e.arrayBuffer():void 0)},_t=function(){P(this,ee,void 0)},_e=async function(){if(f(this,X))throw new Error("PGlite is closing");if(f(this,J))throw new Error("PGlite is closed");f(this,ie)||await this.waitReady},V=async function(e,s={}){return await this.execProtocol(e,{...s,syncToFs:!1})},Ce=async function(){if(f(this,oe))return;P(this,oe,!0);let e=async()=>{await f(this,it).runExclusive(async()=>{P(this,oe,!1),await this.fs.syncToFs(this.mod.FS,f(this,ne))})};f(this,ne)?e():await e()},Y=function(...e){this.debug>0&&console.log(...e)};var Es=Ct;b();export{Ss as IdbFs,Ps as MemoryFS,$ as Mutex,Es as PGlite,Rs as formatQuery,Wt as messages,Xt as parse,bs as protocol,Yt as types,vs as uuid};
import{b as Ge,d as se,e as Ce,f as We,g as X,h as G,i as ie,j as re}from"./chunk-SJVDOE3S.js";import{A as Q,B as Ae,C as $,D as Me,E as Y,F as Ve,G as Re,a as ze,b as je,c as ae,d as le,e as ce,f as de,g as ue,h as pe,i as fe,j as me,k as he,l as ye,m as ge,n as we,o as xe,p as be,q as C,r as ve,s as Ee,t as Pe,u as _e,v as Te,w as Fe,x as Se,y as W,z as De}from"./chunk-7M5G4I52.js";import"./chunk-TAZBUB4Z.js";import{a as ne,b as oe,c as Qe,d as $e}from"./chunk-3BCYDNSE.js";import{b as Le,c as qe,d as i,e as p,f,g as S,i as h}from"./chunk-Y3AVQXKT.js";h();h();h();var et=new Error("timeout while waiting for mutex to become available"),tt=new Error("mutex already locked"),Ke=new Error("request for lock canceled"),Xe=function(u,t,e,s){function d(r){return r instanceof e?r:new e(function(n){n(r)})}return new(e||(e=Promise))(function(r,n){function o(c){try{l(s.next(c))}catch(m){n(m)}}function a(c){try{l(s.throw(c))}catch(m){n(m)}}function l(c){c.done?r(c.value):d(c.value).then(o,a)}l((s=s.apply(u,t||[])).next())})},H=class{constructor(t,e=Ke){this._value=t,this._cancelError=e,this._weightedQueues=[],this._weightedWaiters=[]}acquire(t=1){if(t<=0)throw new Error(`invalid weight ${t}: must be positive`);return new Promise((e,s)=>{this._weightedQueues[t-1]||(this._weightedQueues[t-1]=[]),this._weightedQueues[t-1].push({resolve:e,reject:s}),this._dispatch()})}runExclusive(t,e=1){return Xe(this,void 0,void 0,function*(){let[s,d]=yield this.acquire(e);try{return yield t(s)}finally{d()}})}waitForUnlock(t=1){if(t<=0)throw new Error(`invalid weight ${t}: must be positive`);return new Promise(e=>{this._weightedWaiters[t-1]||(this._weightedWaiters[t-1]=[]),this._weightedWaiters[t-1].push(e),this._dispatch()})}isLocked(){return this._value<=0}getValue(){return this._value}setValue(t){this._value=t,this._dispatch()}release(t=1){if(t<=0)throw new Error(`invalid weight ${t}: must be positive`);this._value+=t,this._dispatch()}cancel(){this._weightedQueues.forEach(t=>t.forEach(e=>e.reject(this._cancelError))),this._weightedQueues=[]}_dispatch(){var t;for(let e=this._value;e>0;e--){let s=(t=this._weightedQueues[e-1])===null||t===void 0?void 0:t.shift();if(!s)continue;let d=this._value,r=e;this._value-=e,e=this._value+1,s.resolve([d,this._newReleaser(r)])}this._drainUnlockWaiters()}_newReleaser(t){let e=!1;return()=>{e||(e=!0,this.release(t))}}_drainUnlockWaiters(){for(let t=this._value;t>0;t--)this._weightedWaiters[t-1]&&(this._weightedWaiters[t-1].forEach(e=>e()),this._weightedWaiters[t-1]=[])}},Ye=function(u,t,e,s){function d(r){return r instanceof e?r:new e(function(n){n(r)})}return new(e||(e=Promise))(function(r,n){function o(c){try{l(s.next(c))}catch(m){n(m)}}function a(c){try{l(s.throw(c))}catch(m){n(m)}}function l(c){c.done?r(c.value):d(c.value).then(o,a)}l((s=s.apply(u,t||[])).next())})},E=class{constructor(t){this._semaphore=new H(1,t)}acquire(){return Ye(this,void 0,void 0,function*(){let[,t]=yield this._semaphore.acquire();return t})}runExclusive(t){return this._semaphore.runExclusive(()=>t())}isLocked(){return this._semaphore.isLocked()}waitForUnlock(){return this._semaphore.waitForUnlock()}release(){this._semaphore.isLocked()&&this._semaphore.release()}cancel(){return this._semaphore.cancel()}};h();import He from"./postgres.js";var Oe=He;h();var Ie=qe(Ge(),1);async function J(u){if(ne){let t=await import("fs"),e=await import("zlib"),{Writable:s}=await import("stream"),{pipeline:d}=await import("stream/promises");if(!t.existsSync(u))throw new Error(`Extension bundle not found: ${u}`);let r=e.createGunzip(),n=[];return await d(t.createReadStream(u),r,new s({write(o,a,l){n.push(o),l()}})),new Blob(n)}else{let t=await fetch(u.toString());if(!t.ok||!t.body)return null;if(t.headers.get("Content-Encoding")==="gzip")return t.blob();{let e=new DecompressionStream("gzip");return new Response(t.body.pipeThrough(e)).blob()}}}async function ke(u,t){for(let e in u.pg_extensions){let s;try{s=await u.pg_extensions[e]}catch(d){console.error("Failed to fetch extension:",e,d);continue}if(s){let d=new Uint8Array(await s.arrayBuffer());Je(u,e,d,t)}else console.error("Could not get binary data for extension:",e)}}function Je(u,t,e,s){Ie.default.untar(e).forEach(r=>{if(!r.name.startsWith(".")){let n=u.WASM_PREFIX+"/"+r.name;if(r.name.endsWith(".so")){let o=(...l)=>{s("pgfs:ext OK",n,l)},a=(...l)=>{s("pgfs:ext FAIL",n,l)};u.FS.createPreloadedFile(Ze(n),r.name.split("/").pop().slice(0,-3),r.data,!0,!0,o,a,!1)}else u.FS.writeFile(n,r.data)}})}function Ze(u){let t=u.lastIndexOf("/");return t>0?u.slice(0,t):u}var Be={};Le(Be,{AuthenticationCleartextPassword:()=>ye,AuthenticationMD5Password:()=>ge,AuthenticationOk:()=>he,AuthenticationSASL:()=>we,AuthenticationSASLContinue:()=>xe,AuthenticationSASLFinal:()=>be,BackendKeyDataMessage:()=>Se,CommandCompleteMessage:()=>Q,CopyDataMessage:()=>ve,CopyResponse:()=>Ee,DataRowMessage:()=>Ae,DatabaseError:()=>C,Field:()=>Pe,NoticeMessage:()=>$,NotificationResponseMessage:()=>W,ParameterDescriptionMessage:()=>Te,ParameterStatusMessage:()=>Fe,ReadyForQueryMessage:()=>De,RowDescriptionMessage:()=>_e,bindComplete:()=>le,closeComplete:()=>ce,copyDone:()=>me,emptyQuery:()=>fe,noData:()=>de,parseComplete:()=>ae,portalSuspended:()=>ue,replicationStart:()=>pe});h();var M,P,_,R,O,z,j,V,I,N,U,L,T,x,y,F,w,Ue,B,Z=class Z extends Re{constructor(e={},s={}){super();p(this,w);p(this,M,!1);p(this,P,!1);p(this,_,!1);p(this,R,!1);p(this,O,!1);p(this,z,new E);p(this,j,new E);p(this,V,new E);p(this,I,!1);this.debug=0;p(this,N);p(this,U,[]);p(this,L,new Y);p(this,T);p(this,x);p(this,y,new Map);p(this,F,new Set);typeof e=="string"?s={dataDir:e,...s}:s=e,this.dataDir=s.dataDir,s?.debug!==void 0&&(this.debug=s.debug),s?.relaxedDurability!==void 0&&f(this,O,s.relaxedDurability),f(this,N,s.extensions??{}),this.waitReady=S(this,w,Ue).call(this,s??{})}static async create(e,s){let d=typeof e=="string"?{dataDir:e,...s??{}}:e??{},r=new Z(d);return await r.waitReady,r}get Module(){return this.mod}get ready(){return i(this,M)&&!i(this,P)&&!i(this,_)}get closed(){return i(this,_)}async close(){await this._checkReady(),f(this,P,!0);for(let e of i(this,U))await e();try{await this.execProtocol(Me.end())}catch(e){let s=e;if(!(s.name==="ExitStatus"&&s.status===0))throw e}await this.fs.close(this.mod.FS),f(this,_,!0),f(this,P,!1)}async[Symbol.asyncDispose](){await this.close()}async _handleBlob(e){f(this,T,e?await e.arrayBuffer():void 0)}async _cleanupBlob(){f(this,T,void 0)}async _getWrittenBlob(){if(!i(this,x))return;let e=new Blob(i(this,x));return f(this,x,void 0),e}async _checkReady(){if(i(this,P))throw new Error("PGlite is closing");if(i(this,_))throw new Error("PGlite is closed");i(this,M)||await this.waitReady}async execProtocolRaw(e,{syncToFs:s=!0}={}){let d=e.length,r=this.mod;r._interactive_write(d),r.HEAPU8.set(e,1),r._interactive_one();let n=d+2,o=n+r._interactive_read(),a=r.HEAPU8.subarray(n,o);return s&&await this.syncToFs(),a}async execProtocol(e,{syncToFs:s=!0,onNotice:d}={}){let r=await this.execProtocolRaw(e,{syncToFs:s}),n=[];return i(this,L).parse(r,o=>{if(o instanceof C)throw f(this,L,new Y),o;if(o instanceof $)this.debug>0&&console.warn(o),d&&d(o);else if(o instanceof Q)switch(o.text){case"BEGIN":f(this,R,!0);break;case"COMMIT":case"ROLLBACK":f(this,R,!1);break}else if(o instanceof W){let a=i(this,y).get(o.channel);a&&a.forEach(l=>{queueMicrotask(()=>l(o.payload))}),i(this,F).forEach(l=>{queueMicrotask(()=>l(o.channel,o.payload))})}n.push([o,r])}),n}isInTransaction(){return i(this,R)}async syncToFs(){if(i(this,I))return;f(this,I,!0);let e=async()=>{await i(this,V).runExclusive(async()=>{f(this,I,!1),await this.fs.syncToFs(this.mod.FS,i(this,O))})};i(this,O)?e():await e()}async listen(e,s){return i(this,y).has(e)||i(this,y).set(e,new Set),i(this,y).get(e).add(s),await this.exec(`LISTEN ${e}`),async()=>{await this.unlisten(e,s)}}async unlisten(e,s){s?(i(this,y).get(e)?.delete(s),i(this,y).get(e)?.size===0&&(await this.exec(`UNLISTEN ${e}`),i(this,y).delete(e))):(await this.exec(`UNLISTEN ${e}`),i(this,y).delete(e))}onNotification(e){return i(this,F).add(e),()=>{i(this,F).delete(e)}}offNotification(e){i(this,F).delete(e)}async dumpDataDir(e){let s=this.dataDir?.split("/").pop()??"pgdata";return this.fs.dumpTar(this.mod.FS,s,e)}_runExclusiveQuery(e){return i(this,z).runExclusive(e)}_runExclusiveTransaction(e){return i(this,j).runExclusive(e)}};M=new WeakMap,P=new WeakMap,_=new WeakMap,R=new WeakMap,O=new WeakMap,z=new WeakMap,j=new WeakMap,V=new WeakMap,I=new WeakMap,N=new WeakMap,U=new WeakMap,L=new WeakMap,T=new WeakMap,x=new WeakMap,y=new WeakMap,F=new WeakMap,w=new WeakSet,Ue=async function(e){if(e.fs)this.fs=e.fs;else{let{dataDir:a,fsType:l}=ie(e.dataDir);this.fs=await re(a,l)}let s={},d=[],r=[`PGDATA=${G}`,`PREFIX=${X}`,`PGUSER=${e.username??"postgres"}`,`PGDATABASE=${e.database??"template1"}`,"MODE=REACT","REPL=N",...this.debug?["-d",this.debug.toString()]:[]],n={WASM_PREFIX:X,arguments:r,INITIAL_MEMORY:e.initialMemory,noExitRuntime:!0,...this.debug>0?{print:console.info,printErr:console.error}:{print:()=>{},printErr:()=>{}},locateFile:await oe(),preRun:[a=>{let l=a.FS.makedev(64,0),c={open:m=>{},close:m=>{},read:(m,k,b,v,g)=>{let ee=i(this,T);if(!ee)throw new Error("No /dev/blob File or Blob provided to read from");let K=new Uint8Array(ee);if(g>=K.length)return 0;let te=Math.min(K.length-g,v);for(let q=0;q<te;q++)k[b+q]=K[g+q];return te},write:(m,k,b,v,g)=>(i(this,x)??f(this,x,[]),i(this,x).push(k.slice(b,b+v)),v),llseek:(m,k,b)=>{let v=i(this,T);if(!v)throw new Error("No /dev/blob File or Blob provided to llseek");let g=k;if(b===1?g+=m.position:b===2&&(g=new Uint8Array(v).length),g<0)throw new a.FS.ErrnoError(28);return g}};a.FS.registerDevice(l,c),a.FS.mkdev("/dev/blob",l)}]};n=await this.fs.emscriptenOpts(n);for(let[a,l]of Object.entries(i(this,N)))if(l instanceof URL)s[a]=J(l);else{let c=await l.setup(this,n);if(c.emscriptenOpts&&(n=c.emscriptenOpts),c.namespaceObj){let m=this;m[a]=c.namespaceObj}c.bundlePath&&(s[a]=J(c.bundlePath)),c.init&&d.push(c.init),c.close&&i(this,U).push(c.close)}if(n.pg_extensions=s,this.mod=await Oe(n),await this.fs.initialSyncFs(this.mod.FS),e.loadDataDir){if(this.mod.FS.analyzePath(G+"/PG_VERSION").exists)throw new Error("Database already exists, cannot load from tarball");S(this,w,B).call(this,"pglite: loading data from tarball"),await se(this.mod.FS,e.loadDataDir)}this.mod.FS.analyzePath(G+"/PG_VERSION").exists?S(this,w,B).call(this,"pglite: found DB, resuming"):S(this,w,B).call(this,"pglite: no db"),await ke(this.mod,(...a)=>S(this,w,B).call(this,...a));let o=this.mod._pg_initdb();if(!o)throw new Error("INITDB failed to return value");if(o&1)throw new Error("INITDB failed");if(o&2){let a=e.username??"postgres",l=e.database??"template1";if(o&4){if(!(o&12))throw new Error("Invalid db/user combination")}else if(l!=="template1"&&a!=="postgres")throw new Error("INITDB created a new datadir, but an alternative db/user was requested")}await this.syncToFs(),f(this,M,!0),await this.exec("SET search_path TO public;");for(let a of d)await a()},B=function(...e){this.debug>0&&console.log(...e)};var Ne=Z;h();export{Ce as IdbFs,We as MemoryFS,E as Mutex,Ne as PGlite,$e as formatQuery,Be as messages,je as parse,Ve as protocol,ze as types,Qe as uuid};
//# sourceMappingURL=index.js.map

@@ -1,4 +0,4 @@

import { R as Results, P as PGliteInterface } from '../interface-Db0XLAWB.js';
import { R as Results, a as PGliteInterface } from '../interface-BChI4DHV.js';
import '@electric-sql/pg-protocol/messages';
import '../types-CQTnnKLt.js';
import '../types-XE-2t5ub.js';

@@ -5,0 +5,0 @@ interface LiveNamespace {

@@ -1,8 +0,8 @@

import{c as g,d}from"../chunk-3BCYDNSE.js";import{i as I}from"../chunk-Y3AVQXKT.js";I();var h=5,C=async(l,A)=>{let y=new Set,v={async query(s,S,t){let E=g().replace(/-/g,""),e,c,o=async()=>{await l.transaction(async n=>{let T=await d(n,s,S);await n.query(`CREATE OR REPLACE TEMP VIEW live_query_${E}_view AS ${T}`),c=await w(n,`live_query_${E}_view`),await O(n,c,y),await n.exec(`
import{c as N,d as g}from"../chunk-3BCYDNSE.js";import{i as I}from"../chunk-Y3AVQXKT.js";I();var h=5,C=async(l,A)=>{let f=new Set,v={async query(s,p,t){let E=N().replace(/-/g,""),e,c,o=async()=>{await l.transaction(async n=>{let T=await g(n,s,p);await n.query(`CREATE OR REPLACE TEMP VIEW live_query_${E}_view AS ${T}`),c=await w(n,`live_query_${E}_view`),await O(n,c,f),await n.exec(`
PREPARE live_query_${E}_get AS
SELECT * FROM live_query_${E}_view;
`),e=await n.query(`EXECUTE live_query_${E}_get;`)})};await o();let u=async(n=0)=>{try{e=await l.query(`EXECUTE live_query_${E}_get;`)}catch(T){if(T.message===`prepared statement "live_query_${E}_get" does not exist`){if(n>h)throw T;await o(),u(n+1)}else throw T}t(e)},f=await Promise.all(c.map(n=>l.listen(`table_change__${n.schema_name}__${n.table_name}`,async()=>{u()}))),L=async()=>{await Promise.all(f.map(n=>n())),await l.exec(`
`),e=await n.query(`EXECUTE live_query_${E}_get;`)})};await o();let u=async(n=0)=>{try{e=await l.query(`EXECUTE live_query_${E}_get;`)}catch(T){if(T.message===`prepared statement "live_query_${E}_get" does not exist`){if(n>h)throw T;await o(),u(n+1)}else throw T}t(e)},m=await Promise.all(c.map(n=>l.listen(`table_change__${n.schema_name}__${n.table_name}`,async()=>{u()}))),y=async()=>{await Promise.all(m.map(n=>n())),await l.exec(`
DROP VIEW IF EXISTS live_query_${E}_view;
DEALLOCATE live_query_${E}_get;
`)};return t(e),{initialResults:e,unsubscribe:L,refresh:u}},async changes(s,S,t,E){let e=g().replace(/-/g,""),c,o=1,u,f=async()=>{await l.transaction(async r=>{let R=await d(r,s,S);await r.query(`CREATE OR REPLACE TEMP VIEW live_query_${e}_view AS ${R}`),c=await w(r,`live_query_${e}_view`),await O(r,c,y);let _=[...(await r.query(`
`)};return t(e),{initialResults:e,unsubscribe:y,refresh:u}},async changes(s,p,t,E){let e=N().replace(/-/g,""),c,o=1,u,m=async()=>{await l.transaction(async r=>{let R=await g(r,s,p);await r.query(`CREATE OR REPLACE TEMP VIEW live_query_${e}_view AS ${R}`),c=await w(r,`live_query_${e}_view`),await O(r,c,f);let _=[...(await r.query(`
SELECT column_name, data_type, udt_name

@@ -33,3 +33,3 @@ FROM information_schema.columns

'DELETE' AS __op__,
${_.map(({column_name:a,data_type:m,udt_name:N})=>a===t?`prev."${a}" AS "${a}"`:`NULL::${m==="USER-DEFINED"?N:m} AS "${a}"`).join(`,
${_.map(({column_name:a,data_type:L,udt_name:d})=>a===t?`prev."${a}" AS "${a}"`:`NULL${L==="USER-DEFINED"?`::${d}`:""} AS "${a}"`).join(`,
`)},

@@ -44,6 +44,6 @@ ARRAY[]::text[] AS __changed_columns__

'UPDATE' AS __op__,
${_.map(({column_name:a,data_type:m,udt_name:N})=>a===t?`curr."${a}" AS "${a}"`:`CASE
${_.map(({column_name:a,data_type:L,udt_name:d})=>a===t?`curr."${a}" AS "${a}"`:`CASE
WHEN curr."${a}" IS DISTINCT FROM prev."${a}"
THEN curr."${a}"
ELSE NULL::${m==="USER-DEFINED"?N:m}
ELSE NULL${L==="USER-DEFINED"?`::${d}`:""}
END AS "${a}"`).join(`,

@@ -61,7 +61,7 @@ `)},

SELECT * FROM data_diff;
`)}})};await f();let L=async()=>{let r=!1;for(let R=0;R<5;R++)try{await l.transaction(async _=>{await _.exec(`
`)}})};await m();let y=async()=>{let r=!1;for(let R=0;R<5;R++)try{await l.transaction(async _=>{await _.exec(`
DELETE FROM live_query_${e}_state${o};
INSERT INTO live_query_${e}_state${o}
SELECT * FROM live_query_${e}_view;
`),u=await _.query(`EXECUTE live_query_${e}_diff${o};`)});break}catch(_){if(_.message===`relation "live_query_${e}_state${o}" does not exist`){r=!0,await f();continue}else throw _}o=o===1?2:1,E([...r?[{__op__:"RESET"}]:[],...u.rows])},n=await Promise.all(c.map(r=>l.listen(`table_change__${r.schema_name}__${r.table_name}`,async()=>L()))),T=async()=>{await Promise.all(n.map(r=>r())),await l.exec(`
`),u=await _.query(`EXECUTE live_query_${e}_diff${o};`)});break}catch(_){if(_.message===`relation "live_query_${e}_state${o}" does not exist`){r=!0,await m();continue}else throw _}o=o===1?2:1,E([...r?[{__op__:"RESET"}]:[],...u.rows])},n=await Promise.all(c.map(r=>l.listen(`table_change__${r.schema_name}__${r.table_name}`,async()=>y()))),T=async()=>{await Promise.all(n.map(r=>r())),await l.exec(`
DROP VIEW IF EXISTS live_query_${e}_view;

@@ -72,3 +72,3 @@ DROP TABLE IF EXISTS live_query_${e}_state1;

DEALLOCATE live_query_${e}_diff2;
`)};return await L(),{fields:u.fields.filter(r=>!["__after__","__op__","__changed_columns__"].includes(r.name)),initialChanges:u.rows,unsubscribe:T,refresh:L}},async incrementalQuery(s,S,t,E){let e=new Map,c=new Map,o=[],u=!0,{fields:f,unsubscribe:L,refresh:n}=await v.changes(s,S,t,T=>{for(let R of T){let{__op__:_,__changed_columns__:$,...i}=R;switch(_){case"RESET":e.clear(),c.clear();break;case"INSERT":e.set(i[t],i),c.set(i.__after__,i[t]);break;case"DELETE":{let a=e.get(i[t]);e.delete(i[t]),c.delete(a.__after__);break}case"UPDATE":{let a={...e.get(i[t])??{}};for(let m of $)a[m]=i[m],m==="__after__"&&c.set(i.__after__,i[t]);e.set(i[t],a);break}}}let p=[],r=null;for(let R=0;R<e.size;R++){let _=c.get(r),$=e.get(_);if(!$)break;let i={...$};delete i.__after__,p.push(i),r=_}o=p,u||E({rows:p,fields:f})});return u=!1,E({rows:o,fields:f}),{initialResults:{rows:o,fields:f},unsubscribe:L,refresh:n}}};return{namespaceObj:v}},b={name:"Live Queries",setup:C};async function w(l,A){return(await l.query(`
`)};return await y(),{fields:u.fields.filter(r=>!["__after__","__op__","__changed_columns__"].includes(r.name)),initialChanges:u.rows,unsubscribe:T,refresh:y}},async incrementalQuery(s,p,t,E){let e=new Map,c=new Map,o=[],u=!0,{fields:m,unsubscribe:y,refresh:n}=await v.changes(s,p,t,T=>{for(let R of T){let{__op__:_,__changed_columns__:$,...i}=R;switch(_){case"RESET":e.clear(),c.clear();break;case"INSERT":e.set(i[t],i),c.set(i.__after__,i[t]);break;case"DELETE":{let a=e.get(i[t]);e.delete(i[t]),c.delete(a.__after__);break}case"UPDATE":{let a={...e.get(i[t])??{}};for(let L of $)a[L]=i[L],L==="__after__"&&c.set(i.__after__,i[t]);e.set(i[t],a);break}}}let S=[],r=null;for(let R=0;R<e.size;R++){let _=c.get(r),$=e.get(_);if(!$)break;let i={...$};delete i.__after__,S.push(i),r=_}o=S,u||E({rows:S,fields:m})});return u=!1,E({rows:o,fields:m}),{initialResults:{rows:o,fields:m},unsubscribe:y,refresh:n}}};return{namespaceObj:v}},b={name:"Live Queries",setup:C};async function w(l,A){return(await l.query(`
SELECT DISTINCT

@@ -86,3 +86,3 @@ cl.relname AS table_name,

AND d.deptype = 'n';
`,[A])).rows.filter(y=>y.table_name!==A)}async function O(l,A,y){let v=A.filter(s=>!y.has(`${s.schema_name}_${s.table_name}`)).map(s=>`
`,[A])).rows.filter(f=>f.table_name!==A)}async function O(l,A,f){let v=A.filter(s=>!f.has(`${s.schema_name}_${s.table_name}`)).map(s=>`
CREATE OR REPLACE FUNCTION _notify_${s.schema_name}_${s.table_name}() RETURNS TRIGGER AS $$

@@ -98,3 +98,3 @@ BEGIN

`).join(`
`);v.trim()!==""&&await l.exec(v),A.map(s=>y.add(`${s.schema_name}_${s.table_name}`))}export{b as live};
`);v.trim()!==""&&await l.exec(v),A.map(s=>f.add(`${s.schema_name}_${s.table_name}`))}export{b as live};
//# sourceMappingURL=index.js.map

@@ -1,4 +0,4 @@

import { P as PGliteInterface } from '../interface-Db0XLAWB.js';
import { a as PGliteInterface } from '../interface-BChI4DHV.js';
import '@electric-sql/pg-protocol/messages';
import '../types-CQTnnKLt.js';
import '../types-XE-2t5ub.js';

@@ -5,0 +5,0 @@ declare const vector: {

@@ -1,4 +0,5 @@

import { a as PGliteOptions, P as PGliteInterface, b as PGliteInterfaceExtensions, D as DebugLevel, Q as QueryOptions, R as Results, T as Transaction } from '../interface-Db0XLAWB.js';
import { h as PGliteOptions, a as PGliteInterface, i as PGliteInterfaceExtensions, D as DebugLevel } from '../interface-BChI4DHV.js';
import { B as BasePGlite, P as PGlite } from '../pglite-Dh_uQEOE.js';
import { BackendMessage } from '@electric-sql/pg-protocol/messages';
import '../types-CQTnnKLt.js';
import '../types-XE-2t5ub.js';

@@ -9,3 +10,3 @@ type PGliteWorkerOptions = PGliteOptions & {

};
declare class PGliteWorker implements PGliteInterface, AsyncDisposable {
declare class PGliteWorker extends BasePGlite implements PGliteInterface, AsyncDisposable {
#private;

@@ -49,41 +50,2 @@ constructor(worker: Worker, options?: PGliteWorkerOptions);

/**
* Execute a single SQL statement
* This uses the "Extended Query" postgres wire protocol message.
* @param query The query to execute
* @param params Optional parameters for the query
* @returns The result of the query
*/
query<T>(query: string, params?: any[], options?: QueryOptions): Promise<Results<T>>;
/**
* Execute a single SQL statement like with {@link PGlite.query}, but with a
* templated statement where template values will be treated as parameters.
*
* You can use helpers from `/template` to further format the query with
* identifiers, raw SQL, and nested statements.
*
* This uses the "Extended Query" postgres wire protocol message.
*
* @param query The query to execute with parameters as template values
* @returns The result of the query
*
* @example
* ```ts
* const results = await db.sql`SELECT * FROM ${identifier`foo`} WHERE id = ${id}`
* ```
*/
sql<T>(sqlStrings: TemplateStringsArray, ...params: any[]): Promise<Results<T>>;
/**
* Execute a SQL query, this can have multiple statements.
* This uses the "Simple Query" postgres wire protocol message.
* @param query The query to execute
* @returns The result of the query
*/
exec(query: string, options?: QueryOptions): Promise<Array<Results>>;
/**
* Execute a transaction
* @param callback A callback function that takes a transaction object
* @returns The result of the transaction
*/
transaction<T>(callback: (tx: Transaction) => Promise<T>): Promise<T | undefined>;
/**
* Execute a postgres wire protocol message directly without wrapping the response.

@@ -107,2 +69,7 @@ * Only use if `execProtocol()` doesn't suite your needs.

/**
* Sync the database to the filesystem
* @returns Promise that resolves when the database is synced to the filesystem
*/
syncToFs(): Promise<void>;
/**
* Listen for a notification

@@ -132,5 +99,11 @@ * @param channel The channel to listen on

offLeaderChange(callback: () => void): void;
_handleBlob(blob?: File | Blob): Promise<void>;
_getWrittenBlob(): Promise<File | Blob | undefined>;
_cleanupBlob(): Promise<void>;
_checkReady(): Promise<void>;
_runExclusiveQuery<T>(fn: () => Promise<T>): Promise<T>;
_runExclusiveTransaction<T>(fn: () => Promise<T>): Promise<T>;
}
interface WorkerOptions {
init: (options: Exclude<PGliteWorkerOptions, 'extensions'>) => Promise<PGliteInterface>;
init: (options: Exclude<PGliteWorkerOptions, 'extensions'>) => Promise<PGlite>;
}

@@ -137,0 +110,0 @@ declare function worker({ init }: WorkerOptions): Promise<void>;

@@ -1,2 +0,2 @@

import{c as N}from"../chunk-3BCYDNSE.js";import{d as s,e as l,f as y,g as h,i as j}from"../chunk-Y3AVQXKT.js";j();var L,b,A,T,O,w,R,E,m,C,I,q,M,k,G,f,W,D,$,o,F,S,g,z,U=class U{constructor(e,t){l(this,o);l(this,L);l(this,b,0);l(this,A,!1);l(this,T,!1);l(this,O,!1);l(this,w,new EventTarget);l(this,R);l(this,E,!1);l(this,m);l(this,C);l(this,I);l(this,q);l(this,M);l(this,k);l(this,G);l(this,f,new Map);l(this,W,new Set);l(this,D);l(this,$,[]);y(this,m,e),y(this,R,N()),y(this,D,t?.extensions??{}),y(this,I,new Promise(r=>{s(this,m).addEventListener("message",a=>{if(a.data.type==="here")r();else throw new Error("Invalid message")},{once:!0})})),y(this,q,new Promise(r=>{let a=n=>{n.data.type==="ready"&&(y(this,C,n.data.id),s(this,m).removeEventListener("message",a),r())};s(this,m).addEventListener("message",a)})),y(this,L,h(this,o,F).call(this,t))}static async create(e,t){let r=new U(e,t);return await s(r,L),r}get waitReady(){return new Promise(e=>{s(this,L).then(()=>{s(this,E)?e():e(new Promise(t=>{s(this,w).addEventListener("connected",()=>{t()})}))})})}get debug(){return s(this,b)}get ready(){return s(this,A)}get closed(){return s(this,T)}get isLeader(){return s(this,O)}async close(){var e;s(this,T)||(y(this,T,!0),s(this,M)?.close(),s(this,k)?.close(),(e=s(this,G))==null||e.call(this),s(this,m).terminate())}async[Symbol.asyncDispose](){await this.close()}async query(e,t,r){return await this.waitReady,await h(this,o,g).call(this,"query",e,t,r)}async sql(e,...t){return await this.waitReady,await h(this,o,g).call(this,"sql",e,e.raw,t)}async exec(e,t){return await this.waitReady,await h(this,o,g).call(this,"exec",e,t)}async transaction(e){await this.waitReady;let t=await h(this,o,g).call(this,"transactionStart"),r;try{r=await e({query:async(a,n,p)=>await h(this,o,g).call(this,"transactionQuery",t,a,n,p),sql:async(a,...n)=>h(this,o,g).call(this,"transactionSql",t,a,a.raw,n),exec:async(a,n)=>await h(this,o,g).call(this,"transactionExec",t,a,n),rollback:async()=>{await h(this,o,g).call(this,"transactionRollback",t)},closed:!1})}catch(a){throw await h(this,o,g).call(this,"transactionRollback",t),a}return await h(this,o,g).call(this,"transactionCommit",t),r}async execProtocolRaw(e){return await this.waitReady,await h(this,o,g).call(this,"execProtocolRaw",e)}async execProtocol(e){return await this.waitReady,await h(this,o,g).call(this,"execProtocol",e)}async listen(e,t){return await this.waitReady,s(this,f).has(e)||s(this,f).set(e,new Set),s(this,f).get(e)?.add(t),await this.exec(`LISTEN ${e}`),async()=>{await this.unlisten(e,t)}}async unlisten(e,t){await this.waitReady,t?s(this,f).get(e)?.delete(t):s(this,f).delete(e),s(this,f).get(e)?.size===0&&await this.exec(`UNLISTEN ${e}`)}onNotification(e){return s(this,W).add(e),()=>{s(this,W).delete(e)}}offNotification(e){s(this,W).delete(e)}async dumpDataDir(){return await h(this,o,g).call(this,"dumpDataDir")}onLeaderChange(e){return s(this,w).addEventListener("leader-change",e),()=>{s(this,w).removeEventListener("leader-change",e)}}offLeaderChange(e){s(this,w).removeEventListener("leader-change",e)}};L=new WeakMap,b=new WeakMap,A=new WeakMap,T=new WeakMap,O=new WeakMap,w=new WeakMap,R=new WeakMap,E=new WeakMap,m=new WeakMap,C=new WeakMap,I=new WeakMap,q=new WeakMap,M=new WeakMap,k=new WeakMap,G=new WeakMap,f=new WeakMap,W=new WeakMap,D=new WeakMap,$=new WeakMap,o=new WeakSet,F=async function(e={}){for(let[i,v]of Object.entries(s(this,D))){if(v instanceof URL)throw new Error("URL extensions are not supported on the client side of a worker");{let d=await v.setup(this,{},!0);if(d.emscriptenOpts&&console.warn(`PGlite extension ${i} returned emscriptenOpts, these are not supported on the client side of a worker`),d.namespaceObj){let u=this;u[i]=d.namespaceObj}d.bundlePath&&console.warn(`PGlite extension ${i} returned bundlePath, this is not supported on the client side of a worker`),d.init&&await d.init(),d.close&&s(this,$).push(d.close)}}await s(this,I);let{extensions:t,...r}=e;s(this,m).postMessage({type:"init",options:r}),await s(this,q);let a=`pglite-tab-close:${s(this,R)}`;y(this,G,await H(a));let n=`pglite-broadcast:${s(this,C)}`;y(this,M,new BroadcastChannel(n));let p=`pglite-tab:${s(this,R)}`;y(this,k,new BroadcastChannel(p)),s(this,M).addEventListener("message",async i=>{i.data.type==="leader-here"?(y(this,E,!1),s(this,w).dispatchEvent(new Event("leader-change")),h(this,o,S).call(this)):i.data.type==="notify"&&h(this,o,z).call(this,i.data.channel,i.data.payload)}),s(this,k).addEventListener("message",async i=>{i.data.type==="connected"&&(y(this,E,!0),s(this,w).dispatchEvent(new Event("connected")),y(this,b,await h(this,o,g).call(this,"getDebugLevel")),y(this,A,!0))}),s(this,m).addEventListener("message",async i=>{i.data.type==="leader-now"&&(y(this,O,!0),s(this,w).dispatchEvent(new Event("leader-change")))}),h(this,o,S).call(this)},S=async function(){s(this,E)||(s(this,M).postMessage({type:"tab-here",id:s(this,R)}),setTimeout(()=>h(this,o,S).call(this),16))},g=async function(e,...t){let r=N(),a={type:"rpc-call",callId:r,method:e,args:t};return s(this,k).postMessage(a),await new Promise((n,p)=>{let i=u=>{if(u.data.callId!==r)return;d();let x=u.data;if(x.type==="rpc-return")n(x.result);else if(x.type==="rpc-error"){let P=new Error(x.error.message);Object.assign(P,x.error),p(P)}else p(new Error("Invalid message"))},v=()=>{d(),p(new B)},d=()=>{s(this,k).removeEventListener("message",i),s(this,w).removeEventListener("leader-change",v)};s(this,w).addEventListener("leader-change",v),s(this,k).addEventListener("message",i)})},z=function(e,t){let r=s(this,f).get(e);if(r)for(let a of r)queueMicrotask(()=>a(t));for(let a of s(this,W))queueMicrotask(()=>a(e,t))};var Q=U;async function _({init:c}){postMessage({type:"here"});let e=await new Promise(d=>{addEventListener("message",u=>{u.data.type==="init"&&d(u.data.options)},{once:!0})}),t=e.id??`${import.meta.url}:${e.dataDir??""}`;postMessage({type:"ready",id:t});let r=`pglite-election-lock:${t}`,a=`pglite-broadcast:${t}`,n=new BroadcastChannel(a),p=new Set;await H(r);let i=c(e);n.onmessage=async d=>{let u=d.data;switch(u.type){case"tab-here":J(u.id,await i,p);break}},n.postMessage({type:"leader-here",id:t}),postMessage({type:"leader-now"}),(await i).onNotification((d,u)=>{n.postMessage({type:"notify",channel:d,payload:u})})}function J(c,e,t){if(t.has(c))return;t.add(c);let r=`pglite-tab:${c}`,a=`pglite-tab-close:${c}`,n=new BroadcastChannel(r);navigator.locks.request(a,()=>new Promise(i=>{n.close(),t.delete(c),i()}));let p=K(e);n.addEventListener("message",async i=>{let v=i.data;switch(v.type){case"rpc-call":{let{callId:d,method:u,args:x}=v;try{let P=await p[u](...x);n.postMessage({type:"rpc-return",callId:d,result:P})}catch(P){console.error(P),n.postMessage({type:"rpc-error",callId:d,error:{message:P.message}})}break}}}),n.postMessage({type:"connected"})}function K(c){let e=new Map;return{async getDebugLevel(){return c.debug},async close(){await c.close()},async query(t,r,a){return await c.query(t,r,a)},async sql(t,r,a){let n=t;return n.raw=r,await c.sql(n,...a)},async exec(t,r){return await c.exec(t,r)},async transactionStart(){let t=N(),{promise:r,resolve:a}=V();return e.set(t,r),c.transaction(n=>new Promise((p,i)=>{a({tx:n,resolve:p,reject:i})})),t},async transactionCommit(t){if(!e.has(t))throw new Error("No transaction");(await e.get(t)).resolve(),e.delete(t)},async transactionQuery(t,r,a,n){if(!e.has(t))throw new Error("No transaction");return await(await e.get(t)).tx.query(r,a,n)},async transactionSql(t,r,a,n){if(!e.has(t))throw new Error("No transaction");let p=r;return p.raw=a,await(await e.get(t)).tx.sql(p,...n)},async transactionExec(t,r,a){if(!e.has(t))throw new Error("No transaction");return(await e.get(t)).tx.exec(r,a)},async transactionRollback(t){if(!e.has(t))throw new Error("No transaction");let r=await e.get(t);await r.tx.rollback(),r.reject(new Error("Transaction rolled back")),e.delete(t)},async execProtocol(t){return await c.execProtocol(t)},async execProtocolRaw(t){return await c.execProtocolRaw(t)},async dumpDataDir(){return await c.dumpDataDir()}}}var B=class extends Error{constructor(){super("Leader changed, pending operation in indeterminate state")}};async function H(c){let e;return await new Promise(t=>{navigator.locks.request(c,()=>new Promise(r=>{e=r,t()}))}),e}function V(){let c,e;return{promise:new Promise((r,a)=>{c=r,e=a}),resolve:c,reject:e}}export{B as LeaderChangedError,Q as PGliteWorker,_ as worker};
import{G as j}from"../chunk-7M5G4I52.js";import"../chunk-TAZBUB4Z.js";import{c as U}from"../chunk-3BCYDNSE.js";import{d as t,e as l,f as y,g as h,i as Q}from"../chunk-Y3AVQXKT.js";Q();var W,B,C,M,_,m,L,b,k,A,T,O,x,v,G,P,R,I,$,o,H,D,w,K,F=class F extends j{constructor(e,r){super();l(this,o);l(this,W);l(this,B,0);l(this,C,!1);l(this,M,!1);l(this,_,!1);l(this,m,new EventTarget);l(this,L);l(this,b,!1);l(this,k);l(this,A);l(this,T);l(this,O);l(this,x);l(this,v);l(this,G);l(this,P,new Map);l(this,R,new Set);l(this,I);l(this,$,[]);y(this,k,e),y(this,L,U()),y(this,I,r?.extensions??{}),y(this,T,new Promise(d=>{t(this,k).addEventListener("message",s=>{if(s.data.type==="here")d();else throw new Error("Invalid message")},{once:!0})})),y(this,O,new Promise(d=>{let s=c=>{c.data.type==="ready"&&(y(this,A,c.data.id),t(this,k).removeEventListener("message",s),d())};t(this,k).addEventListener("message",s)})),y(this,W,h(this,o,H).call(this,r))}static async create(e,r){let d=new F(e,r);return await t(d,W),d}get waitReady(){return new Promise(e=>{t(this,W).then(()=>{t(this,b)?e():e(new Promise(r=>{t(this,m).addEventListener("connected",()=>{r()})}))})})}get debug(){return t(this,B)}get ready(){return t(this,C)}get closed(){return t(this,M)}get isLeader(){return t(this,_)}async close(){var e;t(this,M)||(y(this,M,!0),t(this,x)?.close(),t(this,v)?.close(),(e=t(this,G))==null||e.call(this),t(this,k).terminate())}async[Symbol.asyncDispose](){await this.close()}async execProtocolRaw(e){return await h(this,o,w).call(this,"execProtocolRaw",e)}async execProtocol(e){return await h(this,o,w).call(this,"execProtocol",e)}async syncToFs(){await h(this,o,w).call(this,"syncToFs")}async listen(e,r){return await this.waitReady,t(this,P).has(e)||t(this,P).set(e,new Set),t(this,P).get(e)?.add(r),await this.exec(`LISTEN ${e}`),async()=>{await this.unlisten(e,r)}}async unlisten(e,r){await this.waitReady,r?t(this,P).get(e)?.delete(r):t(this,P).delete(e),t(this,P).get(e)?.size===0&&await this.exec(`UNLISTEN ${e}`)}onNotification(e){return t(this,R).add(e),()=>{t(this,R).delete(e)}}offNotification(e){t(this,R).delete(e)}async dumpDataDir(){return await h(this,o,w).call(this,"dumpDataDir")}onLeaderChange(e){return t(this,m).addEventListener("leader-change",e),()=>{t(this,m).removeEventListener("leader-change",e)}}offLeaderChange(e){t(this,m).removeEventListener("leader-change",e)}async _handleBlob(e){await h(this,o,w).call(this,"_handleBlob",e)}async _getWrittenBlob(){return await h(this,o,w).call(this,"_getWrittenBlob")}async _cleanupBlob(){await h(this,o,w).call(this,"_cleanupBlob")}async _checkReady(){await this.waitReady}async _runExclusiveQuery(e){await h(this,o,w).call(this,"_acquireQueryLock");try{return await e()}finally{await h(this,o,w).call(this,"_releaseQueryLock")}}async _runExclusiveTransaction(e){await h(this,o,w).call(this,"_acquireTransactionLock");try{return await e()}finally{await h(this,o,w).call(this,"_releaseTransactionLock")}}};W=new WeakMap,B=new WeakMap,C=new WeakMap,M=new WeakMap,_=new WeakMap,m=new WeakMap,L=new WeakMap,b=new WeakMap,k=new WeakMap,A=new WeakMap,T=new WeakMap,O=new WeakMap,x=new WeakMap,v=new WeakMap,G=new WeakMap,P=new WeakMap,R=new WeakMap,I=new WeakMap,$=new WeakMap,o=new WeakSet,H=async function(e={}){for(let[i,u]of Object.entries(t(this,I))){if(u instanceof URL)throw new Error("URL extensions are not supported on the client side of a worker");{let a=await u.setup(this,{},!0);if(a.emscriptenOpts&&console.warn(`PGlite extension ${i} returned emscriptenOpts, these are not supported on the client side of a worker`),a.namespaceObj){let E=this;E[i]=a.namespaceObj}a.bundlePath&&console.warn(`PGlite extension ${i} returned bundlePath, this is not supported on the client side of a worker`),a.init&&await a.init(),a.close&&t(this,$).push(a.close)}}await t(this,T);let{extensions:r,...d}=e;t(this,k).postMessage({type:"init",options:d}),await t(this,O);let s=`pglite-tab-close:${t(this,L)}`;y(this,G,await N(s));let c=`pglite-broadcast:${t(this,A)}`;y(this,x,new BroadcastChannel(c));let p=`pglite-tab:${t(this,L)}`;y(this,v,new BroadcastChannel(p)),t(this,x).addEventListener("message",async i=>{i.data.type==="leader-here"?(y(this,b,!1),t(this,m).dispatchEvent(new Event("leader-change")),h(this,o,D).call(this)):i.data.type==="notify"&&h(this,o,K).call(this,i.data.channel,i.data.payload)}),t(this,v).addEventListener("message",async i=>{i.data.type==="connected"&&(y(this,b,!0),t(this,m).dispatchEvent(new Event("connected")),y(this,B,await h(this,o,w).call(this,"getDebugLevel")),y(this,C,!0))}),t(this,k).addEventListener("message",async i=>{i.data.type==="leader-now"&&(y(this,_,!0),t(this,m).dispatchEvent(new Event("leader-change")))}),h(this,o,D).call(this)},D=async function(){t(this,b)||(t(this,x).postMessage({type:"tab-here",id:t(this,L)}),setTimeout(()=>h(this,o,D).call(this),16))},w=async function(e,...r){let d=U(),s={type:"rpc-call",callId:d,method:e,args:r};return t(this,v).postMessage(s),await new Promise((c,p)=>{let i=E=>{if(E.data.callId!==d)return;a();let f=E.data;if(f.type==="rpc-return")c(f.result);else if(f.type==="rpc-error"){let S=new Error(f.error.message);Object.assign(S,f.error),p(S)}else p(new Error("Invalid message"))},u=()=>{a(),p(new q)},a=()=>{t(this,v).removeEventListener("message",i),t(this,m).removeEventListener("leader-change",u)};t(this,m).addEventListener("leader-change",u),t(this,v).addEventListener("message",i)})},K=function(e,r){let d=t(this,P).get(e);if(d)for(let s of d)queueMicrotask(()=>s(r));for(let s of t(this,R))queueMicrotask(()=>s(e,r))};var z=F;async function te({init:g}){postMessage({type:"here"});let n=await new Promise(u=>{addEventListener("message",a=>{a.data.type==="init"&&u(a.data.options)},{once:!0})}),e=n.id??`${import.meta.url}:${n.dataDir??""}`;postMessage({type:"ready",id:e});let r=`pglite-election-lock:${e}`,d=`pglite-broadcast:${e}`,s=new BroadcastChannel(d),c=new Set;await N(r);let p=g(n);s.onmessage=async u=>{let a=u.data;switch(a.type){case"tab-here":J(a.id,await p,c);break}},s.postMessage({type:"leader-here",id:e}),postMessage({type:"leader-now"}),(await p).onNotification((u,a)=>{s.postMessage({type:"notify",channel:u,payload:a})})}function J(g,n,e){if(e.has(g))return;e.add(g);let r=`pglite-tab:${g}`,d=`pglite-tab-close:${g}`,s=new BroadcastChannel(r);navigator.locks.request(d,()=>new Promise(p=>{s.close(),e.delete(g),p()}));let c=V(g,n);s.addEventListener("message",async p=>{let i=p.data;switch(i.type){case"rpc-call":{await n.waitReady;let{callId:u,method:a,args:E}=i;try{let f=await c[a](...E);s.postMessage({type:"rpc-return",callId:u,result:f})}catch(f){console.error(f),s.postMessage({type:"rpc-error",callId:u,error:{message:f.message}})}break}}}),s.postMessage({type:"connected"})}function V(g,n){let e=null,r=null,d=`pglite-tab-close:${g}`;return N(d).then(()=>{r&&n.exec("ROLLBACK"),e?.(),r?.()}),{async getDebugLevel(){return n.debug},async close(){await n.close()},async execProtocol(s){return(await n.execProtocol(s)).map(([p,i])=>{if(i.byteLength!==i.buffer.byteLength){let u=new ArrayBuffer(i.byteLength),a=new Uint8Array(u);return a.set(i),[p,a]}else return[p,i]})},async execProtocolRaw(s){let c=await n.execProtocolRaw(s);if(c.byteLength!==c.buffer.byteLength){let p=new ArrayBuffer(c.byteLength),i=new Uint8Array(p);return i.set(c),i}else return c},async dumpDataDir(){return await n.dumpDataDir()},async syncToFs(){return await n.syncToFs()},async _handleBlob(s){return await n._handleBlob(s)},async _getWrittenBlob(){return await n._getWrittenBlob()},async _cleanupBlob(){return await n._cleanupBlob()},async _checkReady(){return await n._checkReady()},async _acquireQueryLock(){return new Promise(s=>{n._runExclusiveQuery(()=>new Promise(c=>{e=c,s()}))})},async _releaseQueryLock(){e?.(),e=null},async _acquireTransactionLock(){return new Promise(s=>{n._runExclusiveTransaction(()=>new Promise(c=>{r=c,s()}))})},async _releaseTransactionLock(){r?.(),r=null}}}var q=class extends Error{constructor(){super("Leader changed, pending operation in indeterminate state")}};async function N(g){let n;return await new Promise(e=>{navigator.locks.request(g,()=>new Promise(r=>{n=r,e()}))}),n}export{q as LeaderChangedError,z as PGliteWorker,te as worker};
//# sourceMappingURL=index.js.map
{
"name": "@electric-sql/pglite",
"version": "0.2.5",
"version": "0.2.6",
"private": false,

@@ -5,0 +5,0 @@ "publishConfig": {

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

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

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc