@cubicecho/server-kit 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Benjamin Van Treese
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,44 @@
1
- # Temporary Holding Version
1
+ <!-- AI agents: read llms.txt and _agents/docs/ for the full, version-matched API. -->
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ # @cubicecho/server-kit
4
+
5
+ The server code every cubicecho GraphQL backend shares. Each server used to copy it, and the copies drifted: a fix reached one repo and not the next. It is functions an app calls, not a framework: the app keeps its own schema, auth setup and boot order.
6
+
7
+ ## Install
8
+
9
+ ```sh
10
+ npm i @cubicecho/server-kit drizzle-orm@1.0.0-rc.5 postgres
11
+ ```
12
+
13
+ ## Quick start
14
+
15
+ ```ts
16
+ import { connectionOptions, DatabaseBootError, prepareDatabase } from '@cubicecho/server-kit/db';
17
+ import { drizzle } from 'drizzle-orm/postgres-js';
18
+
19
+ const url = process.env.DATABASE_URL ?? '';
20
+ const isProduction = process.env.NODE_ENV === 'production';
21
+ const db = drizzle({ connection: { url, ...connectionOptions(url, isProduction) } });
22
+
23
+ try {
24
+ await prepareDatabase(db, { url, isProduction });
25
+ } catch (error) {
26
+ if (error instanceof DatabaseBootError) {
27
+ console.error(`[db] ${error.message}`);
28
+ process.exit(1);
29
+ }
30
+ throw error;
31
+ }
32
+ ```
33
+
34
+ It waits for Postgres, creates the database when it is missing, and refuses a server older than 18, with a message that says what to do.
35
+
36
+ ## Documentation
37
+
38
+ - [llms.txt](https://cdn.jsdelivr.net/npm/@cubicecho/server-kit/llms.txt)
39
+ - [Pages](https://github.com/cubicecho/server-kit/tree/main/_agents/docs)
40
+ - [Changelog](https://github.com/cubicecho/server-kit/blob/main/CHANGELOG.md)
41
+
42
+ ## License
43
+
44
+ MIT
@@ -0,0 +1,31 @@
1
+ # Database boot
2
+
3
+ `@cubicecho/server-kit/db` makes a Postgres database ready to migrate: it waits for the server, creates the database when it is missing, and refuses a server the app cannot run on.
4
+
5
+ ```ts
6
+ import { connectionOptions, DatabaseBootError, prepareDatabase } from '@cubicecho/server-kit/db';
7
+ import { drizzle } from 'drizzle-orm/postgres-js';
8
+ import { migrate } from 'drizzle-orm/postgres-js/migrator';
9
+
10
+ const url = process.env.DATABASE_URL ?? '';
11
+ const isProduction = process.env.NODE_ENV === 'production';
12
+ const db = drizzle({ connection: { url, ...connectionOptions(url, isProduction) } });
13
+
14
+ try {
15
+ await prepareDatabase(db, { url, isProduction, extensions: ['vector'] });
16
+ } catch (error) {
17
+ if (error instanceof DatabaseBootError) {
18
+ console.error(`[db] ${error.message}`);
19
+ process.exit(1);
20
+ }
21
+ throw error;
22
+ }
23
+ await migrate(db, { migrationsFolder: 'drizzle' });
24
+ ```
25
+
26
+ - Call it before `migrate`. It checks the version and the extensions before it creates or changes anything.
27
+ - `extensions` names what the migrations create. It asks what the server can create, so the migration still creates it.
28
+ - A server older than `MIN_POSTGRES_MAJOR` is refused. One newer than `testedMajor` gets a warning through `log`.
29
+ - `connectTimeoutMs`, `firstRetryDelayMs`, `maxRetryDelayMs` and `retryBackoffFactor` override `DATABASE_DEFAULTS`.
30
+ - Any other error is the driver's own, such as a wrong password. Let it surface.
31
+ - `requiresSsl(url)` is false for a private host and for a URL with its own `sslmode`.
@@ -0,0 +1,25 @@
1
+ # Columns
2
+
3
+ `@cubicecho/server-kit/columns` has the Drizzle columns that keep a table to the conventions: a UUIDv7 id, moments with a time zone, and a table limited to one row.
4
+
5
+ ```ts
6
+ import { id, moment, singleton, singletonRules, timestamps } from '@cubicecho/server-kit/columns';
7
+ import { integer, pgTable, text } from 'drizzle-orm/pg-core';
8
+
9
+ export const todos = pgTable('todos', {
10
+ id: id(),
11
+ title: text('title').notNull(),
12
+ completedAt: moment('completed_at'),
13
+ ...timestamps(),
14
+ });
15
+
16
+ export const instanceSettings = pgTable(
17
+ 'instance_settings',
18
+ { id: id(), singleton: singleton(), runLimit: integer('run_limit').notNull().default(2) },
19
+ (table) => singletonRules('instance_settings', table.singleton),
20
+ );
21
+ ```
22
+
23
+ - `id()` defaults to the database's `uuidv7()`, which needs Postgres 18 or PGlite 0.5.
24
+ - An upsert of a singleton targets `table.singleton`, never `table.id`.
25
+ - A join table has no `id()`. Its primary key is its foreign keys.
@@ -0,0 +1,18 @@
1
+ # Test checks
2
+
3
+ `@cubicecho/server-kit/testing` registers Vitest tests that hold an app to the backend standard: its tables, and the Postgres it runs.
4
+
5
+ ```ts
6
+ import { resolve } from 'node:path';
7
+ import { checkPostgresVersion, checkSchemaConventions } from '@cubicecho/server-kit/testing';
8
+ import * as dbSchema from '../../../../db/src/schema.ts';
9
+
10
+ checkSchemaConventions(dbSchema, {
11
+ derived: { change_log: 'Triggers write it from the other tables.' },
12
+ });
13
+ checkPostgresVersion({ root: resolve(import.meta.dirname, '../../../..') });
14
+ ```
15
+
16
+ - `checkSchemaConventions` checks ids, join tables, time zones and foreign-key indexes, one test per table. `derived` and `legacyIds` excuse a table from the id rule, by SQL name with the reason, and an exception nothing needs fails.
17
+ - `checkPostgresVersion` fails unless both compose files and CI run one major, 18 or later, and PGlite is not behind it. PGlite ahead is a warning.
18
+ - `schemaProblems` and `postgresProblems` return the findings for another runner.
@@ -0,0 +1,23 @@
1
+ # Common mistakes
2
+
3
+ What goes wrong when the kit is wired up slightly differently, and the fix for each.
4
+
5
+ ## A second copy of drizzle-orm
6
+
7
+ `drizzle-orm` is a peer at one exact version. Pin the same version in the root `overrides` and as a root dependency, so npm installs one copy.
8
+
9
+ ## Migrating before `prepareDatabase`
10
+
11
+ On a server that is too old the migrations stop partway. Call `prepareDatabase` first: it changes nothing on a server it refuses.
12
+
13
+ ## Upserting a singleton on its id
14
+
15
+ Each insert has a new id, so it never conflicts on it, and the unique index refuses the row. Target the column that does conflict.
16
+
17
+ ```ts
18
+ .onConflictDoUpdate({ target: instanceSettings.singleton, set: { runLimit: 5 } })
19
+ ```
20
+
21
+ ## Importing the testing entry in a server
22
+
23
+ `@cubicecho/server-kit/testing` imports Vitest and PGlite, which are dev dependencies. Import it only from tests.
@@ -0,0 +1,38 @@
1
+ import { type PgColumn } from 'drizzle-orm/pg-core';
2
+ /**
3
+ * The primary key of an entity: a UUIDv7, made by the database.
4
+ *
5
+ * @returns The `id` column.
6
+ */
7
+ export declare function id(): import("drizzle-orm/pg-core").SetHasDefault<import("drizzle-orm/pg-core").SetIsPrimaryKey<import("drizzle-orm/pg-core").PgUUIDBuilder>>;
8
+ /**
9
+ * A moment, with its time zone.
10
+ *
11
+ * @typeParam Name - The column's SQL name.
12
+ * @param name - The column's SQL name.
13
+ * @returns The column.
14
+ */
15
+ export declare function moment<Name extends string>(name: Name): import("drizzle-orm/pg-core").PgTimestampBuilder;
16
+ /**
17
+ * When a row was made, and when it last changed. Spread into a mutable table's columns.
18
+ *
19
+ * @returns `createdAt` and `updatedAt`.
20
+ */
21
+ export declare function timestamps(): {
22
+ createdAt: import("drizzle-orm/pg-core").SetHasDefault<import("drizzle-orm/pg-core").SetNotNull<import("drizzle-orm/pg-core").PgTimestampBuilder>>;
23
+ updatedAt: import("drizzle-orm/pg-core").SetHasDefault<import("drizzle-orm/pg-core").SetHasDefault<import("drizzle-orm/pg-core").SetNotNull<import("drizzle-orm/pg-core").PgTimestampBuilder>>>;
24
+ };
25
+ /**
26
+ * The column that keeps a table to one row. It is always true and unique, and an upsert targets it.
27
+ *
28
+ * @returns The `singleton` column. The table also needs `singletonRules`.
29
+ */
30
+ export declare function singleton(): import("drizzle-orm/pg-core").SetHasDefault<import("drizzle-orm/pg-core").SetNotNull<import("drizzle-orm/pg-core").PgBooleanBuilder>>;
31
+ /**
32
+ * The unique index and the check that make `singleton` work.
33
+ *
34
+ * @param table - The table's SQL name.
35
+ * @param column - Its `singleton` column.
36
+ * @returns Both, to spread into the table's extras.
37
+ */
38
+ export declare function singletonRules(table: string, column: PgColumn): (import("drizzle-orm/pg-core").CheckBuilder | import("drizzle-orm/pg-core").IndexBuilder)[];
@@ -0,0 +1,53 @@
1
+ import { sql } from 'drizzle-orm';
2
+ import { boolean, check, timestamp, uniqueIndex, uuid } from 'drizzle-orm/pg-core';
3
+ /**
4
+ * The primary key of an entity: a UUIDv7, made by the database.
5
+ *
6
+ * @returns The `id` column.
7
+ */
8
+ export function id() {
9
+ return uuid('id').primaryKey().default(sql `uuidv7()`);
10
+ }
11
+ /**
12
+ * A moment, with its time zone.
13
+ *
14
+ * @typeParam Name - The column's SQL name.
15
+ * @param name - The column's SQL name.
16
+ * @returns The column.
17
+ */
18
+ export function moment(name) {
19
+ return timestamp(name, { withTimezone: true });
20
+ }
21
+ /**
22
+ * When a row was made, and when it last changed. Spread into a mutable table's columns.
23
+ *
24
+ * @returns `createdAt` and `updatedAt`.
25
+ */
26
+ export function timestamps() {
27
+ return {
28
+ createdAt: moment('created_at').notNull().defaultNow(),
29
+ updatedAt: moment('updated_at')
30
+ .notNull()
31
+ .defaultNow()
32
+ .$onUpdate(() => new Date()),
33
+ };
34
+ }
35
+ /**
36
+ * The column that keeps a table to one row. It is always true and unique, and an upsert targets it.
37
+ *
38
+ * @returns The `singleton` column. The table also needs `singletonRules`.
39
+ */
40
+ export function singleton() {
41
+ return boolean('singleton').notNull().default(true);
42
+ }
43
+ /**
44
+ * The unique index and the check that make `singleton` work.
45
+ *
46
+ * @param table - The table's SQL name.
47
+ * @param column - Its `singleton` column.
48
+ * @returns Both, to spread into the table's extras.
49
+ */
50
+ export function singletonRules(table, column) {
51
+ const isTrue = sql `${column}`;
52
+ return [uniqueIndex(`uq_${table}_singleton`).on(column), check(`ck_${table}_singleton`, isTrue)];
53
+ }
@@ -0,0 +1,4 @@
1
+ /** The first Postgres with `uuidv7()`, which ids default to. Boot refuses an older one. */
2
+ export declare const MIN_POSTGRES_MAJOR = 18;
3
+ /** The newest Postgres this package is tested on. Boot warns on a newer one. */
4
+ export declare const TESTED_POSTGRES_MAJOR = 18;
package/dist/consts.js ADDED
@@ -0,0 +1,4 @@
1
+ /** The first Postgres with `uuidv7()`, which ids default to. Boot refuses an older one. */
2
+ export const MIN_POSTGRES_MAJOR = 18;
3
+ /** The newest Postgres this package is tested on. Boot warns on a newer one. */
4
+ export const TESTED_POSTGRES_MAJOR = 18;
@@ -0,0 +1,18 @@
1
+ /** What a postgres-js client is given besides its URL. */
2
+ export interface ConnectionOptions {
3
+ /** Present when TLS has to be forced on. */
4
+ ssl?: 'require';
5
+ /** Drops notices. */
6
+ onnotice: () => void;
7
+ }
8
+ /**
9
+ * The postgres-js options a server connects with.
10
+ *
11
+ * @param url - The connection string.
12
+ * @param isProduction - Whether to force TLS to a host that is not private.
13
+ * @returns The options, to spread beside `url`.
14
+ *
15
+ * @remarks
16
+ * Idempotent migrations emit a NOTICE on every boot, and printing it makes a healthy restart look like a failure.
17
+ */
18
+ export declare function connectionOptions(url: string, isProduction: boolean): ConnectionOptions;
@@ -0,0 +1,15 @@
1
+ import { requiresSsl } from './ssl.js';
2
+ /**
3
+ * The postgres-js options a server connects with.
4
+ *
5
+ * @param url - The connection string.
6
+ * @param isProduction - Whether to force TLS to a host that is not private.
7
+ * @returns The options, to spread beside `url`.
8
+ *
9
+ * @remarks
10
+ * Idempotent migrations emit a NOTICE on every boot, and printing it makes a healthy restart look like a failure.
11
+ */
12
+ export function connectionOptions(url, isProduction) {
13
+ const mustForceSsl = isProduction && requiresSsl(url);
14
+ return { onnotice: () => { }, ...(mustForceSsl ? { ssl: 'require' } : {}) };
15
+ }
@@ -0,0 +1,40 @@
1
+ import type { Queryable } from './wait.ts';
2
+ /** The least boot needs of a connection to the maintenance database. */
3
+ export interface AdminClient {
4
+ unsafe: (query: string, parameters?: string[]) => PromiseLike<unknown>;
5
+ end: () => Promise<void>;
6
+ }
7
+ /** Opens a connection to the maintenance database. */
8
+ export type OpenAdmin = (url: string) => AdminClient;
9
+ /** A connection string's database, and where to create it from. */
10
+ export interface MaintenanceTarget {
11
+ /** The database the connection string names. */
12
+ database: string;
13
+ /** The same server and credentials, on the maintenance database. */
14
+ maintenanceUrl: string;
15
+ }
16
+ /**
17
+ * Opens one connection, with TLS decided as the app's own pool decides it.
18
+ *
19
+ * @param isProduction - Whether to force TLS to a host that is not private.
20
+ * @returns A function that opens a client the caller must end.
21
+ */
22
+ export declare function openAdmin(isProduction: boolean): OpenAdmin;
23
+ /**
24
+ * Splits a connection string into its database and the server's maintenance database.
25
+ *
26
+ * @param url - The connection string.
27
+ * @returns Both.
28
+ * @throws {@link DatabaseBootError} If it names no database.
29
+ */
30
+ export declare function maintenanceTarget(url: string): MaintenanceTarget;
31
+ /**
32
+ * Creates the database a connection string names.
33
+ *
34
+ * @param url - The connection string whose database is missing.
35
+ * @param open - Opens the maintenance connection.
36
+ * @param check - Throws when the app cannot run on the server. Called before anything is created.
37
+ * @returns true when this call created it, false when another instance got there first.
38
+ * @throws {@link DatabaseBootError} If the role may not create databases.
39
+ */
40
+ export declare function createDatabase(url: string, open: OpenAdmin, check: (server: Queryable) => Promise<void>): Promise<boolean>;
@@ -0,0 +1,91 @@
1
+ import { PgDialect } from 'drizzle-orm/pg-core';
2
+ import postgres from 'postgres';
3
+ import { connectionOptions } from './connection.js';
4
+ import { DatabaseBootError, errorCode } from './errors.js';
5
+ /** CREATE DATABASE lost a race with another instance doing the same. */
6
+ const ALREADY_EXISTS = '42P04';
7
+ /** The role may not create databases. */
8
+ const NOT_ALLOWED = '42501';
9
+ /** The database every server has, to connect to while the app's is missing. */
10
+ const MAINTENANCE_DATABASE = 'postgres';
11
+ const dialect = new PgDialect();
12
+ /**
13
+ * Opens one connection, with TLS decided as the app's own pool decides it.
14
+ *
15
+ * @param isProduction - Whether to force TLS to a host that is not private.
16
+ * @returns A function that opens a client the caller must end.
17
+ */
18
+ export function openAdmin(isProduction) {
19
+ return (url) => postgres(url, { max: 1, ...connectionOptions(url, isProduction) });
20
+ }
21
+ /**
22
+ * Splits a connection string into its database and the server's maintenance database.
23
+ *
24
+ * @param url - The connection string.
25
+ * @returns Both.
26
+ * @throws {@link DatabaseBootError} If it names no database.
27
+ */
28
+ export function maintenanceTarget(url) {
29
+ const parsed = new URL(url);
30
+ // Undecoded, as postgres-js reads it. Without one it falls back to the environment, which is not read here.
31
+ const database = parsed.pathname.slice(1);
32
+ if (database === '') {
33
+ throw new DatabaseBootError('DATABASE_URL names no database, so there is nothing to create.');
34
+ }
35
+ parsed.pathname = `/${MAINTENANCE_DATABASE}`;
36
+ return { database, maintenanceUrl: parsed.toString() };
37
+ }
38
+ /**
39
+ * Quotes a name as a SQL identifier.
40
+ *
41
+ * @param name - The raw identifier.
42
+ * @returns The identifier, safe in a statement.
43
+ */
44
+ function quoteIdentifier(name) {
45
+ return `"${name.replaceAll('"', '""')}"`;
46
+ }
47
+ /**
48
+ * Lets a maintenance connection run Drizzle's queries.
49
+ *
50
+ * @param client - The connection.
51
+ * @returns It, as something `requirePostgres` can ask.
52
+ */
53
+ function queryable(client) {
54
+ return {
55
+ execute: (query) => {
56
+ const { sql, params } = dialect.sqlToQuery(query);
57
+ return client.unsafe(sql, params.map(String));
58
+ },
59
+ };
60
+ }
61
+ /**
62
+ * Creates the database a connection string names.
63
+ *
64
+ * @param url - The connection string whose database is missing.
65
+ * @param open - Opens the maintenance connection.
66
+ * @param check - Throws when the app cannot run on the server. Called before anything is created.
67
+ * @returns true when this call created it, false when another instance got there first.
68
+ * @throws {@link DatabaseBootError} If the role may not create databases.
69
+ */
70
+ export async function createDatabase(url, open, check) {
71
+ const { database, maintenanceUrl } = maintenanceTarget(url);
72
+ const client = open(maintenanceUrl);
73
+ try {
74
+ await check(queryable(client));
75
+ await client.unsafe(`create database ${quoteIdentifier(database)}`);
76
+ return true;
77
+ }
78
+ catch (error) {
79
+ const code = errorCode(error);
80
+ if (code === ALREADY_EXISTS) {
81
+ return false;
82
+ }
83
+ if (code === NOT_ALLOWED) {
84
+ throw new DatabaseBootError(`Database "${database}" does not exist, and this role may not create it. Create it, or grant the role CREATEDB.`, { cause: error });
85
+ }
86
+ throw error;
87
+ }
88
+ finally {
89
+ await client.end();
90
+ }
91
+ }
@@ -0,0 +1,13 @@
1
+ /** Settings for reaching Postgres at boot. */
2
+ export interface DatabaseSettings {
3
+ /** How long boot waits for Postgres before giving up. */
4
+ connectTimeoutMs: number;
5
+ /** The wait before the first retry. */
6
+ firstRetryDelayMs: number;
7
+ /** The longest wait between two retries. */
8
+ maxRetryDelayMs: number;
9
+ /** How much the wait grows after each failed attempt. */
10
+ retryBackoffFactor: number;
11
+ }
12
+ /** What boot uses when the app overrides nothing. */
13
+ export declare const DATABASE_DEFAULTS: Readonly<DatabaseSettings>;
@@ -0,0 +1,8 @@
1
+ // Every value someone might tune, as plain data. Nothing here computes, reads the environment or imports.
2
+ /** What boot uses when the app overrides nothing. */
3
+ export const DATABASE_DEFAULTS = Object.freeze({
4
+ connectTimeoutMs: 60_000,
5
+ firstRetryDelayMs: 500,
6
+ maxRetryDelayMs: 5_000,
7
+ retryBackoffFactor: 2,
8
+ });
@@ -0,0 +1,11 @@
1
+ /** Thrown when boot cannot use the database. Its message is written for whoever runs the server. */
2
+ export declare class DatabaseBootError extends Error {
3
+ name: string;
4
+ }
5
+ /**
6
+ * Reads the driver or errno code of an error, or of whatever caused it.
7
+ *
8
+ * @param error - Whatever was thrown. Drizzle wraps the driver's error.
9
+ * @returns The code, or undefined when there is none.
10
+ */
11
+ export declare function errorCode(error: unknown): string | undefined;
@@ -0,0 +1,19 @@
1
+ /** Thrown when boot cannot use the database. Its message is written for whoever runs the server. */
2
+ export class DatabaseBootError extends Error {
3
+ name = 'DatabaseBootError';
4
+ }
5
+ /**
6
+ * Reads the driver or errno code of an error, or of whatever caused it.
7
+ *
8
+ * @param error - Whatever was thrown. Drizzle wraps the driver's error.
9
+ * @returns The code, or undefined when there is none.
10
+ */
11
+ export function errorCode(error) {
12
+ if (typeof error !== 'object' || error === null) {
13
+ return undefined;
14
+ }
15
+ if ('code' in error && typeof error.code === 'string') {
16
+ return error.code;
17
+ }
18
+ return 'cause' in error ? errorCode(error.cause) : undefined;
19
+ }
@@ -0,0 +1,9 @@
1
+ export { MIN_POSTGRES_MAJOR, TESTED_POSTGRES_MAJOR } from '../consts.ts';
2
+ export { type ConnectionOptions, connectionOptions } from './connection.ts';
3
+ export type { AdminClient, OpenAdmin } from './create.ts';
4
+ export { DATABASE_DEFAULTS, type DatabaseSettings } from './defaults.ts';
5
+ export { DatabaseBootError, errorCode } from './errors.ts';
6
+ export { type PrepareOptions, prepareDatabase } from './prepare.ts';
7
+ export { isPrivateHost, requiresSsl } from './ssl.ts';
8
+ export { type PostgresNeeds, requirePostgres } from './version.ts';
9
+ export { type Queryable, waitForDatabase } from './wait.ts';
@@ -0,0 +1,8 @@
1
+ export { MIN_POSTGRES_MAJOR, TESTED_POSTGRES_MAJOR } from '../consts.js';
2
+ export { connectionOptions } from './connection.js';
3
+ export { DATABASE_DEFAULTS } from './defaults.js';
4
+ export { DatabaseBootError, errorCode } from './errors.js';
5
+ export { prepareDatabase } from './prepare.js';
6
+ export { isPrivateHost, requiresSsl } from './ssl.js';
7
+ export { requirePostgres } from './version.js';
8
+ export { waitForDatabase } from './wait.js';
@@ -0,0 +1,32 @@
1
+ import { type OpenAdmin } from './create.ts';
2
+ import type { DatabaseSettings } from './defaults.ts';
3
+ import { type PostgresNeeds } from './version.ts';
4
+ import { type Queryable } from './wait.ts';
5
+ /** How a database is made ready. */
6
+ export interface PrepareOptions extends PostgresNeeds, Partial<DatabaseSettings> {
7
+ /** The connection string the client was built from. */
8
+ url: string;
9
+ /** Whether to force TLS to a host that is not private. */
10
+ isProduction: boolean;
11
+ /**
12
+ * Where retries, the creation and warnings are reported.
13
+ *
14
+ * @defaultValue `console.warn`
15
+ */
16
+ log?: (message: string) => void;
17
+ /**
18
+ * Opens the maintenance connection. Tests replace it.
19
+ *
20
+ * @defaultValue a postgres-js client
21
+ */
22
+ open?: OpenAdmin;
23
+ }
24
+ /**
25
+ * Makes the database ready to migrate: waits for it, creates it when it is missing, and checks its version.
26
+ *
27
+ * @param db - The app's Drizzle client.
28
+ * @param options - Where the database is, and what the app needs of it.
29
+ * @returns Resolves once the app may migrate.
30
+ * @throws {@link DatabaseBootError} If the app cannot run on it. The message says why, and what to do.
31
+ */
32
+ export declare function prepareDatabase(db: Queryable, options: PrepareOptions): Promise<void>;
@@ -0,0 +1,75 @@
1
+ import { createDatabase, maintenanceTarget, openAdmin } from './create.js';
2
+ import { DatabaseBootError, errorCode } from './errors.js';
3
+ import { requirePostgres } from './version.js';
4
+ import { isStillStarting, waitForDatabase } from './wait.js';
5
+ /** Postgres's answer when the database a connection names does not exist. */
6
+ const MISSING_DATABASE = '3D000';
7
+ /** Postgres's port, shown when a connection string names none. */
8
+ const DEFAULT_POSTGRES_PORT = '5432';
9
+ /**
10
+ * Makes the database ready to migrate: waits for it, creates it when it is missing, and checks its version.
11
+ *
12
+ * @param db - The app's Drizzle client.
13
+ * @param options - Where the database is, and what the app needs of it.
14
+ * @returns Resolves once the app may migrate.
15
+ * @throws {@link DatabaseBootError} If the app cannot run on it. The message says why, and what to do.
16
+ */
17
+ export async function prepareDatabase(db, options) {
18
+ const { url, isProduction, log = console.warn, open = openAdmin(isProduction), extensions, testedMajor } = options;
19
+ const { connectTimeoutMs, firstRetryDelayMs, maxRetryDelayMs, retryBackoffFactor } = options;
20
+ const settings = withoutUnset({ connectTimeoutMs, firstRetryDelayMs, maxRetryDelayMs, retryBackoffFactor });
21
+ const needs = { extensions, testedMajor };
22
+ try {
23
+ await waitOrCreate(db, { url, settings, needs, log, open });
24
+ }
25
+ catch (error) {
26
+ if (isStillStarting(error)) {
27
+ throw new DatabaseBootError(unreachable(url, errorCode(error)), { cause: error });
28
+ }
29
+ throw error;
30
+ }
31
+ await requirePostgres(db, needs, log);
32
+ }
33
+ /**
34
+ * Drops the settings a caller left out, so a spread does not copy `undefined` over a default.
35
+ *
36
+ * @param settings - Settings, some unset.
37
+ * @returns The ones that are set.
38
+ */
39
+ function withoutUnset(settings) {
40
+ return Object.fromEntries(Object.entries(settings).filter(([, value]) => value !== undefined));
41
+ }
42
+ /**
43
+ * Waits for the database, creating it first when the server is up without it.
44
+ *
45
+ * @param db - The app's Drizzle client.
46
+ * @param options - Where the database is, and how long to wait.
47
+ */
48
+ async function waitOrCreate(db, { url, settings, needs, log, open }) {
49
+ try {
50
+ await waitForDatabase(db, settings, log);
51
+ }
52
+ catch (error) {
53
+ if (errorCode(error) !== MISSING_DATABASE) {
54
+ throw error;
55
+ }
56
+ const created = await createDatabase(url, open, (server) => requirePostgres(server, needs, () => { }));
57
+ if (created) {
58
+ log(`[db] created database "${maintenanceTarget(url).database}"`);
59
+ }
60
+ await waitForDatabase(db, settings, log);
61
+ }
62
+ }
63
+ /**
64
+ * Says that a server cannot be reached, without its credentials.
65
+ *
66
+ * @param url - The connection string.
67
+ * @param code - Why, as the driver put it.
68
+ * @returns The message.
69
+ */
70
+ function unreachable(url, code) {
71
+ const { hostname, port } = new URL(url);
72
+ return (`Cannot reach Postgres at ${hostname}:${port || DEFAULT_POSTGRES_PORT} (${code}). ` +
73
+ 'Check DATABASE_URL, and that the database is up and reachable from here. With a remote Docker daemon, a port ' +
74
+ "published on 127.0.0.1 is on the daemon host's loopback.");
75
+ }
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Whether a host is this machine or on a private network.
3
+ *
4
+ * "Private" is wider than loopback, because self-hosting is: a compose service
5
+ * and a box on the LAN are both names nothing outside can reach.
6
+ *
7
+ * @param hostname - The host from a URL, lowercased and without IPv6 brackets.
8
+ * @returns true for localhost, a dotless name, a private-use suffix or a private address.
9
+ */
10
+ export declare function isPrivateHost(hostname: string): boolean;
11
+ /**
12
+ * Whether to insist on TLS for a connection string.
13
+ *
14
+ * Read from the parsed hostname, never the raw string: a URL carrying
15
+ * credentials puts the userinfo where a prefix match looks for the host. A
16
+ * private host speaks no TLS by default, and demanding it breaks the connection.
17
+ *
18
+ * @param url - The connection string.
19
+ * @returns false for a private host, and when the URL sets its own `sslmode`.
20
+ */
21
+ export declare function requiresSsl(url: string): boolean;