@cossackframework/database 0.7.7 → 0.8.0-licenseprobe.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.
@@ -1,36 +0,0 @@
1
- // src/create-database.ts
2
- import { Kysely } from 'kysely';
3
- import { D1Dialect } from './dialects/d1';
4
- import { LibsqlDialect } from './dialects/libsql';
5
- import type { Database, D1Config, DbClient, LibsqlConfig } from './types';
6
-
7
- /**
8
- * Creates a {@link DbClient} (a typed Kysely instance) for the configured
9
- * dialect.
10
- *
11
- * - **D1**: pass the Cloudflare binding.
12
- * - **libSQL / Turso**: pass a client created from `@tursodatabase/serverless/compat`
13
- * (recommended) or `@libsql/client/web`.
14
- *
15
- * ```ts
16
- * // Cloudflare D1
17
- * const db = createDatabase({ dialect: 'd1', binding: env.DB })
18
- *
19
- * // Turso
20
- * import { createClient } from '@tursodatabase/serverless/compat'
21
- * const db = createDatabase({
22
- * dialect: 'libsql',
23
- * client: createClient({ url: env.TURSO_URL, authToken: env.TURSO_TOKEN }),
24
- * })
25
- * ```
26
- */
27
- export function createDatabase(config: D1Config | LibsqlConfig): DbClient;
28
- export function createDatabase(config: D1Config): DbClient;
29
- export function createDatabase(config: LibsqlConfig): DbClient;
30
- export function createDatabase(config: D1Config | LibsqlConfig): DbClient {
31
- const dialect =
32
- config.dialect === 'd1'
33
- ? new D1Dialect(config.binding)
34
- : new LibsqlDialect(config.client);
35
- return new Kysely<Database>({ dialect });
36
- }
@@ -1,215 +0,0 @@
1
- // src/dialects/d1.ts
2
- import {
3
- SqliteAdapter,
4
- SqliteQueryCompiler,
5
- sql,
6
- } from 'kysely';
7
- import type {
8
- CompiledQuery,
9
- DatabaseConnection,
10
- DatabaseMetadataOptions,
11
- DatabaseIntrospector,
12
- Dialect,
13
- Driver,
14
- Kysely,
15
- QueryResult,
16
- TableMetadata,
17
- } from 'kysely';
18
- import {
19
- DEFAULT_MIGRATION_LOCK_TABLE,
20
- DEFAULT_MIGRATION_TABLE,
21
- } from 'kysely/migration';
22
- import type { D1DatabaseLike } from '../types';
23
-
24
- /**
25
- * Kysely's SQLite behavior with an explicit, duplicate-install-safe D1 brand.
26
- *
27
- * Consumers should inspect `cossackDialect` instead of relying on
28
- * `instanceof` or constructor names, which can change across package copies
29
- * and build tools.
30
- */
31
- export class D1Adapter extends SqliteAdapter {
32
- readonly cossackDialect = 'd1' as const;
33
- }
34
-
35
- /**
36
- * Kysely {@link Dialect} for Cloudflare D1.
37
- *
38
- * Uses Kysely's SQLite query compiler/adapter/introspector and a custom driver
39
- * that talks to the `D1Database` binding (`prepare().bind().all()`). No extra
40
- * runtime dependencies — the D1 binding is provided by the Workers runtime.
41
- *
42
- * Note: D1 does not support interactive (`BEGIN`/`COMMIT`) transactions. For
43
- * atomic multi-statement writes, use the raw D1 binding's `.batch([...])`
44
- * (e.g. `c.env.DB.batch([...])` with prepared statements) — Kysely has no
45
- * `.batch()`. Kysely's migrator is unaffected because the SQLite adapter
46
- * reports `supportsTransactionalDdl: false`.
47
- */
48
- export class D1Dialect implements Dialect {
49
- constructor(private readonly d1: D1DatabaseLike) {}
50
-
51
- createDriver(): Driver {
52
- return new D1Driver(this.d1);
53
- }
54
- createQueryCompiler(): SqliteQueryCompiler {
55
- return new SqliteQueryCompiler();
56
- }
57
- createAdapter(): D1Adapter {
58
- return new D1Adapter();
59
- }
60
- createIntrospector(db: Kysely<any>): DatabaseIntrospector {
61
- return new D1Introspector(db);
62
- }
63
- }
64
-
65
- interface D1TableRow {
66
- name: string;
67
- sql: string | null;
68
- type: 'table' | 'view';
69
- }
70
-
71
- interface D1ColumnRow {
72
- cid: number;
73
- name: string;
74
- type: string;
75
- notnull: number;
76
- dflt_value: unknown;
77
- pk: number;
78
- }
79
-
80
- /**
81
- * D1 stores a protected `_cf_METADATA` table beside application tables.
82
- * Kysely's stock SQLite introspector feeds every non-`sqlite_*` table into
83
- * `pragma_table_info()`, which includes `_cf_METADATA`; D1 rejects inspection
84
- * of that internal table with `SQLITE_AUTH`. Query application tables first,
85
- * explicitly excluding `_cf_*`, then introspect each safe name separately.
86
- */
87
- class D1Introspector implements DatabaseIntrospector {
88
- constructor(private readonly db: Kysely<any>) {}
89
-
90
- async getSchemas(): Promise<[]> {
91
- return [];
92
- }
93
-
94
- async getTables(
95
- options: DatabaseMetadataOptions = { withInternalKyselyTables: false },
96
- ): Promise<TableMetadata[]> {
97
- let query = this.db
98
- .selectFrom('sqlite_master')
99
- .where('type', 'in', ['table', 'view'])
100
- .where('name', 'not like', 'sqlite_%')
101
- .where(sql<boolean>`name not glob ${'_cf_*'}`)
102
- .select(['name', 'sql', 'type'])
103
- .orderBy('name');
104
-
105
- if (!options.withInternalKyselyTables) {
106
- query = query
107
- .where('name', '!=', DEFAULT_MIGRATION_TABLE)
108
- .where('name', '!=', DEFAULT_MIGRATION_LOCK_TABLE);
109
- }
110
-
111
- const tables = await query.execute() as D1TableRow[];
112
- return Promise.all(tables.map(async (table): Promise<TableMetadata> => {
113
- const result = await sql<D1ColumnRow>`
114
- select * from pragma_table_info(${table.name})
115
- `.execute(this.db);
116
- const columns = result.rows;
117
- const autoIncrementColumn = findAutoIncrementColumn(table.sql, columns);
118
- return {
119
- name: table.name,
120
- isView: table.type === 'view',
121
- isForeign: false,
122
- columns: columns.map((column) => ({
123
- name: column.name,
124
- dataType: column.type,
125
- isNullable: !column.notnull,
126
- isAutoIncrementing: column.name === autoIncrementColumn,
127
- hasDefaultValue: column.dflt_value != null,
128
- comment: undefined,
129
- })),
130
- };
131
- }));
132
- }
133
- }
134
-
135
- function findAutoIncrementColumn(
136
- tableSql: string | null,
137
- columns: D1ColumnRow[],
138
- ): string | undefined {
139
- const declared = tableSql
140
- ?.split(/[\(\),]/)
141
- .find((part) => part.toLowerCase().includes('autoincrement'))
142
- ?.trimStart()
143
- .split(/\s+/)[0]
144
- ?.replace(/["`]/g, '');
145
- if (declared) return declared;
146
-
147
- const primaryKeys = columns.filter((column) => column.pk > 0);
148
- if (primaryKeys.length === 1 &&
149
- primaryKeys[0].type.toLowerCase() === 'integer') {
150
- return primaryKeys[0].name;
151
- }
152
- return undefined;
153
- }
154
-
155
- /** Marshals a Kysely parameter into a value D1's `bind()` accepts. */
156
- function marshalD1Param(value: unknown): unknown {
157
- if (value === undefined) return null;
158
- if (typeof value === 'boolean') return value ? 1 : 0;
159
- if (typeof value === 'bigint') return Number(value);
160
- if (value instanceof Date) return value.toISOString();
161
- return value;
162
- }
163
-
164
- class D1Driver implements Driver {
165
- private readonly connection: D1Connection;
166
- constructor(d1: D1DatabaseLike) {
167
- this.connection = new D1Connection(d1);
168
- }
169
- async init(): Promise<void> {}
170
- async acquireConnection(): Promise<DatabaseConnection> {
171
- return this.connection;
172
- }
173
- async beginTransaction(): Promise<void> {
174
- throw new Error(
175
- '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().',
176
- );
177
- }
178
- async commitTransaction(): Promise<void> {
179
- throw new Error(
180
- '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().',
181
- );
182
- }
183
- async rollbackTransaction(): Promise<void> {
184
- throw new Error(
185
- '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().',
186
- );
187
- }
188
- async releaseConnection(): Promise<void> {}
189
- async destroy(): Promise<void> {}
190
- }
191
-
192
- class D1Connection implements DatabaseConnection {
193
- constructor(private readonly d1: D1DatabaseLike) {}
194
-
195
- async executeQuery<R>(compiledQuery: CompiledQuery): Promise<QueryResult<R>> {
196
- const statement = this.d1.prepare(compiledQuery.sql);
197
- const bound =
198
- compiledQuery.parameters.length > 0
199
- ? statement.bind(...compiledQuery.parameters.map(marshalD1Param))
200
- : statement;
201
- const result = await bound.all<R>();
202
-
203
- const rows = (result.results ?? []) as R[];
204
- const out: { rows: R[]; numAffectedRows?: bigint; insertId?: bigint } = { rows };
205
- const changes = result.meta?.changes;
206
- const lastRowId = result.meta?.last_row_id;
207
- if (typeof changes === 'number') out.numAffectedRows = BigInt(changes);
208
- if (lastRowId !== undefined && lastRowId !== null) out.insertId = BigInt(lastRowId);
209
- return out as QueryResult<R>;
210
- }
211
-
212
- async *streamQuery<R>(compiledQuery: CompiledQuery): AsyncIterableIterator<QueryResult<R>> {
213
- yield await this.executeQuery<R>(compiledQuery);
214
- }
215
- }
@@ -1,104 +0,0 @@
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 DELETED
@@ -1,67 +0,0 @@
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 { D1Adapter, 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';
package/src/middleware.ts DELETED
@@ -1,42 +0,0 @@
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
- }
@@ -1,90 +0,0 @@
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
- }
@@ -1,73 +0,0 @@
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
- }
@@ -1,46 +0,0 @@
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
- }