@backifydev/cli 0.3.10 → 0.3.12

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 +12 -2
  2. package/dist/index.js +651 -452
  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: 10
17770
+ Versioned guide: https://agent.backify.dev/v10/delivery.md
17771
+
17772
+ ## Environment and documentation prerequisites
17773
+
17774
+ Before installation or connection, read https://agent.backify.dev/v10 for execution capability checks, required endpoints (including https://docs.backify.dev), native permission requests, verified retries and fallback guidance. Follow the current tool's supported approval mechanism; never bypass restrictions. Read relevant capability documentation before implementation. Local validation must not depend on cloud deployment.
17775
+
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 in project files, Git, prompt history, or logs. Record the user-supplied setup request in prompt history only after redacting credentials; do not drop the request. The CLI stores an application-scoped session outside the repository. If CLI access expires, use the browser reauthentication workflow below, never another setup prompt. A fresh pairing code is needed only if initial pairing expired or was consumed.
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,13 +17791,13 @@ 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/v10 for instruction version 10; use the guide matching backify.json in an existing application. Do not silently upgrade its managed instruction version or overwrite instructions outside the managed block.
17884
17795
 
17885
17796
  Run the following to discover the connected hosting target, repository, branch, reports, releases, and deployment failures:
17886
17797
 
17887
17798
  npx @backifydev/cli@latest status
17888
17799
 
17889
- Connection and initialization may proceed without application requirements. Then ask what to build if none were supplied; never invent requirements or record this setup text as a user requirement.
17800
+ Connection and initialization may proceed without application requirements. Then ask what to build if none were supplied; never invent requirements or treat setup text as an application requirement. Record user-supplied setup requests in prompt history as other after redacting credentials.
17890
17801
 
17891
17802
  ## Reauthenticate CLI access
17892
17803
 
@@ -17894,11 +17805,13 @@ If CLI authentication expires or is rejected, ask the user to reauthenticate. Ru
17894
17805
 
17895
17806
  ## Record each user request
17896
17807
 
17897
- For EVERY user request to build or modify this application, including the initial requirements supplied alongside or after setup, record only the user's own requirement text before changing application code. Submit the text through standard input to:
17808
+ For EVERY user request associated with this application, including the initial requirements supplied alongside or after setup, record the user's own text before acting on it. Include setup, building, deployment, launch, questions, application bug fixes, and Backify platform troubleshooting; never exclude a request because it does not change application code. If recording access is not yet available, retain the request in the current conversation and record it in order as soon as authenticated application access is available, without saving credentials to project files. Submit the text through standard input to:
17898
17809
 
17899
- npx @backifydev/cli@latest prompt record --stdin --id <new-UUID> [--filename <basename> ...] [--model <model>] [--ai-tool <tool>] [--access-level <access>]
17810
+ npx @backifydev/cli@latest prompt record --stdin --id <new-UUID> [--filename <basename> ...] --type <build|deploy|fixing|other> [--model <full-model-name-and-version>] [--ai-tool <tool>] [--access-level <access>] [--sdk-version <installed-version>]
17900
17811
 
17901
- Record requests separately and in order. Generate a new UUID per request and reuse that UUID on retries. Add one --filename argument per attachment, using only its basename. Never send attachment bodies, extracted text, images, full paths, assistant responses, tool output, secrets, connection commands, or this setup/pairing block. Filename arguments are metadata only; never read attachment bodies to submit them. If recording fails, retry or report the blocker; never silently claim a request was recorded. Record the model, AI coding tool, and effective access for each request with --model, --ai-tool, and --access-level whenever known. Access is a short description of the tool\u2019s actual filesystem, network, and approval permissions at the time of the request, not its Backify role. Use only exposed session information; never guess unknown values or inspect credentials to discover them. Omit unknown fields; older or incomplete records display \u201CNot recorded\u201D. These values are self-reported metadata, not verified authorization. Reuse the same metadata on retries. Model and tool names are limited to 200 characters each; access descriptions to 500. Never include secrets, tokens, full paths, or configuration file contents.
17812
+ Choose the type from the request's primary intent: build for application features, changes, and application bug fixes; deploy for shipping, deployment, or launching the application; fixing only for troubleshooting Backify platform, SDK, CLI, connection, or hosting issues affecting the user, not application-code bugs; other for setup, questions, or requests outside those categories. Never drop an unclassified request; use other. These are request types, not execution or deployment statuses. Reuse the same type on retries. Older untyped records remain visible as Not recorded.
17813
+
17814
+ Record requests separately and in order. Generate a new UUID per request and reuse that UUID on retries. Add one --filename argument per attachment, using only its basename. Never send attachment bodies, extracted text, images, full paths, assistant responses, tool output, or secrets. Do not exclude user-supplied setup or connection requests: replace credentials with [REDACTED] and record the remaining request, not assistant-generated instructions. The CLI and API also redact recognized Backify session tokens and pairing codes; redact all other secrets before submission. Filename arguments are metadata only; never read attachment bodies to submit them. If recording fails, retry or report the blocker; never silently claim a request was recorded. Record the model, AI coding tool, and effective access for each request with --model, --ai-tool, and --access-level whenever known. Access is a short description of the tool\u2019s actual filesystem, network, and approval permissions at the time of the request, not its Backify role. Use only exposed session information; never guess unknown values or inspect credentials to discover them. Omit unknown fields; older or incomplete records display \u201CNot recorded\u201D. These values are self-reported metadata, not verified authorization. Reuse the same metadata on retries. Model and tool names are limited to 200 characters each; access descriptions to 500. Never include secrets, tokens, full paths, or configuration file contents. Include the exposed model family and version, for example gpt-6-luna or gpt-6.1-sol, rather than only the tool name. Separate filesystem, network, and approval access descriptions with semicolons so each appears as a separate badge. The CLI automatically records the installed @backifydev/sdk version from the project or its hoisted node_modules, never the dependency range. Use --sdk-version to preserve the original installed version on retries or when auto-detection is unavailable; SDK versions are limited to 100 characters. Unknown SDK and model versions remain \u201CNot recorded\u201D; never guess them.
17902
17815
 
17903
17816
  ## Keep local source current
17904
17817
 
@@ -17920,11 +17833,13 @@ Do not claim unsupported hosted server functions or SDK execution paths work. Re
17920
17833
 
17921
17834
  ## Local development before delivery
17922
17835
 
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.
17836
+ 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.
17837
+
17838
+ Start the application, wait for readiness, request the actual local application URL, and verify a representative user flow before shipping. Document safe seed data and local test identities where needed. A failed connection or required setup check must stop implementation, including local fallback. After setup passes, later preview approval or deployment failure must not prevent safe local testing; report those blockers separately without bypassing authorization. If requirements are missing after successful setup, ask the required final question without creating a minimal runnable shell. Never claim local readiness from a build or management-dashboard response alone.
17924
17839
 
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.
17840
+ ## Verify, push, and deploy to preview
17926
17841
 
17927
- ## Verify, push, and publish
17842
+ Plain deployment requests are preview-only. Requests such as "Now deploy", "deploy", "ship", "launch", or "merge and retry" do not authorize production. Approval to merge a remote commit, push source, retry deployment, or run checks applies only to that action and preserves the preview target. Never infer production intent from permissive policy, a healthy preview, or an existing production URL.
17928
17843
 
17929
17844
  Run:
17930
17845
 
@@ -17934,19 +17849,23 @@ Fix relevant failures, then commit only application changes for this request usi
17934
17849
 
17935
17850
  npx @backifydev/cli@latest ship
17936
17851
 
17937
- The CLI verifies the repository and branch, runs checks, pushes committed source using a short-lived repository-scoped credential, waits for the exact source's healthy preview, and publishes through existing Backify permissions and policy. It never stages or commits files, force-pushes, changes hosting, fabricates preview testing, or bypasses approval. Use --preview-only only when the user requests a preview.
17852
+ The CLI verifies the repository and branch, runs checks, pushes committed source using a short-lived repository-scoped credential, waits for the exact source's healthy preview, and returns the preview URL without requesting production publication. It never stages or commits files, force-pushes, changes hosting, fabricates preview testing, or bypasses approval. The legacy --preview-only flag is optional; preview is already the default.
17853
+
17854
+ Production requires an explicit user request to deploy to production, such as "deploy to production", "publish to production", or "promote this preview to production". Only for that request run:
17855
+
17856
+ npx @backifydev/cli@latest ship --production-deploy
17938
17857
 
17939
- If testing or approval is required, return the preview URL and explain the remaining action. Otherwise return the verified production URL and actual check results only after healthy activation. Inspect failures with the status command, fix them, and retry without asking the user to perform routine deployment steps. Never invent a successful check or deployment.
17858
+ Production publication still follows existing Backify permissions, testing, and approval policy. If testing or approval is required, return the preview URL and explain the remaining action; never fabricate testing or bypass approval. Otherwise return the verified production URL and actual check results only after healthy activation. For a plain deployment request, stop at the verified healthy preview even when production testing and approval are not required. Inspect failures with the status command, fix them, and retry the same target without asking the user to perform routine deployment steps. Never invent a successful check or deployment.
17940
17859
 
17941
17860
  ## User-facing handoff
17942
17861
 
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.
17862
+ 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
17863
 
17945
17864
  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
17865
 
17947
17866
  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
17867
 
17949
- If application requirements are missing after setup, finish the response with this exact question as its final line, without any text after it:
17868
+ 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
17869
 
17951
17870
  What should the application do, and what should it look like?
17952
17871
 
@@ -17954,7 +17873,7 @@ These instructions are an explicit agent workflow, not a universal chat intercep
17954
17873
  `;
17955
17874
 
17956
17875
  // ../platform/dist/index.js
17957
- var INSTRUCTION_VERSION = 5;
17876
+ var INSTRUCTION_VERSION = 10;
17958
17877
  var SDK_PACKAGE = "@backifydev/sdk";
17959
17878
  var DOCS_URL = "https://docs.backify.dev";
17960
17879
  var MAIL_LIMITS = Object.freeze({
@@ -17984,7 +17903,7 @@ var CAPABILITIES = [
17984
17903
  capability("secrets", "secrets", "Server-side secret retrieval", true),
17985
17904
  capability("integrations", "integrations", "Approved, versioned API contracts and environment-scoped operation grants", true),
17986
17905
  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."),
17906
+ 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
17907
  capability("audit", "audit", "Structured audit records"),
17989
17908
  capability("logs", "logs", "Structured application logging"),
17990
17909
  capability("config", "config", "Non-secret application configuration")
@@ -18008,6 +17927,8 @@ Use \`@backifydev/sdk\` for platform capabilities. Do not directly integrate or
18008
17927
 
18009
17928
  ## SDK capability map
18010
17929
 
17930
+ 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.
17931
+
18011
17932
  - Authentication and authorization: \`auth\`.
18012
17933
  - Persistent data and files: \`db\` and \`storage\`.
18013
17934
  - Server functions: \`defineFunction\`; background work and schedules: \`jobs\` and \`jobs.schedule\`.
@@ -18030,7 +17951,7 @@ Run relevant tests, typechecking, lint, and builds using the repository's script
18030
17951
 
18031
17952
  ## Connected application delivery
18032
17953
 
18033
- For connected applications, follow \`BACKIFY.md\` and https://agent.backify.dev/v${INSTRUCTION_VERSION}/delivery.md before changing application code. Record every user build or modification request, including initial requirements, with attachment filenames only; never submit attachment contents or setup credentials. Verify checks and publish through the connected CLI workflow without bypassing testing, approval, or coding-tool permissions. Report only verified deployment URLs.
17954
+ For connected applications, follow \`BACKIFY.md\` and https://agent.backify.dev/v${INSTRUCTION_VERSION}/delivery.md before changing application code. Record every user build or modification request, including initial requirements, with attachment filenames only; never submit attachment contents or setup credentials. Verify checks and deploy to preview through the connected CLI workflow without bypassing testing, approval, or coding-tool permissions. Plain deployment requests are preview-only. Production requires an explicit user request to deploy to production; approval to merge, push, or retry does not authorize production. Use \`ship\` for preview and \`ship --production-deploy\` only for that explicit production request. Report only verified deployment URLs.
18034
17955
 
18035
17956
  ## Instruction maintenance
18036
17957
 
@@ -18088,39 +18009,277 @@ function validateConfig(value) {
18088
18009
  }
18089
18010
  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
18011
 
18012
+ // src/environment.ts
18013
+ function classifyEnvironmentFailure(error) {
18014
+ const value = error;
18015
+ const code = value?.code;
18016
+ if (code === "EACCES" || code === "EPERM") return "permission";
18017
+ if (code === "ENOTFOUND" || code === "EAI_AGAIN") return "dns";
18018
+ if (code && /CERT|TLS|SSL/.test(code)) return "tls";
18019
+ if (value?.name === "TimeoutError" || value?.name === "AbortError" || code === "ETIMEDOUT" || code === "UND_ERR_CONNECT_TIMEOUT") return "timeout";
18020
+ if (code === "ECONNREFUSED" || code === "ECONNRESET" || code === "ENETUNREACH" || code === "EHOSTUNREACH") return "connection";
18021
+ if (code === "ENOENT") return "missing_tool";
18022
+ if (value?.cause && value.cause !== error) return classifyEnvironmentFailure(value.cause);
18023
+ return "unknown";
18024
+ }
18025
+ function environmentRecovery(failure2) {
18026
+ switch (failure2) {
18027
+ case "permission":
18028
+ 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.";
18029
+ case "dns":
18030
+ return "Check DNS and the endpoint hostname; retry once for a temporary failure. Request network access only if policy confirms it is blocked.";
18031
+ case "tls":
18032
+ return "Check the certificate, system clock and trusted proxy configuration; never disable TLS verification.";
18033
+ case "timeout":
18034
+ case "connection":
18035
+ return "Check connectivity and exposed network policy; retry once if temporary. A timeout or connection error alone does not prove a sandbox restriction.";
18036
+ case "authentication":
18037
+ 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.";
18038
+ case "not_found":
18039
+ return "Check the documented URL and resource; HTTP 404 is not an environment restriction.";
18040
+ case "rate_limit":
18041
+ return "Respect Retry-After within the task's time budget; do not repeatedly retry.";
18042
+ case "server":
18043
+ return "Report the endpoint's HTTP 5xx; retry once if temporary and keep cloud failures separate from local work.";
18044
+ case "missing_tool":
18045
+ return "Install the missing prerequisite with authorized tools or use a terminal-enabled environment that supplies it.";
18046
+ default:
18047
+ return "Report the failed check without exposing credentials. Consult https://agent.backify.dev for diagnosis and safe fallback; do not claim verification succeeded.";
18048
+ }
18049
+ }
18050
+ function environmentEndpoints(capability2) {
18051
+ if (capability2 !== void 0 && !Object.hasOwn(CAPABILITY_REGISTRY, capability2)) throw new Error("Select a documented Backify capability name.");
18052
+ return [
18053
+ "https://agent.backify.dev/",
18054
+ "https://docs.backify.dev/",
18055
+ "https://api.backify.dev/health",
18056
+ "https://registry.npmjs.org/@backifydev%2fcli",
18057
+ "https://registry.npmjs.org/@backifydev%2fsdk",
18058
+ ...capability2 ? [CAPABILITY_REGISTRY[capability2].docs] : []
18059
+ ];
18060
+ }
18061
+ async function probeEndpoint(url, transport = fetch) {
18062
+ const response = await transport(url, { signal: AbortSignal.timeout(5e3), redirect: "error", credentials: "omit" });
18063
+ await response.body?.cancel();
18064
+ return response.status;
18065
+ }
18066
+ function workspaceProbe(root) {
18067
+ const directory2 = resolve2(root);
18068
+ const filename2 = join(directory2, ".backify-environment-" + randomUUID());
18069
+ const content = randomUUID();
18070
+ let created = false;
18071
+ try {
18072
+ writeFileSync2(filename2, content, { flag: "wx" });
18073
+ created = true;
18074
+ if (readFileSync(filename2, "utf8") !== content) throw new Error("Workspace read/write failed.");
18075
+ } finally {
18076
+ if (created) unlinkSync(filename2);
18077
+ }
18078
+ }
18079
+ async function localhostProbe() {
18080
+ const server = createServer((_request, response) => {
18081
+ response.end("backify-environment-probe");
18082
+ });
18083
+ try {
18084
+ await new Promise((accept, reject) => {
18085
+ server.once("error", reject);
18086
+ server.listen(0, "127.0.0.1", () => accept());
18087
+ });
18088
+ const address = server.address();
18089
+ if (!address || typeof address === "string") throw new Error("No loopback address.");
18090
+ const response = await fetch("http://127.0.0.1:" + address.port, { signal: AbortSignal.timeout(5e3), redirect: "error" });
18091
+ if (!response.ok || await response.text() !== "backify-environment-probe") throw new Error("Loopback verification failed.");
18092
+ } finally {
18093
+ server.closeAllConnections();
18094
+ if (server.listening) await new Promise((accept) => server.close(() => accept()));
18095
+ }
18096
+ }
18097
+ function environmentProbes(root) {
18098
+ return {
18099
+ nodeVersion: process.versions.node,
18100
+ command: (name2) => {
18101
+ const windowsNpm = name2 === "npm" && process.platform === "win32";
18102
+ const executable = windowsNpm ? process.env.ComSpec ?? "cmd.exe" : name2;
18103
+ const argumentsList = windowsNpm ? ["/d", "/s", "/c", "npm.cmd --version"] : ["--version"];
18104
+ const result = spawnSync(executable, argumentsList, { timeout: 5e3, stdio: "ignore", windowsHide: true });
18105
+ if (result.error) throw result.error;
18106
+ if (result.status !== 0) throw Object.assign(new Error("Prerequisite command failed."), { code: result.status === 127 || result.status === 9009 ? "ENOENT" : void 0 });
18107
+ },
18108
+ workspace: () => workspaceProbe(root),
18109
+ localhost: localhostProbe,
18110
+ request: probeEndpoint
18111
+ };
18112
+ }
18113
+ async function diagnoseEnvironment(root = process.cwd(), options = {}, probes = environmentProbes(root)) {
18114
+ const endpoints = environmentEndpoints(options.capability);
18115
+ const checks = [];
18116
+ const check = async (name2, required, operation) => {
18117
+ try {
18118
+ await operation();
18119
+ checks.push({ name: name2, required, status: "passed" });
18120
+ } catch (error) {
18121
+ const failure2 = classifyEnvironmentFailure(error);
18122
+ checks.push({ name: name2, required, status: "failed", failure: failure2, recovery: environmentRecovery(failure2) });
18123
+ }
18124
+ };
18125
+ 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." } });
18126
+ await check("npm", true, () => probes.command("npm"));
18127
+ await check("git", false, () => probes.command("git"));
18128
+ await check("workspace", true, probes.workspace);
18129
+ await check("localhost", true, probes.localhost);
18130
+ for (const endpoint of endpoints) {
18131
+ if (!options.network) {
18132
+ checks.push({ name: "network", endpoint, required: true, status: "unverified", recovery: "Run backify doctor --environment --network using authorized network access." });
18133
+ continue;
18134
+ }
18135
+ try {
18136
+ const httpStatus = await probes.request(endpoint);
18137
+ 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";
18138
+ checks.push({ name: "network", endpoint, required: true, httpStatus, status: failure2 ? "failed" : "passed", ...failure2 ? { failure: failure2, recovery: environmentRecovery(failure2) } : {} });
18139
+ } catch (error) {
18140
+ const failure2 = classifyEnvironmentFailure(error);
18141
+ checks.push({ name: "network", endpoint, required: true, status: "failed", failure: failure2, recovery: environmentRecovery(failure2) });
18142
+ }
18143
+ }
18144
+ 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." });
18145
+ return { schemaVersion: 1, valid: !checks.some((item) => item.required && item.status === "failed"), verified: checks.filter((item) => item.required).every((item) => item.status === "passed"), checks };
18146
+ }
18147
+
18148
+ // src/integrations.ts
18149
+ function integrationDiscoveryPath(command3, options) {
18150
+ const uuid4 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
18151
+ if (!uuid4.test(options.applicationId)) throw new Error("An application UUID is required");
18152
+ const base = "/apps/" + options.applicationId + "/integrations/connectors";
18153
+ if (command3 === "list") return base;
18154
+ if (command3 === "catalog") return "/apps/" + options.applicationId + "/integrations/catalog";
18155
+ if (!options.connectionId || !uuid4.test(options.connectionId)) throw new Error("Use --connection with an integration connection UUID");
18156
+ const connection = base + "/" + options.connectionId;
18157
+ if (command3 === "contract" || command3 === "types") return connection + "/" + command3;
18158
+ if (command3 === "describe") {
18159
+ if (!options.operationId) throw new Error("Use --operation to select an operation");
18160
+ return connection + "/operations/" + encodeURIComponent(options.operationId);
18161
+ }
18162
+ if (command3 === "search") {
18163
+ if (!Number.isInteger(options.offset ?? 0) || (options.offset ?? 0) < 0 || (options.offset ?? 0) > 500) throw new Error("Offset must be between 0 and 500");
18164
+ const query = new URLSearchParams({ query: options.query ?? "", offset: String(options.offset ?? 0), limit: "50" });
18165
+ return connection + "/operations?" + query;
18166
+ }
18167
+ throw new Error("Use backify integrations list|catalog|search|describe|contract|types");
18168
+ }
18169
+
18170
+ // src/cli-session.ts
18171
+ import { hostname, platform, release, arch } from "node:os";
18172
+
18173
+ // package.json
18174
+ var package_default = {
18175
+ name: "@backifydev/cli",
18176
+ version: "0.3.12",
18177
+ description: "Command-line setup and diagnostics for Backify applications",
18178
+ type: "module",
18179
+ bin: {
18180
+ backify: "dist/index.js"
18181
+ },
18182
+ files: [
18183
+ "dist/index.js",
18184
+ "README.md"
18185
+ ],
18186
+ scripts: {
18187
+ prebuild: "npm run build -w @backify/platform && npm run build -w @backifydev/sdk && npm run build -w @backify/analyzer",
18188
+ 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);"`,
18189
+ prepack: "npm run build",
18190
+ pretypecheck: "npm run build -w @backify/platform && npm run build -w @backifydev/sdk && npm run build -w @backify/analyzer",
18191
+ typecheck: "tsc --noEmit",
18192
+ pretest: "npm run build -w @backify/platform && npm run build -w @backifydev/sdk && npm run build -w @backify/analyzer",
18193
+ test: "vitest run"
18194
+ },
18195
+ publishConfig: {
18196
+ access: "public"
18197
+ },
18198
+ repository: {
18199
+ type: "git",
18200
+ url: "git+https://github.com/frejnorling/backify.git",
18201
+ directory: "packages/cli"
18202
+ },
18203
+ homepage: "https://agent.backify.dev/",
18204
+ license: "MIT",
18205
+ engines: {
18206
+ node: ">=20"
18207
+ },
18208
+ dependencies: {
18209
+ "@azure/functions": "^4.7.2",
18210
+ "@backifydev/sdk": "^0.1.1",
18211
+ esbuild: "^0.25.10",
18212
+ fflate: "^0.8.2",
18213
+ typescript: "^5.9.2"
18214
+ },
18215
+ devDependencies: {
18216
+ "@backify/analyzer": "*",
18217
+ "@backify/platform": "*",
18218
+ "@hono/node-server": "2.1.3",
18219
+ "@types/node": "^24.3.1",
18220
+ hono: "4.13.12",
18221
+ vitest: "^4.1.11"
18222
+ }
18223
+ };
18224
+
18225
+ // src/cli-session.ts
18226
+ function cliDevice() {
18227
+ return { deviceName: hostname(), operatingSystem: platform() + " " + release(), architecture: arch(), cliVersion: package_default.version };
18228
+ }
18229
+ var cliUserAgent = "BackifyCLI/" + package_default.version;
18230
+ async function registerCliSession(client, applicationId, apiUrl) {
18231
+ const session = await client("/apps/" + applicationId + "/developer/session", { method: "POST", body: JSON.stringify(cliDevice()) });
18232
+ return { ...session, apiUrl };
18233
+ }
18234
+
18235
+ // src/browser-auth.ts
18236
+ import { randomBytes } from "node:crypto";
18237
+ import { createServer as createServer2 } from "node:http";
18238
+
18239
+ // src/development.ts
18240
+ import { existsSync as existsSync4, readFileSync as readFileSync4, readdirSync as readdirSync2, writeFileSync as writeFileSync5, renameSync, rmSync, mkdtempSync, lstatSync as lstatSync2, cpSync } from "node:fs";
18241
+ import { dirname as dirname4, join as join4, resolve as resolve4 } from "node:path";
18242
+ import { spawnSync as spawnSync3 } from "node:child_process";
18243
+ import { randomUUID as randomUUID2 } from "node:crypto";
18244
+
18245
+ // src/setup.ts
18246
+ import { existsSync as existsSync3, readFileSync as readFileSync3, writeFileSync as writeFileSync4, mkdirSync as mkdirSync2, readdirSync, lstatSync } from "node:fs";
18247
+ import { basename, dirname as dirname3, join as join3, resolve as resolve3, isAbsolute } from "node:path";
18248
+ import { spawnSync as spawnSync2 } from "node:child_process";
18249
+
18091
18250
  // 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";
18251
+ import { existsSync as existsSync2, readFileSync as readFileSync2, writeFileSync as writeFileSync3 } from "node:fs";
18252
+ import { dirname as dirname2, join as join2, relative as relativePath } from "node:path";
18094
18253
  import { createHash } from "node:crypto";
18095
18254
  var previousGeneratedWorkflowHashes = /* @__PURE__ */ new Set(["33e962274e8493f7cbac2afbac05a4e96afeec49ee08cf2bf82f8add9081b28b", "578dfb4c771c623fd04454e8a604efd701d5563d11e11191324862369bd24718", "6eb280ae7bdb14c390011686c41400f59c023304c3015d8440b7e80aaafa1c11", "545e03a1d5b996ade179e0e60ed5c86accdadc1982c1c25efd094e34f72f47ee"]);
18096
18255
  function validateDeliveryInstructions(root) {
18097
18256
  for (const filename2 of ["BACKIFY.md", "BACKIFY-WORKFLOW.md"]) {
18098
- const path = join(root, filename2);
18257
+ const path = join2(root, filename2);
18099
18258
  if (existsSync2(path)) {
18100
- const existing = readFileSync(path, "utf8").replace(/\r\n/g, "\n");
18259
+ const existing = readFileSync2(path, "utf8").replace(/\r\n/g, "\n");
18101
18260
  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
18261
  }
18103
18262
  }
18104
18263
  }
18105
18264
  function installDeliveryInstructions(root, instructionFiles2) {
18106
18265
  validateDeliveryInstructions(root);
18107
- writeFileSync2(join(root, "BACKIFY.md"), deliveryInstructions);
18266
+ writeFileSync3(join2(root, "BACKIFY.md"), deliveryInstructions);
18108
18267
  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("\\", "/");
18268
+ const instructionPath = join2(root, relative11), content = readFileSync2(instructionPath, "utf8");
18269
+ const link = relativePath(dirname2(instructionPath), join2(root, "BACKIFY.md")).replaceAll("\\", "/");
18270
+ const legacyLink = relativePath(dirname2(instructionPath), join2(root, "BACKIFY-WORKFLOW.md")).replaceAll("\\", "/");
18112
18271
  const legacy = "For application delivery and recording each user request, follow [BACKIFY-WORKFLOW.md](" + legacyLink + ").";
18113
18272
  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");
18273
+ if (content.includes(legacy)) writeFileSync3(instructionPath, content.replace(legacy, guidance));
18274
+ else if (!content.includes("## Backify delivery")) writeFileSync3(instructionPath, content.trimEnd() + "\n\n## Backify delivery\n\n" + guidance + "\n");
18116
18275
  }
18117
18276
  }
18118
18277
 
18119
18278
  // src/setup.ts
18120
18279
  var instructionFiles = ["AGENTS.md"];
18121
- var agentInstructionFiles = { codex: "AGENTS.md", claude: "CLAUDE.md", copilot: join2(".github", "copilot-instructions.md"), gemini: "GEMINI.md" };
18280
+ var agentInstructionFiles = { codex: "AGENTS.md", claude: "CLAUDE.md", copilot: join3(".github", "copilot-instructions.md"), gemini: "GEMINI.md" };
18122
18281
  function instructionSelection(root, agent, instructionFile) {
18123
- const configPath2 = join2(root, "backify.json"), configured = existsSync3(configPath2) ? JSON.parse(readFileSync2(configPath2, "utf8")) : {};
18282
+ const configPath2 = join3(root, "backify.json"), configured = existsSync3(configPath2) ? JSON.parse(readFileSync3(configPath2, "utf8")) : {};
18124
18283
  const custom = instructionFile ?? (agent === void 0 ? configured.instructionFile : void 0);
18125
18284
  const selected = instructionFile !== void 0 ? "custom" : agent ?? configured.agent ?? "codex";
18126
18285
  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 +18288,7 @@ function instructionSelection(root, agent, instructionFile) {
18129
18288
  const normalized = filename2.replaceAll("\\", "/"), parts = normalized.split("/");
18130
18289
  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
18290
  for (let index = 1; index <= parts.length; index++) {
18132
- const entry = join2(root, ...parts.slice(0, index));
18291
+ const entry = join3(root, ...parts.slice(0, index));
18133
18292
  try {
18134
18293
  const metadata = lstatSync(entry);
18135
18294
  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 +18303,26 @@ function selectedInstructionFiles(root = process.cwd(), agent, instructionFile)
18144
18303
  }
18145
18304
  function isToolWorkspaceEntry(entry, root = process.cwd()) {
18146
18305
  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));
18306
+ 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
18307
  }
18149
18308
  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;
18309
+ 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
18310
  return "npm";
18152
18311
  }
18153
18312
  function updateInstructions(root = process.cwd(), agent, instructionFile) {
18154
18313
  const updates = selectedInstructionFiles(root, agent, instructionFile).map((relative11) => {
18155
- const path = join2(root, relative11);
18156
- return { path, content: updateManagedInstructions(existsSync3(path) ? readFileSync2(path, "utf8") : "") };
18314
+ const path = join3(root, relative11);
18315
+ return { path, content: updateManagedInstructions(existsSync3(path) ? readFileSync3(path, "utf8") : "") };
18157
18316
  });
18158
18317
  for (const { path, content } of updates) {
18159
18318
  mkdirSync2(dirname3(path), { recursive: true });
18160
- writeFileSync3(path, content);
18319
+ writeFileSync4(path, content);
18161
18320
  }
18162
18321
  }
18163
18322
  function synchronize(root = process.cwd(), agent, instructionFile) {
18164
- const path = join2(root, "backify.json");
18323
+ const path = join3(root, "backify.json");
18165
18324
  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);
18325
+ const value = JSON.parse(readFileSync3(path, "utf8")), issues = validateConfig(value);
18167
18326
  if (issues.length) throw new Error(issues.join("; "));
18168
18327
  if (value.instructionVersion > INSTRUCTION_VERSION) throw new Error("This app uses newer instructions. Install a matching or newer CLI before syncing.");
18169
18328
  const selected = instructionSelection(root, agent, instructionFile);
@@ -18173,11 +18332,11 @@ function synchronize(root = process.cwd(), agent, instructionFile) {
18173
18332
  value.agent = selected.agent;
18174
18333
  value.instructionFile = selected.instructionFile;
18175
18334
  value.instructionVersion = INSTRUCTION_VERSION;
18176
- writeFileSync3(path, JSON.stringify(value, null, 2) + "\n");
18335
+ writeFileSync4(path, JSON.stringify(value, null, 2) + "\n");
18177
18336
  }
18178
18337
  function sdkInstalled(root = process.cwd()) {
18179
18338
  try {
18180
- const pkg = JSON.parse(readFileSync2(join2(root, "package.json"), "utf8"));
18339
+ const pkg = JSON.parse(readFileSync3(join3(root, "package.json"), "utf8"));
18181
18340
  return Boolean(pkg.dependencies?.[SDK_PACKAGE] || pkg.devDependencies?.[SDK_PACKAGE]);
18182
18341
  } catch {
18183
18342
  return false;
@@ -18185,26 +18344,26 @@ function sdkInstalled(root = process.cwd()) {
18185
18344
  }
18186
18345
  function installSdk(root = process.cwd()) {
18187
18346
  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" });
18347
+ 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
18348
  if (result.status !== 0) throw new Error(`Could not install ${SDK_PACKAGE} with ${manager}`);
18190
18349
  }
18191
18350
  function ensurePackageManifest(root) {
18192
- const path = join2(root, "package.json");
18351
+ const path = join3(root, "package.json");
18193
18352
  if (existsSync3(path)) return;
18194
18353
  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
18354
  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" });
18355
+ const name2 = basename(resolve3(root)).toLowerCase().replace(/[^a-z0-9-]+/g, "-").replace(/^-+|-+$/g, "") || "backify-app";
18356
+ writeFileSync4(path, JSON.stringify({ name: name2, version: "0.0.0", private: true, type: "module" }, null, 2) + "\n", { flag: "wx" });
18198
18357
  }
18199
18358
  function initialize(appId, root = process.cwd(), install = true, agent, instructionFile) {
18200
18359
  if (!/^app_[A-Za-z0-9_-]+$/.test(appId)) throw new Error("Provide an application ID using --app app_xxxxx");
18201
18360
  const selected = instructionSelection(root, agent, instructionFile), files = selected.files;
18202
18361
  validateDeliveryInstructions(root);
18203
- for (const relative11 of files) if (existsSync3(join2(root, relative11))) updateManagedInstructions(readFileSync2(join2(root, relative11), "utf8"));
18362
+ for (const relative11 of files) if (existsSync3(join3(root, relative11))) updateManagedInstructions(readFileSync3(join3(root, relative11), "utf8"));
18204
18363
  ensurePackageManifest(root);
18205
18364
  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");
18365
+ const configPath2 = join3(root, "backify.json"), existing = existsSync3(configPath2) ? JSON.parse(readFileSync3(configPath2, "utf8")) : {};
18366
+ writeFileSync4(configPath2, JSON.stringify({ ...existing, ...createConfig(appId), agent: selected.agent, instructionFile: selected.instructionFile }, null, 2) + "\n");
18208
18367
  updateInstructions(root, selected.agent, selected.instructionFile);
18209
18368
  installDeliveryInstructions(root, files);
18210
18369
  }
@@ -18213,7 +18372,7 @@ function doctor(root = process.cwd(), agent, instructionFile) {
18213
18372
  if (!sdkInstalled(root)) issues.push(`${SDK_PACKAGE} is not installed`);
18214
18373
  let config;
18215
18374
  try {
18216
- config = JSON.parse(readFileSync2(join2(root, "backify.json"), "utf8"));
18375
+ config = JSON.parse(readFileSync3(join3(root, "backify.json"), "utf8"));
18217
18376
  issues.push(...validateConfig(config));
18218
18377
  } catch {
18219
18378
  issues.push("backify.json is missing or invalid JSON");
@@ -18226,16 +18385,16 @@ function doctor(root = process.cwd(), agent, instructionFile) {
18226
18385
  issues.push(reason instanceof Error ? reason.message : String(reason));
18227
18386
  }
18228
18387
  for (const relative11 of files) {
18229
- const path = join2(root, relative11);
18388
+ const path = join3(root, relative11);
18230
18389
  if (!existsSync3(path)) {
18231
18390
  issues.push(`${relative11} is missing`);
18232
18391
  continue;
18233
18392
  }
18234
- issues.push(...managedInstructionIssues(readFileSync2(path, "utf8")).map((issue) => `${relative11} ${issue}`));
18393
+ issues.push(...managedInstructionIssues(readFileSync3(path, "utf8")).map((issue) => `${relative11} ${issue}`));
18235
18394
  }
18236
18395
  let version = "unknown";
18237
18396
  try {
18238
- const pkg = JSON.parse(readFileSync2(join2(root, "package.json"), "utf8"));
18397
+ const pkg = JSON.parse(readFileSync3(join3(root, "package.json"), "utf8"));
18239
18398
  version = pkg.dependencies?.[SDK_PACKAGE] ?? pkg.devDependencies?.[SDK_PACKAGE] ?? "missing";
18240
18399
  } catch {
18241
18400
  }
@@ -18243,8 +18402,33 @@ function doctor(root = process.cwd(), agent, instructionFile) {
18243
18402
  }
18244
18403
 
18245
18404
  // src/development.ts
18405
+ function promptContext(root = process.cwd()) {
18406
+ let commitSha = null;
18407
+ try {
18408
+ commitSha = git(["rev-parse", "HEAD"], root);
18409
+ } catch {
18410
+ }
18411
+ return { device: cliDevice(), commitSha, sdkVersion: installedSdkVersion(root) };
18412
+ }
18413
+ function installedSdkVersion(root) {
18414
+ let directory2 = resolve4(root);
18415
+ while (true) {
18416
+ const manifest = join4(directory2, "node_modules", "@backifydev", "sdk", "package.json");
18417
+ if (existsSync4(manifest)) {
18418
+ try {
18419
+ const sdk = JSON.parse(readFileSync4(manifest, "utf8"));
18420
+ return sdk.name === "@backifydev/sdk" && typeof sdk.version === "string" && /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/.test(sdk.version) ? sdk.version : null;
18421
+ } catch {
18422
+ return null;
18423
+ }
18424
+ }
18425
+ const parent = dirname4(directory2);
18426
+ if (parent === directory2) return null;
18427
+ directory2 = parent;
18428
+ }
18429
+ }
18246
18430
  function promptMetadata(args2) {
18247
- const fields5 = [["--model", "model", 200], ["--ai-tool", "aiTool", 200], ["--access-level", "accessLevel", 500]];
18431
+ const fields5 = [["--model", "model", 200], ["--ai-tool", "aiTool", 200], ["--access-level", "accessLevel", 500], ["--sdk-version", "sdkVersion", 100], ["--type", "promptType", 20]];
18248
18432
  const metadata = {};
18249
18433
  for (const [flag, field, maxLength] of fields5) {
18250
18434
  const index = args2.indexOf(flag);
@@ -18254,6 +18438,16 @@ function promptMetadata(args2) {
18254
18438
  throw new Error(`Provide ${flag} with a nonempty value of at most ${maxLength} characters without control characters or credentials.`);
18255
18439
  metadata[field] = value;
18256
18440
  }
18441
+ if (metadata.promptType !== void 0) {
18442
+ metadata.promptType = metadata.promptType.toLowerCase();
18443
+ if (!["build", "deploy", "fixing", "other"].includes(metadata.promptType)) throw new Error("Use --type build, deploy, fixing, or other.");
18444
+ }
18445
+ const commitIndex = args2.indexOf("--commit-sha");
18446
+ if (commitIndex >= 0) {
18447
+ const value = args2[commitIndex + 1];
18448
+ 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.");
18449
+ metadata.commitSha = value;
18450
+ }
18257
18451
  return metadata;
18258
18452
  }
18259
18453
  function applicationGuid(appId) {
@@ -18264,8 +18458,8 @@ function applicationGuid(appId) {
18264
18458
  return [value.slice(0, 8), value.slice(8, 12), value.slice(12, 16), value.slice(16, 20), value.slice(20)].join("-");
18265
18459
  }
18266
18460
  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;
18461
+ if (!existsSync4(join4(root, "backify.json"))) throw new Error("Run backify connect --app <application-id>, then backify init.");
18462
+ return JSON.parse(readFileSync4(join4(root, "backify.json"), "utf8")).appId;
18269
18463
  }
18270
18464
  function apiAddress(value) {
18271
18465
  const address = new URL(value);
@@ -18298,13 +18492,13 @@ function apiClient(session, transport = fetch) {
18298
18492
  };
18299
18493
  }
18300
18494
  function saveUserConfig(path, config) {
18301
- const temporary = path + "." + randomUUID() + ".tmp";
18495
+ const temporary = path + "." + randomUUID2() + ".tmp";
18302
18496
  try {
18303
- writeFileSync4(temporary, JSON.stringify(config, null, 2) + "\n", { mode: 384, flag: "wx" });
18497
+ writeFileSync5(temporary, JSON.stringify(config, null, 2) + "\n", { mode: 384, flag: "wx" });
18304
18498
  if (process.platform === "win32") {
18305
18499
  const account = [process.env.USERDOMAIN, process.env.USERNAME].filter(Boolean).join("\\");
18306
18500
  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" });
18501
+ const secured = spawnSync3("icacls", [temporary, "/inheritance:r", "/grant:r", account + ":(F)"], { windowsHide: true, encoding: "utf8" });
18308
18502
  if (secured.status !== 0) throw new Error("Could not restrict CLI credential file permissions.");
18309
18503
  }
18310
18504
  renameSync(temporary, path);
@@ -18318,7 +18512,7 @@ function repositoryName(remote) {
18318
18512
  return match[1].toLowerCase();
18319
18513
  }
18320
18514
  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 });
18515
+ const result = spawnSync3("git", args2, { cwd: root, env: environment, encoding: "utf8", windowsHide: true, maxBuffer: 2 * 1024 * 1024 });
18322
18516
  if (result.status !== 0) throw new Error("Git " + args2[0] + " failed. Check repository access, branch protection, and local changes.");
18323
18517
  return result.stdout.trim();
18324
18518
  }
@@ -18328,7 +18522,7 @@ function gitEnvironment(repository, token) {
18328
18522
  }
18329
18523
  function validateCloneMerge(source, target) {
18330
18524
  for (const entry of readdirSync2(source, { withFileTypes: true })) {
18331
- const destination = join3(target, entry.name);
18525
+ const destination = join4(target, entry.name);
18332
18526
  let existing;
18333
18527
  try {
18334
18528
  existing = lstatSync2(destination);
@@ -18336,7 +18530,7 @@ function validateCloneMerge(source, target) {
18336
18530
  if (reason.code === "ENOENT") continue;
18337
18531
  throw reason;
18338
18532
  }
18339
- if (entry.isDirectory() && existing.isDirectory() && !existing.isSymbolicLink()) validateCloneMerge(join3(source, entry.name), destination);
18533
+ if (entry.isDirectory() && existing.isDirectory() && !existing.isSymbolicLink()) validateCloneMerge(join4(source, entry.name), destination);
18340
18534
  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
18535
  }
18342
18536
  }
@@ -18346,22 +18540,22 @@ async function cloneProject(call2, appId, root = process.cwd()) {
18346
18540
  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
18541
  const credential = await call2("/apps/" + applicationGuid(appId) + "/developer/git-credential", { method: "POST" });
18348
18542
  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-"));
18543
+ const staging = mkdtempSync(join4(dirname4(resolve4(root)), ".backify-clone-"));
18350
18544
  try {
18351
18545
  git(["clone", "--single-branch", "--branch", status.branch, "--", "https://github.com/" + status.repository + ".git", "."], staging, gitEnvironment(status.repository, credential.token));
18352
18546
  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 });
18547
+ for (const entry of readdirSync2(staging)) cpSync(join4(staging, entry), join4(root, entry), { recursive: true, force: false, errorOnExist: true, dereference: false });
18354
18548
  } 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.");
18549
+ 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
18550
  rmSync(staging, { recursive: true, force: true });
18357
18551
  }
18358
18552
  }
18359
18553
  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.");
18554
+ if (existsSync4(join4(root, "backify.json")) && applicationGuid(projectApplication(root)) !== applicationGuid(appId)) throw new Error("Local application ID does not match the connected application.");
18361
18555
  const prefix = "/apps/" + applicationGuid(appId);
18362
18556
  const status = await call2(prefix + "/developer");
18363
18557
  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.");
18558
+ if (resolve4(git(["rev-parse", "--show-toplevel"], root)) !== resolve4(root)) throw new Error("Run pull from the connected repository root.");
18365
18559
  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
18560
  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
18561
  git(["check-ref-format", "--branch", status.branch], root);
@@ -18389,8 +18583,7 @@ async function readPrompt(input) {
18389
18583
  }
18390
18584
  const text3 = Buffer.concat(chunks).toString("utf8");
18391
18585
  if (!text3.trim() || text3.length > 32e3) throw new Error("Provide between 1 and 32000 characters of user prompt text.");
18392
- if (/\bbfcli_[0-9a-f]{64}\b|--pair\s+[0-9a-f]{64}/i.test(text3)) throw new Error("Do not record setup prompts or Backify credentials.");
18393
- return text3;
18586
+ return text3.replace(/bfcli_[0-9a-f]{64}/gi, "[REDACTED]").replace(/(--pair(?:\s+|=)["']?|\bPair:\s*)[0-9a-f]{64}/gi, "$1[REDACTED]");
18394
18587
  }
18395
18588
  function attachmentNames(values) {
18396
18589
  if (values.length > 50) throw new Error("At most 50 attachment filenames are allowed.");
@@ -18401,7 +18594,7 @@ function attachmentNames(values) {
18401
18594
  }))];
18402
18595
  }
18403
18596
  function localReport(runChecks, root = process.cwd()) {
18404
- const pkg = JSON.parse(readFileSync3(join3(root, "package.json"), "utf8"));
18597
+ const pkg = JSON.parse(readFileSync4(join4(root, "package.json"), "utf8"));
18405
18598
  const dependencies = { ...pkg.devDependencies, ...pkg.dependencies };
18406
18599
  const framework = ["next", "vite", "astro", "@sveltejs/kit", "nuxt", "react", "express"].find((name2) => dependencies[name2]) ?? "unknown";
18407
18600
  const setup = doctor(root);
@@ -18409,7 +18602,7 @@ function localReport(runChecks, root = process.cwd()) {
18409
18602
  const manager = detectPackageManager(root);
18410
18603
  for (const name2 of ["typecheck", "lint", "test", "build"]) {
18411
18604
  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;
18605
+ 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
18606
  checks.push({ name: name2, status: result ? result.status === 0 ? "passed" : "failed" : "not-run" });
18414
18607
  }
18415
18608
  let branch = null, commitSha = null, dirty = true;
@@ -18419,8 +18612,8 @@ function localReport(runChecks, root = process.cwd()) {
18419
18612
  dirty = Boolean(git(["status", "--porcelain"], root));
18420
18613
  } catch {
18421
18614
  }
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 };
18615
+ const outputDirectory = ["dist", "build", "out", "."].find((directory2) => existsSync4(join4(root, directory2, "index.html"))) ?? null;
18616
+ 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
18617
  }
18425
18618
  function matchesSource(release2, commit) {
18426
18619
  return release2?.commitSha === commit || release2?.sourceCommitSha === commit;
@@ -18442,7 +18635,7 @@ function pushSource(appId, commit, branch, destination, root, environment) {
18442
18635
  }
18443
18636
  async function waitForPreview(call2, prefix, commit, options = {}) {
18444
18637
  const deadline = Date.now() + (options.timeoutMs ?? 20 * 6e4);
18445
- const sleep = options.sleep ?? ((delay) => new Promise((resolve23) => setTimeout(resolve23, delay)));
18638
+ const sleep = options.sleep ?? ((delay) => new Promise((resolve24) => setTimeout(resolve24, delay)));
18446
18639
  do {
18447
18640
  const deployments = await call2(prefix + "/deployments");
18448
18641
  const matching = deployments.find((release2) => release2.kind === "preview" && matchesSource(release2, commit) && !options.previousDeploymentIds?.includes(release2.id));
@@ -18462,7 +18655,7 @@ async function ship(call2, appId, options = {}) {
18462
18655
  if (!doctor(root).valid) throw new Error("Run backify doctor and fix project setup before shipping.");
18463
18656
  if (applicationGuid(projectApplication(root)) !== applicationGuid(appId)) throw new Error("Local application ID does not match the application being shipped.");
18464
18657
  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.");
18658
+ if (resolve4(actualRoot).toLowerCase() !== resolve4(root).toLowerCase()) throw new Error("Shipping currently requires the application at the repository root.");
18466
18659
  const origin = git(["remote", "get-url", "origin"], root);
18467
18660
  const pushOrigin = git(["remote", "get-url", "--push", "origin"], root);
18468
18661
  if (repositoryName(origin) !== status.repository.toLowerCase() || repositoryName(pushOrigin) !== status.repository.toLowerCase()) throw new Error("Local repository does not match this Backify application.");
@@ -18512,7 +18705,7 @@ async function publishPreview(call2, prefix, overview, options = {}) {
18512
18705
  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
18706
  return { status: "live", url: releases.live.url };
18514
18707
  }
18515
- await new Promise((resolve23) => setTimeout(resolve23, 4e3));
18708
+ await new Promise((resolve24) => setTimeout(resolve24, 4e3));
18516
18709
  } while (Date.now() < deadline);
18517
18710
  throw new Error("Publication is still pending. Run backify status; deployment success has not been verified.");
18518
18711
  }
@@ -18525,12 +18718,12 @@ async function browserAuthenticate(options) {
18525
18718
  };
18526
18719
  let rejectSession = () => {
18527
18720
  };
18528
- const completed = new Promise((resolve23, reject) => {
18529
- resolveSession = resolve23;
18721
+ const completed = new Promise((resolve24, reject) => {
18722
+ resolveSession = resolve24;
18530
18723
  rejectSession = reject;
18531
18724
  });
18532
18725
  let accepted = false;
18533
- const server = createServer((request, response) => {
18726
+ const server = createServer2((request, response) => {
18534
18727
  if (request.headers.origin !== auth.origin) {
18535
18728
  response.writeHead(403);
18536
18729
  response.end();
@@ -18630,11 +18823,11 @@ function reconnectingApiClient(session, reconnect, transport = fetch) {
18630
18823
  }
18631
18824
 
18632
18825
  // 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";
18826
+ import { createHash as createHash2, randomUUID as randomUUID3 } from "node:crypto";
18827
+ import { chmodSync, existsSync as existsSync5, lstatSync as lstatSync3, mkdirSync as mkdirSync3, readFileSync as readFileSync5, readdirSync as readdirSync3, writeFileSync as writeFileSync6 } from "node:fs";
18828
+ import { dirname as dirname5, join as join5, resolve as resolve5, sep } from "node:path";
18636
18829
  import { homedir } from "node:os";
18637
- import { spawnSync as spawnSync3 } from "node:child_process";
18830
+ import { spawnSync as spawnSync4 } from "node:child_process";
18638
18831
 
18639
18832
  // src/local-state.ts
18640
18833
  import { renameSync as renameSync2 } from "node:fs";
@@ -18663,8 +18856,8 @@ function runtimeIdentifier(platform2 = process.platform, architecture = process.
18663
18856
  return system + "-" + architecture;
18664
18857
  }
18665
18858
  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");
18859
+ const target = resolve5(root, filename2);
18860
+ if (target !== resolve5(root) && !target.startsWith(resolve5(root) + sep)) throw new Error("Runtime path escapes its installation");
18668
18861
  let current = target;
18669
18862
  while (true) {
18670
18863
  if (existsSync5(current) && lstatSync3(current).isSymbolicLink()) throw new Error("Runtime installation must not follow links");
@@ -18675,25 +18868,25 @@ function checkedPath(root, filename2) {
18675
18868
  }
18676
18869
  function verifyInstallationFiles(root, expected, directory2 = root) {
18677
18870
  for (const entry of readdirSync3(directory2, { withFileTypes: true })) {
18678
- const path = checkedPath(root, join4(directory2, entry.name));
18871
+ const path = checkedPath(root, join5(directory2, entry.name));
18679
18872
  if (entry.isDirectory()) verifyInstallationFiles(root, expected, path);
18680
18873
  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
18874
  }
18682
18875
  }
18683
- function installedLocalRuntime(base = join4(homedir(), ".backify")) {
18876
+ function installedLocalRuntime(base = join5(homedir(), ".backify")) {
18684
18877
  const pointer = checkedPath(base, "runtime.json");
18685
18878
  if (!existsSync5(pointer)) return void 0;
18686
- const installed = JSON.parse(readFileSync4(pointer, "utf8"));
18879
+ const installed = JSON.parse(readFileSync5(pointer, "utf8"));
18687
18880
  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));
18881
+ const root = checkedPath(base, join5("runtimes", installed.version, installed.rid));
18689
18882
  verifyInstallationFiles(root, installed.files);
18690
18883
  for (const [filename2, digest4] of Object.entries(installed.files)) {
18691
18884
  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");
18885
+ 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
18886
  }
18694
18887
  const executableName = installed.rid.startsWith("win-") ? "Backify.Hcr.exe" : "Backify.Hcr";
18695
18888
  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 };
18889
+ return { path: join5(root, "Backify.Hcr.dll"), executable: join5(root, executableName), version: installed.version, rid: installed.rid };
18697
18890
  }
18698
18891
  function installLocalRuntime(archive, options) {
18699
18892
  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 +18900,28 @@ function installLocalRuntime(archive, options) {
18707
18900
  const rid = runtimeIdentifier();
18708
18901
  const executable = rid.startsWith("win-") ? "Backify.Hcr.exe" : "Backify.Hcr";
18709
18902
  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));
18903
+ const base = options.base ?? join5(homedir(), ".backify");
18904
+ const parent = checkedPath(base, join5("runtimes", options.version));
18712
18905
  mkdirSync3(parent, { recursive: true, mode: 448 });
18713
18906
  const destination = checkedPath(parent, rid);
18714
18907
  const receipt = { version: options.version, rid, files: Object.fromEntries(Object.entries(files).map(([name2, bytes]) => [name2, hash(bytes)])) };
18715
18908
  if (!existsSync5(destination)) {
18716
- const staging = checkedPath(parent, ".install-" + randomUUID2());
18909
+ const staging = checkedPath(parent, ".install-" + randomUUID3());
18717
18910
  mkdirSync3(staging, { mode: 448 });
18718
18911
  for (const [name2, bytes] of Object.entries(files)) {
18719
18912
  const filename2 = checkedPath(staging, name2);
18720
18913
  mkdirSync3(dirname5(filename2), { recursive: true, mode: 448 });
18721
- writeFileSync5(filename2, bytes, { flag: "wx", mode: name2 === executable ? 448 : 384 });
18914
+ writeFileSync6(filename2, bytes, { flag: "wx", mode: name2 === executable ? 448 : 384 });
18722
18915
  }
18723
- if (process.platform !== "win32") chmodSync(join4(staging, executable), 448);
18916
+ if (process.platform !== "win32") chmodSync(join5(staging, executable), 448);
18724
18917
  renameLocalFile(staging, destination);
18725
18918
  } else {
18726
18919
  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");
18920
+ 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
18921
  }
18729
18922
  const pointer = checkedPath(base, "runtime.json");
18730
- const temporary = checkedPath(base, ".runtime-" + randomUUID2() + ".json");
18731
- writeFileSync5(temporary, JSON.stringify(receipt), { flag: "wx", mode: 384 });
18923
+ const temporary = checkedPath(base, ".runtime-" + randomUUID3() + ".json");
18924
+ writeFileSync6(temporary, JSON.stringify(receipt), { flag: "wx", mode: 384 });
18732
18925
  renameLocalFile(temporary, pointer);
18733
18926
  return installedLocalRuntime(base);
18734
18927
  }
@@ -18756,10 +18949,10 @@ async function downloadLocalRuntime(version) {
18756
18949
  }
18757
18950
  function localPrerequisites() {
18758
18951
  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);
18952
+ const directory2 = process.env.BACKIFY_LOCAL_POSTGRES_BIN ?? (process.platform === "win32" ? join5(process.env.ProgramFiles ?? "C:/Program Files", "PostgreSQL", "17", "bin") : void 0);
18760
18953
  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" });
18954
+ const executable = directory2 ? join5(directory2, name2 + (process.platform === "win32" ? ".exe" : "")) : name2;
18955
+ const result = spawnSync4(executable, ["--version"], { windowsHide: true, timeout: 1e4, encoding: "utf8" });
18763
18956
  return { name: name2, available: result.status === 0 };
18764
18957
  });
18765
18958
  return { rid: runtimeIdentifier(), runtime: runtime ? { installed: true, version: runtime.version } : { installed: false }, postgres: checks, ready: !!runtime && checks.every((check) => check.available) };
@@ -18768,20 +18961,20 @@ function localPrerequisites() {
18768
18961
  // src/workload.ts
18769
18962
  import { build as build2 } from "esbuild";
18770
18963
  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";
18964
+ import { existsSync as existsSync12, mkdirSync as mkdirSync7, readFileSync as readFileSync20, realpathSync as realpathSync6, readdirSync as readdirSync6, writeFileSync as writeFileSync12 } from "node:fs";
18965
+ import { dirname as dirname13, isAbsolute as isAbsolute14, join as join14, relative as relative8, resolve as resolve19 } from "node:path";
18773
18966
 
18774
18967
  // src/local-development.ts
18775
18968
  import { context as context2 } from "esbuild";
18776
18969
  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";
18970
+ import { randomBytes as randomBytes6, randomUUID as randomUUID10, createHash as createHash13 } from "node:crypto";
18971
+ 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";
18972
+ import { resolve as resolve18, join as join13, relative as relative7, isAbsolute as isAbsolute13, dirname as dirname12 } from "node:path";
18780
18973
 
18781
18974
  // ../analyzer/dist/index.js
18782
18975
  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";
18976
+ import { readFileSync as readFileSync6, readdirSync as readdirSync4, existsSync as existsSync6 } from "node:fs";
18977
+ import { join as join6, extname } from "node:path";
18785
18978
 
18786
18979
  // ../analyzer/dist/authentication.js
18787
18980
  import ts from "typescript";
@@ -19198,11 +19391,11 @@ function repositorySources(root) {
19198
19391
  for (const entry of readdirSync4(dir, { withFileTypes: true })) {
19199
19392
  if (entry.name === "node_modules" || entry.name === "dist" || entry.name === ".backify" || entry.name.startsWith(".git"))
19200
19393
  continue;
19201
- const path = join5(dir, entry.name);
19394
+ const path = join6(dir, entry.name);
19202
19395
  if (entry.isDirectory())
19203
19396
  walk(path);
19204
19397
  else if ([".ts", ".tsx", ".js", ".jsx", ".mts", ".mjs"].includes(extname(path)))
19205
- result.push({ path, content: readFileSync5(path, "utf8") });
19398
+ result.push({ path, content: readFileSync6(path, "utf8") });
19206
19399
  }
19207
19400
  };
19208
19401
  if (existsSync6(root))
@@ -19419,8 +19612,8 @@ function createLocalNativeEvents(local, native) {
19419
19612
  // src/local-job-executor.ts
19420
19613
  import { spawn as spawn2 } from "node:child_process";
19421
19614
  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";
19615
+ import { lstatSync as lstatSync11, readFileSync as readFileSync13 } from "node:fs";
19616
+ import { isAbsolute as isAbsolute8, join as join9, relative as relative3, resolve as resolve12 } from "node:path";
19424
19617
 
19425
19618
  // ../sdk/dist/schedules.js
19426
19619
  var import_cron_parser = __toESM(require_dist2(), 1);
@@ -19631,14 +19824,14 @@ function createApplicationAuthProvider(source, options) {
19631
19824
  }
19632
19825
 
19633
19826
  // ../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";
19827
+ import { createHash as createHash3, randomUUID as randomUUID4 } from "node:crypto";
19828
+ import { closeSync, constants, fstatSync, fsyncSync, lstatSync as lstatSync4, openSync, readSync, renameSync as renameSync3, unlinkSync as unlinkSync2, writeFileSync as writeFileSync7 } from "node:fs";
19829
+ import { dirname as dirname6, isAbsolute as isAbsolute2, parse, resolve as resolve6, sep as sep2 } from "node:path";
19637
19830
  function unavailable2() {
19638
19831
  throw new ApplicationAuthenticationError("application_identity_unavailable");
19639
19832
  }
19640
19833
  function safePath(filename2) {
19641
- if (!isAbsolute2(filename2) || resolve5(filename2) !== filename2 || filename2 === parse(filename2).root)
19834
+ if (!isAbsolute2(filename2) || resolve6(filename2) !== filename2 || filename2 === parse(filename2).root)
19642
19835
  unavailable2();
19643
19836
  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
19837
  unavailable2();
@@ -19704,10 +19897,10 @@ function readState(filename2) {
19704
19897
  }
19705
19898
  }
19706
19899
  function persist(filename2, state) {
19707
- const temporary = filename2 + "." + randomUUID3() + ".tmp";
19900
+ const temporary = filename2 + "." + randomUUID4() + ".tmp";
19708
19901
  const descriptor2 = openSync(temporary, "wx", 384);
19709
19902
  try {
19710
- writeFileSync6(descriptor2, JSON.stringify(state));
19903
+ writeFileSync7(descriptor2, JSON.stringify(state));
19711
19904
  fsyncSync(descriptor2);
19712
19905
  } finally {
19713
19906
  closeSync(descriptor2);
@@ -19719,7 +19912,7 @@ function checkpoint(filename2, trust, initialize2) {
19719
19912
  try {
19720
19913
  if (!isAbsolute2(filename2))
19721
19914
  unavailable2();
19722
- filename2 = resolve5(filename2);
19915
+ filename2 = resolve6(filename2);
19723
19916
  safePath(filename2);
19724
19917
  const lock = filename2 + ".lock";
19725
19918
  const next = { version: 1, scope: trust.scope, revision: trust.revision, digest: createHash3("sha256").update(trust.content).digest("hex") };
@@ -19738,7 +19931,7 @@ function checkpoint(filename2, trust, initialize2) {
19738
19931
  }
19739
19932
  const descriptor2 = openSync(lock, "wx", 384);
19740
19933
  try {
19741
- writeFileSync6(descriptor2, "backify-application-auth-state-v1");
19934
+ writeFileSync7(descriptor2, "backify-application-auth-state-v1");
19742
19935
  fsyncSync(descriptor2);
19743
19936
  } finally {
19744
19937
  closeSync(descriptor2);
@@ -19769,7 +19962,7 @@ function checkpoint(filename2, trust, initialize2) {
19769
19962
  }
19770
19963
  } finally {
19771
19964
  if (!writePending) {
19772
- unlinkSync(lock);
19965
+ unlinkSync2(lock);
19773
19966
  syncDirectory(filename2);
19774
19967
  }
19775
19968
  }
@@ -19785,9 +19978,9 @@ function createPersistentApplicationAuthProvider(source, options) {
19785
19978
  }
19786
19979
 
19787
19980
  // ../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";
19981
+ import { createHash as createHash4, createPublicKey as createPublicKey2, randomUUID as randomUUID5, verify as verify2 } from "node:crypto";
19982
+ import { closeSync as closeSync2, constants as constants2, fsyncSync as fsyncSync2, lstatSync as lstatSync5, openSync as openSync2, readFileSync as readFileSync7, renameSync as renameSync4, unlinkSync as unlinkSync3, writeFileSync as writeFileSync8 } from "node:fs";
19983
+ import { dirname as dirname7, isAbsolute as isAbsolute3, parse as parse2, resolve as resolve7, sep as sep3 } from "node:path";
19791
19984
  var maximumBytes = 512 * 1024;
19792
19985
  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
19986
  function unavailable3() {
@@ -19796,7 +19989,7 @@ function unavailable3() {
19796
19989
  function filename(value) {
19797
19990
  if (typeof value !== "string" || /[\x00-\x1f\x7f]/.test(value) || !isAbsolute3(value))
19798
19991
  unavailable3();
19799
- const result = resolve6(value);
19992
+ const result = resolve7(value);
19800
19993
  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
19994
  unavailable3();
19802
19995
  return result;
@@ -19858,7 +20051,7 @@ function currentPublicFile(filename2) {
19858
20051
  const metadata = lstatSync5(filename2);
19859
20052
  if (!metadata.isFile() || metadata.isSymbolicLink() || metadata.nlink !== 1 || metadata.size > 131072 || process.platform !== "win32" && (metadata.uid !== process.getuid?.() || (metadata.mode & 18) !== 0))
19860
20053
  unavailable3();
19861
- const bytes = readFileSync6(filename2);
20054
+ const bytes = readFileSync7(filename2);
19862
20055
  if (bytes.length > 131072)
19863
20056
  unavailable3();
19864
20057
  return new TextDecoder("utf8", { fatal: true }).decode(bytes);
@@ -19925,7 +20118,7 @@ async function synchronizeApplicationAuthTrustWithDigest(options) {
19925
20118
  const lock = prepared.stateFile + ".delivery.lock";
19926
20119
  const descriptor2 = openSync2(lock, "wx", 384);
19927
20120
  try {
19928
- writeFileSync7(descriptor2, "backify-application-auth-delivery-v1");
20121
+ writeFileSync8(descriptor2, "backify-application-auth-delivery-v1");
19929
20122
  fsyncSync2(descriptor2);
19930
20123
  } finally {
19931
20124
  closeSync2(descriptor2);
@@ -19940,10 +20133,10 @@ async function synchronizeApplicationAuthTrustWithDigest(options) {
19940
20133
  if (current === content)
19941
20134
  return { status: "unchanged", revision: trust.revision, validUntil: trust.validUntil, trustDigest };
19942
20135
  writePending = true;
19943
- const temporary = prepared.trustFile + "." + randomUUID4() + ".tmp";
20136
+ const temporary = prepared.trustFile + "." + randomUUID5() + ".tmp";
19944
20137
  const output = openSync2(temporary, "wx", process.platform === "win32" ? 384 : 292);
19945
20138
  try {
19946
- writeFileSync7(output, content);
20139
+ writeFileSync8(output, content);
19947
20140
  fsyncSync2(output);
19948
20141
  } finally {
19949
20142
  closeSync2(output);
@@ -19954,7 +20147,7 @@ async function synchronizeApplicationAuthTrustWithDigest(options) {
19954
20147
  return { status: "updated", revision: trust.revision, validUntil: trust.validUntil, trustDigest };
19955
20148
  } finally {
19956
20149
  if (!writePending) {
19957
- unlinkSync2(lock);
20150
+ unlinkSync3(lock);
19958
20151
  syncDirectory2(lock);
19959
20152
  }
19960
20153
  }
@@ -20525,16 +20718,16 @@ function jsonValue(value) {
20525
20718
 
20526
20719
  // src/local-services.ts
20527
20720
  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";
20721
+ import { createHash as createHash6, generateKeyPairSync, randomBytes as randomBytes3, randomUUID as randomUUID7, sign } from "node:crypto";
20722
+ import { createServer as createServer3 } from "node:net";
20723
+ 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";
20724
+ import { basename as basename2, dirname as dirname9, isAbsolute as isAbsolute4, join as join8, relative, resolve as resolve8 } from "node:path";
20532
20725
 
20533
20726
  // 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";
20727
+ import { createHash as createHash5, randomBytes as randomBytes2, randomUUID as randomUUID6 } from "node:crypto";
20728
+ import { existsSync as existsSync7, lstatSync as lstatSync6, readFileSync as readFileSync8 } from "node:fs";
20536
20729
  import { isIP } from "node:net";
20537
- import { dirname as dirname8, join as join6 } from "node:path";
20730
+ import { dirname as dirname8, join as join7 } from "node:path";
20538
20731
  function fields3(value, names) {
20539
20732
  return !!value && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === names.length && names.every((name2) => Object.hasOwn(value, name2));
20540
20733
  }
@@ -20585,9 +20778,9 @@ function validLocalJobState(value, otherIds) {
20585
20778
  function prepareLocalJobService(hcrPath, retained, artifacts, applyMigrations) {
20586
20779
  const requested = validateLocalJobArtifacts(artifacts);
20587
20780
  const readSchema = (name2) => {
20588
- const filename2 = join6(dirname8(hcrPath), "sql", name2), info = existsSync7(filename2) ? lstatSync6(filename2) : void 0;
20781
+ const filename2 = join7(dirname8(hcrPath), "sql", name2), info = existsSync7(filename2) ? lstatSync6(filename2) : void 0;
20589
20782
  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");
20783
+ return readFileSync8(filename2, "utf8");
20591
20784
  };
20592
20785
  const base = readSchema("jobs-v1.sql"), producer = readSchema("jobs-producer-v1.sql");
20593
20786
  const schemaDigests = { base: createHash5("sha256").update(base).digest("hex"), producer: createHash5("sha256").update(producer).digest("hex") };
@@ -20599,15 +20792,15 @@ function prepareLocalJobService(hcrPath, retained, artifacts, applyMigrations) {
20599
20792
  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
20793
  if (!previous) retainedArtifacts.push(artifact);
20601
20794
  }
20602
- const state = { ...retained ?? { id: randomUUID5(), password: randomBytes2(32).toString("hex"), initialized: false }, schemaDigests, artifacts: validateLocalJobArtifacts(retainedArtifacts) };
20795
+ const state = { ...retained ?? { id: randomUUID6(), password: randomBytes2(32).toString("hex"), initialized: false }, schemaDigests, artifacts: validateLocalJobArtifacts(retainedArtifacts) };
20603
20796
  return { state, base, producer };
20604
20797
  }
20605
20798
 
20606
20799
  // src/local-services.ts
20607
20800
  function writePrivate(filename2, value) {
20608
20801
  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 });
20802
+ const temporary = filename2 + "." + randomUUID7() + ".tmp";
20803
+ writeFileSync9(temporary, value, { flag: "wx", mode: 384 });
20611
20804
  renameLocalFile(temporary, filename2);
20612
20805
  }
20613
20806
  function isLink(filename2) {
@@ -20620,7 +20813,7 @@ function isLink(filename2) {
20620
20813
  }
20621
20814
  function assertLocalStatePath(root, filename2) {
20622
20815
  const base = realpathSync(root);
20623
- for (let current = resolve7(filename2); current !== base; current = resolve7(current, "..")) {
20816
+ for (let current = resolve8(filename2); current !== base; current = resolve8(current, "..")) {
20624
20817
  const part = relative(base, current);
20625
20818
  if (part === ".." || part.startsWith(".." + (process.platform === "win32" ? "\\" : "/")) || isAbsolute4(part)) throw new Error("Local service state must stay inside the repository");
20626
20819
  if (isLink(current)) throw new Error("Local service paths must not contain links");
@@ -20633,22 +20826,22 @@ function stateValid(value) {
20633
20826
  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
20827
  }
20635
20828
  function acquireLocalLease(root, relativePath2 = ".backify/dev/development.lock") {
20636
- const filename2 = join7(root, relativePath2);
20829
+ const filename2 = join8(root, relativePath2);
20637
20830
  assertLocalStatePath(root, filename2);
20638
- mkdirSync4(resolve7(filename2, ".."), { recursive: true, mode: 448 });
20639
- const owner = JSON.stringify({ version: 1, pid: process.pid, id: randomUUID6() });
20831
+ mkdirSync4(resolve8(filename2, ".."), { recursive: true, mode: 448 });
20832
+ const owner = JSON.stringify({ version: 1, pid: process.pid, id: randomUUID7() });
20640
20833
  try {
20641
- writeFileSync8(filename2, owner, { flag: "wx", mode: 384 });
20834
+ writeFileSync9(filename2, owner, { flag: "wx", mode: 384 });
20642
20835
  } catch {
20643
20836
  throw new Error("Local development already owns this repository, or a stale lifecycle lock requires explicit recovery");
20644
20837
  }
20645
20838
  return () => {
20646
- if (existsSync8(filename2) && readFileSync8(filename2, "utf8") === owner) unlinkSync3(filename2);
20839
+ if (existsSync8(filename2) && readFileSync9(filename2, "utf8") === owner) unlinkSync4(filename2);
20647
20840
  };
20648
20841
  }
20649
20842
  async function allocateLocalPort(requested) {
20650
20843
  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();
20844
+ const server = createServer3();
20652
20845
  return new Promise((resolvePort, reject) => {
20653
20846
  server.once("error", reject);
20654
20847
  server.listen(requested ?? 0, "127.0.0.1", () => {
@@ -20686,13 +20879,13 @@ function command(executable, args2, options = {}) {
20686
20879
  });
20687
20880
  }
20688
20881
  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;
20882
+ const directory2 = bin ?? process.env.BACKIFY_LOCAL_POSTGRES_BIN ?? (process.platform === "win32" ? join8(process.env.ProgramFiles ?? "C:/Program Files", "PostgreSQL", "17", "bin") : void 0);
20883
+ return directory2 ? join8(directory2, name2 + (process.platform === "win32" ? ".exe" : "")) : name2;
20691
20884
  }
20692
20885
  function localMigrationFiles(root, directory2) {
20693
20886
  if (directory2 === void 0) return [];
20694
20887
  if (typeof directory2 !== "string") throw new Error("Local migrations require a repository-relative directory");
20695
- const folder = resolve7(root, directory2);
20888
+ const folder = resolve8(root, directory2);
20696
20889
  assertLocalStatePath(root, folder);
20697
20890
  if (!existsSync8(folder)) throw new Error("Declared migration directory does not exist");
20698
20891
  const entries = readdirSync5(folder);
@@ -20701,11 +20894,11 @@ function localMigrationFiles(root, directory2) {
20701
20894
  let total = 0;
20702
20895
  return filenames.map((name2) => {
20703
20896
  if (!/^[A-Za-z0-9_.-]{1,150}\.sql$/.test(name2)) throw new Error("Invalid migration filename");
20704
- const filename2 = join7(folder, name2);
20897
+ const filename2 = join8(folder, name2);
20705
20898
  assertLocalStatePath(root, filename2);
20706
20899
  const info = lstatSync7(filename2);
20707
20900
  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");
20901
+ const sql = readFileSync9(filename2, "utf8");
20709
20902
  if (!sql.trim()) throw new Error("Migration SQL must not be empty");
20710
20903
  validateLocalMigrationSql(sql);
20711
20904
  return { name: name2, digest: createHash6("sha256").update(sql).digest("hex"), sql };
@@ -20782,19 +20975,19 @@ async function startLocalServices(root, manifest, options = {}) {
20782
20975
  const reviewedScope = options.jobIdentityScope;
20783
20976
  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
20977
  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"));
20978
+ 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
20979
  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");
20980
+ const directory2 = join8(root, ".backify", "dev", "services");
20788
20981
  assertLocalStatePath(root, directory2);
20789
20982
  mkdirSync4(directory2, { recursive: true, mode: 448 });
20790
20983
  assertLocalStatePath(root, directory2);
20791
- const statePath = join7(directory2, "host.json");
20984
+ const statePath = join8(directory2, "host.json");
20792
20985
  assertLocalStatePath(root, statePath);
20793
20986
  let existing;
20794
20987
  if (existsSync8(statePath)) {
20795
20988
  if (lstatSync7(statePath).size > 16384) throw new Error("Local ownership state exceeds supported limits");
20796
20989
  try {
20797
- existing = JSON.parse(readFileSync8(statePath, "utf8"));
20990
+ existing = JSON.parse(readFileSync9(statePath, "utf8"));
20798
20991
  } catch {
20799
20992
  throw new Error("Invalid local service ownership state; preserve the data and repair explicitly");
20800
20993
  }
@@ -20802,9 +20995,9 @@ async function startLocalServices(root, manifest, options = {}) {
20802
20995
  }
20803
20996
  const state = existing ?? {
20804
20997
  version: 1,
20805
- scope: reviewedScope ? structuredClone(reviewedScope) : { organizationId: randomUUID6(), applicationId: randomUUID6(), environmentId: randomUUID6() },
20806
- databaseId: randomUUID6(),
20807
- storageId: randomUUID6(),
20998
+ scope: reviewedScope ? structuredClone(reviewedScope) : { organizationId: randomUUID7(), applicationId: randomUUID7(), environmentId: randomUUID7() },
20999
+ databaseId: randomUUID7(),
21000
+ storageId: randomUUID7(),
20808
21001
  configurationVersion: 0,
20809
21002
  adminPassword: randomBytes3(32).toString("hex"),
20810
21003
  databasePassword: randomBytes3(32).toString("hex")
@@ -20813,20 +21006,20 @@ async function startLocalServices(root, manifest, options = {}) {
20813
21006
  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
21007
  let eventSchema;
20815
21008
  if (events) {
20816
- const filename2 = join7(dirname9(hcrPath), "sql", "events-v1.sql");
21009
+ const filename2 = join8(dirname9(hcrPath), "sql", "events-v1.sql");
20817
21010
  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");
21011
+ eventSchema = readFileSync9(filename2, "utf8");
20819
21012
  const digest4 = createHash6("sha256").update(eventSchema).digest("hex");
20820
21013
  if (state.events && state.events.schemaDigest !== digest4) throw new Error("Native event schema changed; preserve its database and plan an explicit migration.");
20821
21014
  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 };
21015
+ state.events ??= { id: randomUUID7(), password: randomBytes3(32).toString("hex"), schemaDigest: digest4, initialized: false };
20823
21016
  }
20824
21017
  const jobSchema = jobs ? prepareLocalJobService(hcrPath, state.jobs, options.jobArtifacts, options.applyMigrations) : void 0;
20825
21018
  if (jobSchema) state.jobs = jobSchema.state;
20826
21019
  const storageNames = manifest.capabilities.storage?.buckets === void 0 ? ["default"] : manifest.capabilities.storage.buckets.map((bucket) => bucket.name);
20827
21020
  state.storageBindings ??= { default: state.storageId };
20828
21021
  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();
21022
+ for (const name2 of storageNames) state.storageBindings[name2] ??= randomUUID7();
20830
21023
  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
21024
  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
21025
  const migrations = database ? localMigrationFiles(root, manifest.capabilities.database?.migrations) : [];
@@ -20834,7 +21027,7 @@ async function startLocalServices(root, manifest, options = {}) {
20834
21027
  const databasePort = database || events || jobs ? await allocateLocalPort(options.databasePort) : void 0;
20835
21028
  if (databasePort !== void 0) state.retainedDatabasePort = databasePort;
20836
21029
  if (databasePort === hcrPort) throw new Error("HCR and PostgreSQL require separate ports");
20837
- const cluster = join7(directory2, "postgres");
21030
+ const cluster = join8(directory2, "postgres");
20838
21031
  assertLocalStatePath(root, cluster);
20839
21032
  const release2 = acquireLocalLease(root, ".backify/dev/services/lifecycle.lock");
20840
21033
  let postgresStarted = false;
@@ -20850,7 +21043,7 @@ async function startLocalServices(root, manifest, options = {}) {
20850
21043
  }
20851
21044
  };
20852
21045
  const runtimeUrl = "http://127.0.0.1:" + hcrPort;
20853
- const tokenPath = join7(directory2, "workload-token");
21046
+ const tokenPath = join8(directory2, "workload-token");
20854
21047
  const stop = () => stopping ??= (async () => {
20855
21048
  if (timer) clearInterval(timer);
20856
21049
  if (snapshotTimer) clearInterval(snapshotTimer);
@@ -20869,9 +21062,9 @@ async function startLocalServices(root, manifest, options = {}) {
20869
21062
  }
20870
21063
  notify("hcr", "stopped");
20871
21064
  try {
20872
- if (postgresStarted && existsSync8(join7(cluster, "postmaster.pid"))) await command(postgresExecutable("pg_ctl", options.postgresBin), ["-D", cluster, "-m", "fast", "-w", "stop"]);
21065
+ if (postgresStarted && existsSync8(join8(cluster, "postmaster.pid"))) await command(postgresExecutable("pg_ctl", options.postgresBin), ["-D", cluster, "-m", "fast", "-w", "stop"]);
20873
21066
  if (postgresStarted) notify("postgres", "stopped");
20874
- if (existsSync8(tokenPath)) unlinkSync3(tokenPath);
21067
+ if (existsSync8(tokenPath)) unlinkSync4(tokenPath);
20875
21068
  } finally {
20876
21069
  release2();
20877
21070
  }
@@ -20881,28 +21074,28 @@ async function startLocalServices(root, manifest, options = {}) {
20881
21074
  writePrivate(statePath, JSON.stringify(state));
20882
21075
  if (database || events || jobs) {
20883
21076
  notify("postgres", "starting");
20884
- if (!existsSync8(join7(cluster, "PG_VERSION"))) {
20885
- const passwordPath = join7(directory2, "init-password");
21077
+ if (!existsSync8(join8(cluster, "PG_VERSION"))) {
21078
+ const passwordPath = join8(directory2, "init-password");
20886
21079
  writePrivate(passwordPath, state.adminPassword);
20887
21080
  try {
20888
21081
  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
21082
  } finally {
20890
- if (existsSync8(passwordPath)) unlinkSync3(passwordPath);
21083
+ if (existsSync8(passwordPath)) unlinkSync4(passwordPath);
20891
21084
  }
20892
21085
  }
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");
21086
+ 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
21087
  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"]);
21088
+ 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
21089
  notify("postgres", "ready");
20897
21090
  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
21091
  if (database) {
20899
21092
  if ((await sql("SELECT count(*) FROM pg_roles WHERE rolname='backify_local'")).trim() === "0") {
20900
- const filename2 = join7(directory2, "role-" + randomUUID6() + ".sql");
21093
+ const filename2 = join8(directory2, "role-" + randomUUID7() + ".sql");
20901
21094
  writePrivate(filename2, "CREATE ROLE backify_local LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE PASSWORD '" + state.databasePassword + "';");
20902
21095
  try {
20903
21096
  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
21097
  } finally {
20905
- if (existsSync8(filename2)) unlinkSync3(filename2);
21098
+ if (existsSync8(filename2)) unlinkSync4(filename2);
20906
21099
  }
20907
21100
  }
20908
21101
  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 +21110,12 @@ async function startLocalServices(root, manifest, options = {}) {
20917
21110
  notify("migrations", "starting");
20918
21111
  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
21112
  for (const migration of pending) {
20920
- const filename2 = join7(directory2, "apply-" + randomUUID6() + ".sql");
21113
+ const filename2 = join8(directory2, "apply-" + randomUUID7() + ".sql");
20921
21114
  writePrivate(filename2, "BEGIN;\n" + migration.sql + "\n;\nINSERT INTO public.__backify_migrations(name,digest) VALUES ('" + migration.name + "','" + migration.digest + "');\nCOMMIT;\n");
20922
21115
  try {
20923
21116
  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
21117
  } finally {
20925
- if (existsSync8(filename2)) unlinkSync3(filename2);
21118
+ if (existsSync8(filename2)) unlinkSync4(filename2);
20926
21119
  }
20927
21120
  applied.push(migration.name);
20928
21121
  }
@@ -20933,20 +21126,20 @@ async function startLocalServices(root, manifest, options = {}) {
20933
21126
  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
21127
  if (!eventState.initialized) {
20935
21128
  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");
21129
+ const roleFile = join8(directory2, "event-role-" + randomUUID7() + ".sql");
20937
21130
  writePrivate(roleFile, "CREATE ROLE backify_events LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE PASSWORD '" + eventState.password + "';");
20938
21131
  try {
20939
21132
  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
21133
  } finally {
20941
- if (existsSync8(roleFile)) unlinkSync3(roleFile);
21134
+ if (existsSync8(roleFile)) unlinkSync4(roleFile);
20942
21135
  }
20943
21136
  await sql("CREATE DATABASE backify_events OWNER backify_events");
20944
- const schemaFile = join7(directory2, "event-schema-" + randomUUID6() + ".sql");
21137
+ const schemaFile = join8(directory2, "event-schema-" + randomUUID7() + ".sql");
20945
21138
  writePrivate(schemaFile, eventSchema);
20946
21139
  try {
20947
21140
  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
21141
  } finally {
20949
- if (existsSync8(schemaFile)) unlinkSync3(schemaFile);
21142
+ if (existsSync8(schemaFile)) unlinkSync4(schemaFile);
20950
21143
  }
20951
21144
  eventState.initialized = true;
20952
21145
  writePrivate(statePath, JSON.stringify(state));
@@ -20960,21 +21153,21 @@ async function startLocalServices(root, manifest, options = {}) {
20960
21153
  const adminSql = (query, databaseName = "postgres") => jobCommand("backify_admin", state.adminPassword, databaseName, ["-c", query]);
20961
21154
  if (!jobState.initialized) {
20962
21155
  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");
21156
+ const roleFile = join8(directory2, "job-role-" + randomUUID7() + ".sql");
20964
21157
  writePrivate(roleFile, "CREATE ROLE backify_jobs LOGIN NOINHERIT NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION NOBYPASSRLS PASSWORD '" + jobState.password + "';");
20965
21158
  try {
20966
21159
  await jobCommand("backify_admin", state.adminPassword, "postgres", ["-f", roleFile]);
20967
21160
  } finally {
20968
- if (existsSync8(roleFile)) unlinkSync3(roleFile);
21161
+ if (existsSync8(roleFile)) unlinkSync4(roleFile);
20969
21162
  }
20970
21163
  await adminSql("CREATE DATABASE backify_jobs OWNER backify_admin");
20971
21164
  for (const schema of [jobSchema.base, jobSchema.producer]) {
20972
- const filename2 = join7(directory2, "job-schema-" + randomUUID6() + ".sql");
21165
+ const filename2 = join8(directory2, "job-schema-" + randomUUID7() + ".sql");
20973
21166
  writePrivate(filename2, schema);
20974
21167
  try {
20975
21168
  await jobCommand("backify_admin", state.adminPassword, "backify_jobs", ["-f", filename2]);
20976
21169
  } finally {
20977
- if (existsSync8(filename2)) unlinkSync3(filename2);
21170
+ if (existsSync8(filename2)) unlinkSync4(filename2);
20978
21171
  }
20979
21172
  }
20980
21173
  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 +21196,7 @@ async function startLocalServices(root, manifest, options = {}) {
21003
21196
  ...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
21197
  ...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
21198
  ];
21006
- const snapshotPath = join7(directory2, "snapshot.json");
21199
+ const snapshotPath = join8(directory2, "snapshot.json");
21007
21200
  const writeSnapshot = () => writePrivate(snapshotPath, JSON.stringify({ schemaVersion: 1, configurationVersion: state.configurationVersion, expiresAt: new Date(Date.now() + 7 * 864e5).toISOString(), bindings }));
21008
21201
  const renewConfiguration = () => {
21009
21202
  if (stopping) throw new Error("Stopped local services cannot renew configuration");
@@ -21013,15 +21206,15 @@ async function startLocalServices(root, manifest, options = {}) {
21013
21206
  writeSnapshot();
21014
21207
  };
21015
21208
  writeSnapshot();
21016
- const settingsPath = join7(directory2, "appsettings.json");
21209
+ const settingsPath = join8(directory2, "appsettings.json");
21017
21210
  writePrivate(settingsPath, JSON.stringify({ Hcr: {
21018
21211
  Authentication: { PublicKeyPem: publicKey.export({ type: "spki", format: "pem" }), Issuer: "backify-local", Audience: "backify-local-hcr" },
21019
21212
  SnapshotPath: snapshotPath,
21020
- SnapshotJournalPath: join7(directory2, "journal.json"),
21213
+ SnapshotJournalPath: join8(directory2, "journal.json"),
21021
21214
  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
21215
  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
21216
  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) }])) }
21217
+ Storage: { Bindings: Object.fromEntries(Object.entries(state.storageBindings).map(([name2, identifier2]) => [identifier2, { Scope: state.scope, ResourceReference: name2, RootPath: join8(directory2, "objects", identifier2) }])) }
21025
21218
  } }));
21026
21219
  issueToken();
21027
21220
  notify("hcr", "starting");
@@ -21035,7 +21228,7 @@ async function startLocalServices(root, manifest, options = {}) {
21035
21228
  while (true) {
21036
21229
  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
21230
  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" });
21231
+ 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
21232
  if (response.ok) {
21040
21233
  const status = await response.json();
21041
21234
  if (status.status === "ready" && status.configurationVersion === state.configurationVersion) break;
@@ -21044,8 +21237,8 @@ async function startLocalServices(root, manifest, options = {}) {
21044
21237
  }
21045
21238
  await new Promise((resolveDelay) => setTimeout(resolveDelay, 100));
21046
21239
  }
21047
- if (events) await createHcrEventsProvider({ runtimeUrl, token: () => readFileSync8(tokenPath, "utf8") }).inspect();
21048
- if (jobs) await createHcrJobsProvider({ runtimeUrl, token: () => readFileSync8(tokenPath, "utf8") }).inspect();
21240
+ if (events) await createHcrEventsProvider({ runtimeUrl, token: () => readFileSync9(tokenPath, "utf8") }).inspect();
21241
+ if (jobs) await createHcrJobsProvider({ runtimeUrl, token: () => readFileSync9(tokenPath, "utf8") }).inspect();
21049
21242
  timer = setInterval(() => {
21050
21243
  try {
21051
21244
  issueToken();
@@ -21071,24 +21264,24 @@ async function startLocalServices(root, manifest, options = {}) {
21071
21264
 
21072
21265
  // src/local-job-auth.ts
21073
21266
  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";
21267
+ import { lstatSync as lstatSync8, readFileSync as readFileSync10 } from "node:fs";
21268
+ import { isAbsolute as isAbsolute5, resolve as resolve9 } from "node:path";
21076
21269
  function prepareLocalJobAuth(root, filename2) {
21077
21270
  const read = (path, maximum) => {
21078
21271
  assertLocalStatePath(root, path);
21079
21272
  const metadata = lstatSync8(path);
21080
21273
  if (!metadata.isFile() || metadata.isSymbolicLink() || metadata.nlink !== 1 || metadata.size > maximum) throw new Error();
21081
- const bytes = readFileSync9(path);
21274
+ const bytes = readFileSync10(path);
21082
21275
  if (bytes.length > maximum) throw new Error();
21083
21276
  return bytes;
21084
21277
  };
21085
21278
  try {
21086
21279
  if (!filename2 || isAbsolute5(filename2)) throw new Error();
21087
- const input = JSON.parse(new TextDecoder("utf8", { fatal: true }).decode(read(resolve8(root, filename2), 16384)));
21280
+ const input = JSON.parse(new TextDecoder("utf8", { fatal: true }).decode(read(resolve9(root, filename2), 16384)));
21088
21281
  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
21282
  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
21283
  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);
21284
+ const trustFile = resolve9(root, input.trustFile), stateFile = resolve9(root, input.stateFile);
21092
21285
  if (trustFile === stateFile) throw new Error();
21093
21286
  const bytes = read(trustFile, 131072), trust = JSON.parse(new TextDecoder("utf8", { fatal: true }).decode(bytes));
21094
21287
  read(stateFile, 2048);
@@ -21102,24 +21295,24 @@ function prepareLocalJobAuth(root, filename2) {
21102
21295
 
21103
21296
  // src/local-job-trust-renewal.ts
21104
21297
  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";
21298
+ import { lstatSync as lstatSync10, readFileSync as readFileSync12 } from "node:fs";
21299
+ import { isAbsolute as isAbsolute7, relative as relative2, resolve as resolve11 } from "node:path";
21107
21300
 
21108
21301
  // 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";
21302
+ import { lstatSync as lstatSync9, readFileSync as readFileSync11 } from "node:fs";
21303
+ import { isAbsolute as isAbsolute6, resolve as resolve10 } from "node:path";
21111
21304
  import { createHash as createHash8 } from "node:crypto";
21112
21305
  function prepareWorkloadTrustSynchronization(filename2) {
21113
21306
  try {
21114
21307
  if (!isAbsolute6(filename2)) throw new Error();
21115
21308
  const metadata = lstatSync9(filename2);
21116
21309
  if (!metadata.isFile() || metadata.isSymbolicLink() || metadata.nlink !== 1 || metadata.size > 65536) throw new Error();
21117
- const bytes = readFileSync10(filename2);
21310
+ const bytes = readFileSync11(filename2);
21118
21311
  if (bytes.length > 65536) throw new Error();
21119
21312
  const value = JSON.parse(new TextDecoder("utf8", { fatal: true }).decode(bytes));
21120
21313
  const allowed = ["controlPlaneUrl", "agentId", "expectedScope", "managementIssuer", "managementAudience", "managementPublicKeyPem", "credentialFile", "trustFile", "stateFile", "intervalSeconds"];
21121
21314
  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);
21315
+ const credentialFile = resolve10(value.credentialFile), trustFile = resolve10(value.trustFile), stateFile = resolve10(value.stateFile);
21123
21316
  const comparison = (filename3) => process.platform === "win32" ? filename3.toLowerCase() : filename3;
21124
21317
  if ([trustFile, stateFile, stateFile + ".lock", stateFile + ".delivery.lock"].map(comparison).includes(comparison(credentialFile))) throw new Error();
21125
21318
  const intervalSeconds = value.intervalSeconds ?? 30;
@@ -21127,7 +21320,7 @@ function prepareWorkloadTrustSynchronization(filename2) {
21127
21320
  const credential = () => {
21128
21321
  const metadata2 = lstatSync9(credentialFile);
21129
21322
  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);
21323
+ const bytes2 = readFileSync11(credentialFile);
21131
21324
  if (bytes2.length > 256) throw new Error("Management credential unavailable");
21132
21325
  return new TextDecoder("utf8", { fatal: true }).decode(bytes2).trim();
21133
21326
  };
@@ -21185,7 +21378,7 @@ async function workloadTrustSynchronization(args2, settings = {}) {
21185
21378
  function prepareLocalJobTrustRenewal(root, filename2, mount) {
21186
21379
  try {
21187
21380
  if (!filename2 || isAbsolute7(filename2)) throw new Error();
21188
- const configurationFile = resolve10(root, filename2);
21381
+ const configurationFile = resolve11(root, filename2);
21189
21382
  assertLocalStatePath(root, configurationFile);
21190
21383
  const configured = prepareWorkloadTrustSynchronization(configurationFile);
21191
21384
  const { credential, ...options } = configured.options;
@@ -21199,9 +21392,9 @@ function prepareLocalJobTrustRenewal(root, filename2, mount) {
21199
21392
  throw new Error("Invalid reviewed native worker trust renewal; preserve trust and state and review explicitly");
21200
21393
  }
21201
21394
  }
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);
21395
+ function createLocalJobTrustRenewal(root, mounts, settings = {}, dependencies = { createHash: createHash9, lstatSync: lstatSync10, readFileSync: readFileSync12, isAbsolute: isAbsolute7, relative: relative2, resolve: resolve11, createPersistentApplicationAuthProvider, synchronizeApplicationAuthTrustWithDigest }) {
21396
+ const { createHash: createHash16, lstatSync: lstatSync19, readFileSync: readFileSync25, isAbsolute: isAbsolute17, relative: relative11, resolve: resolve24, createPersistentApplicationAuthProvider: createPersistentApplicationAuthProvider2, synchronizeApplicationAuthTrustWithDigest: synchronizeApplicationAuthTrustWithDigest2 } = dependencies;
21397
+ const key = (filename2) => process.platform === "win32" ? resolve24(filename2).toLowerCase() : resolve24(filename2);
21205
21398
  const groups = [];
21206
21399
  for (const mount of mounts) {
21207
21400
  if (!mount.renewal) continue;
@@ -21218,13 +21411,13 @@ function createLocalJobTrustRenewal(root, mounts, settings = {}, dependencies =
21218
21411
  groups.push({ mount, followers, renewal, nextAt: 0, failures: 0, status: "waiting" });
21219
21412
  }
21220
21413
  const read = (filename2, maximum, privateFile2 = false) => {
21221
- for (let current = resolve23(filename2); current !== root; current = resolve23(current, "..")) {
21414
+ for (let current = resolve24(filename2); current !== root; current = resolve24(current, "..")) {
21222
21415
  const part = relative11(root, current);
21223
21416
  if (part === ".." || part.startsWith("../") || part.startsWith("..\\") || isAbsolute17(part) || lstatSync19(current).isSymbolicLink()) throw new Error();
21224
21417
  }
21225
21418
  const metadata = lstatSync19(filename2);
21226
21419
  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);
21420
+ const bytes = readFileSync25(filename2);
21228
21421
  if (bytes.length > maximum) throw new Error();
21229
21422
  return bytes;
21230
21423
  };
@@ -21305,11 +21498,11 @@ function prepareLocalJobWorker(root, directory2, artifacts, manifest, authFile,
21305
21498
  if (trustSyncFile !== void 0 && authFile === void 0) throw new Error("Native worker trust renewal requires explicit reviewed auth mounts");
21306
21499
  const authTrust = authFile === void 0 ? void 0 : prepareLocalJobAuth(root, authFile);
21307
21500
  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");
21501
+ const workerFile = join9(resolve12(root, directory2), "workload.mjs"), metadataFile = join9(resolve12(root, directory2), "artifact.json");
21309
21502
  for (const filename2 of [workerFile, metadataFile]) assertLocalStatePath(root, filename2);
21310
21503
  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);
21504
+ const metadata = JSON.parse(readFileSync13(metadataFile, "utf8"));
21505
+ const bundle = readFileSync13(workerFile);
21313
21506
  const actual = createHash10("sha256").update(bundle).digest("hex");
21314
21507
  const scheduleDiscovery = bundle.subarray(0, 100).toString("utf8").startsWith('var __backifyWorkerProtocols = ["hcr-v1","hcr-schedules-v1"];\n');
21315
21508
  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 +21513,31 @@ function prepareLocalJobWorker(root, directory2, artifacts, manifest, authFile,
21320
21513
  }
21321
21514
  function readLocalJobArtifacts(root, filename2) {
21322
21515
  if (!filename2 || isAbsolute8(filename2)) throw new Error("Job artifact admission requires a repository-relative reviewed JSON file");
21323
- const path = resolve11(root, filename2);
21516
+ const path = resolve12(root, filename2);
21324
21517
  assertLocalStatePath(root, path);
21325
21518
  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")));
21519
+ return validateLocalJobArtifacts(JSON.parse(readFileSync13(path, "utf8")));
21327
21520
  }
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;
21521
+ function createLocalJobExecutor(options, dependencies = { spawn: spawn2, createHash: createHash10, lstatSync: lstatSync11, readFileSync: readFileSync13, isAbsolute: isAbsolute8, relative: relative3, resolve: resolve12, validateWorkloadJobSchedules, createPersistentApplicationAuthProvider }) {
21522
+ const { spawn: spawn6, createHash: createHash16, lstatSync: lstatSync19, readFileSync: readFileSync25, isAbsolute: isAbsolute17, relative: relative11, resolve: resolve24, validateWorkloadJobSchedules: validateWorkloadJobSchedules2, createPersistentApplicationAuthProvider: createPersistentApplicationAuthProvider2 } = dependencies;
21330
21523
  const assertReady = () => {
21331
- for (let current = resolve23(options.workerFile); current !== options.root; current = resolve23(current, "..")) {
21524
+ for (let current = resolve24(options.workerFile); current !== options.root; current = resolve24(current, "..")) {
21332
21525
  const part = relative11(options.root, current);
21333
21526
  if (part === ".." || part.startsWith("../") || part.startsWith("..\\") || isAbsolute17(part) || lstatSync19(current).isSymbolicLink()) throw new Error("Native worker paths or pins changed");
21334
21527
  }
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");
21528
+ 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
21529
  if (options.authTrust) {
21337
21530
  try {
21338
21531
  const mount = options.authTrust;
21339
21532
  for (const path of [mount.trustFile, mount.stateFile]) {
21340
- for (let current = resolve23(path); current !== options.root; current = resolve23(current, "..")) {
21533
+ for (let current = resolve24(path); current !== options.root; current = resolve24(current, "..")) {
21341
21534
  const part = relative11(options.root, current);
21342
21535
  if (part === ".." || part.startsWith("../") || part.startsWith("..\\") || isAbsolute17(part) || lstatSync19(current).isSymbolicLink()) throw new Error();
21343
21536
  }
21344
21537
  const metadata = lstatSync19(path);
21345
21538
  if (!metadata.isFile() || metadata.nlink !== 1 || metadata.size > (path === mount.trustFile ? 131072 : 2048)) throw new Error();
21346
21539
  }
21347
- const bytes = readFileSync24(mount.trustFile);
21540
+ const bytes = readFileSync25(mount.trustFile);
21348
21541
  if (bytes.length > 131072 || createHash16("sha256").update(bytes).digest("hex") !== mount.trustDigest) throw new Error();
21349
21542
  const trust = JSON.parse(new TextDecoder("utf8", { fatal: true }).decode(bytes));
21350
21543
  if (trust.revision !== mount.revision) throw new Error();
@@ -21718,9 +21911,9 @@ process.on("SIGTERM", stop); process.on("SIGINT", stop); process.once("disconnec
21718
21911
 
21719
21912
  // src/local-frontend.ts
21720
21913
  import { spawn as spawn3 } from "node:child_process";
21721
- import { readFileSync as readFileSync14, realpathSync as realpathSync3, existsSync as existsSync9, statSync } from "node:fs";
21914
+ import { readFileSync as readFileSync15, realpathSync as realpathSync3, existsSync as existsSync9, statSync } from "node:fs";
21722
21915
  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";
21916
+ import { dirname as dirname10, isAbsolute as isAbsolute10, join as join11, relative as relative5, resolve as resolve14 } from "node:path";
21724
21917
  import { pathToFileURL } from "node:url";
21725
21918
 
21726
21919
  // src/local-frontend-guard.ts
@@ -21787,21 +21980,21 @@ await server.listen();
21787
21980
  `;
21788
21981
 
21789
21982
  // 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";
21983
+ import { createServer as createServer4 } from "node:http";
21984
+ import { lstatSync as lstatSync12, readFileSync as readFileSync14, realpathSync as realpathSync2, watch } from "node:fs";
21985
+ import { extname as extname2, isAbsolute as isAbsolute9, join as join10, relative as relative4, resolve as resolve13, sep as sep4 } from "node:path";
21793
21986
  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
21987
  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
21988
  function publicFile(directory2, pathname) {
21796
21989
  const parts = pathname.split("/").slice(1);
21797
21990
  if (parts.at(-1) === "") parts[parts.length - 1] = "index.html";
21798
21991
  if (!publicParts(parts)) throw new Error("refused");
21799
- const filename2 = resolve12(directory2, ...parts), part = relative4(directory2, filename2);
21992
+ const filename2 = resolve13(directory2, ...parts), part = relative4(directory2, filename2);
21800
21993
  if (part === ".." || part.startsWith(".." + sep4) || isAbsolute9(part) || !contentTypes[extname2(filename2).toLowerCase()]) throw new Error("refused");
21801
21994
  let current = directory2;
21802
21995
  if (lstatSync12(current).isSymbolicLink() || realpathSync2(current) !== directory2) throw new Error("refused");
21803
21996
  for (const segment of parts) {
21804
- current = join9(current, segment);
21997
+ current = join10(current, segment);
21805
21998
  if (lstatSync12(current).isSymbolicLink()) throw new Error("refused");
21806
21999
  }
21807
22000
  const stat = lstatSync12(filename2);
@@ -21819,7 +22012,7 @@ async function startLocalStaticFrontend(directory2, port, backendUrl) {
21819
22012
  const watcher = watch(directory2, { recursive: true }, (_, filename2) => {
21820
22013
  if (filename2 && publicParts(filename2.toString().split(/[\\/]/)) && contentTypes[extname2(filename2.toString()).toLowerCase()]) revision++;
21821
22014
  });
21822
- const server = createServer3((request, response) => {
22015
+ const server = createServer4((request, response) => {
21823
22016
  const send = (status, type, body) => {
21824
22017
  response.writeHead(status, { "content-type": type, "cache-control": "no-store", "x-content-type-options": "nosniff", "content-length": Buffer.byteLength(body) });
21825
22018
  response.end(request.method === "HEAD" ? void 0 : body);
@@ -21832,7 +22025,7 @@ async function startLocalStaticFrontend(directory2, port, backendUrl) {
21832
22025
  if (pathname === "/__backify/revision") return send(200, "text/plain", String(revision));
21833
22026
  if (pathname === "/__backify/config.json") return send(200, "application/json", JSON.stringify({ backendUrl: backendUrl ?? null }));
21834
22027
  const filename2 = publicFile(directory2, pathname);
21835
- const content = readFileSync13(filename2);
22028
+ const content = readFileSync14(filename2);
21836
22029
  if (content.length > 5242880) throw new Error("refused");
21837
22030
  const extension = extname2(filename2).toLowerCase();
21838
22031
  const body = extension === ".html" ? content.toString("utf8") + '\n<script src="/__backify/reload.js?revision=' + revision + '"></script>\n' : content;
@@ -21875,24 +22068,24 @@ function prepareLocalFrontend(root, options, privateFiles = []) {
21875
22068
  if (options.frontendPort !== void 0) throw new Error("Frontend port requires an explicit frontend directory");
21876
22069
  return void 0;
21877
22070
  }
21878
- const directory2 = realpathSync3(resolve13(root, options.frontend));
22071
+ const directory2 = realpathSync3(resolve14(root, options.frontend));
21879
22072
  const part = relative5(realpathSync3(root), directory2);
21880
22073
  if (part === ".." || part.startsWith("../") || part.startsWith("..\\") || isAbsolute10(part) || !statSync(directory2).isDirectory()) throw new Error("Frontend must be a directory inside this repository");
21881
22074
  if (options.frontendAdapter === "static") {
21882
22075
  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
22076
  return prepareLocalStaticFrontend(directory2);
21884
22077
  }
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"));
22078
+ if (!existsSync9(join11(directory2, "package.json"))) throw new Error("Frontend requires an existing package.json and installed Vite");
22079
+ const require3 = createRequire3(join11(directory2, "package.json"));
21887
22080
  let packagePath;
21888
22081
  try {
21889
22082
  packagePath = require3.resolve("vite/package.json");
21890
22083
  } catch {
21891
22084
  throw new Error("Frontend requires locally installed Vite; Backify does not install dependencies automatically");
21892
22085
  }
21893
- const metadata = JSON.parse(readFileSync14(packagePath, "utf8"));
22086
+ const metadata = JSON.parse(readFileSync15(packagePath, "utf8"));
21894
22087
  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));
22088
+ const executable = realpathSync3(resolve14(dirname10(packagePath), metadata.bin.vite));
21896
22089
  const executablePart = relative5(realpathSync3(dirname10(packagePath)), executable);
21897
22090
  if (executablePart === ".." || executablePart.startsWith("../") || executablePart.startsWith("..\\") || isAbsolute10(executablePart)) throw new Error("Vite CLI entrypoint must remain inside its package");
21898
22091
  const timeout = options.frontendStartupTimeoutMs ?? 3e4;
@@ -21954,8 +22147,8 @@ async function startLocalFrontend(prepared, port, backendUrl) {
21954
22147
  }
21955
22148
 
21956
22149
  // src/local-identity.ts
21957
- import { readFileSync as readFileSync15, statSync as statSync2 } from "node:fs";
21958
- import { resolve as resolve14 } from "node:path";
22150
+ import { readFileSync as readFileSync16, statSync as statSync2 } from "node:fs";
22151
+ import { resolve as resolve15 } from "node:path";
21959
22152
 
21960
22153
  // ../sdk/dist/local-identity.js
21961
22154
  import { createHash as createHash12, randomBytes as randomBytes4 } from "node:crypto";
@@ -22054,22 +22247,22 @@ function createLocalIdentityProvider(options) {
22054
22247
  }
22055
22248
 
22056
22249
  // src/local-identity.ts
22057
- import { randomUUID as randomUUID7 } from "node:crypto";
22250
+ import { randomUUID as randomUUID8 } from "node:crypto";
22058
22251
  function prepareLocalIdentity(root, filename2) {
22059
22252
  if (filename2 === void 0) return void 0;
22060
- const path = resolve14(root, filename2);
22253
+ const path = resolve15(root, filename2);
22061
22254
  assertLocalStatePath(root, path);
22062
22255
  if (!statSync2(path).isFile() || statSync2(path).size > 16384) throw new Error("Local identity profiles require a file at most 16 KiB");
22063
22256
  let input;
22064
22257
  try {
22065
- input = JSON.parse(readFileSync15(path, "utf8"));
22258
+ input = JSON.parse(readFileSync16(path, "utf8"));
22066
22259
  } catch {
22067
22260
  throw new Error("Invalid local identity profile JSON");
22068
22261
  }
22069
22262
  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
22263
  const value = input;
22071
22264
  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"] });
22265
+ const identity = createLocalIdentityProvider({ scope: { organizationId: randomUUID8(), applicationId: randomUUID8(), environmentId: randomUUID8() }, organizationName: value.organizationName, users: value.users, requestOrigins: ["http://127.0.0.1:3000"] });
22073
22266
  return { organizationName: value.organizationName, users: identity.profiles() };
22074
22267
  }
22075
22268
  function localIdentityCommand(args2) {
@@ -22095,17 +22288,17 @@ function localIdentityCommand(args2) {
22095
22288
  }
22096
22289
 
22097
22290
  // 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";
22291
+ import { lstatSync as lstatSync13, readFileSync as readFileSync17 } from "node:fs";
22292
+ import { isAbsolute as isAbsolute11, resolve as resolve16 } from "node:path";
22100
22293
  function prepareLocalJobHistory(root, filename2, artifacts, manifest, current) {
22101
22294
  if (filename2 === void 0) return [];
22102
22295
  const read = (filename3, maximum) => {
22103
22296
  if (typeof filename3 !== "string" || !filename3 || isAbsolute11(filename3)) throw new Error();
22104
- const path = resolve15(root, filename3);
22297
+ const path = resolve16(root, filename3);
22105
22298
  assertLocalStatePath(root, path);
22106
22299
  const metadata = lstatSync13(path);
22107
22300
  if (!metadata.isFile() || metadata.isSymbolicLink() || metadata.nlink !== 1 || metadata.size > maximum) throw new Error();
22108
- const bytes = readFileSync16(path);
22301
+ const bytes = readFileSync17(path);
22109
22302
  if (bytes.length > maximum) throw new Error();
22110
22303
  return new TextDecoder("utf8", { fatal: true }).decode(bytes);
22111
22304
  };
@@ -22151,30 +22344,30 @@ function prepareLocalJobHistory(root, filename2, artifacts, manifest, current) {
22151
22344
  }
22152
22345
 
22153
22346
  // 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";
22347
+ import { createCipheriv, createDecipheriv, randomBytes as randomBytes5, randomUUID as randomUUID9 } from "node:crypto";
22348
+ 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";
22349
+ import { dirname as dirname11, isAbsolute as isAbsolute12, join as join12, relative as relative6, resolve as resolve17 } from "node:path";
22157
22350
  var maximumBytes2 = 1048576;
22158
22351
  var secretName = /^[A-Z][A-Z0-9_]{0,127}$/;
22159
22352
  var failure = () => new Error("Local secret vault unavailable or invalid; review the vault and external key privately");
22160
22353
  function vaultPath(root) {
22161
- return join11(realpathSync4(root), ".backify", "dev", "secrets.enc.json");
22354
+ return join12(realpathSync4(root), ".backify", "dev", "secrets.enc.json");
22162
22355
  }
22163
22356
  function inside(root, filename2) {
22164
22357
  const part = relative6(root, filename2);
22165
22358
  return part !== ".." && !part.startsWith("../") && !part.startsWith("..\\") && !isAbsolute12(part);
22166
22359
  }
22167
22360
  function privateFile(filename2, limit) {
22168
- for (let current = resolve16(filename2); ; current = dirname11(current)) {
22361
+ for (let current = resolve17(filename2); ; current = dirname11(current)) {
22169
22362
  if (lstatSync14(current).isSymbolicLink()) throw failure();
22170
22363
  if (dirname11(current) === current) break;
22171
22364
  }
22172
22365
  const stat = lstatSync14(filename2);
22173
22366
  if (!stat.isFile() || stat.size > limit || stat.nlink !== 1 || process.platform !== "win32" && (stat.mode & 63) !== 0) throw failure();
22174
- return readFileSync17(filename2);
22367
+ return readFileSync18(filename2);
22175
22368
  }
22176
22369
  function externalKey(root, filename2) {
22177
- const keyFile = resolve16(filename2);
22370
+ const keyFile = resolve17(filename2);
22178
22371
  if (inside(realpathSync4(root), keyFile) || inside(realpathSync4(root), realpathSync4(keyFile))) throw failure();
22179
22372
  const encoded = privateFile(keyFile, 64).toString("utf8");
22180
22373
  if (!/^[a-f0-9]{64}$/.test(encoded)) throw failure();
@@ -22203,17 +22396,17 @@ function encrypt(root, application, key, secrets) {
22203
22396
  function writePrivate2(filename2, value) {
22204
22397
  const descriptor2 = openSync3(filename2, "wx", 384);
22205
22398
  try {
22206
- writeFileSync9(descriptor2, value);
22399
+ writeFileSync10(descriptor2, value);
22207
22400
  fsyncSync3(descriptor2);
22208
22401
  } finally {
22209
22402
  closeSync3(descriptor2);
22210
22403
  }
22211
22404
  }
22212
22405
  function ensureIgnored(root) {
22213
- const filename2 = join11(root, ".gitignore");
22406
+ const filename2 = join12(root, ".gitignore");
22214
22407
  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");
22408
+ const current = existsSync10(filename2) ? readFileSync18(filename2, "utf8") : "";
22409
+ if (!current.split(/\r?\n/).some((line) => line.trim() === ".backify/")) writeFileSync10(filename2, current + (current && !current.endsWith("\n") ? "\n" : "") + ".backify/\n");
22217
22410
  }
22218
22411
  function readLocalSecrets(root, application, keyFile) {
22219
22412
  const filename2 = vaultPath(root);
@@ -22246,7 +22439,7 @@ function readLocalSecrets(root, application, keyFile) {
22246
22439
  }
22247
22440
  }
22248
22441
  function initializeLocalSecrets(root, application, keyFile) {
22249
- const filename2 = vaultPath(root), external = resolve16(keyFile);
22442
+ const filename2 = vaultPath(root), external = resolve17(keyFile);
22250
22443
  assertLocalStatePath(root, filename2);
22251
22444
  if (existsSync10(filename2) || existsSync10(external)) throw new Error("Local secret initialization never overwrites an existing vault or key");
22252
22445
  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 +22473,7 @@ function setLocalSecret(root, application, keyFile, name2, value) {
22280
22473
  const secrets = readLocalSecrets(root, application, keyFile);
22281
22474
  secrets[name2] = value;
22282
22475
  key = externalKey(root, keyFile);
22283
- const temporary = filename2 + "." + randomUUID8() + ".tmp";
22476
+ const temporary = filename2 + "." + randomUUID9() + ".tmp";
22284
22477
  assertLocalStatePath(root, temporary);
22285
22478
  writePrivate2(temporary, encrypt(root, application, key, secrets));
22286
22479
  renameLocalFile(temporary, filename2);
@@ -22317,10 +22510,10 @@ async function localSecretsCommand(args2, root, application, input = process.std
22317
22510
 
22318
22511
  // src/local-development.ts
22319
22512
  function localManifest(root = process.cwd()) {
22320
- const filename2 = join12(root, "backify.yaml");
22513
+ const filename2 = join13(root, "backify.yaml");
22321
22514
  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);
22515
+ const manifest = parseApplicationManifest(readFileSync19(filename2, "utf8"));
22516
+ const entry = resolve18(root, manifest.runtime.entrypoint);
22324
22517
  if (!existsSync11(entry) || !inside2(root, realpathSync5(entry))) throw new Error("Runtime entrypoint must exist inside this repository");
22325
22518
  const discovered = analyzeSources(repositorySources(root));
22326
22519
  const diagnostics = manifestDiagnostics(manifest, Object.keys(discovered.capabilities), discovered.capabilities.auth?.configuration);
@@ -22332,12 +22525,12 @@ function inside2(root, path) {
22332
22525
  return part !== ".." && !part.startsWith(".." + (process.platform === "win32" ? "\\" : "/")) && !isAbsolute13(part);
22333
22526
  }
22334
22527
  function sessionPath(root) {
22335
- return join12(root, ".backify", "dev", "session.json");
22528
+ return join13(root, ".backify", "dev", "session.json");
22336
22529
  }
22337
22530
  async function localRequest(path, input, root = process.cwd()) {
22338
22531
  if (!/^\/v1\/[a-z/-]+$/.test(path)) throw new Error("Invalid local command path");
22339
22532
  if (!existsSync11(sessionPath(root))) throw new Error("Start backify dev before using local commands");
22340
- const session = JSON.parse(readFileSync18(sessionPath(root), "utf8"));
22533
+ const session = JSON.parse(readFileSync19(sessionPath(root), "utf8"));
22341
22534
  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
22535
  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
22536
  if (!response.ok) {
@@ -22370,7 +22563,7 @@ async function startLocalDevelopment(options = {}) {
22370
22563
  if (options.jobTrustSyncFile !== void 0 && options.jobAuthFile === void 0) throw new Error("Native worker trust renewal requires explicit reviewed auth mounts");
22371
22564
  if (options.jobHistoryFile !== void 0 && options.jobWorkerDirectory === void 0) throw new Error("Historical workers require paired reviewed job artifacts and current worker");
22372
22565
  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());
22566
+ const root = resolve18(options.root ?? process.cwd());
22374
22567
  const manifest = localManifest(root);
22375
22568
  const validateSecretIntent = (values, intent = manifest) => {
22376
22569
  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 +22580,15 @@ async function startLocalDevelopment(options = {}) {
22387
22580
  createLocalJobTrustRenewal(root, authMounts);
22388
22581
  const identityProfiles = prepareLocalIdentity(root, options.identityUsers);
22389
22582
  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");
22583
+ const preparedFrontend = prepareLocalFrontend(root, options, options.localSecretsKey ? [realpathSync5(resolve18(options.localSecretsKey))] : []);
22584
+ const ignorePath = join13(root, ".gitignore");
22392
22585
  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");
22586
+ const ignore = existsSync11(ignorePath) ? readFileSync19(ignorePath, "utf8") : "";
22587
+ if (!ignore.split(/\r?\n/).some((line) => line.trim() === ".backify/")) writeFileSync11(ignorePath, ignore + (ignore.endsWith("\n") || !ignore ? "" : "\n") + ".backify/\n");
22395
22588
  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");
22589
+ const directory2 = join13(root, ".backify", "dev");
22397
22590
  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));
22591
+ 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
22592
  mkdirSync6(directory2, { recursive: true });
22400
22593
  if (!inside2(root, realpathSync5(directory2))) throw new Error("Local state directory must remain inside this repository");
22401
22594
  if (existsSync11(sessionPath(root))) {
@@ -22429,14 +22622,14 @@ async function startLocalDevelopment(options = {}) {
22429
22622
  throw error;
22430
22623
  }
22431
22624
  const token = randomBytes6(32).toString("hex");
22432
- const identityScope = services?.identityScope ?? { organizationId: randomUUID9(), applicationId: randomUUID9(), environmentId: randomUUID9() };
22625
+ const identityScope = services?.identityScope ?? { organizationId: randomUUID10(), applicationId: randomUUID10(), environmentId: randomUUID10() };
22433
22626
  const workerEnvironment = (worker) => {
22434
22627
  if (!worker.authTrust) return worker;
22435
22628
  const { renewal, ...authTrust } = worker.authTrust;
22436
22629
  return { ...worker, authTrust };
22437
22630
  };
22438
22631
  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");
22632
+ const outfile = join13(directory2, "worker.mjs");
22440
22633
  let child;
22441
22634
  const trustRenewal = createLocalJobTrustRenewal(root, authMounts, { onFailure: () => console.error("Native worker trust renewal unavailable; existing validity and pin guards remain enforced."), onUpdate: () => {
22442
22635
  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 +22667,8 @@ async function startLocalDevelopment(options = {}) {
22474
22667
  }
22475
22668
  await stopChild(child);
22476
22669
  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" } });
22670
+ const version = createHash13("sha256").update(readFileSync19(outfile)).update(services?.configurationFingerprint ?? "lightweight").digest("hex");
22671
+ const worker = spawn4(process.execPath, [outfile], { cwd: root, windowsHide: true, stdio: ["ignore", 2, 2, "ipc"], env: { ...process.env, ...identityEnvironment(), BACKIFY_LOCAL_SECRETS_IPC: "1", HOST: "127.0.0.1", ...backendPort === void 0 ? {} : { PORT: String(backendPort) }, BACKIFY_LOCAL_BACKEND_URL: backendUrl ?? "", BACKIFY_LOCAL_FRONTEND_URL: frontend?.url ?? "", BACKIFY_LOCAL_DATABASE_ENABLED: manifest.capabilities.database && manifest.capabilities.database.enabled !== false ? "1" : "0", BACKIFY_LOCAL_STORAGE_ENABLED: manifest.capabilities.storage && manifest.capabilities.storage.enabled !== false ? "1" : "0", BACKIFY_LOCAL_STORAGE_BUCKETS: JSON.stringify(manifest.capabilities.storage?.buckets?.map((bucket) => bucket.name) ?? (manifest.capabilities.storage ? ["default"] : [])), BACKIFY_LOCAL_TOKEN: token, BACKIFY_LOCAL_PORT: String(dashboardPort), BACKIFY_LOCAL_STATE: 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
22672
  child = worker;
22480
22673
  worker.send({ type: "local-secrets", secrets }, (error) => {
22481
22674
  if (error) {
@@ -22497,7 +22690,7 @@ async function startLocalDevelopment(options = {}) {
22497
22690
  workerReady = true;
22498
22691
  const session = { version: 1, port: message.port, token, pid: worker.pid };
22499
22692
  const temp = sessionPath(root) + ".tmp";
22500
- writeFileSync10(temp, JSON.stringify(session), { mode: 384 });
22693
+ writeFileSync11(temp, JSON.stringify(session), { mode: 384 });
22501
22694
  renameLocalFile(temp, sessionPath(root));
22502
22695
  const url = "http://127.0.0.1:" + message.port;
22503
22696
  options.onReady?.(url, { frontendUrl: frontend?.url, backendUrl });
@@ -22509,17 +22702,17 @@ async function startLocalDevelopment(options = {}) {
22509
22702
  });
22510
22703
  };
22511
22704
  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) {
22705
+ 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
22706
  build3.onLoad({ filter: /./, namespace: "file" }, (input) => {
22514
- if (input.path !== resolve17(root, manifest.runtime.entrypoint)) return;
22707
+ if (input.path !== resolve18(root, manifest.runtime.entrypoint)) return;
22515
22708
  try {
22516
22709
  const updated = localManifest(root);
22517
22710
  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
22711
  if (updated.runtime.entrypoint !== manifest.runtime.entrypoint) throw new Error("Runtime entrypoint changed; restart backify dev");
22519
22712
  } catch (error) {
22520
- return { errors: [{ text: error instanceof Error ? error.message : "Manifest validation failed" }], watchFiles: [join12(root, "backify.yaml")] };
22713
+ return { errors: [{ text: error instanceof Error ? error.message : "Manifest validation failed" }], watchFiles: [join13(root, "backify.yaml")] };
22521
22714
  }
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")] };
22715
+ 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
22716
  });
22524
22717
  build3.onEnd((result) => {
22525
22718
  if (result.errors.length) rejectStartup(new Error("Local application build failed"));
@@ -22576,8 +22769,8 @@ async function startLocalDevelopment(options = {}) {
22576
22769
  }
22577
22770
  }
22578
22771
  if (existsSync11(sessionPath(root))) {
22579
- const session = JSON.parse(readFileSync18(sessionPath(root), "utf8"));
22580
- if (session.token === token) unlinkSync4(sessionPath(root));
22772
+ const session = JSON.parse(readFileSync19(sessionPath(root), "utf8"));
22773
+ if (session.token === token) unlinkSync5(sessionPath(root));
22581
22774
  }
22582
22775
  };
22583
22776
  return {
@@ -22590,10 +22783,10 @@ async function startLocalDevelopment(options = {}) {
22590
22783
  }
22591
22784
  async function runLocalTests(root = process.cwd()) {
22592
22785
  const manifest = localManifest(root);
22593
- const project = JSON.parse(readFileSync18(join12(root, "package.json"), "utf8"));
22786
+ const project = JSON.parse(readFileSync19(join13(root, "package.json"), "utf8"));
22594
22787
  if (!project.scripts?.test) throw new Error("Add a test script to package.json so AI agents can run backify test");
22595
22788
  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;
22789
+ const npmPath = process.platform === "win32" ? process.env.npm_execpath ?? join13(dirname12(process.execPath), "node_modules", "npm", "bin", "npm-cli.js") : void 0;
22597
22790
  if (npmPath && !existsSync11(npmPath)) {
22598
22791
  reject(new Error("Cannot locate npm-cli.js; run backify test through npx or npm"));
22599
22792
  return;
@@ -22621,7 +22814,7 @@ function digest3(contents) {
22621
22814
  }
22622
22815
  function packageDirectory(filename2) {
22623
22816
  for (let current = dirname13(filename2); ; current = dirname13(current)) {
22624
- if (existsSync12(join13(current, "package.json"))) return current;
22817
+ if (existsSync12(join14(current, "package.json"))) return current;
22625
22818
  if (dirname13(current) === current) throw new Error("Cannot locate an installed dependency package");
22626
22819
  }
22627
22820
  }
@@ -22703,11 +22896,11 @@ main().catch(() => finish({ schemaVersion: 1, status: "failed", error: "workload
22703
22896
  `.replace("__KIND__", JSON.stringify(kind)).replace("__CAPABILITIES__", JSON.stringify(capabilities)).replace("__AUTH_ENABLED__", String(capabilities.includes("auth"))).replace("__ENTRY__", JSON.stringify(entry));
22704
22897
  }
22705
22898
  async function prepareWorkload(options) {
22706
- const root = realpathSync6(resolve18(options.root ?? process.cwd()));
22899
+ const root = realpathSync6(resolve19(options.root ?? process.cwd()));
22707
22900
  const manifest = localManifest(root);
22708
22901
  if (options.kind !== "http" && options.kind !== "worker") throw new Error("Workload kind must be http or worker");
22709
22902
  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));
22903
+ const entry = realpathSync6(resolve19(root, options.entry ?? manifest.runtime.entrypoint));
22711
22904
  if (!inside3(root, entry)) throw new Error("Workload entrypoint must stay inside this repository");
22712
22905
  const enabled = Object.entries(manifest.capabilities).filter(([, settings]) => settings?.enabled !== false).map(([name2]) => name2).sort();
22713
22906
  if (options.kind === "worker" && !enabled.includes("jobs")) throw new Error("Workers require declared jobs capability");
@@ -22733,11 +22926,11 @@ async function prepareWorkload(options) {
22733
22926
  context3.onResolve({ filter: /./ }, async (input) => {
22734
22927
  if (input.pluginData?.backifyResolved) return;
22735
22928
  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 } });
22929
+ 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
22930
  if (!resolved.external && !resolved.errors.length && resolved.path) {
22738
22931
  const directory2 = realpathSync6(packageDirectory(resolved.path));
22739
22932
  const target = relative8(directory2, realpathSync6(resolved.path)).replaceAll("\\", "/");
22740
- if (JSON.parse(readFileSync19(join13(directory2, "package.json"), "utf8")).name === "@backifydev/sdk") {
22933
+ if (JSON.parse(readFileSync20(join14(directory2, "package.json"), "utf8")).name === "@backifydev/sdk") {
22741
22934
  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
22935
  }
22743
22936
  if (!isAbsolute14(input.path) && !input.path.startsWith(".")) trustedPackages.add(directory2);
@@ -22799,30 +22992,30 @@ async function packageWorkload(options) {
22799
22992
  if (plan.blockers.includes("bundle-warning-review-required")) throw new Error("Workload bundle warnings require review before packaging");
22800
22993
  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
22994
  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));
22995
+ const output = resolve19(root, options.output ?? ".backify/artifacts/" + options.kind + "-" + plan.artifactVersion.slice(0, 16));
22803
22996
  assertLocalStatePath(root, output);
22804
22997
  if (existsSync12(output)) {
22805
22998
  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));
22999
+ assertLocalStatePath(root, join14(output, name2));
23000
+ return !readFileSync20(join14(output, name2)).equals(Buffer.from(value));
22808
23001
  })) throw new Error("Refusing to overwrite an existing workload artifact directory");
22809
23002
  } else {
22810
23003
  mkdirSync7(output, { recursive: true });
22811
- for (const [name2, value] of Object.entries(files)) writeFileSync11(join13(output, name2), value, { flag: "wx", mode: 384 });
23004
+ for (const [name2, value] of Object.entries(files)) writeFileSync12(join14(output, name2), value, { flag: "wx", mode: 384 });
22812
23005
  }
22813
23006
  return { ...plan, outputDirectory: relative8(root, output).replaceAll("\\", "/") };
22814
23007
  }
22815
23008
 
22816
23009
  // src/workload-provenance.ts
22817
23010
  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";
23011
+ import { mkdirSync as mkdirSync8, mkdtempSync as mkdtempSync2, readdirSync as readdirSync7, rmSync as rmSync2, writeFileSync as writeFileSync13 } from "node:fs";
22819
23012
  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";
23013
+ import { basename as basename3, dirname as dirname15, isAbsolute as isAbsolute15, join as join16, relative as relative9, resolve as resolve21 } from "node:path";
22821
23014
 
22822
23015
  // src/workload-provenance-oci.ts
22823
23016
  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";
23017
+ import { createReadStream, lstatSync as lstatSync16, readFileSync as readFileSync21 } from "node:fs";
23018
+ import { dirname as dirname14, join as join15, parse as parse3, resolve as resolve20 } from "node:path";
22826
23019
  import { Transform, Writable } from "node:stream";
22827
23020
  import { pipeline } from "node:stream/promises";
22828
23021
  import { createGunzip } from "node:zlib";
@@ -22837,14 +23030,14 @@ function provenanceRef(value) {
22837
23030
  return value.slice(value.lastIndexOf("@") + 1);
22838
23031
  }
22839
23032
  function provenanceFile(filename2, maximum) {
22840
- const absolute = resolve19(filename2);
23033
+ const absolute = resolve20(filename2);
22841
23034
  for (let ancestor = absolute; ; ancestor = dirname14(ancestor)) {
22842
23035
  if (lstatSync16(ancestor).isSymbolicLink()) throw new Error("Provenance paths must not contain links");
22843
23036
  if (ancestor === parse3(absolute).root) break;
22844
23037
  }
22845
23038
  const stat = lstatSync16(absolute);
22846
23039
  if (!stat.isFile() || stat.nlink !== 1 || stat.size < 1 || stat.size > maximum) throw new Error("Invalid provenance file");
22847
- const bytes = readFileSync20(absolute);
23040
+ const bytes = readFileSync21(absolute);
22848
23041
  if (bytes.length !== stat.size) throw new Error("Provenance file changed during read");
22849
23042
  return bytes;
22850
23043
  }
@@ -22853,7 +23046,7 @@ function descriptor(value) {
22853
23046
  return value;
22854
23047
  }
22855
23048
  function blobPath(root, value) {
22856
- return join14(root, "blobs", "sha256", descriptor(value).digest.slice(7));
23049
+ return join15(root, "blobs", "sha256", descriptor(value).digest.slice(7));
22857
23050
  }
22858
23051
  function jsonBlob(root, value) {
22859
23052
  const bytes = provenanceFile(blobPath(root, value), 1024 * 1024);
@@ -22862,8 +23055,8 @@ function jsonBlob(root, value) {
22862
23055
  }
22863
23056
  async function inspectProvenanceImage(root, architecture, requestedDigest) {
22864
23057
  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);
23058
+ if (JSON.parse(provenanceFile(join15(root, "oci-layout"), 1024).toString()).imageLayoutVersion !== "1.0.0") throw new Error("OCI layout required");
23059
+ const indexBytes = provenanceFile(join15(root, "index.json"), 1024 * 1024);
22867
23060
  let current = JSON.parse(indexBytes.toString());
22868
23061
  let selected;
22869
23062
  let manifestDigest = provenanceHash(indexBytes);
@@ -22920,7 +23113,7 @@ async function inspectProvenanceImage(root, architecture, requestedDigest) {
22920
23113
  return { manifestDigest, configDigest: configuration.digest, architecture, layers };
22921
23114
  }
22922
23115
  function provenanceFileMetadata(filename2, expectedSize) {
22923
- const absolute = resolve19(filename2);
23116
+ const absolute = resolve20(filename2);
22924
23117
  for (let ancestor = absolute; ; ancestor = dirname14(ancestor)) {
22925
23118
  if (lstatSync16(ancestor).isSymbolicLink()) throw new Error("Provenance paths must not contain links");
22926
23119
  if (ancestor === parse3(absolute).root) break;
@@ -22983,28 +23176,28 @@ function dependencyMaterials(lock) {
22983
23176
  return { digest: provenanceHash(canonical(materials.sort((left, right) => left.path.localeCompare(right.path, "en")))), count: materials.length };
22984
23177
  }
22985
23178
  async function captureWorkloadProvenance(options) {
22986
- const root = resolve20(options.root ?? process.cwd());
23179
+ const root = resolve21(options.root ?? process.cwd());
22987
23180
  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("\\", "/");
23181
+ const applicationPath = relative9(root, resolve21(root, options.application)).replaceAll("\\", "/");
22989
23182
  if (!applicationPath || isAbsolute15(applicationPath) || applicationPath.split("/").includes("..")) throw new Error("Application must be inside the source checkout");
22990
23183
  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
23184
  const commit = git2(root, ["rev-parse", "HEAD"]), tree = git2(root, ["rev-parse", "HEAD^{tree}"]);
22992
23185
  if (!sha.test(commit) || !sha.test(tree)) throw new Error("Full Git commit and tree required");
22993
23186
  const origin = git2(root, ["remote", "get-url", "origin"]);
22994
23187
  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);
23188
+ const lockBytes = provenanceFile(join16(root, "package-lock.json"), 16 * 1024 * 1024);
22996
23189
  const dependencies = dependencyMaterials(JSON.parse(lockBytes.toString("utf8")));
22997
- const context3 = resolve20(root, options.context);
23190
+ const context3 = resolve21(root, options.context);
22998
23191
  if (canonical(readdirSync7(context3).sort()) !== canonical(contextNames)) throw new Error("Exact allowlisted workload context required");
22999
23192
  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"));
23193
+ for (const name2 of contextNames) contextDigests[name2] = provenanceHash(provenanceFile(join16(context3, name2), name2 === "workload.mjs" ? 16 * 1024 * 1024 : 65536));
23194
+ const plan = boundedJson(join16(context3, "artifact.json"));
23002
23195
  const baseDigest = provenanceRef(options.baseImage);
23003
23196
  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
23197
  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);
23198
+ 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");
23199
+ const base = await inspectProvenanceImage(resolve21(root, options.baseLayout), options.architecture, baseDigest);
23200
+ const image2 = await inspectProvenanceImage(resolve21(root, options.imageLayout), options.architecture);
23008
23201
  verifyBaseLineage(base, image2);
23009
23202
  let npm;
23010
23203
  try {
@@ -23077,17 +23270,17 @@ function verifyWorkloadProvenance(options, now = /* @__PURE__ */ new Date()) {
23077
23270
  if (provenanceHash(baseSubject) !== provenanceRef(policy.baseImage)) throw new Error("Base attestation subject does not match the approved image digest");
23078
23271
  evidence.push({ bytes: baseSubject, bundle: provenanceFile(options.baseBundle, 4 * 1024 * 1024), identity: { ...policy, ...supplier } });
23079
23272
  }
23080
- const scratchRoot = resolve20(tmpdir());
23081
- const scratch = mkdtempSync2(join15(scratchRoot, "backify-provenance-"));
23273
+ const scratchRoot = resolve21(tmpdir());
23274
+ const scratch = mkdtempSync2(join16(scratchRoot, "backify-provenance-"));
23082
23275
  if (dirname15(scratch) !== scratchRoot || !basename3(scratch).startsWith("backify-provenance-")) throw new Error("Unsafe provenance evidence directory");
23083
23276
  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 });
23277
+ mkdirSync8(join16(scratch, "evidence"), { mode: 448 });
23278
+ const trustedRoot = join16(scratch, "evidence", "trusted-root.jsonl");
23279
+ writeFileSync13(trustedRoot, rootBytes, { flag: "wx", mode: 384 });
23087
23280
  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 });
23281
+ const report = join16(scratch, "evidence", "report-" + index + ".json"), bundle = join16(scratch, "evidence", "bundle-" + index + ".jsonl");
23282
+ writeFileSync13(report, bytes, { flag: "wx", mode: 384 });
23283
+ writeFileSync13(bundle, bundleBytes, { flag: "wx", mode: 384 });
23091
23284
  try {
23092
23285
  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
23286
  if (!Array.isArray(JSON.parse(result)) || !JSON.parse(result).length) throw new Error();
@@ -23118,13 +23311,13 @@ async function workloadProvenanceCommand(args2) {
23118
23311
  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
23312
  }
23120
23313
  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 });
23314
+ writeFileSync13(resolve21(required("--output")), JSON.stringify(result, null, 2) + "\n", { flag: "wx", mode: 384 });
23122
23315
  return { schemaVersion: 1, status: "captured-unsigned", deploymentReady: false, reportDigest: provenanceHash(JSON.stringify(result, null, 2) + "\n") };
23123
23316
  }
23124
23317
 
23125
23318
  // 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";
23319
+ import { lstatSync as lstatSync17, readFileSync as readFileSync22 } from "node:fs";
23320
+ import { isAbsolute as isAbsolute16, resolve as resolve22 } from "node:path";
23128
23321
  function parseWorkloadTrustState(args2) {
23129
23322
  const action = args2[0];
23130
23323
  if (action !== "plan" && action !== "initialize") throw new Error("Use backify workload trust-state plan|initialize");
@@ -23146,12 +23339,12 @@ function parseWorkloadTrustState(args2) {
23146
23339
  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
23340
  }
23148
23341
  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");
23342
+ 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
23343
  let trust;
23151
23344
  try {
23152
23345
  const metadata = lstatSync17(options.trustFile);
23153
23346
  if (!metadata.isFile() || metadata.isSymbolicLink() || metadata.nlink !== 1 || metadata.size > 131072) throw new Error();
23154
- const bytes = readFileSync21(options.trustFile);
23347
+ const bytes = readFileSync22(options.trustFile);
23155
23348
  if (bytes.length > 131072) throw new Error();
23156
23349
  trust = JSON.parse(new TextDecoder("utf8", { fatal: true }).decode(bytes));
23157
23350
  } catch {
@@ -23161,14 +23354,14 @@ function workloadTrustState(options) {
23161
23354
  if (trust.revision !== options.expectedRevision) throw new Error("Application identity trust revision changed; review again");
23162
23355
  if (options.action === "initialize") {
23163
23356
  if (!options.confirmed) throw new Error("Initialization requires explicit --confirm after reviewing the plan");
23164
- initializeApplicationAuthState(trust, { expectedScope: options.expectedScope, stateFile: resolve21(options.stateFile) });
23357
+ initializeApplicationAuthState(trust, { expectedScope: options.expectedScope, stateFile: resolve22(options.stateFile) });
23165
23358
  }
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 };
23359
+ 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
23360
  }
23168
23361
 
23169
23362
  // 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";
23363
+ 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";
23364
+ import { dirname as dirname16, join as join17, relative as relative10, resolve as resolve23 } from "node:path";
23172
23365
  function json2(value) {
23173
23366
  return JSON.stringify(value, null, 2) + "\n";
23174
23367
  }
@@ -23346,21 +23539,21 @@ provider-readiness claim, cloud deployment or browser authentication is implied.
23346
23539
  }
23347
23540
  function scaffoldFullStack(options) {
23348
23541
  const files = fullStackTemplate(options.appId, options.name);
23349
- const root = resolve22(options.root ?? process.cwd());
23542
+ const root = resolve23(options.root ?? process.cwd());
23350
23543
  if (!existsSync13(root) || !lstatSync18(root).isDirectory() || lstatSync18(root).isSymbolicLink()) throw new Error("Scaffold destination must be an existing non-linked directory");
23351
23544
  const allowed = /* @__PURE__ */ new Set([...Object.keys(files).map((filename2) => filename2.split("/")[0]), ".git", "node_modules", "package-lock.json", ".backify"]);
23352
23545
  if (readdirSync8(root).some((filename2) => !allowed.has(filename2))) throw new Error("Scaffolding requires an empty folder or an unchanged generated starter");
23353
23546
  const canonicalRoot = realpathSync7(root);
23354
23547
  const pending = [];
23355
23548
  for (const [filename2, content] of Object.entries(files)) {
23356
- const destination = join16(root, filename2);
23549
+ const destination = join17(root, filename2);
23357
23550
  let current = destination;
23358
23551
  while (current !== root) {
23359
23552
  try {
23360
23553
  const stat = lstatSync18(current);
23361
23554
  if (stat.isSymbolicLink() || current !== destination && !stat.isDirectory()) throw new Error("Scaffolding refuses linked or invalid output paths: " + filename2);
23362
23555
  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);
23556
+ if (current === destination && (!stat.isFile() || readFileSync23(current, "utf8") !== content)) throw new Error("Scaffolding refuses to overwrite existing content: " + filename2);
23364
23557
  } catch (error) {
23365
23558
  if (!(error instanceof Error) || !("code" in error) || error.code !== "ENOENT") throw error;
23366
23559
  if (current === destination) pending.push(filename2);
@@ -23369,9 +23562,9 @@ function scaffoldFullStack(options) {
23369
23562
  }
23370
23563
  }
23371
23564
  for (const filename2 of pending) {
23372
- const destination = join16(root, filename2);
23565
+ const destination = join17(root, filename2);
23373
23566
  mkdirSync9(dirname16(destination), { recursive: true });
23374
- writeFileSync13(destination, files[filename2], { flag: "wx" });
23567
+ writeFileSync14(destination, files[filename2], { flag: "wx" });
23375
23568
  }
23376
23569
  return { template: "react-vite-hono", created: pending, unchanged: Object.keys(files).length - pending.length, installed: false, deployed: false };
23377
23570
  }
@@ -23415,16 +23608,16 @@ function localInspectionCommand(args2) {
23415
23608
  }
23416
23609
 
23417
23610
  // src/index.ts
23418
- import { readFileSync as readFileSync23, existsSync as existsSync14, rmSync as rmSync3 } from "node:fs";
23611
+ import { readFileSync as readFileSync24, existsSync as existsSync14, rmSync as rmSync3 } from "node:fs";
23419
23612
  import { homedir as homedir2 } from "node:os";
23420
- import { join as join17 } from "node:path";
23613
+ import { join as join18 } from "node:path";
23421
23614
  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")) : {};
23615
+ var configPath = join18(homedir2(), ".backify.json");
23616
+ var userConfig = existsSync14(configPath) ? JSON.parse(readFileSync24(configPath, "utf8")) : {};
23424
23617
  var [command2, ...args] = process.argv.slice(2);
23425
23618
  async function call(path, init) {
23426
23619
  let appId = option("--app");
23427
- if (!appId && existsSync14(join17(process.cwd(), "backify.json"))) appId = projectApplication();
23620
+ if (!appId && existsSync14(join18(process.cwd(), "backify.json"))) appId = projectApplication();
23428
23621
  const session = appId ? userConfig.sessions?.[sessionKey(appId)] : void 0;
23429
23622
  const credential = session ?? { token: userConfig.token ?? "", organizationId: userConfig.organizationId ?? "", apiUrl: process.env.BACKIFY_API_URL ?? userConfig.apiUrl ?? "https://api.backify.dev/api" };
23430
23623
  return (appId ? applicationClient(credential, appId) : apiClient(credential))(path, init);
@@ -23563,7 +23756,7 @@ async function main() {
23563
23756
  const name2 = option("--name");
23564
23757
  if (!name2) throw new Error("Specify --name <job>");
23565
23758
  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));
23759
+ console.log(JSON.stringify(await localRequest("/v1/jobs/run", { name: name2, payload: payload ? JSON.parse(readFileSync24(payload, "utf8")) : null }), null, 2));
23567
23760
  } else if (["retry", "cancel"].includes(args[0])) {
23568
23761
  const id = option("--id");
23569
23762
  if (!id) throw new Error("Specify --id <run>");
@@ -23586,7 +23779,7 @@ async function main() {
23586
23779
  const environmentId = option("--environment");
23587
23780
  const packagePath = option("--package");
23588
23781
  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) });
23782
+ await deployFunctions(call, appId, applicationGuid(environmentId), new Uint8Array(readFileSync24(packagePath)), { progress: (message) => console.log(message) });
23590
23783
  console.log("Functions deployed.");
23591
23784
  } else throw new Error("Use backify functions package or backify functions deploy");
23592
23785
  break;
@@ -23605,6 +23798,12 @@ async function main() {
23605
23798
  console.log("Backify instructions synchronized to version " + INSTRUCTION_VERSION);
23606
23799
  break;
23607
23800
  case "doctor": {
23801
+ if (args.includes("--environment")) {
23802
+ const result2 = await diagnoseEnvironment(process.cwd(), { network: args.includes("--network"), capability: option("--capability") });
23803
+ console.log(JSON.stringify(result2, null, 2));
23804
+ if (!result2.valid) process.exitCode = 1;
23805
+ break;
23806
+ }
23608
23807
  const result = doctor(process.cwd(), option("--agent"), option("--instruction-file"));
23609
23808
  console.log(JSON.stringify(result, null, 2));
23610
23809
  if (!result.valid) process.exitCode = 1;
@@ -23615,7 +23814,7 @@ async function main() {
23615
23814
  userConfig.token = args[0];
23616
23815
  userConfig.organizationId = args[1] ?? userConfig.organizationId;
23617
23816
  saveUserConfig(configPath, userConfig);
23618
- } else await browserLogin(option("--app") ?? (existsSync14(join17(process.cwd(), "backify.json")) ? projectApplication() : void 0), option("--organization"));
23817
+ } else await browserLogin(option("--app") ?? (existsSync14(join18(process.cwd(), "backify.json")) ? projectApplication() : void 0), option("--organization"));
23619
23818
  console.log("Logged in to Backify");
23620
23819
  break;
23621
23820
  case "logout":
@@ -23654,7 +23853,7 @@ async function main() {
23654
23853
  userConfig.sessions[key] ??= session;
23655
23854
  saveUserConfig(configPath, userConfig);
23656
23855
  if (args.includes("--clone")) await cloneProject(client, appId);
23657
- else if (existsSync14(join17(process.cwd(), ".git"))) {
23856
+ else if (existsSync14(join18(process.cwd(), ".git"))) {
23658
23857
  const update = await pullProject(client, appId);
23659
23858
  console.log(JSON.stringify(update, null, 2));
23660
23859
  if (update.status === "blocked") throw new Error(update.reason);
@@ -23700,13 +23899,13 @@ async function main() {
23700
23899
  break;
23701
23900
  }
23702
23901
  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.");
23902
+ if (args[0] !== "record" || !args.includes("--stdin")) throw new Error("Use backify prompt record --stdin --id <UUID> [--filename <name> ...] [--type build|deploy|fixing|other] [--model <full-model-name-and-version>] [--ai-tool <tool>] [--access-level <access>] [--sdk-version <installed-version>] [--commit-sha <full-SHA>]. User text is recorded for every request with Backify credentials redacted. Only prompt type, user text, filenames, device, commit, SDK version, and AI context metadata are sent.");
23704
23903
  const id = option("--id");
23705
23904
  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
23905
  const filenames = attachmentNames(args.flatMap((value, index) => value === "--filename" ? [args[index + 1] ?? ""] : []));
23707
23906
  const metadata = promptMetadata(args);
23708
23907
  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 }) })));
23908
+ console.log(JSON.stringify(await call("/apps/" + applicationGuid(projectApplication()) + "/prompts", { method: "POST", body: JSON.stringify({ clientPromptId: id, text: text3, filenames, ...promptContext(), ...metadata }) })));
23710
23909
  break;
23711
23910
  }
23712
23911
  case "runtime": {
@@ -23717,7 +23916,7 @@ async function main() {
23717
23916
  } else if (args[0] === "install") {
23718
23917
  const version = option("--version"), sha256 = option("--sha256");
23719
23918
  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);
23919
+ const bytes = option("--archive") ? readFileSync24(option("--archive")) : await downloadLocalRuntime(version);
23721
23920
  console.log(JSON.stringify(installLocalRuntime(bytes, { version, sha256 }), null, 2));
23722
23921
  } else throw new Error("Use backify runtime install or backify runtime doctor");
23723
23922
  break;
@@ -23732,7 +23931,7 @@ async function main() {
23732
23931
  case "request": {
23733
23932
  const workspaceId = option("--workspace"), name2 = option("--name"), slug = option("--slug"), description = option("--description"), configurationFile = option("--configuration");
23734
23933
  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;
23934
+ const configuration = configurationFile ? JSON.parse(readFileSync24(configurationFile, "utf8")) : void 0;
23736
23935
  console.log(await call("/apps/requests", { method: "POST", body: JSON.stringify({ workspaceId, name: name2, slug, description, configuration }) }));
23737
23936
  break;
23738
23937
  }
@@ -23750,7 +23949,7 @@ async function main() {
23750
23949
  else if (args[0] === "test") {
23751
23950
  const name2 = option("--name"), payload = option("--payload");
23752
23951
  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));
23952
+ 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
23953
  } else throw new Error("Use backify events environments|inspect|test");
23755
23954
  break;
23756
23955
  }