@cossackframework/database 0.8.3 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -7
- package/agent-docs.json +90 -0
- package/dist/adapter/types.d.ts +14 -1
- package/dist/adapter/types.d.ts.map +1 -1
- package/dist/config.d.ts +10 -1
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js.map +1 -1
- package/dist/cossack/cache-policy.d.ts +18 -0
- package/dist/cossack/cache-policy.d.ts.map +1 -0
- package/dist/cossack/cache-policy.js +64 -0
- package/dist/cossack/cache-policy.js.map +1 -0
- package/dist/cossack/index.d.ts +20 -3
- package/dist/cossack/index.d.ts.map +1 -1
- package/dist/cossack/index.js +105 -51
- package/dist/cossack/index.js.map +1 -1
- package/dist/index.d.ts +5 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -1
- package/dist/metadata/finalize.d.ts.map +1 -1
- package/dist/metadata/finalize.js +22 -5
- package/dist/metadata/finalize.js.map +1 -1
- package/dist/metadata/inspection.d.ts +51 -0
- package/dist/metadata/inspection.d.ts.map +1 -0
- package/dist/metadata/inspection.js +19 -0
- package/dist/metadata/inspection.js.map +1 -0
- package/dist/migration/plan.d.ts +13 -0
- package/dist/migration/plan.d.ts.map +1 -0
- package/dist/migration/plan.js +73 -0
- package/dist/migration/plan.js.map +1 -0
- package/dist/migration/runner.d.ts +13 -3
- package/dist/migration/runner.d.ts.map +1 -1
- package/dist/migration/runner.js +143 -11
- package/dist/migration/runner.js.map +1 -1
- package/dist/migration/types.d.ts +42 -2
- package/dist/migration/types.d.ts.map +1 -1
- package/dist/orm.d.ts +51 -0
- package/dist/orm.d.ts.map +1 -1
- package/dist/orm.js +44 -11
- package/dist/orm.js.map +1 -1
- package/dist/query/builder.d.ts +3 -2
- package/dist/query/builder.d.ts.map +1 -1
- package/dist/query/builder.js +63 -12
- package/dist/query/builder.js.map +1 -1
- package/dist/query/diagnostics.d.ts +3 -0
- package/dist/query/diagnostics.d.ts.map +1 -0
- package/dist/query/diagnostics.js +75 -0
- package/dist/query/diagnostics.js.map +1 -0
- package/dist/runtime/cloudflare-turso.d.ts +29 -0
- package/dist/runtime/cloudflare-turso.d.ts.map +1 -0
- package/dist/runtime/cloudflare-turso.js +47 -0
- package/dist/runtime/cloudflare-turso.js.map +1 -0
- package/dist/runtime/cloudflare.d.ts +1 -26
- package/dist/runtime/cloudflare.d.ts.map +1 -1
- package/dist/runtime/cloudflare.js +4 -45
- package/dist/runtime/cloudflare.js.map +1 -1
- package/dist/runtime/node.d.ts +2 -0
- package/dist/runtime/node.d.ts.map +1 -1
- package/dist/runtime/node.js +6 -1
- package/dist/runtime/node.js.map +1 -1
- package/dist/runtime/turso.d.ts +5 -1
- package/dist/runtime/turso.d.ts.map +1 -1
- package/dist/runtime/turso.js +19 -5
- package/dist/runtime/turso.js.map +1 -1
- package/dist/runtime-capabilities.d.ts +25 -0
- package/dist/runtime-capabilities.d.ts.map +1 -0
- package/dist/runtime-capabilities.js +17 -0
- package/dist/runtime-capabilities.js.map +1 -0
- package/dist/schema/builder.d.ts.map +1 -1
- package/dist/schema/builder.js +6 -10
- package/dist/schema/builder.js.map +1 -1
- package/dist/schema/ddl.d.ts.map +1 -1
- package/dist/schema/ddl.js +29 -5
- package/dist/schema/ddl.js.map +1 -1
- package/dist/schema/introspection.d.ts +3 -1
- package/dist/schema/introspection.d.ts.map +1 -1
- package/dist/schema/introspection.js +9 -7
- package/dist/schema/introspection.js.map +1 -1
- package/dist/seeding/runner.d.ts +5 -1
- package/dist/seeding/runner.d.ts.map +1 -1
- package/dist/seeding/runner.js +66 -1
- package/dist/seeding/runner.js.map +1 -1
- package/dist/seeding/types.d.ts +15 -1
- package/dist/seeding/types.d.ts.map +1 -1
- package/dist/seeding/types.js.map +1 -1
- package/dist/sql/client.d.ts +1 -1
- package/dist/sql/client.d.ts.map +1 -1
- package/dist/sql/client.js +10 -51
- package/dist/sql/client.js.map +1 -1
- package/dist/sql/node-client.d.ts +7 -0
- package/dist/sql/node-client.d.ts.map +1 -0
- package/dist/sql/node-client.js +61 -0
- package/dist/sql/node-client.js.map +1 -0
- package/dist/tooling/cloudflare.d.ts +61 -0
- package/dist/tooling/cloudflare.d.ts.map +1 -0
- package/dist/tooling/cloudflare.js +130 -0
- package/dist/tooling/cloudflare.js.map +1 -0
- package/dist/tooling/generate.d.ts.map +1 -1
- package/dist/tooling/generate.js +5 -15
- package/dist/tooling/generate.js.map +1 -1
- package/dist/tooling/index.d.ts +6 -2
- package/dist/tooling/index.d.ts.map +1 -1
- package/dist/tooling/index.js +231 -64
- package/dist/tooling/index.js.map +1 -1
- package/dist/tooling/inspection.d.ts +40 -0
- package/dist/tooling/inspection.d.ts.map +1 -0
- package/dist/tooling/inspection.js +63 -0
- package/dist/tooling/inspection.js.map +1 -0
- package/dist/tooling/process-json.d.ts +4 -0
- package/dist/tooling/process-json.d.ts.map +1 -0
- package/dist/tooling/process-json.js +79 -0
- package/dist/tooling/process-json.js.map +1 -0
- package/docs/comparison.md +3 -3
- package/docs/inspection.md +50 -0
- package/docs/installation.md +0 -2
- package/docs/introduction.md +1 -1
- package/docs/migrations.md +90 -1
- package/docs/queries.md +18 -0
- package/docs/raw-queries.md +19 -4
- package/docs/relationships.md +11 -0
- package/docs/runtimes.md +77 -36
- package/docs/seeders.md +38 -0
- package/package.json +5 -4
- package/dist/runtime/deno.d.ts +0 -38
- package/dist/runtime/deno.d.ts.map +0 -1
- package/dist/runtime/deno.js +0 -57
- package/dist/runtime/deno.js.map +0 -1
package/README.md
CHANGED
|
@@ -116,10 +116,10 @@ Values always become parameters. `sql.id()` is the identifier escape hatch,
|
|
|
116
116
|
builds object/bulk insert tuples. `sql.unsafe()` is the only API that injects
|
|
117
117
|
literal SQL.
|
|
118
118
|
|
|
119
|
-
`
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
119
|
+
The neutral `SQL` export accepts an explicit adapter, so it is safe in Workers.
|
|
120
|
+
For lazy Node/Bun adapter selection from a URL or SQLite path, import `SQL` from
|
|
121
|
+
`@cossackframework/database/node`. Workers should pass their D1, Hyperdrive or
|
|
122
|
+
Turso adapter explicitly rather than guess from an environment URL.
|
|
123
123
|
|
|
124
124
|
## Relations
|
|
125
125
|
|
|
@@ -142,11 +142,10 @@ are never replayed across an in-memory object graph.
|
|
|
142
142
|
|
|
143
143
|
| Runtime entry | Adapters |
|
|
144
144
|
| --- | --- |
|
|
145
|
-
| `@cossackframework/database/node` | `nodeSQLite`, `betterSQLite`, `postgres`, `mysql`, `turso` |
|
|
146
|
-
| `@cossackframework/database/deno` | `deno`, `denoSQLite`, `postgres`, `mysql`, `turso` |
|
|
145
|
+
| `@cossackframework/database/node` | `nodeSQLite`, `betterSQLite`, `postgres`, `mysql`, `turso`, `SQL` |
|
|
147
146
|
| `@cossackframework/database/bun` | `bun` over the documented Bun SQL core API |
|
|
148
147
|
| `@cossackframework/database/cloudflare` | `d1`, `hyperdrivePostgres`, `hyperdriveMySQL` |
|
|
149
|
-
| `@cossackframework/database/
|
|
148
|
+
| `@cossackframework/database/cloudflare-turso` | `turso` (remote Turso on Workers) |
|
|
150
149
|
| `@cossackframework/database/adapter` | public dialect, driver, result, scope, and capability contracts |
|
|
151
150
|
| `@cossackframework/database/cossack` | middleware plus database cache/session stores |
|
|
152
151
|
|
package/agent-docs.json
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
{
|
|
2
|
+
"schemaVersion": 1,
|
|
3
|
+
"guides": [
|
|
4
|
+
{
|
|
5
|
+
"id": "parameterized-node-sqlite",
|
|
6
|
+
"title": "Run parameterized SQL with an owned ORM",
|
|
7
|
+
"summary": "Create a Node SQLite adapter, execute bound SQL through an explicit ORM instance, and close the database you own.",
|
|
8
|
+
"imports": [
|
|
9
|
+
"@cossackframework/database",
|
|
10
|
+
"@cossackframework/database/node"
|
|
11
|
+
],
|
|
12
|
+
"markdown": "Use a runtime-specific entry point for the adapter. This example uses Node 22 or later and the built-in SQLite adapter, so it needs no native driver package. The neutral package root exports ORM APIs; do not import Node adapters from code that must run in Workers. For Cloudflare, use the D1 or Hyperdrive adapter from `@cossackframework/database/cloudflare` and pass the binding explicitly. Generated Cloudflare apps need Workers Node compatibility support for AsyncLocalStorage request scopes. `nodejs_als` enables only that API when the compatibility date does not already provide it. D1's binding offers atomic sequential `batch()` calls, but the ORM does not expose general interactive transactions, savepoints, connection reservation, or query cancellation; check its capability limits before relying on those operations.\n\nWhen you own an ORM instance, `orm.sql` executes directly without a current request scope. Use `orm.run()` around static Active Record calls and the global `sql` tag. Close an ORM only when your code owns its adapter; request middleware owns adapters it creates.\n\nInterpolated values become bound parameters. Use `orm.sql.id()` for table and column names. Never build identifiers from request values, and reserve `sql.unsafe()` for reviewed static SQL. Keep schema changes in migrations rather than synchronizing production schemas at startup.\n\nThe executable example uses an isolated in-memory SQLite database and proves Node package behavior only. It does not establish D1, PostgreSQL, MySQL, or Hyperdrive compatibility for SQLite-specific SQL.",
|
|
13
|
+
"examples": [
|
|
14
|
+
{
|
|
15
|
+
"id": "bound-sql",
|
|
16
|
+
"language": "typescript",
|
|
17
|
+
"source": "import { createORM } from '@cossackframework/database';\nimport { nodeSQLite } from '@cossackframework/database/node';\n\nconst orm = createORM({ adapter: await nodeSQLite(), entities: [] });\ntry {\n const notes = orm.sql.id('notes');\n const body = orm.sql.id('body');\n await orm.sql`CREATE TABLE ${notes} (${body} TEXT NOT NULL)`;\n await orm.sql`INSERT INTO ${notes} (${body}) VALUES (${'hello'})`;\n\n const hostile = \"' OR 1=1 --\";\n const result = await orm.sql<{ body: string }>`SELECT ${body} FROM ${notes} WHERE ${body} = ${hostile}`;\n if (result.rows.length !== 0) throw new Error('Query input must remain a bound value');\n\n const stored = await orm.sql<{ body: string }>`SELECT ${body} FROM ${notes} WHERE ${body} = ${'hello'}`;\n if (stored.rows[0]?.body !== 'hello') throw new Error('The safe value was not stored');\n} finally {\n await orm.close();\n}\n"
|
|
18
|
+
}
|
|
19
|
+
]
|
|
20
|
+
},
|
|
21
|
+
{
|
|
22
|
+
"id": "cloudflare-d1-bound-query",
|
|
23
|
+
"title": "Query Cloudflare D1 with bound values",
|
|
24
|
+
"summary": "Create the D1 adapter from a Worker binding and keep request values in prepared-statement parameters.",
|
|
25
|
+
"imports": [
|
|
26
|
+
"@cossackframework/database",
|
|
27
|
+
"@cossackframework/database/cloudflare"
|
|
28
|
+
],
|
|
29
|
+
"markdown": "Import `d1` from `@cossackframework/database/cloudflare` and pass the D1 binding from the Worker's `env`. Do not import runtime adapters from the neutral database package. The example assumes a `notes` table created by a migration and uses an owned ORM for one direct query. In a Cossack app, prefer the request ORM middleware so it owns request scoping and cleanup.\n\nThe SQL tag binds interpolated values. Use `orm.sql.id()` for dynamic table or column names. D1 uses prepared statements and supports atomic sequential `batch()` calls. It does not support interactive transactions, savepoints, connection reservation or cancellation; unsupported transaction operations raise `UnsupportedCapabilityError`. The migration runner submits schema changes and migration bookkeeping in one D1 batch. Do not treat multiple ordinary queries as one transaction.\n\nThe installed docs acceptance runs this exact example in workerd with a local D1 database and checks that SQL-looking input stays a bound value. It does not provision or contact a Cloudflare account. For Worker request scopes that rely on AsyncLocalStorage, check the compatibility date and enable the Workers Node compatibility support only when needed.",
|
|
30
|
+
"examples": [
|
|
31
|
+
{
|
|
32
|
+
"id": "bound-query",
|
|
33
|
+
"language": "typescript",
|
|
34
|
+
"source": "import { createORM } from '@cossackframework/database';\nimport { d1, type D1DatabaseBinding } from '@cossackframework/database/cloudflare';\n\nexport async function findNote(database: D1DatabaseBinding, body: string) {\n const orm = createORM({ adapter: await d1(database), entities: [] });\n try {\n const result = await orm.sql<{ body: string }>`SELECT body FROM notes WHERE body = ${body}`;\n return result.rows[0]?.body;\n } finally {\n await orm.close();\n }\n}\n"
|
|
35
|
+
}
|
|
36
|
+
]
|
|
37
|
+
},
|
|
38
|
+
{
|
|
39
|
+
"id": "node-sqlite-migrations-and-seeding",
|
|
40
|
+
"title": "Apply migrations and rerunnable seeders",
|
|
41
|
+
"summary": "Run a reversible migration, verify its recorded status, and seed stable records idempotently.",
|
|
42
|
+
"imports": [
|
|
43
|
+
"@cossackframework/database",
|
|
44
|
+
"@cossackframework/database/node"
|
|
45
|
+
],
|
|
46
|
+
"markdown": "Use MigrationRunner to apply versioned schema changes and SeederRunner for application data. Migrations are ordered by their stable names and store a checksum; once applied, edit by adding a new migration instead of changing its source. This example uses reviewed, static SQLite DDL because it targets the Node SQLite adapter. Keep values in seeder SQL bound parameters.\n\nSeeder callbacks run in configuration order and are not recorded as applied migrations. Make them safe to repeat with a stable key or upsert. The default `auto` transaction policy uses a transaction when the adapter supports it. D1 does not support interactive transactions, so `auto` runs without one there and `required` fails before the callback. D1 migrations use an atomic prepared batch.\n\nThis in-memory example proves the installed Node SQLite migration and seeder APIs, including apply, status, repeat execution and rollback. It does not establish D1, PostgreSQL or MySQL compatibility for SQLite-specific SQL, nor does it prove a deployed database is ready.",
|
|
47
|
+
"examples": [
|
|
48
|
+
{
|
|
49
|
+
"id": "migration-and-seeder-lifecycle",
|
|
50
|
+
"language": "typescript",
|
|
51
|
+
"source": "import { createORM, defineSeeder, MigrationRunner, SeederRunner, type Migration } from '@cossackframework/database';\nimport { nodeSQLite } from '@cossackframework/database/node';\n\nconst migration = {\n name: '0001_create_guide_notes',\n up({ orm, schema }) {\n schema.raw(orm.sql.fragment`CREATE TABLE guide_notes (id INTEGER PRIMARY KEY, key TEXT NOT NULL UNIQUE, body TEXT NOT NULL)`);\n },\n down({ orm, schema }) {\n schema.raw(orm.sql.fragment`DROP TABLE guide_notes`);\n },\n} satisfies Migration;\n\nconst orm = createORM({ adapter: await nodeSQLite(), entities: [] });\ntry {\n const migrations = new MigrationRunner(orm, [migration]);\n const applied = await orm.run(() => migrations.up());\n if (applied[0] !== migration.name) throw new Error('Migration was not applied');\n\n const status = await orm.run(() => migrations.status());\n if (status[0]?.state !== 'applied') throw new Error('Migration checksum status is not applied');\n\n const welcome = defineSeeder({\n name: 'welcome-note',\n async run({ sql }) {\n await sql`INSERT INTO guide_notes (key, body) VALUES (${'welcome'}, ${'Hello'}) ON CONFLICT (key) DO UPDATE SET body = excluded.body`;\n },\n });\n const seeders = new SeederRunner(orm, [welcome]);\n await seeders.run();\n await seeders.run();\n\n const notes = await orm.sql<{ key: string; body: string }>`SELECT key, body FROM guide_notes`;\n if (notes.rows.length !== 1 || notes.rows[0]?.key !== 'welcome') {\n throw new Error('Repeating the seeder must not duplicate its stable key');\n }\n\n const reverted = await orm.run(() => migrations.down());\n if (reverted[0] !== migration.name) throw new Error('Migration was not reverted');\n} finally {\n await orm.close();\n}\n"
|
|
52
|
+
}
|
|
53
|
+
]
|
|
54
|
+
},
|
|
55
|
+
{
|
|
56
|
+
"id": "typed-model-queries",
|
|
57
|
+
"title": "Query typed models with operators and projections",
|
|
58
|
+
"summary": "Register a decorated entity, filter with typed operators, and select a narrow raw result with the query builder.",
|
|
59
|
+
"imports": [
|
|
60
|
+
"@cossackframework/database",
|
|
61
|
+
"@cossackframework/database/node"
|
|
62
|
+
],
|
|
63
|
+
"markdown": "Decorated models describe logical columns and must be included in `createORM({ entities })`. Use `orm.model(Note)` when the caller already owns an ORM; its methods do not need an ambient request scope. Static `Note.find()` and instance persistence methods do need `orm.run()`. Keep schema creation in migrations in applications; this isolated example uses reviewed SQLite DDL for its in-memory database.\n\n`find()` accepts typed `where`, `select`, ordering, and pagination options. Find operators such as `MoreThanOrEqual()` express comparisons while keeping values bound. The fluent builder supports typed predicates and projections; `getRawMany()` returns the selected row shape, while `getMany()` hydrates complete model instances. Never interpolate user input into SQL text or identifiers. This example proves only the Node SQLite path.",
|
|
64
|
+
"examples": [
|
|
65
|
+
{
|
|
66
|
+
"id": "typed-query-and-projection",
|
|
67
|
+
"language": "typescript",
|
|
68
|
+
"source": "import { BaseEntity, Column, Entity, MoreThanOrEqual, PrimaryGeneratedColumn, createORM } from '@cossackframework/database';\nimport { nodeSQLite } from '@cossackframework/database/node';\n\n@Entity()\nclass Note extends BaseEntity {\n @PrimaryGeneratedColumn()\n declare id: number;\n\n @Column({ type: 'text' })\n declare title: string;\n\n @Column({ type: 'integer' })\n declare priority: number;\n\n @Column({ type: 'boolean' })\n declare published: boolean;\n}\n\nconst orm = createORM({ adapter: await nodeSQLite(), entities: [Note] });\ntry {\n const notes = orm.sql.id('notes');\n await orm.sql`CREATE TABLE ${notes} (id INTEGER PRIMARY KEY, title TEXT NOT NULL, priority INTEGER NOT NULL, published INTEGER NOT NULL)`;\n await orm.model(Note).insert([\n { title: 'Draft', priority: 1, published: false },\n { title: 'Query guide', priority: 3, published: true },\n { title: 'Release notes', priority: 2, published: true },\n ]);\n\n const highPriority = await orm.model(Note).find({\n where: { published: true, priority: MoreThanOrEqual(2) },\n select: ['id', 'title'],\n order: { title: 'asc' },\n take: 2,\n });\n if (highPriority.length !== 2 || highPriority[0]?.title !== 'Query guide') {\n throw new Error('The typed find filter or ordering returned unexpected rows');\n }\n\n const projection = await orm.model(Note).query('note')\n .select('id', 'title')\n .where(where => where.eq('published', true))\n .orderBy('priority', 'desc')\n .getRawMany();\n if (projection[0]?.title !== 'Query guide' || 'priority' in (projection[0] ?? {})) {\n throw new Error('The typed projection returned unexpected columns');\n }\n} finally {\n await orm.close();\n}\n"
|
|
69
|
+
}
|
|
70
|
+
]
|
|
71
|
+
},
|
|
72
|
+
{
|
|
73
|
+
"id": "node-sqlite-transaction-rollback",
|
|
74
|
+
"title": "Commit or roll back one Node database transaction",
|
|
75
|
+
"summary": "Group related writes in an interactive transaction and verify that failures leave no partial changes.",
|
|
76
|
+
"imports": [
|
|
77
|
+
"@cossackframework/database",
|
|
78
|
+
"@cossackframework/database/node"
|
|
79
|
+
],
|
|
80
|
+
"markdown": "Call `orm.transaction(async () => { ... })` to group writes on an adapter that supports interactive transactions. The callback uses the transaction-scoped driver, and a rejected callback rolls its writes back. Keep every operation that must commit together inside the callback. This example uses Node's in-memory SQLite adapter and only proves that runtime path. Cloudflare D1 supports atomic sequential `batch()` calls but not interactive ORM transactions; `orm.transaction()` fails before its callback on D1. Separate database connections also do not form one distributed transaction.",
|
|
81
|
+
"examples": [
|
|
82
|
+
{
|
|
83
|
+
"id": "atomic-transfer-and-rollback",
|
|
84
|
+
"language": "typescript",
|
|
85
|
+
"source": "import { createORM } from '@cossackframework/database';\nimport { nodeSQLite } from '@cossackframework/database/node';\n\nconst orm = createORM({ adapter: await nodeSQLite(), entities: [] });\ntry {\n await orm.sql`CREATE TABLE accounts (id TEXT PRIMARY KEY, balance INTEGER NOT NULL CHECK (balance >= 0))`;\n await orm.sql`INSERT INTO accounts (id, balance) VALUES (${'alice'}, ${100}), (${'bob'}, ${30})`;\n\n await orm.transaction(async () => {\n await orm.sql`UPDATE accounts SET balance = balance - ${25} WHERE id = ${'alice'}`;\n await orm.sql`UPDATE accounts SET balance = balance + ${25} WHERE id = ${'bob'}`;\n });\n\n const readBalances = () => orm.sql<{ id: string; balance: number }>`SELECT id, balance FROM accounts ORDER BY id`;\n let balances = await readBalances();\n if (balances.rows[0]?.balance !== 75 || balances.rows[1]?.balance !== 55) {\n throw new Error('The transfer did not commit both writes');\n }\n\n let rejected = false;\n try {\n await orm.transaction(async () => {\n await orm.sql`UPDATE accounts SET balance = balance - ${10} WHERE id = ${'alice'}`;\n throw new Error('cancel this transfer');\n });\n } catch (error) {\n rejected = error instanceof Error && error.message === 'cancel this transfer';\n }\n if (!rejected) throw new Error('The transaction callback error was not returned');\n\n balances = await readBalances();\n if (balances.rows[0]?.balance !== 75 || balances.rows[1]?.balance !== 55) {\n throw new Error('The failed transfer left a partial write');\n }\n} finally {\n await orm.close();\n}\n"
|
|
86
|
+
}
|
|
87
|
+
]
|
|
88
|
+
}
|
|
89
|
+
]
|
|
90
|
+
}
|
package/dist/adapter/types.d.ts
CHANGED
|
@@ -45,6 +45,16 @@ export interface ScopeStorage<T> {
|
|
|
45
45
|
export interface Adapter {
|
|
46
46
|
readonly driver: Driver;
|
|
47
47
|
readonly scope?: ScopeStorage<unknown>;
|
|
48
|
+
/** Public connection identity for tooling. Never include URLs with credentials or secret values. */
|
|
49
|
+
readonly tooling?: {
|
|
50
|
+
readonly provider: string;
|
|
51
|
+
readonly target: "local" | "remote";
|
|
52
|
+
readonly accountId?: string;
|
|
53
|
+
readonly environment?: string;
|
|
54
|
+
readonly binding?: string;
|
|
55
|
+
readonly databaseName?: string;
|
|
56
|
+
readonly databaseId?: string;
|
|
57
|
+
};
|
|
48
58
|
}
|
|
49
59
|
export interface DialectCapabilities {
|
|
50
60
|
readonly returning: boolean;
|
|
@@ -65,7 +75,10 @@ export interface LoggerEvent {
|
|
|
65
75
|
readonly durationMs: number;
|
|
66
76
|
readonly dialect: DialectName;
|
|
67
77
|
readonly operation: QueryOperation;
|
|
68
|
-
readonly
|
|
78
|
+
readonly provider: string;
|
|
79
|
+
readonly outcome: "success" | "failure";
|
|
80
|
+
/** Arbitrary driver exceptions are never passed to diagnostic observers. */
|
|
81
|
+
readonly code?: "COSSACK_DATABASE_QUERY_FAILED";
|
|
69
82
|
}
|
|
70
83
|
export interface ORMLogger {
|
|
71
84
|
query(event: LoggerEvent): void;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/adapter/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACxD,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAC;AAEpD,MAAM,MAAM,WAAW,GAAG,QAAQ,GAAG,UAAU,GAAG,OAAO,CAAC;AAC1D,MAAM,MAAM,cAAc,GAAG,QAAQ,GAAG,QAAQ,GAAG,QAAQ,GAAG,QAAQ,GAAG,KAAK,GAAG,KAAK,CAAC;AACvF,MAAM,MAAM,aAAa,GAAG,MAAM,GAAG,MAAM,GAAG,MAAM,GAAG,OAAO,GAAG,IAAI,GAAG,UAAU,GAAG,IAAI,CAAC;AAE1F,MAAM,WAAW,kBAAkB;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AAG,IAAI,CAAC;CACjC"}
|
package/dist/config.d.ts
CHANGED
|
@@ -5,7 +5,7 @@ import type { NamingStrategy } from "./metadata/naming.js";
|
|
|
5
5
|
import type { SeederInput } from "./seeding/types.js";
|
|
6
6
|
export interface ORMConfig {
|
|
7
7
|
readonly entities: readonly EntityTarget[];
|
|
8
|
-
readonly adapter: Adapter | (() => Adapter | Promise<Adapter>);
|
|
8
|
+
readonly adapter: Adapter | ((context: ORMToolingContext) => Adapter | Promise<Adapter>);
|
|
9
9
|
readonly migrations?: readonly Migration[];
|
|
10
10
|
/** Directory used by model-first migration generation. Defaults to `migrations`. */
|
|
11
11
|
readonly migrationDirectory?: string;
|
|
@@ -15,5 +15,14 @@ export interface ORMConfig {
|
|
|
15
15
|
readonly namingStrategy?: NamingStrategy;
|
|
16
16
|
readonly logger?: ORMLogger;
|
|
17
17
|
}
|
|
18
|
+
/** Node-only tooling passes this context to the application's adapter factory. */
|
|
19
|
+
export interface ORMToolingContext {
|
|
20
|
+
readonly cwd: string;
|
|
21
|
+
readonly configPath: string;
|
|
22
|
+
readonly environment?: string;
|
|
23
|
+
readonly target: "local" | "remote";
|
|
24
|
+
/** The command inspects metadata/state and must not apply changes. */
|
|
25
|
+
readonly readOnly: boolean;
|
|
26
|
+
}
|
|
18
27
|
export declare function defineConfig<const T extends ORMConfig>(config: T): T;
|
|
19
28
|
//# sourceMappingURL=config.d.ts.map
|
package/dist/config.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAC;AAC7D,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AACxD,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,sBAAsB,CAAC;AACtD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;A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AC,UAAU,EAAE,MAAM,CAAC;IAC5B,QAAQ,CAAC,WAAW,CAAC,EAAE,MAAM,CAAC;IAC9B,QAAQ,CAAC,MAAM,EAAE,OAAO,GAAG,QAAQ,CAAC;IACpC,sEAAsE;IACtE,QAAQ,CAAC,QAAQ,EAAE,OAAO,CAAC;CAC5B;AAED,wBAAgB,YAAY,CAAC,KAAK,CAAC,CAAC,SAAS,SAAS,EAAE,MAAM,EAAE,CAAC,GAAG,CAAC,CAEpE"}
|
package/dist/config.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"config.js","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"config.js","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AA6BA,MAAM,UAAU,YAAY,CAA4B,MAAS;IAC/D,OAAO,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;AAC/B,CAAC"}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/** Private cache validation. Public durations are integer milliseconds. */
|
|
2
|
+
export declare const CACHE_MAX_KEY_BYTES = 512;
|
|
3
|
+
export declare const CACHE_MAX_VALUE_BYTES: number;
|
|
4
|
+
export declare const CACHE_MAX_BATCH_ENTRIES = 128;
|
|
5
|
+
export declare const CACHE_MAX_BATCH_BYTES: number;
|
|
6
|
+
export declare function cacheKey(key: unknown): asserts key is string;
|
|
7
|
+
export declare function cacheExpiry(ttlMs?: number): number | undefined;
|
|
8
|
+
export declare function cacheJson(value: unknown): string | undefined;
|
|
9
|
+
export declare function cacheKeys(keys: unknown): asserts keys is string[];
|
|
10
|
+
export type PreparedCacheEntry = {
|
|
11
|
+
key: string;
|
|
12
|
+
raw?: string | undefined;
|
|
13
|
+
expiresAt?: number | undefined;
|
|
14
|
+
ttlMs?: number | undefined;
|
|
15
|
+
};
|
|
16
|
+
/** Snapshot values and validate the entire batch before performing any writes. */
|
|
17
|
+
export declare function prepareCacheEntries(entries: unknown): PreparedCacheEntry[];
|
|
18
|
+
//# sourceMappingURL=cache-policy.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cache-policy.d.ts","sourceRoot":"","sources":["../../src/cossack/cache-policy.ts"],"names":[],"mappings":"AAAA,2EAA2E;AAC3E,eAAO,MAAM,mBAAmB,MAAM,CAAC;AACvC,eAAO,MAAM,qBAAqB,QAAc,CAAC;AACjD,eAAO,MAAM,uBAAuB,MAAM,CAAC;AAC3C,eAAO,MAAM,qBAAqB,QAAkB,CAAC;AAGrD,wBAAgB,QAAQ,CAAC,GAAG,EAAE,OAAO,GAAG,OAAO,CAAC,GAAG,IAAI,MAAM,CAK5D;AAED,wBAAgB,WAAW,CAAC,KAAK,CAAC,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAU9D;AAED,wBAAgB,SAAS,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,GAAG,SAAS,CAQ5D;AAED,wBAAgB,SAAS,CAAC,IAAI,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,IAAI,MAAM,EAAE,CAKjE;AAED,MAAM,MAAM,kBAAkB,GAAG;IAAE,GAAG,EAAE,MAAM,CAAC;IAAC,GAAG,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IAAC,SAAS,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IAAC,KAAK,CAAC,EAAE,MAAM,GAAG,SAAS,CAAA;CAAE,CAAC;AAEvI,kFAAkF;AAClF,wBAAgB,mBAAmB,CAAC,OAAO,EAAE,OAAO,GAAG,kBAAkB,EAAE,CAgB1E"}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
/** Private cache validation. Public durations are integer milliseconds. */
|
|
2
|
+
export const CACHE_MAX_KEY_BYTES = 512;
|
|
3
|
+
export const CACHE_MAX_VALUE_BYTES = 1024 * 1024;
|
|
4
|
+
export const CACHE_MAX_BATCH_ENTRIES = 128;
|
|
5
|
+
export const CACHE_MAX_BATCH_BYTES = 2 * 1024 * 1024;
|
|
6
|
+
const encoder = new TextEncoder();
|
|
7
|
+
export function cacheKey(key) {
|
|
8
|
+
if (typeof key !== 'string' || key.length === 0 || encoder.encode(key).length > CACHE_MAX_KEY_BYTES ||
|
|
9
|
+
new TextDecoder().decode(encoder.encode(key)) !== key) {
|
|
10
|
+
throw new Error('[Cossack] Cache keys must be nonempty valid UTF-8 strings of at most 512 bytes.');
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
export function cacheExpiry(ttlMs) {
|
|
14
|
+
if (ttlMs === undefined)
|
|
15
|
+
return undefined;
|
|
16
|
+
if (!Number.isSafeInteger(ttlMs) || ttlMs < 0) {
|
|
17
|
+
throw new Error('[Cossack] Cache ttlMs must be a nonnegative integer with a valid expiration timestamp.');
|
|
18
|
+
}
|
|
19
|
+
const expiresAt = Date.now() + ttlMs;
|
|
20
|
+
if (expiresAt > 8_640_000_000_000_000) {
|
|
21
|
+
throw new Error('[Cossack] Cache ttlMs must be a nonnegative integer with a valid expiration timestamp.');
|
|
22
|
+
}
|
|
23
|
+
return expiresAt;
|
|
24
|
+
}
|
|
25
|
+
export function cacheJson(value) {
|
|
26
|
+
if (value === undefined)
|
|
27
|
+
return undefined;
|
|
28
|
+
let raw;
|
|
29
|
+
try {
|
|
30
|
+
raw = JSON.stringify(value);
|
|
31
|
+
}
|
|
32
|
+
catch { /* Report no payload or secret values. */ }
|
|
33
|
+
if (raw === undefined || encoder.encode(raw).length > CACHE_MAX_VALUE_BYTES) {
|
|
34
|
+
throw new Error('[Cossack] Cache values must serialize to JSON of at most 1 MiB.');
|
|
35
|
+
}
|
|
36
|
+
return raw;
|
|
37
|
+
}
|
|
38
|
+
export function cacheKeys(keys) {
|
|
39
|
+
if (!Array.isArray(keys) || keys.length > CACHE_MAX_BATCH_ENTRIES) {
|
|
40
|
+
throw new Error('[Cossack] Cache batches accept at most 128 entries.');
|
|
41
|
+
}
|
|
42
|
+
for (const key of keys)
|
|
43
|
+
cacheKey(key);
|
|
44
|
+
}
|
|
45
|
+
/** Snapshot values and validate the entire batch before performing any writes. */
|
|
46
|
+
export function prepareCacheEntries(entries) {
|
|
47
|
+
if (!Array.isArray(entries) || entries.length > CACHE_MAX_BATCH_ENTRIES) {
|
|
48
|
+
throw new Error('[Cossack] Cache batches accept at most 128 entries.');
|
|
49
|
+
}
|
|
50
|
+
let bytes = 0;
|
|
51
|
+
return entries.map(entry => {
|
|
52
|
+
if (!entry || typeof entry !== 'object' || Array.isArray(entry) || 'ttlSeconds' in entry) {
|
|
53
|
+
throw new Error('[Cossack] Cache batch entries require key, value and optional ttlMs; ttlSeconds is unsupported.');
|
|
54
|
+
}
|
|
55
|
+
cacheKey(entry.key);
|
|
56
|
+
const expiresAt = cacheExpiry(entry.ttlMs);
|
|
57
|
+
const raw = cacheJson(entry.value);
|
|
58
|
+
bytes += encoder.encode(entry.key).length + (raw === undefined ? 0 : encoder.encode(raw).length) + 128;
|
|
59
|
+
if (bytes > CACHE_MAX_BATCH_BYTES)
|
|
60
|
+
throw new Error('[Cossack] Cache batch JSON exceeds 2 MiB.');
|
|
61
|
+
return { key: entry.key, raw, expiresAt, ttlMs: entry.ttlMs };
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
//# sourceMappingURL=cache-policy.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cache-policy.js","sourceRoot":"","sources":["../../src/cossack/cache-policy.ts"],"names":[],"mappings":"AAAA,2EAA2E;AAC3E,MAAM,CAAC,MAAM,mBAAmB,GAAG,GAAG,CAAC;AACvC,MAAM,CAAC,MAAM,qBAAqB,GAAG,IAAI,GAAG,IAAI,CAAC;AACjD,MAAM,CAAC,MAAM,uBAAuB,GAAG,GAAG,CAAC;AAC3C,MAAM,CAAC,MAAM,qBAAqB,GAAG,CAAC,GAAG,IAAI,GAAG,IAAI,CAAC;AACrD,MAAM,OAAO,GAAG,IAAI,WAAW,EAAE,CAAC;AAElC,MAAM,UAAU,QAAQ,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K,GAAG,qBAAqB;YAAE,MAAM,IAAI,KAAK,CAAC,2CAA2C,CAAC,CAAC;QAChG,OAAO,EAAE,GAAG,EAAE,KAAK,CAAC,GAAG,EAAE,GAAG,EAAE,SAAS,EAAE,KAAK,EAAE,KAAK,CAAC,KAAK,EAAE,CAAC;IAClE,CAAC,CAAC,CAAC;AACP,CAAC"}
|
package/dist/cossack/index.d.ts
CHANGED
|
@@ -2,6 +2,7 @@ import type { ORM } from "../orm.js";
|
|
|
2
2
|
import type { SQLFragment } from "../sql/fragment.js";
|
|
3
3
|
export interface MiddlewareContext {
|
|
4
4
|
set?(key: string, value: unknown): void;
|
|
5
|
+
get?(key: string): unknown;
|
|
5
6
|
}
|
|
6
7
|
export type MiddlewareNext = () => Promise<void>;
|
|
7
8
|
export type ORMFactory<Context extends MiddlewareContext = MiddlewareContext> = (context: Context) => ORM | Promise<ORM>;
|
|
@@ -10,17 +11,30 @@ export type ORMFactory<Context extends MiddlewareContext = MiddlewareContext> =
|
|
|
10
11
|
*
|
|
11
12
|
* An ORM instance is caller-owned and is never closed by middleware. An ORM
|
|
12
13
|
* created by a request factory is owned by middleware and is always closed,
|
|
13
|
-
* including when downstream throws.
|
|
14
|
+
* including when downstream throws. A framework streaming response can retain
|
|
15
|
+
* cleanup until its body completes or is cancelled.
|
|
14
16
|
*/
|
|
15
17
|
export declare function ormMiddleware<Context extends MiddlewareContext>(source: ORM | ORMFactory<Context>, contextKey?: string): (context: Context, next: MiddlewareNext) => Promise<void>;
|
|
16
18
|
export interface CacheEntry<T = unknown> {
|
|
17
19
|
readonly key: string;
|
|
18
20
|
readonly value: T;
|
|
19
|
-
readonly
|
|
21
|
+
readonly ttlMs?: number;
|
|
20
22
|
}
|
|
23
|
+
declare const DATABASE_CACHE_CAPABILITIES: Readonly<{
|
|
24
|
+
kind: 'cache';
|
|
25
|
+
provider: "database";
|
|
26
|
+
durationUnit: 'milliseconds';
|
|
27
|
+
locality: 'unknown';
|
|
28
|
+
persistence: 'unknown';
|
|
29
|
+
consistency: 'unknown';
|
|
30
|
+
atomicIncrement: false;
|
|
31
|
+
expiryPrecision: 'milliseconds';
|
|
32
|
+
operations: readonly ["get", "set", "has", "delete", "flush", "getMany", "setMany", "deleteMany"];
|
|
33
|
+
}>;
|
|
21
34
|
export interface CacheStore {
|
|
35
|
+
readonly capabilities?: typeof DATABASE_CACHE_CAPABILITIES;
|
|
22
36
|
get<T = unknown>(key: string): Promise<T | undefined>;
|
|
23
|
-
set<T = unknown>(key: string, value: T,
|
|
37
|
+
set<T = unknown>(key: string, value: T, ttlMs?: number): Promise<void>;
|
|
24
38
|
has(key: string): Promise<boolean>;
|
|
25
39
|
delete(key: string): Promise<void>;
|
|
26
40
|
flush(): Promise<void>;
|
|
@@ -37,7 +51,9 @@ export interface DatabaseSessionStore {
|
|
|
37
51
|
load(sessionId: string): Promise<Record<string, unknown>>;
|
|
38
52
|
get<T = unknown>(sessionId: string, key: string): Promise<T | undefined>;
|
|
39
53
|
getAll(sessionId: string): Promise<Record<string, unknown>>;
|
|
54
|
+
/** Atomically updates one key while preserving unrelated concurrent writes. */
|
|
40
55
|
set(sessionId: string, key: string, value: unknown, ttlMs?: number): Promise<void>;
|
|
56
|
+
/** Atomically removes one key while preserving unrelated concurrent writes. */
|
|
41
57
|
unset(sessionId: string, key: string): Promise<void>;
|
|
42
58
|
destroy(sessionId: string): Promise<void>;
|
|
43
59
|
bindUser(sessionId: string, userId: string): Promise<void>;
|
|
@@ -47,4 +63,5 @@ export declare function createDatabaseSessionStore(orm?: ORM, options?: {
|
|
|
47
63
|
readonly tableName?: string;
|
|
48
64
|
}): DatabaseSessionStore;
|
|
49
65
|
export declare function rawStoreQuery(orm: ORM, fragment: SQLFragment): Promise<import("../index.js").QueryResult<Record<string, unknown>>>;
|
|
66
|
+
export {};
|
|
50
67
|
//# sourceMappingURL=index.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/cossack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