diff --git a/.env.template b/.env.template
new file mode 100644
index 0000000..c475336
--- /dev/null
+++ b/.env.template
@@ -0,0 +1,7 @@
+# copy to .env.test and fill in the blanks
+VITE_NEON_DB_URL="postgresql:// ..."
+VITE_NEON_DB_POOLER_URL="postgresql:// ..."
+VITE_WSPROXY="... .workers.dev"
+VITE_VERCEL_TOKEN="..."
+VITE_CLERK_USER="... @neon.tech"
+VITE_CLERK_SECRET_KEY="sk_test_ ..."
diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml
index 50d5535..8d46933 100644
--- a/.github/workflows/lint.yml
+++ b/.github/workflows/lint.yml
@@ -11,14 +11,14 @@ jobs:
steps:
# setup
- uses: actions/checkout@v4
- - uses: oven-sh/setup-bun@v2
+ - uses: actions/setup-node@v4
- name: Install package dependencies
- run: bun install
+ run: npm install
# goal
- name: Check TypeScript types
- run: bun run check
+ run: npm run check
- name: Check code formatting
- run: bun run format
+ run: npm run format
diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml
index 2cf54ae..651a0eb 100644
--- a/.github/workflows/test.yml
+++ b/.github/workflows/test.yml
@@ -5,17 +5,48 @@ on:
branches:
- main
+env:
+ VITE_NEON_DB_URL: ${{ secrets.VITE_NEON_DB_URL }}
+ VITE_NEON_DB_POOLER_URL: ${{ secrets.VITE_NEON_DB_POOLER_URL }}
+ VITE_VERCEL_TOKEN: ${{ secrets.VITE_VERCEL_TOKEN }}
+ VITE_CLERK_SECRET_KEY: ${{ secrets.VITE_CLERK_SECRET_KEY }}
+ VITE_WSPROXY: ${{ vars.VITE_WSPROXY }}
+ VITE_CLERK_USER: ${{ vars.VITE_CLERK_USER }}
+
jobs:
- test:
+ test-node-16:
+ runs-on: ubuntu-latest
+ steps:
+ # setup
+ - uses: actions/checkout@v4
+ - uses: actions/setup-node@v4
+ with:
+ node-version: 16
+
+ - name: Install package dependencies
+ run: |
+ # strip Prisma, whose preinstall script throws on Node versions less than 18.x
+ sudo apt-get install jq && \
+ mv package.json package.json.old && \
+ jq 'del(.devDependencies.prisma, .devDependencies."@prisma/client")' package.json.old > package.json
+ npm install
+
+ # goal
+ - name: Run CLI-based tests in Node 16 (no native WebSocket or fetch), node environment
+ run: npm run test:node
+
+ test-node-lts:
runs-on: ubuntu-latest
steps:
# setup
- uses: actions/checkout@v4
- - uses: oven-sh/setup-bun@v2
+ - uses: actions/setup-node@v4
+ with:
+ node-version: lts/*
- name: Install package dependencies
- run: bun install
+ run: npm install
# goal
- - name: Run tests
- run: bun run test
+ - name: Run all tests in Node LTS
+ run: npm run test
diff --git a/.gitignore b/.gitignore
index 05d3425..d1eee11 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,4 +1,6 @@
.dev.vars
-.env.local
+.env.*
+!.env.template
node_modules
tmp
+.DS_Store
diff --git a/api-extractor.json b/api-extractor.json
new file mode 100644
index 0000000..eb63b62
--- /dev/null
+++ b/api-extractor.json
@@ -0,0 +1,29 @@
+{
+ "mainEntryPointFilePath": "dist/dts/export/index.d.ts",
+ "newlineKind": "lf",
+ "enumMemberOrder": "preserve",
+ "bundledPackages": ["subtls"],
+ "dtsRollup": {
+ "enabled": true,
+ "untrimmedFilePath": "dist/dts/_extracted.d.ts"
+ },
+ "apiReport": {
+ "enabled": false
+ },
+ "docModel": {
+ "enabled": false
+ },
+ "tsdocMetadata": {
+ "enabled": false
+ },
+ "messages": {
+ "extractorMessageReporting": {
+ "ae-wrong-input-file-type": {
+ "logLevel": "none"
+ },
+ "ae-missing-release-tag": {
+ "logLevel": "none"
+ }
+ }
+ }
+}
diff --git a/dist/dts/_extracted.d.ts b/dist/dts/_extracted.d.ts
new file mode 100644
index 0000000..82e9d68
--- /dev/null
+++ b/dist/dts/_extracted.d.ts
@@ -0,0 +1,784 @@
+///
+
+import { BindConfig } from 'pg';
+import { Client as Client_2 } from 'pg';
+import { ClientBase } from 'pg';
+import { ClientConfig } from 'pg';
+import { Connection } from 'pg';
+import { ConnectionConfig } from 'pg';
+import { CustomTypesConfig } from 'pg';
+import { Defaults } from 'pg';
+import { defaults } from 'pg';
+import { EventEmitter } from 'events';
+import { Events } from 'pg';
+import { ExecuteConfig } from 'pg';
+import { FieldDef } from 'pg';
+import { MessageConfig } from 'pg';
+import { Notification } from 'pg';
+import { Pool as Pool_2 } from 'pg';
+import { PoolConfig } from 'pg';
+import { Query } from 'pg';
+import { QueryArrayConfig } from 'pg';
+import { QueryArrayResult } from 'pg';
+import { QueryConfig } from 'pg';
+import type { QueryConfigValues } from 'pg';
+import { QueryParse } from 'pg';
+import { QueryResult } from 'pg';
+import { QueryResultBase } from 'pg';
+import { QueryResultRow } from 'pg';
+import { ResultBuilder } from 'pg';
+import type { Socket } from 'net';
+import { Submittable } from 'pg';
+import { types } from 'pg';
+
+declare const allKeyUsages: readonly ["digitalSignature", "nonRepudiation", "keyEncipherment", "dataEncipherment", "keyAgreement", "keyCertSign", "cRLSign", "encipherOnly", "decipherOnly"];
+
+declare class ASN1Bytes extends Bytes {
+ readASN1Length(comment?: string): number;
+ expectASN1Length(comment?: string): readonly [() => void, () => number];
+ readASN1OID(comment?: string): string;
+ readASN1Boolean(comment?: string): boolean;
+ readASN1UTCTime(): Date;
+ readASN1GeneralizedTime(): Date;
+ readASN1BitString(): Uint8Array;
+}
+
+declare function base64Decode(input: string, charCodes?: typeof stdCharCodes, autoPad?: boolean): Uint8Array;
+
+export { BindConfig }
+
+export declare const _bundleExt: 'js' | 'mjs';
+
+declare class Bytes {
+ offset: number;
+ dataView: DataView;
+ data: Uint8Array;
+ comments: Record;
+ indents: Record;
+ indent: number;
+ constructor(arrayOrMaxBytes: number | Uint8Array);
+ extend(arrayOrMaxBytes: number | Uint8Array): void;
+ remaining(): number;
+ subarray(length: number): Uint8Array;
+ skip(length: number, comment?: string): this;
+ comment(s: string, offset?: number): this;
+ lengthComment(length: number, comment?: string, inclusive?: boolean): string;
+ readBytes(length: number): Uint8Array;
+ readUTF8String(length: number): string;
+ readUTF8StringNullTerminated(): string;
+ readUint8(comment?: string): number;
+ readUint16(comment?: string): number;
+ readUint24(comment?: string): number;
+ readUint32(comment?: string): number;
+ expectBytes(expected: Uint8Array | number[], comment?: string): void;
+ expectUint8(expectedValue: number, comment?: string): void;
+ expectUint16(expectedValue: number, comment?: string): void;
+ expectUint24(expectedValue: number, comment?: string): void;
+ expectUint32(expectedValue: number, comment?: string): void;
+ expectLength(length: number, indentDelta?: number): readonly [() => void, () => number];
+ expectLengthUint8(comment?: string): readonly [() => void, () => number];
+ expectLengthUint16(comment?: string): readonly [() => void, () => number];
+ expectLengthUint24(comment?: string): readonly [() => void, () => number];
+ expectLengthUint32(comment?: string): readonly [() => void, () => number];
+ expectLengthUint8Incl(comment?: string): readonly [() => void, () => number];
+ expectLengthUint16Incl(comment?: string): readonly [() => void, () => number];
+ expectLengthUint24Incl(comment?: string): readonly [() => void, () => number];
+ expectLengthUint32Incl(comment?: string): readonly [() => void, () => number];
+ writeBytes(bytes: number[] | Uint8Array): this;
+ writeUTF8String(s: string): this;
+ writeUTF8StringNullTerminated(s: string): this;
+ writeUint8(value: number, comment?: string): Bytes;
+ writeUint16(value: number, comment?: string): Bytes;
+ writeUint24(value: number, comment?: string): Bytes;
+ writeUint32(value: number, comment?: string): Bytes;
+ _writeLengthGeneric(lengthBytes: 1 | 2 | 3 | 4, inclusive: boolean, comment?: string): () => void;
+ writeLengthUint8(comment?: string): () => void;
+ writeLengthUint16(comment?: string): () => void;
+ writeLengthUint24(comment?: string): () => void;
+ writeLengthUint32(comment?: string): () => void;
+ writeLengthUint8Incl(comment?: string): () => void;
+ writeLengthUint16Incl(comment?: string): () => void;
+ writeLengthUint24Incl(comment?: string): () => void;
+ writeLengthUint32Incl(comment?: string): () => void;
+ array(): Uint8Array;
+ commentedString(all?: boolean): string;
+}
+
+declare class Cert {
+ serialNumber: Uint8Array;
+ algorithm: OID;
+ issuer: DistinguishedName;
+ validityPeriod: {
+ notBefore: Date;
+ notAfter: Date;
+ };
+ subject: DistinguishedName;
+ publicKey: {
+ identifiers: OID[];
+ data: Uint8Array;
+ all: Uint8Array;
+ };
+ signature: Uint8Array;
+ keyUsage?: {
+ critical?: boolean;
+ usages: Set;
+ };
+ subjectAltNames?: string[];
+ extKeyUsage?: {
+ clientTls?: true;
+ serverTls?: true;
+ };
+ authorityKeyIdentifier?: Uint8Array;
+ subjectKeyIdentifier?: Uint8Array;
+ basicConstraints?: {
+ critical?: boolean;
+ ca?: boolean;
+ pathLength?: number;
+ } | undefined;
+ signedData: Uint8Array;
+ static distinguishedNamesAreEqual(dn1: DistinguishedName, dn2: DistinguishedName): boolean;
+ static stringFromDistinguishedName(dn: DistinguishedName): string;
+ constructor(certData: Uint8Array | ASN1Bytes | CertJSON);
+ subjectAltNameMatchingHost(host: string): string | undefined;
+ isValidAtMoment(moment?: Date): boolean;
+ description(): string;
+ toJSON(): {
+ serialNumber: string;
+ algorithm: string;
+ issuer: DistinguishedName;
+ validityPeriod: {
+ notBefore: string;
+ notAfter: string;
+ };
+ subject: DistinguishedName;
+ publicKey: {
+ identifiers: string[];
+ data: string;
+ all: string;
+ };
+ signature: string;
+ keyUsage: {
+ critical: boolean | undefined;
+ usages: ("digitalSignature" | "nonRepudiation" | "keyEncipherment" | "dataEncipherment" | "keyAgreement" | "keyCertSign" | "cRLSign" | "encipherOnly" | "decipherOnly")[];
+ };
+ subjectAltNames: string[] | undefined;
+ extKeyUsage: {
+ clientTls?: true;
+ serverTls?: true;
+ } | undefined;
+ authorityKeyIdentifier: string | undefined;
+ subjectKeyIdentifier: string | undefined;
+ basicConstraints: {
+ critical?: boolean;
+ ca?: boolean;
+ pathLength?: number;
+ } | undefined;
+ signedData: string;
+ };
+ static uint8ArraysFromPEM(pem: string): Uint8Array[];
+ static fromPEM(pem: string): Cert[];
+}
+
+declare type CertJSON = ReturnType;
+
+export declare interface Client {
+ connection: Connection & {
+ stream: neonConfig;
+ sendSCRAMClientFinalMessage: (response: any) => void;
+ ssl: any;
+ };
+ _handleReadyForQuery: any;
+ _handleAuthCleartextPassword: any;
+ startup: any;
+ getStartupConf: any;
+ saslSession: any;
+}
+
+/**
+ * The node-postgres `Client` object re-exported with minor modifications.
+ * https://node-postgres.com/apis/client
+ */
+export declare class Client extends Client_2 {
+ config: any;
+ get neonConfig(): neonConfig;
+ constructor(config: any);
+ connect(): Promise;
+ connect(callback: (err?: Error) => void): void;
+ _handleAuthSASLContinue(msg: any): Promise;
+}
+
+export { ClientBase }
+
+export { ClientConfig }
+
+export { Connection }
+
+export { ConnectionConfig }
+
+export { CustomTypesConfig }
+
+declare interface DataRequest {
+ bytes: number;
+ resolve: (data: Uint8Array | undefined) => void;
+}
+
+export { Defaults }
+
+export { defaults }
+
+declare type DistinguishedName = Record;
+
+export { Events }
+
+export { ExecuteConfig }
+
+export declare interface FetchEndpointOptions {
+ jwtAuth?: boolean;
+}
+
+export { FieldDef }
+
+export declare interface FullQueryResults {
+ fields: FieldDef[];
+ command: string;
+ rowCount: number;
+ rows: QueryRows;
+ rowAsArray: ArrayMode;
+}
+
+declare function hexFromU8(u8: Uint8Array | number[], spacer?: string): string;
+
+export declare interface HTTPQueryOptions {
+ /**
+ * When `arrayMode` is `false`, which is the default, result rows are
+ * returned as objects whose keys represent column names, such as
+ * `{ id: 1 }`).
+ *
+ * When `arrayMode` is `true`, rows are returned as arrays (and keys are not
+ * provided), e.g. `[1]`.
+ */
+ arrayMode?: ArrayMode;
+ /**
+ * When `fullResults` is `false`, which is the default, only result rows are
+ * returned, e.g. `[{ id: 1 }]`).
+ *
+ * When `fullResults` is `true`, a result object is returned that matches
+ * what's returned by node-postgres. This has a `rows` property, which is an
+ * array of result rows, plus `fields`, which provides column names and
+ * types, `command` and `rowCount`.
+ */
+ fullResults?: FullResults;
+ /**
+ * Any options in `fetchOptions` are merged in to the options passed to
+ * `fetch`. In case of conflict with what would otherwise be passed, these
+ * options take precedence.
+ */
+ fetchOptions?: Record;
+ /**
+ * JWT auth token to be passed as the Bearer token in the Authorization header.
+ * Can be string, or a function (sync or async) returning a string.
+ *
+ * Default: `undefined`
+ */
+ authToken?: string | (() => Promise | string);
+ /**
+ * Custom type parsers. See https://github.com/brianc/node-pg-types.
+ */
+ types?: typeof types;
+ queryCallback?: (query: ParameterizedQuery) => void;
+ resultCallback?: (query: ParameterizedQuery, result: any, rows: any, opts: any) => void;
+}
+
+export declare interface HTTPTransactionOptions extends HTTPQueryOptions {
+ isolationLevel?: 'ReadUncommitted' | 'ReadCommitted' | 'RepeatableRead' | 'Serializable';
+ readOnly?: boolean;
+ deferrable?: boolean;
+}
+
+export { MessageConfig }
+
+/**
+ * This function returns an async tagged-template function that runs a single
+ * SQL query (no session or transactions) with low latency over https. Support
+ * for multiple queries (as a non-interactive transaction) is provided by
+ * the `transaction` property of the query function.
+ *
+ * By default, the query function returns database rows directly. Types should
+ * match those returned by this driver (i.e. Pool or Client) over WebSockets.
+ *
+ * The returned function can also be called directly (i.e. not as a template
+ * function). In that case, pass it a query string with embedded `$1`, `$2`
+ * (etc.), followed by an array of query parameters, followed (optionally) by
+ * any of the same options you can pass to this function.
+ *
+ * Some examples:
+ * ```
+ * import { neon } from "@neondatabase/serverless";
+ * const h = "hello", w = "world";
+ *
+ * // example 1: default options, tagged-template usage
+ * const sql = neon("postgres://user:pass@host/db");
+ * const rows = await sql`SELECT ${h} || ' ' || ${w} AS greeting`;
+ * // -> [ { greeting: "hello world" } ]
+ *
+ * // example 2: `arrayMode` and `fullResults` options, ordinary function usage
+ * const options = { arrayMode: true, fullResults: true };
+ * const sql = neon("postgres://user:pass@host/db", options);
+ * const rows = await sql("SELECT $1 || ' ' || $2 AS greeting", [h, w]);
+ * // -> {
+ * // command: "SELECT",
+ * // fields: [ { name: "greeting", dataTypeID: 25 } ],
+ * // rowAsArray: true,
+ * // rowCount: 1,
+ * // rows: [ [ "hello world" ] ]
+ * // }
+ *
+ * // example 3: `fetchOptions` option, ordinary function usage
+ * const sql = neon("postgres://user:pass@host/db");
+ * const rows = await sql(
+ * "SELECT $1 || ' ' || $2 AS greeting", [h, w],
+ * { fetchOptions: { priority: "high" } }
+ * );
+ * // -> [ { greeting: "hello world" } ]
+ * ```
+ *
+ * @param connectionString - this has the format `postgres://user:pass@host/db`
+ * @param options - pass `arrayMode: true` to receive results as an array of
+ * arrays, instead of the default array of objects; pass `fullResults: true`
+ * to receive a complete result object similar to one returned by node-postgres
+ * (with properties `rows`, `fields`, `command`, `rowCount`, `rowAsArray`);
+ * pass as `fetchOptions` an object which will be merged into the options
+ * passed to `fetch`.
+ */
+export declare function neon(connectionString: string, { arrayMode: neonOptArrayMode, fullResults: neonOptFullResults, fetchOptions: neonOptFetchOptions, isolationLevel: neonOptIsolationLevel, readOnly: neonOptReadOnly, deferrable: neonOptDeferrable, queryCallback, resultCallback, authToken, }?: HTTPTransactionOptions): NeonQueryFunction;
+
+export declare class neonConfig extends EventEmitter {
+ static defaults: SocketDefaults;
+ static opts: Partial;
+ /**
+ * **Experimentally**, when `poolQueryViaFetch` is `true`, and no listeners
+ * for the `"connect"`, `"acquire"`, `"release"` or `"remove"` events are set
+ * on the `Pool`, queries via `Pool.query()` will be sent by low-latency HTTP
+ * fetch request.
+ *
+ * Default: `false`.
+ */
+ static get poolQueryViaFetch(): SocketDefaults["poolQueryViaFetch"];
+ static set poolQueryViaFetch(newValue: SocketDefaults['poolQueryViaFetch']);
+ /**
+ * Set `fetchEndpoint` to set the server endpoint to be sent queries via http
+ * fetch. May be useful in local development (e.g. to set a port that's not
+ * the default 443).
+ *
+ * Provide either the full endpoint URL, or a function that takes the
+ * database host address, port and options, and returns the full endpoint URL
+ * (including protocol).
+ *
+ * Default: custom logic to connect to Neon endpoints.
+ */
+ static get fetchEndpoint(): SocketDefaults["fetchEndpoint"];
+ static set fetchEndpoint(newValue: SocketDefaults['fetchEndpoint']);
+ /**
+ * **DEPRECATED**. Previously, only when `fetchConnectionCache` was `true`
+ * did queries carried via HTTP fetch make use of a connection pool/cache
+ * on the server. All queries now use the connection pool/cache: this setting
+ * is ignored.
+ *
+ * Default: `true`.
+ */
+ static get fetchConnectionCache(): SocketDefaults["fetchConnectionCache"];
+ static set fetchConnectionCache(newValue: SocketDefaults['fetchConnectionCache']);
+ /**
+ * The `fetchFunction` option allows you to supply an alternative function
+ * for making http requests. The function must accept the same arguments as
+ * native `fetch`.
+ *
+ * Default: `undefined`.
+ */
+ static get fetchFunction(): SocketDefaults["fetchFunction"];
+ static set fetchFunction(newValue: SocketDefaults['fetchFunction']);
+ /**
+ * Only if no global `WebSocket` object is available, such as in older
+ * versions of Node, set `webSocketConstructor` to the constructor for a
+ * custom WebSocket implementation, such as those provided by `ws` or
+ * `undici`.
+ *
+ * Default: `undefined`.
+ */
+ static get webSocketConstructor(): SocketDefaults["webSocketConstructor"];
+ static set webSocketConstructor(newValue: SocketDefaults['webSocketConstructor']);
+ get webSocketConstructor(): SocketDefaults["webSocketConstructor"];
+ set webSocketConstructor(newValue: SocketDefaults['webSocketConstructor']);
+ /**
+ * Set `wsProxy` to use your own WebSocket proxy server.
+ *
+ * Provide either the proxy server’s domain name, or a function that takes
+ * the database host and port and returns the proxy server address (without
+ * protocol).
+ *
+ * Example: `(host, port) => "myproxy.example.net?address=" + host + ":" + port`
+ *
+ * Default: `host => host + '/v2'`
+ */
+ static get wsProxy(): SocketDefaults["wsProxy"];
+ static set wsProxy(newValue: SocketDefaults['wsProxy']);
+ get wsProxy(): SocketDefaults["wsProxy"];
+ set wsProxy(newValue: SocketDefaults['wsProxy']);
+ /**
+ * Batch multiple network writes per run-loop into a single outgoing
+ * WebSocket message.
+ *
+ * Default: `true`.
+ */
+ static get coalesceWrites(): SocketDefaults["coalesceWrites"];
+ static set coalesceWrites(newValue: SocketDefaults['coalesceWrites']);
+ get coalesceWrites(): SocketDefaults["coalesceWrites"];
+ set coalesceWrites(newValue: SocketDefaults['coalesceWrites']);
+ /**
+ * Use a secure (`wss:`) connection to the WebSocket proxy.
+ *
+ * Default: `true`.
+ */
+ static get useSecureWebSocket(): SocketDefaults["useSecureWebSocket"];
+ static set useSecureWebSocket(newValue: SocketDefaults['useSecureWebSocket']);
+ get useSecureWebSocket(): SocketDefaults["useSecureWebSocket"];
+ set useSecureWebSocket(newValue: SocketDefaults['useSecureWebSocket']);
+ /**
+ * Disable TLS encryption in the Postgres protocol (as set via e.g.
+ * `?sslmode=require` in the connection string). Connection remains secure
+ * as long as `useSecureWebSocket` is `true`, which is the default.
+ *
+ * Default: `true`
+ */
+ static get forceDisablePgSSL(): SocketDefaults["forceDisablePgSSL"];
+ static set forceDisablePgSSL(newValue: SocketDefaults['forceDisablePgSSL']);
+ get forceDisablePgSSL(): SocketDefaults["forceDisablePgSSL"];
+ set forceDisablePgSSL(newValue: SocketDefaults['forceDisablePgSSL']);
+ /**
+ * When using subtls with `forceDisablePgSSL = false` and Postgres connection
+ * parameters that specify TLS, setting `disableSNI = true` means that no SNI
+ * data in included in the Postgres TLS handshake.
+ *
+ * On Neon, disabling SNI and including the Neon project name in the password
+ * avoids CPU-intensive SCRAM authentication, but this is only relevant for
+ * earlier iterations of Neon's WebSocket support.
+ *
+ * Default: `false`.
+ */
+ static get disableSNI(): SocketDefaults["disableSNI"];
+ static set disableSNI(newValue: SocketDefaults['disableSNI']);
+ get disableSNI(): SocketDefaults["disableSNI"];
+ set disableSNI(newValue: SocketDefaults['disableSNI']);
+ /**
+ * Pipelines the startup message, cleartext password message and first query
+ * when set to `"password"`. This works only for cleartext password auth.
+ *
+ * Default: `"password"`.
+ */
+ static get pipelineConnect(): SocketDefaults["pipelineConnect"];
+ static set pipelineConnect(newValue: SocketDefaults['pipelineConnect']);
+ get pipelineConnect(): SocketDefaults["pipelineConnect"];
+ set pipelineConnect(newValue: SocketDefaults['pipelineConnect']);
+ /**
+ * If `forceDisablePgSSL` is `false` and the Postgres connection parameters
+ * specify TLS, you must supply the subtls TLS library to this option:
+ *
+ * ```
+ * import { neonConfig } from '@neondatabase/serverless';
+ * import * as subtls from 'subtls';
+ * neonConfig.subtls = subtls;
+ * ```
+ *
+ * Default: `undefined`.
+ */
+ static get subtls(): SocketDefaults["subtls"];
+ static set subtls(newValue: SocketDefaults['subtls']);
+ get subtls(): SocketDefaults["subtls"];
+ set subtls(newValue: SocketDefaults['subtls']);
+ /**
+ * Pipeline the pg SSL request and TLS handshake when `forceDisablePgSSL` is
+ * `false` and the Postgres connection parameters specify TLS. Currently
+ * compatible only with Neon hosts.
+ *
+ * Default: `false`.
+ */
+ static get pipelineTLS(): SocketDefaults["pipelineTLS"];
+ static set pipelineTLS(newValue: SocketDefaults['pipelineTLS']);
+ get pipelineTLS(): SocketDefaults["pipelineTLS"];
+ set pipelineTLS(newValue: SocketDefaults['pipelineTLS']);
+ /**
+ * Set `rootCerts` to a string comprising one or more PEM files. These are
+ * the trusted root certificates for a TLS connection to Postgres when
+ * `forceDisablePgSSL` is `false` and the Postgres connection parameters
+ * specify TLS.
+ *
+ * Default: `""`.
+ */
+ static get rootCerts(): SocketDefaults["rootCerts"];
+ static set rootCerts(newValue: SocketDefaults['rootCerts']);
+ get rootCerts(): SocketDefaults["rootCerts"];
+ set rootCerts(newValue: SocketDefaults['rootCerts']);
+ wsProxyAddrForHost(host: string, port: number): string;
+ connecting: boolean;
+ pending: boolean;
+ writable: boolean;
+ encrypted: boolean;
+ authorized: boolean;
+ destroyed: boolean;
+ setNoDelay(): this;
+ setKeepAlive(): this;
+ ref(): this;
+ unref(): this;
+ connect(port: number | string, host: string, connectListener?: () => void): void;
+ startTls(host: string): Promise;
+ tlsReadLoop(): Promise;
+ rawWrite(data: Uint8Array): void;
+ write(data: Buffer | string, encoding?: string, callback?: (err?: any) => void): boolean;
+ end(data?: Buffer | string, encoding?: string, callback?: () => void): this;
+ destroy(): this;
+}
+
+export declare class NeonDbError extends Error {
+ name: "NeonDbError";
+ severity: string | undefined;
+ code: string | undefined;
+ detail: string | undefined;
+ hint: string | undefined;
+ position: string | undefined;
+ internalPosition: string | undefined;
+ internalQuery: string | undefined;
+ where: string | undefined;
+ schema: string | undefined;
+ table: string | undefined;
+ column: string | undefined;
+ dataType: string | undefined;
+ constraint: string | undefined;
+ file: string | undefined;
+ line: string | undefined;
+ routine: string | undefined;
+ sourceError: Error | undefined;
+ constructor(message: string);
+}
+
+export declare interface NeonQueryFunction {
+ (strings: TemplateStringsArray, ...params: any[]): NeonQueryPromise : QueryRows>;
+ (string: string, params?: any[], opts?: HTTPQueryOptions): NeonQueryPromise : QueryRows>;
+ /**
+ * The `transaction()` function allows multiple queries to be submitted (over
+ * HTTP) as a single, non-interactive Postgres transaction.
+ *
+ * For example:
+ * ```
+ * import { neon } from "@neondatabase/serverless";
+ * const sql = neon("postgres://user:pass@host/db");
+ *
+ * const results = await sql.transaction([
+ * sql`SELECT 1 AS num`,
+ * sql`SELECT 'a' AS str`,
+ * ]);
+ * // -> [[{ num: 1 }], [{ str: "a" }]]
+ *
+ * // or equivalently:
+ * const results = await sql.transaction(txn => [
+ * txn`SELECT 1 AS num`,
+ * txn`SELECT 'a' AS str`,
+ * ]);
+ * // -> [[{ num: 1 }], [{ str: "a" }]]
+ * ```
+ * @param queriesOrFn - Either an array of queries, or a (non-`async`) function
+ * that receives a query function and returns an array of queries.
+ * @param opts - The same options that may be set on individual queries in a
+ * non-transaction setting -- that is, `arrayMode` `fullResults` and
+ * `fetchOptions` -- plus the transaction options `isolationLevel`,
+ * `readOnly` and `deferrable`. Note that none of these options can be set on
+ * individual queries within a transaction.
+ * @returns An array of results. The structure of each result object depends
+ * on the `arrayMode` and `fullResults` options.
+ */
+ transaction: (queriesOrFn: NeonQueryPromise[] | ((sql: NeonQueryFunctionInTransaction) => NeonQueryInTransaction[]), opts?: HTTPTransactionOptions) => Promise[] : QueryRows[]>;
+}
+
+export declare interface NeonQueryFunctionInTransaction {
+ (strings: TemplateStringsArray, ...params: any[]): NeonQueryPromise : QueryRows>;
+ (string: string, params?: any[]): NeonQueryPromise : QueryRows>;
+}
+
+export declare interface NeonQueryInTransaction {
+ parameterizedQuery: ParameterizedQuery;
+}
+
+export declare interface NeonQueryPromise extends Promise {
+ parameterizedQuery: ParameterizedQuery;
+ opts?: HTTPQueryOptions;
+}
+
+export { Notification }
+
+declare type OID = string;
+
+export declare interface ParameterizedQuery {
+ query: string;
+ params: any[];
+}
+
+/**
+ * The node-postgres `Pool` object re-exported with minor modifications.
+ * https://node-postgres.com/apis/pool
+ */
+export declare class Pool extends Pool_2 {
+ Client: typeof Client;
+ hasFetchUnsupportedListeners: boolean;
+ on(event: 'error' | 'connect' | 'acquire' | 'release' | 'remove', listener: any): this;
+ addListener: (event: "error" | "connect" | "acquire" | "release" | "remove", listener: any) => this;
+ query(queryStream: T): T;
+ query(queryConfig: QueryArrayConfig, values?: QueryConfigValues): Promise>;
+ query(queryConfig: QueryConfig): Promise>;
+ query(queryTextOrConfig: string | QueryConfig, values?: QueryConfigValues): Promise>;
+ query(queryConfig: QueryArrayConfig, callback: (err: Error, result: QueryArrayResult) => void): void;
+ query(queryTextOrConfig: string | QueryConfig, callback: (err: Error, result: QueryResult) => void): void;
+ query(queryText: string, values: QueryConfigValues, callback: (err: Error, result: QueryResult) => void): void;
+}
+
+export { PoolConfig }
+
+export declare interface ProcessQueryResultOptions {
+ arrayMode: boolean;
+ fullResults: boolean;
+ parameterizedQuery: ParameterizedQuery;
+ resultCallback: HTTPQueryOptions['resultCallback'];
+ types?: typeof types;
+}
+
+export { Query }
+
+export { QueryArrayConfig }
+
+export { QueryArrayResult }
+
+export { QueryConfig }
+
+export { QueryParse }
+
+export { QueryResult }
+
+export { QueryResultBase }
+
+export { QueryResultRow }
+
+export declare type QueryRows = ArrayMode extends true ? any[][] : Record[];
+
+declare abstract class ReadQueue {
+ queue: Uint8Array[];
+ outstandingRequest: DataRequest | undefined;
+ constructor();
+ abstract socketIsNotClosed(): boolean;
+ enqueue(data: Uint8Array): void;
+ dequeue(): void;
+ bytesInQueue(): number;
+ read(bytes: number): Promise | undefined>;
+}
+
+export { ResultBuilder }
+
+declare type RootCertsData = Uint8Array;
+
+declare interface RootCertsDatabase {
+ index: RootCertsIndex;
+ data: RootCertsData;
+}
+
+declare interface RootCertsIndex {
+ offsets: number[];
+ subjects: Record;
+}
+
+export declare interface SocketDefaults {
+ poolQueryViaFetch: boolean;
+ fetchEndpoint: string | ((host: string, port: number | string, options?: FetchEndpointOptions) => string);
+ fetchConnectionCache: boolean;
+ fetchFunction: any;
+ webSocketConstructor: WebSocketConstructor | undefined;
+ wsProxy: string | ((host: string, port: number | string) => string);
+ useSecureWebSocket: boolean;
+ forceDisablePgSSL: boolean;
+ coalesceWrites: boolean;
+ pipelineConnect: 'password' | false;
+ subtls: typeof subtls | undefined;
+ rootCerts: string;
+ pipelineTLS: boolean;
+ disableSNI: boolean;
+}
+
+declare class SocketReadQueue extends ReadQueue {
+ constructor(socket: Socket);
+ socketIsNotClosed(): boolean;
+}
+
+declare function stableStringify(x: any, replacer?: (key: string, value: any) => any, indent?: string | number): string;
+
+declare function startTls(host: string, rootCertsDatabase: RootCertsDatabase | string, networkRead: (bytes: number) => Promise, networkWrite: (data: Uint8Array) => void, { useSNI, requireServerTlsExtKeyUsage, requireDigitalSigKeyUsage, writePreData, expectPreData, commentPreData }?: {
+ useSNI?: boolean;
+ requireServerTlsExtKeyUsage?: boolean;
+ requireDigitalSigKeyUsage?: boolean;
+ writePreData?: Uint8Array;
+ expectPreData?: Uint8Array;
+ commentPreData?: string;
+}): Promise Promise | undefined>, (data: Uint8Array) => Promise]>;
+
+declare function stdCharCodes(charCode: number): number | void;
+
+export { Submittable }
+
+declare namespace subtls {
+ export {
+ base64Decode,
+ hexFromU8,
+ stableStringify,
+ startTls,
+ stdCharCodes,
+ u8FromHex,
+ allKeyUsages,
+ ASN1Bytes,
+ Bytes,
+ Cert,
+ CertJSON,
+ DataRequest,
+ DistinguishedName,
+ OID,
+ ReadQueue,
+ RootCertsData,
+ RootCertsDatabase,
+ RootCertsIndex,
+ SocketReadQueue,
+ TrustedCert,
+ WebSocketReadQueue
+ }
+}
+export { subtls }
+
+declare class TrustedCert extends Cert {
+ static databaseFromPEM(pem: string): RootCertsDatabase;
+ static findInDatabase(subjectOrSubjectKeyId: DistinguishedName | string, db: RootCertsDatabase): TrustedCert | undefined;
+}
+
+export { types }
+
+declare function u8FromHex(hex: string): Uint8Array;
+
+export declare interface WebSocketConstructor {
+ new (...args: any[]): WebSocketLike;
+}
+
+export declare interface WebSocketLike {
+ readonly readyState: number;
+ binaryType: string;
+ close(code?: number, reason?: string): void;
+ send(data: any): void;
+ addEventListener(type: 'open' | 'message' | 'close' | 'error', listener: (this: WebSocketLike, ev: any) => any, options?: any): void;
+}
+
+declare class WebSocketReadQueue extends ReadQueue {
+ constructor(socket: WebSocket);
+ socketIsNotClosed(): boolean;
+}
+
diff --git a/dist/dts/_extracted.d.ts.orig b/dist/dts/_extracted.d.ts.orig
new file mode 100644
index 0000000..ca92e54
--- /dev/null
+++ b/dist/dts/_extracted.d.ts.orig
@@ -0,0 +1,793 @@
+///
+
+import { BindConfig } from 'pg';
+import { Client as Client_2 } from 'pg';
+import { ClientBase } from 'pg';
+import { ClientConfig } from 'pg';
+import { Connection } from 'pg';
+import { ConnectionConfig } from 'pg';
+import { CustomTypesConfig } from 'pg';
+import { Defaults } from 'pg';
+import { defaults } from 'pg';
+import { EventEmitter } from 'events';
+import { Events } from 'pg';
+import { ExecuteConfig } from 'pg';
+import { FieldDef } from 'pg';
+import { MessageConfig } from 'pg';
+import { Notification } from 'pg';
+import { Pool as Pool_2 } from 'pg';
+import { PoolConfig } from 'pg';
+import { Query } from 'pg';
+import { QueryArrayConfig } from 'pg';
+import { QueryArrayResult } from 'pg';
+import { QueryConfig } from 'pg';
+import type { QueryConfigValues } from 'pg';
+import { QueryParse } from 'pg';
+import { QueryResult } from 'pg';
+import { QueryResultBase } from 'pg';
+import { QueryResultRow } from 'pg';
+import { ResultBuilder } from 'pg';
+import type { Socket } from 'net';
+import { Submittable } from 'pg';
+import { types } from 'pg';
+
+declare const allKeyUsages: readonly ["digitalSignature", "nonRepudiation", "keyEncipherment", "dataEncipherment", "keyAgreement", "keyCertSign", "cRLSign", "encipherOnly", "decipherOnly"];
+
+declare class ASN1Bytes extends Bytes {
+ readASN1Length(comment?: string): number;
+ expectASN1Length(comment?: string): readonly [() => void, () => number];
+ readASN1OID(comment?: string): string;
+ readASN1Boolean(comment?: string): boolean;
+ readASN1UTCTime(): Date;
+ readASN1GeneralizedTime(): Date;
+ readASN1BitString(): Uint8Array;
+}
+
+declare function base64Decode(input: string, charCodes?: typeof stdCharCodes, autoPad?: boolean): Uint8Array;
+
+export { BindConfig }
+
+export declare const _bundleExt: 'js' | 'mjs';
+
+declare class Bytes {
+ offset: number;
+ dataView: DataView;
+ data: Uint8Array;
+ comments: Record;
+ indents: Record;
+ indent: number;
+ constructor(arrayOrMaxBytes: number | Uint8Array);
+ extend(arrayOrMaxBytes: number | Uint8Array): void;
+ remaining(): number;
+ subarray(length: number): Uint8Array;
+ skip(length: number, comment?: string): this;
+ comment(s: string, offset?: number): this;
+ lengthComment(length: number, comment?: string, inclusive?: boolean): string;
+ readBytes(length: number): Uint8Array;
+ readUTF8String(length: number): string;
+ readUTF8StringNullTerminated(): string;
+ readUint8(comment?: string): number;
+ readUint16(comment?: string): number;
+ readUint24(comment?: string): number;
+ readUint32(comment?: string): number;
+ expectBytes(expected: Uint8Array | number[], comment?: string): void;
+ expectUint8(expectedValue: number, comment?: string): void;
+ expectUint16(expectedValue: number, comment?: string): void;
+ expectUint24(expectedValue: number, comment?: string): void;
+ expectUint32(expectedValue: number, comment?: string): void;
+ expectLength(length: number, indentDelta?: number): readonly [() => void, () => number];
+ expectLengthUint8(comment?: string): readonly [() => void, () => number];
+ expectLengthUint16(comment?: string): readonly [() => void, () => number];
+ expectLengthUint24(comment?: string): readonly [() => void, () => number];
+ expectLengthUint32(comment?: string): readonly [() => void, () => number];
+ expectLengthUint8Incl(comment?: string): readonly [() => void, () => number];
+ expectLengthUint16Incl(comment?: string): readonly [() => void, () => number];
+ expectLengthUint24Incl(comment?: string): readonly [() => void, () => number];
+ expectLengthUint32Incl(comment?: string): readonly [() => void, () => number];
+ writeBytes(bytes: number[] | Uint8Array): this;
+ writeUTF8String(s: string): this;
+ writeUTF8StringNullTerminated(s: string): this;
+ writeUint8(value: number, comment?: string): Bytes;
+ writeUint16(value: number, comment?: string): Bytes;
+ writeUint24(value: number, comment?: string): Bytes;
+ writeUint32(value: number, comment?: string): Bytes;
+ _writeLengthGeneric(lengthBytes: 1 | 2 | 3 | 4, inclusive: boolean, comment?: string): () => void;
+ writeLengthUint8(comment?: string): () => void;
+ writeLengthUint16(comment?: string): () => void;
+ writeLengthUint24(comment?: string): () => void;
+ writeLengthUint32(comment?: string): () => void;
+ writeLengthUint8Incl(comment?: string): () => void;
+ writeLengthUint16Incl(comment?: string): () => void;
+ writeLengthUint24Incl(comment?: string): () => void;
+ writeLengthUint32Incl(comment?: string): () => void;
+ array(): Uint8Array;
+ commentedString(all?: boolean): string;
+}
+
+declare class Cert {
+ serialNumber: Uint8Array;
+ algorithm: OID;
+ issuer: DistinguishedName;
+ validityPeriod: {
+ notBefore: Date;
+ notAfter: Date;
+ };
+ subject: DistinguishedName;
+ publicKey: {
+ identifiers: OID[];
+ data: Uint8Array;
+ all: Uint8Array;
+ };
+ signature: Uint8Array;
+ keyUsage?: {
+ critical?: boolean;
+ usages: Set;
+ };
+ subjectAltNames?: string[];
+ extKeyUsage?: {
+ clientTls?: true;
+ serverTls?: true;
+ };
+ authorityKeyIdentifier?: Uint8Array;
+ subjectKeyIdentifier?: Uint8Array;
+ basicConstraints?: {
+ critical?: boolean;
+ ca?: boolean;
+ pathLength?: number;
+ } | undefined;
+ signedData: Uint8Array;
+ static distinguishedNamesAreEqual(dn1: DistinguishedName, dn2: DistinguishedName): boolean;
+ static stringFromDistinguishedName(dn: DistinguishedName): string;
+ constructor(certData: Uint8Array | ASN1Bytes | CertJSON);
+ subjectAltNameMatchingHost(host: string): string | undefined;
+ isValidAtMoment(moment?: Date): boolean;
+ description(): string;
+ toJSON(): {
+ serialNumber: string;
+ algorithm: string;
+ issuer: DistinguishedName;
+ validityPeriod: {
+ notBefore: string;
+ notAfter: string;
+ };
+ subject: DistinguishedName;
+ publicKey: {
+ identifiers: string[];
+ data: string;
+ all: string;
+ };
+ signature: string;
+ keyUsage: {
+ critical: boolean | undefined;
+ usages: ("digitalSignature" | "nonRepudiation" | "keyEncipherment" | "dataEncipherment" | "keyAgreement" | "keyCertSign" | "cRLSign" | "encipherOnly" | "decipherOnly")[];
+ };
+ subjectAltNames: string[] | undefined;
+ extKeyUsage: {
+ clientTls?: true;
+ serverTls?: true;
+ } | undefined;
+ authorityKeyIdentifier: string | undefined;
+ subjectKeyIdentifier: string | undefined;
+ basicConstraints: {
+ critical?: boolean;
+ ca?: boolean;
+ pathLength?: number;
+ } | undefined;
+ signedData: string;
+ };
+ static uint8ArraysFromPEM(pem: string): Uint8Array[];
+ static fromPEM(pem: string): Cert[];
+}
+
+declare type CertJSON = ReturnType;
+
+export declare interface Client {
+ connection: Connection & {
+ stream: neonConfig;
+ sendSCRAMClientFinalMessage: (response: any) => void;
+ ssl: any;
+ };
+ _handleReadyForQuery: any;
+ _handleAuthCleartextPassword: any;
+ startup: any;
+ getStartupConf: any;
+ saslSession: any;
+}
+
+/**
+ * The node-postgres `Client` object re-exported with minor modifications.
+ * https://node-postgres.com/apis/client
+ */
+export declare class Client extends Client_2 {
+ config: any;
+ get neonConfig(): neonConfig;
+ constructor(config: any);
+ connect(): Promise;
+ connect(callback: (err?: Error) => void): void;
+ _handleAuthSASLContinue(msg: any): Promise;
+}
+
+export { ClientBase }
+
+export { ClientConfig }
+
+export { Connection }
+
+export { ConnectionConfig }
+
+export { CustomTypesConfig }
+
+declare interface DataRequest {
+ bytes: number;
+ resolve: (data: Uint8Array | undefined) => void;
+}
+
+export { Defaults }
+
+export { defaults }
+
+declare type DistinguishedName = Record;
+
+export { Events }
+
+export { ExecuteConfig }
+
+export declare interface FetchEndpointOptions {
+ jwtAuth?: boolean;
+}
+
+export { FieldDef }
+
+export declare interface FullQueryResults {
+ fields: FieldDef[];
+ command: string;
+ rowCount: number;
+ rows: QueryRows;
+ rowAsArray: ArrayMode;
+}
+
+declare function hexFromU8(u8: Uint8Array | number[], spacer?: string): string;
+
+export declare interface HTTPQueryOptions {
+ /**
+ * When `arrayMode` is `false`, which is the default, result rows are
+ * returned as objects whose keys represent column names, such as
+ * `{ id: 1 }`).
+ *
+ * When `arrayMode` is `true`, rows are returned as arrays (and keys are not
+ * provided), e.g. `[1]`.
+ */
+ arrayMode?: ArrayMode;
+ /**
+ * When `fullResults` is `false`, which is the default, only result rows are
+ * returned, e.g. `[{ id: 1 }]`).
+ *
+ * When `fullResults` is `true`, a result object is returned that matches
+ * what's returned by node-postgres. This has a `rows` property, which is an
+ * array of result rows, plus `fields`, which provides column names and
+ * types, `command` and `rowCount`.
+ */
+ fullResults?: FullResults;
+ /**
+ * Any options in `fetchOptions` are merged in to the options passed to
+ * `fetch`. In case of conflict with what would otherwise be passed, these
+ * options take precedence.
+ */
+ fetchOptions?: Record;
+ /**
+ * JWT auth token to be passed as the Bearer token in the Authorization header.
+ * Can be string, or a function (sync or async) returning a string.
+ *
+ * Default: `undefined`
+ */
+ authToken?: string | (() => Promise | string);
+ /**
+ * Custom type parsers. See https://github.com/brianc/node-pg-types.
+ */
+ types?: typeof types;
+ queryCallback?: (query: ParameterizedQuery) => void;
+ resultCallback?: (query: ParameterizedQuery, result: any, rows: any, opts: any) => void;
+}
+
+export declare interface HTTPTransactionOptions extends HTTPQueryOptions {
+ isolationLevel?: 'ReadUncommitted' | 'ReadCommitted' | 'RepeatableRead' | 'Serializable';
+ readOnly?: boolean;
+ deferrable?: boolean;
+}
+
+export { MessageConfig }
+
+/**
+ * This function returns an async tagged-template function that runs a single
+ * SQL query (no session or transactions) with low latency over https. Support
+ * for multiple queries (as a non-interactive transaction) is provided by
+ * the `transaction` property of the query function.
+ *
+ * By default, the query function returns database rows directly. Types should
+ * match those returned by this driver (i.e. Pool or Client) over WebSockets.
+ *
+ * The returned function can also be called directly (i.e. not as a template
+ * function). In that case, pass it a query string with embedded `$1`, `$2`
+ * (etc.), followed by an array of query parameters, followed (optionally) by
+ * any of the same options you can pass to this function.
+ *
+ * Some examples:
+ * ```
+ * import { neon } from "@neondatabase/serverless";
+ * const h = "hello", w = "world";
+ *
+ * // example 1: default options, tagged-template usage
+ * const sql = neon("postgres://user:pass@host/db");
+ * const rows = await sql`SELECT ${h} || ' ' || ${w} AS greeting`;
+ * // -> [ { greeting: "hello world" } ]
+ *
+ * // example 2: `arrayMode` and `fullResults` options, ordinary function usage
+ * const options = { arrayMode: true, fullResults: true };
+ * const sql = neon("postgres://user:pass@host/db", options);
+ * const rows = await sql("SELECT $1 || ' ' || $2 AS greeting", [h, w]);
+ * // -> {
+ * // command: "SELECT",
+ * // fields: [ { name: "greeting", dataTypeID: 25 } ],
+ * // rowAsArray: true,
+ * // rowCount: 1,
+ * // rows: [ [ "hello world" ] ]
+ * // }
+ *
+ * // example 3: `fetchOptions` option, ordinary function usage
+ * const sql = neon("postgres://user:pass@host/db");
+ * const rows = await sql(
+ * "SELECT $1 || ' ' || $2 AS greeting", [h, w],
+ * { fetchOptions: { priority: "high" } }
+ * );
+ * // -> [ { greeting: "hello world" } ]
+ * ```
+ *
+ * @param connectionString - this has the format `postgres://user:pass@host/db`
+ * @param options - pass `arrayMode: true` to receive results as an array of
+ * arrays, instead of the default array of objects; pass `fullResults: true`
+ * to receive a complete result object similar to one returned by node-postgres
+ * (with properties `rows`, `fields`, `command`, `rowCount`, `rowAsArray`);
+ * pass as `fetchOptions` an object which will be merged into the options
+ * passed to `fetch`.
+ */
+export declare function neon(connectionString: string, { arrayMode: neonOptArrayMode, fullResults: neonOptFullResults, fetchOptions: neonOptFetchOptions, isolationLevel: neonOptIsolationLevel, readOnly: neonOptReadOnly, deferrable: neonOptDeferrable, queryCallback, resultCallback, authToken, }?: HTTPTransactionOptions): NeonQueryFunction;
+
+export declare class neonConfig extends EventEmitter {
+ static defaults: SocketDefaults;
+ static opts: Partial;
+ private opts;
+ /**
+ * **Experimentally**, when `poolQueryViaFetch` is `true`, and no listeners
+ * for the `"connect"`, `"acquire"`, `"release"` or `"remove"` events are set
+ * on the `Pool`, queries via `Pool.query()` will be sent by low-latency HTTP
+ * fetch request.
+ *
+ * Default: `false`.
+ */
+ static get poolQueryViaFetch(): SocketDefaults["poolQueryViaFetch"];
+ static set poolQueryViaFetch(newValue: SocketDefaults['poolQueryViaFetch']);
+ /**
+ * Set `fetchEndpoint` to set the server endpoint to be sent queries via http
+ * fetch. May be useful in local development (e.g. to set a port that's not
+ * the default 443).
+ *
+ * Provide either the full endpoint URL, or a function that takes the
+ * database host address, port and options, and returns the full endpoint URL
+ * (including protocol).
+ *
+ * Default: custom logic to connect to Neon endpoints.
+ */
+ static get fetchEndpoint(): SocketDefaults["fetchEndpoint"];
+ static set fetchEndpoint(newValue: SocketDefaults['fetchEndpoint']);
+ /**
+ * **DEPRECATED**. Previously, only when `fetchConnectionCache` was `true`
+ * did queries carried via HTTP fetch make use of a connection pool/cache
+ * on the server. All queries now use the connection pool/cache: this setting
+ * is ignored.
+ *
+ * Default: `true`.
+ */
+ static get fetchConnectionCache(): SocketDefaults["fetchConnectionCache"];
+ static set fetchConnectionCache(newValue: SocketDefaults['fetchConnectionCache']);
+ /**
+ * The `fetchFunction` option allows you to supply an alternative function
+ * for making http requests. The function must accept the same arguments as
+ * native `fetch`.
+ *
+ * Default: `undefined`.
+ */
+ static get fetchFunction(): SocketDefaults["fetchFunction"];
+ static set fetchFunction(newValue: SocketDefaults['fetchFunction']);
+ /**
+ * Only if no global `WebSocket` object is available, such as in older
+ * versions of Node, set `webSocketConstructor` to the constructor for a
+ * custom WebSocket implementation, such as those provided by `ws` or
+ * `undici`.
+ *
+ * Default: `undefined`.
+ */
+ static get webSocketConstructor(): SocketDefaults["webSocketConstructor"];
+ static set webSocketConstructor(newValue: SocketDefaults['webSocketConstructor']);
+ get webSocketConstructor(): SocketDefaults["webSocketConstructor"];
+ set webSocketConstructor(newValue: SocketDefaults['webSocketConstructor']);
+ /**
+ * Set `wsProxy` to use your own WebSocket proxy server.
+ *
+ * Provide either the proxy server’s domain name, or a function that takes
+ * the database host and port and returns the proxy server address (without
+ * protocol).
+ *
+ * Example: `(host, port) => "myproxy.example.net?address=" + host + ":" + port`
+ *
+ * Default: `host => host + '/v2'`
+ */
+ static get wsProxy(): SocketDefaults["wsProxy"];
+ static set wsProxy(newValue: SocketDefaults['wsProxy']);
+ get wsProxy(): SocketDefaults["wsProxy"];
+ set wsProxy(newValue: SocketDefaults['wsProxy']);
+ /**
+ * Batch multiple network writes per run-loop into a single outgoing
+ * WebSocket message.
+ *
+ * Default: `true`.
+ */
+ static get coalesceWrites(): SocketDefaults["coalesceWrites"];
+ static set coalesceWrites(newValue: SocketDefaults['coalesceWrites']);
+ get coalesceWrites(): SocketDefaults["coalesceWrites"];
+ set coalesceWrites(newValue: SocketDefaults['coalesceWrites']);
+ /**
+ * Use a secure (`wss:`) connection to the WebSocket proxy.
+ *
+ * Default: `true`.
+ */
+ static get useSecureWebSocket(): SocketDefaults["useSecureWebSocket"];
+ static set useSecureWebSocket(newValue: SocketDefaults['useSecureWebSocket']);
+ get useSecureWebSocket(): SocketDefaults["useSecureWebSocket"];
+ set useSecureWebSocket(newValue: SocketDefaults['useSecureWebSocket']);
+ /**
+ * Disable TLS encryption in the Postgres protocol (as set via e.g.
+ * `?sslmode=require` in the connection string). Connection remains secure
+ * as long as `useSecureWebSocket` is `true`, which is the default.
+ *
+ * Default: `true`
+ */
+ static get forceDisablePgSSL(): SocketDefaults["forceDisablePgSSL"];
+ static set forceDisablePgSSL(newValue: SocketDefaults['forceDisablePgSSL']);
+ get forceDisablePgSSL(): SocketDefaults["forceDisablePgSSL"];
+ set forceDisablePgSSL(newValue: SocketDefaults['forceDisablePgSSL']);
+ /**
+ * When using subtls with `forceDisablePgSSL = false` and Postgres connection
+ * parameters that specify TLS, setting `disableSNI = true` means that no SNI
+ * data in included in the Postgres TLS handshake.
+ *
+ * On Neon, disabling SNI and including the Neon project name in the password
+ * avoids CPU-intensive SCRAM authentication, but this is only relevant for
+ * earlier iterations of Neon's WebSocket support.
+ *
+ * Default: `false`.
+ */
+ static get disableSNI(): SocketDefaults["disableSNI"];
+ static set disableSNI(newValue: SocketDefaults['disableSNI']);
+ get disableSNI(): SocketDefaults["disableSNI"];
+ set disableSNI(newValue: SocketDefaults['disableSNI']);
+ /**
+ * Pipelines the startup message, cleartext password message and first query
+ * when set to `"password"`. This works only for cleartext password auth.
+ *
+ * Default: `"password"`.
+ */
+ static get pipelineConnect(): SocketDefaults["pipelineConnect"];
+ static set pipelineConnect(newValue: SocketDefaults['pipelineConnect']);
+ get pipelineConnect(): SocketDefaults["pipelineConnect"];
+ set pipelineConnect(newValue: SocketDefaults['pipelineConnect']);
+ /**
+ * If `forceDisablePgSSL` is `false` and the Postgres connection parameters
+ * specify TLS, you must supply the subtls TLS library to this option:
+ *
+ * ```
+ * import { neonConfig } from '@neondatabase/serverless';
+ * import * as subtls from 'subtls';
+ * neonConfig.subtls = subtls;
+ * ```
+ *
+ * Default: `undefined`.
+ */
+ static get subtls(): SocketDefaults["subtls"];
+ static set subtls(newValue: SocketDefaults['subtls']);
+ get subtls(): SocketDefaults["subtls"];
+ set subtls(newValue: SocketDefaults['subtls']);
+ /**
+ * Pipeline the pg SSL request and TLS handshake when `forceDisablePgSSL` is
+ * `false` and the Postgres connection parameters specify TLS. Currently
+ * compatible only with Neon hosts.
+ *
+ * Default: `false`.
+ */
+ static get pipelineTLS(): SocketDefaults["pipelineTLS"];
+ static set pipelineTLS(newValue: SocketDefaults['pipelineTLS']);
+ get pipelineTLS(): SocketDefaults["pipelineTLS"];
+ set pipelineTLS(newValue: SocketDefaults['pipelineTLS']);
+ /**
+ * Set `rootCerts` to a string comprising one or more PEM files. These are
+ * the trusted root certificates for a TLS connection to Postgres when
+ * `forceDisablePgSSL` is `false` and the Postgres connection parameters
+ * specify TLS.
+ *
+ * Default: `""`.
+ */
+ static get rootCerts(): SocketDefaults["rootCerts"];
+ static set rootCerts(newValue: SocketDefaults['rootCerts']);
+ get rootCerts(): SocketDefaults["rootCerts"];
+ set rootCerts(newValue: SocketDefaults['rootCerts']);
+ wsProxyAddrForHost(host: string, port: number): string;
+ connecting: boolean;
+ pending: boolean;
+ writable: boolean;
+ encrypted: boolean;
+ authorized: boolean;
+ destroyed: boolean;
+ private ws;
+ private writeBuffer;
+ private tlsState;
+ private tlsRead;
+ private tlsWrite;
+ setNoDelay(): this;
+ setKeepAlive(): this;
+ ref(): this;
+ unref(): this;
+ connect(port: number | string, host: string, connectListener?: () => void): void;
+ startTls(host: string): Promise;
+ tlsReadLoop(): Promise;
+ rawWrite(data: Uint8Array): void;
+ write(data: Buffer | string, encoding?: string, callback?: (err?: any) => void): boolean;
+ end(data?: Buffer | string, encoding?: string, callback?: () => void): this;
+ destroy(): this;
+}
+
+export declare class NeonDbError extends Error {
+ name: "NeonDbError";
+ severity: string | undefined;
+ code: string | undefined;
+ detail: string | undefined;
+ hint: string | undefined;
+ position: string | undefined;
+ internalPosition: string | undefined;
+ internalQuery: string | undefined;
+ where: string | undefined;
+ schema: string | undefined;
+ table: string | undefined;
+ column: string | undefined;
+ dataType: string | undefined;
+ constraint: string | undefined;
+ file: string | undefined;
+ line: string | undefined;
+ routine: string | undefined;
+ sourceError: Error | undefined;
+ constructor(message: string);
+}
+
+export declare interface NeonQueryFunction {
+ (strings: TemplateStringsArray, ...params: any[]): NeonQueryPromise : QueryRows>;
+ (string: string, params?: any[], opts?: HTTPQueryOptions): NeonQueryPromise : QueryRows>;
+ /**
+ * The `transaction()` function allows multiple queries to be submitted (over
+ * HTTP) as a single, non-interactive Postgres transaction.
+ *
+ * For example:
+ * ```
+ * import { neon } from "@neondatabase/serverless";
+ * const sql = neon("postgres://user:pass@host/db");
+ *
+ * const results = await sql.transaction([
+ * sql`SELECT 1 AS num`,
+ * sql`SELECT 'a' AS str`,
+ * ]);
+ * // -> [[{ num: 1 }], [{ str: "a" }]]
+ *
+ * // or equivalently:
+ * const results = await sql.transaction(txn => [
+ * txn`SELECT 1 AS num`,
+ * txn`SELECT 'a' AS str`,
+ * ]);
+ * // -> [[{ num: 1 }], [{ str: "a" }]]
+ * ```
+ * @param queriesOrFn - Either an array of queries, or a (non-`async`) function
+ * that receives a query function and returns an array of queries.
+ * @param opts - The same options that may be set on individual queries in a
+ * non-transaction setting -- that is, `arrayMode` `fullResults` and
+ * `fetchOptions` -- plus the transaction options `isolationLevel`,
+ * `readOnly` and `deferrable`. Note that none of these options can be set on
+ * individual queries within a transaction.
+ * @returns An array of results. The structure of each result object depends
+ * on the `arrayMode` and `fullResults` options.
+ */
+ transaction: (queriesOrFn: NeonQueryPromise[] | ((sql: NeonQueryFunctionInTransaction) => NeonQueryInTransaction[]), opts?: HTTPTransactionOptions) => Promise[] : QueryRows[]>;
+}
+
+export declare interface NeonQueryFunctionInTransaction {
+ (strings: TemplateStringsArray, ...params: any[]): NeonQueryPromise : QueryRows>;
+ (string: string, params?: any[]): NeonQueryPromise : QueryRows>;
+}
+
+export declare interface NeonQueryInTransaction {
+ parameterizedQuery: ParameterizedQuery;
+}
+
+export declare interface NeonQueryPromise extends Promise {
+ parameterizedQuery: ParameterizedQuery;
+ opts?: HTTPQueryOptions;
+}
+
+export { Notification }
+
+declare type OID = string;
+
+export declare interface ParameterizedQuery {
+ query: string;
+ params: any[];
+}
+
+/**
+ * The node-postgres `Pool` object re-exported with minor modifications.
+ * https://node-postgres.com/apis/pool
+ */
+export declare class Pool extends Pool_2 {
+ Client: typeof Client;
+ hasFetchUnsupportedListeners: boolean;
+ on(event: 'error' | 'connect' | 'acquire' | 'release' | 'remove', listener: any): this;
+ addListener: (event: "error" | "connect" | "acquire" | "release" | "remove", listener: any) => this;
+ query(queryStream: T): T;
+ query(queryConfig: QueryArrayConfig, values?: QueryConfigValues): Promise>;
+ query(queryConfig: QueryConfig): Promise>;
+ query(queryTextOrConfig: string | QueryConfig, values?: QueryConfigValues): Promise>;
+ query(queryConfig: QueryArrayConfig, callback: (err: Error, result: QueryArrayResult) => void): void;
+ query(queryTextOrConfig: string | QueryConfig, callback: (err: Error, result: QueryResult) => void): void;
+ query(queryText: string, values: QueryConfigValues, callback: (err: Error, result: QueryResult) => void): void;
+}
+
+export { PoolConfig }
+
+export declare interface ProcessQueryResultOptions {
+ arrayMode: boolean;
+ fullResults: boolean;
+ parameterizedQuery: ParameterizedQuery;
+ resultCallback: HTTPQueryOptions['resultCallback'];
+ types?: typeof types;
+}
+
+export { Query }
+
+export { QueryArrayConfig }
+
+export { QueryArrayResult }
+
+export { QueryConfig }
+
+export { QueryParse }
+
+export { QueryResult }
+
+export { QueryResultBase }
+
+export { QueryResultRow }
+
+export declare type QueryRows = ArrayMode extends true ? any[][] : Record[];
+
+declare abstract class ReadQueue {
+ queue: Uint8Array[];
+ outstandingRequest: DataRequest | undefined;
+ constructor();
+ abstract socketIsNotClosed(): boolean;
+ enqueue(data: Uint8Array): void;
+ dequeue(): void;
+ bytesInQueue(): number;
+ read(bytes: number): Promise | undefined>;
+}
+
+export { ResultBuilder }
+
+declare type RootCertsData = Uint8Array;
+
+declare interface RootCertsDatabase {
+ index: RootCertsIndex;
+ data: RootCertsData;
+}
+
+declare interface RootCertsIndex {
+ offsets: number[];
+ subjects: Record;
+}
+
+export declare interface SocketDefaults {
+ poolQueryViaFetch: boolean;
+ fetchEndpoint: string | ((host: string, port: number | string, options?: FetchEndpointOptions) => string);
+ fetchConnectionCache: boolean;
+ fetchFunction: any;
+ webSocketConstructor: WebSocketConstructor | undefined;
+ wsProxy: string | ((host: string, port: number | string) => string);
+ useSecureWebSocket: boolean;
+ forceDisablePgSSL: boolean;
+ coalesceWrites: boolean;
+ pipelineConnect: 'password' | false;
+ subtls: typeof subtls | undefined;
+ rootCerts: string;
+ pipelineTLS: boolean;
+ disableSNI: boolean;
+}
+
+declare class SocketReadQueue extends ReadQueue {
+ private socket;
+ constructor(socket: Socket);
+ socketIsNotClosed(): boolean;
+}
+
+declare function stableStringify(x: any, replacer?: (key: string, value: any) => any, indent?: string | number): string;
+
+declare function startTls(host: string, rootCertsDatabase: RootCertsDatabase | string, networkRead: (bytes: number) => Promise, networkWrite: (data: Uint8Array) => void, { useSNI, requireServerTlsExtKeyUsage, requireDigitalSigKeyUsage, writePreData, expectPreData, commentPreData }?: {
+ useSNI?: boolean;
+ requireServerTlsExtKeyUsage?: boolean;
+ requireDigitalSigKeyUsage?: boolean;
+ writePreData?: Uint8Array;
+ expectPreData?: Uint8Array;
+ commentPreData?: string;
+}): Promise Promise | undefined>, (data: Uint8Array) => Promise]>;
+
+declare function stdCharCodes(charCode: number): number | void;
+
+export { Submittable }
+
+declare namespace subtls {
+ export {
+ base64Decode,
+ hexFromU8,
+ stableStringify,
+ startTls,
+ stdCharCodes,
+ u8FromHex,
+ allKeyUsages,
+ ASN1Bytes,
+ Bytes,
+ Cert,
+ CertJSON,
+ DataRequest,
+ DistinguishedName,
+ OID,
+ ReadQueue,
+ RootCertsData,
+ RootCertsDatabase,
+ RootCertsIndex,
+ SocketReadQueue,
+ TrustedCert,
+ WebSocketReadQueue
+ }
+}
+export { subtls }
+
+declare class TrustedCert extends Cert {
+ static databaseFromPEM(pem: string): RootCertsDatabase;
+ static findInDatabase(subjectOrSubjectKeyId: DistinguishedName | string, db: RootCertsDatabase): TrustedCert | undefined;
+}
+
+export { types }
+
+declare function u8FromHex(hex: string): Uint8Array;
+
+export declare interface WebSocketConstructor {
+ new (...args: any[]): WebSocketLike;
+}
+
+export declare interface WebSocketLike {
+ readonly readyState: number;
+ binaryType: string;
+ close(code?: number, reason?: string): void;
+ send(data: any): void;
+ addEventListener(type: 'open' | 'message' | 'close' | 'error', listener: (this: WebSocketLike, ev: any) => any, options?: any): void;
+}
+
+declare class WebSocketReadQueue extends ReadQueue {
+ private socket;
+ constructor(socket: WebSocket);
+ socketIsNotClosed(): boolean;
+}
+
+export { }
diff --git a/dist/dts/export/httpQuery.d.ts b/dist/dts/export/httpQuery.d.ts
new file mode 100644
index 0000000..b51b3f4
--- /dev/null
+++ b/dist/dts/export/httpQuery.d.ts
@@ -0,0 +1,189 @@
+import { types as defaultTypes } from '.';
+import type { FieldDef, types as PgTypes } from 'pg';
+export declare class NeonDbError extends Error {
+ name: "NeonDbError";
+ severity: string | undefined;
+ code: string | undefined;
+ detail: string | undefined;
+ hint: string | undefined;
+ position: string | undefined;
+ internalPosition: string | undefined;
+ internalQuery: string | undefined;
+ where: string | undefined;
+ schema: string | undefined;
+ table: string | undefined;
+ column: string | undefined;
+ dataType: string | undefined;
+ constraint: string | undefined;
+ file: string | undefined;
+ line: string | undefined;
+ routine: string | undefined;
+ sourceError: Error | undefined;
+ constructor(message: string);
+}
+export type QueryRows = ArrayMode extends true ? any[][] : Record[];
+export interface FullQueryResults {
+ fields: FieldDef[];
+ command: string;
+ rowCount: number;
+ rows: QueryRows;
+ rowAsArray: ArrayMode;
+}
+export interface ParameterizedQuery {
+ query: string;
+ params: any[];
+}
+export interface HTTPQueryOptions {
+ /**
+ * When `arrayMode` is `false`, which is the default, result rows are
+ * returned as objects whose keys represent column names, such as
+ * `{ id: 1 }`).
+ *
+ * When `arrayMode` is `true`, rows are returned as arrays (and keys are not
+ * provided), e.g. `[1]`.
+ */
+ arrayMode?: ArrayMode;
+ /**
+ * When `fullResults` is `false`, which is the default, only result rows are
+ * returned, e.g. `[{ id: 1 }]`).
+ *
+ * When `fullResults` is `true`, a result object is returned that matches
+ * what's returned by node-postgres. This has a `rows` property, which is an
+ * array of result rows, plus `fields`, which provides column names and
+ * types, `command` and `rowCount`.
+ */
+ fullResults?: FullResults;
+ /**
+ * Any options in `fetchOptions` are merged in to the options passed to
+ * `fetch`. In case of conflict with what would otherwise be passed, these
+ * options take precedence.
+ */
+ fetchOptions?: Record;
+ /**
+ * JWT auth token to be passed as the Bearer token in the Authorization header.
+ * Can be string, or a function (sync or async) returning a string.
+ *
+ * Default: `undefined`
+ */
+ authToken?: string | (() => Promise | string);
+ /**
+ * Custom type parsers. See https://github.com/brianc/node-pg-types.
+ */
+ types?: typeof PgTypes;
+ queryCallback?: (query: ParameterizedQuery) => void;
+ resultCallback?: (query: ParameterizedQuery, result: any, rows: any, opts: any) => void;
+}
+export interface HTTPTransactionOptions extends HTTPQueryOptions {
+ isolationLevel?: 'ReadUncommitted' | 'ReadCommitted' | 'RepeatableRead' | 'Serializable';
+ readOnly?: boolean;
+ deferrable?: boolean;
+}
+export interface NeonQueryPromise extends Promise {
+ parameterizedQuery: ParameterizedQuery;
+ opts?: HTTPQueryOptions;
+}
+export interface ProcessQueryResultOptions {
+ arrayMode: boolean;
+ fullResults: boolean;
+ parameterizedQuery: ParameterizedQuery;
+ resultCallback: HTTPQueryOptions['resultCallback'];
+ types?: typeof defaultTypes;
+}
+export interface NeonQueryFunctionInTransaction {
+ (strings: TemplateStringsArray, ...params: any[]): NeonQueryPromise : QueryRows>;
+ (string: string, params?: any[]): NeonQueryPromise : QueryRows>;
+}
+export interface NeonQueryInTransaction {
+ parameterizedQuery: ParameterizedQuery;
+}
+export interface NeonQueryFunction {
+ (strings: TemplateStringsArray, ...params: any[]): NeonQueryPromise : QueryRows>;
+ (string: string, params?: any[], opts?: HTTPQueryOptions): NeonQueryPromise : QueryRows>;
+ /**
+ * The `transaction()` function allows multiple queries to be submitted (over
+ * HTTP) as a single, non-interactive Postgres transaction.
+ *
+ * For example:
+ * ```
+ * import { neon } from "@neondatabase/serverless";
+ * const sql = neon("postgres://user:pass@host/db");
+ *
+ * const results = await sql.transaction([
+ * sql`SELECT 1 AS num`,
+ * sql`SELECT 'a' AS str`,
+ * ]);
+ * // -> [[{ num: 1 }], [{ str: "a" }]]
+ *
+ * // or equivalently:
+ * const results = await sql.transaction(txn => [
+ * txn`SELECT 1 AS num`,
+ * txn`SELECT 'a' AS str`,
+ * ]);
+ * // -> [[{ num: 1 }], [{ str: "a" }]]
+ * ```
+ * @param queriesOrFn - Either an array of queries, or a (non-`async`) function
+ * that receives a query function and returns an array of queries.
+ * @param opts - The same options that may be set on individual queries in a
+ * non-transaction setting -- that is, `arrayMode` `fullResults` and
+ * `fetchOptions` -- plus the transaction options `isolationLevel`,
+ * `readOnly` and `deferrable`. Note that none of these options can be set on
+ * individual queries within a transaction.
+ * @returns An array of results. The structure of each result object depends
+ * on the `arrayMode` and `fullResults` options.
+ */
+ transaction: (queriesOrFn: NeonQueryPromise[] | ((sql: NeonQueryFunctionInTransaction) => NeonQueryInTransaction[]), opts?: HTTPTransactionOptions) => Promise[] : QueryRows[]>;
+}
+/**
+ * This function returns an async tagged-template function that runs a single
+ * SQL query (no session or transactions) with low latency over https. Support
+ * for multiple queries (as a non-interactive transaction) is provided by
+ * the `transaction` property of the query function.
+ *
+ * By default, the query function returns database rows directly. Types should
+ * match those returned by this driver (i.e. Pool or Client) over WebSockets.
+ *
+ * The returned function can also be called directly (i.e. not as a template
+ * function). In that case, pass it a query string with embedded `$1`, `$2`
+ * (etc.), followed by an array of query parameters, followed (optionally) by
+ * any of the same options you can pass to this function.
+ *
+ * Some examples:
+ * ```
+ * import { neon } from "@neondatabase/serverless";
+ * const h = "hello", w = "world";
+ *
+ * // example 1: default options, tagged-template usage
+ * const sql = neon("postgres://user:pass@host/db");
+ * const rows = await sql`SELECT ${h} || ' ' || ${w} AS greeting`;
+ * // -> [ { greeting: "hello world" } ]
+ *
+ * // example 2: `arrayMode` and `fullResults` options, ordinary function usage
+ * const options = { arrayMode: true, fullResults: true };
+ * const sql = neon("postgres://user:pass@host/db", options);
+ * const rows = await sql("SELECT $1 || ' ' || $2 AS greeting", [h, w]);
+ * // -> {
+ * // command: "SELECT",
+ * // fields: [ { name: "greeting", dataTypeID: 25 } ],
+ * // rowAsArray: true,
+ * // rowCount: 1,
+ * // rows: [ [ "hello world" ] ]
+ * // }
+ *
+ * // example 3: `fetchOptions` option, ordinary function usage
+ * const sql = neon("postgres://user:pass@host/db");
+ * const rows = await sql(
+ * "SELECT $1 || ' ' || $2 AS greeting", [h, w],
+ * { fetchOptions: { priority: "high" } }
+ * );
+ * // -> [ { greeting: "hello world" } ]
+ * ```
+ *
+ * @param connectionString - this has the format `postgres://user:pass@host/db`
+ * @param options - pass `arrayMode: true` to receive results as an array of
+ * arrays, instead of the default array of objects; pass `fullResults: true`
+ * to receive a complete result object similar to one returned by node-postgres
+ * (with properties `rows`, `fields`, `command`, `rowCount`, `rowAsArray`);
+ * pass as `fetchOptions` an object which will be merged into the options
+ * passed to `fetch`.
+ */
+export declare function neon(connectionString: string, { arrayMode: neonOptArrayMode, fullResults: neonOptFullResults, fetchOptions: neonOptFetchOptions, isolationLevel: neonOptIsolationLevel, readOnly: neonOptReadOnly, deferrable: neonOptDeferrable, queryCallback, resultCallback, authToken, }?: HTTPTransactionOptions): NeonQueryFunction;
diff --git a/dist/dts/export/index.d.ts b/dist/dts/export/index.d.ts
new file mode 100644
index 0000000..e496e93
--- /dev/null
+++ b/dist/dts/export/index.d.ts
@@ -0,0 +1,52 @@
+import { Client, Connection, Pool } from 'pg';
+import { Socket } from '../shims/net';
+import { neon, NeonDbError } from './httpQuery';
+import type { QueryResultRow, Submittable, QueryArrayConfig, QueryConfigValues, QueryConfig, QueryArrayResult, QueryResult } from 'pg';
+declare interface NeonClient {
+ connection: Connection & {
+ stream: Socket;
+ sendSCRAMClientFinalMessage: (response: any) => void;
+ ssl: any;
+ };
+ _handleReadyForQuery: any;
+ _handleAuthCleartextPassword: any;
+ startup: any;
+ getStartupConf: any;
+ saslSession: any;
+}
+/**
+ * The node-postgres `Client` object re-exported with minor modifications.
+ * https://node-postgres.com/apis/client
+ */
+declare class NeonClient extends Client {
+ config: any;
+ get neonConfig(): Socket;
+ constructor(config: any);
+ connect(): Promise;
+ connect(callback: (err?: Error) => void): void;
+ _handleAuthSASLContinue(msg: any): Promise;
+}
+/**
+ * The node-postgres `Pool` object re-exported with minor modifications.
+ * https://node-postgres.com/apis/pool
+ */
+declare class NeonPool extends Pool {
+ Client: typeof NeonClient;
+ hasFetchUnsupportedListeners: boolean;
+ on(event: 'error' | 'connect' | 'acquire' | 'release' | 'remove', listener: any): this;
+ addListener: (event: "error" | "connect" | "acquire" | "release" | "remove", listener: any) => this;
+ query(queryStream: T): T;
+ query(queryConfig: QueryArrayConfig, values?: QueryConfigValues): Promise>;
+ query(queryConfig: QueryConfig): Promise>;
+ query(queryTextOrConfig: string | QueryConfig, values?: QueryConfigValues): Promise>;
+ query(queryConfig: QueryArrayConfig, callback: (err: Error, result: QueryArrayResult) => void): void;
+ query(queryTextOrConfig: string | QueryConfig, callback: (err: Error, result: QueryResult) => void): void;
+ query(queryText: string, values: QueryConfigValues, callback: (err: Error, result: QueryResult) => void): void;
+}
+export { defaults, types, ClientBase } from 'pg';
+export type { BindConfig, ClientConfig, Connection, ConnectionConfig, CustomTypesConfig, Defaults, Events, ExecuteConfig, FieldDef, MessageConfig, Notification, PoolConfig, Query, QueryArrayConfig, QueryArrayResult, QueryConfig, QueryParse, QueryResult, QueryResultBase, QueryResultRow, ResultBuilder, Submittable, } from 'pg';
+export * from './httpQuery';
+export { Socket as neonConfig, NeonPool as Pool, NeonClient as Client, neon, NeonDbError, };
+export type { SocketDefaults, FetchEndpointOptions, WebSocketConstructor, WebSocketLike, subtls, } from '../shims/net';
+declare const _bundleExt: 'js' | 'mjs';
+export { _bundleExt };
diff --git a/dist/dts/export/index.d.ts.orig b/dist/dts/export/index.d.ts.orig
new file mode 100644
index 0000000..761e01a
--- /dev/null
+++ b/dist/dts/export/index.d.ts.orig
@@ -0,0 +1,49 @@
+import { Client, Connection, Pool } from 'pg';
+import { Socket } from '../shims/net';
+import { neon, NeonDbError } from './httpQuery';
+import type { NeonConfigGlobalAndClient } from './neonConfig';
+/**
+ * We export the pg library mostly unchanged, but we do make a few tweaks.
+ *
+ * (1) Connecting and querying can require a lot of network round-trips. We
+ * add a pipelining option for the connection (startup + auth + first query),
+ * but this works with cleartext password auth only. We can also pipeline TLS
+ * startup, but currently this works only with Neon hosts (not vanilla pg or
+ * pgbouncer).
+ *
+ * (2) SCRAM auth is deliberately CPU-intensive, and this is not appropriate
+ * for a serverless environment. In case it is still used, however, we replace
+ * the standard (synchronous) pg implementation with one that uses SubtleCrypto
+ * for repeated SHA-256 digests. This saves some time and CPU.
+ *
+ * (3) We now (experimentally) redirect Pool.query over a fetch request if the
+ * circumstances are right.
+ */
+declare interface NeonClient {
+ connection: Connection & {
+ stream: Socket;
+ sendSCRAMClientFinalMessage: (response: any) => void;
+ ssl: any;
+ };
+ _handleReadyForQuery: any;
+ _handleAuthCleartextPassword: any;
+ startup: any;
+ getStartupConf: any;
+ saslSession: any;
+}
+declare class NeonClient extends Client {
+ config: any;
+ get neonConfig(): NeonConfigGlobalAndClient;
+ constructor(config: any);
+ connect(): Promise;
+ connect(callback: (err?: Error) => void): void;
+ _handleAuthSASLContinue(msg: any): Promise;
+}
+declare class NeonPool extends Pool {
+ Client: typeof NeonClient;
+ hasFetchUnsupportedListeners: boolean;
+ on(event: 'error' | 'connect' | 'acquire' | 'release' | 'remove', listener: any): this;
+ query(config?: any, values?: any, cb?: any): any;
+}
+export { Socket as neonConfig, NeonPool as Pool, NeonClient as Client, neon, NeonDbError, };
+export { Connection, DatabaseError, Query, ClientBase, defaults, types, } from 'pg';
diff --git a/dist/dts/export/neonConfig.d.ts b/dist/dts/export/neonConfig.d.ts
new file mode 100644
index 0000000..dfc246c
--- /dev/null
+++ b/dist/dts/export/neonConfig.d.ts
@@ -0,0 +1,131 @@
+export interface NeonConfigGlobalOnly {
+ /**
+ * Set `fetchEndpoint` to set the server endpoint to be sent queries via http
+ * fetch. May be useful in local development (e.g. to set a port that's not
+ * the default 443).
+ *
+ * Provide either the full endpoint URL, or a function that takes the
+ * database host address and port and returns the full endpoint URL
+ * (including protocol).
+ *
+ * Default: `host => 'https://' + host + '/sql'`
+ *
+ */
+ fetchEndpoint: string | ((host: string, port: number | string) => string);
+ /**
+ * **Experimentally**, when `poolQueryViaFetch` is `true`, and no listeners
+ * for the `"connect"`, `"acquire"`, `"release"` or `"remove"` events are set
+ * on the `Pool`, queries via `Pool.query()` will be sent by low-latency HTTP
+ * fetch request.
+ *
+ * Default: `false`.
+ */
+ poolQueryViaFetch: boolean;
+ /**
+ * **Experimentally**, when `fetchConnectionCache` is `true`, queries carried
+ * via HTTP fetch make use of a connection cache on the server.
+ *
+ * Default: `false`.
+ */
+ fetchConnectionCache: boolean;
+ /**
+ * The `fetchFunction` option allows you to supply an alternative function
+ * for making http requests. The function must accept the same arguments as
+ * native `fetch`.
+ *
+ * Default: `undefined`.
+ */
+ fetchFunction: any;
+}
+export interface NeonConfigGlobalAndClient {
+ /**
+ * If no global `WebSocket` object is available, set `webSocketConstructor`
+ * to the constructor for a custom WebSocket implementation, such as those
+ * provided by `ws` or `undici`.
+ */
+ webSocketConstructor: any;
+ /**
+ * Set `wsProxy` to use your own WebSocket proxy server.
+ *
+ * Provide either the proxy server’s domain name, or a function that takes
+ * the database host and port and returns the proxy server address (without
+ * protocol).
+ *
+ * Example: `(host, port) => "myproxy.example.net?address=" + host + ":" + port`
+ *
+ * Default: `host => host + '/v2'`
+ */
+ wsProxy: string | ((host: string, port: number | string) => string) | undefined;
+ /**
+ * Use a secure (`wss:`) connection to the WebSocket proxy.
+ *
+ * Default: `true`.
+ */
+ useSecureWebSocket: boolean;
+ /**
+ * Disable TLS encryption in the Postgres protocol (as set via e.g.
+ * `?sslmode=require` in the connection string). Connection remains secure
+ * if `useSecureWebSocket` is `true`.
+ *
+ * Default: `true`
+ */
+ forceDisablePgSSL: boolean;
+ /**
+ * Pipelines the startup message, cleartext password message and first query
+ * when set to `"password"`. This works only for cleartext password auth.
+ *
+ * Default: `"password"`.
+ */
+ pipelineConnect: 'password' | false;
+ /**
+ * If `forceDisablePgSSL` is `false` and the Postgres connection parameters
+ * specify TLS, you must supply the subtls TLS library to this option:
+ *
+ * ```
+ * import { neonConfig } from '@neondatabase/serverless';
+ * import * as subtls from 'subtls';
+ * neonConfig.subtls = subtls;
+ * ```
+ *
+ * Default: `undefined`.
+ */
+ subtls: any;
+ /**
+ * Pipeline the pg SSL request and TLS handshake when `forceDisablePgSSL` is
+ * `false` and the Postgres connection parameters specify TLS. Currently
+ * compatible only with Neon hosts.
+ *
+ * Default: `false`.
+ */
+ pipelineTLS: boolean;
+ /**
+ * Set `rootCerts` to a string comprising one or more PEM files. These are
+ * the trusted root certificates for a TLS connection to Postgres when
+ * `forceDisablePgSSL` is `false` and the Postgres connection parameters
+ * specify TLS.
+ *
+ * Default: `""`.
+ */
+ rootCerts: string;
+ /**
+ * Batch multiple network writes per run-loop into a single outgoing
+ * WebSocket message.
+ *
+ * Default: `true`.
+ */
+ coalesceWrites: boolean;
+ /**
+ * When `disableSNI` is `true`, `forceDisablePgSSL` is `false` and the
+ * Postgres connection parameters specify TLS, we send no SNI data in the
+ * Postgres TLS handshake.
+ *
+ * On Neon, disabling SNI and including the Neon project name in the password
+ * avoids CPU-intensive SCRAM authentication, but this is only relevant for
+ * earlier iterations of Neon's WebSocket support.
+ *
+ * Default: `false`.
+ */
+ disableSNI: boolean;
+}
+export interface NeonConfig extends NeonConfigGlobalOnly, NeonConfigGlobalAndClient {
+}
diff --git a/dist/dts/ext/events.d.ts b/dist/dts/ext/events.d.ts
new file mode 100644
index 0000000..d04af49
--- /dev/null
+++ b/dist/dts/ext/events.d.ts
@@ -0,0 +1,22 @@
+export type Listener = (...args: any[]) => void;
+
+export class EventEmitter {
+ static listenerCount(emitter: EventEmitter, type: string | number): number;
+ static defaultMaxListeners: number;
+
+ eventNames(): Array;
+ setMaxListeners(n: number): this;
+ getMaxListeners(): number;
+ emit(type: string | number, ...args: any[]): boolean;
+ addListener(type: string | number, listener: Listener): this;
+ on(type: string | number, listener: Listener): this;
+ once(type: string | number, listener: Listener): this;
+ prependListener(type: string | number, listener: Listener): this;
+ prependOnceListener(type: string | number, listener: Listener): this;
+ removeListener(type: string | number, listener: Listener): this;
+ off(type: string | number, listener: Listener): this;
+ removeAllListeners(type?: string | number): this;
+ listeners(type: string | number): Listener[];
+ listenerCount(type: string | number): number;
+ rawListeners(type: string | number): Listener[];
+}
diff --git a/dist/dts/ext/pg.d.ts b/dist/dts/ext/pg.d.ts
new file mode 100644
index 0000000..94a942e
--- /dev/null
+++ b/dist/dts/ext/pg.d.ts
@@ -0,0 +1,325 @@
+///
+
+import events = require("events");
+import stream = require("stream");
+import pgTypes = require("pg-types");
+import { NoticeMessage } from "pg-protocol/dist/messages";
+
+import { ConnectionOptions } from "tls";
+
+export type QueryConfigValues = T extends Array ? T : never;
+
+export interface ClientConfig {
+ user?: string | undefined;
+ database?: string | undefined;
+ password?: string | (() => string | Promise) | undefined;
+ port?: number | undefined;
+ host?: string | undefined;
+ connectionString?: string | undefined;
+ keepAlive?: boolean | undefined;
+ stream?: () => stream.Duplex | stream.Duplex | undefined;
+ statement_timeout?: false | number | undefined;
+ ssl?: boolean | ConnectionOptions | undefined;
+ query_timeout?: number | undefined;
+ keepAliveInitialDelayMillis?: number | undefined;
+ idle_in_transaction_session_timeout?: number | undefined;
+ application_name?: string | undefined;
+ connectionTimeoutMillis?: number | undefined;
+ types?: CustomTypesConfig | undefined;
+ options?: string | undefined;
+}
+
+export type ConnectionConfig = ClientConfig;
+
+export interface Defaults extends ClientConfig {
+ poolSize?: number | undefined;
+ poolIdleTimeout?: number | undefined;
+ reapIntervalMillis?: number | undefined;
+ binary?: boolean | undefined;
+ parseInt8?: boolean | undefined;
+ parseInputDatesAsUTC?: boolean | undefined;
+}
+
+export interface PoolConfig extends ClientConfig {
+ // properties from module 'node-pool'
+ max?: number | undefined;
+ min?: number | undefined;
+ idleTimeoutMillis?: number | undefined | null;
+ log?: ((...messages: any[]) => void) | undefined;
+ Promise?: PromiseConstructorLike | undefined;
+ allowExitOnIdle?: boolean | undefined;
+ maxUses?: number | undefined;
+ maxLifetimeSeconds?: number | undefined;
+ Client?: (new() => ClientBase) | undefined;
+}
+
+export interface QueryConfig {
+ name?: string | undefined;
+ text: string;
+ values?: QueryConfigValues;
+ types?: CustomTypesConfig | undefined;
+}
+
+export interface CustomTypesConfig {
+ getTypeParser: typeof pgTypes.getTypeParser;
+}
+
+export interface Submittable {
+ submit: (connection: Connection) => void;
+}
+
+export interface QueryArrayConfig extends QueryConfig {
+ rowMode: "array";
+}
+
+export interface FieldDef {
+ name: string;
+ tableID: number;
+ columnID: number;
+ dataTypeID: number;
+ dataTypeSize: number;
+ dataTypeModifier: number;
+ format: string;
+}
+
+export interface QueryResultBase {
+ command: string;
+ rowCount: number | null;
+ oid: number;
+ fields: FieldDef[];
+}
+
+export interface QueryResultRow {
+ [column: string]: any;
+}
+
+export interface QueryResult extends QueryResultBase {
+ rows: R[];
+}
+
+export interface QueryArrayResult extends QueryResultBase {
+ rows: R[];
+}
+
+export interface Notification {
+ processId: number;
+ channel: string;
+ payload?: string | undefined;
+}
+
+export interface ResultBuilder extends QueryResult {
+ addRow(row: R): void;
+}
+
+export interface QueryParse {
+ name: string;
+ text: string;
+ types: string[];
+}
+
+type ValueMapper = (param: any, index: number) => any;
+
+export interface BindConfig {
+ portal?: string | undefined;
+ statement?: string | undefined;
+ binary?: string | undefined;
+ values?: Array | undefined;
+ valueMapper?: ValueMapper | undefined;
+}
+
+export interface ExecuteConfig {
+ portal?: string | undefined;
+ rows?: string | undefined;
+}
+
+export interface MessageConfig {
+ type: string;
+ name?: string | undefined;
+}
+
+export function escapeIdentifier(str: string): string;
+
+export function escapeLiteral(str: string): string;
+
+export class Connection extends events.EventEmitter {
+ readonly stream: stream.Duplex;
+
+ constructor(config?: ConnectionConfig);
+
+ bind(config: BindConfig | null, more: boolean): void;
+ execute(config: ExecuteConfig | null, more: boolean): void;
+ parse(query: QueryParse, more: boolean): void;
+
+ query(text: string): void;
+
+ describe(msg: MessageConfig, more: boolean): void;
+ close(msg: MessageConfig, more: boolean): void;
+
+ flush(): void;
+ sync(): void;
+ end(): void;
+}
+
+export interface PoolOptions extends PoolConfig {
+ max: number;
+ maxUses: number;
+ allowExitOnIdle: boolean;
+ maxLifetimeSeconds: number;
+ idleTimeoutMillis: number | null;
+}
+
+/**
+ * {@link https://node-postgres.com/apis/pool}
+ */
+export class Pool extends events.EventEmitter {
+ /**
+ * Every field of the config object is entirely optional.
+ * The config passed to the pool is also passed to every client
+ * instance within the pool when the pool creates that client.
+ */
+ constructor(config?: PoolConfig);
+
+ readonly totalCount: number;
+ readonly idleCount: number;
+ readonly waitingCount: number;
+ readonly expiredCount: number;
+
+ readonly ending: boolean;
+ readonly ended: boolean;
+
+ options: PoolOptions;
+
+ connect(): Promise;
+ connect(
+ callback: (err: Error | undefined, client: PoolClient | undefined, done: (release?: any) => void) => void,
+ ): void;
+
+ end(): Promise;
+ end(callback: () => void): void;
+
+ query(queryStream: T): T;
+ // tslint:disable:no-unnecessary-generics
+ query(
+ queryConfig: QueryArrayConfig,
+ values?: QueryConfigValues,
+ ): Promise>;
+ query(
+ queryConfig: QueryConfig,
+ ): Promise>;
+ query(
+ queryTextOrConfig: string | QueryConfig,
+ values?: QueryConfigValues,
+ ): Promise>;
+ query(
+ queryConfig: QueryArrayConfig,
+ callback: (err: Error, result: QueryArrayResult) => void,
+ ): void;
+ query(
+ queryTextOrConfig: string | QueryConfig,
+ callback: (err: Error, result: QueryResult) => void,
+ ): void;
+ query(
+ queryText: string,
+ values: QueryConfigValues,
+ callback: (err: Error, result: QueryResult) => void,
+ ): void;
+ // tslint:enable:no-unnecessary-generics
+
+ on(event: "release" | "error", listener: (err: Error, client: PoolClient) => void): this;
+ on(event: "connect" | "acquire" | "remove", listener: (client: PoolClient) => void): this;
+}
+
+export class ClientBase extends events.EventEmitter {
+ constructor(config?: string | ClientConfig);
+
+ connect(): Promise;
+ connect(callback: (err: Error) => void): void;
+
+ query(queryStream: T): T;
+ // tslint:disable:no-unnecessary-generics
+ query(
+ queryConfig: QueryArrayConfig