@backifydev/cli 0.3.10 → 0.3.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +10 -0
  2. package/dist/index.js +612 -441
  3. 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: readFileSync24 } = __require("fs");
16505
- const data = readFileSync24(filePath, "utf8");
16504
+ const { readFileSync: readFileSync25 } = __require("fs");
16505
+ const data = readFileSync25(filePath, "utf8");
16506
16506
  return _CronFileParser.#parseContent(data);
16507
16507
  }
16508
16508
  /**
@@ -17599,7 +17599,7 @@ async function deployFunctions(call2, appId, environmentId, packageBytes, option
17599
17599
  if (!result.operationId) throw new Error("Function deployment did not return a tracking operation. Success has not been verified.");
17600
17600
  const now = options.now ?? Date.now;
17601
17601
  const deadline = now() + (options.timeoutMs ?? 20 * 6e4);
17602
- const sleep = options.sleep ?? ((milliseconds) => new Promise((resolve23) => setTimeout(resolve23, milliseconds)));
17602
+ const sleep = options.sleep ?? ((milliseconds) => new Promise((resolve24) => setTimeout(resolve24, milliseconds)));
17603
17603
  options.progress?.("Function deployment queued. Waiting for operation " + result.operationId + ".");
17604
17604
  while (now() < deadline) {
17605
17605
  let operation;
@@ -17660,107 +17660,12 @@ async function packageFunctions(entry, output) {
17660
17660
  return outputPath;
17661
17661
  }
17662
17662
 
17663
- // src/integrations.ts
17664
- function integrationDiscoveryPath(command3, options) {
17665
- const uuid4 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
17666
- if (!uuid4.test(options.applicationId)) throw new Error("An application UUID is required");
17667
- const base = "/apps/" + options.applicationId + "/integrations/connectors";
17668
- if (command3 === "list") return base;
17669
- if (command3 === "catalog") return "/apps/" + options.applicationId + "/integrations/catalog";
17670
- if (!options.connectionId || !uuid4.test(options.connectionId)) throw new Error("Use --connection with an integration connection UUID");
17671
- const connection = base + "/" + options.connectionId;
17672
- if (command3 === "contract" || command3 === "types") return connection + "/" + command3;
17673
- if (command3 === "describe") {
17674
- if (!options.operationId) throw new Error("Use --operation to select an operation");
17675
- return connection + "/operations/" + encodeURIComponent(options.operationId);
17676
- }
17677
- if (command3 === "search") {
17678
- if (!Number.isInteger(options.offset ?? 0) || (options.offset ?? 0) < 0 || (options.offset ?? 0) > 500) throw new Error("Offset must be between 0 and 500");
17679
- const query = new URLSearchParams({ query: options.query ?? "", offset: String(options.offset ?? 0), limit: "50" });
17680
- return connection + "/operations?" + query;
17681
- }
17682
- throw new Error("Use backify integrations list|catalog|search|describe|contract|types");
17683
- }
17684
-
17685
- // src/cli-session.ts
17686
- import { hostname, platform, release, arch } from "node:os";
17687
-
17688
- // package.json
17689
- var package_default = {
17690
- name: "@backifydev/cli",
17691
- version: "0.3.10",
17692
- description: "Command-line setup and diagnostics for Backify applications",
17693
- type: "module",
17694
- bin: {
17695
- backify: "dist/index.js"
17696
- },
17697
- files: [
17698
- "dist/index.js",
17699
- "README.md"
17700
- ],
17701
- scripts: {
17702
- prebuild: "npm run build -w @backify/platform && npm run build -w @backifydev/sdk && npm run build -w @backify/analyzer",
17703
- build: `esbuild src/index.ts --bundle --platform=node --format=esm --external:esbuild --external:typescript --outfile=dist/index.js --banner:js="import { createRequire as __backifyCreateRequire } from 'node:module'; var require = __backifyCreateRequire(import.meta.url);"`,
17704
- prepack: "npm run build",
17705
- pretypecheck: "npm run build -w @backify/platform && npm run build -w @backifydev/sdk && npm run build -w @backify/analyzer",
17706
- typecheck: "tsc --noEmit",
17707
- pretest: "npm run build -w @backify/platform && npm run build -w @backifydev/sdk && npm run build -w @backify/analyzer",
17708
- test: "vitest run"
17709
- },
17710
- publishConfig: {
17711
- access: "public"
17712
- },
17713
- repository: {
17714
- type: "git",
17715
- url: "git+https://github.com/frejnorling/backify.git",
17716
- directory: "packages/cli"
17717
- },
17718
- homepage: "https://agent.backify.dev/",
17719
- license: "MIT",
17720
- engines: {
17721
- node: ">=20"
17722
- },
17723
- dependencies: {
17724
- "@azure/functions": "^4.7.2",
17725
- "@backifydev/sdk": "^0.1.1",
17726
- esbuild: "^0.25.10",
17727
- fflate: "^0.8.2",
17728
- typescript: "^5.9.2"
17729
- },
17730
- devDependencies: {
17731
- "@backify/analyzer": "*",
17732
- "@backify/platform": "*",
17733
- "@hono/node-server": "2.1.3",
17734
- "@types/node": "^24.3.1",
17735
- hono: "4.13.12",
17736
- vitest: "^4.1.11"
17737
- }
17738
- };
17739
-
17740
- // src/cli-session.ts
17741
- function cliDevice() {
17742
- return { deviceName: hostname(), operatingSystem: platform() + " " + release(), architecture: arch(), cliVersion: package_default.version };
17743
- }
17744
- var cliUserAgent = "BackifyCLI/" + package_default.version;
17745
- async function registerCliSession(client, applicationId, apiUrl) {
17746
- const session = await client("/apps/" + applicationId + "/developer/session", { method: "POST", body: JSON.stringify(cliDevice()) });
17747
- return { ...session, apiUrl };
17748
- }
17749
-
17750
- // src/browser-auth.ts
17751
- import { randomBytes } from "node:crypto";
17752
- import { createServer } from "node:http";
17753
-
17754
- // src/development.ts
17755
- import { existsSync as existsSync4, readFileSync as readFileSync3, readdirSync as readdirSync2, writeFileSync as writeFileSync4, renameSync, rmSync, mkdtempSync, lstatSync as lstatSync2, cpSync } from "node:fs";
17756
- import { dirname as dirname4, join as join3, resolve as resolve3 } from "node:path";
17757
- import { spawnSync as spawnSync2 } from "node:child_process";
17758
- import { randomUUID } from "node:crypto";
17759
-
17760
- // src/setup.ts
17761
- import { existsSync as existsSync3, readFileSync as readFileSync2, writeFileSync as writeFileSync3, mkdirSync as mkdirSync2, readdirSync, lstatSync } from "node:fs";
17762
- import { basename, dirname as dirname3, join as join2, resolve as resolve2, isAbsolute } from "node:path";
17663
+ // src/environment.ts
17763
17664
  import { spawnSync } from "node:child_process";
17665
+ import { randomUUID } from "node:crypto";
17666
+ import { readFileSync, unlinkSync, writeFileSync as writeFileSync2 } from "node:fs";
17667
+ import { createServer } from "node:http";
17668
+ import { join, resolve as resolve2 } from "node:path";
17764
17669
 
17765
17670
  // ../platform/dist/manifest.js
17766
17671
  var import_yaml = __toESM(require_dist(), 1);
@@ -17798,8 +17703,8 @@ function parseApplicationManifest(source) {
17798
17703
  if (name2 === "ai") {
17799
17704
  if (Object.keys(settings).some((key) => !["enabled", "models"].includes(key)))
17800
17705
  throw new Error("Unknown AI setting");
17801
- if (settings.models !== void 0 && (!Array.isArray(settings.models) || settings.models.length === 0 || settings.models.length > 3 || settings.models.some((model) => !["default", "fast", "smart"].includes(String(model))) || new Set(settings.models).size !== settings.models.length))
17802
- throw new Error("AI models must be distinct logical names: default, fast, smart");
17706
+ if (settings.models !== void 0 && (!Array.isArray(settings.models) || settings.models.length === 0 || settings.models.length > 100 || settings.models.some((model) => typeof model !== "string" || !["default", "fast", "smart"].includes(model) && (model.length !== 32 || !/^foundry-[0-9a-f]{24}$/.test(model))) || new Set(settings.models).size !== settings.models.length))
17707
+ throw new Error("AI models must be distinct logical names or Foundry IDs from the application AI catalog");
17803
17708
  }
17804
17709
  if (settings.enabled !== void 0 && typeof settings.enabled !== "boolean")
17805
17710
  throw new Error("enabled must be boolean: " + name2);
@@ -17861,8 +17766,14 @@ function manifestDiagnostics(manifest, used, authentication) {
17861
17766
  // ../platform/dist/delivery.js
17862
17767
  var deliveryInstructions = `# Backify application delivery and prompt history
17863
17768
 
17864
- Instruction version: 5
17865
- Versioned guide: https://agent.backify.dev/v5/delivery.md
17769
+ Instruction version: 9
17770
+ Versioned guide: https://agent.backify.dev/v9/delivery.md
17771
+
17772
+ ## Environment and documentation prerequisites
17773
+
17774
+ Before installation or connection, read https://agent.backify.dev/v9 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
+
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.
17866
17777
 
17867
17778
  These instructions are for AI coding tools building applications on Backify, not the Backify platform implementation. Complete the application and deliver a verified deployment, not just SDK setup. Respect the coding tool's own permissions and confirmation settings; preserve unrelated work and applicable repository instructions.
17868
17779
 
@@ -17872,7 +17783,7 @@ The copied Backify prompt supplies App Id, Organization, and, when available, Pa
17872
17783
 
17873
17784
  npx @backifydev/cli@latest connect --app <app-id> --organization <organization-id> --api https://api.backify.dev/api --pair <pairing-code>
17874
17785
 
17875
- If Pair is absent, omit --pair and use CLI browser login. Pairing expires after 15 minutes. Never record the code or setup prompt in project files, Git, prompt history, or logs. The CLI stores an application-scoped session outside the repository. If access expires, obtain a new setup prompt or use CLI browser login.
17786
+ If Pair is absent, omit --pair and use CLI browser login. Pairing expires after 15 minutes. Never record the code or setup prompt in project files, Git, prompt history, or logs. 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.
17876
17787
 
17877
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.
17878
17789
 
@@ -17880,7 +17791,7 @@ Initialize using App Id from the copied prompt and the current tool selection:
17880
17791
 
17881
17792
  npx @backifydev/cli@latest init --app <app-id> --agent <current-tool>
17882
17793
 
17883
- 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/v5 for instruction version 5; 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.
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/v9 for instruction version 9; 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.
17884
17795
 
17885
17796
  Run the following to discover the connected hosting target, repository, branch, reports, releases, and deployment failures:
17886
17797
 
@@ -17920,9 +17831,9 @@ Do not claim unsupported hosted server functions or SDK execution paths work. Re
17920
17831
 
17921
17832
  ## Local development before delivery
17922
17833
 
17923
- From the first setup, make every new application runnable and testable locally without a cloud deployment. Follow the matching setup guide's local development steps: preserve the framework, provide a package-manager dev script and README, use @backifydev/sdk/local for platform capabilities and tests, and keep local state and credentials out of Git. Use a native framework dev server for frontend-only apps; for Backify server capabilities, configure backify.yaml and npx @backifydev/cli@latest dev --mode lightweight --json with the supported frontend adapter when needed. Disclose emulator limits and any full-runtime prerequisites.
17834
+ After the required setup gate passes and application requirements are supplied, make every new application runnable and testable locally without a cloud deployment. Follow the matching setup guide's local development steps: preserve the framework, provide a package-manager dev script and README, use @backifydev/sdk/local for platform capabilities and tests, and keep local state and credentials out of Git. Use a native framework dev server for frontend-only apps; for Backify server capabilities, configure backify.yaml and npx @backifydev/cli@latest dev --mode lightweight --json with the supported frontend adapter when needed. Disclose emulator limits and any full-runtime prerequisites.
17924
17835
 
17925
- 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. Cloud connection, preview approval, or deployment failure must not prevent safe local testing; report those blockers separately without bypassing authorization. If requirements are missing, verify a minimal runnable shell before asking the required final question. Never claim local readiness from a build or management-dashboard response alone.
17836
+ 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.
17926
17837
 
17927
17838
  ## Verify, push, and publish
17928
17839
 
@@ -17940,13 +17851,13 @@ If testing or approval is required, return the preview URL and explain the remai
17940
17851
 
17941
17852
  ## User-facing handoff
17942
17853
 
17943
- After setup or a delivery attempt, give the user concise instructions: explain what is ready, how to open and use the application, and any sign-in, testing, approval, or other next steps. Summarize actual checks and blockers without exposing credentials or asking the user to perform routine deployment work the coding tool can complete.
17854
+ If setup is blocked, report the failed or unverified checks and recommend an AI coding tool as described above and stop. Do not present a local application, download, or start command as a substitute for successful setup. After successful setup or a later delivery attempt, give the user concise instructions: explain what is ready, how to open and use the application, and any sign-in, testing, approval, or other next steps. Summarize actual checks and blockers without exposing credentials or asking the user to perform routine deployment work the coding tool can complete.
17944
17855
 
17945
17856
  Include the verified Local URL, exact start command, and local testing/sign-in steps even when cloud delivery is blocked. If local startup was not verified, say unavailable and explain the blocker.
17946
17857
 
17947
17858
  Include separate Preview URL and Production URL lines, using the actual URLs returned by CLI status or deployment results. Include both URLs when available. If either is unavailable, say not deployed or unavailable and explain why; never invent a URL or claim an unverified deployment is live. When production still serves an earlier release, label it as the existing production version and explain that the new changes are preview-only or awaiting approval.
17948
17859
 
17949
- If application requirements are missing after setup, finish the response with this exact question as its final line, without any text after it:
17860
+ If application requirements are missing after successful setup, finish the response with this exact question as its final line, without any text after it:
17950
17861
 
17951
17862
  What should the application do, and what should it look like?
17952
17863
 
@@ -17954,7 +17865,7 @@ These instructions are an explicit agent workflow, not a universal chat intercep
17954
17865
  `;
17955
17866
 
17956
17867
  // ../platform/dist/index.js
17957
- var INSTRUCTION_VERSION = 5;
17868
+ var INSTRUCTION_VERSION = 9;
17958
17869
  var SDK_PACKAGE = "@backifydev/sdk";
17959
17870
  var DOCS_URL = "https://docs.backify.dev";
17960
17871
  var MAIL_LIMITS = Object.freeze({
@@ -17984,7 +17895,7 @@ var CAPABILITIES = [
17984
17895
  capability("secrets", "secrets", "Server-side secret retrieval", true),
17985
17896
  capability("integrations", "integrations", "Approved, versioned API contracts and environment-scoped operation grants", true),
17986
17897
  capability("http", "http", "Governed outbound HTTP"),
17987
- capability("ai", "ai", "Server-only ai.generate, ai.extract, ai.classify and ai.embed. Declare capabilities.ai in backify.yaml; optional models: [default, fast, smart] must stay within the application allowed-model policy. Backify provisions isolated Azure Foundry model deployments and supplies scoped runtime credentials automatically. Do not add Azure/OpenAI credentials to application code."),
17898
+ capability("ai", "ai", "Server-only ai.generate, ai.extract, ai.classify and ai.embed. Declare capabilities.ai in backify.yaml; optional models may use default, fast, smart or foundry- IDs from the application's location-aware AI catalog, within its allowed-model policy. Backify provisions isolated Azure Foundry model deployments and supplies scoped runtime credentials automatically. Do not add Azure/OpenAI credentials to application code."),
17988
17899
  capability("audit", "audit", "Structured audit records"),
17989
17900
  capability("logs", "logs", "Structured application logging"),
17990
17901
  capability("config", "config", "Non-secret application configuration")
@@ -18008,6 +17919,8 @@ Use \`@backifydev/sdk\` for platform capabilities. Do not directly integrate or
18008
17919
 
18009
17920
  ## SDK capability map
18010
17921
 
17922
+ Before dependent setup operations, follow the environment checks and permission recovery in https://agent.backify.dev/v${INSTRUCTION_VERSION}. Retrieve and read the relevant documentation at ${DOCS_URL}/capabilities/ before implementing capabilities, then verify installed SDK types. If access is blocked, use only the coding tool's supported native approval mechanism, retry after approval, and report unverified work honestly. Never bypass restrictions or invent approval tools. 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.
17923
+
18011
17924
  - Authentication and authorization: \`auth\`.
18012
17925
  - Persistent data and files: \`db\` and \`storage\`.
18013
17926
  - Server functions: \`defineFunction\`; background work and schedules: \`jobs\` and \`jobs.schedule\`.
@@ -18088,39 +18001,277 @@ function validateConfig(value) {
18088
18001
  }
18089
18002
  var BACKIFY_SCHEMA = { $schema: "https://json-schema.org/draft/2020-12/schema", $id: `${DOCS_URL}/schema/backify.json`, type: "object", additionalProperties: false, required: ["$schema", "platform", "sdk", "appId", "instructionVersion", "docs", "instructions"], properties: { $schema: { const: `${DOCS_URL}/schema/backify.json` }, platform: { const: "backify" }, sdk: { const: SDK_PACKAGE }, appId: { type: "string", pattern: "^app_[A-Za-z0-9_-]+$" }, instructionVersion: { type: "integer", minimum: 1 }, agent: { enum: ["codex", "claude", "copilot", "gemini", "custom"] }, instructionFile: { type: "string", minLength: 1 }, docs: { type: "string", format: "uri" }, instructions: { type: "object", additionalProperties: false, required: ["preferBackifyCapabilities", "allowDirectCloudInfrastructure"], properties: { preferBackifyCapabilities: { const: true }, allowDirectCloudInfrastructure: { const: false } } } } };
18090
18003
 
18004
+ // src/environment.ts
18005
+ function classifyEnvironmentFailure(error) {
18006
+ const value = error;
18007
+ const code = value?.code;
18008
+ if (code === "EACCES" || code === "EPERM") return "permission";
18009
+ if (code === "ENOTFOUND" || code === "EAI_AGAIN") return "dns";
18010
+ if (code && /CERT|TLS|SSL/.test(code)) return "tls";
18011
+ if (value?.name === "TimeoutError" || value?.name === "AbortError" || code === "ETIMEDOUT" || code === "UND_ERR_CONNECT_TIMEOUT") return "timeout";
18012
+ if (code === "ECONNREFUSED" || code === "ECONNRESET" || code === "ENETUNREACH" || code === "EHOSTUNREACH") return "connection";
18013
+ if (code === "ENOENT") return "missing_tool";
18014
+ if (value?.cause && value.cause !== error) return classifyEnvironmentFailure(value.cause);
18015
+ return "unknown";
18016
+ }
18017
+ function environmentRecovery(failure2) {
18018
+ switch (failure2) {
18019
+ case "permission":
18020
+ return "Use the current agent's supported native approval mechanism for minimum required access, retry after approval and verify. If unsupported or denied, enable access or switch environments; never bypass restrictions.";
18021
+ case "dns":
18022
+ return "Check DNS and the endpoint hostname; retry once for a temporary failure. Request network access only if policy confirms it is blocked.";
18023
+ case "tls":
18024
+ return "Check the certificate, system clock and trusted proxy configuration; never disable TLS verification.";
18025
+ case "timeout":
18026
+ case "connection":
18027
+ return "Check connectivity and exposed network policy; retry once if temporary. A timeout or connection error alone does not prove a sandbox restriction.";
18028
+ case "authentication":
18029
+ return "HTTP 401/403 indicates authentication or access denial, not necessarily a sandbox. For expired CLI sessions use backify connect --reauth; never request another setup prompt or send credentials to a public probe.";
18030
+ case "not_found":
18031
+ return "Check the documented URL and resource; HTTP 404 is not an environment restriction.";
18032
+ case "rate_limit":
18033
+ return "Respect Retry-After within the task's time budget; do not repeatedly retry.";
18034
+ case "server":
18035
+ return "Report the endpoint's HTTP 5xx; retry once if temporary and keep cloud failures separate from local work.";
18036
+ case "missing_tool":
18037
+ return "Install the missing prerequisite with authorized tools or use a terminal-enabled environment that supplies it.";
18038
+ default:
18039
+ return "Report the failed check without exposing credentials. Consult https://agent.backify.dev for diagnosis and safe fallback; do not claim verification succeeded.";
18040
+ }
18041
+ }
18042
+ function environmentEndpoints(capability2) {
18043
+ if (capability2 !== void 0 && !Object.hasOwn(CAPABILITY_REGISTRY, capability2)) throw new Error("Select a documented Backify capability name.");
18044
+ return [
18045
+ "https://agent.backify.dev/",
18046
+ "https://docs.backify.dev/",
18047
+ "https://api.backify.dev/health",
18048
+ "https://registry.npmjs.org/@backifydev%2fcli",
18049
+ "https://registry.npmjs.org/@backifydev%2fsdk",
18050
+ ...capability2 ? [CAPABILITY_REGISTRY[capability2].docs] : []
18051
+ ];
18052
+ }
18053
+ async function probeEndpoint(url, transport = fetch) {
18054
+ const response = await transport(url, { signal: AbortSignal.timeout(5e3), redirect: "error", credentials: "omit" });
18055
+ await response.body?.cancel();
18056
+ return response.status;
18057
+ }
18058
+ function workspaceProbe(root) {
18059
+ const directory2 = resolve2(root);
18060
+ const filename2 = join(directory2, ".backify-environment-" + randomUUID());
18061
+ const content = randomUUID();
18062
+ let created = false;
18063
+ try {
18064
+ writeFileSync2(filename2, content, { flag: "wx" });
18065
+ created = true;
18066
+ if (readFileSync(filename2, "utf8") !== content) throw new Error("Workspace read/write failed.");
18067
+ } finally {
18068
+ if (created) unlinkSync(filename2);
18069
+ }
18070
+ }
18071
+ async function localhostProbe() {
18072
+ const server = createServer((_request, response) => {
18073
+ response.end("backify-environment-probe");
18074
+ });
18075
+ try {
18076
+ await new Promise((accept, reject) => {
18077
+ server.once("error", reject);
18078
+ server.listen(0, "127.0.0.1", () => accept());
18079
+ });
18080
+ const address = server.address();
18081
+ if (!address || typeof address === "string") throw new Error("No loopback address.");
18082
+ const response = await fetch("http://127.0.0.1:" + address.port, { signal: AbortSignal.timeout(5e3), redirect: "error" });
18083
+ if (!response.ok || await response.text() !== "backify-environment-probe") throw new Error("Loopback verification failed.");
18084
+ } finally {
18085
+ server.closeAllConnections();
18086
+ if (server.listening) await new Promise((accept) => server.close(() => accept()));
18087
+ }
18088
+ }
18089
+ function environmentProbes(root) {
18090
+ return {
18091
+ nodeVersion: process.versions.node,
18092
+ command: (name2) => {
18093
+ const windowsNpm = name2 === "npm" && process.platform === "win32";
18094
+ const executable = windowsNpm ? process.env.ComSpec ?? "cmd.exe" : name2;
18095
+ const argumentsList = windowsNpm ? ["/d", "/s", "/c", "npm.cmd --version"] : ["--version"];
18096
+ const result = spawnSync(executable, argumentsList, { timeout: 5e3, stdio: "ignore", windowsHide: true });
18097
+ if (result.error) throw result.error;
18098
+ if (result.status !== 0) throw Object.assign(new Error("Prerequisite command failed."), { code: result.status === 127 || result.status === 9009 ? "ENOENT" : void 0 });
18099
+ },
18100
+ workspace: () => workspaceProbe(root),
18101
+ localhost: localhostProbe,
18102
+ request: probeEndpoint
18103
+ };
18104
+ }
18105
+ async function diagnoseEnvironment(root = process.cwd(), options = {}, probes = environmentProbes(root)) {
18106
+ const endpoints = environmentEndpoints(options.capability);
18107
+ const checks = [];
18108
+ const check = async (name2, required, operation) => {
18109
+ try {
18110
+ await operation();
18111
+ checks.push({ name: name2, required, status: "passed" });
18112
+ } catch (error) {
18113
+ const failure2 = classifyEnvironmentFailure(error);
18114
+ checks.push({ name: name2, required, status: "failed", failure: failure2, recovery: environmentRecovery(failure2) });
18115
+ }
18116
+ };
18117
+ checks.push({ name: "node", required: true, status: Number(probes.nodeVersion.split(".")[0]) >= 20 ? "passed" : "failed", ...Number(probes.nodeVersion.split(".")[0]) >= 20 ? {} : { failure: "missing_tool", recovery: "Install Node.js 20 or later with authorized tools." } });
18118
+ await check("npm", true, () => probes.command("npm"));
18119
+ await check("git", false, () => probes.command("git"));
18120
+ await check("workspace", true, probes.workspace);
18121
+ await check("localhost", true, probes.localhost);
18122
+ for (const endpoint of endpoints) {
18123
+ if (!options.network) {
18124
+ checks.push({ name: "network", endpoint, required: true, status: "unverified", recovery: "Run backify doctor --environment --network using authorized network access." });
18125
+ continue;
18126
+ }
18127
+ try {
18128
+ const httpStatus = await probes.request(endpoint);
18129
+ const failure2 = httpStatus === 401 || httpStatus === 403 ? "authentication" : httpStatus === 404 ? "not_found" : httpStatus === 429 ? "rate_limit" : httpStatus >= 500 ? "server" : httpStatus >= 200 && httpStatus < 300 ? void 0 : "http";
18130
+ checks.push({ name: "network", endpoint, required: true, httpStatus, status: failure2 ? "failed" : "passed", ...failure2 ? { failure: failure2, recovery: environmentRecovery(failure2) } : {} });
18131
+ } catch (error) {
18132
+ const failure2 = classifyEnvironmentFailure(error);
18133
+ checks.push({ name: "network", endpoint, required: true, status: "failed", failure: failure2, recovery: environmentRecovery(failure2) });
18134
+ }
18135
+ }
18136
+ for (const name2 of ["agent_approval_support", "browser_authentication", "cross_session_persistence", "application_tests", "deployment_authorization"]) checks.push({ name: name2, required: false, status: "unverified", recovery: "Verify with the current agent's exposed tools and the actual workflow; CLI diagnostics cannot grant or infer authorization." });
18137
+ return { schemaVersion: 1, valid: !checks.some((item) => item.required && item.status === "failed"), verified: checks.filter((item) => item.required).every((item) => item.status === "passed"), checks };
18138
+ }
18139
+
18140
+ // src/integrations.ts
18141
+ function integrationDiscoveryPath(command3, options) {
18142
+ const uuid4 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
18143
+ if (!uuid4.test(options.applicationId)) throw new Error("An application UUID is required");
18144
+ const base = "/apps/" + options.applicationId + "/integrations/connectors";
18145
+ if (command3 === "list") return base;
18146
+ if (command3 === "catalog") return "/apps/" + options.applicationId + "/integrations/catalog";
18147
+ if (!options.connectionId || !uuid4.test(options.connectionId)) throw new Error("Use --connection with an integration connection UUID");
18148
+ const connection = base + "/" + options.connectionId;
18149
+ if (command3 === "contract" || command3 === "types") return connection + "/" + command3;
18150
+ if (command3 === "describe") {
18151
+ if (!options.operationId) throw new Error("Use --operation to select an operation");
18152
+ return connection + "/operations/" + encodeURIComponent(options.operationId);
18153
+ }
18154
+ if (command3 === "search") {
18155
+ if (!Number.isInteger(options.offset ?? 0) || (options.offset ?? 0) < 0 || (options.offset ?? 0) > 500) throw new Error("Offset must be between 0 and 500");
18156
+ const query = new URLSearchParams({ query: options.query ?? "", offset: String(options.offset ?? 0), limit: "50" });
18157
+ return connection + "/operations?" + query;
18158
+ }
18159
+ throw new Error("Use backify integrations list|catalog|search|describe|contract|types");
18160
+ }
18161
+
18162
+ // src/cli-session.ts
18163
+ import { hostname, platform, release, arch } from "node:os";
18164
+
18165
+ // package.json
18166
+ var package_default = {
18167
+ name: "@backifydev/cli",
18168
+ version: "0.3.11",
18169
+ description: "Command-line setup and diagnostics for Backify applications",
18170
+ type: "module",
18171
+ bin: {
18172
+ backify: "dist/index.js"
18173
+ },
18174
+ files: [
18175
+ "dist/index.js",
18176
+ "README.md"
18177
+ ],
18178
+ scripts: {
18179
+ prebuild: "npm run build -w @backify/platform && npm run build -w @backifydev/sdk && npm run build -w @backify/analyzer",
18180
+ build: `esbuild src/index.ts --bundle --platform=node --format=esm --external:esbuild --external:typescript --outfile=dist/index.js --banner:js="import { createRequire as __backifyCreateRequire } from 'node:module'; var require = __backifyCreateRequire(import.meta.url);"`,
18181
+ prepack: "npm run build",
18182
+ pretypecheck: "npm run build -w @backify/platform && npm run build -w @backifydev/sdk && npm run build -w @backify/analyzer",
18183
+ typecheck: "tsc --noEmit",
18184
+ pretest: "npm run build -w @backify/platform && npm run build -w @backifydev/sdk && npm run build -w @backify/analyzer",
18185
+ test: "vitest run"
18186
+ },
18187
+ publishConfig: {
18188
+ access: "public"
18189
+ },
18190
+ repository: {
18191
+ type: "git",
18192
+ url: "git+https://github.com/frejnorling/backify.git",
18193
+ directory: "packages/cli"
18194
+ },
18195
+ homepage: "https://agent.backify.dev/",
18196
+ license: "MIT",
18197
+ engines: {
18198
+ node: ">=20"
18199
+ },
18200
+ dependencies: {
18201
+ "@azure/functions": "^4.7.2",
18202
+ "@backifydev/sdk": "^0.1.1",
18203
+ esbuild: "^0.25.10",
18204
+ fflate: "^0.8.2",
18205
+ typescript: "^5.9.2"
18206
+ },
18207
+ devDependencies: {
18208
+ "@backify/analyzer": "*",
18209
+ "@backify/platform": "*",
18210
+ "@hono/node-server": "2.1.3",
18211
+ "@types/node": "^24.3.1",
18212
+ hono: "4.13.12",
18213
+ vitest: "^4.1.11"
18214
+ }
18215
+ };
18216
+
18217
+ // src/cli-session.ts
18218
+ function cliDevice() {
18219
+ return { deviceName: hostname(), operatingSystem: platform() + " " + release(), architecture: arch(), cliVersion: package_default.version };
18220
+ }
18221
+ var cliUserAgent = "BackifyCLI/" + package_default.version;
18222
+ async function registerCliSession(client, applicationId, apiUrl) {
18223
+ const session = await client("/apps/" + applicationId + "/developer/session", { method: "POST", body: JSON.stringify(cliDevice()) });
18224
+ return { ...session, apiUrl };
18225
+ }
18226
+
18227
+ // src/browser-auth.ts
18228
+ import { randomBytes } from "node:crypto";
18229
+ import { createServer as createServer2 } from "node:http";
18230
+
18231
+ // src/development.ts
18232
+ import { existsSync as existsSync4, readFileSync as readFileSync4, readdirSync as readdirSync2, writeFileSync as writeFileSync5, renameSync, rmSync, mkdtempSync, lstatSync as lstatSync2, cpSync } from "node:fs";
18233
+ import { dirname as dirname4, join as join4, resolve as resolve4 } from "node:path";
18234
+ import { spawnSync as spawnSync3 } from "node:child_process";
18235
+ import { randomUUID as randomUUID2 } from "node:crypto";
18236
+
18237
+ // src/setup.ts
18238
+ import { existsSync as existsSync3, readFileSync as readFileSync3, writeFileSync as writeFileSync4, mkdirSync as mkdirSync2, readdirSync, lstatSync } from "node:fs";
18239
+ import { basename, dirname as dirname3, join as join3, resolve as resolve3, isAbsolute } from "node:path";
18240
+ import { spawnSync as spawnSync2 } from "node:child_process";
18241
+
18091
18242
  // src/delivery.ts
18092
- import { existsSync as existsSync2, readFileSync, writeFileSync as writeFileSync2 } from "node:fs";
18093
- import { dirname as dirname2, join, relative as relativePath } from "node:path";
18243
+ import { existsSync as existsSync2, readFileSync as readFileSync2, writeFileSync as writeFileSync3 } from "node:fs";
18244
+ import { dirname as dirname2, join as join2, relative as relativePath } from "node:path";
18094
18245
  import { createHash } from "node:crypto";
18095
18246
  var previousGeneratedWorkflowHashes = /* @__PURE__ */ new Set(["33e962274e8493f7cbac2afbac05a4e96afeec49ee08cf2bf82f8add9081b28b", "578dfb4c771c623fd04454e8a604efd701d5563d11e11191324862369bd24718", "6eb280ae7bdb14c390011686c41400f59c023304c3015d8440b7e80aaafa1c11", "545e03a1d5b996ade179e0e60ed5c86accdadc1982c1c25efd094e34f72f47ee"]);
18096
18247
  function validateDeliveryInstructions(root) {
18097
18248
  for (const filename2 of ["BACKIFY.md", "BACKIFY-WORKFLOW.md"]) {
18098
- const path = join(root, filename2);
18249
+ const path = join2(root, filename2);
18099
18250
  if (existsSync2(path)) {
18100
- const existing = readFileSync(path, "utf8").replace(/\r\n/g, "\n");
18251
+ const existing = readFileSync2(path, "utf8").replace(/\r\n/g, "\n");
18101
18252
  if (existing !== deliveryInstructions && !previousGeneratedWorkflowHashes.has(createHash("sha256").update(existing).digest("hex"))) throw new Error(filename2 + " contains different instructions. Review it before initializing; it will not be overwritten.");
18102
18253
  }
18103
18254
  }
18104
18255
  }
18105
18256
  function installDeliveryInstructions(root, instructionFiles2) {
18106
18257
  validateDeliveryInstructions(root);
18107
- writeFileSync2(join(root, "BACKIFY.md"), deliveryInstructions);
18258
+ writeFileSync3(join2(root, "BACKIFY.md"), deliveryInstructions);
18108
18259
  for (const relative11 of instructionFiles2) {
18109
- const instructionPath = join(root, relative11), content = readFileSync(instructionPath, "utf8");
18110
- const link = relativePath(dirname2(instructionPath), join(root, "BACKIFY.md")).replaceAll("\\", "/");
18111
- const legacyLink = relativePath(dirname2(instructionPath), join(root, "BACKIFY-WORKFLOW.md")).replaceAll("\\", "/");
18260
+ const instructionPath = join2(root, relative11), content = readFileSync2(instructionPath, "utf8");
18261
+ const link = relativePath(dirname2(instructionPath), join2(root, "BACKIFY.md")).replaceAll("\\", "/");
18262
+ const legacyLink = relativePath(dirname2(instructionPath), join2(root, "BACKIFY-WORKFLOW.md")).replaceAll("\\", "/");
18112
18263
  const legacy = "For application delivery and recording each user request, follow [BACKIFY-WORKFLOW.md](" + legacyLink + ").";
18113
18264
  const guidance = "For application delivery and recording each user request, follow [BACKIFY.md](" + link + ").";
18114
- if (content.includes(legacy)) writeFileSync2(instructionPath, content.replace(legacy, guidance));
18115
- else if (!content.includes("## Backify delivery")) writeFileSync2(instructionPath, content.trimEnd() + "\n\n## Backify delivery\n\n" + guidance + "\n");
18265
+ if (content.includes(legacy)) writeFileSync3(instructionPath, content.replace(legacy, guidance));
18266
+ else if (!content.includes("## Backify delivery")) writeFileSync3(instructionPath, content.trimEnd() + "\n\n## Backify delivery\n\n" + guidance + "\n");
18116
18267
  }
18117
18268
  }
18118
18269
 
18119
18270
  // src/setup.ts
18120
18271
  var instructionFiles = ["AGENTS.md"];
18121
- var agentInstructionFiles = { codex: "AGENTS.md", claude: "CLAUDE.md", copilot: join2(".github", "copilot-instructions.md"), gemini: "GEMINI.md" };
18272
+ var agentInstructionFiles = { codex: "AGENTS.md", claude: "CLAUDE.md", copilot: join3(".github", "copilot-instructions.md"), gemini: "GEMINI.md" };
18122
18273
  function instructionSelection(root, agent, instructionFile) {
18123
- const configPath2 = join2(root, "backify.json"), configured = existsSync3(configPath2) ? JSON.parse(readFileSync2(configPath2, "utf8")) : {};
18274
+ const configPath2 = join3(root, "backify.json"), configured = existsSync3(configPath2) ? JSON.parse(readFileSync3(configPath2, "utf8")) : {};
18124
18275
  const custom = instructionFile ?? (agent === void 0 ? configured.instructionFile : void 0);
18125
18276
  const selected = instructionFile !== void 0 ? "custom" : agent ?? configured.agent ?? "codex";
18126
18277
  if (typeof selected !== "string" || selected !== "custom" && !Object.hasOwn(agentInstructionFiles, selected)) throw new Error("Select the current tool with --agent or --instruction-file <relative-path>.");
@@ -18129,7 +18280,7 @@ function instructionSelection(root, agent, instructionFile) {
18129
18280
  const normalized = filename2.replaceAll("\\", "/"), parts = normalized.split("/");
18130
18281
  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.");
18131
18282
  for (let index = 1; index <= parts.length; index++) {
18132
- const entry = join2(root, ...parts.slice(0, index));
18283
+ const entry = join3(root, ...parts.slice(0, index));
18133
18284
  try {
18134
18285
  const metadata = lstatSync(entry);
18135
18286
  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.");
@@ -18144,26 +18295,26 @@ function selectedInstructionFiles(root = process.cwd(), agent, instructionFile)
18144
18295
  }
18145
18296
  function isToolWorkspaceEntry(entry, root = process.cwd()) {
18146
18297
  if (entry.name.toLowerCase() === ".git" || entry.name.toLowerCase() === ".env" || entry.name.toLowerCase().startsWith(".env.")) return false;
18147
- return entry.isDirectory() && (entry.name.startsWith(".") || ["work", "outputs"].includes(entry.name) || readdirSync(join2(root, entry.name)).length === 0) || entry.isFile() && (entry.name.startsWith(".") || /\.(md|mdc)$/i.test(entry.name));
18298
+ return entry.isDirectory() && (entry.name.startsWith(".") || ["work", "outputs"].includes(entry.name) || readdirSync(join3(root, entry.name)).length === 0) || entry.isFile() && (entry.name.startsWith(".") || /\.(md|mdc)$/i.test(entry.name));
18148
18299
  }
18149
18300
  function detectPackageManager(root = process.cwd()) {
18150
- for (const [file, name2] of [["pnpm-lock.yaml", "pnpm"], ["yarn.lock", "yarn"], ["bun.lockb", "bun"], ["bun.lock", "bun"], ["package-lock.json", "npm"]]) if (existsSync3(join2(root, file))) return name2;
18301
+ for (const [file, name2] of [["pnpm-lock.yaml", "pnpm"], ["yarn.lock", "yarn"], ["bun.lockb", "bun"], ["bun.lock", "bun"], ["package-lock.json", "npm"]]) if (existsSync3(join3(root, file))) return name2;
18151
18302
  return "npm";
18152
18303
  }
18153
18304
  function updateInstructions(root = process.cwd(), agent, instructionFile) {
18154
18305
  const updates = selectedInstructionFiles(root, agent, instructionFile).map((relative11) => {
18155
- const path = join2(root, relative11);
18156
- return { path, content: updateManagedInstructions(existsSync3(path) ? readFileSync2(path, "utf8") : "") };
18306
+ const path = join3(root, relative11);
18307
+ return { path, content: updateManagedInstructions(existsSync3(path) ? readFileSync3(path, "utf8") : "") };
18157
18308
  });
18158
18309
  for (const { path, content } of updates) {
18159
18310
  mkdirSync2(dirname3(path), { recursive: true });
18160
- writeFileSync3(path, content);
18311
+ writeFileSync4(path, content);
18161
18312
  }
18162
18313
  }
18163
18314
  function synchronize(root = process.cwd(), agent, instructionFile) {
18164
- const path = join2(root, "backify.json");
18315
+ const path = join3(root, "backify.json");
18165
18316
  if (!existsSync3(path)) throw new Error("backify.json is missing; run backify init --app app_xxxxx");
18166
- const value = JSON.parse(readFileSync2(path, "utf8")), issues = validateConfig(value);
18317
+ const value = JSON.parse(readFileSync3(path, "utf8")), issues = validateConfig(value);
18167
18318
  if (issues.length) throw new Error(issues.join("; "));
18168
18319
  if (value.instructionVersion > INSTRUCTION_VERSION) throw new Error("This app uses newer instructions. Install a matching or newer CLI before syncing.");
18169
18320
  const selected = instructionSelection(root, agent, instructionFile);
@@ -18173,11 +18324,11 @@ function synchronize(root = process.cwd(), agent, instructionFile) {
18173
18324
  value.agent = selected.agent;
18174
18325
  value.instructionFile = selected.instructionFile;
18175
18326
  value.instructionVersion = INSTRUCTION_VERSION;
18176
- writeFileSync3(path, JSON.stringify(value, null, 2) + "\n");
18327
+ writeFileSync4(path, JSON.stringify(value, null, 2) + "\n");
18177
18328
  }
18178
18329
  function sdkInstalled(root = process.cwd()) {
18179
18330
  try {
18180
- const pkg = JSON.parse(readFileSync2(join2(root, "package.json"), "utf8"));
18331
+ const pkg = JSON.parse(readFileSync3(join3(root, "package.json"), "utf8"));
18181
18332
  return Boolean(pkg.dependencies?.[SDK_PACKAGE] || pkg.devDependencies?.[SDK_PACKAGE]);
18182
18333
  } catch {
18183
18334
  return false;
@@ -18185,26 +18336,26 @@ function sdkInstalled(root = process.cwd()) {
18185
18336
  }
18186
18337
  function installSdk(root = process.cwd()) {
18187
18338
  if (sdkInstalled(root)) return;
18188
- const manager = detectPackageManager(root), args2 = manager === "npm" ? ["install", SDK_PACKAGE] : ["add", SDK_PACKAGE], result = spawnSync(manager, args2, { cwd: root, stdio: "inherit", shell: process.platform === "win32" });
18339
+ const manager = detectPackageManager(root), args2 = manager === "npm" ? ["install", SDK_PACKAGE] : ["add", SDK_PACKAGE], result = spawnSync2(manager, args2, { cwd: root, stdio: "inherit", shell: process.platform === "win32" });
18189
18340
  if (result.status !== 0) throw new Error(`Could not install ${SDK_PACKAGE} with ${manager}`);
18190
18341
  }
18191
18342
  function ensurePackageManifest(root) {
18192
- const path = join2(root, "package.json");
18343
+ const path = join3(root, "package.json");
18193
18344
  if (existsSync3(path)) return;
18194
18345
  const setupFiles = /* @__PURE__ */ new Set([".git", ".gitignore", ".github", "AGENTS.md", "CLAUDE.md", "GEMINI.md", "BACKIFY.md", "BACKIFY-WORKFLOW.md", "README.md", "LICENSE", "backify.json"]);
18195
18346
  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/");
18196
- const name2 = basename(resolve2(root)).toLowerCase().replace(/[^a-z0-9-]+/g, "-").replace(/^-+|-+$/g, "") || "backify-app";
18197
- writeFileSync3(path, JSON.stringify({ name: name2, version: "0.0.0", private: true, type: "module" }, null, 2) + "\n", { flag: "wx" });
18347
+ const name2 = basename(resolve3(root)).toLowerCase().replace(/[^a-z0-9-]+/g, "-").replace(/^-+|-+$/g, "") || "backify-app";
18348
+ writeFileSync4(path, JSON.stringify({ name: name2, version: "0.0.0", private: true, type: "module" }, null, 2) + "\n", { flag: "wx" });
18198
18349
  }
18199
18350
  function initialize(appId, root = process.cwd(), install = true, agent, instructionFile) {
18200
18351
  if (!/^app_[A-Za-z0-9_-]+$/.test(appId)) throw new Error("Provide an application ID using --app app_xxxxx");
18201
18352
  const selected = instructionSelection(root, agent, instructionFile), files = selected.files;
18202
18353
  validateDeliveryInstructions(root);
18203
- for (const relative11 of files) if (existsSync3(join2(root, relative11))) updateManagedInstructions(readFileSync2(join2(root, relative11), "utf8"));
18354
+ for (const relative11 of files) if (existsSync3(join3(root, relative11))) updateManagedInstructions(readFileSync3(join3(root, relative11), "utf8"));
18204
18355
  ensurePackageManifest(root);
18205
18356
  if (install) installSdk(root);
18206
- const configPath2 = join2(root, "backify.json"), existing = existsSync3(configPath2) ? JSON.parse(readFileSync2(configPath2, "utf8")) : {};
18207
- writeFileSync3(configPath2, JSON.stringify({ ...existing, ...createConfig(appId), agent: selected.agent, instructionFile: selected.instructionFile }, null, 2) + "\n");
18357
+ const configPath2 = join3(root, "backify.json"), existing = existsSync3(configPath2) ? JSON.parse(readFileSync3(configPath2, "utf8")) : {};
18358
+ writeFileSync4(configPath2, JSON.stringify({ ...existing, ...createConfig(appId), agent: selected.agent, instructionFile: selected.instructionFile }, null, 2) + "\n");
18208
18359
  updateInstructions(root, selected.agent, selected.instructionFile);
18209
18360
  installDeliveryInstructions(root, files);
18210
18361
  }
@@ -18213,7 +18364,7 @@ function doctor(root = process.cwd(), agent, instructionFile) {
18213
18364
  if (!sdkInstalled(root)) issues.push(`${SDK_PACKAGE} is not installed`);
18214
18365
  let config;
18215
18366
  try {
18216
- config = JSON.parse(readFileSync2(join2(root, "backify.json"), "utf8"));
18367
+ config = JSON.parse(readFileSync3(join3(root, "backify.json"), "utf8"));
18217
18368
  issues.push(...validateConfig(config));
18218
18369
  } catch {
18219
18370
  issues.push("backify.json is missing or invalid JSON");
@@ -18226,16 +18377,16 @@ function doctor(root = process.cwd(), agent, instructionFile) {
18226
18377
  issues.push(reason instanceof Error ? reason.message : String(reason));
18227
18378
  }
18228
18379
  for (const relative11 of files) {
18229
- const path = join2(root, relative11);
18380
+ const path = join3(root, relative11);
18230
18381
  if (!existsSync3(path)) {
18231
18382
  issues.push(`${relative11} is missing`);
18232
18383
  continue;
18233
18384
  }
18234
- issues.push(...managedInstructionIssues(readFileSync2(path, "utf8")).map((issue) => `${relative11} ${issue}`));
18385
+ issues.push(...managedInstructionIssues(readFileSync3(path, "utf8")).map((issue) => `${relative11} ${issue}`));
18235
18386
  }
18236
18387
  let version = "unknown";
18237
18388
  try {
18238
- const pkg = JSON.parse(readFileSync2(join2(root, "package.json"), "utf8"));
18389
+ const pkg = JSON.parse(readFileSync3(join3(root, "package.json"), "utf8"));
18239
18390
  version = pkg.dependencies?.[SDK_PACKAGE] ?? pkg.devDependencies?.[SDK_PACKAGE] ?? "missing";
18240
18391
  } catch {
18241
18392
  }
@@ -18243,6 +18394,14 @@ function doctor(root = process.cwd(), agent, instructionFile) {
18243
18394
  }
18244
18395
 
18245
18396
  // src/development.ts
18397
+ function promptContext(root = process.cwd()) {
18398
+ let commitSha = null;
18399
+ try {
18400
+ commitSha = git(["rev-parse", "HEAD"], root);
18401
+ } catch {
18402
+ }
18403
+ return { device: cliDevice(), commitSha };
18404
+ }
18246
18405
  function promptMetadata(args2) {
18247
18406
  const fields5 = [["--model", "model", 200], ["--ai-tool", "aiTool", 200], ["--access-level", "accessLevel", 500]];
18248
18407
  const metadata = {};
@@ -18254,6 +18413,12 @@ function promptMetadata(args2) {
18254
18413
  throw new Error(`Provide ${flag} with a nonempty value of at most ${maxLength} characters without control characters or credentials.`);
18255
18414
  metadata[field] = value;
18256
18415
  }
18416
+ const commitIndex = args2.indexOf("--commit-sha");
18417
+ if (commitIndex >= 0) {
18418
+ const value = args2[commitIndex + 1];
18419
+ if (!value || !/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/i.test(value)) throw new Error("Provide --commit-sha with a full hexadecimal Git commit.");
18420
+ metadata.commitSha = value;
18421
+ }
18257
18422
  return metadata;
18258
18423
  }
18259
18424
  function applicationGuid(appId) {
@@ -18264,8 +18429,8 @@ function applicationGuid(appId) {
18264
18429
  return [value.slice(0, 8), value.slice(8, 12), value.slice(12, 16), value.slice(16, 20), value.slice(20)].join("-");
18265
18430
  }
18266
18431
  function projectApplication(root = process.cwd()) {
18267
- if (!existsSync4(join3(root, "backify.json"))) throw new Error("Run backify connect --app <application-id>, then backify init.");
18268
- return JSON.parse(readFileSync3(join3(root, "backify.json"), "utf8")).appId;
18432
+ if (!existsSync4(join4(root, "backify.json"))) throw new Error("Run backify connect --app <application-id>, then backify init.");
18433
+ return JSON.parse(readFileSync4(join4(root, "backify.json"), "utf8")).appId;
18269
18434
  }
18270
18435
  function apiAddress(value) {
18271
18436
  const address = new URL(value);
@@ -18298,13 +18463,13 @@ function apiClient(session, transport = fetch) {
18298
18463
  };
18299
18464
  }
18300
18465
  function saveUserConfig(path, config) {
18301
- const temporary = path + "." + randomUUID() + ".tmp";
18466
+ const temporary = path + "." + randomUUID2() + ".tmp";
18302
18467
  try {
18303
- writeFileSync4(temporary, JSON.stringify(config, null, 2) + "\n", { mode: 384, flag: "wx" });
18468
+ writeFileSync5(temporary, JSON.stringify(config, null, 2) + "\n", { mode: 384, flag: "wx" });
18304
18469
  if (process.platform === "win32") {
18305
18470
  const account = [process.env.USERDOMAIN, process.env.USERNAME].filter(Boolean).join("\\");
18306
18471
  if (!account) throw new Error("Cannot identify the account to protect CLI credentials.");
18307
- const secured = spawnSync2("icacls", [temporary, "/inheritance:r", "/grant:r", account + ":(F)"], { windowsHide: true, encoding: "utf8" });
18472
+ const secured = spawnSync3("icacls", [temporary, "/inheritance:r", "/grant:r", account + ":(F)"], { windowsHide: true, encoding: "utf8" });
18308
18473
  if (secured.status !== 0) throw new Error("Could not restrict CLI credential file permissions.");
18309
18474
  }
18310
18475
  renameSync(temporary, path);
@@ -18318,7 +18483,7 @@ function repositoryName(remote) {
18318
18483
  return match[1].toLowerCase();
18319
18484
  }
18320
18485
  function git(args2, root = process.cwd(), environment = process.env) {
18321
- const result = spawnSync2("git", args2, { cwd: root, env: environment, encoding: "utf8", windowsHide: true, maxBuffer: 2 * 1024 * 1024 });
18486
+ const result = spawnSync3("git", args2, { cwd: root, env: environment, encoding: "utf8", windowsHide: true, maxBuffer: 2 * 1024 * 1024 });
18322
18487
  if (result.status !== 0) throw new Error("Git " + args2[0] + " failed. Check repository access, branch protection, and local changes.");
18323
18488
  return result.stdout.trim();
18324
18489
  }
@@ -18328,7 +18493,7 @@ function gitEnvironment(repository, token) {
18328
18493
  }
18329
18494
  function validateCloneMerge(source, target) {
18330
18495
  for (const entry of readdirSync2(source, { withFileTypes: true })) {
18331
- const destination = join3(target, entry.name);
18496
+ const destination = join4(target, entry.name);
18332
18497
  let existing;
18333
18498
  try {
18334
18499
  existing = lstatSync2(destination);
@@ -18336,7 +18501,7 @@ function validateCloneMerge(source, target) {
18336
18501
  if (reason.code === "ENOENT") continue;
18337
18502
  throw reason;
18338
18503
  }
18339
- if (entry.isDirectory() && existing.isDirectory() && !existing.isSymbolicLink()) validateCloneMerge(join3(source, entry.name), destination);
18504
+ if (entry.isDirectory() && existing.isDirectory() && !existing.isSymbolicLink()) validateCloneMerge(join4(source, entry.name), destination);
18340
18505
  else throw new Error("Clone conflicts with existing workspace entry: " + destination + ". Existing files are never overwritten; reconcile the conflict or use a new folder.");
18341
18506
  }
18342
18507
  }
@@ -18346,22 +18511,22 @@ async function cloneProject(call2, appId, root = process.cwd()) {
18346
18511
  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.");
18347
18512
  const credential = await call2("/apps/" + applicationGuid(appId) + "/developer/git-credential", { method: "POST" });
18348
18513
  if (credential.repository.toLowerCase() !== status.repository.toLowerCase()) throw new Error("Repository changed. Run connect again.");
18349
- const staging = mkdtempSync(join3(dirname4(resolve3(root)), ".backify-clone-"));
18514
+ const staging = mkdtempSync(join4(dirname4(resolve4(root)), ".backify-clone-"));
18350
18515
  try {
18351
18516
  git(["clone", "--single-branch", "--branch", status.branch, "--", "https://github.com/" + status.repository + ".git", "."], staging, gitEnvironment(status.repository, credential.token));
18352
18517
  validateCloneMerge(staging, root);
18353
- for (const entry of readdirSync2(staging)) cpSync(join3(staging, entry), join3(root, entry), { recursive: true, force: false, errorOnExist: true, dereference: false });
18518
+ for (const entry of readdirSync2(staging)) cpSync(join4(staging, entry), join4(root, entry), { recursive: true, force: false, errorOnExist: true, dereference: false });
18354
18519
  } finally {
18355
- if (dirname4(staging) !== dirname4(resolve3(root)) || !staging.startsWith(join3(dirname4(resolve3(root)), ".backify-clone-"))) throw new Error("Refusing to clean up an unexpected clone staging path.");
18520
+ if (dirname4(staging) !== dirname4(resolve4(root)) || !staging.startsWith(join4(dirname4(resolve4(root)), ".backify-clone-"))) throw new Error("Refusing to clean up an unexpected clone staging path.");
18356
18521
  rmSync(staging, { recursive: true, force: true });
18357
18522
  }
18358
18523
  }
18359
18524
  async function pullProject(call2, appId, root = process.cwd()) {
18360
- if (existsSync4(join3(root, "backify.json")) && applicationGuid(projectApplication(root)) !== applicationGuid(appId)) throw new Error("Local application ID does not match the connected application.");
18525
+ if (existsSync4(join4(root, "backify.json")) && applicationGuid(projectApplication(root)) !== applicationGuid(appId)) throw new Error("Local application ID does not match the connected application.");
18361
18526
  const prefix = "/apps/" + applicationGuid(appId);
18362
18527
  const status = await call2(prefix + "/developer");
18363
18528
  if (!status.repository || !status.branch) throw new Error("Connect the repository and branch in Backify before pulling.");
18364
- if (resolve3(git(["rev-parse", "--show-toplevel"], root)) !== resolve3(root)) throw new Error("Run pull from the connected repository root.");
18529
+ if (resolve4(git(["rev-parse", "--show-toplevel"], root)) !== resolve4(root)) throw new Error("Run pull from the connected repository root.");
18365
18530
  if (repositoryName(git(["remote", "get-url", "origin"], root)) !== status.repository.toLowerCase()) throw new Error("Local origin does not match the repository connected in Backify.");
18366
18531
  if (git(["branch", "--show-current"], root) !== status.branch) throw new Error("Local branch does not match the branch connected in Backify. The CLI never switches branches automatically.");
18367
18532
  git(["check-ref-format", "--branch", status.branch], root);
@@ -18401,7 +18566,7 @@ function attachmentNames(values) {
18401
18566
  }))];
18402
18567
  }
18403
18568
  function localReport(runChecks, root = process.cwd()) {
18404
- const pkg = JSON.parse(readFileSync3(join3(root, "package.json"), "utf8"));
18569
+ const pkg = JSON.parse(readFileSync4(join4(root, "package.json"), "utf8"));
18405
18570
  const dependencies = { ...pkg.devDependencies, ...pkg.dependencies };
18406
18571
  const framework = ["next", "vite", "astro", "@sveltejs/kit", "nuxt", "react", "express"].find((name2) => dependencies[name2]) ?? "unknown";
18407
18572
  const setup = doctor(root);
@@ -18409,7 +18574,7 @@ function localReport(runChecks, root = process.cwd()) {
18409
18574
  const manager = detectPackageManager(root);
18410
18575
  for (const name2 of ["typecheck", "lint", "test", "build"]) {
18411
18576
  if (!pkg.scripts?.[name2]) continue;
18412
- const result = runChecks ? spawnSync2(manager, ["run", name2], { cwd: root, stdio: ["ignore", "inherit", "inherit"], env: { ...process.env, CI: "true" }, shell: process.platform === "win32", windowsHide: true, timeout: 10 * 6e4 }) : void 0;
18577
+ const result = runChecks ? spawnSync3(manager, ["run", name2], { cwd: root, stdio: ["ignore", "inherit", "inherit"], env: { ...process.env, CI: "true" }, shell: process.platform === "win32", windowsHide: true, timeout: 10 * 6e4 }) : void 0;
18413
18578
  checks.push({ name: name2, status: result ? result.status === 0 ? "passed" : "failed" : "not-run" });
18414
18579
  }
18415
18580
  let branch = null, commitSha = null, dirty = true;
@@ -18419,8 +18584,8 @@ function localReport(runChecks, root = process.cwd()) {
18419
18584
  dirty = Boolean(git(["status", "--porcelain"], root));
18420
18585
  } catch {
18421
18586
  }
18422
- const outputDirectory = ["dist", "build", "out", "."].find((directory2) => existsSync4(join3(root, directory2, "index.html"))) ?? null;
18423
- return { framework, sdkVersion: dependencies["@backifydev/sdk"] ?? null, branch, commitSha, dirty, buildCommand: pkg.scripts?.build ? manager + " run build" : null, outputDirectory, hasDockerfile: existsSync4(join3(root, "Dockerfile")), checks };
18587
+ const outputDirectory = ["dist", "build", "out", "."].find((directory2) => existsSync4(join4(root, directory2, "index.html"))) ?? null;
18588
+ return { framework, sdkVersion: dependencies["@backifydev/sdk"] ?? null, branch, commitSha, dirty, buildCommand: pkg.scripts?.build ? manager + " run build" : null, outputDirectory, hasDockerfile: existsSync4(join4(root, "Dockerfile")), checks };
18424
18589
  }
18425
18590
  function matchesSource(release2, commit) {
18426
18591
  return release2?.commitSha === commit || release2?.sourceCommitSha === commit;
@@ -18442,7 +18607,7 @@ function pushSource(appId, commit, branch, destination, root, environment) {
18442
18607
  }
18443
18608
  async function waitForPreview(call2, prefix, commit, options = {}) {
18444
18609
  const deadline = Date.now() + (options.timeoutMs ?? 20 * 6e4);
18445
- const sleep = options.sleep ?? ((delay) => new Promise((resolve23) => setTimeout(resolve23, delay)));
18610
+ const sleep = options.sleep ?? ((delay) => new Promise((resolve24) => setTimeout(resolve24, delay)));
18446
18611
  do {
18447
18612
  const deployments = await call2(prefix + "/deployments");
18448
18613
  const matching = deployments.find((release2) => release2.kind === "preview" && matchesSource(release2, commit) && !options.previousDeploymentIds?.includes(release2.id));
@@ -18462,7 +18627,7 @@ async function ship(call2, appId, options = {}) {
18462
18627
  if (!doctor(root).valid) throw new Error("Run backify doctor and fix project setup before shipping.");
18463
18628
  if (applicationGuid(projectApplication(root)) !== applicationGuid(appId)) throw new Error("Local application ID does not match the application being shipped.");
18464
18629
  const actualRoot = git(["rev-parse", "--show-toplevel"], root);
18465
- if (resolve3(actualRoot).toLowerCase() !== resolve3(root).toLowerCase()) throw new Error("Shipping currently requires the application at the repository root.");
18630
+ if (resolve4(actualRoot).toLowerCase() !== resolve4(root).toLowerCase()) throw new Error("Shipping currently requires the application at the repository root.");
18466
18631
  const origin = git(["remote", "get-url", "origin"], root);
18467
18632
  const pushOrigin = git(["remote", "get-url", "--push", "origin"], root);
18468
18633
  if (repositoryName(origin) !== status.repository.toLowerCase() || repositoryName(pushOrigin) !== status.repository.toLowerCase()) throw new Error("Local repository does not match this Backify application.");
@@ -18512,7 +18677,7 @@ async function publishPreview(call2, prefix, overview, options = {}) {
18512
18677
  if (releases.live?.previewDeploymentId !== preview.id || releases.live.status !== "succeeded" || releases.live.healthResult !== "healthy") throw new Error("Production did not activate this healthy release. Run backify status.");
18513
18678
  return { status: "live", url: releases.live.url };
18514
18679
  }
18515
- await new Promise((resolve23) => setTimeout(resolve23, 4e3));
18680
+ await new Promise((resolve24) => setTimeout(resolve24, 4e3));
18516
18681
  } while (Date.now() < deadline);
18517
18682
  throw new Error("Publication is still pending. Run backify status; deployment success has not been verified.");
18518
18683
  }
@@ -18525,12 +18690,12 @@ async function browserAuthenticate(options) {
18525
18690
  };
18526
18691
  let rejectSession = () => {
18527
18692
  };
18528
- const completed = new Promise((resolve23, reject) => {
18529
- resolveSession = resolve23;
18693
+ const completed = new Promise((resolve24, reject) => {
18694
+ resolveSession = resolve24;
18530
18695
  rejectSession = reject;
18531
18696
  });
18532
18697
  let accepted = false;
18533
- const server = createServer((request, response) => {
18698
+ const server = createServer2((request, response) => {
18534
18699
  if (request.headers.origin !== auth.origin) {
18535
18700
  response.writeHead(403);
18536
18701
  response.end();
@@ -18630,11 +18795,11 @@ function reconnectingApiClient(session, reconnect, transport = fetch) {
18630
18795
  }
18631
18796
 
18632
18797
  // src/local-runtime.ts
18633
- import { createHash as createHash2, randomUUID as randomUUID2 } from "node:crypto";
18634
- import { chmodSync, existsSync as existsSync5, lstatSync as lstatSync3, mkdirSync as mkdirSync3, readFileSync as readFileSync4, readdirSync as readdirSync3, writeFileSync as writeFileSync5 } from "node:fs";
18635
- import { dirname as dirname5, join as join4, resolve as resolve4, sep } from "node:path";
18798
+ import { createHash as createHash2, randomUUID as randomUUID3 } from "node:crypto";
18799
+ import { chmodSync, existsSync as existsSync5, lstatSync as lstatSync3, mkdirSync as mkdirSync3, readFileSync as readFileSync5, readdirSync as readdirSync3, writeFileSync as writeFileSync6 } from "node:fs";
18800
+ import { dirname as dirname5, join as join5, resolve as resolve5, sep } from "node:path";
18636
18801
  import { homedir } from "node:os";
18637
- import { spawnSync as spawnSync3 } from "node:child_process";
18802
+ import { spawnSync as spawnSync4 } from "node:child_process";
18638
18803
 
18639
18804
  // src/local-state.ts
18640
18805
  import { renameSync as renameSync2 } from "node:fs";
@@ -18663,8 +18828,8 @@ function runtimeIdentifier(platform2 = process.platform, architecture = process.
18663
18828
  return system + "-" + architecture;
18664
18829
  }
18665
18830
  function checkedPath(root, filename2) {
18666
- const target = resolve4(root, filename2);
18667
- if (target !== resolve4(root) && !target.startsWith(resolve4(root) + sep)) throw new Error("Runtime path escapes its installation");
18831
+ const target = resolve5(root, filename2);
18832
+ if (target !== resolve5(root) && !target.startsWith(resolve5(root) + sep)) throw new Error("Runtime path escapes its installation");
18668
18833
  let current = target;
18669
18834
  while (true) {
18670
18835
  if (existsSync5(current) && lstatSync3(current).isSymbolicLink()) throw new Error("Runtime installation must not follow links");
@@ -18675,25 +18840,25 @@ function checkedPath(root, filename2) {
18675
18840
  }
18676
18841
  function verifyInstallationFiles(root, expected, directory2 = root) {
18677
18842
  for (const entry of readdirSync3(directory2, { withFileTypes: true })) {
18678
- const path = checkedPath(root, join4(directory2, entry.name));
18843
+ const path = checkedPath(root, join5(directory2, entry.name));
18679
18844
  if (entry.isDirectory()) verifyInstallationFiles(root, expected, path);
18680
18845
  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");
18681
18846
  }
18682
18847
  }
18683
- function installedLocalRuntime(base = join4(homedir(), ".backify")) {
18848
+ function installedLocalRuntime(base = join5(homedir(), ".backify")) {
18684
18849
  const pointer = checkedPath(base, "runtime.json");
18685
18850
  if (!existsSync5(pointer)) return void 0;
18686
- const installed = JSON.parse(readFileSync4(pointer, "utf8"));
18851
+ const installed = JSON.parse(readFileSync5(pointer, "utf8"));
18687
18852
  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");
18688
- const root = checkedPath(base, join4("runtimes", installed.version, installed.rid));
18853
+ const root = checkedPath(base, join5("runtimes", installed.version, installed.rid));
18689
18854
  verifyInstallationFiles(root, installed.files);
18690
18855
  for (const [filename2, digest4] of Object.entries(installed.files)) {
18691
18856
  const path = checkedPath(root, filename2);
18692
- if (!/^[a-f0-9]{64}$/.test(digest4) || !lstatSync3(path).isFile() || lstatSync3(path).size > maxArchiveBytes || hash(readFileSync4(path)) !== digest4) throw new Error("Installed runtime bytes changed; reinstall a reviewed version");
18857
+ if (!/^[a-f0-9]{64}$/.test(digest4) || !lstatSync3(path).isFile() || lstatSync3(path).size > maxArchiveBytes || hash(readFileSync5(path)) !== digest4) throw new Error("Installed runtime bytes changed; reinstall a reviewed version");
18693
18858
  }
18694
18859
  const executableName = installed.rid.startsWith("win-") ? "Backify.Hcr.exe" : "Backify.Hcr";
18695
18860
  if (!installed.files["Backify.Hcr.dll"] || !installed.files[executableName]) throw new Error("Runtime archive requires the self-contained HCR executable and DLL");
18696
- return { path: join4(root, "Backify.Hcr.dll"), executable: join4(root, executableName), version: installed.version, rid: installed.rid };
18861
+ return { path: join5(root, "Backify.Hcr.dll"), executable: join5(root, executableName), version: installed.version, rid: installed.rid };
18697
18862
  }
18698
18863
  function installLocalRuntime(archive, options) {
18699
18864
  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");
@@ -18707,28 +18872,28 @@ function installLocalRuntime(archive, options) {
18707
18872
  const rid = runtimeIdentifier();
18708
18873
  const executable = rid.startsWith("win-") ? "Backify.Hcr.exe" : "Backify.Hcr";
18709
18874
  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");
18710
- const base = options.base ?? join4(homedir(), ".backify");
18711
- const parent = checkedPath(base, join4("runtimes", options.version));
18875
+ const base = options.base ?? join5(homedir(), ".backify");
18876
+ const parent = checkedPath(base, join5("runtimes", options.version));
18712
18877
  mkdirSync3(parent, { recursive: true, mode: 448 });
18713
18878
  const destination = checkedPath(parent, rid);
18714
18879
  const receipt = { version: options.version, rid, files: Object.fromEntries(Object.entries(files).map(([name2, bytes]) => [name2, hash(bytes)])) };
18715
18880
  if (!existsSync5(destination)) {
18716
- const staging = checkedPath(parent, ".install-" + randomUUID2());
18881
+ const staging = checkedPath(parent, ".install-" + randomUUID3());
18717
18882
  mkdirSync3(staging, { mode: 448 });
18718
18883
  for (const [name2, bytes] of Object.entries(files)) {
18719
18884
  const filename2 = checkedPath(staging, name2);
18720
18885
  mkdirSync3(dirname5(filename2), { recursive: true, mode: 448 });
18721
- writeFileSync5(filename2, bytes, { flag: "wx", mode: name2 === executable ? 448 : 384 });
18886
+ writeFileSync6(filename2, bytes, { flag: "wx", mode: name2 === executable ? 448 : 384 });
18722
18887
  }
18723
- if (process.platform !== "win32") chmodSync(join4(staging, executable), 448);
18888
+ if (process.platform !== "win32") chmodSync(join5(staging, executable), 448);
18724
18889
  renameLocalFile(staging, destination);
18725
18890
  } else {
18726
18891
  verifyInstallationFiles(destination, receipt.files);
18727
- for (const [name2, digest4] of Object.entries(receipt.files)) if (hash(readFileSync4(checkedPath(destination, name2))) !== digest4) throw new Error("Runtime version already exists with different bytes; never overwrite an installation");
18892
+ for (const [name2, digest4] of Object.entries(receipt.files)) if (hash(readFileSync5(checkedPath(destination, name2))) !== digest4) throw new Error("Runtime version already exists with different bytes; never overwrite an installation");
18728
18893
  }
18729
18894
  const pointer = checkedPath(base, "runtime.json");
18730
- const temporary = checkedPath(base, ".runtime-" + randomUUID2() + ".json");
18731
- writeFileSync5(temporary, JSON.stringify(receipt), { flag: "wx", mode: 384 });
18895
+ const temporary = checkedPath(base, ".runtime-" + randomUUID3() + ".json");
18896
+ writeFileSync6(temporary, JSON.stringify(receipt), { flag: "wx", mode: 384 });
18732
18897
  renameLocalFile(temporary, pointer);
18733
18898
  return installedLocalRuntime(base);
18734
18899
  }
@@ -18756,10 +18921,10 @@ async function downloadLocalRuntime(version) {
18756
18921
  }
18757
18922
  function localPrerequisites() {
18758
18923
  const runtime = installedLocalRuntime();
18759
- const directory2 = process.env.BACKIFY_LOCAL_POSTGRES_BIN ?? (process.platform === "win32" ? join4(process.env.ProgramFiles ?? "C:/Program Files", "PostgreSQL", "17", "bin") : void 0);
18924
+ const directory2 = process.env.BACKIFY_LOCAL_POSTGRES_BIN ?? (process.platform === "win32" ? join5(process.env.ProgramFiles ?? "C:/Program Files", "PostgreSQL", "17", "bin") : void 0);
18760
18925
  const checks = ["initdb", "pg_ctl", "psql"].map((name2) => {
18761
- const executable = directory2 ? join4(directory2, name2 + (process.platform === "win32" ? ".exe" : "")) : name2;
18762
- const result = spawnSync3(executable, ["--version"], { windowsHide: true, timeout: 1e4, encoding: "utf8" });
18926
+ const executable = directory2 ? join5(directory2, name2 + (process.platform === "win32" ? ".exe" : "")) : name2;
18927
+ const result = spawnSync4(executable, ["--version"], { windowsHide: true, timeout: 1e4, encoding: "utf8" });
18763
18928
  return { name: name2, available: result.status === 0 };
18764
18929
  });
18765
18930
  return { rid: runtimeIdentifier(), runtime: runtime ? { installed: true, version: runtime.version } : { installed: false }, postgres: checks, ready: !!runtime && checks.every((check) => check.available) };
@@ -18768,20 +18933,20 @@ function localPrerequisites() {
18768
18933
  // src/workload.ts
18769
18934
  import { build as build2 } from "esbuild";
18770
18935
  import { createHash as createHash14 } from "node:crypto";
18771
- import { existsSync as existsSync12, mkdirSync as mkdirSync7, readFileSync as readFileSync19, realpathSync as realpathSync6, readdirSync as readdirSync6, writeFileSync as writeFileSync11 } from "node:fs";
18772
- import { dirname as dirname13, isAbsolute as isAbsolute14, join as join13, relative as relative8, resolve as resolve18 } from "node:path";
18936
+ import { existsSync as existsSync12, mkdirSync as mkdirSync7, readFileSync as readFileSync20, realpathSync as realpathSync6, readdirSync as readdirSync6, writeFileSync as writeFileSync12 } from "node:fs";
18937
+ import { dirname as dirname13, isAbsolute as isAbsolute14, join as join14, relative as relative8, resolve as resolve19 } from "node:path";
18773
18938
 
18774
18939
  // src/local-development.ts
18775
18940
  import { context as context2 } from "esbuild";
18776
18941
  import { spawn as spawn4 } from "node:child_process";
18777
- import { randomBytes as randomBytes6, randomUUID as randomUUID9, createHash as createHash13 } from "node:crypto";
18778
- import { existsSync as existsSync11, lstatSync as lstatSync15, mkdirSync as mkdirSync6, readFileSync as readFileSync18, realpathSync as realpathSync5, writeFileSync as writeFileSync10, unlinkSync as unlinkSync4 } from "node:fs";
18779
- import { resolve as resolve17, join as join12, relative as relative7, isAbsolute as isAbsolute13, dirname as dirname12 } from "node:path";
18942
+ import { randomBytes as randomBytes6, randomUUID as randomUUID10, createHash as createHash13 } from "node:crypto";
18943
+ import { existsSync as existsSync11, lstatSync as lstatSync15, mkdirSync as mkdirSync6, readFileSync as readFileSync19, realpathSync as realpathSync5, writeFileSync as writeFileSync11, unlinkSync as unlinkSync5 } from "node:fs";
18944
+ import { resolve as resolve18, join as join13, relative as relative7, isAbsolute as isAbsolute13, dirname as dirname12 } from "node:path";
18780
18945
 
18781
18946
  // ../analyzer/dist/index.js
18782
18947
  import ts3 from "typescript";
18783
- import { readFileSync as readFileSync5, readdirSync as readdirSync4, existsSync as existsSync6 } from "node:fs";
18784
- import { join as join5, extname } from "node:path";
18948
+ import { readFileSync as readFileSync6, readdirSync as readdirSync4, existsSync as existsSync6 } from "node:fs";
18949
+ import { join as join6, extname } from "node:path";
18785
18950
 
18786
18951
  // ../analyzer/dist/authentication.js
18787
18952
  import ts from "typescript";
@@ -19198,11 +19363,11 @@ function repositorySources(root) {
19198
19363
  for (const entry of readdirSync4(dir, { withFileTypes: true })) {
19199
19364
  if (entry.name === "node_modules" || entry.name === "dist" || entry.name === ".backify" || entry.name.startsWith(".git"))
19200
19365
  continue;
19201
- const path = join5(dir, entry.name);
19366
+ const path = join6(dir, entry.name);
19202
19367
  if (entry.isDirectory())
19203
19368
  walk(path);
19204
19369
  else if ([".ts", ".tsx", ".js", ".jsx", ".mts", ".mjs"].includes(extname(path)))
19205
- result.push({ path, content: readFileSync5(path, "utf8") });
19370
+ result.push({ path, content: readFileSync6(path, "utf8") });
19206
19371
  }
19207
19372
  };
19208
19373
  if (existsSync6(root))
@@ -19419,8 +19584,8 @@ function createLocalNativeEvents(local, native) {
19419
19584
  // src/local-job-executor.ts
19420
19585
  import { spawn as spawn2 } from "node:child_process";
19421
19586
  import { createHash as createHash10 } from "node:crypto";
19422
- import { lstatSync as lstatSync11, readFileSync as readFileSync12 } from "node:fs";
19423
- import { isAbsolute as isAbsolute8, join as join8, relative as relative3, resolve as resolve11 } from "node:path";
19587
+ import { lstatSync as lstatSync11, readFileSync as readFileSync13 } from "node:fs";
19588
+ import { isAbsolute as isAbsolute8, join as join9, relative as relative3, resolve as resolve12 } from "node:path";
19424
19589
 
19425
19590
  // ../sdk/dist/schedules.js
19426
19591
  var import_cron_parser = __toESM(require_dist2(), 1);
@@ -19631,14 +19796,14 @@ function createApplicationAuthProvider(source, options) {
19631
19796
  }
19632
19797
 
19633
19798
  // ../sdk/dist/application-auth-state.js
19634
- import { createHash as createHash3, randomUUID as randomUUID3 } from "node:crypto";
19635
- import { closeSync, constants, fstatSync, fsyncSync, lstatSync as lstatSync4, openSync, readSync, renameSync as renameSync3, unlinkSync, writeFileSync as writeFileSync6 } from "node:fs";
19636
- import { dirname as dirname6, isAbsolute as isAbsolute2, parse, resolve as resolve5, sep as sep2 } from "node:path";
19799
+ import { createHash as createHash3, randomUUID as randomUUID4 } from "node:crypto";
19800
+ import { closeSync, constants, fstatSync, fsyncSync, lstatSync as lstatSync4, openSync, readSync, renameSync as renameSync3, unlinkSync as unlinkSync2, writeFileSync as writeFileSync7 } from "node:fs";
19801
+ import { dirname as dirname6, isAbsolute as isAbsolute2, parse, resolve as resolve6, sep as sep2 } from "node:path";
19637
19802
  function unavailable2() {
19638
19803
  throw new ApplicationAuthenticationError("application_identity_unavailable");
19639
19804
  }
19640
19805
  function safePath(filename2) {
19641
- if (!isAbsolute2(filename2) || resolve5(filename2) !== filename2 || filename2 === parse(filename2).root)
19806
+ if (!isAbsolute2(filename2) || resolve6(filename2) !== filename2 || filename2 === parse(filename2).root)
19642
19807
  unavailable2();
19643
19808
  if (process.platform === "win32" && filename2.slice(parse(filename2).root.length).split(sep2).some((component) => component.includes(":") || /[. ]$/.test(component) || /^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(component)))
19644
19809
  unavailable2();
@@ -19704,10 +19869,10 @@ function readState(filename2) {
19704
19869
  }
19705
19870
  }
19706
19871
  function persist(filename2, state) {
19707
- const temporary = filename2 + "." + randomUUID3() + ".tmp";
19872
+ const temporary = filename2 + "." + randomUUID4() + ".tmp";
19708
19873
  const descriptor2 = openSync(temporary, "wx", 384);
19709
19874
  try {
19710
- writeFileSync6(descriptor2, JSON.stringify(state));
19875
+ writeFileSync7(descriptor2, JSON.stringify(state));
19711
19876
  fsyncSync(descriptor2);
19712
19877
  } finally {
19713
19878
  closeSync(descriptor2);
@@ -19719,7 +19884,7 @@ function checkpoint(filename2, trust, initialize2) {
19719
19884
  try {
19720
19885
  if (!isAbsolute2(filename2))
19721
19886
  unavailable2();
19722
- filename2 = resolve5(filename2);
19887
+ filename2 = resolve6(filename2);
19723
19888
  safePath(filename2);
19724
19889
  const lock = filename2 + ".lock";
19725
19890
  const next = { version: 1, scope: trust.scope, revision: trust.revision, digest: createHash3("sha256").update(trust.content).digest("hex") };
@@ -19738,7 +19903,7 @@ function checkpoint(filename2, trust, initialize2) {
19738
19903
  }
19739
19904
  const descriptor2 = openSync(lock, "wx", 384);
19740
19905
  try {
19741
- writeFileSync6(descriptor2, "backify-application-auth-state-v1");
19906
+ writeFileSync7(descriptor2, "backify-application-auth-state-v1");
19742
19907
  fsyncSync(descriptor2);
19743
19908
  } finally {
19744
19909
  closeSync(descriptor2);
@@ -19769,7 +19934,7 @@ function checkpoint(filename2, trust, initialize2) {
19769
19934
  }
19770
19935
  } finally {
19771
19936
  if (!writePending) {
19772
- unlinkSync(lock);
19937
+ unlinkSync2(lock);
19773
19938
  syncDirectory(filename2);
19774
19939
  }
19775
19940
  }
@@ -19785,9 +19950,9 @@ function createPersistentApplicationAuthProvider(source, options) {
19785
19950
  }
19786
19951
 
19787
19952
  // ../sdk/dist/application-auth-sync.js
19788
- import { createHash as createHash4, createPublicKey as createPublicKey2, randomUUID as randomUUID4, verify as verify2 } from "node:crypto";
19789
- import { closeSync as closeSync2, constants as constants2, fsyncSync as fsyncSync2, lstatSync as lstatSync5, openSync as openSync2, readFileSync as readFileSync6, renameSync as renameSync4, unlinkSync as unlinkSync2, writeFileSync as writeFileSync7 } from "node:fs";
19790
- import { dirname as dirname7, isAbsolute as isAbsolute3, parse as parse2, resolve as resolve6, sep as sep3 } from "node:path";
19953
+ 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 readFileSync7, renameSync as renameSync4, unlinkSync as unlinkSync3, writeFileSync as writeFileSync8 } from "node:fs";
19955
+ import { dirname as dirname7, isAbsolute as isAbsolute3, parse as parse2, resolve as resolve7, sep as sep3 } from "node:path";
19791
19956
  var maximumBytes = 512 * 1024;
19792
19957
  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";
19793
19958
  function unavailable3() {
@@ -19796,7 +19961,7 @@ function unavailable3() {
19796
19961
  function filename(value) {
19797
19962
  if (typeof value !== "string" || /[\x00-\x1f\x7f]/.test(value) || !isAbsolute3(value))
19798
19963
  unavailable3();
19799
- const result = resolve6(value);
19964
+ const result = resolve7(value);
19800
19965
  if (result === parse2(result).root || process.platform === "win32" && result.slice(parse2(result).root.length).split(sep3).some((component) => component.includes(":") || /[. ]$/.test(component) || /^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(component)))
19801
19966
  unavailable3();
19802
19967
  return result;
@@ -19858,7 +20023,7 @@ function currentPublicFile(filename2) {
19858
20023
  const metadata = lstatSync5(filename2);
19859
20024
  if (!metadata.isFile() || metadata.isSymbolicLink() || metadata.nlink !== 1 || metadata.size > 131072 || process.platform !== "win32" && (metadata.uid !== process.getuid?.() || (metadata.mode & 18) !== 0))
19860
20025
  unavailable3();
19861
- const bytes = readFileSync6(filename2);
20026
+ const bytes = readFileSync7(filename2);
19862
20027
  if (bytes.length > 131072)
19863
20028
  unavailable3();
19864
20029
  return new TextDecoder("utf8", { fatal: true }).decode(bytes);
@@ -19925,7 +20090,7 @@ async function synchronizeApplicationAuthTrustWithDigest(options) {
19925
20090
  const lock = prepared.stateFile + ".delivery.lock";
19926
20091
  const descriptor2 = openSync2(lock, "wx", 384);
19927
20092
  try {
19928
- writeFileSync7(descriptor2, "backify-application-auth-delivery-v1");
20093
+ writeFileSync8(descriptor2, "backify-application-auth-delivery-v1");
19929
20094
  fsyncSync2(descriptor2);
19930
20095
  } finally {
19931
20096
  closeSync2(descriptor2);
@@ -19940,10 +20105,10 @@ async function synchronizeApplicationAuthTrustWithDigest(options) {
19940
20105
  if (current === content)
19941
20106
  return { status: "unchanged", revision: trust.revision, validUntil: trust.validUntil, trustDigest };
19942
20107
  writePending = true;
19943
- const temporary = prepared.trustFile + "." + randomUUID4() + ".tmp";
20108
+ const temporary = prepared.trustFile + "." + randomUUID5() + ".tmp";
19944
20109
  const output = openSync2(temporary, "wx", process.platform === "win32" ? 384 : 292);
19945
20110
  try {
19946
- writeFileSync7(output, content);
20111
+ writeFileSync8(output, content);
19947
20112
  fsyncSync2(output);
19948
20113
  } finally {
19949
20114
  closeSync2(output);
@@ -19954,7 +20119,7 @@ async function synchronizeApplicationAuthTrustWithDigest(options) {
19954
20119
  return { status: "updated", revision: trust.revision, validUntil: trust.validUntil, trustDigest };
19955
20120
  } finally {
19956
20121
  if (!writePending) {
19957
- unlinkSync2(lock);
20122
+ unlinkSync3(lock);
19958
20123
  syncDirectory2(lock);
19959
20124
  }
19960
20125
  }
@@ -20525,16 +20690,16 @@ function jsonValue(value) {
20525
20690
 
20526
20691
  // src/local-services.ts
20527
20692
  import { spawn, execFile } from "node:child_process";
20528
- import { createHash as createHash6, generateKeyPairSync, randomBytes as randomBytes3, randomUUID as randomUUID6, sign } from "node:crypto";
20529
- import { createServer as createServer2 } from "node:net";
20530
- import { existsSync as existsSync8, lstatSync as lstatSync7, mkdirSync as mkdirSync4, readFileSync as readFileSync8, readdirSync as readdirSync5, realpathSync, unlinkSync as unlinkSync3, writeFileSync as writeFileSync8 } from "node:fs";
20531
- import { basename as basename2, dirname as dirname9, isAbsolute as isAbsolute4, join as join7, relative, resolve as resolve7 } from "node:path";
20693
+ import { createHash as createHash6, generateKeyPairSync, randomBytes as randomBytes3, randomUUID as randomUUID7, sign } from "node:crypto";
20694
+ import { createServer as createServer3 } from "node:net";
20695
+ import { existsSync as existsSync8, lstatSync as lstatSync7, mkdirSync as mkdirSync4, readFileSync as readFileSync9, readdirSync as readdirSync5, realpathSync, unlinkSync as unlinkSync4, writeFileSync as writeFileSync9 } from "node:fs";
20696
+ import { basename as basename2, dirname as dirname9, isAbsolute as isAbsolute4, join as join8, relative, resolve as resolve8 } from "node:path";
20532
20697
 
20533
20698
  // src/local-job-services.ts
20534
- import { createHash as createHash5, randomBytes as randomBytes2, randomUUID as randomUUID5 } from "node:crypto";
20535
- import { existsSync as existsSync7, lstatSync as lstatSync6, readFileSync as readFileSync7 } from "node:fs";
20699
+ import { createHash as createHash5, randomBytes as randomBytes2, randomUUID as randomUUID6 } from "node:crypto";
20700
+ import { existsSync as existsSync7, lstatSync as lstatSync6, readFileSync as readFileSync8 } from "node:fs";
20536
20701
  import { isIP } from "node:net";
20537
- import { dirname as dirname8, join as join6 } from "node:path";
20702
+ import { dirname as dirname8, join as join7 } from "node:path";
20538
20703
  function fields3(value, names) {
20539
20704
  return !!value && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === names.length && names.every((name2) => Object.hasOwn(value, name2));
20540
20705
  }
@@ -20585,9 +20750,9 @@ function validLocalJobState(value, otherIds) {
20585
20750
  function prepareLocalJobService(hcrPath, retained, artifacts, applyMigrations) {
20586
20751
  const requested = validateLocalJobArtifacts(artifacts);
20587
20752
  const readSchema = (name2) => {
20588
- const filename2 = join6(dirname8(hcrPath), "sql", name2), info = existsSync7(filename2) ? lstatSync6(filename2) : void 0;
20753
+ const filename2 = join7(dirname8(hcrPath), "sql", name2), info = existsSync7(filename2) ? lstatSync6(filename2) : void 0;
20589
20754
  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");
20590
- return readFileSync7(filename2, "utf8");
20755
+ return readFileSync8(filename2, "utf8");
20591
20756
  };
20592
20757
  const base = readSchema("jobs-v1.sql"), producer = readSchema("jobs-producer-v1.sql");
20593
20758
  const schemaDigests = { base: createHash5("sha256").update(base).digest("hex"), producer: createHash5("sha256").update(producer).digest("hex") };
@@ -20599,15 +20764,15 @@ function prepareLocalJobService(hcrPath, retained, artifacts, applyMigrations) {
20599
20764
  if (previous && JSON.stringify(previous) !== JSON.stringify(artifact)) throw new Error("Retained local job artifact metadata cannot change; preserve the original pins and policies");
20600
20765
  if (!previous) retainedArtifacts.push(artifact);
20601
20766
  }
20602
- const state = { ...retained ?? { id: randomUUID5(), password: randomBytes2(32).toString("hex"), initialized: false }, schemaDigests, artifacts: validateLocalJobArtifacts(retainedArtifacts) };
20767
+ const state = { ...retained ?? { id: randomUUID6(), password: randomBytes2(32).toString("hex"), initialized: false }, schemaDigests, artifacts: validateLocalJobArtifacts(retainedArtifacts) };
20603
20768
  return { state, base, producer };
20604
20769
  }
20605
20770
 
20606
20771
  // src/local-services.ts
20607
20772
  function writePrivate(filename2, value) {
20608
20773
  if (isLink(filename2)) throw new Error("Local service files must not be symbolic links");
20609
- const temporary = filename2 + "." + randomUUID6() + ".tmp";
20610
- writeFileSync8(temporary, value, { flag: "wx", mode: 384 });
20774
+ const temporary = filename2 + "." + randomUUID7() + ".tmp";
20775
+ writeFileSync9(temporary, value, { flag: "wx", mode: 384 });
20611
20776
  renameLocalFile(temporary, filename2);
20612
20777
  }
20613
20778
  function isLink(filename2) {
@@ -20620,7 +20785,7 @@ function isLink(filename2) {
20620
20785
  }
20621
20786
  function assertLocalStatePath(root, filename2) {
20622
20787
  const base = realpathSync(root);
20623
- for (let current = resolve7(filename2); current !== base; current = resolve7(current, "..")) {
20788
+ for (let current = resolve8(filename2); current !== base; current = resolve8(current, "..")) {
20624
20789
  const part = relative(base, current);
20625
20790
  if (part === ".." || part.startsWith(".." + (process.platform === "win32" ? "\\" : "/")) || isAbsolute4(part)) throw new Error("Local service state must stay inside the repository");
20626
20791
  if (isLink(current)) throw new Error("Local service paths must not contain links");
@@ -20633,22 +20798,22 @@ function stateValid(value) {
20633
20798
  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);
20634
20799
  }
20635
20800
  function acquireLocalLease(root, relativePath2 = ".backify/dev/development.lock") {
20636
- const filename2 = join7(root, relativePath2);
20801
+ const filename2 = join8(root, relativePath2);
20637
20802
  assertLocalStatePath(root, filename2);
20638
- mkdirSync4(resolve7(filename2, ".."), { recursive: true, mode: 448 });
20639
- const owner = JSON.stringify({ version: 1, pid: process.pid, id: randomUUID6() });
20803
+ mkdirSync4(resolve8(filename2, ".."), { recursive: true, mode: 448 });
20804
+ const owner = JSON.stringify({ version: 1, pid: process.pid, id: randomUUID7() });
20640
20805
  try {
20641
- writeFileSync8(filename2, owner, { flag: "wx", mode: 384 });
20806
+ writeFileSync9(filename2, owner, { flag: "wx", mode: 384 });
20642
20807
  } catch {
20643
20808
  throw new Error("Local development already owns this repository, or a stale lifecycle lock requires explicit recovery");
20644
20809
  }
20645
20810
  return () => {
20646
- if (existsSync8(filename2) && readFileSync8(filename2, "utf8") === owner) unlinkSync3(filename2);
20811
+ if (existsSync8(filename2) && readFileSync9(filename2, "utf8") === owner) unlinkSync4(filename2);
20647
20812
  };
20648
20813
  }
20649
20814
  async function allocateLocalPort(requested) {
20650
20815
  if (requested !== void 0 && (!Number.isInteger(requested) || requested < 0 || requested > 65535)) throw new Error("Local service ports must be 0-65535");
20651
- const server = createServer2();
20816
+ const server = createServer3();
20652
20817
  return new Promise((resolvePort, reject) => {
20653
20818
  server.once("error", reject);
20654
20819
  server.listen(requested ?? 0, "127.0.0.1", () => {
@@ -20686,13 +20851,13 @@ function command(executable, args2, options = {}) {
20686
20851
  });
20687
20852
  }
20688
20853
  function postgresExecutable(name2, bin) {
20689
- const directory2 = bin ?? process.env.BACKIFY_LOCAL_POSTGRES_BIN ?? (process.platform === "win32" ? join7(process.env.ProgramFiles ?? "C:/Program Files", "PostgreSQL", "17", "bin") : void 0);
20690
- return directory2 ? join7(directory2, name2 + (process.platform === "win32" ? ".exe" : "")) : name2;
20854
+ const directory2 = bin ?? process.env.BACKIFY_LOCAL_POSTGRES_BIN ?? (process.platform === "win32" ? join8(process.env.ProgramFiles ?? "C:/Program Files", "PostgreSQL", "17", "bin") : void 0);
20855
+ return directory2 ? join8(directory2, name2 + (process.platform === "win32" ? ".exe" : "")) : name2;
20691
20856
  }
20692
20857
  function localMigrationFiles(root, directory2) {
20693
20858
  if (directory2 === void 0) return [];
20694
20859
  if (typeof directory2 !== "string") throw new Error("Local migrations require a repository-relative directory");
20695
- const folder = resolve7(root, directory2);
20860
+ const folder = resolve8(root, directory2);
20696
20861
  assertLocalStatePath(root, folder);
20697
20862
  if (!existsSync8(folder)) throw new Error("Declared migration directory does not exist");
20698
20863
  const entries = readdirSync5(folder);
@@ -20701,11 +20866,11 @@ function localMigrationFiles(root, directory2) {
20701
20866
  let total = 0;
20702
20867
  return filenames.map((name2) => {
20703
20868
  if (!/^[A-Za-z0-9_.-]{1,150}\.sql$/.test(name2)) throw new Error("Invalid migration filename");
20704
- const filename2 = join7(folder, name2);
20869
+ const filename2 = join8(folder, name2);
20705
20870
  assertLocalStatePath(root, filename2);
20706
20871
  const info = lstatSync7(filename2);
20707
20872
  if (!info.isFile() || info.size > 1024 * 1024 || (total += info.size) > 4 * 1024 * 1024) throw new Error("Migration SQL exceeds supported limits");
20708
- const sql = readFileSync8(filename2, "utf8");
20873
+ const sql = readFileSync9(filename2, "utf8");
20709
20874
  if (!sql.trim()) throw new Error("Migration SQL must not be empty");
20710
20875
  validateLocalMigrationSql(sql);
20711
20876
  return { name: name2, digest: createHash6("sha256").update(sql).digest("hex"), sql };
@@ -20782,19 +20947,19 @@ async function startLocalServices(root, manifest, options = {}) {
20782
20947
  const reviewedScope = options.jobIdentityScope;
20783
20948
  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");
20784
20949
  const installed = options.hcrPath || process.env.BACKIFY_LOCAL_HCR_PATH ? void 0 : installedLocalRuntime();
20785
- const hcrPath = resolve7(options.hcrPath ?? process.env.BACKIFY_LOCAL_HCR_PATH ?? installed?.path ?? join7(root, "apps/hcr/bin/Debug/net9.0/Backify.Hcr.dll"));
20950
+ const hcrPath = resolve8(options.hcrPath ?? process.env.BACKIFY_LOCAL_HCR_PATH ?? installed?.path ?? join8(root, "apps/hcr/bin/Debug/net9.0/Backify.Hcr.dll"));
20786
20951
  if (!existsSync8(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");
20787
- const directory2 = join7(root, ".backify", "dev", "services");
20952
+ const directory2 = join8(root, ".backify", "dev", "services");
20788
20953
  assertLocalStatePath(root, directory2);
20789
20954
  mkdirSync4(directory2, { recursive: true, mode: 448 });
20790
20955
  assertLocalStatePath(root, directory2);
20791
- const statePath = join7(directory2, "host.json");
20956
+ const statePath = join8(directory2, "host.json");
20792
20957
  assertLocalStatePath(root, statePath);
20793
20958
  let existing;
20794
20959
  if (existsSync8(statePath)) {
20795
20960
  if (lstatSync7(statePath).size > 16384) throw new Error("Local ownership state exceeds supported limits");
20796
20961
  try {
20797
- existing = JSON.parse(readFileSync8(statePath, "utf8"));
20962
+ existing = JSON.parse(readFileSync9(statePath, "utf8"));
20798
20963
  } catch {
20799
20964
  throw new Error("Invalid local service ownership state; preserve the data and repair explicitly");
20800
20965
  }
@@ -20802,9 +20967,9 @@ async function startLocalServices(root, manifest, options = {}) {
20802
20967
  }
20803
20968
  const state = existing ?? {
20804
20969
  version: 1,
20805
- scope: reviewedScope ? structuredClone(reviewedScope) : { organizationId: randomUUID6(), applicationId: randomUUID6(), environmentId: randomUUID6() },
20806
- databaseId: randomUUID6(),
20807
- storageId: randomUUID6(),
20970
+ scope: reviewedScope ? structuredClone(reviewedScope) : { organizationId: randomUUID7(), applicationId: randomUUID7(), environmentId: randomUUID7() },
20971
+ databaseId: randomUUID7(),
20972
+ storageId: randomUUID7(),
20808
20973
  configurationVersion: 0,
20809
20974
  adminPassword: randomBytes3(32).toString("hex"),
20810
20975
  databasePassword: randomBytes3(32).toString("hex")
@@ -20813,20 +20978,20 @@ async function startLocalServices(root, manifest, options = {}) {
20813
20978
  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");
20814
20979
  let eventSchema;
20815
20980
  if (events) {
20816
- const filename2 = join7(dirname9(hcrPath), "sql", "events-v1.sql");
20981
+ const filename2 = join8(dirname9(hcrPath), "sql", "events-v1.sql");
20817
20982
  if (!existsSync8(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.");
20818
- eventSchema = readFileSync8(filename2, "utf8");
20983
+ eventSchema = readFileSync9(filename2, "utf8");
20819
20984
  const digest4 = createHash6("sha256").update(eventSchema).digest("hex");
20820
20985
  if (state.events && state.events.schemaDigest !== digest4) throw new Error("Native event schema changed; preserve its database and plan an explicit migration.");
20821
20986
  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.");
20822
- state.events ??= { id: randomUUID6(), password: randomBytes3(32).toString("hex"), schemaDigest: digest4, initialized: false };
20987
+ state.events ??= { id: randomUUID7(), password: randomBytes3(32).toString("hex"), schemaDigest: digest4, initialized: false };
20823
20988
  }
20824
20989
  const jobSchema = jobs ? prepareLocalJobService(hcrPath, state.jobs, options.jobArtifacts, options.applyMigrations) : void 0;
20825
20990
  if (jobSchema) state.jobs = jobSchema.state;
20826
20991
  const storageNames = manifest.capabilities.storage?.buckets === void 0 ? ["default"] : manifest.capabilities.storage.buckets.map((bucket) => bucket.name);
20827
20992
  state.storageBindings ??= { default: state.storageId };
20828
20993
  if (typeof state.storageBindings !== "object" || state.storageBindings === null || Array.isArray(state.storageBindings) || Object.entries(state.storageBindings).some(([name2, identifier2]) => !/^[A-Za-z0-9_-]{1,100}$/.test(name2) || typeof identifier2 !== "string" || !/^[0-9a-f-]{36}$/i.test(identifier2))) throw new Error("Invalid local storage binding ownership state");
20829
- for (const name2 of storageNames) state.storageBindings[name2] ??= randomUUID6();
20994
+ for (const name2 of storageNames) state.storageBindings[name2] ??= randomUUID7();
20830
20995
  if (Object.keys(state.storageBindings).length > 100) throw new Error("Local storage ownership history exceeds 100 bindings; preserve the data and plan an explicit migration");
20831
20996
  if (Buffer.byteLength(JSON.stringify({ ...state, configurationVersion: Number.MAX_SAFE_INTEGER, retainedDatabasePort: 65535 }), "utf8") > 16384) throw new Error("Local ownership history exceeds supported limits; preserve state and plan an explicit migration");
20832
20997
  const migrations = database ? localMigrationFiles(root, manifest.capabilities.database?.migrations) : [];
@@ -20834,7 +20999,7 @@ async function startLocalServices(root, manifest, options = {}) {
20834
20999
  const databasePort = database || events || jobs ? await allocateLocalPort(options.databasePort) : void 0;
20835
21000
  if (databasePort !== void 0) state.retainedDatabasePort = databasePort;
20836
21001
  if (databasePort === hcrPort) throw new Error("HCR and PostgreSQL require separate ports");
20837
- const cluster = join7(directory2, "postgres");
21002
+ const cluster = join8(directory2, "postgres");
20838
21003
  assertLocalStatePath(root, cluster);
20839
21004
  const release2 = acquireLocalLease(root, ".backify/dev/services/lifecycle.lock");
20840
21005
  let postgresStarted = false;
@@ -20850,7 +21015,7 @@ async function startLocalServices(root, manifest, options = {}) {
20850
21015
  }
20851
21016
  };
20852
21017
  const runtimeUrl = "http://127.0.0.1:" + hcrPort;
20853
- const tokenPath = join7(directory2, "workload-token");
21018
+ const tokenPath = join8(directory2, "workload-token");
20854
21019
  const stop = () => stopping ??= (async () => {
20855
21020
  if (timer) clearInterval(timer);
20856
21021
  if (snapshotTimer) clearInterval(snapshotTimer);
@@ -20869,9 +21034,9 @@ async function startLocalServices(root, manifest, options = {}) {
20869
21034
  }
20870
21035
  notify("hcr", "stopped");
20871
21036
  try {
20872
- if (postgresStarted && existsSync8(join7(cluster, "postmaster.pid"))) await command(postgresExecutable("pg_ctl", options.postgresBin), ["-D", cluster, "-m", "fast", "-w", "stop"]);
21037
+ if (postgresStarted && existsSync8(join8(cluster, "postmaster.pid"))) await command(postgresExecutable("pg_ctl", options.postgresBin), ["-D", cluster, "-m", "fast", "-w", "stop"]);
20873
21038
  if (postgresStarted) notify("postgres", "stopped");
20874
- if (existsSync8(tokenPath)) unlinkSync3(tokenPath);
21039
+ if (existsSync8(tokenPath)) unlinkSync4(tokenPath);
20875
21040
  } finally {
20876
21041
  release2();
20877
21042
  }
@@ -20881,28 +21046,28 @@ async function startLocalServices(root, manifest, options = {}) {
20881
21046
  writePrivate(statePath, JSON.stringify(state));
20882
21047
  if (database || events || jobs) {
20883
21048
  notify("postgres", "starting");
20884
- if (!existsSync8(join7(cluster, "PG_VERSION"))) {
20885
- const passwordPath = join7(directory2, "init-password");
21049
+ if (!existsSync8(join8(cluster, "PG_VERSION"))) {
21050
+ const passwordPath = join8(directory2, "init-password");
20886
21051
  writePrivate(passwordPath, state.adminPassword);
20887
21052
  try {
20888
21053
  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"]);
20889
21054
  } finally {
20890
- if (existsSync8(passwordPath)) unlinkSync3(passwordPath);
21055
+ if (existsSync8(passwordPath)) unlinkSync4(passwordPath);
20891
21056
  }
20892
21057
  }
20893
- if (existsSync8(join7(cluster, "postmaster.pid"))) throw new Error("A retained local PostgreSQL server is still running; stop or recover that exact owned cluster before restarting dev");
21058
+ if (existsSync8(join8(cluster, "postmaster.pid"))) throw new Error("A retained local PostgreSQL server is still running; stop or recover that exact owned cluster before restarting dev");
20894
21059
  postgresStarted = true;
20895
- await command(postgresExecutable("pg_ctl", options.postgresBin), ["-D", cluster, "-l", join7(directory2, "postgres.log"), "-o", "-h 127.0.0.1 -p " + databasePort, "-w", "start"]);
21060
+ await command(postgresExecutable("pg_ctl", options.postgresBin), ["-D", cluster, "-l", join8(directory2, "postgres.log"), "-o", "-h 127.0.0.1 -p " + databasePort, "-w", "start"]);
20896
21061
  notify("postgres", "ready");
20897
21062
  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 } });
20898
21063
  if (database) {
20899
21064
  if ((await sql("SELECT count(*) FROM pg_roles WHERE rolname='backify_local'")).trim() === "0") {
20900
- const filename2 = join7(directory2, "role-" + randomUUID6() + ".sql");
21065
+ const filename2 = join8(directory2, "role-" + randomUUID7() + ".sql");
20901
21066
  writePrivate(filename2, "CREATE ROLE backify_local LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE PASSWORD '" + state.databasePassword + "';");
20902
21067
  try {
20903
21068
  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 } });
20904
21069
  } finally {
20905
- if (existsSync8(filename2)) unlinkSync3(filename2);
21070
+ if (existsSync8(filename2)) unlinkSync4(filename2);
20906
21071
  }
20907
21072
  }
20908
21073
  if ((await sql("SELECT count(*) FROM pg_database WHERE datname='backify_local'")).trim() === "0") await sql("CREATE DATABASE backify_local OWNER backify_local");
@@ -20917,12 +21082,12 @@ async function startLocalServices(root, manifest, options = {}) {
20917
21082
  notify("migrations", "starting");
20918
21083
  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);
20919
21084
  for (const migration of pending) {
20920
- const filename2 = join7(directory2, "apply-" + randomUUID6() + ".sql");
21085
+ const filename2 = join8(directory2, "apply-" + randomUUID7() + ".sql");
20921
21086
  writePrivate(filename2, "BEGIN;\n" + migration.sql + "\n;\nINSERT INTO public.__backify_migrations(name,digest) VALUES ('" + migration.name + "','" + migration.digest + "');\nCOMMIT;\n");
20922
21087
  try {
20923
21088
  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 } });
20924
21089
  } finally {
20925
- if (existsSync8(filename2)) unlinkSync3(filename2);
21090
+ if (existsSync8(filename2)) unlinkSync4(filename2);
20926
21091
  }
20927
21092
  applied.push(migration.name);
20928
21093
  }
@@ -20933,20 +21098,20 @@ async function startLocalServices(root, manifest, options = {}) {
20933
21098
  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 } });
20934
21099
  if (!eventState.initialized) {
20935
21100
  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.");
20936
- const roleFile = join7(directory2, "event-role-" + randomUUID6() + ".sql");
21101
+ const roleFile = join8(directory2, "event-role-" + randomUUID7() + ".sql");
20937
21102
  writePrivate(roleFile, "CREATE ROLE backify_events LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE PASSWORD '" + eventState.password + "';");
20938
21103
  try {
20939
21104
  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 } });
20940
21105
  } finally {
20941
- if (existsSync8(roleFile)) unlinkSync3(roleFile);
21106
+ if (existsSync8(roleFile)) unlinkSync4(roleFile);
20942
21107
  }
20943
21108
  await sql("CREATE DATABASE backify_events OWNER backify_events");
20944
- const schemaFile = join7(directory2, "event-schema-" + randomUUID6() + ".sql");
21109
+ const schemaFile = join8(directory2, "event-schema-" + randomUUID7() + ".sql");
20945
21110
  writePrivate(schemaFile, eventSchema);
20946
21111
  try {
20947
21112
  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 } });
20948
21113
  } finally {
20949
- if (existsSync8(schemaFile)) unlinkSync3(schemaFile);
21114
+ if (existsSync8(schemaFile)) unlinkSync4(schemaFile);
20950
21115
  }
20951
21116
  eventState.initialized = true;
20952
21117
  writePrivate(statePath, JSON.stringify(state));
@@ -20960,21 +21125,21 @@ async function startLocalServices(root, manifest, options = {}) {
20960
21125
  const adminSql = (query, databaseName = "postgres") => jobCommand("backify_admin", state.adminPassword, databaseName, ["-c", query]);
20961
21126
  if (!jobState.initialized) {
20962
21127
  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");
20963
- const roleFile = join7(directory2, "job-role-" + randomUUID6() + ".sql");
21128
+ const roleFile = join8(directory2, "job-role-" + randomUUID7() + ".sql");
20964
21129
  writePrivate(roleFile, "CREATE ROLE backify_jobs LOGIN NOINHERIT NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION NOBYPASSRLS PASSWORD '" + jobState.password + "';");
20965
21130
  try {
20966
21131
  await jobCommand("backify_admin", state.adminPassword, "postgres", ["-f", roleFile]);
20967
21132
  } finally {
20968
- if (existsSync8(roleFile)) unlinkSync3(roleFile);
21133
+ if (existsSync8(roleFile)) unlinkSync4(roleFile);
20969
21134
  }
20970
21135
  await adminSql("CREATE DATABASE backify_jobs OWNER backify_admin");
20971
21136
  for (const schema of [jobSchema.base, jobSchema.producer]) {
20972
- const filename2 = join7(directory2, "job-schema-" + randomUUID6() + ".sql");
21137
+ const filename2 = join8(directory2, "job-schema-" + randomUUID7() + ".sql");
20973
21138
  writePrivate(filename2, schema);
20974
21139
  try {
20975
21140
  await jobCommand("backify_admin", state.adminPassword, "backify_jobs", ["-f", filename2]);
20976
21141
  } finally {
20977
- if (existsSync8(filename2)) unlinkSync3(filename2);
21142
+ if (existsSync8(filename2)) unlinkSync4(filename2);
20978
21143
  }
20979
21144
  }
20980
21145
  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");
@@ -21003,7 +21168,7 @@ async function startLocalServices(root, manifest, options = {}) {
21003
21168
  ...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" }] : [],
21004
21169
  ...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" }] : []
21005
21170
  ];
21006
- const snapshotPath = join7(directory2, "snapshot.json");
21171
+ const snapshotPath = join8(directory2, "snapshot.json");
21007
21172
  const writeSnapshot = () => writePrivate(snapshotPath, JSON.stringify({ schemaVersion: 1, configurationVersion: state.configurationVersion, expiresAt: new Date(Date.now() + 7 * 864e5).toISOString(), bindings }));
21008
21173
  const renewConfiguration = () => {
21009
21174
  if (stopping) throw new Error("Stopped local services cannot renew configuration");
@@ -21013,15 +21178,15 @@ async function startLocalServices(root, manifest, options = {}) {
21013
21178
  writeSnapshot();
21014
21179
  };
21015
21180
  writeSnapshot();
21016
- const settingsPath = join7(directory2, "appsettings.json");
21181
+ const settingsPath = join8(directory2, "appsettings.json");
21017
21182
  writePrivate(settingsPath, JSON.stringify({ Hcr: {
21018
21183
  Authentication: { PublicKeyPem: publicKey.export({ type: "spki", format: "pem" }), Issuer: "backify-local", Audience: "backify-local-hcr" },
21019
21184
  SnapshotPath: snapshotPath,
21020
- SnapshotJournalPath: join7(directory2, "journal.json"),
21185
+ SnapshotJournalPath: join8(directory2, "journal.json"),
21021
21186
  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 } } : {} },
21022
21187
  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 } } : {} },
21023
21188
  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 } } : {} },
21024
- Storage: { Bindings: Object.fromEntries(Object.entries(state.storageBindings).map(([name2, identifier2]) => [identifier2, { Scope: state.scope, ResourceReference: name2, RootPath: join7(directory2, "objects", identifier2) }])) }
21189
+ Storage: { Bindings: Object.fromEntries(Object.entries(state.storageBindings).map(([name2, identifier2]) => [identifier2, { Scope: state.scope, ResourceReference: name2, RootPath: join8(directory2, "objects", identifier2) }])) }
21025
21190
  } }));
21026
21191
  issueToken();
21027
21192
  notify("hcr", "starting");
@@ -21035,7 +21200,7 @@ async function startLocalServices(root, manifest, options = {}) {
21035
21200
  while (true) {
21036
21201
  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");
21037
21202
  try {
21038
- const response = await fetch(runtimeUrl + "/v1/health", { headers: { authorization: "Bearer " + readFileSync8(tokenPath, "utf8") }, signal: AbortSignal.timeout(500), redirect: "error", credentials: "omit", cache: "no-store" });
21203
+ const response = await fetch(runtimeUrl + "/v1/health", { headers: { authorization: "Bearer " + readFileSync9(tokenPath, "utf8") }, signal: AbortSignal.timeout(500), redirect: "error", credentials: "omit", cache: "no-store" });
21039
21204
  if (response.ok) {
21040
21205
  const status = await response.json();
21041
21206
  if (status.status === "ready" && status.configurationVersion === state.configurationVersion) break;
@@ -21044,8 +21209,8 @@ async function startLocalServices(root, manifest, options = {}) {
21044
21209
  }
21045
21210
  await new Promise((resolveDelay) => setTimeout(resolveDelay, 100));
21046
21211
  }
21047
- if (events) await createHcrEventsProvider({ runtimeUrl, token: () => readFileSync8(tokenPath, "utf8") }).inspect();
21048
- if (jobs) await createHcrJobsProvider({ runtimeUrl, token: () => readFileSync8(tokenPath, "utf8") }).inspect();
21212
+ if (events) await createHcrEventsProvider({ runtimeUrl, token: () => readFileSync9(tokenPath, "utf8") }).inspect();
21213
+ if (jobs) await createHcrJobsProvider({ runtimeUrl, token: () => readFileSync9(tokenPath, "utf8") }).inspect();
21049
21214
  timer = setInterval(() => {
21050
21215
  try {
21051
21216
  issueToken();
@@ -21071,24 +21236,24 @@ async function startLocalServices(root, manifest, options = {}) {
21071
21236
 
21072
21237
  // src/local-job-auth.ts
21073
21238
  import { createHash as createHash7 } from "node:crypto";
21074
- import { lstatSync as lstatSync8, readFileSync as readFileSync9 } from "node:fs";
21075
- import { isAbsolute as isAbsolute5, resolve as resolve8 } from "node:path";
21239
+ import { lstatSync as lstatSync8, readFileSync as readFileSync10 } from "node:fs";
21240
+ import { isAbsolute as isAbsolute5, resolve as resolve9 } from "node:path";
21076
21241
  function prepareLocalJobAuth(root, filename2) {
21077
21242
  const read = (path, maximum) => {
21078
21243
  assertLocalStatePath(root, path);
21079
21244
  const metadata = lstatSync8(path);
21080
21245
  if (!metadata.isFile() || metadata.isSymbolicLink() || metadata.nlink !== 1 || metadata.size > maximum) throw new Error();
21081
- const bytes = readFileSync9(path);
21246
+ const bytes = readFileSync10(path);
21082
21247
  if (bytes.length > maximum) throw new Error();
21083
21248
  return bytes;
21084
21249
  };
21085
21250
  try {
21086
21251
  if (!filename2 || isAbsolute5(filename2)) throw new Error();
21087
- const input = JSON.parse(new TextDecoder("utf8", { fatal: true }).decode(read(resolve8(root, filename2), 16384)));
21252
+ const input = JSON.parse(new TextDecoder("utf8", { fatal: true }).decode(read(resolve9(root, filename2), 16384)));
21088
21253
  if (!input || Object.keys(input).sort().join(",") !== "revision,schemaVersion,scope,stateFile,trustDigest,trustFile" || input.schemaVersion !== 1 || !Number.isSafeInteger(input.revision) || input.revision < 1 || typeof input.trustDigest !== "string" || input.trustDigest.length !== 64 || !/^[a-f0-9]{64}$/.test(input.trustDigest)) throw new Error();
21089
21254
  if (!input.scope || Object.keys(input.scope).sort().join(",") !== "applicationId,environmentId,organizationId" || Object.values(input.scope).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();
21090
21255
  if ([input.trustFile, input.stateFile].some((path) => typeof path !== "string" || !path || isAbsolute5(path))) throw new Error();
21091
- const trustFile = resolve8(root, input.trustFile), stateFile = resolve8(root, input.stateFile);
21256
+ const trustFile = resolve9(root, input.trustFile), stateFile = resolve9(root, input.stateFile);
21092
21257
  if (trustFile === stateFile) throw new Error();
21093
21258
  const bytes = read(trustFile, 131072), trust = JSON.parse(new TextDecoder("utf8", { fatal: true }).decode(bytes));
21094
21259
  read(stateFile, 2048);
@@ -21102,24 +21267,24 @@ function prepareLocalJobAuth(root, filename2) {
21102
21267
 
21103
21268
  // src/local-job-trust-renewal.ts
21104
21269
  import { createHash as createHash9 } from "node:crypto";
21105
- import { lstatSync as lstatSync10, readFileSync as readFileSync11 } from "node:fs";
21106
- import { isAbsolute as isAbsolute7, relative as relative2, resolve as resolve10 } from "node:path";
21270
+ import { lstatSync as lstatSync10, readFileSync as readFileSync12 } from "node:fs";
21271
+ import { isAbsolute as isAbsolute7, relative as relative2, resolve as resolve11 } from "node:path";
21107
21272
 
21108
21273
  // src/workload-trust-sync.ts
21109
- import { lstatSync as lstatSync9, readFileSync as readFileSync10 } from "node:fs";
21110
- import { isAbsolute as isAbsolute6, resolve as resolve9 } from "node:path";
21274
+ import { lstatSync as lstatSync9, readFileSync as readFileSync11 } from "node:fs";
21275
+ import { isAbsolute as isAbsolute6, resolve as resolve10 } from "node:path";
21111
21276
  import { createHash as createHash8 } from "node:crypto";
21112
21277
  function prepareWorkloadTrustSynchronization(filename2) {
21113
21278
  try {
21114
21279
  if (!isAbsolute6(filename2)) throw new Error();
21115
21280
  const metadata = lstatSync9(filename2);
21116
21281
  if (!metadata.isFile() || metadata.isSymbolicLink() || metadata.nlink !== 1 || metadata.size > 65536) throw new Error();
21117
- const bytes = readFileSync10(filename2);
21282
+ const bytes = readFileSync11(filename2);
21118
21283
  if (bytes.length > 65536) throw new Error();
21119
21284
  const value = JSON.parse(new TextDecoder("utf8", { fatal: true }).decode(bytes));
21120
21285
  const allowed = ["controlPlaneUrl", "agentId", "expectedScope", "managementIssuer", "managementAudience", "managementPublicKeyPem", "credentialFile", "trustFile", "stateFile", "intervalSeconds"];
21121
21286
  if (!value || typeof value !== "object" || Array.isArray(value) || Object.keys(value).some((name2) => !allowed.includes(name2)) || typeof value.credentialFile !== "string" || !isAbsolute6(value.credentialFile) || typeof value.trustFile !== "string" || !isAbsolute6(value.trustFile) || typeof value.stateFile !== "string" || !isAbsolute6(value.stateFile)) throw new Error();
21122
- const credentialFile = resolve9(value.credentialFile), trustFile = resolve9(value.trustFile), stateFile = resolve9(value.stateFile);
21287
+ const credentialFile = resolve10(value.credentialFile), trustFile = resolve10(value.trustFile), stateFile = resolve10(value.stateFile);
21123
21288
  const comparison = (filename3) => process.platform === "win32" ? filename3.toLowerCase() : filename3;
21124
21289
  if ([trustFile, stateFile, stateFile + ".lock", stateFile + ".delivery.lock"].map(comparison).includes(comparison(credentialFile))) throw new Error();
21125
21290
  const intervalSeconds = value.intervalSeconds ?? 30;
@@ -21127,7 +21292,7 @@ function prepareWorkloadTrustSynchronization(filename2) {
21127
21292
  const credential = () => {
21128
21293
  const metadata2 = lstatSync9(credentialFile);
21129
21294
  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");
21130
- const bytes2 = readFileSync10(credentialFile);
21295
+ const bytes2 = readFileSync11(credentialFile);
21131
21296
  if (bytes2.length > 256) throw new Error("Management credential unavailable");
21132
21297
  return new TextDecoder("utf8", { fatal: true }).decode(bytes2).trim();
21133
21298
  };
@@ -21185,7 +21350,7 @@ async function workloadTrustSynchronization(args2, settings = {}) {
21185
21350
  function prepareLocalJobTrustRenewal(root, filename2, mount) {
21186
21351
  try {
21187
21352
  if (!filename2 || isAbsolute7(filename2)) throw new Error();
21188
- const configurationFile = resolve10(root, filename2);
21353
+ const configurationFile = resolve11(root, filename2);
21189
21354
  assertLocalStatePath(root, configurationFile);
21190
21355
  const configured = prepareWorkloadTrustSynchronization(configurationFile);
21191
21356
  const { credential, ...options } = configured.options;
@@ -21199,9 +21364,9 @@ function prepareLocalJobTrustRenewal(root, filename2, mount) {
21199
21364
  throw new Error("Invalid reviewed native worker trust renewal; preserve trust and state and review explicitly");
21200
21365
  }
21201
21366
  }
21202
- function createLocalJobTrustRenewal(root, mounts, settings = {}, dependencies = { createHash: createHash9, lstatSync: lstatSync10, readFileSync: readFileSync11, isAbsolute: isAbsolute7, relative: relative2, resolve: resolve10, createPersistentApplicationAuthProvider, synchronizeApplicationAuthTrustWithDigest }) {
21203
- const { createHash: createHash16, lstatSync: lstatSync19, readFileSync: readFileSync24, isAbsolute: isAbsolute17, relative: relative11, resolve: resolve23, createPersistentApplicationAuthProvider: createPersistentApplicationAuthProvider2, synchronizeApplicationAuthTrustWithDigest: synchronizeApplicationAuthTrustWithDigest2 } = dependencies;
21204
- const key = (filename2) => process.platform === "win32" ? resolve23(filename2).toLowerCase() : resolve23(filename2);
21367
+ function createLocalJobTrustRenewal(root, mounts, settings = {}, dependencies = { createHash: createHash9, lstatSync: lstatSync10, readFileSync: readFileSync12, isAbsolute: isAbsolute7, relative: relative2, resolve: resolve11, createPersistentApplicationAuthProvider, synchronizeApplicationAuthTrustWithDigest }) {
21368
+ const { createHash: createHash16, lstatSync: lstatSync19, readFileSync: readFileSync25, isAbsolute: isAbsolute17, relative: relative11, resolve: resolve24, createPersistentApplicationAuthProvider: createPersistentApplicationAuthProvider2, synchronizeApplicationAuthTrustWithDigest: synchronizeApplicationAuthTrustWithDigest2 } = dependencies;
21369
+ const key = (filename2) => process.platform === "win32" ? resolve24(filename2).toLowerCase() : resolve24(filename2);
21205
21370
  const groups = [];
21206
21371
  for (const mount of mounts) {
21207
21372
  if (!mount.renewal) continue;
@@ -21218,13 +21383,13 @@ function createLocalJobTrustRenewal(root, mounts, settings = {}, dependencies =
21218
21383
  groups.push({ mount, followers, renewal, nextAt: 0, failures: 0, status: "waiting" });
21219
21384
  }
21220
21385
  const read = (filename2, maximum, privateFile2 = false) => {
21221
- for (let current = resolve23(filename2); current !== root; current = resolve23(current, "..")) {
21386
+ for (let current = resolve24(filename2); current !== root; current = resolve24(current, "..")) {
21222
21387
  const part = relative11(root, current);
21223
21388
  if (part === ".." || part.startsWith("../") || part.startsWith("..\\") || isAbsolute17(part) || lstatSync19(current).isSymbolicLink()) throw new Error();
21224
21389
  }
21225
21390
  const metadata = lstatSync19(filename2);
21226
21391
  if (!metadata.isFile() || metadata.nlink !== 1 || metadata.size > maximum || privateFile2 && process.platform !== "win32" && (metadata.uid !== process.getuid?.() || (metadata.mode & 63) !== 0)) throw new Error();
21227
- const bytes = readFileSync24(filename2);
21392
+ const bytes = readFileSync25(filename2);
21228
21393
  if (bytes.length > maximum) throw new Error();
21229
21394
  return bytes;
21230
21395
  };
@@ -21305,11 +21470,11 @@ function prepareLocalJobWorker(root, directory2, artifacts, manifest, authFile,
21305
21470
  if (trustSyncFile !== void 0 && authFile === void 0) throw new Error("Native worker trust renewal requires explicit reviewed auth mounts");
21306
21471
  const authTrust = authFile === void 0 ? void 0 : prepareLocalJobAuth(root, authFile);
21307
21472
  if (authTrust && trustSyncFile !== void 0) authTrust.renewal = prepareLocalJobTrustRenewal(root, trustSyncFile, authTrust);
21308
- const workerFile = join8(resolve11(root, directory2), "workload.mjs"), metadataFile = join8(resolve11(root, directory2), "artifact.json");
21473
+ const workerFile = join9(resolve12(root, directory2), "workload.mjs"), metadataFile = join9(resolve12(root, directory2), "artifact.json");
21309
21474
  for (const filename2 of [workerFile, metadataFile]) assertLocalStatePath(root, filename2);
21310
21475
  if (!lstatSync11(workerFile).isFile() || lstatSync11(workerFile).size > 16777216 || !lstatSync11(metadataFile).isFile() || lstatSync11(metadataFile).size > 65536) throw new Error("Invalid bounded native worker artifact");
21311
- const metadata = JSON.parse(readFileSync12(metadataFile, "utf8"));
21312
- const bundle = readFileSync12(workerFile);
21476
+ const metadata = JSON.parse(readFileSync13(metadataFile, "utf8"));
21477
+ const bundle = readFileSync13(workerFile);
21313
21478
  const actual = createHash10("sha256").update(bundle).digest("hex");
21314
21479
  const scheduleDiscovery = bundle.subarray(0, 100).toString("utf8").startsWith('var __backifyWorkerProtocols = ["hcr-v1","hcr-schedules-v1"];\n');
21315
21480
  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");
@@ -21320,31 +21485,31 @@ function prepareLocalJobWorker(root, directory2, artifacts, manifest, authFile,
21320
21485
  }
21321
21486
  function readLocalJobArtifacts(root, filename2) {
21322
21487
  if (!filename2 || isAbsolute8(filename2)) throw new Error("Job artifact admission requires a repository-relative reviewed JSON file");
21323
- const path = resolve11(root, filename2);
21488
+ const path = resolve12(root, filename2);
21324
21489
  assertLocalStatePath(root, path);
21325
21490
  if (!lstatSync11(path).isFile() || lstatSync11(path).size > 16384) throw new Error("Reviewed job artifact admission exceeds supported bounds");
21326
- return validateLocalJobArtifacts(JSON.parse(readFileSync12(path, "utf8")));
21491
+ return validateLocalJobArtifacts(JSON.parse(readFileSync13(path, "utf8")));
21327
21492
  }
21328
- function createLocalJobExecutor(options, dependencies = { spawn: spawn2, createHash: createHash10, lstatSync: lstatSync11, readFileSync: readFileSync12, isAbsolute: isAbsolute8, relative: relative3, resolve: resolve11, validateWorkloadJobSchedules, createPersistentApplicationAuthProvider }) {
21329
- const { spawn: spawn6, createHash: createHash16, lstatSync: lstatSync19, readFileSync: readFileSync24, isAbsolute: isAbsolute17, relative: relative11, resolve: resolve23, validateWorkloadJobSchedules: validateWorkloadJobSchedules2, createPersistentApplicationAuthProvider: createPersistentApplicationAuthProvider2 } = dependencies;
21493
+ function createLocalJobExecutor(options, dependencies = { spawn: spawn2, createHash: createHash10, lstatSync: lstatSync11, readFileSync: readFileSync13, isAbsolute: isAbsolute8, relative: relative3, resolve: resolve12, validateWorkloadJobSchedules, createPersistentApplicationAuthProvider }) {
21494
+ const { spawn: spawn6, createHash: createHash16, lstatSync: lstatSync19, readFileSync: readFileSync25, isAbsolute: isAbsolute17, relative: relative11, resolve: resolve24, validateWorkloadJobSchedules: validateWorkloadJobSchedules2, createPersistentApplicationAuthProvider: createPersistentApplicationAuthProvider2 } = dependencies;
21330
21495
  const assertReady = () => {
21331
- for (let current = resolve23(options.workerFile); current !== options.root; current = resolve23(current, "..")) {
21496
+ for (let current = resolve24(options.workerFile); current !== options.root; current = resolve24(current, "..")) {
21332
21497
  const part = relative11(options.root, current);
21333
21498
  if (part === ".." || part.startsWith("../") || part.startsWith("..\\") || isAbsolute17(part) || lstatSync19(current).isSymbolicLink()) throw new Error("Native worker paths or pins changed");
21334
21499
  }
21335
- if (!lstatSync19(options.workerFile).isFile() || lstatSync19(options.workerFile).size > 16777216 || createHash16("sha256").update(readFileSync24(options.workerFile)).digest("hex") !== options.artifact.artifactVersion) throw new Error("Native worker paths or pins changed");
21500
+ if (!lstatSync19(options.workerFile).isFile() || lstatSync19(options.workerFile).size > 16777216 || createHash16("sha256").update(readFileSync25(options.workerFile)).digest("hex") !== options.artifact.artifactVersion) throw new Error("Native worker paths or pins changed");
21336
21501
  if (options.authTrust) {
21337
21502
  try {
21338
21503
  const mount = options.authTrust;
21339
21504
  for (const path of [mount.trustFile, mount.stateFile]) {
21340
- for (let current = resolve23(path); current !== options.root; current = resolve23(current, "..")) {
21505
+ for (let current = resolve24(path); current !== options.root; current = resolve24(current, "..")) {
21341
21506
  const part = relative11(options.root, current);
21342
21507
  if (part === ".." || part.startsWith("../") || part.startsWith("..\\") || isAbsolute17(part) || lstatSync19(current).isSymbolicLink()) throw new Error();
21343
21508
  }
21344
21509
  const metadata = lstatSync19(path);
21345
21510
  if (!metadata.isFile() || metadata.nlink !== 1 || metadata.size > (path === mount.trustFile ? 131072 : 2048)) throw new Error();
21346
21511
  }
21347
- const bytes = readFileSync24(mount.trustFile);
21512
+ const bytes = readFileSync25(mount.trustFile);
21348
21513
  if (bytes.length > 131072 || createHash16("sha256").update(bytes).digest("hex") !== mount.trustDigest) throw new Error();
21349
21514
  const trust = JSON.parse(new TextDecoder("utf8", { fatal: true }).decode(bytes));
21350
21515
  if (trust.revision !== mount.revision) throw new Error();
@@ -21718,9 +21883,9 @@ process.on("SIGTERM", stop); process.on("SIGINT", stop); process.once("disconnec
21718
21883
 
21719
21884
  // src/local-frontend.ts
21720
21885
  import { spawn as spawn3 } from "node:child_process";
21721
- import { readFileSync as readFileSync14, realpathSync as realpathSync3, existsSync as existsSync9, statSync } from "node:fs";
21886
+ import { readFileSync as readFileSync15, realpathSync as realpathSync3, existsSync as existsSync9, statSync } from "node:fs";
21722
21887
  import { createRequire as createRequire3 } from "node:module";
21723
- import { dirname as dirname10, isAbsolute as isAbsolute10, join as join10, relative as relative5, resolve as resolve13 } from "node:path";
21888
+ import { dirname as dirname10, isAbsolute as isAbsolute10, join as join11, relative as relative5, resolve as resolve14 } from "node:path";
21724
21889
  import { pathToFileURL } from "node:url";
21725
21890
 
21726
21891
  // src/local-frontend-guard.ts
@@ -21787,21 +21952,21 @@ await server.listen();
21787
21952
  `;
21788
21953
 
21789
21954
  // src/local-static-frontend.ts
21790
- import { createServer as createServer3 } from "node:http";
21791
- import { lstatSync as lstatSync12, readFileSync as readFileSync13, realpathSync as realpathSync2, watch } from "node:fs";
21792
- import { extname as extname2, isAbsolute as isAbsolute9, join as join9, relative as relative4, resolve as resolve12, sep as sep4 } from "node:path";
21955
+ import { createServer as createServer4 } from "node:http";
21956
+ import { lstatSync as lstatSync12, readFileSync as readFileSync14, realpathSync as realpathSync2, watch } from "node:fs";
21957
+ import { extname as extname2, isAbsolute as isAbsolute9, join as join10, relative as relative4, resolve as resolve13, sep as sep4 } from "node:path";
21793
21958
  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" };
21794
21959
  var publicParts = (parts) => parts.every((part) => part.length > 0 && !part.startsWith(".") && !part.includes(":") && !part.includes("\\") && !part.includes("\0") && !["node_modules", "__backify"].includes(part.toLowerCase()));
21795
21960
  function publicFile(directory2, pathname) {
21796
21961
  const parts = pathname.split("/").slice(1);
21797
21962
  if (parts.at(-1) === "") parts[parts.length - 1] = "index.html";
21798
21963
  if (!publicParts(parts)) throw new Error("refused");
21799
- const filename2 = resolve12(directory2, ...parts), part = relative4(directory2, filename2);
21964
+ const filename2 = resolve13(directory2, ...parts), part = relative4(directory2, filename2);
21800
21965
  if (part === ".." || part.startsWith(".." + sep4) || isAbsolute9(part) || !contentTypes[extname2(filename2).toLowerCase()]) throw new Error("refused");
21801
21966
  let current = directory2;
21802
21967
  if (lstatSync12(current).isSymbolicLink() || realpathSync2(current) !== directory2) throw new Error("refused");
21803
21968
  for (const segment of parts) {
21804
- current = join9(current, segment);
21969
+ current = join10(current, segment);
21805
21970
  if (lstatSync12(current).isSymbolicLink()) throw new Error("refused");
21806
21971
  }
21807
21972
  const stat = lstatSync12(filename2);
@@ -21819,7 +21984,7 @@ async function startLocalStaticFrontend(directory2, port, backendUrl) {
21819
21984
  const watcher = watch(directory2, { recursive: true }, (_, filename2) => {
21820
21985
  if (filename2 && publicParts(filename2.toString().split(/[\\/]/)) && contentTypes[extname2(filename2.toString()).toLowerCase()]) revision++;
21821
21986
  });
21822
- const server = createServer3((request, response) => {
21987
+ const server = createServer4((request, response) => {
21823
21988
  const send = (status, type, body) => {
21824
21989
  response.writeHead(status, { "content-type": type, "cache-control": "no-store", "x-content-type-options": "nosniff", "content-length": Buffer.byteLength(body) });
21825
21990
  response.end(request.method === "HEAD" ? void 0 : body);
@@ -21832,7 +21997,7 @@ async function startLocalStaticFrontend(directory2, port, backendUrl) {
21832
21997
  if (pathname === "/__backify/revision") return send(200, "text/plain", String(revision));
21833
21998
  if (pathname === "/__backify/config.json") return send(200, "application/json", JSON.stringify({ backendUrl: backendUrl ?? null }));
21834
21999
  const filename2 = publicFile(directory2, pathname);
21835
- const content = readFileSync13(filename2);
22000
+ const content = readFileSync14(filename2);
21836
22001
  if (content.length > 5242880) throw new Error("refused");
21837
22002
  const extension = extname2(filename2).toLowerCase();
21838
22003
  const body = extension === ".html" ? content.toString("utf8") + '\n<script src="/__backify/reload.js?revision=' + revision + '"></script>\n' : content;
@@ -21875,24 +22040,24 @@ function prepareLocalFrontend(root, options, privateFiles = []) {
21875
22040
  if (options.frontendPort !== void 0) throw new Error("Frontend port requires an explicit frontend directory");
21876
22041
  return void 0;
21877
22042
  }
21878
- const directory2 = realpathSync3(resolve13(root, options.frontend));
22043
+ const directory2 = realpathSync3(resolve14(root, options.frontend));
21879
22044
  const part = relative5(realpathSync3(root), directory2);
21880
22045
  if (part === ".." || part.startsWith("../") || part.startsWith("..\\") || isAbsolute10(part) || !statSync(directory2).isDirectory()) throw new Error("Frontend must be a directory inside this repository");
21881
22046
  if (options.frontendAdapter === "static") {
21882
22047
  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");
21883
22048
  return prepareLocalStaticFrontend(directory2);
21884
22049
  }
21885
- if (!existsSync9(join10(directory2, "package.json"))) throw new Error("Frontend requires an existing package.json and installed Vite");
21886
- const require3 = createRequire3(join10(directory2, "package.json"));
22050
+ if (!existsSync9(join11(directory2, "package.json"))) throw new Error("Frontend requires an existing package.json and installed Vite");
22051
+ const require3 = createRequire3(join11(directory2, "package.json"));
21887
22052
  let packagePath;
21888
22053
  try {
21889
22054
  packagePath = require3.resolve("vite/package.json");
21890
22055
  } catch {
21891
22056
  throw new Error("Frontend requires locally installed Vite; Backify does not install dependencies automatically");
21892
22057
  }
21893
- const metadata = JSON.parse(readFileSync14(packagePath, "utf8"));
22058
+ const metadata = JSON.parse(readFileSync15(packagePath, "utf8"));
21894
22059
  if (metadata.name !== "vite" || typeof metadata.bin?.vite !== "string") throw new Error("Installed Vite has no supported CLI entrypoint");
21895
- const executable = realpathSync3(resolve13(dirname10(packagePath), metadata.bin.vite));
22060
+ const executable = realpathSync3(resolve14(dirname10(packagePath), metadata.bin.vite));
21896
22061
  const executablePart = relative5(realpathSync3(dirname10(packagePath)), executable);
21897
22062
  if (executablePart === ".." || executablePart.startsWith("../") || executablePart.startsWith("..\\") || isAbsolute10(executablePart)) throw new Error("Vite CLI entrypoint must remain inside its package");
21898
22063
  const timeout = options.frontendStartupTimeoutMs ?? 3e4;
@@ -21954,8 +22119,8 @@ async function startLocalFrontend(prepared, port, backendUrl) {
21954
22119
  }
21955
22120
 
21956
22121
  // src/local-identity.ts
21957
- import { readFileSync as readFileSync15, statSync as statSync2 } from "node:fs";
21958
- import { resolve as resolve14 } from "node:path";
22122
+ import { readFileSync as readFileSync16, statSync as statSync2 } from "node:fs";
22123
+ import { resolve as resolve15 } from "node:path";
21959
22124
 
21960
22125
  // ../sdk/dist/local-identity.js
21961
22126
  import { createHash as createHash12, randomBytes as randomBytes4 } from "node:crypto";
@@ -22054,22 +22219,22 @@ function createLocalIdentityProvider(options) {
22054
22219
  }
22055
22220
 
22056
22221
  // src/local-identity.ts
22057
- import { randomUUID as randomUUID7 } from "node:crypto";
22222
+ import { randomUUID as randomUUID8 } from "node:crypto";
22058
22223
  function prepareLocalIdentity(root, filename2) {
22059
22224
  if (filename2 === void 0) return void 0;
22060
- const path = resolve14(root, filename2);
22225
+ const path = resolve15(root, filename2);
22061
22226
  assertLocalStatePath(root, path);
22062
22227
  if (!statSync2(path).isFile() || statSync2(path).size > 16384) throw new Error("Local identity profiles require a file at most 16 KiB");
22063
22228
  let input;
22064
22229
  try {
22065
- input = JSON.parse(readFileSync15(path, "utf8"));
22230
+ input = JSON.parse(readFileSync16(path, "utf8"));
22066
22231
  } catch {
22067
22232
  throw new Error("Invalid local identity profile JSON");
22068
22233
  }
22069
22234
  if (!input || typeof input !== "object" || Array.isArray(input) || Object.keys(input).some((name2) => !["version", "organizationName", "users"].includes(name2))) throw new Error("Invalid local identity profiles");
22070
22235
  const value = input;
22071
22236
  if (value.version !== 1) throw new Error("Invalid local identity profile version");
22072
- const identity = createLocalIdentityProvider({ scope: { organizationId: randomUUID7(), applicationId: randomUUID7(), environmentId: randomUUID7() }, organizationName: value.organizationName, users: value.users, requestOrigins: ["http://127.0.0.1:3000"] });
22237
+ const identity = createLocalIdentityProvider({ scope: { organizationId: randomUUID8(), applicationId: randomUUID8(), environmentId: randomUUID8() }, organizationName: value.organizationName, users: value.users, requestOrigins: ["http://127.0.0.1:3000"] });
22073
22238
  return { organizationName: value.organizationName, users: identity.profiles() };
22074
22239
  }
22075
22240
  function localIdentityCommand(args2) {
@@ -22095,17 +22260,17 @@ function localIdentityCommand(args2) {
22095
22260
  }
22096
22261
 
22097
22262
  // src/local-job-history.ts
22098
- import { lstatSync as lstatSync13, readFileSync as readFileSync16 } from "node:fs";
22099
- import { isAbsolute as isAbsolute11, resolve as resolve15 } from "node:path";
22263
+ import { lstatSync as lstatSync13, readFileSync as readFileSync17 } from "node:fs";
22264
+ import { isAbsolute as isAbsolute11, resolve as resolve16 } from "node:path";
22100
22265
  function prepareLocalJobHistory(root, filename2, artifacts, manifest, current) {
22101
22266
  if (filename2 === void 0) return [];
22102
22267
  const read = (filename3, maximum) => {
22103
22268
  if (typeof filename3 !== "string" || !filename3 || isAbsolute11(filename3)) throw new Error();
22104
- const path = resolve15(root, filename3);
22269
+ const path = resolve16(root, filename3);
22105
22270
  assertLocalStatePath(root, path);
22106
22271
  const metadata = lstatSync13(path);
22107
22272
  if (!metadata.isFile() || metadata.isSymbolicLink() || metadata.nlink !== 1 || metadata.size > maximum) throw new Error();
22108
- const bytes = readFileSync16(path);
22273
+ const bytes = readFileSync17(path);
22109
22274
  if (bytes.length > maximum) throw new Error();
22110
22275
  return new TextDecoder("utf8", { fatal: true }).decode(bytes);
22111
22276
  };
@@ -22151,30 +22316,30 @@ function prepareLocalJobHistory(root, filename2, artifacts, manifest, current) {
22151
22316
  }
22152
22317
 
22153
22318
  // src/local-secrets.ts
22154
- import { createCipheriv, createDecipheriv, randomBytes as randomBytes5, randomUUID as randomUUID8 } from "node:crypto";
22155
- import { closeSync as closeSync3, existsSync as existsSync10, fsyncSync as fsyncSync3, lstatSync as lstatSync14, mkdirSync as mkdirSync5, openSync as openSync3, readFileSync as readFileSync17, realpathSync as realpathSync4, writeFileSync as writeFileSync9 } from "node:fs";
22156
- import { dirname as dirname11, isAbsolute as isAbsolute12, join as join11, relative as relative6, resolve as resolve16 } from "node:path";
22319
+ import { createCipheriv, createDecipheriv, randomBytes as randomBytes5, randomUUID as randomUUID9 } from "node:crypto";
22320
+ import { closeSync as closeSync3, existsSync as existsSync10, fsyncSync as fsyncSync3, lstatSync as lstatSync14, mkdirSync as mkdirSync5, openSync as openSync3, readFileSync as readFileSync18, realpathSync as realpathSync4, writeFileSync as writeFileSync10 } from "node:fs";
22321
+ import { dirname as dirname11, isAbsolute as isAbsolute12, join as join12, relative as relative6, resolve as resolve17 } from "node:path";
22157
22322
  var maximumBytes2 = 1048576;
22158
22323
  var secretName = /^[A-Z][A-Z0-9_]{0,127}$/;
22159
22324
  var failure = () => new Error("Local secret vault unavailable or invalid; review the vault and external key privately");
22160
22325
  function vaultPath(root) {
22161
- return join11(realpathSync4(root), ".backify", "dev", "secrets.enc.json");
22326
+ return join12(realpathSync4(root), ".backify", "dev", "secrets.enc.json");
22162
22327
  }
22163
22328
  function inside(root, filename2) {
22164
22329
  const part = relative6(root, filename2);
22165
22330
  return part !== ".." && !part.startsWith("../") && !part.startsWith("..\\") && !isAbsolute12(part);
22166
22331
  }
22167
22332
  function privateFile(filename2, limit) {
22168
- for (let current = resolve16(filename2); ; current = dirname11(current)) {
22333
+ for (let current = resolve17(filename2); ; current = dirname11(current)) {
22169
22334
  if (lstatSync14(current).isSymbolicLink()) throw failure();
22170
22335
  if (dirname11(current) === current) break;
22171
22336
  }
22172
22337
  const stat = lstatSync14(filename2);
22173
22338
  if (!stat.isFile() || stat.size > limit || stat.nlink !== 1 || process.platform !== "win32" && (stat.mode & 63) !== 0) throw failure();
22174
- return readFileSync17(filename2);
22339
+ return readFileSync18(filename2);
22175
22340
  }
22176
22341
  function externalKey(root, filename2) {
22177
- const keyFile = resolve16(filename2);
22342
+ const keyFile = resolve17(filename2);
22178
22343
  if (inside(realpathSync4(root), keyFile) || inside(realpathSync4(root), realpathSync4(keyFile))) throw failure();
22179
22344
  const encoded = privateFile(keyFile, 64).toString("utf8");
22180
22345
  if (!/^[a-f0-9]{64}$/.test(encoded)) throw failure();
@@ -22203,17 +22368,17 @@ function encrypt(root, application, key, secrets) {
22203
22368
  function writePrivate2(filename2, value) {
22204
22369
  const descriptor2 = openSync3(filename2, "wx", 384);
22205
22370
  try {
22206
- writeFileSync9(descriptor2, value);
22371
+ writeFileSync10(descriptor2, value);
22207
22372
  fsyncSync3(descriptor2);
22208
22373
  } finally {
22209
22374
  closeSync3(descriptor2);
22210
22375
  }
22211
22376
  }
22212
22377
  function ensureIgnored(root) {
22213
- const filename2 = join11(root, ".gitignore");
22378
+ const filename2 = join12(root, ".gitignore");
22214
22379
  assertLocalStatePath(root, filename2);
22215
- const current = existsSync10(filename2) ? readFileSync17(filename2, "utf8") : "";
22216
- if (!current.split(/\r?\n/).some((line) => line.trim() === ".backify/")) writeFileSync9(filename2, current + (current && !current.endsWith("\n") ? "\n" : "") + ".backify/\n");
22380
+ const current = existsSync10(filename2) ? readFileSync18(filename2, "utf8") : "";
22381
+ if (!current.split(/\r?\n/).some((line) => line.trim() === ".backify/")) writeFileSync10(filename2, current + (current && !current.endsWith("\n") ? "\n" : "") + ".backify/\n");
22217
22382
  }
22218
22383
  function readLocalSecrets(root, application, keyFile) {
22219
22384
  const filename2 = vaultPath(root);
@@ -22246,7 +22411,7 @@ function readLocalSecrets(root, application, keyFile) {
22246
22411
  }
22247
22412
  }
22248
22413
  function initializeLocalSecrets(root, application, keyFile) {
22249
- const filename2 = vaultPath(root), external = resolve16(keyFile);
22414
+ const filename2 = vaultPath(root), external = resolve17(keyFile);
22250
22415
  assertLocalStatePath(root, filename2);
22251
22416
  if (existsSync10(filename2) || existsSync10(external)) throw new Error("Local secret initialization never overwrites an existing vault or key");
22252
22417
  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");
@@ -22280,7 +22445,7 @@ function setLocalSecret(root, application, keyFile, name2, value) {
22280
22445
  const secrets = readLocalSecrets(root, application, keyFile);
22281
22446
  secrets[name2] = value;
22282
22447
  key = externalKey(root, keyFile);
22283
- const temporary = filename2 + "." + randomUUID8() + ".tmp";
22448
+ const temporary = filename2 + "." + randomUUID9() + ".tmp";
22284
22449
  assertLocalStatePath(root, temporary);
22285
22450
  writePrivate2(temporary, encrypt(root, application, key, secrets));
22286
22451
  renameLocalFile(temporary, filename2);
@@ -22317,10 +22482,10 @@ async function localSecretsCommand(args2, root, application, input = process.std
22317
22482
 
22318
22483
  // src/local-development.ts
22319
22484
  function localManifest(root = process.cwd()) {
22320
- const filename2 = join12(root, "backify.yaml");
22485
+ const filename2 = join13(root, "backify.yaml");
22321
22486
  if (!existsSync11(filename2)) throw new Error("Create backify.yaml with version, application, runtime and explicit capabilities before running backify dev");
22322
- const manifest = parseApplicationManifest(readFileSync18(filename2, "utf8"));
22323
- const entry = resolve17(root, manifest.runtime.entrypoint);
22487
+ const manifest = parseApplicationManifest(readFileSync19(filename2, "utf8"));
22488
+ const entry = resolve18(root, manifest.runtime.entrypoint);
22324
22489
  if (!existsSync11(entry) || !inside2(root, realpathSync5(entry))) throw new Error("Runtime entrypoint must exist inside this repository");
22325
22490
  const discovered = analyzeSources(repositorySources(root));
22326
22491
  const diagnostics = manifestDiagnostics(manifest, Object.keys(discovered.capabilities), discovered.capabilities.auth?.configuration);
@@ -22332,12 +22497,12 @@ function inside2(root, path) {
22332
22497
  return part !== ".." && !part.startsWith(".." + (process.platform === "win32" ? "\\" : "/")) && !isAbsolute13(part);
22333
22498
  }
22334
22499
  function sessionPath(root) {
22335
- return join12(root, ".backify", "dev", "session.json");
22500
+ return join13(root, ".backify", "dev", "session.json");
22336
22501
  }
22337
22502
  async function localRequest(path, input, root = process.cwd()) {
22338
22503
  if (!/^\/v1\/[a-z/-]+$/.test(path)) throw new Error("Invalid local command path");
22339
22504
  if (!existsSync11(sessionPath(root))) throw new Error("Start backify dev before using local commands");
22340
- const session = JSON.parse(readFileSync18(sessionPath(root), "utf8"));
22505
+ const session = JSON.parse(readFileSync19(sessionPath(root), "utf8"));
22341
22506
  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");
22342
22507
  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) });
22343
22508
  if (!response.ok) {
@@ -22370,7 +22535,7 @@ async function startLocalDevelopment(options = {}) {
22370
22535
  if (options.jobTrustSyncFile !== void 0 && options.jobAuthFile === void 0) throw new Error("Native worker trust renewal requires explicit reviewed auth mounts");
22371
22536
  if (options.jobHistoryFile !== void 0 && options.jobWorkerDirectory === void 0) throw new Error("Historical workers require paired reviewed job artifacts and current worker");
22372
22537
  if (options.jobAuthFile !== void 0 && options.identityUsers !== void 0) throw new Error("Reviewed worker issuer trust cannot be mixed with local identity fixtures");
22373
- const root = resolve17(options.root ?? process.cwd());
22538
+ const root = resolve18(options.root ?? process.cwd());
22374
22539
  const manifest = localManifest(root);
22375
22540
  const validateSecretIntent = (values, intent = manifest) => {
22376
22541
  if (Object.keys(values).length && (!intent.capabilities.secrets || intent.capabilities.secrets.enabled === false)) throw new Error("Encrypted local secrets require enabled capabilities.secrets");
@@ -22387,15 +22552,15 @@ async function startLocalDevelopment(options = {}) {
22387
22552
  createLocalJobTrustRenewal(root, authMounts);
22388
22553
  const identityProfiles = prepareLocalIdentity(root, options.identityUsers);
22389
22554
  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");
22390
- const preparedFrontend = prepareLocalFrontend(root, options, options.localSecretsKey ? [realpathSync5(resolve17(options.localSecretsKey))] : []);
22391
- const ignorePath = join12(root, ".gitignore");
22555
+ const preparedFrontend = prepareLocalFrontend(root, options, options.localSecretsKey ? [realpathSync5(resolve18(options.localSecretsKey))] : []);
22556
+ const ignorePath = join13(root, ".gitignore");
22392
22557
  if (existsSync11(ignorePath) && lstatSync15(ignorePath).isSymbolicLink()) throw new Error("Local development cannot update a symlinked .gitignore");
22393
- const ignore = existsSync11(ignorePath) ? readFileSync18(ignorePath, "utf8") : "";
22394
- if (!ignore.split(/\r?\n/).some((line) => line.trim() === ".backify/")) writeFileSync10(ignorePath, ignore + (ignore.endsWith("\n") || !ignore ? "" : "\n") + ".backify/\n");
22558
+ const ignore = existsSync11(ignorePath) ? readFileSync19(ignorePath, "utf8") : "";
22559
+ if (!ignore.split(/\r?\n/).some((line) => line.trim() === ".backify/")) writeFileSync11(ignorePath, ignore + (ignore.endsWith("\n") || !ignore ? "" : "\n") + ".backify/\n");
22395
22560
  if (options.port !== void 0 && (!Number.isInteger(options.port) || options.port < 0 || options.port > 65535)) throw new Error("Dashboard port must be 0-65535");
22396
- const directory2 = join12(root, ".backify", "dev");
22561
+ const directory2 = join13(root, ".backify", "dev");
22397
22562
  assertLocalStatePath(root, directory2);
22398
- for (const filename2 of ["session.json", "session.json.tmp", "worker.mjs", "worker.mjs.map", "state.json", "state.json.tmp"]) assertLocalStatePath(root, join12(directory2, filename2));
22563
+ for (const filename2 of ["session.json", "session.json.tmp", "worker.mjs", "worker.mjs.map", "state.json", "state.json.tmp"]) assertLocalStatePath(root, join13(directory2, filename2));
22399
22564
  mkdirSync6(directory2, { recursive: true });
22400
22565
  if (!inside2(root, realpathSync5(directory2))) throw new Error("Local state directory must remain inside this repository");
22401
22566
  if (existsSync11(sessionPath(root))) {
@@ -22429,14 +22594,14 @@ async function startLocalDevelopment(options = {}) {
22429
22594
  throw error;
22430
22595
  }
22431
22596
  const token = randomBytes6(32).toString("hex");
22432
- const identityScope = services?.identityScope ?? { organizationId: randomUUID9(), applicationId: randomUUID9(), environmentId: randomUUID9() };
22597
+ const identityScope = services?.identityScope ?? { organizationId: randomUUID10(), applicationId: randomUUID10(), environmentId: randomUUID10() };
22433
22598
  const workerEnvironment = (worker) => {
22434
22599
  if (!worker.authTrust) return worker;
22435
22600
  const { renewal, ...authTrust } = worker.authTrust;
22436
22601
  return { ...worker, authTrust };
22437
22602
  };
22438
22603
  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" });
22439
- const outfile = join12(directory2, "worker.mjs");
22604
+ const outfile = join13(directory2, "worker.mjs");
22440
22605
  let child;
22441
22606
  const trustRenewal = createLocalJobTrustRenewal(root, authMounts, { onFailure: () => console.error("Native worker trust renewal unavailable; existing validity and pin guards remain enforced."), onUpdate: () => {
22442
22607
  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) => {
@@ -22474,8 +22639,8 @@ async function startLocalDevelopment(options = {}) {
22474
22639
  }
22475
22640
  await stopChild(child);
22476
22641
  if (stopping) return;
22477
- const version = createHash13("sha256").update(readFileSync18(outfile)).update(services?.configurationFingerprint ?? "lightweight").digest("hex");
22478
- 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: join12(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" } });
22642
+ const version = createHash13("sha256").update(readFileSync19(outfile)).update(services?.configurationFingerprint ?? "lightweight").digest("hex");
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: join13(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" } });
22479
22644
  child = worker;
22480
22645
  worker.send({ type: "local-secrets", secrets }, (error) => {
22481
22646
  if (error) {
@@ -22497,7 +22662,7 @@ async function startLocalDevelopment(options = {}) {
22497
22662
  workerReady = true;
22498
22663
  const session = { version: 1, port: message.port, token, pid: worker.pid };
22499
22664
  const temp = sessionPath(root) + ".tmp";
22500
- writeFileSync10(temp, JSON.stringify(session), { mode: 384 });
22665
+ writeFileSync11(temp, JSON.stringify(session), { mode: 384 });
22501
22666
  renameLocalFile(temp, sessionPath(root));
22502
22667
  const url = "http://127.0.0.1:" + message.port;
22503
22668
  options.onReady?.(url, { frontendUrl: frontend?.url, backendUrl });
@@ -22509,17 +22674,17 @@ async function startLocalDevelopment(options = {}) {
22509
22674
  });
22510
22675
  };
22511
22676
  try {
22512
- buildContext = await context2({ absWorkingDir: root, stdin: { contents: localWorkerSource(resolve17(root, manifest.runtime.entrypoint)), resolveDir: root, sourcefile: "backify-local-worker.ts", loader: "ts" }, bundle: true, platform: "node", format: "esm", target: "node20", outfile, sourcemap: true, banner: { js: 'import { createRequire as __backifyCreateRequire } from "node:module"; var require = __backifyCreateRequire(import.meta.url);' }, plugins: [{ name: "backify-local-lifecycle", setup(build3) {
22677
+ buildContext = await context2({ absWorkingDir: root, stdin: { contents: localWorkerSource(resolve18(root, manifest.runtime.entrypoint)), resolveDir: root, sourcefile: "backify-local-worker.ts", loader: "ts" }, bundle: true, platform: "node", format: "esm", target: "node20", outfile, sourcemap: true, banner: { js: 'import { createRequire as __backifyCreateRequire } from "node:module"; var require = __backifyCreateRequire(import.meta.url);' }, plugins: [{ name: "backify-local-lifecycle", setup(build3) {
22513
22678
  build3.onLoad({ filter: /./, namespace: "file" }, (input) => {
22514
- if (input.path !== resolve17(root, manifest.runtime.entrypoint)) return;
22679
+ if (input.path !== resolve18(root, manifest.runtime.entrypoint)) return;
22515
22680
  try {
22516
22681
  const updated = localManifest(root);
22517
22682
  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");
22518
22683
  if (updated.runtime.entrypoint !== manifest.runtime.entrypoint) throw new Error("Runtime entrypoint changed; restart backify dev");
22519
22684
  } catch (error) {
22520
- return { errors: [{ text: error instanceof Error ? error.message : "Manifest validation failed" }], watchFiles: [join12(root, "backify.yaml")] };
22685
+ return { errors: [{ text: error instanceof Error ? error.message : "Manifest validation failed" }], watchFiles: [join13(root, "backify.yaml")] };
22521
22686
  }
22522
- return { contents: readFileSync18(input.path, "utf8"), loader: input.path.endsWith(".tsx") ? "tsx" : /\.(ts|mts|cts)$/.test(input.path) ? "ts" : input.path.endsWith(".jsx") ? "jsx" : "js", watchFiles: [join12(root, "backify.yaml")] };
22687
+ return { contents: readFileSync19(input.path, "utf8"), loader: input.path.endsWith(".tsx") ? "tsx" : /\.(ts|mts|cts)$/.test(input.path) ? "ts" : input.path.endsWith(".jsx") ? "jsx" : "js", watchFiles: [join13(root, "backify.yaml")] };
22523
22688
  });
22524
22689
  build3.onEnd((result) => {
22525
22690
  if (result.errors.length) rejectStartup(new Error("Local application build failed"));
@@ -22576,8 +22741,8 @@ async function startLocalDevelopment(options = {}) {
22576
22741
  }
22577
22742
  }
22578
22743
  if (existsSync11(sessionPath(root))) {
22579
- const session = JSON.parse(readFileSync18(sessionPath(root), "utf8"));
22580
- if (session.token === token) unlinkSync4(sessionPath(root));
22744
+ const session = JSON.parse(readFileSync19(sessionPath(root), "utf8"));
22745
+ if (session.token === token) unlinkSync5(sessionPath(root));
22581
22746
  }
22582
22747
  };
22583
22748
  return {
@@ -22590,10 +22755,10 @@ async function startLocalDevelopment(options = {}) {
22590
22755
  }
22591
22756
  async function runLocalTests(root = process.cwd()) {
22592
22757
  const manifest = localManifest(root);
22593
- const project = JSON.parse(readFileSync18(join12(root, "package.json"), "utf8"));
22758
+ const project = JSON.parse(readFileSync19(join13(root, "package.json"), "utf8"));
22594
22759
  if (!project.scripts?.test) throw new Error("Add a test script to package.json so AI agents can run backify test");
22595
22760
  const result = await new Promise((resolveResult, reject) => {
22596
- const npmPath = process.platform === "win32" ? process.env.npm_execpath ?? join12(dirname12(process.execPath), "node_modules", "npm", "bin", "npm-cli.js") : void 0;
22761
+ const npmPath = process.platform === "win32" ? process.env.npm_execpath ?? join13(dirname12(process.execPath), "node_modules", "npm", "bin", "npm-cli.js") : void 0;
22597
22762
  if (npmPath && !existsSync11(npmPath)) {
22598
22763
  reject(new Error("Cannot locate npm-cli.js; run backify test through npx or npm"));
22599
22764
  return;
@@ -22621,7 +22786,7 @@ function digest3(contents) {
22621
22786
  }
22622
22787
  function packageDirectory(filename2) {
22623
22788
  for (let current = dirname13(filename2); ; current = dirname13(current)) {
22624
- if (existsSync12(join13(current, "package.json"))) return current;
22789
+ if (existsSync12(join14(current, "package.json"))) return current;
22625
22790
  if (dirname13(current) === current) throw new Error("Cannot locate an installed dependency package");
22626
22791
  }
22627
22792
  }
@@ -22703,11 +22868,11 @@ main().catch(() => finish({ schemaVersion: 1, status: "failed", error: "workload
22703
22868
  `.replace("__KIND__", JSON.stringify(kind)).replace("__CAPABILITIES__", JSON.stringify(capabilities)).replace("__AUTH_ENABLED__", String(capabilities.includes("auth"))).replace("__ENTRY__", JSON.stringify(entry));
22704
22869
  }
22705
22870
  async function prepareWorkload(options) {
22706
- const root = realpathSync6(resolve18(options.root ?? process.cwd()));
22871
+ const root = realpathSync6(resolve19(options.root ?? process.cwd()));
22707
22872
  const manifest = localManifest(root);
22708
22873
  if (options.kind !== "http" && options.kind !== "worker") throw new Error("Workload kind must be http or worker");
22709
22874
  if (options.kind === "worker" && !options.entry) throw new Error("Workers require an explicit declaration-only entrypoint");
22710
- const entry = realpathSync6(resolve18(root, options.entry ?? manifest.runtime.entrypoint));
22875
+ const entry = realpathSync6(resolve19(root, options.entry ?? manifest.runtime.entrypoint));
22711
22876
  if (!inside3(root, entry)) throw new Error("Workload entrypoint must stay inside this repository");
22712
22877
  const enabled = Object.entries(manifest.capabilities).filter(([, settings]) => settings?.enabled !== false).map(([name2]) => name2).sort();
22713
22878
  if (options.kind === "worker" && !enabled.includes("jobs")) throw new Error("Workers require declared jobs capability");
@@ -22733,11 +22898,11 @@ async function prepareWorkload(options) {
22733
22898
  context3.onResolve({ filter: /./ }, async (input) => {
22734
22899
  if (input.pluginData?.backifyResolved) return;
22735
22900
  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" }] };
22736
- const resolved = await context3.resolve(input.path, { importer: input.namespace === "backify-workload-host" ? join13(root, input.importer) : input.importer, resolveDir: input.resolveDir, kind: input.kind, pluginData: { backifyResolved: true } });
22901
+ const resolved = await context3.resolve(input.path, { importer: input.namespace === "backify-workload-host" ? join14(root, input.importer) : input.importer, resolveDir: input.resolveDir, kind: input.kind, pluginData: { backifyResolved: true } });
22737
22902
  if (!resolved.external && !resolved.errors.length && resolved.path) {
22738
22903
  const directory2 = realpathSync6(packageDirectory(resolved.path));
22739
22904
  const target = relative8(directory2, realpathSync6(resolved.path)).replaceAll("\\", "/");
22740
- if (JSON.parse(readFileSync19(join13(directory2, "package.json"), "utf8")).name === "@backifydev/sdk") {
22905
+ if (JSON.parse(readFileSync20(join14(directory2, "package.json"), "utf8")).name === "@backifydev/sdk") {
22741
22906
  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" }] };
22742
22907
  }
22743
22908
  if (!isAbsolute14(input.path) && !input.path.startsWith(".")) trustedPackages.add(directory2);
@@ -22799,30 +22964,30 @@ async function packageWorkload(options) {
22799
22964
  if (plan.blockers.includes("bundle-warning-review-required")) throw new Error("Workload bundle warnings require review before packaging");
22800
22965
  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", ...options.kind === "http" ? ["EXPOSE 8080"] : [], "STOPSIGNAL SIGTERM", 'ENTRYPOINT ["node", "workload.mjs"]', ""].join("\n");
22801
22966
  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" };
22802
- const output = resolve18(root, options.output ?? ".backify/artifacts/" + options.kind + "-" + plan.artifactVersion.slice(0, 16));
22967
+ const output = resolve19(root, options.output ?? ".backify/artifacts/" + options.kind + "-" + plan.artifactVersion.slice(0, 16));
22803
22968
  assertLocalStatePath(root, output);
22804
22969
  if (existsSync12(output)) {
22805
22970
  if (JSON.stringify(readdirSync6(output).sort()) !== JSON.stringify(Object.keys(files).sort()) || Object.entries(files).some(([name2, value]) => {
22806
- assertLocalStatePath(root, join13(output, name2));
22807
- return !readFileSync19(join13(output, name2)).equals(Buffer.from(value));
22971
+ assertLocalStatePath(root, join14(output, name2));
22972
+ return !readFileSync20(join14(output, name2)).equals(Buffer.from(value));
22808
22973
  })) throw new Error("Refusing to overwrite an existing workload artifact directory");
22809
22974
  } else {
22810
22975
  mkdirSync7(output, { recursive: true });
22811
- for (const [name2, value] of Object.entries(files)) writeFileSync11(join13(output, name2), value, { flag: "wx", mode: 384 });
22976
+ for (const [name2, value] of Object.entries(files)) writeFileSync12(join14(output, name2), value, { flag: "wx", mode: 384 });
22812
22977
  }
22813
22978
  return { ...plan, outputDirectory: relative8(root, output).replaceAll("\\", "/") };
22814
22979
  }
22815
22980
 
22816
22981
  // src/workload-provenance.ts
22817
22982
  import { execFileSync } from "node:child_process";
22818
- import { mkdirSync as mkdirSync8, mkdtempSync as mkdtempSync2, readdirSync as readdirSync7, rmSync as rmSync2, writeFileSync as writeFileSync12 } from "node:fs";
22983
+ import { mkdirSync as mkdirSync8, mkdtempSync as mkdtempSync2, readdirSync as readdirSync7, rmSync as rmSync2, writeFileSync as writeFileSync13 } from "node:fs";
22819
22984
  import { tmpdir } from "node:os";
22820
- import { basename as basename3, dirname as dirname15, isAbsolute as isAbsolute15, join as join15, relative as relative9, resolve as resolve20 } from "node:path";
22985
+ import { basename as basename3, dirname as dirname15, isAbsolute as isAbsolute15, join as join16, relative as relative9, resolve as resolve21 } from "node:path";
22821
22986
 
22822
22987
  // src/workload-provenance-oci.ts
22823
22988
  import { createHash as createHash15 } from "node:crypto";
22824
- import { createReadStream, lstatSync as lstatSync16, readFileSync as readFileSync20 } from "node:fs";
22825
- import { dirname as dirname14, join as join14, parse as parse3, resolve as resolve19 } from "node:path";
22989
+ import { createReadStream, lstatSync as lstatSync16, readFileSync as readFileSync21 } from "node:fs";
22990
+ import { dirname as dirname14, join as join15, parse as parse3, resolve as resolve20 } from "node:path";
22826
22991
  import { Transform, Writable } from "node:stream";
22827
22992
  import { pipeline } from "node:stream/promises";
22828
22993
  import { createGunzip } from "node:zlib";
@@ -22837,14 +23002,14 @@ function provenanceRef(value) {
22837
23002
  return value.slice(value.lastIndexOf("@") + 1);
22838
23003
  }
22839
23004
  function provenanceFile(filename2, maximum) {
22840
- const absolute = resolve19(filename2);
23005
+ const absolute = resolve20(filename2);
22841
23006
  for (let ancestor = absolute; ; ancestor = dirname14(ancestor)) {
22842
23007
  if (lstatSync16(ancestor).isSymbolicLink()) throw new Error("Provenance paths must not contain links");
22843
23008
  if (ancestor === parse3(absolute).root) break;
22844
23009
  }
22845
23010
  const stat = lstatSync16(absolute);
22846
23011
  if (!stat.isFile() || stat.nlink !== 1 || stat.size < 1 || stat.size > maximum) throw new Error("Invalid provenance file");
22847
- const bytes = readFileSync20(absolute);
23012
+ const bytes = readFileSync21(absolute);
22848
23013
  if (bytes.length !== stat.size) throw new Error("Provenance file changed during read");
22849
23014
  return bytes;
22850
23015
  }
@@ -22853,7 +23018,7 @@ function descriptor(value) {
22853
23018
  return value;
22854
23019
  }
22855
23020
  function blobPath(root, value) {
22856
- return join14(root, "blobs", "sha256", descriptor(value).digest.slice(7));
23021
+ return join15(root, "blobs", "sha256", descriptor(value).digest.slice(7));
22857
23022
  }
22858
23023
  function jsonBlob(root, value) {
22859
23024
  const bytes = provenanceFile(blobPath(root, value), 1024 * 1024);
@@ -22862,8 +23027,8 @@ function jsonBlob(root, value) {
22862
23027
  }
22863
23028
  async function inspectProvenanceImage(root, architecture, requestedDigest) {
22864
23029
  if (!["amd64", "arm64"].includes(architecture) || requestedDigest && !digestPattern.test(requestedDigest)) throw new Error("Invalid OCI platform or digest");
22865
- if (JSON.parse(provenanceFile(join14(root, "oci-layout"), 1024).toString()).imageLayoutVersion !== "1.0.0") throw new Error("OCI layout required");
22866
- const indexBytes = provenanceFile(join14(root, "index.json"), 1024 * 1024);
23030
+ if (JSON.parse(provenanceFile(join15(root, "oci-layout"), 1024).toString()).imageLayoutVersion !== "1.0.0") throw new Error("OCI layout required");
23031
+ const indexBytes = provenanceFile(join15(root, "index.json"), 1024 * 1024);
22867
23032
  let current = JSON.parse(indexBytes.toString());
22868
23033
  let selected;
22869
23034
  let manifestDigest = provenanceHash(indexBytes);
@@ -22920,7 +23085,7 @@ async function inspectProvenanceImage(root, architecture, requestedDigest) {
22920
23085
  return { manifestDigest, configDigest: configuration.digest, architecture, layers };
22921
23086
  }
22922
23087
  function provenanceFileMetadata(filename2, expectedSize) {
22923
- const absolute = resolve19(filename2);
23088
+ const absolute = resolve20(filename2);
22924
23089
  for (let ancestor = absolute; ; ancestor = dirname14(ancestor)) {
22925
23090
  if (lstatSync16(ancestor).isSymbolicLink()) throw new Error("Provenance paths must not contain links");
22926
23091
  if (ancestor === parse3(absolute).root) break;
@@ -22983,28 +23148,28 @@ function dependencyMaterials(lock) {
22983
23148
  return { digest: provenanceHash(canonical(materials.sort((left, right) => left.path.localeCompare(right.path, "en")))), count: materials.length };
22984
23149
  }
22985
23150
  async function captureWorkloadProvenance(options) {
22986
- const root = resolve20(options.root ?? process.cwd());
23151
+ const root = resolve21(options.root ?? process.cwd());
22987
23152
  if (!repositoryPattern.test(options.repository) || !["first", "second"].includes(options.replica)) throw new Error("Invalid provenance repository or replica");
22988
- const applicationPath = relative9(root, resolve20(root, options.application)).replaceAll("\\", "/");
23153
+ const applicationPath = relative9(root, resolve21(root, options.application)).replaceAll("\\", "/");
22989
23154
  if (!applicationPath || isAbsolute15(applicationPath) || applicationPath.split("/").includes("..")) throw new Error("Application must be inside the source checkout");
22990
23155
  if (git2(root, ["rev-parse", "--show-toplevel"]).replaceAll("\\", "/").toLowerCase() !== root.replaceAll("\\", "/").toLowerCase() || git2(root, ["status", "--porcelain", "--untracked-files=all"]) || git2(root, ["ls-files", "--stage"]).split("\n").some((line) => line.startsWith("160000 "))) throw new Error("Clean root checkout without submodules required");
22991
23156
  const commit = git2(root, ["rev-parse", "HEAD"]), tree = git2(root, ["rev-parse", "HEAD^{tree}"]);
22992
23157
  if (!sha.test(commit) || !sha.test(tree)) throw new Error("Full Git commit and tree required");
22993
23158
  const origin = git2(root, ["remote", "get-url", "origin"]);
22994
23159
  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");
22995
- const lockBytes = provenanceFile(join15(root, "package-lock.json"), 16 * 1024 * 1024);
23160
+ const lockBytes = provenanceFile(join16(root, "package-lock.json"), 16 * 1024 * 1024);
22996
23161
  const dependencies = dependencyMaterials(JSON.parse(lockBytes.toString("utf8")));
22997
- const context3 = resolve20(root, options.context);
23162
+ const context3 = resolve21(root, options.context);
22998
23163
  if (canonical(readdirSync7(context3).sort()) !== canonical(contextNames)) throw new Error("Exact allowlisted workload context required");
22999
23164
  const contextDigests = {};
23000
- for (const name2 of contextNames) contextDigests[name2] = provenanceHash(provenanceFile(join15(context3, name2), name2 === "workload.mjs" ? 16 * 1024 * 1024 : 65536));
23001
- const plan = boundedJson(join15(context3, "artifact.json"));
23165
+ for (const name2 of contextNames) contextDigests[name2] = provenanceHash(provenanceFile(join16(context3, name2), name2 === "workload.mjs" ? 16 * 1024 * 1024 : 65536));
23166
+ const plan = boundedJson(join16(context3, "artifact.json"));
23002
23167
  const baseDigest = provenanceRef(options.baseImage);
23003
23168
  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");
23004
23169
  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");
23005
- if (!provenanceFile(join15(context3, "Dockerfile"), 65536).equals(Buffer.from(dockerfile)) || provenanceFile(join15(context3, ".dockerignore"), 65536).toString() !== "**\n!Dockerfile\n!workload.mjs\n!artifact.json\n!.dockerignore\n") throw new Error("Unreviewed workload build recipe");
23006
- const base = await inspectProvenanceImage(resolve20(root, options.baseLayout), options.architecture, baseDigest);
23007
- const image2 = await inspectProvenanceImage(resolve20(root, options.imageLayout), options.architecture);
23170
+ if (!provenanceFile(join16(context3, "Dockerfile"), 65536).equals(Buffer.from(dockerfile)) || provenanceFile(join16(context3, ".dockerignore"), 65536).toString() !== "**\n!Dockerfile\n!workload.mjs\n!artifact.json\n!.dockerignore\n") throw new Error("Unreviewed workload build recipe");
23171
+ const base = await inspectProvenanceImage(resolve21(root, options.baseLayout), options.architecture, baseDigest);
23172
+ const image2 = await inspectProvenanceImage(resolve21(root, options.imageLayout), options.architecture);
23008
23173
  verifyBaseLineage(base, image2);
23009
23174
  let npm;
23010
23175
  try {
@@ -23077,17 +23242,17 @@ function verifyWorkloadProvenance(options, now = /* @__PURE__ */ new Date()) {
23077
23242
  if (provenanceHash(baseSubject) !== provenanceRef(policy.baseImage)) throw new Error("Base attestation subject does not match the approved image digest");
23078
23243
  evidence.push({ bytes: baseSubject, bundle: provenanceFile(options.baseBundle, 4 * 1024 * 1024), identity: { ...policy, ...supplier } });
23079
23244
  }
23080
- const scratchRoot = resolve20(tmpdir());
23081
- const scratch = mkdtempSync2(join15(scratchRoot, "backify-provenance-"));
23245
+ const scratchRoot = resolve21(tmpdir());
23246
+ const scratch = mkdtempSync2(join16(scratchRoot, "backify-provenance-"));
23082
23247
  if (dirname15(scratch) !== scratchRoot || !basename3(scratch).startsWith("backify-provenance-")) throw new Error("Unsafe provenance evidence directory");
23083
23248
  try {
23084
- mkdirSync8(join15(scratch, "evidence"), { mode: 448 });
23085
- const trustedRoot = join15(scratch, "evidence", "trusted-root.jsonl");
23086
- writeFileSync12(trustedRoot, rootBytes, { flag: "wx", mode: 384 });
23249
+ mkdirSync8(join16(scratch, "evidence"), { mode: 448 });
23250
+ const trustedRoot = join16(scratch, "evidence", "trusted-root.jsonl");
23251
+ writeFileSync13(trustedRoot, rootBytes, { flag: "wx", mode: 384 });
23087
23252
  for (const [index, { bytes, bundle: bundleBytes, identity }] of evidence.entries()) {
23088
- const report = join15(scratch, "evidence", "report-" + index + ".json"), bundle = join15(scratch, "evidence", "bundle-" + index + ".jsonl");
23089
- writeFileSync12(report, bytes, { flag: "wx", mode: 384 });
23090
- writeFileSync12(bundle, bundleBytes, { flag: "wx", mode: 384 });
23253
+ const report = join16(scratch, "evidence", "report-" + index + ".json"), bundle = join16(scratch, "evidence", "bundle-" + index + ".jsonl");
23254
+ writeFileSync13(report, bytes, { flag: "wx", mode: 384 });
23255
+ writeFileSync13(bundle, bundleBytes, { flag: "wx", mode: 384 });
23091
23256
  try {
23092
23257
  const result = execFileSync("gh", ["attestation", "verify", report, "--bundle", bundle, "--custom-trusted-root", trustedRoot, "--hostname", "github.com", "--repo", identity.repository, "--signer-workflow", identity.signerWorkflow, "--signer-digest", identity.signerDigest, "--source-digest", identity.sourceCommit, "--source-ref", identity.sourceRef, "--deny-self-hosted-runners", "--predicate-type", "https://slsa.dev/provenance/v1", "--format", "json"], { encoding: "utf8", windowsHide: true, timeout: 12e4, maxBuffer: 4 * 1024 * 1024, stdio: ["ignore", "pipe", "pipe"] });
23093
23258
  if (!Array.isArray(JSON.parse(result)) || !JSON.parse(result).length) throw new Error();
@@ -23118,13 +23283,13 @@ async function workloadProvenanceCommand(args2) {
23118
23283
  return verifyWorkloadProvenance({ policy: required("--policy"), firstReport: options.get("--report") ?? required("--first-report"), firstBundle: options.get("--bundle") ?? required("--first-bundle"), secondReport: options.get("--second-report"), secondBundle: options.get("--second-bundle"), baseSubject: options.get("--base-subject"), baseBundle: options.get("--base-bundle"), trustedRoot: required("--trusted-root") });
23119
23284
  }
23120
23285
  const result = await captureWorkloadProvenance({ root: options.get("--root"), repository: required("--repository"), application: required("--application"), context: required("--context"), baseLayout: required("--base-layout"), imageLayout: required("--image-layout"), baseImage: required("--base-image"), architecture: required("--architecture"), replica: options.get("--replica") ?? "first" });
23121
- writeFileSync12(resolve20(required("--output")), JSON.stringify(result, null, 2) + "\n", { flag: "wx", mode: 384 });
23286
+ writeFileSync13(resolve21(required("--output")), JSON.stringify(result, null, 2) + "\n", { flag: "wx", mode: 384 });
23122
23287
  return { schemaVersion: 1, status: "captured-unsigned", deploymentReady: false, reportDigest: provenanceHash(JSON.stringify(result, null, 2) + "\n") };
23123
23288
  }
23124
23289
 
23125
23290
  // src/workload-trust-state.ts
23126
- import { lstatSync as lstatSync17, readFileSync as readFileSync21 } from "node:fs";
23127
- import { isAbsolute as isAbsolute16, resolve as resolve21 } from "node:path";
23291
+ import { lstatSync as lstatSync17, readFileSync as readFileSync22 } from "node:fs";
23292
+ import { isAbsolute as isAbsolute16, resolve as resolve22 } from "node:path";
23128
23293
  function parseWorkloadTrustState(args2) {
23129
23294
  const action = args2[0];
23130
23295
  if (action !== "plan" && action !== "initialize") throw new Error("Use backify workload trust-state plan|initialize");
@@ -23146,12 +23311,12 @@ function parseWorkloadTrustState(args2) {
23146
23311
  return { action, trustFile: values.get("--trust-file"), stateFile: values.get("--state-file"), expectedRevision: Number(values.get("--revision")), expectedScope: { organizationId: values.get("--organization"), applicationId: values.get("--application"), environmentId: values.get("--environment") }, confirmed: values.has("--confirm") };
23147
23312
  }
23148
23313
  function workloadTrustState(options) {
23149
- if (!["plan", "initialize"].includes(options.action) || !isAbsolute16(options.trustFile) || !isAbsolute16(options.stateFile) || resolve21(options.trustFile) === resolve21(options.stateFile) || !Number.isSafeInteger(options.expectedRevision) || options.expectedRevision < 1) throw new Error("Specify separate absolute trust/state paths and a positive reviewed revision");
23314
+ if (!["plan", "initialize"].includes(options.action) || !isAbsolute16(options.trustFile) || !isAbsolute16(options.stateFile) || resolve22(options.trustFile) === resolve22(options.stateFile) || !Number.isSafeInteger(options.expectedRevision) || options.expectedRevision < 1) throw new Error("Specify separate absolute trust/state paths and a positive reviewed revision");
23150
23315
  let trust;
23151
23316
  try {
23152
23317
  const metadata = lstatSync17(options.trustFile);
23153
23318
  if (!metadata.isFile() || metadata.isSymbolicLink() || metadata.nlink !== 1 || metadata.size > 131072) throw new Error();
23154
- const bytes = readFileSync21(options.trustFile);
23319
+ const bytes = readFileSync22(options.trustFile);
23155
23320
  if (bytes.length > 131072) throw new Error();
23156
23321
  trust = JSON.parse(new TextDecoder("utf8", { fatal: true }).decode(bytes));
23157
23322
  } catch {
@@ -23161,14 +23326,14 @@ function workloadTrustState(options) {
23161
23326
  if (trust.revision !== options.expectedRevision) throw new Error("Application identity trust revision changed; review again");
23162
23327
  if (options.action === "initialize") {
23163
23328
  if (!options.confirmed) throw new Error("Initialization requires explicit --confirm after reviewing the plan");
23164
- initializeApplicationAuthState(trust, { expectedScope: options.expectedScope, stateFile: resolve21(options.stateFile) });
23329
+ initializeApplicationAuthState(trust, { expectedScope: options.expectedScope, stateFile: resolve22(options.stateFile) });
23165
23330
  }
23166
- return { schemaVersion: 1, status: options.action === "plan" ? "planned" : "initialized", scope: options.expectedScope, revision: trust.revision, validUntil: trust.validUntil, stateFile: resolve21(options.stateFile), requiresPrivatePersistentDirectory: true, recoveryAutomatic: false, productionChanges: false };
23331
+ return { schemaVersion: 1, status: options.action === "plan" ? "planned" : "initialized", scope: options.expectedScope, revision: trust.revision, validUntil: trust.validUntil, stateFile: resolve22(options.stateFile), requiresPrivatePersistentDirectory: true, recoveryAutomatic: false, productionChanges: false };
23167
23332
  }
23168
23333
 
23169
23334
  // src/scaffold.ts
23170
- import { existsSync as existsSync13, lstatSync as lstatSync18, mkdirSync as mkdirSync9, readFileSync as readFileSync22, readdirSync as readdirSync8, realpathSync as realpathSync7, writeFileSync as writeFileSync13 } from "node:fs";
23171
- import { dirname as dirname16, join as join16, relative as relative10, resolve as resolve22 } from "node:path";
23335
+ import { existsSync as existsSync13, lstatSync as lstatSync18, mkdirSync as mkdirSync9, readFileSync as readFileSync23, readdirSync as readdirSync8, realpathSync as realpathSync7, writeFileSync as writeFileSync14 } from "node:fs";
23336
+ import { dirname as dirname16, join as join17, relative as relative10, resolve as resolve23 } from "node:path";
23172
23337
  function json2(value) {
23173
23338
  return JSON.stringify(value, null, 2) + "\n";
23174
23339
  }
@@ -23346,21 +23511,21 @@ provider-readiness claim, cloud deployment or browser authentication is implied.
23346
23511
  }
23347
23512
  function scaffoldFullStack(options) {
23348
23513
  const files = fullStackTemplate(options.appId, options.name);
23349
- const root = resolve22(options.root ?? process.cwd());
23514
+ const root = resolve23(options.root ?? process.cwd());
23350
23515
  if (!existsSync13(root) || !lstatSync18(root).isDirectory() || lstatSync18(root).isSymbolicLink()) throw new Error("Scaffold destination must be an existing non-linked directory");
23351
23516
  const allowed = /* @__PURE__ */ new Set([...Object.keys(files).map((filename2) => filename2.split("/")[0]), ".git", "node_modules", "package-lock.json", ".backify"]);
23352
23517
  if (readdirSync8(root).some((filename2) => !allowed.has(filename2))) throw new Error("Scaffolding requires an empty folder or an unchanged generated starter");
23353
23518
  const canonicalRoot = realpathSync7(root);
23354
23519
  const pending = [];
23355
23520
  for (const [filename2, content] of Object.entries(files)) {
23356
- const destination = join16(root, filename2);
23521
+ const destination = join17(root, filename2);
23357
23522
  let current = destination;
23358
23523
  while (current !== root) {
23359
23524
  try {
23360
23525
  const stat = lstatSync18(current);
23361
23526
  if (stat.isSymbolicLink() || current !== destination && !stat.isDirectory()) throw new Error("Scaffolding refuses linked or invalid output paths: " + filename2);
23362
23527
  if (relative10(canonicalRoot, realpathSync7(current)).startsWith("..")) throw new Error("Scaffold output must remain inside its directory");
23363
- if (current === destination && (!stat.isFile() || readFileSync22(current, "utf8") !== content)) throw new Error("Scaffolding refuses to overwrite existing content: " + filename2);
23528
+ if (current === destination && (!stat.isFile() || readFileSync23(current, "utf8") !== content)) throw new Error("Scaffolding refuses to overwrite existing content: " + filename2);
23364
23529
  } catch (error) {
23365
23530
  if (!(error instanceof Error) || !("code" in error) || error.code !== "ENOENT") throw error;
23366
23531
  if (current === destination) pending.push(filename2);
@@ -23369,9 +23534,9 @@ function scaffoldFullStack(options) {
23369
23534
  }
23370
23535
  }
23371
23536
  for (const filename2 of pending) {
23372
- const destination = join16(root, filename2);
23537
+ const destination = join17(root, filename2);
23373
23538
  mkdirSync9(dirname16(destination), { recursive: true });
23374
- writeFileSync13(destination, files[filename2], { flag: "wx" });
23539
+ writeFileSync14(destination, files[filename2], { flag: "wx" });
23375
23540
  }
23376
23541
  return { template: "react-vite-hono", created: pending, unchanged: Object.keys(files).length - pending.length, installed: false, deployed: false };
23377
23542
  }
@@ -23415,16 +23580,16 @@ function localInspectionCommand(args2) {
23415
23580
  }
23416
23581
 
23417
23582
  // src/index.ts
23418
- import { readFileSync as readFileSync23, existsSync as existsSync14, rmSync as rmSync3 } from "node:fs";
23583
+ import { readFileSync as readFileSync24, existsSync as existsSync14, rmSync as rmSync3 } from "node:fs";
23419
23584
  import { homedir as homedir2 } from "node:os";
23420
- import { join as join17 } from "node:path";
23585
+ import { join as join18 } from "node:path";
23421
23586
  import { spawn as spawn5 } from "node:child_process";
23422
- var configPath = join17(homedir2(), ".backify.json");
23423
- var userConfig = existsSync14(configPath) ? JSON.parse(readFileSync23(configPath, "utf8")) : {};
23587
+ var configPath = join18(homedir2(), ".backify.json");
23588
+ var userConfig = existsSync14(configPath) ? JSON.parse(readFileSync24(configPath, "utf8")) : {};
23424
23589
  var [command2, ...args] = process.argv.slice(2);
23425
23590
  async function call(path, init) {
23426
23591
  let appId = option("--app");
23427
- if (!appId && existsSync14(join17(process.cwd(), "backify.json"))) appId = projectApplication();
23592
+ if (!appId && existsSync14(join18(process.cwd(), "backify.json"))) appId = projectApplication();
23428
23593
  const session = appId ? userConfig.sessions?.[sessionKey(appId)] : void 0;
23429
23594
  const credential = session ?? { token: userConfig.token ?? "", organizationId: userConfig.organizationId ?? "", apiUrl: process.env.BACKIFY_API_URL ?? userConfig.apiUrl ?? "https://api.backify.dev/api" };
23430
23595
  return (appId ? applicationClient(credential, appId) : apiClient(credential))(path, init);
@@ -23563,7 +23728,7 @@ async function main() {
23563
23728
  const name2 = option("--name");
23564
23729
  if (!name2) throw new Error("Specify --name <job>");
23565
23730
  const payload = option("--payload");
23566
- console.log(JSON.stringify(await localRequest("/v1/jobs/run", { name: name2, payload: payload ? JSON.parse(readFileSync23(payload, "utf8")) : null }), null, 2));
23731
+ console.log(JSON.stringify(await localRequest("/v1/jobs/run", { name: name2, payload: payload ? JSON.parse(readFileSync24(payload, "utf8")) : null }), null, 2));
23567
23732
  } else if (["retry", "cancel"].includes(args[0])) {
23568
23733
  const id = option("--id");
23569
23734
  if (!id) throw new Error("Specify --id <run>");
@@ -23586,7 +23751,7 @@ async function main() {
23586
23751
  const environmentId = option("--environment");
23587
23752
  const packagePath = option("--package");
23588
23753
  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.");
23589
- await deployFunctions(call, appId, applicationGuid(environmentId), new Uint8Array(readFileSync23(packagePath)), { progress: (message) => console.log(message) });
23754
+ await deployFunctions(call, appId, applicationGuid(environmentId), new Uint8Array(readFileSync24(packagePath)), { progress: (message) => console.log(message) });
23590
23755
  console.log("Functions deployed.");
23591
23756
  } else throw new Error("Use backify functions package or backify functions deploy");
23592
23757
  break;
@@ -23605,6 +23770,12 @@ async function main() {
23605
23770
  console.log("Backify instructions synchronized to version " + INSTRUCTION_VERSION);
23606
23771
  break;
23607
23772
  case "doctor": {
23773
+ if (args.includes("--environment")) {
23774
+ const result2 = await diagnoseEnvironment(process.cwd(), { network: args.includes("--network"), capability: option("--capability") });
23775
+ console.log(JSON.stringify(result2, null, 2));
23776
+ if (!result2.valid) process.exitCode = 1;
23777
+ break;
23778
+ }
23608
23779
  const result = doctor(process.cwd(), option("--agent"), option("--instruction-file"));
23609
23780
  console.log(JSON.stringify(result, null, 2));
23610
23781
  if (!result.valid) process.exitCode = 1;
@@ -23615,7 +23786,7 @@ async function main() {
23615
23786
  userConfig.token = args[0];
23616
23787
  userConfig.organizationId = args[1] ?? userConfig.organizationId;
23617
23788
  saveUserConfig(configPath, userConfig);
23618
- } else await browserLogin(option("--app") ?? (existsSync14(join17(process.cwd(), "backify.json")) ? projectApplication() : void 0), option("--organization"));
23789
+ } else await browserLogin(option("--app") ?? (existsSync14(join18(process.cwd(), "backify.json")) ? projectApplication() : void 0), option("--organization"));
23619
23790
  console.log("Logged in to Backify");
23620
23791
  break;
23621
23792
  case "logout":
@@ -23654,7 +23825,7 @@ async function main() {
23654
23825
  userConfig.sessions[key] ??= session;
23655
23826
  saveUserConfig(configPath, userConfig);
23656
23827
  if (args.includes("--clone")) await cloneProject(client, appId);
23657
- else if (existsSync14(join17(process.cwd(), ".git"))) {
23828
+ else if (existsSync14(join18(process.cwd(), ".git"))) {
23658
23829
  const update = await pullProject(client, appId);
23659
23830
  console.log(JSON.stringify(update, null, 2));
23660
23831
  if (update.status === "blocked") throw new Error(update.reason);
@@ -23700,13 +23871,13 @@ async function main() {
23700
23871
  break;
23701
23872
  }
23702
23873
  case "prompt": {
23703
- 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>]. Only user text, filenames, and AI context metadata are sent.");
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.");
23704
23875
  const id = option("--id");
23705
23876
  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.");
23706
23877
  const filenames = attachmentNames(args.flatMap((value, index) => value === "--filename" ? [args[index + 1] ?? ""] : []));
23707
23878
  const metadata = promptMetadata(args);
23708
23879
  const text3 = await readPrompt(process.stdin);
23709
- console.log(JSON.stringify(await call("/apps/" + applicationGuid(projectApplication()) + "/prompts", { method: "POST", body: JSON.stringify({ clientPromptId: id, text: text3, filenames, ...metadata }) })));
23880
+ console.log(JSON.stringify(await call("/apps/" + applicationGuid(projectApplication()) + "/prompts", { method: "POST", body: JSON.stringify({ clientPromptId: id, text: text3, filenames, ...promptContext(), ...metadata }) })));
23710
23881
  break;
23711
23882
  }
23712
23883
  case "runtime": {
@@ -23717,7 +23888,7 @@ async function main() {
23717
23888
  } else if (args[0] === "install") {
23718
23889
  const version = option("--version"), sha256 = option("--sha256");
23719
23890
  if (!version || !sha256) throw new Error("Use backify runtime install --version vX.Y.Z --sha256 <reviewed-digest> [--archive <local-zip>]");
23720
- const bytes = option("--archive") ? readFileSync23(option("--archive")) : await downloadLocalRuntime(version);
23891
+ const bytes = option("--archive") ? readFileSync24(option("--archive")) : await downloadLocalRuntime(version);
23721
23892
  console.log(JSON.stringify(installLocalRuntime(bytes, { version, sha256 }), null, 2));
23722
23893
  } else throw new Error("Use backify runtime install or backify runtime doctor");
23723
23894
  break;
@@ -23732,7 +23903,7 @@ async function main() {
23732
23903
  case "request": {
23733
23904
  const workspaceId = option("--workspace"), name2 = option("--name"), slug = option("--slug"), description = option("--description"), configurationFile = option("--configuration");
23734
23905
  if (!workspaceId || !name2 || !slug || !description) throw new Error("Use backify request --workspace <id> --name <name> --slug <slug> --description <purpose> [--configuration <json-file>]");
23735
- const configuration = configurationFile ? JSON.parse(readFileSync23(configurationFile, "utf8")) : void 0;
23906
+ const configuration = configurationFile ? JSON.parse(readFileSync24(configurationFile, "utf8")) : void 0;
23736
23907
  console.log(await call("/apps/requests", { method: "POST", body: JSON.stringify({ workspaceId, name: name2, slug, description, configuration }) }));
23737
23908
  break;
23738
23909
  }
@@ -23750,7 +23921,7 @@ async function main() {
23750
23921
  else if (args[0] === "test") {
23751
23922
  const name2 = option("--name"), payload = option("--payload");
23752
23923
  if (!name2 || !payload) throw new Error("Specify --name and --payload <json-file>. Never include secrets in event payloads.");
23753
- console.log(JSON.stringify(await call(path + "/test", { method: "POST", body: JSON.stringify({ name: name2, payload: JSON.parse(readFileSync23(payload, "utf8")), idempotencyKey: option("--idempotency-key") }) }), null, 2));
23924
+ console.log(JSON.stringify(await call(path + "/test", { method: "POST", body: JSON.stringify({ name: name2, payload: JSON.parse(readFileSync24(payload, "utf8")), idempotencyKey: option("--idempotency-key") }) }), null, 2));
23754
23925
  } else throw new Error("Use backify events environments|inspect|test");
23755
23926
  break;
23756
23927
  }