@backifydev/cli 0.3.12 → 0.3.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +14 -1
- package/dist/index.js +286 -232
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -16501,8 +16501,8 @@ var require_CronFileParser = __commonJS({
|
|
|
16501
16501
|
* @throws If file cannot be read
|
|
16502
16502
|
*/
|
|
16503
16503
|
static parseFileSync(filePath) {
|
|
16504
|
-
const { readFileSync:
|
|
16505
|
-
const data =
|
|
16504
|
+
const { readFileSync: readFileSync27 } = __require("fs");
|
|
16505
|
+
const data = readFileSync27(filePath, "utf8");
|
|
16506
16506
|
return _CronFileParser.#parseContent(data);
|
|
16507
16507
|
}
|
|
16508
16508
|
/**
|
|
@@ -18173,7 +18173,7 @@ import { hostname, platform, release, arch } from "node:os";
|
|
|
18173
18173
|
// package.json
|
|
18174
18174
|
var package_default = {
|
|
18175
18175
|
name: "@backifydev/cli",
|
|
18176
|
-
version: "0.3.
|
|
18176
|
+
version: "0.3.13",
|
|
18177
18177
|
description: "Command-line setup and diagnostics for Backify applications",
|
|
18178
18178
|
type: "module",
|
|
18179
18179
|
bin: {
|
|
@@ -18237,14 +18237,14 @@ import { randomBytes } from "node:crypto";
|
|
|
18237
18237
|
import { createServer as createServer2 } from "node:http";
|
|
18238
18238
|
|
|
18239
18239
|
// src/development.ts
|
|
18240
|
-
import { existsSync as
|
|
18241
|
-
import { dirname as dirname4, join as
|
|
18240
|
+
import { existsSync as existsSync6, readFileSync as readFileSync6, readdirSync as readdirSync2, writeFileSync as writeFileSync5, renameSync, rmSync, mkdtempSync, lstatSync as lstatSync2, cpSync } from "node:fs";
|
|
18241
|
+
import { dirname as dirname4, join as join6, resolve as resolve4 } from "node:path";
|
|
18242
18242
|
import { spawnSync as spawnSync3 } from "node:child_process";
|
|
18243
18243
|
import { randomUUID as randomUUID2 } from "node:crypto";
|
|
18244
18244
|
|
|
18245
18245
|
// src/setup.ts
|
|
18246
|
-
import { existsSync as
|
|
18247
|
-
import { basename, dirname as dirname3, join as
|
|
18246
|
+
import { existsSync as existsSync4, readFileSync as readFileSync4, writeFileSync as writeFileSync4, mkdirSync as mkdirSync2, readdirSync, lstatSync } from "node:fs";
|
|
18247
|
+
import { basename, dirname as dirname3, join as join4, resolve as resolve3, isAbsolute } from "node:path";
|
|
18248
18248
|
import { spawnSync as spawnSync2 } from "node:child_process";
|
|
18249
18249
|
|
|
18250
18250
|
// src/delivery.ts
|
|
@@ -18275,11 +18275,32 @@ function installDeliveryInstructions(root, instructionFiles2) {
|
|
|
18275
18275
|
}
|
|
18276
18276
|
}
|
|
18277
18277
|
|
|
18278
|
+
// src/application-support.ts
|
|
18279
|
+
import { existsSync as existsSync3, readFileSync as readFileSync3 } from "node:fs";
|
|
18280
|
+
import { join as join3 } from "node:path";
|
|
18281
|
+
function applicationSupport(root) {
|
|
18282
|
+
const manifestPath = join3(root, "package.json");
|
|
18283
|
+
const manifest = existsSync3(manifestPath) ? JSON.parse(readFileSync3(manifestPath, "utf8")) : {};
|
|
18284
|
+
const dependencies = { ...manifest.devDependencies, ...manifest.dependencies };
|
|
18285
|
+
const framework = ["next", "astro", "@sveltejs/kit", "nuxt", "express", "vite", "react"].find((name2) => dependencies[name2]) ?? "unknown";
|
|
18286
|
+
if (existsSync3(join3(root, "Dockerfile"))) {
|
|
18287
|
+
return { tier: "advanced", framework, guidance: "Custom-container hosting is an advanced path, not a guarantee of Backify SDK integration or framework support. Preserve the Dockerfile and verify capability integration separately." };
|
|
18288
|
+
}
|
|
18289
|
+
if (framework === "vite" && dependencies.react) {
|
|
18290
|
+
return { tier: "recommended", framework, guidance: "React with Vite is the recommended frontend baseline. Prefer TypeScript for new code and use an explicit Backify TypeScript backend for server capabilities. This assessment does not verify deployment or authorization." };
|
|
18291
|
+
}
|
|
18292
|
+
return {
|
|
18293
|
+
tier: existsSync3(manifestPath) ? "compatible" : "unassessed",
|
|
18294
|
+
framework,
|
|
18295
|
+
guidance: "Backify is TypeScript-first. For new apps, prefer React with Vite and an explicit Backify TypeScript backend. Preserve existing JavaScript/TypeScript frameworks; assess SSR, build, identity and capability integration before claiming support. Browser-only apps do not require Node.js in production."
|
|
18296
|
+
};
|
|
18297
|
+
}
|
|
18298
|
+
|
|
18278
18299
|
// src/setup.ts
|
|
18279
18300
|
var instructionFiles = ["AGENTS.md"];
|
|
18280
|
-
var agentInstructionFiles = { codex: "AGENTS.md", claude: "CLAUDE.md", copilot:
|
|
18301
|
+
var agentInstructionFiles = { codex: "AGENTS.md", claude: "CLAUDE.md", copilot: join4(".github", "copilot-instructions.md"), gemini: "GEMINI.md" };
|
|
18281
18302
|
function instructionSelection(root, agent, instructionFile) {
|
|
18282
|
-
const configPath2 =
|
|
18303
|
+
const configPath2 = join4(root, "backify.json"), configured = existsSync4(configPath2) ? JSON.parse(readFileSync4(configPath2, "utf8")) : {};
|
|
18283
18304
|
const custom = instructionFile ?? (agent === void 0 ? configured.instructionFile : void 0);
|
|
18284
18305
|
const selected = instructionFile !== void 0 ? "custom" : agent ?? configured.agent ?? "codex";
|
|
18285
18306
|
if (typeof selected !== "string" || selected !== "custom" && !Object.hasOwn(agentInstructionFiles, selected)) throw new Error("Select the current tool with --agent or --instruction-file <relative-path>.");
|
|
@@ -18288,7 +18309,7 @@ function instructionSelection(root, agent, instructionFile) {
|
|
|
18288
18309
|
const normalized = filename2.replaceAll("\\", "/"), parts = normalized.split("/");
|
|
18289
18310
|
if (isAbsolute(filename2) || /^[A-Za-z]:/.test(filename2) || parts.some((part) => !part || part === "." || part === ".." || part.toLowerCase() === ".git") || ["backify.md", "backify-workflow.md", "backify.json", "package.json", "package-lock.json"].includes(normalized.toLowerCase())) throw new Error("Instruction file must be a relative tool-instruction path inside the project, not Git metadata or a Backify configuration file.");
|
|
18290
18311
|
for (let index = 1; index <= parts.length; index++) {
|
|
18291
|
-
const entry =
|
|
18312
|
+
const entry = join4(root, ...parts.slice(0, index));
|
|
18292
18313
|
try {
|
|
18293
18314
|
const metadata = lstatSync(entry);
|
|
18294
18315
|
if (metadata.isSymbolicLink() || index < parts.length && !metadata.isDirectory() || index === parts.length && !metadata.isFile()) throw new Error("Instruction file path cannot traverse symlinks or replace a directory.");
|
|
@@ -18303,16 +18324,16 @@ function selectedInstructionFiles(root = process.cwd(), agent, instructionFile)
|
|
|
18303
18324
|
}
|
|
18304
18325
|
function isToolWorkspaceEntry(entry, root = process.cwd()) {
|
|
18305
18326
|
if (entry.name.toLowerCase() === ".git" || entry.name.toLowerCase() === ".env" || entry.name.toLowerCase().startsWith(".env.")) return false;
|
|
18306
|
-
return entry.isDirectory() && (entry.name.startsWith(".") || ["work", "outputs"].includes(entry.name) || readdirSync(
|
|
18327
|
+
return entry.isDirectory() && (entry.name.startsWith(".") || ["work", "outputs"].includes(entry.name) || readdirSync(join4(root, entry.name)).length === 0) || entry.isFile() && (entry.name.startsWith(".") || /\.(md|mdc)$/i.test(entry.name));
|
|
18307
18328
|
}
|
|
18308
18329
|
function detectPackageManager(root = process.cwd()) {
|
|
18309
|
-
for (const [file, name2] of [["pnpm-lock.yaml", "pnpm"], ["yarn.lock", "yarn"], ["bun.lockb", "bun"], ["bun.lock", "bun"], ["package-lock.json", "npm"]]) if (
|
|
18330
|
+
for (const [file, name2] of [["pnpm-lock.yaml", "pnpm"], ["yarn.lock", "yarn"], ["bun.lockb", "bun"], ["bun.lock", "bun"], ["package-lock.json", "npm"]]) if (existsSync4(join4(root, file))) return name2;
|
|
18310
18331
|
return "npm";
|
|
18311
18332
|
}
|
|
18312
18333
|
function updateInstructions(root = process.cwd(), agent, instructionFile) {
|
|
18313
18334
|
const updates = selectedInstructionFiles(root, agent, instructionFile).map((relative11) => {
|
|
18314
|
-
const path =
|
|
18315
|
-
return { path, content: updateManagedInstructions(
|
|
18335
|
+
const path = join4(root, relative11);
|
|
18336
|
+
return { path, content: updateManagedInstructions(existsSync4(path) ? readFileSync4(path, "utf8") : "") };
|
|
18316
18337
|
});
|
|
18317
18338
|
for (const { path, content } of updates) {
|
|
18318
18339
|
mkdirSync2(dirname3(path), { recursive: true });
|
|
@@ -18320,9 +18341,9 @@ function updateInstructions(root = process.cwd(), agent, instructionFile) {
|
|
|
18320
18341
|
}
|
|
18321
18342
|
}
|
|
18322
18343
|
function synchronize(root = process.cwd(), agent, instructionFile) {
|
|
18323
|
-
const path =
|
|
18324
|
-
if (!
|
|
18325
|
-
const value = JSON.parse(
|
|
18344
|
+
const path = join4(root, "backify.json");
|
|
18345
|
+
if (!existsSync4(path)) throw new Error("backify.json is missing; run backify init --app app_xxxxx");
|
|
18346
|
+
const value = JSON.parse(readFileSync4(path, "utf8")), issues = validateConfig(value);
|
|
18326
18347
|
if (issues.length) throw new Error(issues.join("; "));
|
|
18327
18348
|
if (value.instructionVersion > INSTRUCTION_VERSION) throw new Error("This app uses newer instructions. Install a matching or newer CLI before syncing.");
|
|
18328
18349
|
const selected = instructionSelection(root, agent, instructionFile);
|
|
@@ -18336,7 +18357,7 @@ function synchronize(root = process.cwd(), agent, instructionFile) {
|
|
|
18336
18357
|
}
|
|
18337
18358
|
function sdkInstalled(root = process.cwd()) {
|
|
18338
18359
|
try {
|
|
18339
|
-
const pkg = JSON.parse(
|
|
18360
|
+
const pkg = JSON.parse(readFileSync4(join4(root, "package.json"), "utf8"));
|
|
18340
18361
|
return Boolean(pkg.dependencies?.[SDK_PACKAGE] || pkg.devDependencies?.[SDK_PACKAGE]);
|
|
18341
18362
|
} catch {
|
|
18342
18363
|
return false;
|
|
@@ -18348,8 +18369,8 @@ function installSdk(root = process.cwd()) {
|
|
|
18348
18369
|
if (result.status !== 0) throw new Error(`Could not install ${SDK_PACKAGE} with ${manager}`);
|
|
18349
18370
|
}
|
|
18350
18371
|
function ensurePackageManifest(root) {
|
|
18351
|
-
const path =
|
|
18352
|
-
if (
|
|
18372
|
+
const path = join4(root, "package.json");
|
|
18373
|
+
if (existsSync4(path)) return;
|
|
18353
18374
|
const setupFiles = /* @__PURE__ */ new Set([".git", ".gitignore", ".github", "AGENTS.md", "CLAUDE.md", "GEMINI.md", "BACKIFY.md", "BACKIFY-WORKFLOW.md", "README.md", "LICENSE", "backify.json"]);
|
|
18354
18375
|
if (readdirSync(root, { withFileTypes: true }).some((entry) => !setupFiles.has(entry.name) && !isToolWorkspaceEntry(entry, root))) throw new Error("package.json is missing. Run backify init from the existing application's JavaScript/TypeScript package directory, or start in an empty folder. See https://agent.backify.dev/");
|
|
18355
18376
|
const name2 = basename(resolve3(root)).toLowerCase().replace(/[^a-z0-9-]+/g, "-").replace(/^-+|-+$/g, "") || "backify-app";
|
|
@@ -18359,20 +18380,33 @@ function initialize(appId, root = process.cwd(), install = true, agent, instruct
|
|
|
18359
18380
|
if (!/^app_[A-Za-z0-9_-]+$/.test(appId)) throw new Error("Provide an application ID using --app app_xxxxx");
|
|
18360
18381
|
const selected = instructionSelection(root, agent, instructionFile), files = selected.files;
|
|
18361
18382
|
validateDeliveryInstructions(root);
|
|
18362
|
-
for (const relative11 of files) if (
|
|
18363
|
-
|
|
18364
|
-
if (
|
|
18365
|
-
|
|
18383
|
+
for (const relative11 of files) if (existsSync4(join4(root, relative11))) updateManagedInstructions(readFileSync4(join4(root, relative11), "utf8"));
|
|
18384
|
+
const customContainer = !existsSync4(join4(root, "package.json")) && existsSync4(join4(root, "Dockerfile"));
|
|
18385
|
+
if (!customContainer) {
|
|
18386
|
+
ensurePackageManifest(root);
|
|
18387
|
+
if (install) installSdk(root);
|
|
18388
|
+
}
|
|
18389
|
+
const configPath2 = join4(root, "backify.json"), existing = existsSync4(configPath2) ? JSON.parse(readFileSync4(configPath2, "utf8")) : {};
|
|
18366
18390
|
writeFileSync4(configPath2, JSON.stringify({ ...existing, ...createConfig(appId), agent: selected.agent, instructionFile: selected.instructionFile }, null, 2) + "\n");
|
|
18367
18391
|
updateInstructions(root, selected.agent, selected.instructionFile);
|
|
18368
18392
|
installDeliveryInstructions(root, files);
|
|
18369
18393
|
}
|
|
18370
18394
|
function doctor(root = process.cwd(), agent, instructionFile) {
|
|
18371
18395
|
const issues = [], warnings = [];
|
|
18372
|
-
|
|
18396
|
+
let support;
|
|
18397
|
+
try {
|
|
18398
|
+
support = applicationSupport(root);
|
|
18399
|
+
if (support.tier !== "recommended") warnings.push(support.guidance);
|
|
18400
|
+
} catch {
|
|
18401
|
+
issues.push("package.json is invalid JSON");
|
|
18402
|
+
}
|
|
18403
|
+
if (!sdkInstalled(root)) {
|
|
18404
|
+
if (!existsSync4(join4(root, "package.json")) && existsSync4(join4(root, "Dockerfile"))) warnings.push("Custom container: JavaScript SDK capabilities are not validated. Use only supported Backify integrations for this language.");
|
|
18405
|
+
else issues.push(`${SDK_PACKAGE} is not installed`);
|
|
18406
|
+
}
|
|
18373
18407
|
let config;
|
|
18374
18408
|
try {
|
|
18375
|
-
config = JSON.parse(
|
|
18409
|
+
config = JSON.parse(readFileSync4(join4(root, "backify.json"), "utf8"));
|
|
18376
18410
|
issues.push(...validateConfig(config));
|
|
18377
18411
|
} catch {
|
|
18378
18412
|
issues.push("backify.json is missing or invalid JSON");
|
|
@@ -18385,20 +18419,34 @@ function doctor(root = process.cwd(), agent, instructionFile) {
|
|
|
18385
18419
|
issues.push(reason instanceof Error ? reason.message : String(reason));
|
|
18386
18420
|
}
|
|
18387
18421
|
for (const relative11 of files) {
|
|
18388
|
-
const path =
|
|
18389
|
-
if (!
|
|
18422
|
+
const path = join4(root, relative11);
|
|
18423
|
+
if (!existsSync4(path)) {
|
|
18390
18424
|
issues.push(`${relative11} is missing`);
|
|
18391
18425
|
continue;
|
|
18392
18426
|
}
|
|
18393
|
-
issues.push(...managedInstructionIssues(
|
|
18427
|
+
issues.push(...managedInstructionIssues(readFileSync4(path, "utf8")).map((issue) => `${relative11} ${issue}`));
|
|
18394
18428
|
}
|
|
18395
18429
|
let version = "unknown";
|
|
18396
18430
|
try {
|
|
18397
|
-
const pkg = JSON.parse(
|
|
18431
|
+
const pkg = JSON.parse(readFileSync4(join4(root, "package.json"), "utf8"));
|
|
18398
18432
|
version = pkg.dependencies?.[SDK_PACKAGE] ?? pkg.devDependencies?.[SDK_PACKAGE] ?? "missing";
|
|
18399
18433
|
} catch {
|
|
18400
18434
|
}
|
|
18401
|
-
return { valid: issues.length === 0, appId: config?.appId, sdkVersion: version, instructionVersion: config?.instructionVersion, currentInstructionVersion: INSTRUCTION_VERSION, issues, warnings };
|
|
18435
|
+
return { valid: issues.length === 0, appId: config?.appId, sdkVersion: version, instructionVersion: config?.instructionVersion, currentInstructionVersion: INSTRUCTION_VERSION, issues, warnings, support };
|
|
18436
|
+
}
|
|
18437
|
+
|
|
18438
|
+
// src/container-build.ts
|
|
18439
|
+
import { existsSync as existsSync5, readFileSync as readFileSync5 } from "node:fs";
|
|
18440
|
+
import { join as join5 } from "node:path";
|
|
18441
|
+
function containerBuildSupport(root) {
|
|
18442
|
+
if (existsSync5(join5(root, "Dockerfile"))) return { adapter: "custom-container", issue: null };
|
|
18443
|
+
if (!existsSync5(join5(root, "package.json"))) return { adapter: null, issue: "Provide a repository-root Dockerfile serving HTTP on port 8080 for this language. Local Docker is not required." };
|
|
18444
|
+
const manifest = JSON.parse(readFileSync5(join5(root, "package.json"), "utf8"));
|
|
18445
|
+
if (!existsSync5(join5(root, "package-lock.json"))) return { adapter: null, issue: "Managed Node builds require package-lock.json. Generate and commit the npm lockfile, or provide a custom Dockerfile." };
|
|
18446
|
+
if (typeof manifest.scripts?.start !== "string" || !manifest.scripts.start || manifest.workspaces || ["pnpm-lock.yaml", "yarn.lock"].some((name2) => existsSync5(join5(root, name2)))) {
|
|
18447
|
+
return { adapter: null, issue: "Managed Node builds require an npm application with a start script at the repository root. Workspaces and other package managers require a custom Dockerfile." };
|
|
18448
|
+
}
|
|
18449
|
+
return { adapter: "node-npm", issue: null };
|
|
18402
18450
|
}
|
|
18403
18451
|
|
|
18404
18452
|
// src/development.ts
|
|
@@ -18413,10 +18461,10 @@ function promptContext(root = process.cwd()) {
|
|
|
18413
18461
|
function installedSdkVersion(root) {
|
|
18414
18462
|
let directory2 = resolve4(root);
|
|
18415
18463
|
while (true) {
|
|
18416
|
-
const manifest =
|
|
18417
|
-
if (
|
|
18464
|
+
const manifest = join6(directory2, "node_modules", "@backifydev", "sdk", "package.json");
|
|
18465
|
+
if (existsSync6(manifest)) {
|
|
18418
18466
|
try {
|
|
18419
|
-
const sdk = JSON.parse(
|
|
18467
|
+
const sdk = JSON.parse(readFileSync6(manifest, "utf8"));
|
|
18420
18468
|
return sdk.name === "@backifydev/sdk" && typeof sdk.version === "string" && /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/.test(sdk.version) ? sdk.version : null;
|
|
18421
18469
|
} catch {
|
|
18422
18470
|
return null;
|
|
@@ -18458,8 +18506,8 @@ function applicationGuid(appId) {
|
|
|
18458
18506
|
return [value.slice(0, 8), value.slice(8, 12), value.slice(12, 16), value.slice(16, 20), value.slice(20)].join("-");
|
|
18459
18507
|
}
|
|
18460
18508
|
function projectApplication(root = process.cwd()) {
|
|
18461
|
-
if (!
|
|
18462
|
-
return JSON.parse(
|
|
18509
|
+
if (!existsSync6(join6(root, "backify.json"))) throw new Error("Run backify connect --app <application-id>, then backify init.");
|
|
18510
|
+
return JSON.parse(readFileSync6(join6(root, "backify.json"), "utf8")).appId;
|
|
18463
18511
|
}
|
|
18464
18512
|
function apiAddress(value) {
|
|
18465
18513
|
const address = new URL(value);
|
|
@@ -18522,7 +18570,7 @@ function gitEnvironment(repository, token) {
|
|
|
18522
18570
|
}
|
|
18523
18571
|
function validateCloneMerge(source, target) {
|
|
18524
18572
|
for (const entry of readdirSync2(source, { withFileTypes: true })) {
|
|
18525
|
-
const destination =
|
|
18573
|
+
const destination = join6(target, entry.name);
|
|
18526
18574
|
let existing;
|
|
18527
18575
|
try {
|
|
18528
18576
|
existing = lstatSync2(destination);
|
|
@@ -18530,7 +18578,7 @@ function validateCloneMerge(source, target) {
|
|
|
18530
18578
|
if (reason.code === "ENOENT") continue;
|
|
18531
18579
|
throw reason;
|
|
18532
18580
|
}
|
|
18533
|
-
if (entry.isDirectory() && existing.isDirectory() && !existing.isSymbolicLink()) validateCloneMerge(
|
|
18581
|
+
if (entry.isDirectory() && existing.isDirectory() && !existing.isSymbolicLink()) validateCloneMerge(join6(source, entry.name), destination);
|
|
18534
18582
|
else throw new Error("Clone conflicts with existing workspace entry: " + destination + ". Existing files are never overwritten; reconcile the conflict or use a new folder.");
|
|
18535
18583
|
}
|
|
18536
18584
|
}
|
|
@@ -18540,18 +18588,18 @@ async function cloneProject(call2, appId, root = process.cwd()) {
|
|
|
18540
18588
|
if (readdirSync2(root, { withFileTypes: true }).some((entry) => !isToolWorkspaceEntry(entry, root))) throw new Error("--clone requires an empty directory or a workspace containing only AI tool metadata and default work/outputs directories. Existing application files and Git repositories are never overwritten.");
|
|
18541
18589
|
const credential = await call2("/apps/" + applicationGuid(appId) + "/developer/git-credential", { method: "POST" });
|
|
18542
18590
|
if (credential.repository.toLowerCase() !== status.repository.toLowerCase()) throw new Error("Repository changed. Run connect again.");
|
|
18543
|
-
const staging = mkdtempSync(
|
|
18591
|
+
const staging = mkdtempSync(join6(dirname4(resolve4(root)), ".backify-clone-"));
|
|
18544
18592
|
try {
|
|
18545
18593
|
git(["clone", "--single-branch", "--branch", status.branch, "--", "https://github.com/" + status.repository + ".git", "."], staging, gitEnvironment(status.repository, credential.token));
|
|
18546
18594
|
validateCloneMerge(staging, root);
|
|
18547
|
-
for (const entry of readdirSync2(staging)) cpSync(
|
|
18595
|
+
for (const entry of readdirSync2(staging)) cpSync(join6(staging, entry), join6(root, entry), { recursive: true, force: false, errorOnExist: true, dereference: false });
|
|
18548
18596
|
} finally {
|
|
18549
|
-
if (dirname4(staging) !== dirname4(resolve4(root)) || !staging.startsWith(
|
|
18597
|
+
if (dirname4(staging) !== dirname4(resolve4(root)) || !staging.startsWith(join6(dirname4(resolve4(root)), ".backify-clone-"))) throw new Error("Refusing to clean up an unexpected clone staging path.");
|
|
18550
18598
|
rmSync(staging, { recursive: true, force: true });
|
|
18551
18599
|
}
|
|
18552
18600
|
}
|
|
18553
18601
|
async function pullProject(call2, appId, root = process.cwd()) {
|
|
18554
|
-
if (
|
|
18602
|
+
if (existsSync6(join6(root, "backify.json")) && applicationGuid(projectApplication(root)) !== applicationGuid(appId)) throw new Error("Local application ID does not match the connected application.");
|
|
18555
18603
|
const prefix = "/apps/" + applicationGuid(appId);
|
|
18556
18604
|
const status = await call2(prefix + "/developer");
|
|
18557
18605
|
if (!status.repository || !status.branch) throw new Error("Connect the repository and branch in Backify before pulling.");
|
|
@@ -18594,9 +18642,9 @@ function attachmentNames(values) {
|
|
|
18594
18642
|
}))];
|
|
18595
18643
|
}
|
|
18596
18644
|
function localReport(runChecks, root = process.cwd()) {
|
|
18597
|
-
const pkg = JSON.parse(
|
|
18645
|
+
const pkg = existsSync6(join6(root, "package.json")) ? JSON.parse(readFileSync6(join6(root, "package.json"), "utf8")) : {};
|
|
18598
18646
|
const dependencies = { ...pkg.devDependencies, ...pkg.dependencies };
|
|
18599
|
-
const framework = ["next", "vite", "astro", "@sveltejs/kit", "nuxt", "react", "express"].find((name2) => dependencies[name2]) ?? "unknown";
|
|
18647
|
+
const framework = ["next", "vite", "astro", "@sveltejs/kit", "nuxt", "react", "express"].find((name2) => dependencies[name2]) ?? (existsSync6(join6(root, "Dockerfile")) ? "custom-container" : "unknown");
|
|
18600
18648
|
const setup = doctor(root);
|
|
18601
18649
|
const checks = [{ name: "backify doctor", status: setup.valid ? "passed" : "failed" }];
|
|
18602
18650
|
const manager = detectPackageManager(root);
|
|
@@ -18612,8 +18660,8 @@ function localReport(runChecks, root = process.cwd()) {
|
|
|
18612
18660
|
dirty = Boolean(git(["status", "--porcelain"], root));
|
|
18613
18661
|
} catch {
|
|
18614
18662
|
}
|
|
18615
|
-
const outputDirectory = ["dist", "build", "out", "."].find((directory2) =>
|
|
18616
|
-
return { framework, sdkVersion: dependencies["@backifydev/sdk"] ?? null, branch, commitSha, dirty, buildCommand: pkg.scripts?.build ? manager + " run build" : null, outputDirectory, hasDockerfile:
|
|
18663
|
+
const outputDirectory = ["dist", "build", "out", "."].find((directory2) => existsSync6(join6(root, directory2, "index.html"))) ?? null;
|
|
18664
|
+
return { framework, sdkVersion: dependencies["@backifydev/sdk"] ?? null, branch, commitSha, dirty, buildCommand: pkg.scripts?.build ? manager + " run build" : null, outputDirectory, hasDockerfile: existsSync6(join6(root, "Dockerfile")), checks, support: setup.support, warnings: setup.warnings };
|
|
18617
18665
|
}
|
|
18618
18666
|
function matchesSource(release2, commit) {
|
|
18619
18667
|
return release2?.commitSha === commit || release2?.sourceCommitSha === commit;
|
|
@@ -18643,7 +18691,10 @@ async function waitForPreview(call2, prefix, commit, options = {}) {
|
|
|
18643
18691
|
const overview = await call2(prefix + "/releases");
|
|
18644
18692
|
if (matchesSource(overview.preview, commit) && overview.preview?.status === "succeeded" && overview.preview.healthResult === "healthy") return overview;
|
|
18645
18693
|
const build3 = await call2(prefix + "/developer/build?commitSha=" + commit);
|
|
18646
|
-
if ((options.previousBuildRunId === void 0 || build3.runId !== options.previousBuildRunId) && ["failure", "cancelled", "timed_out", "action_required", "startup_failure"].includes(build3.conclusion ?? ""))
|
|
18694
|
+
if ((options.previousBuildRunId === void 0 || build3.runId !== options.previousBuildRunId) && ["failure", "cancelled", "timed_out", "action_required", "startup_failure"].includes(build3.conclusion ?? "")) {
|
|
18695
|
+
const details = build3.failure ? " Stage: " + build3.failure.stage + ". " + build3.failure.remediation : "";
|
|
18696
|
+
throw new Error("GitHub build " + build3.conclusion + " for source " + commit + "." + details + " No production release was requested. " + (build3.url ?? "Run backify status for details."));
|
|
18697
|
+
}
|
|
18647
18698
|
await sleep(options.intervalMs ?? 4e3);
|
|
18648
18699
|
} while (Date.now() < deadline);
|
|
18649
18700
|
throw new Error("Timed out waiting for this commit's healthy preview. Run backify status; no production release was requested.");
|
|
@@ -18666,7 +18717,10 @@ async function ship(call2, appId, options = {}) {
|
|
|
18666
18717
|
await call2(prefix + "/developer/report", { method: "POST", body: JSON.stringify(report) });
|
|
18667
18718
|
if (report.checks.some((check) => check.status === "failed")) throw new Error("Checks failed; nothing was pushed.");
|
|
18668
18719
|
if (status.hostingTargetType === "backify-cloud" && !report.outputDirectory && !report.hasDockerfile) throw new Error("Backify Cloud requires a static build containing index.html or a Dockerfile serving port 8080.");
|
|
18669
|
-
if (status.hostingTargetType === "azure"
|
|
18720
|
+
if (status.hostingTargetType === "azure") {
|
|
18721
|
+
const build3 = containerBuildSupport(root);
|
|
18722
|
+
if (!build3.adapter) throw new Error(build3.issue);
|
|
18723
|
+
}
|
|
18670
18724
|
if (git(["status", "--porcelain"], root) || git(["rev-parse", "HEAD"], root) !== commit) throw new Error("Checks changed tracked source. Review and commit those changes before shipping.");
|
|
18671
18725
|
const previousDeployments = await call2(prefix + "/deployments");
|
|
18672
18726
|
const previousBuild = await call2(prefix + "/developer/build?commitSha=" + commit);
|
|
@@ -18824,8 +18878,8 @@ function reconnectingApiClient(session, reconnect, transport = fetch) {
|
|
|
18824
18878
|
|
|
18825
18879
|
// src/local-runtime.ts
|
|
18826
18880
|
import { createHash as createHash2, randomUUID as randomUUID3 } from "node:crypto";
|
|
18827
|
-
import { chmodSync, existsSync as
|
|
18828
|
-
import { dirname as dirname5, join as
|
|
18881
|
+
import { chmodSync, existsSync as existsSync7, lstatSync as lstatSync3, mkdirSync as mkdirSync3, readFileSync as readFileSync7, readdirSync as readdirSync3, writeFileSync as writeFileSync6 } from "node:fs";
|
|
18882
|
+
import { dirname as dirname5, join as join7, resolve as resolve5, sep } from "node:path";
|
|
18829
18883
|
import { homedir } from "node:os";
|
|
18830
18884
|
import { spawnSync as spawnSync4 } from "node:child_process";
|
|
18831
18885
|
|
|
@@ -18860,7 +18914,7 @@ function checkedPath(root, filename2) {
|
|
|
18860
18914
|
if (target !== resolve5(root) && !target.startsWith(resolve5(root) + sep)) throw new Error("Runtime path escapes its installation");
|
|
18861
18915
|
let current = target;
|
|
18862
18916
|
while (true) {
|
|
18863
|
-
if (
|
|
18917
|
+
if (existsSync7(current) && lstatSync3(current).isSymbolicLink()) throw new Error("Runtime installation must not follow links");
|
|
18864
18918
|
if (dirname5(current) === current) break;
|
|
18865
18919
|
current = dirname5(current);
|
|
18866
18920
|
}
|
|
@@ -18868,25 +18922,25 @@ function checkedPath(root, filename2) {
|
|
|
18868
18922
|
}
|
|
18869
18923
|
function verifyInstallationFiles(root, expected, directory2 = root) {
|
|
18870
18924
|
for (const entry of readdirSync3(directory2, { withFileTypes: true })) {
|
|
18871
|
-
const path = checkedPath(root,
|
|
18925
|
+
const path = checkedPath(root, join7(directory2, entry.name));
|
|
18872
18926
|
if (entry.isDirectory()) verifyInstallationFiles(root, expected, path);
|
|
18873
18927
|
else if (!entry.isFile() || !Object.hasOwn(expected, path.slice(root.length + 1).split(sep).join("/"))) throw new Error("Installed runtime contains unexpected files; reinstall a reviewed version");
|
|
18874
18928
|
}
|
|
18875
18929
|
}
|
|
18876
|
-
function installedLocalRuntime(base =
|
|
18930
|
+
function installedLocalRuntime(base = join7(homedir(), ".backify")) {
|
|
18877
18931
|
const pointer = checkedPath(base, "runtime.json");
|
|
18878
|
-
if (!
|
|
18879
|
-
const installed = JSON.parse(
|
|
18932
|
+
if (!existsSync7(pointer)) return void 0;
|
|
18933
|
+
const installed = JSON.parse(readFileSync7(pointer, "utf8"));
|
|
18880
18934
|
if (!/^v[0-9]+\.[0-9]+\.[0-9]+$/.test(installed.version) || installed.rid !== runtimeIdentifier() || !installed.files || Object.keys(installed.files).length > 3e3) throw new Error("Invalid local runtime installation receipt");
|
|
18881
|
-
const root = checkedPath(base,
|
|
18935
|
+
const root = checkedPath(base, join7("runtimes", installed.version, installed.rid));
|
|
18882
18936
|
verifyInstallationFiles(root, installed.files);
|
|
18883
18937
|
for (const [filename2, digest4] of Object.entries(installed.files)) {
|
|
18884
18938
|
const path = checkedPath(root, filename2);
|
|
18885
|
-
if (!/^[a-f0-9]{64}$/.test(digest4) || !lstatSync3(path).isFile() || lstatSync3(path).size > maxArchiveBytes || hash(
|
|
18939
|
+
if (!/^[a-f0-9]{64}$/.test(digest4) || !lstatSync3(path).isFile() || lstatSync3(path).size > maxArchiveBytes || hash(readFileSync7(path)) !== digest4) throw new Error("Installed runtime bytes changed; reinstall a reviewed version");
|
|
18886
18940
|
}
|
|
18887
18941
|
const executableName = installed.rid.startsWith("win-") ? "Backify.Hcr.exe" : "Backify.Hcr";
|
|
18888
18942
|
if (!installed.files["Backify.Hcr.dll"] || !installed.files[executableName]) throw new Error("Runtime archive requires the self-contained HCR executable and DLL");
|
|
18889
|
-
return { path:
|
|
18943
|
+
return { path: join7(root, "Backify.Hcr.dll"), executable: join7(root, executableName), version: installed.version, rid: installed.rid };
|
|
18890
18944
|
}
|
|
18891
18945
|
function installLocalRuntime(archive, options) {
|
|
18892
18946
|
if (!/^v[0-9]+\.[0-9]+\.[0-9]+$/.test(options.version) || !/^[a-f0-9]{64}$/.test(options.sha256)) throw new Error("Provide a release version vX.Y.Z and an independently reviewed SHA-256");
|
|
@@ -18900,12 +18954,12 @@ function installLocalRuntime(archive, options) {
|
|
|
18900
18954
|
const rid = runtimeIdentifier();
|
|
18901
18955
|
const executable = rid.startsWith("win-") ? "Backify.Hcr.exe" : "Backify.Hcr";
|
|
18902
18956
|
if (!files["Backify.Hcr.dll"] || !files[executable] || !files["sql/events-v1.sql"] || !files["sql/jobs-v1.sql"]) throw new Error("Runtime archive is missing required host assets");
|
|
18903
|
-
const base = options.base ??
|
|
18904
|
-
const parent = checkedPath(base,
|
|
18957
|
+
const base = options.base ?? join7(homedir(), ".backify");
|
|
18958
|
+
const parent = checkedPath(base, join7("runtimes", options.version));
|
|
18905
18959
|
mkdirSync3(parent, { recursive: true, mode: 448 });
|
|
18906
18960
|
const destination = checkedPath(parent, rid);
|
|
18907
18961
|
const receipt = { version: options.version, rid, files: Object.fromEntries(Object.entries(files).map(([name2, bytes]) => [name2, hash(bytes)])) };
|
|
18908
|
-
if (!
|
|
18962
|
+
if (!existsSync7(destination)) {
|
|
18909
18963
|
const staging = checkedPath(parent, ".install-" + randomUUID3());
|
|
18910
18964
|
mkdirSync3(staging, { mode: 448 });
|
|
18911
18965
|
for (const [name2, bytes] of Object.entries(files)) {
|
|
@@ -18913,11 +18967,11 @@ function installLocalRuntime(archive, options) {
|
|
|
18913
18967
|
mkdirSync3(dirname5(filename2), { recursive: true, mode: 448 });
|
|
18914
18968
|
writeFileSync6(filename2, bytes, { flag: "wx", mode: name2 === executable ? 448 : 384 });
|
|
18915
18969
|
}
|
|
18916
|
-
if (process.platform !== "win32") chmodSync(
|
|
18970
|
+
if (process.platform !== "win32") chmodSync(join7(staging, executable), 448);
|
|
18917
18971
|
renameLocalFile(staging, destination);
|
|
18918
18972
|
} else {
|
|
18919
18973
|
verifyInstallationFiles(destination, receipt.files);
|
|
18920
|
-
for (const [name2, digest4] of Object.entries(receipt.files)) if (hash(
|
|
18974
|
+
for (const [name2, digest4] of Object.entries(receipt.files)) if (hash(readFileSync7(checkedPath(destination, name2))) !== digest4) throw new Error("Runtime version already exists with different bytes; never overwrite an installation");
|
|
18921
18975
|
}
|
|
18922
18976
|
const pointer = checkedPath(base, "runtime.json");
|
|
18923
18977
|
const temporary = checkedPath(base, ".runtime-" + randomUUID3() + ".json");
|
|
@@ -18949,9 +19003,9 @@ async function downloadLocalRuntime(version) {
|
|
|
18949
19003
|
}
|
|
18950
19004
|
function localPrerequisites() {
|
|
18951
19005
|
const runtime = installedLocalRuntime();
|
|
18952
|
-
const directory2 = process.env.BACKIFY_LOCAL_POSTGRES_BIN ?? (process.platform === "win32" ?
|
|
19006
|
+
const directory2 = process.env.BACKIFY_LOCAL_POSTGRES_BIN ?? (process.platform === "win32" ? join7(process.env.ProgramFiles ?? "C:/Program Files", "PostgreSQL", "17", "bin") : void 0);
|
|
18953
19007
|
const checks = ["initdb", "pg_ctl", "psql"].map((name2) => {
|
|
18954
|
-
const executable = directory2 ?
|
|
19008
|
+
const executable = directory2 ? join7(directory2, name2 + (process.platform === "win32" ? ".exe" : "")) : name2;
|
|
18955
19009
|
const result = spawnSync4(executable, ["--version"], { windowsHide: true, timeout: 1e4, encoding: "utf8" });
|
|
18956
19010
|
return { name: name2, available: result.status === 0 };
|
|
18957
19011
|
});
|
|
@@ -18961,20 +19015,20 @@ function localPrerequisites() {
|
|
|
18961
19015
|
// src/workload.ts
|
|
18962
19016
|
import { build as build2 } from "esbuild";
|
|
18963
19017
|
import { createHash as createHash14 } from "node:crypto";
|
|
18964
|
-
import { existsSync as
|
|
18965
|
-
import { dirname as dirname13, isAbsolute as isAbsolute14, join as
|
|
19018
|
+
import { existsSync as existsSync14, mkdirSync as mkdirSync7, readFileSync as readFileSync22, realpathSync as realpathSync6, readdirSync as readdirSync6, writeFileSync as writeFileSync12 } from "node:fs";
|
|
19019
|
+
import { dirname as dirname13, isAbsolute as isAbsolute14, join as join16, relative as relative8, resolve as resolve19 } from "node:path";
|
|
18966
19020
|
|
|
18967
19021
|
// src/local-development.ts
|
|
18968
19022
|
import { context as context2 } from "esbuild";
|
|
18969
19023
|
import { spawn as spawn4 } from "node:child_process";
|
|
18970
19024
|
import { randomBytes as randomBytes6, randomUUID as randomUUID10, createHash as createHash13 } from "node:crypto";
|
|
18971
|
-
import { existsSync as
|
|
18972
|
-
import { resolve as resolve18, join as
|
|
19025
|
+
import { existsSync as existsSync13, lstatSync as lstatSync15, mkdirSync as mkdirSync6, readFileSync as readFileSync21, realpathSync as realpathSync5, writeFileSync as writeFileSync11, unlinkSync as unlinkSync5 } from "node:fs";
|
|
19026
|
+
import { resolve as resolve18, join as join15, relative as relative7, isAbsolute as isAbsolute13, dirname as dirname12 } from "node:path";
|
|
18973
19027
|
|
|
18974
19028
|
// ../analyzer/dist/index.js
|
|
18975
19029
|
import ts3 from "typescript";
|
|
18976
|
-
import { readFileSync as
|
|
18977
|
-
import { join as
|
|
19030
|
+
import { readFileSync as readFileSync8, readdirSync as readdirSync4, existsSync as existsSync8 } from "node:fs";
|
|
19031
|
+
import { join as join8, extname } from "node:path";
|
|
18978
19032
|
|
|
18979
19033
|
// ../analyzer/dist/authentication.js
|
|
18980
19034
|
import ts from "typescript";
|
|
@@ -19391,14 +19445,14 @@ function repositorySources(root) {
|
|
|
19391
19445
|
for (const entry of readdirSync4(dir, { withFileTypes: true })) {
|
|
19392
19446
|
if (entry.name === "node_modules" || entry.name === "dist" || entry.name === ".backify" || entry.name.startsWith(".git"))
|
|
19393
19447
|
continue;
|
|
19394
|
-
const path =
|
|
19448
|
+
const path = join8(dir, entry.name);
|
|
19395
19449
|
if (entry.isDirectory())
|
|
19396
19450
|
walk(path);
|
|
19397
19451
|
else if ([".ts", ".tsx", ".js", ".jsx", ".mts", ".mjs"].includes(extname(path)))
|
|
19398
|
-
result.push({ path, content:
|
|
19452
|
+
result.push({ path, content: readFileSync8(path, "utf8") });
|
|
19399
19453
|
}
|
|
19400
19454
|
};
|
|
19401
|
-
if (
|
|
19455
|
+
if (existsSync8(root))
|
|
19402
19456
|
walk(root);
|
|
19403
19457
|
return result;
|
|
19404
19458
|
}
|
|
@@ -19612,8 +19666,8 @@ function createLocalNativeEvents(local, native) {
|
|
|
19612
19666
|
// src/local-job-executor.ts
|
|
19613
19667
|
import { spawn as spawn2 } from "node:child_process";
|
|
19614
19668
|
import { createHash as createHash10 } from "node:crypto";
|
|
19615
|
-
import { lstatSync as lstatSync11, readFileSync as
|
|
19616
|
-
import { isAbsolute as isAbsolute8, join as
|
|
19669
|
+
import { lstatSync as lstatSync11, readFileSync as readFileSync15 } from "node:fs";
|
|
19670
|
+
import { isAbsolute as isAbsolute8, join as join11, relative as relative3, resolve as resolve12 } from "node:path";
|
|
19617
19671
|
|
|
19618
19672
|
// ../sdk/dist/schedules.js
|
|
19619
19673
|
var import_cron_parser = __toESM(require_dist2(), 1);
|
|
@@ -19979,7 +20033,7 @@ function createPersistentApplicationAuthProvider(source, options) {
|
|
|
19979
20033
|
|
|
19980
20034
|
// ../sdk/dist/application-auth-sync.js
|
|
19981
20035
|
import { createHash as createHash4, createPublicKey as createPublicKey2, randomUUID as randomUUID5, verify as verify2 } from "node:crypto";
|
|
19982
|
-
import { closeSync as closeSync2, constants as constants2, fsyncSync as fsyncSync2, lstatSync as lstatSync5, openSync as openSync2, readFileSync as
|
|
20036
|
+
import { closeSync as closeSync2, constants as constants2, fsyncSync as fsyncSync2, lstatSync as lstatSync5, openSync as openSync2, readFileSync as readFileSync9, renameSync as renameSync4, unlinkSync as unlinkSync3, writeFileSync as writeFileSync8 } from "node:fs";
|
|
19983
20037
|
import { dirname as dirname7, isAbsolute as isAbsolute3, parse as parse2, resolve as resolve7, sep as sep3 } from "node:path";
|
|
19984
20038
|
var maximumBytes = 512 * 1024;
|
|
19985
20039
|
var identifier = (value) => typeof value === "string" && /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(value) && value !== "00000000-0000-0000-0000-000000000000";
|
|
@@ -20051,7 +20105,7 @@ function currentPublicFile(filename2) {
|
|
|
20051
20105
|
const metadata = lstatSync5(filename2);
|
|
20052
20106
|
if (!metadata.isFile() || metadata.isSymbolicLink() || metadata.nlink !== 1 || metadata.size > 131072 || process.platform !== "win32" && (metadata.uid !== process.getuid?.() || (metadata.mode & 18) !== 0))
|
|
20053
20107
|
unavailable3();
|
|
20054
|
-
const bytes =
|
|
20108
|
+
const bytes = readFileSync9(filename2);
|
|
20055
20109
|
if (bytes.length > 131072)
|
|
20056
20110
|
unavailable3();
|
|
20057
20111
|
return new TextDecoder("utf8", { fatal: true }).decode(bytes);
|
|
@@ -20720,14 +20774,14 @@ function jsonValue(value) {
|
|
|
20720
20774
|
import { spawn, execFile } from "node:child_process";
|
|
20721
20775
|
import { createHash as createHash6, generateKeyPairSync, randomBytes as randomBytes3, randomUUID as randomUUID7, sign } from "node:crypto";
|
|
20722
20776
|
import { createServer as createServer3 } from "node:net";
|
|
20723
|
-
import { existsSync as
|
|
20724
|
-
import { basename as basename2, dirname as dirname9, isAbsolute as isAbsolute4, join as
|
|
20777
|
+
import { existsSync as existsSync10, lstatSync as lstatSync7, mkdirSync as mkdirSync4, readFileSync as readFileSync11, readdirSync as readdirSync5, realpathSync, unlinkSync as unlinkSync4, writeFileSync as writeFileSync9 } from "node:fs";
|
|
20778
|
+
import { basename as basename2, dirname as dirname9, isAbsolute as isAbsolute4, join as join10, relative, resolve as resolve8 } from "node:path";
|
|
20725
20779
|
|
|
20726
20780
|
// src/local-job-services.ts
|
|
20727
20781
|
import { createHash as createHash5, randomBytes as randomBytes2, randomUUID as randomUUID6 } from "node:crypto";
|
|
20728
|
-
import { existsSync as
|
|
20782
|
+
import { existsSync as existsSync9, lstatSync as lstatSync6, readFileSync as readFileSync10 } from "node:fs";
|
|
20729
20783
|
import { isIP } from "node:net";
|
|
20730
|
-
import { dirname as dirname8, join as
|
|
20784
|
+
import { dirname as dirname8, join as join9 } from "node:path";
|
|
20731
20785
|
function fields3(value, names) {
|
|
20732
20786
|
return !!value && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === names.length && names.every((name2) => Object.hasOwn(value, name2));
|
|
20733
20787
|
}
|
|
@@ -20778,9 +20832,9 @@ function validLocalJobState(value, otherIds) {
|
|
|
20778
20832
|
function prepareLocalJobService(hcrPath, retained, artifacts, applyMigrations) {
|
|
20779
20833
|
const requested = validateLocalJobArtifacts(artifacts);
|
|
20780
20834
|
const readSchema = (name2) => {
|
|
20781
|
-
const filename2 =
|
|
20835
|
+
const filename2 = join9(dirname8(hcrPath), "sql", name2), info = existsSync9(filename2) ? lstatSync6(filename2) : void 0;
|
|
20782
20836
|
if (!info?.isFile() || info.isSymbolicLink() || info.size > 65536) throw new Error("Native jobs require the reviewed jobs-v1.sql and jobs-producer-v1.sql assets beside the HCR host");
|
|
20783
|
-
return
|
|
20837
|
+
return readFileSync10(filename2, "utf8");
|
|
20784
20838
|
};
|
|
20785
20839
|
const base = readSchema("jobs-v1.sql"), producer = readSchema("jobs-producer-v1.sql");
|
|
20786
20840
|
const schemaDigests = { base: createHash5("sha256").update(base).digest("hex"), producer: createHash5("sha256").update(producer).digest("hex") };
|
|
@@ -20826,7 +20880,7 @@ function stateValid(value) {
|
|
|
20826
20880
|
return value?.version === 1 && value.scope && [value.scope.organizationId, value.scope.applicationId, value.scope.environmentId, value.databaseId, value.storageId].every((identifier2) => typeof identifier2 === "string" && uuid4.test(identifier2)) && Number.isSafeInteger(value.configurationVersion) && value.configurationVersion >= 0 && /^[a-f0-9]{64}$/.test(value.adminPassword) && /^[a-f0-9]{64}$/.test(value.databasePassword) && (value.retainedDatabasePort === void 0 || Number.isInteger(value.retainedDatabasePort) && value.retainedDatabasePort > 0 && value.retainedDatabasePort <= 65535);
|
|
20827
20881
|
}
|
|
20828
20882
|
function acquireLocalLease(root, relativePath2 = ".backify/dev/development.lock") {
|
|
20829
|
-
const filename2 =
|
|
20883
|
+
const filename2 = join10(root, relativePath2);
|
|
20830
20884
|
assertLocalStatePath(root, filename2);
|
|
20831
20885
|
mkdirSync4(resolve8(filename2, ".."), { recursive: true, mode: 448 });
|
|
20832
20886
|
const owner = JSON.stringify({ version: 1, pid: process.pid, id: randomUUID7() });
|
|
@@ -20836,7 +20890,7 @@ function acquireLocalLease(root, relativePath2 = ".backify/dev/development.lock"
|
|
|
20836
20890
|
throw new Error("Local development already owns this repository, or a stale lifecycle lock requires explicit recovery");
|
|
20837
20891
|
}
|
|
20838
20892
|
return () => {
|
|
20839
|
-
if (
|
|
20893
|
+
if (existsSync10(filename2) && readFileSync11(filename2, "utf8") === owner) unlinkSync4(filename2);
|
|
20840
20894
|
};
|
|
20841
20895
|
}
|
|
20842
20896
|
async function allocateLocalPort(requested) {
|
|
@@ -20879,26 +20933,26 @@ function command(executable, args2, options = {}) {
|
|
|
20879
20933
|
});
|
|
20880
20934
|
}
|
|
20881
20935
|
function postgresExecutable(name2, bin) {
|
|
20882
|
-
const directory2 = bin ?? process.env.BACKIFY_LOCAL_POSTGRES_BIN ?? (process.platform === "win32" ?
|
|
20883
|
-
return directory2 ?
|
|
20936
|
+
const directory2 = bin ?? process.env.BACKIFY_LOCAL_POSTGRES_BIN ?? (process.platform === "win32" ? join10(process.env.ProgramFiles ?? "C:/Program Files", "PostgreSQL", "17", "bin") : void 0);
|
|
20937
|
+
return directory2 ? join10(directory2, name2 + (process.platform === "win32" ? ".exe" : "")) : name2;
|
|
20884
20938
|
}
|
|
20885
20939
|
function localMigrationFiles(root, directory2) {
|
|
20886
20940
|
if (directory2 === void 0) return [];
|
|
20887
20941
|
if (typeof directory2 !== "string") throw new Error("Local migrations require a repository-relative directory");
|
|
20888
20942
|
const folder = resolve8(root, directory2);
|
|
20889
20943
|
assertLocalStatePath(root, folder);
|
|
20890
|
-
if (!
|
|
20944
|
+
if (!existsSync10(folder)) throw new Error("Declared migration directory does not exist");
|
|
20891
20945
|
const entries = readdirSync5(folder);
|
|
20892
20946
|
const filenames = entries.filter((entry) => entry.endsWith(".sql")).sort();
|
|
20893
20947
|
if (filenames.length > 100 || entries.some((entry) => !entry.endsWith(".sql"))) throw new Error("Migrations require at most 100 flat .sql files");
|
|
20894
20948
|
let total = 0;
|
|
20895
20949
|
return filenames.map((name2) => {
|
|
20896
20950
|
if (!/^[A-Za-z0-9_.-]{1,150}\.sql$/.test(name2)) throw new Error("Invalid migration filename");
|
|
20897
|
-
const filename2 =
|
|
20951
|
+
const filename2 = join10(folder, name2);
|
|
20898
20952
|
assertLocalStatePath(root, filename2);
|
|
20899
20953
|
const info = lstatSync7(filename2);
|
|
20900
20954
|
if (!info.isFile() || info.size > 1024 * 1024 || (total += info.size) > 4 * 1024 * 1024) throw new Error("Migration SQL exceeds supported limits");
|
|
20901
|
-
const sql =
|
|
20955
|
+
const sql = readFileSync11(filename2, "utf8");
|
|
20902
20956
|
if (!sql.trim()) throw new Error("Migration SQL must not be empty");
|
|
20903
20957
|
validateLocalMigrationSql(sql);
|
|
20904
20958
|
return { name: name2, digest: createHash6("sha256").update(sql).digest("hex"), sql };
|
|
@@ -20975,19 +21029,19 @@ async function startLocalServices(root, manifest, options = {}) {
|
|
|
20975
21029
|
const reviewedScope = options.jobIdentityScope;
|
|
20976
21030
|
if (reviewedScope !== void 0 && (!jobs || !manifest.capabilities.auth || manifest.capabilities.auth.enabled === false || !reviewedScope || Object.keys(reviewedScope).sort().join(",") !== "applicationId,environmentId,organizationId" || Object.values(reviewedScope).some((value) => typeof value !== "string" || value.length !== 36 || !/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(value) || value === "00000000-0000-0000-0000-000000000000"))) throw new Error("Native worker identity scope requires reviewed jobs and enabled auth");
|
|
20977
21031
|
const installed = options.hcrPath || process.env.BACKIFY_LOCAL_HCR_PATH ? void 0 : installedLocalRuntime();
|
|
20978
|
-
const hcrPath = resolve8(options.hcrPath ?? process.env.BACKIFY_LOCAL_HCR_PATH ?? installed?.path ??
|
|
20979
|
-
if (!
|
|
20980
|
-
const directory2 =
|
|
21032
|
+
const hcrPath = resolve8(options.hcrPath ?? process.env.BACKIFY_LOCAL_HCR_PATH ?? installed?.path ?? join10(root, "apps/hcr/bin/Debug/net9.0/Backify.Hcr.dll"));
|
|
21033
|
+
if (!existsSync10(hcrPath) || !lstatSync7(hcrPath).isFile() || !hcrPath.endsWith(".dll")) throw new Error("Full-fidelity mode requires a built Backify.Hcr.dll; set --hcr-path or BACKIFY_LOCAL_HCR_PATH");
|
|
21034
|
+
const directory2 = join10(root, ".backify", "dev", "services");
|
|
20981
21035
|
assertLocalStatePath(root, directory2);
|
|
20982
21036
|
mkdirSync4(directory2, { recursive: true, mode: 448 });
|
|
20983
21037
|
assertLocalStatePath(root, directory2);
|
|
20984
|
-
const statePath =
|
|
21038
|
+
const statePath = join10(directory2, "host.json");
|
|
20985
21039
|
assertLocalStatePath(root, statePath);
|
|
20986
21040
|
let existing;
|
|
20987
|
-
if (
|
|
21041
|
+
if (existsSync10(statePath)) {
|
|
20988
21042
|
if (lstatSync7(statePath).size > 16384) throw new Error("Local ownership state exceeds supported limits");
|
|
20989
21043
|
try {
|
|
20990
|
-
existing = JSON.parse(
|
|
21044
|
+
existing = JSON.parse(readFileSync11(statePath, "utf8"));
|
|
20991
21045
|
} catch {
|
|
20992
21046
|
throw new Error("Invalid local service ownership state; preserve the data and repair explicitly");
|
|
20993
21047
|
}
|
|
@@ -21006,9 +21060,9 @@ async function startLocalServices(root, manifest, options = {}) {
|
|
|
21006
21060
|
if (reviewedScope && ["organizationId", "applicationId", "environmentId"].some((name2) => state.scope[name2] !== reviewedScope[name2])) throw new Error("Reviewed native worker identity scope conflicts with retained local ownership; preserve data and use a separate reviewed workspace");
|
|
21007
21061
|
let eventSchema;
|
|
21008
21062
|
if (events) {
|
|
21009
|
-
const filename2 =
|
|
21010
|
-
if (!
|
|
21011
|
-
eventSchema =
|
|
21063
|
+
const filename2 = join10(dirname9(hcrPath), "sql", "events-v1.sql");
|
|
21064
|
+
if (!existsSync10(filename2) || lstatSync7(filename2).isSymbolicLink() || !lstatSync7(filename2).isFile() || lstatSync7(filename2).size > 65536) throw new Error("Native events require the reviewed events-v1.sql asset beside the HCR host.");
|
|
21065
|
+
eventSchema = readFileSync11(filename2, "utf8");
|
|
21012
21066
|
const digest4 = createHash6("sha256").update(eventSchema).digest("hex");
|
|
21013
21067
|
if (state.events && state.events.schemaDigest !== digest4) throw new Error("Native event schema changed; preserve its database and plan an explicit migration.");
|
|
21014
21068
|
if (!state.events?.initialized && !options.applyMigrations) throw new Error("Review the HCR events-v1.sql asset and pass --apply-migrations for explicit native event schema approval.");
|
|
@@ -21027,7 +21081,7 @@ async function startLocalServices(root, manifest, options = {}) {
|
|
|
21027
21081
|
const databasePort = database || events || jobs ? await allocateLocalPort(options.databasePort) : void 0;
|
|
21028
21082
|
if (databasePort !== void 0) state.retainedDatabasePort = databasePort;
|
|
21029
21083
|
if (databasePort === hcrPort) throw new Error("HCR and PostgreSQL require separate ports");
|
|
21030
|
-
const cluster =
|
|
21084
|
+
const cluster = join10(directory2, "postgres");
|
|
21031
21085
|
assertLocalStatePath(root, cluster);
|
|
21032
21086
|
const release2 = acquireLocalLease(root, ".backify/dev/services/lifecycle.lock");
|
|
21033
21087
|
let postgresStarted = false;
|
|
@@ -21043,7 +21097,7 @@ async function startLocalServices(root, manifest, options = {}) {
|
|
|
21043
21097
|
}
|
|
21044
21098
|
};
|
|
21045
21099
|
const runtimeUrl = "http://127.0.0.1:" + hcrPort;
|
|
21046
|
-
const tokenPath =
|
|
21100
|
+
const tokenPath = join10(directory2, "workload-token");
|
|
21047
21101
|
const stop = () => stopping ??= (async () => {
|
|
21048
21102
|
if (timer) clearInterval(timer);
|
|
21049
21103
|
if (snapshotTimer) clearInterval(snapshotTimer);
|
|
@@ -21062,9 +21116,9 @@ async function startLocalServices(root, manifest, options = {}) {
|
|
|
21062
21116
|
}
|
|
21063
21117
|
notify("hcr", "stopped");
|
|
21064
21118
|
try {
|
|
21065
|
-
if (postgresStarted &&
|
|
21119
|
+
if (postgresStarted && existsSync10(join10(cluster, "postmaster.pid"))) await command(postgresExecutable("pg_ctl", options.postgresBin), ["-D", cluster, "-m", "fast", "-w", "stop"]);
|
|
21066
21120
|
if (postgresStarted) notify("postgres", "stopped");
|
|
21067
|
-
if (
|
|
21121
|
+
if (existsSync10(tokenPath)) unlinkSync4(tokenPath);
|
|
21068
21122
|
} finally {
|
|
21069
21123
|
release2();
|
|
21070
21124
|
}
|
|
@@ -21074,28 +21128,28 @@ async function startLocalServices(root, manifest, options = {}) {
|
|
|
21074
21128
|
writePrivate(statePath, JSON.stringify(state));
|
|
21075
21129
|
if (database || events || jobs) {
|
|
21076
21130
|
notify("postgres", "starting");
|
|
21077
|
-
if (!
|
|
21078
|
-
const passwordPath =
|
|
21131
|
+
if (!existsSync10(join10(cluster, "PG_VERSION"))) {
|
|
21132
|
+
const passwordPath = join10(directory2, "init-password");
|
|
21079
21133
|
writePrivate(passwordPath, state.adminPassword);
|
|
21080
21134
|
try {
|
|
21081
21135
|
await command(postgresExecutable("initdb", options.postgresBin), ["-D", cluster, "-U", "backify_admin", "--auth-host=scram-sha-256", "--auth-local=scram-sha-256", "--pwfile=" + passwordPath, "--no-locale", "--encoding=UTF8"]);
|
|
21082
21136
|
} finally {
|
|
21083
|
-
if (
|
|
21137
|
+
if (existsSync10(passwordPath)) unlinkSync4(passwordPath);
|
|
21084
21138
|
}
|
|
21085
21139
|
}
|
|
21086
|
-
if (
|
|
21140
|
+
if (existsSync10(join10(cluster, "postmaster.pid"))) throw new Error("A retained local PostgreSQL server is still running; stop or recover that exact owned cluster before restarting dev");
|
|
21087
21141
|
postgresStarted = true;
|
|
21088
|
-
await command(postgresExecutable("pg_ctl", options.postgresBin), ["-D", cluster, "-l",
|
|
21142
|
+
await command(postgresExecutable("pg_ctl", options.postgresBin), ["-D", cluster, "-l", join10(directory2, "postgres.log"), "-o", "-h 127.0.0.1 -p " + databasePort, "-w", "start"]);
|
|
21089
21143
|
notify("postgres", "ready");
|
|
21090
21144
|
const sql = (query, application = false) => command(postgresExecutable("psql", options.postgresBin), ["-h", "127.0.0.1", "-p", String(databasePort), "-U", application ? "backify_local" : "backify_admin", "-d", application ? "backify_local" : "postgres", "-X", "-q", "-t", "-A", "-v", "ON_ERROR_STOP=1", "-c", query], { env: { ...process.env, PGPASSWORD: application ? state.databasePassword : state.adminPassword } });
|
|
21091
21145
|
if (database) {
|
|
21092
21146
|
if ((await sql("SELECT count(*) FROM pg_roles WHERE rolname='backify_local'")).trim() === "0") {
|
|
21093
|
-
const filename2 =
|
|
21147
|
+
const filename2 = join10(directory2, "role-" + randomUUID7() + ".sql");
|
|
21094
21148
|
writePrivate(filename2, "CREATE ROLE backify_local LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE PASSWORD '" + state.databasePassword + "';");
|
|
21095
21149
|
try {
|
|
21096
21150
|
await command(postgresExecutable("psql", options.postgresBin), ["-h", "127.0.0.1", "-p", String(databasePort), "-U", "backify_admin", "-d", "postgres", "-X", "-q", "-v", "ON_ERROR_STOP=1", "-f", filename2], { env: { ...process.env, PGPASSWORD: state.adminPassword } });
|
|
21097
21151
|
} finally {
|
|
21098
|
-
if (
|
|
21152
|
+
if (existsSync10(filename2)) unlinkSync4(filename2);
|
|
21099
21153
|
}
|
|
21100
21154
|
}
|
|
21101
21155
|
if ((await sql("SELECT count(*) FROM pg_database WHERE datname='backify_local'")).trim() === "0") await sql("CREATE DATABASE backify_local OWNER backify_local");
|
|
@@ -21110,12 +21164,12 @@ async function startLocalServices(root, manifest, options = {}) {
|
|
|
21110
21164
|
notify("migrations", "starting");
|
|
21111
21165
|
if (pending.length) await sql("CREATE TABLE IF NOT EXISTS public.__backify_migrations (name text PRIMARY KEY, digest text NOT NULL, applied_at timestamptz NOT NULL DEFAULT now())", true);
|
|
21112
21166
|
for (const migration of pending) {
|
|
21113
|
-
const filename2 =
|
|
21167
|
+
const filename2 = join10(directory2, "apply-" + randomUUID7() + ".sql");
|
|
21114
21168
|
writePrivate(filename2, "BEGIN;\n" + migration.sql + "\n;\nINSERT INTO public.__backify_migrations(name,digest) VALUES ('" + migration.name + "','" + migration.digest + "');\nCOMMIT;\n");
|
|
21115
21169
|
try {
|
|
21116
21170
|
await command(postgresExecutable("psql", options.postgresBin), ["-h", "127.0.0.1", "-p", String(databasePort), "-U", "backify_local", "-d", "backify_local", "-X", "-q", "-v", "ON_ERROR_STOP=1", "-f", filename2], { env: { ...process.env, PGPASSWORD: state.databasePassword } });
|
|
21117
21171
|
} finally {
|
|
21118
|
-
if (
|
|
21172
|
+
if (existsSync10(filename2)) unlinkSync4(filename2);
|
|
21119
21173
|
}
|
|
21120
21174
|
applied.push(migration.name);
|
|
21121
21175
|
}
|
|
@@ -21126,20 +21180,20 @@ async function startLocalServices(root, manifest, options = {}) {
|
|
|
21126
21180
|
const eventSql = (query) => command(postgresExecutable("psql", options.postgresBin), ["-h", "127.0.0.1", "-p", String(databasePort), "-U", "backify_events", "-d", "backify_events", "-X", "-q", "-t", "-A", "-v", "ON_ERROR_STOP=1", "-c", query], { env: { ...process.env, PGPASSWORD: eventState.password } });
|
|
21127
21181
|
if (!eventState.initialized) {
|
|
21128
21182
|
if ((await sql("SELECT count(*) FROM pg_database WHERE datname='backify_events'")).trim() !== "0" || (await sql("SELECT count(*) FROM pg_roles WHERE rolname='backify_events'")).trim() !== "0") throw new Error("Uninitialized native event ownership conflicts with retained state; preserve it and repair explicitly.");
|
|
21129
|
-
const roleFile =
|
|
21183
|
+
const roleFile = join10(directory2, "event-role-" + randomUUID7() + ".sql");
|
|
21130
21184
|
writePrivate(roleFile, "CREATE ROLE backify_events LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE PASSWORD '" + eventState.password + "';");
|
|
21131
21185
|
try {
|
|
21132
21186
|
await command(postgresExecutable("psql", options.postgresBin), ["-h", "127.0.0.1", "-p", String(databasePort), "-U", "backify_admin", "-d", "postgres", "-X", "-q", "-v", "ON_ERROR_STOP=1", "-f", roleFile], { env: { ...process.env, PGPASSWORD: state.adminPassword } });
|
|
21133
21187
|
} finally {
|
|
21134
|
-
if (
|
|
21188
|
+
if (existsSync10(roleFile)) unlinkSync4(roleFile);
|
|
21135
21189
|
}
|
|
21136
21190
|
await sql("CREATE DATABASE backify_events OWNER backify_events");
|
|
21137
|
-
const schemaFile =
|
|
21191
|
+
const schemaFile = join10(directory2, "event-schema-" + randomUUID7() + ".sql");
|
|
21138
21192
|
writePrivate(schemaFile, eventSchema);
|
|
21139
21193
|
try {
|
|
21140
21194
|
await command(postgresExecutable("psql", options.postgresBin), ["-h", "127.0.0.1", "-p", String(databasePort), "-U", "backify_events", "-d", "backify_events", "-X", "-q", "-v", "ON_ERROR_STOP=1", "-f", schemaFile], { env: { ...process.env, PGPASSWORD: eventState.password } });
|
|
21141
21195
|
} finally {
|
|
21142
|
-
if (
|
|
21196
|
+
if (existsSync10(schemaFile)) unlinkSync4(schemaFile);
|
|
21143
21197
|
}
|
|
21144
21198
|
eventState.initialized = true;
|
|
21145
21199
|
writePrivate(statePath, JSON.stringify(state));
|
|
@@ -21153,21 +21207,21 @@ async function startLocalServices(root, manifest, options = {}) {
|
|
|
21153
21207
|
const adminSql = (query, databaseName = "postgres") => jobCommand("backify_admin", state.adminPassword, databaseName, ["-c", query]);
|
|
21154
21208
|
if (!jobState.initialized) {
|
|
21155
21209
|
if ((await adminSql("SELECT count(*) FROM pg_database WHERE datname='backify_jobs'")).trim() !== "0" || (await adminSql("SELECT count(*) FROM pg_roles WHERE rolname='backify_jobs'")).trim() !== "0") throw new Error("Uninitialized native job ownership conflicts with retained state; preserve it and repair explicitly");
|
|
21156
|
-
const roleFile =
|
|
21210
|
+
const roleFile = join10(directory2, "job-role-" + randomUUID7() + ".sql");
|
|
21157
21211
|
writePrivate(roleFile, "CREATE ROLE backify_jobs LOGIN NOINHERIT NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION NOBYPASSRLS PASSWORD '" + jobState.password + "';");
|
|
21158
21212
|
try {
|
|
21159
21213
|
await jobCommand("backify_admin", state.adminPassword, "postgres", ["-f", roleFile]);
|
|
21160
21214
|
} finally {
|
|
21161
|
-
if (
|
|
21215
|
+
if (existsSync10(roleFile)) unlinkSync4(roleFile);
|
|
21162
21216
|
}
|
|
21163
21217
|
await adminSql("CREATE DATABASE backify_jobs OWNER backify_admin");
|
|
21164
21218
|
for (const schema of [jobSchema.base, jobSchema.producer]) {
|
|
21165
|
-
const filename2 =
|
|
21219
|
+
const filename2 = join10(directory2, "job-schema-" + randomUUID7() + ".sql");
|
|
21166
21220
|
writePrivate(filename2, schema);
|
|
21167
21221
|
try {
|
|
21168
21222
|
await jobCommand("backify_admin", state.adminPassword, "backify_jobs", ["-f", filename2]);
|
|
21169
21223
|
} finally {
|
|
21170
|
-
if (
|
|
21224
|
+
if (existsSync10(filename2)) unlinkSync4(filename2);
|
|
21171
21225
|
}
|
|
21172
21226
|
}
|
|
21173
21227
|
await adminSql("REVOKE ALL ON DATABASE backify_jobs FROM PUBLIC; GRANT CONNECT ON DATABASE backify_jobs TO backify_jobs; REVOKE CREATE ON SCHEMA public FROM PUBLIC; GRANT USAGE ON SCHEMA __backify_jobs TO backify_jobs; GRANT SELECT ON __backify_jobs.schema_version,__backify_jobs.producer_schema_version TO backify_jobs; GRANT SELECT,INSERT,UPDATE ON __backify_jobs.runs,__backify_jobs.attempts TO backify_jobs; GRANT SELECT,INSERT ON __backify_jobs.producers TO backify_jobs", "backify_jobs");
|
|
@@ -21196,7 +21250,7 @@ async function startLocalServices(root, manifest, options = {}) {
|
|
|
21196
21250
|
...events ? [{ id: state.events.id, scope: state.scope, capability: "events", contractVersion: 1, logicalBinding: "default", provider: "postgres-events", resourceReference: "backify_events", ownership: "Managed", accessMode: "Gateway", permissions: ["events.emit", "events.receive", "events.complete", "events.inspect"], status: "ready" }] : [],
|
|
21197
21251
|
...jobs ? [{ id: state.jobs.id, scope: state.scope, capability: "jobs", contractVersion: 1, logicalBinding: "default", provider: "postgres-jobs", resourceReference: "backify_jobs", ownership: "Managed", accessMode: "Gateway", permissions: ["jobs.enqueue", "jobs.receive", "jobs.complete", "jobs.cancel", "jobs.inspect", "jobs.retry"], status: "ready" }] : []
|
|
21198
21252
|
];
|
|
21199
|
-
const snapshotPath =
|
|
21253
|
+
const snapshotPath = join10(directory2, "snapshot.json");
|
|
21200
21254
|
const writeSnapshot = () => writePrivate(snapshotPath, JSON.stringify({ schemaVersion: 1, configurationVersion: state.configurationVersion, expiresAt: new Date(Date.now() + 7 * 864e5).toISOString(), bindings }));
|
|
21201
21255
|
const renewConfiguration = () => {
|
|
21202
21256
|
if (stopping) throw new Error("Stopped local services cannot renew configuration");
|
|
@@ -21206,15 +21260,15 @@ async function startLocalServices(root, manifest, options = {}) {
|
|
|
21206
21260
|
writeSnapshot();
|
|
21207
21261
|
};
|
|
21208
21262
|
writeSnapshot();
|
|
21209
|
-
const settingsPath =
|
|
21263
|
+
const settingsPath = join10(directory2, "appsettings.json");
|
|
21210
21264
|
writePrivate(settingsPath, JSON.stringify({ Hcr: {
|
|
21211
21265
|
Authentication: { PublicKeyPem: publicKey.export({ type: "spki", format: "pem" }), Issuer: "backify-local", Audience: "backify-local-hcr" },
|
|
21212
21266
|
SnapshotPath: snapshotPath,
|
|
21213
|
-
SnapshotJournalPath:
|
|
21267
|
+
SnapshotJournalPath: join10(directory2, "journal.json"),
|
|
21214
21268
|
Postgres: { Bindings: state.retainedDatabasePort ? { [state.databaseId]: { Scope: state.scope, ConnectionString: "Host=127.0.0.1;Port=" + state.retainedDatabasePort + ";Database=backify_local;Username=backify_local;Password=" + state.databasePassword } } : {} },
|
|
21215
21269
|
Events: { Bindings: state.retainedDatabasePort && state.events?.initialized ? { [state.events.id]: { Scope: state.scope, ConnectionString: "Host=127.0.0.1;Port=" + state.retainedDatabasePort + ";Database=backify_events;Username=backify_events;Password=" + state.events.password } } : {} },
|
|
21216
21270
|
Jobs: { Bindings: state.retainedDatabasePort && state.jobs?.initialized ? { [state.jobs.id]: { Scope: state.scope, ConnectionString: "Host=127.0.0.1;Port=" + state.retainedDatabasePort + ";Database=backify_jobs;Username=backify_jobs;Password=" + state.jobs.password, Artifacts: state.jobs.artifacts } } : {} },
|
|
21217
|
-
Storage: { Bindings: Object.fromEntries(Object.entries(state.storageBindings).map(([name2, identifier2]) => [identifier2, { Scope: state.scope, ResourceReference: name2, RootPath:
|
|
21271
|
+
Storage: { Bindings: Object.fromEntries(Object.entries(state.storageBindings).map(([name2, identifier2]) => [identifier2, { Scope: state.scope, ResourceReference: name2, RootPath: join10(directory2, "objects", identifier2) }])) }
|
|
21218
21272
|
} }));
|
|
21219
21273
|
issueToken();
|
|
21220
21274
|
notify("hcr", "starting");
|
|
@@ -21228,7 +21282,7 @@ async function startLocalServices(root, manifest, options = {}) {
|
|
|
21228
21282
|
while (true) {
|
|
21229
21283
|
if (spawnFailed || hcr.exitCode !== null || hcr.signalCode !== null || Date.now() > deadline) throw new Error("Local HCR could not become ready; check the .NET runtime, bindings and retained journal");
|
|
21230
21284
|
try {
|
|
21231
|
-
const response = await fetch(runtimeUrl + "/v1/health", { headers: { authorization: "Bearer " +
|
|
21285
|
+
const response = await fetch(runtimeUrl + "/v1/health", { headers: { authorization: "Bearer " + readFileSync11(tokenPath, "utf8") }, signal: AbortSignal.timeout(500), redirect: "error", credentials: "omit", cache: "no-store" });
|
|
21232
21286
|
if (response.ok) {
|
|
21233
21287
|
const status = await response.json();
|
|
21234
21288
|
if (status.status === "ready" && status.configurationVersion === state.configurationVersion) break;
|
|
@@ -21237,8 +21291,8 @@ async function startLocalServices(root, manifest, options = {}) {
|
|
|
21237
21291
|
}
|
|
21238
21292
|
await new Promise((resolveDelay) => setTimeout(resolveDelay, 100));
|
|
21239
21293
|
}
|
|
21240
|
-
if (events) await createHcrEventsProvider({ runtimeUrl, token: () =>
|
|
21241
|
-
if (jobs) await createHcrJobsProvider({ runtimeUrl, token: () =>
|
|
21294
|
+
if (events) await createHcrEventsProvider({ runtimeUrl, token: () => readFileSync11(tokenPath, "utf8") }).inspect();
|
|
21295
|
+
if (jobs) await createHcrJobsProvider({ runtimeUrl, token: () => readFileSync11(tokenPath, "utf8") }).inspect();
|
|
21242
21296
|
timer = setInterval(() => {
|
|
21243
21297
|
try {
|
|
21244
21298
|
issueToken();
|
|
@@ -21264,14 +21318,14 @@ async function startLocalServices(root, manifest, options = {}) {
|
|
|
21264
21318
|
|
|
21265
21319
|
// src/local-job-auth.ts
|
|
21266
21320
|
import { createHash as createHash7 } from "node:crypto";
|
|
21267
|
-
import { lstatSync as lstatSync8, readFileSync as
|
|
21321
|
+
import { lstatSync as lstatSync8, readFileSync as readFileSync12 } from "node:fs";
|
|
21268
21322
|
import { isAbsolute as isAbsolute5, resolve as resolve9 } from "node:path";
|
|
21269
21323
|
function prepareLocalJobAuth(root, filename2) {
|
|
21270
21324
|
const read = (path, maximum) => {
|
|
21271
21325
|
assertLocalStatePath(root, path);
|
|
21272
21326
|
const metadata = lstatSync8(path);
|
|
21273
21327
|
if (!metadata.isFile() || metadata.isSymbolicLink() || metadata.nlink !== 1 || metadata.size > maximum) throw new Error();
|
|
21274
|
-
const bytes =
|
|
21328
|
+
const bytes = readFileSync12(path);
|
|
21275
21329
|
if (bytes.length > maximum) throw new Error();
|
|
21276
21330
|
return bytes;
|
|
21277
21331
|
};
|
|
@@ -21295,11 +21349,11 @@ function prepareLocalJobAuth(root, filename2) {
|
|
|
21295
21349
|
|
|
21296
21350
|
// src/local-job-trust-renewal.ts
|
|
21297
21351
|
import { createHash as createHash9 } from "node:crypto";
|
|
21298
|
-
import { lstatSync as lstatSync10, readFileSync as
|
|
21352
|
+
import { lstatSync as lstatSync10, readFileSync as readFileSync14 } from "node:fs";
|
|
21299
21353
|
import { isAbsolute as isAbsolute7, relative as relative2, resolve as resolve11 } from "node:path";
|
|
21300
21354
|
|
|
21301
21355
|
// src/workload-trust-sync.ts
|
|
21302
|
-
import { lstatSync as lstatSync9, readFileSync as
|
|
21356
|
+
import { lstatSync as lstatSync9, readFileSync as readFileSync13 } from "node:fs";
|
|
21303
21357
|
import { isAbsolute as isAbsolute6, resolve as resolve10 } from "node:path";
|
|
21304
21358
|
import { createHash as createHash8 } from "node:crypto";
|
|
21305
21359
|
function prepareWorkloadTrustSynchronization(filename2) {
|
|
@@ -21307,7 +21361,7 @@ function prepareWorkloadTrustSynchronization(filename2) {
|
|
|
21307
21361
|
if (!isAbsolute6(filename2)) throw new Error();
|
|
21308
21362
|
const metadata = lstatSync9(filename2);
|
|
21309
21363
|
if (!metadata.isFile() || metadata.isSymbolicLink() || metadata.nlink !== 1 || metadata.size > 65536) throw new Error();
|
|
21310
|
-
const bytes =
|
|
21364
|
+
const bytes = readFileSync13(filename2);
|
|
21311
21365
|
if (bytes.length > 65536) throw new Error();
|
|
21312
21366
|
const value = JSON.parse(new TextDecoder("utf8", { fatal: true }).decode(bytes));
|
|
21313
21367
|
const allowed = ["controlPlaneUrl", "agentId", "expectedScope", "managementIssuer", "managementAudience", "managementPublicKeyPem", "credentialFile", "trustFile", "stateFile", "intervalSeconds"];
|
|
@@ -21320,7 +21374,7 @@ function prepareWorkloadTrustSynchronization(filename2) {
|
|
|
21320
21374
|
const credential = () => {
|
|
21321
21375
|
const metadata2 = lstatSync9(credentialFile);
|
|
21322
21376
|
if (!metadata2.isFile() || metadata2.isSymbolicLink() || metadata2.nlink !== 1 || metadata2.size > 256 || process.platform !== "win32" && (metadata2.uid !== process.getuid?.() || (metadata2.mode & 63) !== 0)) throw new Error("Management credential unavailable");
|
|
21323
|
-
const bytes2 =
|
|
21377
|
+
const bytes2 = readFileSync13(credentialFile);
|
|
21324
21378
|
if (bytes2.length > 256) throw new Error("Management credential unavailable");
|
|
21325
21379
|
return new TextDecoder("utf8", { fatal: true }).decode(bytes2).trim();
|
|
21326
21380
|
};
|
|
@@ -21392,8 +21446,8 @@ function prepareLocalJobTrustRenewal(root, filename2, mount) {
|
|
|
21392
21446
|
throw new Error("Invalid reviewed native worker trust renewal; preserve trust and state and review explicitly");
|
|
21393
21447
|
}
|
|
21394
21448
|
}
|
|
21395
|
-
function createLocalJobTrustRenewal(root, mounts, settings = {}, dependencies = { createHash: createHash9, lstatSync: lstatSync10, readFileSync:
|
|
21396
|
-
const { createHash: createHash16, lstatSync: lstatSync19, readFileSync:
|
|
21449
|
+
function createLocalJobTrustRenewal(root, mounts, settings = {}, dependencies = { createHash: createHash9, lstatSync: lstatSync10, readFileSync: readFileSync14, isAbsolute: isAbsolute7, relative: relative2, resolve: resolve11, createPersistentApplicationAuthProvider, synchronizeApplicationAuthTrustWithDigest }) {
|
|
21450
|
+
const { createHash: createHash16, lstatSync: lstatSync19, readFileSync: readFileSync27, isAbsolute: isAbsolute17, relative: relative11, resolve: resolve24, createPersistentApplicationAuthProvider: createPersistentApplicationAuthProvider2, synchronizeApplicationAuthTrustWithDigest: synchronizeApplicationAuthTrustWithDigest2 } = dependencies;
|
|
21397
21451
|
const key = (filename2) => process.platform === "win32" ? resolve24(filename2).toLowerCase() : resolve24(filename2);
|
|
21398
21452
|
const groups = [];
|
|
21399
21453
|
for (const mount of mounts) {
|
|
@@ -21417,7 +21471,7 @@ function createLocalJobTrustRenewal(root, mounts, settings = {}, dependencies =
|
|
|
21417
21471
|
}
|
|
21418
21472
|
const metadata = lstatSync19(filename2);
|
|
21419
21473
|
if (!metadata.isFile() || metadata.nlink !== 1 || metadata.size > maximum || privateFile2 && process.platform !== "win32" && (metadata.uid !== process.getuid?.() || (metadata.mode & 63) !== 0)) throw new Error();
|
|
21420
|
-
const bytes =
|
|
21474
|
+
const bytes = readFileSync27(filename2);
|
|
21421
21475
|
if (bytes.length > maximum) throw new Error();
|
|
21422
21476
|
return bytes;
|
|
21423
21477
|
};
|
|
@@ -21498,11 +21552,11 @@ function prepareLocalJobWorker(root, directory2, artifacts, manifest, authFile,
|
|
|
21498
21552
|
if (trustSyncFile !== void 0 && authFile === void 0) throw new Error("Native worker trust renewal requires explicit reviewed auth mounts");
|
|
21499
21553
|
const authTrust = authFile === void 0 ? void 0 : prepareLocalJobAuth(root, authFile);
|
|
21500
21554
|
if (authTrust && trustSyncFile !== void 0) authTrust.renewal = prepareLocalJobTrustRenewal(root, trustSyncFile, authTrust);
|
|
21501
|
-
const workerFile =
|
|
21555
|
+
const workerFile = join11(resolve12(root, directory2), "workload.mjs"), metadataFile = join11(resolve12(root, directory2), "artifact.json");
|
|
21502
21556
|
for (const filename2 of [workerFile, metadataFile]) assertLocalStatePath(root, filename2);
|
|
21503
21557
|
if (!lstatSync11(workerFile).isFile() || lstatSync11(workerFile).size > 16777216 || !lstatSync11(metadataFile).isFile() || lstatSync11(metadataFile).size > 65536) throw new Error("Invalid bounded native worker artifact");
|
|
21504
|
-
const metadata = JSON.parse(
|
|
21505
|
-
const bundle =
|
|
21558
|
+
const metadata = JSON.parse(readFileSync15(metadataFile, "utf8"));
|
|
21559
|
+
const bundle = readFileSync15(workerFile);
|
|
21506
21560
|
const actual = createHash10("sha256").update(bundle).digest("hex");
|
|
21507
21561
|
const scheduleDiscovery = bundle.subarray(0, 100).toString("utf8").startsWith('var __backifyWorkerProtocols = ["hcr-v1","hcr-schedules-v1"];\n');
|
|
21508
21562
|
if (!metadata || metadata.schemaVersion !== 1 || metadata.kind !== "worker" || metadata.artifactVersion !== actual || metadata.manifestVersion !== createHash10("sha256").update(JSON.stringify(manifest)).digest("hex")) throw new Error("Native worker kind, bundle or manifest pin does not match the reviewed artifact");
|
|
@@ -21516,16 +21570,16 @@ function readLocalJobArtifacts(root, filename2) {
|
|
|
21516
21570
|
const path = resolve12(root, filename2);
|
|
21517
21571
|
assertLocalStatePath(root, path);
|
|
21518
21572
|
if (!lstatSync11(path).isFile() || lstatSync11(path).size > 16384) throw new Error("Reviewed job artifact admission exceeds supported bounds");
|
|
21519
|
-
return validateLocalJobArtifacts(JSON.parse(
|
|
21573
|
+
return validateLocalJobArtifacts(JSON.parse(readFileSync15(path, "utf8")));
|
|
21520
21574
|
}
|
|
21521
|
-
function createLocalJobExecutor(options, dependencies = { spawn: spawn2, createHash: createHash10, lstatSync: lstatSync11, readFileSync:
|
|
21522
|
-
const { spawn: spawn6, createHash: createHash16, lstatSync: lstatSync19, readFileSync:
|
|
21575
|
+
function createLocalJobExecutor(options, dependencies = { spawn: spawn2, createHash: createHash10, lstatSync: lstatSync11, readFileSync: readFileSync15, isAbsolute: isAbsolute8, relative: relative3, resolve: resolve12, validateWorkloadJobSchedules, createPersistentApplicationAuthProvider }) {
|
|
21576
|
+
const { spawn: spawn6, createHash: createHash16, lstatSync: lstatSync19, readFileSync: readFileSync27, isAbsolute: isAbsolute17, relative: relative11, resolve: resolve24, validateWorkloadJobSchedules: validateWorkloadJobSchedules2, createPersistentApplicationAuthProvider: createPersistentApplicationAuthProvider2 } = dependencies;
|
|
21523
21577
|
const assertReady = () => {
|
|
21524
21578
|
for (let current = resolve24(options.workerFile); current !== options.root; current = resolve24(current, "..")) {
|
|
21525
21579
|
const part = relative11(options.root, current);
|
|
21526
21580
|
if (part === ".." || part.startsWith("../") || part.startsWith("..\\") || isAbsolute17(part) || lstatSync19(current).isSymbolicLink()) throw new Error("Native worker paths or pins changed");
|
|
21527
21581
|
}
|
|
21528
|
-
if (!lstatSync19(options.workerFile).isFile() || lstatSync19(options.workerFile).size > 16777216 || createHash16("sha256").update(
|
|
21582
|
+
if (!lstatSync19(options.workerFile).isFile() || lstatSync19(options.workerFile).size > 16777216 || createHash16("sha256").update(readFileSync27(options.workerFile)).digest("hex") !== options.artifact.artifactVersion) throw new Error("Native worker paths or pins changed");
|
|
21529
21583
|
if (options.authTrust) {
|
|
21530
21584
|
try {
|
|
21531
21585
|
const mount = options.authTrust;
|
|
@@ -21537,7 +21591,7 @@ function createLocalJobExecutor(options, dependencies = { spawn: spawn2, createH
|
|
|
21537
21591
|
const metadata = lstatSync19(path);
|
|
21538
21592
|
if (!metadata.isFile() || metadata.nlink !== 1 || metadata.size > (path === mount.trustFile ? 131072 : 2048)) throw new Error();
|
|
21539
21593
|
}
|
|
21540
|
-
const bytes =
|
|
21594
|
+
const bytes = readFileSync27(mount.trustFile);
|
|
21541
21595
|
if (bytes.length > 131072 || createHash16("sha256").update(bytes).digest("hex") !== mount.trustDigest) throw new Error();
|
|
21542
21596
|
const trust = JSON.parse(new TextDecoder("utf8", { fatal: true }).decode(bytes));
|
|
21543
21597
|
if (trust.revision !== mount.revision) throw new Error();
|
|
@@ -21911,9 +21965,9 @@ process.on("SIGTERM", stop); process.on("SIGINT", stop); process.once("disconnec
|
|
|
21911
21965
|
|
|
21912
21966
|
// src/local-frontend.ts
|
|
21913
21967
|
import { spawn as spawn3 } from "node:child_process";
|
|
21914
|
-
import { readFileSync as
|
|
21968
|
+
import { readFileSync as readFileSync17, realpathSync as realpathSync3, existsSync as existsSync11, statSync } from "node:fs";
|
|
21915
21969
|
import { createRequire as createRequire3 } from "node:module";
|
|
21916
|
-
import { dirname as dirname10, isAbsolute as isAbsolute10, join as
|
|
21970
|
+
import { dirname as dirname10, isAbsolute as isAbsolute10, join as join13, relative as relative5, resolve as resolve14 } from "node:path";
|
|
21917
21971
|
import { pathToFileURL } from "node:url";
|
|
21918
21972
|
|
|
21919
21973
|
// src/local-frontend-guard.ts
|
|
@@ -21981,8 +22035,8 @@ await server.listen();
|
|
|
21981
22035
|
|
|
21982
22036
|
// src/local-static-frontend.ts
|
|
21983
22037
|
import { createServer as createServer4 } from "node:http";
|
|
21984
|
-
import { lstatSync as lstatSync12, readFileSync as
|
|
21985
|
-
import { extname as extname2, isAbsolute as isAbsolute9, join as
|
|
22038
|
+
import { lstatSync as lstatSync12, readFileSync as readFileSync16, realpathSync as realpathSync2, watch } from "node:fs";
|
|
22039
|
+
import { extname as extname2, isAbsolute as isAbsolute9, join as join12, relative as relative4, resolve as resolve13, sep as sep4 } from "node:path";
|
|
21986
22040
|
var contentTypes = { ".html": "text/html; charset=utf-8", ".js": "text/javascript; charset=utf-8", ".mjs": "text/javascript; charset=utf-8", ".css": "text/css; charset=utf-8", ".json": "application/json", ".txt": "text/plain; charset=utf-8", ".svg": "image/svg+xml", ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".gif": "image/gif", ".webp": "image/webp", ".ico": "image/x-icon", ".woff": "font/woff", ".woff2": "font/woff2", ".ttf": "font/ttf" };
|
|
21987
22041
|
var publicParts = (parts) => parts.every((part) => part.length > 0 && !part.startsWith(".") && !part.includes(":") && !part.includes("\\") && !part.includes("\0") && !["node_modules", "__backify"].includes(part.toLowerCase()));
|
|
21988
22042
|
function publicFile(directory2, pathname) {
|
|
@@ -21994,7 +22048,7 @@ function publicFile(directory2, pathname) {
|
|
|
21994
22048
|
let current = directory2;
|
|
21995
22049
|
if (lstatSync12(current).isSymbolicLink() || realpathSync2(current) !== directory2) throw new Error("refused");
|
|
21996
22050
|
for (const segment of parts) {
|
|
21997
|
-
current =
|
|
22051
|
+
current = join12(current, segment);
|
|
21998
22052
|
if (lstatSync12(current).isSymbolicLink()) throw new Error("refused");
|
|
21999
22053
|
}
|
|
22000
22054
|
const stat = lstatSync12(filename2);
|
|
@@ -22025,7 +22079,7 @@ async function startLocalStaticFrontend(directory2, port, backendUrl) {
|
|
|
22025
22079
|
if (pathname === "/__backify/revision") return send(200, "text/plain", String(revision));
|
|
22026
22080
|
if (pathname === "/__backify/config.json") return send(200, "application/json", JSON.stringify({ backendUrl: backendUrl ?? null }));
|
|
22027
22081
|
const filename2 = publicFile(directory2, pathname);
|
|
22028
|
-
const content =
|
|
22082
|
+
const content = readFileSync16(filename2);
|
|
22029
22083
|
if (content.length > 5242880) throw new Error("refused");
|
|
22030
22084
|
const extension = extname2(filename2).toLowerCase();
|
|
22031
22085
|
const body = extension === ".html" ? content.toString("utf8") + '\n<script src="/__backify/reload.js?revision=' + revision + '"></script>\n' : content;
|
|
@@ -22075,15 +22129,15 @@ function prepareLocalFrontend(root, options, privateFiles = []) {
|
|
|
22075
22129
|
if (part && part.split(/[\\/]/).some((segment) => segment.startsWith(".") || segment.toLowerCase() === "node_modules")) throw new Error("Static frontend must not use a private state or dependency directory");
|
|
22076
22130
|
return prepareLocalStaticFrontend(directory2);
|
|
22077
22131
|
}
|
|
22078
|
-
if (!
|
|
22079
|
-
const require3 = createRequire3(
|
|
22132
|
+
if (!existsSync11(join13(directory2, "package.json"))) throw new Error("Frontend requires an existing package.json and installed Vite");
|
|
22133
|
+
const require3 = createRequire3(join13(directory2, "package.json"));
|
|
22080
22134
|
let packagePath;
|
|
22081
22135
|
try {
|
|
22082
22136
|
packagePath = require3.resolve("vite/package.json");
|
|
22083
22137
|
} catch {
|
|
22084
22138
|
throw new Error("Frontend requires locally installed Vite; Backify does not install dependencies automatically");
|
|
22085
22139
|
}
|
|
22086
|
-
const metadata = JSON.parse(
|
|
22140
|
+
const metadata = JSON.parse(readFileSync17(packagePath, "utf8"));
|
|
22087
22141
|
if (metadata.name !== "vite" || typeof metadata.bin?.vite !== "string") throw new Error("Installed Vite has no supported CLI entrypoint");
|
|
22088
22142
|
const executable = realpathSync3(resolve14(dirname10(packagePath), metadata.bin.vite));
|
|
22089
22143
|
const executablePart = relative5(realpathSync3(dirname10(packagePath)), executable);
|
|
@@ -22147,7 +22201,7 @@ async function startLocalFrontend(prepared, port, backendUrl) {
|
|
|
22147
22201
|
}
|
|
22148
22202
|
|
|
22149
22203
|
// src/local-identity.ts
|
|
22150
|
-
import { readFileSync as
|
|
22204
|
+
import { readFileSync as readFileSync18, statSync as statSync2 } from "node:fs";
|
|
22151
22205
|
import { resolve as resolve15 } from "node:path";
|
|
22152
22206
|
|
|
22153
22207
|
// ../sdk/dist/local-identity.js
|
|
@@ -22255,7 +22309,7 @@ function prepareLocalIdentity(root, filename2) {
|
|
|
22255
22309
|
if (!statSync2(path).isFile() || statSync2(path).size > 16384) throw new Error("Local identity profiles require a file at most 16 KiB");
|
|
22256
22310
|
let input;
|
|
22257
22311
|
try {
|
|
22258
|
-
input = JSON.parse(
|
|
22312
|
+
input = JSON.parse(readFileSync18(path, "utf8"));
|
|
22259
22313
|
} catch {
|
|
22260
22314
|
throw new Error("Invalid local identity profile JSON");
|
|
22261
22315
|
}
|
|
@@ -22288,7 +22342,7 @@ function localIdentityCommand(args2) {
|
|
|
22288
22342
|
}
|
|
22289
22343
|
|
|
22290
22344
|
// src/local-job-history.ts
|
|
22291
|
-
import { lstatSync as lstatSync13, readFileSync as
|
|
22345
|
+
import { lstatSync as lstatSync13, readFileSync as readFileSync19 } from "node:fs";
|
|
22292
22346
|
import { isAbsolute as isAbsolute11, resolve as resolve16 } from "node:path";
|
|
22293
22347
|
function prepareLocalJobHistory(root, filename2, artifacts, manifest, current) {
|
|
22294
22348
|
if (filename2 === void 0) return [];
|
|
@@ -22298,7 +22352,7 @@ function prepareLocalJobHistory(root, filename2, artifacts, manifest, current) {
|
|
|
22298
22352
|
assertLocalStatePath(root, path);
|
|
22299
22353
|
const metadata = lstatSync13(path);
|
|
22300
22354
|
if (!metadata.isFile() || metadata.isSymbolicLink() || metadata.nlink !== 1 || metadata.size > maximum) throw new Error();
|
|
22301
|
-
const bytes =
|
|
22355
|
+
const bytes = readFileSync19(path);
|
|
22302
22356
|
if (bytes.length > maximum) throw new Error();
|
|
22303
22357
|
return new TextDecoder("utf8", { fatal: true }).decode(bytes);
|
|
22304
22358
|
};
|
|
@@ -22345,13 +22399,13 @@ function prepareLocalJobHistory(root, filename2, artifacts, manifest, current) {
|
|
|
22345
22399
|
|
|
22346
22400
|
// src/local-secrets.ts
|
|
22347
22401
|
import { createCipheriv, createDecipheriv, randomBytes as randomBytes5, randomUUID as randomUUID9 } from "node:crypto";
|
|
22348
|
-
import { closeSync as closeSync3, existsSync as
|
|
22349
|
-
import { dirname as dirname11, isAbsolute as isAbsolute12, join as
|
|
22402
|
+
import { closeSync as closeSync3, existsSync as existsSync12, fsyncSync as fsyncSync3, lstatSync as lstatSync14, mkdirSync as mkdirSync5, openSync as openSync3, readFileSync as readFileSync20, realpathSync as realpathSync4, writeFileSync as writeFileSync10 } from "node:fs";
|
|
22403
|
+
import { dirname as dirname11, isAbsolute as isAbsolute12, join as join14, relative as relative6, resolve as resolve17 } from "node:path";
|
|
22350
22404
|
var maximumBytes2 = 1048576;
|
|
22351
22405
|
var secretName = /^[A-Z][A-Z0-9_]{0,127}$/;
|
|
22352
22406
|
var failure = () => new Error("Local secret vault unavailable or invalid; review the vault and external key privately");
|
|
22353
22407
|
function vaultPath(root) {
|
|
22354
|
-
return
|
|
22408
|
+
return join14(realpathSync4(root), ".backify", "dev", "secrets.enc.json");
|
|
22355
22409
|
}
|
|
22356
22410
|
function inside(root, filename2) {
|
|
22357
22411
|
const part = relative6(root, filename2);
|
|
@@ -22364,7 +22418,7 @@ function privateFile(filename2, limit) {
|
|
|
22364
22418
|
}
|
|
22365
22419
|
const stat = lstatSync14(filename2);
|
|
22366
22420
|
if (!stat.isFile() || stat.size > limit || stat.nlink !== 1 || process.platform !== "win32" && (stat.mode & 63) !== 0) throw failure();
|
|
22367
|
-
return
|
|
22421
|
+
return readFileSync20(filename2);
|
|
22368
22422
|
}
|
|
22369
22423
|
function externalKey(root, filename2) {
|
|
22370
22424
|
const keyFile = resolve17(filename2);
|
|
@@ -22403,15 +22457,15 @@ function writePrivate2(filename2, value) {
|
|
|
22403
22457
|
}
|
|
22404
22458
|
}
|
|
22405
22459
|
function ensureIgnored(root) {
|
|
22406
|
-
const filename2 =
|
|
22460
|
+
const filename2 = join14(root, ".gitignore");
|
|
22407
22461
|
assertLocalStatePath(root, filename2);
|
|
22408
|
-
const current =
|
|
22462
|
+
const current = existsSync12(filename2) ? readFileSync20(filename2, "utf8") : "";
|
|
22409
22463
|
if (!current.split(/\r?\n/).some((line) => line.trim() === ".backify/")) writeFileSync10(filename2, current + (current && !current.endsWith("\n") ? "\n" : "") + ".backify/\n");
|
|
22410
22464
|
}
|
|
22411
22465
|
function readLocalSecrets(root, application, keyFile) {
|
|
22412
22466
|
const filename2 = vaultPath(root);
|
|
22413
22467
|
assertLocalStatePath(root, filename2);
|
|
22414
|
-
if (!
|
|
22468
|
+
if (!existsSync12(filename2) && keyFile === void 0) return {};
|
|
22415
22469
|
if (!keyFile) throw new Error("Encrypted local secrets require --local-secrets-key <external-key-file>");
|
|
22416
22470
|
let key, plaintext;
|
|
22417
22471
|
try {
|
|
@@ -22441,7 +22495,7 @@ function readLocalSecrets(root, application, keyFile) {
|
|
|
22441
22495
|
function initializeLocalSecrets(root, application, keyFile) {
|
|
22442
22496
|
const filename2 = vaultPath(root), external = resolve17(keyFile);
|
|
22443
22497
|
assertLocalStatePath(root, filename2);
|
|
22444
|
-
if (
|
|
22498
|
+
if (existsSync12(filename2) || existsSync12(external)) throw new Error("Local secret initialization never overwrites an existing vault or key");
|
|
22445
22499
|
if (inside(realpathSync4(root), external) || inside(realpathSync4(root), realpathSync4(dirname11(external)))) throw new Error("Local secret key must be outside the repository in an existing private directory");
|
|
22446
22500
|
for (let current = dirname11(external); ; current = dirname11(current)) {
|
|
22447
22501
|
const stat = lstatSync14(current);
|
|
@@ -22453,7 +22507,7 @@ function initializeLocalSecrets(root, application, keyFile) {
|
|
|
22453
22507
|
const release2 = acquireLocalLease(root, ".backify/dev/secrets.lock");
|
|
22454
22508
|
const key = randomBytes5(32);
|
|
22455
22509
|
try {
|
|
22456
|
-
if (
|
|
22510
|
+
if (existsSync12(filename2)) throw failure();
|
|
22457
22511
|
mkdirSync5(dirname11(filename2), { recursive: true, mode: 448 });
|
|
22458
22512
|
writePrivate2(external, key.toString("hex"));
|
|
22459
22513
|
writePrivate2(filename2, encrypt(root, application, key, {}));
|
|
@@ -22510,11 +22564,11 @@ async function localSecretsCommand(args2, root, application, input = process.std
|
|
|
22510
22564
|
|
|
22511
22565
|
// src/local-development.ts
|
|
22512
22566
|
function localManifest(root = process.cwd()) {
|
|
22513
|
-
const filename2 =
|
|
22514
|
-
if (!
|
|
22515
|
-
const manifest = parseApplicationManifest(
|
|
22567
|
+
const filename2 = join15(root, "backify.yaml");
|
|
22568
|
+
if (!existsSync13(filename2)) throw new Error("Create backify.yaml with version, application, runtime and explicit capabilities before running backify dev");
|
|
22569
|
+
const manifest = parseApplicationManifest(readFileSync21(filename2, "utf8"));
|
|
22516
22570
|
const entry = resolve18(root, manifest.runtime.entrypoint);
|
|
22517
|
-
if (!
|
|
22571
|
+
if (!existsSync13(entry) || !inside2(root, realpathSync5(entry))) throw new Error("Runtime entrypoint must exist inside this repository");
|
|
22518
22572
|
const discovered = analyzeSources(repositorySources(root));
|
|
22519
22573
|
const diagnostics = manifestDiagnostics(manifest, Object.keys(discovered.capabilities), discovered.capabilities.auth?.configuration);
|
|
22520
22574
|
if (diagnostics.length) throw new Error(diagnostics.map((diagnostic) => diagnostic.message).join("; "));
|
|
@@ -22525,12 +22579,12 @@ function inside2(root, path) {
|
|
|
22525
22579
|
return part !== ".." && !part.startsWith(".." + (process.platform === "win32" ? "\\" : "/")) && !isAbsolute13(part);
|
|
22526
22580
|
}
|
|
22527
22581
|
function sessionPath(root) {
|
|
22528
|
-
return
|
|
22582
|
+
return join15(root, ".backify", "dev", "session.json");
|
|
22529
22583
|
}
|
|
22530
22584
|
async function localRequest(path, input, root = process.cwd()) {
|
|
22531
22585
|
if (!/^\/v1\/[a-z/-]+$/.test(path)) throw new Error("Invalid local command path");
|
|
22532
|
-
if (!
|
|
22533
|
-
const session = JSON.parse(
|
|
22586
|
+
if (!existsSync13(sessionPath(root))) throw new Error("Start backify dev before using local commands");
|
|
22587
|
+
const session = JSON.parse(readFileSync21(sessionPath(root), "utf8"));
|
|
22534
22588
|
if (session.version !== 1 || !Number.isInteger(session.port) || session.port < 1 || session.port > 65535 || !/^[a-f0-9]{64}$/.test(session.token)) throw new Error("Invalid local session");
|
|
22535
22589
|
const response = await fetch("http://127.0.0.1:" + session.port + path, { method: input === void 0 ? "GET" : "POST", headers: { authorization: "Bearer " + session.token, "content-type": "application/json" }, body: input === void 0 ? void 0 : JSON.stringify(input), redirect: "error", signal: AbortSignal.timeout(35e3) });
|
|
22536
22590
|
if (!response.ok) {
|
|
@@ -22581,17 +22635,17 @@ async function startLocalDevelopment(options = {}) {
|
|
|
22581
22635
|
const identityProfiles = prepareLocalIdentity(root, options.identityUsers);
|
|
22582
22636
|
if (identityProfiles && (!manifest.capabilities.auth || manifest.capabilities.auth.enabled === false || options.backendPort === void 0)) throw new Error("Explicit local identities require capabilities.auth and --backend-port");
|
|
22583
22637
|
const preparedFrontend = prepareLocalFrontend(root, options, options.localSecretsKey ? [realpathSync5(resolve18(options.localSecretsKey))] : []);
|
|
22584
|
-
const ignorePath =
|
|
22585
|
-
if (
|
|
22586
|
-
const ignore =
|
|
22638
|
+
const ignorePath = join15(root, ".gitignore");
|
|
22639
|
+
if (existsSync13(ignorePath) && lstatSync15(ignorePath).isSymbolicLink()) throw new Error("Local development cannot update a symlinked .gitignore");
|
|
22640
|
+
const ignore = existsSync13(ignorePath) ? readFileSync21(ignorePath, "utf8") : "";
|
|
22587
22641
|
if (!ignore.split(/\r?\n/).some((line) => line.trim() === ".backify/")) writeFileSync11(ignorePath, ignore + (ignore.endsWith("\n") || !ignore ? "" : "\n") + ".backify/\n");
|
|
22588
22642
|
if (options.port !== void 0 && (!Number.isInteger(options.port) || options.port < 0 || options.port > 65535)) throw new Error("Dashboard port must be 0-65535");
|
|
22589
|
-
const directory2 =
|
|
22643
|
+
const directory2 = join15(root, ".backify", "dev");
|
|
22590
22644
|
assertLocalStatePath(root, directory2);
|
|
22591
|
-
for (const filename2 of ["session.json", "session.json.tmp", "worker.mjs", "worker.mjs.map", "state.json", "state.json.tmp"]) assertLocalStatePath(root,
|
|
22645
|
+
for (const filename2 of ["session.json", "session.json.tmp", "worker.mjs", "worker.mjs.map", "state.json", "state.json.tmp"]) assertLocalStatePath(root, join15(directory2, filename2));
|
|
22592
22646
|
mkdirSync6(directory2, { recursive: true });
|
|
22593
22647
|
if (!inside2(root, realpathSync5(directory2))) throw new Error("Local state directory must remain inside this repository");
|
|
22594
|
-
if (
|
|
22648
|
+
if (existsSync13(sessionPath(root))) {
|
|
22595
22649
|
try {
|
|
22596
22650
|
await localRequest("/v1/status", void 0, root);
|
|
22597
22651
|
throw new Error("Backify dev is already running for this repository");
|
|
@@ -22629,7 +22683,7 @@ async function startLocalDevelopment(options = {}) {
|
|
|
22629
22683
|
return { ...worker, authTrust };
|
|
22630
22684
|
};
|
|
22631
22685
|
const identityEnvironment = () => ({ BACKIFY_LOCAL_IDENTITY: identityProfiles ? JSON.stringify({ ...identityProfiles, scope: identityScope, requestOrigins: [backendUrl, frontend?.url].filter(Boolean) }) : "", BACKIFY_LOCAL_JOB_WORKER: jobWorker ? JSON.stringify({ ...workerEnvironment(jobWorker), scope: identityScope, historicalWorkers: historicalWorkers.map(workerEnvironment) }) : "", BACKIFY_LOCAL_JOBS: services?.jobs ? "postgres-jobs" : "snapshot-emulator" });
|
|
22632
|
-
const outfile =
|
|
22686
|
+
const outfile = join15(directory2, "worker.mjs");
|
|
22633
22687
|
let child;
|
|
22634
22688
|
const trustRenewal = createLocalJobTrustRenewal(root, authMounts, { onFailure: () => console.error("Native worker trust renewal unavailable; existing validity and pin guards remain enforced."), onUpdate: () => {
|
|
22635
22689
|
if (child?.connected) child.send({ type: "trust-renewed", workers: activeWorkers.filter((worker) => worker.authTrust).map((worker) => ({ artifactVersion: worker.artifact.artifactVersion, revision: worker.authTrust.revision, trustDigest: worker.authTrust.trustDigest })) }, (error) => {
|
|
@@ -22667,8 +22721,8 @@ async function startLocalDevelopment(options = {}) {
|
|
|
22667
22721
|
}
|
|
22668
22722
|
await stopChild(child);
|
|
22669
22723
|
if (stopping) return;
|
|
22670
|
-
const version = createHash13("sha256").update(
|
|
22671
|
-
const worker = spawn4(process.execPath, [outfile], { cwd: root, windowsHide: true, stdio: ["ignore", 2, 2, "ipc"], env: { ...process.env, ...identityEnvironment(), BACKIFY_LOCAL_SECRETS_IPC: "1", HOST: "127.0.0.1", ...backendPort === void 0 ? {} : { PORT: String(backendPort) }, BACKIFY_LOCAL_BACKEND_URL: backendUrl ?? "", BACKIFY_LOCAL_FRONTEND_URL: frontend?.url ?? "", BACKIFY_LOCAL_DATABASE_ENABLED: manifest.capabilities.database && manifest.capabilities.database.enabled !== false ? "1" : "0", BACKIFY_LOCAL_STORAGE_ENABLED: manifest.capabilities.storage && manifest.capabilities.storage.enabled !== false ? "1" : "0", BACKIFY_LOCAL_STORAGE_BUCKETS: JSON.stringify(manifest.capabilities.storage?.buckets?.map((bucket) => bucket.name) ?? (manifest.capabilities.storage ? ["default"] : [])), BACKIFY_LOCAL_TOKEN: token, BACKIFY_LOCAL_PORT: String(dashboardPort), BACKIFY_LOCAL_STATE:
|
|
22724
|
+
const version = createHash13("sha256").update(readFileSync21(outfile)).update(services?.configurationFingerprint ?? "lightweight").digest("hex");
|
|
22725
|
+
const worker = spawn4(process.execPath, [outfile], { cwd: root, windowsHide: true, stdio: ["ignore", 2, 2, "ipc"], env: { ...process.env, ...identityEnvironment(), BACKIFY_LOCAL_SECRETS_IPC: "1", HOST: "127.0.0.1", ...backendPort === void 0 ? {} : { PORT: String(backendPort) }, BACKIFY_LOCAL_BACKEND_URL: backendUrl ?? "", BACKIFY_LOCAL_FRONTEND_URL: frontend?.url ?? "", BACKIFY_LOCAL_DATABASE_ENABLED: manifest.capabilities.database && manifest.capabilities.database.enabled !== false ? "1" : "0", BACKIFY_LOCAL_STORAGE_ENABLED: manifest.capabilities.storage && manifest.capabilities.storage.enabled !== false ? "1" : "0", BACKIFY_LOCAL_STORAGE_BUCKETS: JSON.stringify(manifest.capabilities.storage?.buckets?.map((bucket) => bucket.name) ?? (manifest.capabilities.storage ? ["default"] : [])), BACKIFY_LOCAL_TOKEN: token, BACKIFY_LOCAL_PORT: String(dashboardPort), BACKIFY_LOCAL_STATE: join15(directory2, "state.json"), BACKIFY_LOCAL_VERSION: version, BACKIFY_LOCAL_HCR_URL: services?.runtimeUrl ?? "", BACKIFY_LOCAL_WORKLOAD_TOKEN_PATH: services?.tokenPath ?? "", BACKIFY_LOCAL_DATABASE: services ? services.database ? "postgres" : "disabled" : "document-emulator", BACKIFY_LOCAL_EVENTS: services?.events ? "postgres-events" : services ? "disabled" : "snapshot-emulator", BACKIFY_LOCAL_STORAGE: services ? services.storage ? "filesystem" : "disabled" : "snapshot-emulator" } });
|
|
22672
22726
|
child = worker;
|
|
22673
22727
|
worker.send({ type: "local-secrets", secrets }, (error) => {
|
|
22674
22728
|
if (error) {
|
|
@@ -22710,9 +22764,9 @@ async function startLocalDevelopment(options = {}) {
|
|
|
22710
22764
|
if (services && JSON.stringify(updated.capabilities) !== JSON.stringify(manifest.capabilities)) throw new Error("Full-fidelity capability or migration intent changed; restart backify dev to review and apply it");
|
|
22711
22765
|
if (updated.runtime.entrypoint !== manifest.runtime.entrypoint) throw new Error("Runtime entrypoint changed; restart backify dev");
|
|
22712
22766
|
} catch (error) {
|
|
22713
|
-
return { errors: [{ text: error instanceof Error ? error.message : "Manifest validation failed" }], watchFiles: [
|
|
22767
|
+
return { errors: [{ text: error instanceof Error ? error.message : "Manifest validation failed" }], watchFiles: [join15(root, "backify.yaml")] };
|
|
22714
22768
|
}
|
|
22715
|
-
return { contents:
|
|
22769
|
+
return { contents: readFileSync21(input.path, "utf8"), loader: input.path.endsWith(".tsx") ? "tsx" : /\.(ts|mts|cts)$/.test(input.path) ? "ts" : input.path.endsWith(".jsx") ? "jsx" : "js", watchFiles: [join15(root, "backify.yaml")] };
|
|
22716
22770
|
});
|
|
22717
22771
|
build3.onEnd((result) => {
|
|
22718
22772
|
if (result.errors.length) rejectStartup(new Error("Local application build failed"));
|
|
@@ -22768,8 +22822,8 @@ async function startLocalDevelopment(options = {}) {
|
|
|
22768
22822
|
}
|
|
22769
22823
|
}
|
|
22770
22824
|
}
|
|
22771
|
-
if (
|
|
22772
|
-
const session = JSON.parse(
|
|
22825
|
+
if (existsSync13(sessionPath(root))) {
|
|
22826
|
+
const session = JSON.parse(readFileSync21(sessionPath(root), "utf8"));
|
|
22773
22827
|
if (session.token === token) unlinkSync5(sessionPath(root));
|
|
22774
22828
|
}
|
|
22775
22829
|
};
|
|
@@ -22783,11 +22837,11 @@ async function startLocalDevelopment(options = {}) {
|
|
|
22783
22837
|
}
|
|
22784
22838
|
async function runLocalTests(root = process.cwd()) {
|
|
22785
22839
|
const manifest = localManifest(root);
|
|
22786
|
-
const project = JSON.parse(
|
|
22840
|
+
const project = JSON.parse(readFileSync21(join15(root, "package.json"), "utf8"));
|
|
22787
22841
|
if (!project.scripts?.test) throw new Error("Add a test script to package.json so AI agents can run backify test");
|
|
22788
22842
|
const result = await new Promise((resolveResult, reject) => {
|
|
22789
|
-
const npmPath = process.platform === "win32" ? process.env.npm_execpath ??
|
|
22790
|
-
if (npmPath && !
|
|
22843
|
+
const npmPath = process.platform === "win32" ? process.env.npm_execpath ?? join15(dirname12(process.execPath), "node_modules", "npm", "bin", "npm-cli.js") : void 0;
|
|
22844
|
+
if (npmPath && !existsSync13(npmPath)) {
|
|
22791
22845
|
reject(new Error("Cannot locate npm-cli.js; run backify test through npx or npm"));
|
|
22792
22846
|
return;
|
|
22793
22847
|
}
|
|
@@ -22814,7 +22868,7 @@ function digest3(contents) {
|
|
|
22814
22868
|
}
|
|
22815
22869
|
function packageDirectory(filename2) {
|
|
22816
22870
|
for (let current = dirname13(filename2); ; current = dirname13(current)) {
|
|
22817
|
-
if (
|
|
22871
|
+
if (existsSync14(join16(current, "package.json"))) return current;
|
|
22818
22872
|
if (dirname13(current) === current) throw new Error("Cannot locate an installed dependency package");
|
|
22819
22873
|
}
|
|
22820
22874
|
}
|
|
@@ -22926,11 +22980,11 @@ async function prepareWorkload(options) {
|
|
|
22926
22980
|
context3.onResolve({ filter: /./ }, async (input) => {
|
|
22927
22981
|
if (input.pluginData?.backifyResolved) return;
|
|
22928
22982
|
if (input.path === "@backifydev/sdk/local" || input.path === "@backifydev/sdk/runtime" && input.namespace !== "backify-workload-host") return { errors: [{ text: "Production application code must not import local emulators or host-only runtime configuration" }] };
|
|
22929
|
-
const resolved = await context3.resolve(input.path, { importer: input.namespace === "backify-workload-host" ?
|
|
22983
|
+
const resolved = await context3.resolve(input.path, { importer: input.namespace === "backify-workload-host" ? join16(root, input.importer) : input.importer, resolveDir: input.resolveDir, kind: input.kind, pluginData: { backifyResolved: true } });
|
|
22930
22984
|
if (!resolved.external && !resolved.errors.length && resolved.path) {
|
|
22931
22985
|
const directory2 = realpathSync6(packageDirectory(resolved.path));
|
|
22932
22986
|
const target = relative8(directory2, realpathSync6(resolved.path)).replaceAll("\\", "/");
|
|
22933
|
-
if (JSON.parse(
|
|
22987
|
+
if (JSON.parse(readFileSync22(join16(directory2, "package.json"), "utf8")).name === "@backifydev/sdk") {
|
|
22934
22988
|
if (/^(src|dist)\/local\.(ts|js)$/.test(target) || /^(src|dist)\/runtime\.(ts|js)$/.test(target) && input.namespace !== "backify-workload-host" && !inside3(directory2, realpathSync6(input.importer))) return { errors: [{ text: "Production application code must not import local emulators or host-only runtime configuration" }] };
|
|
22935
22989
|
}
|
|
22936
22990
|
if (!isAbsolute14(input.path) && !input.path.startsWith(".")) trustedPackages.add(directory2);
|
|
@@ -22994,14 +23048,14 @@ async function packageWorkload(options) {
|
|
|
22994
23048
|
const files = { "workload.mjs": bundle, "artifact.json": JSON.stringify(plan, null, 2) + "\n", "Dockerfile": dockerfile, ".dockerignore": "**\n!Dockerfile\n!workload.mjs\n!artifact.json\n!.dockerignore\n" };
|
|
22995
23049
|
const output = resolve19(root, options.output ?? ".backify/artifacts/" + options.kind + "-" + plan.artifactVersion.slice(0, 16));
|
|
22996
23050
|
assertLocalStatePath(root, output);
|
|
22997
|
-
if (
|
|
23051
|
+
if (existsSync14(output)) {
|
|
22998
23052
|
if (JSON.stringify(readdirSync6(output).sort()) !== JSON.stringify(Object.keys(files).sort()) || Object.entries(files).some(([name2, value]) => {
|
|
22999
|
-
assertLocalStatePath(root,
|
|
23000
|
-
return !
|
|
23053
|
+
assertLocalStatePath(root, join16(output, name2));
|
|
23054
|
+
return !readFileSync22(join16(output, name2)).equals(Buffer.from(value));
|
|
23001
23055
|
})) throw new Error("Refusing to overwrite an existing workload artifact directory");
|
|
23002
23056
|
} else {
|
|
23003
23057
|
mkdirSync7(output, { recursive: true });
|
|
23004
|
-
for (const [name2, value] of Object.entries(files)) writeFileSync12(
|
|
23058
|
+
for (const [name2, value] of Object.entries(files)) writeFileSync12(join16(output, name2), value, { flag: "wx", mode: 384 });
|
|
23005
23059
|
}
|
|
23006
23060
|
return { ...plan, outputDirectory: relative8(root, output).replaceAll("\\", "/") };
|
|
23007
23061
|
}
|
|
@@ -23010,12 +23064,12 @@ async function packageWorkload(options) {
|
|
|
23010
23064
|
import { execFileSync } from "node:child_process";
|
|
23011
23065
|
import { mkdirSync as mkdirSync8, mkdtempSync as mkdtempSync2, readdirSync as readdirSync7, rmSync as rmSync2, writeFileSync as writeFileSync13 } from "node:fs";
|
|
23012
23066
|
import { tmpdir } from "node:os";
|
|
23013
|
-
import { basename as basename3, dirname as dirname15, isAbsolute as isAbsolute15, join as
|
|
23067
|
+
import { basename as basename3, dirname as dirname15, isAbsolute as isAbsolute15, join as join18, relative as relative9, resolve as resolve21 } from "node:path";
|
|
23014
23068
|
|
|
23015
23069
|
// src/workload-provenance-oci.ts
|
|
23016
23070
|
import { createHash as createHash15 } from "node:crypto";
|
|
23017
|
-
import { createReadStream, lstatSync as lstatSync16, readFileSync as
|
|
23018
|
-
import { dirname as dirname14, join as
|
|
23071
|
+
import { createReadStream, lstatSync as lstatSync16, readFileSync as readFileSync23 } from "node:fs";
|
|
23072
|
+
import { dirname as dirname14, join as join17, parse as parse3, resolve as resolve20 } from "node:path";
|
|
23019
23073
|
import { Transform, Writable } from "node:stream";
|
|
23020
23074
|
import { pipeline } from "node:stream/promises";
|
|
23021
23075
|
import { createGunzip } from "node:zlib";
|
|
@@ -23037,7 +23091,7 @@ function provenanceFile(filename2, maximum) {
|
|
|
23037
23091
|
}
|
|
23038
23092
|
const stat = lstatSync16(absolute);
|
|
23039
23093
|
if (!stat.isFile() || stat.nlink !== 1 || stat.size < 1 || stat.size > maximum) throw new Error("Invalid provenance file");
|
|
23040
|
-
const bytes =
|
|
23094
|
+
const bytes = readFileSync23(absolute);
|
|
23041
23095
|
if (bytes.length !== stat.size) throw new Error("Provenance file changed during read");
|
|
23042
23096
|
return bytes;
|
|
23043
23097
|
}
|
|
@@ -23046,7 +23100,7 @@ function descriptor(value) {
|
|
|
23046
23100
|
return value;
|
|
23047
23101
|
}
|
|
23048
23102
|
function blobPath(root, value) {
|
|
23049
|
-
return
|
|
23103
|
+
return join17(root, "blobs", "sha256", descriptor(value).digest.slice(7));
|
|
23050
23104
|
}
|
|
23051
23105
|
function jsonBlob(root, value) {
|
|
23052
23106
|
const bytes = provenanceFile(blobPath(root, value), 1024 * 1024);
|
|
@@ -23055,8 +23109,8 @@ function jsonBlob(root, value) {
|
|
|
23055
23109
|
}
|
|
23056
23110
|
async function inspectProvenanceImage(root, architecture, requestedDigest) {
|
|
23057
23111
|
if (!["amd64", "arm64"].includes(architecture) || requestedDigest && !digestPattern.test(requestedDigest)) throw new Error("Invalid OCI platform or digest");
|
|
23058
|
-
if (JSON.parse(provenanceFile(
|
|
23059
|
-
const indexBytes = provenanceFile(
|
|
23112
|
+
if (JSON.parse(provenanceFile(join17(root, "oci-layout"), 1024).toString()).imageLayoutVersion !== "1.0.0") throw new Error("OCI layout required");
|
|
23113
|
+
const indexBytes = provenanceFile(join17(root, "index.json"), 1024 * 1024);
|
|
23060
23114
|
let current = JSON.parse(indexBytes.toString());
|
|
23061
23115
|
let selected;
|
|
23062
23116
|
let manifestDigest = provenanceHash(indexBytes);
|
|
@@ -23185,17 +23239,17 @@ async function captureWorkloadProvenance(options) {
|
|
|
23185
23239
|
if (!sha.test(commit) || !sha.test(tree)) throw new Error("Full Git commit and tree required");
|
|
23186
23240
|
const origin = git2(root, ["remote", "get-url", "origin"]);
|
|
23187
23241
|
if (!["https://github.com/" + options.repository, "https://github.com/" + options.repository + ".git", "git@github.com:" + options.repository + ".git"].includes(origin)) throw new Error("Source repository does not match origin");
|
|
23188
|
-
const lockBytes = provenanceFile(
|
|
23242
|
+
const lockBytes = provenanceFile(join18(root, "package-lock.json"), 16 * 1024 * 1024);
|
|
23189
23243
|
const dependencies = dependencyMaterials(JSON.parse(lockBytes.toString("utf8")));
|
|
23190
23244
|
const context3 = resolve21(root, options.context);
|
|
23191
23245
|
if (canonical(readdirSync7(context3).sort()) !== canonical(contextNames)) throw new Error("Exact allowlisted workload context required");
|
|
23192
23246
|
const contextDigests = {};
|
|
23193
|
-
for (const name2 of contextNames) contextDigests[name2] = provenanceHash(provenanceFile(
|
|
23194
|
-
const plan = boundedJson(
|
|
23247
|
+
for (const name2 of contextNames) contextDigests[name2] = provenanceHash(provenanceFile(join18(context3, name2), name2 === "workload.mjs" ? 16 * 1024 * 1024 : 65536));
|
|
23248
|
+
const plan = boundedJson(join18(context3, "artifact.json"));
|
|
23195
23249
|
const baseDigest = provenanceRef(options.baseImage);
|
|
23196
23250
|
if (plan.schemaVersion !== 1 || plan.kind !== "worker" || plan.baseImage !== options.baseImage || !/^[a-f0-9]{64}$/.test(plan.artifactVersion) || !/^[a-f0-9]{64}$/.test(plan.manifestVersion) || contextDigests["workload.mjs"] !== "sha256:" + plan.artifactVersion || typeof plan.entrypoint !== "string") throw new Error("Worker context does not match artifact metadata");
|
|
23197
23251
|
const dockerfile = ["FROM " + options.baseImage, "WORKDIR /app", "COPY --chown=1000:1000 workload.mjs artifact.json ./", "ENV NODE_ENV=production PORT=8080 BACKIFY_ARTIFACT_SHA256=" + plan.artifactVersion + " BACKIFY_WORKLOAD_TOKEN_FILE=/run/backify/workload/token", "USER 1000:1000", "STOPSIGNAL SIGTERM", 'ENTRYPOINT ["node", "workload.mjs"]', ""].join("\n");
|
|
23198
|
-
if (!provenanceFile(
|
|
23252
|
+
if (!provenanceFile(join18(context3, "Dockerfile"), 65536).equals(Buffer.from(dockerfile)) || provenanceFile(join18(context3, ".dockerignore"), 65536).toString() !== "**\n!Dockerfile\n!workload.mjs\n!artifact.json\n!.dockerignore\n") throw new Error("Unreviewed workload build recipe");
|
|
23199
23253
|
const base = await inspectProvenanceImage(resolve21(root, options.baseLayout), options.architecture, baseDigest);
|
|
23200
23254
|
const image2 = await inspectProvenanceImage(resolve21(root, options.imageLayout), options.architecture);
|
|
23201
23255
|
verifyBaseLineage(base, image2);
|
|
@@ -23271,14 +23325,14 @@ function verifyWorkloadProvenance(options, now = /* @__PURE__ */ new Date()) {
|
|
|
23271
23325
|
evidence.push({ bytes: baseSubject, bundle: provenanceFile(options.baseBundle, 4 * 1024 * 1024), identity: { ...policy, ...supplier } });
|
|
23272
23326
|
}
|
|
23273
23327
|
const scratchRoot = resolve21(tmpdir());
|
|
23274
|
-
const scratch = mkdtempSync2(
|
|
23328
|
+
const scratch = mkdtempSync2(join18(scratchRoot, "backify-provenance-"));
|
|
23275
23329
|
if (dirname15(scratch) !== scratchRoot || !basename3(scratch).startsWith("backify-provenance-")) throw new Error("Unsafe provenance evidence directory");
|
|
23276
23330
|
try {
|
|
23277
|
-
mkdirSync8(
|
|
23278
|
-
const trustedRoot =
|
|
23331
|
+
mkdirSync8(join18(scratch, "evidence"), { mode: 448 });
|
|
23332
|
+
const trustedRoot = join18(scratch, "evidence", "trusted-root.jsonl");
|
|
23279
23333
|
writeFileSync13(trustedRoot, rootBytes, { flag: "wx", mode: 384 });
|
|
23280
23334
|
for (const [index, { bytes, bundle: bundleBytes, identity }] of evidence.entries()) {
|
|
23281
|
-
const report =
|
|
23335
|
+
const report = join18(scratch, "evidence", "report-" + index + ".json"), bundle = join18(scratch, "evidence", "bundle-" + index + ".jsonl");
|
|
23282
23336
|
writeFileSync13(report, bytes, { flag: "wx", mode: 384 });
|
|
23283
23337
|
writeFileSync13(bundle, bundleBytes, { flag: "wx", mode: 384 });
|
|
23284
23338
|
try {
|
|
@@ -23316,7 +23370,7 @@ async function workloadProvenanceCommand(args2) {
|
|
|
23316
23370
|
}
|
|
23317
23371
|
|
|
23318
23372
|
// src/workload-trust-state.ts
|
|
23319
|
-
import { lstatSync as lstatSync17, readFileSync as
|
|
23373
|
+
import { lstatSync as lstatSync17, readFileSync as readFileSync24 } from "node:fs";
|
|
23320
23374
|
import { isAbsolute as isAbsolute16, resolve as resolve22 } from "node:path";
|
|
23321
23375
|
function parseWorkloadTrustState(args2) {
|
|
23322
23376
|
const action = args2[0];
|
|
@@ -23344,7 +23398,7 @@ function workloadTrustState(options) {
|
|
|
23344
23398
|
try {
|
|
23345
23399
|
const metadata = lstatSync17(options.trustFile);
|
|
23346
23400
|
if (!metadata.isFile() || metadata.isSymbolicLink() || metadata.nlink !== 1 || metadata.size > 131072) throw new Error();
|
|
23347
|
-
const bytes =
|
|
23401
|
+
const bytes = readFileSync24(options.trustFile);
|
|
23348
23402
|
if (bytes.length > 131072) throw new Error();
|
|
23349
23403
|
trust = JSON.parse(new TextDecoder("utf8", { fatal: true }).decode(bytes));
|
|
23350
23404
|
} catch {
|
|
@@ -23360,8 +23414,8 @@ function workloadTrustState(options) {
|
|
|
23360
23414
|
}
|
|
23361
23415
|
|
|
23362
23416
|
// src/scaffold.ts
|
|
23363
|
-
import { existsSync as
|
|
23364
|
-
import { dirname as dirname16, join as
|
|
23417
|
+
import { existsSync as existsSync15, lstatSync as lstatSync18, mkdirSync as mkdirSync9, readFileSync as readFileSync25, readdirSync as readdirSync8, realpathSync as realpathSync7, writeFileSync as writeFileSync14 } from "node:fs";
|
|
23418
|
+
import { dirname as dirname16, join as join19, relative as relative10, resolve as resolve23 } from "node:path";
|
|
23365
23419
|
function json2(value) {
|
|
23366
23420
|
return JSON.stringify(value, null, 2) + "\n";
|
|
23367
23421
|
}
|
|
@@ -23540,20 +23594,20 @@ provider-readiness claim, cloud deployment or browser authentication is implied.
|
|
|
23540
23594
|
function scaffoldFullStack(options) {
|
|
23541
23595
|
const files = fullStackTemplate(options.appId, options.name);
|
|
23542
23596
|
const root = resolve23(options.root ?? process.cwd());
|
|
23543
|
-
if (!
|
|
23597
|
+
if (!existsSync15(root) || !lstatSync18(root).isDirectory() || lstatSync18(root).isSymbolicLink()) throw new Error("Scaffold destination must be an existing non-linked directory");
|
|
23544
23598
|
const allowed = /* @__PURE__ */ new Set([...Object.keys(files).map((filename2) => filename2.split("/")[0]), ".git", "node_modules", "package-lock.json", ".backify"]);
|
|
23545
23599
|
if (readdirSync8(root).some((filename2) => !allowed.has(filename2))) throw new Error("Scaffolding requires an empty folder or an unchanged generated starter");
|
|
23546
23600
|
const canonicalRoot = realpathSync7(root);
|
|
23547
23601
|
const pending = [];
|
|
23548
23602
|
for (const [filename2, content] of Object.entries(files)) {
|
|
23549
|
-
const destination =
|
|
23603
|
+
const destination = join19(root, filename2);
|
|
23550
23604
|
let current = destination;
|
|
23551
23605
|
while (current !== root) {
|
|
23552
23606
|
try {
|
|
23553
23607
|
const stat = lstatSync18(current);
|
|
23554
23608
|
if (stat.isSymbolicLink() || current !== destination && !stat.isDirectory()) throw new Error("Scaffolding refuses linked or invalid output paths: " + filename2);
|
|
23555
23609
|
if (relative10(canonicalRoot, realpathSync7(current)).startsWith("..")) throw new Error("Scaffold output must remain inside its directory");
|
|
23556
|
-
if (current === destination && (!stat.isFile() ||
|
|
23610
|
+
if (current === destination && (!stat.isFile() || readFileSync25(current, "utf8") !== content)) throw new Error("Scaffolding refuses to overwrite existing content: " + filename2);
|
|
23557
23611
|
} catch (error) {
|
|
23558
23612
|
if (!(error instanceof Error) || !("code" in error) || error.code !== "ENOENT") throw error;
|
|
23559
23613
|
if (current === destination) pending.push(filename2);
|
|
@@ -23562,7 +23616,7 @@ function scaffoldFullStack(options) {
|
|
|
23562
23616
|
}
|
|
23563
23617
|
}
|
|
23564
23618
|
for (const filename2 of pending) {
|
|
23565
|
-
const destination =
|
|
23619
|
+
const destination = join19(root, filename2);
|
|
23566
23620
|
mkdirSync9(dirname16(destination), { recursive: true });
|
|
23567
23621
|
writeFileSync14(destination, files[filename2], { flag: "wx" });
|
|
23568
23622
|
}
|
|
@@ -23608,16 +23662,16 @@ function localInspectionCommand(args2) {
|
|
|
23608
23662
|
}
|
|
23609
23663
|
|
|
23610
23664
|
// src/index.ts
|
|
23611
|
-
import { readFileSync as
|
|
23665
|
+
import { readFileSync as readFileSync26, existsSync as existsSync16, rmSync as rmSync3 } from "node:fs";
|
|
23612
23666
|
import { homedir as homedir2 } from "node:os";
|
|
23613
|
-
import { join as
|
|
23667
|
+
import { join as join20 } from "node:path";
|
|
23614
23668
|
import { spawn as spawn5 } from "node:child_process";
|
|
23615
|
-
var configPath =
|
|
23616
|
-
var userConfig =
|
|
23669
|
+
var configPath = join20(homedir2(), ".backify.json");
|
|
23670
|
+
var userConfig = existsSync16(configPath) ? JSON.parse(readFileSync26(configPath, "utf8")) : {};
|
|
23617
23671
|
var [command2, ...args] = process.argv.slice(2);
|
|
23618
23672
|
async function call(path, init) {
|
|
23619
23673
|
let appId = option("--app");
|
|
23620
|
-
if (!appId &&
|
|
23674
|
+
if (!appId && existsSync16(join20(process.cwd(), "backify.json"))) appId = projectApplication();
|
|
23621
23675
|
const session = appId ? userConfig.sessions?.[sessionKey(appId)] : void 0;
|
|
23622
23676
|
const credential = session ?? { token: userConfig.token ?? "", organizationId: userConfig.organizationId ?? "", apiUrl: process.env.BACKIFY_API_URL ?? userConfig.apiUrl ?? "https://api.backify.dev/api" };
|
|
23623
23677
|
return (appId ? applicationClient(credential, appId) : apiClient(credential))(path, init);
|
|
@@ -23756,7 +23810,7 @@ async function main() {
|
|
|
23756
23810
|
const name2 = option("--name");
|
|
23757
23811
|
if (!name2) throw new Error("Specify --name <job>");
|
|
23758
23812
|
const payload = option("--payload");
|
|
23759
|
-
console.log(JSON.stringify(await localRequest("/v1/jobs/run", { name: name2, payload: payload ? JSON.parse(
|
|
23813
|
+
console.log(JSON.stringify(await localRequest("/v1/jobs/run", { name: name2, payload: payload ? JSON.parse(readFileSync26(payload, "utf8")) : null }), null, 2));
|
|
23760
23814
|
} else if (["retry", "cancel"].includes(args[0])) {
|
|
23761
23815
|
const id = option("--id");
|
|
23762
23816
|
if (!id) throw new Error("Specify --id <run>");
|
|
@@ -23779,7 +23833,7 @@ async function main() {
|
|
|
23779
23833
|
const environmentId = option("--environment");
|
|
23780
23834
|
const packagePath = option("--package");
|
|
23781
23835
|
if (!environmentId || !packagePath || !args.includes("--confirm")) throw new Error("Use backify functions deploy --environment <environment-id> --package <functions.zip> --confirm. This replaces the complete function project.");
|
|
23782
|
-
await deployFunctions(call, appId, applicationGuid(environmentId), new Uint8Array(
|
|
23836
|
+
await deployFunctions(call, appId, applicationGuid(environmentId), new Uint8Array(readFileSync26(packagePath)), { progress: (message) => console.log(message) });
|
|
23783
23837
|
console.log("Functions deployed.");
|
|
23784
23838
|
} else throw new Error("Use backify functions package or backify functions deploy");
|
|
23785
23839
|
break;
|
|
@@ -23814,7 +23868,7 @@ async function main() {
|
|
|
23814
23868
|
userConfig.token = args[0];
|
|
23815
23869
|
userConfig.organizationId = args[1] ?? userConfig.organizationId;
|
|
23816
23870
|
saveUserConfig(configPath, userConfig);
|
|
23817
|
-
} else await browserLogin(option("--app") ?? (
|
|
23871
|
+
} else await browserLogin(option("--app") ?? (existsSync16(join20(process.cwd(), "backify.json")) ? projectApplication() : void 0), option("--organization"));
|
|
23818
23872
|
console.log("Logged in to Backify");
|
|
23819
23873
|
break;
|
|
23820
23874
|
case "logout":
|
|
@@ -23853,7 +23907,7 @@ async function main() {
|
|
|
23853
23907
|
userConfig.sessions[key] ??= session;
|
|
23854
23908
|
saveUserConfig(configPath, userConfig);
|
|
23855
23909
|
if (args.includes("--clone")) await cloneProject(client, appId);
|
|
23856
|
-
else if (
|
|
23910
|
+
else if (existsSync16(join20(process.cwd(), ".git"))) {
|
|
23857
23911
|
const update = await pullProject(client, appId);
|
|
23858
23912
|
console.log(JSON.stringify(update, null, 2));
|
|
23859
23913
|
if (update.status === "blocked") throw new Error(update.reason);
|
|
@@ -23916,7 +23970,7 @@ async function main() {
|
|
|
23916
23970
|
} else if (args[0] === "install") {
|
|
23917
23971
|
const version = option("--version"), sha256 = option("--sha256");
|
|
23918
23972
|
if (!version || !sha256) throw new Error("Use backify runtime install --version vX.Y.Z --sha256 <reviewed-digest> [--archive <local-zip>]");
|
|
23919
|
-
const bytes = option("--archive") ?
|
|
23973
|
+
const bytes = option("--archive") ? readFileSync26(option("--archive")) : await downloadLocalRuntime(version);
|
|
23920
23974
|
console.log(JSON.stringify(installLocalRuntime(bytes, { version, sha256 }), null, 2));
|
|
23921
23975
|
} else throw new Error("Use backify runtime install or backify runtime doctor");
|
|
23922
23976
|
break;
|
|
@@ -23931,7 +23985,7 @@ async function main() {
|
|
|
23931
23985
|
case "request": {
|
|
23932
23986
|
const workspaceId = option("--workspace"), name2 = option("--name"), slug = option("--slug"), description = option("--description"), configurationFile = option("--configuration");
|
|
23933
23987
|
if (!workspaceId || !name2 || !slug || !description) throw new Error("Use backify request --workspace <id> --name <name> --slug <slug> --description <purpose> [--configuration <json-file>]");
|
|
23934
|
-
const configuration = configurationFile ? JSON.parse(
|
|
23988
|
+
const configuration = configurationFile ? JSON.parse(readFileSync26(configurationFile, "utf8")) : void 0;
|
|
23935
23989
|
console.log(await call("/apps/requests", { method: "POST", body: JSON.stringify({ workspaceId, name: name2, slug, description, configuration }) }));
|
|
23936
23990
|
break;
|
|
23937
23991
|
}
|
|
@@ -23949,7 +24003,7 @@ async function main() {
|
|
|
23949
24003
|
else if (args[0] === "test") {
|
|
23950
24004
|
const name2 = option("--name"), payload = option("--payload");
|
|
23951
24005
|
if (!name2 || !payload) throw new Error("Specify --name and --payload <json-file>. Never include secrets in event payloads.");
|
|
23952
|
-
console.log(JSON.stringify(await call(path + "/test", { method: "POST", body: JSON.stringify({ name: name2, payload: JSON.parse(
|
|
24006
|
+
console.log(JSON.stringify(await call(path + "/test", { method: "POST", body: JSON.stringify({ name: name2, payload: JSON.parse(readFileSync26(payload, "utf8")), idempotencyKey: option("--idempotency-key") }) }), null, 2));
|
|
23953
24007
|
} else throw new Error("Use backify events environments|inspect|test");
|
|
23954
24008
|
break;
|
|
23955
24009
|
}
|