@blinkhost/cli 2.6.0 → 2.8.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.
Files changed (65) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/README.md +534 -2
  3. package/dist/api.d.ts +2 -2
  4. package/dist/api.js +57 -8
  5. package/dist/assistant.js +6 -1
  6. package/dist/cli.js +162 -9
  7. package/dist/design.d.ts +5 -0
  8. package/dist/design.js +82 -0
  9. package/dist/guidance.d.ts +1 -1
  10. package/dist/guidance.js +55 -12
  11. package/dist/javascript-runtime/resource-limits.js +3 -0
  12. package/dist/javascript-runtime/resource-profiles.js +2 -0
  13. package/dist/local-dev.d.ts +3 -0
  14. package/dist/local-dev.js +145 -0
  15. package/dist/local-development/README.md +410 -0
  16. package/dist/local-development/artifact-watch.mjs +36 -0
  17. package/dist/local-development/blinkhost.local.example.json +15 -0
  18. package/dist/local-development/frontend-proxy.mjs +189 -0
  19. package/dist/local-development/hello.rs +24 -0
  20. package/dist/local-development/local-stack.mjs +511 -0
  21. package/dist/local-development/native-database.mjs +37 -0
  22. package/dist/local-development/provider-fixtures.example.json +36 -0
  23. package/dist/local-development/provider-fixtures.mjs +203 -0
  24. package/dist/local-development/provider-grants.mjs +36 -0
  25. package/dist/local-development/test-provider-example.mjs +74 -0
  26. package/dist/local-source-build.d.ts +39 -0
  27. package/dist/local-source-build.js +225 -0
  28. package/dist/local-source-watch.d.ts +24 -0
  29. package/dist/local-source-watch.js +87 -0
  30. package/dist/local-test-command.d.ts +49 -0
  31. package/dist/local-test-command.js +128 -0
  32. package/dist/local-test-config.d.ts +37 -0
  33. package/dist/local-test-config.js +174 -0
  34. package/dist/local-test-gates.d.ts +71 -0
  35. package/dist/local-test-gates.js +247 -0
  36. package/dist/local-test-go-runner.d.ts +27 -0
  37. package/dist/local-test-go-runner.js +209 -0
  38. package/dist/local-test-node-arguments.d.ts +2 -0
  39. package/dist/local-test-node-arguments.js +14 -0
  40. package/dist/local-test-node-reporter.d.ts +7 -0
  41. package/dist/local-test-node-reporter.js +159 -0
  42. package/dist/local-test-results.d.ts +65 -0
  43. package/dist/local-test-results.js +163 -0
  44. package/dist/local-test-rust-runner.d.ts +18 -0
  45. package/dist/local-test-rust-runner.js +252 -0
  46. package/dist/local-test-starters.d.ts +3 -0
  47. package/dist/local-test-starters.js +157 -0
  48. package/dist/logs.d.ts +43 -0
  49. package/dist/logs.js +417 -0
  50. package/dist/module-build-diagnostics.d.ts +10 -0
  51. package/dist/module-build-diagnostics.js +208 -0
  52. package/dist/module-build.js +4 -0
  53. package/dist/release-preparation-diagnostics.d.ts +38 -0
  54. package/dist/release-preparation-diagnostics.js +204 -0
  55. package/dist/remote.js +14 -0
  56. package/dist/templates.d.ts +1 -0
  57. package/dist/templates.js +4 -1
  58. package/dist/test-credentials.d.ts +7 -0
  59. package/dist/test-credentials.js +236 -0
  60. package/dist/version.d.ts +1 -1
  61. package/dist/version.js +1 -1
  62. package/dist/workflows.d.ts +39 -2
  63. package/dist/workflows.js +241 -14
  64. package/package.json +4 -3
  65. package/test-runners/python-unittest.py +266 -0
@@ -0,0 +1,24 @@
1
+ #![no_std]
2
+ #![no_main]
3
+
4
+ use core::panic::PanicInfo;
5
+
6
+ #[link(wasm_import_module = "blinkhost_system")]
7
+ unsafe extern "C" {
8
+ fn write_response(bytes: *const u8, len: usize) -> i32;
9
+ }
10
+
11
+ #[unsafe(no_mangle)]
12
+ pub extern "C" fn _start() {
13
+ let response = br#"{"status":200,"headers":{"content-type":"text/plain"},"body":"Hello from BlinkHost!"}"#;
14
+ // The host returns the number of response bytes it accepted.
15
+ let written = unsafe { write_response(response.as_ptr(), response.len()) };
16
+ if written != response.len() as i32 {
17
+ core::arch::wasm32::unreachable();
18
+ }
19
+ }
20
+
21
+ #[panic_handler]
22
+ fn panic(_: &PanicInfo) -> ! {
23
+ core::arch::wasm32::unreachable()
24
+ }
@@ -0,0 +1,511 @@
1
+ /** Owned Linux customer-local libSQL/WasmEdge/frontend lifecycle. No cloud authority. */
2
+ import { execFile, spawn } from 'node:child_process';
3
+ import { createHash } from 'node:crypto';
4
+ import { closeSync, constants, openSync, writeSync } from 'node:fs';
5
+ import { mkdir, open, readFile, readdir, readlink, realpath, stat, writeFile } from 'node:fs/promises';
6
+ import path from 'node:path';
7
+ import { pathToFileURL } from 'node:url';
8
+ import { promisify, isDeepStrictEqual } from 'node:util';
9
+ import { createLocalFrontendServer } from './frontend-proxy.mjs';
10
+ import { providerFixtures, startProviderFixture } from './provider-fixtures.mjs';
11
+ import { providerPermissions, localProviderGrant } from './provider-grants.mjs';
12
+ import { nativeDatabasePermissions, newNativeDatabase } from './native-database.mjs';
13
+ import { RESOURCE_PROFILE_CONTRACT_SHA256 } from '../javascript-runtime/resource-profiles.js';
14
+
15
+ const CONFIG_BYTES = 65_536, LOG_BYTES = 1_048_576, RESPONSE_BYTES = 1_048_576;
16
+ const fail = code => { throw new Error(code); };
17
+ const object = value => value !== null && typeof value === 'object' && !Array.isArray(value);
18
+ function keys(value, required, optional = []) {
19
+ if (!object(value) || required.some(key => !Object.hasOwn(value, key))
20
+ || Object.keys(value).some(key => ![...required, ...optional].includes(key))) fail('invalid_local_stack_configuration');
21
+ }
22
+ function integer(value, min, max) { if (!Number.isSafeInteger(value) || value < min || value > max) fail('invalid_local_stack_limit'); return value; }
23
+ function localPath(value, root) {
24
+ if (typeof value !== 'string' || !value || value.length > 4096 || /[\x00-\x1f]/.test(value)) fail('invalid_local_stack_path');
25
+ return path.resolve(root, value);
26
+ }
27
+ function pinnedFile(value, root) {
28
+ keys(value, ['path', 'sha256']);
29
+ if (typeof value.sha256 !== 'string' || !/^[a-f0-9]{64}$/.test(value.sha256)) fail('invalid_local_stack_digest');
30
+ return { path: localPath(value.path, root), sha256: value.sha256 };
31
+ }
32
+
33
+ export function configuration(value, root) {
34
+ keys(value, ['schema', 'runtime', 'engine', 'database', 'artifact', 'frontend'], ['limits', 'providers', 'provider_permissions']);
35
+ if (value.schema !== 'blinkhost.local-stack/v1') fail('unsupported_local_stack_schema');
36
+ keys(value.database, ['executable', 'setup'], ['native']);
37
+ if (!Array.isArray(value.database.setup) || value.database.setup.length > 128) fail('invalid_local_stack_setup');
38
+ const setup = value.database.setup.map(statement => {
39
+ keys(statement, ['sql'], ['args']);
40
+ if (typeof statement.sql !== 'string' || !statement.sql.trim() || Buffer.byteLength(statement.sql) > 16_384
41
+ || statement.sql.includes('\0')) fail('invalid_local_stack_sql');
42
+ const args = statement.args ?? [];
43
+ if (!Array.isArray(args) || args.length > 128) fail('invalid_local_stack_sql_arguments');
44
+ for (const arg of args) {
45
+ keys(arg, ['type'], arg.type === 'null' ? [] : ['value', 'base64']);
46
+ switch (arg.type) {
47
+ case 'null': break;
48
+ case 'text':
49
+ if (Object.keys(arg).length !== 2 || typeof arg.value !== 'string' || Buffer.byteLength(arg.value) > 16_384) fail('invalid_local_stack_sql_arguments');
50
+ break;
51
+ case 'integer':
52
+ if (Object.keys(arg).length !== 2 || typeof arg.value !== 'string' || !/^-?(0|[1-9][0-9]{0,18})$/.test(arg.value)
53
+ || BigInt(arg.value) < -(1n << 63n) || BigInt(arg.value) >= (1n << 63n)) fail('invalid_local_stack_sql_arguments');
54
+ break;
55
+ case 'float':
56
+ if (Object.keys(arg).length !== 2 || typeof arg.value !== 'number' || !Number.isFinite(arg.value)) fail('invalid_local_stack_sql_arguments');
57
+ break;
58
+ case 'blob':
59
+ if (Object.keys(arg).length !== 2 || typeof arg.base64 !== 'string' || arg.base64.length > 21_848
60
+ || Buffer.from(arg.base64, 'base64').toString('base64') !== arg.base64) fail('invalid_local_stack_sql_arguments');
61
+ break;
62
+ default: fail('invalid_local_stack_sql_arguments');
63
+ }
64
+ }
65
+ return { sql: statement.sql, args };
66
+ });
67
+ const limits = value.limits ?? {};
68
+ keys(limits, [], ['max_concurrent', 'request_timeout_ms']);
69
+ const providers = providerFixtures(value.providers);
70
+ const providerGrant = providerPermissions(value.provider_permissions, providers);
71
+ return { runtime: pinnedFile(value.runtime, root), engine: pinnedFile(value.engine, root),
72
+ database: pinnedFile(value.database.executable, root), artifact: pinnedFile(value.artifact, root),
73
+ frontend: localPath(value.frontend, root), setup, native: nativeDatabasePermissions(value.database.native), providers, providerGrant,
74
+ concurrent: integer(limits.max_concurrent ?? 4, 1, 10),
75
+ requestTimeout: integer(limits.request_timeout_ms ?? 30_000, 1, 30_000) };
76
+ }
77
+
78
+ async function boundedRead(filename, maximum) {
79
+ const file = await open(filename, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
80
+ try {
81
+ const metadata = await file.stat();
82
+ if (!metadata.isFile() || metadata.size > maximum) fail('local_stack_file_limit');
83
+ const bytes = Buffer.alloc(metadata.size + 1);
84
+ let length = 0;
85
+ while (length < bytes.length) {
86
+ const chunk = await file.read(bytes, length, bytes.length - length, length);
87
+ if (!chunk.bytesRead) break;
88
+ length += chunk.bytesRead;
89
+ }
90
+ if (length !== metadata.size) fail('local_stack_file_changed');
91
+ return bytes.subarray(0, length);
92
+ } finally { await file.close(); }
93
+ }
94
+
95
+ export async function readConfiguration(filename) {
96
+ const absolute = await realpath(filename);
97
+ const bytes = await boundedRead(absolute, CONFIG_BYTES);
98
+ let parsed;
99
+ try { parsed = JSON.parse(bytes.toString('utf8')); } catch { fail('invalid_local_stack_json'); }
100
+ return { ...configuration(parsed, path.dirname(absolute)), configSha256: createHash('sha256').update(bytes).digest('hex') };
101
+ }
102
+
103
+ export async function configurationDigest(filename) {
104
+ return createHash('sha256').update(await boundedRead(filename, CONFIG_BYTES)).digest('hex');
105
+ }
106
+
107
+ function runtimeIdentity(health, config, native, providerGrant) {
108
+ if (health.schema !== 'blinkhost.local-runtime/v1' || health.engine !== '0.18.1'
109
+ || health.artifact_sha256 !== config.artifact.sha256 || health.guest_memory_bytes !== 134_217_728
110
+ || health.resource_contract_sha256 !== RESOURCE_PROFILE_CONTRACT_SHA256 || !health.database_read
111
+ || health.native_database !== Boolean(native) || health.max_concurrent !== config.concurrent
112
+ || health.request_timeout_ms !== config.requestTimeout) fail('local_stack_runtime_identity_mismatch');
113
+ if (native && (!health.native_database_scope || Object.keys(health.native_database_scope).length !== 4
114
+ || Object.keys(native.scope).some(key => health.native_database_scope[key] !== native.scope[key])
115
+ || !health.native_database_permissions || Object.keys(health.native_database_permissions).length !== 3
116
+ || ['read', 'write', 'transaction'].some(key => health.native_database_permissions[key] !== config.native[key]))) {
117
+ fail('local_stack_runtime_native_identity_mismatch');
118
+ }
119
+ if (Boolean(health.provider_permissions) !== Boolean(providerGrant)
120
+ || !isDeepStrictEqual(health.provider_grant ?? null, providerGrant)) fail('local_stack_runtime_provider_identity_mismatch');
121
+ }
122
+
123
+ function runtimeArguments(config, databaseOrigin, native, providerGrant) {
124
+ const args = ['--artifact', config.artifact.path, '--database-url', databaseOrigin,
125
+ '--listen', '127.0.0.1:0', '--max-concurrent', String(config.concurrent),
126
+ '--request-timeout-ms', String(config.requestTimeout)];
127
+ if (native) args.push('--native-database', JSON.stringify(native.grant));
128
+ if (providerGrant) args.push('--local-providers', JSON.stringify(providerGrant));
129
+ return args;
130
+ }
131
+
132
+ async function verifyFile(item, maximum) {
133
+ item.path = await realpath(item.path);
134
+ const file = await open(item.path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
135
+ try {
136
+ const metadata = await file.stat();
137
+ if (!metadata.isFile() || metadata.size > maximum) fail('local_stack_file_limit');
138
+ const hash = createHash('sha256'); let size = 0;
139
+ for await (const bytes of file.createReadStream({ autoClose: false })) {
140
+ size += bytes.length;
141
+ if (size > maximum) fail('local_stack_file_limit');
142
+ hash.update(bytes);
143
+ }
144
+ if (size !== metadata.size || hash.digest('hex') !== item.sha256) fail('local_stack_digest_mismatch');
145
+ } finally { await file.close(); }
146
+ }
147
+
148
+ // Discover the ephemeral listener from sockets owned by this exact child. No
149
+ // reserve/close/rebind race, no chosen public listener and no existing DB origin.
150
+ export async function ownedListenerOrigin(pid) {
151
+ if (!Number.isSafeInteger(pid) || pid <= 0) fail('invalid_local_stack_pid');
152
+ const directory = `/proc/${pid}/fd`;
153
+ const sockets = new Set();
154
+ for (const fd of await readdir(directory)) {
155
+ try {
156
+ const target = await readlink(`${directory}/${fd}`);
157
+ const match = /^socket:\[(\d+)\]$/.exec(target);
158
+ if (match) sockets.add(match[1]);
159
+ } catch (error) { if (error.code !== 'ENOENT') throw error; }
160
+ }
161
+ const listeners = new Set();
162
+ for (const line of (await readFile(`/proc/${pid}/net/tcp`, 'utf8')).trim().split('\n').slice(1)) {
163
+ const columns = line.trim().split(/\s+/);
164
+ if (columns[3] !== '0A' || !sockets.has(columns[9])) continue;
165
+ const [address, port] = columns[1].split(':');
166
+ if (address !== '0100007F') fail('local_stack_child_listener_changed');
167
+ listeners.add(`http://127.0.0.1:${Number.parseInt(port, 16)}`);
168
+ }
169
+ if (listeners.size > 1) fail('local_stack_child_listener_ambiguous');
170
+ return [...listeners][0];
171
+ }
172
+
173
+ function launch(name, executable, args, directory, env) {
174
+ const descriptor = openSync(path.join(directory, `${name}.log`), 'wx', 0o600);
175
+ const child = spawn(executable, args, { cwd: directory, env, shell: false, stdio: ['ignore', 'pipe', 'pipe'] });
176
+ let notifyFailure;
177
+ const owner = { name, child, exited: false, spawnError: false, code: null, signal: null,
178
+ loggedBytes: 0, droppedLogBytes: 0, logFailed: false, failure: new Promise(resolve => { notifyFailure = resolve; }) };
179
+ const log = bytes => {
180
+ const remaining = LOG_BYTES - owner.loggedBytes;
181
+ if (remaining > 0) {
182
+ const part = bytes.subarray(0, remaining);
183
+ try { writeSync(descriptor, part); owner.loggedBytes += part.length; }
184
+ catch { owner.logFailed = true; notifyFailure(); }
185
+ }
186
+ owner.droppedLogBytes += Math.max(0, bytes.length - Math.max(0, remaining));
187
+ };
188
+ child.stdout.on('data', log); child.stderr.on('data', log);
189
+ child.once('error', () => { owner.spawnError = true; });
190
+ owner.done = new Promise(resolve => child.once('close', (code, signal) => {
191
+ owner.exited = true; owner.code = code; owner.signal = signal;
192
+ try { closeSync(descriptor); } catch { owner.logFailed = true; }
193
+ notifyFailure(); resolve(owner);
194
+ }));
195
+ return owner;
196
+ }
197
+
198
+ const pause = (milliseconds, signal) => new Promise((resolve, reject) => {
199
+ signal?.throwIfAborted();
200
+ const abort = () => { clearTimeout(timer); reject(new Error('local_stack_interrupted')); };
201
+ const timer = setTimeout(() => { signal?.removeEventListener('abort', abort); resolve(); }, milliseconds);
202
+ signal?.addEventListener('abort', abort, { once: true });
203
+ });
204
+ async function stopChild(owner) {
205
+ if (!owner.exited) owner.child.kill('SIGTERM');
206
+ const wait = async milliseconds => {
207
+ let timer;
208
+ try { await Promise.race([owner.done, new Promise(resolve => { timer = setTimeout(resolve, milliseconds); })]); }
209
+ finally { clearTimeout(timer); }
210
+ };
211
+ await wait(6000);
212
+ if (!owner.exited) {
213
+ owner.child.kill('SIGKILL');
214
+ await wait(3000);
215
+ }
216
+ if (!owner.exited) fail('local_stack_child_stop_failed');
217
+ }
218
+
219
+ async function jsonRequest(url, body, signal) {
220
+ const abort = AbortSignal.timeout(2000);
221
+ const response = await fetch(url, { method: body ? 'POST' : 'GET', redirect: 'error',
222
+ headers: body ? { 'content-type': 'application/json' } : {},
223
+ body: body ? JSON.stringify(body) : undefined, signal: signal ? AbortSignal.any([abort, signal]) : abort });
224
+ if (response.status !== 200) { await response.body?.cancel(); fail('local_stack_http_failure'); }
225
+ const chunks = []; let length = 0;
226
+ for await (const chunk of response.body) {
227
+ length += chunk.length;
228
+ if (length > RESPONSE_BYTES) { await response.body.cancel().catch(() => {}); fail('local_stack_response_limit'); }
229
+ chunks.push(chunk);
230
+ }
231
+ return JSON.parse(Buffer.concat(chunks).toString('utf8'));
232
+ }
233
+
234
+ export async function sqlExecute(origin, statement, signal) {
235
+ // Only the orchestrator's discovered local child origin is used by setup.
236
+ const port = typeof origin === 'string' && /^http:\/\/127\.0\.0\.1:([1-9][0-9]{0,4})$/.exec(origin);
237
+ if (!port || Number(port[1]) > 65535) fail('invalid_local_stack_origin');
238
+ const payload = await jsonRequest(origin + '/v2/pipeline', { requests: [
239
+ { type: 'execute', stmt: { ...statement, want_rows: true } }, { type: 'close' } ] }, signal);
240
+ if (!Array.isArray(payload.results) || payload.results.length !== 2
241
+ || payload.results.some(row => row.type !== 'ok') || payload.results[0].response?.type !== 'execute') fail('local_stack_sql_failure');
242
+ return payload.results[0].response.result;
243
+ }
244
+
245
+ async function ready(owner, suffix, signal) {
246
+ const deadline = Date.now() + 30_000;
247
+ while (Date.now() < deadline) {
248
+ signal?.throwIfAborted();
249
+ if (owner.exited || owner.spawnError || owner.logFailed) fail('local_stack_child_start_failed');
250
+ let origin;
251
+ try { origin = await ownedListenerOrigin(owner.child.pid); }
252
+ catch (error) { if (!['ENOENT', 'ESRCH'].includes(error.code)) throw error; }
253
+ if (origin) {
254
+ try {
255
+ const health = suffix ? await jsonRequest(origin + suffix, undefined, signal)
256
+ : await sqlExecute(origin, { sql: 'SELECT 1', args: [] }, signal);
257
+ if (!owner.exited) return { origin, health };
258
+ } catch { signal?.throwIfAborted(); }
259
+ }
260
+ await pause(25, signal);
261
+ }
262
+ fail('local_stack_readiness_timeout');
263
+ }
264
+
265
+ export async function startLocalStack(filename, requestedDirectory, { signal } = {}) {
266
+ const [nodeMajor, nodeMinor] = process.versions.node.split('.').map(Number);
267
+ if (process.platform !== 'linux' || nodeMajor < 22 || (nodeMajor === 22 && nodeMinor < 12)) fail('unsupported_local_stack_platform');
268
+ signal?.throwIfAborted();
269
+ const config = await readConfiguration(filename);
270
+ if (path.basename(config.engine.path) !== 'libwasmedge.so') fail('invalid_local_stack_engine_path');
271
+ const engineDirectory = await realpath(path.dirname(config.engine.path));
272
+ await verifyFile(config.runtime, 512 * 1024 * 1024);
273
+ await verifyFile(config.engine, 512 * 1024 * 1024);
274
+ await verifyFile(config.database, 512 * 1024 * 1024);
275
+ await verifyFile(config.artifact, 20_000_000);
276
+ const version = await promisify(execFile)(config.database.path, ['--version'], {
277
+ env: { PATH: path.dirname(process.execPath), LANG: 'C.UTF-8' },
278
+ timeout: 2000, maxBuffer: 4096, signal });
279
+ if (!/^sqld sqld 0\.24\.32 \(/.test(version.stdout.trim())) fail('local_stack_database_version_mismatch');
280
+ config.frontend = await realpath(config.frontend);
281
+ if (!(await stat(config.frontend)).isDirectory()) fail('invalid_local_stack_frontend');
282
+ const requested = path.resolve(requestedDirectory);
283
+ const directory = path.join(await realpath(path.dirname(requested)), path.basename(requested));
284
+ if (directory === config.frontend || directory.startsWith(config.frontend + path.sep)) fail('local_stack_private_state_in_frontend');
285
+ signal?.throwIfAborted();
286
+ // Never resume/reset an existing directory or erase a failed run's database.
287
+ await mkdir(directory, { mode: 0o700 });
288
+ const children = [], providers = [], lifecycle = new AbortController();
289
+ let frontend, stopping, resolveClosed, reloading, reloadAttempts = 0, phase = 'initializing';
290
+ const closed = new Promise(resolve => { resolveClosed = resolve; });
291
+ const env = { PATH: path.dirname(process.execPath), LANG: 'C.UTF-8',
292
+ LD_LIBRARY_PATH: engineDirectory, TMPDIR: path.join(directory, 'tmp') };
293
+ const stop = (reason = 'stopped') => {
294
+ if (stopping) return stopping;
295
+ stopping = (async () => {
296
+ signal?.removeEventListener('abort', interrupted);
297
+ lifecycle.abort();
298
+ if (frontend) { frontend.closeAllConnections(); await new Promise(resolve => frontend.close(resolve)); }
299
+ if (reloading) await reloading.catch(() => {});
300
+ let stopFailed = false;
301
+ // VM shutdown precedes libSQL shutdown; both handles were started here.
302
+ for (const owner of [...children].reverse()) {
303
+ try { await stopChild(owner); } catch { stopFailed = true; }
304
+ }
305
+ const providerEvidence = {};
306
+ for (const provider of providers) {
307
+ try { providerEvidence[provider.name] = await provider.fixture.stop(); } catch { stopFailed = true; }
308
+ }
309
+ if (providers.length) {
310
+ try { await writeFile(path.join(directory, 'provider-fixtures.json'), JSON.stringify(providerEvidence, null, 2) + '\n', { flag: 'wx', mode: 0o600 }); }
311
+ catch { stopFailed = true; }
312
+ }
313
+ const result = { schema: 'blinkhost.local-stack-stop/v1', status: stopFailed ? 'failed' : reason,
314
+ phase, children_stopped: children.every(owner => owner.exited),
315
+ provider_fixtures_stopped: Object.keys(providerEvidence).length === providers.length
316
+ && Object.values(providerEvidence).every(provider => provider.active === 0),
317
+ children: children.map(owner => ({ name: owner.name, pid: owner.child.pid ?? null,
318
+ exit_code: owner.code, signal: owner.signal, log_bytes: owner.loggedBytes,
319
+ dropped_log_bytes: owner.droppedLogBytes, log_error: owner.logFailed })),
320
+ data_preserved: true, production_authority: false };
321
+ try { await writeFile(path.join(directory, 'stopped.json'), JSON.stringify(result, null, 2) + '\n', { flag: 'wx', mode: 0o600 }); }
322
+ catch { result.status = 'failed'; result.stop_evidence_written = false; }
323
+ resolveClosed(result); return result;
324
+ })();
325
+ return stopping;
326
+ };
327
+ const interrupted = () => { stop('interrupted').catch(() => {}); };
328
+ try {
329
+ await mkdir(env.TMPDIR, { mode: 0o700 });
330
+ signal?.throwIfAborted();
331
+ phase = 'database';
332
+ const database = launch('database', config.database.path, ['--no-welcome', '--disable-metrics',
333
+ '--http-listen-addr', '127.0.0.1:0', '--db-path', path.join(directory, 'project.sqld')], directory, env);
334
+ children.push(database);
335
+ const { origin: databaseOrigin } = await ready(database, undefined, signal);
336
+ phase = 'setup';
337
+ for (const statement of config.setup) await sqlExecute(databaseOrigin, statement, signal);
338
+ // Only this freshly created child database receives privileged receipt state.
339
+ const native = newNativeDatabase(config.native ?? undefined);
340
+ if (native) {
341
+ phase = 'native-database-setup';
342
+ for (const statement of native.setup) await sqlExecute(databaseOrigin, statement, signal);
343
+ }
344
+ phase = 'providers';
345
+ for (const [name, definition] of Object.entries(config.providers)) {
346
+ signal?.throwIfAborted();
347
+ providers.push({ name, fixture: await startProviderFixture(name, definition) });
348
+ }
349
+ phase = 'runtime';
350
+ const providerGrant = localProviderGrant(config.providerGrant, config.artifact.sha256, config.providers, providers);
351
+ let runtime = launch('runtime', config.runtime.path, runtimeArguments(config, databaseOrigin, native, providerGrant), directory, env);
352
+ children.push(runtime);
353
+ const { origin: runtimeOrigin, health } = await ready(runtime, '/__blinkhost/health', signal);
354
+ runtimeIdentity(health, config, native, providerGrant);
355
+ phase = 'frontend';
356
+ frontend = await createLocalFrontendServer({ frontend: config.frontend, runtime: runtimeOrigin });
357
+ await new Promise((resolve, reject) => {
358
+ frontend.once('error', reject); frontend.listen(0, '127.0.0.1', resolve);
359
+ });
360
+ signal?.throwIfAborted();
361
+ if (children.some(owner => owner.exited)) fail('local_stack_child_start_failed');
362
+ phase = 'ready';
363
+ let manifest = { schema: 'blinkhost.local-stack/v1', ready: true,
364
+ frontend: `http://127.0.0.1:${frontend.address().port}`, runtime: runtimeOrigin, database: databaseOrigin,
365
+ state_directory: directory, config_sha256: config.configSha256,
366
+ inputs: Object.fromEntries(['runtime', 'engine', 'database', 'artifact'].map(key => [key, config[key].sha256])),
367
+ engine: health.engine, libsql: '0.24.32', guest_memory_bytes: health.guest_memory_bytes, max_concurrent: config.concurrent,
368
+ request_timeout_ms: config.requestTimeout, setup_statements: config.setup.length,
369
+ children: children.map(owner => ({ name: owner.name, pid: owner.child.pid })),
370
+ provider_fixtures: Object.fromEntries(providers.map(provider => [provider.name, provider.fixture.origin])),
371
+ database_read: true, native_database: Boolean(native), native_database_scope: native?.scope ?? null,
372
+ native_database_permissions: config.native, provider_permissions: Boolean(providerGrant),
373
+ provider_grant: providerGrant, reload_generation: 0, production_authority: false };
374
+ await writeFile(path.join(directory, 'ready.json'), JSON.stringify(manifest, null, 2) + '\n', { flag: 'wx', mode: 0o600 });
375
+ const supervise = owner => owner.failure.then(() => {
376
+ if (!stopping && owner.published && !owner.intentionalExit) stop('failed').catch(() => {});
377
+ });
378
+ for (const owner of children) { owner.published = true; supervise(owner); }
379
+
380
+ const reload = ({ verifyCandidate } = {}) => {
381
+ if (verifyCandidate !== undefined && typeof verifyCandidate !== 'function') return Promise.reject(new Error('invalid_local_stack_reload_guard'));
382
+ if (stopping) return Promise.reject(new Error('local_stack_stopped'));
383
+ if (reloading) return Promise.reject(new Error('local_stack_reload_busy'));
384
+ reloading = (async () => {
385
+ const next = await readConfiguration(filename);
386
+ if (next.configSha256 === manifest.config_sha256) {
387
+ await verifyCandidate?.();
388
+ return { status: 'unchanged', manifest };
389
+ }
390
+ // Changed permissions, tools, frontend, limits or setup need a fresh
391
+ // stack. Reload is exclusively an artifact replacement, never a seed
392
+ // replay, scope reset or permission escalation.
393
+ for (const name of ['runtime', 'engine', 'database']) next[name].path = await realpath(next[name].path);
394
+ next.frontend = await realpath(next.frontend);
395
+ const stable = value => ({ ...value, artifact: undefined, configSha256: undefined });
396
+ if (!isDeepStrictEqual(stable(next), stable(config))) fail('local_stack_reload_configuration_changed');
397
+ for (const name of ['runtime', 'engine', 'database']) await verifyFile(next[name], 512 * 1024 * 1024);
398
+ await verifyFile(next.artifact, 20_000_000);
399
+ if (next.artifact.sha256 === manifest.inputs.artifact) {
400
+ await verifyCandidate?.();
401
+ manifest = { ...manifest, config_sha256: next.configSha256 };
402
+ return { status: 'unchanged', manifest };
403
+ }
404
+ if (reloadAttempts >= 32) fail('local_stack_reload_limit');
405
+ const bytes = await boundedRead(next.artifact.path, 20_000_000);
406
+ if (createHash('sha256').update(bytes).digest('hex') !== next.artifact.sha256) fail('local_stack_digest_mismatch');
407
+ await verifyCandidate?.();
408
+ lifecycle.signal.throwIfAborted();
409
+ const attempt = ++reloadAttempts, stem = `reload-${String(attempt).padStart(3, '0')}`;
410
+ next.artifact.path = path.join(directory, stem + '.wasm');
411
+ await writeFile(next.artifact.path, bytes, { flag: 'wx', mode: 0o600 });
412
+ let candidate, paused = false, retirementStarted = false, result;
413
+ const began = performance.now();
414
+ try {
415
+ const grant = localProviderGrant(next.providerGrant, next.artifact.sha256, next.providers, providers);
416
+ candidate = launch(stem, config.runtime.path, runtimeArguments(next, databaseOrigin, native, grant), directory, env);
417
+ children.push(candidate); supervise(candidate);
418
+ const replacement = await ready(candidate, '/__blinkhost/health', lifecycle.signal);
419
+ runtimeIdentity(replacement.health, next, native, grant);
420
+ if (replacement.health.available_slots !== config.concurrent || replacement.health.active_executions !== 0) {
421
+ fail('local_stack_reload_candidate_busy');
422
+ }
423
+ if (await configurationDigest(filename) !== next.configSha256) fail('local_stack_reload_configuration_raced');
424
+ lifecycle.signal.throwIfAborted();
425
+ frontend.setRuntimePaused(true); paused = true;
426
+ const deadline = performance.now() + 35_000;
427
+ while (true) {
428
+ lifecycle.signal.throwIfAborted();
429
+ if (candidate.exited || runtime.exited) fail('local_stack_reload_process_failed');
430
+ const current = await jsonRequest(manifest.runtime + '/__blinkhost/health', undefined, lifecycle.signal);
431
+ if (current.artifact_sha256 !== manifest.inputs.artifact) fail('local_stack_reload_previous_identity_changed');
432
+ if (frontend.activeRuntimeRequests === 0 && current.available_slots === config.concurrent
433
+ && current.active_executions === 0) break;
434
+ if (performance.now() >= deadline) fail('local_stack_reload_drain_timeout');
435
+ await pause(25, lifecycle.signal);
436
+ }
437
+ // Verify again after draining: a build/config edit during the wait
438
+ // cannot publish a candidate from an obsolete input snapshot.
439
+ if (await configurationDigest(filename) !== next.configSha256) fail('local_stack_reload_configuration_raced');
440
+ const candidateHealth = await jsonRequest(replacement.origin + '/__blinkhost/health', undefined, lifecycle.signal);
441
+ runtimeIdentity(candidateHealth, next, native, grant);
442
+ if (candidateHealth.available_slots !== config.concurrent || candidateHealth.active_executions !== 0) {
443
+ fail('local_stack_reload_candidate_busy');
444
+ }
445
+ await verifyCandidate?.();
446
+ lifecycle.signal.throwIfAborted();
447
+ runtime.intentionalExit = true;
448
+ retirementStarted = true;
449
+ await stopChild(runtime);
450
+ lifecycle.signal.throwIfAborted();
451
+ if (candidate.exited) fail('local_stack_reload_process_failed');
452
+ const updated = { ...manifest, runtime: replacement.origin, config_sha256: next.configSha256,
453
+ inputs: { ...manifest.inputs, artifact: next.artifact.sha256 }, provider_grant: grant,
454
+ children: [database, candidate].map(owner => ({ name: owner.name, pid: owner.child.pid })),
455
+ reload_generation: manifest.reload_generation + 1 };
456
+ result = { schema: 'blinkhost.local-artifact-reload/v1', status: 'reloaded',
457
+ attempt, previous_artifact_sha256: manifest.inputs.artifact,
458
+ artifact_sha256: next.artifact.sha256, config_sha256: next.configSha256,
459
+ artifact_path: next.artifact.path, manifest: updated,
460
+ duration_ms: Math.ceil(performance.now() - began), production_authority: false };
461
+ await writeFile(path.join(directory, stem + '.json'), JSON.stringify(result, null, 2) + '\n', { flag: 'wx', mode: 0o600 });
462
+ frontend.setRuntime(replacement.origin);
463
+ candidate.published = true; runtime = candidate; manifest = updated;
464
+ frontend.setRuntimePaused(false); paused = false;
465
+ return result;
466
+ } catch (error) {
467
+ let candidateStopFailed = false;
468
+ if (candidate) {
469
+ candidate.intentionalExit = true;
470
+ try { await stopChild(candidate); } catch { candidateStopFailed = true; }
471
+ }
472
+ // Before retirement, any invalid replacement retains the working
473
+ // module. A shutdown/crash after retirement must fail the whole stack.
474
+ if ((retirementStarted || candidateStopFailed) && !stopping) queueMicrotask(() => { stop('failed').catch(() => {}); });
475
+ const code = candidateStopFailed ? 'local_stack_child_stop_failed'
476
+ : error instanceof Error && /^[a-z_]{1,96}$/.test(error.message) ? error.message : 'local_stack_reload_failed';
477
+ result = { schema: 'blinkhost.local-artifact-reload/v1', status: 'rejected',
478
+ attempt, artifact_sha256: next.artifact.sha256, config_sha256: next.configSha256,
479
+ artifact_path: next.artifact.path, error: code,
480
+ previous_runtime_retained: !retirementStarted && !candidateStopFailed && !stopping,
481
+ duration_ms: Math.ceil(performance.now() - began), production_authority: false };
482
+ await writeFile(path.join(directory, stem + '.json'), JSON.stringify(result, null, 2) + '\n', { flag: 'wx', mode: 0o600 });
483
+ return result;
484
+ } finally { if (paused && !stopping) frontend.setRuntimePaused(false); }
485
+ })().finally(() => { reloading = undefined; });
486
+ return reloading;
487
+ };
488
+ signal?.addEventListener('abort', interrupted, { once: true });
489
+ if (signal?.aborted) interrupted();
490
+ return { get manifest() { return manifest; },
491
+ get runtimeAvailable() { return !stopping && !runtime.exited; }, stop, closed, reload };
492
+ } catch (error) {
493
+ await stop('failed'); throw error;
494
+ }
495
+ }
496
+
497
+ if (process.argv[1] && import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href) {
498
+ const controller = new AbortController();
499
+ const interrupt = () => controller.abort();
500
+ process.once('SIGINT', interrupt); process.once('SIGTERM', interrupt);
501
+ try {
502
+ const args = process.argv.slice(2);
503
+ if (args.length !== 4 || args[0] !== '--config' || args[2] !== '--state-dir') fail('expected_local_stack_config_and_new_state_directory');
504
+ const stack = await startLocalStack(args[1], args[3], { signal: controller.signal });
505
+ console.log(JSON.stringify(stack.manifest));
506
+ const result = await stack.closed;
507
+ process.exitCode = result.status === 'failed' ? 1 : 0;
508
+ } catch (error) {
509
+ console.error(/^[a-z_]+$/.test(error.message) ? error.message : 'local_stack_start_failed'); process.exitCode = 1;
510
+ } finally { process.off('SIGINT', interrupt); process.off('SIGTERM', interrupt); }
511
+ }
@@ -0,0 +1,37 @@
1
+ /** Explicit permissions and protected schema for a fresh owned local database. */
2
+ import { randomUUID } from 'node:crypto';
3
+
4
+ export function nativeDatabasePermissions(value) {
5
+ if (value === undefined) return null;
6
+ if (!value || typeof value !== 'object' || Array.isArray(value)
7
+ || Object.keys(value).length !== 3 || ['read', 'write', 'transaction'].some(key => !Object.hasOwn(value, key) || typeof value[key] !== 'boolean')
8
+ || !(value.read || value.write || value.transaction)) throw new Error('invalid_local_native_database_permissions');
9
+ return { read: value.read, write: value.write, transaction: value.transaction };
10
+ }
11
+
12
+ // Kept identical to edge::runtime::database::schema; the source conformance test
13
+ // checks all three definitions. No IF NOT EXISTS: unexpected preexisting state
14
+ // fails startup rather than adopting another scope or weakening receipt rules.
15
+ export const RECEIPT_SCHEMA = `CREATE TABLE __blinkhost_receipts (
16
+ scope TEXT NOT NULL, operation_id TEXT NOT NULL, request_hash TEXT NOT NULL,
17
+ result TEXT, created_at INTEGER NOT NULL DEFAULT (unixepoch()) CHECK(created_at>=0),
18
+ PRIMARY KEY(scope, operation_id)
19
+ ) WITHOUT ROWID`;
20
+ export const RECEIPT_INDEX_SCHEMA = `CREATE INDEX __blinkhost_receipt_results
21
+ ON __blinkhost_receipts(created_at) WHERE result IS NOT NULL`;
22
+ export const STATE_SCHEMA = `CREATE TABLE __blinkhost_database_state (
23
+ singleton INTEGER NOT NULL PRIMARY KEY CHECK(singleton=1),
24
+ database_id TEXT NOT NULL, generation TEXT NOT NULL,
25
+ environment TEXT NOT NULL, schema_version INTEGER NOT NULL CHECK(schema_version=1)
26
+ ) WITHOUT ROWID`;
27
+
28
+ export function newNativeDatabase(permissions) {
29
+ const checked = nativeDatabasePermissions(permissions);
30
+ if (!checked) return null;
31
+ const database_id = randomUUID(), generation = randomUUID();
32
+ return { grant: { database_id, generation, permissions: checked },
33
+ scope: { database_id, generation, environment: 'development', namespace: 'customer-local' },
34
+ setup: [{ sql: RECEIPT_SCHEMA }, { sql: RECEIPT_INDEX_SCHEMA }, { sql: STATE_SCHEMA },
35
+ { sql: 'INSERT INTO __blinkhost_database_state VALUES(1, ?1, ?2, ?3, 1)', args: [
36
+ { type: 'text', value: database_id }, { type: 'text', value: generation }, { type: 'text', value: 'development' } ] }] };
37
+ }
@@ -0,0 +1,36 @@
1
+ {
2
+ "providers": {
3
+ "email": {
4
+ "routes": [{
5
+ "method": "POST",
6
+ "path": "/send",
7
+ "request_sha256": "a1fc390f121787025c46673119fa7502d2c038615d9e716b601fb9f466b14c94",
8
+ "responses": [
9
+ { "status": 429, "headers": { "retry-after": "1" }, "body": "{\"error\":\"limited\"}" },
10
+ { "status": 202, "body": "{\"id\":\"local-send\"}" }
11
+ ]
12
+ }]
13
+ },
14
+ "payment": {
15
+ "routes": [{
16
+ "method": "POST",
17
+ "path": "/charge",
18
+ "responses": [{ "status": 402, "body": "{\"error\":\"declined\"}" }]
19
+ }]
20
+ },
21
+ "ai": {
22
+ "routes": [{
23
+ "method": "POST",
24
+ "path": "/chat",
25
+ "responses": [{
26
+ "status": 200,
27
+ "headers": { "content-type": "text/event-stream" },
28
+ "chunks": [
29
+ { "body": "data: {\"token\":\"hello\"}\n\n" },
30
+ { "body": "data: [DONE]\n\n", "delay_ms": 20 }
31
+ ]
32
+ }]
33
+ }]
34
+ }
35
+ }
36
+ }