nitro-drizzle 0.2.7 → 0.2.9
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 +54 -66
- package/dist/context/internal/templates.mjs.map +1 -1
- package/dist/context/internal/virtual.mjs +19 -2
- package/dist/context/internal/virtual.mjs.map +1 -1
- package/dist/context.d.mts +24 -17
- package/dist/context.mjs +68 -13
- package/dist/context.mjs.map +1 -1
- package/dist/module/internal/assets.mjs +8 -16
- package/dist/module/internal/assets.mjs.map +1 -1
- package/dist/module/internal/externals.mjs +2 -11
- package/dist/module/internal/externals.mjs.map +1 -1
- package/dist/module/internal/resolver.mjs +0 -3
- package/dist/module/internal/resolver.mjs.map +1 -1
- package/dist/module.d.mts +3 -3
- package/dist/module.mjs +44 -42
- package/dist/module.mjs.map +1 -1
- package/package.json +26 -16
- package/dist/module/internal/assets.d.mts +0 -12
- package/dist/module/internal/plugins.mjs +0 -13
- package/dist/module/internal/plugins.mjs.map +0 -1
- package/dist/module/internal/virtual.mjs +0 -23
- package/dist/module/internal/virtual.mjs.map +0 -1
package/README.md
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
[](https://www.npmjs.com/package/nitro-drizzle)
|
|
4
4
|
[](https://github.com/Myshkouski/nitro-drizzle/actions/workflows/ci.yml)
|
|
5
|
+
[](https://codecov.io/github/myshkouski/nitro-drizzle)
|
|
5
6
|
[](https://github.com/Myshkouski/nitro-drizzle/blob/main/LICENSE)
|
|
6
7
|
|
|
7
8
|
`nitro-drizzle` is a powerful module designed to seamlessly integrate the [Drizzle ORM](https://orm.drizzle.team/) with your [Nitro](https://nitro.unjs.io/) applications. It simplifies database management, schema definition, and migrations, allowing you to build robust and scalable backend services with ease.
|
|
@@ -46,7 +47,7 @@ export default defineNitroConfig({
|
|
|
46
47
|
modules: ["nitro-drizzle/module"],
|
|
47
48
|
drizzle: {
|
|
48
49
|
datasources: {
|
|
49
|
-
|
|
50
|
+
content: { connector: "sqlite" },
|
|
50
51
|
},
|
|
51
52
|
},
|
|
52
53
|
});
|
|
@@ -56,9 +57,9 @@ See [ModuleOptions](src/module/index.ts) for all available options.
|
|
|
56
57
|
|
|
57
58
|
### 2. Define Drizzle Config and Schema
|
|
58
59
|
|
|
59
|
-
Create your Drizzle configuration files and schemas in the `baseDir` specified in `nitro.config.ts` (e.g., `server/drizzle/
|
|
60
|
+
Create your Drizzle configuration files and schemas in the `baseDir` specified in `nitro.config.ts` (e.g., `server/drizzle/content/drizzle-sqlite.config.ts` and `server/drizzle/content/sqlite/schema.ts`).
|
|
60
61
|
|
|
61
|
-
#### Example: `server/drizzle/
|
|
62
|
+
#### Example: `server/drizzle/content/drizzle-sqlite.config.ts`
|
|
62
63
|
|
|
63
64
|
```ts
|
|
64
65
|
import { defineConfig } from "nitro-drizzle/config";
|
|
@@ -68,94 +69,59 @@ export default defineConfig(
|
|
|
68
69
|
strict: true,
|
|
69
70
|
dialect: "sqlite",
|
|
70
71
|
out: "./sqlite/migrations", // Migration output directory
|
|
71
|
-
schema:
|
|
72
|
+
schema: "./sqlite/schema.ts", // Path to your schema files
|
|
72
73
|
migrations: {
|
|
73
74
|
table: "drizzle_migrations", // Table to track migrations
|
|
74
75
|
},
|
|
75
76
|
},
|
|
76
|
-
import.meta.url, // Pass import.meta.url for
|
|
77
|
+
import.meta.url, // Pass import.meta.url for compatibility with "drizzle-kit"
|
|
77
78
|
);
|
|
78
79
|
```
|
|
79
80
|
|
|
80
|
-
#### Example: `server/drizzle/
|
|
81
|
+
#### Example: `server/drizzle/content/sqlite/schema.ts`
|
|
81
82
|
|
|
82
83
|
```ts
|
|
83
84
|
import { sqliteTable, integer, text } from "drizzle-orm/sqlite-core";
|
|
84
85
|
|
|
85
|
-
export const
|
|
86
|
-
id: integer("id").primaryKey(),
|
|
87
|
-
|
|
88
|
-
|
|
86
|
+
export const posts = sqliteTable("posts", {
|
|
87
|
+
id: integer("id").primaryKey({ autoIncrement: true }),
|
|
88
|
+
title: text("title").notNull(),
|
|
89
|
+
description: text("description").notNull(),
|
|
90
|
+
image: text("image").notNull(),
|
|
91
|
+
date: integer("date", { mode: "timestamp" }).notNull().defaultNow(),
|
|
92
|
+
authors: text("authors", { mode: "json" }).$type<number[]>(),
|
|
89
93
|
});
|
|
90
|
-
```
|
|
91
|
-
|
|
92
|
-
#### Example: `server/drizzle/bar/drizzle-pglite.config.ts`
|
|
93
|
-
|
|
94
|
-
```ts
|
|
95
|
-
import { defineConfig } from "nitro-drizzle/config";
|
|
96
94
|
|
|
97
|
-
export
|
|
98
|
-
{
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
table: "drizzle_migrations",
|
|
105
|
-
},
|
|
106
|
-
},
|
|
107
|
-
import.meta.url,
|
|
108
|
-
);
|
|
95
|
+
export const comments = sqliteTable("comments", {
|
|
96
|
+
id: integer("id").primaryKey({ autoIncrement: true }),
|
|
97
|
+
postId: integer("post_id").notNull(),
|
|
98
|
+
authorId: integer("author_id").notNull(),
|
|
99
|
+
content: text("content").notNull(),
|
|
100
|
+
createdAt: integer("created_at", { mode: "timestamp" }).notNull(),
|
|
101
|
+
});
|
|
109
102
|
```
|
|
110
103
|
|
|
111
|
-
|
|
104
|
+
### 3. Generate migrations
|
|
112
105
|
|
|
113
|
-
```
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
export const products = pgTable("products", {
|
|
117
|
-
id: serial("id").primaryKey(),
|
|
118
|
-
name: text("name").notNull(),
|
|
119
|
-
description: text("description"),
|
|
120
|
-
});
|
|
106
|
+
```shell
|
|
107
|
+
drizzle-kit generate --config server/drizzle/content/drizzle-sqlite.config.ts
|
|
121
108
|
```
|
|
122
109
|
|
|
123
|
-
###
|
|
110
|
+
### 4. Use Datasources in API Routes
|
|
124
111
|
|
|
125
112
|
You can access your configured datasources in your Nitro API routes using `useDatasource`.
|
|
126
113
|
|
|
127
114
|
```ts
|
|
128
115
|
// server/routes/index.ts
|
|
129
|
-
import {
|
|
116
|
+
import { defineEventHandler } from "h3";
|
|
130
117
|
import { useDatasource } from "nitro-drizzle/runtime";
|
|
131
118
|
|
|
132
|
-
export default
|
|
133
|
-
|
|
134
|
-
const
|
|
135
|
-
|
|
136
|
-
await
|
|
137
|
-
|
|
138
|
-
// Example usage with 'foo' (SQLite)
|
|
139
|
-
const newUsers = await fooDatasource.database
|
|
140
|
-
.insert(fooDatasource.schema.users)
|
|
141
|
-
.values([
|
|
142
|
-
{ name: "Alice", email: "alice@example.com" },
|
|
143
|
-
{ name: "Bob", email: "bob@example.com" },
|
|
144
|
-
])
|
|
145
|
-
.returning()
|
|
146
|
-
.all();
|
|
147
|
-
|
|
148
|
-
// Example usage with 'bar' (PostgreSQL with pglite)
|
|
149
|
-
const newProducts = await barDatasource.database
|
|
150
|
-
.insert(barDatasource.schema.products)
|
|
151
|
-
.values([
|
|
152
|
-
{ name: "Laptop", description: "Powerful laptop" },
|
|
153
|
-
{ name: "Mouse", description: "Wireless mouse" },
|
|
154
|
-
])
|
|
155
|
-
.returning()
|
|
156
|
-
.all();
|
|
157
|
-
|
|
158
|
-
return { newUsers, newProducts };
|
|
119
|
+
export default defineEventHandler(async () => {
|
|
120
|
+
await event.context.drizzle.waitReady(); // Wait for "drizzle:init" hook finished
|
|
121
|
+
const { database, waitReady } = await useDatasource("content"); // Access the 'content' datasource
|
|
122
|
+
await waitReady(); // Wait datasource is ready
|
|
123
|
+
const posts = await database.select().from(schema.posts).limit(10);
|
|
124
|
+
return { posts };
|
|
159
125
|
});
|
|
160
126
|
```
|
|
161
127
|
|
|
@@ -167,6 +133,28 @@ If you enabled Nitro tasks in `nitro.config.ts`, you can run migrations via the
|
|
|
167
133
|
npx nitro task drizzle:migrate
|
|
168
134
|
```
|
|
169
135
|
|
|
136
|
+
## 📁 Sample Project Structure
|
|
137
|
+
|
|
138
|
+
A minimal layout with SQLite database for `content` and PostgreSQL database for `users`. Each datasource has its own drizzle config, schema, and migrations folder.
|
|
139
|
+
|
|
140
|
+
```
|
|
141
|
+
blog-api/
|
|
142
|
+
├── nitro.config.ts
|
|
143
|
+
├── package.json
|
|
144
|
+
└── server/
|
|
145
|
+
└── drizzle/
|
|
146
|
+
├── content/
|
|
147
|
+
│ ├── drizzle-sqlite.config.ts
|
|
148
|
+
│ └── sqlite/
|
|
149
|
+
│ ├── migrations/*.sql
|
|
150
|
+
│ └── schema/*.ts
|
|
151
|
+
└── users/
|
|
152
|
+
├── drizzle-postgresql.config.ts
|
|
153
|
+
└── postgresql/
|
|
154
|
+
├── migrations/*.sql
|
|
155
|
+
└── schema.ts
|
|
156
|
+
```
|
|
157
|
+
|
|
170
158
|
## 📖 API Documentation
|
|
171
159
|
|
|
172
160
|
### `useDatasource(name: string, options?: UseDatasourceOptions)`
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"templates.mjs","names":[],"sources":["../../../src/context/internal/templates.ts"],"sourcesContent":["import {\n genTypeImport,\n genAugmentation,\n genInlineTypeImport,\n genString,\n genExport,\n} from \"knitwork\";\nimport type { DatasourceInfo } from \"..\";\nimport type { VirtualModules } from \"nitro-drizzle/shared\";\n\nexport function runtimeDeclarations(datasources: DatasourceInfo[]) {\n if (!datasources.length) {\n return \"\";\n }\n\n return [\n genTypeImport(\"nitro-drizzle/runtime\", [\"ToDatasourceProvider\"]),\n genAugmentation(\"nitro-drizzle/runtime\", {\n DatasourceRegistry: Object.fromEntries(\n datasources\n .filter((datasource) => {\n return datasource.enabled;\n })\n .map(({ name, imports }): [string, string] => {\n const schemaType = genSchemaType(imports.schema);\n const driverType = genInlineTypeImport(imports.connector);\n return [name, `${\"ToDatasourceProvider\"}<${schemaType}, ${driverType}<${schemaType}>>`];\n }),\n ),\n }),\n ].join(\"\\n\");\n}\n\nfunction genSchemaType(imports: string[]) {\n return imports.map((id) => `typeof import('${id}')`).join(\" & \");\n}\n\nexport type TypeReference = { types: string };\n\nexport type PathReference = { path: string };\n\nexport function genReference(reference: TypeReference | PathReference) {\n return /* ts */ `/// <reference ${Object.entries(reference)\n .map(([prop, value]) => `${prop}=\"${value}\"`)\n .join(\"\")} />`;\n}\n\nexport function moduleTypeDeclarations(\n datasources: DatasourceInfo[],\n): VirtualModules<`${string}.d.ts`> {\n if (!datasources.length) {\n return {};\n }\n\n const names = datasources.map((d) => d.name);\n\n const moduleId = \"nitro-drizzle/module\";\n\n const content = [\n genReference({ types: moduleId }),\n genAugmentation(moduleId, {\n DatasourceOptions: [\n {},\n {\n extends: `Record<${names.map((n) => genString(n)).join(\" | \")}, { connector: string; }>`,\n },\n ],\n }),\n /* ts */ `export {};`,\n ].join(\"\\n\");\n\n return {\n \"nitro-drizzle/module.d.ts\": content,\n };\n}\n\nexport function dialectDeclarations(datasources: DatasourceInfo[]) {\n return datasources\n .filter((d) => d.enabled)\n .map(({ name, dialect }) => {\n return /*ts*/ `\n declare module \"#nitro-drizzle/dialects/${name}\" {\n ${genExport(`nitro-drizzle/dialects/${dialect}`, \"*\")}\n }\n `;\n })\n .join(\"\\n\");\n}\n"],"mappings":";;AAUA,SAAgB,oBAAoB,
|
|
1
|
+
{"version":3,"file":"templates.mjs","names":[],"sources":["../../../src/context/internal/templates.ts"],"sourcesContent":["import {\n genTypeImport,\n genAugmentation,\n genInlineTypeImport,\n genString,\n genExport,\n} from \"knitwork\";\nimport type { DatasourceInfo } from \"..\";\nimport type { VirtualModules } from \"nitro-drizzle/shared\";\n\nexport function runtimeDeclarations(datasources: readonly DatasourceInfo[]) {\n if (!datasources.length) {\n return \"\";\n }\n\n return [\n genTypeImport(\"nitro-drizzle/runtime\", [\"ToDatasourceProvider\"]),\n genAugmentation(\"nitro-drizzle/runtime\", {\n DatasourceRegistry: Object.fromEntries(\n datasources\n .filter((datasource) => {\n return datasource.enabled;\n })\n .map(({ name, imports }): [string, string] => {\n const schemaType = genSchemaType(imports.schema);\n const driverType = genInlineTypeImport(imports.connector);\n return [name, `${\"ToDatasourceProvider\"}<${schemaType}, ${driverType}<${schemaType}>>`];\n }),\n ),\n }),\n ].join(\"\\n\");\n}\n\nfunction genSchemaType(imports: string[]) {\n return imports.map((id) => `typeof import('${id}')`).join(\" & \");\n}\n\nexport type TypeReference = { types: string };\n\nexport type PathReference = { path: string };\n\nexport function genReference(reference: TypeReference | PathReference) {\n return /* ts */ `/// <reference ${Object.entries(reference)\n .map(([prop, value]) => `${prop}=\"${value}\"`)\n .join(\"\")} />`;\n}\n\nexport function moduleTypeDeclarations(\n datasources: readonly DatasourceInfo[],\n): VirtualModules<`${string}.d.ts`> {\n if (!datasources.length) {\n return {};\n }\n\n const names = datasources.map((d) => d.name);\n\n const moduleId = \"nitro-drizzle/module\";\n\n const content = [\n genReference({ types: moduleId }),\n genAugmentation(moduleId, {\n DatasourceOptions: [\n {},\n {\n extends: `Record<${names.map((n) => genString(n)).join(\" | \")}, { connector: string; }>`,\n },\n ],\n }),\n /* ts */ `export {};`,\n ].join(\"\\n\");\n\n return {\n \"nitro-drizzle/module.d.ts\": content,\n };\n}\n\nexport function dialectDeclarations(datasources: readonly DatasourceInfo[]) {\n return datasources\n .filter((d) => d.enabled)\n .map(({ name, dialect }) => {\n return /*ts*/ `\n declare module \"#nitro-drizzle/dialects/${name}\" {\n ${genExport(`nitro-drizzle/dialects/${dialect}`, \"*\")}\n }\n `;\n })\n .join(\"\\n\");\n}\n"],"mappings":";;AAUA,SAAgB,oBAAoB,aAAwC;CAC1E,IAAI,CAAC,YAAY,QACf,OAAO;CAGT,OAAO,CACL,cAAc,yBAAyB,CAAC,sBAAsB,CAAC,GAC/D,gBAAgB,yBAAyB,EACvC,oBAAoB,OAAO,YACzB,YACG,QAAQ,eAAe;EACtB,OAAO,WAAW;CACpB,CAAC,CAAC,CACD,KAAK,EAAE,MAAM,cAAgC;EAC5C,MAAM,aAAa,cAAc,QAAQ,MAAM;EAE/C,OAAO,CAAC,MAAM,wBAA6B,WAAW,IADnC,oBAAoB,QAAQ,SACoB,EAAE,GAAG,WAAW,GAAG;CACxF,CAAC,CACL,EACF,CAAC,CACH,CAAC,CAAC,KAAK,IAAI;AACb;AAEA,SAAS,cAAc,SAAmB;CACxC,OAAO,QAAQ,KAAK,OAAO,kBAAkB,GAAG,GAAG,CAAC,CAAC,KAAK,KAAK;AACjE;AAMA,SAAgB,aAAa,WAA0C;CACrE,OAAgB,kBAAkB,OAAO,QAAQ,SAAS,CAAC,CACxD,KAAK,CAAC,MAAM,WAAW,GAAG,KAAK,IAAI,MAAM,EAAE,CAAC,CAC5C,KAAK,EAAE,EAAE;AACd;AAEA,SAAgB,uBACd,aACkC;CAClC,IAAI,CAAC,YAAY,QACf,OAAO,CAAC;CAGV,MAAM,QAAQ,YAAY,KAAK,MAAM,EAAE,IAAI;CAE3C,MAAM,WAAW;CAejB,OAAO,EACL,6BAdc;EACd,aAAa,EAAE,OAAO,SAAS,CAAC;EAChC,gBAAgB,UAAU,EACxB,mBAAmB,CACjB,CAAC,GACD,EACE,SAAS,UAAU,MAAM,KAAK,MAAM,UAAU,CAAC,CAAC,CAAC,CAAC,KAAK,KAAK,EAAE,2BAChE,CACF,EACF,CAAC;EACQ;CACX,CAAC,CAAC,KAAK,IAG8B,EACrC;AACF;AAEA,SAAgB,oBAAoB,aAAwC;CAC1E,OAAO,YACJ,QAAQ,MAAM,EAAE,OAAO,CAAC,CACxB,KAAK,EAAE,MAAM,cAAc;EAC1B,OAAc;kDAC8B,KAAK;YAC3C,UAAU,0BAA0B,WAAW,GAAG,EAAE;;;CAG5D,CAAC,CAAC,CACD,KAAK,IAAI;AACd"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { genExport, genImport, genObjectFromRaw, genObjectFromRawEntries, genSafeVariableName } from "knitwork";
|
|
1
|
+
import { genArrayFromRaw, genExport, genImport, genObjectFromRaw, genObjectFromRawEntries, genSafeVariableName, genString } from "knitwork";
|
|
2
2
|
//#region src/context/internal/virtual.ts
|
|
3
3
|
function genDatasourceModuleVariableName(dbModuleIndex) {
|
|
4
4
|
return genSafeVariableName(`dbModule${dbModuleIndex}`);
|
|
@@ -61,7 +61,24 @@ function dialectVirtualModules(datasources) {
|
|
|
61
61
|
return [`#nitro-drizzle/dialects/${name}`, genExport(`nitro-drizzle/dialects/${dialect}`, "*")];
|
|
62
62
|
}));
|
|
63
63
|
}
|
|
64
|
+
function migrationsVirtualModule(datasources, options) {
|
|
65
|
+
if (!options) return {};
|
|
66
|
+
const parts = [];
|
|
67
|
+
const enabledDatasources = datasources.filter((d) => d.enabled);
|
|
68
|
+
parts.push(`
|
|
69
|
+
export const migrationConfig = ${genObjectFromRawEntries(enabledDatasources.map(({ name, migrations }) => {
|
|
70
|
+
return [name, JSON.stringify(migrations.config)];
|
|
71
|
+
}))};
|
|
72
|
+
`);
|
|
73
|
+
let migrateOnInit = enabledDatasources.map((d) => d.name);
|
|
74
|
+
if (options && Array.isArray(options.migrateOnInit)) migrateOnInit = migrateOnInit.filter((name) => options.migrateOnInit.includes(name));
|
|
75
|
+
parts.push(`
|
|
76
|
+
export const MIGRATIONS_STORAGE_BASE = ${genString(options.storageBase)};
|
|
77
|
+
export const MIGRATE_ON_INIT = ${genArrayFromRaw(migrateOnInit.map((name) => genString(name)))};
|
|
78
|
+
`);
|
|
79
|
+
return { "#nitro-drizzle/migrations": parts.join("\n") };
|
|
80
|
+
}
|
|
64
81
|
//#endregion
|
|
65
|
-
export { dialectVirtualModules, runtimeVirtualModule };
|
|
82
|
+
export { dialectVirtualModules, migrationsVirtualModule, runtimeVirtualModule };
|
|
66
83
|
|
|
67
84
|
//# sourceMappingURL=virtual.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"virtual.mjs","names":[],"sources":["../../../src/context/internal/virtual.ts"],"sourcesContent":["import {\n genExport,\n genImport,\n genObjectFromRaw,\n genObjectFromRawEntries,\n genSafeVariableName,\n} from \"knitwork\";\nimport type { DatasourceInfo } from \"..\";\nimport type { VirtualModules } from \"nitro-drizzle/shared\";\n\nfunction genDatasourceModuleVariableName(dbModuleIndex: number) {\n return genSafeVariableName(`dbModule${dbModuleIndex}`);\n}\n\nfunction genMergedSchemaVariableName(dbModuleIndex: number) {\n return genSafeVariableName(`mergedSchema${dbModuleIndex}`);\n}\n\nconst genSchemaModuleVariableName = (dbModuleIndex: number, schemaIndex: number) =>\n genSafeVariableName(`schemaModule${dbModuleIndex}_${schemaIndex}`);\n\nfunction mergeSchemaModules(schemaIds: string[], dbModuleIndex: number) {\n return /* js */ `\n Object.assign(\n ${[\n /* js */ `{}`,\n ...schemaIds.map((_, schemaModuleIdIndex) =>\n genSchemaModuleVariableName(dbModuleIndex, schemaModuleIdIndex),\n ),\n ].join(\",\")}\n )\n `;\n}\n\nexport function runtimeVirtualModule(datasources: DatasourceInfo[]) {\n const parts = datasources\n .filter((datasource) => datasource.enabled)\n .map(({ name, imports: { schema, connector } }, datasourceIndex) => {\n const datasourceModuleVariableName = genDatasourceModuleVariableName(datasourceIndex);\n\n const imports = [\n genImport(connector, datasourceModuleVariableName),\n ...schema.map((schemaModuleId, schemaIndex) => {\n return genImport(schemaModuleId, {\n name: \"*\",\n as: genSchemaModuleVariableName(datasourceIndex, schemaIndex),\n });\n }),\n ];\n\n const mergedSchemaVariableName = genMergedSchemaVariableName(datasourceIndex);\n const mergedSchemaObject = mergeSchemaModules(schema, datasourceIndex);\n\n const schemaDefinitions = [\n /* js */ `const ${mergedSchemaVariableName} = ${mergedSchemaObject};`,\n ];\n\n const entries: [string, string][] = [\n [\n name,\n genObjectFromRaw({\n create: /* js */ `(config) => ${datasourceModuleVariableName}(config, ${mergedSchemaVariableName})`,\n schema: mergedSchemaVariableName,\n }),\n ],\n ];\n\n return {\n imports,\n schemaDefinitions,\n entries,\n };\n })\n .reduce(\n (acc, { imports, schemaDefinitions, entries }) => {\n return {\n imports: [...acc.imports, ...imports],\n schemaDefinitions: [...acc.schemaDefinitions, ...schemaDefinitions],\n entries: [...acc.entries, ...entries],\n };\n },\n {\n imports: [] as string[],\n schemaDefinitions: [] as string[],\n entries: [] as [string, string][],\n },\n );\n\n const datasourceRegistryVarName = genSafeVariableName(\"datasourceRegistry\");\n\n return /* js */ `\n ${parts.imports.join(\"\\n\")}\n \n ${parts.schemaDefinitions.join(\"\\n\")}\n \n const ${datasourceRegistryVarName} = ${genObjectFromRawEntries(parts.entries)};\n\n export function useDatasourceRegistry() {\n return ${datasourceRegistryVarName};\n }\n `;\n}\n\n// Replaced with aliases\nexport function dialectVirtualModules(\n datasources: DatasourceInfo[],\n): VirtualModules<`#nitro-drizzle/${string}`> {\n return Object.fromEntries(\n datasources\n .filter((d) => d.enabled)\n .map(({ name, dialect }) => {\n return [\n `#nitro-drizzle/dialects/${name}`,\n genExport(`nitro-drizzle/dialects/${dialect}`, \"*\"),\n ] as const;\n }),\n );\n}\n"],"mappings":";;
|
|
1
|
+
{"version":3,"file":"virtual.mjs","names":[],"sources":["../../../src/context/internal/virtual.ts"],"sourcesContent":["import {\n genArrayFromRaw,\n genExport,\n genImport,\n genObjectFromRaw,\n genObjectFromRawEntries,\n genSafeVariableName,\n genString,\n} from \"knitwork\";\nimport type { DatasourceInfo, MigrationOptions } from \"..\";\nimport type { VirtualModules } from \"nitro-drizzle/shared\";\n\nfunction genDatasourceModuleVariableName(dbModuleIndex: number) {\n return genSafeVariableName(`dbModule${dbModuleIndex}`);\n}\n\nfunction genMergedSchemaVariableName(dbModuleIndex: number) {\n return genSafeVariableName(`mergedSchema${dbModuleIndex}`);\n}\n\nconst genSchemaModuleVariableName = (dbModuleIndex: number, schemaIndex: number) =>\n genSafeVariableName(`schemaModule${dbModuleIndex}_${schemaIndex}`);\n\nfunction mergeSchemaModules(schemaIds: string[], dbModuleIndex: number) {\n return /* js */ `\n Object.assign(\n ${[\n /* js */ `{}`,\n ...schemaIds.map((_, schemaModuleIdIndex) =>\n genSchemaModuleVariableName(dbModuleIndex, schemaModuleIdIndex),\n ),\n ].join(\",\")}\n )\n `;\n}\n\nexport function runtimeVirtualModule(datasources: readonly DatasourceInfo[]) {\n const parts = datasources\n .filter((datasource) => datasource.enabled)\n .map(({ name, imports: { schema, connector } }, datasourceIndex) => {\n const datasourceModuleVariableName = genDatasourceModuleVariableName(datasourceIndex);\n\n const imports = [\n genImport(connector, datasourceModuleVariableName),\n ...schema.map((schemaModuleId, schemaIndex) => {\n return genImport(schemaModuleId, {\n name: \"*\",\n as: genSchemaModuleVariableName(datasourceIndex, schemaIndex),\n });\n }),\n ];\n\n const mergedSchemaVariableName = genMergedSchemaVariableName(datasourceIndex);\n const mergedSchemaObject = mergeSchemaModules(schema, datasourceIndex);\n\n const schemaDefinitions = [\n /* js */ `const ${mergedSchemaVariableName} = ${mergedSchemaObject};`,\n ];\n\n const entries: [string, string][] = [\n [\n name,\n genObjectFromRaw({\n create: /* js */ `(config) => ${datasourceModuleVariableName}(config, ${mergedSchemaVariableName})`,\n schema: mergedSchemaVariableName,\n }),\n ],\n ];\n\n return {\n imports,\n schemaDefinitions,\n entries,\n };\n })\n .reduce(\n (acc, { imports, schemaDefinitions, entries }) => {\n return {\n imports: [...acc.imports, ...imports],\n schemaDefinitions: [...acc.schemaDefinitions, ...schemaDefinitions],\n entries: [...acc.entries, ...entries],\n };\n },\n {\n imports: [] as string[],\n schemaDefinitions: [] as string[],\n entries: [] as [string, string][],\n },\n );\n\n const datasourceRegistryVarName = genSafeVariableName(\"datasourceRegistry\");\n\n return /* js */ `\n ${parts.imports.join(\"\\n\")}\n \n ${parts.schemaDefinitions.join(\"\\n\")}\n \n const ${datasourceRegistryVarName} = ${genObjectFromRawEntries(parts.entries)};\n\n export function useDatasourceRegistry() {\n return ${datasourceRegistryVarName};\n }\n `;\n}\n\n// Replaced with aliases\nexport function dialectVirtualModules(\n datasources: readonly DatasourceInfo[],\n): VirtualModules<`#nitro-drizzle/${string}`> {\n return Object.fromEntries(\n datasources\n .filter((d) => d.enabled)\n .map(({ name, dialect }) => {\n return [\n `#nitro-drizzle/dialects/${name}`,\n genExport(`nitro-drizzle/dialects/${dialect}`, \"*\"),\n ] as const;\n }),\n );\n}\n\nexport function migrationsVirtualModule(\n datasources: readonly DatasourceInfo[],\n options: MigrationOptions | undefined,\n): VirtualModules<`#nitro-drizzle/${string}`> {\n if (!options) {\n return {};\n }\n\n const parts: string[] = [];\n\n const enabledDatasources = datasources.filter((d) => d.enabled);\n\n parts.push(/*js*/ `\n export const migrationConfig = ${genObjectFromRawEntries(\n enabledDatasources.map(({ name, migrations }) => {\n return [name, JSON.stringify(migrations.config)];\n }),\n )};\n `);\n\n let migrateOnInit = enabledDatasources.map((d) => d.name);\n if (options && Array.isArray(options.migrateOnInit)) {\n migrateOnInit = migrateOnInit.filter((name) =>\n (options.migrateOnInit as readonly string[]).includes(name),\n );\n }\n\n parts.push(/*js*/ `\n export const MIGRATIONS_STORAGE_BASE = ${genString(options.storageBase)};\n export const MIGRATE_ON_INIT = ${genArrayFromRaw(migrateOnInit.map((name) => genString(name)))};\n `);\n\n return {\n \"#nitro-drizzle/migrations\": parts.join(\"\\n\"),\n };\n}\n"],"mappings":";;AAYA,SAAS,gCAAgC,eAAuB;CAC9D,OAAO,oBAAoB,WAAW,eAAe;AACvD;AAEA,SAAS,4BAA4B,eAAuB;CAC1D,OAAO,oBAAoB,eAAe,eAAe;AAC3D;AAEA,MAAM,+BAA+B,eAAuB,gBAC1D,oBAAoB,eAAe,cAAc,GAAG,aAAa;AAEnE,SAAS,mBAAmB,WAAqB,eAAuB;CACtE,OAAgB;;QAEV,CACS,MACT,GAAG,UAAU,KAAK,GAAG,wBACnB,4BAA4B,eAAe,mBAAmB,CAChE,CACF,CAAC,CAAC,KAAK,GAAG,EAAE;;;AAGlB;AAEA,SAAgB,qBAAqB,aAAwC;CAC3E,MAAM,QAAQ,YACX,QAAQ,eAAe,WAAW,OAAO,CAAC,CAC1C,KAAK,EAAE,MAAM,SAAS,EAAE,QAAQ,eAAe,oBAAoB;EAClE,MAAM,+BAA+B,gCAAgC,eAAe;EAEpF,MAAM,UAAU,CACd,UAAU,WAAW,4BAA4B,GACjD,GAAG,OAAO,KAAK,gBAAgB,gBAAgB;GAC7C,OAAO,UAAU,gBAAgB;IAC/B,MAAM;IACN,IAAI,4BAA4B,iBAAiB,WAAW;GAC9D,CAAC;EACH,CAAC,CACH;EAEA,MAAM,2BAA2B,4BAA4B,eAAe;EAiB5E,OAAO;GACL;GACA,mBAAA,CAfS,SAAS,yBAAyB,KAHlB,mBAAmB,QAAQ,eAGa,EAAE,EAenD;GAChB,SAAA,CAZA,CACE,MACA,iBAAiB;IACf,QAAiB,eAAe,6BAA6B,WAAW,yBAAyB;IACjG,QAAQ;GACV,CAAC,CACH,CAMM;EACR;CACF,CAAC,CAAC,CACD,QACE,KAAK,EAAE,SAAS,mBAAmB,cAAc;EAChD,OAAO;GACL,SAAS,CAAC,GAAG,IAAI,SAAS,GAAG,OAAO;GACpC,mBAAmB,CAAC,GAAG,IAAI,mBAAmB,GAAG,iBAAiB;GAClE,SAAS,CAAC,GAAG,IAAI,SAAS,GAAG,OAAO;EACtC;CACF,GACA;EACE,SAAS,CAAC;EACV,mBAAmB,CAAC;EACpB,SAAS,CAAC;CACZ,CACF;CAEF,MAAM,4BAA4B,oBAAoB,oBAAoB;CAE1E,OAAgB;MACZ,MAAM,QAAQ,KAAK,IAAI,EAAE;;MAEzB,MAAM,kBAAkB,KAAK,IAAI,EAAE;;YAE7B,0BAA0B,KAAK,wBAAwB,MAAM,OAAO,EAAE;;;eAGnE,0BAA0B;;;AAGzC;AAGA,SAAgB,sBACd,aAC4C;CAC5C,OAAO,OAAO,YACZ,YACG,QAAQ,MAAM,EAAE,OAAO,CAAC,CACxB,KAAK,EAAE,MAAM,cAAc;EAC1B,OAAO,CACL,2BAA2B,QAC3B,UAAU,0BAA0B,WAAW,GAAG,CACpD;CACF,CAAC,CACL;AACF;AAEA,SAAgB,wBACd,aACA,SAC4C;CAC5C,IAAI,CAAC,SACH,OAAO,CAAC;CAGV,MAAM,QAAkB,CAAC;CAEzB,MAAM,qBAAqB,YAAY,QAAQ,MAAM,EAAE,OAAO;CAE9D,MAAM,KAAY;qCACiB,wBAC/B,mBAAmB,KAAK,EAAE,MAAM,iBAAiB;EAC/C,OAAO,CAAC,MAAM,KAAK,UAAU,WAAW,MAAM,CAAC;CACjD,CAAC,CACH,EAAE;GACH;CAED,IAAI,gBAAgB,mBAAmB,KAAK,MAAM,EAAE,IAAI;CACxD,IAAI,WAAW,MAAM,QAAQ,QAAQ,aAAa,GAChD,gBAAgB,cAAc,QAAQ,SACnC,QAAQ,cAAoC,SAAS,IAAI,CAC5D;CAGF,MAAM,KAAY;6CACyB,UAAU,QAAQ,WAAW,EAAE;qCACvC,gBAAgB,cAAc,KAAK,SAAS,UAAU,IAAI,CAAC,CAAC,EAAE;GAChG;CAED,OAAO,EACL,6BAA6B,MAAM,KAAK,IAAI,EAC9C;AACF"}
|
package/dist/context.d.mts
CHANGED
|
@@ -1,12 +1,14 @@
|
|
|
1
1
|
import { Config } from "drizzle-kit";
|
|
2
2
|
import { ConsolaInstance } from "consola";
|
|
3
3
|
import { MaybePromise, VirtualModules } from "nitro-drizzle/shared";
|
|
4
|
+
import { ServerAssetDir } from "nitropack/types";
|
|
4
5
|
|
|
5
6
|
//#region src/context/index.d.ts
|
|
6
7
|
/**
|
|
7
8
|
* Context interface for managing Drizzle datasource configurations.
|
|
8
9
|
*/
|
|
9
10
|
interface Context {
|
|
11
|
+
init(): MaybePromise<void>;
|
|
10
12
|
/**
|
|
11
13
|
* Reloads the context, clearing any cached datasource information.
|
|
12
14
|
*/
|
|
@@ -15,13 +17,6 @@ interface Context {
|
|
|
15
17
|
* Returns a list of all resolved datasource information.
|
|
16
18
|
*/
|
|
17
19
|
datasources(): MaybePromise<DatasourceInfo[]>;
|
|
18
|
-
/**
|
|
19
|
-
* Returns virtual module code for runtime datasource access.
|
|
20
|
-
*/
|
|
21
|
-
virtualModules(): MaybePromise<VirtualModules>;
|
|
22
|
-
virtualTypeDeclarations(): MaybePromise<Record<string, VirtualModules>>;
|
|
23
|
-
moduleTypeDeclarations(): MaybePromise<VirtualModules<`${string}.d.ts`>>;
|
|
24
|
-
runtimeTypeDeclarations(): MaybePromise<VirtualModules<`${string}.d.ts`>>;
|
|
25
20
|
}
|
|
26
21
|
/**
|
|
27
22
|
* Glob pattern or array of patterns to match Drizzle configuration files.
|
|
@@ -39,14 +34,13 @@ interface Resolver {
|
|
|
39
34
|
* Attempts to resolve a module ID, returns undefined if not found.
|
|
40
35
|
*/
|
|
41
36
|
tryResolve(id: string): string | undefined;
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
}): Promise<T>;
|
|
37
|
+
}
|
|
38
|
+
type ContextHook<TArgs extends readonly any[] = []> = (this: void, ...args: TArgs) => MaybePromise<void>;
|
|
39
|
+
interface MigrationOptions {
|
|
40
|
+
/** Base storage key path for migrations. */
|
|
41
|
+
storageBase: string;
|
|
42
|
+
/** Whether and which datasources to migrate on initialization. */
|
|
43
|
+
migrateOnInit: boolean | readonly string[];
|
|
50
44
|
}
|
|
51
45
|
interface ContextOptions {
|
|
52
46
|
logger?: ConsolaInstance;
|
|
@@ -72,7 +66,20 @@ interface ContextOptions {
|
|
|
72
66
|
datasource: Record<string, {
|
|
73
67
|
connector: string;
|
|
74
68
|
}>;
|
|
75
|
-
|
|
69
|
+
migrations: MigrationOptions | undefined;
|
|
70
|
+
tasks?: ContextHook<[tasks: Record<string, {
|
|
71
|
+
handler: string;
|
|
72
|
+
description: string;
|
|
73
|
+
}>]>;
|
|
74
|
+
plugins: ContextHook<[plugins: readonly string[]]>;
|
|
75
|
+
declarations: ContextHook<[declarations: {
|
|
76
|
+
module: VirtualModules<`${string}.d.ts`>;
|
|
77
|
+
runtime: VirtualModules<`${string}.d.ts`>;
|
|
78
|
+
virtual: Record<string, VirtualModules<`${string}.d.ts`>>;
|
|
79
|
+
}]>;
|
|
80
|
+
virtualModules: ContextHook<[modules: VirtualModules]>;
|
|
81
|
+
assets: ContextHook<[assets: readonly ServerAssetDir[]]>;
|
|
82
|
+
inlineExternals?: ContextHook<[modules: readonly string[]]>;
|
|
76
83
|
}
|
|
77
84
|
/**
|
|
78
85
|
* Creates a Context instance for managing Drizzle datasource configurations.
|
|
@@ -108,5 +115,5 @@ interface DatasourceInfo {
|
|
|
108
115
|
};
|
|
109
116
|
}
|
|
110
117
|
//#endregion
|
|
111
|
-
export { ConfigPattern, Context, ContextOptions, DatasourceInfo, Resolver, createContext };
|
|
118
|
+
export { ConfigPattern, Context, ContextHook, ContextOptions, DatasourceInfo, MigrationOptions, Resolver, createContext };
|
|
112
119
|
//# sourceMappingURL=context.d.mts.map
|
package/dist/context.mjs
CHANGED
|
@@ -3,8 +3,11 @@ import { accent } from "./context/internal/logger.mjs";
|
|
|
3
3
|
import { resolveFiles } from "./context/internal/fs.mjs";
|
|
4
4
|
import { dialectDeclarations, genReference, moduleTypeDeclarations, runtimeDeclarations } from "./context/internal/templates.mjs";
|
|
5
5
|
import { transformDrizzleConfig } from "./context/internal/config.mjs";
|
|
6
|
-
import { dialectVirtualModules, runtimeVirtualModule } from "./context/internal/virtual.mjs";
|
|
6
|
+
import { dialectVirtualModules, migrationsVirtualModule, runtimeVirtualModule } from "./context/internal/virtual.mjs";
|
|
7
|
+
import { join } from "pathe";
|
|
8
|
+
import { pkgDir, pkgName } from "nitro-drizzle/meta";
|
|
7
9
|
import { colorize } from "consola/utils";
|
|
10
|
+
import { loadConfig } from "c12";
|
|
8
11
|
//#region src/context/index.ts
|
|
9
12
|
var DefaultContext = class {
|
|
10
13
|
#datasources = null;
|
|
@@ -12,12 +15,46 @@ var DefaultContext = class {
|
|
|
12
15
|
constructor(options) {
|
|
13
16
|
this.#options = options;
|
|
14
17
|
}
|
|
18
|
+
async init() {
|
|
19
|
+
const datasources = await this.datasources();
|
|
20
|
+
await this.#options.plugins(this.enabledPlugins());
|
|
21
|
+
const [virtualModules, virtualTypes, moduleTypes, runtimeTypes] = await Promise.all([
|
|
22
|
+
this.virtualModules(datasources),
|
|
23
|
+
this.virtualTypeDeclarations(datasources),
|
|
24
|
+
this.moduleTypeDeclarations(datasources),
|
|
25
|
+
this.runtimeTypeDeclarations(datasources)
|
|
26
|
+
]);
|
|
27
|
+
await this.#options.virtualModules(virtualModules);
|
|
28
|
+
await this.#options.declarations({
|
|
29
|
+
virtual: virtualTypes,
|
|
30
|
+
module: moduleTypes,
|
|
31
|
+
runtime: runtimeTypes
|
|
32
|
+
});
|
|
33
|
+
if (this.#options.migrations) {
|
|
34
|
+
const assets = await this.migrationAssets(datasources);
|
|
35
|
+
if (assets) await this.#options.assets(assets);
|
|
36
|
+
await this.#options.tasks?.({ "drizzle:migrate": {
|
|
37
|
+
description: "Run drizzle migrations for a datasource.",
|
|
38
|
+
handler: "nitro-drizzle/migrations/task"
|
|
39
|
+
} });
|
|
40
|
+
}
|
|
41
|
+
if (this.#options.inlineExternals) {
|
|
42
|
+
const inlineModuleIds = [
|
|
43
|
+
"runtime",
|
|
44
|
+
"plugins",
|
|
45
|
+
"migrations"
|
|
46
|
+
].flatMap((id) => {
|
|
47
|
+
return [join(pkgName, id), join(pkgDir, "dist", id)];
|
|
48
|
+
});
|
|
49
|
+
await this.#options.inlineExternals(inlineModuleIds);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
15
52
|
async datasources() {
|
|
16
53
|
const { logger, baseDir, configPattern, resolver, datasource: datasourceOptions } = this.#options;
|
|
17
54
|
if (!this.#datasources) {
|
|
18
55
|
logger?.info("Searching drizzle datasources in", colorize("blue", baseDir));
|
|
19
56
|
let datasources = await mapAsync(await resolveFiles(baseDir, [configPattern].flat().map((pattern) => "*/" + pattern)), async (path) => {
|
|
20
|
-
const config = await
|
|
57
|
+
const { config } = await loadConfig({ configFile: path });
|
|
21
58
|
const [_, dirName] = path.match(/(.+\/(.+))\/.+$/).slice(1, 3);
|
|
22
59
|
return await transformDrizzleConfig(config, {
|
|
23
60
|
cwd: this.#options.cwd,
|
|
@@ -28,7 +65,7 @@ var DefaultContext = class {
|
|
|
28
65
|
});
|
|
29
66
|
datasources = Object.entries(datasourceOptions).reduce((_datasources, [name, options]) => {
|
|
30
67
|
const datasource = datasources.find((d) => d.name == name && options.connector == (d.driver ? d.driver : d.dialect));
|
|
31
|
-
if (!datasource)
|
|
68
|
+
if (!datasource) return _datasources;
|
|
32
69
|
return [..._datasources, datasource];
|
|
33
70
|
}, []);
|
|
34
71
|
logger?.info("Found drizzle datasources:", datasources.toSorted((datasource) => {
|
|
@@ -51,27 +88,45 @@ var DefaultContext = class {
|
|
|
51
88
|
}
|
|
52
89
|
return this.#datasources;
|
|
53
90
|
}
|
|
54
|
-
async
|
|
55
|
-
|
|
91
|
+
async migrationAssets(datasources) {
|
|
92
|
+
const migrationOptions = this.#options.migrations;
|
|
93
|
+
if (!migrationOptions) return [];
|
|
94
|
+
return datasources.reduce((acc, { name, migrations }) => {
|
|
95
|
+
const dir = migrations.assets;
|
|
96
|
+
if (dir) acc.push({
|
|
97
|
+
baseName: `${migrationOptions.storageBase}:${name}`,
|
|
98
|
+
dir
|
|
99
|
+
});
|
|
100
|
+
return acc;
|
|
101
|
+
}, []);
|
|
56
102
|
}
|
|
57
|
-
async
|
|
58
|
-
return
|
|
103
|
+
async virtualTypeDeclarations(datasources) {
|
|
104
|
+
return { "#nitro-drizzle/*": { "nitro-drizzle/virtual.d.ts": [dialectDeclarations(datasources)].join("\n") } };
|
|
59
105
|
}
|
|
60
|
-
|
|
61
|
-
const
|
|
106
|
+
enabledPlugins() {
|
|
107
|
+
const plugins = [];
|
|
108
|
+
const migrationOptions = this.#options.migrations;
|
|
109
|
+
if (migrationOptions ? Array.isArray(migrationOptions) ? 0 < migrationOptions.length : true == migrationOptions.migrateOnInit : false) plugins.push("migrate");
|
|
110
|
+
plugins.push("init");
|
|
111
|
+
return plugins.map((pluginName) => `nitro-drizzle/plugins/${pluginName}`);
|
|
112
|
+
}
|
|
113
|
+
async moduleTypeDeclarations(datasources) {
|
|
114
|
+
return moduleTypeDeclarations(datasources);
|
|
115
|
+
}
|
|
116
|
+
async runtimeTypeDeclarations(datasources) {
|
|
62
117
|
return { "nitro-drizzle/runtime.d.ts": [
|
|
63
|
-
...[...(/* @__PURE__ */ new Set([{ types: "nitro-drizzle/runtime" }, ...this
|
|
118
|
+
...[...(/* @__PURE__ */ new Set([{ types: "nitro-drizzle/runtime" }, ...this.enabledPlugins().map((pluginId) => {
|
|
64
119
|
return { types: pluginId };
|
|
65
120
|
})])).values()].map((reference) => genReference(reference)),
|
|
66
121
|
runtimeDeclarations(datasources),
|
|
67
122
|
`export {};`
|
|
68
123
|
].join("\n") };
|
|
69
124
|
}
|
|
70
|
-
async virtualModules() {
|
|
71
|
-
const datasources = await this.datasources();
|
|
125
|
+
async virtualModules(datasources) {
|
|
72
126
|
return {
|
|
73
127
|
"#nitro-drizzle/runtime": runtimeVirtualModule(datasources),
|
|
74
|
-
...dialectVirtualModules(datasources)
|
|
128
|
+
...dialectVirtualModules(datasources),
|
|
129
|
+
...migrationsVirtualModule(datasources, this.#options.migrations)
|
|
75
130
|
};
|
|
76
131
|
}
|
|
77
132
|
reload() {
|
package/dist/context.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"context.mjs","names":["#options","#datasources"],"sources":["../src/context/index.ts"],"sourcesContent":["import type { ConsolaInstance } from \"consola\";\nimport { colorize, type ColorName } from \"consola/utils\";\nimport type { Config, Config as DrizzleConfig } from \"drizzle-kit\";\n\nimport { mapAsync } from \"./internal/async\";\nimport { accent } from \"./internal/logger\";\nimport { resolveFiles } from \"./internal/fs\";\nimport {\n dialectDeclarations,\n genReference,\n moduleTypeDeclarations,\n runtimeDeclarations,\n} from \"./internal/templates\";\nimport { transformDrizzleConfig } from \"./internal/config\";\nimport { dialectVirtualModules, runtimeVirtualModule } from \"./internal/virtual\";\n\nimport type { MaybePromise, VirtualModules } from \"nitro-drizzle/shared\";\n\n/**\n * Context interface for managing Drizzle datasource configurations.\n */\nexport interface Context {\n /**\n * Reloads the context, clearing any cached datasource information.\n */\n reload(): MaybePromise<void>;\n /**\n * Returns a list of all resolved datasource information.\n */\n datasources(): MaybePromise<DatasourceInfo[]>;\n /**\n * Returns virtual module code for runtime datasource access.\n */\n virtualModules(): MaybePromise<VirtualModules>;\n virtualTypeDeclarations(): MaybePromise<Record<string, VirtualModules>>;\n moduleTypeDeclarations(): MaybePromise<VirtualModules<`${string}.d.ts`>>;\n runtimeTypeDeclarations(\n // options?: RuntimeDeclarationOptions,\n ): MaybePromise<VirtualModules<`${string}.d.ts`>>;\n}\n\nclass DefaultContext implements Context {\n #datasources: DatasourceInfo[] | null = null;\n readonly #options: ContextOptions;\n\n constructor(options: ContextOptions) {\n this.#options = options;\n }\n\n async datasources() {\n const {\n logger,\n baseDir,\n configPattern,\n resolver,\n datasource: datasourceOptions,\n } = this.#options;\n\n if (!this.#datasources) {\n logger?.info(\"Searching drizzle datasources in\", colorize(\"blue\", baseDir));\n\n const drizzleConfigsResolvedPaths = await resolveFiles(\n baseDir,\n [configPattern].flat().map((pattern) => \"*/\" + pattern),\n );\n\n let datasources: DatasourceInfo[] = await mapAsync(\n drizzleConfigsResolvedPaths,\n async (path) => {\n const config = await this.#options.resolver.import<DrizzleConfig>(path, {\n default: true,\n });\n const [_, dirName] = path.match(/(.+\\/(.+))\\/.+$/)!.slice(1, 3) as [string, string];\n\n return await transformDrizzleConfig(config, {\n cwd: this.#options.cwd,\n path,\n dirName,\n resolver,\n });\n },\n );\n\n datasources = Object.entries(datasourceOptions).reduce((_datasources, [name, options]) => {\n const datasource = datasources.find(\n (d) => d.name == name && options.connector == (d.driver ? d.driver : d.dialect),\n );\n if (!datasource) {\n throw new Error(\"Unable to resolve datasource \" + name);\n }\n return [..._datasources, datasource];\n }, [] as DatasourceInfo[]);\n\n logger?.info(\n \"Found drizzle datasources:\",\n datasources\n .toSorted((datasource) => {\n return datasource.enabled ? -1 : 1;\n })\n .map((datasource) => {\n let msg = [datasource.name];\n let color: ColorName;\n if (datasource.enabled) {\n color = \"greenBright\";\n } else {\n color = \"gray\";\n msg.push(\"(disabled)\");\n }\n return colorize(color, msg.join(\" \"));\n })\n .join(\", \"),\n );\n\n const enabledDatasources = datasources.filter((d) => d.enabled);\n\n logger?.info(\n accent`Using ${enabledDatasources.length} of ${datasources.length} resolved datasources` +\n (enabledDatasources.length > 0 ? \":\" : \"\"),\n enabledDatasources\n .map((datasource) => {\n return [\n colorize(\"greenBright\", datasource.name),\n colorize(\"yellow\", \"(\" + (datasource.driver || datasource.dialect) + \")\"),\n ].join(\" \");\n })\n .join(\", \"),\n );\n\n this.#datasources = datasources;\n }\n\n return this.#datasources;\n }\n\n async virtualTypeDeclarations(): Promise<Record<string, VirtualModules<`${string}.d.ts`>>> {\n const datasources = [...(await this.datasources())].filter((d) => d.enabled);\n return {\n \"#nitro-drizzle/*\": {\n \"nitro-drizzle/virtual.d.ts\": [dialectDeclarations(datasources)].join(\"\\n\"),\n },\n };\n }\n\n async moduleTypeDeclarations(): Promise<VirtualModules> {\n return moduleTypeDeclarations(await this.datasources());\n }\n\n async runtimeTypeDeclarations(\n // options?: RuntimeDeclarationOptions,\n ): Promise<VirtualModules<`${string}.d.ts`>> {\n const datasources = await this.datasources();\n const references = new Set([\n { types: \"nitro-drizzle/runtime\" },\n ...this.#options.plugins.map((pluginId) => {\n return { types: pluginId };\n }),\n ]);\n const content = [\n ...[...references.values()].map((reference) => genReference(reference)),\n runtimeDeclarations(datasources),\n /* ts */ `export {};`,\n ].join(\"\\n\");\n return {\n \"nitro-drizzle/runtime.d.ts\": content,\n };\n }\n\n async virtualModules(): Promise<VirtualModules<`#nitro-drizzle/${string}`>> {\n const datasources = await this.datasources();\n return {\n \"#nitro-drizzle/runtime\": runtimeVirtualModule(datasources),\n ...dialectVirtualModules(datasources),\n };\n }\n\n reload() {\n this.#datasources = null;\n }\n}\n\n/**\n * Glob pattern or array of patterns to match Drizzle configuration files.\n */\nexport type ConfigPattern = string | readonly string[];\n\n/**\n * Resolver interface for importing modules and resolving paths.\n */\nexport interface Resolver {\n /**\n * Resolves a module ID to its full path.\n */\n resolve(id: string): string;\n /**\n * Attempts to resolve a module ID, returns undefined if not found.\n */\n tryResolve(id: string): string | undefined;\n /**\n * Imports a module dynamically.\n * @param id - Module identifier to import\n * @param options - Import options, set default: true to import default export\n */\n import<T>(id: string, options?: { default?: boolean }): Promise<T>;\n}\n\nexport interface ContextOptions {\n logger?: ConsolaInstance;\n /**\n * Current working directory\n */\n cwd: string;\n /**\n * Base project directory to search drizzle config files\n */\n baseDir: string;\n /**\n * Pattern for drizzle config files\n */\n configPattern: ConfigPattern;\n /**\n * Nuxt Kit resolver\n */\n resolver: Resolver;\n /**\n * Connector options\n */\n datasource: Record<string, { connector: string }>;\n\n plugins: readonly string[];\n}\n\n/**\n * Creates a Context instance for managing Drizzle datasource configurations.\n * @param options - Configuration options for the context\n * @returns A Context instance\n */\nexport function createContext(options: ContextOptions): Context {\n return new DefaultContext(options);\n}\n\n/**\n * Information about a resolved Drizzle datasource.\n */\nexport interface DatasourceInfo {\n /** Directory name of the datasource (derived from config file location). */\n dirName: string;\n /** Unique name identifier for the datasource. */\n name: string;\n /** Whether the datasource is enabled (filtered by connector configuration). */\n enabled: boolean;\n /** Database dialect (e.g., 'sqlite', 'postgresql', 'mysql'). */\n dialect: string;\n /** Driver type if specified in config, otherwise undefined. */\n driver: string | undefined;\n /** Import paths for schema, connector, and helpers. */\n imports: {\n config: string;\n schema: string[];\n connector: string;\n helpers: string;\n };\n /** Migration configuration for this datasource. */\n migrations: {\n assets?: string;\n config?: Config[\"migrations\"];\n };\n}\n"],"mappings":"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"}
|
|
1
|
+
{"version":3,"file":"context.mjs","names":["#options","#datasources"],"sources":["../src/context/index.ts"],"sourcesContent":["import type { ConsolaInstance } from \"consola\";\nimport { colorize, type ColorName } from \"consola/utils\";\nimport type { Config, Config as DrizzleConfig } from \"drizzle-kit\";\nimport { loadConfig } from \"c12\";\nimport { pkgDir, pkgName } from \"nitro-drizzle/meta\";\n\nimport { mapAsync } from \"./internal/async\";\nimport { accent } from \"./internal/logger\";\nimport { resolveFiles } from \"./internal/fs\";\nimport {\n dialectDeclarations,\n genReference,\n moduleTypeDeclarations,\n runtimeDeclarations,\n} from \"./internal/templates\";\nimport { transformDrizzleConfig } from \"./internal/config\";\nimport {\n dialectVirtualModules,\n migrationsVirtualModule,\n runtimeVirtualModule,\n} from \"./internal/virtual\";\n\nimport type { MaybePromise, VirtualModules } from \"nitro-drizzle/shared\";\nimport type { ServerAssetDir } from \"nitropack/types\";\nimport { join } from \"pathe\";\n\n/**\n * Context interface for managing Drizzle datasource configurations.\n */\nexport interface Context {\n init(): MaybePromise<void>;\n /**\n * Reloads the context, clearing any cached datasource information.\n */\n reload(): MaybePromise<void>;\n /**\n * Returns a list of all resolved datasource information.\n */\n datasources(): MaybePromise<DatasourceInfo[]>;\n}\n\nclass DefaultContext implements Context {\n #datasources: DatasourceInfo[] | null = null;\n readonly #options: ContextOptions;\n\n constructor(options: ContextOptions) {\n this.#options = options;\n }\n\n async init(): Promise<void> {\n const datasources = await this.datasources();\n\n await this.#options.plugins(this.enabledPlugins());\n\n const [virtualModules, virtualTypes, moduleTypes, runtimeTypes] = await Promise.all([\n this.virtualModules(datasources),\n this.virtualTypeDeclarations(datasources),\n this.moduleTypeDeclarations(datasources),\n this.runtimeTypeDeclarations(datasources),\n ]);\n\n await this.#options.virtualModules(virtualModules);\n\n await this.#options.declarations({\n virtual: virtualTypes,\n module: moduleTypes,\n runtime: runtimeTypes,\n });\n\n if (this.#options.migrations) {\n const assets = await this.migrationAssets(datasources);\n if (assets) {\n await this.#options.assets(assets);\n }\n\n await this.#options.tasks?.({\n \"drizzle:migrate\": {\n description: \"Run drizzle migrations for a datasource.\",\n handler: \"nitro-drizzle/migrations/task\",\n },\n });\n }\n\n if (this.#options.inlineExternals) {\n const inlineModuleIds = [\"runtime\", \"plugins\", \"migrations\"].flatMap((id) => {\n return [join(pkgName, id), join(pkgDir, \"dist\", id)];\n });\n\n await this.#options.inlineExternals(inlineModuleIds);\n }\n }\n\n async datasources() {\n const {\n logger,\n baseDir,\n configPattern,\n resolver,\n datasource: datasourceOptions,\n } = this.#options;\n\n if (!this.#datasources) {\n logger?.info(\"Searching drizzle datasources in\", colorize(\"blue\", baseDir));\n\n const drizzleConfigsResolvedPaths = await resolveFiles(\n baseDir,\n [configPattern].flat().map((pattern) => \"*/\" + pattern),\n );\n\n let datasources: DatasourceInfo[] = await mapAsync(\n drizzleConfigsResolvedPaths,\n async (path) => {\n const { config } = await loadConfig<DrizzleConfig>({\n configFile: path,\n });\n const [_, dirName] = path.match(/(.+\\/(.+))\\/.+$/)!.slice(1, 3) as [string, string];\n\n return await transformDrizzleConfig(config, {\n cwd: this.#options.cwd,\n path,\n dirName,\n resolver,\n });\n },\n );\n\n datasources = Object.entries(datasourceOptions).reduce((_datasources, [name, options]) => {\n const datasource = datasources.find(\n (d) => d.name == name && options.connector == (d.driver ? d.driver : d.dialect),\n );\n if (!datasource) {\n return _datasources;\n }\n return [..._datasources, datasource];\n }, [] as DatasourceInfo[]);\n\n logger?.info(\n \"Found drizzle datasources:\",\n datasources\n .toSorted((datasource) => {\n return datasource.enabled ? -1 : 1;\n })\n .map((datasource) => {\n let msg = [datasource.name];\n let color: ColorName;\n if (datasource.enabled) {\n color = \"greenBright\";\n } else {\n color = \"gray\";\n msg.push(\"(disabled)\");\n }\n return colorize(color, msg.join(\" \"));\n })\n .join(\", \"),\n );\n\n const enabledDatasources = datasources.filter((d) => d.enabled);\n\n logger?.info(\n accent`Using ${enabledDatasources.length} of ${datasources.length} resolved datasources` +\n (enabledDatasources.length > 0 ? \":\" : \"\"),\n enabledDatasources\n .map((datasource) => {\n return [\n colorize(\"greenBright\", datasource.name),\n colorize(\"yellow\", \"(\" + (datasource.driver || datasource.dialect) + \")\"),\n ].join(\" \");\n })\n .join(\", \"),\n );\n\n this.#datasources = datasources;\n }\n\n return this.#datasources;\n }\n\n private async migrationAssets(\n datasources: readonly DatasourceInfo[],\n ): Promise<readonly ServerAssetDir[]> {\n const migrationOptions = this.#options.migrations;\n\n if (!migrationOptions) {\n return [];\n }\n\n return datasources.reduce((acc, { name, migrations }) => {\n const dir = migrations.assets;\n if (dir) {\n acc.push({\n baseName: `${migrationOptions.storageBase}:${name}`,\n dir,\n /**\n * @todo Doesn't work in dev mode - 'fs' driver does not support 'pattern'\n * Disabled - include all files to use with meta/_journal.json\n */\n // pattern: '*.sql',\n });\n }\n return acc;\n }, [] as ServerAssetDir[]);\n }\n\n private async virtualTypeDeclarations(\n datasources: readonly DatasourceInfo[],\n ): Promise<Record<string, VirtualModules<`${string}.d.ts`>>> {\n return {\n \"#nitro-drizzle/*\": {\n \"nitro-drizzle/virtual.d.ts\": [dialectDeclarations(datasources)].join(\"\\n\"),\n },\n };\n }\n\n private enabledPlugins(): readonly string[] {\n const plugins: (\"init\" | \"migrate\")[] = [];\n\n const migrationOptions = this.#options.migrations;\n const enableMigrationPlugin = migrationOptions\n ? Array.isArray(migrationOptions)\n ? 0 < migrationOptions.length\n : true == migrationOptions.migrateOnInit\n : false;\n\n if (enableMigrationPlugin) {\n plugins.push(\"migrate\");\n }\n\n plugins.push(\"init\");\n\n const pluginIds = plugins.map((pluginName) => `nitro-drizzle/plugins/${pluginName}`);\n\n return pluginIds;\n }\n\n private async moduleTypeDeclarations(\n datasources: readonly DatasourceInfo[],\n ): Promise<VirtualModules> {\n return moduleTypeDeclarations(datasources);\n }\n\n private async runtimeTypeDeclarations(\n datasources: readonly DatasourceInfo[],\n ): Promise<VirtualModules<`${string}.d.ts`>> {\n const references = new Set([\n { types: \"nitro-drizzle/runtime\" },\n ...this.enabledPlugins().map((pluginId) => {\n return { types: pluginId };\n }),\n ]);\n const content = [\n ...[...references.values()].map((reference) => genReference(reference)),\n runtimeDeclarations(datasources),\n /* ts */ `export {};`,\n ].join(\"\\n\");\n return {\n \"nitro-drizzle/runtime.d.ts\": content,\n };\n }\n\n private async virtualModules(\n datasources: readonly DatasourceInfo[],\n ): Promise<VirtualModules<`#nitro-drizzle/${string}`>> {\n return {\n \"#nitro-drizzle/runtime\": runtimeVirtualModule(datasources),\n ...dialectVirtualModules(datasources),\n ...migrationsVirtualModule(datasources, this.#options.migrations),\n };\n }\n\n reload() {\n this.#datasources = null;\n }\n}\n\n/**\n * Glob pattern or array of patterns to match Drizzle configuration files.\n */\nexport type ConfigPattern = string | readonly string[];\n\n/**\n * Resolver interface for importing modules and resolving paths.\n */\nexport interface Resolver {\n /**\n * Resolves a module ID to its full path.\n */\n resolve(id: string): string;\n /**\n * Attempts to resolve a module ID, returns undefined if not found.\n */\n tryResolve(id: string): string | undefined;\n}\n\nexport type ContextHook<TArgs extends readonly any[] = []> = (\n this: void,\n ...args: TArgs\n) => MaybePromise<void>;\n\nexport interface MigrationOptions {\n /** Base storage key path for migrations. */\n storageBase: string;\n /** Whether and which datasources to migrate on initialization. */\n migrateOnInit: boolean | readonly string[];\n}\n\nexport interface ContextOptions {\n logger?: ConsolaInstance;\n /**\n * Current working directory\n */\n cwd: string;\n /**\n * Base project directory to search drizzle config files\n */\n baseDir: string;\n /**\n * Pattern for drizzle config files\n */\n configPattern: ConfigPattern;\n /**\n * Nuxt Kit resolver\n */\n resolver: Resolver;\n /**\n * Connector options\n */\n datasource: Record<string, { connector: string }>;\n\n migrations: MigrationOptions | undefined;\n\n tasks?: ContextHook<\n [\n tasks: Record<\n string,\n {\n handler: string;\n description: string;\n }\n >,\n ]\n >;\n\n plugins: ContextHook<[plugins: readonly string[]]>;\n\n declarations: ContextHook<\n [\n declarations: {\n module: VirtualModules<`${string}.d.ts`>;\n runtime: VirtualModules<`${string}.d.ts`>;\n virtual: Record<string, VirtualModules<`${string}.d.ts`>>;\n },\n ]\n >;\n\n virtualModules: ContextHook<[modules: VirtualModules]>;\n\n assets: ContextHook<[assets: readonly ServerAssetDir[]]>;\n\n inlineExternals?: ContextHook<[modules: readonly string[]]>;\n}\n\n/**\n * Creates a Context instance for managing Drizzle datasource configurations.\n * @param options - Configuration options for the context\n * @returns A Context instance\n */\nexport function createContext(options: ContextOptions): Context {\n return new DefaultContext(options);\n}\n\n/**\n * Information about a resolved Drizzle datasource.\n */\nexport interface DatasourceInfo {\n /** Directory name of the datasource (derived from config file location). */\n dirName: string;\n /** Unique name identifier for the datasource. */\n name: string;\n /** Whether the datasource is enabled (filtered by connector configuration). */\n enabled: boolean;\n /** Database dialect (e.g., 'sqlite', 'postgresql', 'mysql'). */\n dialect: string;\n /** Driver type if specified in config, otherwise undefined. */\n driver: string | undefined;\n /** Import paths for schema, connector, and helpers. */\n imports: {\n config: string;\n schema: string[];\n connector: string;\n helpers: string;\n };\n /** Migration configuration for this datasource. */\n migrations: {\n assets?: string;\n config?: Config[\"migrations\"];\n };\n}\n"],"mappings":"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"}
|
|
@@ -1,21 +1,13 @@
|
|
|
1
1
|
//#region src/module/internal/assets.ts
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
if (dir) return {
|
|
10
|
-
baseName: `${migrationOptions.storageBase}:${name}`,
|
|
11
|
-
dir
|
|
12
|
-
};
|
|
13
|
-
}).filter((value) => !!value);
|
|
14
|
-
config.serverAssets = [config.serverAssets ?? []].flat().filter((serverAsset) => {
|
|
15
|
-
return serverAsset?.baseName?.startsWith(migrationOptions.storageBase);
|
|
16
|
-
}).concat(migrationAssets);
|
|
2
|
+
function updateServerAssets(config, assets) {
|
|
3
|
+
config.serverAssets ||= [];
|
|
4
|
+
config.serverAssets = config.serverAssets.filter((_assets) => {
|
|
5
|
+
const baseName = _assets?.baseName;
|
|
6
|
+
if (!baseName) return true;
|
|
7
|
+
return assets.some((assets) => baseName == assets.baseName);
|
|
8
|
+
}).concat(assets);
|
|
17
9
|
}
|
|
18
10
|
//#endregion
|
|
19
|
-
export {
|
|
11
|
+
export { updateServerAssets };
|
|
20
12
|
|
|
21
13
|
//# sourceMappingURL=assets.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"assets.mjs","names":[],"sources":["../../../src/module/internal/assets.ts"],"sourcesContent":["import type {
|
|
1
|
+
{"version":3,"file":"assets.mjs","names":[],"sources":["../../../src/module/internal/assets.ts"],"sourcesContent":["import type { NitroConfig, ServerAssetDir } from \"nitropack/types\";\n\nexport function updateServerAssets(config: NitroConfig, assets: readonly ServerAssetDir[]) {\n config.serverAssets ||= [];\n config.serverAssets = config.serverAssets\n .filter((_assets) => {\n const baseName = _assets?.baseName;\n if (!baseName) {\n return true;\n }\n return assets.some((assets) => baseName == assets.baseName);\n })\n .concat(assets);\n}\n"],"mappings":";AAEA,SAAgB,mBAAmB,QAAqB,QAAmC;CACzF,OAAO,iBAAiB,CAAC;CACzB,OAAO,eAAe,OAAO,aAC1B,QAAQ,YAAY;EACnB,MAAM,WAAW,SAAS;EAC1B,IAAI,CAAC,UACH,OAAO;EAET,OAAO,OAAO,MAAM,WAAW,YAAY,OAAO,QAAQ;CAC5D,CAAC,CAAC,CACD,OAAO,MAAM;AAClB"}
|
|
@@ -1,17 +1,8 @@
|
|
|
1
|
-
import { pkgDir, pkgName } from "nitro-drizzle/meta";
|
|
2
|
-
import { join } from "node:path";
|
|
3
1
|
//#region src/module/internal/externals.ts
|
|
4
|
-
|
|
5
|
-
"runtime",
|
|
6
|
-
"plugins",
|
|
7
|
-
"migrations"
|
|
8
|
-
].flatMap((id) => {
|
|
9
|
-
return [join(pkgName, id), join(pkgDir, "dist", id)];
|
|
10
|
-
});
|
|
11
|
-
function addInlineExternals(nitroOptions) {
|
|
2
|
+
function addInlineExternals(nitroOptions, moduleIds) {
|
|
12
3
|
nitroOptions.externals ||= {};
|
|
13
4
|
nitroOptions.externals.inline ||= [];
|
|
14
|
-
nitroOptions.externals.inline.push(...
|
|
5
|
+
nitroOptions.externals.inline.push(...moduleIds);
|
|
15
6
|
}
|
|
16
7
|
//#endregion
|
|
17
8
|
export { addInlineExternals };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"externals.mjs","names":[],"sources":["../../../src/module/internal/externals.ts"],"sourcesContent":["import type { NitroOptions } from \"nitropack/types\";\
|
|
1
|
+
{"version":3,"file":"externals.mjs","names":[],"sources":["../../../src/module/internal/externals.ts"],"sourcesContent":["import type { NitroOptions } from \"nitropack/types\";\n\nexport function addInlineExternals(nitroOptions: NitroOptions, moduleIds: readonly string[]) {\n // @ts-expect-error\n nitroOptions.externals ||= {};\n nitroOptions.externals.inline ||= [];\n nitroOptions.externals.inline.push(...moduleIds);\n}\n"],"mappings":";AAEA,SAAgB,mBAAmB,cAA4B,WAA8B;CAE3F,aAAa,cAAc,CAAC;CAC5B,aAAa,UAAU,WAAW,CAAC;CACnC,aAAa,UAAU,OAAO,KAAK,GAAG,SAAS;AACjD"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"resolver.mjs","names":["#jiti"],"sources":["../../../src/module/internal/resolver.ts"],"sourcesContent":["import { createJiti, type Jiti, type JitiOptions } from \"jiti\";\nimport type { Resolver } from \"nitro-drizzle/context\";\nimport { fileURLToPath } from \"url\";\n\nexport function createResolver(id: string, options?: { alias?: Record<string, string> }): Resolver {\n return new JitiResolver(id, {\n alias: options?.alias,\n });\n}\n\nclass JitiResolver implements Resolver {\n readonly #jiti: Jiti;\n\n constructor(id: string, options?: JitiOptions) {\n this.#jiti = createJiti(id, options);\n }\n\n resolve(id: string): string {\n return fileURLToPath(this.#jiti.esmResolve(id));\n }\n\n tryResolve(id: string): string | undefined {\n try {\n return this.resolve(id);\n } catch {}\n }\n
|
|
1
|
+
{"version":3,"file":"resolver.mjs","names":["#jiti"],"sources":["../../../src/module/internal/resolver.ts"],"sourcesContent":["import { createJiti, type Jiti, type JitiOptions } from \"jiti\";\nimport type { Resolver } from \"nitro-drizzle/context\";\nimport { fileURLToPath } from \"url\";\n\nexport function createResolver(id: string, options?: { alias?: Record<string, string> }): Resolver {\n return new JitiResolver(id, {\n alias: options?.alias,\n });\n}\n\nclass JitiResolver implements Resolver {\n readonly #jiti: Jiti;\n\n constructor(id: string, options?: JitiOptions) {\n this.#jiti = createJiti(id, options);\n }\n\n resolve(id: string): string {\n return fileURLToPath(this.#jiti.esmResolve(id));\n }\n\n tryResolve(id: string): string | undefined {\n try {\n return this.resolve(id);\n } catch {}\n }\n}\n"],"mappings":";;;AAIA,SAAgB,eAAe,IAAY,SAAwD;CACjG,OAAO,IAAI,aAAa,IAAI,EAC1B,OAAO,SAAS,MAClB,CAAC;AACH;AAEA,IAAM,eAAN,MAAuC;CACrC;CAEA,YAAY,IAAY,SAAuB;EAC7C,KAAKA,QAAQ,WAAW,IAAI,OAAO;CACrC;CAEA,QAAQ,IAAoB;EAC1B,OAAO,cAAc,KAAKA,MAAM,WAAW,EAAE,CAAC;CAChD;CAEA,WAAW,IAAgC;EACzC,IAAI;GACF,OAAO,KAAK,QAAQ,EAAE;EACxB,QAAQ,CAAC;CACX;AACF"}
|
package/dist/module.d.mts
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
|
-
import { MigrationOptions } from "
|
|
2
|
-
import { ConfigPattern } from "nitro-drizzle/context";
|
|
1
|
+
import { ConfigPattern, MigrationOptions } from "nitro-drizzle/context";
|
|
3
2
|
import { NitroModule } from "nitropack/types";
|
|
4
3
|
|
|
5
4
|
//#region src/module/index.d.ts
|
|
@@ -28,7 +27,8 @@ interface ModuleOptions {
|
|
|
28
27
|
*/
|
|
29
28
|
migrations: false | MigrationOptions;
|
|
30
29
|
}
|
|
30
|
+
declare function createDefaultOptions(): ModuleOptions;
|
|
31
31
|
declare const module: NitroModule;
|
|
32
32
|
//#endregion
|
|
33
|
-
export { DatasourceOptions, ModuleOptions, module as default };
|
|
33
|
+
export { DatasourceOptions, ModuleOptions, createDefaultOptions, module as default };
|
|
34
34
|
//# sourceMappingURL=module.d.mts.map
|
package/dist/module.mjs
CHANGED
|
@@ -1,71 +1,73 @@
|
|
|
1
1
|
import { addAugmentations, addDeclarations } from "./module/internal/types.mjs";
|
|
2
2
|
import { createResolver } from "./module/internal/resolver.mjs";
|
|
3
|
-
import {
|
|
3
|
+
import { updateServerAssets } from "./module/internal/assets.mjs";
|
|
4
4
|
import { addInlineExternals } from "./module/internal/externals.mjs";
|
|
5
5
|
import { reloadPlugin } from "./module/internal/reload.mjs";
|
|
6
6
|
import { addPlugin } from "./module/internal/rollup.mjs";
|
|
7
|
-
import { migrationsVirtualModule } from "./module/internal/virtual.mjs";
|
|
8
|
-
import { enablePlugins } from "./module/internal/plugins.mjs";
|
|
9
7
|
import { defu } from "defu";
|
|
10
8
|
import { resolve } from "pathe";
|
|
11
9
|
import { resolveAlias } from "pathe/utils";
|
|
12
10
|
import { createContext } from "nitro-drizzle/context";
|
|
13
11
|
import { pkgName } from "nitro-drizzle/meta";
|
|
14
12
|
//#region src/module/index.ts
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
}
|
|
13
|
+
function createDefaultOptions() {
|
|
14
|
+
return {
|
|
15
|
+
baseDir: "~/drizzle",
|
|
16
|
+
configPattern: ["drizzle.config.{js,ts}", "drizzle-*.config.{js,ts}"],
|
|
17
|
+
migrations: {
|
|
18
|
+
storageBase: "drizzle:migrations",
|
|
19
|
+
migrateOnInit: false
|
|
20
|
+
}
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
23
|
const module = {
|
|
24
24
|
name: pkgName,
|
|
25
25
|
async setup(nitro) {
|
|
26
|
-
const moduleOptions = defu(nitro.options.drizzle,
|
|
27
|
-
const plugins = enablePlugins(nitro.options, moduleOptions);
|
|
26
|
+
const moduleOptions = defu(nitro.options.drizzle, createDefaultOptions());
|
|
28
27
|
const resolver = createResolver(nitro.options.rootDir, { alias: nitro.options.alias });
|
|
29
|
-
const
|
|
30
|
-
const
|
|
28
|
+
const baseDir = resolve(nitro.options.srcDir, resolveAlias(moduleOptions.baseDir, nitro.options.alias));
|
|
29
|
+
const context = createContext({
|
|
31
30
|
cwd: process.cwd(),
|
|
32
31
|
resolver,
|
|
33
|
-
baseDir
|
|
32
|
+
baseDir,
|
|
34
33
|
logger: nitro.logger,
|
|
35
34
|
configPattern: moduleOptions.configPattern,
|
|
36
35
|
datasource: { ...moduleOptions.datasources },
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
const context = createContext(contextOptions);
|
|
40
|
-
addInlineExternals(nitro.options);
|
|
41
|
-
Object.assign(nitro.options.virtual, await context.virtualModules(), migrationsVirtualModule(await context.datasources(), moduleOptions.migrations));
|
|
42
|
-
if (nitro.options.imports) nitro.options.imports.imports ||= [];
|
|
43
|
-
if (moduleOptions.migrations) {
|
|
44
|
-
await updateMigrationAssets(context, nitro.options, moduleOptions.migrations);
|
|
45
|
-
if (nitro.options.experimental.tasks) {
|
|
36
|
+
migrations: moduleOptions.migrations || void 0,
|
|
37
|
+
tasks: nitro.options.experimental.tasks ? (tasks) => {
|
|
46
38
|
nitro.options.tasks ||= {};
|
|
47
|
-
nitro.options.tasks
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
39
|
+
Object.assign(nitro.options.tasks, tasks);
|
|
40
|
+
} : void 0,
|
|
41
|
+
plugins(plugins) {
|
|
42
|
+
nitro.options.plugins.push(...plugins);
|
|
43
|
+
},
|
|
44
|
+
virtualModules(modules) {
|
|
45
|
+
Object.assign(nitro.options.virtual, modules);
|
|
46
|
+
},
|
|
47
|
+
declarations(declarations) {
|
|
48
|
+
nitro.hooks.hook("types:extend", async (types) => {
|
|
49
|
+
await addAugmentations(nitro.options, types, {
|
|
50
|
+
...declarations.runtime,
|
|
51
|
+
...declarations.module
|
|
52
|
+
});
|
|
53
|
+
await addDeclarations(nitro.options, types, declarations.virtual);
|
|
54
|
+
});
|
|
55
|
+
},
|
|
56
|
+
assets(assets) {
|
|
57
|
+
updateServerAssets(nitro.options, assets);
|
|
58
|
+
},
|
|
59
|
+
inlineExternals(modules) {
|
|
60
|
+
addInlineExternals(nitro.options, modules);
|
|
51
61
|
}
|
|
52
|
-
}
|
|
53
|
-
nitro.hooks.hook("rollup:before", async (nitro, config) => {
|
|
54
|
-
await addPlugin(config, reloadPlugin(nitro, contextOptions));
|
|
55
62
|
});
|
|
56
|
-
nitro.
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
await addAugmentations(nitro.options, types, {
|
|
60
|
-
...runtimeTypeDeclarations,
|
|
61
|
-
...moduleTypeDeclarations
|
|
62
|
-
});
|
|
63
|
-
const virtualTypeDeclarations = await context.virtualTypeDeclarations();
|
|
64
|
-
await addDeclarations(nitro.options, types, virtualTypeDeclarations);
|
|
63
|
+
if (nitro.options.imports) nitro.options.imports.imports ||= [];
|
|
64
|
+
nitro.hooks.hook("rollup:before", async (nitro, config) => {
|
|
65
|
+
await addPlugin(config, reloadPlugin(nitro, { baseDir }));
|
|
65
66
|
});
|
|
67
|
+
await context.init();
|
|
66
68
|
}
|
|
67
69
|
};
|
|
68
70
|
//#endregion
|
|
69
|
-
export { module as default };
|
|
71
|
+
export { createDefaultOptions, module as default };
|
|
70
72
|
|
|
71
73
|
//# sourceMappingURL=module.mjs.map
|
package/dist/module.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"module.mjs","names":[],"sources":["../src/module/index.ts"],"sourcesContent":["import type { NitroModule } from \"nitropack/types\";\nimport { defu } from \"defu\";\nimport { resolve } from \"pathe\";\nimport { resolveAlias } from \"pathe/utils\";\n\nimport {
|
|
1
|
+
{"version":3,"file":"module.mjs","names":[],"sources":["../src/module/index.ts"],"sourcesContent":["import type { NitroModule } from \"nitropack/types\";\nimport { defu } from \"defu\";\nimport { resolve } from \"pathe\";\nimport { resolveAlias } from \"pathe/utils\";\n\nimport {\n createContext,\n type ConfigPattern,\n type ContextOptions,\n type MigrationOptions,\n} from \"nitro-drizzle/context\";\nimport type { VirtualModules, MaybePromise } from \"nitro-drizzle/shared\";\nimport { pkgName } from \"nitro-drizzle/meta\";\n\nimport { addAugmentations, addDeclarations } from \"./internal/types\";\nimport { createResolver } from \"./internal/resolver\";\nimport { updateServerAssets } from \"./internal/assets\";\nimport { addInlineExternals } from \"./internal/externals\";\nimport { reloadPlugin } from \"./internal/reload\";\nimport { addPlugin } from \"./internal/rollup\";\n\n/**\n * Datasource-specific configuration options.\n * This interface is augmented by the module with connector-specific options.\n */\nexport interface DatasourceOptions {\n // augmented by module\n}\n\ndeclare module \"nitropack/types\" {\n interface NitroOptions {\n drizzle: ModuleOptions;\n }\n}\n\nexport interface ModuleOptions {\n /**\n * Directory to search datasources\n */\n baseDir: string;\n /**\n * Patterns to search Drizzle configs\n */\n configPattern: ConfigPattern;\n\n datasources?: DatasourceOptions;\n\n /**\n * Enable migrations storage\n */\n migrations: false | MigrationOptions;\n}\n\nexport function createDefaultOptions(): ModuleOptions {\n return {\n baseDir: \"~/drizzle\",\n configPattern: [\"drizzle.config.{js,ts}\", \"drizzle-*.config.{js,ts}\"],\n migrations: {\n storageBase: \"drizzle:migrations\",\n migrateOnInit: false,\n },\n };\n}\n\nconst module: NitroModule = {\n name: pkgName,\n async setup(nitro) {\n const moduleOptions = defu(nitro.options.drizzle, createDefaultOptions());\n\n const resolver = createResolver(nitro.options.rootDir, {\n alias: nitro.options.alias,\n });\n\n const baseDir = resolve(\n nitro.options.srcDir,\n resolveAlias(moduleOptions.baseDir, nitro.options.alias),\n );\n\n const contextOptions: ContextOptions = {\n cwd: process.cwd(),\n resolver: resolver,\n baseDir,\n logger: nitro.logger,\n configPattern: moduleOptions.configPattern,\n datasource: { ...moduleOptions.datasources },\n migrations: moduleOptions.migrations || void 0,\n\n tasks: nitro.options.experimental.tasks\n ? (tasks) => {\n nitro.options.tasks ||= {};\n Object.assign(nitro.options.tasks, tasks);\n }\n : void 0,\n\n plugins(plugins) {\n nitro.options.plugins.push(...plugins);\n },\n\n virtualModules(modules: VirtualModules): MaybePromise<void> {\n Object.assign(nitro.options.virtual, modules);\n },\n\n declarations(declarations): MaybePromise<void> {\n nitro.hooks.hook(\"types:extend\", async (types) => {\n await addAugmentations(nitro.options, types, {\n ...declarations.runtime,\n ...declarations.module,\n });\n\n await addDeclarations(nitro.options, types, declarations.virtual);\n });\n },\n\n assets(assets) {\n updateServerAssets(nitro.options, assets);\n },\n\n inlineExternals(modules: readonly string[]) {\n addInlineExternals(nitro.options, modules);\n },\n };\n\n const context = createContext(contextOptions);\n\n // auto-imports\n if (nitro.options.imports) {\n nitro.options.imports.imports ||= [];\n\n // TODO\n // nitro.options.imports.imports.push({\n // name: 'useMigrations',\n // as: 'useDrizzleMigrations',\n // from: 'nitro-drizzle/runtime',\n // })\n }\n\n nitro.hooks.hook(\"rollup:before\", async (nitro, config) => {\n await addPlugin(config, reloadPlugin(nitro, { baseDir }));\n });\n\n await context.init();\n },\n};\n\nexport default module;\n"],"mappings":";;;;;;;;;;;;AAqDA,SAAgB,uBAAsC;CACpD,OAAO;EACL,SAAS;EACT,eAAe,CAAC,0BAA0B,0BAA0B;EACpE,YAAY;GACV,aAAa;GACb,eAAe;EACjB;CACF;AACF;AAEA,MAAM,SAAsB;CAC1B,MAAM;CACN,MAAM,MAAM,OAAO;EACjB,MAAM,gBAAgB,KAAK,MAAM,QAAQ,SAAS,qBAAqB,CAAC;EAExE,MAAM,WAAW,eAAe,MAAM,QAAQ,SAAS,EACrD,OAAO,MAAM,QAAQ,MACvB,CAAC;EAED,MAAM,UAAU,QACd,MAAM,QAAQ,QACd,aAAa,cAAc,SAAS,MAAM,QAAQ,KAAK,CACzD;EA8CA,MAAM,UAAU,cAAc;GA3C5B,KAAK,QAAQ,IAAI;GACP;GACV;GACA,QAAQ,MAAM;GACd,eAAe,cAAc;GAC7B,YAAY,EAAE,GAAG,cAAc,YAAY;GAC3C,YAAY,cAAc,cAAc,KAAK;GAE7C,OAAO,MAAM,QAAQ,aAAa,SAC7B,UAAU;IACT,MAAM,QAAQ,UAAU,CAAC;IACzB,OAAO,OAAO,MAAM,QAAQ,OAAO,KAAK;GAC1C,IACA,KAAK;GAET,QAAQ,SAAS;IACf,MAAM,QAAQ,QAAQ,KAAK,GAAG,OAAO;GACvC;GAEA,eAAe,SAA6C;IAC1D,OAAO,OAAO,MAAM,QAAQ,SAAS,OAAO;GAC9C;GAEA,aAAa,cAAkC;IAC7C,MAAM,MAAM,KAAK,gBAAgB,OAAO,UAAU;KAChD,MAAM,iBAAiB,MAAM,SAAS,OAAO;MAC3C,GAAG,aAAa;MAChB,GAAG,aAAa;KAClB,CAAC;KAED,MAAM,gBAAgB,MAAM,SAAS,OAAO,aAAa,OAAO;IAClE,CAAC;GACH;GAEA,OAAO,QAAQ;IACb,mBAAmB,MAAM,SAAS,MAAM;GAC1C;GAEA,gBAAgB,SAA4B;IAC1C,mBAAmB,MAAM,SAAS,OAAO;GAC3C;EAGyC,CAAC;EAG5C,IAAI,MAAM,QAAQ,SAChB,MAAM,QAAQ,QAAQ,YAAY,CAAC;EAUrC,MAAM,MAAM,KAAK,iBAAiB,OAAO,OAAO,WAAW;GACzD,MAAM,UAAU,QAAQ,aAAa,OAAO,EAAE,QAAQ,CAAC,CAAC;EAC1D,CAAC;EAED,MAAM,QAAQ,KAAK;CACrB;AACF"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "nitro-drizzle",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.9",
|
|
4
4
|
"description": "Nitro module to integrate Drizzle ORM with ease.",
|
|
5
5
|
"homepage": "https://github.com/Myshkouski/nitro-drizzle#readme",
|
|
6
6
|
"bugs": {
|
|
@@ -36,41 +36,49 @@
|
|
|
36
36
|
"dependencies": {
|
|
37
37
|
"@types/better-sqlite3": "^7.6.13",
|
|
38
38
|
"@typescript/native-preview": "7.0.0-dev.20260606.1",
|
|
39
|
+
"c12": "^3.3.4",
|
|
39
40
|
"consola": "^3.4.2",
|
|
40
41
|
"db0": "^0.3.4",
|
|
41
42
|
"defu": "^6.1.7",
|
|
42
43
|
"drizzle-kit": "^0.31.10",
|
|
43
|
-
"exsolve": "^1.0.8",
|
|
44
|
-
"h3": "^1.15.11",
|
|
45
44
|
"jiti": "^2.7.0",
|
|
46
45
|
"knitwork": "^1.3.0",
|
|
47
|
-
"nitropack": "^2
|
|
46
|
+
"nitropack": "^2",
|
|
48
47
|
"ohash": "^2.0.11",
|
|
49
48
|
"pathe": "^2.0.3",
|
|
50
|
-
"rollup": "^4.62.
|
|
49
|
+
"rollup": "^4.62.2",
|
|
51
50
|
"strip-indent": "^4.1.1",
|
|
52
51
|
"tinyglobby": "^0.2.17",
|
|
53
52
|
"unstorage": "^1.17.5"
|
|
54
53
|
},
|
|
55
54
|
"devDependencies": {
|
|
56
|
-
"@
|
|
57
|
-
"@types
|
|
58
|
-
"
|
|
55
|
+
"@arethetypeswrong/core": "^0.18.4",
|
|
56
|
+
"@cloudflare/workers-types": "^4.20260702.1",
|
|
57
|
+
"@testcontainers/mysql": "^12.0.4",
|
|
58
|
+
"@testcontainers/postgresql": "^12.0.4",
|
|
59
|
+
"@types/node": "^25.9.4",
|
|
60
|
+
"@vitest/coverage-v8": "^4.1.10",
|
|
61
|
+
"@vitest/ui": "^4.1.10",
|
|
62
|
+
"changelogen": "^0.6.2",
|
|
63
|
+
"lefthook": "^2.1.9",
|
|
59
64
|
"listhen": "^1.10.0",
|
|
60
65
|
"oxfmt": "^0.57.0",
|
|
61
|
-
"oxlint": "^1.
|
|
62
|
-
"oxlint-tsgolint": "^0.
|
|
63
|
-
"
|
|
66
|
+
"oxlint": "^1.72.0",
|
|
67
|
+
"oxlint-tsgolint": "^0.24.0",
|
|
68
|
+
"publint": "^0.3.21",
|
|
69
|
+
"testcontainers": "^12.0.4",
|
|
70
|
+
"tsdown": "^0.22.3",
|
|
64
71
|
"typescript": "^6.0.3",
|
|
65
|
-
"
|
|
72
|
+
"unplugin-unused": "^0.5.7",
|
|
73
|
+
"vitest": "^4.1.10"
|
|
66
74
|
},
|
|
67
75
|
"peerDependencies": {
|
|
68
76
|
"@cloudflare/workers-types": "^4.20260624.1",
|
|
69
|
-
"@electric-sql/pglite": "^0.5.
|
|
70
|
-
"better-sqlite3": "^12.
|
|
77
|
+
"@electric-sql/pglite": "^0.5.4",
|
|
78
|
+
"better-sqlite3": "^12.11.1",
|
|
71
79
|
"drizzle-orm": "^0.45.2",
|
|
72
|
-
"h3": "^1
|
|
73
|
-
"mysql2": "^3.22.
|
|
80
|
+
"h3": "^1",
|
|
81
|
+
"mysql2": "^3.22.5",
|
|
74
82
|
"postgres": "^3.4.9"
|
|
75
83
|
},
|
|
76
84
|
"peerDependenciesMeta": {
|
|
@@ -98,7 +106,9 @@
|
|
|
98
106
|
"lint": "oxlint",
|
|
99
107
|
"playground": "nitro dev playground",
|
|
100
108
|
"test": "vitest run",
|
|
109
|
+
"test:coverage": "vitest run --coverage",
|
|
101
110
|
"typecheck": "tsc --noEmit",
|
|
111
|
+
"typecheck:fixtures": "nitro prepare fixtures/blog-api && tsc --noEmit -p fixtures/blog-api/tsconfig.json",
|
|
102
112
|
"release": "changelogen --release"
|
|
103
113
|
}
|
|
104
114
|
}
|
|
@@ -1,12 +0,0 @@
|
|
|
1
|
-
import { DatasourceOptions } from "../../module.mjs";
|
|
2
|
-
//#region src/module/internal/assets.d.ts
|
|
3
|
-
/** Options for configuring migration storage. */
|
|
4
|
-
interface MigrationOptions {
|
|
5
|
-
/** Base storage key path for migrations. */
|
|
6
|
-
storageBase: string;
|
|
7
|
-
/** Whether and which datasources to migrate on initialization. */
|
|
8
|
-
migrateOnInit: boolean | readonly (keyof DatasourceOptions extends never ? string : keyof DatasourceOptions)[];
|
|
9
|
-
}
|
|
10
|
-
//#endregion
|
|
11
|
-
export { MigrationOptions };
|
|
12
|
-
//# sourceMappingURL=assets.d.mts.map
|
|
@@ -1,13 +0,0 @@
|
|
|
1
|
-
//#region src/module/internal/plugins.ts
|
|
2
|
-
function enablePlugins(nitroOptions, moduleOptions) {
|
|
3
|
-
const plugins = [];
|
|
4
|
-
if (moduleOptions.migrations && moduleOptions.migrations.migrateOnInit) plugins.push("migrate");
|
|
5
|
-
plugins.push("init");
|
|
6
|
-
const pluginIds = plugins.map((pluginName) => `nitro-drizzle/plugins/${pluginName}`);
|
|
7
|
-
nitroOptions.plugins.push(...pluginIds);
|
|
8
|
-
return pluginIds;
|
|
9
|
-
}
|
|
10
|
-
//#endregion
|
|
11
|
-
export { enablePlugins };
|
|
12
|
-
|
|
13
|
-
//# sourceMappingURL=plugins.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"plugins.mjs","names":[],"sources":["../../../src/module/internal/plugins.ts"],"sourcesContent":["import type { NitroOptions } from \"nitropack\";\nimport type { ModuleOptions } from \"..\";\n\nexport function enablePlugins(\n nitroOptions: NitroOptions,\n moduleOptions: ModuleOptions,\n): readonly string[] {\n const plugins: (\"init\" | \"migrate\")[] = [];\n\n if (moduleOptions.migrations && moduleOptions.migrations.migrateOnInit) {\n plugins.push(\"migrate\");\n }\n\n plugins.push(\"init\");\n\n const pluginIds = plugins.map((pluginName) => `nitro-drizzle/plugins/${pluginName}`);\n\n nitroOptions.plugins.push(...pluginIds);\n\n return pluginIds;\n}\n"],"mappings":";AAGA,SAAgB,cACd,cACA,eACmB;CACnB,MAAM,UAAkC,CAAC;CAEzC,IAAI,cAAc,cAAc,cAAc,WAAW,eACvD,QAAQ,KAAK,SAAS;CAGxB,QAAQ,KAAK,MAAM;CAEnB,MAAM,YAAY,QAAQ,KAAK,eAAe,yBAAyB,YAAY;CAEnF,aAAa,QAAQ,KAAK,GAAG,SAAS;CAEtC,OAAO;AACT"}
|
|
@@ -1,23 +0,0 @@
|
|
|
1
|
-
import { genArrayFromRaw, genObjectFromRawEntries, genString } from "knitwork";
|
|
2
|
-
//#region src/module/internal/virtual.ts
|
|
3
|
-
function migrationsVirtualModule(datasources, options) {
|
|
4
|
-
if (!options) return {};
|
|
5
|
-
const parts = [];
|
|
6
|
-
const enabledDatasources = datasources.filter((d) => d.enabled);
|
|
7
|
-
parts.push(`
|
|
8
|
-
export const migrationConfig = ${genObjectFromRawEntries(enabledDatasources.map(({ name, migrations }) => {
|
|
9
|
-
return [name, JSON.stringify(migrations.config)];
|
|
10
|
-
}))};
|
|
11
|
-
`);
|
|
12
|
-
let migrateOnInit = enabledDatasources.map((d) => d.name);
|
|
13
|
-
if (options && Array.isArray(options.migrateOnInit)) migrateOnInit = migrateOnInit.filter((name) => options.migrateOnInit.includes(name));
|
|
14
|
-
parts.push(`
|
|
15
|
-
export const MIGRATIONS_STORAGE_BASE = ${genString(options.storageBase)};
|
|
16
|
-
export const MIGRATE_ON_INIT = ${genArrayFromRaw(migrateOnInit.map((name) => genString(name)))};
|
|
17
|
-
`);
|
|
18
|
-
return { "#nitro-drizzle/migrations": parts.join("\n") };
|
|
19
|
-
}
|
|
20
|
-
//#endregion
|
|
21
|
-
export { migrationsVirtualModule };
|
|
22
|
-
|
|
23
|
-
//# sourceMappingURL=virtual.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"virtual.mjs","names":[],"sources":["../../../src/module/internal/virtual.ts"],"sourcesContent":["import { genString, genArrayFromRaw, genObjectFromRawEntries } from \"knitwork\";\nimport type { VirtualModules } from \"nitro-drizzle/shared\";\nimport type { MigrationOptions } from \"./assets\";\nimport type { DatasourceInfo } from \"nitro-drizzle/context\";\n\nexport function migrationsVirtualModule(\n datasources: DatasourceInfo[],\n options: false | MigrationOptions,\n): VirtualModules {\n if (!options) {\n return {};\n }\n\n const parts: string[] = [];\n\n const enabledDatasources = datasources.filter((d) => d.enabled);\n\n parts.push(/*js*/ `\n export const migrationConfig = ${genObjectFromRawEntries(\n enabledDatasources.map(({ name, migrations }) => {\n return [name, JSON.stringify(migrations.config)];\n }),\n )};\n `);\n\n let migrateOnInit = enabledDatasources.map((d) => d.name);\n if (options && Array.isArray(options.migrateOnInit)) {\n migrateOnInit = migrateOnInit.filter((name) =>\n (options.migrateOnInit as readonly string[]).includes(name),\n );\n }\n\n parts.push(/*js*/ `\n export const MIGRATIONS_STORAGE_BASE = ${genString(options.storageBase)};\n export const MIGRATE_ON_INIT = ${genArrayFromRaw(migrateOnInit.map((name) => genString(name)))};\n `);\n\n return {\n \"#nitro-drizzle/migrations\": parts.join(\"\\n\"),\n };\n}\n"],"mappings":";;AAKA,SAAgB,wBACd,aACA,SACgB;CAChB,IAAI,CAAC,SACH,OAAO,CAAC;CAGV,MAAM,QAAkB,CAAC;CAEzB,MAAM,qBAAqB,YAAY,QAAQ,MAAM,EAAE,OAAO;CAE9D,MAAM,KAAY;qCACiB,wBAC/B,mBAAmB,KAAK,EAAE,MAAM,iBAAiB;EAC/C,OAAO,CAAC,MAAM,KAAK,UAAU,WAAW,MAAM,CAAC;CACjD,CAAC,CACH,EAAE;GACH;CAED,IAAI,gBAAgB,mBAAmB,KAAK,MAAM,EAAE,IAAI;CACxD,IAAI,WAAW,MAAM,QAAQ,QAAQ,aAAa,GAChD,gBAAgB,cAAc,QAAQ,SACnC,QAAQ,cAAoC,SAAS,IAAI,CAC5D;CAGF,MAAM,KAAY;6CACyB,UAAU,QAAQ,WAAW,EAAE;qCACvC,gBAAgB,cAAc,KAAK,SAAS,UAAU,IAAI,CAAC,CAAC,EAAE;GAChG;CAED,OAAO,EACL,6BAA6B,MAAM,KAAK,IAAI,EAC9C;AACF"}
|