@runlot/pg 0.1.0-rc.100
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/README.md +60 -0
- package/dist/bundler.d.ts +33 -0
- package/dist/bundler.d.ts.map +1 -0
- package/dist/bundler.js +276 -0
- package/dist/bundler.js.map +1 -0
- package/dist/client.d.ts +138 -0
- package/dist/client.d.ts.map +1 -0
- package/dist/client.js +505 -0
- package/dist/client.js.map +1 -0
- package/dist/emitter.d.ts +14 -0
- package/dist/emitter.d.ts.map +1 -0
- package/dist/emitter.js +63 -0
- package/dist/emitter.js.map +1 -0
- package/dist/errors.d.ts +34 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +46 -0
- package/dist/errors.js.map +1 -0
- package/dist/index.d.ts +94 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +27 -0
- package/dist/index.js.map +1 -0
- package/dist/orm/drizzle.d.ts +9 -0
- package/dist/orm/drizzle.d.ts.map +1 -0
- package/dist/orm/drizzle.js +13 -0
- package/dist/orm/drizzle.js.map +1 -0
- package/dist/orm/knex.d.ts +6 -0
- package/dist/orm/knex.d.ts.map +1 -0
- package/dist/orm/knex.js +28 -0
- package/dist/orm/knex.js.map +1 -0
- package/dist/orm/kysely.d.ts +5 -0
- package/dist/orm/kysely.d.ts.map +1 -0
- package/dist/orm/kysely.js +14 -0
- package/dist/orm/kysely.js.map +1 -0
- package/dist/orm/prisma.d.ts +49 -0
- package/dist/orm/prisma.d.ts.map +1 -0
- package/dist/orm/prisma.js +344 -0
- package/dist/orm/prisma.js.map +1 -0
- package/dist/orm/sequelize.d.ts +4 -0
- package/dist/orm/sequelize.d.ts.map +1 -0
- package/dist/orm/sequelize.js +24 -0
- package/dist/orm/sequelize.js.map +1 -0
- package/dist/orm/typeorm.d.ts +11 -0
- package/dist/orm/typeorm.d.ts.map +1 -0
- package/dist/orm/typeorm.js +22 -0
- package/dist/orm/typeorm.js.map +1 -0
- package/dist/type-parsers.d.ts +159 -0
- package/dist/type-parsers.d.ts.map +1 -0
- package/dist/type-parsers.js +329 -0
- package/dist/type-parsers.js.map +1 -0
- package/dist/types.d.ts +93 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +9 -0
- package/dist/types.js.map +1 -0
- package/package.json +83 -0
package/README.md
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
# @runlot/pg
|
|
2
|
+
|
|
3
|
+
`env.db` 위에서 node-postgres(`pg`) 모양으로 쓰는 어댑터입니다. 이미 `pg` 를 쓰는 코드와
|
|
4
|
+
ORM 을 고치지 않고 runlot 의 데이터베이스에 붙일 수 있습니다.
|
|
5
|
+
|
|
6
|
+
```ts
|
|
7
|
+
import { Pool } from "@runlot/pg";
|
|
8
|
+
|
|
9
|
+
export default {
|
|
10
|
+
async fetch(req, env) {
|
|
11
|
+
const pool = new Pool({ db: env.db });
|
|
12
|
+
const { rows } = await pool.query("select id, name from users where id = $1", [1]);
|
|
13
|
+
return Response.json(rows);
|
|
14
|
+
},
|
|
15
|
+
};
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
## 무엇을 할 수 있나요
|
|
19
|
+
|
|
20
|
+
- `Pool.query(text, values)` — 호출마다 새 세션입니다. 문장 하나짜리 질의에 알맞습니다.
|
|
21
|
+
- `Pool.connect()` / `new Client({ db })` — 세션 하나를 쥐어요. `BEGIN … COMMIT`,
|
|
22
|
+
prepared statement, `SET` 이 그 안에서 유지됩니다. `release()` 나 `end()` 로 돌려주세요.
|
|
23
|
+
- 오류는 `DatabaseError` 로 던지고 `err.code` 가 SQLSTATE 입니다 (`23505` 같은 값).
|
|
24
|
+
- `types.setTypeParser(oid, fn)` 으로 타입 변환을 바꿀 수 있어요. 기본은 `pg` 와
|
|
25
|
+
같습니다 — `timestamptz`·`date` 는 `Date`, `int8`·`numeric` 은 문자열입니다.
|
|
26
|
+
|
|
27
|
+
## ORM
|
|
28
|
+
|
|
29
|
+
| ORM | 쓰는 법 |
|
|
30
|
+
|---|---|
|
|
31
|
+
| Prisma | `import { PrismaRunlot } from "@runlot/pg/prisma"` → `new PrismaClient({ adapter: new PrismaRunlot(env.db) })` |
|
|
32
|
+
| Drizzle | `import { drizzle } from "@runlot/pg/drizzle"` → `drizzle(env.db, { schema })` |
|
|
33
|
+
| Kysely | `import { kysely } from "@runlot/pg/kysely"` → `kysely<DB>(env.db)` |
|
|
34
|
+
| TypeORM | `import { dataSource } from "@runlot/pg/typeorm"` → `dataSource(env.db, { entities })` |
|
|
35
|
+
| Sequelize | `import { sequelize } from "@runlot/pg/sequelize"` → `sequelize(env.db)` |
|
|
36
|
+
| Knex | `import { knex } from "@runlot/pg/knex"` → `knex(env.db)` |
|
|
37
|
+
|
|
38
|
+
`runlot deploy` 로 배포하면 따로 할 일이 없습니다. 배포 번들러(`@runlot/pg/bundler`)가
|
|
39
|
+
`pg` 를 이 패키지로 풀고, ORM 이 node 내장 모듈을 쓰면 `nodejs_compat` 를,
|
|
40
|
+
Prisma 의 WASM 쿼리 컴파일러는 별도 모듈로 `runlot.json` 에 적습니다.
|
|
41
|
+
|
|
42
|
+
다른 도구로 직접 묶는다면 같은 일을 해야 합니다: `pg` → `@runlot/pg` alias,
|
|
43
|
+
node 내장은 `node:` 접두로 외부에 두고 매니페스트에 `"compatibilityFlags":
|
|
44
|
+
["nodejs_compat"]`, `fs`·`os`·`tty` 는 빈 스텁, `.wasm` 은 번들 밖 모듈로 두고
|
|
45
|
+
매니페스트 `modules` 에 `{ "name", "type": "wasm", "path" }` 로 적습니다. `buildWorker`
|
|
46
|
+
를 직접 불러도 됩니다:
|
|
47
|
+
|
|
48
|
+
```ts
|
|
49
|
+
import { buildWorker } from "@runlot/pg/bundler";
|
|
50
|
+
const { code, report } = await buildWorker({ entry: "src/index.ts", absWorkingDir: process.cwd() });
|
|
51
|
+
// report.nodeImports 가 비어 있지 않으면 nodejs_compat, report.wasmModules 는 곁에 실을 파일
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
## 개발
|
|
55
|
+
|
|
56
|
+
```sh
|
|
57
|
+
pnpm --filter @runlot/pg test # 가짜 env.db 상대 단위 시험
|
|
58
|
+
pnpm --filter @runlot/pg e2e:build # e2e/*.ts → e2e-dist/*.js (실물 workerd 시험용)
|
|
59
|
+
go test ./node/internal/workerd -run TestLiveORM -v # 실물 workerd 위 ORM 별 E2E
|
|
60
|
+
```
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
export interface WasmModule {
|
|
2
|
+
/** The specifier imported by the worker and manifest `modules[].name`. */
|
|
3
|
+
name: string;
|
|
4
|
+
/** Absolute source-file path. */
|
|
5
|
+
path: string;
|
|
6
|
+
}
|
|
7
|
+
export interface WorkerBundleReport {
|
|
8
|
+
/** Node built-ins left external by the worker (sorted, such as `node:util`). Requires `nodejs_compat` when nonempty. */
|
|
9
|
+
nodeImports: string[];
|
|
10
|
+
/** WASM modules that must be included alongside it. */
|
|
11
|
+
wasmModules: WasmModule[];
|
|
12
|
+
}
|
|
13
|
+
export interface BuildWorkerOptions {
|
|
14
|
+
/** Entry point, relative to absWorkingDir or absolute. */
|
|
15
|
+
entry: string;
|
|
16
|
+
absWorkingDir: string;
|
|
17
|
+
/** Metafile output name. Defaults to `worker/index.js`; no file is written. */
|
|
18
|
+
outfile?: string;
|
|
19
|
+
/** Where to resolve `pg`. Defaults to `@runlot/pg`; leaves `pg` alone if unresolved. */
|
|
20
|
+
pgAlias?: string;
|
|
21
|
+
define?: Record<string, string>;
|
|
22
|
+
minify?: boolean;
|
|
23
|
+
}
|
|
24
|
+
export interface WorkerBundle {
|
|
25
|
+
code: Uint8Array;
|
|
26
|
+
report: WorkerBundleReport;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Bundles one worker without writing files. Returns its bytes and report; the caller
|
|
30
|
+
* (the deployment tool or E2E) chooses where and under what name to place them.
|
|
31
|
+
*/
|
|
32
|
+
export declare function buildWorker(opts: BuildWorkerOptions): Promise<WorkerBundle>;
|
|
33
|
+
//# sourceMappingURL=bundler.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"bundler.d.ts","sourceRoot":"","sources":["../src/bundler.ts"],"names":[],"mappings":"AAkCA,MAAM,WAAW,UAAU;IACzB,0EAA0E;IAC1E,IAAI,EAAE,MAAM,CAAC;IACb,iCAAiC;IACjC,IAAI,EAAE,MAAM,CAAC;CACd;AAED,MAAM,WAAW,kBAAkB;IACjC,wHAAwH;IACxH,WAAW,EAAE,MAAM,EAAE,CAAC;IACtB,uDAAuD;IACvD,WAAW,EAAE,UAAU,EAAE,CAAC;CAC3B;AAED,MAAM,WAAW,kBAAkB;IACjC,0DAA0D;IAC1D,KAAK,EAAE,MAAM,CAAC;IACd,aAAa,EAAE,MAAM,CAAC;IACtB,+EAA+E;IAC/E,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,wFAAwF;IACxF,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAChC,MAAM,CAAC,EAAE,OAAO,CAAC;CAClB;AAED,MAAM,WAAW,YAAY;IAC3B,IAAI,EAAE,UAAU,CAAC;IACjB,MAAM,EAAE,kBAAkB,CAAC;CAC5B;AA0MD;;;GAGG;AACH,wBAAsB,WAAW,CAAC,IAAI,EAAE,kBAAkB,GAAG,OAAO,CAAC,YAAY,CAAC,CA4CjF"}
|
package/dist/bundler.js
ADDED
|
@@ -0,0 +1,276 @@
|
|
|
1
|
+
// Worker bundler — the user's deployment tool (`runlot deploy`) and this package's E2E
|
|
2
|
+
// bundle workers with the **same** rules (docs/pg-driver-support.md §3.3).
|
|
3
|
+
//
|
|
4
|
+
// The rules must live in one place because the E2E measures whether a worker bundled with
|
|
5
|
+
// these rules runs in real workerd. A green result from different deployment rules does not
|
|
6
|
+
// answer anything about the user's deployment.
|
|
7
|
+
//
|
|
8
|
+
// It:
|
|
9
|
+
// - aliases `pg` to `@runlot/pg`; ORMs import `pg` at module top level. The alias holds
|
|
10
|
+
// only for the modules **this** pass resolves: on the `framework: next` path OpenNext
|
|
11
|
+
// has already bundled the app before we run, so an ORM inside that bundle got its `pg`
|
|
12
|
+
// from the project. Nothing here can make `instanceof Pool` hold across that seam, which
|
|
13
|
+
// is why the classes in client.ts pin their own constructor names.
|
|
14
|
+
// - leaves Node built-ins external with the `node:` prefix for workerd's `nodejs_compat`.
|
|
15
|
+
// Requested built-ins go in report.nodeImports, which tells the deployer to add
|
|
16
|
+
// `nodejs_compat` to the manifest.
|
|
17
|
+
// - stubs built-ins missing from this workerd build's `nodejs_compat` (`fs`, `os`, and
|
|
18
|
+
// `tty`, verified) plus `module`, which requires a file URL at load time. This is what
|
|
19
|
+
// Wrangler fills with unenv. ORMs require these at load time but do not use them on the
|
|
20
|
+
// paths we run; using one throws.
|
|
21
|
+
// - resolves CJS `require("util")` through a require table in the banner. Dynamic require
|
|
22
|
+
// cannot remain in ESM output, and esbuild's `__toCommonJS` bridge returns an object,
|
|
23
|
+
// which breaks modules such as `assert(x)` whose default is a function. A table returning
|
|
24
|
+
// statically imported namespaces fixes that; it is added on the second bundle after the
|
|
25
|
+
// first pass identifies required modules.
|
|
26
|
+
// - keeps `.wasm` as an external module name. workerd disallows WASM compilation inside a
|
|
27
|
+
// bundle, so it can enter only through a configuration `wasm = embed` module.
|
|
28
|
+
// report.wasmModules tells the deployer which files to include and under which names.
|
|
29
|
+
// - uses the browser build of `debug`, because its Node build accesses `process.stderr.fd`.
|
|
30
|
+
// - resolves other DB drivers and optional dependencies as empty modules; workers lack and
|
|
31
|
+
// do not need them.
|
|
32
|
+
import { createHash } from "node:crypto";
|
|
33
|
+
import { build } from "esbuild";
|
|
34
|
+
/** Node built-in module names. Leaves bare names such as `util` external as `node:util`. */
|
|
35
|
+
const NODE_BUILTINS = new Set([
|
|
36
|
+
"assert", "async_hooks", "buffer", "child_process", "cluster", "console", "constants", "crypto", "dgram",
|
|
37
|
+
"diagnostics_channel", "dns", "domain", "events", "fs", "http", "http2", "https", "inspector", "module", "net",
|
|
38
|
+
"os", "path", "perf_hooks", "process", "punycode", "querystring", "readline", "repl", "stream", "string_decoder",
|
|
39
|
+
"sys", "timers", "tls", "trace_events", "tty", "url", "util", "v8", "vm", "wasi", "worker_threads", "zlib",
|
|
40
|
+
]);
|
|
41
|
+
/** Other database drivers and optional dependencies, resolved as empty modules. */
|
|
42
|
+
const EMPTY = new Set([
|
|
43
|
+
"mariadb/callback", "mariadb", "mysql", "mysql2", "sqlite3", "better-sqlite3", "oracledb", "tedious", "mssql",
|
|
44
|
+
"ibm_db", "pg-native", "pg-query-stream", "pg-hstore", "pg-copy-streams", "snowflake-sdk", "@sap/hana-client",
|
|
45
|
+
"hdb-pool", "mongodb", "typeorm-aurora-data-api-driver", "sql.js", "react-native-sqlite-storage",
|
|
46
|
+
"@google-cloud/spanner", "spanner", "libsql", "@libsql/client", "@sqlite.org/sqlite-wasm", "sap-hana-client",
|
|
47
|
+
"@sap/hana-client/extension/Stream", "pg-cloudflare", "cloudflare:sockets", "pgpass",
|
|
48
|
+
]);
|
|
49
|
+
/** Stubs for built-ins unavailable in `nodejs_compat` (fs, os, tty) or requiring a file URL at load time (module). */
|
|
50
|
+
const STUBS = {
|
|
51
|
+
fs: `// Empty stub for node:fs. This workerd build's nodejs_compat does not include fs (verified).
|
|
52
|
+
const missing = (name) => (..._a) => { throw new Error("node:fs." + name + " is not available in the worker"); };
|
|
53
|
+
export const existsSync = () => false;
|
|
54
|
+
export const readFileSync = missing("readFileSync");
|
|
55
|
+
export const writeFileSync = missing("writeFileSync");
|
|
56
|
+
export const appendFileSync = missing("appendFileSync");
|
|
57
|
+
export const statSync = missing("statSync");
|
|
58
|
+
export const lstatSync = missing("lstatSync");
|
|
59
|
+
export const readdirSync = missing("readdirSync");
|
|
60
|
+
export const mkdirSync = missing("mkdirSync");
|
|
61
|
+
export const unlinkSync = missing("unlinkSync");
|
|
62
|
+
export const realpathSync = missing("realpathSync");
|
|
63
|
+
export const createReadStream = missing("createReadStream");
|
|
64
|
+
export const createWriteStream = missing("createWriteStream");
|
|
65
|
+
export const readFile = missing("readFile");
|
|
66
|
+
export const writeFile = missing("writeFile");
|
|
67
|
+
export const readdir = missing("readdir");
|
|
68
|
+
export const realpath = missing("realpath");
|
|
69
|
+
export const stat = missing("stat");
|
|
70
|
+
export const lstat = missing("lstat");
|
|
71
|
+
export const mkdir = missing("mkdir");
|
|
72
|
+
export const unlink = missing("unlink");
|
|
73
|
+
export const access = missing("access");
|
|
74
|
+
export const promises = {
|
|
75
|
+
readFile: missing("readFile"), writeFile: missing("writeFile"), stat: missing("stat"), lstat: missing("lstat"),
|
|
76
|
+
access: missing("access"), readdir: missing("readdir"), realpath: missing("realpath"), mkdir: missing("mkdir"), unlink: missing("unlink"),
|
|
77
|
+
};
|
|
78
|
+
export const constants = { F_OK: 0, R_OK: 4, W_OK: 2, X_OK: 1 };
|
|
79
|
+
export default {
|
|
80
|
+
existsSync, readFileSync, writeFileSync, appendFileSync, statSync, lstatSync, readdirSync, mkdirSync, unlinkSync, realpathSync,
|
|
81
|
+
createReadStream, createWriteStream, readFile, writeFile, readdir, realpath, stat, lstat, mkdir, unlink, access, promises, constants,
|
|
82
|
+
};
|
|
83
|
+
`,
|
|
84
|
+
os: `// Stub for node:os. Same values as unenv.
|
|
85
|
+
export const EOL = "\\n";
|
|
86
|
+
export const platform = () => "linux";
|
|
87
|
+
export const type = () => "Linux";
|
|
88
|
+
export const release = () => "";
|
|
89
|
+
export const hostname = () => "localhost";
|
|
90
|
+
export const homedir = () => "/";
|
|
91
|
+
export const tmpdir = () => "/tmp";
|
|
92
|
+
export const cpus = () => [];
|
|
93
|
+
export const totalmem = () => 0;
|
|
94
|
+
export const freemem = () => 0;
|
|
95
|
+
export const arch = () => "wasm";
|
|
96
|
+
export const endianness = () => "LE";
|
|
97
|
+
export const networkInterfaces = () => ({});
|
|
98
|
+
export const userInfo = () => ({ username: "", uid: -1, gid: -1, shell: null, homedir: "/" });
|
|
99
|
+
export default { EOL, platform, type, release, hostname, homedir, tmpdir, cpus, totalmem, freemem, arch, endianness, networkInterfaces, userInfo };
|
|
100
|
+
`,
|
|
101
|
+
tty: `// Stub for node:tty. Only used when colorette (knex) asks whether to enable color.
|
|
102
|
+
export const isatty = () => false;
|
|
103
|
+
export class ReadStream {}
|
|
104
|
+
export class WriteStream {}
|
|
105
|
+
export default { isatty, ReadStream, WriteStream };
|
|
106
|
+
`,
|
|
107
|
+
// node:module is **present** in nodejs_compat; only one of its functions is
|
|
108
|
+
// unusable here. fdir (tinyglobby ← TypeORM) calls createRequire(import.meta.url)
|
|
109
|
+
// at module scope and the worker's import.meta.url is not a file URL, so the
|
|
110
|
+
// real createRequire throws. Replacing the whole module was too wide a fix:
|
|
111
|
+
// Next's require-hook.js reads `require("module").prototype.require` and
|
|
112
|
+
// `_resolveFilename`, and against a plain object that is
|
|
113
|
+
// "Cannot read properties of undefined" on the first request
|
|
114
|
+
// (docs/nextjs.md §8). So stand on the real one and narrow the repair to
|
|
115
|
+
// createRequire. CommonJS on purpose — `require("node:module")` has to come
|
|
116
|
+
// back as the Module **function**, which a namespace object is not.
|
|
117
|
+
module: `const real = require("node:module");
|
|
118
|
+
const FALLBACK = "file:///worker.js";
|
|
119
|
+
const createRequire = (from) => {
|
|
120
|
+
try {
|
|
121
|
+
return real.createRequire(from);
|
|
122
|
+
} catch {
|
|
123
|
+
// Not a file URL — the worker's own module identity. Resolution still only
|
|
124
|
+
// reaches built-ins, which is all that ever worked here.
|
|
125
|
+
return real.createRequire(FALLBACK);
|
|
126
|
+
}
|
|
127
|
+
};
|
|
128
|
+
module.exports = new Proxy(real, {
|
|
129
|
+
get: (target, prop, recv) => (prop === "createRequire" ? createRequire : Reflect.get(target, prop, recv)),
|
|
130
|
+
});
|
|
131
|
+
`,
|
|
132
|
+
};
|
|
133
|
+
const STUB_NS = "runlot-stub";
|
|
134
|
+
const EMPTY_NS = "runlot-empty";
|
|
135
|
+
function requireBanner(mods) {
|
|
136
|
+
const names = [...mods].sort();
|
|
137
|
+
const lines = [];
|
|
138
|
+
names.forEach((m, i) => lines.push(`import * as __rl_node_${i} from ${JSON.stringify(m)};`));
|
|
139
|
+
lines.push(`const __rl_node = { ${names.map((m, i) => `${JSON.stringify(m)}: __rl_node_${i}`).join(", ")} };`);
|
|
140
|
+
// What require() hands back has to be **patchable**. An ES module namespace
|
|
141
|
+
// is not: assigning to one throws, and CJS code written for Node patches the
|
|
142
|
+
// module object in place. Next does exactly that —
|
|
143
|
+
// `nodeTimers.setImmediate = patchedSetImmediate` — and against a namespace
|
|
144
|
+
// it died with "Cannot assign to property 'setImmediate' of [object Module]"
|
|
145
|
+
// on the first request (docs/nextjs.md §8).
|
|
146
|
+
//
|
|
147
|
+
// A builtin's `default` is the CJS object: measured writable, and carrying
|
|
148
|
+
// the same functions as the namespace. So prefer it whenever it is an object,
|
|
149
|
+
// and fill in any named export it happens to lack — one shared object, so a
|
|
150
|
+
// patch one module makes is the patch every other one sees, as in Node.
|
|
151
|
+
lines.push(`const require = (id) => { const k = id.startsWith("node:") ? id : "node:" + id; const ns = __rl_node[k]; ` +
|
|
152
|
+
`if (!ns) throw new Error("require(" + JSON.stringify(id) + ") is not available in the worker"); ` +
|
|
153
|
+
`if (typeof ns.default === "function") return ns.default; ` +
|
|
154
|
+
`if (!ns.default || typeof ns.default !== "object") return ns; ` +
|
|
155
|
+
`for (const key of Object.keys(ns)) { if (key !== "default" && !(key in ns.default)) { try { ns.default[key] = ns[key]; } catch {} } } ` +
|
|
156
|
+
`return ns.default; };`);
|
|
157
|
+
return lines.join("\n");
|
|
158
|
+
}
|
|
159
|
+
/** Module name for a WASM file. Defaults to its filename; adds a hash if another file uses it. */
|
|
160
|
+
function wasmName(state, abs) {
|
|
161
|
+
const base = abs.slice(abs.lastIndexOf("/") + 1);
|
|
162
|
+
const have = state.wasm.get(base);
|
|
163
|
+
if (have === undefined || have === abs)
|
|
164
|
+
return base;
|
|
165
|
+
const h = createHash("sha256").update(abs).digest("hex").slice(0, 8);
|
|
166
|
+
return base.replace(/\.wasm$/, `-${h}.wasm`);
|
|
167
|
+
}
|
|
168
|
+
function workerPlugin(state, opts) {
|
|
169
|
+
const pgAlias = opts.pgAlias ?? "@runlot/pg";
|
|
170
|
+
return {
|
|
171
|
+
name: "runlot-worker",
|
|
172
|
+
setup(b) {
|
|
173
|
+
b.onResolve({ filter: /\.wasm(\?module)?$/ }, (args) => {
|
|
174
|
+
const rel = args.path.replace(/\?module$/, "");
|
|
175
|
+
const abs = rel.startsWith("/") ? rel : new URL(rel, "file://" + args.resolveDir + "/").pathname;
|
|
176
|
+
const name = wasmName(state, abs);
|
|
177
|
+
state.wasm.set(name, abs);
|
|
178
|
+
return { path: name, external: true };
|
|
179
|
+
});
|
|
180
|
+
b.onResolve({ filter: /^[^./]/ }, async (args) => {
|
|
181
|
+
if (args.namespace === STUB_NS) {
|
|
182
|
+
// A stub may stand **on top of** the real module rather than replace
|
|
183
|
+
// it (node:module does). Its own import has to reach workerd, not
|
|
184
|
+
// come back here and recurse.
|
|
185
|
+
const b0 = args.path.startsWith("node:") ? args.path.slice(5) : args.path;
|
|
186
|
+
if (NODE_BUILTINS.has(b0)) {
|
|
187
|
+
state.nodeBuiltins.add("node:" + b0);
|
|
188
|
+
if (args.kind === "require-call")
|
|
189
|
+
state.requireBuiltins.add("node:" + b0);
|
|
190
|
+
return { path: "node:" + b0, external: true };
|
|
191
|
+
}
|
|
192
|
+
return undefined;
|
|
193
|
+
}
|
|
194
|
+
if (args.namespace === EMPTY_NS)
|
|
195
|
+
return undefined;
|
|
196
|
+
if (args.path === "pg" && args.kind !== "entry-point") {
|
|
197
|
+
const r = await b.resolve(pgAlias, { kind: args.kind, resolveDir: opts.absWorkingDir, importer: args.importer });
|
|
198
|
+
if (r.errors.length === 0 && r.path)
|
|
199
|
+
return { path: r.path };
|
|
200
|
+
return undefined;
|
|
201
|
+
}
|
|
202
|
+
if (args.path === "debug" && args.namespace !== "debug-browser") {
|
|
203
|
+
const r = await b.resolve("debug/src/browser.js", { kind: args.kind, resolveDir: args.resolveDir, namespace: "debug-browser" });
|
|
204
|
+
if (r.errors.length === 0 && r.path)
|
|
205
|
+
return { path: r.path };
|
|
206
|
+
}
|
|
207
|
+
const bare = args.path.startsWith("node:") ? args.path.slice(5) : args.path;
|
|
208
|
+
const bareBase = bare.split("/")[0];
|
|
209
|
+
if (NODE_BUILTINS.has(bare) || (NODE_BUILTINS.has(bareBase) && bare.startsWith(bareBase + "/"))) {
|
|
210
|
+
state.nodeBuiltins.add("node:" + bare);
|
|
211
|
+
if (bare in STUBS)
|
|
212
|
+
return { path: bare, namespace: STUB_NS };
|
|
213
|
+
if (args.kind === "require-call")
|
|
214
|
+
state.requireBuiltins.add("node:" + bare);
|
|
215
|
+
return { path: "node:" + bare, external: true };
|
|
216
|
+
}
|
|
217
|
+
if (EMPTY.has(args.path))
|
|
218
|
+
return { path: args.path, namespace: EMPTY_NS };
|
|
219
|
+
return undefined;
|
|
220
|
+
});
|
|
221
|
+
b.onLoad({ filter: /.*/, namespace: STUB_NS }, (args) => ({ contents: STUBS[args.path], loader: "js" }));
|
|
222
|
+
b.onLoad({ filter: /.*/, namespace: EMPTY_NS }, () => ({ contents: "export default {};", loader: "js" }));
|
|
223
|
+
},
|
|
224
|
+
};
|
|
225
|
+
}
|
|
226
|
+
/**
|
|
227
|
+
* Bundles one worker without writing files. Returns its bytes and report; the caller
|
|
228
|
+
* (the deployment tool or E2E) chooses where and under what name to place them.
|
|
229
|
+
*/
|
|
230
|
+
export async function buildWorker(opts) {
|
|
231
|
+
const outfile = opts.outfile ?? "worker/index.js";
|
|
232
|
+
const pass = async (banner) => {
|
|
233
|
+
const state = { nodeBuiltins: new Set(), requireBuiltins: new Set(), wasm: new Map() };
|
|
234
|
+
const options = {
|
|
235
|
+
bundle: true,
|
|
236
|
+
// Do not use the `browser` condition or field: TypeORM's package.json `browser` map
|
|
237
|
+
// replaces every driver with an empty stub, leaving DataSource without a driver.
|
|
238
|
+
platform: "neutral",
|
|
239
|
+
conditions: ["workerd", "worker", "node", "import", "default"],
|
|
240
|
+
mainFields: ["module", "main"],
|
|
241
|
+
format: "esm",
|
|
242
|
+
target: "es2022",
|
|
243
|
+
// Do not escape non-ASCII strings as \u: workerd reads UTF-8 directly, and Korean
|
|
244
|
+
// messages in stacks must remain human-readable.
|
|
245
|
+
charset: "utf8",
|
|
246
|
+
entryPoints: [opts.entry],
|
|
247
|
+
outfile,
|
|
248
|
+
absWorkingDir: opts.absWorkingDir,
|
|
249
|
+
plugins: [workerPlugin(state, opts)],
|
|
250
|
+
external: ["node:*", "cloudflare:*"],
|
|
251
|
+
define: { "process.env.NODE_ENV": '"production"', ...(opts.define ?? {}) },
|
|
252
|
+
write: false,
|
|
253
|
+
logLevel: "silent",
|
|
254
|
+
...(opts.minify ? { minify: true } : {}),
|
|
255
|
+
...(banner !== undefined ? { banner: { js: banner } } : {}),
|
|
256
|
+
};
|
|
257
|
+
const r = await build(options);
|
|
258
|
+
const file = r.outputFiles?.[0];
|
|
259
|
+
if (!file)
|
|
260
|
+
throw new Error("esbuild produced no output");
|
|
261
|
+
return { code: file.contents, state };
|
|
262
|
+
};
|
|
263
|
+
let { code, state } = await pass();
|
|
264
|
+
// If CJS required Node built-ins, bundle again with the banner's require table.
|
|
265
|
+
if (state.requireBuiltins.size > 0) {
|
|
266
|
+
({ code, state } = await pass(requireBanner(state.requireBuiltins)));
|
|
267
|
+
}
|
|
268
|
+
return {
|
|
269
|
+
code,
|
|
270
|
+
report: {
|
|
271
|
+
nodeImports: [...state.nodeBuiltins].sort(),
|
|
272
|
+
wasmModules: [...state.wasm.entries()].map(([name, path]) => ({ name, path })).sort((a, b) => a.name.localeCompare(b.name)),
|
|
273
|
+
},
|
|
274
|
+
};
|
|
275
|
+
}
|
|
276
|
+
//# sourceMappingURL=bundler.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"bundler.js","sourceRoot":"","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,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,aAAa,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC;SAC5H;KACF,CAAC;AACJ,CAAC"}
|
package/dist/client.d.ts
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
import { Emitter } from "./emitter.js";
|
|
2
|
+
import { DatabaseError } from "./errors.js";
|
|
3
|
+
import { types, type TypeParser } from "./type-parsers.js";
|
|
4
|
+
import type { Db, DbSession } from "./types.js";
|
|
5
|
+
export interface FieldDef {
|
|
6
|
+
name: string;
|
|
7
|
+
tableID: number;
|
|
8
|
+
columnID: number;
|
|
9
|
+
dataTypeID: number;
|
|
10
|
+
dataTypeSize: number;
|
|
11
|
+
dataTypeModifier: number;
|
|
12
|
+
format: string;
|
|
13
|
+
}
|
|
14
|
+
export interface QueryResult<R = Record<string, unknown>> {
|
|
15
|
+
command: string;
|
|
16
|
+
rowCount: number | null;
|
|
17
|
+
oid: number;
|
|
18
|
+
rows: R[];
|
|
19
|
+
fields: FieldDef[];
|
|
20
|
+
}
|
|
21
|
+
export interface QueryConfig {
|
|
22
|
+
text: string;
|
|
23
|
+
values?: unknown[] | undefined;
|
|
24
|
+
name?: string | undefined;
|
|
25
|
+
rowMode?: "array" | undefined;
|
|
26
|
+
types?: {
|
|
27
|
+
getTypeParser(oid: number, format: "text"): TypeParser;
|
|
28
|
+
} | undefined;
|
|
29
|
+
}
|
|
30
|
+
export type QueryCallback<R = Record<string, unknown>> = (err: Error | null, result?: QueryResult<R>) => void;
|
|
31
|
+
/** The material for `new Client({ db })` / `new Pool({ db })`. The other keys
|
|
32
|
+
* are there for pg compatibility and are ignored. */
|
|
33
|
+
export interface ClientConfig {
|
|
34
|
+
db?: Db | undefined;
|
|
35
|
+
[key: string]: unknown;
|
|
36
|
+
}
|
|
37
|
+
/** Moves a CommandComplete tag into pg's `command`, `rowCount` and `oid`. */
|
|
38
|
+
export declare function parseCommandTag(tag: string | null): {
|
|
39
|
+
command: string;
|
|
40
|
+
rowCount: number | null;
|
|
41
|
+
oid: number;
|
|
42
|
+
};
|
|
43
|
+
/**
|
|
44
|
+
* A client that holds one session. `connect()` opens the session and `end()`
|
|
45
|
+
* closes it. A `query` before `connect()` opens the session on its own — pg
|
|
46
|
+
* throws there, but opening is easier for an ORM to deal with and loses
|
|
47
|
+
* nothing.
|
|
48
|
+
*/
|
|
49
|
+
export declare class Client extends Emitter {
|
|
50
|
+
#private;
|
|
51
|
+
readonly db: Db;
|
|
52
|
+
/** Sequelize hooks `client.connection.on('parameterStatus')`. */
|
|
53
|
+
readonly connection: Emitter;
|
|
54
|
+
readonly processID: number | null;
|
|
55
|
+
readonly secretKey: number | null;
|
|
56
|
+
_ending: boolean;
|
|
57
|
+
_connected: boolean;
|
|
58
|
+
_connecting: boolean;
|
|
59
|
+
constructor(config: ClientConfig | Db);
|
|
60
|
+
get session(): DbSession | null;
|
|
61
|
+
connect(): Promise<void>;
|
|
62
|
+
connect(cb: (err: Error | null) => void): void;
|
|
63
|
+
query<R = Record<string, unknown>>(text: string | QueryConfig, values?: unknown[]): Promise<QueryResult<R>>;
|
|
64
|
+
query<R = Record<string, unknown>>(text: string | QueryConfig, cb: QueryCallback<R>): void;
|
|
65
|
+
query<R = Record<string, unknown>>(text: string | QueryConfig, values: unknown[], cb: QueryCallback<R>): void;
|
|
66
|
+
end(): Promise<void>;
|
|
67
|
+
end(cb: (err?: Error) => void): void;
|
|
68
|
+
escapeIdentifier(s: string): string;
|
|
69
|
+
escapeLiteral(s: string): string;
|
|
70
|
+
}
|
|
71
|
+
export declare class PoolClient extends Client {
|
|
72
|
+
#private;
|
|
73
|
+
constructor(pool: Pool, db: Db);
|
|
74
|
+
/** pg's `release(err?)`. Passing an error throws the session away — we
|
|
75
|
+
* always throw it away, so it is the same. */
|
|
76
|
+
release(_err?: Error | boolean): void;
|
|
77
|
+
}
|
|
78
|
+
export interface PoolConfig extends ClientConfig {
|
|
79
|
+
max?: number | undefined;
|
|
80
|
+
/**
|
|
81
|
+
* How long `connect()` and `end()` wait for the closes that `release()`
|
|
82
|
+
* started, in milliseconds. Defaults to `DEFAULT_CLOSE_WAIT_MS`.
|
|
83
|
+
*
|
|
84
|
+
* The wait is bounded on purpose: a close that never settles — a session the
|
|
85
|
+
* actor has already lost — must not turn into a pool that never hands out a
|
|
86
|
+
* client again. pg has no such option and ignores unknown ones, so this is
|
|
87
|
+
* additive.
|
|
88
|
+
*/
|
|
89
|
+
closeWaitMs?: number | undefined;
|
|
90
|
+
}
|
|
91
|
+
/** The bound on how long a pool waits for `release()`'s closes. */
|
|
92
|
+
export declare const DEFAULT_CLOSE_WAIT_MS = 5000;
|
|
93
|
+
export declare class Pool extends Emitter {
|
|
94
|
+
#private;
|
|
95
|
+
readonly db: Db;
|
|
96
|
+
readonly options: PoolConfig;
|
|
97
|
+
constructor(config: PoolConfig | Db);
|
|
98
|
+
get totalCount(): number;
|
|
99
|
+
get idleCount(): number;
|
|
100
|
+
get waitingCount(): number;
|
|
101
|
+
get ended(): boolean;
|
|
102
|
+
connect(): Promise<PoolClient>;
|
|
103
|
+
connect(cb: (err: Error | null, client?: PoolClient, release?: (err?: Error) => void) => void): void;
|
|
104
|
+
/** Called by `PoolClient.release()`, which cannot await its own close. */
|
|
105
|
+
_closing(close: Promise<void>): void;
|
|
106
|
+
_forget(c: PoolClient): void;
|
|
107
|
+
/** A query with no session. The facade's session-per-call is the same as
|
|
108
|
+
* pg's "borrow it, use it, give it back". */
|
|
109
|
+
query<R = Record<string, unknown>>(text: string | QueryConfig, values?: unknown[]): Promise<QueryResult<R>>;
|
|
110
|
+
query<R = Record<string, unknown>>(text: string | QueryConfig, cb: QueryCallback<R>): void;
|
|
111
|
+
query<R = Record<string, unknown>>(text: string | QueryConfig, values: unknown[], cb: QueryCallback<R>): void;
|
|
112
|
+
end(): Promise<void>;
|
|
113
|
+
end(cb: (err?: Error) => void): void;
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* A pg-shaped module with `db` bound in advance.
|
|
117
|
+
*
|
|
118
|
+
* It is handed to the places where an ORM takes a whole driver module
|
|
119
|
+
* (TypeORM's `driver`, Sequelize's `dialectModule`, Knex's `_driver()`). Those
|
|
120
|
+
* ORMs call `new Pool(options)` with their own options, so there is no way to
|
|
121
|
+
* put `db` into the options — it is bound here.
|
|
122
|
+
*/
|
|
123
|
+
export declare function pgModule(db: Db): PgModule;
|
|
124
|
+
export interface PgModule {
|
|
125
|
+
Client: typeof Client;
|
|
126
|
+
Pool: typeof Pool;
|
|
127
|
+
DatabaseError: typeof DatabaseError;
|
|
128
|
+
defaults: typeof defaults;
|
|
129
|
+
/** Sequelize's `lib.types.getTypeParser`, Drizzle's `types.builtins`. */
|
|
130
|
+
types: typeof types;
|
|
131
|
+
native: null;
|
|
132
|
+
escapeIdentifier(s: string): string;
|
|
133
|
+
escapeLiteral(s: string): string;
|
|
134
|
+
}
|
|
135
|
+
/** pg's `defaults`. TypeORM touches `parseInt8` — we always keep int8 as a
|
|
136
|
+
* string. */
|
|
137
|
+
export declare const defaults: Record<string, unknown>;
|
|
138
|
+
//# sourceMappingURL=client.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAOA,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AACvC,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC5C,OAAO,EAAe,KAAK,EAAE,KAAK,UAAU,EAAE,MAAM,mBAAmB,CAAC;AACxE,OAAO,KAAK,EAAE,EAAE,EAAE,SAAS,EAAiB,MAAM,YAAY,CAAC;AAE/D,MAAM,WAAW,QAAQ;IACvB,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;IAChB,QAAQ,EAAE,MAAM,CAAC;IACjB,UAAU,EAAE,MAAM,CAAC;IACnB,YAAY,EAAE,MAAM,CAAC;IACrB,gBAAgB,EAAE,MAAM,CAAC;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