@backifydev/cli 0.3.11 → 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 +15 -2
- package/dist/index.js +330 -248
- 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
|
/**
|
|
@@ -17766,12 +17766,12 @@ function manifestDiagnostics(manifest, used, authentication) {
|
|
|
17766
17766
|
// ../platform/dist/delivery.js
|
|
17767
17767
|
var deliveryInstructions = `# Backify application delivery and prompt history
|
|
17768
17768
|
|
|
17769
|
-
Instruction version:
|
|
17770
|
-
Versioned guide: https://agent.backify.dev/
|
|
17769
|
+
Instruction version: 10
|
|
17770
|
+
Versioned guide: https://agent.backify.dev/v10/delivery.md
|
|
17771
17771
|
|
|
17772
17772
|
## Environment and documentation prerequisites
|
|
17773
17773
|
|
|
17774
|
-
Before installation or connection, read https://agent.backify.dev/
|
|
17774
|
+
Before installation or connection, read https://agent.backify.dev/v10 for execution capability checks, required endpoints (including https://docs.backify.dev), native permission requests, verified retries and fallback guidance. Follow the current tool's supported approval mechanism; never bypass restrictions. Read relevant capability documentation before implementation. Local validation must not depend on cloud deployment.
|
|
17775
17775
|
|
|
17776
17776
|
Before application implementation, all required setup checks and connected status must be verified OK. If any required check fails or remains unverified after supported recovery, stop setup and implementation; do not build a local website, minimal shell, placeholder, dependency-free fallback, or downloadable application archive. Report the blockers and recommend running the setup prompt in an AI coding tool such as Codex, Claude Code, or VS Code with GitHub Copilot agent mode, with terminal access, a persistent writable workspace, package installation, outbound HTTPS/DNS, and test execution enabled. Tool names alone do not guarantee readiness. Do not ask the application requirements question while setup is blocked. Later preview approval or deployment failures do not invalidate an already verified setup gate.
|
|
17777
17777
|
|
|
@@ -17783,7 +17783,7 @@ The copied Backify prompt supplies App Id, Organization, and, when available, Pa
|
|
|
17783
17783
|
|
|
17784
17784
|
npx @backifydev/cli@latest connect --app <app-id> --organization <organization-id> --api https://api.backify.dev/api --pair <pairing-code>
|
|
17785
17785
|
|
|
17786
|
-
If Pair is absent, omit --pair and use CLI browser login. Pairing expires after 15 minutes. Never record the code
|
|
17786
|
+
If Pair is absent, omit --pair and use CLI browser login. Pairing expires after 15 minutes. Never record the code in project files, Git, prompt history, or logs. Record the user-supplied setup request in prompt history only after redacting credentials; do not drop the request. The CLI stores an application-scoped session outside the repository. If CLI access expires, use the browser reauthentication workflow below, never another setup prompt. A fresh pairing code is needed only if initial pairing expired or was consumed.
|
|
17787
17787
|
|
|
17788
17788
|
Before connecting, inspect the current folder. If it is not a Git repository, is missing its .git directory or file, or has no Git remote, add --clone to the connect command. Default AI coding-tool directories and instruction files do not make a workspace an existing application. Run connect --clone in the current folder even when tool scaffolding exists, including configuration, rules, agents, skills, commands, prompts, and work/output directories. This is tool-independent: preserve the current tool's metadata and instructions regardless of its name; never delete or overwrite them to make the folder empty. The CLI recognizes empty directories of any name, hidden tool-metadata directories and files, Markdown instruction files, and default work/outputs directories, including their contents. It clones into a temporary folder, checks for file conflicts, and safely merges the repository into the current workspace. If actual application source or an existing .git is present, or repository files conflict with existing entries, stop and reconcile the workspace or use a new folder; never overwrite user work. In an existing repository with a remote, verify it matches the connected repository and branch; never overwrite unrelated files or force-push.
|
|
17789
17789
|
|
|
@@ -17791,13 +17791,13 @@ Initialize using App Id from the copied prompt and the current tool selection:
|
|
|
17791
17791
|
|
|
17792
17792
|
npx @backifydev/cli@latest init --app <app-id> --agent <current-tool>
|
|
17793
17793
|
|
|
17794
|
-
For a tool without a built-in preset, replace --agent <current-tool> with --instruction-file <relative-path>. Read BACKIFY.md and the instruction file used by the current AI coding tool before changing application code. Create or update only instruction files used by that tool; never create files for other coding tools. Use --agent for a built-in tool preset or --instruction-file <relative-path> for the current tool's native instruction file, as described in the setup guide. Initialization installs this workflow alongside the persistent SDK instructions. Follow https://agent.backify.dev/
|
|
17794
|
+
For a tool without a built-in preset, replace --agent <current-tool> with --instruction-file <relative-path>. Read BACKIFY.md and the instruction file used by the current AI coding tool before changing application code. Create or update only instruction files used by that tool; never create files for other coding tools. Use --agent for a built-in tool preset or --instruction-file <relative-path> for the current tool's native instruction file, as described in the setup guide. Initialization installs this workflow alongside the persistent SDK instructions. Follow https://agent.backify.dev/v10 for instruction version 10; use the guide matching backify.json in an existing application. Do not silently upgrade its managed instruction version or overwrite instructions outside the managed block.
|
|
17795
17795
|
|
|
17796
17796
|
Run the following to discover the connected hosting target, repository, branch, reports, releases, and deployment failures:
|
|
17797
17797
|
|
|
17798
17798
|
npx @backifydev/cli@latest status
|
|
17799
17799
|
|
|
17800
|
-
Connection and initialization may proceed without application requirements. Then ask what to build if none were supplied; never invent requirements or
|
|
17800
|
+
Connection and initialization may proceed without application requirements. Then ask what to build if none were supplied; never invent requirements or treat setup text as an application requirement. Record user-supplied setup requests in prompt history as other after redacting credentials.
|
|
17801
17801
|
|
|
17802
17802
|
## Reauthenticate CLI access
|
|
17803
17803
|
|
|
@@ -17805,11 +17805,13 @@ If CLI authentication expires or is rejected, ask the user to reauthenticate. Ru
|
|
|
17805
17805
|
|
|
17806
17806
|
## Record each user request
|
|
17807
17807
|
|
|
17808
|
-
For EVERY user request
|
|
17808
|
+
For EVERY user request associated with this application, including the initial requirements supplied alongside or after setup, record the user's own text before acting on it. Include setup, building, deployment, launch, questions, application bug fixes, and Backify platform troubleshooting; never exclude a request because it does not change application code. If recording access is not yet available, retain the request in the current conversation and record it in order as soon as authenticated application access is available, without saving credentials to project files. Submit the text through standard input to:
|
|
17809
17809
|
|
|
17810
|
-
npx @backifydev/cli@latest prompt record --stdin --id <new-UUID> [--filename <basename> ...] [--model <model>] [--ai-tool <tool>] [--access-level <access>]
|
|
17810
|
+
npx @backifydev/cli@latest prompt record --stdin --id <new-UUID> [--filename <basename> ...] --type <build|deploy|fixing|other> [--model <full-model-name-and-version>] [--ai-tool <tool>] [--access-level <access>] [--sdk-version <installed-version>]
|
|
17811
17811
|
|
|
17812
|
-
|
|
17812
|
+
Choose the type from the request's primary intent: build for application features, changes, and application bug fixes; deploy for shipping, deployment, or launching the application; fixing only for troubleshooting Backify platform, SDK, CLI, connection, or hosting issues affecting the user, not application-code bugs; other for setup, questions, or requests outside those categories. Never drop an unclassified request; use other. These are request types, not execution or deployment statuses. Reuse the same type on retries. Older untyped records remain visible as Not recorded.
|
|
17813
|
+
|
|
17814
|
+
Record requests separately and in order. Generate a new UUID per request and reuse that UUID on retries. Add one --filename argument per attachment, using only its basename. Never send attachment bodies, extracted text, images, full paths, assistant responses, tool output, or secrets. Do not exclude user-supplied setup or connection requests: replace credentials with [REDACTED] and record the remaining request, not assistant-generated instructions. The CLI and API also redact recognized Backify session tokens and pairing codes; redact all other secrets before submission. Filename arguments are metadata only; never read attachment bodies to submit them. If recording fails, retry or report the blocker; never silently claim a request was recorded. Record the model, AI coding tool, and effective access for each request with --model, --ai-tool, and --access-level whenever known. Access is a short description of the tool\u2019s actual filesystem, network, and approval permissions at the time of the request, not its Backify role. Use only exposed session information; never guess unknown values or inspect credentials to discover them. Omit unknown fields; older or incomplete records display \u201CNot recorded\u201D. These values are self-reported metadata, not verified authorization. Reuse the same metadata on retries. Model and tool names are limited to 200 characters each; access descriptions to 500. Never include secrets, tokens, full paths, or configuration file contents. Include the exposed model family and version, for example gpt-6-luna or gpt-6.1-sol, rather than only the tool name. Separate filesystem, network, and approval access descriptions with semicolons so each appears as a separate badge. The CLI automatically records the installed @backifydev/sdk version from the project or its hoisted node_modules, never the dependency range. Use --sdk-version to preserve the original installed version on retries or when auto-detection is unavailable; SDK versions are limited to 100 characters. Unknown SDK and model versions remain \u201CNot recorded\u201D; never guess them.
|
|
17813
17815
|
|
|
17814
17816
|
## Keep local source current
|
|
17815
17817
|
|
|
@@ -17835,7 +17837,9 @@ After the required setup gate passes and application requirements are supplied,
|
|
|
17835
17837
|
|
|
17836
17838
|
Start the application, wait for readiness, request the actual local application URL, and verify a representative user flow before shipping. Document safe seed data and local test identities where needed. A failed connection or required setup check must stop implementation, including local fallback. After setup passes, later preview approval or deployment failure must not prevent safe local testing; report those blockers separately without bypassing authorization. If requirements are missing after successful setup, ask the required final question without creating a minimal runnable shell. Never claim local readiness from a build or management-dashboard response alone.
|
|
17837
17839
|
|
|
17838
|
-
## Verify, push, and
|
|
17840
|
+
## Verify, push, and deploy to preview
|
|
17841
|
+
|
|
17842
|
+
Plain deployment requests are preview-only. Requests such as "Now deploy", "deploy", "ship", "launch", or "merge and retry" do not authorize production. Approval to merge a remote commit, push source, retry deployment, or run checks applies only to that action and preserves the preview target. Never infer production intent from permissive policy, a healthy preview, or an existing production URL.
|
|
17839
17843
|
|
|
17840
17844
|
Run:
|
|
17841
17845
|
|
|
@@ -17845,9 +17849,13 @@ Fix relevant failures, then commit only application changes for this request usi
|
|
|
17845
17849
|
|
|
17846
17850
|
npx @backifydev/cli@latest ship
|
|
17847
17851
|
|
|
17848
|
-
The CLI verifies the repository and branch, runs checks, pushes committed source using a short-lived repository-scoped credential, waits for the exact source's healthy preview, and
|
|
17852
|
+
The CLI verifies the repository and branch, runs checks, pushes committed source using a short-lived repository-scoped credential, waits for the exact source's healthy preview, and returns the preview URL without requesting production publication. It never stages or commits files, force-pushes, changes hosting, fabricates preview testing, or bypasses approval. The legacy --preview-only flag is optional; preview is already the default.
|
|
17853
|
+
|
|
17854
|
+
Production requires an explicit user request to deploy to production, such as "deploy to production", "publish to production", or "promote this preview to production". Only for that request run:
|
|
17855
|
+
|
|
17856
|
+
npx @backifydev/cli@latest ship --production-deploy
|
|
17849
17857
|
|
|
17850
|
-
If testing or approval is required, return the preview URL and explain the remaining action. Otherwise return the verified production URL and actual check results only after healthy activation. Inspect failures with the status command, fix them, and retry without asking the user to perform routine deployment steps. Never invent a successful check or deployment.
|
|
17858
|
+
Production publication still follows existing Backify permissions, testing, and approval policy. If testing or approval is required, return the preview URL and explain the remaining action; never fabricate testing or bypass approval. Otherwise return the verified production URL and actual check results only after healthy activation. For a plain deployment request, stop at the verified healthy preview even when production testing and approval are not required. Inspect failures with the status command, fix them, and retry the same target without asking the user to perform routine deployment steps. Never invent a successful check or deployment.
|
|
17851
17859
|
|
|
17852
17860
|
## User-facing handoff
|
|
17853
17861
|
|
|
@@ -17865,7 +17873,7 @@ These instructions are an explicit agent workflow, not a universal chat intercep
|
|
|
17865
17873
|
`;
|
|
17866
17874
|
|
|
17867
17875
|
// ../platform/dist/index.js
|
|
17868
|
-
var INSTRUCTION_VERSION =
|
|
17876
|
+
var INSTRUCTION_VERSION = 10;
|
|
17869
17877
|
var SDK_PACKAGE = "@backifydev/sdk";
|
|
17870
17878
|
var DOCS_URL = "https://docs.backify.dev";
|
|
17871
17879
|
var MAIL_LIMITS = Object.freeze({
|
|
@@ -17943,7 +17951,7 @@ Run relevant tests, typechecking, lint, and builds using the repository's script
|
|
|
17943
17951
|
|
|
17944
17952
|
## Connected application delivery
|
|
17945
17953
|
|
|
17946
|
-
For connected applications, follow \`BACKIFY.md\` and https://agent.backify.dev/v${INSTRUCTION_VERSION}/delivery.md before changing application code. Record every user build or modification request, including initial requirements, with attachment filenames only; never submit attachment contents or setup credentials. Verify checks and
|
|
17954
|
+
For connected applications, follow \`BACKIFY.md\` and https://agent.backify.dev/v${INSTRUCTION_VERSION}/delivery.md before changing application code. Record every user build or modification request, including initial requirements, with attachment filenames only; never submit attachment contents or setup credentials. Verify checks and deploy to preview through the connected CLI workflow without bypassing testing, approval, or coding-tool permissions. Plain deployment requests are preview-only. Production requires an explicit user request to deploy to production; approval to merge, push, or retry does not authorize production. Use \`ship\` for preview and \`ship --production-deploy\` only for that explicit production request. Report only verified deployment URLs.
|
|
17947
17955
|
|
|
17948
17956
|
## Instruction maintenance
|
|
17949
17957
|
|
|
@@ -18165,7 +18173,7 @@ import { hostname, platform, release, arch } from "node:os";
|
|
|
18165
18173
|
// package.json
|
|
18166
18174
|
var package_default = {
|
|
18167
18175
|
name: "@backifydev/cli",
|
|
18168
|
-
version: "0.3.
|
|
18176
|
+
version: "0.3.13",
|
|
18169
18177
|
description: "Command-line setup and diagnostics for Backify applications",
|
|
18170
18178
|
type: "module",
|
|
18171
18179
|
bin: {
|
|
@@ -18229,14 +18237,14 @@ import { randomBytes } from "node:crypto";
|
|
|
18229
18237
|
import { createServer as createServer2 } from "node:http";
|
|
18230
18238
|
|
|
18231
18239
|
// src/development.ts
|
|
18232
|
-
import { existsSync as
|
|
18233
|
-
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";
|
|
18234
18242
|
import { spawnSync as spawnSync3 } from "node:child_process";
|
|
18235
18243
|
import { randomUUID as randomUUID2 } from "node:crypto";
|
|
18236
18244
|
|
|
18237
18245
|
// src/setup.ts
|
|
18238
|
-
import { existsSync as
|
|
18239
|
-
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";
|
|
18240
18248
|
import { spawnSync as spawnSync2 } from "node:child_process";
|
|
18241
18249
|
|
|
18242
18250
|
// src/delivery.ts
|
|
@@ -18267,11 +18275,32 @@ function installDeliveryInstructions(root, instructionFiles2) {
|
|
|
18267
18275
|
}
|
|
18268
18276
|
}
|
|
18269
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
|
+
|
|
18270
18299
|
// src/setup.ts
|
|
18271
18300
|
var instructionFiles = ["AGENTS.md"];
|
|
18272
|
-
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" };
|
|
18273
18302
|
function instructionSelection(root, agent, instructionFile) {
|
|
18274
|
-
const configPath2 =
|
|
18303
|
+
const configPath2 = join4(root, "backify.json"), configured = existsSync4(configPath2) ? JSON.parse(readFileSync4(configPath2, "utf8")) : {};
|
|
18275
18304
|
const custom = instructionFile ?? (agent === void 0 ? configured.instructionFile : void 0);
|
|
18276
18305
|
const selected = instructionFile !== void 0 ? "custom" : agent ?? configured.agent ?? "codex";
|
|
18277
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>.");
|
|
@@ -18280,7 +18309,7 @@ function instructionSelection(root, agent, instructionFile) {
|
|
|
18280
18309
|
const normalized = filename2.replaceAll("\\", "/"), parts = normalized.split("/");
|
|
18281
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.");
|
|
18282
18311
|
for (let index = 1; index <= parts.length; index++) {
|
|
18283
|
-
const entry =
|
|
18312
|
+
const entry = join4(root, ...parts.slice(0, index));
|
|
18284
18313
|
try {
|
|
18285
18314
|
const metadata = lstatSync(entry);
|
|
18286
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.");
|
|
@@ -18295,16 +18324,16 @@ function selectedInstructionFiles(root = process.cwd(), agent, instructionFile)
|
|
|
18295
18324
|
}
|
|
18296
18325
|
function isToolWorkspaceEntry(entry, root = process.cwd()) {
|
|
18297
18326
|
if (entry.name.toLowerCase() === ".git" || entry.name.toLowerCase() === ".env" || entry.name.toLowerCase().startsWith(".env.")) return false;
|
|
18298
|
-
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));
|
|
18299
18328
|
}
|
|
18300
18329
|
function detectPackageManager(root = process.cwd()) {
|
|
18301
|
-
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;
|
|
18302
18331
|
return "npm";
|
|
18303
18332
|
}
|
|
18304
18333
|
function updateInstructions(root = process.cwd(), agent, instructionFile) {
|
|
18305
18334
|
const updates = selectedInstructionFiles(root, agent, instructionFile).map((relative11) => {
|
|
18306
|
-
const path =
|
|
18307
|
-
return { path, content: updateManagedInstructions(
|
|
18335
|
+
const path = join4(root, relative11);
|
|
18336
|
+
return { path, content: updateManagedInstructions(existsSync4(path) ? readFileSync4(path, "utf8") : "") };
|
|
18308
18337
|
});
|
|
18309
18338
|
for (const { path, content } of updates) {
|
|
18310
18339
|
mkdirSync2(dirname3(path), { recursive: true });
|
|
@@ -18312,9 +18341,9 @@ function updateInstructions(root = process.cwd(), agent, instructionFile) {
|
|
|
18312
18341
|
}
|
|
18313
18342
|
}
|
|
18314
18343
|
function synchronize(root = process.cwd(), agent, instructionFile) {
|
|
18315
|
-
const path =
|
|
18316
|
-
if (!
|
|
18317
|
-
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);
|
|
18318
18347
|
if (issues.length) throw new Error(issues.join("; "));
|
|
18319
18348
|
if (value.instructionVersion > INSTRUCTION_VERSION) throw new Error("This app uses newer instructions. Install a matching or newer CLI before syncing.");
|
|
18320
18349
|
const selected = instructionSelection(root, agent, instructionFile);
|
|
@@ -18328,7 +18357,7 @@ function synchronize(root = process.cwd(), agent, instructionFile) {
|
|
|
18328
18357
|
}
|
|
18329
18358
|
function sdkInstalled(root = process.cwd()) {
|
|
18330
18359
|
try {
|
|
18331
|
-
const pkg = JSON.parse(
|
|
18360
|
+
const pkg = JSON.parse(readFileSync4(join4(root, "package.json"), "utf8"));
|
|
18332
18361
|
return Boolean(pkg.dependencies?.[SDK_PACKAGE] || pkg.devDependencies?.[SDK_PACKAGE]);
|
|
18333
18362
|
} catch {
|
|
18334
18363
|
return false;
|
|
@@ -18340,8 +18369,8 @@ function installSdk(root = process.cwd()) {
|
|
|
18340
18369
|
if (result.status !== 0) throw new Error(`Could not install ${SDK_PACKAGE} with ${manager}`);
|
|
18341
18370
|
}
|
|
18342
18371
|
function ensurePackageManifest(root) {
|
|
18343
|
-
const path =
|
|
18344
|
-
if (
|
|
18372
|
+
const path = join4(root, "package.json");
|
|
18373
|
+
if (existsSync4(path)) return;
|
|
18345
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"]);
|
|
18346
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/");
|
|
18347
18376
|
const name2 = basename(resolve3(root)).toLowerCase().replace(/[^a-z0-9-]+/g, "-").replace(/^-+|-+$/g, "") || "backify-app";
|
|
@@ -18351,20 +18380,33 @@ function initialize(appId, root = process.cwd(), install = true, agent, instruct
|
|
|
18351
18380
|
if (!/^app_[A-Za-z0-9_-]+$/.test(appId)) throw new Error("Provide an application ID using --app app_xxxxx");
|
|
18352
18381
|
const selected = instructionSelection(root, agent, instructionFile), files = selected.files;
|
|
18353
18382
|
validateDeliveryInstructions(root);
|
|
18354
|
-
for (const relative11 of files) if (
|
|
18355
|
-
|
|
18356
|
-
if (
|
|
18357
|
-
|
|
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")) : {};
|
|
18358
18390
|
writeFileSync4(configPath2, JSON.stringify({ ...existing, ...createConfig(appId), agent: selected.agent, instructionFile: selected.instructionFile }, null, 2) + "\n");
|
|
18359
18391
|
updateInstructions(root, selected.agent, selected.instructionFile);
|
|
18360
18392
|
installDeliveryInstructions(root, files);
|
|
18361
18393
|
}
|
|
18362
18394
|
function doctor(root = process.cwd(), agent, instructionFile) {
|
|
18363
18395
|
const issues = [], warnings = [];
|
|
18364
|
-
|
|
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
|
+
}
|
|
18365
18407
|
let config;
|
|
18366
18408
|
try {
|
|
18367
|
-
config = JSON.parse(
|
|
18409
|
+
config = JSON.parse(readFileSync4(join4(root, "backify.json"), "utf8"));
|
|
18368
18410
|
issues.push(...validateConfig(config));
|
|
18369
18411
|
} catch {
|
|
18370
18412
|
issues.push("backify.json is missing or invalid JSON");
|
|
@@ -18377,20 +18419,34 @@ function doctor(root = process.cwd(), agent, instructionFile) {
|
|
|
18377
18419
|
issues.push(reason instanceof Error ? reason.message : String(reason));
|
|
18378
18420
|
}
|
|
18379
18421
|
for (const relative11 of files) {
|
|
18380
|
-
const path =
|
|
18381
|
-
if (!
|
|
18422
|
+
const path = join4(root, relative11);
|
|
18423
|
+
if (!existsSync4(path)) {
|
|
18382
18424
|
issues.push(`${relative11} is missing`);
|
|
18383
18425
|
continue;
|
|
18384
18426
|
}
|
|
18385
|
-
issues.push(...managedInstructionIssues(
|
|
18427
|
+
issues.push(...managedInstructionIssues(readFileSync4(path, "utf8")).map((issue) => `${relative11} ${issue}`));
|
|
18386
18428
|
}
|
|
18387
18429
|
let version = "unknown";
|
|
18388
18430
|
try {
|
|
18389
|
-
const pkg = JSON.parse(
|
|
18431
|
+
const pkg = JSON.parse(readFileSync4(join4(root, "package.json"), "utf8"));
|
|
18390
18432
|
version = pkg.dependencies?.[SDK_PACKAGE] ?? pkg.devDependencies?.[SDK_PACKAGE] ?? "missing";
|
|
18391
18433
|
} catch {
|
|
18392
18434
|
}
|
|
18393
|
-
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 };
|
|
18394
18450
|
}
|
|
18395
18451
|
|
|
18396
18452
|
// src/development.ts
|
|
@@ -18400,10 +18456,27 @@ function promptContext(root = process.cwd()) {
|
|
|
18400
18456
|
commitSha = git(["rev-parse", "HEAD"], root);
|
|
18401
18457
|
} catch {
|
|
18402
18458
|
}
|
|
18403
|
-
return { device: cliDevice(), commitSha };
|
|
18459
|
+
return { device: cliDevice(), commitSha, sdkVersion: installedSdkVersion(root) };
|
|
18460
|
+
}
|
|
18461
|
+
function installedSdkVersion(root) {
|
|
18462
|
+
let directory2 = resolve4(root);
|
|
18463
|
+
while (true) {
|
|
18464
|
+
const manifest = join6(directory2, "node_modules", "@backifydev", "sdk", "package.json");
|
|
18465
|
+
if (existsSync6(manifest)) {
|
|
18466
|
+
try {
|
|
18467
|
+
const sdk = JSON.parse(readFileSync6(manifest, "utf8"));
|
|
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;
|
|
18469
|
+
} catch {
|
|
18470
|
+
return null;
|
|
18471
|
+
}
|
|
18472
|
+
}
|
|
18473
|
+
const parent = dirname4(directory2);
|
|
18474
|
+
if (parent === directory2) return null;
|
|
18475
|
+
directory2 = parent;
|
|
18476
|
+
}
|
|
18404
18477
|
}
|
|
18405
18478
|
function promptMetadata(args2) {
|
|
18406
|
-
const fields5 = [["--model", "model", 200], ["--ai-tool", "aiTool", 200], ["--access-level", "accessLevel", 500]];
|
|
18479
|
+
const fields5 = [["--model", "model", 200], ["--ai-tool", "aiTool", 200], ["--access-level", "accessLevel", 500], ["--sdk-version", "sdkVersion", 100], ["--type", "promptType", 20]];
|
|
18407
18480
|
const metadata = {};
|
|
18408
18481
|
for (const [flag, field, maxLength] of fields5) {
|
|
18409
18482
|
const index = args2.indexOf(flag);
|
|
@@ -18413,6 +18486,10 @@ function promptMetadata(args2) {
|
|
|
18413
18486
|
throw new Error(`Provide ${flag} with a nonempty value of at most ${maxLength} characters without control characters or credentials.`);
|
|
18414
18487
|
metadata[field] = value;
|
|
18415
18488
|
}
|
|
18489
|
+
if (metadata.promptType !== void 0) {
|
|
18490
|
+
metadata.promptType = metadata.promptType.toLowerCase();
|
|
18491
|
+
if (!["build", "deploy", "fixing", "other"].includes(metadata.promptType)) throw new Error("Use --type build, deploy, fixing, or other.");
|
|
18492
|
+
}
|
|
18416
18493
|
const commitIndex = args2.indexOf("--commit-sha");
|
|
18417
18494
|
if (commitIndex >= 0) {
|
|
18418
18495
|
const value = args2[commitIndex + 1];
|
|
@@ -18429,8 +18506,8 @@ function applicationGuid(appId) {
|
|
|
18429
18506
|
return [value.slice(0, 8), value.slice(8, 12), value.slice(12, 16), value.slice(16, 20), value.slice(20)].join("-");
|
|
18430
18507
|
}
|
|
18431
18508
|
function projectApplication(root = process.cwd()) {
|
|
18432
|
-
if (!
|
|
18433
|
-
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;
|
|
18434
18511
|
}
|
|
18435
18512
|
function apiAddress(value) {
|
|
18436
18513
|
const address = new URL(value);
|
|
@@ -18493,7 +18570,7 @@ function gitEnvironment(repository, token) {
|
|
|
18493
18570
|
}
|
|
18494
18571
|
function validateCloneMerge(source, target) {
|
|
18495
18572
|
for (const entry of readdirSync2(source, { withFileTypes: true })) {
|
|
18496
|
-
const destination =
|
|
18573
|
+
const destination = join6(target, entry.name);
|
|
18497
18574
|
let existing;
|
|
18498
18575
|
try {
|
|
18499
18576
|
existing = lstatSync2(destination);
|
|
@@ -18501,7 +18578,7 @@ function validateCloneMerge(source, target) {
|
|
|
18501
18578
|
if (reason.code === "ENOENT") continue;
|
|
18502
18579
|
throw reason;
|
|
18503
18580
|
}
|
|
18504
|
-
if (entry.isDirectory() && existing.isDirectory() && !existing.isSymbolicLink()) validateCloneMerge(
|
|
18581
|
+
if (entry.isDirectory() && existing.isDirectory() && !existing.isSymbolicLink()) validateCloneMerge(join6(source, entry.name), destination);
|
|
18505
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.");
|
|
18506
18583
|
}
|
|
18507
18584
|
}
|
|
@@ -18511,18 +18588,18 @@ async function cloneProject(call2, appId, root = process.cwd()) {
|
|
|
18511
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.");
|
|
18512
18589
|
const credential = await call2("/apps/" + applicationGuid(appId) + "/developer/git-credential", { method: "POST" });
|
|
18513
18590
|
if (credential.repository.toLowerCase() !== status.repository.toLowerCase()) throw new Error("Repository changed. Run connect again.");
|
|
18514
|
-
const staging = mkdtempSync(
|
|
18591
|
+
const staging = mkdtempSync(join6(dirname4(resolve4(root)), ".backify-clone-"));
|
|
18515
18592
|
try {
|
|
18516
18593
|
git(["clone", "--single-branch", "--branch", status.branch, "--", "https://github.com/" + status.repository + ".git", "."], staging, gitEnvironment(status.repository, credential.token));
|
|
18517
18594
|
validateCloneMerge(staging, root);
|
|
18518
|
-
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 });
|
|
18519
18596
|
} finally {
|
|
18520
|
-
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.");
|
|
18521
18598
|
rmSync(staging, { recursive: true, force: true });
|
|
18522
18599
|
}
|
|
18523
18600
|
}
|
|
18524
18601
|
async function pullProject(call2, appId, root = process.cwd()) {
|
|
18525
|
-
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.");
|
|
18526
18603
|
const prefix = "/apps/" + applicationGuid(appId);
|
|
18527
18604
|
const status = await call2(prefix + "/developer");
|
|
18528
18605
|
if (!status.repository || !status.branch) throw new Error("Connect the repository and branch in Backify before pulling.");
|
|
@@ -18554,8 +18631,7 @@ async function readPrompt(input) {
|
|
|
18554
18631
|
}
|
|
18555
18632
|
const text3 = Buffer.concat(chunks).toString("utf8");
|
|
18556
18633
|
if (!text3.trim() || text3.length > 32e3) throw new Error("Provide between 1 and 32000 characters of user prompt text.");
|
|
18557
|
-
|
|
18558
|
-
return text3;
|
|
18634
|
+
return text3.replace(/bfcli_[0-9a-f]{64}/gi, "[REDACTED]").replace(/(--pair(?:\s+|=)["']?|\bPair:\s*)[0-9a-f]{64}/gi, "$1[REDACTED]");
|
|
18559
18635
|
}
|
|
18560
18636
|
function attachmentNames(values) {
|
|
18561
18637
|
if (values.length > 50) throw new Error("At most 50 attachment filenames are allowed.");
|
|
@@ -18566,9 +18642,9 @@ function attachmentNames(values) {
|
|
|
18566
18642
|
}))];
|
|
18567
18643
|
}
|
|
18568
18644
|
function localReport(runChecks, root = process.cwd()) {
|
|
18569
|
-
const pkg = JSON.parse(
|
|
18645
|
+
const pkg = existsSync6(join6(root, "package.json")) ? JSON.parse(readFileSync6(join6(root, "package.json"), "utf8")) : {};
|
|
18570
18646
|
const dependencies = { ...pkg.devDependencies, ...pkg.dependencies };
|
|
18571
|
-
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");
|
|
18572
18648
|
const setup = doctor(root);
|
|
18573
18649
|
const checks = [{ name: "backify doctor", status: setup.valid ? "passed" : "failed" }];
|
|
18574
18650
|
const manager = detectPackageManager(root);
|
|
@@ -18584,8 +18660,8 @@ function localReport(runChecks, root = process.cwd()) {
|
|
|
18584
18660
|
dirty = Boolean(git(["status", "--porcelain"], root));
|
|
18585
18661
|
} catch {
|
|
18586
18662
|
}
|
|
18587
|
-
const outputDirectory = ["dist", "build", "out", "."].find((directory2) =>
|
|
18588
|
-
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 };
|
|
18589
18665
|
}
|
|
18590
18666
|
function matchesSource(release2, commit) {
|
|
18591
18667
|
return release2?.commitSha === commit || release2?.sourceCommitSha === commit;
|
|
@@ -18615,7 +18691,10 @@ async function waitForPreview(call2, prefix, commit, options = {}) {
|
|
|
18615
18691
|
const overview = await call2(prefix + "/releases");
|
|
18616
18692
|
if (matchesSource(overview.preview, commit) && overview.preview?.status === "succeeded" && overview.preview.healthResult === "healthy") return overview;
|
|
18617
18693
|
const build3 = await call2(prefix + "/developer/build?commitSha=" + commit);
|
|
18618
|
-
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
|
+
}
|
|
18619
18698
|
await sleep(options.intervalMs ?? 4e3);
|
|
18620
18699
|
} while (Date.now() < deadline);
|
|
18621
18700
|
throw new Error("Timed out waiting for this commit's healthy preview. Run backify status; no production release was requested.");
|
|
@@ -18638,7 +18717,10 @@ async function ship(call2, appId, options = {}) {
|
|
|
18638
18717
|
await call2(prefix + "/developer/report", { method: "POST", body: JSON.stringify(report) });
|
|
18639
18718
|
if (report.checks.some((check) => check.status === "failed")) throw new Error("Checks failed; nothing was pushed.");
|
|
18640
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.");
|
|
18641
|
-
if (status.hostingTargetType === "azure"
|
|
18720
|
+
if (status.hostingTargetType === "azure") {
|
|
18721
|
+
const build3 = containerBuildSupport(root);
|
|
18722
|
+
if (!build3.adapter) throw new Error(build3.issue);
|
|
18723
|
+
}
|
|
18642
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.");
|
|
18643
18725
|
const previousDeployments = await call2(prefix + "/deployments");
|
|
18644
18726
|
const previousBuild = await call2(prefix + "/developer/build?commitSha=" + commit);
|
|
@@ -18796,8 +18878,8 @@ function reconnectingApiClient(session, reconnect, transport = fetch) {
|
|
|
18796
18878
|
|
|
18797
18879
|
// src/local-runtime.ts
|
|
18798
18880
|
import { createHash as createHash2, randomUUID as randomUUID3 } from "node:crypto";
|
|
18799
|
-
import { chmodSync, existsSync as
|
|
18800
|
-
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";
|
|
18801
18883
|
import { homedir } from "node:os";
|
|
18802
18884
|
import { spawnSync as spawnSync4 } from "node:child_process";
|
|
18803
18885
|
|
|
@@ -18832,7 +18914,7 @@ function checkedPath(root, filename2) {
|
|
|
18832
18914
|
if (target !== resolve5(root) && !target.startsWith(resolve5(root) + sep)) throw new Error("Runtime path escapes its installation");
|
|
18833
18915
|
let current = target;
|
|
18834
18916
|
while (true) {
|
|
18835
|
-
if (
|
|
18917
|
+
if (existsSync7(current) && lstatSync3(current).isSymbolicLink()) throw new Error("Runtime installation must not follow links");
|
|
18836
18918
|
if (dirname5(current) === current) break;
|
|
18837
18919
|
current = dirname5(current);
|
|
18838
18920
|
}
|
|
@@ -18840,25 +18922,25 @@ function checkedPath(root, filename2) {
|
|
|
18840
18922
|
}
|
|
18841
18923
|
function verifyInstallationFiles(root, expected, directory2 = root) {
|
|
18842
18924
|
for (const entry of readdirSync3(directory2, { withFileTypes: true })) {
|
|
18843
|
-
const path = checkedPath(root,
|
|
18925
|
+
const path = checkedPath(root, join7(directory2, entry.name));
|
|
18844
18926
|
if (entry.isDirectory()) verifyInstallationFiles(root, expected, path);
|
|
18845
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");
|
|
18846
18928
|
}
|
|
18847
18929
|
}
|
|
18848
|
-
function installedLocalRuntime(base =
|
|
18930
|
+
function installedLocalRuntime(base = join7(homedir(), ".backify")) {
|
|
18849
18931
|
const pointer = checkedPath(base, "runtime.json");
|
|
18850
|
-
if (!
|
|
18851
|
-
const installed = JSON.parse(
|
|
18932
|
+
if (!existsSync7(pointer)) return void 0;
|
|
18933
|
+
const installed = JSON.parse(readFileSync7(pointer, "utf8"));
|
|
18852
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");
|
|
18853
|
-
const root = checkedPath(base,
|
|
18935
|
+
const root = checkedPath(base, join7("runtimes", installed.version, installed.rid));
|
|
18854
18936
|
verifyInstallationFiles(root, installed.files);
|
|
18855
18937
|
for (const [filename2, digest4] of Object.entries(installed.files)) {
|
|
18856
18938
|
const path = checkedPath(root, filename2);
|
|
18857
|
-
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");
|
|
18858
18940
|
}
|
|
18859
18941
|
const executableName = installed.rid.startsWith("win-") ? "Backify.Hcr.exe" : "Backify.Hcr";
|
|
18860
18942
|
if (!installed.files["Backify.Hcr.dll"] || !installed.files[executableName]) throw new Error("Runtime archive requires the self-contained HCR executable and DLL");
|
|
18861
|
-
return { path:
|
|
18943
|
+
return { path: join7(root, "Backify.Hcr.dll"), executable: join7(root, executableName), version: installed.version, rid: installed.rid };
|
|
18862
18944
|
}
|
|
18863
18945
|
function installLocalRuntime(archive, options) {
|
|
18864
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");
|
|
@@ -18872,12 +18954,12 @@ function installLocalRuntime(archive, options) {
|
|
|
18872
18954
|
const rid = runtimeIdentifier();
|
|
18873
18955
|
const executable = rid.startsWith("win-") ? "Backify.Hcr.exe" : "Backify.Hcr";
|
|
18874
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");
|
|
18875
|
-
const base = options.base ??
|
|
18876
|
-
const parent = checkedPath(base,
|
|
18957
|
+
const base = options.base ?? join7(homedir(), ".backify");
|
|
18958
|
+
const parent = checkedPath(base, join7("runtimes", options.version));
|
|
18877
18959
|
mkdirSync3(parent, { recursive: true, mode: 448 });
|
|
18878
18960
|
const destination = checkedPath(parent, rid);
|
|
18879
18961
|
const receipt = { version: options.version, rid, files: Object.fromEntries(Object.entries(files).map(([name2, bytes]) => [name2, hash(bytes)])) };
|
|
18880
|
-
if (!
|
|
18962
|
+
if (!existsSync7(destination)) {
|
|
18881
18963
|
const staging = checkedPath(parent, ".install-" + randomUUID3());
|
|
18882
18964
|
mkdirSync3(staging, { mode: 448 });
|
|
18883
18965
|
for (const [name2, bytes] of Object.entries(files)) {
|
|
@@ -18885,11 +18967,11 @@ function installLocalRuntime(archive, options) {
|
|
|
18885
18967
|
mkdirSync3(dirname5(filename2), { recursive: true, mode: 448 });
|
|
18886
18968
|
writeFileSync6(filename2, bytes, { flag: "wx", mode: name2 === executable ? 448 : 384 });
|
|
18887
18969
|
}
|
|
18888
|
-
if (process.platform !== "win32") chmodSync(
|
|
18970
|
+
if (process.platform !== "win32") chmodSync(join7(staging, executable), 448);
|
|
18889
18971
|
renameLocalFile(staging, destination);
|
|
18890
18972
|
} else {
|
|
18891
18973
|
verifyInstallationFiles(destination, receipt.files);
|
|
18892
|
-
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");
|
|
18893
18975
|
}
|
|
18894
18976
|
const pointer = checkedPath(base, "runtime.json");
|
|
18895
18977
|
const temporary = checkedPath(base, ".runtime-" + randomUUID3() + ".json");
|
|
@@ -18921,9 +19003,9 @@ async function downloadLocalRuntime(version) {
|
|
|
18921
19003
|
}
|
|
18922
19004
|
function localPrerequisites() {
|
|
18923
19005
|
const runtime = installedLocalRuntime();
|
|
18924
|
-
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);
|
|
18925
19007
|
const checks = ["initdb", "pg_ctl", "psql"].map((name2) => {
|
|
18926
|
-
const executable = directory2 ?
|
|
19008
|
+
const executable = directory2 ? join7(directory2, name2 + (process.platform === "win32" ? ".exe" : "")) : name2;
|
|
18927
19009
|
const result = spawnSync4(executable, ["--version"], { windowsHide: true, timeout: 1e4, encoding: "utf8" });
|
|
18928
19010
|
return { name: name2, available: result.status === 0 };
|
|
18929
19011
|
});
|
|
@@ -18933,20 +19015,20 @@ function localPrerequisites() {
|
|
|
18933
19015
|
// src/workload.ts
|
|
18934
19016
|
import { build as build2 } from "esbuild";
|
|
18935
19017
|
import { createHash as createHash14 } from "node:crypto";
|
|
18936
|
-
import { existsSync as
|
|
18937
|
-
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";
|
|
18938
19020
|
|
|
18939
19021
|
// src/local-development.ts
|
|
18940
19022
|
import { context as context2 } from "esbuild";
|
|
18941
19023
|
import { spawn as spawn4 } from "node:child_process";
|
|
18942
19024
|
import { randomBytes as randomBytes6, randomUUID as randomUUID10, createHash as createHash13 } from "node:crypto";
|
|
18943
|
-
import { existsSync as
|
|
18944
|
-
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";
|
|
18945
19027
|
|
|
18946
19028
|
// ../analyzer/dist/index.js
|
|
18947
19029
|
import ts3 from "typescript";
|
|
18948
|
-
import { readFileSync as
|
|
18949
|
-
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";
|
|
18950
19032
|
|
|
18951
19033
|
// ../analyzer/dist/authentication.js
|
|
18952
19034
|
import ts from "typescript";
|
|
@@ -19363,14 +19445,14 @@ function repositorySources(root) {
|
|
|
19363
19445
|
for (const entry of readdirSync4(dir, { withFileTypes: true })) {
|
|
19364
19446
|
if (entry.name === "node_modules" || entry.name === "dist" || entry.name === ".backify" || entry.name.startsWith(".git"))
|
|
19365
19447
|
continue;
|
|
19366
|
-
const path =
|
|
19448
|
+
const path = join8(dir, entry.name);
|
|
19367
19449
|
if (entry.isDirectory())
|
|
19368
19450
|
walk(path);
|
|
19369
19451
|
else if ([".ts", ".tsx", ".js", ".jsx", ".mts", ".mjs"].includes(extname(path)))
|
|
19370
|
-
result.push({ path, content:
|
|
19452
|
+
result.push({ path, content: readFileSync8(path, "utf8") });
|
|
19371
19453
|
}
|
|
19372
19454
|
};
|
|
19373
|
-
if (
|
|
19455
|
+
if (existsSync8(root))
|
|
19374
19456
|
walk(root);
|
|
19375
19457
|
return result;
|
|
19376
19458
|
}
|
|
@@ -19584,8 +19666,8 @@ function createLocalNativeEvents(local, native) {
|
|
|
19584
19666
|
// src/local-job-executor.ts
|
|
19585
19667
|
import { spawn as spawn2 } from "node:child_process";
|
|
19586
19668
|
import { createHash as createHash10 } from "node:crypto";
|
|
19587
|
-
import { lstatSync as lstatSync11, readFileSync as
|
|
19588
|
-
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";
|
|
19589
19671
|
|
|
19590
19672
|
// ../sdk/dist/schedules.js
|
|
19591
19673
|
var import_cron_parser = __toESM(require_dist2(), 1);
|
|
@@ -19951,7 +20033,7 @@ function createPersistentApplicationAuthProvider(source, options) {
|
|
|
19951
20033
|
|
|
19952
20034
|
// ../sdk/dist/application-auth-sync.js
|
|
19953
20035
|
import { createHash as createHash4, createPublicKey as createPublicKey2, randomUUID as randomUUID5, verify as verify2 } from "node:crypto";
|
|
19954
|
-
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";
|
|
19955
20037
|
import { dirname as dirname7, isAbsolute as isAbsolute3, parse as parse2, resolve as resolve7, sep as sep3 } from "node:path";
|
|
19956
20038
|
var maximumBytes = 512 * 1024;
|
|
19957
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";
|
|
@@ -20023,7 +20105,7 @@ function currentPublicFile(filename2) {
|
|
|
20023
20105
|
const metadata = lstatSync5(filename2);
|
|
20024
20106
|
if (!metadata.isFile() || metadata.isSymbolicLink() || metadata.nlink !== 1 || metadata.size > 131072 || process.platform !== "win32" && (metadata.uid !== process.getuid?.() || (metadata.mode & 18) !== 0))
|
|
20025
20107
|
unavailable3();
|
|
20026
|
-
const bytes =
|
|
20108
|
+
const bytes = readFileSync9(filename2);
|
|
20027
20109
|
if (bytes.length > 131072)
|
|
20028
20110
|
unavailable3();
|
|
20029
20111
|
return new TextDecoder("utf8", { fatal: true }).decode(bytes);
|
|
@@ -20692,14 +20774,14 @@ function jsonValue(value) {
|
|
|
20692
20774
|
import { spawn, execFile } from "node:child_process";
|
|
20693
20775
|
import { createHash as createHash6, generateKeyPairSync, randomBytes as randomBytes3, randomUUID as randomUUID7, sign } from "node:crypto";
|
|
20694
20776
|
import { createServer as createServer3 } from "node:net";
|
|
20695
|
-
import { existsSync as
|
|
20696
|
-
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";
|
|
20697
20779
|
|
|
20698
20780
|
// src/local-job-services.ts
|
|
20699
20781
|
import { createHash as createHash5, randomBytes as randomBytes2, randomUUID as randomUUID6 } from "node:crypto";
|
|
20700
|
-
import { existsSync as
|
|
20782
|
+
import { existsSync as existsSync9, lstatSync as lstatSync6, readFileSync as readFileSync10 } from "node:fs";
|
|
20701
20783
|
import { isIP } from "node:net";
|
|
20702
|
-
import { dirname as dirname8, join as
|
|
20784
|
+
import { dirname as dirname8, join as join9 } from "node:path";
|
|
20703
20785
|
function fields3(value, names) {
|
|
20704
20786
|
return !!value && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === names.length && names.every((name2) => Object.hasOwn(value, name2));
|
|
20705
20787
|
}
|
|
@@ -20750,9 +20832,9 @@ function validLocalJobState(value, otherIds) {
|
|
|
20750
20832
|
function prepareLocalJobService(hcrPath, retained, artifacts, applyMigrations) {
|
|
20751
20833
|
const requested = validateLocalJobArtifacts(artifacts);
|
|
20752
20834
|
const readSchema = (name2) => {
|
|
20753
|
-
const filename2 =
|
|
20835
|
+
const filename2 = join9(dirname8(hcrPath), "sql", name2), info = existsSync9(filename2) ? lstatSync6(filename2) : void 0;
|
|
20754
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");
|
|
20755
|
-
return
|
|
20837
|
+
return readFileSync10(filename2, "utf8");
|
|
20756
20838
|
};
|
|
20757
20839
|
const base = readSchema("jobs-v1.sql"), producer = readSchema("jobs-producer-v1.sql");
|
|
20758
20840
|
const schemaDigests = { base: createHash5("sha256").update(base).digest("hex"), producer: createHash5("sha256").update(producer).digest("hex") };
|
|
@@ -20798,7 +20880,7 @@ function stateValid(value) {
|
|
|
20798
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);
|
|
20799
20881
|
}
|
|
20800
20882
|
function acquireLocalLease(root, relativePath2 = ".backify/dev/development.lock") {
|
|
20801
|
-
const filename2 =
|
|
20883
|
+
const filename2 = join10(root, relativePath2);
|
|
20802
20884
|
assertLocalStatePath(root, filename2);
|
|
20803
20885
|
mkdirSync4(resolve8(filename2, ".."), { recursive: true, mode: 448 });
|
|
20804
20886
|
const owner = JSON.stringify({ version: 1, pid: process.pid, id: randomUUID7() });
|
|
@@ -20808,7 +20890,7 @@ function acquireLocalLease(root, relativePath2 = ".backify/dev/development.lock"
|
|
|
20808
20890
|
throw new Error("Local development already owns this repository, or a stale lifecycle lock requires explicit recovery");
|
|
20809
20891
|
}
|
|
20810
20892
|
return () => {
|
|
20811
|
-
if (
|
|
20893
|
+
if (existsSync10(filename2) && readFileSync11(filename2, "utf8") === owner) unlinkSync4(filename2);
|
|
20812
20894
|
};
|
|
20813
20895
|
}
|
|
20814
20896
|
async function allocateLocalPort(requested) {
|
|
@@ -20851,26 +20933,26 @@ function command(executable, args2, options = {}) {
|
|
|
20851
20933
|
});
|
|
20852
20934
|
}
|
|
20853
20935
|
function postgresExecutable(name2, bin) {
|
|
20854
|
-
const directory2 = bin ?? process.env.BACKIFY_LOCAL_POSTGRES_BIN ?? (process.platform === "win32" ?
|
|
20855
|
-
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;
|
|
20856
20938
|
}
|
|
20857
20939
|
function localMigrationFiles(root, directory2) {
|
|
20858
20940
|
if (directory2 === void 0) return [];
|
|
20859
20941
|
if (typeof directory2 !== "string") throw new Error("Local migrations require a repository-relative directory");
|
|
20860
20942
|
const folder = resolve8(root, directory2);
|
|
20861
20943
|
assertLocalStatePath(root, folder);
|
|
20862
|
-
if (!
|
|
20944
|
+
if (!existsSync10(folder)) throw new Error("Declared migration directory does not exist");
|
|
20863
20945
|
const entries = readdirSync5(folder);
|
|
20864
20946
|
const filenames = entries.filter((entry) => entry.endsWith(".sql")).sort();
|
|
20865
20947
|
if (filenames.length > 100 || entries.some((entry) => !entry.endsWith(".sql"))) throw new Error("Migrations require at most 100 flat .sql files");
|
|
20866
20948
|
let total = 0;
|
|
20867
20949
|
return filenames.map((name2) => {
|
|
20868
20950
|
if (!/^[A-Za-z0-9_.-]{1,150}\.sql$/.test(name2)) throw new Error("Invalid migration filename");
|
|
20869
|
-
const filename2 =
|
|
20951
|
+
const filename2 = join10(folder, name2);
|
|
20870
20952
|
assertLocalStatePath(root, filename2);
|
|
20871
20953
|
const info = lstatSync7(filename2);
|
|
20872
20954
|
if (!info.isFile() || info.size > 1024 * 1024 || (total += info.size) > 4 * 1024 * 1024) throw new Error("Migration SQL exceeds supported limits");
|
|
20873
|
-
const sql =
|
|
20955
|
+
const sql = readFileSync11(filename2, "utf8");
|
|
20874
20956
|
if (!sql.trim()) throw new Error("Migration SQL must not be empty");
|
|
20875
20957
|
validateLocalMigrationSql(sql);
|
|
20876
20958
|
return { name: name2, digest: createHash6("sha256").update(sql).digest("hex"), sql };
|
|
@@ -20947,19 +21029,19 @@ async function startLocalServices(root, manifest, options = {}) {
|
|
|
20947
21029
|
const reviewedScope = options.jobIdentityScope;
|
|
20948
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");
|
|
20949
21031
|
const installed = options.hcrPath || process.env.BACKIFY_LOCAL_HCR_PATH ? void 0 : installedLocalRuntime();
|
|
20950
|
-
const hcrPath = resolve8(options.hcrPath ?? process.env.BACKIFY_LOCAL_HCR_PATH ?? installed?.path ??
|
|
20951
|
-
if (!
|
|
20952
|
-
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");
|
|
20953
21035
|
assertLocalStatePath(root, directory2);
|
|
20954
21036
|
mkdirSync4(directory2, { recursive: true, mode: 448 });
|
|
20955
21037
|
assertLocalStatePath(root, directory2);
|
|
20956
|
-
const statePath =
|
|
21038
|
+
const statePath = join10(directory2, "host.json");
|
|
20957
21039
|
assertLocalStatePath(root, statePath);
|
|
20958
21040
|
let existing;
|
|
20959
|
-
if (
|
|
21041
|
+
if (existsSync10(statePath)) {
|
|
20960
21042
|
if (lstatSync7(statePath).size > 16384) throw new Error("Local ownership state exceeds supported limits");
|
|
20961
21043
|
try {
|
|
20962
|
-
existing = JSON.parse(
|
|
21044
|
+
existing = JSON.parse(readFileSync11(statePath, "utf8"));
|
|
20963
21045
|
} catch {
|
|
20964
21046
|
throw new Error("Invalid local service ownership state; preserve the data and repair explicitly");
|
|
20965
21047
|
}
|
|
@@ -20978,9 +21060,9 @@ async function startLocalServices(root, manifest, options = {}) {
|
|
|
20978
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");
|
|
20979
21061
|
let eventSchema;
|
|
20980
21062
|
if (events) {
|
|
20981
|
-
const filename2 =
|
|
20982
|
-
if (!
|
|
20983
|
-
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");
|
|
20984
21066
|
const digest4 = createHash6("sha256").update(eventSchema).digest("hex");
|
|
20985
21067
|
if (state.events && state.events.schemaDigest !== digest4) throw new Error("Native event schema changed; preserve its database and plan an explicit migration.");
|
|
20986
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.");
|
|
@@ -20999,7 +21081,7 @@ async function startLocalServices(root, manifest, options = {}) {
|
|
|
20999
21081
|
const databasePort = database || events || jobs ? await allocateLocalPort(options.databasePort) : void 0;
|
|
21000
21082
|
if (databasePort !== void 0) state.retainedDatabasePort = databasePort;
|
|
21001
21083
|
if (databasePort === hcrPort) throw new Error("HCR and PostgreSQL require separate ports");
|
|
21002
|
-
const cluster =
|
|
21084
|
+
const cluster = join10(directory2, "postgres");
|
|
21003
21085
|
assertLocalStatePath(root, cluster);
|
|
21004
21086
|
const release2 = acquireLocalLease(root, ".backify/dev/services/lifecycle.lock");
|
|
21005
21087
|
let postgresStarted = false;
|
|
@@ -21015,7 +21097,7 @@ async function startLocalServices(root, manifest, options = {}) {
|
|
|
21015
21097
|
}
|
|
21016
21098
|
};
|
|
21017
21099
|
const runtimeUrl = "http://127.0.0.1:" + hcrPort;
|
|
21018
|
-
const tokenPath =
|
|
21100
|
+
const tokenPath = join10(directory2, "workload-token");
|
|
21019
21101
|
const stop = () => stopping ??= (async () => {
|
|
21020
21102
|
if (timer) clearInterval(timer);
|
|
21021
21103
|
if (snapshotTimer) clearInterval(snapshotTimer);
|
|
@@ -21034,9 +21116,9 @@ async function startLocalServices(root, manifest, options = {}) {
|
|
|
21034
21116
|
}
|
|
21035
21117
|
notify("hcr", "stopped");
|
|
21036
21118
|
try {
|
|
21037
|
-
if (postgresStarted &&
|
|
21119
|
+
if (postgresStarted && existsSync10(join10(cluster, "postmaster.pid"))) await command(postgresExecutable("pg_ctl", options.postgresBin), ["-D", cluster, "-m", "fast", "-w", "stop"]);
|
|
21038
21120
|
if (postgresStarted) notify("postgres", "stopped");
|
|
21039
|
-
if (
|
|
21121
|
+
if (existsSync10(tokenPath)) unlinkSync4(tokenPath);
|
|
21040
21122
|
} finally {
|
|
21041
21123
|
release2();
|
|
21042
21124
|
}
|
|
@@ -21046,28 +21128,28 @@ async function startLocalServices(root, manifest, options = {}) {
|
|
|
21046
21128
|
writePrivate(statePath, JSON.stringify(state));
|
|
21047
21129
|
if (database || events || jobs) {
|
|
21048
21130
|
notify("postgres", "starting");
|
|
21049
|
-
if (!
|
|
21050
|
-
const passwordPath =
|
|
21131
|
+
if (!existsSync10(join10(cluster, "PG_VERSION"))) {
|
|
21132
|
+
const passwordPath = join10(directory2, "init-password");
|
|
21051
21133
|
writePrivate(passwordPath, state.adminPassword);
|
|
21052
21134
|
try {
|
|
21053
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"]);
|
|
21054
21136
|
} finally {
|
|
21055
|
-
if (
|
|
21137
|
+
if (existsSync10(passwordPath)) unlinkSync4(passwordPath);
|
|
21056
21138
|
}
|
|
21057
21139
|
}
|
|
21058
|
-
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");
|
|
21059
21141
|
postgresStarted = true;
|
|
21060
|
-
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"]);
|
|
21061
21143
|
notify("postgres", "ready");
|
|
21062
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 } });
|
|
21063
21145
|
if (database) {
|
|
21064
21146
|
if ((await sql("SELECT count(*) FROM pg_roles WHERE rolname='backify_local'")).trim() === "0") {
|
|
21065
|
-
const filename2 =
|
|
21147
|
+
const filename2 = join10(directory2, "role-" + randomUUID7() + ".sql");
|
|
21066
21148
|
writePrivate(filename2, "CREATE ROLE backify_local LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE PASSWORD '" + state.databasePassword + "';");
|
|
21067
21149
|
try {
|
|
21068
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 } });
|
|
21069
21151
|
} finally {
|
|
21070
|
-
if (
|
|
21152
|
+
if (existsSync10(filename2)) unlinkSync4(filename2);
|
|
21071
21153
|
}
|
|
21072
21154
|
}
|
|
21073
21155
|
if ((await sql("SELECT count(*) FROM pg_database WHERE datname='backify_local'")).trim() === "0") await sql("CREATE DATABASE backify_local OWNER backify_local");
|
|
@@ -21082,12 +21164,12 @@ async function startLocalServices(root, manifest, options = {}) {
|
|
|
21082
21164
|
notify("migrations", "starting");
|
|
21083
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);
|
|
21084
21166
|
for (const migration of pending) {
|
|
21085
|
-
const filename2 =
|
|
21167
|
+
const filename2 = join10(directory2, "apply-" + randomUUID7() + ".sql");
|
|
21086
21168
|
writePrivate(filename2, "BEGIN;\n" + migration.sql + "\n;\nINSERT INTO public.__backify_migrations(name,digest) VALUES ('" + migration.name + "','" + migration.digest + "');\nCOMMIT;\n");
|
|
21087
21169
|
try {
|
|
21088
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 } });
|
|
21089
21171
|
} finally {
|
|
21090
|
-
if (
|
|
21172
|
+
if (existsSync10(filename2)) unlinkSync4(filename2);
|
|
21091
21173
|
}
|
|
21092
21174
|
applied.push(migration.name);
|
|
21093
21175
|
}
|
|
@@ -21098,20 +21180,20 @@ async function startLocalServices(root, manifest, options = {}) {
|
|
|
21098
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 } });
|
|
21099
21181
|
if (!eventState.initialized) {
|
|
21100
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.");
|
|
21101
|
-
const roleFile =
|
|
21183
|
+
const roleFile = join10(directory2, "event-role-" + randomUUID7() + ".sql");
|
|
21102
21184
|
writePrivate(roleFile, "CREATE ROLE backify_events LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE PASSWORD '" + eventState.password + "';");
|
|
21103
21185
|
try {
|
|
21104
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 } });
|
|
21105
21187
|
} finally {
|
|
21106
|
-
if (
|
|
21188
|
+
if (existsSync10(roleFile)) unlinkSync4(roleFile);
|
|
21107
21189
|
}
|
|
21108
21190
|
await sql("CREATE DATABASE backify_events OWNER backify_events");
|
|
21109
|
-
const schemaFile =
|
|
21191
|
+
const schemaFile = join10(directory2, "event-schema-" + randomUUID7() + ".sql");
|
|
21110
21192
|
writePrivate(schemaFile, eventSchema);
|
|
21111
21193
|
try {
|
|
21112
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 } });
|
|
21113
21195
|
} finally {
|
|
21114
|
-
if (
|
|
21196
|
+
if (existsSync10(schemaFile)) unlinkSync4(schemaFile);
|
|
21115
21197
|
}
|
|
21116
21198
|
eventState.initialized = true;
|
|
21117
21199
|
writePrivate(statePath, JSON.stringify(state));
|
|
@@ -21125,21 +21207,21 @@ async function startLocalServices(root, manifest, options = {}) {
|
|
|
21125
21207
|
const adminSql = (query, databaseName = "postgres") => jobCommand("backify_admin", state.adminPassword, databaseName, ["-c", query]);
|
|
21126
21208
|
if (!jobState.initialized) {
|
|
21127
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");
|
|
21128
|
-
const roleFile =
|
|
21210
|
+
const roleFile = join10(directory2, "job-role-" + randomUUID7() + ".sql");
|
|
21129
21211
|
writePrivate(roleFile, "CREATE ROLE backify_jobs LOGIN NOINHERIT NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION NOBYPASSRLS PASSWORD '" + jobState.password + "';");
|
|
21130
21212
|
try {
|
|
21131
21213
|
await jobCommand("backify_admin", state.adminPassword, "postgres", ["-f", roleFile]);
|
|
21132
21214
|
} finally {
|
|
21133
|
-
if (
|
|
21215
|
+
if (existsSync10(roleFile)) unlinkSync4(roleFile);
|
|
21134
21216
|
}
|
|
21135
21217
|
await adminSql("CREATE DATABASE backify_jobs OWNER backify_admin");
|
|
21136
21218
|
for (const schema of [jobSchema.base, jobSchema.producer]) {
|
|
21137
|
-
const filename2 =
|
|
21219
|
+
const filename2 = join10(directory2, "job-schema-" + randomUUID7() + ".sql");
|
|
21138
21220
|
writePrivate(filename2, schema);
|
|
21139
21221
|
try {
|
|
21140
21222
|
await jobCommand("backify_admin", state.adminPassword, "backify_jobs", ["-f", filename2]);
|
|
21141
21223
|
} finally {
|
|
21142
|
-
if (
|
|
21224
|
+
if (existsSync10(filename2)) unlinkSync4(filename2);
|
|
21143
21225
|
}
|
|
21144
21226
|
}
|
|
21145
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");
|
|
@@ -21168,7 +21250,7 @@ async function startLocalServices(root, manifest, options = {}) {
|
|
|
21168
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" }] : [],
|
|
21169
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" }] : []
|
|
21170
21252
|
];
|
|
21171
|
-
const snapshotPath =
|
|
21253
|
+
const snapshotPath = join10(directory2, "snapshot.json");
|
|
21172
21254
|
const writeSnapshot = () => writePrivate(snapshotPath, JSON.stringify({ schemaVersion: 1, configurationVersion: state.configurationVersion, expiresAt: new Date(Date.now() + 7 * 864e5).toISOString(), bindings }));
|
|
21173
21255
|
const renewConfiguration = () => {
|
|
21174
21256
|
if (stopping) throw new Error("Stopped local services cannot renew configuration");
|
|
@@ -21178,15 +21260,15 @@ async function startLocalServices(root, manifest, options = {}) {
|
|
|
21178
21260
|
writeSnapshot();
|
|
21179
21261
|
};
|
|
21180
21262
|
writeSnapshot();
|
|
21181
|
-
const settingsPath =
|
|
21263
|
+
const settingsPath = join10(directory2, "appsettings.json");
|
|
21182
21264
|
writePrivate(settingsPath, JSON.stringify({ Hcr: {
|
|
21183
21265
|
Authentication: { PublicKeyPem: publicKey.export({ type: "spki", format: "pem" }), Issuer: "backify-local", Audience: "backify-local-hcr" },
|
|
21184
21266
|
SnapshotPath: snapshotPath,
|
|
21185
|
-
SnapshotJournalPath:
|
|
21267
|
+
SnapshotJournalPath: join10(directory2, "journal.json"),
|
|
21186
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 } } : {} },
|
|
21187
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 } } : {} },
|
|
21188
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 } } : {} },
|
|
21189
|
-
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) }])) }
|
|
21190
21272
|
} }));
|
|
21191
21273
|
issueToken();
|
|
21192
21274
|
notify("hcr", "starting");
|
|
@@ -21200,7 +21282,7 @@ async function startLocalServices(root, manifest, options = {}) {
|
|
|
21200
21282
|
while (true) {
|
|
21201
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");
|
|
21202
21284
|
try {
|
|
21203
|
-
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" });
|
|
21204
21286
|
if (response.ok) {
|
|
21205
21287
|
const status = await response.json();
|
|
21206
21288
|
if (status.status === "ready" && status.configurationVersion === state.configurationVersion) break;
|
|
@@ -21209,8 +21291,8 @@ async function startLocalServices(root, manifest, options = {}) {
|
|
|
21209
21291
|
}
|
|
21210
21292
|
await new Promise((resolveDelay) => setTimeout(resolveDelay, 100));
|
|
21211
21293
|
}
|
|
21212
|
-
if (events) await createHcrEventsProvider({ runtimeUrl, token: () =>
|
|
21213
|
-
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();
|
|
21214
21296
|
timer = setInterval(() => {
|
|
21215
21297
|
try {
|
|
21216
21298
|
issueToken();
|
|
@@ -21236,14 +21318,14 @@ async function startLocalServices(root, manifest, options = {}) {
|
|
|
21236
21318
|
|
|
21237
21319
|
// src/local-job-auth.ts
|
|
21238
21320
|
import { createHash as createHash7 } from "node:crypto";
|
|
21239
|
-
import { lstatSync as lstatSync8, readFileSync as
|
|
21321
|
+
import { lstatSync as lstatSync8, readFileSync as readFileSync12 } from "node:fs";
|
|
21240
21322
|
import { isAbsolute as isAbsolute5, resolve as resolve9 } from "node:path";
|
|
21241
21323
|
function prepareLocalJobAuth(root, filename2) {
|
|
21242
21324
|
const read = (path, maximum) => {
|
|
21243
21325
|
assertLocalStatePath(root, path);
|
|
21244
21326
|
const metadata = lstatSync8(path);
|
|
21245
21327
|
if (!metadata.isFile() || metadata.isSymbolicLink() || metadata.nlink !== 1 || metadata.size > maximum) throw new Error();
|
|
21246
|
-
const bytes =
|
|
21328
|
+
const bytes = readFileSync12(path);
|
|
21247
21329
|
if (bytes.length > maximum) throw new Error();
|
|
21248
21330
|
return bytes;
|
|
21249
21331
|
};
|
|
@@ -21267,11 +21349,11 @@ function prepareLocalJobAuth(root, filename2) {
|
|
|
21267
21349
|
|
|
21268
21350
|
// src/local-job-trust-renewal.ts
|
|
21269
21351
|
import { createHash as createHash9 } from "node:crypto";
|
|
21270
|
-
import { lstatSync as lstatSync10, readFileSync as
|
|
21352
|
+
import { lstatSync as lstatSync10, readFileSync as readFileSync14 } from "node:fs";
|
|
21271
21353
|
import { isAbsolute as isAbsolute7, relative as relative2, resolve as resolve11 } from "node:path";
|
|
21272
21354
|
|
|
21273
21355
|
// src/workload-trust-sync.ts
|
|
21274
|
-
import { lstatSync as lstatSync9, readFileSync as
|
|
21356
|
+
import { lstatSync as lstatSync9, readFileSync as readFileSync13 } from "node:fs";
|
|
21275
21357
|
import { isAbsolute as isAbsolute6, resolve as resolve10 } from "node:path";
|
|
21276
21358
|
import { createHash as createHash8 } from "node:crypto";
|
|
21277
21359
|
function prepareWorkloadTrustSynchronization(filename2) {
|
|
@@ -21279,7 +21361,7 @@ function prepareWorkloadTrustSynchronization(filename2) {
|
|
|
21279
21361
|
if (!isAbsolute6(filename2)) throw new Error();
|
|
21280
21362
|
const metadata = lstatSync9(filename2);
|
|
21281
21363
|
if (!metadata.isFile() || metadata.isSymbolicLink() || metadata.nlink !== 1 || metadata.size > 65536) throw new Error();
|
|
21282
|
-
const bytes =
|
|
21364
|
+
const bytes = readFileSync13(filename2);
|
|
21283
21365
|
if (bytes.length > 65536) throw new Error();
|
|
21284
21366
|
const value = JSON.parse(new TextDecoder("utf8", { fatal: true }).decode(bytes));
|
|
21285
21367
|
const allowed = ["controlPlaneUrl", "agentId", "expectedScope", "managementIssuer", "managementAudience", "managementPublicKeyPem", "credentialFile", "trustFile", "stateFile", "intervalSeconds"];
|
|
@@ -21292,7 +21374,7 @@ function prepareWorkloadTrustSynchronization(filename2) {
|
|
|
21292
21374
|
const credential = () => {
|
|
21293
21375
|
const metadata2 = lstatSync9(credentialFile);
|
|
21294
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");
|
|
21295
|
-
const bytes2 =
|
|
21377
|
+
const bytes2 = readFileSync13(credentialFile);
|
|
21296
21378
|
if (bytes2.length > 256) throw new Error("Management credential unavailable");
|
|
21297
21379
|
return new TextDecoder("utf8", { fatal: true }).decode(bytes2).trim();
|
|
21298
21380
|
};
|
|
@@ -21364,8 +21446,8 @@ function prepareLocalJobTrustRenewal(root, filename2, mount) {
|
|
|
21364
21446
|
throw new Error("Invalid reviewed native worker trust renewal; preserve trust and state and review explicitly");
|
|
21365
21447
|
}
|
|
21366
21448
|
}
|
|
21367
|
-
function createLocalJobTrustRenewal(root, mounts, settings = {}, dependencies = { createHash: createHash9, lstatSync: lstatSync10, readFileSync:
|
|
21368
|
-
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;
|
|
21369
21451
|
const key = (filename2) => process.platform === "win32" ? resolve24(filename2).toLowerCase() : resolve24(filename2);
|
|
21370
21452
|
const groups = [];
|
|
21371
21453
|
for (const mount of mounts) {
|
|
@@ -21389,7 +21471,7 @@ function createLocalJobTrustRenewal(root, mounts, settings = {}, dependencies =
|
|
|
21389
21471
|
}
|
|
21390
21472
|
const metadata = lstatSync19(filename2);
|
|
21391
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();
|
|
21392
|
-
const bytes =
|
|
21474
|
+
const bytes = readFileSync27(filename2);
|
|
21393
21475
|
if (bytes.length > maximum) throw new Error();
|
|
21394
21476
|
return bytes;
|
|
21395
21477
|
};
|
|
@@ -21470,11 +21552,11 @@ function prepareLocalJobWorker(root, directory2, artifacts, manifest, authFile,
|
|
|
21470
21552
|
if (trustSyncFile !== void 0 && authFile === void 0) throw new Error("Native worker trust renewal requires explicit reviewed auth mounts");
|
|
21471
21553
|
const authTrust = authFile === void 0 ? void 0 : prepareLocalJobAuth(root, authFile);
|
|
21472
21554
|
if (authTrust && trustSyncFile !== void 0) authTrust.renewal = prepareLocalJobTrustRenewal(root, trustSyncFile, authTrust);
|
|
21473
|
-
const workerFile =
|
|
21555
|
+
const workerFile = join11(resolve12(root, directory2), "workload.mjs"), metadataFile = join11(resolve12(root, directory2), "artifact.json");
|
|
21474
21556
|
for (const filename2 of [workerFile, metadataFile]) assertLocalStatePath(root, filename2);
|
|
21475
21557
|
if (!lstatSync11(workerFile).isFile() || lstatSync11(workerFile).size > 16777216 || !lstatSync11(metadataFile).isFile() || lstatSync11(metadataFile).size > 65536) throw new Error("Invalid bounded native worker artifact");
|
|
21476
|
-
const metadata = JSON.parse(
|
|
21477
|
-
const bundle =
|
|
21558
|
+
const metadata = JSON.parse(readFileSync15(metadataFile, "utf8"));
|
|
21559
|
+
const bundle = readFileSync15(workerFile);
|
|
21478
21560
|
const actual = createHash10("sha256").update(bundle).digest("hex");
|
|
21479
21561
|
const scheduleDiscovery = bundle.subarray(0, 100).toString("utf8").startsWith('var __backifyWorkerProtocols = ["hcr-v1","hcr-schedules-v1"];\n');
|
|
21480
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");
|
|
@@ -21488,16 +21570,16 @@ function readLocalJobArtifacts(root, filename2) {
|
|
|
21488
21570
|
const path = resolve12(root, filename2);
|
|
21489
21571
|
assertLocalStatePath(root, path);
|
|
21490
21572
|
if (!lstatSync11(path).isFile() || lstatSync11(path).size > 16384) throw new Error("Reviewed job artifact admission exceeds supported bounds");
|
|
21491
|
-
return validateLocalJobArtifacts(JSON.parse(
|
|
21573
|
+
return validateLocalJobArtifacts(JSON.parse(readFileSync15(path, "utf8")));
|
|
21492
21574
|
}
|
|
21493
|
-
function createLocalJobExecutor(options, dependencies = { spawn: spawn2, createHash: createHash10, lstatSync: lstatSync11, readFileSync:
|
|
21494
|
-
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;
|
|
21495
21577
|
const assertReady = () => {
|
|
21496
21578
|
for (let current = resolve24(options.workerFile); current !== options.root; current = resolve24(current, "..")) {
|
|
21497
21579
|
const part = relative11(options.root, current);
|
|
21498
21580
|
if (part === ".." || part.startsWith("../") || part.startsWith("..\\") || isAbsolute17(part) || lstatSync19(current).isSymbolicLink()) throw new Error("Native worker paths or pins changed");
|
|
21499
21581
|
}
|
|
21500
|
-
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");
|
|
21501
21583
|
if (options.authTrust) {
|
|
21502
21584
|
try {
|
|
21503
21585
|
const mount = options.authTrust;
|
|
@@ -21509,7 +21591,7 @@ function createLocalJobExecutor(options, dependencies = { spawn: spawn2, createH
|
|
|
21509
21591
|
const metadata = lstatSync19(path);
|
|
21510
21592
|
if (!metadata.isFile() || metadata.nlink !== 1 || metadata.size > (path === mount.trustFile ? 131072 : 2048)) throw new Error();
|
|
21511
21593
|
}
|
|
21512
|
-
const bytes =
|
|
21594
|
+
const bytes = readFileSync27(mount.trustFile);
|
|
21513
21595
|
if (bytes.length > 131072 || createHash16("sha256").update(bytes).digest("hex") !== mount.trustDigest) throw new Error();
|
|
21514
21596
|
const trust = JSON.parse(new TextDecoder("utf8", { fatal: true }).decode(bytes));
|
|
21515
21597
|
if (trust.revision !== mount.revision) throw new Error();
|
|
@@ -21883,9 +21965,9 @@ process.on("SIGTERM", stop); process.on("SIGINT", stop); process.once("disconnec
|
|
|
21883
21965
|
|
|
21884
21966
|
// src/local-frontend.ts
|
|
21885
21967
|
import { spawn as spawn3 } from "node:child_process";
|
|
21886
|
-
import { readFileSync as
|
|
21968
|
+
import { readFileSync as readFileSync17, realpathSync as realpathSync3, existsSync as existsSync11, statSync } from "node:fs";
|
|
21887
21969
|
import { createRequire as createRequire3 } from "node:module";
|
|
21888
|
-
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";
|
|
21889
21971
|
import { pathToFileURL } from "node:url";
|
|
21890
21972
|
|
|
21891
21973
|
// src/local-frontend-guard.ts
|
|
@@ -21953,8 +22035,8 @@ await server.listen();
|
|
|
21953
22035
|
|
|
21954
22036
|
// src/local-static-frontend.ts
|
|
21955
22037
|
import { createServer as createServer4 } from "node:http";
|
|
21956
|
-
import { lstatSync as lstatSync12, readFileSync as
|
|
21957
|
-
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";
|
|
21958
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" };
|
|
21959
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()));
|
|
21960
22042
|
function publicFile(directory2, pathname) {
|
|
@@ -21966,7 +22048,7 @@ function publicFile(directory2, pathname) {
|
|
|
21966
22048
|
let current = directory2;
|
|
21967
22049
|
if (lstatSync12(current).isSymbolicLink() || realpathSync2(current) !== directory2) throw new Error("refused");
|
|
21968
22050
|
for (const segment of parts) {
|
|
21969
|
-
current =
|
|
22051
|
+
current = join12(current, segment);
|
|
21970
22052
|
if (lstatSync12(current).isSymbolicLink()) throw new Error("refused");
|
|
21971
22053
|
}
|
|
21972
22054
|
const stat = lstatSync12(filename2);
|
|
@@ -21997,7 +22079,7 @@ async function startLocalStaticFrontend(directory2, port, backendUrl) {
|
|
|
21997
22079
|
if (pathname === "/__backify/revision") return send(200, "text/plain", String(revision));
|
|
21998
22080
|
if (pathname === "/__backify/config.json") return send(200, "application/json", JSON.stringify({ backendUrl: backendUrl ?? null }));
|
|
21999
22081
|
const filename2 = publicFile(directory2, pathname);
|
|
22000
|
-
const content =
|
|
22082
|
+
const content = readFileSync16(filename2);
|
|
22001
22083
|
if (content.length > 5242880) throw new Error("refused");
|
|
22002
22084
|
const extension = extname2(filename2).toLowerCase();
|
|
22003
22085
|
const body = extension === ".html" ? content.toString("utf8") + '\n<script src="/__backify/reload.js?revision=' + revision + '"></script>\n' : content;
|
|
@@ -22047,15 +22129,15 @@ function prepareLocalFrontend(root, options, privateFiles = []) {
|
|
|
22047
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");
|
|
22048
22130
|
return prepareLocalStaticFrontend(directory2);
|
|
22049
22131
|
}
|
|
22050
|
-
if (!
|
|
22051
|
-
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"));
|
|
22052
22134
|
let packagePath;
|
|
22053
22135
|
try {
|
|
22054
22136
|
packagePath = require3.resolve("vite/package.json");
|
|
22055
22137
|
} catch {
|
|
22056
22138
|
throw new Error("Frontend requires locally installed Vite; Backify does not install dependencies automatically");
|
|
22057
22139
|
}
|
|
22058
|
-
const metadata = JSON.parse(
|
|
22140
|
+
const metadata = JSON.parse(readFileSync17(packagePath, "utf8"));
|
|
22059
22141
|
if (metadata.name !== "vite" || typeof metadata.bin?.vite !== "string") throw new Error("Installed Vite has no supported CLI entrypoint");
|
|
22060
22142
|
const executable = realpathSync3(resolve14(dirname10(packagePath), metadata.bin.vite));
|
|
22061
22143
|
const executablePart = relative5(realpathSync3(dirname10(packagePath)), executable);
|
|
@@ -22119,7 +22201,7 @@ async function startLocalFrontend(prepared, port, backendUrl) {
|
|
|
22119
22201
|
}
|
|
22120
22202
|
|
|
22121
22203
|
// src/local-identity.ts
|
|
22122
|
-
import { readFileSync as
|
|
22204
|
+
import { readFileSync as readFileSync18, statSync as statSync2 } from "node:fs";
|
|
22123
22205
|
import { resolve as resolve15 } from "node:path";
|
|
22124
22206
|
|
|
22125
22207
|
// ../sdk/dist/local-identity.js
|
|
@@ -22227,7 +22309,7 @@ function prepareLocalIdentity(root, filename2) {
|
|
|
22227
22309
|
if (!statSync2(path).isFile() || statSync2(path).size > 16384) throw new Error("Local identity profiles require a file at most 16 KiB");
|
|
22228
22310
|
let input;
|
|
22229
22311
|
try {
|
|
22230
|
-
input = JSON.parse(
|
|
22312
|
+
input = JSON.parse(readFileSync18(path, "utf8"));
|
|
22231
22313
|
} catch {
|
|
22232
22314
|
throw new Error("Invalid local identity profile JSON");
|
|
22233
22315
|
}
|
|
@@ -22260,7 +22342,7 @@ function localIdentityCommand(args2) {
|
|
|
22260
22342
|
}
|
|
22261
22343
|
|
|
22262
22344
|
// src/local-job-history.ts
|
|
22263
|
-
import { lstatSync as lstatSync13, readFileSync as
|
|
22345
|
+
import { lstatSync as lstatSync13, readFileSync as readFileSync19 } from "node:fs";
|
|
22264
22346
|
import { isAbsolute as isAbsolute11, resolve as resolve16 } from "node:path";
|
|
22265
22347
|
function prepareLocalJobHistory(root, filename2, artifacts, manifest, current) {
|
|
22266
22348
|
if (filename2 === void 0) return [];
|
|
@@ -22270,7 +22352,7 @@ function prepareLocalJobHistory(root, filename2, artifacts, manifest, current) {
|
|
|
22270
22352
|
assertLocalStatePath(root, path);
|
|
22271
22353
|
const metadata = lstatSync13(path);
|
|
22272
22354
|
if (!metadata.isFile() || metadata.isSymbolicLink() || metadata.nlink !== 1 || metadata.size > maximum) throw new Error();
|
|
22273
|
-
const bytes =
|
|
22355
|
+
const bytes = readFileSync19(path);
|
|
22274
22356
|
if (bytes.length > maximum) throw new Error();
|
|
22275
22357
|
return new TextDecoder("utf8", { fatal: true }).decode(bytes);
|
|
22276
22358
|
};
|
|
@@ -22317,13 +22399,13 @@ function prepareLocalJobHistory(root, filename2, artifacts, manifest, current) {
|
|
|
22317
22399
|
|
|
22318
22400
|
// src/local-secrets.ts
|
|
22319
22401
|
import { createCipheriv, createDecipheriv, randomBytes as randomBytes5, randomUUID as randomUUID9 } from "node:crypto";
|
|
22320
|
-
import { closeSync as closeSync3, existsSync as
|
|
22321
|
-
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";
|
|
22322
22404
|
var maximumBytes2 = 1048576;
|
|
22323
22405
|
var secretName = /^[A-Z][A-Z0-9_]{0,127}$/;
|
|
22324
22406
|
var failure = () => new Error("Local secret vault unavailable or invalid; review the vault and external key privately");
|
|
22325
22407
|
function vaultPath(root) {
|
|
22326
|
-
return
|
|
22408
|
+
return join14(realpathSync4(root), ".backify", "dev", "secrets.enc.json");
|
|
22327
22409
|
}
|
|
22328
22410
|
function inside(root, filename2) {
|
|
22329
22411
|
const part = relative6(root, filename2);
|
|
@@ -22336,7 +22418,7 @@ function privateFile(filename2, limit) {
|
|
|
22336
22418
|
}
|
|
22337
22419
|
const stat = lstatSync14(filename2);
|
|
22338
22420
|
if (!stat.isFile() || stat.size > limit || stat.nlink !== 1 || process.platform !== "win32" && (stat.mode & 63) !== 0) throw failure();
|
|
22339
|
-
return
|
|
22421
|
+
return readFileSync20(filename2);
|
|
22340
22422
|
}
|
|
22341
22423
|
function externalKey(root, filename2) {
|
|
22342
22424
|
const keyFile = resolve17(filename2);
|
|
@@ -22375,15 +22457,15 @@ function writePrivate2(filename2, value) {
|
|
|
22375
22457
|
}
|
|
22376
22458
|
}
|
|
22377
22459
|
function ensureIgnored(root) {
|
|
22378
|
-
const filename2 =
|
|
22460
|
+
const filename2 = join14(root, ".gitignore");
|
|
22379
22461
|
assertLocalStatePath(root, filename2);
|
|
22380
|
-
const current =
|
|
22462
|
+
const current = existsSync12(filename2) ? readFileSync20(filename2, "utf8") : "";
|
|
22381
22463
|
if (!current.split(/\r?\n/).some((line) => line.trim() === ".backify/")) writeFileSync10(filename2, current + (current && !current.endsWith("\n") ? "\n" : "") + ".backify/\n");
|
|
22382
22464
|
}
|
|
22383
22465
|
function readLocalSecrets(root, application, keyFile) {
|
|
22384
22466
|
const filename2 = vaultPath(root);
|
|
22385
22467
|
assertLocalStatePath(root, filename2);
|
|
22386
|
-
if (!
|
|
22468
|
+
if (!existsSync12(filename2) && keyFile === void 0) return {};
|
|
22387
22469
|
if (!keyFile) throw new Error("Encrypted local secrets require --local-secrets-key <external-key-file>");
|
|
22388
22470
|
let key, plaintext;
|
|
22389
22471
|
try {
|
|
@@ -22413,7 +22495,7 @@ function readLocalSecrets(root, application, keyFile) {
|
|
|
22413
22495
|
function initializeLocalSecrets(root, application, keyFile) {
|
|
22414
22496
|
const filename2 = vaultPath(root), external = resolve17(keyFile);
|
|
22415
22497
|
assertLocalStatePath(root, filename2);
|
|
22416
|
-
if (
|
|
22498
|
+
if (existsSync12(filename2) || existsSync12(external)) throw new Error("Local secret initialization never overwrites an existing vault or key");
|
|
22417
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");
|
|
22418
22500
|
for (let current = dirname11(external); ; current = dirname11(current)) {
|
|
22419
22501
|
const stat = lstatSync14(current);
|
|
@@ -22425,7 +22507,7 @@ function initializeLocalSecrets(root, application, keyFile) {
|
|
|
22425
22507
|
const release2 = acquireLocalLease(root, ".backify/dev/secrets.lock");
|
|
22426
22508
|
const key = randomBytes5(32);
|
|
22427
22509
|
try {
|
|
22428
|
-
if (
|
|
22510
|
+
if (existsSync12(filename2)) throw failure();
|
|
22429
22511
|
mkdirSync5(dirname11(filename2), { recursive: true, mode: 448 });
|
|
22430
22512
|
writePrivate2(external, key.toString("hex"));
|
|
22431
22513
|
writePrivate2(filename2, encrypt(root, application, key, {}));
|
|
@@ -22482,11 +22564,11 @@ async function localSecretsCommand(args2, root, application, input = process.std
|
|
|
22482
22564
|
|
|
22483
22565
|
// src/local-development.ts
|
|
22484
22566
|
function localManifest(root = process.cwd()) {
|
|
22485
|
-
const filename2 =
|
|
22486
|
-
if (!
|
|
22487
|
-
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"));
|
|
22488
22570
|
const entry = resolve18(root, manifest.runtime.entrypoint);
|
|
22489
|
-
if (!
|
|
22571
|
+
if (!existsSync13(entry) || !inside2(root, realpathSync5(entry))) throw new Error("Runtime entrypoint must exist inside this repository");
|
|
22490
22572
|
const discovered = analyzeSources(repositorySources(root));
|
|
22491
22573
|
const diagnostics = manifestDiagnostics(manifest, Object.keys(discovered.capabilities), discovered.capabilities.auth?.configuration);
|
|
22492
22574
|
if (diagnostics.length) throw new Error(diagnostics.map((diagnostic) => diagnostic.message).join("; "));
|
|
@@ -22497,12 +22579,12 @@ function inside2(root, path) {
|
|
|
22497
22579
|
return part !== ".." && !part.startsWith(".." + (process.platform === "win32" ? "\\" : "/")) && !isAbsolute13(part);
|
|
22498
22580
|
}
|
|
22499
22581
|
function sessionPath(root) {
|
|
22500
|
-
return
|
|
22582
|
+
return join15(root, ".backify", "dev", "session.json");
|
|
22501
22583
|
}
|
|
22502
22584
|
async function localRequest(path, input, root = process.cwd()) {
|
|
22503
22585
|
if (!/^\/v1\/[a-z/-]+$/.test(path)) throw new Error("Invalid local command path");
|
|
22504
|
-
if (!
|
|
22505
|
-
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"));
|
|
22506
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");
|
|
22507
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) });
|
|
22508
22590
|
if (!response.ok) {
|
|
@@ -22553,17 +22635,17 @@ async function startLocalDevelopment(options = {}) {
|
|
|
22553
22635
|
const identityProfiles = prepareLocalIdentity(root, options.identityUsers);
|
|
22554
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");
|
|
22555
22637
|
const preparedFrontend = prepareLocalFrontend(root, options, options.localSecretsKey ? [realpathSync5(resolve18(options.localSecretsKey))] : []);
|
|
22556
|
-
const ignorePath =
|
|
22557
|
-
if (
|
|
22558
|
-
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") : "";
|
|
22559
22641
|
if (!ignore.split(/\r?\n/).some((line) => line.trim() === ".backify/")) writeFileSync11(ignorePath, ignore + (ignore.endsWith("\n") || !ignore ? "" : "\n") + ".backify/\n");
|
|
22560
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");
|
|
22561
|
-
const directory2 =
|
|
22643
|
+
const directory2 = join15(root, ".backify", "dev");
|
|
22562
22644
|
assertLocalStatePath(root, directory2);
|
|
22563
|
-
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));
|
|
22564
22646
|
mkdirSync6(directory2, { recursive: true });
|
|
22565
22647
|
if (!inside2(root, realpathSync5(directory2))) throw new Error("Local state directory must remain inside this repository");
|
|
22566
|
-
if (
|
|
22648
|
+
if (existsSync13(sessionPath(root))) {
|
|
22567
22649
|
try {
|
|
22568
22650
|
await localRequest("/v1/status", void 0, root);
|
|
22569
22651
|
throw new Error("Backify dev is already running for this repository");
|
|
@@ -22601,7 +22683,7 @@ async function startLocalDevelopment(options = {}) {
|
|
|
22601
22683
|
return { ...worker, authTrust };
|
|
22602
22684
|
};
|
|
22603
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" });
|
|
22604
|
-
const outfile =
|
|
22686
|
+
const outfile = join15(directory2, "worker.mjs");
|
|
22605
22687
|
let child;
|
|
22606
22688
|
const trustRenewal = createLocalJobTrustRenewal(root, authMounts, { onFailure: () => console.error("Native worker trust renewal unavailable; existing validity and pin guards remain enforced."), onUpdate: () => {
|
|
22607
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) => {
|
|
@@ -22639,8 +22721,8 @@ async function startLocalDevelopment(options = {}) {
|
|
|
22639
22721
|
}
|
|
22640
22722
|
await stopChild(child);
|
|
22641
22723
|
if (stopping) return;
|
|
22642
|
-
const version = createHash13("sha256").update(
|
|
22643
|
-
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" } });
|
|
22644
22726
|
child = worker;
|
|
22645
22727
|
worker.send({ type: "local-secrets", secrets }, (error) => {
|
|
22646
22728
|
if (error) {
|
|
@@ -22682,9 +22764,9 @@ async function startLocalDevelopment(options = {}) {
|
|
|
22682
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");
|
|
22683
22765
|
if (updated.runtime.entrypoint !== manifest.runtime.entrypoint) throw new Error("Runtime entrypoint changed; restart backify dev");
|
|
22684
22766
|
} catch (error) {
|
|
22685
|
-
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")] };
|
|
22686
22768
|
}
|
|
22687
|
-
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")] };
|
|
22688
22770
|
});
|
|
22689
22771
|
build3.onEnd((result) => {
|
|
22690
22772
|
if (result.errors.length) rejectStartup(new Error("Local application build failed"));
|
|
@@ -22740,8 +22822,8 @@ async function startLocalDevelopment(options = {}) {
|
|
|
22740
22822
|
}
|
|
22741
22823
|
}
|
|
22742
22824
|
}
|
|
22743
|
-
if (
|
|
22744
|
-
const session = JSON.parse(
|
|
22825
|
+
if (existsSync13(sessionPath(root))) {
|
|
22826
|
+
const session = JSON.parse(readFileSync21(sessionPath(root), "utf8"));
|
|
22745
22827
|
if (session.token === token) unlinkSync5(sessionPath(root));
|
|
22746
22828
|
}
|
|
22747
22829
|
};
|
|
@@ -22755,11 +22837,11 @@ async function startLocalDevelopment(options = {}) {
|
|
|
22755
22837
|
}
|
|
22756
22838
|
async function runLocalTests(root = process.cwd()) {
|
|
22757
22839
|
const manifest = localManifest(root);
|
|
22758
|
-
const project = JSON.parse(
|
|
22840
|
+
const project = JSON.parse(readFileSync21(join15(root, "package.json"), "utf8"));
|
|
22759
22841
|
if (!project.scripts?.test) throw new Error("Add a test script to package.json so AI agents can run backify test");
|
|
22760
22842
|
const result = await new Promise((resolveResult, reject) => {
|
|
22761
|
-
const npmPath = process.platform === "win32" ? process.env.npm_execpath ??
|
|
22762
|
-
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)) {
|
|
22763
22845
|
reject(new Error("Cannot locate npm-cli.js; run backify test through npx or npm"));
|
|
22764
22846
|
return;
|
|
22765
22847
|
}
|
|
@@ -22786,7 +22868,7 @@ function digest3(contents) {
|
|
|
22786
22868
|
}
|
|
22787
22869
|
function packageDirectory(filename2) {
|
|
22788
22870
|
for (let current = dirname13(filename2); ; current = dirname13(current)) {
|
|
22789
|
-
if (
|
|
22871
|
+
if (existsSync14(join16(current, "package.json"))) return current;
|
|
22790
22872
|
if (dirname13(current) === current) throw new Error("Cannot locate an installed dependency package");
|
|
22791
22873
|
}
|
|
22792
22874
|
}
|
|
@@ -22898,11 +22980,11 @@ async function prepareWorkload(options) {
|
|
|
22898
22980
|
context3.onResolve({ filter: /./ }, async (input) => {
|
|
22899
22981
|
if (input.pluginData?.backifyResolved) return;
|
|
22900
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" }] };
|
|
22901
|
-
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 } });
|
|
22902
22984
|
if (!resolved.external && !resolved.errors.length && resolved.path) {
|
|
22903
22985
|
const directory2 = realpathSync6(packageDirectory(resolved.path));
|
|
22904
22986
|
const target = relative8(directory2, realpathSync6(resolved.path)).replaceAll("\\", "/");
|
|
22905
|
-
if (JSON.parse(
|
|
22987
|
+
if (JSON.parse(readFileSync22(join16(directory2, "package.json"), "utf8")).name === "@backifydev/sdk") {
|
|
22906
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" }] };
|
|
22907
22989
|
}
|
|
22908
22990
|
if (!isAbsolute14(input.path) && !input.path.startsWith(".")) trustedPackages.add(directory2);
|
|
@@ -22966,14 +23048,14 @@ async function packageWorkload(options) {
|
|
|
22966
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" };
|
|
22967
23049
|
const output = resolve19(root, options.output ?? ".backify/artifacts/" + options.kind + "-" + plan.artifactVersion.slice(0, 16));
|
|
22968
23050
|
assertLocalStatePath(root, output);
|
|
22969
|
-
if (
|
|
23051
|
+
if (existsSync14(output)) {
|
|
22970
23052
|
if (JSON.stringify(readdirSync6(output).sort()) !== JSON.stringify(Object.keys(files).sort()) || Object.entries(files).some(([name2, value]) => {
|
|
22971
|
-
assertLocalStatePath(root,
|
|
22972
|
-
return !
|
|
23053
|
+
assertLocalStatePath(root, join16(output, name2));
|
|
23054
|
+
return !readFileSync22(join16(output, name2)).equals(Buffer.from(value));
|
|
22973
23055
|
})) throw new Error("Refusing to overwrite an existing workload artifact directory");
|
|
22974
23056
|
} else {
|
|
22975
23057
|
mkdirSync7(output, { recursive: true });
|
|
22976
|
-
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 });
|
|
22977
23059
|
}
|
|
22978
23060
|
return { ...plan, outputDirectory: relative8(root, output).replaceAll("\\", "/") };
|
|
22979
23061
|
}
|
|
@@ -22982,12 +23064,12 @@ async function packageWorkload(options) {
|
|
|
22982
23064
|
import { execFileSync } from "node:child_process";
|
|
22983
23065
|
import { mkdirSync as mkdirSync8, mkdtempSync as mkdtempSync2, readdirSync as readdirSync7, rmSync as rmSync2, writeFileSync as writeFileSync13 } from "node:fs";
|
|
22984
23066
|
import { tmpdir } from "node:os";
|
|
22985
|
-
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";
|
|
22986
23068
|
|
|
22987
23069
|
// src/workload-provenance-oci.ts
|
|
22988
23070
|
import { createHash as createHash15 } from "node:crypto";
|
|
22989
|
-
import { createReadStream, lstatSync as lstatSync16, readFileSync as
|
|
22990
|
-
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";
|
|
22991
23073
|
import { Transform, Writable } from "node:stream";
|
|
22992
23074
|
import { pipeline } from "node:stream/promises";
|
|
22993
23075
|
import { createGunzip } from "node:zlib";
|
|
@@ -23009,7 +23091,7 @@ function provenanceFile(filename2, maximum) {
|
|
|
23009
23091
|
}
|
|
23010
23092
|
const stat = lstatSync16(absolute);
|
|
23011
23093
|
if (!stat.isFile() || stat.nlink !== 1 || stat.size < 1 || stat.size > maximum) throw new Error("Invalid provenance file");
|
|
23012
|
-
const bytes =
|
|
23094
|
+
const bytes = readFileSync23(absolute);
|
|
23013
23095
|
if (bytes.length !== stat.size) throw new Error("Provenance file changed during read");
|
|
23014
23096
|
return bytes;
|
|
23015
23097
|
}
|
|
@@ -23018,7 +23100,7 @@ function descriptor(value) {
|
|
|
23018
23100
|
return value;
|
|
23019
23101
|
}
|
|
23020
23102
|
function blobPath(root, value) {
|
|
23021
|
-
return
|
|
23103
|
+
return join17(root, "blobs", "sha256", descriptor(value).digest.slice(7));
|
|
23022
23104
|
}
|
|
23023
23105
|
function jsonBlob(root, value) {
|
|
23024
23106
|
const bytes = provenanceFile(blobPath(root, value), 1024 * 1024);
|
|
@@ -23027,8 +23109,8 @@ function jsonBlob(root, value) {
|
|
|
23027
23109
|
}
|
|
23028
23110
|
async function inspectProvenanceImage(root, architecture, requestedDigest) {
|
|
23029
23111
|
if (!["amd64", "arm64"].includes(architecture) || requestedDigest && !digestPattern.test(requestedDigest)) throw new Error("Invalid OCI platform or digest");
|
|
23030
|
-
if (JSON.parse(provenanceFile(
|
|
23031
|
-
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);
|
|
23032
23114
|
let current = JSON.parse(indexBytes.toString());
|
|
23033
23115
|
let selected;
|
|
23034
23116
|
let manifestDigest = provenanceHash(indexBytes);
|
|
@@ -23157,17 +23239,17 @@ async function captureWorkloadProvenance(options) {
|
|
|
23157
23239
|
if (!sha.test(commit) || !sha.test(tree)) throw new Error("Full Git commit and tree required");
|
|
23158
23240
|
const origin = git2(root, ["remote", "get-url", "origin"]);
|
|
23159
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");
|
|
23160
|
-
const lockBytes = provenanceFile(
|
|
23242
|
+
const lockBytes = provenanceFile(join18(root, "package-lock.json"), 16 * 1024 * 1024);
|
|
23161
23243
|
const dependencies = dependencyMaterials(JSON.parse(lockBytes.toString("utf8")));
|
|
23162
23244
|
const context3 = resolve21(root, options.context);
|
|
23163
23245
|
if (canonical(readdirSync7(context3).sort()) !== canonical(contextNames)) throw new Error("Exact allowlisted workload context required");
|
|
23164
23246
|
const contextDigests = {};
|
|
23165
|
-
for (const name2 of contextNames) contextDigests[name2] = provenanceHash(provenanceFile(
|
|
23166
|
-
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"));
|
|
23167
23249
|
const baseDigest = provenanceRef(options.baseImage);
|
|
23168
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");
|
|
23169
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");
|
|
23170
|
-
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");
|
|
23171
23253
|
const base = await inspectProvenanceImage(resolve21(root, options.baseLayout), options.architecture, baseDigest);
|
|
23172
23254
|
const image2 = await inspectProvenanceImage(resolve21(root, options.imageLayout), options.architecture);
|
|
23173
23255
|
verifyBaseLineage(base, image2);
|
|
@@ -23243,14 +23325,14 @@ function verifyWorkloadProvenance(options, now = /* @__PURE__ */ new Date()) {
|
|
|
23243
23325
|
evidence.push({ bytes: baseSubject, bundle: provenanceFile(options.baseBundle, 4 * 1024 * 1024), identity: { ...policy, ...supplier } });
|
|
23244
23326
|
}
|
|
23245
23327
|
const scratchRoot = resolve21(tmpdir());
|
|
23246
|
-
const scratch = mkdtempSync2(
|
|
23328
|
+
const scratch = mkdtempSync2(join18(scratchRoot, "backify-provenance-"));
|
|
23247
23329
|
if (dirname15(scratch) !== scratchRoot || !basename3(scratch).startsWith("backify-provenance-")) throw new Error("Unsafe provenance evidence directory");
|
|
23248
23330
|
try {
|
|
23249
|
-
mkdirSync8(
|
|
23250
|
-
const trustedRoot =
|
|
23331
|
+
mkdirSync8(join18(scratch, "evidence"), { mode: 448 });
|
|
23332
|
+
const trustedRoot = join18(scratch, "evidence", "trusted-root.jsonl");
|
|
23251
23333
|
writeFileSync13(trustedRoot, rootBytes, { flag: "wx", mode: 384 });
|
|
23252
23334
|
for (const [index, { bytes, bundle: bundleBytes, identity }] of evidence.entries()) {
|
|
23253
|
-
const report =
|
|
23335
|
+
const report = join18(scratch, "evidence", "report-" + index + ".json"), bundle = join18(scratch, "evidence", "bundle-" + index + ".jsonl");
|
|
23254
23336
|
writeFileSync13(report, bytes, { flag: "wx", mode: 384 });
|
|
23255
23337
|
writeFileSync13(bundle, bundleBytes, { flag: "wx", mode: 384 });
|
|
23256
23338
|
try {
|
|
@@ -23288,7 +23370,7 @@ async function workloadProvenanceCommand(args2) {
|
|
|
23288
23370
|
}
|
|
23289
23371
|
|
|
23290
23372
|
// src/workload-trust-state.ts
|
|
23291
|
-
import { lstatSync as lstatSync17, readFileSync as
|
|
23373
|
+
import { lstatSync as lstatSync17, readFileSync as readFileSync24 } from "node:fs";
|
|
23292
23374
|
import { isAbsolute as isAbsolute16, resolve as resolve22 } from "node:path";
|
|
23293
23375
|
function parseWorkloadTrustState(args2) {
|
|
23294
23376
|
const action = args2[0];
|
|
@@ -23316,7 +23398,7 @@ function workloadTrustState(options) {
|
|
|
23316
23398
|
try {
|
|
23317
23399
|
const metadata = lstatSync17(options.trustFile);
|
|
23318
23400
|
if (!metadata.isFile() || metadata.isSymbolicLink() || metadata.nlink !== 1 || metadata.size > 131072) throw new Error();
|
|
23319
|
-
const bytes =
|
|
23401
|
+
const bytes = readFileSync24(options.trustFile);
|
|
23320
23402
|
if (bytes.length > 131072) throw new Error();
|
|
23321
23403
|
trust = JSON.parse(new TextDecoder("utf8", { fatal: true }).decode(bytes));
|
|
23322
23404
|
} catch {
|
|
@@ -23332,8 +23414,8 @@ function workloadTrustState(options) {
|
|
|
23332
23414
|
}
|
|
23333
23415
|
|
|
23334
23416
|
// src/scaffold.ts
|
|
23335
|
-
import { existsSync as
|
|
23336
|
-
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";
|
|
23337
23419
|
function json2(value) {
|
|
23338
23420
|
return JSON.stringify(value, null, 2) + "\n";
|
|
23339
23421
|
}
|
|
@@ -23512,20 +23594,20 @@ provider-readiness claim, cloud deployment or browser authentication is implied.
|
|
|
23512
23594
|
function scaffoldFullStack(options) {
|
|
23513
23595
|
const files = fullStackTemplate(options.appId, options.name);
|
|
23514
23596
|
const root = resolve23(options.root ?? process.cwd());
|
|
23515
|
-
if (!
|
|
23597
|
+
if (!existsSync15(root) || !lstatSync18(root).isDirectory() || lstatSync18(root).isSymbolicLink()) throw new Error("Scaffold destination must be an existing non-linked directory");
|
|
23516
23598
|
const allowed = /* @__PURE__ */ new Set([...Object.keys(files).map((filename2) => filename2.split("/")[0]), ".git", "node_modules", "package-lock.json", ".backify"]);
|
|
23517
23599
|
if (readdirSync8(root).some((filename2) => !allowed.has(filename2))) throw new Error("Scaffolding requires an empty folder or an unchanged generated starter");
|
|
23518
23600
|
const canonicalRoot = realpathSync7(root);
|
|
23519
23601
|
const pending = [];
|
|
23520
23602
|
for (const [filename2, content] of Object.entries(files)) {
|
|
23521
|
-
const destination =
|
|
23603
|
+
const destination = join19(root, filename2);
|
|
23522
23604
|
let current = destination;
|
|
23523
23605
|
while (current !== root) {
|
|
23524
23606
|
try {
|
|
23525
23607
|
const stat = lstatSync18(current);
|
|
23526
23608
|
if (stat.isSymbolicLink() || current !== destination && !stat.isDirectory()) throw new Error("Scaffolding refuses linked or invalid output paths: " + filename2);
|
|
23527
23609
|
if (relative10(canonicalRoot, realpathSync7(current)).startsWith("..")) throw new Error("Scaffold output must remain inside its directory");
|
|
23528
|
-
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);
|
|
23529
23611
|
} catch (error) {
|
|
23530
23612
|
if (!(error instanceof Error) || !("code" in error) || error.code !== "ENOENT") throw error;
|
|
23531
23613
|
if (current === destination) pending.push(filename2);
|
|
@@ -23534,7 +23616,7 @@ function scaffoldFullStack(options) {
|
|
|
23534
23616
|
}
|
|
23535
23617
|
}
|
|
23536
23618
|
for (const filename2 of pending) {
|
|
23537
|
-
const destination =
|
|
23619
|
+
const destination = join19(root, filename2);
|
|
23538
23620
|
mkdirSync9(dirname16(destination), { recursive: true });
|
|
23539
23621
|
writeFileSync14(destination, files[filename2], { flag: "wx" });
|
|
23540
23622
|
}
|
|
@@ -23580,16 +23662,16 @@ function localInspectionCommand(args2) {
|
|
|
23580
23662
|
}
|
|
23581
23663
|
|
|
23582
23664
|
// src/index.ts
|
|
23583
|
-
import { readFileSync as
|
|
23665
|
+
import { readFileSync as readFileSync26, existsSync as existsSync16, rmSync as rmSync3 } from "node:fs";
|
|
23584
23666
|
import { homedir as homedir2 } from "node:os";
|
|
23585
|
-
import { join as
|
|
23667
|
+
import { join as join20 } from "node:path";
|
|
23586
23668
|
import { spawn as spawn5 } from "node:child_process";
|
|
23587
|
-
var configPath =
|
|
23588
|
-
var userConfig =
|
|
23669
|
+
var configPath = join20(homedir2(), ".backify.json");
|
|
23670
|
+
var userConfig = existsSync16(configPath) ? JSON.parse(readFileSync26(configPath, "utf8")) : {};
|
|
23589
23671
|
var [command2, ...args] = process.argv.slice(2);
|
|
23590
23672
|
async function call(path, init) {
|
|
23591
23673
|
let appId = option("--app");
|
|
23592
|
-
if (!appId &&
|
|
23674
|
+
if (!appId && existsSync16(join20(process.cwd(), "backify.json"))) appId = projectApplication();
|
|
23593
23675
|
const session = appId ? userConfig.sessions?.[sessionKey(appId)] : void 0;
|
|
23594
23676
|
const credential = session ?? { token: userConfig.token ?? "", organizationId: userConfig.organizationId ?? "", apiUrl: process.env.BACKIFY_API_URL ?? userConfig.apiUrl ?? "https://api.backify.dev/api" };
|
|
23595
23677
|
return (appId ? applicationClient(credential, appId) : apiClient(credential))(path, init);
|
|
@@ -23728,7 +23810,7 @@ async function main() {
|
|
|
23728
23810
|
const name2 = option("--name");
|
|
23729
23811
|
if (!name2) throw new Error("Specify --name <job>");
|
|
23730
23812
|
const payload = option("--payload");
|
|
23731
|
-
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));
|
|
23732
23814
|
} else if (["retry", "cancel"].includes(args[0])) {
|
|
23733
23815
|
const id = option("--id");
|
|
23734
23816
|
if (!id) throw new Error("Specify --id <run>");
|
|
@@ -23751,7 +23833,7 @@ async function main() {
|
|
|
23751
23833
|
const environmentId = option("--environment");
|
|
23752
23834
|
const packagePath = option("--package");
|
|
23753
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.");
|
|
23754
|
-
await deployFunctions(call, appId, applicationGuid(environmentId), new Uint8Array(
|
|
23836
|
+
await deployFunctions(call, appId, applicationGuid(environmentId), new Uint8Array(readFileSync26(packagePath)), { progress: (message) => console.log(message) });
|
|
23755
23837
|
console.log("Functions deployed.");
|
|
23756
23838
|
} else throw new Error("Use backify functions package or backify functions deploy");
|
|
23757
23839
|
break;
|
|
@@ -23786,7 +23868,7 @@ async function main() {
|
|
|
23786
23868
|
userConfig.token = args[0];
|
|
23787
23869
|
userConfig.organizationId = args[1] ?? userConfig.organizationId;
|
|
23788
23870
|
saveUserConfig(configPath, userConfig);
|
|
23789
|
-
} else await browserLogin(option("--app") ?? (
|
|
23871
|
+
} else await browserLogin(option("--app") ?? (existsSync16(join20(process.cwd(), "backify.json")) ? projectApplication() : void 0), option("--organization"));
|
|
23790
23872
|
console.log("Logged in to Backify");
|
|
23791
23873
|
break;
|
|
23792
23874
|
case "logout":
|
|
@@ -23825,7 +23907,7 @@ async function main() {
|
|
|
23825
23907
|
userConfig.sessions[key] ??= session;
|
|
23826
23908
|
saveUserConfig(configPath, userConfig);
|
|
23827
23909
|
if (args.includes("--clone")) await cloneProject(client, appId);
|
|
23828
|
-
else if (
|
|
23910
|
+
else if (existsSync16(join20(process.cwd(), ".git"))) {
|
|
23829
23911
|
const update = await pullProject(client, appId);
|
|
23830
23912
|
console.log(JSON.stringify(update, null, 2));
|
|
23831
23913
|
if (update.status === "blocked") throw new Error(update.reason);
|
|
@@ -23871,7 +23953,7 @@ async function main() {
|
|
|
23871
23953
|
break;
|
|
23872
23954
|
}
|
|
23873
23955
|
case "prompt": {
|
|
23874
|
-
if (args[0] !== "record" || !args.includes("--stdin")) throw new Error("Use backify prompt record --stdin --id <UUID> [--filename <name> ...] [--model <model>] [--ai-tool <tool>] [--access-level <access>] [--commit-sha <full-SHA>]. Only user text, filenames, device, commit, and AI context metadata are sent.");
|
|
23956
|
+
if (args[0] !== "record" || !args.includes("--stdin")) throw new Error("Use backify prompt record --stdin --id <UUID> [--filename <name> ...] [--type build|deploy|fixing|other] [--model <full-model-name-and-version>] [--ai-tool <tool>] [--access-level <access>] [--sdk-version <installed-version>] [--commit-sha <full-SHA>]. User text is recorded for every request with Backify credentials redacted. Only prompt type, user text, filenames, device, commit, SDK version, and AI context metadata are sent.");
|
|
23875
23957
|
const id = option("--id");
|
|
23876
23958
|
if (!id || !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(id)) throw new Error("Provide a UUID with --id; reuse it when retrying this prompt.");
|
|
23877
23959
|
const filenames = attachmentNames(args.flatMap((value, index) => value === "--filename" ? [args[index + 1] ?? ""] : []));
|
|
@@ -23888,7 +23970,7 @@ async function main() {
|
|
|
23888
23970
|
} else if (args[0] === "install") {
|
|
23889
23971
|
const version = option("--version"), sha256 = option("--sha256");
|
|
23890
23972
|
if (!version || !sha256) throw new Error("Use backify runtime install --version vX.Y.Z --sha256 <reviewed-digest> [--archive <local-zip>]");
|
|
23891
|
-
const bytes = option("--archive") ?
|
|
23973
|
+
const bytes = option("--archive") ? readFileSync26(option("--archive")) : await downloadLocalRuntime(version);
|
|
23892
23974
|
console.log(JSON.stringify(installLocalRuntime(bytes, { version, sha256 }), null, 2));
|
|
23893
23975
|
} else throw new Error("Use backify runtime install or backify runtime doctor");
|
|
23894
23976
|
break;
|
|
@@ -23903,7 +23985,7 @@ async function main() {
|
|
|
23903
23985
|
case "request": {
|
|
23904
23986
|
const workspaceId = option("--workspace"), name2 = option("--name"), slug = option("--slug"), description = option("--description"), configurationFile = option("--configuration");
|
|
23905
23987
|
if (!workspaceId || !name2 || !slug || !description) throw new Error("Use backify request --workspace <id> --name <name> --slug <slug> --description <purpose> [--configuration <json-file>]");
|
|
23906
|
-
const configuration = configurationFile ? JSON.parse(
|
|
23988
|
+
const configuration = configurationFile ? JSON.parse(readFileSync26(configurationFile, "utf8")) : void 0;
|
|
23907
23989
|
console.log(await call("/apps/requests", { method: "POST", body: JSON.stringify({ workspaceId, name: name2, slug, description, configuration }) }));
|
|
23908
23990
|
break;
|
|
23909
23991
|
}
|
|
@@ -23921,7 +24003,7 @@ async function main() {
|
|
|
23921
24003
|
else if (args[0] === "test") {
|
|
23922
24004
|
const name2 = option("--name"), payload = option("--payload");
|
|
23923
24005
|
if (!name2 || !payload) throw new Error("Specify --name and --payload <json-file>. Never include secrets in event payloads.");
|
|
23924
|
-
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));
|
|
23925
24007
|
} else throw new Error("Use backify events environments|inspect|test");
|
|
23926
24008
|
break;
|
|
23927
24009
|
}
|