@rebasepro/server-postgres 0.34.1 → 0.34.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2,7 +2,7 @@ import { createRequire as __createRequire } from "module";
2
2
  __createRequire(import.meta.url);
3
3
  import { n as require_arg, o as __toESM } from "./cli-prompt-DXG0yk-h.js";
4
4
  import { d as poolMaxCeiling } from "./connection-C1zXTPJq.js";
5
- import { t as openRebase } from "./open-rebase-DykxNl1j.js";
5
+ import { t as openRebase } from "./open-rebase-BQrU-FAV.js";
6
6
  import { c as diagnoseDbError } from "./cli-schema-dir-CdEqBcph.js";
7
7
  import { i as outError, n as describeFailure, r as out } from "./source-VxbrQojV.js";
8
8
  import { h as RELAYED_FLAGS } from "./migrate-baseline-CnIbBRgh.js";
@@ -317,4 +317,4 @@ async function feedLineByLine(source, server, feed, exited) {
317
317
  //#endregion
318
318
  export { consoleCommand };
319
319
 
320
- //# sourceMappingURL=cli-console-E5TM3GaL.js.map
320
+ //# sourceMappingURL=cli-console-oVdz6rG3.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"cli-console-E5TM3GaL.js","names":[],"sources":["../src/cli-console.ts"],"sourcesContent":["/**\n * `rebase console` — the driver's half.\n *\n * Loads the project's tables (`backend/schema`) the way `rebase db push` does,\n * and the global table hooks `backend/hooks.ts` exports, opens the database with\n * {@link openRebase}, and either evaluates one piece of code\n * (`--eval`) or starts a Node REPL with `rebase` and `tables` in scope.\n * The `rebase` CLI resolves the database first (the managed one included) and\n * hands this process `DATABASE_URL`, exactly as it does for `db` commands.\n *\n * This is the boot side of `openRebase`: it is where the environment is read\n * — `DATABASE_URL`, and the `REBASE_DB_POOL_MAX` ceiling the managed\n * development database needs — and turned into explicit options.\n */\nimport arg from \"arg\";\nimport fs from \"fs\";\nimport path from \"path\";\nimport readline from \"node:readline\";\nimport repl from \"node:repl\";\nimport { PassThrough } from \"node:stream\";\nimport tty from \"node:tty\";\nimport { pathToFileURL } from \"node:url\";\nimport { inspect } from \"node:util\";\nimport { setLogOutput } from \"@rebasepro/server\";\nimport type { TableDescriptor, TableHooks } from \"@rebasepro/types\";\nimport { RELAYED_FLAGS } from \"./cli-flags\";\nimport { DEFAULT_SCHEMA_DIR } from \"./cli-schema-dir\";\nimport { diagnoseDbError } from \"./cli-errors\";\nimport { out, outError, describeFailure } from \"./cli-output\";\nimport { poolMaxCeiling } from \"./connection\";\nimport { openRebase, type OpenedRebase } from \"./open-rebase\";\n\n/**\n * The flags `rebase console` takes. `--history` is the CLI's own: where it\n * keeps the REPL's history (`.rebase/console_history` in the project).\n */\nexport const CONSOLE_FLAGS = {\n \"--schema-dir\": String,\n \"--eval\": String,\n \"-e\": \"--eval\",\n \"--history\": String\n} satisfies arg.Spec;\n\n/** What the code the console runs can name. */\nexport interface ConsoleScope {\n rebase: OpenedRebase;\n /** The descriptors of the tables the project serves. */\n tables: TableDescriptor[];\n}\n\ntype ScopedFunction = (rebase: OpenedRebase, tables: TableDescriptor[]) => Promise<unknown>;\ntype AsyncFunctionConstructor = new (...parameters: string[]) => ScopedFunction;\n\n/** The constructor of `async function` — what `new Function` is for a body that awaits. */\nconst AsyncFunction: AsyncFunctionConstructor = Object.getPrototypeOf(async () => undefined).constructor;\n\n/**\n * Run `code` with `rebase` and `tables` in scope and resolve with its\n * value.\n *\n * Read as an expression first, so `rebase.dataAsAdmin.posts.find()` is its own\n * result; code that is not one expression runs as a function body, where\n * `await` works everywhere and `return` gives the result.\n */\nexport async function evaluateInConsole(code: string, scope: ConsoleScope): Promise<unknown> {\n let run: ScopedFunction;\n try {\n run = new AsyncFunction(\"rebase\", \"tables\", `return (${code}\\n);`);\n } catch (error) {\n if (!(error instanceof SyntaxError)) throw error;\n run = new AsyncFunction(\"rebase\", \"tables\", code);\n }\n return run(scope.rebase, scope.tables);\n}\n\n/** A result as JSON, the way `--eval` prints it: dates as ISO strings, bigints as strings. */\nexport function consoleJson(value: unknown): string {\n return JSON.stringify(value, (_key, item: unknown) => typeof item === \"bigint\" ? item.toString() : item, 2) ?? \"undefined\";\n}\n\n/** The host and database a URL names, for the banner — never its credentials. */\nfunction describeDatabase(databaseUrl: string): string {\n try {\n const url = new URL(databaseUrl);\n return `${url.hostname}${url.port ? `:${url.port}` : \"\"}${url.pathname}`;\n } catch {\n return \"the configured database\";\n }\n}\n\n/** Where the REPL reads and writes; the terminal unless a caller hands it streams. */\nexport interface ConsoleStreams {\n input?: NodeJS.ReadableStream;\n output?: NodeJS.WritableStream;\n}\n\n/**\n * `rebase console [--eval <code>] [--schema-dir <dir>]`, from the driver\n * line `[\"console\", …flags]`. Resolves with the exit code.\n */\nexport async function consoleCommand(args: string[], streams: ConsoleStreams = {}): Promise<number> {\n const flags = arg({ ...RELAYED_FLAGS, ...CONSOLE_FLAGS }, { argv: args.slice(1) });\n if (flags[\"--help\"]) {\n out(\"Run `rebase console --help` for the options — this is the driver's own entry point.\");\n return 0;\n }\n\n const databaseUrl = flags[\"--database-url\"] || process.env.DATABASE_URL;\n if (!databaseUrl) {\n outError(\"✗ No database to open: DATABASE_URL is not set. Set it in .env, or pass --database-url.\");\n return 1;\n }\n\n // The console's own lines are what the reader is here for; the driver's\n // info-level boot notes are not, unless they asked for them.\n if (process.env.LOG_LEVEL === undefined) process.env.LOG_LEVEL = \"warn\";\n\n // And whatever level they asked for, a log line is never part of the\n // answer: stdout holds the `--eval` result a pipe reads (`| jq .`) and the\n // REPL's values. The scaffold's `.env` sets LOG_LEVEL=info, and under\n // NODE_ENV=production warnings go to stdout too.\n setLogOutput(\"stderr\");\n try {\n return await openAndRun({\n databaseUrl,\n schemaDir: flags[\"--schema-dir\"],\n eval: flags[\"--eval\"],\n history: flags[\"--history\"]\n }, streams);\n } finally {\n setLogOutput();\n }\n}\n\n/** Whether a connection was reset or cut off before it answered, anywhere in the error's chain. */\nfunction connectionCutOff(error: unknown, depth = 0): boolean {\n if (!error || typeof error !== \"object\" || depth > 4) return false;\n if (\"code\" in error && error.code === \"ECONNRESET\") return true;\n if (error instanceof Error && /Connection terminated unexpectedly/.test(error.message)) return true;\n if (\"errors\" in error && Array.isArray(error.errors) && error.errors.some(inner => connectionCutOff(inner, depth + 1))) return true;\n return \"cause\" in error && connectionCutOff(error.cause, depth + 1);\n}\n\n/** Whether Postgres refused the connection for want of one: SQLSTATE 53300, anywhere in the error's chain. */\nfunction noFreeConnection(error: unknown, depth = 0): boolean {\n if (!error || typeof error !== \"object\" || depth > 4) return false;\n if (\"code\" in error && error.code === \"53300\") return true;\n return \"cause\" in error && noFreeConnection(error.cause, depth + 1);\n}\n\n/**\n * What the console says when the project's database will not open: the banner\n * every db command prints for a database it cannot reach, or one sentence —\n * never the driver's error serialised onto one line, stack and all.\n *\n * The managed development database accepts only a few connections at a time,\n * and a running `rebase dev` holds some of them. Its proxy refuses one over the\n * limit with SQLSTATE 53300; a database an earlier CLI started resets it\n * instead, and `read ECONNRESET` says nothing about why.\n */\nexport function describeOpenFailure(error: unknown, databaseUrl: string, managed: boolean): string {\n if (managed && (connectionCutOff(error) || noFreeConnection(error))) {\n return \"✗ The managed development database has no free connection: it accepts only a few at a time, \" +\n \"and other clients hold them — a running `rebase dev` holds some.\\n\" +\n \" Close another `rebase console`, psql or database GUI and run this again, \" +\n \"or stop `rebase dev` while you use the console.\";\n }\n return diagnoseDbError(error, databaseUrl) ?? describeFailure(error);\n}\n\n/** The names a table hook can have; anything else on a `hooks` export is not one. */\nconst TABLE_HOOK_NAMES = [\"beforeQuery\", \"afterRead\", \"beforeSave\", \"afterSave\", \"afterSaveError\", \"beforeDelete\", \"afterDelete\"] as const;\n\n/** Whether a module's `hooks` export is table hooks: an object whose every key is a hook name holding a function. */\nfunction isTableHooks(value: unknown): value is TableHooks {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) return false;\n return Object.entries(value).every(([key, hook]) =>\n (TABLE_HOOK_NAMES as readonly string[]).includes(key) && (hook === undefined || typeof hook === \"function\"));\n}\n\n/**\n * The project's global table hooks: the `hooks` its `backend/hooks.ts`\n * exports, which the server runs for every table ahead of each table's own.\n *\n * `backend/` is the schema directory's parent. No module there means no global\n * hooks, as it does for the server.\n *\n * One that is there and cannot be imported — an import that needs an\n * environment variable the console was not given, say — does not stop the\n * console, which can still read and write. It says so, once, and runs without\n * them: writes from this session then skip the global tier, and the reader\n * knows it.\n *\n * They are handed on as declared: the driver calls each with the descriptor\n * of the table it runs for.\n *\n * @param schemaDir the schema directory, absolute.\n */\nexport async function loadProjectHooks(schemaDir: string): Promise<TableHooks | undefined> {\n const backendDir = path.dirname(schemaDir);\n // `.js` first, as the server's own loader reads a built module.\n const modulePath = [\".js\", \".mjs\", \".ts\", \".mts\"]\n .map(ext => path.join(backendDir, `hooks${ext}`))\n .find(candidate => fs.existsSync(candidate));\n if (!modulePath) return undefined;\n\n let mod: Record<string, unknown>;\n try {\n mod = await import(pathToFileURL(modulePath).href);\n } catch (error) {\n const reason = (error instanceof Error ? error.message : String(error)).split(\"\\n\")[0];\n outError(`⚠ Global hooks are off in this session: ${modulePath} could not be loaded (${reason}). Each table's own hooks still run.`);\n return undefined;\n }\n if (mod.hooks === undefined) return undefined;\n if (!isTableHooks(mod.hooks)) {\n outError(`⚠ Global hooks are off in this session: the \\`hooks\\` ${modulePath} exports is not an object of table hooks (${TABLE_HOOK_NAMES.join(\", \")}).`);\n return undefined;\n }\n return mod.hooks;\n}\n\n/** Open the project, run `--eval` or the REPL, and close it again. Resolves with the exit code. */\nasync function openAndRun(\n options: { databaseUrl: string; schemaDir?: string; eval?: string; history?: string },\n streams: ConsoleStreams\n): Promise<number> {\n const { databaseUrl } = options;\n // The tables the way every other driver command reads them: a schema that\n // does not compile stops the console too, rather than opening it over a\n // subset of the tables.\n const { loadTableSchema } = await import(\"./schema/load-tables\");\n const schemaDir = path.resolve(options.schemaDir || DEFAULT_SCHEMA_DIR);\n const { tables } = await loadTableSchema(schemaDir);\n // Writes from the console run the same hook tiers as a server write.\n const hooks = await loadProjectHooks(schemaDir);\n\n const ceiling = poolMaxCeiling();\n let rebase: OpenedRebase;\n try {\n rebase = await openRebase({\n databaseUrl,\n tables,\n ...(hooks ? { hooks } : {}),\n ...(ceiling !== null ? { pool: { max: ceiling } } : {})\n });\n } catch (error) {\n outError(describeOpenFailure(error, databaseUrl, process.env.REBASE_DEV_DATABASE_KIND === \"managed\"));\n return 1;\n }\n\n try {\n const code = options.eval;\n if (code !== undefined) {\n try {\n const result = await evaluateInConsole(code, { rebase, tables: rebase.tables });\n if (result !== undefined) out(consoleJson(result));\n return 0;\n } catch (error) {\n outError(describeFailure(error));\n return 1;\n }\n }\n\n await startRepl({ rebase, tables: rebase.tables }, {\n history: options.history,\n database: describeDatabase(databaseUrl),\n ...streams\n });\n return 0;\n } finally {\n await rebase.close();\n }\n}\n\n/** The interactive half: a Node REPL until `.exit`, Ctrl-D or the end of piped input. */\nasync function startRepl(scope: ConsoleScope, options: { history?: string; database: string } & ConsoleStreams): Promise<void> {\n const input = options.input ?? process.stdin;\n const output = options.output ?? process.stdout;\n const typed = input instanceof tty.ReadStream && input.isTTY;\n\n // For a person at a terminal. Piped, stdout is the REPL's answers, which\n // whatever reads the pipe is after, so the banner goes to stderr with the\n // rest of what the console says about itself.\n const say = typed ? out : outError;\n say(\"\");\n say(` rebase console — ${options.database}, ${scope.tables.length} table(s)`);\n say(\" In scope: rebase (dataAsAdmin, sql, withAuth, close) and tables. Top-level await works.\");\n say(\" Try: await rebase.dataAsAdmin.<table>.find({ limit: 5 })\");\n say(\"\");\n\n // Typed at a terminal, the REPL reads it as one. Anything else — a pipe, a\n // file, a stream handed in — reaches it a line at a time through `feed`\n // (see `feedLineByLine`).\n const feed = typed ? undefined : new PassThrough();\n // Colours for a terminal only: piped to a file or another program, the\n // escape codes are noise in the text.\n const colors = output instanceof tty.WriteStream && output.isTTY;\n // Started without a prompt, and given one once the scope is in place: a\n // line that arrives with the first prompt must already see `rebase`.\n const server = repl.start({\n prompt: \"\",\n useGlobal: false,\n ...(feed ? { input: feed, output, terminal: false } : { input, output }),\n writer: (value: unknown) => inspect(value, { colors, depth: 6 })\n });\n server.context.rebase = scope.rebase;\n server.context.tables = scope.tables;\n server.setPrompt(\"rebase> \");\n\n const history = options.history;\n if (history) {\n fs.mkdirSync(path.dirname(history), { recursive: true });\n await new Promise<void>((resolve) => {\n server.setupHistory(history, (error) => {\n if (error) outError(` (history is off: ${error.message})`);\n resolve();\n });\n });\n }\n\n const exited = new Promise<void>((resolve) => server.once(\"exit\", () => resolve()));\n server.displayPrompt();\n if (feed) await feedLineByLine(input, server, feed, exited);\n await exited;\n}\n\n/**\n * Hand input that is not typed at a terminal to the REPL a line at a time,\n * each once the REPL has finished the one before.\n *\n * Typed, the REPL holds keystrokes back while a top-level `await` is pending.\n * Piped, every line arrives at once and each is evaluated as it arrives, so in\n * `const { data } = await …` followed by `data.map(…)` the second line read\n * `data` before the first had assigned it.\n *\n * The REPL is paused as each line reaches it, and it resumes its input when it\n * displays its prompt again: once the line's value has settled, its error has\n * been printed, or it needs the next line to complete it. That resumption is\n * when the next line goes in. Lines are written one per chunk, because a\n * chunk holding several is split and every line of it handed over at once.\n */\nasync function feedLineByLine(\n source: NodeJS.ReadableStream,\n server: repl.REPLServer,\n feed: PassThrough,\n exited: Promise<void>\n): Promise<void> {\n let evaluated: (() => void) | undefined;\n const ready = () => {\n const resolve = evaluated;\n evaluated = undefined;\n resolve?.();\n };\n // Before the REPL's own handler, so a line it evaluates at once resumes\n // after this pause rather than before it.\n server.prependListener(\"line\", () => {\n if (!server.editorMode) server.pause();\n });\n // `.editor` collects lines with no prompt until Ctrl-D: they go straight in.\n server.on(\"line\", () => {\n if (!server.editorMode) return;\n server.resume();\n ready();\n });\n server.on(\"resume\", ready);\n\n const closed = exited.then(() => \"closed\" as const);\n const lines = readline.createInterface({ input: source, crlfDelay: Infinity });\n for await (const line of lines) {\n const done = new Promise<\"done\">((resolve) => { evaluated = () => resolve(\"done\"); });\n feed.write(`${line}\\n`);\n // `.exit`: the rest of the input is not for this REPL.\n if (await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],"sources":["../src/cli-console.ts"],"sourcesContent":["/**\n * `rebase console` — the driver's half.\n *\n * Loads the project's tables (`backend/schema`) the way `rebase db push` does,\n * and the global table hooks `backend/hooks.ts` exports, opens the database with\n * {@link openRebase}, and either evaluates one piece of code\n * (`--eval`) or starts a Node REPL with `rebase` and `tables` in scope.\n * The `rebase` CLI resolves the database first (the managed one included) and\n * hands this process `DATABASE_URL`, exactly as it does for `db` commands.\n *\n * This is the boot side of `openRebase`: it is where the environment is read\n * — `DATABASE_URL`, and the `REBASE_DB_POOL_MAX` ceiling the managed\n * development database needs — and turned into explicit options.\n */\nimport arg from \"arg\";\nimport fs from \"fs\";\nimport path from \"path\";\nimport readline from \"node:readline\";\nimport repl from \"node:repl\";\nimport { PassThrough } from \"node:stream\";\nimport tty from \"node:tty\";\nimport { pathToFileURL } from \"node:url\";\nimport { inspect } from \"node:util\";\nimport { setLogOutput } from \"@rebasepro/server\";\nimport type { TableDescriptor, TableHooks } from \"@rebasepro/types\";\nimport { RELAYED_FLAGS } from \"./cli-flags\";\nimport { DEFAULT_SCHEMA_DIR } from \"./cli-schema-dir\";\nimport { diagnoseDbError } from \"./cli-errors\";\nimport { out, outError, describeFailure } from \"./cli-output\";\nimport { poolMaxCeiling } from \"./connection\";\nimport { openRebase, type OpenedRebase } from \"./open-rebase\";\n\n/**\n * The flags `rebase console` takes. `--history` is the CLI's own: where it\n * keeps the REPL's history (`.rebase/console_history` in the project).\n */\nexport const CONSOLE_FLAGS = {\n \"--schema-dir\": String,\n \"--eval\": String,\n \"-e\": \"--eval\",\n \"--history\": String\n} satisfies arg.Spec;\n\n/** What the code the console runs can name. */\nexport interface ConsoleScope {\n rebase: OpenedRebase;\n /** The descriptors of the tables the project serves. */\n tables: TableDescriptor[];\n}\n\ntype ScopedFunction = (rebase: OpenedRebase, tables: TableDescriptor[]) => Promise<unknown>;\ntype AsyncFunctionConstructor = new (...parameters: string[]) => ScopedFunction;\n\n/** The constructor of `async function` — what `new Function` is for a body that awaits. */\nconst AsyncFunction: AsyncFunctionConstructor = Object.getPrototypeOf(async () => undefined).constructor;\n\n/**\n * Run `code` with `rebase` and `tables` in scope and resolve with its\n * value.\n *\n * Read as an expression first, so `rebase.dataAsAdmin.posts.find()` is its own\n * result; code that is not one expression runs as a function body, where\n * `await` works everywhere and `return` gives the result.\n */\nexport async function evaluateInConsole(code: string, scope: ConsoleScope): Promise<unknown> {\n let run: ScopedFunction;\n try {\n run = new AsyncFunction(\"rebase\", \"tables\", `return (${code}\\n);`);\n } catch (error) {\n if (!(error instanceof SyntaxError)) throw error;\n run = new AsyncFunction(\"rebase\", \"tables\", code);\n }\n return run(scope.rebase, scope.tables);\n}\n\n/** A result as JSON, the way `--eval` prints it: dates as ISO strings, bigints as strings. */\nexport function consoleJson(value: unknown): string {\n return JSON.stringify(value, (_key, item: unknown) => typeof item === \"bigint\" ? item.toString() : item, 2) ?? \"undefined\";\n}\n\n/** The host and database a URL names, for the banner — never its credentials. */\nfunction describeDatabase(databaseUrl: string): string {\n try {\n const url = new URL(databaseUrl);\n return `${url.hostname}${url.port ? `:${url.port}` : \"\"}${url.pathname}`;\n } catch {\n return \"the configured database\";\n }\n}\n\n/** Where the REPL reads and writes; the terminal unless a caller hands it streams. */\nexport interface ConsoleStreams {\n input?: NodeJS.ReadableStream;\n output?: NodeJS.WritableStream;\n}\n\n/**\n * `rebase console [--eval <code>] [--schema-dir <dir>]`, from the driver\n * line `[\"console\", …flags]`. Resolves with the exit code.\n */\nexport async function consoleCommand(args: string[], streams: ConsoleStreams = {}): Promise<number> {\n const flags = arg({ ...RELAYED_FLAGS, ...CONSOLE_FLAGS }, { argv: args.slice(1) });\n if (flags[\"--help\"]) {\n out(\"Run `rebase console --help` for the options — this is the driver's own entry point.\");\n return 0;\n }\n\n const databaseUrl = flags[\"--database-url\"] || process.env.DATABASE_URL;\n if (!databaseUrl) {\n outError(\"✗ No database to open: DATABASE_URL is not set. Set it in .env, or pass --database-url.\");\n return 1;\n }\n\n // The console's own lines are what the reader is here for; the driver's\n // info-level boot notes are not, unless they asked for them.\n if (process.env.LOG_LEVEL === undefined) process.env.LOG_LEVEL = \"warn\";\n\n // And whatever level they asked for, a log line is never part of the\n // answer: stdout holds the `--eval` result a pipe reads (`| jq .`) and the\n // REPL's values. The scaffold's `.env` sets LOG_LEVEL=info, and under\n // NODE_ENV=production warnings go to stdout too.\n setLogOutput(\"stderr\");\n try {\n return await openAndRun({\n databaseUrl,\n schemaDir: flags[\"--schema-dir\"],\n eval: flags[\"--eval\"],\n history: flags[\"--history\"]\n }, streams);\n } finally {\n setLogOutput();\n }\n}\n\n/** Whether a connection was reset or cut off before it answered, anywhere in the error's chain. */\nfunction connectionCutOff(error: unknown, depth = 0): boolean {\n if (!error || typeof error !== \"object\" || depth > 4) return false;\n if (\"code\" in error && error.code === \"ECONNRESET\") return true;\n if (error instanceof Error && /Connection terminated unexpectedly/.test(error.message)) return true;\n if (\"errors\" in error && Array.isArray(error.errors) && error.errors.some(inner => connectionCutOff(inner, depth + 1))) return true;\n return \"cause\" in error && connectionCutOff(error.cause, depth + 1);\n}\n\n/** Whether Postgres refused the connection for want of one: SQLSTATE 53300, anywhere in the error's chain. */\nfunction noFreeConnection(error: unknown, depth = 0): boolean {\n if (!error || typeof error !== \"object\" || depth > 4) return false;\n if (\"code\" in error && error.code === \"53300\") return true;\n return \"cause\" in error && noFreeConnection(error.cause, depth + 1);\n}\n\n/**\n * What the console says when the project's database will not open: the banner\n * every db command prints for a database it cannot reach, or one sentence —\n * never the driver's error serialised onto one line, stack and all.\n *\n * The managed development database accepts only a few connections at a time,\n * and a running `rebase dev` holds some of them. Its proxy refuses one over the\n * limit with SQLSTATE 53300; a database an earlier CLI started resets it\n * instead, and `read ECONNRESET` says nothing about why.\n */\nexport function describeOpenFailure(error: unknown, databaseUrl: string, managed: boolean): string {\n if (managed && (connectionCutOff(error) || noFreeConnection(error))) {\n return \"✗ The managed development database has no free connection: it accepts only a few at a time, \" +\n \"and other clients hold them — a running `rebase dev` holds some.\\n\" +\n \" Close another `rebase console`, psql or database GUI and run this again, \" +\n \"or stop `rebase dev` while you use the console.\";\n }\n return diagnoseDbError(error, databaseUrl) ?? describeFailure(error);\n}\n\n/** The names a table hook can have; anything else on a `hooks` export is not one. */\nconst TABLE_HOOK_NAMES = [\"beforeQuery\", \"afterRead\", \"beforeSave\", \"afterSave\", \"afterSaveError\", \"beforeDelete\", \"afterDelete\"] as const;\n\n/** Whether a module's `hooks` export is table hooks: an object whose every key is a hook name holding a function. */\nfunction isTableHooks(value: unknown): value is TableHooks {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) return false;\n return Object.entries(value).every(([key, hook]) =>\n (TABLE_HOOK_NAMES as readonly string[]).includes(key) && (hook === undefined || typeof hook === \"function\"));\n}\n\n/**\n * The project's global table hooks: the `hooks` its `backend/hooks.ts`\n * exports, which the server runs for every table ahead of each table's own.\n *\n * `backend/` is the schema directory's parent. No module there means no global\n * hooks, as it does for the server.\n *\n * One that is there and cannot be imported — an import that needs an\n * environment variable the console was not given, say — does not stop the\n * console, which can still read and write. It says so, once, and runs without\n * them: writes from this session then skip the global tier, and the reader\n * knows it.\n *\n * They are handed on as declared: the driver calls each with the descriptor\n * of the table it runs for.\n *\n * @param schemaDir the schema directory, absolute.\n */\nexport async function loadProjectHooks(schemaDir: string): Promise<TableHooks | undefined> {\n const backendDir = path.dirname(schemaDir);\n // `.js` first, as the server's own loader reads a built module.\n const modulePath = [\".js\", \".mjs\", \".ts\", \".mts\"]\n .map(ext => path.join(backendDir, `hooks${ext}`))\n .find(candidate => fs.existsSync(candidate));\n if (!modulePath) return undefined;\n\n let mod: Record<string, unknown>;\n try {\n mod = await import(pathToFileURL(modulePath).href);\n } catch (error) {\n const reason = (error instanceof Error ? error.message : String(error)).split(\"\\n\")[0];\n outError(`⚠ Global hooks are off in this session: ${modulePath} could not be loaded (${reason}). Each table's own hooks still run.`);\n return undefined;\n }\n if (mod.hooks === undefined) return undefined;\n if (!isTableHooks(mod.hooks)) {\n outError(`⚠ Global hooks are off in this session: the \\`hooks\\` ${modulePath} exports is not an object of table hooks (${TABLE_HOOK_NAMES.join(\", \")}).`);\n return undefined;\n }\n return mod.hooks;\n}\n\n/** Open the project, run `--eval` or the REPL, and close it again. Resolves with the exit code. */\nasync function openAndRun(\n options: { databaseUrl: string; schemaDir?: string; eval?: string; history?: string },\n streams: ConsoleStreams\n): Promise<number> {\n const { databaseUrl } = options;\n // The tables the way every other driver command reads them: a schema that\n // does not compile stops the console too, rather than opening it over a\n // subset of the tables.\n const { loadTableSchema } = await import(\"./schema/load-tables\");\n const schemaDir = path.resolve(options.schemaDir || DEFAULT_SCHEMA_DIR);\n const { tables } = await loadTableSchema(schemaDir);\n // Writes from the console run the same hook tiers as a server write.\n const hooks = await loadProjectHooks(schemaDir);\n\n const ceiling = poolMaxCeiling();\n let rebase: OpenedRebase;\n try {\n rebase = await openRebase({\n databaseUrl,\n tables,\n ...(hooks ? { hooks } : {}),\n ...(ceiling !== null ? { pool: { max: ceiling } } : {})\n });\n } catch (error) {\n outError(describeOpenFailure(error, databaseUrl, process.env.REBASE_DEV_DATABASE_KIND === \"managed\"));\n return 1;\n }\n\n try {\n const code = options.eval;\n if (code !== undefined) {\n try {\n const result = await evaluateInConsole(code, { rebase, tables: rebase.tables });\n if (result !== undefined) out(consoleJson(result));\n return 0;\n } catch (error) {\n outError(describeFailure(error));\n return 1;\n }\n }\n\n await startRepl({ rebase, tables: rebase.tables }, {\n history: options.history,\n database: describeDatabase(databaseUrl),\n ...streams\n });\n return 0;\n } finally {\n await rebase.close();\n }\n}\n\n/** The interactive half: a Node REPL until `.exit`, Ctrl-D or the end of piped input. */\nasync function startRepl(scope: ConsoleScope, options: { history?: string; database: string } & ConsoleStreams): Promise<void> {\n const input = options.input ?? process.stdin;\n const output = options.output ?? process.stdout;\n const typed = input instanceof tty.ReadStream && input.isTTY;\n\n // For a person at a terminal. Piped, stdout is the REPL's answers, which\n // whatever reads the pipe is after, so the banner goes to stderr with the\n // rest of what the console says about itself.\n const say = typed ? out : outError;\n say(\"\");\n say(` rebase console — ${options.database}, ${scope.tables.length} table(s)`);\n say(\" In scope: rebase (dataAsAdmin, sql, withAuth, close) and tables. Top-level await works.\");\n say(\" Try: await rebase.dataAsAdmin.<table>.find({ limit: 5 })\");\n say(\"\");\n\n // Typed at a terminal, the REPL reads it as one. Anything else — a pipe, a\n // file, a stream handed in — reaches it a line at a time through `feed`\n // (see `feedLineByLine`).\n const feed = typed ? undefined : new PassThrough();\n // Colours for a terminal only: piped to a file or another program, the\n // escape codes are noise in the text.\n const colors = output instanceof tty.WriteStream && output.isTTY;\n // Started without a prompt, and given one once the scope is in place: a\n // line that arrives with the first prompt must already see `rebase`.\n const server = repl.start({\n prompt: \"\",\n useGlobal: false,\n ...(feed ? { input: feed, output, terminal: false } : { input, output }),\n writer: (value: unknown) => inspect(value, { colors, depth: 6 })\n });\n server.context.rebase = scope.rebase;\n server.context.tables = scope.tables;\n server.setPrompt(\"rebase> \");\n\n const history = options.history;\n if (history) {\n fs.mkdirSync(path.dirname(history), { recursive: true });\n await new Promise<void>((resolve) => {\n server.setupHistory(history, (error) => {\n if (error) outError(` (history is off: ${error.message})`);\n resolve();\n });\n });\n }\n\n const exited = new Promise<void>((resolve) => server.once(\"exit\", () => resolve()));\n server.displayPrompt();\n if (feed) await feedLineByLine(input, server, feed, exited);\n await exited;\n}\n\n/**\n * Hand input that is not typed at a terminal to the REPL a line at a time,\n * each once the REPL has finished the one before.\n *\n * Typed, the REPL holds keystrokes back while a top-level `await` is pending.\n * Piped, every line arrives at once and each is evaluated as it arrives, so in\n * `const { data } = await …` followed by `data.map(…)` the second line read\n * `data` before the first had assigned it.\n *\n * The REPL is paused as each line reaches it, and it resumes its input when it\n * displays its prompt again: once the line's value has settled, its error has\n * been printed, or it needs the next line to complete it. That resumption is\n * when the next line goes in. Lines are written one per chunk, because a\n * chunk holding several is split and every line of it handed over at once.\n */\nasync function feedLineByLine(\n source: NodeJS.ReadableStream,\n server: repl.REPLServer,\n feed: PassThrough,\n exited: Promise<void>\n): Promise<void> {\n let evaluated: (() => void) | undefined;\n const ready = () => {\n const resolve = evaluated;\n evaluated = undefined;\n resolve?.();\n };\n // Before the REPL's own handler, so a line it evaluates at once resumes\n // after this pause rather than before it.\n server.prependListener(\"line\", () => {\n if (!server.editorMode) server.pause();\n });\n // `.editor` collects lines with no prompt until Ctrl-D: they go straight in.\n server.on(\"line\", () => {\n if (!server.editorMode) return;\n server.resume();\n ready();\n });\n server.on(\"resume\", ready);\n\n const closed = exited.then(() => \"closed\" as const);\n const lines = readline.createInterface({ input: source, crlfDelay: Infinity });\n for await (const line of lines) {\n const done = new Promise<\"done\">((resolve) => { evaluated = () => resolve(\"done\"); });\n feed.write(`${line}\\n`);\n // `.exit`: the rest of the input is not for this REPL.\n if (await Promise.race([done, closed]) === \"closed\") break;\n }\n feed.end();\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAoCA,IAAa,gBAAgB;CACzB,gBAAgB;CAChB,UAAU;CACV,MAAM;CACN,aAAa;AACjB;;AAaA,IAAM,gBAA0C,OAAO,eAAe,YAAY,KAAA,CAAS,CAAC,CAAC;;;;;;;;;AAU7F,eAAsB,kBAAkB,MAAc,OAAuC;CACzF,IAAI;CACJ,IAAI;EACA,MAAM,IAAI,cAAc,UAAU,UAAU,WAAW,KAAK,KAAK;CACrE,SAAS,OAAO;EACZ,IAAI,EAAE,iBAAiB,cAAc,MAAM;EAC3C,MAAM,IAAI,cAAc,UAAU,UAAU,IAAI;CACpD;CACA,OAAO,IAAI,MAAM,QAAQ,MAAM,MAAM;AACzC;;AAGA,SAAgB,YAAY,OAAwB;CAChD,OAAO,KAAK,UAAU,QAAQ,MAAM,SAAkB,OAAO,SAAS,WAAW,KAAK,SAAS,IAAI,MAAM,CAAC,KAAK;AACnH;;AAGA,SAAS,iBAAiB,aAA6B;CACnD,IAAI;EACA,MAAM,MAAM,IAAI,IAAI,WAAW;EAC/B,OAAO,GAAG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OAAO,GAAG,cAAc;EACpB,IAAI,CAAC,OAAO,YAAY;EACxB,OAAO,OAAO;EACd,MAAM;CACV,CAAC;CACD,OAAO,GAAG,UAAU,KAAK;CAEzB,MAAM,SAAS,OAAO,WAAW,QAAiB;CAClD,MAAM,QAAQ,SAAS,gBAAgB;EAAE,OAAO;EAAQ,WAAW;CAAS,CAAC;CAC7E,WAAW,MAAM,QAAQ,OAAO;EAC5B,MAAM,OAAO,IAAI,SAAiB,YAAY;GAAE,kBAAkB,QAAQ,MAAM;EAAG,CAAC;EACpF,KAAK,MAAM,GAAG,KAAK,GAAG;EAEtB,IAAI,MAAM,QAAQ,KAAK,CAAC,MAAM,MAAM,CAAC,MAAM,UAAU;CACzD;CACA,KAAK,IAAI;AACb"}
package/dist/cli.js CHANGED
@@ -1189,7 +1189,7 @@ async function runPluginCommand(args) {
1189
1189
  else if (domain === "schema") await schemaCommand(subcommand, args);
1190
1190
  else if (domain === "doctor") await doctorPluginCommand(args);
1191
1191
  else if (domain === "console") {
1192
- const { consoleCommand } = await import("./cli-console-E5TM3GaL.js");
1192
+ const { consoleCommand } = await import("./cli-console-oVdz6rG3.js");
1193
1193
  process.exitCode = await consoleCommand(args);
1194
1194
  } else {
1195
1195
  outError(chalk.red(`Unknown domain command: ${domain}`));
package/dist/index.es.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { createRequire as __createRequire } from "module";
2
2
  __createRequire(import.meta.url);
3
3
  import { a as createPostgresDatabaseConnection, c as guardPoolAgainstDirtyRelease, d as poolMaxCeiling, i as createDirectDatabaseConnection, o as createReadReplicaConnection, s as defaultPoolTimeouts, t as cappedPoolMax, u as pinSearchPath } from "./connection-C1zXTPJq.js";
4
- import { $ as PostgresBackendDriver, B as passwordResetTokens, C as PostgresChannelBus, D as frameByteLength, E as MemoryChannelBus, F as magicLinkTokensRelations, G as refreshTokensRelations, H as recoveryCodes, I as mfaChallenges, J as users, K as userIdentities, L as mfaChallengesRelations, M as appConfig, N as createAuthSchema, O as isChannelBusInstance, P as magicLinkTokens, Q as CONNECTION_OWNER, R as mfaFactors, S as PG_NOTIFY_MAX_PAYLOAD_BYTES, T as parseChannelBusPayload, U as recoveryCodesRelations, V as passwordResetTokensRelations, W as refreshTokens, X as usersSchema, Y as usersRelations, Z as AuthenticatedPostgresBackendDriver, _ as refetchConcurrencyFor, a as openPostgresDriver, b as CHANNEL_BUS_NOTIFY_CHANNEL, c as PostgresTableRegistry, d as PostgresRealtimeProvider, dt as PostgresConditionBuilder, et as RoleSwitchUnavailableError, f as RealtimeService, ft as configureUnknownFilterFields, g as parseRealtimeTuning, gt as listedColumnKeys, h as parseMaxSubscriptionsPerSocket, ht as joinColumn, i as isScaffoldedLocalDatabase, it as sqlRoleRanAs, l as DEFAULT_MAX_SUBSCRIPTIONS_PER_SOCKET, m as parseMaxSocketsPerUser, mt as getUnknownFilterFieldsMode, n as createPostgresBootstrapper, nt as effectiveSqlRole, o as postgresDriverConfigFromEnv, p as packEntityChanges, pt as escapeLikePattern, q as userIdentitiesRelations, r as describeSchemaDriftCause, rt as isRoleSwitchingOptedOut, s as resolveSourceUrls, t as openRebase, tt as branchParentDatabase, u as DEFAULT_RECOUNT_MIN_ROWS, ut as DrizzleConditionBuilder, v as createChannelBus, w as parseChannelBusFrame, x as DEFAULT_BATCH_WINDOW_MS, y as resolveChannelBusSetting, z as mfaFactorsRelations } from "./open-rebase-DykxNl1j.js";
4
+ import { $ as userIdentities, A as MemoryChannelBus, B as createAuthSchema, C as PG_BUS_MAX_FRAME_BYTES, Ct as listedColumnKeys, D as parseChannelBusPayload, E as parseChannelBusFrame, G as mfaFactors, H as magicLinkTokensRelations, J as passwordResetTokensRelations, K as mfaFactorsRelations, M as isChannelBusInstance, O as parsePart, Q as refreshTokensRelations, S as FrameAssembler, St as joinColumn, T as PostgresChannelBus, U as mfaChallenges, V as magicLinkTokens, W as mfaChallengesRelations, X as recoveryCodesRelations, Y as recoveryCodes, Z as refreshTokens, _ as refetchConcurrencyFor, _t as DrizzleConditionBuilder, a as openPostgresDriver, at as CONNECTION_OWNER, b as CHANNEL_BUS_NOTIFY_CHANNEL, bt as escapeLikePattern, c as PostgresTableRegistry, ct as branchParentDatabase, d as PostgresRealtimeProvider, dt as sqlRoleRanAs, et as userIdentitiesRelations, f as RealtimeService, g as parseRealtimeTuning, h as parseMaxSubscriptionsPerSocket, i as isScaffoldedLocalDatabase, it as AuthenticatedPostgresBackendDriver, j as frameByteLength, k as splitIntoParts, l as DEFAULT_MAX_SUBSCRIPTIONS_PER_SOCKET, lt as effectiveSqlRole, m as parseMaxSocketsPerUser, n as createPostgresBootstrapper, nt as usersRelations, o as postgresDriverConfigFromEnv, ot as PostgresBackendDriver, p as packEntityChanges, q as passwordResetTokens, r as describeSchemaDriftCause, rt as usersSchema, s as resolveSourceUrls, st as RoleSwitchUnavailableError, t as openRebase, tt as users, u as DEFAULT_RECOUNT_MIN_ROWS, ut as isRoleSwitchingOptedOut, v as createChannelBus, vt as PostgresConditionBuilder, w as PG_NOTIFY_MAX_PAYLOAD_BYTES, x as DEFAULT_BATCH_WINDOW_MS, xt as getUnknownFilterFieldsMode, y as resolveChannelBusSetting, yt as configureUnknownFilterFields, z as appConfig } from "./open-rebase-BQrU-FAV.js";
5
5
  import { n as assertNoCollectionsFlag } from "./cli-schema-dir-CdEqBcph.js";
6
6
  import { a as reopenedDatabasesNotice, i as reopenClosedDatabases, r as BranchingUnsupportedError, t as BranchService } from "./BranchService-BLcVK_Rd.js";
7
7
  import { n as resolveRlsSettings, r as rlsConfigFromEnv, t as cliRlsSettings } from "./rls-settings-CmGK2U0a.js";
@@ -14,7 +14,7 @@ import { r as planTableSchemaEnsure } from "./ensure-tables-DjuNRClr.js";
14
14
  import { a as mergeDatabaseBranch, i as diffDatabaseBranch, n as DEFAULT_BRANCH_DIFF_SAMPLE_LIMIT, t as DEFAULT_BRANCH_DIFF_MAX_ROWS } from "./branch-diff-CxE4VlxT.js";
15
15
  import { t as DatabasePoolManager } from "./databasePoolManager-DIjzlTK4.js";
16
16
  import { t as main } from "./generate-drizzle-schema-B-Mkf8UI.js";
17
- import { a as createPostgresWebSocket, i as TOO_MANY_SOCKETS_CLOSE_CODE, n as PUBLIC_TYPES, o as isSocketRealtimeService, r as SESSION_ENDED_CLOSE_CODE, s as socketRealtimeMissing, t as ADMIN_PLANE_TYPES } from "./websocket-CvmbzBeS.js";
17
+ import { a as createPostgresWebSocket, i as TOO_MANY_SOCKETS_CLOSE_CODE, n as PUBLIC_TYPES, o as isSocketRealtimeService, r as SESSION_ENDED_CLOSE_CODE, s as socketRealtimeMissing, t as ADMIN_PLANE_TYPES } from "./websocket-C9Ev5FQs.js";
18
18
  import { A as buildBackupFilename, B as diagnoseRowSecurityDumpFailure, C as restoreDumpReplacing, D as resolvePgBinary, E as pgToolVariable, F as buildPgRestoreScriptArgs, G as parseBackupTimestamp, H as isBackupOfDatabase, I as buildPsqlScriptArgs, J as parsePgToolMajor, K as parseDbNameFromUrl, L as buildRowSecurityPgOptions, M as buildPgDumpallGlobalsArgs, N as buildPgRestoreArgs, O as selectBackupsToPrune, P as buildPgRestoreListArgs, Q as withDatabaseName, R as checkToolServerCompatibility, S as restoreDump, T as validateDump, U as joinStorageKey, V as globalsFileForDump, W as parseBackupDestination, X as serverVersionNumToMajor, Y as resolveConnectionString, Z as splitGlobalsStatements, _ as listBackups, a as BackupToolError, b as readDumpObjects, d as detectToolMajor, f as discardPartialDump, g as getServerVersionMajor, h as findRestoreConflicts, i as parseRestoreLine, j as buildPgDumpArgs, k as CLEAN_LOCK_TIMEOUT, l as createDump, m as findCleanExtras, n as parseBackupLine, o as CleanRestoreFailed, p as ensureDatabaseExists, q as parseDumpObjects, r as parseBackupsListLine, s as applyGlobals, u as describeUnreadableDump, v as preflight, w as uploadBackup, x as resetSharedSession, y as pruneBackups, z as cleanRestorePrelude } from "./backup-cli-CVLOCTo_.js";
19
19
  import { n as parseRequestRoleLine, t as parseProvisionLine } from "./request-role-cli-Y5Uqalop.js";
20
20
  import { a as isGeneratedPolicyName } from "./policy-drift-B2Czzs2Z.js";
@@ -661,6 +661,6 @@ function renderSchemaOutputs(tables, options = {}) {
661
661
  });
662
662
  }
663
663
  //#endregion
664
- export { ADMIN_PLANE_TYPES, AuthenticatedPostgresBackendDriver, BackupToolError, BranchService, BranchingUnsupportedError, CHANNEL_BUS_NOTIFY_CHANNEL, CLEAN_LOCK_TIMEOUT, CONNECTION_OWNER, CleanRestoreFailed, DEFAULT_BATCH_WINDOW_MS, DEFAULT_BRANCH_DIFF_MAX_ROWS, DEFAULT_BRANCH_DIFF_SAMPLE_LIMIT, DEFAULT_MAX_SUBSCRIPTIONS_PER_SOCKET, DEFAULT_RECOUNT_MIN_ROWS, DatabasePoolManager, DrizzleConditionBuilder, MemoryChannelBus, PG_NOTIFY_MAX_PAYLOAD_BYTES, PLANNER_ENV_VARIABLES, PUBLIC_TYPES, PostgresBackendDriver, PostgresChannelBus, PostgresConditionBuilder, PostgresRealtimeProvider, PostgresTableRegistry, REBASE_USER_ROLE, RealtimeService, RoleSwitchUnavailableError, SESSION_ENDED_CLOSE_CODE, TOO_MANY_SOCKETS_CLOSE_CODE, appConfig, applyGlobals, assertDbCommandLine, backupCronConfigFromEnv, branchParentDatabase, buildBackupFilename, buildPgDumpArgs, buildPgDumpallGlobalsArgs, buildPgRestoreArgs, buildPgRestoreListArgs, buildPgRestoreScriptArgs, buildPsqlScriptArgs, buildRowSecurityPgOptions, cappedPoolMax, checkToolServerCompatibility, cleanRestorePrelude, cliRlsSettings, compareMigrationVersions, configureUnknownFilterFields, createAuthSchema, createBackupCron, createChannelBus, createDirectDatabaseConnection, createDump, createPostgresAdapter, createPostgresBootstrapper, createPostgresDatabaseConnection, createPostgresWebSocket, createReadReplicaConnection, defaultPoolTimeouts, describeSchemaDriftCause, describeUnreadableDump, detectConnectionPosture, detectToolMajor, diagnoseRowSecurityDumpFailure, diffDatabaseBranch, discardPartialDump, effectiveSqlRole, ensureAppRole, ensureAppRoleGrants, ensureDatabaseExists, escapeLikePattern, findCleanExtras, findOtherRoleMembers, findRestoreConflicts, findUnmigratedSchema, frameByteLength, generateSchema, getServerVersionMajor, getUnknownFilterFieldsMode, globalsFileForDump, guardPoolAgainstDirtyRelease, isBackupOfDatabase, isChannelBusInstance, isGeneratedPolicyName, isRoleSwitchingOptedOut, isScaffoldedLocalDatabase, isSocketRealtimeService, joinColumn, joinStorageKey, listBackups, listedColumnKeys, magicLinkTokens, magicLinkTokensRelations, main, mergeDatabaseBranch, mfaChallenges, mfaChallengesRelations, mfaFactors, mfaFactorsRelations, migrationVersionOf, openPostgresDriver, openRebase, packEntityChanges, parseBackupDestination, parseBackupTimestamp, parseChannelBusFrame, parseChannelBusPayload, parseDbNameFromUrl, parseDumpObjects, parseMaxSocketsPerUser, parseMaxSubscriptionsPerSocket, parsePgToolMajor, parseRealtimeTuning, passwordResetTokens, passwordResetTokensRelations, pinSearchPath, planPolicyDefinitions, poolMaxCeiling, postgresDriverConfigFromEnv, preflight, pruneBackups, readDumpObjects, readRecordedRequestRoles, recordRequestRoles, recoveryCodes, recoveryCodesRelations, refetchConcurrencyFor, refreshTokens, refreshTokensRelations, renderSchemaOutputs, reopenClosedDatabases, reopenedDatabasesNotice, resetSharedSession, resolveChannelBusSetting, resolveConnectionString, resolvePgBinary, resolveRlsSettings, resolveSourceUrls, restoreDump, restoreDumpReplacing, rlsConfigFromEnv, selectBackupsToPrune, serverVersionNumToMajor, socketRealtimeMissing, splitGlobalsStatements, sqlRoleRanAs, toStableJson, uploadBackup, userIdentities, userIdentitiesRelations, users, usersRelations, usersSchema, validateDump, withDatabaseName, withPinnedPlannerWorld };
664
+ export { ADMIN_PLANE_TYPES, AuthenticatedPostgresBackendDriver, BackupToolError, BranchService, BranchingUnsupportedError, CHANNEL_BUS_NOTIFY_CHANNEL, CLEAN_LOCK_TIMEOUT, CONNECTION_OWNER, CleanRestoreFailed, DEFAULT_BATCH_WINDOW_MS, DEFAULT_BRANCH_DIFF_MAX_ROWS, DEFAULT_BRANCH_DIFF_SAMPLE_LIMIT, DEFAULT_MAX_SUBSCRIPTIONS_PER_SOCKET, DEFAULT_RECOUNT_MIN_ROWS, DatabasePoolManager, DrizzleConditionBuilder, FrameAssembler, MemoryChannelBus, PG_BUS_MAX_FRAME_BYTES, PG_NOTIFY_MAX_PAYLOAD_BYTES, PLANNER_ENV_VARIABLES, PUBLIC_TYPES, PostgresBackendDriver, PostgresChannelBus, PostgresConditionBuilder, PostgresRealtimeProvider, PostgresTableRegistry, REBASE_USER_ROLE, RealtimeService, RoleSwitchUnavailableError, SESSION_ENDED_CLOSE_CODE, TOO_MANY_SOCKETS_CLOSE_CODE, appConfig, applyGlobals, assertDbCommandLine, backupCronConfigFromEnv, branchParentDatabase, buildBackupFilename, buildPgDumpArgs, buildPgDumpallGlobalsArgs, buildPgRestoreArgs, buildPgRestoreListArgs, buildPgRestoreScriptArgs, buildPsqlScriptArgs, buildRowSecurityPgOptions, cappedPoolMax, checkToolServerCompatibility, cleanRestorePrelude, cliRlsSettings, compareMigrationVersions, configureUnknownFilterFields, createAuthSchema, createBackupCron, createChannelBus, createDirectDatabaseConnection, createDump, createPostgresAdapter, createPostgresBootstrapper, createPostgresDatabaseConnection, createPostgresWebSocket, createReadReplicaConnection, defaultPoolTimeouts, describeSchemaDriftCause, describeUnreadableDump, detectConnectionPosture, detectToolMajor, diagnoseRowSecurityDumpFailure, diffDatabaseBranch, discardPartialDump, effectiveSqlRole, ensureAppRole, ensureAppRoleGrants, ensureDatabaseExists, escapeLikePattern, findCleanExtras, findOtherRoleMembers, findRestoreConflicts, findUnmigratedSchema, frameByteLength, generateSchema, getServerVersionMajor, getUnknownFilterFieldsMode, globalsFileForDump, guardPoolAgainstDirtyRelease, isBackupOfDatabase, isChannelBusInstance, isGeneratedPolicyName, isRoleSwitchingOptedOut, isScaffoldedLocalDatabase, isSocketRealtimeService, joinColumn, joinStorageKey, listBackups, listedColumnKeys, magicLinkTokens, magicLinkTokensRelations, main, mergeDatabaseBranch, mfaChallenges, mfaChallengesRelations, mfaFactors, mfaFactorsRelations, migrationVersionOf, openPostgresDriver, openRebase, packEntityChanges, parseBackupDestination, parseBackupTimestamp, parseChannelBusFrame, parseChannelBusPayload, parseDbNameFromUrl, parseDumpObjects, parseMaxSocketsPerUser, parseMaxSubscriptionsPerSocket, parsePart, parsePgToolMajor, parseRealtimeTuning, passwordResetTokens, passwordResetTokensRelations, pinSearchPath, planPolicyDefinitions, poolMaxCeiling, postgresDriverConfigFromEnv, preflight, pruneBackups, readDumpObjects, readRecordedRequestRoles, recordRequestRoles, recoveryCodes, recoveryCodesRelations, refetchConcurrencyFor, refreshTokens, refreshTokensRelations, renderSchemaOutputs, reopenClosedDatabases, reopenedDatabasesNotice, resetSharedSession, resolveChannelBusSetting, resolveConnectionString, resolvePgBinary, resolveRlsSettings, resolveSourceUrls, restoreDump, restoreDumpReplacing, rlsConfigFromEnv, selectBackupsToPrune, serverVersionNumToMajor, socketRealtimeMissing, splitGlobalsStatements, splitIntoParts, sqlRoleRanAs, toStableJson, uploadBackup, userIdentities, userIdentitiesRelations, users, usersRelations, usersSchema, validateDump, withDatabaseName, withPinnedPlannerWorld };
665
665
 
666
666
  //# sourceMappingURL=index.es.js.map
@@ -30,11 +30,11 @@ import { ALL_WHERE_FILTER_OPS, ANONYMOUS_USER_ID, DEFAULT_COMMIT_PATHS, DEFAULT_
30
30
  import { COMPOSITE_ID_SEPARATOR, COMPOSITE_ID_SEPARATOR as COMPOSITE_ID_SEPARATOR$1, OrderBySpecError, UNSERVED_TABLE, UnknownFilterOperatorError, anonymousWriteRefusedBy, apiHiddenKeys, applyCreateDefaults, applyStamps, arrayElementType, buildCompositeId, buildCompositeId as buildCompositeId$1, buildSdkData, callbackRefusal, canReadColumn, canReadRelation, classifyTable, columnMaps, createAccessorSlugResolver, createStampKeys, declaredSchemaOf, deserializeFilter, detectJunctionTables, encodeCursor, fieldOperationBounds, firstSqlRow, getColumnName, grantExecuteToRequestRolesSql, hasColumnAccessRules, hasJoinAccessRules, includableRelations, isAddressableId, isIlikeSearchable, isJsNumberType, isSoftDeleteRestore, keyAddressInfoOf, keyColumns, normalizeDriverOrderBy, normalizeEmail, normalizeInclude, parseIdValues, parseIdValues as parseIdValues$1, parseOrderBySpecStrict, queryableColumnKeys, relationOf, relationsOfKind, requireCallbackClient, resolveTenantWrite, restCodecOf, restrictedKeys, revokeInternalTableSql, softDeleteColumn, sqlRows, stampModifier, tenantOf, toCallbackError, toFilterTuples, unknownAggregateField, unknownFilterField, unknownIncludeRelation, unknownOrderByField, unknownProjectionField, unknownRelationTargetField, unknownVectorProperty, updateStampKeys, valueCodecOf, valueCodecOfType, viaJoinTableNames, warnOnTableDdl } from "@rebasepro/common";
31
31
  import { camelCase, generateForeignKeyName, isPrototypePollutingKey, legacyForeignKeyName, splitSearchTerms, toSnakeCase, toWireKey, unref } from "@rebasepro/utils";
32
32
  import { AsyncLocalStorage } from "node:async_hooks";
33
- import { createHash } from "node:crypto";
33
+ import { createHash, randomUUID } from "node:crypto";
34
34
  import { prepareValue } from "pg/lib/utils.js";
35
35
  import { WebSocket } from "ws";
36
36
  import { EventEmitter } from "events";
37
- import { createHash as createHash$1, randomBytes, randomUUID } from "crypto";
37
+ import { createHash as createHash$1, randomBytes, randomUUID as randomUUID$1 } from "crypto";
38
38
  //#region src/services/field-viewer.ts
39
39
  /**
40
40
  * Who the current read is *for*, available to the row walk without threading it
@@ -15990,6 +15990,75 @@ async function retireTriggerCaptureIfUnused(run, ownInstanceName) {
15990
15990
  };
15991
15991
  return { removed: await removeTriggerCdc(run) };
15992
15992
  }
15993
+ var serverCauses = /* @__PURE__ */ new WeakMap();
15994
+ /**
15995
+ * Record that this server is ending `ws`, and why, before it closes or
15996
+ * terminates it. The first cause given is the one kept.
15997
+ */
15998
+ function noteServerClose(ws, cause) {
15999
+ if (!serverCauses.has(ws)) serverCauses.set(ws, cause);
16000
+ }
16001
+ /** Who ended `ws`, given the code its `close` event carried. */
16002
+ function closerOf(ws, code) {
16003
+ const cause = serverCauses.get(ws);
16004
+ if (cause) return cause;
16005
+ if (code === 4003) return "client_watchdog";
16006
+ if (code === 1006) return "network";
16007
+ return "client";
16008
+ }
16009
+ /**
16010
+ * A close code as a metric label: the codes the protocol defines and the ones
16011
+ * Rebase uses as themselves, anything else as `other` — a client may close
16012
+ * with any of two thousand application codes, and a label per one is
16013
+ * unbounded.
16014
+ */
16015
+ function closeCodeLabel(code) {
16016
+ if (code >= 1e3 && code <= 1015 || code >= 4e3 && code <= 4003) return String(code);
16017
+ return "other";
16018
+ }
16019
+ var SocketStats = class {
16020
+ opened = 0;
16021
+ closedBy = /* @__PURE__ */ new Map();
16022
+ closeCodes = /* @__PURE__ */ new Map();
16023
+ framesIn = 0;
16024
+ bytesIn = 0;
16025
+ framesOut = 0;
16026
+ bytesOut = 0;
16027
+ refused = /* @__PURE__ */ new Map();
16028
+ noteOpened() {
16029
+ this.opened++;
16030
+ }
16031
+ noteClosed(closer, code) {
16032
+ this.closedBy.set(closer, (this.closedBy.get(closer) ?? 0) + 1);
16033
+ const label = closeCodeLabel(code);
16034
+ this.closeCodes.set(label, (this.closeCodes.get(label) ?? 0) + 1);
16035
+ }
16036
+ noteFrameIn(bytes) {
16037
+ this.framesIn++;
16038
+ this.bytesIn += bytes;
16039
+ }
16040
+ noteFrameOut(bytes) {
16041
+ this.framesOut++;
16042
+ this.bytesOut += bytes;
16043
+ }
16044
+ noteRefused(code) {
16045
+ this.refused.set(code, (this.refused.get(code) ?? 0) + 1);
16046
+ }
16047
+ totals() {
16048
+ return {
16049
+ opened: this.opened,
16050
+ closedBy: Object.fromEntries(this.closedBy),
16051
+ closeCodes: Object.fromEntries(this.closeCodes),
16052
+ framesIn: this.framesIn,
16053
+ bytesIn: this.bytesIn,
16054
+ framesOut: this.framesOut,
16055
+ bytesOut: this.bytesOut,
16056
+ refused: Object.fromEntries(this.refused)
16057
+ };
16058
+ }
16059
+ };
16060
+ /** This process's totals. */
16061
+ var socketStats = new SocketStats();
15993
16062
  //#endregion
15994
16063
  //#region src/services/socket-liveness.ts
15995
16064
  /**
@@ -16102,6 +16171,7 @@ function enforceProcessSendBudget(budget) {
16102
16171
  const terminated = [];
16103
16172
  for (const { ws, bytes } of backlogged) {
16104
16173
  if (total <= limit) break;
16174
+ noteServerClose(ws, "backlog");
16105
16175
  ws.terminate();
16106
16176
  total -= bytes;
16107
16177
  terminated.push(ws);
@@ -16124,6 +16194,7 @@ function reapSilentSockets(wss, intervalMs = SOCKET_PING_INTERVAL_MS) {
16124
16194
  for (const ws of clients) {
16125
16195
  if (awaitingPong.has(ws)) {
16126
16196
  logger.debug(`[WebSocket Server] Terminated a socket that did not answer a ping within ${intervalMs}ms.`);
16197
+ noteServerClose(ws, "no_pong");
16127
16198
  ws.terminate();
16128
16199
  continue;
16129
16200
  }
@@ -16147,6 +16218,7 @@ function terminateIfBacklogged(ws, clientId) {
16147
16218
  const backlog = ws.bufferedAmount;
16148
16219
  if (backlog > 16777216) {
16149
16220
  logger.warn(`[WebSocket Server] Terminated ${clientId}: ${backlog} bytes sent to it are still unread, past the ${MAX_SOCKET_BUFFERED_BYTES}-byte ceiling for one socket.`);
16221
+ noteServerClose(ws, "backlog");
16150
16222
  ws.terminate();
16151
16223
  return true;
16152
16224
  }
@@ -16693,8 +16765,13 @@ function frameByteLength(frame) {
16693
16765
  * is the same trick the entity path uses (notify an address, refetch the
16694
16766
  * row), applied to a different table, and for the same reason: any database
16695
16767
  * login can `LISTEN`. On an ephemeral channel there is nothing to point at,
16696
- * so the frame carries the message, and an oversized one is refused loudly
16697
- * instead of reaching some instances and not others.
16768
+ * so a frame over the ceiling is cut into parts that leave together, in one
16769
+ * statement, and each instance puts them back together (see
16770
+ * {@link FrameAssembler}). It used to be refused instead: delivered on the
16771
+ * sender's instance and nowhere else, with an error frame to a sender that
16772
+ * had no reason to read one — a game screen's ~10 KB state reached the
16773
+ * phones on its own pod and silently never the others. Only a frame over
16774
+ * {@link PG_BUS_MAX_FRAME_BYTES} is refused now.
16698
16775
  *
16699
16776
  * - **A notify is a query on the primary database.** Not a slow one, but it
16700
16777
  * competes with the application's real queries, and that — not throughput —
@@ -16716,6 +16793,29 @@ var CHANNEL_BUS_NOTIFY_CHANNEL = "rebase_channel_bus";
16716
16793
  */
16717
16794
  var PG_NOTIFY_MAX_PAYLOAD_BYTES = 7500;
16718
16795
  /**
16796
+ * The largest frame the Postgres bus carries, cut into parts, in bytes of
16797
+ * encoded JSON. A frame larger than this is refused to its sender, as every
16798
+ * oversized frame used to be. One MiB is ~190 notifications in one statement:
16799
+ * far past any state a realtime app should broadcast, short of making the bus
16800
+ * a file transfer.
16801
+ */
16802
+ var PG_BUS_MAX_FRAME_BYTES = 1024 * 1024;
16803
+ /**
16804
+ * Base64 characters of a frame per part. The envelope around them
16805
+ * (`{"part":{"id":"…","i":…,"n":…,"data":"…"}}`) stays under 100 bytes, so a
16806
+ * part is always under {@link PG_NOTIFY_MAX_PAYLOAD_BYTES}.
16807
+ */
16808
+ var PART_DATA_CHARS = 7200;
16809
+ /** A frame whose parts have not all arrived after this long is given up on, in ms. */
16810
+ var PART_ASSEMBLY_TIMEOUT_MS = 3e4;
16811
+ /**
16812
+ * How many bytes of unfinished parts an instance holds at most. Past it the
16813
+ * oldest unfinished frame is dropped: parts from one statement arrive
16814
+ * together, so a frame that waits at all has lost a part, and memory must not
16815
+ * be what an unlucky reconnect costs.
16816
+ */
16817
+ var MAX_PENDING_PART_BYTES = 16 * 1024 * 1024;
16818
+ /**
16719
16819
  * How long a batching window stays open.
16720
16820
  *
16721
16821
  * Ten milliseconds is below the threshold where a human notices a cursor lag,
@@ -16731,9 +16831,16 @@ var PostgresChannelBus = class {
16731
16831
  db;
16732
16832
  connectionString;
16733
16833
  kind = "postgres";
16734
- maxFrameBytes = PG_NOTIFY_MAX_PAYLOAD_BYTES;
16834
+ /**
16835
+ * What the bus carries, not what one notification does: a frame over
16836
+ * {@link PG_NOTIFY_MAX_PAYLOAD_BYTES} travels in parts.
16837
+ */
16838
+ maxFrameBytes = PG_BUS_MAX_FRAME_BYTES;
16735
16839
  publishesOnDemand = true;
16736
16840
  listener;
16841
+ assembler = new FrameAssembler();
16842
+ /** Frames this instance cut into parts, so its own listener skips putting them back together. */
16843
+ ownPartIds = /* @__PURE__ */ new Set();
16737
16844
  batchWindowMs;
16738
16845
  /**
16739
16846
  * Frames waiting for the current window to close.
@@ -16757,7 +16864,18 @@ var PostgresChannelBus = class {
16757
16864
  connectionString: this.connectionString,
16758
16865
  channel: CHANNEL_BUS_NOTIFY_CHANNEL,
16759
16866
  logLabel: "[ChannelBus]",
16760
- onPayload: async (payload) => {
16867
+ onPayload: async (raw) => {
16868
+ const part = parsePart(raw);
16869
+ let payload = raw;
16870
+ if (part) {
16871
+ if (this.ownPartIds.has(part.id)) {
16872
+ if (part.i === part.n - 1) this.ownPartIds.delete(part.id);
16873
+ return;
16874
+ }
16875
+ const whole = this.assembler.add(part);
16876
+ if (whole === void 0) return;
16877
+ payload = whole;
16878
+ }
16761
16879
  const frames = parseChannelBusPayload(payload);
16762
16880
  if (!frames.length) {
16763
16881
  logger.warn("⚠️ [ChannelBus] Dropping unparseable payload.");
@@ -16793,7 +16911,12 @@ var PostgresChannelBus = class {
16793
16911
  return;
16794
16912
  }
16795
16913
  const bytes = frameByteLength(frame) + BATCH_SEPARATOR_BYTES;
16796
- if (this.pending.length && this.pendingBytes + bytes > this.maxFrameBytes) this.flush();
16914
+ if (bytes > 7500) {
16915
+ this.flush();
16916
+ await this.send([frame]);
16917
+ return;
16918
+ }
16919
+ if (this.pending.length && this.pendingBytes + bytes > 7500) this.flush();
16797
16920
  return new Promise((resolve, reject) => {
16798
16921
  this.pending.push({
16799
16922
  frame,
@@ -16817,6 +16940,8 @@ var PostgresChannelBus = class {
16817
16940
  this.flush();
16818
16941
  await this.listener?.stop();
16819
16942
  this.listener = void 0;
16943
+ this.assembler.clear();
16944
+ this.ownPartIds.clear();
16820
16945
  }
16821
16946
  openWindow() {
16822
16947
  this.windowTimer = setTimeout(() => {
@@ -16853,7 +16978,122 @@ var PostgresChannelBus = class {
16853
16978
  async send(frames) {
16854
16979
  if (!frames.length) return;
16855
16980
  const payload = frames.length === 1 ? JSON.stringify(frames[0]) : JSON.stringify({ batch: frames });
16856
- await this.db.execute(sql`SELECT pg_notify(${CHANNEL_BUS_NOTIFY_CHANNEL}, ${payload})`);
16981
+ if (Buffer.byteLength(payload, "utf8") <= 7500) {
16982
+ await this.db.execute(sql`SELECT pg_notify(${CHANNEL_BUS_NOTIFY_CHANNEL}, ${payload})`);
16983
+ return;
16984
+ }
16985
+ const parts = splitIntoParts(payload, randomUUID());
16986
+ this.ownPartIds.add(parts[0].id);
16987
+ if (this.ownPartIds.size > 1e3) this.ownPartIds.delete(this.ownPartIds.values().next().value);
16988
+ const notifies = parts.map((part) => sql`pg_notify(${CHANNEL_BUS_NOTIFY_CHANNEL}, ${JSON.stringify({ part })})`);
16989
+ await this.db.execute(sql`SELECT ${sql.join(notifies, sql`, `)}`);
16990
+ }
16991
+ };
16992
+ /** Cut a bus payload into parts, each of which fits one notification. */
16993
+ function splitIntoParts(payload, id) {
16994
+ const data = Buffer.from(payload, "utf8").toString("base64");
16995
+ const n = Math.ceil(data.length / PART_DATA_CHARS);
16996
+ return Array.from({ length: n }, (_, i) => ({
16997
+ id,
16998
+ i,
16999
+ n,
17000
+ data: data.slice(i * PART_DATA_CHARS, (i + 1) * PART_DATA_CHARS)
17001
+ }));
17002
+ }
17003
+ /** Most parts one frame can have, so a forged `n` cannot reserve unbounded memory. */
17004
+ var MAX_PARTS = Math.ceil(PG_BUS_MAX_FRAME_BYTES * 4 / 3 / PART_DATA_CHARS) + 1;
17005
+ /** The part a notification carries, or undefined when it carries a whole frame. */
17006
+ function parsePart(payload) {
17007
+ if (!payload.startsWith("{\"part\"")) return void 0;
17008
+ let parsed;
17009
+ try {
17010
+ parsed = JSON.parse(payload);
17011
+ } catch {
17012
+ return;
17013
+ }
17014
+ const part = parsed && typeof parsed === "object" ? parsed.part : void 0;
17015
+ if (!part || typeof part !== "object") return void 0;
17016
+ const { id, i, n, data } = part;
17017
+ if (typeof id !== "string" || typeof data !== "string") return void 0;
17018
+ if (!Number.isInteger(i) || !Number.isInteger(n)) return void 0;
17019
+ const index = i;
17020
+ const count = n;
17021
+ if (count < 1 || count > MAX_PARTS || index < 0 || index >= count) return void 0;
17022
+ return {
17023
+ id,
17024
+ i: index,
17025
+ n: count,
17026
+ data
17027
+ };
17028
+ }
17029
+ /**
17030
+ * Puts frames that travelled in parts back together.
17031
+ *
17032
+ * The parts of one frame are sent in one statement, so they arrive in a row;
17033
+ * a frame still waiting after {@link PART_ASSEMBLY_TIMEOUT_MS} lost one (the
17034
+ * listener reconnected between them) and is dropped, as a lost notification
17035
+ * always was.
17036
+ */
17037
+ var FrameAssembler = class {
17038
+ now;
17039
+ pending = /* @__PURE__ */ new Map();
17040
+ pendingBytes = 0;
17041
+ constructor(now = Date.now) {
17042
+ this.now = now;
17043
+ }
17044
+ /** Add a part; the whole payload once its last part is in, otherwise undefined. */
17045
+ add(part) {
17046
+ this.expire();
17047
+ let entry = this.pending.get(part.id);
17048
+ if (!entry) {
17049
+ if (part.n === 1) return Buffer.from(part.data, "base64").toString("utf8");
17050
+ entry = {
17051
+ parts: new Array(part.n),
17052
+ got: 0,
17053
+ bytes: 0,
17054
+ at: this.now()
17055
+ };
17056
+ this.pending.set(part.id, entry);
17057
+ }
17058
+ if (entry.parts.length !== part.n || entry.parts[part.i] !== void 0) return void 0;
17059
+ entry.parts[part.i] = part.data;
17060
+ entry.got++;
17061
+ entry.bytes += part.data.length;
17062
+ this.pendingBytes += part.data.length;
17063
+ if (entry.got < part.n) {
17064
+ while (this.pendingBytes > MAX_PENDING_PART_BYTES && this.pending.size > 1) this.dropOldest();
17065
+ return;
17066
+ }
17067
+ this.forget(part.id);
17068
+ return Buffer.from(entry.parts.join(""), "base64").toString("utf8");
17069
+ }
17070
+ /** How many frames are waiting for parts. */
17071
+ get size() {
17072
+ return this.pending.size;
17073
+ }
17074
+ clear() {
17075
+ this.pending.clear();
17076
+ this.pendingBytes = 0;
17077
+ }
17078
+ expire() {
17079
+ const cutoff = this.now() - PART_ASSEMBLY_TIMEOUT_MS;
17080
+ for (const [id, entry] of this.pending) {
17081
+ if (entry.at >= cutoff) break;
17082
+ logger.warn(`⚠️ [ChannelBus] Dropping a frame that arrived ${entry.got} of ${entry.parts.length} parts.`);
17083
+ this.forget(id);
17084
+ }
17085
+ }
17086
+ dropOldest() {
17087
+ const oldest = this.pending.keys().next().value;
17088
+ if (oldest === void 0) return;
17089
+ logger.warn("⚠️ [ChannelBus] Dropping an unfinished multi-part frame: too many parts waiting.");
17090
+ this.forget(oldest);
17091
+ }
17092
+ forget(id) {
17093
+ const entry = this.pending.get(id);
17094
+ if (!entry) return;
17095
+ this.pendingBytes -= entry.bytes;
17096
+ this.pending.delete(id);
16857
17097
  }
16858
17098
  };
16859
17099
  /**
@@ -17147,6 +17387,7 @@ var WEBSOCKET_CLOSE_GRACE_MS = 1e3;
17147
17387
  */
17148
17388
  function closeWebSockets(sockets, graceMs) {
17149
17389
  for (const ws of sockets) {
17390
+ noteServerClose(ws, "shutdown");
17150
17391
  if (ws.readyState === WebSocket.OPEN) ws.close(1001, "server shutting down");
17151
17392
  if (ws.readyState !== WebSocket.CLOSED) unref(setTimeout(() => ws.terminate(), graceMs));
17152
17393
  }
@@ -17219,6 +17460,8 @@ var RealtimeService = class RealtimeService extends EventEmitter {
17219
17460
  busFramesPublished = /* @__PURE__ */ new Map();
17220
17461
  /** Frames not sent because no other instance had members. See {@link counts}. */
17221
17462
  busFramesSkipped = 0;
17463
+ /** Frames and bytes pushed to each socket, for the line its close logs. */
17464
+ trafficByClient = /* @__PURE__ */ new Map();
17222
17465
  busStartedAt = 0;
17223
17466
  busGossipInterval;
17224
17467
  /**
@@ -17370,7 +17613,7 @@ var RealtimeService = class RealtimeService extends EventEmitter {
17370
17613
  recountMinRows = DEFAULT_RECOUNT_MIN_ROWS;
17371
17614
  driver;
17372
17615
  /** Unique identifier for this process instance, used to skip own notifications. */
17373
- instanceId = `inst_${randomUUID().slice(0, 8)}`;
17616
+ instanceId = `inst_${randomUUID$1().slice(0, 8)}`;
17374
17617
  /**
17375
17618
  * The name this instance's realtime connections report in
17376
17619
  * `pg_stat_activity` (`application_name`), each followed by what the
@@ -17991,6 +18234,7 @@ var RealtimeService = class RealtimeService extends EventEmitter {
17991
18234
  async removeClient(clientId) {
17992
18235
  this.clients.delete(clientId);
17993
18236
  this.clientOptIns.delete(clientId);
18237
+ this.trafficByClient.delete(clientId);
17994
18238
  for (const key of [...this.subscriptionsByClient.get(clientId) ?? []]) this.dropSubscription(key);
17995
18239
  if (this.presenceTrackers.delete(clientId)) await this.presenceStoreOp(clientId, (store) => store.removeClient(clientId), "client removal");
17996
18240
  for (const channel of [...this.channelsByClient.get(clientId) ?? []]) {
@@ -18784,6 +19028,28 @@ var RealtimeService = class RealtimeService extends EventEmitter {
18784
19028
  if (!client || client.readyState !== WebSocket.OPEN) return;
18785
19029
  if (terminateIfBacklogged(client, clientId)) return;
18786
19030
  client.send(frame);
19031
+ const bytes = Buffer.byteLength(frame, "utf8");
19032
+ socketStats.noteFrameOut(bytes);
19033
+ const traffic = this.trafficByClient.get(clientId);
19034
+ if (traffic) {
19035
+ traffic.frames++;
19036
+ traffic.bytes += bytes;
19037
+ } else this.trafficByClient.set(clientId, {
19038
+ frames: 1,
19039
+ bytes
19040
+ });
19041
+ }
19042
+ /**
19043
+ * What a socket is in and what it was pushed, for the line its close
19044
+ * logs. Read before the socket's own close handler forgets it.
19045
+ */
19046
+ describeClient(clientId) {
19047
+ const traffic = this.trafficByClient.get(clientId);
19048
+ return {
19049
+ channels: [...this.channelsByClient.get(clientId) ?? []],
19050
+ framesOut: traffic?.frames ?? 0,
19051
+ bytesOut: traffic?.bytes ?? 0
19052
+ };
18787
19053
  }
18788
19054
  /**
18789
19055
  * Extract parent paths from a nested path like "posts/70/tags"
@@ -18957,6 +19223,7 @@ var RealtimeService = class RealtimeService extends EventEmitter {
18957
19223
  /** Tell the client why its channel frame went nowhere, and say so in the log. */
18958
19224
  denyChannelAction(clientId, channel, action, reason) {
18959
19225
  this.debugLog(`🚫 [Channels] Refused ${action} on "${channel}" for ${clientId}: ${reason}`);
19226
+ socketStats.noteRefused("CHANNEL_FORBIDDEN");
18960
19227
  this.sendError(clientId, `Refused ${action} on channel "${channel}": ${reason}`, void 0, "CHANNEL_FORBIDDEN", channel);
18961
19228
  }
18962
19229
  /** Join a broadcast channel */
@@ -19220,6 +19487,7 @@ var RealtimeService = class RealtimeService extends EventEmitter {
19220
19487
  * so the message says exactly that.
19221
19488
  */
19222
19489
  reportOversizedBroadcast(clientId, channel) {
19490
+ socketStats.noteRefused("CHANNEL_BUS_PAYLOAD_TOO_LARGE");
19223
19491
  const remedy = `Add a retention rule for "${channel}" (realtime.channels) — retained messages travel by reference and have no size limit.`;
19224
19492
  if (!this.oversizedBroadcastWarned.has(channel)) {
19225
19493
  this.oversizedBroadcastWarned.add(channel);
@@ -19695,7 +19963,8 @@ var RealtimeService = class RealtimeService extends EventEmitter {
19695
19963
  sockets: this.clients.size,
19696
19964
  channels: this.channels.size,
19697
19965
  busFramesPublished: Object.fromEntries(this.busFramesPublished),
19698
- busFramesSkipped: this.busFramesSkipped
19966
+ busFramesSkipped: this.busFramesSkipped,
19967
+ socketTotals: socketStats.totals()
19699
19968
  };
19700
19969
  }
19701
19970
  /** The LISTEN connections this service depends on — see `RealtimeProvider.health`. */
@@ -24858,7 +25127,7 @@ function createPostgresBootstrapper(pgConfig) {
24858
25127
  return driverResult.internals.driver.admin;
24859
25128
  },
24860
25129
  async initializeWebsockets(server, realtimeService, driver, config, adapter, limits) {
24861
- const { createPostgresWebSocket, isSocketRealtimeService, socketRealtimeMissing } = await import("./websocket-CvmbzBeS.js").then((n) => n.c);
25130
+ const { createPostgresWebSocket, isSocketRealtimeService, socketRealtimeMissing } = await import("./websocket-C9Ev5FQs.js").then((n) => n.c);
24862
25131
  if (!isSocketRealtimeService(realtimeService)) throw new Error(`The realtime service handed to the Postgres socket cannot serve it — it has no ${socketRealtimeMissing(realtimeService).join(", ")}. Every socket would fail on its first frame.`);
24863
25132
  const realtimeConfig = effectiveConfig().realtime;
24864
25133
  const maxSocketsPerUser = realtimeConfig?.maxSocketsPerUser !== void 0 ? parseMaxSocketsPerUser(realtimeConfig.maxSocketsPerUser, "realtime.maxSocketsPerUser") : void 0;
@@ -25017,6 +25286,6 @@ async function openRebase(options) {
25017
25286
  };
25018
25287
  }
25019
25288
  //#endregion
25020
- export { PostgresBackendDriver as $, reapSilentSockets as A, passwordResetTokens as B, PostgresChannelBus as C, frameByteLength as D, MemoryChannelBus as E, magicLinkTokensRelations as F, refreshTokensRelations as G, recoveryCodes as H, mfaChallenges as I, users as J, userIdentities as K, mfaChallengesRelations as L, appConfig as M, createAuthSchema as N, isChannelBusInstance$1 as O, magicLinkTokens as P, CONNECTION_OWNER as Q, mfaFactors as R, PG_NOTIFY_MAX_PAYLOAD_BYTES as S, parseChannelBusPayload as T, recoveryCodesRelations as U, passwordResetTokensRelations as V, refreshTokens as W, usersSchema as X, usersRelations as Y, AuthenticatedPostgresBackendDriver as Z, refetchConcurrencyFor as _, openPostgresDriver as a, SQL_RESULT_BYTE_BUDGET as at, CHANNEL_BUS_NOTIFY_CHANNEL as b, PostgresTableRegistry as c, resolveNestedPath as ct, PostgresRealtimeProvider as d, PostgresConditionBuilder as dt, RoleSwitchUnavailableError as et, RealtimeService as f, configureUnknownFilterFields as ft, parseRealtimeTuning as g, listedColumnKeys as gt, parseMaxSubscriptionsPerSocket as h, joinColumn as ht, isScaffoldedLocalDatabase as i, sqlRoleRanAs as it, terminateIfBacklogged as j, budgetSendBuffers as k, DEFAULT_MAX_SUBSCRIPTIONS_PER_SOCKET as l, assertReadRequestReadable as lt, parseMaxSocketsPerUser as m, getUnknownFilterFieldsMode as mt, createPostgresBootstrapper as n, effectiveSqlRole as nt, postgresDriverConfigFromEnv as o, SqlResultTooLargeError as ot, packEntityChanges as p, escapeLikePattern as pt, userIdentitiesRelations as q, describeSchemaDriftCause as r, isRoleSwitchingOptedOut as rt, resolveSourceUrls as s, isNestedPath as st, openRebase as t, branchParentDatabase as tt, DEFAULT_RECOUNT_MIN_ROWS as u, DrizzleConditionBuilder as ut, createChannelBus as v, parseChannelBusFrame as w, DEFAULT_BATCH_WINDOW_MS as x, resolveChannelBusSetting as y, mfaFactorsRelations as z };
25289
+ export { userIdentities as $, MemoryChannelBus as A, createAuthSchema as B, PG_BUS_MAX_FRAME_BYTES as C, listedColumnKeys as Ct, parseChannelBusPayload as D, parseChannelBusFrame as E, terminateIfBacklogged as F, mfaFactors as G, magicLinkTokensRelations as H, closerOf as I, passwordResetTokensRelations as J, mfaFactorsRelations as K, noteServerClose as L, isChannelBusInstance$1 as M, budgetSendBuffers as N, parsePart as O, reapSilentSockets as P, refreshTokensRelations as Q, socketStats as R, FrameAssembler as S, joinColumn as St, PostgresChannelBus as T, mfaChallenges as U, magicLinkTokens as V, mfaChallengesRelations as W, recoveryCodesRelations as X, recoveryCodes as Y, refreshTokens as Z, refetchConcurrencyFor as _, DrizzleConditionBuilder as _t, openPostgresDriver as a, CONNECTION_OWNER as at, CHANNEL_BUS_NOTIFY_CHANNEL as b, escapeLikePattern as bt, PostgresTableRegistry as c, branchParentDatabase as ct, PostgresRealtimeProvider as d, sqlRoleRanAs as dt, userIdentitiesRelations as et, RealtimeService as f, SQL_RESULT_BYTE_BUDGET as ft, parseRealtimeTuning as g, assertReadRequestReadable as gt, parseMaxSubscriptionsPerSocket as h, resolveNestedPath as ht, isScaffoldedLocalDatabase as i, AuthenticatedPostgresBackendDriver as it, frameByteLength as j, splitIntoParts as k, DEFAULT_MAX_SUBSCRIPTIONS_PER_SOCKET as l, effectiveSqlRole as lt, parseMaxSocketsPerUser as m, isNestedPath as mt, createPostgresBootstrapper as n, usersRelations as nt, postgresDriverConfigFromEnv as o, PostgresBackendDriver as ot, packEntityChanges as p, SqlResultTooLargeError as pt, passwordResetTokens as q, describeSchemaDriftCause as r, usersSchema as rt, resolveSourceUrls as s, RoleSwitchUnavailableError as st, openRebase as t, users as tt, DEFAULT_RECOUNT_MIN_ROWS as u, isRoleSwitchingOptedOut as ut, createChannelBus as v, PostgresConditionBuilder as vt, PG_NOTIFY_MAX_PAYLOAD_BYTES as w, DEFAULT_BATCH_WINDOW_MS as x, getUnknownFilterFieldsMode as xt, resolveChannelBusSetting as y, configureUnknownFilterFields as yt, appConfig as z };
25021
25290
 
25022
- //# sourceMappingURL=open-rebase-DykxNl1j.js.map
25291
+ //# sourceMappingURL=open-rebase-BQrU-FAV.js.map