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
|
import { createServer } from 'node:http';
import { LibsqlError, createClient } from '@libsql/client';
import { z } from 'zod';
import { cli } from '../dist/core/cli/index.js';
import { resolveDbConfig } from '../dist/core/load-file.js';
import { getCreateIndexQueries, getCreateTableQuery } from '../dist/core/queries.js';
const singleQuerySchema = z.object({
sql: z.string(),
args: z.array(z.any()).or(z.record(z.string(), z.any())),
});
const querySchema = singleQuerySchema.or(z.array(singleQuerySchema));
let portIncrementer = 8030;
/**
* @param {import('astro').AstroConfig} astroConfig
* @param {number | undefined} port
*/
export async function setupRemoteDbServer(astroConfig) {
const port = portIncrementer++;
process.env.ASTRO_STUDIO_REMOTE_DB_URL = `http://localhost:${port}`;
process.env.ASTRO_INTERNAL_TEST_REMOTE = true;
const server = createRemoteDbServer().listen(port);
const { dbConfig } = await resolveDbConfig(astroConfig);
const setupQueries = [];
for (const [name, table] of Object.entries(dbConfig?.tables ?? {})) {
const createQuery = getCreateTableQuery(name, table);
const indexQueries = getCreateIndexQueries(name, table);
setupQueries.push(createQuery, ...indexQueries);
}
await fetch(`http://localhost:${port}/db/query`, {
method: 'POST',
body: JSON.stringify(setupQueries.map((sql) => ({ sql, args: [] }))),
headers: {
'Content-Type': 'application/json',
},
});
await cli({
config: astroConfig,
flags: {
_: [undefined, 'astro', 'db', 'execute', 'db/seed.ts'],
remote: true,
},
});
return {
server,
async stop() {
delete process.env.ASTRO_STUDIO_REMOTE_DB_URL;
delete process.env.ASTRO_INTERNAL_TEST_REMOTE;
return new Promise((resolve, reject) => {
server.close((err) => {
if (err) {
reject(err);
} else {
resolve();
}
});
});
},
};
}
export async function initializeRemoteDb(astroConfig) {
await cli({
config: astroConfig,
flags: {
_: [undefined, 'astro', 'db', 'push'],
remote: true,
},
});
await cli({
config: astroConfig,
flags: {
_: [undefined, 'astro', 'db', 'execute', 'db/seed.ts'],
remote: true,
},
});
}
/**
* Clears the environment variables related to Astro DB and Astro Studio.
*/
export function clearEnvironment() {
const keys = Array.from(Object.keys(process.env));
for (const key of keys) {
if (key.startsWith('ASTRO_DB_') || key.startsWith('ASTRO_STUDIO_')) {
delete process.env[key];
}
}
}
function createRemoteDbServer() {
const dbClient = createClient({
url: ':memory:',
});
const server = createServer((req, res) => {
if (
!req.url.startsWith('/db/query') ||
req.method !== 'POST' ||
req.headers['content-type'] !== 'application/json'
) {
res.writeHead(404, { 'Content-Type': 'application/json' });
res.end(
JSON.stringify({
success: false,
}),
);
return;
}
const rawBody = [];
req.on('data', (chunk) => {
rawBody.push(chunk);
});
req.on('end', async () => {
let json;
try {
json = JSON.parse(Buffer.concat(rawBody).toString());
} catch {
applyParseError(res);
return;
}
const parsed = querySchema.safeParse(json);
if (parsed.success === false) {
applyParseError(res);
return;
}
const body = parsed.data;
try {
const result = Array.isArray(body)
? await dbClient.batch(body)
: await dbClient.execute(body);
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(result));
} catch (e) {
res.writeHead(500, { 'Content-Type': 'application/json' });
res.statusMessage = e.message;
res.end(
JSON.stringify({
success: false,
error: {
code: e instanceof LibsqlError ? e.code : 'SQLITE_QUERY_FAILED',
details: e.message,
},
}),
);
}
});
});
server.on('close', () => {
dbClient.close();
});
return server;
}
function applyParseError(res) {
res.writeHead(400, { 'Content-Type': 'application/json' });
res.statusMessage = 'Invalid request body';
res.end(
JSON.stringify({
// Use JSON response with `success: boolean` property
// to match remote error responses.
success: false,
}),
);
}
|