@jami-studio/core 0.92.17 → 0.92.19
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/corpus/core/CHANGELOG.md +12 -0
- package/corpus/core/package.json +1 -1
- package/corpus/core/src/db/client.ts +17 -2
- package/corpus/core/src/db/create-get-db.ts +30 -14
- package/corpus/core/src/deploy/build.ts +25 -1
- package/corpus/core/src/deploy/workspace-deploy.ts +5 -3
- package/dist/db/client.d.ts.map +1 -1
- package/dist/db/client.js +15 -2
- package/dist/db/client.js.map +1 -1
- package/dist/db/create-get-db.d.ts.map +1 -1
- package/dist/db/create-get-db.js +14 -1
- package/dist/db/create-get-db.js.map +1 -1
- package/dist/deploy/build.d.ts.map +1 -1
- package/dist/deploy/build.js +24 -1
- package/dist/deploy/build.js.map +1 -1
- package/dist/deploy/workspace-deploy.js +5 -3
- package/dist/deploy/workspace-deploy.js.map +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"create-get-db.js","sourceRoot":"","sources":["../../src/db/create-get-db.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAErD,OAAO,EAAE,OAAO,IAAI,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAGtD,OAAO,EACL,UAAU,EACV,sBAAsB,EACtB,cAAc,EACd,oBAAoB,EACpB,gBAAgB,EAChB,WAAW,EACX,iBAAiB,EACjB,eAAe,EACf,iBAAiB,EACjB,qBAAqB,EACrB,qBAAqB,EACrB,aAAa,EACb,WAAW,EACX,yBAAyB,EACzB,aAAa,EACb,sBAAsB,EACtB,aAAa,GACd,MAAM,aAAa,CAAC;AAErB,0EAA0E;AAC1E,IAAI,UAAgE,CAAC;AACrE,SAAS,YAAY;IACnB,IAAI,CAAC,UAAU,EAAE,CAAC;QAChB,UAAU,GAAG,OAAO,CAAC,GAAG,CAAC;YACvB,MAAM,CAAC,yBAAyB,CA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AS,KAAK;QACZ,IAAI,GAAG;YAAE,OAAO,GAAG,CAAC;QACpB,SAAS,EAAE,CAAC;QACZ,IAAI,GAAG;YAAE,OAAO,GAAG,CAAC;QAEpB,OAAO,eAAe,CAAC,QAAS,EAAE,EAAE,CAAsB,CAAC;IAC7D,CAAC;IAED,OAAO,KAAK,CAAC;AACf,CAAC","sourcesContent":["import { AsyncLocalStorage } from \"node:async_hooks\";\r\n\r\nimport { drizzle as drizzleD1 } from \"drizzle-orm/d1\";\r\nimport type { LibSQLDatabase } from \"drizzle-orm/libsql\";\r\n\r\nimport {\r\n getDialect,\r\n getCloudflareD1Binding,\r\n getDatabaseUrl,\r\n getDatabaseAuthToken,\r\n isLocalSqliteUrl,\r\n isPgliteUrl,\r\n isConnectionError,\r\n getPgliteClient,\r\n loadPgliteDrizzle,\r\n prepareLocalSqliteUrl,\r\n sqliteFilenameFromUrl,\r\n pgPoolOptions,\r\n neonPoolMax,\r\n attachNeonPoolErrorLogger,\r\n withDbTimeout,\r\n retryOnConnectionError,\r\n dbOpTimeoutMs,\r\n} from \"./client.js\";\r\n\r\n// Lazy driver loaders — cached promises so dynamic import only runs once.\r\nlet _pgDrizzle: Promise<{ drizzle: any; postgres: any }> | undefined;\r\nfunction getPgDrizzle() {\r\n if (!_pgDrizzle) {\r\n _pgDrizzle = Promise.all([\r\n import(\"drizzle-orm/postgres-js\"),\r\n import(\"postgres\"),\r\n ]).then(([drizzleMod, pgMod]) => ({\r\n drizzle: drizzleMod.drizzle,\r\n postgres: pgMod.default,\r\n }));\r\n }\r\n return _pgDrizzle;\r\n}\r\n\r\nlet _neonServerlessDrizzle: Promise<{ drizzle: any; Pool: any }> | undefined;\r\nfunction getNeonServerlessDrizzle() {\r\n if (!_neonServerlessDrizzle) {\r\n _neonServerlessDrizzle = Promise.all([\r\n import(\"drizzle-orm/neon-serverless\"),\r\n import(\"@neondatabase/serverless\"),\r\n ]).then(([drizzleMod, neonMod]) => ({\r\n drizzle: drizzleMod.drizzle,\r\n Pool: neonMod.Pool,\r\n }));\r\n }\r\n return _neonServerlessDrizzle;\r\n}\r\n\r\n/**\r\n * Returns true when a SQL string starts with a SELECT-class verb.\r\n * Used by the Neon resilience wrapper to decide retry safety:\r\n * - reads (SELECT) → retryable on any connection-class error\r\n * - writes (INSERT/UPDATE/DELETE/…) → only retryable on errors that\r\n * provably occurred BEFORE the statement was sent (e.g. an acquire /\r\n * connect timeout). Post-send write failures must propagate to the caller\r\n * to avoid double-execution.\r\n */\r\nexport function isSqlRead(sql: string): boolean {\r\n return /^\\s*(SELECT|WITH\\s)/i.test(sql);\r\n}\r\n\r\n/**\r\n * Wraps a @neondatabase/serverless Pool so every query goes through\r\n * the same withDbTimeout + retryOnConnectionError resilience that the\r\n * raw DbExec path in client.ts uses. This protects Drizzle queries\r\n * (which bypass DbExec) from the frozen-WebSocket failure mode documented\r\n * in client.ts (~lines 378–408).\r\n *\r\n * Retry-safety rule (prevents double-execution on writes):\r\n * - Reads (SELECT / WITH …): retry freely on any connection-class error.\r\n * - Writes: only retry when the error occurred during connection acquire\r\n * (i.e. withDbTimeout \"connect\" timed out before the statement was ever\r\n * sent). Post-send failures on writes are rethrown immediately.\r\n *\r\n * Transactions: we do NOT wrap individual queries inside a drizzle\r\n * transaction — drizzle-neon-serverless manages the session itself, so\r\n * interposing a per-query client acquire/release would break the sticky\r\n * connection the transaction needs. The pool-level error logger still fires\r\n * on idle-client drops inside transactions.\r\n */\r\nexport function buildResilientNeonPool(pool: {\r\n connect(): Promise<any>;\r\n query(\r\n sql: string,\r\n args?: any[],\r\n ): Promise<{ rows: unknown[]; rowCount?: number }>;\r\n end(): Promise<void>;\r\n on(event: string, listener: (...args: any[]) => void): unknown;\r\n}): typeof pool {\r\n // Preserve all original pool methods and properties; only override `connect`\r\n // and `query` at the Pool level (used by drizzle's neon-serverless adapter\r\n // when it calls pool.query() directly, e.g. outside a transaction).\r\n const resilientQuery = async (\r\n sql: string,\r\n args?: any[],\r\n ): Promise<{ rows: unknown[]; rowCount?: number }> => {\r\n const isRead = isSqlRead(sql);\r\n\r\n const runAttempt = async (): Promise<{\r\n rows: unknown[];\r\n rowCount?: number;\r\n }> => {\r\n // Bound the pool.connect() acquire — a frozen Neon WebSocket stalls here\r\n // before the query ever starts, so a query-level timeout alone won't help.\r\n let acquireTimedOut = false;\r\n const client = await withDbTimeout(\r\n \"connect\",\r\n () =>\r\n pool.connect().then((c: any) => {\r\n // If we already gave up on this slot, immediately release it so\r\n // the scarce pool connection isn't leaked.\r\n if (acquireTimedOut) c.release();\r\n return c;\r\n }),\r\n dbOpTimeoutMs(),\r\n () => {\r\n acquireTimedOut = true;\r\n },\r\n );\r\n\r\n let released = false;\r\n const releaseClient = (err?: Error | boolean) => {\r\n if (released) return;\r\n released = true;\r\n client.release(err);\r\n };\r\n\r\n try {\r\n const result = await withDbTimeout(\r\n \"query\",\r\n () =>\r\n client.query(sql, args ?? []) as Promise<{\r\n rows: unknown[];\r\n rowCount?: number;\r\n }>,\r\n dbOpTimeoutMs(),\r\n () => releaseClient(true),\r\n );\r\n releaseClient();\r\n return result;\r\n } catch (err) {\r\n releaseClient(isConnectionError(err) ? true : undefined);\r\n throw err;\r\n }\r\n };\r\n\r\n if (isRead) {\r\n // Reads: retry on any connection-class error (safe — no side effects).\r\n return retryOnConnectionError(runAttempt);\r\n }\r\n\r\n // Writes: attempt once. If the acquire itself times out (error occurs\r\n // before the statement was sent), that produces a CONNECT_TIMEOUT which\r\n // isConnectionError() recognises → retry is safe. Any error that surfaces\r\n // AFTER the statement was sent must propagate immediately to avoid\r\n // double-execution.\r\n try {\r\n return await runAttempt();\r\n } catch (err) {\r\n // acquire-timeout fires before the statement → safe to retry once.\r\n if (isConnectionError(err) && (err as any)?.code === \"CONNECT_TIMEOUT\") {\r\n return runAttempt();\r\n }\r\n throw err;\r\n }\r\n };\r\n\r\n // Return a proxy so every pool property/method is forwarded as-is, but\r\n // pool.query() goes through the resilient wrapper. drizzle-neon-serverless\r\n // calls pool.connect() for transactions and pool.query() for simple queries.\r\n return new Proxy(pool, {\r\n get(target, prop) {\r\n if (prop === \"query\") return resilientQuery;\r\n const val = (target as any)[prop];\r\n return typeof val === \"function\" ? val.bind(target) : val;\r\n },\r\n });\r\n}\r\n\r\n/**\r\n * Wraps a postgres.js client so Drizzle queries on the non-Neon Postgres\r\n * path get the same withDbTimeout + retryOnConnectionError protection as\r\n * every other Postgres path (raw DbExec postgres.js, raw DbExec Neon, and\r\n * the Drizzle Neon pool above). Without this, one hung query on a BYO\r\n * Postgres deployment stalls its request forever.\r\n *\r\n * Drizzle's postgres-js session only calls `client.unsafe(query, params)` —\r\n * awaited directly for row-object results or via `.values()` for row-array\r\n * results — plus `client.begin(...)` for transactions. We interpose on\r\n * `unsafe` with a lazy thenable that re-issues the query per retry attempt,\r\n * and leave transactions unwrapped (same rule as the Neon wrapper: the\r\n * driver manages the sticky connection inside `begin`).\r\n *\r\n * Retry-safety mirrors buildResilientNeonPool: reads retry freely on\r\n * connection-class errors; writes retry only on CONNECT_TIMEOUT (postgres.js\r\n * raises it before the statement is ever sent), so writes can't\r\n * double-execute.\r\n */\r\nexport function buildResilientPostgresJsClient<\r\n T extends {\r\n unsafe(query: string, params?: any[], options?: any): any;\r\n },\r\n>(client: T): T {\r\n const wrapUnsafe = (query: string, params?: any[], options?: any) => {\r\n const isRead = isSqlRead(query);\r\n\r\n const runAttempt = (mode: \"rows\" | \"values\") => async (): Promise<any> => {\r\n const pending = client.unsafe(query, params, options);\r\n return withDbTimeout(\r\n \"query\",\r\n async () => (mode === \"values\" ? pending.values() : pending),\r\n dbOpTimeoutMs(),\r\n () => {\r\n // Best-effort cancel so the timed-out statement doesn't keep\r\n // occupying one of the (small, serverless-capped) pool slots.\r\n try {\r\n pending.cancel?.();\r\n } catch {\r\n // ignore — cancellation is advisory\r\n }\r\n },\r\n );\r\n };\r\n\r\n const execute = async (mode: \"rows\" | \"values\"): Promise<any> => {\r\n if (isRead) return retryOnConnectionError(runAttempt(mode));\r\n try {\r\n return await runAttempt(mode)();\r\n } catch (err) {\r\n // Connect timeout fires before the statement is sent → one retry is\r\n // safe even for writes.\r\n if (\r\n isConnectionError(err) &&\r\n (err as any)?.code === \"CONNECT_TIMEOUT\"\r\n ) {\r\n return runAttempt(mode)();\r\n }\r\n throw err;\r\n }\r\n };\r\n\r\n // Lazy thenable mirroring the slice of postgres.js's PendingQuery\r\n // surface that Drizzle uses: `await q` or `await q.values()`.\r\n return {\r\n then: (onFulfilled?: any, onRejected?: any) =>\r\n execute(\"rows\").then(onFulfilled, onRejected),\r\n catch: (onRejected?: any) => execute(\"rows\").catch(onRejected),\r\n finally: (onFinally?: any) => execute(\"rows\").finally(onFinally),\r\n values: () => execute(\"values\"),\r\n };\r\n };\r\n\r\n return new Proxy(client as any, {\r\n get(target, prop) {\r\n if (prop === \"unsafe\") return wrapUnsafe;\r\n const val = target[prop];\r\n return typeof val === \"function\" ? val.bind(target) : val;\r\n },\r\n }) as T;\r\n}\r\n\r\n/**\r\n * Neon's pooler endpoints cold-start in 5–10s. Serverless environments\r\n * (Netlify Functions, Vercel Edge, CF Workers) have short cold-start\r\n * budgets of their own, and `postgres-js` opens a raw TCP connection on\r\n * port 5432 that can't negotiate around Neon's wake-up window — every\r\n * request after an idle period 502s. `@neondatabase/serverless` rides\r\n * over WebSockets (HTTP/443 upgrade) and handles Neon wake-up\r\n * transparently, supports transactions, and works in every serverless\r\n * runtime we deploy to, so we prefer it whenever the URL points at Neon.\r\n */\r\nexport function isNeonUrl(url: string): boolean {\r\n // Must match neon.tech followed by port/path/query/end — include `?` so\r\n // URLs like `postgres://…@ep.neon.tech?sslmode=require` (no explicit port\r\n // or path) still route through the serverless driver.\r\n return /\\.neon\\.tech([:/?]|$)/.test(url);\r\n}\r\n\r\nlet _libsqlWebDrizzle: Promise<{ drizzle: any }> | undefined;\r\nfunction getLibsqlWebDrizzle() {\r\n if (!_libsqlWebDrizzle) {\r\n _libsqlWebDrizzle = import(\"drizzle-orm/libsql/web\").then((mod) => ({\r\n drizzle: mod.drizzle,\r\n }));\r\n }\r\n return _libsqlWebDrizzle;\r\n}\r\n\r\nlet _betterSqliteDrizzle: Promise<{ drizzle: any; Database: any }> | undefined;\r\nfunction getBetterSqliteDrizzle() {\r\n if (!_betterSqliteDrizzle) {\r\n _betterSqliteDrizzle = Promise.all([\r\n import(\"drizzle-orm/better-sqlite3\"),\r\n import(\"better-sqlite3\"),\r\n ]).then(([drizzleMod, sqliteMod]) => ({\r\n drizzle: drizzleMod.drizzle,\r\n Database: sqliteMod.default,\r\n }));\r\n }\r\n return _betterSqliteDrizzle;\r\n}\r\n\r\n/**\r\n * Patch a drizzle-orm/better-sqlite3 instance so that db.transaction(async …)\r\n * works. The native better-sqlite3 Transaction wrapper is sync-only — passing\r\n * an async callback throws \"Transaction function cannot return a promise\".\r\n *\r\n * This wrapper bypasses the native path by issuing raw SQL control statements\r\n * on the single better-sqlite3 connection, which is safe because:\r\n * - better-sqlite3 is single-connection (no concurrency inside one process)\r\n * - the framework serialises all async work through one Database instance\r\n *\r\n * Nesting: if a transaction is already open (sqlite.inTransaction === true),\r\n * SAVEPOINT / RELEASE / ROLLBACK TO is used instead of BEGIN / COMMIT /\r\n * ROLLBACK, matching drizzle's own BetterSQLiteTransaction.transaction().\r\n *\r\n * The patched transaction also patches the tx object it passes to the callback\r\n * so that nested async calls (tx.transaction(async …)) work recursively.\r\n */\r\n/** @internal exported for the async-tx concurrency spec */\r\nexport function patchBetterSqliteTransactions<\r\n DB extends { transaction: (...args: any[]) => any; session: any },\r\n>(db: DB, sqlite: { inTransaction: boolean; exec: (sql: string) => void }): DB {\r\n let savepointSeq = 0;\r\n // Concurrent TOP-LEVEL async transactions on the single better-sqlite3\r\n // connection must not interleave: a second transaction starting while the\r\n // first is open would see `inTransaction` and open a savepoint INSIDE the\r\n // first transaction, which then commits out from under it (\"no such\r\n // savepoint\"). Serialize top-level transactions through a promise chain;\r\n // genuine same-task nesting (tx.transaction or db.transaction inside an\r\n // open callback) is detected via AsyncLocalStorage and keeps the direct\r\n // savepoint path so it cannot deadlock on the queue.\r\n const txContext = new AsyncLocalStorage<boolean>();\r\n let txChain: Promise<unknown> = Promise.resolve();\r\n\r\n function makeAsyncTransaction(\r\n originalTransaction: (...args: any[]) => any,\r\n ): (...args: any[]) => Promise<unknown> {\r\n async function runTransactionBody(\r\n cb: (tx: unknown) => unknown,\r\n ): Promise<unknown> {\r\n // Extract the drizzle tx proxy synchronously — call the original with a\r\n // stub that captures the tx arg then immediately throws a sentinel so\r\n // better-sqlite3's native wrapper rolls back the stub and re-throws.\r\n // The sentinel is caught here and never propagates further.\r\n let capturedTx: unknown;\r\n try {\r\n originalTransaction((tx: unknown) => {\r\n capturedTx = tx;\r\n throw _EXTRACT_TX;\r\n });\r\n } catch (e) {\r\n if (e !== _EXTRACT_TX) throw e;\r\n }\r\n\r\n // Recursively patch the nested tx so tx.transaction(async …) also works.\r\n const tx = capturedTx as { transaction: (...a: any[]) => any };\r\n if (tx && typeof tx.transaction === \"function\") {\r\n tx.transaction = makeAsyncTransaction(tx.transaction.bind(tx));\r\n }\r\n\r\n const nested = sqlite.inTransaction;\r\n if (nested) {\r\n const sp = `sp_async_${++savepointSeq}`;\r\n sqlite.exec(`SAVEPOINT ${sp}`);\r\n let released = false;\r\n try {\r\n const result = await cb(tx);\r\n sqlite.exec(`RELEASE SAVEPOINT ${sp}`);\r\n released = true;\r\n return result;\r\n } catch (err) {\r\n if (!released) {\r\n try {\r\n sqlite.exec(`ROLLBACK TO SAVEPOINT ${sp}`);\r\n sqlite.exec(`RELEASE SAVEPOINT ${sp}`);\r\n } catch {\r\n /* ignore: connection may already be in an error state */\r\n }\r\n }\r\n throw err;\r\n }\r\n }\r\n\r\n // Top-level: BEGIN IMMEDIATE … COMMIT / ROLLBACK.\r\n sqlite.exec(\"BEGIN IMMEDIATE\");\r\n let committed = false;\r\n try {\r\n const result = await cb(tx);\r\n sqlite.exec(\"COMMIT\");\r\n committed = true;\r\n return result;\r\n } catch (err) {\r\n if (!committed) {\r\n try {\r\n sqlite.exec(\"ROLLBACK\");\r\n } catch {\r\n /* swallow: connection may already be unusable */\r\n }\r\n }\r\n throw err;\r\n }\r\n }\r\n\r\n return function asyncTransaction(\r\n cb: (tx: unknown) => unknown,\r\n ): Promise<unknown> {\r\n if (txContext.getStore()) {\r\n // Same-task nesting: run directly (savepoint path inside the open\r\n // transaction). Queueing here would deadlock behind the outer tx.\r\n return runTransactionBody(cb);\r\n }\r\n const run = () => txContext.run(true, () => runTransactionBody(cb));\r\n const next = txChain.then(run, run);\r\n txChain = next.then(\r\n () => undefined,\r\n () => undefined,\r\n );\r\n return next;\r\n };\r\n }\r\n\r\n db.transaction = makeAsyncTransaction(db.transaction.bind(db));\r\n return db;\r\n}\r\n\r\n/** Sentinel thrown inside the tx-extraction stub — never escapes the catch. */\r\nconst _EXTRACT_TX = Symbol(\"extract-tx\");\r\n\r\nexport function createGetDb<T extends Record<string, unknown>>(schema: T) {\r\n let _db: any;\r\n let _dbReady: Promise<any> | undefined;\r\n\r\n function startInit(): Promise<any> {\r\n if (_dbReady) return _dbReady;\r\n\r\n const url = getDatabaseUrl(\"file:./data/app.db\");\r\n const dialect = getDialect();\r\n\r\n // D1 only if dialect detected it (DATABASE_URL takes priority)\r\n if (dialect === \"d1\") {\r\n const d1 = getCloudflareD1Binding() as\r\n | Parameters<typeof drizzleD1>[0]\r\n | undefined;\r\n if (d1) {\r\n _db = drizzleD1(d1, { schema }) as unknown as LibSQLDatabase<T>;\r\n _dbReady = Promise.resolve(_db);\r\n return _dbReady;\r\n }\r\n }\r\n\r\n if (isPgliteUrl(url)) {\r\n _dbReady = loadPgliteDrizzle().then(async ({ drizzle }) => {\r\n const client = await getPgliteClient(url);\r\n _db = drizzle({ client, schema });\r\n });\r\n return _dbReady;\r\n }\r\n\r\n if (dialect === \"postgres\") {\r\n if (isNeonUrl(url)) {\r\n _dbReady = getNeonServerlessDrizzle().then(({ drizzle, Pool }) => {\r\n const rawPool = new Pool({\r\n connectionString: url,\r\n max: neonPoolMax(),\r\n });\r\n attachNeonPoolErrorLogger(rawPool);\r\n // Wrap the pool with the resilience layer so Drizzle queries get the\r\n // same withDbTimeout + retryOnConnectionError protection as the raw\r\n // DbExec path in client.ts. Reads retry freely; writes only retry on\r\n // acquire-timeout (pre-send) errors to avoid double-execution.\r\n const pool = buildResilientNeonPool(rawPool);\r\n _db = drizzle(pool, { schema });\r\n });\r\n } else {\r\n _dbReady = getPgDrizzle().then(({ drizzle, postgres }) => {\r\n // pgPoolOptions caps the pool to a small size on serverless so\r\n // concurrent frozen instances don't exhaust Neon/Postgres'\r\n // connection limit (\"Max client connections reached\").\r\n const client = postgres(url, pgPoolOptions(url));\r\n _db = drizzle(buildResilientPostgresJsClient(client), { schema });\r\n });\r\n }\r\n } else if (isLocalSqliteUrl(url)) {\r\n _dbReady = Promise.all([\r\n prepareLocalSqliteUrl(url.startsWith(\"file:\") ? url : `file:${url}`),\r\n getBetterSqliteDrizzle(),\r\n ]).then(([sqliteUrl, { drizzle, Database }]) => {\r\n const sqlite = new Database(sqliteFilenameFromUrl(sqliteUrl));\r\n // Wait up to 10s for a concurrent writer instead of failing fast\r\n // with SQLITE_BUSY — mirrors the raw DbExec SQLite path in client.ts.\r\n sqlite.pragma(\"busy_timeout = 10000\");\r\n sqlite.pragma(\"journal_mode = WAL\");\r\n const db = drizzle(sqlite, { schema });\r\n _db = patchBetterSqliteTransactions(db, sqlite);\r\n });\r\n } else {\r\n _dbReady = getLibsqlWebDrizzle().then(({ drizzle }) => {\r\n _db = drizzle({\r\n connection: { url, authToken: getDatabaseAuthToken() },\r\n schema,\r\n });\r\n });\r\n }\r\n return _dbReady;\r\n }\r\n\r\n /**\r\n * Create a lazy proxy that records property accesses and method calls,\r\n * then replays them on the real DB once init completes. Supports\r\n * Drizzle's chained API: db.select().from(table).where(...).\r\n *\r\n * When `.then()` is called (i.e. the chain is awaited), the proxy\r\n * awaits _dbReady and replays the recorded chain on the real _db.\r\n */\r\n function createLazyProxy(\r\n ready: Promise<any>,\r\n chain: Array<{ prop: string | symbol; args?: any[] }>,\r\n ): any {\r\n return new Proxy(function () {} as any, {\r\n get(_target, prop) {\r\n // When awaited, replay the chain on the real db\r\n if (prop === \"then\" || prop === \"catch\" || prop === \"finally\") {\r\n const promise = ready.then(() => {\r\n let result: any = _db;\r\n for (const step of chain) {\r\n const val = result[step.prop];\r\n result =\r\n typeof val === \"function\" ? val.apply(result, step.args) : val;\r\n }\r\n return result;\r\n });\r\n return (promise as any)[prop].bind(promise);\r\n }\r\n // Symbol.toStringTag, Symbol.iterator, etc. — return another proxy\r\n // Property access (e.g. db.query) — record and return another proxy\r\n return createLazyProxy(ready, [...chain, { prop }]);\r\n },\r\n apply(_target, _thisArg, args) {\r\n // Method call (e.g. .from(table)) — record args and return another proxy\r\n if (chain.length === 0) return createLazyProxy(ready, []);\r\n const last = chain[chain.length - 1];\r\n const newChain = chain.slice(0, -1);\r\n newChain.push({ prop: last.prop, args });\r\n return createLazyProxy(ready, newChain);\r\n },\r\n });\r\n }\r\n\r\n /**\r\n * Get the Drizzle DB instance. Kicks off lazy init on first call.\r\n * If the async init hasn't completed yet, returns a lazy Proxy that\r\n * records the Drizzle chain (select/from/where/etc.) and replays it\r\n * once the DB driver finishes loading. Since callers always `await`\r\n * the final result, the proxy is transparent.\r\n */\r\n function getDb(): LibSQLDatabase<T> {\r\n if (_db) return _db;\r\n startInit();\r\n if (_db) return _db;\r\n\r\n return createLazyProxy(_dbReady!, []) as LibSQLDatabase<T>;\r\n }\r\n\r\n return getDb;\r\n}\r\n"]}
|
|
1
|
+
{"version":3,"file":"create-get-db.js","sourceRoot":"","sources":["../../src/db/create-get-db.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAErD,OAAO,EAAE,OAAO,IAAI,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAGtD,OAAO,EACL,UAAU,EACV,sBAAsB,EACtB,cAAc,EACd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CAAC,CAAC;oBACH,OAAQ,OAAe,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;gBAC9C,CAAC;gBACD,mEAAmE;gBACnE,oEAAoE;gBACpE,OAAO,eAAe,CAAC,KAAK,EAAE,CAAC,GAAG,KAAK,EAAE,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC;YACtD,CAAC;YACD,KAAK,CAAC,OAAO,EAAE,QAAQ,EAAE,IAAI;gBAC3B,yEAAyE;gBACzE,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC;oBAAE,OAAO,eAAe,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;gBAC1D,MAAM,IAAI,GAAG,KAAK,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;gBACrC,MAAM,QAAQ,GAAG,KAAK,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;gBACpC,QAAQ,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,IAAI,CAAC,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;gBACzC,OAAO,eAAe,CAAC,KAAK,EAAE,QAAQ,CAAC,CAAC;YAC1C,CAAC;SACF,CAAC,CAAC;IACL,CAAC;IAED;;;;;;OAMG;IACH,SAAS,KAAK;QACZ,IAAI,GAAG;YAAE,OAAO,GAAG,CAAC;QACpB,SAAS,EAAE,CAAC;QACZ,IAAI,GAAG;YAAE,OAAO,GAAG,CAAC;QAEpB,OAAO,eAAe,CAAC,QAAS,EAAE,EAAE,CAAsB,CAAC;IAC7D,CAAC;IAED,OAAO,KAAK,CAAC;AACf,CAAC","sourcesContent":["import { AsyncLocalStorage } from \"node:async_hooks\";\r\n\r\nimport { drizzle as drizzleD1 } from \"drizzle-orm/d1\";\r\nimport type { LibSQLDatabase } from \"drizzle-orm/libsql\";\r\n\r\nimport {\r\n getDialect,\r\n getCloudflareD1Binding,\r\n getDatabaseUrl,\r\n getDatabaseAuthToken,\r\n isLocalSqliteUrl,\r\n isPgliteUrl,\r\n isConnectionError,\r\n getPgliteClient,\r\n loadPgliteDrizzle,\r\n prepareLocalSqliteUrl,\r\n sqliteFilenameFromUrl,\r\n pgPoolOptions,\r\n neonPoolMax,\r\n attachNeonPoolErrorLogger,\r\n withDbTimeout,\r\n retryOnConnectionError,\r\n dbOpTimeoutMs,\r\n} from \"./client.js\";\r\nimport { isCloudflareRuntime } from \"../shared/runtime.js\";\r\n\r\n// Lazy driver loaders — cached promises so dynamic import only runs once.\r\nlet _pgDrizzle: Promise<{ drizzle: any; postgres: any }> | undefined;\r\nfunction getPgDrizzle() {\r\n if (!_pgDrizzle) {\r\n _pgDrizzle = Promise.all([\r\n import(\"drizzle-orm/postgres-js\"),\r\n import(\"postgres\"),\r\n ]).then(([drizzleMod, pgMod]) => ({\r\n drizzle: drizzleMod.drizzle,\r\n postgres: pgMod.default,\r\n }));\r\n }\r\n return _pgDrizzle;\r\n}\r\n\r\nlet _neonServerlessDrizzle:\r\n | Promise<{ drizzle: any; Pool: any; neonConfig: any }>\r\n | undefined;\r\nfunction getNeonServerlessDrizzle() {\r\n if (!_neonServerlessDrizzle) {\r\n _neonServerlessDrizzle = Promise.all([\r\n import(\"drizzle-orm/neon-serverless\"),\r\n import(\"@neondatabase/serverless\"),\r\n ]).then(([drizzleMod, neonMod]) => ({\r\n drizzle: drizzleMod.drizzle,\r\n Pool: neonMod.Pool,\r\n neonConfig: neonMod.neonConfig,\r\n }));\r\n }\r\n return _neonServerlessDrizzle;\r\n}\r\n\r\n/**\r\n * Returns true when a SQL string starts with a SELECT-class verb.\r\n * Used by the Neon resilience wrapper to decide retry safety:\r\n * - reads (SELECT) → retryable on any connection-class error\r\n * - writes (INSERT/UPDATE/DELETE/…) → only retryable on errors that\r\n * provably occurred BEFORE the statement was sent (e.g. an acquire /\r\n * connect timeout). Post-send write failures must propagate to the caller\r\n * to avoid double-execution.\r\n */\r\nexport function isSqlRead(sql: string): boolean {\r\n return /^\\s*(SELECT|WITH\\s)/i.test(sql);\r\n}\r\n\r\n/**\r\n * Wraps a @neondatabase/serverless Pool so every query goes through\r\n * the same withDbTimeout + retryOnConnectionError resilience that the\r\n * raw DbExec path in client.ts uses. This protects Drizzle queries\r\n * (which bypass DbExec) from the frozen-WebSocket failure mode documented\r\n * in client.ts (~lines 378–408).\r\n *\r\n * Retry-safety rule (prevents double-execution on writes):\r\n * - Reads (SELECT / WITH …): retry freely on any connection-class error.\r\n * - Writes: only retry when the error occurred during connection acquire\r\n * (i.e. withDbTimeout \"connect\" timed out before the statement was ever\r\n * sent). Post-send failures on writes are rethrown immediately.\r\n *\r\n * Transactions: we do NOT wrap individual queries inside a drizzle\r\n * transaction — drizzle-neon-serverless manages the session itself, so\r\n * interposing a per-query client acquire/release would break the sticky\r\n * connection the transaction needs. The pool-level error logger still fires\r\n * on idle-client drops inside transactions.\r\n */\r\nexport function buildResilientNeonPool(pool: {\r\n connect(): Promise<any>;\r\n query(\r\n sql: string,\r\n args?: any[],\r\n ): Promise<{ rows: unknown[]; rowCount?: number }>;\r\n end(): Promise<void>;\r\n on(event: string, listener: (...args: any[]) => void): unknown;\r\n}): typeof pool {\r\n // Preserve all original pool methods and properties; only override `connect`\r\n // and `query` at the Pool level (used by drizzle's neon-serverless adapter\r\n // when it calls pool.query() directly, e.g. outside a transaction).\r\n const resilientQuery = async (\r\n sql: string,\r\n args?: any[],\r\n ): Promise<{ rows: unknown[]; rowCount?: number }> => {\r\n const isRead = isSqlRead(sql);\r\n\r\n const runAttempt = async (): Promise<{\r\n rows: unknown[];\r\n rowCount?: number;\r\n }> => {\r\n // Bound the pool.connect() acquire — a frozen Neon WebSocket stalls here\r\n // before the query ever starts, so a query-level timeout alone won't help.\r\n let acquireTimedOut = false;\r\n const client = await withDbTimeout(\r\n \"connect\",\r\n () =>\r\n pool.connect().then((c: any) => {\r\n // If we already gave up on this slot, immediately release it so\r\n // the scarce pool connection isn't leaked.\r\n if (acquireTimedOut) c.release();\r\n return c;\r\n }),\r\n dbOpTimeoutMs(),\r\n () => {\r\n acquireTimedOut = true;\r\n },\r\n );\r\n\r\n let released = false;\r\n const releaseClient = (err?: Error | boolean) => {\r\n if (released) return;\r\n released = true;\r\n client.release(err);\r\n };\r\n\r\n try {\r\n const result = await withDbTimeout(\r\n \"query\",\r\n () =>\r\n client.query(sql, args ?? []) as Promise<{\r\n rows: unknown[];\r\n rowCount?: number;\r\n }>,\r\n dbOpTimeoutMs(),\r\n () => releaseClient(true),\r\n );\r\n releaseClient();\r\n return result;\r\n } catch (err) {\r\n releaseClient(isConnectionError(err) ? true : undefined);\r\n throw err;\r\n }\r\n };\r\n\r\n if (isRead) {\r\n // Reads: retry on any connection-class error (safe — no side effects).\r\n return retryOnConnectionError(runAttempt);\r\n }\r\n\r\n // Writes: attempt once. If the acquire itself times out (error occurs\r\n // before the statement was sent), that produces a CONNECT_TIMEOUT which\r\n // isConnectionError() recognises → retry is safe. Any error that surfaces\r\n // AFTER the statement was sent must propagate immediately to avoid\r\n // double-execution.\r\n try {\r\n return await runAttempt();\r\n } catch (err) {\r\n // acquire-timeout fires before the statement → safe to retry once.\r\n if (isConnectionError(err) && (err as any)?.code === \"CONNECT_TIMEOUT\") {\r\n return runAttempt();\r\n }\r\n throw err;\r\n }\r\n };\r\n\r\n // Return a proxy so every pool property/method is forwarded as-is, but\r\n // pool.query() goes through the resilient wrapper. drizzle-neon-serverless\r\n // calls pool.connect() for transactions and pool.query() for simple queries.\r\n return new Proxy(pool, {\r\n get(target, prop) {\r\n if (prop === \"query\") return resilientQuery;\r\n const val = (target as any)[prop];\r\n return typeof val === \"function\" ? val.bind(target) : val;\r\n },\r\n });\r\n}\r\n\r\n/**\r\n * Wraps a postgres.js client so Drizzle queries on the non-Neon Postgres\r\n * path get the same withDbTimeout + retryOnConnectionError protection as\r\n * every other Postgres path (raw DbExec postgres.js, raw DbExec Neon, and\r\n * the Drizzle Neon pool above). Without this, one hung query on a BYO\r\n * Postgres deployment stalls its request forever.\r\n *\r\n * Drizzle's postgres-js session only calls `client.unsafe(query, params)` —\r\n * awaited directly for row-object results or via `.values()` for row-array\r\n * results — plus `client.begin(...)` for transactions. We interpose on\r\n * `unsafe` with a lazy thenable that re-issues the query per retry attempt,\r\n * and leave transactions unwrapped (same rule as the Neon wrapper: the\r\n * driver manages the sticky connection inside `begin`).\r\n *\r\n * Retry-safety mirrors buildResilientNeonPool: reads retry freely on\r\n * connection-class errors; writes retry only on CONNECT_TIMEOUT (postgres.js\r\n * raises it before the statement is ever sent), so writes can't\r\n * double-execute.\r\n */\r\nexport function buildResilientPostgresJsClient<\r\n T extends {\r\n unsafe(query: string, params?: any[], options?: any): any;\r\n },\r\n>(client: T): T {\r\n const wrapUnsafe = (query: string, params?: any[], options?: any) => {\r\n const isRead = isSqlRead(query);\r\n\r\n const runAttempt = (mode: \"rows\" | \"values\") => async (): Promise<any> => {\r\n const pending = client.unsafe(query, params, options);\r\n return withDbTimeout(\r\n \"query\",\r\n async () => (mode === \"values\" ? pending.values() : pending),\r\n dbOpTimeoutMs(),\r\n () => {\r\n // Best-effort cancel so the timed-out statement doesn't keep\r\n // occupying one of the (small, serverless-capped) pool slots.\r\n try {\r\n pending.cancel?.();\r\n } catch {\r\n // ignore — cancellation is advisory\r\n }\r\n },\r\n );\r\n };\r\n\r\n const execute = async (mode: \"rows\" | \"values\"): Promise<any> => {\r\n if (isRead) return retryOnConnectionError(runAttempt(mode));\r\n try {\r\n return await runAttempt(mode)();\r\n } catch (err) {\r\n // Connect timeout fires before the statement is sent → one retry is\r\n // safe even for writes.\r\n if (\r\n isConnectionError(err) &&\r\n (err as any)?.code === \"CONNECT_TIMEOUT\"\r\n ) {\r\n return runAttempt(mode)();\r\n }\r\n throw err;\r\n }\r\n };\r\n\r\n // Lazy thenable mirroring the slice of postgres.js's PendingQuery\r\n // surface that Drizzle uses: `await q` or `await q.values()`.\r\n return {\r\n then: (onFulfilled?: any, onRejected?: any) =>\r\n execute(\"rows\").then(onFulfilled, onRejected),\r\n catch: (onRejected?: any) => execute(\"rows\").catch(onRejected),\r\n finally: (onFinally?: any) => execute(\"rows\").finally(onFinally),\r\n values: () => execute(\"values\"),\r\n };\r\n };\r\n\r\n return new Proxy(client as any, {\r\n get(target, prop) {\r\n if (prop === \"unsafe\") return wrapUnsafe;\r\n const val = target[prop];\r\n return typeof val === \"function\" ? val.bind(target) : val;\r\n },\r\n }) as T;\r\n}\r\n\r\n/**\r\n * Neon's pooler endpoints cold-start in 5–10s. Serverless environments\r\n * (Netlify Functions, Vercel Edge, CF Workers) have short cold-start\r\n * budgets of their own, and `postgres-js` opens a raw TCP connection on\r\n * port 5432 that can't negotiate around Neon's wake-up window — every\r\n * request after an idle period 502s. `@neondatabase/serverless` rides\r\n * over WebSockets (HTTP/443 upgrade) and handles Neon wake-up\r\n * transparently, supports transactions, and works in every serverless\r\n * runtime we deploy to, so we prefer it whenever the URL points at Neon.\r\n */\r\nexport function isNeonUrl(url: string): boolean {\r\n // Must match neon.tech followed by port/path/query/end — include `?` so\r\n // URLs like `postgres://…@ep.neon.tech?sslmode=require` (no explicit port\r\n // or path) still route through the serverless driver.\r\n return /\\.neon\\.tech([:/?]|$)/.test(url);\r\n}\r\n\r\nlet _libsqlWebDrizzle: Promise<{ drizzle: any }> | undefined;\r\nfunction getLibsqlWebDrizzle() {\r\n if (!_libsqlWebDrizzle) {\r\n _libsqlWebDrizzle = import(\"drizzle-orm/libsql/web\").then((mod) => ({\r\n drizzle: mod.drizzle,\r\n }));\r\n }\r\n return _libsqlWebDrizzle;\r\n}\r\n\r\nlet _betterSqliteDrizzle: Promise<{ drizzle: any; Database: any }> | undefined;\r\nfunction getBetterSqliteDrizzle() {\r\n if (!_betterSqliteDrizzle) {\r\n _betterSqliteDrizzle = Promise.all([\r\n import(\"drizzle-orm/better-sqlite3\"),\r\n import(\"better-sqlite3\"),\r\n ]).then(([drizzleMod, sqliteMod]) => ({\r\n drizzle: drizzleMod.drizzle,\r\n Database: sqliteMod.default,\r\n }));\r\n }\r\n return _betterSqliteDrizzle;\r\n}\r\n\r\n/**\r\n * Patch a drizzle-orm/better-sqlite3 instance so that db.transaction(async …)\r\n * works. The native better-sqlite3 Transaction wrapper is sync-only — passing\r\n * an async callback throws \"Transaction function cannot return a promise\".\r\n *\r\n * This wrapper bypasses the native path by issuing raw SQL control statements\r\n * on the single better-sqlite3 connection, which is safe because:\r\n * - better-sqlite3 is single-connection (no concurrency inside one process)\r\n * - the framework serialises all async work through one Database instance\r\n *\r\n * Nesting: if a transaction is already open (sqlite.inTransaction === true),\r\n * SAVEPOINT / RELEASE / ROLLBACK TO is used instead of BEGIN / COMMIT /\r\n * ROLLBACK, matching drizzle's own BetterSQLiteTransaction.transaction().\r\n *\r\n * The patched transaction also patches the tx object it passes to the callback\r\n * so that nested async calls (tx.transaction(async …)) work recursively.\r\n */\r\n/** @internal exported for the async-tx concurrency spec */\r\nexport function patchBetterSqliteTransactions<\r\n DB extends { transaction: (...args: any[]) => any; session: any },\r\n>(db: DB, sqlite: { inTransaction: boolean; exec: (sql: string) => void }): DB {\r\n let savepointSeq = 0;\r\n // Concurrent TOP-LEVEL async transactions on the single better-sqlite3\r\n // connection must not interleave: a second transaction starting while the\r\n // first is open would see `inTransaction` and open a savepoint INSIDE the\r\n // first transaction, which then commits out from under it (\"no such\r\n // savepoint\"). Serialize top-level transactions through a promise chain;\r\n // genuine same-task nesting (tx.transaction or db.transaction inside an\r\n // open callback) is detected via AsyncLocalStorage and keeps the direct\r\n // savepoint path so it cannot deadlock on the queue.\r\n const txContext = new AsyncLocalStorage<boolean>();\r\n let txChain: Promise<unknown> = Promise.resolve();\r\n\r\n function makeAsyncTransaction(\r\n originalTransaction: (...args: any[]) => any,\r\n ): (...args: any[]) => Promise<unknown> {\r\n async function runTransactionBody(\r\n cb: (tx: unknown) => unknown,\r\n ): Promise<unknown> {\r\n // Extract the drizzle tx proxy synchronously — call the original with a\r\n // stub that captures the tx arg then immediately throws a sentinel so\r\n // better-sqlite3's native wrapper rolls back the stub and re-throws.\r\n // The sentinel is caught here and never propagates further.\r\n let capturedTx: unknown;\r\n try {\r\n originalTransaction((tx: unknown) => {\r\n capturedTx = tx;\r\n throw _EXTRACT_TX;\r\n });\r\n } catch (e) {\r\n if (e !== _EXTRACT_TX) throw e;\r\n }\r\n\r\n // Recursively patch the nested tx so tx.transaction(async …) also works.\r\n const tx = capturedTx as { transaction: (...a: any[]) => any };\r\n if (tx && typeof tx.transaction === \"function\") {\r\n tx.transaction = makeAsyncTransaction(tx.transaction.bind(tx));\r\n }\r\n\r\n const nested = sqlite.inTransaction;\r\n if (nested) {\r\n const sp = `sp_async_${++savepointSeq}`;\r\n sqlite.exec(`SAVEPOINT ${sp}`);\r\n let released = false;\r\n try {\r\n const result = await cb(tx);\r\n sqlite.exec(`RELEASE SAVEPOINT ${sp}`);\r\n released = true;\r\n return result;\r\n } catch (err) {\r\n if (!released) {\r\n try {\r\n sqlite.exec(`ROLLBACK TO SAVEPOINT ${sp}`);\r\n sqlite.exec(`RELEASE SAVEPOINT ${sp}`);\r\n } catch {\r\n /* ignore: connection may already be in an error state */\r\n }\r\n }\r\n throw err;\r\n }\r\n }\r\n\r\n // Top-level: BEGIN IMMEDIATE … COMMIT / ROLLBACK.\r\n sqlite.exec(\"BEGIN IMMEDIATE\");\r\n let committed = false;\r\n try {\r\n const result = await cb(tx);\r\n sqlite.exec(\"COMMIT\");\r\n committed = true;\r\n return result;\r\n } catch (err) {\r\n if (!committed) {\r\n try {\r\n sqlite.exec(\"ROLLBACK\");\r\n } catch {\r\n /* swallow: connection may already be unusable */\r\n }\r\n }\r\n throw err;\r\n }\r\n }\r\n\r\n return function asyncTransaction(\r\n cb: (tx: unknown) => unknown,\r\n ): Promise<unknown> {\r\n if (txContext.getStore()) {\r\n // Same-task nesting: run directly (savepoint path inside the open\r\n // transaction). Queueing here would deadlock behind the outer tx.\r\n return runTransactionBody(cb);\r\n }\r\n const run = () => txContext.run(true, () => runTransactionBody(cb));\r\n const next = txChain.then(run, run);\r\n txChain = next.then(\r\n () => undefined,\r\n () => undefined,\r\n );\r\n return next;\r\n };\r\n }\r\n\r\n db.transaction = makeAsyncTransaction(db.transaction.bind(db));\r\n return db;\r\n}\r\n\r\n/** Sentinel thrown inside the tx-extraction stub — never escapes the catch. */\r\nconst _EXTRACT_TX = Symbol(\"extract-tx\");\r\n\r\nexport function createGetDb<T extends Record<string, unknown>>(schema: T) {\r\n let _db: any;\r\n let _dbReady: Promise<any> | undefined;\r\n\r\n function startInit(): Promise<any> {\r\n if (_dbReady) return _dbReady;\r\n\r\n const url = getDatabaseUrl(\"file:./data/app.db\");\r\n const dialect = getDialect();\r\n\r\n // D1 only if dialect detected it (DATABASE_URL takes priority)\r\n if (dialect === \"d1\") {\r\n const d1 = getCloudflareD1Binding() as\r\n | Parameters<typeof drizzleD1>[0]\r\n | undefined;\r\n if (d1) {\r\n _db = drizzleD1(d1, { schema }) as unknown as LibSQLDatabase<T>;\r\n _dbReady = Promise.resolve(_db);\r\n return _dbReady;\r\n }\r\n }\r\n\r\n if (isPgliteUrl(url)) {\r\n _dbReady = loadPgliteDrizzle().then(async ({ drizzle }) => {\r\n const client = await getPgliteClient(url);\r\n _db = drizzle({ client, schema });\r\n });\r\n return _dbReady;\r\n }\r\n\r\n if (dialect === \"postgres\") {\r\n if (isNeonUrl(url)) {\r\n _dbReady = getNeonServerlessDrizzle().then(\r\n ({ drizzle, Pool, neonConfig }) => {\r\n // Cloudflare Workers (workerd) forbids reusing I/O objects across\r\n // requests — a WebSocket client cached in the pool by request A and\r\n // handed to request B throws \"Cannot perform I/O on behalf of a\r\n // different request\" and hangs the worker. Route plain queries over\r\n // Neon's stateless HTTP transport (poolQueryViaFetch) and cap each\r\n // WebSocket client (used for transactions) to a single use so it is\r\n // never reused across requests.\r\n const cfWorker = isCloudflareRuntime();\r\n if (cfWorker) neonConfig.poolQueryViaFetch = true;\r\n const rawPool = new Pool({\r\n connectionString: url,\r\n max: neonPoolMax(),\r\n ...(cfWorker ? { maxUses: 1 } : {}),\r\n });\r\n attachNeonPoolErrorLogger(rawPool);\r\n // Wrap the pool with the resilience layer so Drizzle queries get the\r\n // same withDbTimeout + retryOnConnectionError protection as the raw\r\n // DbExec path in client.ts. Reads retry freely; writes only retry on\r\n // acquire-timeout (pre-send) errors to avoid double-execution.\r\n const pool = buildResilientNeonPool(rawPool);\r\n _db = drizzle(pool, { schema });\r\n },\r\n );\r\n } else {\r\n _dbReady = getPgDrizzle().then(({ drizzle, postgres }) => {\r\n // pgPoolOptions caps the pool to a small size on serverless so\r\n // concurrent frozen instances don't exhaust Neon/Postgres'\r\n // connection limit (\"Max client connections reached\").\r\n const client = postgres(url, pgPoolOptions(url));\r\n _db = drizzle(buildResilientPostgresJsClient(client), { schema });\r\n });\r\n }\r\n } else if (isLocalSqliteUrl(url)) {\r\n _dbReady = Promise.all([\r\n prepareLocalSqliteUrl(url.startsWith(\"file:\") ? url : `file:${url}`),\r\n getBetterSqliteDrizzle(),\r\n ]).then(([sqliteUrl, { drizzle, Database }]) => {\r\n const sqlite = new Database(sqliteFilenameFromUrl(sqliteUrl));\r\n // Wait up to 10s for a concurrent writer instead of failing fast\r\n // with SQLITE_BUSY — mirrors the raw DbExec SQLite path in client.ts.\r\n sqlite.pragma(\"busy_timeout = 10000\");\r\n sqlite.pragma(\"journal_mode = WAL\");\r\n const db = drizzle(sqlite, { schema });\r\n _db = patchBetterSqliteTransactions(db, sqlite);\r\n });\r\n } else {\r\n _dbReady = getLibsqlWebDrizzle().then(({ drizzle }) => {\r\n _db = drizzle({\r\n connection: { url, authToken: getDatabaseAuthToken() },\r\n schema,\r\n });\r\n });\r\n }\r\n return _dbReady;\r\n }\r\n\r\n /**\r\n * Create a lazy proxy that records property accesses and method calls,\r\n * then replays them on the real DB once init completes. Supports\r\n * Drizzle's chained API: db.select().from(table).where(...).\r\n *\r\n * When `.then()` is called (i.e. the chain is awaited), the proxy\r\n * awaits _dbReady and replays the recorded chain on the real _db.\r\n */\r\n function createLazyProxy(\r\n ready: Promise<any>,\r\n chain: Array<{ prop: string | symbol; args?: any[] }>,\r\n ): any {\r\n return new Proxy(function () {} as any, {\r\n get(_target, prop) {\r\n // When awaited, replay the chain on the real db\r\n if (prop === \"then\" || prop === \"catch\" || prop === \"finally\") {\r\n const promise = ready.then(() => {\r\n let result: any = _db;\r\n for (const step of chain) {\r\n const val = result[step.prop];\r\n result =\r\n typeof val === \"function\" ? val.apply(result, step.args) : val;\r\n }\r\n return result;\r\n });\r\n return (promise as any)[prop].bind(promise);\r\n }\r\n // Symbol.toStringTag, Symbol.iterator, etc. — return another proxy\r\n // Property access (e.g. db.query) — record and return another proxy\r\n return createLazyProxy(ready, [...chain, { prop }]);\r\n },\r\n apply(_target, _thisArg, args) {\r\n // Method call (e.g. .from(table)) — record args and return another proxy\r\n if (chain.length === 0) return createLazyProxy(ready, []);\r\n const last = chain[chain.length - 1];\r\n const newChain = chain.slice(0, -1);\r\n newChain.push({ prop: last.prop, args });\r\n return createLazyProxy(ready, newChain);\r\n },\r\n });\r\n }\r\n\r\n /**\r\n * Get the Drizzle DB instance. Kicks off lazy init on first call.\r\n * If the async init hasn't completed yet, returns a lazy Proxy that\r\n * records the Drizzle chain (select/from/where/etc.) and replays it\r\n * once the DB driver finishes loading. Since callers always `await`\r\n * the final result, the proxy is transparent.\r\n */\r\n function getDb(): LibSQLDatabase<T> {\r\n if (_db) return _db;\r\n startInit();\r\n if (_db) return _db;\r\n\r\n return createLazyProxy(_dbReady!, []) as LibSQLDatabase<T>;\r\n }\r\n\r\n return getDb;\r\n}\r\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"build.d.ts","sourceRoot":"","sources":["../../src/deploy/build.ts"],"names":[],"mappings":";AAEA;;;;;;;;;;;;GAYG;AAmCH,OAAO,EAML,KAAK,eAAe,EACpB,KAAK,gBAAgB,EACtB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAEL,KAAK,oBAAoB,EAC1B,MAAM,qBAAqB,CAAC;AAI7B,eAA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AK,OAAO,CAAC,IAAI,CAAC,CAAC;IAChD,UAAU,EAAE,CAAC,KAAK,EAAE,GAAG,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;CAC3C;AAED,MAAM,WAAW,yBAAyB;IACxC,KAAK,EAAE,GAAG,CAAC;IACX,KAAK,EAAE,eAAe,CAAC;IACvB,SAAS,EAAE,MAAM,CAAC;IAClB,eAAe,EAAE,MAAM,GAAG,SAAS,CAAC;IACpC,WAAW,EAAE,MAAM,CAAC;IACpB,GAAG,EAAE,MAAM,CAAC;CACb;AAED;;;;;;;;;;;GAWG;AACH,wBAAsB,qBAAqB,CACzC,IAAI,EAAE,yBAAyB,GAC9B,OAAO,CAAC,IAAI,CAAC,CA+Bf;AAkBD;;;;;;;;;;GAUG;AACH,eAAO,MAAM,iCAAiC,YAAI,KAAK,CAAU,CAAC;AAElE;;;GAGG;AACH,wBAAgB,yBAAyB,CACvC,YAAY,EAAE,MAAM,GACnB,IAAI,GAAG,SAAS,MAAM,EAAE,CAK1B"}
|
package/dist/deploy/build.js
CHANGED
|
@@ -82,6 +82,16 @@ export const CLOUDFLARE_WORKER_STUB_MODULES = {
|
|
|
82
82
|
"",
|
|
83
83
|
].join("\n"),
|
|
84
84
|
"better-sqlite3": "export default {}; export const Database = class {}; export const watch = () => ({ close() {} });\n",
|
|
85
|
+
// sharp loads its native binary (@img/sharp-<platform>) at require time and
|
|
86
|
+
// throws "Could not load the sharp module using the linux- runtime" at
|
|
87
|
+
// worker module init. Stub it with a callable that throws at call time —
|
|
88
|
+
// image processing can't run on workerd regardless.
|
|
89
|
+
sharp: [
|
|
90
|
+
"const unavailable = () => { throw new Error('sharp unavailable in Cloudflare Pages worker'); };",
|
|
91
|
+
"const sharp = new Proxy(unavailable, { get: (_t, prop) => (prop === 'default' ? sharp : unavailable), apply: unavailable });",
|
|
92
|
+
"export default sharp;",
|
|
93
|
+
"",
|
|
94
|
+
].join("\n"),
|
|
85
95
|
"node-pty": "export default {}; export const watch = () => ({ close() {} });\n",
|
|
86
96
|
chokidar: "export default {}; export const watch = () => ({ close() {} });\n",
|
|
87
97
|
fsevents: "export default {}; export const watch = () => ({ close() {} });\n",
|
|
@@ -215,11 +225,18 @@ function cloudflareNodeBuiltinStubSource(moduleName, namedExports, overrides = [
|
|
|
215
225
|
const exports = Array.from(new Set(namedExports))
|
|
216
226
|
.filter((name) => !overridden.has(name))
|
|
217
227
|
.sort();
|
|
228
|
+
// The default export must expose the SAME members as the named exports —
|
|
229
|
+
// including functional overrides like os.tmpdir() — because most consumers
|
|
230
|
+
// use the default import (`import os from "os"; os.tmpdir()`). A bare
|
|
231
|
+
// throwing proxy here killed workers at module init whenever a dependency
|
|
232
|
+
// called an overridden member through the default export.
|
|
233
|
+
const allNames = Array.from(new Set([...overridden, ...exports])).sort();
|
|
218
234
|
return [
|
|
219
235
|
`const unavailable = (name) => (..._args) => { throw new Error(name + " is unavailable in Cloudflare Pages workers"); };`,
|
|
220
|
-
`const proxy = new Proxy({}, { get(_target, prop) { return unavailable("${moduleName}." + String(prop)); } });`,
|
|
221
236
|
...overrides,
|
|
222
237
|
...exports.map((name) => `export const ${name} = unavailable("${moduleName}.${name}");`),
|
|
238
|
+
`const __members = { ${allNames.join(", ")} };`,
|
|
239
|
+
`const proxy = new Proxy(__members, { get(target, prop) { return prop in target ? target[prop] : unavailable("${moduleName}." + String(prop)); } });`,
|
|
223
240
|
"export default proxy;",
|
|
224
241
|
"",
|
|
225
242
|
].join("\n");
|
|
@@ -1542,6 +1559,12 @@ async function buildCloudflarePages() {
|
|
|
1542
1559
|
// Matches both `from "module"` and `from "node:module"` — with the node:
|
|
1543
1560
|
// prefix preserved (for nodejs_compat_v2), the latter is what esbuild now emits.
|
|
1544
1561
|
code = code.replace(/\bimport\s*\{\s*createRequire\s+as\s+([\w$]+)\s*\}\s*from\s*["'](?:node:)?module["']\s*;/g, "var $1 = function() { return typeof require !== 'undefined' ? require : function(m) { throw new Error('require not supported: ' + m); }; };");
|
|
1562
|
+
// Patch remaining import.meta.url occurrences — when wrangler/Pages
|
|
1563
|
+
// re-bundles the worker, inner modules get an emptied import.meta, so
|
|
1564
|
+
// fileURLToPath(import.meta.url) throws at module init ("path" argument
|
|
1565
|
+
// must be string, received undefined). Same treatment as the Vite
|
|
1566
|
+
// server-build path: replace with a stable synthetic file URL.
|
|
1567
|
+
code = code.replace(/\bimport\.meta\.url\b/g, '"file:///worker.mjs"');
|
|
1545
1568
|
// Patch setInterval/setTimeout at module scope — CF Workers disallows timers in global scope.
|
|
1546
1569
|
// Some dependencies (e.g. Anthropic SDK rate limiter) call setInterval at module init.
|
|
1547
1570
|
// With code splitting, chunks evaluate before the entry, so the shim must be in every file.
|