@coreframe/cli-bridge 0.0.0-stage → 3.0.0-beta.2

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 (3) hide show
  1. package/dist/runtime.js +1945 -0
  2. package/package.json +43 -3
  3. package/README.md +0 -3
@@ -0,0 +1,1945 @@
1
+ import { createRequire } from "node:module";
2
+ import { createConnection } from "node:net";
3
+ import { Peer, RpcError, isRecord } from "@coreframe/cli-transport";
4
+ import { inspect, parseEnv } from "node:util";
5
+ import { createHash, randomUUID } from "node:crypto";
6
+ import { access, glob, lstat, mkdir, mkdtemp, open, readFile, realpath, rm, stat, writeFile } from "node:fs/promises";
7
+ import { isAbsolute, join, posix, relative, resolve, sep } from "node:path";
8
+ import { importProjectDependency, importProjectModule, normalizeWorkerEnvironment, readProjectConfig, wranglerEnvironmentNames } from "@coreframe/config";
9
+ import { sql } from "drizzle-orm";
10
+ import { defaultJobLeaseMs, defineDevelopmentJobs, parseJobCooldown } from "@coreframe/jobs";
11
+ import { tmpdir } from "node:os";
12
+ import { constants } from "node:fs";
13
+ import { pathToFileURL } from "node:url";
14
+ import { resolve as resolve$1 } from "import-meta-resolve";
15
+ import { parseSync } from "oxc-parser";
16
+ import { Writable } from "node:stream";
17
+ //#region package.json
18
+ var version = "3.0.0-beta.2";
19
+ //#endregion
20
+ //#region src/failure.ts
21
+ const maxDiagnostic = 65536;
22
+ const credentialField = /AUTH|COOKIE|CREDENTIAL|DATABASE_URL|DSN|KEY|PASSWORD|PRIVATE|SECRET|SESSION|TOKEN|connectionString/i;
23
+ const payloadField = /^(?:env|body|headers|params|\$?request|\$?response)$/i;
24
+ function bounded(text, limit = maxDiagnostic) {
25
+ return Buffer.byteLength(text) <= limit ? text : Buffer.from(text).subarray(0, limit - 3).toString("utf8");
26
+ }
27
+ async function applicationFailure(error, peer) {
28
+ if (error instanceof RpcError) return error;
29
+ try {
30
+ const visited = /* @__PURE__ */ new WeakSet();
31
+ function remember(value, depth = 0) {
32
+ if (!value || typeof value !== "object" || visited.has(value)) return;
33
+ if (depth > 10 || visitedSize++ >= 128) throw new Error("Diagnostic limit");
34
+ visited.add(value);
35
+ const keys = Reflect.ownKeys(value);
36
+ if (keys.length > 128) throw new Error("Diagnostic limit");
37
+ for (const key of keys) {
38
+ const field = Object.getOwnPropertyDescriptor(value, key);
39
+ if (!field || !("value" in field)) continue;
40
+ if (typeof key === "string" && key.toLowerCase() === "env") {
41
+ const environment = field.value;
42
+ if (environment && typeof environment === "object") {
43
+ const values = Object.create(null);
44
+ const names = Reflect.ownKeys(environment);
45
+ if (names.length > 4096) throw new Error("Diagnostic limit");
46
+ for (const name of names) {
47
+ const entry = Object.getOwnPropertyDescriptor(environment, name);
48
+ if (typeof name === "string" && entry && "value" in entry && typeof entry.value === "string") values[name] = entry.value;
49
+ }
50
+ peer.rememberEnvironment(values);
51
+ }
52
+ } else {
53
+ if (typeof key === "string" && credentialField.test(key) && typeof field.value === "string") peer.rememberEnvironment({ CREDENTIAL: field.value });
54
+ remember(field.value, depth + 1);
55
+ }
56
+ }
57
+ }
58
+ let visitedSize = 0;
59
+ remember(error);
60
+ const seen = /* @__PURE__ */ new WeakSet();
61
+ let nodes = 0;
62
+ function sanitize(value, depth = 0) {
63
+ if (typeof value === "string") return bounded(peer.redactText(value));
64
+ if (typeof value === "function") return "[Function]";
65
+ if (!value || typeof value !== "object") return value;
66
+ if (seen.has(value)) return "[Circular]";
67
+ if (depth > 10 || nodes++ >= 128) return "[Diagnostic limit]";
68
+ seen.add(value);
69
+ const result = Object.create(null);
70
+ for (const key of Reflect.ownKeys(value).slice(0, 128)) {
71
+ if (typeof key !== "string" || payloadField.test(key) || credentialField.test(key)) continue;
72
+ const field = Object.getOwnPropertyDescriptor(value, key);
73
+ if (field && "value" in field) result[key] = sanitize(field.value, depth + 1);
74
+ }
75
+ if (value instanceof Error) {
76
+ result.name = peer.redactText(value.name);
77
+ result.message = bounded(peer.redactText(value.message));
78
+ result.stack = bounded(peer.redactText(value.stack ?? value.message));
79
+ }
80
+ return result;
81
+ }
82
+ const diagnostic = bounded(peer.redactText(inspect(sanitize(error), {
83
+ customInspect: false,
84
+ depth: 12,
85
+ maxStringLength: Infinity
86
+ })));
87
+ const message = error instanceof Error ? error.message.split(/\r?\n/, 1)[0] || "Unknown error" : typeof error === "string" || typeof error === "number" || typeof error === "boolean" ? String(error).split(/\r?\n/, 1)[0] || "Unknown error" : "Unknown error";
88
+ const summary = (error instanceof Error && error.name === "DrizzleQueryError" ? (await import("@coreframe/db")).formatDbErrorMessage(error) : void 0) ?? message;
89
+ return new RpcError(-32e3, bounded(peer.redactText(summary), 8192), void 0, { diagnostic: {
90
+ version: 1,
91
+ text: diagnostic
92
+ } });
93
+ } catch {
94
+ return new RpcError(-32e3, "Application operation failed", void 0, { diagnostic: {
95
+ version: 1,
96
+ text: "The thrown value could not be inspected."
97
+ } });
98
+ }
99
+ }
100
+ //#endregion
101
+ //#region src/assets.ts
102
+ /** Retain shared JS configuration and the existing credential/S3 integration. */
103
+ var AssetServices = class {
104
+ config;
105
+ store;
106
+ async describe(project) {
107
+ const { resolveAssetsConfig } = await import("@coreframe/assets/integrations");
108
+ this.config ??= await resolveAssetsConfig(process.cwd(), project.assets);
109
+ return this.config;
110
+ }
111
+ async handle(method, args, project) {
112
+ if (method === "assets.media.inspect" || method === "assets.media.renderRaster") return this.media(method, args);
113
+ if (method === "assets.describe") return this.describe(project ?? {});
114
+ if (method === "assets.storage.open") {
115
+ const config = await this.describe(project ?? {});
116
+ const { createB2PrivateObjectStore } = await import("@coreframe/object-storage");
117
+ this.store ??= {
118
+ id: randomUUID(),
119
+ client: createB2PrivateObjectStore({ config })
120
+ };
121
+ return { resource: this.store.id };
122
+ }
123
+ const store = this.store;
124
+ const config = this.config;
125
+ if (!store || !config || args.resource !== store.id || typeof args.bucket !== "string" || ![config.sourceBucket, config.publicBucket].includes(args.bucket)) throw new RpcError(-32602, "Invalid asset store resource or configured bucket");
126
+ switch (method) {
127
+ case "assets.storage.inventory": {
128
+ if (typeof args.target !== "string" || !isAbsolute(args.target)) throw new RpcError(-32602, "An absolute asset inventory target is required");
129
+ const objects = await store.client.list(args.bucket);
130
+ await writeFile(args.target, JSON.stringify(objects), {
131
+ flag: "wx",
132
+ mode: 384
133
+ });
134
+ return null;
135
+ }
136
+ case "assets.storage.download":
137
+ if (typeof args.key !== "string" || args.key.includes("\0") || typeof args.target !== "string" || !isAbsolute(args.target)) throw new RpcError(-32602, "An asset object key and absolute target are required");
138
+ await store.client.download(args.bucket, args.key, args.target);
139
+ return null;
140
+ case "assets.storage.has":
141
+ if (typeof args.key !== "string" || args.key.includes("\0")) throw new RpcError(-32602, "An asset object key is required");
142
+ return store.client.has(args.bucket, args.key);
143
+ case "assets.storage.uploadSource":
144
+ if (args.bucket !== config.sourceBucket || typeof args.key !== "string" || !/^sources\/v1\/sha256\/([a-f0-9]{2})\/\1[a-f0-9]{62}$/.test(args.key) || typeof args.source !== "string" || !isAbsolute(args.source) || !(await lstat(args.source)).isFile() || typeof args.contentType !== "string" || ![
145
+ "image/avif",
146
+ "image/gif",
147
+ "image/jpeg",
148
+ "image/png",
149
+ "image/tiff",
150
+ "image/webp",
151
+ "image/svg+xml",
152
+ "audio/mpeg",
153
+ "video/mp4",
154
+ "application/json"
155
+ ].includes(args.contentType)) throw new RpcError(-32602, "A managed source asset key, regular source and media type are required");
156
+ await store.client.upload(args.bucket, args.key, args.source, args.contentType);
157
+ return null;
158
+ case "assets.storage.upload":
159
+ if (args.bucket !== config.publicBucket || typeof args.key !== "string" || !args.key.startsWith(`projects/${config.projectId}/assets/`) || args.key.includes("\0") || args.key.includes("\\") || args.key.split("/").some((part) => !part || part === "." || part === "..") || typeof args.source !== "string" || !isAbsolute(args.source) || typeof args.contentType !== "string" || ![
160
+ "image/webp",
161
+ "image/svg+xml",
162
+ "audio/mpeg",
163
+ "video/mp4",
164
+ "application/json"
165
+ ].includes(args.contentType)) throw new RpcError(-32602, "A managed generated asset key, source and media type are required");
166
+ if (!(await lstat(args.source)).isFile()) throw new RpcError(-32602, "An asset upload source must be a regular file");
167
+ await store.client.upload(args.bucket, args.key, args.source, args.contentType);
168
+ return null;
169
+ }
170
+ throw new RpcError(-32601, `Unknown asset operation: ${method}`);
171
+ }
172
+ async media(method, args) {
173
+ if (typeof args.source !== "string" || !isAbsolute(args.source) || !(await lstat(args.source)).isFile()) throw new RpcError(-32602, "An absolute regular media source is required");
174
+ const media = await import("@coreframe/assets/media-integrations");
175
+ if (method === "assets.media.inspect") switch (args.kind) {
176
+ case "image": return media.readImageDimensions(args.source);
177
+ case "svg": return media.inspectSvg(args.source);
178
+ case "audio": return media.inspectAudio(args.source);
179
+ case "video": return media.inspectVideo(args.source);
180
+ case "lottie": try {
181
+ return await media.inspectLottie(args.source);
182
+ } catch (error) {
183
+ if (error instanceof Error && error.message.startsWith("Lottie source must be valid JSON:")) throw new Error("Lottie source must be valid JSON.");
184
+ throw error;
185
+ }
186
+ default: throw new RpcError(-32602, "A supported asset media kind is required");
187
+ }
188
+ if (typeof args.target !== "string" || !isAbsolute(args.target) || !Number.isInteger(args.width) || args.width <= 0 || typeof args.sourceWidth !== "number" || !Number.isFinite(args.sourceWidth) || args.sourceWidth <= 0 || typeof args.sourceHeight !== "number" || !Number.isFinite(args.sourceHeight) || args.sourceHeight <= 0) throw new RpcError(-32602, "A fresh raster target, width and source dimensions are required");
189
+ const { data, width, height } = await media.renderRasterVariant({
190
+ sourcePath: args.source,
191
+ width: args.width,
192
+ sourceDimensions: {
193
+ width: args.sourceWidth,
194
+ height: args.sourceHeight
195
+ }
196
+ });
197
+ await writeFile(args.target, data, {
198
+ flag: "wx",
199
+ mode: 384
200
+ });
201
+ return {
202
+ width,
203
+ height
204
+ };
205
+ }
206
+ };
207
+ //#endregion
208
+ //#region src/jobs.ts
209
+ /** Retains application-owned definitions and persistence closures in Node. */
210
+ var DevelopmentJobServices = class {
211
+ jobs;
212
+ async describe(entry) {
213
+ if (!entry) throw new Error("coreframe.config.ts must configure jobs.entry before managing development job state.");
214
+ if (!this.jobs) {
215
+ const jobs = (await importProjectModule(entry, process.cwd())).developmentJobs;
216
+ if (!jobs || !Array.isArray(jobs.jobs) || typeof jobs.createStateAdmin !== "function") throw new Error(`${entry} must export developmentJobs with jobs and createStateAdmin properties.`);
217
+ this.jobs = defineDevelopmentJobs(jobs);
218
+ }
219
+ return this.jobs.jobs.map((job) => ({
220
+ id: job.id,
221
+ cooldownMs: parseJobCooldown(job.dev.cooldown),
222
+ leaseMs: job.dev.leaseMs ?? defaultJobLeaseMs
223
+ }));
224
+ }
225
+ async handle(method, database, args) {
226
+ if (!this.jobs) throw new RpcError(-32602, "Describe the project development jobs before accessing state");
227
+ try {
228
+ const admin = this.jobs.createStateAdmin(database);
229
+ if (method === "jobs.list") {
230
+ const records = await admin.list();
231
+ if (!Array.isArray(records) || !records.every((record) => isRecord(record) && typeof record.jobId === "string" && validDate(record.lastSucceededAt) && (record.leaseId === null || typeof record.leaseId === "string") && validDate(record.leaseUntil))) throw new Error("Invalid development job state records");
232
+ return records;
233
+ }
234
+ if (method !== "jobs.reset" || typeof args.breakLeases !== "boolean" || typeof args.now !== "string" || !Number.isFinite(Date.parse(args.now)) || !Array.isArray(args.jobIds) || !args.jobIds.every((id) => typeof id === "string")) throw new RpcError(-32602, "Invalid development job reset");
235
+ const result = await admin.reset({
236
+ breakLeases: args.breakLeases,
237
+ jobIds: args.jobIds,
238
+ now: new Date(args.now)
239
+ });
240
+ if (!isRecord(result) || !Array.isArray(result.resetIds) || !result.resetIds.every((id) => typeof id === "string") || !Array.isArray(result.activeLeaseIds) || !result.activeLeaseIds.every((id) => typeof id === "string")) throw new Error("Invalid development job reset result");
241
+ return result;
242
+ } catch (error) {
243
+ let current = error;
244
+ while (current instanceof Error) {
245
+ const message = current.message.toLowerCase();
246
+ if (message.includes("coreframe_dev_job_state") && (message.includes("does not exist") || message.includes("no such table"))) throw new RpcError(-32010, "The local development job state table is missing; apply local migrations before retrying.");
247
+ current = current.cause;
248
+ }
249
+ throw error;
250
+ }
251
+ }
252
+ };
253
+ function validDate(value) {
254
+ return value === null || value instanceof Date && Number.isFinite(value.getTime());
255
+ }
256
+ //#endregion
257
+ //#region src/database.ts
258
+ /** Owns project Drizzle handles; Go retains target and workflow decisions. */
259
+ var DatabaseServices = class {
260
+ jobs = new DevelopmentJobServices();
261
+ resource;
262
+ closing;
263
+ disposed = false;
264
+ describeJobs(entry) {
265
+ return this.jobs.describe(entry);
266
+ }
267
+ async open(args, configuredDialect) {
268
+ if (this.disposed || this.resource || this.closing || args.dialect !== "postgres" && args.dialect !== "sqlite" || args.dialect !== configuredDialect || typeof args.local !== "boolean" || typeof args.schema !== "boolean") throw new RpcError(-32602, "Invalid database session or project dialect");
269
+ if (args.local) {
270
+ const flag = args.dialect === "postgres" ? "COREFRAME_LOCAL_POSTGRES" : "COREFRAME_LOCAL_TURSO";
271
+ if (process.env[flag] !== "1") throw new RpcError(-32602, "A managed local database environment is required");
272
+ const connection = new URL(process.env.DATABASE_URL ?? "");
273
+ if (![
274
+ "127.0.0.1",
275
+ "localhost",
276
+ "[::1]"
277
+ ].includes(connection.hostname)) throw new RpcError(-32602, "A managed loopback connection is required");
278
+ }
279
+ const schema = args.schema ? await importProjectModule("src/db/schema.ts", process.cwd()) : void 0;
280
+ const { createLocalPostgresDb, createProjectPostgresDrizzleDatabase, createProjectSqliteDrizzleDatabase, inferSchemaDialect } = await import("@coreframe/db");
281
+ const schemaDialect = schema ? inferSchemaDialect(schema) : void 0;
282
+ const database = args.dialect === "postgres" ? await (args.local ? createLocalPostgresDb : createProjectPostgresDrizzleDatabase)({ env: process.env }) : await createProjectSqliteDrizzleDatabase({ env: process.env });
283
+ if (this.disposed) {
284
+ await closeDatabase(database);
285
+ throw new Error("Database session disconnected during startup");
286
+ }
287
+ const id = randomUUID();
288
+ this.resource = {
289
+ id,
290
+ dialect: args.dialect,
291
+ local: args.local,
292
+ database,
293
+ schema,
294
+ plans: /* @__PURE__ */ new Map()
295
+ };
296
+ return {
297
+ resource: id,
298
+ schemaDialect
299
+ };
300
+ }
301
+ async handle(method, args) {
302
+ const resource = this.resource;
303
+ if (!resource || args.resource !== resource.id) throw new RpcError(-32602, "Unknown database session resource");
304
+ const { database, dialect } = resource;
305
+ switch (method) {
306
+ case "db.readAppliedMigrations": {
307
+ const { createDatabaseAdapter, readAppliedMigrationNames } = await import("@coreframe/db");
308
+ return { names: [...await readAppliedMigrationNames(dialect === "postgres" ? createDatabaseAdapter({
309
+ dialect: "postgres",
310
+ database
311
+ }) : createDatabaseAdapter({
312
+ dialect: "sqlite",
313
+ database
314
+ }))] };
315
+ }
316
+ case "jobs.list":
317
+ case "jobs.reset": return this.jobs.handle(method, database, args);
318
+ case "db.close":
319
+ this.resource = void 0;
320
+ this.closing = (async () => {
321
+ try {
322
+ if (resource.foreignKeysDisabled) await database.run(sql`pragma foreign_keys = on`);
323
+ } finally {
324
+ await closeDatabase(database);
325
+ }
326
+ })();
327
+ await this.closing;
328
+ this.closing = void 0;
329
+ return null;
330
+ case "db.findSeedUser":
331
+ if (typeof args.email !== "string" || !resource.schema) throw new RpcError(-32602, "A seed email and project schema are required");
332
+ try {
333
+ const users = resource.schema.users;
334
+ if (!isRecord(users)) return { id: null };
335
+ const [user] = await database.select({ id: users.id }).from(users).where(sql`${users.email} = ${args.email}`).limit(1);
336
+ return { id: typeof user?.id === "string" ? user.id : null };
337
+ } catch {
338
+ return { id: null };
339
+ }
340
+ case "db.inspectObjects":
341
+ if (dialect !== "sqlite") throw new RpcError(-32602, "Object inspection requires SQLite");
342
+ return database.all(sql`
343
+ select name, type from sqlite_schema
344
+ where type in ('table', 'index', 'trigger', 'view') and name not like 'sqlite_%'
345
+ `);
346
+ case "db.clearLocalSchema": {
347
+ const flag = dialect === "postgres" ? "COREFRAME_LOCAL_POSTGRES" : "COREFRAME_LOCAL_TURSO";
348
+ if (!resource.local || process.env[flag] !== "1") throw new RpcError(-32602, "Schema clearing requires a managed local database");
349
+ if (dialect === "postgres") await database.transaction(async (transaction) => {
350
+ await transaction.execute(sql`drop schema if exists public cascade`);
351
+ await transaction.execute(sql`drop schema if exists drizzle cascade`);
352
+ await transaction.execute(sql`create schema public`);
353
+ });
354
+ else {
355
+ if (!Array.isArray(args.objects) || !args.objects.every((object) => isRecord(object) && typeof object.name === "string" && [
356
+ "trigger",
357
+ "view",
358
+ "index",
359
+ "table"
360
+ ].includes(String(object.type)))) throw new RpcError(-32602, "Invalid local SQLite object list");
361
+ await database.run(sql`pragma foreign_keys = off`);
362
+ resource.foreignKeysDisabled = true;
363
+ await database.transaction(async (transaction) => {
364
+ for (const object of args.objects) await transaction.run(sql`drop ${sql.raw(object.type)} if exists ${sql.identifier(object.name)}`);
365
+ });
366
+ }
367
+ return null;
368
+ }
369
+ case "db.planSchema": {
370
+ if (!resource.schema) throw new RpcError(-32602, "A project schema is required");
371
+ if (resource.plans.size >= 8) throw new RpcError(-32602, "Too many unapplied schema plans");
372
+ const { planLocalSchemaPush } = await import("@coreframe/db");
373
+ const plan = await planLocalSchemaPush(dialect, resource.schema, database);
374
+ const id = randomUUID();
375
+ resource.plans.set(id, plan);
376
+ return {
377
+ plan: id,
378
+ statements: plan.sqlStatements.length
379
+ };
380
+ }
381
+ case "db.applySchema": {
382
+ const plan = typeof args.plan === "string" ? resource.plans.get(args.plan) : void 0;
383
+ if (!plan) throw new RpcError(-32602, "Unknown schema plan resource");
384
+ resource.plans.delete(args.plan);
385
+ await plan.apply();
386
+ return null;
387
+ }
388
+ case "db.baselineMigrations": {
389
+ if (!resource.local || !Array.isArray(args.entries) || args.entries.length > 1e3 || !args.entries.every((entry) => isRecord(entry) && typeof entry.name === "string" && typeof entry.sha256 === "string" && /^[a-f0-9]{64}$/.test(entry.sha256) && (entry.createdAt === null || Number.isSafeInteger(entry.createdAt)))) throw new RpcError(-32602, "Invalid migration baseline entries");
390
+ const entries = args.entries;
391
+ await database.transaction(async (transaction) => {
392
+ if (dialect === "postgres") {
393
+ await transaction.execute(sql`create schema if not exists drizzle`);
394
+ await transaction.execute(sql`create table if not exists drizzle.__drizzle_migrations (
395
+ id serial primary key, hash text not null, created_at bigint, name text,
396
+ applied_at timestamp with time zone default now()
397
+ )`);
398
+ for (const entry of entries) await transaction.execute(sql`insert into drizzle.__drizzle_migrations (hash, created_at, name)
399
+ values (${entry.sha256}, ${entry.createdAt}, ${entry.name})`);
400
+ } else {
401
+ await transaction.run(sql`create table if not exists __drizzle_migrations (
402
+ id integer primary key, hash text not null, created_at numeric, name text, applied_at text
403
+ )`);
404
+ const appliedAt = (/* @__PURE__ */ new Date()).toISOString();
405
+ for (const entry of entries) await transaction.run(sql`insert into __drizzle_migrations (hash, created_at, name, applied_at)
406
+ values (${entry.sha256}, ${entry.createdAt}, ${entry.name}, ${appliedAt})`);
407
+ }
408
+ });
409
+ return null;
410
+ }
411
+ case "db.ensureHeldJournal":
412
+ if (dialect === "postgres") {
413
+ await database.execute(sql`create schema if not exists drizzle`);
414
+ await database.execute(sql`create table if not exists drizzle.__held_migrations (
415
+ id text primary key, sha256 text not null, applied_at timestamptz not null default now()
416
+ )`);
417
+ } else await database.run(sql`create table if not exists __held_migrations (
418
+ id text primary key, sha256 text not null, applied_at text not null default current_timestamp
419
+ )`);
420
+ return null;
421
+ case "db.readHeldMigration": {
422
+ if (typeof args.id !== "string" || !args.id) throw new RpcError(-32602, "A held migration ID is required");
423
+ const result = dialect === "postgres" ? await database.execute(sql`select sha256 from drizzle.__held_migrations where id = ${args.id}`) : await database.all(sql`select sha256 from __held_migrations where id = ${args.id}`);
424
+ const rows = Array.isArray(result) ? result : isRecord(result) ? result.rows : void 0;
425
+ if (!Array.isArray(rows) || rows.length > 1 || rows.length === 1 && (!isRecord(rows[0]) || typeof rows[0].sha256 !== "string")) throw new Error("Invalid held migration journal result");
426
+ return { sha256: rows[0]?.sha256 ?? null };
427
+ }
428
+ case "db.applyHeldMigration": {
429
+ if (typeof args.id !== "string" || !args.id || typeof args.sql !== "string" || typeof args.sha256 !== "string" || !/^[a-f0-9]{64}$/.test(args.sha256) || createHash("sha256").update(args.sql).digest("hex") !== args.sha256) throw new RpcError(-32602, "Invalid held migration content or digest");
430
+ const { id, sha256, sql: content } = args;
431
+ if (dialect === "postgres") await database.transaction(async (transaction) => {
432
+ await transaction.execute(sql.raw(content));
433
+ await transaction.execute(sql`insert into drizzle.__held_migrations (id, sha256)
434
+ values (${id}, ${sha256})`);
435
+ });
436
+ else {
437
+ const transaction = await database.$client?.transaction?.("write");
438
+ if (!transaction) throw new Error("The project libSQL client does not support held migration transactions");
439
+ try {
440
+ await transaction.executeMultiple(content);
441
+ await transaction.execute({
442
+ sql: "insert into __held_migrations (id, sha256) values (?, ?)",
443
+ args: [id, sha256]
444
+ });
445
+ await transaction.commit();
446
+ } catch (error) {
447
+ await transaction.rollback();
448
+ throw error;
449
+ } finally {
450
+ transaction.close();
451
+ }
452
+ }
453
+ return null;
454
+ }
455
+ default: throw new RpcError(-32601, "Unsupported database session operation");
456
+ }
457
+ }
458
+ async dispose() {
459
+ this.disposed = true;
460
+ try {
461
+ if (this.resource) await this.handle("db.close", { resource: this.resource.id });
462
+ else await this.closing;
463
+ } catch {
464
+ console.error("Could not close a project database client during bridge disposal.");
465
+ }
466
+ }
467
+ };
468
+ async function closeDatabase(database) {
469
+ await database.$client?.close?.();
470
+ await database.$client?.end?.();
471
+ }
472
+ //#endregion
473
+ //#region src/deploy-artifacts.ts
474
+ /** Shared JS config derivation only; Go owns selection and publication. */
475
+ var DeployArtifacts = class {
476
+ resource;
477
+ closed = false;
478
+ async prepare(args, readConfig) {
479
+ if (this.closed || this.resource || !["full", "client"].includes(String(args.mode)) || !["staging", "production"].includes(String(args.environment)) || typeof args.releaseName !== "string" || !args.releaseName || args.preserveOnDisconnect !== void 0 && typeof args.preserveOnDisconnect !== "boolean") throw new RpcError(-32602, "Invalid deployment artifact options or existing artifact");
480
+ const preserveOnDisconnect = args.preserveOnDisconnect === true;
481
+ const { materializeBuiltClientDeployConfig, materializeBuiltWorkerDeployConfig } = await import("@coreframe/deploy");
482
+ const artifact = args.mode === "full" ? await materializeBuiltWorkerDeployConfig({
483
+ coreframeConfig: await readConfig(),
484
+ environment: args.environment,
485
+ contributions: { generatedValues: {
486
+ DEPLOY_ENV: args.environment,
487
+ POSTHOG_RELEASE: args.releaseName
488
+ } }
489
+ }) : await materializeBuiltClientDeployConfig();
490
+ let identity;
491
+ const dispose = async () => {
492
+ if (!identity) throw new Error("Deployment artifact identity was not confirmed; preserve its files for inspection.");
493
+ let current;
494
+ try {
495
+ current = await lstat(artifact.path, { bigint: true });
496
+ } catch (error) {
497
+ if (error.code === "ENOENT") return;
498
+ throw error;
499
+ }
500
+ if (!identity.isFile() || !current.isFile() || identity.dev !== current.dev || identity.ino !== current.ino) throw new Error("Deployment artifact was replaced; its current contents were preserved.");
501
+ await artifact.dispose();
502
+ };
503
+ this.resource = {
504
+ id: randomUUID(),
505
+ path: artifact.path,
506
+ preserveOnDisconnect,
507
+ dispose
508
+ };
509
+ identity = await lstat(artifact.path, { bigint: true });
510
+ if (!identity.isFile()) throw new Error("Deployment artifact is not a regular file; its contents were preserved.");
511
+ if (this.closed) {
512
+ if (!preserveOnDisconnect) await dispose();
513
+ this.resource = void 0;
514
+ throw new Error("Application session is closed");
515
+ }
516
+ return {
517
+ resource: this.resource.id,
518
+ path: artifact.path
519
+ };
520
+ }
521
+ async close(args) {
522
+ if (!this.resource || this.resource.id !== args.resource) throw new RpcError(-32602, "Unknown deployment artifact resource");
523
+ await this.resource.dispose();
524
+ this.resource = void 0;
525
+ return null;
526
+ }
527
+ async dispose() {
528
+ this.closed = true;
529
+ if (!this.resource?.preserveOnDisconnect) await this.resource?.dispose();
530
+ this.resource = void 0;
531
+ }
532
+ };
533
+ //#endregion
534
+ //#region src/development-logs.ts
535
+ /** Leylines handles only; Go owns native scope selection and output lifetime. */
536
+ var DevelopmentLogs = class {
537
+ resource;
538
+ async open(args) {
539
+ if (this.resource || ![
540
+ "ios",
541
+ "android",
542
+ "macos",
543
+ "ios,android"
544
+ ].includes(args.platform) || args.deviceId !== void 0 && typeof args.deviceId !== "string") throw new RpcError(-32602, "Invalid native log identity or existing resource");
545
+ let opened;
546
+ try {
547
+ const directory = resolve(".leylines");
548
+ await mkdir(directory, { mode: 448 }).catch((error) => {
549
+ if (error.code !== "EEXIST") throw error;
550
+ });
551
+ const parent = await lstat(directory);
552
+ if (!parent.isDirectory() || parent.isSymbolicLink()) throw new Error("Invalid log directory");
553
+ for (const suffix of [
554
+ "",
555
+ "-wal",
556
+ "-shm",
557
+ "-journal"
558
+ ]) {
559
+ const info = await lstat(resolve(directory, `logs.sqlite${suffix}`)).catch((error) => {
560
+ if (error.code === "ENOENT") return;
561
+ throw error;
562
+ });
563
+ if (info && (!info.isFile() || info.isSymbolicLink())) throw new Error("Invalid log file");
564
+ }
565
+ const { openScopedLogs } = await import("leylines");
566
+ const logs = openScopedLogs({ path: resolve(directory, "logs.sqlite") });
567
+ opened = logs;
568
+ const logger = logs.logger({
569
+ scope: "dev.xplat",
570
+ properties: {
571
+ platform: args.platform,
572
+ ...args.deviceId ? { deviceId: args.deviceId } : {}
573
+ }
574
+ });
575
+ this.resource = {
576
+ id: randomUUID(),
577
+ logs,
578
+ logger
579
+ };
580
+ return {
581
+ resource: this.resource.id,
582
+ enabled: logs.enabled
583
+ };
584
+ } catch {
585
+ try {
586
+ opened?.close();
587
+ } catch {
588
+ console.error("Could not confirm native development log-store cleanup.");
589
+ }
590
+ throw new Error("Could not open the project's native development log store.");
591
+ }
592
+ }
593
+ write(args) {
594
+ const resource = this.get(args.resource);
595
+ if (args.stream !== "stdout" && args.stream !== "stderr" || typeof args.text !== "string" || Buffer.byteLength(args.text) > 64 * 1024) throw new RpcError(-32602, "Invalid native output line");
596
+ try {
597
+ resource.logger.write(args.stream === "stderr" ? "warn" : "info", args.text, { properties: { stream: args.stream } });
598
+ return { written: true };
599
+ } catch {
600
+ throw new Error("Could not confirm the native output record. Inspect the log store before retrying.");
601
+ }
602
+ }
603
+ close(args) {
604
+ const resource = this.get(args.resource);
605
+ try {
606
+ resource.logs.close();
607
+ this.resource = void 0;
608
+ return { closed: true };
609
+ } catch {
610
+ throw new Error("Could not confirm native development log-store cleanup.");
611
+ }
612
+ }
613
+ dispose() {
614
+ try {
615
+ this.resource?.logs.close();
616
+ } catch {
617
+ console.error("Could not confirm native development log-store cleanup.");
618
+ } finally {
619
+ this.resource = void 0;
620
+ }
621
+ }
622
+ get(id) {
623
+ if (!this.resource || this.resource.id !== id) throw new RpcError(-32602, "Unknown native log resource");
624
+ return this.resource;
625
+ }
626
+ };
627
+ //#endregion
628
+ //#region src/i18n.ts
629
+ /** Native JS catalog/ICU and S3 operations; Go owns release and file policy. */
630
+ var I18nServices = class {
631
+ catalogs;
632
+ po;
633
+ requests = /* @__PURE__ */ new Map();
634
+ store;
635
+ disposed = false;
636
+ catalogModule() {
637
+ return this.catalogs ??= (async () => {
638
+ const module = await importProjectDependency("@coreframe/scripts/i18n-catalogs", process.cwd());
639
+ if (![
640
+ "collectMissingTranslations",
641
+ "applyGeneratedTranslations",
642
+ "assertCompleteCatalogs",
643
+ "parseTranslationResponse",
644
+ "readRichCatalog",
645
+ "writeRichCatalog"
646
+ ].every((name) => typeof module[name] === "function")) throw new Error("The project workflow package lacks the i18n catalog integration export");
647
+ return module;
648
+ })();
649
+ }
650
+ async handle(method, args, project) {
651
+ if (this.disposed) throw new Error("The i18n integration session is closed");
652
+ if (method === "i18n.storage.open") {
653
+ const assets = project.assets;
654
+ if (!assets || !/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(assets.projectId)) throw new RpcError(-32602, "A valid project asset store is required for i18n snapshots");
655
+ const { createB2PrivateObjectStore } = await import("@coreframe/object-storage");
656
+ this.store ??= {
657
+ id: randomUUID(),
658
+ bucket: assets.sourceBucket,
659
+ prefix: `projects/${assets.projectId}/i18n/v1/`,
660
+ client: createB2PrivateObjectStore({ config: assets })
661
+ };
662
+ return { resource: this.store.id };
663
+ }
664
+ if (method.startsWith("i18n.storage.")) {
665
+ const store = this.store;
666
+ if (!store || args.resource !== store.id || typeof args.key !== "string" || !args.key.startsWith(store.prefix) || args.key.includes("\0") || args.key.split("/").some((part) => part === "." || part === "..")) throw new RpcError(-32602, "Invalid i18n store resource or object key");
667
+ switch (method) {
668
+ case "i18n.storage.has": return store.client.has(store.bucket, args.key);
669
+ case "i18n.storage.download":
670
+ if (typeof args.target !== "string") throw new RpcError(-32602, "An i18n download target is required");
671
+ await store.client.download(store.bucket, args.key, args.target);
672
+ return null;
673
+ case "i18n.storage.upload":
674
+ if (typeof args.source !== "string" || args.contentType !== "application/json" && args.contentType !== "application/octet-stream") throw new RpcError(-32602, "Invalid i18n upload source or content type");
675
+ await store.client.upload(store.bucket, args.key, args.source, args.contentType);
676
+ return null;
677
+ default: throw new RpcError(-32601, "Unsupported i18n store operation");
678
+ }
679
+ }
680
+ if (!project.i18n) throw new RpcError(-32602, "Project i18n configuration is required");
681
+ const config = {
682
+ ...project.i18n,
683
+ catalogs: [...new Set(project.i18n.catalogs)],
684
+ directory: project.i18n.directory ?? "locales",
685
+ locales: [...new Set(project.i18n.locales)]
686
+ };
687
+ const catalogs = await this.catalogModule();
688
+ switch (method) {
689
+ case "i18n.catalogs.open":
690
+ if (args.legacyPo === true) {
691
+ this.po ??= importProjectDependency("@lingui/format-po", process.cwd()).then((module) => module.formatter({ lineNumbers: false }));
692
+ await this.po;
693
+ }
694
+ return null;
695
+ case "i18n.catalogs.collectMissing": {
696
+ if (this.requests.size >= 4) throw new RpcError(-32602, "Too many outstanding translation requests");
697
+ const messages = await catalogs.collectMissingTranslations({
698
+ config,
699
+ cwd: process.cwd()
700
+ });
701
+ const directory = await mkdtemp(join(tmpdir(), "coreframe-i18n-request-"));
702
+ if (this.disposed) {
703
+ await rm(directory, {
704
+ recursive: true,
705
+ force: true
706
+ });
707
+ throw new Error("The i18n session disconnected during catalog inspection");
708
+ }
709
+ const resource = randomUUID();
710
+ const path = join(directory, "request.json");
711
+ this.requests.set(resource, {
712
+ directory,
713
+ messages
714
+ });
715
+ await writeFile(path, JSON.stringify({
716
+ messages,
717
+ sourceLocale: config.sourceLocale,
718
+ version: 1
719
+ }), {
720
+ flag: "wx",
721
+ mode: 384
722
+ });
723
+ return {
724
+ resource,
725
+ path,
726
+ count: messages.length
727
+ };
728
+ }
729
+ case "i18n.catalogs.applyTranslations": {
730
+ const request = typeof args.resource === "string" ? this.requests.get(args.resource) : void 0;
731
+ if (!request || typeof args.response !== "string" || (await stat(args.response)).size > 10 * 1024 * 1024) throw new RpcError(-32602, "Invalid translation request resource or response file");
732
+ await catalogs.applyGeneratedTranslations({
733
+ config,
734
+ cwd: process.cwd(),
735
+ missing: request.messages,
736
+ response: catalogs.parseTranslationResponse(await readFile(args.response, "utf8"))
737
+ });
738
+ this.requests.delete(args.resource);
739
+ await rm(request.directory, {
740
+ recursive: true,
741
+ force: true
742
+ });
743
+ return null;
744
+ }
745
+ case "i18n.catalogs.assertComplete":
746
+ for (const locale of config.locales) for (const catalog of config.catalogs) await catalogs.readRichCatalog(resolve(process.cwd(), config.directory, locale, catalog + ".json"));
747
+ await catalogs.assertCompleteCatalogs({
748
+ config,
749
+ cwd: process.cwd()
750
+ });
751
+ return null;
752
+ case "i18n.catalogs.importPo": {
753
+ if (!this.po || typeof args.source !== "string" || typeof args.target !== "string") throw new RpcError(-32602, "Open the PO integration and provide catalog paths");
754
+ const target = resolve(args.target);
755
+ const locale = config.locales.find((locale) => config.catalogs.some((catalog) => target === resolve(process.cwd(), config.directory, locale, catalog + ".json")));
756
+ if (!locale) throw new RpcError(-32602, "PO imports require a configured catalog target");
757
+ await catalogs.writeRichCatalog(target, await (await this.po).parse(await readFile(args.source, "utf8"), {
758
+ locale,
759
+ sourceLocale: config.sourceLocale,
760
+ filename: args.source
761
+ }));
762
+ return null;
763
+ }
764
+ default: throw new RpcError(-32601, "Unsupported i18n catalog operation");
765
+ }
766
+ }
767
+ async dispose() {
768
+ this.disposed = true;
769
+ const requests = [...this.requests.values()];
770
+ this.requests.clear();
771
+ await Promise.all(requests.map(({ directory }) => rm(directory, {
772
+ recursive: true,
773
+ force: true
774
+ })));
775
+ }
776
+ };
777
+ //#endregion
778
+ //#region src/maintenance.ts
779
+ /** Native backup/SQL handles only; Go owns ordering, leases and recovery policy. */
780
+ var MaintenanceServices = class {
781
+ resource;
782
+ async open(dialect, configured) {
783
+ if (this.resource || dialect !== "postgres" && dialect !== "sqlite" || dialect !== configured) throw new RpcError(-32602, "Invalid local maintenance dialect or existing resource");
784
+ const connection = new URL(process.env.DATABASE_URL ?? "");
785
+ if (![
786
+ "127.0.0.1",
787
+ "localhost",
788
+ "[::1]"
789
+ ].includes(connection.hostname)) throw new RpcError(-32602, "Database maintenance requires a managed loopback connection");
790
+ const resource = {
791
+ id: randomUUID(),
792
+ dialect,
793
+ database: ""
794
+ };
795
+ if (dialect === "sqlite") {
796
+ if (process.env.COREFRAME_LOCAL_TURSO !== "1" || connection.protocol !== "http:" || !process.env.TURSO_AUTH_TOKEN || process.env.TURSO_DATABASE_URL !== process.env.DATABASE_URL) throw new RpcError(-32602, "SQLite maintenance requires managed local authentication");
797
+ const { createClient } = await importProjectDependency("@libsql/client");
798
+ const client = createClient({
799
+ url: connection.href,
800
+ authToken: process.env.TURSO_AUTH_TOKEN
801
+ });
802
+ try {
803
+ await client.execute("select 1");
804
+ } finally {
805
+ client.close();
806
+ }
807
+ await confinedFile(".coreframe/turso.db");
808
+ } else {
809
+ if (process.env.COREFRAME_LOCAL_POSTGRES !== "1" || connection.protocol !== "postgresql:") throw new RpcError(-32602, "PostgreSQL maintenance requires a managed local database");
810
+ if (await realpath(process.env.PGDATA ?? "") !== await realpath(resolve(".coreframe/postgres"))) throw new RpcError(-32602, "PostgreSQL maintenance requires this project's data directory");
811
+ resource.database = decodeURIComponent(connection.pathname.slice(1));
812
+ if (!resource.database || resource.database !== process.env.PGDATABASE) throw new RpcError(-32602, "PostgreSQL maintenance database identity is inconsistent");
813
+ connection.pathname = resource.database === "postgres" ? "/template1" : "/postgres";
814
+ const { Client } = await loadPostgres();
815
+ const client = new Client({
816
+ connectionString: connection.href,
817
+ connectionTimeoutMillis: 1e4,
818
+ statement_timeout: 15e3,
819
+ query_timeout: 16e3
820
+ });
821
+ try {
822
+ await client.connect();
823
+ } catch {
824
+ await client.end().catch(() => {});
825
+ throw new Error("Could not connect to local PostgreSQL maintenance");
826
+ }
827
+ resource.client = client;
828
+ }
829
+ this.resource = resource;
830
+ return {
831
+ resource: resource.id,
832
+ database: resource.database
833
+ };
834
+ }
835
+ async handle(method, args) {
836
+ const resource = this.resource;
837
+ if (!resource || args.resource !== resource.id) throw new RpcError(-32602, "Unknown maintenance resource");
838
+ if (method === "maintenance.close") {
839
+ this.resource = void 0;
840
+ await resource.client?.end();
841
+ return null;
842
+ }
843
+ if (method === "maintenance.sqlite.copy") {
844
+ if (resource.dialect !== "sqlite" || typeof args.source !== "string" || typeof args.target !== "string" || args.source === args.target) throw new RpcError(-32602, "Invalid SQLite backup endpoints");
845
+ const live = ".coreframe/turso.db";
846
+ if (args.source !== live && args.target !== live || !sqlitePath(args.source) || !sqlitePath(args.target)) throw new RpcError(-32602, "SQLite backup endpoints must be project-scoped managed files");
847
+ const source = await confinedFile(args.source);
848
+ const target = await confinedFile(args.target);
849
+ const targetInfo = await lstat(target, { bigint: true });
850
+ if (args.target !== live && targetInfo.size !== 0n) throw new RpcError(-32602, "A new SQLite backup target must be an empty reserved file");
851
+ const held = await open(target, constants.O_RDWR | (constants.O_NOFOLLOW ?? 0));
852
+ const heldInfo = await held.stat({ bigint: true });
853
+ if (heldInfo.dev !== targetInfo.dev || heldInfo.ino !== targetInfo.ino) {
854
+ await held.close();
855
+ throw new RpcError(-32602, "SQLite backup target changed");
856
+ }
857
+ const { backup, DatabaseSync } = await import("node:sqlite");
858
+ let database;
859
+ try {
860
+ database = new DatabaseSync(source, {
861
+ readOnly: true,
862
+ timeout: 5e3
863
+ });
864
+ const checked = database.prepare("pragma quick_check").get();
865
+ if (!checked || Object.values(checked)[0] !== "ok") throw new Error("Source SQLite integrity could not be confirmed");
866
+ await backup(database, target, { rate: 128 });
867
+ const after = await lstat(target, { bigint: true });
868
+ if (after.dev !== heldInfo.dev || after.ino !== heldInfo.ino) throw new Error("SQLite backup target identity changed");
869
+ await held.sync();
870
+ const verify = new DatabaseSync(target, {
871
+ readOnly: true,
872
+ timeout: 5e3
873
+ });
874
+ try {
875
+ const row = verify.prepare("pragma quick_check").get();
876
+ if (!row || Object.values(row)[0] !== "ok") throw new Error("SQLite backup integrity could not be confirmed");
877
+ } finally {
878
+ verify.close();
879
+ }
880
+ return null;
881
+ } finally {
882
+ database?.close();
883
+ await held.close();
884
+ }
885
+ }
886
+ if (method === "maintenance.postgres.control") {
887
+ const client = resource.client;
888
+ if (!client || resource.dialect !== "postgres" || typeof args.name !== "string" || !databaseName(args.name, resource.database)) throw new RpcError(-32602, "Invalid local PostgreSQL control target");
889
+ const name = quote(args.name);
890
+ switch (args.action) {
891
+ case "cluster": return (await client.query("select system_identifier::text as id from pg_control_system()")).rows[0] ?? null;
892
+ case "state": return (await client.query("select oid::text as oid, datallowconn as allowed from pg_database where datname=$1", [args.name])).rows[0] ?? null;
893
+ case "allow":
894
+ if (typeof args.allowed !== "boolean") throw new RpcError(-32602, "Invalid connection state");
895
+ await client.query(`alter database ${name} with allow_connections ${args.allowed ? "true" : "false"}`);
896
+ return null;
897
+ case "terminate":
898
+ await client.query("select pg_terminate_backend(pid) from pg_stat_activity where datname=$1 and pid<>pg_backend_pid()", [args.name]);
899
+ return null;
900
+ case "clone":
901
+ if (args.source !== resource.database || args.name === resource.database || !backupName(args.name)) throw new RpcError(-32602, "Invalid local PostgreSQL snapshot source");
902
+ await client.query(`create database ${name} with template ${quote(resource.database)}`);
903
+ return null;
904
+ case "rename":
905
+ if (typeof args.target !== "string" || !databaseName(args.target, resource.database) || !(args.name === resource.database && failedName(args.target) || backupName(args.name) && args.target === resource.database || failedName(args.name) && args.target === resource.database)) throw new RpcError(-32602, "Invalid local PostgreSQL recovery rename");
906
+ await client.query(`alter database ${name} rename to ${quote(args.target)}`);
907
+ return null;
908
+ case "drop":
909
+ if (args.name === resource.database || !backupName(args.name) || typeof args.oid !== "string") throw new RpcError(-32602, "Only a confirmed managed backup can be discarded");
910
+ if ((await client.query("select oid::text as oid from pg_database where datname=$1", [args.name])).rows[0]?.oid !== args.oid) throw new RpcError(-32602, "Backup identity changed; it was preserved");
911
+ await client.query(`drop database ${name}`);
912
+ return null;
913
+ }
914
+ }
915
+ throw new RpcError(-32601, "Unsupported local maintenance operation");
916
+ }
917
+ async dispose() {
918
+ const resource = this.resource;
919
+ this.resource = void 0;
920
+ await resource?.client?.end().catch(() => {});
921
+ }
922
+ };
923
+ const backupName = (name) => /^coreframe_backup_[a-z0-9]{16,32}$/.test(name);
924
+ const failedName = (name) => /^coreframe_failed_[a-z0-9]{16,32}$/.test(name);
925
+ const databaseName = (name, main) => name === main || backupName(name) || failedName(name);
926
+ const quote = (name) => `"${name.replaceAll("\"", "\"\"")}"`;
927
+ const sqlitePath = (name) => name === ".coreframe/turso.db" || /^\.coreframe\/managed-dev-backups\/(go\/)?[A-Za-z0-9_-]{8,128}\/(snapshot|failed|failed-[a-z0-9]{16,32})\.sqlite$/.test(name);
928
+ async function confinedFile(name) {
929
+ if (isAbsolute(name) || name.includes("\\") || name.includes("\0") || name.split("/").some((part) => !part || part === "." || part === "..")) throw new RpcError(-32602, "Invalid managed file path");
930
+ const root = await realpath(process.cwd());
931
+ const absolute = resolve(root, name);
932
+ const local = relative(root, absolute);
933
+ if (local === ".." || local.startsWith(`..${sep}`) || isAbsolute(local)) throw new RpcError(-32602, "Managed file escaped the project");
934
+ const parts = name.split("/");
935
+ for (let index = 1; index <= parts.length; index++) {
936
+ const info = await lstat(resolve(root, ...parts.slice(0, index)));
937
+ if (info.isSymbolicLink() || (index === parts.length ? !info.isFile() : !info.isDirectory())) throw new RpcError(-32602, "Managed file must have regular, unlinked parents");
938
+ }
939
+ return absolute;
940
+ }
941
+ async function loadPostgres() {
942
+ let entry;
943
+ try {
944
+ entry = resolve$1("pg", pathToFileURL(resolve("package.json")).href);
945
+ } catch (error) {
946
+ if (!isRecord(error) || error.code !== "ERR_MODULE_NOT_FOUND" || typeof error.message !== "string" || !error.message.startsWith("Cannot find package 'pg' imported from ")) throw error;
947
+ entry = resolve$1("pg", import.meta.url);
948
+ }
949
+ return await import(entry);
950
+ }
951
+ //#endregion
952
+ //#region src/managed-resolution.ts
953
+ /** Parse prepared source without evaluating application configuration or code. */
954
+ async function validateResolution(paths) {
955
+ if (!Array.isArray(paths) || paths.length > 1e5 || paths.some((path) => typeof path !== "string" || !path || path.includes("\0"))) throw new RpcError(-32602, "Resolution paths must be relative file names");
956
+ const root = await realpath(process.cwd());
957
+ const diagnostics = [];
958
+ const contained = (path) => {
959
+ const name = relative(root, path);
960
+ return name !== ".." && !name.startsWith(`..${sep}`) && !isAbsolute(name);
961
+ };
962
+ for (const path of new Set(paths)) {
963
+ const file = resolve(root, path);
964
+ if (isAbsolute(path) || !contained(file) || path.split(/[\\/]/).some((part) => part.toLowerCase() === ".git")) throw new RpcError(-32602, "Resolution path is outside the worktree");
965
+ const stat = await lstat(file).catch((error) => {
966
+ if (error.code !== "ENOENT") throw error;
967
+ });
968
+ if (!stat?.isFile()) continue;
969
+ if (!contained(await realpath(file))) throw new RpcError(-32602, "Resolution path is outside the worktree");
970
+ const handle = await open(file, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
971
+ try {
972
+ const current = await handle.stat();
973
+ if (!current.isFile() || current.dev !== stat.dev || current.ino !== stat.ino) throw new Error("Resolution file changed during validation");
974
+ if (current.size > 16 * 1024 * 1024) throw new Error("Resolved source exceeds the 16 MiB validation limit");
975
+ const { errors } = parseSync(path, await handle.readFile("utf8"), { showSemanticErrors: false });
976
+ if (errors.length) diagnostics.push({
977
+ path,
978
+ message: errors.map((error) => error.message).join("; ").slice(0, 4096)
979
+ });
980
+ } finally {
981
+ await handle.close();
982
+ }
983
+ if (diagnostics.length >= 100) break;
984
+ }
985
+ return { diagnostics };
986
+ }
987
+ //#endregion
988
+ //#region src/postgres.ts
989
+ /** Keeps the local-postgres library handle behind a Go-owned service lifetime. */
990
+ var PostgresServices = class {
991
+ peer;
992
+ resources = /* @__PURE__ */ new Map();
993
+ disposed = false;
994
+ constructor(peer) {
995
+ this.peer = peer;
996
+ }
997
+ async start(config, temporary = false, recovery = false) {
998
+ if (this.disposed || this.resources.size > 0) throw new RpcError(-32602, "This bridge already owns a PostgreSQL service");
999
+ if ((config.database?.dialect ?? "postgres") !== "postgres") throw new RpcError(-32602, "The requested service does not match the project database dialect");
1000
+ const { startProjectPostgres, startTemporaryProjectPostgres, startProjectPostgresForRecovery } = await import("@coreframe/db");
1001
+ const id = randomUUID();
1002
+ const output = new PostgresOutput(this.peer);
1003
+ const resource = {
1004
+ id,
1005
+ output,
1006
+ temporary,
1007
+ sidecar: (temporary ? startTemporaryProjectPostgres : recovery ? startProjectPostgresForRecovery : startProjectPostgres)({
1008
+ config,
1009
+ cwd: process.cwd(),
1010
+ env: process.env,
1011
+ useSupervisorLease: false,
1012
+ postgresOutput: output
1013
+ })
1014
+ };
1015
+ this.resources.set(id, resource);
1016
+ try {
1017
+ const sidecar = await resource.sidecar;
1018
+ if (this.disposed) {
1019
+ await this.stop(id);
1020
+ throw new Error("PostgreSQL service bridge disconnected during startup");
1021
+ }
1022
+ const pid = await readPid(sidecar.env.PGDATA);
1023
+ if (!pid) throw new Error("Local PostgreSQL did not publish its process identity");
1024
+ let checking = false;
1025
+ resource.timer = setInterval(() => {
1026
+ if (checking || resource.stopping) return;
1027
+ checking = true;
1028
+ readPid(sidecar.env.PGDATA).then((current) => {
1029
+ if (current !== pid && resource.timer) {
1030
+ clearInterval(resource.timer);
1031
+ resource.timer = void 0;
1032
+ this.peer.call("service.postgres.failed", { resource: id }).catch(() => {});
1033
+ }
1034
+ }).finally(() => {
1035
+ checking = false;
1036
+ });
1037
+ }, 1e3);
1038
+ resource.timer.unref();
1039
+ return {
1040
+ resource: id,
1041
+ env: sidecar.env,
1042
+ pid,
1043
+ temporary
1044
+ };
1045
+ } catch (error) {
1046
+ await this.stop(id).catch(() => {});
1047
+ throw error;
1048
+ }
1049
+ }
1050
+ async stop(id) {
1051
+ const resource = this.require(id);
1052
+ resource.stopping ??= (async () => {
1053
+ if (resource.timer) clearInterval(resource.timer);
1054
+ try {
1055
+ await (await resource.sidecar)[Symbol.asyncDispose]();
1056
+ } finally {
1057
+ this.resources.delete(id);
1058
+ }
1059
+ })();
1060
+ await resource.stopping;
1061
+ }
1062
+ async park(id) {
1063
+ const resource = this.require(id);
1064
+ if (resource.temporary) throw new RpcError(-32602, "A temporary PostgreSQL database cannot be parked");
1065
+ if (resource.stopping) throw new RpcError(-32602, "PostgreSQL service is stopping");
1066
+ if (resource.timer) clearInterval(resource.timer);
1067
+ await resource.output.park();
1068
+ this.resources.delete(id);
1069
+ return {
1070
+ resource: id,
1071
+ parked: true
1072
+ };
1073
+ }
1074
+ async dispose() {
1075
+ this.disposed = true;
1076
+ if ((await Promise.allSettled([...this.resources.keys()].map((id) => this.stop(id)))).some((result) => result.status === "rejected")) console.error("Could not stop a local PostgreSQL service during bridge disposal.");
1077
+ }
1078
+ require(id) {
1079
+ const resource = this.resources.get(id);
1080
+ if (!resource) throw new RpcError(-32602, "Unknown PostgreSQL service resource");
1081
+ return resource;
1082
+ }
1083
+ };
1084
+ var PostgresOutput = class extends Writable {
1085
+ peer;
1086
+ parked = false;
1087
+ constructor(peer) {
1088
+ super();
1089
+ this.peer = peer;
1090
+ this.on("error", () => {});
1091
+ }
1092
+ _write(chunk, _encoding, callback) {
1093
+ (this.parked ? this.writeParked(chunk) : this.peer.call("service.postgres.log", { data: chunk.toString("utf8") })).then(() => callback(), () => callback(/* @__PURE__ */ new Error("Could not write PostgreSQL service output")));
1094
+ }
1095
+ async park() {
1096
+ this.parked = true;
1097
+ await new Promise((accept, reject) => this.write(Buffer.alloc(0), (error) => error ? reject(error) : accept()));
1098
+ }
1099
+ async writeParked(chunk) {
1100
+ if (chunk.length === 0) return;
1101
+ const file = resolve(".coreframe/dev-supervisor/logs/postgres.log");
1102
+ const tail = chunk.subarray(Math.max(0, chunk.length - 1024 * 1024));
1103
+ for (const directory of [
1104
+ ".coreframe",
1105
+ ".coreframe/dev-supervisor",
1106
+ ".coreframe/dev-supervisor/logs"
1107
+ ]) if (!(await lstat(directory)).isDirectory()) throw new Error("PostgreSQL log directory is not a regular project directory");
1108
+ const before = await lstat(file);
1109
+ if (!before.isFile()) throw new Error("PostgreSQL log is not a regular project file");
1110
+ const handle = await open(file, constants.O_WRONLY | constants.O_APPEND | (constants.O_NOFOLLOW ?? 0));
1111
+ try {
1112
+ const current = await handle.stat();
1113
+ if (current.dev !== before.dev || current.ino !== before.ino) throw new Error("PostgreSQL log changed while opening it");
1114
+ if (current.size + tail.length > 1024 * 1024) await handle.truncate(0);
1115
+ await handle.write(tail);
1116
+ } finally {
1117
+ await handle.close();
1118
+ }
1119
+ }
1120
+ };
1121
+ async function readPid(directory) {
1122
+ if (!directory) return;
1123
+ try {
1124
+ const pid = Number((await readFile(resolve(directory, "postmaster.pid"), "utf8")).split(/\r?\n/)[0]);
1125
+ if (!Number.isSafeInteger(pid) || pid < 1) return;
1126
+ process.kill(pid, 0);
1127
+ return pid;
1128
+ } catch {
1129
+ return;
1130
+ }
1131
+ }
1132
+ function postgresResource(args) {
1133
+ if (!isRecord(args) || typeof args.resource !== "string") throw new RpcError(-32602, "A PostgreSQL service resource is required");
1134
+ return args.resource;
1135
+ }
1136
+ //#endregion
1137
+ //#region src/preview-credentials.ts
1138
+ /** Only Coreframe's existing preview credential namespaces are addressable. */
1139
+ async function previewCredentials(method, args) {
1140
+ if (args.kind !== "account" && args.kind !== "tunnel" || typeof args.profile !== "string" || !/^[a-z0-9][a-z0-9._-]*$/u.test(args.profile) || args.kind === "tunnel" && (typeof args.name !== "string" || !args.name.trim()) || method === "preview.credentials.write" && typeof args.value !== "string") throw new RpcError(-32602, "Invalid preview credential operation");
1141
+ const service = `dev.coreframe.preview.cloudflare.${args.kind}`;
1142
+ const account = args.kind === "account" ? args.profile : `${args.profile}/${args.name}`;
1143
+ try {
1144
+ const { AsyncEntry } = await import("@napi-rs/keyring");
1145
+ const entry = new AsyncEntry(service, account);
1146
+ if (method === "preview.credentials.read") return { value: await entry.getPassword() ?? null };
1147
+ await entry.setPassword(args.value);
1148
+ return { stored: true };
1149
+ } catch {
1150
+ throw new Error("Could not access Coreframe preview credentials in the operating system credential store. Verify credential-store access before retrying.");
1151
+ }
1152
+ }
1153
+ //#endregion
1154
+ //#region src/dashboard.ts
1155
+ function dashboardBuildPlan(config, mode) {
1156
+ const enabled = config.deploy?.mode !== "client" && config.dashboard?.enabled !== false;
1157
+ return {
1158
+ enabled,
1159
+ output: ".coreframe/dashboard-build",
1160
+ commands: enabled ? [{
1161
+ cwd: "dashboard",
1162
+ tool: "bamboo",
1163
+ args: ["cssgen"]
1164
+ }, {
1165
+ cwd: "dashboard",
1166
+ tool: "vite",
1167
+ args: ["build", ...mode ? ["--mode", mode] : []]
1168
+ }] : []
1169
+ };
1170
+ }
1171
+ function dashboardDevCommand(port) {
1172
+ return {
1173
+ cwd: "dashboard",
1174
+ tool: "vite",
1175
+ args: [
1176
+ "--host",
1177
+ "127.0.0.1",
1178
+ "--port",
1179
+ String(port)
1180
+ ],
1181
+ env: { NODE_OPTIONS: `${process.env.NODE_OPTIONS ?? ""} --conditions=development`.trim() }
1182
+ };
1183
+ }
1184
+ //#endregion
1185
+ //#region src/deployment-secrets.ts
1186
+ const dashboardPassword = process.env.DASHBOARD_PASSWORD;
1187
+ /** Selects the installed app's local inputs for Worker secret publication. */
1188
+ async function prepareLocalSecrets(config, environment, queuedNames) {
1189
+ if (config.dashboard?.enabled === false || queuedNames.includes("DASHBOARD_PASSWORD")) return {};
1190
+ let password = dashboardPassword?.trim();
1191
+ if (!password) {
1192
+ let contents;
1193
+ try {
1194
+ contents = await readFile(".env", "utf8");
1195
+ } catch (error) {
1196
+ if (!(error instanceof Error && "code" in error && error.code === "ENOENT")) throw new Error("Could not read .env while preparing the dashboard password.");
1197
+ contents = "";
1198
+ }
1199
+ try {
1200
+ password = parseEnv(contents).DASHBOARD_PASSWORD?.trim();
1201
+ } catch {
1202
+ throw new Error("Could not parse .env while preparing the dashboard password.");
1203
+ }
1204
+ }
1205
+ if (!password) throw new Error(`Missing ${environment} dashboard password. Set DASHBOARD_PASSWORD in ".env".`);
1206
+ return { DASHBOARD_PASSWORD: password };
1207
+ }
1208
+ //#endregion
1209
+ //#region src/development.ts
1210
+ function describeDevelopment(config, _debug) {
1211
+ return {
1212
+ dashboard: config.dashboard?.enabled !== false,
1213
+ dashboardConfig: "dashboard/dashboard.config.ts",
1214
+ web: {
1215
+ tool: "vite",
1216
+ env: {
1217
+ CLOUDFLARE_ENV: "development",
1218
+ NODE_OPTIONS: `${process.env.NODE_OPTIONS ?? ""} --conditions=development`.trim()
1219
+ }
1220
+ },
1221
+ hostFlag: "--host",
1222
+ portFlag: "--port",
1223
+ strictArgs: ["--strictPort"],
1224
+ watcher: {
1225
+ label: "bamboo",
1226
+ tool: "pnpm",
1227
+ args: [
1228
+ "exec",
1229
+ "bamboo",
1230
+ "--watch"
1231
+ ]
1232
+ }
1233
+ };
1234
+ }
1235
+ //#endregion
1236
+ //#region src/typecheck.ts
1237
+ const projects = [
1238
+ "scripts/tsconfig.json",
1239
+ "src/shared/tsconfig.json",
1240
+ "src/api/tsconfig.json",
1241
+ "src/api/worker/tsconfig.json",
1242
+ "src/web/tsconfig.json",
1243
+ "dashboard/tsconfig.json"
1244
+ ];
1245
+ function typecheckPlan() {
1246
+ return projects.map((path) => ({
1247
+ requiresPath: path,
1248
+ tool: "pnpm",
1249
+ args: [
1250
+ "exec",
1251
+ "tsc",
1252
+ "-p",
1253
+ path
1254
+ ]
1255
+ }));
1256
+ }
1257
+ //#endregion
1258
+ //#region src/project-tooling.ts
1259
+ const builtIn = {
1260
+ dashboardBuildPlan,
1261
+ dashboardDevCommand,
1262
+ describeDevelopment,
1263
+ prepareLocalSecrets,
1264
+ typecheckPlan
1265
+ };
1266
+ async function loadProjectTooling() {
1267
+ const require = createRequire(resolve("package.json"));
1268
+ let file;
1269
+ try {
1270
+ file = require.resolve("@coreframe/scripts/tooling");
1271
+ } catch (error) {
1272
+ if (error instanceof Error && "code" in error && (error.code === "ERR_PACKAGE_PATH_NOT_EXPORTED" || error.code === "MODULE_NOT_FOUND" && !("path" in error))) return builtIn;
1273
+ throw error;
1274
+ }
1275
+ const adapter = await import(pathToFileURL(file).href);
1276
+ if (adapter.version !== 1 || !adapter.tools || !Object.keys(builtIn).every((name) => typeof adapter.tools?.[name] === "function")) throw new Error("The installed Coreframe project tooling adapter is incompatible with this bridge.");
1277
+ return adapter.tools;
1278
+ }
1279
+ //#endregion
1280
+ //#region src/reviewer.ts
1281
+ /** Retains application code and identity; Go owns policy and stage admission. */
1282
+ var DeploymentReviewer = class {
1283
+ resource;
1284
+ async open(args) {
1285
+ const inputs = args.inputs;
1286
+ if (this.resource || typeof args.entrypoint !== "string" || !args.entrypoint.trim() || !isRecord(inputs) || !["staging", "production"].includes(String(inputs.environment)) || !["postgres", "sqlite"].includes(String(inputs.dialect)) || [
1287
+ "url",
1288
+ "email",
1289
+ "password"
1290
+ ].some((key) => typeof inputs[key] !== "string") || !isRecord(inputs.env) || Object.values(inputs.env).some((value) => typeof value !== "string")) throw new RpcError(-32602, "Invalid reviewer inputs or existing reviewer resource");
1291
+ const id = randomUUID();
1292
+ this.resource = {
1293
+ id,
1294
+ module: {},
1295
+ inputs,
1296
+ original: {
1297
+ environment: inputs.environment,
1298
+ url: inputs.url
1299
+ },
1300
+ stage: "opening"
1301
+ };
1302
+ try {
1303
+ const module = await importProjectModule(args.entrypoint);
1304
+ if (![
1305
+ module.validate,
1306
+ module.provision,
1307
+ module.verify
1308
+ ].every((fn) => typeof fn === "function")) throw new Error("Invalid reviewer module");
1309
+ this.resource.module = module;
1310
+ this.resource.stage = "opened";
1311
+ return { reviewer: id };
1312
+ } catch {
1313
+ this.resource.stage = "failed";
1314
+ throw new RpcError(-32020, "Reviewer module loading failed. Secret details suppressed.");
1315
+ }
1316
+ }
1317
+ async run(method, args) {
1318
+ const resource = this.resource;
1319
+ const expected = {
1320
+ "deploy.reviewer.validate": "opened",
1321
+ "deploy.reviewer.provision": "validated",
1322
+ "deploy.reviewer.verify": "provisioned"
1323
+ }[method];
1324
+ if (!resource || resource.id !== args.reviewer || !expected || resource.stage !== expected) throw new RpcError(-32602, "Invalid reviewer resource or stage; no action was repeated");
1325
+ let context;
1326
+ if (method === "deploy.reviewer.provision") {
1327
+ const value = args.context;
1328
+ if (!isRecord(value) || value.environment !== resource.original.environment || value.url !== resource.original.url || ["releaseName", "version"].some((key) => typeof value[key] !== "string")) throw new RpcError(-32602, "Reviewer deployment context changed after validation");
1329
+ context = value;
1330
+ }
1331
+ resource.stage = "running";
1332
+ try {
1333
+ if (method === "deploy.reviewer.validate") {
1334
+ await resource.module.validate(resource.inputs);
1335
+ resource.stage = "validated";
1336
+ } else if (method === "deploy.reviewer.provision") {
1337
+ resource.context = {
1338
+ ...context,
1339
+ ...resource.inputs
1340
+ };
1341
+ const identity = await resource.module.provision(resource.context);
1342
+ if (!identity?.userId) throw new Error("Missing reviewer identity");
1343
+ resource.identity = identity;
1344
+ resource.stage = "provisioned";
1345
+ } else {
1346
+ await resource.module.verify(resource.context, resource.identity);
1347
+ resource.stage = "verified";
1348
+ }
1349
+ return null;
1350
+ } catch {
1351
+ resource.stage = "failed";
1352
+ throw new RpcError(-32020, "Reviewer application operation failed. Secret details suppressed.");
1353
+ }
1354
+ }
1355
+ dispose() {
1356
+ this.resource = void 0;
1357
+ }
1358
+ };
1359
+ //#endregion
1360
+ //#region src/session.ts
1361
+ const callbackPaths = /* @__PURE__ */ new Set([
1362
+ "config.deploy.afterDeploy",
1363
+ "config.deploy.afterWorkerDeploy",
1364
+ "config.deploy.beforeDeploy",
1365
+ "config.preview.access.bypass.ips"
1366
+ ]);
1367
+ /** Application modules and closures are retained for one application workflow. */
1368
+ var ApplicationSession = class {
1369
+ peer;
1370
+ config;
1371
+ tooling;
1372
+ hooks;
1373
+ previewDescribed = false;
1374
+ previewConfigured = false;
1375
+ runtimeStarted = false;
1376
+ root;
1377
+ queue = Promise.resolve();
1378
+ disposers = /* @__PURE__ */ new Map();
1379
+ disposed = false;
1380
+ postgres;
1381
+ databases = new DatabaseServices();
1382
+ maintenance = new MaintenanceServices();
1383
+ i18n = new I18nServices();
1384
+ assets = new AssetServices();
1385
+ developmentLogs = new DevelopmentLogs();
1386
+ reviewer = new DeploymentReviewer();
1387
+ deployArtifacts = new DeployArtifacts();
1388
+ constructor(peer) {
1389
+ this.peer = peer;
1390
+ this.postgres = new PostgresServices(peer);
1391
+ }
1392
+ async handle(method, params, context) {
1393
+ if (this.disposed) throw new Error("Application session is closed");
1394
+ if (context && context === this.root) return this.execute(method, params);
1395
+ const next = this.queue.then(async () => {
1396
+ this.root = context;
1397
+ try {
1398
+ return await this.execute(method, params);
1399
+ } finally {
1400
+ this.root = void 0;
1401
+ }
1402
+ });
1403
+ this.queue = next.catch(() => {});
1404
+ return next;
1405
+ }
1406
+ readConfig() {
1407
+ return this.config ??= readProjectConfig();
1408
+ }
1409
+ projectTooling() {
1410
+ return this.tooling ??= loadProjectTooling();
1411
+ }
1412
+ async dispose() {
1413
+ this.disposed = true;
1414
+ this.reviewer.dispose();
1415
+ this.developmentLogs.dispose();
1416
+ await this.postgres.dispose();
1417
+ await this.databases.dispose();
1418
+ await this.maintenance.dispose();
1419
+ await this.i18n.dispose();
1420
+ const disposers = [...this.disposers.values()];
1421
+ this.disposers.clear();
1422
+ if ((await Promise.allSettled([this.deployArtifacts.dispose(), ...disposers.map((dispose) => dispose())])).some((result) => result.status === "rejected")) console.error("Could not remove a temporary Coreframe configuration file.");
1423
+ }
1424
+ async execute(method, params) {
1425
+ const args = params ?? {};
1426
+ if (!isRecord(args)) throw new RpcError(-32602, "Operation parameters must be an object");
1427
+ if (![
1428
+ "config.read",
1429
+ "preview.describe",
1430
+ "preview.configure",
1431
+ "managed-dev.validateResolution"
1432
+ ].includes(method) && !method.startsWith("environment.")) this.runtimeStarted = true;
1433
+ switch (method) {
1434
+ case "managed-dev.validateResolution": return validateResolution(args.paths);
1435
+ case "deploy.artifact.prepare": return this.deployArtifacts.prepare(args, () => this.readConfig());
1436
+ case "deploy.artifact.close": return this.deployArtifacts.close(args);
1437
+ case "deploy.reviewer.open": return this.reviewer.open(args);
1438
+ case "deploy.reviewer.validate":
1439
+ case "deploy.reviewer.provision":
1440
+ case "deploy.reviewer.verify": return this.reviewer.run(method, args);
1441
+ case "environment.describeUrl":
1442
+ if (typeof args.value !== "string") throw new RpcError(-32602, "A URL string is required");
1443
+ try {
1444
+ const url = new URL(args.value);
1445
+ return {
1446
+ valid: true,
1447
+ protocol: url.protocol,
1448
+ credentialed: Boolean(url.username || url.password)
1449
+ };
1450
+ } catch {
1451
+ return { valid: false };
1452
+ }
1453
+ case "environment.normalizeUrl":
1454
+ if (typeof args.value !== "string") throw new RpcError(-32602, "A URL string is required");
1455
+ try {
1456
+ return { url: new URL(args.value).href };
1457
+ } catch {
1458
+ return { url: null };
1459
+ }
1460
+ case "development.describe":
1461
+ if (args.debug !== void 0 && typeof args.debug !== "string") throw new RpcError(-32602, "Development debug mode must be a string");
1462
+ return (await this.projectTooling()).describeDevelopment(await this.readConfig(), args.debug);
1463
+ case "development.logs.open": return this.developmentLogs.open(args);
1464
+ case "development.logs.write": return this.developmentLogs.write(args);
1465
+ case "development.logs.close": return this.developmentLogs.close(args);
1466
+ case "preview.credentials.read":
1467
+ case "preview.credentials.write": return previewCredentials(method, args);
1468
+ case "assets.media.inspect":
1469
+ case "assets.media.renderRaster": return this.assets.handle(method, args);
1470
+ case "assets.describe":
1471
+ case "assets.storage.open":
1472
+ case "assets.storage.inventory":
1473
+ case "assets.storage.download":
1474
+ case "assets.storage.has":
1475
+ case "assets.storage.uploadSource":
1476
+ case "assets.storage.upload": return this.assets.handle(method, args, await this.readConfig());
1477
+ case "assets.credentials.store": {
1478
+ if (typeof args.profile !== "string" || typeof args.applicationKeyId !== "string" || typeof args.applicationKey !== "string") throw new RpcError(-32602, "An asset profile, application key ID and application key are required");
1479
+ const { assertAssetCredentialProfile, configureAssetCredentials } = await import("@coreframe/object-storage");
1480
+ const profile = assertAssetCredentialProfile(args.profile);
1481
+ try {
1482
+ await configureAssetCredentials({
1483
+ profile,
1484
+ applicationKeyId: args.applicationKeyId,
1485
+ applicationKey: args.applicationKey
1486
+ });
1487
+ } catch {
1488
+ throw new Error(`Could not store asset credential profile "${profile}" in the operating system credential store. Verify credential-store access before retrying.`);
1489
+ }
1490
+ return null;
1491
+ }
1492
+ case "environment.describeHttpsOrigin":
1493
+ if (typeof args.value !== "string") throw new RpcError(-32602, "An HTTPS origin input is required");
1494
+ try {
1495
+ const url = new URL(args.value);
1496
+ if (url.protocol === "https:" && !url.username && !url.password && url.pathname === "/" && !url.search && !url.hash) return { origin: url.origin };
1497
+ } catch {}
1498
+ return { origin: null };
1499
+ case "i18n.catalogs.open":
1500
+ case "i18n.catalogs.collectMissing":
1501
+ case "i18n.catalogs.applyTranslations":
1502
+ case "i18n.catalogs.assertComplete":
1503
+ case "i18n.catalogs.importPo":
1504
+ case "i18n.storage.open":
1505
+ case "i18n.storage.has":
1506
+ case "i18n.storage.download":
1507
+ case "i18n.storage.upload": return this.i18n.handle(method, args, await this.readConfig());
1508
+ case "jobs.describe": return this.databases.describeJobs((await this.readConfig()).jobs?.entry);
1509
+ case "jobs.list":
1510
+ case "jobs.reset": return this.databases.handle(method, args);
1511
+ case "maintenance.open": {
1512
+ if (args.config !== void 0 && (!isRecord(args.config) || !isRecord(args.config.database))) throw new RpcError(-32602, "Invalid local maintenance configuration");
1513
+ const configured = args.config === void 0 ? (await this.readConfig()).database?.dialect ?? "postgres" : args.config.database.dialect;
1514
+ return this.maintenance.open(args.dialect, configured);
1515
+ }
1516
+ case "maintenance.close":
1517
+ case "maintenance.sqlite.copy":
1518
+ case "maintenance.postgres.control": return this.maintenance.handle(method, args);
1519
+ case "db.open": return this.databases.open(args, (await this.readConfig()).database?.dialect ?? "postgres");
1520
+ case "db.close":
1521
+ case "db.readAppliedMigrations":
1522
+ case "db.findSeedUser":
1523
+ case "db.inspectObjects":
1524
+ case "db.clearLocalSchema":
1525
+ case "db.planSchema":
1526
+ case "db.applySchema":
1527
+ case "db.ensureHeldJournal":
1528
+ case "db.readHeldMigration":
1529
+ case "db.applyHeldMigration":
1530
+ case "db.baselineMigrations": return this.databases.handle(method, args);
1531
+ case "service.postgres.start":
1532
+ case "service.postgres.startRecovery":
1533
+ case "service.postgres.startTemporary":
1534
+ if (args.config !== void 0 && args.config !== null && !isRecord(args.config)) throw new RpcError(-32602, "Invalid PostgreSQL service configuration");
1535
+ return this.postgres.start(args.config ?? await this.readConfig(), method === "service.postgres.startTemporary", method === "service.postgres.startRecovery");
1536
+ case "service.postgres.stop":
1537
+ await this.postgres.stop(postgresResource(args));
1538
+ return null;
1539
+ case "service.postgres.park": return this.postgres.park(postgresResource(args));
1540
+ case "worker.describeEnvironment": {
1541
+ if (args.includeStatusInputs !== void 0 && typeof args.includeStatusInputs !== "boolean") throw new RpcError(-32602, "Invalid Worker environment inventory options");
1542
+ const declarations = normalizeWorkerEnvironment((await this.readConfig()).worker?.environment);
1543
+ if (!args.includeStatusInputs) return { declarations };
1544
+ const { readPrimaryWorkerConfig } = await import("@coreframe/deploy");
1545
+ const config = await readPrimaryWorkerConfig();
1546
+ let localOverrides = [];
1547
+ try {
1548
+ localOverrides = Object.entries(parseEnv(await readFile(".env", "utf8"))).filter(([, value]) => Boolean(value?.trim())).map(([name]) => name);
1549
+ } catch (error) {
1550
+ if (!(error instanceof Error && "code" in error && error.code === "ENOENT")) throw new Error("Could not read local Worker environment overrides.");
1551
+ }
1552
+ return {
1553
+ declarations,
1554
+ localOverrides,
1555
+ configuredVariables: Object.fromEntries(["staging", "production"].map((environment) => {
1556
+ const environments = isRecord(config.env) ? config.env : {};
1557
+ const selected = isRecord(environments[environment]) ? environments[environment] : {};
1558
+ return [environment, Object.keys(isRecord(selected.vars) ? selected.vars : {})];
1559
+ }))
1560
+ };
1561
+ }
1562
+ case "environment.parseDotenv":
1563
+ if (typeof args.contents !== "string") throw new RpcError(-32602, "Dotenv contents must be a string");
1564
+ try {
1565
+ return parseEnv(args.contents);
1566
+ } catch {
1567
+ throw new Error("Could not parse the pasted dotenv contents.");
1568
+ }
1569
+ case "worker.readConfig": {
1570
+ const { readPrimaryWorkerConfig } = await import("@coreframe/deploy");
1571
+ return readPrimaryWorkerConfig();
1572
+ }
1573
+ case "typecheck.plan": return (await this.projectTooling()).typecheckPlan();
1574
+ case "worker.prepareTypes": {
1575
+ const coreframeConfig = await this.readConfig();
1576
+ const { materializePrimaryWorkerTypeConfig } = await import("@coreframe/deploy");
1577
+ const materialized = await materializePrimaryWorkerTypeConfig({ coreframeConfig });
1578
+ if (this.disposed) {
1579
+ await materialized.dispose();
1580
+ throw new Error("Application session is closed");
1581
+ }
1582
+ const resource = randomUUID();
1583
+ this.disposers.set(resource, materialized.dispose);
1584
+ const known = wranglerEnvironmentNames(materialized.config);
1585
+ return {
1586
+ resource,
1587
+ path: materialized.path,
1588
+ inventory: normalizeWorkerEnvironment(coreframeConfig.worker?.environment).filter((entry) => !known.has(entry.name)).map(({ name, description }) => ({
1589
+ name,
1590
+ description
1591
+ }))
1592
+ };
1593
+ }
1594
+ case "worker.disposeTypes":
1595
+ if (typeof args.resource !== "string" || !this.disposers.has(args.resource)) throw new RpcError(-32602, "Unknown Worker configuration resource");
1596
+ await this.disposers.get(args.resource)();
1597
+ this.disposers.delete(args.resource);
1598
+ return null;
1599
+ case "dashboard.planBuild":
1600
+ if (args.mode !== void 0 && typeof args.mode !== "string") throw new RpcError(-32602, "Dashboard build mode must be a string");
1601
+ return (await this.projectTooling()).dashboardBuildPlan(await this.readConfig(), args.mode);
1602
+ case "dashboard.planDev": {
1603
+ const { port } = args;
1604
+ if (typeof port !== "number" || !Number.isInteger(port) || port < 1 || port > 65535) throw new RpcError(-32602, "Dashboard development requires a valid upstream port");
1605
+ return (await this.projectTooling()).dashboardDevCommand(port, () => this.readConfig());
1606
+ }
1607
+ case "dashboard.planTypegen": return (await this.projectTooling()).dashboardTypegenCommand?.() ?? null;
1608
+ case "dashboard.describeProxy": return (await this.projectTooling()).dashboardProxyOptions?.() ?? null;
1609
+ case "typegen.planRoutes": return (await this.projectTooling()).routeTypegenPlan?.() ?? null;
1610
+ case "db.held": {
1611
+ const { operation, id, target } = args;
1612
+ if (operation !== "list" && operation !== "inspect" && operation !== "apply" && operation !== "validate" || typeof id !== "string" || target !== "" && target !== "local" && target !== "staging" && target !== "production" || operation === "apply" && !target || operation === "validate" && target) throw new RpcError(-32602, "Invalid held migration operation or target");
1613
+ const tools = await this.projectTooling();
1614
+ if (!tools.heldMigration) throw new Error("The installed project integration does not provide held migration operations.");
1615
+ return tools.heldMigration(operation, id, target);
1616
+ }
1617
+ case "config.read": {
1618
+ const config = await this.readConfig();
1619
+ return {
1620
+ config: projectJson(config, "config"),
1621
+ callbacks: {
1622
+ afterDeploy: typeof config.deploy?.afterDeploy === "function",
1623
+ afterWorkerDeploy: typeof config.deploy?.afterWorkerDeploy === "function",
1624
+ beforeDeploy: typeof config.deploy?.beforeDeploy === "function",
1625
+ resolvePreviewAccessIps: typeof config.preview?.access?.bypass.ips === "function"
1626
+ }
1627
+ };
1628
+ }
1629
+ case "deploy.prepareLocalSecrets": {
1630
+ const { environment, queuedNames } = args;
1631
+ if (environment !== "staging" && environment !== "production" || !Array.isArray(queuedNames) || !queuedNames.every((name) => typeof name === "string")) throw new RpcError(-32602, "Invalid deployment secret selection");
1632
+ return (await this.projectTooling()).prepareLocalSecrets(await this.readConfig(), environment, queuedNames);
1633
+ }
1634
+ case "deploy.afterDeploy":
1635
+ case "deploy.afterWorkerDeploy":
1636
+ case "deploy.beforeDeploy": {
1637
+ const config = await this.readConfig();
1638
+ const name = method === "deploy.afterDeploy" ? "afterDeploy" : method === "deploy.afterWorkerDeploy" ? "afterWorkerDeploy" : "beforeDeploy";
1639
+ const context = deployContext(args);
1640
+ await config.deploy?.[name]?.(context);
1641
+ return null;
1642
+ }
1643
+ case "preview.describe": {
1644
+ const config = await this.readConfig();
1645
+ const tunnel = config.preview?.tunnel;
1646
+ this.previewDescribed = true;
1647
+ return {
1648
+ config: projectJson(config, "config"),
1649
+ resolveAccessIps: typeof config.preview?.access?.bypass.ips === "function",
1650
+ legacyTunnelKeys: tunnel ? [
1651
+ "credentialsFile",
1652
+ "tokenEnv",
1653
+ "tokenFile"
1654
+ ].filter((key) => key in tunnel) : []
1655
+ };
1656
+ }
1657
+ case "preview.configure":
1658
+ if (!this.previewDescribed || this.previewConfigured || this.runtimeStarted) throw new Error("Preview environment must be configured once after discovery and before application operations.");
1659
+ if (!isRecord(args.env) || Object.entries(args.env).some(([name, value]) => !name || name.includes("=") || name.includes("\0") || typeof value !== "string" || value.includes("\0"))) throw new RpcError(-32602, "Invalid preview environment");
1660
+ this.peer.rememberEnvironment(process.env);
1661
+ for (const name of Object.keys(process.env)) delete process.env[name];
1662
+ Object.assign(process.env, args.env);
1663
+ this.peer.rememberEnvironment(process.env);
1664
+ this.previewConfigured = true;
1665
+ return { configured: true };
1666
+ case "preview.describeArtifactPath":
1667
+ if (typeof args.pathname !== "string" || typeof args.origin !== "string") throw new RpcError(-32602, "An artifact pathname and preview origin are required");
1668
+ try {
1669
+ const artifact = new URL(args.pathname, "https://coreframe.invalid");
1670
+ const publicUrl = new URL(args.pathname, `${args.origin.replace(/\/$/u, "")}/`);
1671
+ return {
1672
+ origin: artifact.origin,
1673
+ pathname: artifact.pathname,
1674
+ normalized: posix.normalize(args.pathname),
1675
+ url: publicUrl.href
1676
+ };
1677
+ } catch {
1678
+ return {
1679
+ origin: null,
1680
+ pathname: null,
1681
+ normalized: null,
1682
+ url: null
1683
+ };
1684
+ }
1685
+ case "preview.findArtifactSources": {
1686
+ if (typeof args.source !== "string") throw new RpcError(-32602, "An artifact source pattern is required");
1687
+ const matches = [];
1688
+ for await (const match of glob(args.source, { cwd: process.cwd() })) if ((await stat(resolve(match))).isFile()) matches.push(match);
1689
+ return matches;
1690
+ }
1691
+ case "preview.resolveAccessIps": {
1692
+ const ips = (await this.readConfig()).preview?.access?.bypass.ips;
1693
+ if (typeof ips !== "function") return ips ?? null;
1694
+ if (typeof args.appOrigin !== "string" || typeof args.hostname !== "string" || !isRecord(args.tunnel) || typeof args.tunnel.name !== "string" || typeof args.tunnel.profile !== "string") throw new RpcError(-32602, "Invalid preview access context");
1695
+ return projectJson(await ips(args), "preview.access.ips");
1696
+ }
1697
+ case "db.applyMigrations": {
1698
+ if (!["postgres", "sqlite"].includes(String(args.dialect)) || ((await this.readConfig()).database?.dialect ?? "postgres") !== args.dialect) throw new RpcError(-32602, "Migration dialect does not match the selected project configuration");
1699
+ const { applyProjectMigrations } = await import("@coreframe/db");
1700
+ await applyProjectMigrations({
1701
+ dialect: args.dialect,
1702
+ env: process.env
1703
+ });
1704
+ return null;
1705
+ }
1706
+ case "db.seed": {
1707
+ if (args.profile !== "default" && args.profile !== "large") throw new RpcError(-32602, "Invalid seed profile");
1708
+ const seedEntryPoint = (await this.readConfig()).database?.seed;
1709
+ if (!seedEntryPoint) throw new Error("coreframe.config.ts must configure database.seed before running db seed.");
1710
+ const { runProjectSeed } = await import("@coreframe/db");
1711
+ await runProjectSeed(args.profile, {
1712
+ env: process.env,
1713
+ seedEntryPoint
1714
+ });
1715
+ return null;
1716
+ }
1717
+ case "preview.beforeBuild":
1718
+ case "preview.afterBuild": {
1719
+ const hook = (await (this.hooks ??= loadPreviewHooks()))[method === "preview.beforeBuild" ? "beforeBuild" : "afterBuild"];
1720
+ if (hook) {
1721
+ const preview = this.previewApi(args);
1722
+ try {
1723
+ await hook(preview.api);
1724
+ } finally {
1725
+ await preview.flushReports();
1726
+ }
1727
+ }
1728
+ return null;
1729
+ }
1730
+ default: throw new RpcError(-32601, `Unsupported bridge operation: ${method}`);
1731
+ }
1732
+ }
1733
+ previewApi(args) {
1734
+ if (typeof args.host !== "string" || typeof args.origin !== "string" || typeof args.port !== "number" || !isRecord(args.database) || !["postgres", "sqlite"].includes(String(args.database.dialect))) throw new RpcError(-32602, "Invalid preview API context");
1735
+ const call = (method, params = {}) => this.peer.call(method, params);
1736
+ const reports = [];
1737
+ return {
1738
+ api: {
1739
+ cwd: process.cwd(),
1740
+ env: { ...process.env },
1741
+ host: args.host,
1742
+ origin: args.origin,
1743
+ port: args.port,
1744
+ database: {
1745
+ dialect: args.database.dialect,
1746
+ env: { ...process.env },
1747
+ migrate: () => call("preview.database.migrate"),
1748
+ seed: () => call("preview.database.seed")
1749
+ },
1750
+ build: () => call("preview.build"),
1751
+ report: (label, value) => {
1752
+ const report = call("preview.report", {
1753
+ label,
1754
+ value
1755
+ });
1756
+ report.catch(() => {});
1757
+ reports.push(report);
1758
+ },
1759
+ run: (command, argv = []) => call("preview.run", {
1760
+ command,
1761
+ args: argv
1762
+ }),
1763
+ runScript: (name, argv = []) => call("preview.runScript", {
1764
+ name,
1765
+ args: argv
1766
+ }),
1767
+ serve: () => call("preview.serve"),
1768
+ stageArtifact: (options) => call("preview.stageArtifact", options),
1769
+ url: (pathname = "/") => new URL(pathname, `${args.origin.replace(/\/$/u, "")}/`).href
1770
+ },
1771
+ flushReports: () => Promise.all(reports)
1772
+ };
1773
+ }
1774
+ };
1775
+ function deployContext(args) {
1776
+ if (!["staging", "production"].includes(String(args.environment)) || [
1777
+ "releaseName",
1778
+ "url",
1779
+ "version"
1780
+ ].some((key) => typeof args[key] !== "string")) throw new RpcError(-32602, "Invalid deployment hook context");
1781
+ return args;
1782
+ }
1783
+ async function loadPreviewHooks() {
1784
+ const entry = "scripts/preview.ts";
1785
+ try {
1786
+ await access(resolve(entry));
1787
+ } catch (error) {
1788
+ if (error.code === "ENOENT") return {};
1789
+ throw error;
1790
+ }
1791
+ const module = await importProjectModule(entry);
1792
+ if (!isRecord(module.default)) throw new Error("scripts/preview.ts must default-export preview hooks.");
1793
+ for (const name of ["beforeBuild", "afterBuild"]) if (module.default[name] !== void 0 && typeof module.default[name] !== "function") throw new Error(`scripts/preview.ts ${name} must be a function.`);
1794
+ return module.default;
1795
+ }
1796
+ /** Reject lossy config serialization, except explicitly represented callbacks. */
1797
+ function projectJson(value, path, seen = /* @__PURE__ */ new Set()) {
1798
+ if (value === null || typeof value === "string" || typeof value === "boolean") return value;
1799
+ if (typeof value === "number" && Number.isFinite(value)) return value;
1800
+ if (typeof value === "function" && callbackPaths.has(path)) return;
1801
+ if (typeof value !== "object" || value === null || seen.has(value) || !Array.isArray(value) && Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) throw new Error(`Non-serializable configuration at ${path}`);
1802
+ seen.add(value);
1803
+ try {
1804
+ if (Array.isArray(value)) return value.map((item, index) => projectJson(item, `${path}[${index}]`, seen));
1805
+ const result = Object.create(null);
1806
+ for (const [key, item] of Object.entries(value)) if (item !== void 0) {
1807
+ const projected = projectJson(item, `${path}.${key}`, seen);
1808
+ if (projected !== void 0) result[key] = projected;
1809
+ }
1810
+ return result;
1811
+ } finally {
1812
+ seen.delete(value);
1813
+ }
1814
+ }
1815
+ //#endregion
1816
+ //#region src/runtime.ts
1817
+ const address = process.env.COREFRAME_BRIDGE_ADDRESS;
1818
+ const token = process.env.COREFRAME_BRIDGE_TOKEN;
1819
+ delete process.env.COREFRAME_BRIDGE_ADDRESS;
1820
+ delete process.env.COREFRAME_BRIDGE_TOKEN;
1821
+ if (!address || !token || !/^127\.0\.0\.1:\d+$/.test(address)) throw new Error("The Coreframe Node bridge must be started by the Go CLI.");
1822
+ const socket = createConnection({
1823
+ host: "127.0.0.1",
1824
+ port: Number(address.split(":")[1])
1825
+ });
1826
+ await new Promise((resolve, reject) => {
1827
+ socket.once("connect", resolve);
1828
+ socket.once("error", reject);
1829
+ });
1830
+ const peer = new Peer(socket);
1831
+ const session = new ApplicationSession(peer);
1832
+ peer.setHandler(async (method, params, context) => {
1833
+ try {
1834
+ return await session.handle(method, params, context);
1835
+ } catch (error) {
1836
+ throw await applicationFailure(error, peer);
1837
+ }
1838
+ });
1839
+ try {
1840
+ await peer.call("bridge.hello", {
1841
+ protocolMajor: 1,
1842
+ protocolMinor: 0,
1843
+ bridgeVersion: version,
1844
+ nodeVersion: process.version,
1845
+ token,
1846
+ capabilities: [
1847
+ "managed-dev.validateResolution",
1848
+ "config.read",
1849
+ "dashboard.planBuild",
1850
+ "dashboard.planDev",
1851
+ "dashboard.planTypegen",
1852
+ "dashboard.describeProxy",
1853
+ "typegen.planRoutes",
1854
+ "development.describe",
1855
+ "typecheck.plan",
1856
+ "development.logs.open",
1857
+ "development.logs.write",
1858
+ "development.logs.close",
1859
+ "assets.credentials.store",
1860
+ "assets.describe",
1861
+ "assets.storage.open",
1862
+ "assets.storage.inventory",
1863
+ "assets.storage.download",
1864
+ "assets.storage.has",
1865
+ "assets.storage.upload",
1866
+ "assets.storage.uploadSource",
1867
+ "assets.media.inspect",
1868
+ "assets.media.renderRaster",
1869
+ "environment.describeHttpsOrigin",
1870
+ "i18n.catalogs.open",
1871
+ "i18n.catalogs.collectMissing",
1872
+ "i18n.catalogs.applyTranslations",
1873
+ "i18n.catalogs.assertComplete",
1874
+ "i18n.catalogs.importPo",
1875
+ "i18n.storage.open",
1876
+ "i18n.storage.has",
1877
+ "i18n.storage.download",
1878
+ "i18n.storage.upload",
1879
+ "jobs.describe",
1880
+ "jobs.list",
1881
+ "jobs.reset",
1882
+ "deploy.afterDeploy",
1883
+ "deploy.afterWorkerDeploy",
1884
+ "deploy.beforeDeploy",
1885
+ "deploy.prepareLocalSecrets",
1886
+ "deploy.reviewer.open",
1887
+ "deploy.reviewer.validate",
1888
+ "deploy.reviewer.provision",
1889
+ "deploy.reviewer.verify",
1890
+ "deploy.artifact.prepare",
1891
+ "deploy.artifact.close",
1892
+ "deploy.artifact.preserve-on-disconnect",
1893
+ "environment.describeUrl",
1894
+ "environment.normalizeUrl",
1895
+ "preview.resolveAccessIps",
1896
+ "preview.describe",
1897
+ "preview.configure",
1898
+ "preview.describeArtifactPath",
1899
+ "preview.findArtifactSources",
1900
+ "preview.process-exit-errors",
1901
+ "preview.credentials.read",
1902
+ "preview.credentials.write",
1903
+ "preview.beforeBuild",
1904
+ "preview.afterBuild",
1905
+ "db.seed",
1906
+ "db.applyMigrations",
1907
+ "maintenance.open",
1908
+ "maintenance.config-snapshot",
1909
+ "maintenance.close",
1910
+ "maintenance.sqlite.copy",
1911
+ "maintenance.postgres.control",
1912
+ "db.open",
1913
+ "db.readAppliedMigrations",
1914
+ "worker.readConfig",
1915
+ "db.close",
1916
+ "db.findSeedUser",
1917
+ "db.inspectObjects",
1918
+ "db.clearLocalSchema",
1919
+ "db.planSchema",
1920
+ "db.applySchema",
1921
+ "db.baselineMigrations",
1922
+ "db.ensureHeldJournal",
1923
+ "db.readHeldMigration",
1924
+ "db.applyHeldMigration",
1925
+ "db.held",
1926
+ "worker.prepareTypes",
1927
+ "worker.disposeTypes",
1928
+ "worker.describeEnvironment",
1929
+ "environment.parseDotenv",
1930
+ "service.postgres.start",
1931
+ "service.postgres.startTemporary",
1932
+ "service.postgres.startRecovery",
1933
+ "service.postgres.stop",
1934
+ "service.postgres.park"
1935
+ ]
1936
+ });
1937
+ await peer.done;
1938
+ } catch (error) {
1939
+ peer.close();
1940
+ throw error;
1941
+ } finally {
1942
+ await session.dispose();
1943
+ }
1944
+ //#endregion
1945
+ export {};