-
-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
vite-plugin-db.ts
195 lines (173 loc) · 5.48 KB
/
vite-plugin-db.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
import { fileURLToPath } from 'node:url';
import type { AstroConfig } from 'astro';
import { normalizePath } from 'vite';
import { SEED_DEV_FILE_NAME } from '../../runtime/queries.js';
import { DB_PATH, RUNTIME_IMPORT, RUNTIME_VIRTUAL_IMPORT, VIRTUAL_MODULE_ID } from '../consts.js';
import type { DBTables } from '../types.js';
import { type VitePlugin, getDbDirectoryUrl, getRemoteDatabaseUrl } from '../utils.js';
const WITH_SEED_VIRTUAL_MODULE_ID = 'astro:db:seed';
export const resolved = {
virtual: '\0' + VIRTUAL_MODULE_ID,
seedVirtual: '\0' + WITH_SEED_VIRTUAL_MODULE_ID,
};
export type LateTables = {
get: () => DBTables;
};
export type LateSeedFiles = {
get: () => Array<string | URL>;
};
type VitePluginDBParams =
| {
connectToStudio: false;
tables: LateTables;
seedFiles: LateSeedFiles;
srcDir: URL;
root: URL;
output: AstroConfig['output'];
}
| {
connectToStudio: true;
tables: LateTables;
appToken: string;
srcDir: URL;
root: URL;
output: AstroConfig['output'];
};
export function vitePluginDb(params: VitePluginDBParams): VitePlugin {
const srcDirPath = normalizePath(fileURLToPath(params.srcDir));
let command: 'build' | 'serve' = 'build';
return {
name: 'astro:db',
enforce: 'pre',
configResolved(resolvedConfig) {
command = resolvedConfig.command;
},
async resolveId(id, rawImporter) {
if (id !== VIRTUAL_MODULE_ID) return;
if (params.connectToStudio) return resolved.virtual;
const importer = rawImporter ? await this.resolve(rawImporter) : null;
if (!importer) return resolved.virtual;
if (importer.id.startsWith(srcDirPath)) {
// Seed only if the importer is in the src directory.
// Otherwise, we may get recursive seed calls (ex. import from db/seed.ts).
return resolved.seedVirtual;
}
return resolved.virtual;
},
async load(id) {
if (id !== resolved.virtual && id !== resolved.seedVirtual) return;
if (params.connectToStudio) {
return getStudioVirtualModContents({
appToken: params.appToken,
tables: params.tables.get(),
isBuild: command === 'build',
output: params.output,
});
}
return getLocalVirtualModContents({
root: params.root,
tables: params.tables.get(),
seedFiles: params.seedFiles.get(),
shouldSeed: id === resolved.seedVirtual,
});
},
};
}
export function getConfigVirtualModContents() {
return `export * from ${RUNTIME_VIRTUAL_IMPORT}`;
}
export function getLocalVirtualModContents({
tables,
root,
seedFiles,
shouldSeed,
}: {
tables: DBTables;
seedFiles: Array<string | URL>;
root: URL;
shouldSeed: boolean;
}) {
const userSeedFilePaths = SEED_DEV_FILE_NAME.map(
// Format as /db/[name].ts
// for Vite import.meta.glob
(name) => new URL(name, getDbDirectoryUrl('file:///')).pathname
);
const resolveId = (id: string) =>
id.startsWith('.') ? normalizePath(fileURLToPath(new URL(id, root))) : id;
// Use top-level imports to correctly resolve `astro:db` within seed files.
// Dynamic imports cause a silent build failure,
// potentially because of circular module references.
const integrationSeedImportStatements: string[] = [];
const integrationSeedImportNames: string[] = [];
seedFiles.forEach((pathOrUrl, index) => {
const path = typeof pathOrUrl === 'string' ? resolveId(pathOrUrl) : pathOrUrl.pathname;
const importName = 'integration_seed_' + index;
integrationSeedImportStatements.push(`import ${importName} from ${JSON.stringify(path)};`);
integrationSeedImportNames.push(importName);
});
const dbUrl = new URL(DB_PATH, root);
return `
import { asDrizzleTable, createLocalDatabaseClient, normalizeDatabaseUrl } from ${RUNTIME_IMPORT};
${shouldSeed ? `import { seedLocal } from ${RUNTIME_IMPORT};` : ''}
${shouldSeed ? integrationSeedImportStatements.join('\n') : ''}
const dbUrl = normalizeDatabaseUrl(import.meta.env.ASTRO_DATABASE_FILE, ${JSON.stringify(dbUrl)});
export const db = createLocalDatabaseClient({ dbUrl });
${
shouldSeed
? `await seedLocal({
db,
tables: ${JSON.stringify(tables)},
userSeedGlob: import.meta.glob(${JSON.stringify(userSeedFilePaths)}, { eager: true }),
integrationSeedFunctions: [${integrationSeedImportNames.join(',')}],
});`
: ''
}
export * from ${RUNTIME_VIRTUAL_IMPORT};
${getStringifiedTableExports(tables)}`;
}
export function getStudioVirtualModContents({
tables,
appToken,
isBuild,
output,
}: {
tables: DBTables;
appToken: string;
isBuild: boolean;
output: AstroConfig['output'];
}) {
function appTokenArg() {
if (isBuild) {
if (output === 'server') {
// In production build, always read the runtime environment variable.
return 'process.env.ASTRO_STUDIO_APP_TOKEN';
} else {
// Static mode or prerendering needs the local app token.
return `process.env.ASTRO_STUDIO_APP_TOKEN ?? ${JSON.stringify(appToken)}`;
}
} else {
return JSON.stringify(appToken);
}
}
function dbUrlArg() {
const dbStr = JSON.stringify(getRemoteDatabaseUrl());
// Allow overriding, mostly for testing
return `import.meta.env.ASTRO_STUDIO_REMOTE_DB_URL ?? ${dbStr}`;
}
return `
import {asDrizzleTable, createRemoteDatabaseClient} from ${RUNTIME_IMPORT};
export const db = await createRemoteDatabaseClient(${appTokenArg()}, ${dbUrlArg()});
export * from ${RUNTIME_VIRTUAL_IMPORT};
${getStringifiedTableExports(tables)}
`;
}
function getStringifiedTableExports(tables: DBTables) {
return Object.entries(tables)
.map(
([name, table]) =>
`export const ${name} = asDrizzleTable(${JSON.stringify(name)}, ${JSON.stringify(
table
)}, false)`
)
.join('\n');
}