@cossackframework/database 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +181 -0
- package/package.json +47 -0
- package/src/accessor.ts +27 -0
- package/src/als.ts +29 -0
- package/src/cache-store.ts +285 -0
- package/src/create-database.ts +36 -0
- package/src/dialects/d1.ts +108 -0
- package/src/dialects/libsql.ts +104 -0
- package/src/index.ts +67 -0
- package/src/middleware.ts +42 -0
- package/src/migrations/migrator.ts +90 -0
- package/src/seeder/runner.ts +73 -0
- package/src/session-als.ts +46 -0
- package/src/session-middleware.ts +98 -0
- package/src/session-store.ts +201 -0
- package/src/session.ts +59 -0
- package/src/store.ts +38 -0
- package/src/types.ts +108 -0
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
// src/dialects/d1.ts
|
|
2
|
+
import {
|
|
3
|
+
SqliteAdapter,
|
|
4
|
+
SqliteIntrospector,
|
|
5
|
+
SqliteQueryCompiler,
|
|
6
|
+
} from 'kysely';
|
|
7
|
+
import type {
|
|
8
|
+
CompiledQuery,
|
|
9
|
+
DatabaseConnection,
|
|
10
|
+
DatabaseIntrospector,
|
|
11
|
+
Dialect,
|
|
12
|
+
Driver,
|
|
13
|
+
Kysely,
|
|
14
|
+
QueryResult,
|
|
15
|
+
} from 'kysely';
|
|
16
|
+
import type { D1DatabaseLike } from '../types';
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Kysely {@link Dialect} for Cloudflare D1.
|
|
20
|
+
*
|
|
21
|
+
* Uses Kysely's SQLite query compiler/adapter/introspector and a custom driver
|
|
22
|
+
* that talks to the `D1Database` binding (`prepare().bind().all()`). No extra
|
|
23
|
+
* runtime dependencies — the D1 binding is provided by the Workers runtime.
|
|
24
|
+
*
|
|
25
|
+
* Note: D1 does not support interactive (`BEGIN`/`COMMIT`) transactions. For
|
|
26
|
+
* atomic multi-statement writes, use the raw D1 binding's `.batch([...])`
|
|
27
|
+
* (e.g. `c.env.DB.batch([...])` with prepared statements) — Kysely has no
|
|
28
|
+
* `.batch()`. Kysely's migrator is unaffected because the SQLite adapter
|
|
29
|
+
* reports `supportsTransactionalDdl: false`.
|
|
30
|
+
*/
|
|
31
|
+
export class D1Dialect implements Dialect {
|
|
32
|
+
constructor(private readonly d1: D1DatabaseLike) {}
|
|
33
|
+
|
|
34
|
+
createDriver(): Driver {
|
|
35
|
+
return new D1Driver(this.d1);
|
|
36
|
+
}
|
|
37
|
+
createQueryCompiler(): SqliteQueryCompiler {
|
|
38
|
+
return new SqliteQueryCompiler();
|
|
39
|
+
}
|
|
40
|
+
createAdapter(): SqliteAdapter {
|
|
41
|
+
return new SqliteAdapter();
|
|
42
|
+
}
|
|
43
|
+
createIntrospector(db: Kysely<any>): DatabaseIntrospector {
|
|
44
|
+
return new SqliteIntrospector(db);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** Marshals a Kysely parameter into a value D1's `bind()` accepts. */
|
|
49
|
+
function marshalD1Param(value: unknown): unknown {
|
|
50
|
+
if (value === undefined) return null;
|
|
51
|
+
if (typeof value === 'boolean') return value ? 1 : 0;
|
|
52
|
+
if (typeof value === 'bigint') return Number(value);
|
|
53
|
+
if (value instanceof Date) return value.toISOString();
|
|
54
|
+
return value;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
class D1Driver implements Driver {
|
|
58
|
+
private readonly connection: D1Connection;
|
|
59
|
+
constructor(d1: D1DatabaseLike) {
|
|
60
|
+
this.connection = new D1Connection(d1);
|
|
61
|
+
}
|
|
62
|
+
async init(): Promise<void> {}
|
|
63
|
+
async acquireConnection(): Promise<DatabaseConnection> {
|
|
64
|
+
return this.connection;
|
|
65
|
+
}
|
|
66
|
+
async beginTransaction(): Promise<void> {
|
|
67
|
+
throw new Error(
|
|
68
|
+
'D1 does not support interactive transactions. For atomic multi-statement writes, use the raw D1 binding (.batch([...]), e.g. c.env.DB.batch([...])) — Kysely has no .batch().',
|
|
69
|
+
);
|
|
70
|
+
}
|
|
71
|
+
async commitTransaction(): Promise<void> {
|
|
72
|
+
throw new Error(
|
|
73
|
+
'D1 does not support interactive transactions. For atomic multi-statement writes, use the raw D1 binding (.batch([...]), e.g. c.env.DB.batch([...])) — Kysely has no .batch().',
|
|
74
|
+
);
|
|
75
|
+
}
|
|
76
|
+
async rollbackTransaction(): Promise<void> {
|
|
77
|
+
throw new Error(
|
|
78
|
+
'D1 does not support interactive transactions. For atomic multi-statement writes, use the raw D1 binding (.batch([...]), e.g. c.env.DB.batch([...])) — Kysely has no .batch().',
|
|
79
|
+
);
|
|
80
|
+
}
|
|
81
|
+
async releaseConnection(): Promise<void> {}
|
|
82
|
+
async destroy(): Promise<void> {}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
class D1Connection implements DatabaseConnection {
|
|
86
|
+
constructor(private readonly d1: D1DatabaseLike) {}
|
|
87
|
+
|
|
88
|
+
async executeQuery<R>(compiledQuery: CompiledQuery): Promise<QueryResult<R>> {
|
|
89
|
+
const statement = this.d1.prepare(compiledQuery.sql);
|
|
90
|
+
const bound =
|
|
91
|
+
compiledQuery.parameters.length > 0
|
|
92
|
+
? statement.bind(...compiledQuery.parameters.map(marshalD1Param))
|
|
93
|
+
: statement;
|
|
94
|
+
const result = await bound.all<R>();
|
|
95
|
+
|
|
96
|
+
const rows = (result.results ?? []) as R[];
|
|
97
|
+
const out: { rows: R[]; numAffectedRows?: bigint; insertId?: bigint } = { rows };
|
|
98
|
+
const changes = result.meta?.changes;
|
|
99
|
+
const lastRowId = result.meta?.last_row_id;
|
|
100
|
+
if (typeof changes === 'number') out.numAffectedRows = BigInt(changes);
|
|
101
|
+
if (lastRowId !== undefined && lastRowId !== null) out.insertId = BigInt(lastRowId);
|
|
102
|
+
return out as QueryResult<R>;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
async *streamQuery<R>(compiledQuery: CompiledQuery): AsyncIterableIterator<QueryResult<R>> {
|
|
106
|
+
yield await this.executeQuery<R>(compiledQuery);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
// src/dialects/libsql.ts
|
|
2
|
+
import {
|
|
3
|
+
CompiledQuery,
|
|
4
|
+
SqliteAdapter,
|
|
5
|
+
SqliteIntrospector,
|
|
6
|
+
SqliteQueryCompiler,
|
|
7
|
+
} from 'kysely';
|
|
8
|
+
import type {
|
|
9
|
+
DatabaseConnection,
|
|
10
|
+
DatabaseIntrospector,
|
|
11
|
+
Dialect,
|
|
12
|
+
Driver,
|
|
13
|
+
Kysely,
|
|
14
|
+
QueryResult,
|
|
15
|
+
} from 'kysely';
|
|
16
|
+
import type { LibsqlClientLike, LibsqlResultSetLike } from '../types';
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Kysely {@link Dialect} for libSQL / Turso.
|
|
20
|
+
*
|
|
21
|
+
* Works with any client that matches the libSQL `Client` contract — pass one
|
|
22
|
+
* built from `@tursodatabase/serverless/compat` (recommended, fetch-based, runs
|
|
23
|
+
* on Workers + Node) or `@libsql/client/web`.
|
|
24
|
+
*
|
|
25
|
+
* The libSQL client returns rows as array-indexable objects; we remap them to
|
|
26
|
+
* plain objects keyed by column name for Kysely.
|
|
27
|
+
*/
|
|
28
|
+
export class LibsqlDialect implements Dialect {
|
|
29
|
+
constructor(private readonly client: LibsqlClientLike) {}
|
|
30
|
+
|
|
31
|
+
createDriver(): Driver {
|
|
32
|
+
return new LibsqlDriver(this.client);
|
|
33
|
+
}
|
|
34
|
+
createQueryCompiler(): SqliteQueryCompiler {
|
|
35
|
+
return new SqliteQueryCompiler();
|
|
36
|
+
}
|
|
37
|
+
createAdapter(): SqliteAdapter {
|
|
38
|
+
return new SqliteAdapter();
|
|
39
|
+
}
|
|
40
|
+
createIntrospector(db: Kysely<any>): DatabaseIntrospector {
|
|
41
|
+
return new SqliteIntrospector(db);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function toRows<R>(resultSet: LibsqlResultSetLike): R[] {
|
|
46
|
+
const { columns, rows } = resultSet;
|
|
47
|
+
return rows.map((row) => {
|
|
48
|
+
const obj: Record<string, unknown> = {};
|
|
49
|
+
for (let i = 0; i < columns.length; i++) {
|
|
50
|
+
obj[columns[i]] = row[i];
|
|
51
|
+
}
|
|
52
|
+
return obj as R;
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
class LibsqlDriver implements Driver {
|
|
57
|
+
private readonly connection: LibsqlConnection;
|
|
58
|
+
constructor(client: LibsqlClientLike) {
|
|
59
|
+
this.connection = new LibsqlConnection(client);
|
|
60
|
+
}
|
|
61
|
+
async init(): Promise<void> {}
|
|
62
|
+
async acquireConnection(): Promise<DatabaseConnection> {
|
|
63
|
+
return this.connection;
|
|
64
|
+
}
|
|
65
|
+
async beginTransaction(connection: DatabaseConnection): Promise<void> {
|
|
66
|
+
await connection.executeQuery(CompiledQuery.raw('BEGIN'));
|
|
67
|
+
}
|
|
68
|
+
async commitTransaction(connection: DatabaseConnection): Promise<void> {
|
|
69
|
+
await connection.executeQuery(CompiledQuery.raw('COMMIT'));
|
|
70
|
+
}
|
|
71
|
+
async rollbackTransaction(connection: DatabaseConnection): Promise<void> {
|
|
72
|
+
await connection.executeQuery(CompiledQuery.raw('ROLLBACK'));
|
|
73
|
+
}
|
|
74
|
+
async releaseConnection(): Promise<void> {}
|
|
75
|
+
async destroy(): Promise<void> {
|
|
76
|
+
this.connection.close();
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
class LibsqlConnection implements DatabaseConnection {
|
|
81
|
+
constructor(private readonly client: LibsqlClientLike) {}
|
|
82
|
+
|
|
83
|
+
close(): void {
|
|
84
|
+
this.client.close?.();
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
async executeQuery<R>(compiledQuery: CompiledQuery): Promise<QueryResult<R>> {
|
|
88
|
+
const args = compiledQuery.parameters.map((p) => (p === undefined ? null : p));
|
|
89
|
+
const resultSet = await this.client.execute({ sql: compiledQuery.sql, args });
|
|
90
|
+
|
|
91
|
+
const out: { rows: R[]; numAffectedRows?: bigint; insertId?: bigint } = {
|
|
92
|
+
rows: toRows<R>(resultSet),
|
|
93
|
+
};
|
|
94
|
+
out.numAffectedRows = BigInt(resultSet.rowsAffected);
|
|
95
|
+
if (resultSet.lastInsertRowid !== undefined && resultSet.lastInsertRowid !== null) {
|
|
96
|
+
out.insertId = BigInt(resultSet.lastInsertRowid);
|
|
97
|
+
}
|
|
98
|
+
return out as QueryResult<R>;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
async *streamQuery<R>(compiledQuery: CompiledQuery): AsyncIterableIterator<QueryResult<R>> {
|
|
102
|
+
yield await this.executeQuery<R>(compiledQuery);
|
|
103
|
+
}
|
|
104
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
// src/index.ts
|
|
2
|
+
|
|
3
|
+
// Re-export all of Kysely so consumers don't need to install it separately.
|
|
4
|
+
// `Kysely`, `Generated`, `sql`, `Insertable`, `Selectable`, etc. are all
|
|
5
|
+
// available via `import { ... } from '@cossackframework/database'`.
|
|
6
|
+
export * from 'kysely';
|
|
7
|
+
export { Migrator, FileMigrationProvider, NO_MIGRATIONS } from 'kysely/migration';
|
|
8
|
+
export type {
|
|
9
|
+
Migration,
|
|
10
|
+
MigrationProvider,
|
|
11
|
+
MigrationResultSet,
|
|
12
|
+
MigrationResult,
|
|
13
|
+
MigrationInfo,
|
|
14
|
+
} from 'kysely/migration';
|
|
15
|
+
|
|
16
|
+
// Core API
|
|
17
|
+
export { createDatabase } from './create-database';
|
|
18
|
+
export { createDbMiddleware } from './middleware';
|
|
19
|
+
export type { DbMiddlewareOptions } from './middleware';
|
|
20
|
+
export { getDb } from './accessor';
|
|
21
|
+
export { db, setDbStoreGetter } from './store';
|
|
22
|
+
export { ensureDbAlsWired, runWithDb } from './als';
|
|
23
|
+
|
|
24
|
+
// Sessions
|
|
25
|
+
export { SessionStore } from './session-store';
|
|
26
|
+
export type { SessionRow } from './session-store';
|
|
27
|
+
export { session } from './session';
|
|
28
|
+
export { createSessionMiddleware } from './session-middleware';
|
|
29
|
+
export type { SessionMiddlewareOptions } from './session-middleware';
|
|
30
|
+
export { runWithSession, ensureSessionAlsWired } from './session-als';
|
|
31
|
+
export type { SessionScope } from './session-als';
|
|
32
|
+
|
|
33
|
+
// Cache (database-backed driver; structurally compatible with core's CacheStore)
|
|
34
|
+
export { DatabaseCacheStore } from './cache-store';
|
|
35
|
+
export type { CacheItemRow, CacheStoreLike } from './cache-store';
|
|
36
|
+
|
|
37
|
+
// Dialects (advanced — for custom Kysely instances)
|
|
38
|
+
export { D1Dialect } from './dialects/d1';
|
|
39
|
+
export { LibsqlDialect } from './dialects/libsql';
|
|
40
|
+
|
|
41
|
+
// Migrations & seeders
|
|
42
|
+
export {
|
|
43
|
+
runMigrations,
|
|
44
|
+
resetMigrations,
|
|
45
|
+
getMigrationStatus,
|
|
46
|
+
formatMigrationResult,
|
|
47
|
+
defaultMigrationsFolder,
|
|
48
|
+
} from './migrations/migrator';
|
|
49
|
+
export type { RunMigrationsOptions, MigrationDirection } from './migrations/migrator';
|
|
50
|
+
export { runSeeders, defaultSeedersFolder } from './seeder/runner';
|
|
51
|
+
export type { Seeder, RunSeedersOptions } from './seeder/runner';
|
|
52
|
+
|
|
53
|
+
// Types
|
|
54
|
+
export type {
|
|
55
|
+
Database,
|
|
56
|
+
DbClient,
|
|
57
|
+
DbConfig,
|
|
58
|
+
D1Config,
|
|
59
|
+
LibsqlConfig,
|
|
60
|
+
D1DatabaseLike,
|
|
61
|
+
D1PreparedStatementLike,
|
|
62
|
+
D1ResultLike,
|
|
63
|
+
LibsqlClientLike,
|
|
64
|
+
LibsqlInStatement,
|
|
65
|
+
LibsqlResultSetLike,
|
|
66
|
+
LibsqlRowLike,
|
|
67
|
+
} from './types';
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
// src/middleware.ts
|
|
2
|
+
import type { MiddlewareHandler } from 'hono';
|
|
3
|
+
import { ensureDbAlsWired, runWithDb } from './als';
|
|
4
|
+
import type { DbClient } from './types';
|
|
5
|
+
|
|
6
|
+
export interface DbMiddlewareOptions {
|
|
7
|
+
/**
|
|
8
|
+
* The Kysely client to expose on the request, or a factory that builds one
|
|
9
|
+
* per request (e.g. reading a D1 binding off `c.env`).
|
|
10
|
+
*
|
|
11
|
+
* For stateless HTTP clients (Turso) pass a single shared instance.
|
|
12
|
+
* For D1 pass `(c) => createDatabase({ dialect: 'd1', binding: c.env.DB })`.
|
|
13
|
+
*/
|
|
14
|
+
client: DbClient | ((c: any) => DbClient | Promise<DbClient>);
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Hono middleware that exposes the database on the request:
|
|
19
|
+
*
|
|
20
|
+
* - sets `c.set('db', client)` so routes read it via `getDb(c)` / `c.get('db')`,
|
|
21
|
+
* - wraps the rest of the request in `runWithDb` so the global `db()` helper
|
|
22
|
+
* resolves to the same per-request client.
|
|
23
|
+
*
|
|
24
|
+
* Register it globally next to your auth/locale middleware.
|
|
25
|
+
*
|
|
26
|
+
* ```ts
|
|
27
|
+
* import { createDbMiddleware, createDatabase } from '@cossackframework/database'
|
|
28
|
+
*
|
|
29
|
+
* app.use('*', createDbMiddleware({
|
|
30
|
+
* client: (c) => createDatabase({ dialect: 'd1', binding: c.env.DB }),
|
|
31
|
+
* }))
|
|
32
|
+
* ```
|
|
33
|
+
*/
|
|
34
|
+
export function createDbMiddleware(options: DbMiddlewareOptions): MiddlewareHandler {
|
|
35
|
+
return async (c, next) => {
|
|
36
|
+
ensureDbAlsWired();
|
|
37
|
+
const client =
|
|
38
|
+
typeof options.client === 'function' ? await options.client(c) : options.client;
|
|
39
|
+
(c as any).set('db', client);
|
|
40
|
+
return runWithDb(client, () => next());
|
|
41
|
+
};
|
|
42
|
+
}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
// src/migrations/migrator.ts
|
|
2
|
+
import { promises as fs } from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { FileMigrationProvider, Migrator, NO_MIGRATIONS } from 'kysely/migration';
|
|
5
|
+
import type { MigrationResultSet } from 'kysely/migration';
|
|
6
|
+
import type { DbClient } from '../types';
|
|
7
|
+
|
|
8
|
+
export interface RunMigrationsOptions {
|
|
9
|
+
client: DbClient;
|
|
10
|
+
/** Absolute path to the folder holding migration files (default `src/migrations`). */
|
|
11
|
+
folder?: string;
|
|
12
|
+
/** Name of the migrations bookkeeping table (Kysely default `kysely_migration`). */
|
|
13
|
+
migrationTableName?: string;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export type MigrationDirection = 'up' | 'down' | 'latest';
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Runs Kysely migrations discovered as `.ts`/`.js` files in `folder`.
|
|
20
|
+
*
|
|
21
|
+
* - `up` / `latest` — apply all pending migrations (`migrateToLatest`).
|
|
22
|
+
* - `down` — revert the single most recent migration (`migrateDown`).
|
|
23
|
+
*
|
|
24
|
+
* Use {@link resetMigrations} to roll everything back.
|
|
25
|
+
*/
|
|
26
|
+
export async function runMigrations(
|
|
27
|
+
direction: MigrationDirection,
|
|
28
|
+
options: RunMigrationsOptions,
|
|
29
|
+
): Promise<MigrationResultSet> {
|
|
30
|
+
const folder = options.folder ?? defaultMigrationsFolder();
|
|
31
|
+
const migrator = new Migrator({
|
|
32
|
+
db: options.client as any,
|
|
33
|
+
provider: new FileMigrationProvider({ fs, path, migrationFolder: folder }),
|
|
34
|
+
migrationTableName: options.migrationTableName,
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
const result =
|
|
38
|
+
direction === 'down' ? await migrator.migrateDown() : await migrator.migrateToLatest();
|
|
39
|
+
return result;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Rolls back every migration (runs all `down` handlers down to nothing).
|
|
44
|
+
*/
|
|
45
|
+
export async function resetMigrations(options: RunMigrationsOptions): Promise<MigrationResultSet> {
|
|
46
|
+
const folder = options.folder ?? defaultMigrationsFolder();
|
|
47
|
+
const migrator = new Migrator({
|
|
48
|
+
db: options.client as any,
|
|
49
|
+
provider: new FileMigrationProvider({ fs, path, migrationFolder: folder }),
|
|
50
|
+
migrationTableName: options.migrationTableName,
|
|
51
|
+
});
|
|
52
|
+
return migrator.migrateTo(NO_MIGRATIONS);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** Returns each migration with its execution state (executedAt if run). */
|
|
56
|
+
export async function getMigrationStatus(
|
|
57
|
+
options: RunMigrationsOptions,
|
|
58
|
+
): Promise<Array<{ name: string; executedAt?: Date }>> {
|
|
59
|
+
const folder = options.folder ?? defaultMigrationsFolder();
|
|
60
|
+
const migrator = new Migrator({
|
|
61
|
+
db: options.client as any,
|
|
62
|
+
provider: new FileMigrationProvider({ fs, path, migrationFolder: folder }),
|
|
63
|
+
migrationTableName: options.migrationTableName,
|
|
64
|
+
});
|
|
65
|
+
const infos = await migrator.getMigrations();
|
|
66
|
+
return infos.map((it) => ({ name: it.name, executedAt: it.executedAt }));
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Prints a human-readable summary of a migration result set. */
|
|
70
|
+
export function formatMigrationResult(result: MigrationResultSet): string {
|
|
71
|
+
if (result.error) {
|
|
72
|
+
const msg = result.error instanceof Error ? result.error.message : String(result.error);
|
|
73
|
+
return `Migration failed: ${msg}`;
|
|
74
|
+
}
|
|
75
|
+
const items = result.results ?? [];
|
|
76
|
+
if (items.length === 0) {
|
|
77
|
+
return 'No migrations to run.';
|
|
78
|
+
}
|
|
79
|
+
return items
|
|
80
|
+
.map((it) => {
|
|
81
|
+
const tag = it.status === 'Success' ? '✓' : it.status === 'Error' ? '✗' : '·';
|
|
82
|
+
return `${tag} ${it.direction.toLowerCase()} ${it.migrationName}`;
|
|
83
|
+
})
|
|
84
|
+
.join('\n');
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** Default migration folder, resolved relative to the current working directory. */
|
|
88
|
+
export function defaultMigrationsFolder(): string {
|
|
89
|
+
return path.resolve(process.cwd(), 'src', 'migrations');
|
|
90
|
+
}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
// src/seeder/runner.ts
|
|
2
|
+
import { promises as fs } from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { pathToFileURL } from 'node:url';
|
|
5
|
+
import type { DbClient } from '../types';
|
|
6
|
+
|
|
7
|
+
export interface Seeder {
|
|
8
|
+
run(db: DbClient): Promise<void>;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export interface RunSeedersOptions {
|
|
12
|
+
client: DbClient;
|
|
13
|
+
/** Absolute path to the folder holding seeder files (default `src/seeders`). */
|
|
14
|
+
folder?: string;
|
|
15
|
+
/** Run only seeders whose filename matches this substring. */
|
|
16
|
+
only?: string;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Imports every `.ts`/`.js` seeder in `folder` (sorted by filename) and calls
|
|
21
|
+
* its default export's `run(db)` method in order.
|
|
22
|
+
*
|
|
23
|
+
* Each seeder file default-exports a {@link Seeder}:
|
|
24
|
+
*
|
|
25
|
+
* ```ts
|
|
26
|
+
* export default {
|
|
27
|
+
* async run(db) {
|
|
28
|
+
* await db.insertInto('users').values({ email: 'demo@cossack.dev' }).execute()
|
|
29
|
+
* },
|
|
30
|
+
* }
|
|
31
|
+
* ```
|
|
32
|
+
*/
|
|
33
|
+
export async function runSeeders(options: RunSeedersOptions): Promise<string[]> {
|
|
34
|
+
const folder = options.folder ?? defaultSeedersFolder();
|
|
35
|
+
let entries: string[];
|
|
36
|
+
try {
|
|
37
|
+
entries = await fs.readdir(folder);
|
|
38
|
+
} catch (err: any) {
|
|
39
|
+
if (err.code === 'ENOENT') return [];
|
|
40
|
+
throw err;
|
|
41
|
+
}
|
|
42
|
+
const files = entries.filter(
|
|
43
|
+
(f) => (f.endsWith('.ts') || f.endsWith('.js')) && !f.endsWith('.d.ts'),
|
|
44
|
+
);
|
|
45
|
+
const filtered = options.only
|
|
46
|
+
? files.filter((f) => f.includes(options.only as string))
|
|
47
|
+
: files;
|
|
48
|
+
filtered.sort();
|
|
49
|
+
|
|
50
|
+
const ran: string[] = [];
|
|
51
|
+
for (const file of filtered) {
|
|
52
|
+
const fullPath = path.resolve(folder, file);
|
|
53
|
+
// `/* @vite-ignore */` suppresses Vite's "cannot analyze dynamic import"
|
|
54
|
+
// warning: the specifiers are built at runtime from a directory listing
|
|
55
|
+
// (user seeder files), so static analysis is impossible by design. This
|
|
56
|
+
// is intentional and matches Vite's documented escape hatch.
|
|
57
|
+
const mod = await import(
|
|
58
|
+
/* @vite-ignore */ `${pathToFileURL(fullPath).href}?t=${Date.now()}`
|
|
59
|
+
);
|
|
60
|
+
const seeder: Seeder = mod.default ?? mod;
|
|
61
|
+
if (typeof seeder?.run !== 'function') {
|
|
62
|
+
throw new Error(`Seeder "${file}" has no \`run(db)\` method (or default export).`);
|
|
63
|
+
}
|
|
64
|
+
await seeder.run(options.client);
|
|
65
|
+
ran.push(file);
|
|
66
|
+
}
|
|
67
|
+
return ran;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** Default seeder folder, resolved relative to the current working directory. */
|
|
71
|
+
export function defaultSeedersFolder(): string {
|
|
72
|
+
return path.resolve(process.cwd(), 'src', 'seeders');
|
|
73
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
// src/session-als.ts
|
|
2
|
+
//
|
|
3
|
+
// Per-request session scoping. The framework's session middleware resolves the
|
|
4
|
+
// session ID (from the auth cookie or the anonymous `cossack_sid` cookie),
|
|
5
|
+
// loads/creates the row, and wraps the request in this scope so the global
|
|
6
|
+
// `session()` helper resolves it.
|
|
7
|
+
//
|
|
8
|
+
// Mirrors the db() ALS pattern (see `als.ts` + `store.ts`).
|
|
9
|
+
|
|
10
|
+
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
11
|
+
import type { SessionStore } from './session-store';
|
|
12
|
+
|
|
13
|
+
/** The per-request session scope: the store + the active session ID. */
|
|
14
|
+
export interface SessionScope {
|
|
15
|
+
/** The active session ID for this request (auth's, or an anonymous one). */
|
|
16
|
+
sessionId: string;
|
|
17
|
+
/** The SessionStore (backed by the scoped `db()` client). */
|
|
18
|
+
store: SessionStore;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
const sessionAls = new AsyncLocalStorage<SessionScope>();
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* One-time wiring hook (kept for symmetry with db/i18n; the `session()` helper
|
|
25
|
+
* reads `sessionAls` directly since it lives in the same package). Idempotent.
|
|
26
|
+
*/
|
|
27
|
+
let wired = false;
|
|
28
|
+
export function ensureSessionAlsWired(): void {
|
|
29
|
+
wired = true;
|
|
30
|
+
}
|
|
31
|
+
export function _isSessionAlsWired(): boolean {
|
|
32
|
+
return wired;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Runs `fn` inside a session scope. `session()` inside `fn` resolves the scope. */
|
|
36
|
+
export function runWithSession<T>(
|
|
37
|
+
scope: SessionScope,
|
|
38
|
+
fn: () => T | Promise<T>,
|
|
39
|
+
): T | Promise<T> {
|
|
40
|
+
return sessionAls.run(scope, fn as () => T);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** @internal Returns the active session scope, if any. Used by `session()`. */
|
|
44
|
+
export function getSessionScope(): SessionScope | undefined {
|
|
45
|
+
return sessionAls.getStore();
|
|
46
|
+
}
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
// src/session-middleware.ts
|
|
2
|
+
//
|
|
3
|
+
// Per-request session middleware. Resolves the session ID (from an optional
|
|
4
|
+
// auth-cookie reader, else the anonymous `cossack_sid` cookie), creates one if
|
|
5
|
+
// missing, and scopes a `SessionStore` into AsyncLocalStorage so `session()`
|
|
6
|
+
// works context-free. Ensures the ID cookie is set on the response when a new
|
|
7
|
+
// anonymous session is issued.
|
|
8
|
+
//
|
|
9
|
+
// Register via `cossack add database` (same pattern as `dbMiddleware`):
|
|
10
|
+
//
|
|
11
|
+
// // src/middlewares/session.ts
|
|
12
|
+
// import { createSessionMiddleware } from '@cossackframework/database';
|
|
13
|
+
// export const sessionMiddleware = createSessionMiddleware();
|
|
14
|
+
//
|
|
15
|
+
// // src/config/middlewares.ts
|
|
16
|
+
// import { sessionMiddleware } from '../middlewares/session';
|
|
17
|
+
// export const middlewares = [sessionMiddleware];
|
|
18
|
+
|
|
19
|
+
import type { MiddlewareHandler } from 'hono';
|
|
20
|
+
import { getCookie, setCookie } from 'hono/cookie';
|
|
21
|
+
import { db } from './store';
|
|
22
|
+
import { SessionStore } from './session-store';
|
|
23
|
+
import { ensureSessionAlsWired, runWithSession } from './session-als';
|
|
24
|
+
|
|
25
|
+
export interface SessionMiddlewareOptions {
|
|
26
|
+
/** Anonymous-session cookie name. Defaults to `cossack_sid`. */
|
|
27
|
+
cookieName?: string;
|
|
28
|
+
/** Session TTL in milliseconds. Defaults to 30 days. */
|
|
29
|
+
ttl?: number;
|
|
30
|
+
/**
|
|
31
|
+
* Optional: read the session ID from auth's cookie instead of the anonymous
|
|
32
|
+
* one. Return the auth session ID when the user is logged in; return
|
|
33
|
+
* undefined to fall back to the anonymous cookie. This is the "ID bridge"
|
|
34
|
+
* that lets an authenticated session reuse its existing ID.
|
|
35
|
+
*/
|
|
36
|
+
authCookieReader?: (c: any) => string | undefined | Promise<string | undefined>;
|
|
37
|
+
/**
|
|
38
|
+
* Whether to set the anonymous cookie as `httpOnly`. Defaults to true.
|
|
39
|
+
* (Auth-managed cookies set their own attributes via the auth module.)
|
|
40
|
+
*/
|
|
41
|
+
httpOnly?: boolean;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const DEFAULT_COOKIE_NAME = 'cossack_sid';
|
|
45
|
+
const DEFAULT_TTL_MS = 30 * 24 * 60 * 60 * 1000;
|
|
46
|
+
|
|
47
|
+
export function createSessionMiddleware(
|
|
48
|
+
options: SessionMiddlewareOptions = {},
|
|
49
|
+
): MiddlewareHandler {
|
|
50
|
+
const cookieName = options.cookieName ?? DEFAULT_COOKIE_NAME;
|
|
51
|
+
const ttl = options.ttl ?? DEFAULT_TTL_MS;
|
|
52
|
+
const httpOnly = options.httpOnly ?? true;
|
|
53
|
+
|
|
54
|
+
return async (c, next) => {
|
|
55
|
+
ensureSessionAlsWired();
|
|
56
|
+
const store = new SessionStore(db());
|
|
57
|
+
|
|
58
|
+
// 1. Resolve an existing session ID: auth cookie first, then anonymous.
|
|
59
|
+
// `authProvidedId` tracks whether auth handed us an ID so we know
|
|
60
|
+
// not to set the anonymous cookie in that case (auth manages its own).
|
|
61
|
+
let sessionId: string | undefined;
|
|
62
|
+
let authProvidedId = false;
|
|
63
|
+
if (options.authCookieReader) {
|
|
64
|
+
sessionId = await options.authCookieReader(c);
|
|
65
|
+
if (sessionId) authProvidedId = true;
|
|
66
|
+
}
|
|
67
|
+
if (!sessionId) {
|
|
68
|
+
sessionId = getCookie(c, cookieName);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// 2. If neither auth nor the anonymous cookie gave us an ID, create a
|
|
72
|
+
// fresh anonymous session. We set its cookie after `next()` so it
|
|
73
|
+
// survives redirects.
|
|
74
|
+
let issuedNewAnonymousId = false;
|
|
75
|
+
if (!sessionId) {
|
|
76
|
+
sessionId = await store.create(ttl);
|
|
77
|
+
issuedNewAnonymousId = true;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
// 3. Scope the session for downstream handlers.
|
|
81
|
+
await runWithSession({ sessionId, store }, () => next());
|
|
82
|
+
|
|
83
|
+
// 4. Persist a newly-issued ANONYMOUS ID as a cookie. We must NOT skip
|
|
84
|
+
// this when `authCookieReader` is configured but returned undefined
|
|
85
|
+
// (an unauthenticated request) — otherwise the new anonymous session
|
|
86
|
+
// is orphaned and lost on the next request. Only an auth-provided ID
|
|
87
|
+
// is excluded, because the auth module sets its own cookie.
|
|
88
|
+
if (issuedNewAnonymousId && !authProvidedId) {
|
|
89
|
+
setCookie(c, cookieName, sessionId, {
|
|
90
|
+
httpOnly,
|
|
91
|
+
secure: c.req.url.startsWith('https://'),
|
|
92
|
+
sameSite: 'Lax',
|
|
93
|
+
path: '/',
|
|
94
|
+
maxAge: Math.floor(ttl / 1000),
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
};
|
|
98
|
+
}
|