@kerf-js/db 0.0.0-stage → 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/package.json CHANGED
@@ -1,6 +1,95 @@
1
1
  {
2
2
  "name": "@kerf-js/db",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "description": "kerf's data layers and list sources in one package: each driver is an optional peer, and a subpath loads only its own",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/Ravonus/kerf.git",
9
+ "directory": "packages/db"
10
+ },
11
+ "homepage": "https://github.com/Ravonus/kerf/tree/main/packages/db#readme",
12
+ "bugs": {
13
+ "url": "https://github.com/Ravonus/kerf/issues"
14
+ },
15
+ "type": "module",
16
+ "exports": {
17
+ "./sql": "./src/sql.ts",
18
+ "./sql/plugin": "./plugins/sql.mjs",
19
+ "./kysely": "./src/kysely.ts",
20
+ "./kysely/plugin": "./plugins/kysely.mjs",
21
+ "./prisma": "./src/prisma.ts",
22
+ "./prisma/plugin": "./plugins/prisma.mjs",
23
+ "./mongo": "./src/mongo.ts",
24
+ "./mongo/plugin": "./plugins/mongo.mjs",
25
+ "./dynamodb": "./src/dynamodb.ts",
26
+ "./dynamodb/plugin": "./plugins/dynamodb.mjs",
27
+ "./firestore": "./src/firestore.ts",
28
+ "./firestore/plugin": "./plugins/firestore.mjs",
29
+ "./plugin-native": "./src/native/index.ts",
30
+ "./plugin-native/sqlite": "./src/native/sqlite.ts",
31
+ "./plugin-native/postgres": "./src/native/postgres.ts",
32
+ "./plugin-native/mysql": "./src/native/mysql.ts",
33
+ "./plugin-native/auth": "./src/native/auth.ts",
34
+ "./plugin-native/plugin": "./plugins/native.mjs",
35
+ "./plugin-prisma": "./src/prisma-client.ts",
36
+ "./plugin-prisma/plugin": "./plugins/prisma-client.mjs"
37
+ },
38
+ "peerDependencies": {
39
+ "@aws-sdk/client-dynamodb": "^3.0.0",
40
+ "@aws-sdk/lib-dynamodb": "^3.0.0",
41
+ "@prisma/client": ">=6",
42
+ "@kerf-js/start": "^0.1.0",
43
+ "better-auth": "^1.7.0",
44
+ "firebase-admin": ">=12",
45
+ "kysely": "^0.29.0",
46
+ "mongodb": ">=6",
47
+ "mysql2": "^3.24.0",
48
+ "postgres": ">=3",
49
+ "@kerf-js/core": "^0.1.0"
50
+ },
51
+ "peerDependenciesMeta": {
52
+ "@aws-sdk/client-dynamodb": {
53
+ "optional": true
54
+ },
55
+ "@aws-sdk/lib-dynamodb": {
56
+ "optional": true
57
+ },
58
+ "@prisma/client": {
59
+ "optional": true
60
+ },
61
+ "better-auth": {
62
+ "optional": true
63
+ },
64
+ "firebase-admin": {
65
+ "optional": true
66
+ },
67
+ "kysely": {
68
+ "optional": true
69
+ },
70
+ "mongodb": {
71
+ "optional": true
72
+ },
73
+ "mysql2": {
74
+ "optional": true
75
+ },
76
+ "postgres": {
77
+ "optional": true
78
+ }
79
+ },
80
+ "publishConfig": {
81
+ "access": "public"
82
+ },
83
+ "engines": {
84
+ "node": ">=24"
85
+ },
86
+ "keywords": [
87
+ "kerf"
88
+ ],
89
+ "files": [
90
+ "src",
91
+ "plugins",
92
+ "README.md",
93
+ "LICENSE"
94
+ ]
6
95
  }
@@ -0,0 +1,6 @@
1
+ import type { PluginInstance } from '@kerf-js/core/plugin'
2
+
3
+ /** Binds the DynamoDB list source to `db.adapter@1`. */
4
+ declare const plugin: (options?: Record<string, unknown>) => PluginInstance<unknown>
5
+ /** Installed under `db.adapter@1` by `kerf plugins sync`. */
6
+ export default plugin
@@ -0,0 +1,25 @@
1
+ // dynamoSource() for kerf.config.ts: the `db.adapter` provider under the key `dynamodb`, so the lock records it and `kerf check` names it.
2
+ import { definePlugin, defineSlot, provide } from '@kerf-js/core/plugin'
3
+
4
+ const slot = defineSlot({ id: 'db.adapter', version: 1, cardinality: 'keyed', sides: ['server'] })
5
+
6
+ export const dynamoSource = definePlugin({
7
+ name: '@kerf-js/db/dynamodb',
8
+ version: '0.0.0',
9
+ kerf: '*',
10
+ permissions: { net: ['driver:aws-sdk'] },
11
+ contribute: () => ({
12
+ provides: [
13
+ provide(slot, {
14
+ key: 'dynamodb',
15
+ sides: { server: { module: '@kerf-js/db/dynamodb', export: 'adapter' } },
16
+ }),
17
+ ],
18
+ agents: {
19
+ title: 'Lists (dynamodb)',
20
+ text: 'Build a source once, in a server module, with `columns`: only those are selected, returned or written. Then `query({ input: listInput({ sort, filter, search }), run: ({ input }) => source.list(input) })`. veneer `Table` reads what comes back. Cursor mode only, and a sort needs a partition and an index.',
21
+ },
22
+ }),
23
+ })
24
+
25
+ export default dynamoSource
@@ -0,0 +1,6 @@
1
+ import type { PluginInstance } from '@kerf-js/core/plugin'
2
+
3
+ /** Binds the Firestore list source to `db.adapter@1`. */
4
+ declare const plugin: (options?: Record<string, unknown>) => PluginInstance<unknown>
5
+ /** Installed under `db.adapter@1` by `kerf plugins sync`. */
6
+ export default plugin
@@ -0,0 +1,25 @@
1
+ // firestoreSource() for kerf.config.ts: the `db.adapter` provider under the key `firestore`, so the lock records it and `kerf check` names it.
2
+ import { definePlugin, defineSlot, provide } from '@kerf-js/core/plugin'
3
+
4
+ const slot = defineSlot({ id: 'db.adapter', version: 1, cardinality: 'keyed', sides: ['server'] })
5
+
6
+ export const firestoreSource = definePlugin({
7
+ name: '@kerf-js/db/firestore',
8
+ version: '0.0.0',
9
+ kerf: '*',
10
+ permissions: { net: ['driver:firebase-admin'] },
11
+ contribute: () => ({
12
+ provides: [
13
+ provide(slot, {
14
+ key: 'firestore',
15
+ sides: { server: { module: '@kerf-js/db/firestore', export: 'adapter' } },
16
+ }),
17
+ ],
18
+ agents: {
19
+ title: 'Lists (firestore)',
20
+ text: 'Build a source once, in a server module, with `columns`: only those are selected, returned or written. Then `query({ input: listInput({ sort, filter, search }), run: ({ input }) => source.list(input) })`. veneer `Table` reads what comes back. Search is by prefix on one field, and only without another sort.',
21
+ },
22
+ }),
23
+ })
24
+
25
+ export default firestoreSource
@@ -0,0 +1,6 @@
1
+ import type { PluginInstance } from '@kerf-js/core/plugin'
2
+
3
+ /** Binds the Kysely list source to `db.adapter@1`. */
4
+ declare const plugin: (options?: Record<string, unknown>) => PluginInstance<unknown>
5
+ /** Installed under `db.adapter@1` by `kerf plugins sync`. */
6
+ export default plugin
@@ -0,0 +1,25 @@
1
+ // kyselySource() for kerf.config.ts: the `db.adapter` provider under the key `kysely`, so the lock records it and `kerf check` names it.
2
+ import { definePlugin, defineSlot, provide } from '@kerf-js/core/plugin'
3
+
4
+ const slot = defineSlot({ id: 'db.adapter', version: 1, cardinality: 'keyed', sides: ['server'] })
5
+
6
+ export const kyselySource = definePlugin({
7
+ name: '@kerf-js/db/kysely',
8
+ version: '0.0.0',
9
+ kerf: '*',
10
+ permissions: { net: ['driver:kysely'] },
11
+ contribute: () => ({
12
+ provides: [
13
+ provide(slot, {
14
+ key: 'kysely',
15
+ sides: { server: { module: '@kerf-js/db/kysely', export: 'adapter' } },
16
+ }),
17
+ ],
18
+ agents: {
19
+ title: 'Lists (kysely)',
20
+ text: 'Build a source once, in a server module, with `columns`: only those are selected, returned or written. Then `query({ input: listInput({ sort, filter, search }), run: ({ input }) => source.list(input) })`. veneer `Table` reads what comes back.',
21
+ },
22
+ }),
23
+ })
24
+
25
+ export default kyselySource
@@ -0,0 +1,6 @@
1
+ import type { PluginInstance } from '@kerf-js/core/plugin'
2
+
3
+ /** Binds the MongoDB list source to `db.adapter@1`. */
4
+ declare const plugin: (options?: Record<string, unknown>) => PluginInstance<unknown>
5
+ /** Installed under `db.adapter@1` by `kerf plugins sync`. */
6
+ export default plugin
@@ -0,0 +1,25 @@
1
+ // mongoSource() for kerf.config.ts: the `db.adapter` provider under the key `mongo`, so the lock records it and `kerf check` names it.
2
+ import { definePlugin, defineSlot, provide } from '@kerf-js/core/plugin'
3
+
4
+ const slot = defineSlot({ id: 'db.adapter', version: 1, cardinality: 'keyed', sides: ['server'] })
5
+
6
+ export const mongoSource = definePlugin({
7
+ name: '@kerf-js/db/mongo',
8
+ version: '0.0.0',
9
+ kerf: '*',
10
+ permissions: { net: ['driver:mongodb'] },
11
+ contribute: () => ({
12
+ provides: [
13
+ provide(slot, {
14
+ key: 'mongo',
15
+ sides: { server: { module: '@kerf-js/db/mongo', export: 'adapter' } },
16
+ }),
17
+ ],
18
+ agents: {
19
+ title: 'Lists (mongo)',
20
+ text: 'Build a source once, in a server module, with `columns`: only those are selected, returned or written. Then `query({ input: listInput({ sort, filter, search }), run: ({ input }) => source.list(input) })`. veneer `Table` reads what comes back. `watchMongo` turns writes from anywhere into tag pokes.',
21
+ },
22
+ }),
23
+ })
24
+
25
+ export default mongoSource
@@ -0,0 +1,6 @@
1
+ import type { PluginInstance } from '@kerf-js/core/plugin'
2
+
3
+ /** The no-ORM database client, as a plugin that fills `ctx.db`. */
4
+ export const native: () => PluginInstance<unknown>
5
+ /** The same as the named export. */
6
+ export default native
@@ -0,0 +1,43 @@
1
+ // native() for kerf.config.ts (research 34 §4): the no-ORM data layer. It holds what the CLI needs: where migrations
2
+ // live and how `kerf db generate` starts one. The runtime is `@kerf-js/db/plugin-native/<engine>`.
3
+ import { mkdirSync, readdirSync, writeFileSync } from 'node:fs'
4
+ import { join } from 'node:path'
5
+ import { definePlugin } from '@kerf-js/core/plugin'
6
+
7
+ const DIR = 'migrations'
8
+
9
+ /** A new, empty, numbered migration for you to write: with no schema there is nothing to diff. */
10
+ function generate(root, name = 'change') {
11
+ const dir = join(root, DIR)
12
+ mkdirSync(dir, { recursive: true })
13
+ const next = readdirSync(dir).filter((f) => f.endsWith('.sql')).length
14
+ const file = `${String(next).padStart(4, '0')}_${name.replace(/[^\w-]/g, '_')}.sql`
15
+ writeFileSync(
16
+ join(dir, file),
17
+ '-- Applies on the next request. Migrations run once, in file order.\n',
18
+ )
19
+ return `${DIR}/${file}`
20
+ }
21
+
22
+ export const native = definePlugin({
23
+ name: '@kerf-js/db/plugin-native',
24
+ version: '0.0.0',
25
+ kerf: '*',
26
+ permissions: { fs: { read: ['migrations/**'], write: ['migrations/**'] } },
27
+ contribute: () => ({
28
+ db: { layer: 'native', migrations: DIR, generate },
29
+ agents: {
30
+ title: 'Database (Native)',
31
+ text: 'No ORM: `ctx.db.sql` is a tagged template, and values are always bound, never concatenated. Rows are plain objects. `ctx.db.transaction(tx => …)` gives `tx.sql`, and `ctx.db.driver` is the real driver. `kerf db generate <name>` starts a file in `migrations/`; write the SQL by hand. Validate input with your own Zod schemas.',
32
+ },
33
+ map: [
34
+ {
35
+ want: 'Change the database',
36
+ call: '`kerf db generate <name>`, then write the SQL in `migrations/`',
37
+ have: 'no ORM',
38
+ },
39
+ ],
40
+ }),
41
+ })
42
+
43
+ export default native
@@ -0,0 +1,6 @@
1
+ import type { PluginInstance } from '@kerf-js/core/plugin'
2
+
3
+ /** Prisma as the app's database client, as a plugin that fills `ctx.db`. */
4
+ export const prisma: () => PluginInstance<unknown>
5
+ /** The same as the named export. */
6
+ export default prisma
@@ -0,0 +1,68 @@
1
+ // prisma() for kerf.config.ts (research 34 §4): what the CLI needs from Prisma. `kerf db generate` writes the client and
2
+ // a migration into `prisma/migrations`. The first needs no database; later ones are Prisma's own diff, which does.
3
+ import { spawnSync } from 'node:child_process'
4
+ import { existsSync, mkdirSync, writeFileSync } from 'node:fs'
5
+ import { createRequire } from 'node:module'
6
+ import { dirname, join } from 'node:path'
7
+ import { definePlugin } from '@kerf-js/core/plugin'
8
+
9
+ const DIR = 'prisma/migrations'
10
+
11
+ function run(root, args) {
12
+ let bin
13
+ try {
14
+ bin = join(
15
+ dirname(createRequire(join(root, 'package.json')).resolve('prisma/package.json')),
16
+ 'build/index.js',
17
+ )
18
+ } catch {
19
+ throw Object.assign(new Error('prisma is not installed in this project'), { code: 'E_USAGE' })
20
+ }
21
+ const r = spawnSync(process.execPath, [bin, ...args], { cwd: root, encoding: 'utf8' })
22
+ if (r.status !== 0)
23
+ throw Object.assign(new Error(`prisma ${args[0]} failed:\n${r.stdout}${r.stderr}`), {
24
+ code: 'E_INTERNAL',
25
+ })
26
+ return r.stdout
27
+ }
28
+
29
+ function generate(root, name = 'change') {
30
+ run(root, ['generate'])
31
+ if (existsSync(join(root, DIR)))
32
+ return run(root, ['migrate', 'dev', '--create-only', '--name', name]).trim()
33
+ const sql = run(root, [
34
+ 'migrate',
35
+ 'diff',
36
+ '--from-empty',
37
+ '--to-schema',
38
+ 'prisma/schema.prisma',
39
+ '--script',
40
+ ])
41
+ const dir = join(root, DIR, '00000000000000_init')
42
+ mkdirSync(dir, { recursive: true })
43
+ writeFileSync(join(dir, 'migration.sql'), sql)
44
+ return `${DIR}/00000000000000_init/migration.sql`
45
+ }
46
+
47
+ export const prisma = definePlugin({
48
+ name: '@kerf-js/db/plugin-prisma',
49
+ version: '0.0.0',
50
+ kerf: '*',
51
+ permissions: { fs: { read: ['prisma/**'], write: ['prisma/migrations/**'] }, spawn: ['node'] },
52
+ contribute: () => ({
53
+ db: { layer: 'prisma', schema: 'prisma/schema.prisma', migrations: DIR, generate },
54
+ agents: {
55
+ title: 'Database (Prisma)',
56
+ text: "`ctx.db` is the real Prisma client, so Prisma's docs apply. The schema is `prisma/schema.prisma`; after changing it, run `kerf db generate <name>`, which updates the client and adds a migration that applies on the next request.",
57
+ },
58
+ map: [
59
+ {
60
+ want: 'Change the database',
61
+ call: 'Edit `prisma/schema.prisma`, then `kerf db generate <name>`',
62
+ have: 'Prisma',
63
+ },
64
+ ],
65
+ }),
66
+ })
67
+
68
+ export default prisma
@@ -0,0 +1,6 @@
1
+ import type { PluginInstance } from '@kerf-js/core/plugin'
2
+
3
+ /** Binds the Prisma list source to `db.adapter@1`. */
4
+ declare const plugin: (options?: Record<string, unknown>) => PluginInstance<unknown>
5
+ /** Installed under `db.adapter@1` by `kerf plugins sync`. */
6
+ export default plugin
@@ -0,0 +1,25 @@
1
+ // prismaSource() for kerf.config.ts: the `db.adapter` provider under the key `prisma`, so the lock records it and `kerf check` names it.
2
+ import { definePlugin, defineSlot, provide } from '@kerf-js/core/plugin'
3
+
4
+ const slot = defineSlot({ id: 'db.adapter', version: 1, cardinality: 'keyed', sides: ['server'] })
5
+
6
+ export const prismaSource = definePlugin({
7
+ name: '@kerf-js/db/prisma',
8
+ version: '0.0.0',
9
+ kerf: '*',
10
+ permissions: { net: ['driver:prisma'] },
11
+ contribute: () => ({
12
+ provides: [
13
+ provide(slot, {
14
+ key: 'prisma',
15
+ sides: { server: { module: '@kerf-js/db/prisma', export: 'adapter' } },
16
+ }),
17
+ ],
18
+ agents: {
19
+ title: 'Lists (prisma)',
20
+ text: 'Build a source once, in a server module, with `columns`: only those are selected, returned or written. Then `query({ input: listInput({ sort, filter, search }), run: ({ input }) => source.list(input) })`. veneer `Table` reads what comes back.',
21
+ },
22
+ }),
23
+ })
24
+
25
+ export default prismaSource
@@ -0,0 +1,6 @@
1
+ import type { PluginInstance } from '@kerf-js/core/plugin'
2
+
3
+ /** Binds the bound-SQL list source to `db.adapter@1`. */
4
+ declare const plugin: (options?: Record<string, unknown>) => PluginInstance<unknown>
5
+ /** Installed under `db.adapter@1` by `kerf plugins sync`. */
6
+ export default plugin
@@ -0,0 +1,25 @@
1
+ // sqlSource() for kerf.config.ts: the `db.adapter` provider under the key `sql`, so the lock records it and `kerf check` names it.
2
+ import { definePlugin, defineSlot, provide } from '@kerf-js/core/plugin'
3
+
4
+ const slot = defineSlot({ id: 'db.adapter', version: 1, cardinality: 'keyed', sides: ['server'] })
5
+
6
+ export const sqlSource = definePlugin({
7
+ name: '@kerf-js/db/sql',
8
+ version: '0.0.0',
9
+ kerf: '*',
10
+ permissions: { net: ['driver:query'] },
11
+ contribute: () => ({
12
+ provides: [
13
+ provide(slot, {
14
+ key: 'sql',
15
+ sides: { server: { module: '@kerf-js/db/sql', export: 'adapter' } },
16
+ }),
17
+ ],
18
+ agents: {
19
+ title: 'Lists (sql)',
20
+ text: 'Build a source once, in a server module, with `columns`: only those are selected, returned or written. Then `query({ input: listInput({ sort, filter, search }), run: ({ input }) => source.list(input) })`. veneer `Table` reads what comes back.',
21
+ },
22
+ }),
23
+ })
24
+
25
+ export default sqlSource
package/src/driver.ts ADDED
@@ -0,0 +1,27 @@
1
+ // Optional peers load at the subpath so missing drivers report what to install.
2
+
3
+ const MISSING = new Set(['ERR_MODULE_NOT_FOUND', 'MODULE_NOT_FOUND'])
4
+
5
+ /** True when this failure is `pkg` itself not being there, not something inside it failing to load. */
6
+ const isMissing = (error: unknown, pkg: string) => {
7
+ const { code = '', message } = (error ?? {}) as { code?: string; message?: unknown }
8
+ return (
9
+ (MISSING.has(code) ||
10
+ /cannot find (module|package)|failed to (load|resolve)/i.test(String(message))) &&
11
+ String(message).includes(pkg)
12
+ )
13
+ }
14
+
15
+ /** `await driver('@kerf-js/db/kysely', 'kysely', () => import('kysely'))`. The import stays literal so a bundler still sees it. */
16
+ export async function driver<T>(subpath: string, pkg: string, load: () => Promise<T>): Promise<T> {
17
+ try {
18
+ return await load()
19
+ } catch (error) {
20
+ if (isMissing(error, pkg))
21
+ throw new Error(
22
+ `${subpath} needs the \`${pkg}\` driver, which isn't installed. Run: npm install ${pkg}`,
23
+ { cause: error },
24
+ )
25
+ throw error
26
+ }
27
+ }