cloudflare-next-intl 0.9.62 → 0.9.63

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.
Files changed (83) hide show
  1. package/bin/check_layout_queries.mjs +0 -0
  2. package/bin/db_codegen.mjs +12 -242
  3. package/bin/db_install_exec.mjs +11 -14
  4. package/dist/src/db/connection.d.ts +2 -13
  5. package/dist/src/db/connection.js +1 -100
  6. package/dist/src/db/context.d.ts +3 -10
  7. package/dist/src/db/context.js +6 -256
  8. package/dist/src/db/eslint_config.d.ts +1 -12
  9. package/dist/src/db/eslint_config.js +1 -20
  10. package/dist/src/db/helpers.d.ts +1 -23
  11. package/dist/src/db/helpers.js +1 -82
  12. package/dist/src/db/resolve_db_config.d.ts +1 -2
  13. package/dist/src/db/resolve_db_config.js +23 -4
  14. package/dist/src/db/schema.d.ts +1 -3
  15. package/dist/src/db/schema.js +1 -3
  16. package/dist/src/db/testing.d.ts +1 -58
  17. package/dist/src/db/testing.js +1 -80
  18. package/dist/src/error_handling/default_ignored_console_errors.js +5 -0
  19. package/dist/src/error_handling/index.d.ts +1 -1
  20. package/dist/src/error_handling/index.js +1 -1
  21. package/dist/src/error_handling/install_console_error_override.js +8 -6
  22. package/dist/src/error_handling/install_global_error_override.d.ts +1 -1
  23. package/dist/src/error_handling/install_global_error_override.js +4 -16
  24. package/dist/src/error_handling/is_stale_deploy_error.js +7 -17
  25. package/dist/src/error_handling/match_error_message.d.ts +2 -0
  26. package/dist/src/error_handling/match_error_message.js +10 -0
  27. package/dist/src/error_handling/merge_report_params.d.ts +2 -0
  28. package/dist/src/error_handling/merge_report_params.js +9 -0
  29. package/dist/src/error_handling/report_client_error.d.ts +3 -0
  30. package/dist/src/error_handling/report_client_error.js +15 -0
  31. package/dist/src/error_handling/report_client_error_action.d.ts +1 -1
  32. package/dist/src/error_handling/report_client_error_core.js +2 -7
  33. package/dist/src/error_handling/stringify_unknown.d.ts +4 -0
  34. package/dist/src/error_handling/stringify_unknown.js +11 -2
  35. package/dist/src/error_handling/use_stale_deploy_recovery.js +15 -3
  36. package/dist/src/errors_board/server/errors_repository.js +4 -2
  37. package/dist/src/types/types.d.ts +2 -20
  38. package/package.json +5 -10
  39. package/bin/ddl_order.mjs +0 -46
  40. package/bin/ephemeral_pg.mjs +0 -164
  41. package/bin/install_exec_step.mjs +0 -39
  42. package/dist/src/db/access_token.d.ts +0 -2
  43. package/dist/src/db/access_token.js +0 -18
  44. package/dist/src/db/codegen_paths.d.ts +0 -25
  45. package/dist/src/db/codegen_paths.js +0 -63
  46. package/dist/src/db/encode_param.d.ts +0 -1
  47. package/dist/src/db/encode_param.js +0 -59
  48. package/dist/src/db/inline_params.d.ts +0 -1
  49. package/dist/src/db/inline_params.js +0 -131
  50. package/dist/src/db/install_exec.d.ts +0 -10
  51. package/dist/src/db/install_exec.js +0 -30
  52. package/dist/src/db/parse_composite.d.ts +0 -1
  53. package/dist/src/db/parse_composite.js +0 -59
  54. package/dist/src/db/parse_statement.d.ts +0 -54
  55. package/dist/src/db/parse_statement.js +0 -386
  56. package/dist/src/db/parse_where.d.ts +0 -41
  57. package/dist/src/db/parse_where.js +0 -227
  58. package/dist/src/db/require_config.d.ts +0 -2
  59. package/dist/src/db/require_config.js +0 -7
  60. package/dist/src/db/resolve_config_value.d.ts +0 -2
  61. package/dist/src/db/resolve_config_value.js +0 -3
  62. package/dist/src/db/resolve_hyperdrive_connection_string.d.ts +0 -5
  63. package/dist/src/db/resolve_hyperdrive_connection_string.js +0 -11
  64. package/dist/src/db/resolve_mode.d.ts +0 -12
  65. package/dist/src/db/resolve_mode.js +0 -18
  66. package/dist/src/db/resolve_raw_sql.d.ts +0 -8
  67. package/dist/src/db/resolve_raw_sql.js +0 -39
  68. package/dist/src/db/rest_client.d.ts +0 -35
  69. package/dist/src/db/rest_client.js +0 -11
  70. package/dist/src/db/rest_execute.d.ts +0 -6
  71. package/dist/src/db/rest_execute.js +0 -94
  72. package/dist/src/db/rest_filters.d.ts +0 -32
  73. package/dist/src/db/rest_filters.js +0 -107
  74. package/dist/src/db/sql_tokens.d.ts +0 -20
  75. package/dist/src/db/sql_tokens.js +0 -192
  76. package/dist/src/db/supabase_config.d.ts +0 -6
  77. package/dist/src/db/supabase_config.js +0 -14
  78. package/dist/src/db/supabase_transport.d.ts +0 -16
  79. package/dist/src/db/supabase_transport.js +0 -62
  80. package/dist/src/db/transaction_batch.d.ts +0 -7
  81. package/dist/src/db/transaction_batch.js +0 -16
  82. package/dist/src/db/unsupported_sql.d.ts +0 -4
  83. package/dist/src/db/unsupported_sql.js +0 -7
File without changes
@@ -1,243 +1,13 @@
1
1
  #!/usr/bin/env node
2
- // Regenerates Drizzle models by introspecting a live Postgres with drizzle-kit.
3
- // Usage: cfni-db-codegen [--check] [--ddl-dir=…] [--out-dir=…] [--out-file=…] [--db-url=…] [--drizzle-config=…]
4
- // [--rpc-dir=…] [--rpc-file-name=…] [--tests-dir=…] [--tests-file-name=…] [--force] [--skip-exec]
5
- //
6
- // --rpc-file-name/--tests-file-name (also CFNI_DB_RPC_FILE_NAME/
7
- // CFNI_DB_TESTS_FILE_NAME) rename the installed cfni_exec.sql/its pgTAP test
8
- // file in the consuming project e.g. if a project prefers a name that
9
- // reflects the file now ships both `cfni_exec` and `cfni_exec_batch`. Default
10
- // to `cfni_exec.sql` for both, unchanged from before.
11
- //
12
- // --out-dir may be repeated, or given a comma-separated list, to generate the
13
- // same schema into several projects at once (CFNI_DB_OUT_DIR accepts a
14
- // comma-separated list too).
15
- //
16
- // Prefers the embedded-postgres library by default (zero setup, no Docker needed)
17
- // to introspect the DDL in --ddl-dir. If the user explicitly sets --db-url or
18
- // CODEGEN_DATABASE_URL, it uses that URL; if the explicit URL is unreachable,
19
- // it warns and falls back to embedded-postgres.
20
- // CODEGEN_CONNECT_TIMEOUT_MS overrides the 5s default reachability-check
21
- // timeout — raise it for a slow/cold-starting remote or serverless target.
22
- //
23
- // After a successful (non-`--check`) run, also installs `cfni_exec.sql` (and
24
- // its pgTAP test file) into `--rpc-dir`/`--tests-dir` (default siblings of
25
- // `--ddl-dir`, e.g. `supabase/rpc`/`supabase/tests`) — but only when the
26
- // project's `db.supabase.rawSql` isn't explicitly `false` (read from
27
- // `next.config.*`'s `@intl-config` alias; a warning is printed if it can't
28
- // be determined). An existing, differing file is left alone unless
29
- // `--force`/CFNI_DB_FORCE_EXEC=true is set. Pass `--skip-exec`/
30
- // CFNI_DB_SKIP_EXEC=true to turn this step off entirely, or use the
31
- // standalone `cfni-db-install-exec` command to run only this step.
32
- import { createHash } from 'node:crypto';
33
- import { execFileSync } from 'node:child_process';
34
- import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
35
- import { createRequire } from 'node:module';
36
- import { dirname, join, relative } from 'node:path';
37
- import { Client } from 'pg';
38
- import resolveCodegenPaths from '../dist/src/db/codegen_paths.js';
39
- import { runInstallExecStep } from './install_exec_step.mjs';
40
- import { startEphemeralPostgres } from './ephemeral_pg.mjs';
41
- import { orderedSqlFiles } from './ddl_order.mjs';
42
-
43
- const paths = resolveCodegenPaths(process.argv.slice(2), process.env, process.cwd());
44
-
45
- async function isReachable(url) {
46
- const client = new Client({ connectionString: url, connectionTimeoutMillis: paths.timeoutMs });
47
- try {
48
- await client.connect();
49
- await client.end();
50
- return true;
51
- } catch {
52
- await client.end().catch(() => { /* already failed to connect */ });
53
- return false;
54
- }
55
- }
56
-
57
- function failUnreachable(target) {
58
- console.error(`❌ Could not reach Postgres at ${target} and embedded-postgres could not be started.`);
59
- console.error("\n drizzle-kit pull needs a Postgres to introspect. You can:");
60
- console.error(" - Ensure embedded-postgres is installed (default, no Docker): npm install --save-dev embedded-postgres");
61
- console.error(" - Or specify a reachable database URL: CODEGEN_DATABASE_URL=postgresql://... npm run db:codegen");
62
- console.error(" - Or start local Supabase (needs Docker): ./supabase/scripts/db_start.sh --reset");
63
- console.error(` Slow/cold-starting target? Raise the timeout: CODEGEN_CONNECT_TIMEOUT_MS=15000 npm run db:codegen`);
64
- process.exit(1);
65
- }
66
-
67
- function sqlFiles(dir) {
68
- return readdirSync(dir, { withFileTypes: true }).flatMap((entry) => {
69
- const path = join(dir, entry.name);
70
- if (entry.isDirectory()) return sqlFiles(path);
71
- return entry.name.endsWith(".sql") || entry.name.endsWith(".txt") ? [path] : [];
72
- }).sort();
73
- }
74
-
75
- function ddlHash() {
76
- const hash = createHash("sha256");
77
- for (const file of sqlFiles(paths.ddlDir)) {
78
- hash.update(relative(process.cwd(), file));
79
- hash.update(readFileSync(file));
80
- }
81
- return hash.digest("hex");
82
- }
83
-
84
- const hash = ddlHash();
85
-
86
- if (paths.check) {
87
- for (const target of paths.targets) {
88
- const previous = existsSync(target.manifest) ? JSON.parse(readFileSync(target.manifest, "utf8")).ddlHash : null;
89
- if (previous === hash) continue;
90
- console.error(`❌ ${relative(process.cwd(), paths.ddlDir)} changed without regenerating models in ${relative(process.cwd(), target.outDir)}. Run: npm run db:codegen`);
91
- process.exit(1);
92
- }
93
- console.log(`✅ Drizzle models are in sync with ${relative(process.cwd(), paths.ddlDir)}`);
94
- process.exit(0);
95
- }
96
-
97
- let effectiveDbUrl = null;
98
- let ephemeral = null;
99
- // drizzle-kit's own default config resolution looks for `drizzle.config.json`
100
- // in the cwd and errors out if it's missing — a project has no reason to
101
- // keep one around just for this script when --db-url/CODEGEN_DATABASE_URL
102
- // (or the ephemeral fallback) already says everything drizzle-kit needs. So
103
- // when the caller didn't pass --drizzle-config, generate one on the fly.
104
- let generatedConfigPath = null;
105
- try {
106
- if (paths.dbUrlExplicit && paths.dbUrl) {
107
- if (await isReachable(paths.dbUrl)) {
108
- effectiveDbUrl = paths.dbUrl;
109
- } else {
110
- console.warn(`⚠️ Database URL '${paths.dbUrl}' is unreachable or invalid. Falling back to embedded-postgres library...\n`);
111
- ephemeral = await startEphemeralPostgres(orderedSqlFiles(paths.ddlDir));
112
- if (ephemeral) {
113
- effectiveDbUrl = ephemeral.url;
114
- } else {
115
- failUnreachable(paths.dbUrl);
116
- }
117
- }
118
- } else {
119
- // By default, prefer embedded-postgres library directly (zero setup, no Docker/external DB dependency)
120
- ephemeral = await startEphemeralPostgres(orderedSqlFiles(paths.ddlDir));
121
- if (ephemeral) {
122
- effectiveDbUrl = ephemeral.url;
123
- } else {
124
- // If embedded-postgres is not available / failed, check local Supabase default as fallback
125
- const localFallback = 'postgresql://postgres:postgres@127.0.0.1:54322/postgres';
126
- if (await isReachable(localFallback)) {
127
- effectiveDbUrl = localFallback;
128
- } else {
129
- failUnreachable('embedded-postgres library or local Supabase (127.0.0.1:54322)');
130
- }
131
- }
132
- }
133
-
134
- let configPath = paths.drizzleConfig;
135
- if (!configPath) {
136
- generatedConfigPath = join(paths.pullDir, '..', '.drizzle-config.json');
137
- mkdirSync(join(paths.pullDir, '..'), { recursive: true });
138
- writeFileSync(generatedConfigPath, JSON.stringify({
139
- out: paths.pullDir,
140
- dialect: 'postgresql',
141
- dbCredentials: { url: effectiveDbUrl },
142
- }, null, 2));
143
- configPath = generatedConfigPath;
144
- }
145
-
146
- rmSync(paths.pullDir, { recursive: true, force: true });
147
- // drizzle-kit itself requires `drizzle-orm` at runtime. This package
148
- // depends on drizzle-orm, but npm doesn't guarantee that dependency gets
149
- // hoisted to the consuming project's own node_modules (it commonly stays
150
- // nested under node_modules/cloudflare-next-intl/node_modules). `npx
151
- // drizzle-kit` resolves the binary through its own lookup rather than
152
- // Node's normal upward node_modules walk from this file, which — even
153
- // pinned to this package's own directory as cwd — resolved drizzle-orm
154
- // inconsistently across runs. Resolving and invoking drizzle-kit's own
155
- // installed binary directly sidesteps npx's resolution entirely: Node's
156
- // ordinary require() from that file's real location always finds
157
- // drizzle-orm right next to it in this package's own node_modules.
158
- // `drizzle-kit/bin.cjs` isn't in the package's `exports` map, so it can't
159
- // be require.resolve()'d directly — but its main entry point can, and
160
- // `bin.cjs` always sits next to it (declared via `bin` in package.json).
161
- const drizzleKitEntry = createRequire(import.meta.url).resolve('drizzle-kit');
162
- const drizzleKitBin = join(dirname(drizzleKitEntry), 'bin.cjs');
163
- execFileSync(process.execPath, [drizzleKitBin, 'pull', `--config=${configPath}`], {
164
- stdio: 'inherit',
165
- env: { ...process.env, CODEGEN_DATABASE_URL: effectiveDbUrl },
166
- });
167
- } finally {
168
- if (ephemeral) await ephemeral.stop();
169
- if (generatedConfigPath) rmSync(generatedConfigPath, { force: true });
170
- }
171
-
172
- const pulled = join(paths.pullDir, "schema.ts");
173
- if (!existsSync(pulled)) {
174
- console.error(`❌ drizzle-kit pull produced no schema at ${pulled}`);
175
- process.exit(1);
176
- }
177
- // Known drizzle-kit 0.31.10 introspection limitation: a column default that
178
- // is a call to a user-defined Postgres function (e.g. `default
179
- // public.current_user_id()`) is emitted as a bare, unimported JS identifier
180
- // call — e.g. `.default(current_user_id())` — instead of being wrapped as a
181
- // raw SQL expression (`.default(sql\`public.current_user_id()\`)`) the way
182
- // other non-literal defaults in the same file correctly are (see `sql\`'1000'\``,
183
- // `sql\`CURRENT_DATE\`` elsewhere in the pulled output). Confirmed via
184
- // drizzle-kit's own introspection source (node_modules/drizzle-kit/api.js):
185
- // the Postgres column-default normalizer only flags a default as an
186
- // expression (`isDefaultAnExpression`) for numeric columns; for
187
- // text/varchar/uuid columns a non-quoted, non-numeric default string is
188
- // returned verbatim with no such flag, so the codegen path that decides
189
- // whether to wrap in sql`` never sees it. There is no newer drizzle-kit
190
- // release (0.31.10 is already `latest`) and no pull/config flag that
191
- // changes this. `now()` and `gen_random_uuid()` don't hit this because
192
- // drizzle-kit special-cases those into `.defaultNow()` / `.defaultRandom()`;
193
- // any other bare `identifier()` call default does not get that treatment.
194
- // This patch detects that specific shape and rewrites it into the correct
195
- // sql`` form so the generated file is importable without throwing
196
- // `ReferenceError: <fn> is not defined`.
197
- function patchBareFunctionCallDefaults(source) {
198
- return source.replace(
199
- /\.default\((?!sql`)([a-zA-Z_][a-zA-Z0-9_]*)\(\)\)/g,
200
- (match, fnName) => `.default(sql\`public.${fnName}()\`)`,
201
- );
202
- }
203
-
204
- // drizzle-kit emits imports from `drizzle-orm/pg-core` and `drizzle-orm`.
205
- // Point them at this package's re-exports so consuming projects don't need a
206
- // direct `drizzle-orm` dependency just to load their generated schema.
207
- function retargetDrizzleImports(source) {
208
- const coreMatch = source.match(
209
- /^import \{([^}]*)\} from "drizzle-orm\/pg-core";?$/m,
210
- );
211
- const rootMatch = source.match(/^import \{([^}]*)\} from "drizzle-orm";?$/m);
212
- if (!coreMatch && !rootMatch) return source;
213
-
214
- const names = [...(coreMatch ? [coreMatch[1]] : []), ...(rootMatch ? [rootMatch[1]] : [])]
215
- .flatMap((group) => group.split(","))
216
- .map((name) => name.trim())
217
- .filter(Boolean);
218
- const merged = `import { ${[...new Set(names)].join(", ")} } from "cloudflare-next-intl/dbSchema"`;
219
-
220
- let seen = false;
221
- return source.replace(
222
- /^import \{[^}]*\} from "drizzle-orm(?:\/pg-core)?";?$/gm,
223
- () => {
224
- if (seen) return "";
225
- seen = true;
226
- return merged;
227
- },
228
- ).replace(/\n{3,}/g, "\n\n");
229
- }
230
-
231
- const banner = `// GENERATED by cfni-db-codegen from ${relative(process.cwd(), paths.ddlDir)} — do not edit.\n`;
232
- const pulledSource = retargetDrizzleImports(
233
- patchBareFunctionCallDefaults(readFileSync(pulled, "utf8")),
234
- );
235
- rmSync(paths.pullDir, { recursive: true, force: true });
236
- for (const target of paths.targets) {
237
- mkdirSync(target.outDir, { recursive: true });
238
- writeFileSync(target.outFile, banner + pulledSource);
239
- writeFileSync(target.manifest, `${JSON.stringify({ ddlHash: hash }, null, 2)}\n`);
240
- console.log(`✅ Generated ${relative(process.cwd(), target.outFile)}`);
241
- }
242
-
243
- runInstallExecStep(paths, process.cwd());
2
+ // Re-exec shim: `cfni-db-codegen` now lives in cloudflare-next-intl-db,
3
+ // installed as this package's dependency. Kept here so existing consumers'
4
+ // `npx cfni-db-codegen` invocations keep working with no changes needed.
5
+ import { fileURLToPath, pathToFileURL } from 'node:url';
6
+ import { dirname, join } from 'node:path';
7
+
8
+ // Resolve via the package's root export (".") its exports map doesn't
9
+ // declare "./package.json", so that can't be resolved directly. The root
10
+ // export ("dist/src/index.js") sits two directories below the package root.
11
+ const indexPath = fileURLToPath(import.meta.resolve('cloudflare-next-intl-db'));
12
+ const dbPackageRoot = join(dirname(indexPath), '..', '..');
13
+ await import(pathToFileURL(join(dbPackageRoot, 'bin', 'db_codegen.mjs')).href);
@@ -1,16 +1,13 @@
1
1
  #!/usr/bin/env node
2
- // Installs cfni_exec.sql (and its pgTAP test file) into the consuming
3
- // project the same step cfni-db-codegen runs after a successful
4
- // generation, exposed standalone for when you only want this and nothing
5
- // else (no drizzle-kit pull, no live Postgres needed).
6
- //
7
- // Usage: cfni-db-install-exec [--rpc-dir=…] [--rpc-file-name=…] [--tests-dir=…] [--tests-file-name=…] [--force]
8
- //
9
- // Gated on the project's `db.supabase.rawSql` (read from `next.config.*`'s
10
- // `@intl-config` alias) the same way cfni-db-codegen's step is — pass
11
- // `--force`/CFNI_DB_FORCE_EXEC=true to overwrite an existing, differing file.
12
- import resolveCodegenPaths from '../dist/src/db/codegen_paths.js';
13
- import { runInstallExecStep } from './install_exec_step.mjs';
2
+ // Re-exec shim: `cfni-db-install-exec` now lives in cloudflare-next-intl-db,
3
+ // installed as this package's dependency. Kept here so existing consumers'
4
+ // `npx cfni-db-install-exec` invocations keep working with no changes needed.
5
+ import { fileURLToPath, pathToFileURL } from 'node:url';
6
+ import { dirname, join } from 'node:path';
14
7
 
15
- const paths = resolveCodegenPaths(process.argv.slice(2), process.env, process.cwd());
16
- runInstallExecStep(paths, process.cwd());
8
+ // Resolve via the package's root export (".") its exports map doesn't
9
+ // declare "./package.json", so that can't be resolved directly. The root
10
+ // export ("dist/src/index.js") sits two directories below the package root.
11
+ const indexPath = fileURLToPath(import.meta.resolve('cloudflare-next-intl-db'));
12
+ const dbPackageRoot = join(dirname(indexPath), '..', '..');
13
+ await import(pathToFileURL(join(dbPackageRoot, 'bin', 'db_install_exec.mjs')).href);
@@ -1,13 +1,2 @@
1
- import type { Client } from 'pg';
2
- import type { DbRoutingConfig, ErrorHandlingRoutingConfig, FirebaseAuthRoutingConfig, GenerateRoutingConfig } from '../types/types.js';
3
- export interface DbConfig {
4
- db?: DbRoutingConfig;
5
- firebaseAuth?: FirebaseAuthRoutingConfig;
6
- generate?: GenerateRoutingConfig;
7
- errorHandling?: ErrorHandlingRoutingConfig;
8
- }
9
- export declare function withDbClient<T>(config: DbConfig, queryFn: (client: Client) => Promise<T>): Promise<T>;
10
- export declare function resetConnectionState(): void;
11
- export declare function withSessionLock<T>(fn: () => Promise<T>): Promise<T>;
12
- export declare function connectToPostgres(config: DbConfig): Promise<Client>;
13
- export declare function disconnectPostgres(client?: Client): Promise<void>;
1
+ export { withDbClient, connectToPostgres, disconnectPostgres, resetConnectionState, withSessionLock, } from 'cloudflare-next-intl-db';
2
+ export type { DbConfig } from 'cloudflare-next-intl-db';
@@ -1,100 +1 @@
1
- import reportError from '../error_handling/report_error.js';
2
- import requireDbConfig from './require_config.js';
3
- import resolveConfigValue from './resolve_config_value.js';
4
- import { resolveHyperdriveConnectionString } from './resolve_hyperdrive_connection_string.js';
5
- const BENIGN_DISCONNECT_PATTERN = /(connection terminated|connection closed|socket closed|unexpected eof)/i;
6
- let pgModule;
7
- function loadPg() {
8
- pgModule ?? (pgModule = import('pg'));
9
- return pgModule;
10
- }
11
- async function resolveConnectionString(db, generate) {
12
- const configured = await resolveConfigValue(db.connectionString);
13
- if (configured)
14
- return configured;
15
- if (db.autoHyperdrive !== false) {
16
- const hyperdriveConn = await resolveHyperdriveConnectionString(generate);
17
- if (hyperdriveConn)
18
- return hyperdriveConn;
19
- }
20
- throw new Error('db: could not resolve a Postgres connection string. Set `db.connectionString` ' +
21
- 'to a connection string, or to a function returning one (e.g. reading a ' +
22
- 'Hyperdrive binding off `env` or `getCloudflareContext().env`).');
23
- }
24
- async function resetSessionState(client) {
25
- try {
26
- await client.query('discard all');
27
- }
28
- catch {
29
- await client.query('reset role').catch(() => undefined);
30
- }
31
- }
32
- export async function withDbClient(config, queryFn) {
33
- const db = config.db;
34
- requireDbConfig(db);
35
- const connectionString = await resolveConnectionString(db, config.generate);
36
- const { Client: PgClient } = await loadPg();
37
- const client = new PgClient({ connectionString });
38
- let result;
39
- let connected = false;
40
- try {
41
- try {
42
- await client.connect();
43
- connected = true;
44
- await resetSessionState(client);
45
- }
46
- catch (error) {
47
- const message = error instanceof Error ? error.message : String(error ?? '');
48
- if (!BENIGN_DISCONNECT_PATTERN.test(message)) {
49
- void reportError({ errorHandling: config.errorHandling, generate: config.generate }, { error, classOrMethodName: 'db.withDbClient.connectError' });
50
- }
51
- throw error;
52
- }
53
- result = await queryFn(client);
54
- }
55
- finally {
56
- const endPromise = connected ? client.end() : Promise.resolve();
57
- let ctx;
58
- if (db.disconnectAfterRequest !== false) {
59
- if (config.generate?.ctx) {
60
- ctx = typeof config.generate.ctx === 'function' ? config.generate.ctx() : config.generate.ctx;
61
- }
62
- else if (config.generate?.getCloudflareContext) {
63
- try {
64
- const context = await config.generate.getCloudflareContext({ async: true });
65
- ctx = context?.ctx;
66
- }
67
- catch {
68
- }
69
- }
70
- }
71
- if (ctx && typeof ctx.waitUntil === 'function') {
72
- ctx.waitUntil(endPromise.catch(() => undefined));
73
- }
74
- else {
75
- await endPromise.catch(() => undefined);
76
- }
77
- }
78
- return result;
79
- }
80
- export function resetConnectionState() {
81
- }
82
- export async function withSessionLock(fn) {
83
- return await fn();
84
- }
85
- export async function connectToPostgres(config) {
86
- const db = config.db;
87
- requireDbConfig(db);
88
- const connectionString = await resolveConnectionString(db, config.generate);
89
- const { Client: PgClient } = await loadPg();
90
- const client = new PgClient({ connectionString });
91
- client.on('error', (error) => {
92
- void reportError({ errorHandling: config.errorHandling, generate: config.generate }, { error, classOrMethodName: 'db.connectToPostgres.clientError' });
93
- });
94
- await client.connect();
95
- await resetSessionState(client);
96
- return client;
97
- }
98
- export async function disconnectPostgres(client) {
99
- await client?.end().catch(() => undefined);
100
- }
1
+ export { withDbClient, connectToPostgres, disconnectPostgres, resetConnectionState, withSessionLock, } from 'cloudflare-next-intl-db';
@@ -1,12 +1,5 @@
1
- import type { NodePgDatabase } from 'drizzle-orm/node-postgres';
2
- import type { DbRoutingConfig } from '../types/types.js';
3
- export type DrizzleDb = NodePgDatabase<Record<string, never>>;
4
- export interface UserDbCredentials {
5
- uid: string | null;
6
- accessToken: string | null;
7
- role: string | null;
8
- }
9
- export declare function resolveUserDbCredentials(dbOverride?: DbRoutingConfig): Promise<UserDbCredentials>;
1
+ import type { DbRoutingConfig, DrizzleDb, TransactionResult, UserDbCredentials } from 'cloudflare-next-intl-db';
2
+ export type { DrizzleDb, TransactionResult, UserDbCredentials };
10
3
  export declare function withPublicDb<T>(fn: (db: DrizzleDb) => Promise<T>, dbOverride?: DbRoutingConfig): Promise<T>;
11
4
  export declare function withUserDb<T>(fn: (db: DrizzleDb) => Promise<T>, auth?: string | null | UserDbCredentials, dbOverride?: DbRoutingConfig): Promise<T>;
12
- export type { ExecResult as TransactionResult } from './supabase_transport.js';
5
+ export declare function resolveUserDbCredentials(dbOverride?: DbRoutingConfig): Promise<UserDbCredentials>;