@backifydev/cli 0.3.18 → 0.3.20

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 +358 -352
  2. package/dist/index.js +999 -791
  3. package/package.json +51 -51
package/dist/index.js CHANGED
@@ -16508,8 +16508,8 @@ var require_CronFileParser = __commonJS({
16508
16508
  * @throws If file cannot be read
16509
16509
  */
16510
16510
  static parseFileSync(filePath) {
16511
- const { readFileSync: readFileSync29 } = __require("fs");
16512
- const data = readFileSync29(filePath, "utf8");
16511
+ const { readFileSync: readFileSync30 } = __require("fs");
16512
+ const data = readFileSync30(filePath, "utf8");
16513
16513
  return _CronFileParser.#parseContent(data);
16514
16514
  }
16515
16515
  /**
@@ -34104,22 +34104,22 @@ __export(mcp_exports, {
34104
34104
  createCodingMcpServer: () => createCodingMcpServer,
34105
34105
  runCodingMcpServer: () => runCodingMcpServer
34106
34106
  });
34107
- import { readFileSync as readFileSync26 } from "node:fs";
34107
+ import { readFileSync as readFileSync27 } from "node:fs";
34108
34108
  import { homedir as homedir2 } from "node:os";
34109
- import { join as join20 } from "node:path";
34109
+ import { join as join21 } from "node:path";
34110
34110
  import { createHash as createHash16 } from "node:crypto";
34111
34111
  function createCodingMcpServer(options = {}) {
34112
34112
  const endpoint2 = new URL(options.endpoint ?? process.env.BACKIFY_MCP_URL ?? "https://mcp.backify.dev");
34113
34113
  if (endpoint2.username || endpoint2.password || endpoint2.search || endpoint2.hash || endpoint2.protocol !== "https:" && !(endpoint2.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(endpoint2.hostname)))
34114
34114
  throw new Error("Backify MCP requires HTTPS (HTTP is allowed only on loopback for development).");
34115
- const configPath2 = options.configPath ?? join20(homedir2(), ".backify.json");
34115
+ const configPath2 = options.configPath ?? join21(homedir2(), ".backify.json");
34116
34116
  let boundOrganizationId = options.organizationId;
34117
34117
  let delegated;
34118
34118
  const server = new Server({ name: "backify", version: "0.2.0" }, { capabilities: { tools: {} }, instructions: "This is a transport bridge to the single Backify MCP at https://mcp.backify.dev. Organization permissions and all tool policies are enforced there. Sign-in is an explicit terminal action, never an MCP tool." });
34119
34119
  async function remote(action) {
34120
34120
  let config2;
34121
34121
  try {
34122
- config2 = JSON.parse(readFileSync26(configPath2, "utf8"));
34122
+ config2 = JSON.parse(readFileSync27(configPath2, "utf8"));
34123
34123
  } catch {
34124
34124
  throw new McpError(ErrorCode.InvalidRequest, signIn);
34125
34125
  }
@@ -34180,9 +34180,9 @@ __export(coding_tools_exports, {
34180
34180
  codingTools: () => codingTools,
34181
34181
  configureCodingTool: () => configureCodingTool
34182
34182
  });
34183
- import { existsSync as existsSync16, lstatSync as lstatSync19, mkdirSync as mkdirSync10, readFileSync as readFileSync27, renameSync as renameSync5, unlinkSync as unlinkSync6, writeFileSync as writeFileSync15 } from "node:fs";
34184
- import { basename as basename4, dirname as dirname17, join as join21, resolve as resolve24 } from "node:path";
34185
- import { randomUUID as randomUUID11 } from "node:crypto";
34183
+ import { existsSync as existsSync17, lstatSync as lstatSync20, mkdirSync as mkdirSync10, readFileSync as readFileSync28, renameSync as renameSync5, unlinkSync as unlinkSync6, writeFileSync as writeFileSync16 } from "node:fs";
34184
+ import { basename as basename4, dirname as dirname17, join as join22, resolve as resolve24 } from "node:path";
34185
+ import { randomUUID as randomUUID12 } from "node:crypto";
34186
34186
  function object6(value) {
34187
34187
  return typeof value === "object" && value !== null && !Array.isArray(value);
34188
34188
  }
@@ -34201,11 +34201,11 @@ function configureCodingTool(options) {
34201
34201
  if (!relative11) throw new Error("Open this tool's MCP configuration and supply its exact path with --config. Backify will not guess or modify an editor's global storage.");
34202
34202
  const path = resolve24(options.root ?? process.cwd(), relative11);
34203
34203
  for (let current = path; ; current = dirname17(current)) {
34204
- if (existsSync16(current) && (lstatSync19(current).isSymbolicLink() || current === path && !lstatSync19(current).isFile())) throw new Error("MCP configuration cannot traverse symlinks or replace a directory.");
34204
+ if (existsSync17(current) && (lstatSync20(current).isSymbolicLink() || current === path && !lstatSync20(current).isFile())) throw new Error("MCP configuration cannot traverse symlinks or replace a directory.");
34205
34205
  if (dirname17(current) === current) break;
34206
34206
  }
34207
34207
  if (options.dryRun) return { agent, transport, path, entry: codingToolEntry(agent, transport), changed: void 0 };
34208
- const previous = existsSync16(path) ? readFileSync27(path, "utf8") : void 0;
34208
+ const previous = existsSync17(path) ? readFileSync28(path, "utf8") : void 0;
34209
34209
  let config2;
34210
34210
  try {
34211
34211
  config2 = previous === void 0 ? {} : JSON.parse(previous);
@@ -34222,13 +34222,13 @@ function configureCodingTool(options) {
34222
34222
  const result = { agent, transport, path, entry, changed };
34223
34223
  if (options.dryRun || !changed) return result;
34224
34224
  mkdirSync10(dirname17(path), { recursive: true });
34225
- const temporary = path + "." + randomUUID11() + ".tmp";
34225
+ const temporary = path + "." + randomUUID12() + ".tmp";
34226
34226
  try {
34227
- writeFileSync15(temporary, JSON.stringify({ ...config2, [key]: { ...servers, backify: entry } }, null, 2) + "\n", { flag: "wx", mode: existsSync16(path) ? lstatSync19(path).mode & 511 : 384 });
34228
- if ((existsSync16(path) ? readFileSync27(path, "utf8") : void 0) !== previous) throw new Error("MCP configuration changed during setup. Retry after reviewing it.");
34227
+ writeFileSync16(temporary, JSON.stringify({ ...config2, [key]: { ...servers, backify: entry } }, null, 2) + "\n", { flag: "wx", mode: existsSync17(path) ? lstatSync20(path).mode & 511 : 384 });
34228
+ if ((existsSync17(path) ? readFileSync28(path, "utf8") : void 0) !== previous) throw new Error("MCP configuration changed during setup. Retry after reviewing it.");
34229
34229
  renameSync5(temporary, path);
34230
34230
  } finally {
34231
- if (existsSync16(temporary)) unlinkSync6(temporary);
34231
+ if (existsSync17(temporary)) unlinkSync6(temporary);
34232
34232
  }
34233
34233
  return result;
34234
34234
  }
@@ -34239,13 +34239,66 @@ var init_coding_tools = __esm({
34239
34239
  codingTools = ["copilot", "cursor", "gemini", "cline", "windsurf"];
34240
34240
  endpoint = "https://mcp.backify.dev";
34241
34241
  defaultPaths = {
34242
- copilot: join21(".vscode", "mcp.json"),
34243
- cursor: join21(".cursor", "mcp.json"),
34244
- gemini: join21(".gemini", "settings.json")
34242
+ copilot: join22(".vscode", "mcp.json"),
34243
+ cursor: join22(".cursor", "mcp.json"),
34244
+ gemini: join22(".gemini", "settings.json")
34245
34245
  };
34246
34246
  }
34247
34247
  });
34248
34248
 
34249
+ // src/upgrade.ts
34250
+ import { existsSync, readFileSync, writeFileSync, lstatSync } from "node:fs";
34251
+ import { join } from "node:path";
34252
+ import { spawnSync } from "node:child_process";
34253
+ var stable = (value) => /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.exec(value)?.slice(1).map(Number);
34254
+ function compatibleUpgrade(current, candidate) {
34255
+ const before = stable(current), after = stable(candidate);
34256
+ return !!before && !!after && after[0] === before[0] && (before[0] !== 0 || after[1] === before[1]) && (after[0] > before[0] || after[0] === before[0] && (after[1] > before[1] || after[1] === before[1] && after[2] > before[2]));
34257
+ }
34258
+ function newestCompatible(current, versions) {
34259
+ return versions.filter((value) => compatibleUpgrade(current, value)).sort((a, b) => {
34260
+ const left = stable(a), right = stable(b);
34261
+ return right[0] - left[0] || right[1] - left[1] || right[2] - left[2];
34262
+ })[0];
34263
+ }
34264
+ function upgradeSdk(root = process.cwd(), suppliedRunner) {
34265
+ const run = suppliedRunner ?? ((command3, args2) => {
34266
+ const result = spawnSync(command3, args2, { cwd: root, encoding: "utf8", shell: process.platform === "win32", windowsHide: true, timeout: 6e5, maxBuffer: 4 * 1024 * 1024 });
34267
+ if (result.error || result.status !== 0) throw new Error("Upgrade check failed: " + command3 + " " + args2.join(" "));
34268
+ return result.stdout ?? "";
34269
+ });
34270
+ for (const file of ["package.json", "package-lock.json"]) if (!existsSync(join(root, file)) || !lstatSync(join(root, file)).isFile() || lstatSync(join(root, file)).isSymbolicLink()) throw new Error("Validated SDK upgrades require regular package.json and package-lock.json files.");
34271
+ if (run("git", ["status", "--porcelain"]).trim()) throw new Error("Commit or preserve local changes before upgrading. No files were changed.");
34272
+ const manifestPath = join(root, "package.json"), lockPath = join(root, "package-lock.json");
34273
+ const originalManifest = readFileSync(manifestPath), originalLock = readFileSync(lockPath);
34274
+ const manifest = JSON.parse(originalManifest.toString("utf8"));
34275
+ if (manifest.workspaces) throw new Error("Upgrade SDK dependencies in their owning workspace; automatic root-workspace rewrites are not supported.");
34276
+ if (!manifest.dependencies?.["@backifydev/sdk"] && !manifest.devDependencies?.["@backifydev/sdk"]) throw new Error("This application has no SDK dependency.");
34277
+ const lock = JSON.parse(originalLock.toString("utf8"));
34278
+ const current = lock.packages?.["node_modules/@backifydev/sdk"]?.version;
34279
+ if (typeof current !== "string" || !stable(current)) throw new Error("The SDK lockfile version must be a stable semantic version.");
34280
+ const available = JSON.parse(run("npm", ["view", "@backifydev/sdk", "versions", "--json"]));
34281
+ if (!Array.isArray(available) || available.some((value) => typeof value !== "string")) throw new Error("The SDK registry returned invalid version metadata.");
34282
+ const candidate = newestCompatible(current, available);
34283
+ if (!candidate) return { status: "current", previousVersion: current, version: current, checks: [] };
34284
+ const checks = ["typecheck", "lint", "test", "build"].filter((name2) => typeof manifest.scripts?.[name2] === "string");
34285
+ if (!checks.includes("build") || !checks.some((name2) => name2 === "typecheck" || name2 === "test")) throw new Error("Add a build script and a typecheck or test script before validated upgrades.");
34286
+ try {
34287
+ run("npm", ["install", "--ignore-scripts", "--save-exact", "@backifydev/sdk@" + candidate]);
34288
+ for (const check2 of checks) run("npm", ["run", check2]);
34289
+ return { status: "upgraded", previousVersion: current, version: candidate, checks };
34290
+ } catch (error2) {
34291
+ writeFileSync(manifestPath, originalManifest);
34292
+ writeFileSync(lockPath, originalLock);
34293
+ try {
34294
+ run("npm", ["ci", "--ignore-scripts"]);
34295
+ } catch {
34296
+ throw new Error("SDK upgrade failed. Original manifests were restored, but dependency recovery failed. Run npm ci before starting the app.");
34297
+ }
34298
+ throw new Error("SDK upgrade failed validation. Original manifests and locked dependencies were restored.", { cause: error2 });
34299
+ }
34300
+ }
34301
+
34249
34302
  // src/functions.ts
34250
34303
  import { build } from "esbuild";
34251
34304
 
@@ -35238,7 +35291,7 @@ function unzipSync(data, opts) {
35238
35291
  // src/functions.ts
35239
35292
  import { createRequire as createRequire2 } from "node:module";
35240
35293
  import { dirname, resolve } from "node:path";
35241
- import { existsSync, mkdirSync, writeFileSync } from "node:fs";
35294
+ import { existsSync as existsSync2, mkdirSync, writeFileSync as writeFileSync2 } from "node:fs";
35242
35295
  async function deployFunctions(call2, appId, environmentId, packageBytes, options = {}) {
35243
35296
  const result = await call2("/apps/" + appId + "/functions/environments/" + environmentId + "/deploy?confirm=true", { method: "POST", headers: { "content-type": "application/zip" }, body: packageBytes });
35244
35297
  if (result.status === "succeeded") return;
@@ -35263,7 +35316,7 @@ async function deployFunctions(call2, appId, environmentId, packageBytes, option
35263
35316
  }
35264
35317
  async function packageFunctions(entry, output) {
35265
35318
  const entryPath = resolve(entry);
35266
- if (!existsSync(entryPath)) throw new Error("Function entrypoint does not exist: " + entryPath);
35319
+ if (!existsSync2(entryPath)) throw new Error("Function entrypoint does not exist: " + entryPath);
35267
35320
  const require3 = createRequire2(import.meta.url);
35268
35321
  const azureFunctions = require3.resolve("@azure/functions");
35269
35322
  const result = await build({
@@ -35302,16 +35355,16 @@ async function packageFunctions(entry, output) {
35302
35355
  });
35303
35356
  const outputPath = resolve(output);
35304
35357
  mkdirSync(dirname(outputPath), { recursive: true });
35305
- writeFileSync(outputPath, archive);
35358
+ writeFileSync2(outputPath, archive);
35306
35359
  return outputPath;
35307
35360
  }
35308
35361
 
35309
35362
  // src/environment.ts
35310
- import { spawnSync } from "node:child_process";
35363
+ import { spawnSync as spawnSync2 } from "node:child_process";
35311
35364
  import { randomUUID } from "node:crypto";
35312
- import { readFileSync, unlinkSync, writeFileSync as writeFileSync2 } from "node:fs";
35365
+ import { readFileSync as readFileSync2, unlinkSync, writeFileSync as writeFileSync3 } from "node:fs";
35313
35366
  import { createServer } from "node:http";
35314
- import { join, resolve as resolve2 } from "node:path";
35367
+ import { join as join2, resolve as resolve2 } from "node:path";
35315
35368
 
35316
35369
  // ../platform/dist/manifest.js
35317
35370
  var import_yaml = __toESM(require_dist(), 1);
@@ -35414,12 +35467,12 @@ function manifestDiagnostics(manifest, used, authentication) {
35414
35467
  // ../platform/dist/delivery.js
35415
35468
  var deliveryInstructions = `# Backify application delivery and prompt history
35416
35469
 
35417
- Instruction version: 12
35418
- Versioned guide: https://agent.backify.dev/v12/delivery.md
35470
+ Instruction version: 14
35471
+ Versioned guide: https://agent.backify.dev/v14/delivery.md
35419
35472
 
35420
35473
  ## Environment and documentation prerequisites
35421
35474
 
35422
- Before installation or connection, read https://agent.backify.dev/v12 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.
35475
+ Before installation or connection, read https://agent.backify.dev/v14 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.
35423
35476
 
35424
35477
  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.
35425
35478
 
@@ -35427,7 +35480,13 @@ These instructions are for AI coding tools building applications on Backify, not
35427
35480
 
35428
35481
  ## Connect and initialize
35429
35482
 
35430
- The copied Backify prompt supplies App Id, Organization, and, when available, Pair, plus this guide reference and a privacy warning. Substitute those values for <app-id>, <organization-id>, and <pairing-code> below; never invent them. Use npx @backifydev/cli@latest so tool-specific setup and metadata-preserving cloning are available. The public API URL is https://api.backify.dev/api. For a nonproduction environment, replace the --api value with an explicitly trusted endpoint, or omit --api when using a trusted BACKIFY_API_URL override; never send a pairing code to an unverified endpoint.
35483
+ The minimal setup prompt supplies only this guide reference and a public app reference. It contains no credential and grants no access by itself. Assume a fresh machine: follow the versioned setup guide to check and install missing Node.js/npm and Git prerequisites using supported permissions, then invoke the CLI through npx; no global CLI installation is required. Use the public app reference as <app-id>:
35484
+
35485
+ npx @backifydev/cli@latest connect --app <app-id> --reauth --api https://api.backify.dev/api
35486
+
35487
+ Add --clone according to the workspace rules below. Keep the CLI running while the user signs in at https://auth.backify.dev, selects the app's organization and explicitly approves application-scoped device access. The CLI receives the organization and credential directly; never ask for tokens or organization IDs in chat. Check the completed command result and retrieve app context using CLI status. Browser approval does not authorize production deployment. If authorization is cancelled, denied or times out, report the blocker and use only supported recovery.
35488
+
35489
+ For compatibility, legacy prompts may supply App Id, Organization, and Pair. Substitute those values for <app-id>, <organization-id>, and <pairing-code> below; never invent them. Use npx @backifydev/cli@latest so tool-specific setup and metadata-preserving cloning are available. The public API URL is https://api.backify.dev/api. For a nonproduction environment, replace the --api value with an explicitly trusted endpoint, or omit --api when using a trusted BACKIFY_API_URL override; never send a pairing code to an unverified endpoint.
35431
35490
 
35432
35491
  npx @backifydev/cli@latest connect --app <app-id> --organization <organization-id> --api https://api.backify.dev/api --pair-stdin
35433
35492
 
@@ -35439,7 +35498,7 @@ Initialize using App Id from the copied prompt and the current tool selection:
35439
35498
 
35440
35499
  npx @backifydev/cli@latest init --app <app-id> --agent <current-tool>
35441
35500
 
35442
- 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/v12 for instruction version 12; 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.
35501
+ 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/v14 for instruction version 13; 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.
35443
35502
 
35444
35503
  Run the following to discover the connected hosting target, repository, branch, reports, releases, and deployment failures:
35445
35504
 
@@ -35521,7 +35580,7 @@ These instructions are an explicit agent workflow, not a universal chat intercep
35521
35580
  `;
35522
35581
 
35523
35582
  // ../platform/dist/index.js
35524
- var INSTRUCTION_VERSION = 12;
35583
+ var INSTRUCTION_VERSION = 14;
35525
35584
  var SDK_PACKAGE = "@backifydev/sdk";
35526
35585
  var DOCS_URL = "https://docs.backify.dev";
35527
35586
  var MAIL_LIMITS = Object.freeze({
@@ -35590,6 +35649,11 @@ Keep secrets server-side. Never commit or log credentials, expose secrets to bro
35590
35649
  Scope cookies to the exact application hostname by omitting the \`Domain\` attribute. Never use a parent-domain cookie unless explicitly required.
35591
35650
  Require explicit confirmation before destructive data operations or removing stateful resources. Removing a capability declaration does not authorize deleting its data.
35592
35651
 
35652
+ ## Application defaults
35653
+
35654
+ When authentication is required, use email magic links by default and ask the builder which implemented additional providers to enable. Provider-specific setup and secure configuration remain available in the application Authentication page and portal. Preserve existing providers and email defaults; explicitly request method magic-link in newly built embedded email forms. Use reviewed local identities and the private CLI inbox to verify magic links locally; do not infer roles from email or fabricate provider support.
35655
+ Read the authenticated developer status branding snapshot before building a new application. Use supplied branding as flexible visual defaults; complete missing design elements as needed and never restrict application functionality because branding is incomplete. Existing applications keep their own branding unless a change is requested.
35656
+
35593
35657
  ## Implementation workflow
35594
35658
 
35595
35659
  Inspect the framework, lockfile, scripts, configuration, and applicable repository instructions before editing. Preserve the existing framework and unrelated work. Implement the requested application rather than stopping at SDK setup; ask what to build if requirements are missing.
@@ -35712,13 +35776,13 @@ async function probeEndpoint(url2, transport = fetch) {
35712
35776
  }
35713
35777
  function workspaceProbe(root) {
35714
35778
  const directory2 = resolve2(root);
35715
- const filename2 = join(directory2, ".backify-environment-" + randomUUID());
35779
+ const filename2 = join2(directory2, ".backify-environment-" + randomUUID());
35716
35780
  const content = randomUUID();
35717
35781
  let created = false;
35718
35782
  try {
35719
- writeFileSync2(filename2, content, { flag: "wx" });
35783
+ writeFileSync3(filename2, content, { flag: "wx" });
35720
35784
  created = true;
35721
- if (readFileSync(filename2, "utf8") !== content) throw new Error("Workspace read/write failed.");
35785
+ if (readFileSync2(filename2, "utf8") !== content) throw new Error("Workspace read/write failed.");
35722
35786
  } finally {
35723
35787
  if (created) unlinkSync(filename2);
35724
35788
  }
@@ -35748,7 +35812,7 @@ function environmentProbes(root) {
35748
35812
  const windowsNpm = name2 === "npm" && process.platform === "win32";
35749
35813
  const executable = windowsNpm ? process.env.ComSpec ?? "cmd.exe" : name2;
35750
35814
  const argumentsList = windowsNpm ? ["/d", "/s", "/c", "npm.cmd --version"] : ["--version"];
35751
- const result = spawnSync(executable, argumentsList, { timeout: 5e3, stdio: "ignore", windowsHide: true });
35815
+ const result = spawnSync2(executable, argumentsList, { timeout: 5e3, stdio: "ignore", windowsHide: true });
35752
35816
  if (result.error) throw result.error;
35753
35817
  if (result.status !== 0) throw Object.assign(new Error("Prerequisite command failed."), { code: result.status === 127 || result.status === 9009 ? "ENOENT" : void 0 });
35754
35818
  },
@@ -35846,7 +35910,7 @@ import { hostname, platform, release, arch } from "node:os";
35846
35910
  // package.json
35847
35911
  var package_default = {
35848
35912
  name: "@backifydev/cli",
35849
- version: "0.3.18",
35913
+ version: "0.3.20",
35850
35914
  description: "Command-line setup and diagnostics for Backify applications",
35851
35915
  type: "module",
35852
35916
  bin: {
@@ -35881,7 +35945,7 @@ var package_default = {
35881
35945
  dependencies: {
35882
35946
  "@modelcontextprotocol/sdk": "^1.31.0",
35883
35947
  "@azure/functions": "^4.7.2",
35884
- "@backifydev/sdk": "^0.1.1",
35948
+ "@backifydev/sdk": "^0.1.13",
35885
35949
  esbuild: "^0.25.10",
35886
35950
  fflate: "^0.8.2",
35887
35951
  typescript: "^5.9.2"
@@ -35911,60 +35975,60 @@ import { randomBytes } from "node:crypto";
35911
35975
  import { createServer as createServer2 } from "node:http";
35912
35976
 
35913
35977
  // src/development.ts
35914
- import { existsSync as existsSync6, readFileSync as readFileSync6, readdirSync as readdirSync2, writeFileSync as writeFileSync5, renameSync, rmSync, mkdtempSync, lstatSync as lstatSync2, cpSync } from "node:fs";
35915
- import { dirname as dirname4, join as join6, resolve as resolve4 } from "node:path";
35916
- import { spawnSync as spawnSync3 } from "node:child_process";
35978
+ import { existsSync as existsSync7, readFileSync as readFileSync7, readdirSync as readdirSync2, writeFileSync as writeFileSync6, renameSync, rmSync, mkdtempSync, lstatSync as lstatSync3, cpSync } from "node:fs";
35979
+ import { dirname as dirname4, join as join7, resolve as resolve4 } from "node:path";
35980
+ import { spawnSync as spawnSync4 } from "node:child_process";
35917
35981
  import { randomUUID as randomUUID2 } from "node:crypto";
35918
35982
 
35919
35983
  // src/setup.ts
35920
- import { existsSync as existsSync4, readFileSync as readFileSync4, writeFileSync as writeFileSync4, mkdirSync as mkdirSync2, readdirSync, lstatSync } from "node:fs";
35921
- import { basename, dirname as dirname3, join as join4, resolve as resolve3, isAbsolute } from "node:path";
35922
- import { spawnSync as spawnSync2 } from "node:child_process";
35984
+ import { existsSync as existsSync5, readFileSync as readFileSync5, writeFileSync as writeFileSync5, mkdirSync as mkdirSync2, readdirSync, lstatSync as lstatSync2 } from "node:fs";
35985
+ import { basename, dirname as dirname3, join as join5, resolve as resolve3, isAbsolute } from "node:path";
35986
+ import { spawnSync as spawnSync3 } from "node:child_process";
35923
35987
 
35924
35988
  // src/delivery.ts
35925
- import { existsSync as existsSync2, readFileSync as readFileSync2, writeFileSync as writeFileSync3 } from "node:fs";
35926
- import { dirname as dirname2, join as join2, relative as relativePath } from "node:path";
35989
+ import { existsSync as existsSync3, readFileSync as readFileSync3, writeFileSync as writeFileSync4 } from "node:fs";
35990
+ import { dirname as dirname2, join as join3, relative as relativePath } from "node:path";
35927
35991
  import { createHash } from "node:crypto";
35928
35992
  var previousGeneratedWorkflowHashes = /* @__PURE__ */ new Set(["33e962274e8493f7cbac2afbac05a4e96afeec49ee08cf2bf82f8add9081b28b", "578dfb4c771c623fd04454e8a604efd701d5563d11e11191324862369bd24718", "6eb280ae7bdb14c390011686c41400f59c023304c3015d8440b7e80aaafa1c11", "545e03a1d5b996ade179e0e60ed5c86accdadc1982c1c25efd094e34f72f47ee"]);
35929
35993
  function validateDeliveryInstructions(root) {
35930
35994
  for (const filename2 of ["BACKIFY.md", "BACKIFY-WORKFLOW.md"]) {
35931
- const path = join2(root, filename2);
35932
- if (existsSync2(path)) {
35933
- const existing = readFileSync2(path, "utf8").replace(/\r\n/g, "\n");
35995
+ const path = join3(root, filename2);
35996
+ if (existsSync3(path)) {
35997
+ const existing = readFileSync3(path, "utf8").replace(/\r\n/g, "\n");
35934
35998
  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.");
35935
35999
  }
35936
36000
  }
35937
36001
  }
35938
36002
  function installDeliveryInstructions(root, instructionFiles2) {
35939
36003
  validateDeliveryInstructions(root);
35940
- writeFileSync3(join2(root, "BACKIFY.md"), deliveryInstructions);
36004
+ writeFileSync4(join3(root, "BACKIFY.md"), deliveryInstructions);
35941
36005
  for (const relative11 of instructionFiles2) {
35942
- const instructionPath = join2(root, relative11), content = readFileSync2(instructionPath, "utf8");
35943
- const link = relativePath(dirname2(instructionPath), join2(root, "BACKIFY.md")).replaceAll("\\", "/");
35944
- const legacyLink = relativePath(dirname2(instructionPath), join2(root, "BACKIFY-WORKFLOW.md")).replaceAll("\\", "/");
36006
+ const instructionPath = join3(root, relative11), content = readFileSync3(instructionPath, "utf8");
36007
+ const link = relativePath(dirname2(instructionPath), join3(root, "BACKIFY.md")).replaceAll("\\", "/");
36008
+ const legacyLink = relativePath(dirname2(instructionPath), join3(root, "BACKIFY-WORKFLOW.md")).replaceAll("\\", "/");
35945
36009
  const legacy = "For application delivery and recording each user request, follow [BACKIFY-WORKFLOW.md](" + legacyLink + ").";
35946
36010
  const guidance = "For application delivery and recording each user request, follow [BACKIFY.md](" + link + ").";
35947
- if (content.includes(legacy)) writeFileSync3(instructionPath, content.replace(legacy, guidance));
35948
- else if (!content.includes("## Backify delivery")) writeFileSync3(instructionPath, content.trimEnd() + "\n\n## Backify delivery\n\n" + guidance + "\n");
36011
+ if (content.includes(legacy)) writeFileSync4(instructionPath, content.replace(legacy, guidance));
36012
+ else if (!content.includes("## Backify delivery")) writeFileSync4(instructionPath, content.trimEnd() + "\n\n## Backify delivery\n\n" + guidance + "\n");
35949
36013
  }
35950
36014
  }
35951
36015
 
35952
36016
  // src/application-support.ts
35953
- import { existsSync as existsSync3, readFileSync as readFileSync3 } from "node:fs";
35954
- import { join as join3 } from "node:path";
36017
+ import { existsSync as existsSync4, readFileSync as readFileSync4 } from "node:fs";
36018
+ import { join as join4 } from "node:path";
35955
36019
  function applicationSupport(root) {
35956
- const manifestPath = join3(root, "package.json");
35957
- const manifest = existsSync3(manifestPath) ? JSON.parse(readFileSync3(manifestPath, "utf8")) : {};
36020
+ const manifestPath = join4(root, "package.json");
36021
+ const manifest = existsSync4(manifestPath) ? JSON.parse(readFileSync4(manifestPath, "utf8")) : {};
35958
36022
  const dependencies = { ...manifest.devDependencies, ...manifest.dependencies };
35959
36023
  const framework = ["next", "astro", "@sveltejs/kit", "nuxt", "express", "vite", "react"].find((name2) => dependencies[name2]) ?? "unknown";
35960
- if (existsSync3(join3(root, "Dockerfile"))) {
36024
+ if (existsSync4(join4(root, "Dockerfile"))) {
35961
36025
  return { tier: "advanced", framework, guidance: "Custom-container hosting is an advanced path, not a guarantee of Backify SDK integration or framework support. Preserve the Dockerfile and verify capability integration separately." };
35962
36026
  }
35963
36027
  if (framework === "vite" && dependencies.react) {
35964
36028
  return { tier: "recommended", framework, guidance: "React with Vite is the recommended frontend baseline. Prefer TypeScript for new code and use an explicit Backify TypeScript backend for server capabilities. This assessment does not verify deployment or authorization." };
35965
36029
  }
35966
36030
  return {
35967
- tier: existsSync3(manifestPath) ? "compatible" : "unassessed",
36031
+ tier: existsSync4(manifestPath) ? "compatible" : "unassessed",
35968
36032
  framework,
35969
36033
  guidance: "Backify is TypeScript-first. For new apps, prefer React with Vite and an explicit Backify TypeScript backend. Preserve existing JavaScript/TypeScript frameworks; assess SSR, build, identity and capability integration before claiming support. Browser-only apps do not require Node.js in production."
35970
36034
  };
@@ -35972,9 +36036,9 @@ function applicationSupport(root) {
35972
36036
 
35973
36037
  // src/setup.ts
35974
36038
  var instructionFiles = ["AGENTS.md"];
35975
- var agentInstructionFiles = { codex: "AGENTS.md", claude: "CLAUDE.md", copilot: join4(".github", "copilot-instructions.md"), gemini: "GEMINI.md", cursor: "AGENTS.md", cline: join4(".clinerules", "backify.md"), windsurf: "AGENTS.md" };
36039
+ var agentInstructionFiles = { codex: "AGENTS.md", claude: "CLAUDE.md", copilot: join5(".github", "copilot-instructions.md"), gemini: "GEMINI.md", cursor: "AGENTS.md", cline: join5(".clinerules", "backify.md"), windsurf: "AGENTS.md" };
35976
36040
  function instructionSelection(root, agent, instructionFile) {
35977
- const configPath2 = join4(root, "backify.json"), configured = existsSync4(configPath2) ? JSON.parse(readFileSync4(configPath2, "utf8")) : {};
36041
+ const configPath2 = join5(root, "backify.json"), configured = existsSync5(configPath2) ? JSON.parse(readFileSync5(configPath2, "utf8")) : {};
35978
36042
  const custom2 = instructionFile ?? (agent === void 0 ? configured.instructionFile : void 0);
35979
36043
  const selected = instructionFile !== void 0 ? "custom" : agent ?? configured.agent ?? "codex";
35980
36044
  if (typeof selected !== "string" || selected !== "custom" && !Object.hasOwn(agentInstructionFiles, selected)) throw new Error("Select the current tool with --agent or --instruction-file <relative-path>.");
@@ -35983,9 +36047,9 @@ function instructionSelection(root, agent, instructionFile) {
35983
36047
  const normalized = filename2.replaceAll("\\", "/"), parts = normalized.split("/");
35984
36048
  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.");
35985
36049
  for (let index = 1; index <= parts.length; index++) {
35986
- const entry = join4(root, ...parts.slice(0, index));
36050
+ const entry = join5(root, ...parts.slice(0, index));
35987
36051
  try {
35988
- const metadata = lstatSync(entry);
36052
+ const metadata = lstatSync2(entry);
35989
36053
  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.");
35990
36054
  } catch (reason) {
35991
36055
  if (reason.code !== "ENOENT") throw reason;
@@ -35998,26 +36062,26 @@ function selectedInstructionFiles(root = process.cwd(), agent, instructionFile)
35998
36062
  }
35999
36063
  function isToolWorkspaceEntry(entry, root = process.cwd()) {
36000
36064
  if (entry.name.toLowerCase() === ".git" || entry.name.toLowerCase() === ".env" || entry.name.toLowerCase().startsWith(".env.")) return false;
36001
- return entry.isDirectory() && (entry.name.startsWith(".") || ["work", "outputs"].includes(entry.name) || readdirSync(join4(root, entry.name)).length === 0) || entry.isFile() && (entry.name.startsWith(".") || /\.(md|mdc)$/i.test(entry.name));
36065
+ return entry.isDirectory() && (entry.name.startsWith(".") || ["work", "outputs"].includes(entry.name) || readdirSync(join5(root, entry.name)).length === 0) || entry.isFile() && (entry.name.startsWith(".") || /\.(md|mdc)$/i.test(entry.name));
36002
36066
  }
36003
36067
  function detectPackageManager(root = process.cwd()) {
36004
- for (const [file, name2] of [["pnpm-lock.yaml", "pnpm"], ["yarn.lock", "yarn"], ["bun.lockb", "bun"], ["bun.lock", "bun"], ["package-lock.json", "npm"]]) if (existsSync4(join4(root, file))) return name2;
36068
+ for (const [file, name2] of [["pnpm-lock.yaml", "pnpm"], ["yarn.lock", "yarn"], ["bun.lockb", "bun"], ["bun.lock", "bun"], ["package-lock.json", "npm"]]) if (existsSync5(join5(root, file))) return name2;
36005
36069
  return "npm";
36006
36070
  }
36007
36071
  function updateInstructions(root = process.cwd(), agent, instructionFile) {
36008
36072
  const updates = selectedInstructionFiles(root, agent, instructionFile).map((relative11) => {
36009
- const path = join4(root, relative11);
36010
- return { path, content: updateManagedInstructions(existsSync4(path) ? readFileSync4(path, "utf8") : "") };
36073
+ const path = join5(root, relative11);
36074
+ return { path, content: updateManagedInstructions(existsSync5(path) ? readFileSync5(path, "utf8") : "") };
36011
36075
  });
36012
36076
  for (const { path, content } of updates) {
36013
36077
  mkdirSync2(dirname3(path), { recursive: true });
36014
- writeFileSync4(path, content);
36078
+ writeFileSync5(path, content);
36015
36079
  }
36016
36080
  }
36017
36081
  function synchronize(root = process.cwd(), agent, instructionFile) {
36018
- const path = join4(root, "backify.json");
36019
- if (!existsSync4(path)) throw new Error("backify.json is missing; run backify init --app app_xxxxx");
36020
- const value = JSON.parse(readFileSync4(path, "utf8")), issues = validateConfig(value);
36082
+ const path = join5(root, "backify.json");
36083
+ if (!existsSync5(path)) throw new Error("backify.json is missing; run backify init --app app_xxxxx");
36084
+ const value = JSON.parse(readFileSync5(path, "utf8")), issues = validateConfig(value);
36021
36085
  if (issues.length) throw new Error(issues.join("; "));
36022
36086
  if (value.instructionVersion > INSTRUCTION_VERSION) throw new Error("This app uses newer instructions. Install a matching or newer CLI before syncing.");
36023
36087
  const selected = instructionSelection(root, agent, instructionFile);
@@ -36027,11 +36091,11 @@ function synchronize(root = process.cwd(), agent, instructionFile) {
36027
36091
  value.agent = selected.agent;
36028
36092
  value.instructionFile = selected.instructionFile;
36029
36093
  value.instructionVersion = INSTRUCTION_VERSION;
36030
- writeFileSync4(path, JSON.stringify(value, null, 2) + "\n");
36094
+ writeFileSync5(path, JSON.stringify(value, null, 2) + "\n");
36031
36095
  }
36032
36096
  function sdkInstalled(root = process.cwd()) {
36033
36097
  try {
36034
- const pkg = JSON.parse(readFileSync4(join4(root, "package.json"), "utf8"));
36098
+ const pkg = JSON.parse(readFileSync5(join5(root, "package.json"), "utf8"));
36035
36099
  return Boolean(pkg.dependencies?.[SDK_PACKAGE] || pkg.devDependencies?.[SDK_PACKAGE]);
36036
36100
  } catch {
36037
36101
  return false;
@@ -36039,29 +36103,29 @@ function sdkInstalled(root = process.cwd()) {
36039
36103
  }
36040
36104
  function installSdk(root = process.cwd()) {
36041
36105
  if (sdkInstalled(root)) return;
36042
- 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" });
36106
+ const manager = detectPackageManager(root), args2 = manager === "npm" ? ["install", SDK_PACKAGE] : ["add", SDK_PACKAGE], result = spawnSync3(manager, args2, { cwd: root, stdio: "inherit", shell: process.platform === "win32" });
36043
36107
  if (result.status !== 0) throw new Error(`Could not install ${SDK_PACKAGE} with ${manager}`);
36044
36108
  }
36045
36109
  function ensurePackageManifest(root) {
36046
- const path = join4(root, "package.json");
36047
- if (existsSync4(path)) return;
36110
+ const path = join5(root, "package.json");
36111
+ if (existsSync5(path)) return;
36048
36112
  const setupFiles = /* @__PURE__ */ new Set([".git", ".gitignore", ".github", "AGENTS.md", "CLAUDE.md", "GEMINI.md", "BACKIFY.md", "BACKIFY-WORKFLOW.md", "README.md", "LICENSE", "backify.json"]);
36049
36113
  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/");
36050
36114
  const name2 = basename(resolve3(root)).toLowerCase().replace(/[^a-z0-9-]+/g, "-").replace(/^-+|-+$/g, "") || "backify-app";
36051
- writeFileSync4(path, JSON.stringify({ name: name2, version: "0.0.0", private: true, type: "module" }, null, 2) + "\n", { flag: "wx" });
36115
+ writeFileSync5(path, JSON.stringify({ name: name2, version: "0.0.0", private: true, type: "module" }, null, 2) + "\n", { flag: "wx" });
36052
36116
  }
36053
36117
  function initialize(appId, root = process.cwd(), install = true, agent, instructionFile) {
36054
36118
  if (!/^app_[A-Za-z0-9_-]+$/.test(appId)) throw new Error("Provide an application ID using --app app_xxxxx");
36055
36119
  const selected = instructionSelection(root, agent, instructionFile), files = selected.files;
36056
36120
  validateDeliveryInstructions(root);
36057
- for (const relative11 of files) if (existsSync4(join4(root, relative11))) updateManagedInstructions(readFileSync4(join4(root, relative11), "utf8"));
36058
- const customContainer = !existsSync4(join4(root, "package.json")) && existsSync4(join4(root, "Dockerfile"));
36121
+ for (const relative11 of files) if (existsSync5(join5(root, relative11))) updateManagedInstructions(readFileSync5(join5(root, relative11), "utf8"));
36122
+ const customContainer = !existsSync5(join5(root, "package.json")) && existsSync5(join5(root, "Dockerfile"));
36059
36123
  if (!customContainer) {
36060
36124
  ensurePackageManifest(root);
36061
36125
  if (install) installSdk(root);
36062
36126
  }
36063
- const configPath2 = join4(root, "backify.json"), existing = existsSync4(configPath2) ? JSON.parse(readFileSync4(configPath2, "utf8")) : {};
36064
- writeFileSync4(configPath2, JSON.stringify({ ...existing, ...createConfig(appId), agent: selected.agent, instructionFile: selected.instructionFile }, null, 2) + "\n");
36127
+ const configPath2 = join5(root, "backify.json"), existing = existsSync5(configPath2) ? JSON.parse(readFileSync5(configPath2, "utf8")) : {};
36128
+ writeFileSync5(configPath2, JSON.stringify({ ...existing, ...createConfig(appId), agent: selected.agent, instructionFile: selected.instructionFile }, null, 2) + "\n");
36065
36129
  updateInstructions(root, selected.agent, selected.instructionFile);
36066
36130
  installDeliveryInstructions(root, files);
36067
36131
  }
@@ -36075,17 +36139,17 @@ function doctor(root = process.cwd(), agent, instructionFile) {
36075
36139
  issues.push("package.json is invalid JSON");
36076
36140
  }
36077
36141
  if (!sdkInstalled(root)) {
36078
- if (!existsSync4(join4(root, "package.json")) && existsSync4(join4(root, "Dockerfile"))) warnings.push("Custom container: JavaScript SDK capabilities are not validated. Use only supported Backify integrations for this language.");
36142
+ if (!existsSync5(join5(root, "package.json")) && existsSync5(join5(root, "Dockerfile"))) warnings.push("Custom container: JavaScript SDK capabilities are not validated. Use only supported Backify integrations for this language.");
36079
36143
  else issues.push(`${SDK_PACKAGE} is not installed`);
36080
36144
  }
36081
36145
  let config2;
36082
36146
  try {
36083
- config2 = JSON.parse(readFileSync4(join4(root, "backify.json"), "utf8"));
36147
+ config2 = JSON.parse(readFileSync5(join5(root, "backify.json"), "utf8"));
36084
36148
  issues.push(...validateConfig(config2));
36085
36149
  } catch {
36086
36150
  issues.push("backify.json is missing or invalid JSON");
36087
36151
  }
36088
- if (config2 && config2.instructionVersion !== INSTRUCTION_VERSION) issues.push(`Repository instruction version ${config2.instructionVersion}; CLI version ${INSTRUCTION_VERSION}. Use the matching CLI or run backify sync to upgrade.`);
36152
+ if (config2 && config2.instructionVersion > INSTRUCTION_VERSION) issues.push(`Repository instruction version ${config2.instructionVersion}; CLI version ${INSTRUCTION_VERSION}. Use the matching CLI or run backify sync to upgrade.`);
36089
36153
  let files = instructionFiles;
36090
36154
  try {
36091
36155
  files = selectedInstructionFiles(root, agent, instructionFile);
@@ -36093,16 +36157,24 @@ function doctor(root = process.cwd(), agent, instructionFile) {
36093
36157
  issues.push(reason instanceof Error ? reason.message : String(reason));
36094
36158
  }
36095
36159
  for (const relative11 of files) {
36096
- const path = join4(root, relative11);
36097
- if (!existsSync4(path)) {
36160
+ const path = join5(root, relative11);
36161
+ if (!existsSync5(path)) {
36098
36162
  issues.push(`${relative11} is missing`);
36099
36163
  continue;
36100
36164
  }
36101
- issues.push(...managedInstructionIssues(readFileSync4(path, "utf8")).map((issue2) => `${relative11} ${issue2}`));
36165
+ const content = readFileSync5(path, "utf8");
36166
+ const managed = managedInstructionIssues(content);
36167
+ if (config2 && config2.instructionVersion < INSTRUCTION_VERSION) {
36168
+ const declared = content.match(/Instruction version:\s*(\d+)/)?.[1];
36169
+ const structural = managed.filter((issue2) => !issue2.includes("stale or inconsistent"));
36170
+ issues.push(...structural.map((issue2) => relative11 + " " + issue2));
36171
+ if (Number(declared) !== config2.instructionVersion || !content.includes("https://agent.backify.dev/v" + config2.instructionVersion)) issues.push(relative11 + " does not match the repository instruction version");
36172
+ else warnings.push(relative11 + " uses supported older instructions; follow the versioned guide. Run backify sync only when intentionally upgrading instructions.");
36173
+ } else issues.push(...managed.map((issue2) => relative11 + " " + issue2));
36102
36174
  }
36103
36175
  let version2 = "unknown";
36104
36176
  try {
36105
- const pkg = JSON.parse(readFileSync4(join4(root, "package.json"), "utf8"));
36177
+ const pkg = JSON.parse(readFileSync5(join5(root, "package.json"), "utf8"));
36106
36178
  version2 = pkg.dependencies?.[SDK_PACKAGE] ?? pkg.devDependencies?.[SDK_PACKAGE] ?? "missing";
36107
36179
  } catch {
36108
36180
  }
@@ -36110,14 +36182,14 @@ function doctor(root = process.cwd(), agent, instructionFile) {
36110
36182
  }
36111
36183
 
36112
36184
  // src/container-build.ts
36113
- import { existsSync as existsSync5, readFileSync as readFileSync5 } from "node:fs";
36114
- import { join as join5 } from "node:path";
36185
+ import { existsSync as existsSync6, readFileSync as readFileSync6 } from "node:fs";
36186
+ import { join as join6 } from "node:path";
36115
36187
  function containerBuildSupport(root) {
36116
- if (existsSync5(join5(root, "Dockerfile"))) return { adapter: "custom-container", issue: null };
36117
- if (!existsSync5(join5(root, "package.json"))) return { adapter: null, issue: "Provide a repository-root Dockerfile serving HTTP on port 8080 for this language. Local Docker is not required." };
36118
- const manifest = JSON.parse(readFileSync5(join5(root, "package.json"), "utf8"));
36119
- if (!existsSync5(join5(root, "package-lock.json"))) return { adapter: null, issue: "Managed Node builds require package-lock.json. Generate and commit the npm lockfile, or provide a custom Dockerfile." };
36120
- if (typeof manifest.scripts?.start !== "string" || !manifest.scripts.start || manifest.workspaces || ["pnpm-lock.yaml", "yarn.lock"].some((name2) => existsSync5(join5(root, name2)))) {
36188
+ if (existsSync6(join6(root, "Dockerfile"))) return { adapter: "custom-container", issue: null };
36189
+ if (!existsSync6(join6(root, "package.json"))) return { adapter: null, issue: "Provide a repository-root Dockerfile serving HTTP on port 8080 for this language. Local Docker is not required." };
36190
+ const manifest = JSON.parse(readFileSync6(join6(root, "package.json"), "utf8"));
36191
+ if (!existsSync6(join6(root, "package-lock.json"))) return { adapter: null, issue: "Managed Node builds require package-lock.json. Generate and commit the npm lockfile, or provide a custom Dockerfile." };
36192
+ if (typeof manifest.scripts?.start !== "string" || !manifest.scripts.start || manifest.workspaces || ["pnpm-lock.yaml", "yarn.lock"].some((name2) => existsSync6(join6(root, name2)))) {
36121
36193
  return { adapter: null, issue: "Managed Node builds require an npm application with a start script at the repository root. Workspaces and other package managers require a custom Dockerfile." };
36122
36194
  }
36123
36195
  return { adapter: "node-npm", issue: null };
@@ -36135,10 +36207,10 @@ function promptContext(root = process.cwd()) {
36135
36207
  function installedSdkVersion(root) {
36136
36208
  let directory2 = resolve4(root);
36137
36209
  while (true) {
36138
- const manifest = join6(directory2, "node_modules", "@backifydev", "sdk", "package.json");
36139
- if (existsSync6(manifest)) {
36210
+ const manifest = join7(directory2, "node_modules", "@backifydev", "sdk", "package.json");
36211
+ if (existsSync7(manifest)) {
36140
36212
  try {
36141
- const sdk = JSON.parse(readFileSync6(manifest, "utf8"));
36213
+ const sdk = JSON.parse(readFileSync7(manifest, "utf8"));
36142
36214
  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;
36143
36215
  } catch {
36144
36216
  return null;
@@ -36180,8 +36252,8 @@ function applicationGuid(appId) {
36180
36252
  return [value.slice(0, 8), value.slice(8, 12), value.slice(12, 16), value.slice(16, 20), value.slice(20)].join("-");
36181
36253
  }
36182
36254
  function projectApplication(root = process.cwd()) {
36183
- if (!existsSync6(join6(root, "backify.json"))) throw new Error("Run backify connect --app <application-id>, then backify init.");
36184
- return JSON.parse(readFileSync6(join6(root, "backify.json"), "utf8")).appId;
36255
+ if (!existsSync7(join7(root, "backify.json"))) throw new Error("Run backify connect --app <application-id>, then backify init.");
36256
+ return JSON.parse(readFileSync7(join7(root, "backify.json"), "utf8")).appId;
36185
36257
  }
36186
36258
  function apiAddress(value) {
36187
36259
  const address = new URL(value);
@@ -36216,11 +36288,11 @@ function apiClient(session, transport = fetch) {
36216
36288
  function saveUserConfig(path, config2) {
36217
36289
  const temporary = path + "." + randomUUID2() + ".tmp";
36218
36290
  try {
36219
- writeFileSync5(temporary, JSON.stringify(config2, null, 2) + "\n", { mode: 384, flag: "wx" });
36291
+ writeFileSync6(temporary, JSON.stringify(config2, null, 2) + "\n", { mode: 384, flag: "wx" });
36220
36292
  if (process.platform === "win32") {
36221
36293
  const account = [process.env.USERDOMAIN, process.env.USERNAME].filter(Boolean).join("\\");
36222
36294
  if (!account) throw new Error("Cannot identify the account to protect CLI credentials.");
36223
- const secured = spawnSync3("icacls", [temporary, "/inheritance:r", "/grant:r", account + ":(F)"], { windowsHide: true, encoding: "utf8" });
36295
+ const secured = spawnSync4("icacls", [temporary, "/inheritance:r", "/grant:r", account + ":(F)"], { windowsHide: true, encoding: "utf8" });
36224
36296
  if (secured.status !== 0) throw new Error("Could not restrict CLI credential file permissions.");
36225
36297
  }
36226
36298
  renameSync(temporary, path);
@@ -36234,7 +36306,7 @@ function repositoryName(remote) {
36234
36306
  return match[1].toLowerCase();
36235
36307
  }
36236
36308
  function git(args2, root = process.cwd(), environment = process.env) {
36237
- const result = spawnSync3("git", args2, { cwd: root, env: environment, encoding: "utf8", windowsHide: true, maxBuffer: 2 * 1024 * 1024 });
36309
+ const result = spawnSync4("git", args2, { cwd: root, env: environment, encoding: "utf8", windowsHide: true, maxBuffer: 2 * 1024 * 1024 });
36238
36310
  if (result.status !== 0) throw new Error("Git " + args2[0] + " failed. Check repository access, branch protection, and local changes.");
36239
36311
  return result.stdout.trim();
36240
36312
  }
@@ -36244,15 +36316,15 @@ function gitEnvironment(repository, token) {
36244
36316
  }
36245
36317
  function validateCloneMerge(source, target) {
36246
36318
  for (const entry of readdirSync2(source, { withFileTypes: true })) {
36247
- const destination = join6(target, entry.name);
36319
+ const destination = join7(target, entry.name);
36248
36320
  let existing;
36249
36321
  try {
36250
- existing = lstatSync2(destination);
36322
+ existing = lstatSync3(destination);
36251
36323
  } catch (reason) {
36252
36324
  if (reason.code === "ENOENT") continue;
36253
36325
  throw reason;
36254
36326
  }
36255
- if (entry.isDirectory() && existing.isDirectory() && !existing.isSymbolicLink()) validateCloneMerge(join6(source, entry.name), destination);
36327
+ if (entry.isDirectory() && existing.isDirectory() && !existing.isSymbolicLink()) validateCloneMerge(join7(source, entry.name), destination);
36256
36328
  else throw new Error("Clone conflicts with existing workspace entry: " + destination + ". Existing files are never overwritten; reconcile the conflict or use a new folder.");
36257
36329
  }
36258
36330
  }
@@ -36262,18 +36334,18 @@ async function cloneProject(call2, appId, root = process.cwd()) {
36262
36334
  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.");
36263
36335
  const credential = await call2("/apps/" + applicationGuid(appId) + "/developer/git-credential", { method: "POST" });
36264
36336
  if (credential.repository.toLowerCase() !== status.repository.toLowerCase()) throw new Error("Repository changed. Run connect again.");
36265
- const staging = mkdtempSync(join6(dirname4(resolve4(root)), ".backify-clone-"));
36337
+ const staging = mkdtempSync(join7(dirname4(resolve4(root)), ".backify-clone-"));
36266
36338
  try {
36267
36339
  git(["clone", "--single-branch", "--branch", status.branch, "--", "https://github.com/" + status.repository + ".git", "."], staging, gitEnvironment(status.repository, credential.token));
36268
36340
  validateCloneMerge(staging, root);
36269
- for (const entry of readdirSync2(staging)) cpSync(join6(staging, entry), join6(root, entry), { recursive: true, force: false, errorOnExist: true, dereference: false });
36341
+ for (const entry of readdirSync2(staging)) cpSync(join7(staging, entry), join7(root, entry), { recursive: true, force: false, errorOnExist: true, dereference: false });
36270
36342
  } finally {
36271
- if (dirname4(staging) !== dirname4(resolve4(root)) || !staging.startsWith(join6(dirname4(resolve4(root)), ".backify-clone-"))) throw new Error("Refusing to clean up an unexpected clone staging path.");
36343
+ if (dirname4(staging) !== dirname4(resolve4(root)) || !staging.startsWith(join7(dirname4(resolve4(root)), ".backify-clone-"))) throw new Error("Refusing to clean up an unexpected clone staging path.");
36272
36344
  rmSync(staging, { recursive: true, force: true });
36273
36345
  }
36274
36346
  }
36275
36347
  async function pullProject(call2, appId, root = process.cwd()) {
36276
- if (existsSync6(join6(root, "backify.json")) && applicationGuid(projectApplication(root)) !== applicationGuid(appId)) throw new Error("Local application ID does not match the connected application.");
36348
+ if (existsSync7(join7(root, "backify.json")) && applicationGuid(projectApplication(root)) !== applicationGuid(appId)) throw new Error("Local application ID does not match the connected application.");
36277
36349
  const prefix = "/apps/" + applicationGuid(appId);
36278
36350
  const status = await call2(prefix + "/developer");
36279
36351
  if (!status.repository || !status.branch) throw new Error("Connect the repository and branch in Backify before pulling.");
@@ -36316,15 +36388,15 @@ function attachmentNames(values) {
36316
36388
  }))];
36317
36389
  }
36318
36390
  function localReport(runChecks, root = process.cwd()) {
36319
- const pkg = existsSync6(join6(root, "package.json")) ? JSON.parse(readFileSync6(join6(root, "package.json"), "utf8")) : {};
36391
+ const pkg = existsSync7(join7(root, "package.json")) ? JSON.parse(readFileSync7(join7(root, "package.json"), "utf8")) : {};
36320
36392
  const dependencies = { ...pkg.devDependencies, ...pkg.dependencies };
36321
- const framework = ["next", "vite", "astro", "@sveltejs/kit", "nuxt", "react", "express"].find((name2) => dependencies[name2]) ?? (existsSync6(join6(root, "Dockerfile")) ? "custom-container" : "unknown");
36393
+ const framework = ["next", "vite", "astro", "@sveltejs/kit", "nuxt", "react", "express"].find((name2) => dependencies[name2]) ?? (existsSync7(join7(root, "Dockerfile")) ? "custom-container" : "unknown");
36322
36394
  const setup = doctor(root);
36323
36395
  const checks = [{ name: "backify doctor", status: setup.valid ? "passed" : "failed" }];
36324
36396
  const manager = detectPackageManager(root);
36325
36397
  for (const name2 of ["typecheck", "lint", "test", "build"]) {
36326
36398
  if (!pkg.scripts?.[name2]) continue;
36327
- 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;
36399
+ const result = runChecks ? spawnSync4(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;
36328
36400
  checks.push({ name: name2, status: result ? result.status === 0 ? "passed" : "failed" : "not-run" });
36329
36401
  }
36330
36402
  let branch = null, commitSha = null, dirty = true;
@@ -36334,8 +36406,8 @@ function localReport(runChecks, root = process.cwd()) {
36334
36406
  dirty = Boolean(git(["status", "--porcelain"], root));
36335
36407
  } catch {
36336
36408
  }
36337
- const outputDirectory = ["dist", "build", "out", "."].find((directory2) => existsSync6(join6(root, directory2, "index.html"))) ?? null;
36338
- return { framework, sdkVersion: dependencies["@backifydev/sdk"] ?? null, branch, commitSha, dirty, buildCommand: pkg.scripts?.build ? manager + " run build" : null, outputDirectory, hasDockerfile: existsSync6(join6(root, "Dockerfile")), checks, support: setup.support, warnings: setup.warnings };
36409
+ const outputDirectory = ["dist", "build", "out", "."].find((directory2) => existsSync7(join7(root, directory2, "index.html"))) ?? null;
36410
+ return { framework, sdkVersion: dependencies["@backifydev/sdk"] ?? null, branch, commitSha, dirty, buildCommand: pkg.scripts?.build ? manager + " run build" : null, outputDirectory, hasDockerfile: existsSync7(join7(root, "Dockerfile")), checks, support: setup.support, warnings: setup.warnings };
36339
36411
  }
36340
36412
  function matchesSource(release2, commit) {
36341
36413
  return release2?.commitSha === commit || release2?.sourceCommitSha === commit;
@@ -36552,10 +36624,10 @@ function reconnectingApiClient(session, reconnect, transport = fetch) {
36552
36624
 
36553
36625
  // src/local-runtime.ts
36554
36626
  import { createHash as createHash2, randomUUID as randomUUID3 } from "node:crypto";
36555
- import { chmodSync, existsSync as existsSync7, lstatSync as lstatSync3, mkdirSync as mkdirSync3, readFileSync as readFileSync7, readdirSync as readdirSync3, writeFileSync as writeFileSync6 } from "node:fs";
36556
- import { dirname as dirname5, join as join7, resolve as resolve5, sep } from "node:path";
36627
+ import { chmodSync, existsSync as existsSync8, lstatSync as lstatSync4, mkdirSync as mkdirSync3, readFileSync as readFileSync8, readdirSync as readdirSync3, writeFileSync as writeFileSync7 } from "node:fs";
36628
+ import { dirname as dirname5, join as join8, resolve as resolve5, sep } from "node:path";
36557
36629
  import { homedir } from "node:os";
36558
- import { spawnSync as spawnSync4 } from "node:child_process";
36630
+ import { spawnSync as spawnSync5 } from "node:child_process";
36559
36631
 
36560
36632
  // src/local-state.ts
36561
36633
  import { renameSync as renameSync2 } from "node:fs";
@@ -36588,7 +36660,7 @@ function checkedPath(root, filename2) {
36588
36660
  if (target !== resolve5(root) && !target.startsWith(resolve5(root) + sep)) throw new Error("Runtime path escapes its installation");
36589
36661
  let current = target;
36590
36662
  while (true) {
36591
- if (existsSync7(current) && lstatSync3(current).isSymbolicLink()) throw new Error("Runtime installation must not follow links");
36663
+ if (existsSync8(current) && lstatSync4(current).isSymbolicLink()) throw new Error("Runtime installation must not follow links");
36592
36664
  if (dirname5(current) === current) break;
36593
36665
  current = dirname5(current);
36594
36666
  }
@@ -36596,25 +36668,25 @@ function checkedPath(root, filename2) {
36596
36668
  }
36597
36669
  function verifyInstallationFiles(root, expected, directory2 = root) {
36598
36670
  for (const entry of readdirSync3(directory2, { withFileTypes: true })) {
36599
- const path = checkedPath(root, join7(directory2, entry.name));
36671
+ const path = checkedPath(root, join8(directory2, entry.name));
36600
36672
  if (entry.isDirectory()) verifyInstallationFiles(root, expected, path);
36601
36673
  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");
36602
36674
  }
36603
36675
  }
36604
- function installedLocalRuntime(base = join7(homedir(), ".backify")) {
36676
+ function installedLocalRuntime(base = join8(homedir(), ".backify")) {
36605
36677
  const pointer = checkedPath(base, "runtime.json");
36606
- if (!existsSync7(pointer)) return void 0;
36607
- const installed = JSON.parse(readFileSync7(pointer, "utf8"));
36678
+ if (!existsSync8(pointer)) return void 0;
36679
+ const installed = JSON.parse(readFileSync8(pointer, "utf8"));
36608
36680
  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");
36609
- const root = checkedPath(base, join7("runtimes", installed.version, installed.rid));
36681
+ const root = checkedPath(base, join8("runtimes", installed.version, installed.rid));
36610
36682
  verifyInstallationFiles(root, installed.files);
36611
36683
  for (const [filename2, digest4] of Object.entries(installed.files)) {
36612
36684
  const path = checkedPath(root, filename2);
36613
- if (!/^[a-f0-9]{64}$/.test(digest4) || !lstatSync3(path).isFile() || lstatSync3(path).size > maxArchiveBytes || hash(readFileSync7(path)) !== digest4) throw new Error("Installed runtime bytes changed; reinstall a reviewed version");
36685
+ if (!/^[a-f0-9]{64}$/.test(digest4) || !lstatSync4(path).isFile() || lstatSync4(path).size > maxArchiveBytes || hash(readFileSync8(path)) !== digest4) throw new Error("Installed runtime bytes changed; reinstall a reviewed version");
36614
36686
  }
36615
36687
  const executableName = installed.rid.startsWith("win-") ? "Backify.Hcr.exe" : "Backify.Hcr";
36616
36688
  if (!installed.files["Backify.Hcr.dll"] || !installed.files[executableName]) throw new Error("Runtime archive requires the self-contained HCR executable and DLL");
36617
- return { path: join7(root, "Backify.Hcr.dll"), executable: join7(root, executableName), version: installed.version, rid: installed.rid };
36689
+ return { path: join8(root, "Backify.Hcr.dll"), executable: join8(root, executableName), version: installed.version, rid: installed.rid };
36618
36690
  }
36619
36691
  function installLocalRuntime(archive, options) {
36620
36692
  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");
@@ -36628,28 +36700,28 @@ function installLocalRuntime(archive, options) {
36628
36700
  const rid = runtimeIdentifier();
36629
36701
  const executable = rid.startsWith("win-") ? "Backify.Hcr.exe" : "Backify.Hcr";
36630
36702
  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");
36631
- const base = options.base ?? join7(homedir(), ".backify");
36632
- const parent = checkedPath(base, join7("runtimes", options.version));
36703
+ const base = options.base ?? join8(homedir(), ".backify");
36704
+ const parent = checkedPath(base, join8("runtimes", options.version));
36633
36705
  mkdirSync3(parent, { recursive: true, mode: 448 });
36634
36706
  const destination = checkedPath(parent, rid);
36635
36707
  const receipt = { version: options.version, rid, files: Object.fromEntries(Object.entries(files).map(([name2, bytes]) => [name2, hash(bytes)])) };
36636
- if (!existsSync7(destination)) {
36708
+ if (!existsSync8(destination)) {
36637
36709
  const staging = checkedPath(parent, ".install-" + randomUUID3());
36638
36710
  mkdirSync3(staging, { mode: 448 });
36639
36711
  for (const [name2, bytes] of Object.entries(files)) {
36640
36712
  const filename2 = checkedPath(staging, name2);
36641
36713
  mkdirSync3(dirname5(filename2), { recursive: true, mode: 448 });
36642
- writeFileSync6(filename2, bytes, { flag: "wx", mode: name2 === executable ? 448 : 384 });
36714
+ writeFileSync7(filename2, bytes, { flag: "wx", mode: name2 === executable ? 448 : 384 });
36643
36715
  }
36644
- if (process.platform !== "win32") chmodSync(join7(staging, executable), 448);
36716
+ if (process.platform !== "win32") chmodSync(join8(staging, executable), 448);
36645
36717
  renameLocalFile(staging, destination);
36646
36718
  } else {
36647
36719
  verifyInstallationFiles(destination, receipt.files);
36648
- for (const [name2, digest4] of Object.entries(receipt.files)) if (hash(readFileSync7(checkedPath(destination, name2))) !== digest4) throw new Error("Runtime version already exists with different bytes; never overwrite an installation");
36720
+ for (const [name2, digest4] of Object.entries(receipt.files)) if (hash(readFileSync8(checkedPath(destination, name2))) !== digest4) throw new Error("Runtime version already exists with different bytes; never overwrite an installation");
36649
36721
  }
36650
36722
  const pointer = checkedPath(base, "runtime.json");
36651
36723
  const temporary = checkedPath(base, ".runtime-" + randomUUID3() + ".json");
36652
- writeFileSync6(temporary, JSON.stringify(receipt), { flag: "wx", mode: 384 });
36724
+ writeFileSync7(temporary, JSON.stringify(receipt), { flag: "wx", mode: 384 });
36653
36725
  renameLocalFile(temporary, pointer);
36654
36726
  return installedLocalRuntime(base);
36655
36727
  }
@@ -36677,10 +36749,10 @@ async function downloadLocalRuntime(version2) {
36677
36749
  }
36678
36750
  function localPrerequisites() {
36679
36751
  const runtime = installedLocalRuntime();
36680
- const directory2 = process.env.BACKIFY_LOCAL_POSTGRES_BIN ?? (process.platform === "win32" ? join7(process.env.ProgramFiles ?? "C:/Program Files", "PostgreSQL", "17", "bin") : void 0);
36752
+ const directory2 = process.env.BACKIFY_LOCAL_POSTGRES_BIN ?? (process.platform === "win32" ? join8(process.env.ProgramFiles ?? "C:/Program Files", "PostgreSQL", "17", "bin") : void 0);
36681
36753
  const checks = ["initdb", "pg_ctl", "psql"].map((name2) => {
36682
- const executable = directory2 ? join7(directory2, name2 + (process.platform === "win32" ? ".exe" : "")) : name2;
36683
- const result = spawnSync4(executable, ["--version"], { windowsHide: true, timeout: 1e4, encoding: "utf8" });
36754
+ const executable = directory2 ? join8(directory2, name2 + (process.platform === "win32" ? ".exe" : "")) : name2;
36755
+ const result = spawnSync5(executable, ["--version"], { windowsHide: true, timeout: 1e4, encoding: "utf8" });
36684
36756
  return { name: name2, available: result.status === 0 };
36685
36757
  });
36686
36758
  return { rid: runtimeIdentifier(), runtime: runtime ? { installed: true, version: runtime.version } : { installed: false }, postgres: checks, ready: !!runtime && checks.every((check2) => check2.available) };
@@ -36689,20 +36761,20 @@ function localPrerequisites() {
36689
36761
  // src/workload.ts
36690
36762
  import { build as build2 } from "esbuild";
36691
36763
  import { createHash as createHash14 } from "node:crypto";
36692
- import { existsSync as existsSync14, mkdirSync as mkdirSync7, readFileSync as readFileSync22, realpathSync as realpathSync6, readdirSync as readdirSync6, writeFileSync as writeFileSync12 } from "node:fs";
36693
- import { dirname as dirname13, isAbsolute as isAbsolute14, join as join16, relative as relative8, resolve as resolve19 } from "node:path";
36764
+ import { existsSync as existsSync15, mkdirSync as mkdirSync7, readFileSync as readFileSync23, realpathSync as realpathSync6, readdirSync as readdirSync6, writeFileSync as writeFileSync13 } from "node:fs";
36765
+ import { dirname as dirname13, isAbsolute as isAbsolute14, join as join17, relative as relative8, resolve as resolve19 } from "node:path";
36694
36766
 
36695
36767
  // src/local-development.ts
36696
36768
  import { context as context2, formatMessagesSync } from "esbuild";
36697
36769
  import { spawn as spawn4 } from "node:child_process";
36698
- import { randomBytes as randomBytes6, randomUUID as randomUUID10, createHash as createHash13 } from "node:crypto";
36699
- import { existsSync as existsSync13, lstatSync as lstatSync15, mkdirSync as mkdirSync6, readFileSync as readFileSync21, realpathSync as realpathSync5, writeFileSync as writeFileSync11, unlinkSync as unlinkSync5 } from "node:fs";
36700
- import { resolve as resolve18, join as join15, relative as relative7, isAbsolute as isAbsolute13, dirname as dirname12 } from "node:path";
36770
+ import { randomBytes as randomBytes6, randomUUID as randomUUID11, createHash as createHash13 } from "node:crypto";
36771
+ import { existsSync as existsSync14, lstatSync as lstatSync16, mkdirSync as mkdirSync6, readFileSync as readFileSync22, realpathSync as realpathSync5, writeFileSync as writeFileSync12, unlinkSync as unlinkSync5 } from "node:fs";
36772
+ import { resolve as resolve18, join as join16, relative as relative7, isAbsolute as isAbsolute13, dirname as dirname12 } from "node:path";
36701
36773
 
36702
36774
  // ../analyzer/dist/index.js
36703
36775
  import ts3 from "typescript";
36704
- import { readFileSync as readFileSync8, readdirSync as readdirSync4, existsSync as existsSync8 } from "node:fs";
36705
- import { join as join8, extname } from "node:path";
36776
+ import { readFileSync as readFileSync9, readdirSync as readdirSync4, existsSync as existsSync9 } from "node:fs";
36777
+ import { join as join9, extname } from "node:path";
36706
36778
 
36707
36779
  // ../analyzer/dist/authentication.js
36708
36780
  import ts from "typescript";
@@ -37119,230 +37191,18 @@ function repositorySources(root) {
37119
37191
  for (const entry of readdirSync4(dir, { withFileTypes: true })) {
37120
37192
  if (entry.name === "node_modules" || entry.name === "dist" || entry.name === ".backify" || entry.name.startsWith(".git"))
37121
37193
  continue;
37122
- const path = join8(dir, entry.name);
37194
+ const path = join9(dir, entry.name);
37123
37195
  if (entry.isDirectory())
37124
37196
  walk(path);
37125
37197
  else if ([".ts", ".tsx", ".js", ".jsx", ".mts", ".mjs"].includes(extname(path)))
37126
- result.push({ path, content: readFileSync8(path, "utf8") });
37198
+ result.push({ path, content: readFileSync9(path, "utf8") });
37127
37199
  }
37128
37200
  };
37129
- if (existsSync8(root))
37201
+ if (existsSync9(root))
37130
37202
  walk(root);
37131
37203
  return result;
37132
37204
  }
37133
37205
 
37134
- // src/local-inspection.ts
37135
- function createLocalDataInspector(runtime, options) {
37136
- const tableName = (value) => typeof value === "string" && /^[A-Za-z_][A-Za-z0-9_]{0,62}$/.test(value) && !/^__backify/i.test(value);
37137
- const bucketName = (value) => typeof value === "string" && /^[A-Za-z0-9_-]{1,100}$/.test(value);
37138
- if (typeof window !== "undefined" || options.buckets.length > 100 || options.buckets.some((name2) => !bucketName(name2)) || new Set(options.buckets).size !== options.buckets.length) throw new Error("invalid_local_inspection");
37139
- const fail = () => {
37140
- throw new Error("invalid_local_inspection");
37141
- };
37142
- const unavailable4 = () => {
37143
- throw new Error("local_inspection_unavailable");
37144
- };
37145
- const providerRequest = async (operation, missingObject = false) => {
37146
- try {
37147
- return await operation();
37148
- } catch (error2) {
37149
- const status = error2?.status;
37150
- if (status === 413) throw new Error("local_inspection_too_large");
37151
- if (status === 400) fail();
37152
- if (status === 404 && missingObject) throw new Error("local_inspection_not_found");
37153
- return unavailable4();
37154
- }
37155
- };
37156
- const object7 = (value, fields5) => {
37157
- if (!value || typeof value !== "object" || Array.isArray(value) || Object.keys(value).some((name2) => !fields5.includes(name2))) fail();
37158
- return value;
37159
- };
37160
- const page = (input) => {
37161
- const limit = input.limit ?? 25, offset = input.offset ?? 0;
37162
- if (typeof limit !== "number" || !Number.isInteger(limit) || limit < 1 || limit > 50 || typeof offset !== "number" || !Number.isInteger(offset) || offset < 0 || offset > 1e4) fail();
37163
- return { limit, offset };
37164
- };
37165
- const bounded = (value) => {
37166
- if (Buffer.byteLength(JSON.stringify(value)) > 65536) throw new Error("local_inspection_too_large");
37167
- return value;
37168
- };
37169
- const redact = (value, depth = 0) => {
37170
- if (depth > 20) return "[DEPTH LIMIT]";
37171
- if (Array.isArray(value)) return value.map((item) => redact(item, depth + 1));
37172
- if (value && typeof value === "object") return Object.fromEntries(Object.entries(value).map(([name2, item]) => [name2, /(?:password|secret|token|credential|private.?key|connection.?string)/i.test(name2) ? "[REDACTED]" : redact(item, depth + 1)]));
37173
- return value;
37174
- };
37175
- const requireBucket = (name2) => {
37176
- if (!options.storageEnabled) unavailable4();
37177
- const known = [...options.buckets, ...options.nativeStorage ? [] : runtime.inspect().buckets.map((bucket) => bucket.name)];
37178
- if (!bucketName(name2) || !known.includes(name2)) fail();
37179
- return name2;
37180
- };
37181
- return {
37182
- async tables() {
37183
- if (!options.databaseEnabled) unavailable4();
37184
- if (runtime.database.listTables) return bounded(await providerRequest(() => runtime.database.listTables()));
37185
- if (options.nativeDatabase) unavailable4();
37186
- const names = runtime.inspect().tables.map((table) => table.name).filter(tableName).sort();
37187
- return { names: names.slice(0, 100), hasMore: names.length > 100 };
37188
- },
37189
- async rows(value) {
37190
- if (!options.databaseEnabled) unavailable4();
37191
- const input = object7(value, ["table", "limit", "offset"]), pagination = page(input);
37192
- if (!tableName(input.table)) fail();
37193
- if (runtime.database.inspectRows) {
37194
- const result = await providerRequest(() => runtime.database.inspectRows(input.table, pagination));
37195
- return bounded({ ...result, rows: result.rows.map((row) => redact(row)) });
37196
- }
37197
- if (options.nativeDatabase) unavailable4();
37198
- const rows = await runtime.database.query(input.table, { filters: [], limit: pagination.limit + 1, offset: pagination.offset });
37199
- return bounded({ rows: rows.slice(0, pagination.limit).map((row) => redact(row)), ...pagination, nextOffset: rows.length > pagination.limit && pagination.offset + pagination.limit <= 1e4 ? pagination.offset + pagination.limit : null });
37200
- },
37201
- buckets() {
37202
- if (!options.storageEnabled) unavailable4();
37203
- return bounded({ names: [.../* @__PURE__ */ new Set([...options.buckets, ...options.nativeStorage ? [] : runtime.inspect().buckets.map((bucket) => bucket.name)])].filter(bucketName).sort().slice(0, 100) });
37204
- },
37205
- async objects(value) {
37206
- const input = object7(value, ["bucket", "prefix", "limit", "offset"]), pagination = page(input);
37207
- const name2 = requireBucket(input.bucket);
37208
- if (input.prefix !== void 0 && (typeof input.prefix !== "string" || input.prefix.length > 512 || /[\\\x00-\x1f\x7f]/.test(input.prefix) || input.prefix.startsWith("/") || input.prefix.split("/").some((part) => part === "." || part === ".."))) fail();
37209
- const objects = await providerRequest(() => runtime.storage.list(name2, input.prefix));
37210
- if (objects.length > 1e3) throw new Error("local_inspection_too_large");
37211
- objects.sort((first, second) => first.key.localeCompare(second.key));
37212
- return bounded({ objects: objects.slice(pagination.offset, pagination.offset + pagination.limit), ...pagination, nextOffset: objects.length > pagination.offset + pagination.limit ? pagination.offset + pagination.limit : null });
37213
- },
37214
- async preview(value) {
37215
- const input = object7(value, ["bucket", "key"]), name2 = requireBucket(input.bucket);
37216
- if (typeof input.key !== "string" || !input.key || input.key.length > 512 || input.key.startsWith("/") || /[\\\x00-\x1f\x7f]/.test(input.key) || input.key.split("/").some((part) => part === "." || part === "..")) fail();
37217
- if (!options.nativeStorage && !await runtime.storage.exists(name2, input.key)) throw new Error("local_inspection_not_found");
37218
- const bytes = await providerRequest(() => runtime.storage.download(name2, input.key), true);
37219
- if (bytes.byteLength > 16384) return { kind: "too-large", size: bytes.byteLength, maximumPreviewBytes: 16384 };
37220
- try {
37221
- const text3 = new TextDecoder("utf8", { fatal: true }).decode(bytes);
37222
- if (text3.includes("\0")) throw new Error("Binary object");
37223
- return bounded({ kind: "text", size: bytes.byteLength, text: text3 });
37224
- } catch (error2) {
37225
- if (error2 instanceof Error && error2.message === "local_inspection_too_large") throw error2;
37226
- return { kind: "binary", size: bytes.byteLength, bytes: [...bytes.slice(0, 64)], truncated: bytes.byteLength > 64 };
37227
- }
37228
- }
37229
- };
37230
- }
37231
-
37232
- // src/local-dashboard.ts
37233
- var dashboardHtml = String.raw`<!doctype html>
37234
- <html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Backify Local</title>
37235
- <style>body{font:16px system-ui;max-width:1100px;margin:30px auto;padding:20px;background:#10131a;color:#ecf1ff}button,select,input,textarea{font:inherit;padding:8px;margin:4px;border:1px solid #8ca1bc;border-radius:5px}button{cursor:pointer}button:disabled{cursor:wait;opacity:.6}button:focus-visible,select:focus-visible,input:focus-visible,textarea:focus-visible{outline:3px solid #78baff}nav{display:flex;flex-wrap:wrap;margin-bottom:20px}section{padding:16px;border:1px solid #36465f;border-radius:8px;margin:12px 0}pre{white-space:pre-wrap;overflow-wrap:anywhere;background:#171f2b;padding:16px;border-radius:6px}label{display:inline-block;margin:4px}p{line-height:1.5;color:#bdcbe0}#message{min-height:24px;color:#f5c575}[hidden]{display:none!important}textarea{display:block;width:30em;max-width:100%;min-height:80px}</style></head>
37236
- <body><h1>Backify Local Development</h1><p>Application data stays on this computer. This is a local operator dashboard, not an application user's login or a production portal.</p>
37237
- <nav aria-label="Inspection panels"><button data-panel="overview">Overview</button><button data-panel="data">Data</button><button data-panel="jobs">Jobs</button><button data-panel="events">Events</button><button data-panel="logs">Logs</button></nav>
37238
- <p id="message" role="status" aria-live="polite">Open this dashboard using backify dev --open to authenticate.</p>
37239
- <section id="overview"><h2>Supervisor and endpoints</h2><p>A responding endpoint is not proof of provider health. Database and storage data are inspected explicitly in the Data panel.</p><button id="refresh">Refresh status</button><pre id="state" aria-label="Local status"></pre></section>
37240
- <section id="data" hidden><h2>Read-only data inspection</h2><p>At most 100 public database table names and 50 rows per page are supported. Common credential-named row fields are redacted; this is not comprehensive secret classification. Object contents require an explicit preview request. No data mutation controls are provided.</p>
37241
- <h3>Database</h3><button id="load-tables">Load tables</button><label>Table <select id="tables" aria-label="Database table"></select></label><button id="load-rows">Inspect rows</button><button id="next-rows" disabled>Next row page</button><pre id="rows" aria-label="Database rows"></pre>
37242
- <h3>Private storage</h3><button id="load-buckets">Load buckets</button><label>Bucket <select id="buckets" aria-label="Storage bucket"></select></label><label>Prefix <input id="prefix" maxlength="512"></label><button id="load-objects">List objects</button><button id="next-objects" disabled>Next object page</button><pre id="objects" aria-label="Storage objects"></pre><label>Object <select id="keys" aria-label="Storage object"></select></label><button id="preview">Preview selected object</button><pre id="object-preview" aria-label="Object preview"></pre></section>
37243
- <section id="jobs" hidden><h2>Declared jobs and retained history</h2><p>These are local operator actions, not application-user permissions. Retries create a new run and may repeat business side effects. Do not enter credentials in job payloads.</p><button id="load-jobs">Refresh jobs</button><label>Job <select id="job-name" aria-label="Declared job"></select></label><label>Payload <textarea id="job-payload" aria-label="Job payload (JSON)" maxlength="32768" placeholder="Optional JSON, otherwise null"></textarea></label><button id="run-job">Run selected job</button><h3>Schedules</h3><label>Schedule <select id="schedule-id" aria-label="Declared schedule"></select></label><button id="pause-schedule" disabled>Pause selected schedule</button><button id="resume-schedule" disabled>Resume selected schedule</button><h3>Run recovery</h3><label>Run <select id="run-id" aria-label="Recoverable run"></select></label><button id="retry-run" disabled>Retry failed run</button><button id="cancel-run" disabled>Cancel selected run</button><pre id="job-state" aria-label="Job history"></pre></section>
37244
- <section id="logs" hidden><h2>Local logs</h2><button id="load-logs">Refresh logs</button><pre id="log-state" aria-label="Local logs"></pre></section>
37245
- <section id="events" hidden><h2>Local event activity</h2><p>Latest 100 delivery metadata rows and retained status counts. Payloads, idempotency keys and lease receipts are never shown. Lightweight mode preserves snapshot leases. Full mode uses a native PostgreSQL inbox and drains retained snapshot records without renaming or deleting them. Local hooks and retained drainage are single-worker, not distributed cloud subscriptions. No acknowledgement or destructive controls are exposed.</p><button id="load-events">Refresh events</button><pre id="event-state" aria-label="Local event activity"></pre></section>
37246
- <script>
37247
- const token=new URLSearchParams(location.hash.slice(1)).get("session");
37248
- history.replaceState(null,"",location.pathname);
37249
- const element=id=>document.getElementById(id);
37250
- let rowPage=null,objectPage=null,rowTable="",objectBucket="",objectPrefix="",jobsBusy=false,jobView={jobs:[],schedules:[],runs:[]};
37251
- const jobActions=["run-job","pause-schedule","resume-schedule","retry-run","cancel-run"];
37252
- function show(id,value){element(id).textContent=JSON.stringify(value,null,2)}
37253
- function choices(id,names){element(id).replaceChildren();for(const name of names){const option=document.createElement("option");option.value=name;option.textContent=name;element(id).append(option)}}
37254
- async function request(path,input){if(!token)throw new Error("Local session required; reopen using backify dev --open.");const response=await fetch(path,{method:input===undefined?"GET":"POST",headers:{authorization:"Bearer "+token,"content-type":"application/json"},body:input===undefined?undefined:JSON.stringify(input),redirect:"error",cache:"no-store",signal:AbortSignal.timeout(35000)});const value=await response.json();if(!response.ok)throw new Error("Inspection failed ("+response.status+"): "+(value.error||"unavailable"));return value}
37255
- function action(id,handler){element(id).onclick=async()=>{if(jobActions.includes(id)){if(jobsBusy)return;jobsBusy=true;jobControls()}element(id).disabled=true;element("message").textContent="Loading...";try{await handler();element("message").textContent="Updated."}catch(error){element("message").textContent=error instanceof Error?error.message:"Local operation unavailable"}finally{if(jobActions.includes(id)){jobsBusy=false;jobControls()}else element(id).disabled=id==="next-rows"?rowPage===null:id==="next-objects"?objectPage===null:false}}}
37256
- async function status(){show("state",await request("/v1/status"))}
37257
- async function rows(offset){const table=element("tables").value;if(!table)throw new Error("Choose a table first.");const result=await request("/v1/database/rows",{table,offset,limit:25});rowTable=table;rowPage=result.nextOffset;show("rows",result);element("next-rows").disabled=rowPage===null}
37258
- async function objects(offset){const bucket=element("buckets").value,prefix=element("prefix").value;if(!bucket)throw new Error("Choose a bucket first.");const result=await request("/v1/storage/objects",{bucket,prefix,offset,limit:25});objectBucket=bucket;objectPrefix=prefix;objectPage=result.nextOffset;show("objects",result);choices("keys",result.objects.map(value=>value.key));element("next-objects").disabled=objectPage===null;element("object-preview").textContent=""}
37259
- function records(id,values,label){const selected=element(id).value;element(id).replaceChildren();for(const value of values){const option=document.createElement("option");option.value=value.id;option.textContent=label(value);element(id).append(option)}if(values.some(value=>value.id===selected))element(id).value=selected}
37260
- function jobControls(){const schedule=jobView.schedules.find(value=>value.id===element("schedule-id").value),run=jobView.runs.find(value=>value.id===element("run-id").value);element("run-job").disabled=jobsBusy||!jobView.jobs.length;element("pause-schedule").disabled=jobsBusy||!schedule||!schedule.enabled;element("resume-schedule").disabled=jobsBusy||!schedule||schedule.enabled;element("retry-run").disabled=jobsBusy||!run||run.status!=="failed"||run.canRetry===false;element("cancel-run").disabled=jobsBusy||!run||!["queued","running","retrying"].includes(run.status)||run.canCancel===false}
37261
- async function jobs(){const result=await request("/v1/jobs");jobView=result;show("job-state",result);choices("job-name",result.jobs.map(value=>value.name));records("schedule-id",result.schedules,value=>value.name+" ("+(value.enabled?"enabled":"paused")+")");records("run-id",result.runs.filter(value=>["failed","queued","running","retrying"].includes(value.status)),value=>value.id+" - "+value.job+" ("+value.status+")");jobControls()}
37262
- element("schedule-id").onchange=jobControls;element("run-id").onchange=jobControls;
37263
- for(const button of document.querySelectorAll("[data-panel]")){button.onclick=()=>{for(const name of ["overview","data","jobs","events","logs"])element(name).hidden=name!==button.dataset.panel}}
37264
- action("refresh",status);
37265
- action("load-tables",async()=>{const result=await request("/v1/database/tables");choices("tables",result.names);show("rows",{tables:result.names.length,hasMore:result.hasMore});rowPage=null;element("next-rows").disabled=true});
37266
- action("load-rows",()=>rows(0));
37267
- action("next-rows",()=>{if(rowPage===null||rowTable!==element("tables").value)throw new Error("Reload rows after changing the table.");return rows(rowPage)});
37268
- action("load-buckets",async()=>{const result=await request("/v1/storage/buckets");choices("buckets",result.names);show("objects",result);objectPage=null;element("next-objects").disabled=true});
37269
- action("load-objects",()=>objects(0));
37270
- action("next-objects",()=>{if(objectPage===null||objectBucket!==element("buckets").value||objectPrefix!==element("prefix").value)throw new Error("Reload objects after changing bucket or prefix.");return objects(objectPage)});
37271
- action("preview",async()=>{const bucket=element("buckets").value,key=element("keys").value;if(!key||bucket!==objectBucket)throw new Error("List and choose an object first.");show("object-preview",await request("/v1/storage/preview",{bucket,key}))});
37272
- action("load-jobs",jobs);
37273
- action("run-job",async()=>{const name=element("job-name").value;if(!name)throw new Error("Choose a declared job first.");const raw=element("job-payload").value;if(new TextEncoder().encode(raw).length>32768)throw new Error("Job payload exceeds 32 KiB.");let payload=null;try{if(raw.trim())payload=JSON.parse(raw)}catch{throw new Error("Enter valid JSON for the job payload.")}const input={name,payload};if(new TextEncoder().encode(JSON.stringify(input)).length>32768)throw new Error("Job payload exceeds 32 KiB.");await request("/v1/jobs/run",input);element("job-payload").value="";await jobs()});
37274
- action("pause-schedule",async()=>{await request("/v1/schedules/enabled",{id:element("schedule-id").value,enabled:false});await jobs()});
37275
- action("resume-schedule",async()=>{await request("/v1/schedules/enabled",{id:element("schedule-id").value,enabled:true});await jobs()});
37276
- action("retry-run",async()=>{await request("/v1/jobs/retry",{id:element("run-id").value});await jobs()});
37277
- action("cancel-run",async()=>{await request("/v1/jobs/cancel",{id:element("run-id").value});await jobs()});
37278
- action("load-logs",async()=>show("log-state",await request("/v1/logs")));
37279
- action("load-events",async()=>show("event-state",await request("/v1/events")));
37280
- if(token)status().then(()=>{element("message").textContent="Local session connected."}).catch(error=>{element("message").textContent=error.message});
37281
- </script></body></html>`;
37282
-
37283
- // src/local-native-events.ts
37284
- function createLocalNativeEvents(local, native) {
37285
- const handlers = /* @__PURE__ */ new Map();
37286
- const validateName2 = (name2) => {
37287
- if (typeof name2 !== "string" || !/^[a-zA-Z][a-zA-Z0-9_.-]{0,127}$/.test(name2) || /[\r\n]/.test(name2)) throw new Error("Invalid event name");
37288
- };
37289
- return {
37290
- track: (name2, data, options) => {
37291
- if (!local.track) throw new Error("Upgrade the local SDK to enable event tracking");
37292
- return local.track(name2, data, options);
37293
- },
37294
- async emit(name2, payload, options) {
37295
- validateName2(name2);
37296
- if (options?.idempotencyKey !== void 0 && (typeof options.idempotencyKey !== "string" || !options.idempotencyKey || options.idempotencyKey.length > 128)) throw new Error("Invalid idempotency key");
37297
- if (options?.idempotencyKey !== void 0 && (local.hasIdempotencyKey ? local.hasIdempotencyKey(options.idempotencyKey) : local.snapshot().deliveries.some((item) => item.idempotencyKey === options.idempotencyKey))) {
37298
- await local.emit(name2, payload, options);
37299
- return;
37300
- }
37301
- let accepted;
37302
- try {
37303
- accepted = JSON.parse(JSON.stringify(payload ?? null));
37304
- } catch {
37305
- throw new Error("Event payload must be JSON serializable");
37306
- }
37307
- if (await native.emitAccepted(name2, accepted, options)) {
37308
- for (const handler of handlers.get(name2) ?? []) await handler(structuredClone(accepted));
37309
- }
37310
- },
37311
- on(name2, handler) {
37312
- if (typeof name2 !== "string" || !/^[a-zA-Z][a-zA-Z0-9_.-]{0,127}$/.test(name2) || /[\r\n]/.test(name2) || typeof handler !== "function") throw new Error("Invalid local event subscription");
37313
- handlers.set(name2, [...handlers.get(name2) ?? [], handler]);
37314
- return () => handlers.set(name2, (handlers.get(name2) ?? []).filter((value) => value !== handler));
37315
- },
37316
- async receive(name2, options) {
37317
- const retained = await local.receive(name2, options);
37318
- return retained.length ? retained : native.receive(name2, options);
37319
- },
37320
- async complete(id, receipt, retry) {
37321
- if (retry !== void 0 && typeof retry !== "boolean") throw new Error("Invalid local event retry");
37322
- if (typeof id === "string" && id.startsWith("event_")) await local.complete(id, receipt, retry);
37323
- else await native.complete(id, receipt, retry);
37324
- },
37325
- async inspect() {
37326
- const retained = local.inspect(), durable = await native.inspect();
37327
- const counts = { ...retained.counts };
37328
- for (const status of Object.keys(counts)) {
37329
- counts[status] += durable.counts[status];
37330
- if (!Number.isSafeInteger(counts[status])) throw new Error("Local event inspection count exceeds bounds");
37331
- }
37332
- const total = Object.values(counts).reduce((sum, count) => sum + count, 0);
37333
- if (!Number.isSafeInteger(total)) throw new Error("Local event inspection count exceeds bounds");
37334
- const deliveries = [...retained.deliveries, ...durable.deliveries].sort((first, second) => Date.parse(second.emittedAt) - Date.parse(first.emittedAt) || (first.id < second.id ? 1 : first.id > second.id ? -1 : 0)).slice(0, 100);
37335
- return { version: 1, counts, deliveries, hasMore: total > deliveries.length };
37336
- }
37337
- };
37338
- }
37339
-
37340
- // src/local-job-executor.ts
37341
- import { spawn as spawn2 } from "node:child_process";
37342
- import { createHash as createHash10 } from "node:crypto";
37343
- import { lstatSync as lstatSync11, readFileSync as readFileSync15 } from "node:fs";
37344
- import { isAbsolute as isAbsolute8, join as join11, relative as relative3, resolve as resolve12 } from "node:path";
37345
-
37346
37206
  // ../sdk/dist/schedules.js
37347
37207
  var import_cron_parser = __toESM(require_dist2(), 1);
37348
37208
  function nextSchedule(input, after, creating = false) {
@@ -37385,6 +37245,9 @@ function declarationInput(declaration) {
37385
37245
  return { ...base, kind: "cron", expression: schedule.kind === "hourly" ? "0 * * * *" : schedule.kind === "daily" ? minute + " " + hour + " * * *" : minute + " " + hour + " * * " + day };
37386
37246
  }
37387
37247
 
37248
+ // ../sdk/dist/local-identity.js
37249
+ import { createHash as createHash3, randomBytes as randomBytes2, randomUUID as randomUUID4 } from "node:crypto";
37250
+
37388
37251
  // ../sdk/dist/application-auth.js
37389
37252
  import { createPublicKey, verify } from "node:crypto";
37390
37253
  var ApplicationAuthenticationError = class extends Error {
@@ -37474,86 +37337,495 @@ function createApplicationAuthProvider(source, options) {
37474
37337
  unavailable();
37475
37338
  return value;
37476
37339
  };
37477
- let current;
37478
- const load = () => {
37479
- try {
37480
- if (typeof window !== "undefined")
37481
- unavailable();
37482
- const input = structuredClone(typeof source === "function" ? source() : source);
37483
- const content = JSON.stringify(input);
37484
- const time3 = now();
37485
- if (Buffer.byteLength(content) > 128 * 1024 || !object2(input) || Object.keys(input).some((key) => !["version", "revision", "scope", "issuer", "audience", "validUntil", "keys"].includes(key)) || input.version !== 1 || !Number.isSafeInteger(input.revision) || input.revision < 1 || !scopeValid(input.scope) || !sameScope(input.scope, expectedScope) || !text(input.issuer, 512) || !text(input.audience, 512) || !Number.isSafeInteger(input.validUntil) || input.validUntil <= time3 || input.validUntil > time3 + 86400 || !Array.isArray(input.keys) || input.keys.length < 1 || input.keys.length > 8)
37486
- unavailable();
37487
- const issuer = new URL(input.issuer);
37488
- if (issuer.protocol !== "https:" || issuer.username || issuer.password || issuer.search || issuer.hash)
37489
- unavailable();
37490
- if (current && (input.revision < current.trust.revision || input.revision === current.trust.revision && content !== current.content))
37491
- unavailable();
37492
- if (current?.content === content) {
37493
- options.checkpoint?.({ revision: input.revision, scope: structuredClone(expectedScope), content });
37494
- return current;
37340
+ let current;
37341
+ const load = () => {
37342
+ try {
37343
+ if (typeof window !== "undefined")
37344
+ unavailable();
37345
+ const input = structuredClone(typeof source === "function" ? source() : source);
37346
+ const content = JSON.stringify(input);
37347
+ const time3 = now();
37348
+ if (Buffer.byteLength(content) > 128 * 1024 || !object2(input) || Object.keys(input).some((key) => !["version", "revision", "scope", "issuer", "audience", "validUntil", "keys"].includes(key)) || input.version !== 1 || !Number.isSafeInteger(input.revision) || input.revision < 1 || !scopeValid(input.scope) || !sameScope(input.scope, expectedScope) || !text(input.issuer, 512) || !text(input.audience, 512) || !Number.isSafeInteger(input.validUntil) || input.validUntil <= time3 || input.validUntil > time3 + 86400 || !Array.isArray(input.keys) || input.keys.length < 1 || input.keys.length > 8)
37349
+ unavailable();
37350
+ const issuer = new URL(input.issuer);
37351
+ if (issuer.protocol !== "https:" || issuer.username || issuer.password || issuer.search || issuer.hash)
37352
+ unavailable();
37353
+ if (current && (input.revision < current.trust.revision || input.revision === current.trust.revision && content !== current.content))
37354
+ unavailable();
37355
+ if (current?.content === content) {
37356
+ options.checkpoint?.({ revision: input.revision, scope: structuredClone(expectedScope), content });
37357
+ return current;
37358
+ }
37359
+ const keys = /* @__PURE__ */ new Map();
37360
+ for (const entry of input.keys) {
37361
+ if (!object2(entry) || Object.keys(entry).some((key2) => !["id", "publicKeyPem"].includes(key2)) || typeof entry.id !== "string" || !/^[a-zA-Z0-9_-]{1,64}$/.test(entry.id) || keys.has(entry.id) || typeof entry.publicKeyPem !== "string" || entry.publicKeyPem.length > 16384 || entry.publicKeyPem.includes("PRIVATE KEY") || !/^-----BEGIN (?:RSA )?PUBLIC KEY-----\r?\n/.test(entry.publicKeyPem))
37362
+ unavailable();
37363
+ const key = createPublicKey(entry.publicKeyPem);
37364
+ const bits2 = key.asymmetricKeyDetails?.modulusLength ?? 0;
37365
+ if (key.asymmetricKeyType !== "rsa" || bits2 < 2048 || bits2 > 8192)
37366
+ unavailable();
37367
+ keys.set(entry.id, key);
37368
+ }
37369
+ options.checkpoint?.({ revision: input.revision, scope: structuredClone(expectedScope), content });
37370
+ current = { trust: input, content, keys };
37371
+ return current;
37372
+ } catch {
37373
+ return unavailable();
37374
+ }
37375
+ };
37376
+ load();
37377
+ return {
37378
+ forRequest(request) {
37379
+ const authorization = request.headers.get("authorization");
37380
+ const identity = () => {
37381
+ const { trust, keys } = load();
37382
+ if (authorization === null)
37383
+ return null;
37384
+ if (authorization.length > 16384)
37385
+ invalid();
37386
+ const match = /^Bearer ([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)$/i.exec(authorization);
37387
+ if (!match)
37388
+ invalid();
37389
+ const header = json(match[1]);
37390
+ fields(header, ["alg", "typ", "kid"]);
37391
+ if (header.alg !== "RS256" || header.typ !== "backify-user+jwt" || typeof header.kid !== "string")
37392
+ invalid();
37393
+ const key = keys.get(header.kid);
37394
+ if (!key)
37395
+ invalid();
37396
+ const signature = Buffer.from(match[3], "base64url");
37397
+ if (signature.toString("base64url") !== match[3] || signature.length !== key.asymmetricKeyDetails.modulusLength / 8 || !verify("RSA-SHA256", Buffer.from(match[1] + "." + match[2]), key, signature))
37398
+ invalid();
37399
+ const payload = json(match[2]);
37400
+ fields(payload, ["ver", "iss", "aud", "sub", "organization_id", "application_id", "environment_id", "iat", "nbf", "exp", "jti", "display_name", "email", "organization_name", "roles"]);
37401
+ const time3 = now();
37402
+ if (payload.ver !== 1 || payload.iss !== trust.issuer || payload.aud !== trust.audience || !uuid(payload.sub) || payload.organization_id !== expectedScope.organizationId || payload.application_id !== expectedScope.applicationId || payload.environment_id !== expectedScope.environmentId || !uuid(payload.jti) || !Number.isSafeInteger(payload.iat) || !Number.isSafeInteger(payload.nbf) || !Number.isSafeInteger(payload.exp))
37403
+ invalid();
37404
+ const issued = payload.iat, notBefore = payload.nbf, expires = payload.exp;
37405
+ if (issued < 0 || issued > time3 || notBefore !== issued || expires <= time3 || expires <= issued || expires - issued > 300 || !text(payload.display_name, 200) || !text(payload.organization_name, 200) || payload.email !== void 0 && !text(payload.email, 320))
37406
+ invalid();
37407
+ return {
37408
+ user: { id: payload.sub, displayName: payload.display_name, ...payload.email === void 0 ? {} : { email: payload.email }, roles: roles(payload.roles), claims: { organizationId: expectedScope.organizationId, applicationId: expectedScope.applicationId, environmentId: expectedScope.environmentId } },
37409
+ organization: { id: expectedScope.organizationId, name: payload.organization_name }
37410
+ };
37411
+ };
37412
+ return { currentUser: async () => identity()?.user ?? null, currentOrganization: async () => identity()?.organization ?? null };
37413
+ }
37414
+ };
37415
+ }
37416
+
37417
+ // ../sdk/dist/local-identity.js
37418
+ function createLocalIdentityProvider(options) {
37419
+ const serverOnly = () => {
37420
+ if (typeof window !== "undefined")
37421
+ throw new Error("Local development identities are server-only");
37422
+ };
37423
+ serverOnly();
37424
+ if (typeof process !== "undefined" && process.env.NODE_ENV === "production")
37425
+ throw new Error("Local Backify identities must not run in production");
37426
+ const uuid5 = (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";
37427
+ const text3 = (value, maximum) => typeof value === "string" && value.length > 0 && value.length <= maximum && !/[\x00-\x1f\x7f]/.test(value);
37428
+ if (!options.scope || Object.keys(options.scope).length !== 3 || !uuid5(options.scope.organizationId) || !uuid5(options.scope.applicationId) || !uuid5(options.scope.environmentId) || !text3(options.organizationName, 200) || !Array.isArray(options.users) || options.users.length < 1 || options.users.length > 32 || !Array.isArray(options.requestOrigins) || options.requestOrigins.length < 1 || options.requestOrigins.length > 8)
37429
+ throw new Error("Invalid local identity configuration");
37430
+ const scope = { ...options.scope }, organizationName = options.organizationName;
37431
+ const users = /* @__PURE__ */ new Map();
37432
+ for (const user of options.users) {
37433
+ if (!user || Object.keys(user).some((name2) => !["id", "displayName", "email", "roles"].includes(name2)) || !uuid5(user.id) || users.has(user.id) || !text3(user.displayName, 200) || user.email !== void 0 && !text3(user.email, 320))
37434
+ throw new Error("Invalid local identity user");
37435
+ if (user.roles !== void 0 && (!Array.isArray(user.roles) || user.roles.length > 32 || user.roles.some((role) => !role || Object.keys(role).some((name2) => !["name", "permissions"].includes(name2)) || !text3(role.name, 100) || !Array.isArray(role.permissions) || role.permissions.length > 128 || role.permissions.some((permission) => !text3(permission, 100)) || new Set(role.permissions).size !== role.permissions.length) || new Set(user.roles.map((role) => role.name)).size !== user.roles.length))
37436
+ throw new Error("Invalid local identity roles");
37437
+ users.set(user.id, structuredClone(user));
37438
+ }
37439
+ const origins = /* @__PURE__ */ new Set();
37440
+ for (const value of options.requestOrigins) {
37441
+ let origin;
37442
+ try {
37443
+ origin = new URL(value);
37444
+ } catch {
37445
+ throw new Error("Invalid local identity origin");
37446
+ }
37447
+ if (!["http:", "https:"].includes(origin.protocol) || !["localhost", "127.0.0.1", "[::1]"].includes(origin.hostname) || origin.origin !== value || origin.username || origin.password || origins.has(value))
37448
+ throw new Error("Local identities require exact loopback origins");
37449
+ origins.add(value);
37450
+ }
37451
+ const clock = options.now ?? (() => Math.floor(Date.now() / 1e3));
37452
+ const now = () => {
37453
+ serverOnly();
37454
+ const value = clock();
37455
+ if (!Number.isSafeInteger(value) || value < 0 || value > 253402300499)
37456
+ throw new ApplicationAuthenticationError("application_identity_unavailable");
37457
+ return value;
37458
+ };
37459
+ const sessions = /* @__PURE__ */ new Map();
37460
+ const digest4 = (token) => createHash3("sha256").update(token).digest("hex");
37461
+ const tokenPattern = /^backify-local-user_[a-zA-Z0-9_-]{43}$/;
37462
+ const requestAuth = {
37463
+ forRequest(request) {
37464
+ serverOnly();
37465
+ const authorization = request.headers.get("authorization"), origin = new URL(request.url).origin;
37466
+ const identity = () => {
37467
+ const time3 = now();
37468
+ if (!origins.has(origin))
37469
+ throw new ApplicationAuthenticationError("application_identity_invalid");
37470
+ if (authorization === null)
37471
+ return null;
37472
+ const match = /^Bearer (backify-local-user_[a-zA-Z0-9_-]{43})$/i.exec(authorization);
37473
+ const session = match && tokenPattern.test(match[1]) ? sessions.get(digest4(match[1])) : void 0;
37474
+ if (!session || session.issued > time3 || session.expires <= time3)
37475
+ throw new ApplicationAuthenticationError("application_identity_invalid");
37476
+ const user = users.get(session.userId);
37477
+ return { ...structuredClone(user), roles: structuredClone(user.roles ?? []), claims: { ...scope, localDevelopment: true } };
37478
+ };
37479
+ return { currentUser: async () => identity(), currentOrganization: async () => identity() ? { id: scope.organizationId, name: organizationName } : null };
37480
+ }
37481
+ };
37482
+ return {
37483
+ requestAuth,
37484
+ profiles() {
37485
+ serverOnly();
37486
+ return [...users.values()].map((user) => structuredClone(user));
37487
+ },
37488
+ issue(userId, lifetimeSeconds = 300) {
37489
+ const time3 = now();
37490
+ if (!users.has(userId) || !Number.isInteger(lifetimeSeconds) || lifetimeSeconds < 1 || lifetimeSeconds > 300)
37491
+ throw new Error("Invalid local identity issuance");
37492
+ for (const [hash2, session] of sessions)
37493
+ if (session.expires <= time3)
37494
+ sessions.delete(hash2);
37495
+ if (sessions.size >= 128)
37496
+ throw new ApplicationAuthenticationError("application_identity_unavailable");
37497
+ const accessToken = "backify-local-user_" + randomBytes2(32).toString("base64url"), expires = time3 + lifetimeSeconds;
37498
+ sessions.set(digest4(accessToken), { userId, issued: time3, expires });
37499
+ return { accessToken, tokenType: "Bearer", expiresAt: new Date(expires * 1e3).toISOString() };
37500
+ },
37501
+ revoke(accessToken) {
37502
+ serverOnly();
37503
+ return typeof accessToken === "string" && tokenPattern.test(accessToken) && sessions.delete(digest4(accessToken));
37504
+ },
37505
+ clear() {
37506
+ serverOnly();
37507
+ sessions.clear();
37508
+ }
37509
+ };
37510
+ }
37511
+ function createLocalEmailAuth(options, crypto2 = { createHash: createHash3, randomBytes: randomBytes2, randomUUID: randomUUID4 }) {
37512
+ const { createHash: createHash17, randomBytes: randomBytes7, randomUUID: randomUUID13 } = crypto2;
37513
+ const origin = new URL(options.origin);
37514
+ if (typeof window !== "undefined" || process.env.NODE_ENV === "production" || !["localhost", "127.0.0.1", "[::1]"].includes(origin.hostname) || !["http:", "https:"].includes(origin.protocol) || options.origin !== origin.origin)
37515
+ throw new Error("Local email authentication requires an exact loopback origin outside production");
37516
+ const clock = options.now ?? (() => Date.now());
37517
+ const challenges = /* @__PURE__ */ new Map();
37518
+ const inbox = [];
37519
+ const starts = /* @__PURE__ */ new Map();
37520
+ const hash2 = (value) => createHash17("sha256").update(value).digest("hex");
37521
+ const random2 = () => randomBytes7(32).toString("base64url");
37522
+ const cookie = (name2, value, seconds) => name2 + "=" + value + "; HttpOnly; SameSite=Strict; Path=/; Max-Age=" + seconds + (origin.protocol === "https:" ? "; Secure" : "");
37523
+ const readCookie = (request, name2) => request.headers.get("cookie")?.split(";").map((item) => item.trim()).find((item) => item.startsWith(name2 + "="))?.slice(name2.length + 1) ?? "";
37524
+ const json4 = (value, status = 200, headers = {}) => Response.json(value, { status, headers: { "cache-control": "no-store", ...headers } });
37525
+ const page = (body, headers = {}) => new Response("<!doctype html><html><head><title>Local email sign-in</title></head><body><h1>Local email sign-in</h1>" + body + "</body></html>", { headers: { "content-type": "text/html; charset=utf-8", "cache-control": "no-store", "referrer-policy": "strict-origin", "content-security-policy": "default-src 'none'; form-action 'self'; base-uri 'none'; frame-ancestors 'none'", ...headers } });
37526
+ const tokenPattern = /^[A-Za-z0-9_-]{43}$/;
37527
+ return {
37528
+ inbox() {
37529
+ return structuredClone(inbox);
37530
+ },
37531
+ async handle(request) {
37532
+ const url2 = new URL(request.url);
37533
+ if (url2.origin !== origin.origin || !url2.pathname.startsWith("/.backify/auth/"))
37534
+ return json4({ error: "invalid_local_origin" }, 403);
37535
+ if (request.method === "POST" && request.headers.get("origin") !== origin.origin)
37536
+ return json4({ error: "invalid_local_origin" }, 403);
37537
+ const path = url2.pathname.slice("/.backify/auth/".length);
37538
+ const ticket = readCookie(request, "backify_local_session");
37539
+ let user = null;
37540
+ try {
37541
+ user = await options.identity.requestAuth.forRequest(new Request(origin.origin, { headers: ticket ? { authorization: "Bearer " + ticket } : {} })).currentUser();
37542
+ } catch {
37543
+ }
37544
+ if (request.method === "GET" && path === "me")
37545
+ return json4(user);
37546
+ if (request.method === "GET" && path === "organization")
37547
+ return json4(user ? { id: user.claims?.organizationId, name: "Local development" } : null);
37548
+ if (request.method === "POST" && path === "access-token")
37549
+ return user ? json4({ accessToken: ticket, tokenType: "Bearer", expiresAt: new Date(clock() + 6e4).toISOString() }) : json4({ error: "authentication_required" }, 401);
37550
+ if (request.method === "POST" && path === "signout") {
37551
+ options.identity.revoke(ticket);
37552
+ return new Response(null, { status: 204, headers: { "set-cookie": cookie("backify_local_session", "", 0), "cache-control": "no-store" } });
37553
+ }
37554
+ if (request.method === "GET" && path === "login")
37555
+ return page("<p>Use an email from your reviewed local identity fixtures. Read the captured link with <code>backify identity inbox --local</code>. No email is sent.</p><form method='post' action='/.backify/auth/email/request'><label>Email <input type='email' name='email' required></label><button>Send magic link</button></form>");
37556
+ if (request.method === "POST" && (path === "email/start" || path === "email/request")) {
37557
+ if (Number(request.headers.get("content-length") ?? 0) > 4096)
37558
+ return json4({ error: "request_too_large" }, 413);
37559
+ const body = await request.text();
37560
+ if (body.length > 4096)
37561
+ return json4({ error: "request_too_large" }, 413);
37562
+ let input;
37563
+ try {
37564
+ input = path === "email/request" ? Object.fromEntries(new URLSearchParams(body)) : JSON.parse(body);
37565
+ } catch {
37566
+ return json4({ error: "invalid_email_request" }, 400);
37567
+ }
37568
+ if (!input || typeof input.email !== "string" || input.email.length > 320 || input.method !== void 0 && input.method !== "magic-link")
37569
+ return json4({ error: "local_magic_links_only" }, 400);
37570
+ const email2 = input.email.trim().toLowerCase();
37571
+ const recent = (starts.get(email2) ?? []).filter((time3) => time3 > clock() - 6e4);
37572
+ if (recent.length >= 5 || starts.size >= 256 && !starts.has(email2))
37573
+ return json4({ error: "rate_limited" }, 429);
37574
+ starts.set(email2, [...recent, clock()]);
37575
+ for (const [id2, challenge] of challenges)
37576
+ if (challenge.expires <= clock())
37577
+ challenges.delete(id2);
37578
+ if (challenges.size >= 128)
37579
+ return json4({ error: "rate_limited" }, 429);
37580
+ const id = randomUUID13(), proof = random2(), secret = random2();
37581
+ const profile = options.identity.profiles().find((item) => item.email?.toLowerCase() === email2);
37582
+ if (profile) {
37583
+ challenges.set(id, { userId: profile.id, proof: hash2(proof), token: hash2(secret), expires: clock() + 6e5 });
37584
+ inbox.push({ email: email2, text: origin.origin + "/.backify/auth/email/link?id=" + id + "&code=" + secret, createdAt: new Date(clock()).toISOString() });
37585
+ if (inbox.length > 128)
37586
+ inbox.shift();
37587
+ }
37588
+ const headers = { "set-cookie": cookie("backify_local_email_proof", proof, 600) };
37589
+ return path === "email/request" ? page("<p>Check the private local inbox. Open the magic link in this browser.</p>", headers) : json4({ challengeId: id, status: "check_email" }, 202, headers);
37590
+ }
37591
+ if (request.method === "GET" && path === "email/link") {
37592
+ const id = url2.searchParams.get("id") ?? "", secret = url2.searchParams.get("code") ?? "";
37593
+ if (!/^[a-f0-9-]{36}$/.test(id) || !tokenPattern.test(secret))
37594
+ return json4({ error: "invalid_email_link" }, 400);
37595
+ return page("<form method='post' action='/.backify/auth/email/confirm'><input type='hidden' name='id' value='" + id + "'><input type='hidden' name='code' value='" + secret + "'><button>Confirm local sign-in</button></form>");
37596
+ }
37597
+ if (request.method === "POST" && path === "email/confirm") {
37598
+ const body = await request.text();
37599
+ if (body.length > 4096)
37600
+ return json4({ error: "request_too_large" }, 413);
37601
+ const input = new URLSearchParams(body), id = input.get("id") ?? "", secret = input.get("code") ?? "";
37602
+ const challenge = challenges.get(id), proof = readCookie(request, "backify_local_email_proof");
37603
+ if (!challenge || challenge.expires <= clock() || !tokenPattern.test(secret) || !tokenPattern.test(proof) || challenge.proof !== hash2(proof) || challenge.token !== hash2(secret))
37604
+ return json4({ error: "invalid_email_link" }, 400);
37605
+ challenges.delete(id);
37606
+ const identity = options.identity.issue(challenge.userId);
37607
+ return new Response(null, { status: 303, headers: { location: "/", "set-cookie": cookie("backify_local_session", identity.accessToken, 300), "cache-control": "no-store" } });
37608
+ }
37609
+ return json4({ error: "local_auth_route_unavailable" }, 404);
37610
+ }
37611
+ };
37612
+ }
37613
+
37614
+ // src/local-inspection.ts
37615
+ function createLocalDataInspector(runtime, options) {
37616
+ const tableName = (value) => typeof value === "string" && /^[A-Za-z_][A-Za-z0-9_]{0,62}$/.test(value) && !/^__backify/i.test(value);
37617
+ const bucketName = (value) => typeof value === "string" && /^[A-Za-z0-9_-]{1,100}$/.test(value);
37618
+ if (typeof window !== "undefined" || options.buckets.length > 100 || options.buckets.some((name2) => !bucketName(name2)) || new Set(options.buckets).size !== options.buckets.length) throw new Error("invalid_local_inspection");
37619
+ const fail = () => {
37620
+ throw new Error("invalid_local_inspection");
37621
+ };
37622
+ const unavailable4 = () => {
37623
+ throw new Error("local_inspection_unavailable");
37624
+ };
37625
+ const providerRequest = async (operation, missingObject = false) => {
37626
+ try {
37627
+ return await operation();
37628
+ } catch (error2) {
37629
+ const status = error2?.status;
37630
+ if (status === 413) throw new Error("local_inspection_too_large");
37631
+ if (status === 400) fail();
37632
+ if (status === 404 && missingObject) throw new Error("local_inspection_not_found");
37633
+ return unavailable4();
37634
+ }
37635
+ };
37636
+ const object7 = (value, fields5) => {
37637
+ if (!value || typeof value !== "object" || Array.isArray(value) || Object.keys(value).some((name2) => !fields5.includes(name2))) fail();
37638
+ return value;
37639
+ };
37640
+ const page = (input) => {
37641
+ const limit = input.limit ?? 25, offset = input.offset ?? 0;
37642
+ if (typeof limit !== "number" || !Number.isInteger(limit) || limit < 1 || limit > 50 || typeof offset !== "number" || !Number.isInteger(offset) || offset < 0 || offset > 1e4) fail();
37643
+ return { limit, offset };
37644
+ };
37645
+ const bounded = (value) => {
37646
+ if (Buffer.byteLength(JSON.stringify(value)) > 65536) throw new Error("local_inspection_too_large");
37647
+ return value;
37648
+ };
37649
+ const redact = (value, depth = 0) => {
37650
+ if (depth > 20) return "[DEPTH LIMIT]";
37651
+ if (Array.isArray(value)) return value.map((item) => redact(item, depth + 1));
37652
+ if (value && typeof value === "object") return Object.fromEntries(Object.entries(value).map(([name2, item]) => [name2, /(?:password|secret|token|credential|private.?key|connection.?string)/i.test(name2) ? "[REDACTED]" : redact(item, depth + 1)]));
37653
+ return value;
37654
+ };
37655
+ const requireBucket = (name2) => {
37656
+ if (!options.storageEnabled) unavailable4();
37657
+ const known = [...options.buckets, ...options.nativeStorage ? [] : runtime.inspect().buckets.map((bucket) => bucket.name)];
37658
+ if (!bucketName(name2) || !known.includes(name2)) fail();
37659
+ return name2;
37660
+ };
37661
+ return {
37662
+ async tables() {
37663
+ if (!options.databaseEnabled) unavailable4();
37664
+ if (runtime.database.listTables) return bounded(await providerRequest(() => runtime.database.listTables()));
37665
+ if (options.nativeDatabase) unavailable4();
37666
+ const names = runtime.inspect().tables.map((table) => table.name).filter(tableName).sort();
37667
+ return { names: names.slice(0, 100), hasMore: names.length > 100 };
37668
+ },
37669
+ async rows(value) {
37670
+ if (!options.databaseEnabled) unavailable4();
37671
+ const input = object7(value, ["table", "limit", "offset"]), pagination = page(input);
37672
+ if (!tableName(input.table)) fail();
37673
+ if (runtime.database.inspectRows) {
37674
+ const result = await providerRequest(() => runtime.database.inspectRows(input.table, pagination));
37675
+ return bounded({ ...result, rows: result.rows.map((row) => redact(row)) });
37676
+ }
37677
+ if (options.nativeDatabase) unavailable4();
37678
+ const rows = await runtime.database.query(input.table, { filters: [], limit: pagination.limit + 1, offset: pagination.offset });
37679
+ return bounded({ rows: rows.slice(0, pagination.limit).map((row) => redact(row)), ...pagination, nextOffset: rows.length > pagination.limit && pagination.offset + pagination.limit <= 1e4 ? pagination.offset + pagination.limit : null });
37680
+ },
37681
+ buckets() {
37682
+ if (!options.storageEnabled) unavailable4();
37683
+ return bounded({ names: [.../* @__PURE__ */ new Set([...options.buckets, ...options.nativeStorage ? [] : runtime.inspect().buckets.map((bucket) => bucket.name)])].filter(bucketName).sort().slice(0, 100) });
37684
+ },
37685
+ async objects(value) {
37686
+ const input = object7(value, ["bucket", "prefix", "limit", "offset"]), pagination = page(input);
37687
+ const name2 = requireBucket(input.bucket);
37688
+ if (input.prefix !== void 0 && (typeof input.prefix !== "string" || input.prefix.length > 512 || /[\\\x00-\x1f\x7f]/.test(input.prefix) || input.prefix.startsWith("/") || input.prefix.split("/").some((part) => part === "." || part === ".."))) fail();
37689
+ const objects = await providerRequest(() => runtime.storage.list(name2, input.prefix));
37690
+ if (objects.length > 1e3) throw new Error("local_inspection_too_large");
37691
+ objects.sort((first, second) => first.key.localeCompare(second.key));
37692
+ return bounded({ objects: objects.slice(pagination.offset, pagination.offset + pagination.limit), ...pagination, nextOffset: objects.length > pagination.offset + pagination.limit ? pagination.offset + pagination.limit : null });
37693
+ },
37694
+ async preview(value) {
37695
+ const input = object7(value, ["bucket", "key"]), name2 = requireBucket(input.bucket);
37696
+ if (typeof input.key !== "string" || !input.key || input.key.length > 512 || input.key.startsWith("/") || /[\\\x00-\x1f\x7f]/.test(input.key) || input.key.split("/").some((part) => part === "." || part === "..")) fail();
37697
+ if (!options.nativeStorage && !await runtime.storage.exists(name2, input.key)) throw new Error("local_inspection_not_found");
37698
+ const bytes = await providerRequest(() => runtime.storage.download(name2, input.key), true);
37699
+ if (bytes.byteLength > 16384) return { kind: "too-large", size: bytes.byteLength, maximumPreviewBytes: 16384 };
37700
+ try {
37701
+ const text3 = new TextDecoder("utf8", { fatal: true }).decode(bytes);
37702
+ if (text3.includes("\0")) throw new Error("Binary object");
37703
+ return bounded({ kind: "text", size: bytes.byteLength, text: text3 });
37704
+ } catch (error2) {
37705
+ if (error2 instanceof Error && error2.message === "local_inspection_too_large") throw error2;
37706
+ return { kind: "binary", size: bytes.byteLength, bytes: [...bytes.slice(0, 64)], truncated: bytes.byteLength > 64 };
37707
+ }
37708
+ }
37709
+ };
37710
+ }
37711
+
37712
+ // src/local-dashboard.ts
37713
+ var dashboardHtml = String.raw`<!doctype html>
37714
+ <html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Backify Local</title>
37715
+ <style>body{font:16px system-ui;max-width:1100px;margin:30px auto;padding:20px;background:#10131a;color:#ecf1ff}button,select,input,textarea{font:inherit;padding:8px;margin:4px;border:1px solid #8ca1bc;border-radius:5px}button{cursor:pointer}button:disabled{cursor:wait;opacity:.6}button:focus-visible,select:focus-visible,input:focus-visible,textarea:focus-visible{outline:3px solid #78baff}nav{display:flex;flex-wrap:wrap;margin-bottom:20px}section{padding:16px;border:1px solid #36465f;border-radius:8px;margin:12px 0}pre{white-space:pre-wrap;overflow-wrap:anywhere;background:#171f2b;padding:16px;border-radius:6px}label{display:inline-block;margin:4px}p{line-height:1.5;color:#bdcbe0}#message{min-height:24px;color:#f5c575}[hidden]{display:none!important}textarea{display:block;width:30em;max-width:100%;min-height:80px}</style></head>
37716
+ <body><h1>Backify Local Development</h1><p>Application data stays on this computer. This is a local operator dashboard, not an application user's login or a production portal.</p>
37717
+ <nav aria-label="Inspection panels"><button data-panel="overview">Overview</button><button data-panel="data">Data</button><button data-panel="jobs">Jobs</button><button data-panel="events">Events</button><button data-panel="logs">Logs</button></nav>
37718
+ <p id="message" role="status" aria-live="polite">Open this dashboard using backify dev --open to authenticate.</p>
37719
+ <section id="overview"><h2>Supervisor and endpoints</h2><p>A responding endpoint is not proof of provider health. Database and storage data are inspected explicitly in the Data panel.</p><button id="refresh">Refresh status</button><pre id="state" aria-label="Local status"></pre></section>
37720
+ <section id="data" hidden><h2>Read-only data inspection</h2><p>At most 100 public database table names and 50 rows per page are supported. Common credential-named row fields are redacted; this is not comprehensive secret classification. Object contents require an explicit preview request. No data mutation controls are provided.</p>
37721
+ <h3>Database</h3><button id="load-tables">Load tables</button><label>Table <select id="tables" aria-label="Database table"></select></label><button id="load-rows">Inspect rows</button><button id="next-rows" disabled>Next row page</button><pre id="rows" aria-label="Database rows"></pre>
37722
+ <h3>Private storage</h3><button id="load-buckets">Load buckets</button><label>Bucket <select id="buckets" aria-label="Storage bucket"></select></label><label>Prefix <input id="prefix" maxlength="512"></label><button id="load-objects">List objects</button><button id="next-objects" disabled>Next object page</button><pre id="objects" aria-label="Storage objects"></pre><label>Object <select id="keys" aria-label="Storage object"></select></label><button id="preview">Preview selected object</button><pre id="object-preview" aria-label="Object preview"></pre></section>
37723
+ <section id="jobs" hidden><h2>Declared jobs and retained history</h2><p>These are local operator actions, not application-user permissions. Retries create a new run and may repeat business side effects. Do not enter credentials in job payloads.</p><button id="load-jobs">Refresh jobs</button><label>Job <select id="job-name" aria-label="Declared job"></select></label><label>Payload <textarea id="job-payload" aria-label="Job payload (JSON)" maxlength="32768" placeholder="Optional JSON, otherwise null"></textarea></label><button id="run-job">Run selected job</button><h3>Schedules</h3><label>Schedule <select id="schedule-id" aria-label="Declared schedule"></select></label><button id="pause-schedule" disabled>Pause selected schedule</button><button id="resume-schedule" disabled>Resume selected schedule</button><h3>Run recovery</h3><label>Run <select id="run-id" aria-label="Recoverable run"></select></label><button id="retry-run" disabled>Retry failed run</button><button id="cancel-run" disabled>Cancel selected run</button><pre id="job-state" aria-label="Job history"></pre></section>
37724
+ <section id="logs" hidden><h2>Local logs</h2><button id="load-logs">Refresh logs</button><pre id="log-state" aria-label="Local logs"></pre></section>
37725
+ <section id="events" hidden><h2>Local event activity</h2><p>Latest 100 delivery metadata rows and retained status counts. Payloads, idempotency keys and lease receipts are never shown. Lightweight mode preserves snapshot leases. Full mode uses a native PostgreSQL inbox and drains retained snapshot records without renaming or deleting them. Local hooks and retained drainage are single-worker, not distributed cloud subscriptions. No acknowledgement or destructive controls are exposed.</p><button id="load-events">Refresh events</button><pre id="event-state" aria-label="Local event activity"></pre></section>
37726
+ <script>
37727
+ const token=new URLSearchParams(location.hash.slice(1)).get("session");
37728
+ history.replaceState(null,"",location.pathname);
37729
+ const element=id=>document.getElementById(id);
37730
+ let rowPage=null,objectPage=null,rowTable="",objectBucket="",objectPrefix="",jobsBusy=false,jobView={jobs:[],schedules:[],runs:[]};
37731
+ const jobActions=["run-job","pause-schedule","resume-schedule","retry-run","cancel-run"];
37732
+ function show(id,value){element(id).textContent=JSON.stringify(value,null,2)}
37733
+ function choices(id,names){element(id).replaceChildren();for(const name of names){const option=document.createElement("option");option.value=name;option.textContent=name;element(id).append(option)}}
37734
+ async function request(path,input){if(!token)throw new Error("Local session required; reopen using backify dev --open.");const response=await fetch(path,{method:input===undefined?"GET":"POST",headers:{authorization:"Bearer "+token,"content-type":"application/json"},body:input===undefined?undefined:JSON.stringify(input),redirect:"error",cache:"no-store",signal:AbortSignal.timeout(35000)});const value=await response.json();if(!response.ok)throw new Error("Inspection failed ("+response.status+"): "+(value.error||"unavailable"));return value}
37735
+ function action(id,handler){element(id).onclick=async()=>{if(jobActions.includes(id)){if(jobsBusy)return;jobsBusy=true;jobControls()}element(id).disabled=true;element("message").textContent="Loading...";try{await handler();element("message").textContent="Updated."}catch(error){element("message").textContent=error instanceof Error?error.message:"Local operation unavailable"}finally{if(jobActions.includes(id)){jobsBusy=false;jobControls()}else element(id).disabled=id==="next-rows"?rowPage===null:id==="next-objects"?objectPage===null:false}}}
37736
+ async function status(){show("state",await request("/v1/status"))}
37737
+ async function rows(offset){const table=element("tables").value;if(!table)throw new Error("Choose a table first.");const result=await request("/v1/database/rows",{table,offset,limit:25});rowTable=table;rowPage=result.nextOffset;show("rows",result);element("next-rows").disabled=rowPage===null}
37738
+ async function objects(offset){const bucket=element("buckets").value,prefix=element("prefix").value;if(!bucket)throw new Error("Choose a bucket first.");const result=await request("/v1/storage/objects",{bucket,prefix,offset,limit:25});objectBucket=bucket;objectPrefix=prefix;objectPage=result.nextOffset;show("objects",result);choices("keys",result.objects.map(value=>value.key));element("next-objects").disabled=objectPage===null;element("object-preview").textContent=""}
37739
+ function records(id,values,label){const selected=element(id).value;element(id).replaceChildren();for(const value of values){const option=document.createElement("option");option.value=value.id;option.textContent=label(value);element(id).append(option)}if(values.some(value=>value.id===selected))element(id).value=selected}
37740
+ function jobControls(){const schedule=jobView.schedules.find(value=>value.id===element("schedule-id").value),run=jobView.runs.find(value=>value.id===element("run-id").value);element("run-job").disabled=jobsBusy||!jobView.jobs.length;element("pause-schedule").disabled=jobsBusy||!schedule||!schedule.enabled;element("resume-schedule").disabled=jobsBusy||!schedule||schedule.enabled;element("retry-run").disabled=jobsBusy||!run||run.status!=="failed"||run.canRetry===false;element("cancel-run").disabled=jobsBusy||!run||!["queued","running","retrying"].includes(run.status)||run.canCancel===false}
37741
+ async function jobs(){const result=await request("/v1/jobs");jobView=result;show("job-state",result);choices("job-name",result.jobs.map(value=>value.name));records("schedule-id",result.schedules,value=>value.name+" ("+(value.enabled?"enabled":"paused")+")");records("run-id",result.runs.filter(value=>["failed","queued","running","retrying"].includes(value.status)),value=>value.id+" - "+value.job+" ("+value.status+")");jobControls()}
37742
+ element("schedule-id").onchange=jobControls;element("run-id").onchange=jobControls;
37743
+ for(const button of document.querySelectorAll("[data-panel]")){button.onclick=()=>{for(const name of ["overview","data","jobs","events","logs"])element(name).hidden=name!==button.dataset.panel}}
37744
+ action("refresh",status);
37745
+ action("load-tables",async()=>{const result=await request("/v1/database/tables");choices("tables",result.names);show("rows",{tables:result.names.length,hasMore:result.hasMore});rowPage=null;element("next-rows").disabled=true});
37746
+ action("load-rows",()=>rows(0));
37747
+ action("next-rows",()=>{if(rowPage===null||rowTable!==element("tables").value)throw new Error("Reload rows after changing the table.");return rows(rowPage)});
37748
+ action("load-buckets",async()=>{const result=await request("/v1/storage/buckets");choices("buckets",result.names);show("objects",result);objectPage=null;element("next-objects").disabled=true});
37749
+ action("load-objects",()=>objects(0));
37750
+ action("next-objects",()=>{if(objectPage===null||objectBucket!==element("buckets").value||objectPrefix!==element("prefix").value)throw new Error("Reload objects after changing bucket or prefix.");return objects(objectPage)});
37751
+ action("preview",async()=>{const bucket=element("buckets").value,key=element("keys").value;if(!key||bucket!==objectBucket)throw new Error("List and choose an object first.");show("object-preview",await request("/v1/storage/preview",{bucket,key}))});
37752
+ action("load-jobs",jobs);
37753
+ action("run-job",async()=>{const name=element("job-name").value;if(!name)throw new Error("Choose a declared job first.");const raw=element("job-payload").value;if(new TextEncoder().encode(raw).length>32768)throw new Error("Job payload exceeds 32 KiB.");let payload=null;try{if(raw.trim())payload=JSON.parse(raw)}catch{throw new Error("Enter valid JSON for the job payload.")}const input={name,payload};if(new TextEncoder().encode(JSON.stringify(input)).length>32768)throw new Error("Job payload exceeds 32 KiB.");await request("/v1/jobs/run",input);element("job-payload").value="";await jobs()});
37754
+ action("pause-schedule",async()=>{await request("/v1/schedules/enabled",{id:element("schedule-id").value,enabled:false});await jobs()});
37755
+ action("resume-schedule",async()=>{await request("/v1/schedules/enabled",{id:element("schedule-id").value,enabled:true});await jobs()});
37756
+ action("retry-run",async()=>{await request("/v1/jobs/retry",{id:element("run-id").value});await jobs()});
37757
+ action("cancel-run",async()=>{await request("/v1/jobs/cancel",{id:element("run-id").value});await jobs()});
37758
+ action("load-logs",async()=>show("log-state",await request("/v1/logs")));
37759
+ action("load-events",async()=>show("event-state",await request("/v1/events")));
37760
+ if(token)status().then(()=>{element("message").textContent="Local session connected."}).catch(error=>{element("message").textContent=error.message});
37761
+ </script></body></html>`;
37762
+
37763
+ // src/local-native-events.ts
37764
+ function createLocalNativeEvents(local, native) {
37765
+ const handlers = /* @__PURE__ */ new Map();
37766
+ const validateName2 = (name2) => {
37767
+ if (typeof name2 !== "string" || !/^[a-zA-Z][a-zA-Z0-9_.-]{0,127}$/.test(name2) || /[\r\n]/.test(name2)) throw new Error("Invalid event name");
37768
+ };
37769
+ return {
37770
+ track: (name2, data, options) => {
37771
+ if (!local.track) throw new Error("Upgrade the local SDK to enable event tracking");
37772
+ return local.track(name2, data, options);
37773
+ },
37774
+ async emit(name2, payload, options) {
37775
+ validateName2(name2);
37776
+ if (options?.idempotencyKey !== void 0 && (typeof options.idempotencyKey !== "string" || !options.idempotencyKey || options.idempotencyKey.length > 128)) throw new Error("Invalid idempotency key");
37777
+ if (options?.idempotencyKey !== void 0 && (local.hasIdempotencyKey ? local.hasIdempotencyKey(options.idempotencyKey) : local.snapshot().deliveries.some((item) => item.idempotencyKey === options.idempotencyKey))) {
37778
+ await local.emit(name2, payload, options);
37779
+ return;
37495
37780
  }
37496
- const keys = /* @__PURE__ */ new Map();
37497
- for (const entry of input.keys) {
37498
- if (!object2(entry) || Object.keys(entry).some((key2) => !["id", "publicKeyPem"].includes(key2)) || typeof entry.id !== "string" || !/^[a-zA-Z0-9_-]{1,64}$/.test(entry.id) || keys.has(entry.id) || typeof entry.publicKeyPem !== "string" || entry.publicKeyPem.length > 16384 || entry.publicKeyPem.includes("PRIVATE KEY") || !/^-----BEGIN (?:RSA )?PUBLIC KEY-----\r?\n/.test(entry.publicKeyPem))
37499
- unavailable();
37500
- const key = createPublicKey(entry.publicKeyPem);
37501
- const bits2 = key.asymmetricKeyDetails?.modulusLength ?? 0;
37502
- if (key.asymmetricKeyType !== "rsa" || bits2 < 2048 || bits2 > 8192)
37503
- unavailable();
37504
- keys.set(entry.id, key);
37781
+ let accepted;
37782
+ try {
37783
+ accepted = JSON.parse(JSON.stringify(payload ?? null));
37784
+ } catch {
37785
+ throw new Error("Event payload must be JSON serializable");
37505
37786
  }
37506
- options.checkpoint?.({ revision: input.revision, scope: structuredClone(expectedScope), content });
37507
- current = { trust: input, content, keys };
37508
- return current;
37509
- } catch {
37510
- return unavailable();
37511
- }
37512
- };
37513
- load();
37514
- return {
37515
- forRequest(request) {
37516
- const authorization = request.headers.get("authorization");
37517
- const identity = () => {
37518
- const { trust, keys } = load();
37519
- if (authorization === null)
37520
- return null;
37521
- if (authorization.length > 16384)
37522
- invalid();
37523
- const match = /^Bearer ([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)$/i.exec(authorization);
37524
- if (!match)
37525
- invalid();
37526
- const header = json(match[1]);
37527
- fields(header, ["alg", "typ", "kid"]);
37528
- if (header.alg !== "RS256" || header.typ !== "backify-user+jwt" || typeof header.kid !== "string")
37529
- invalid();
37530
- const key = keys.get(header.kid);
37531
- if (!key)
37532
- invalid();
37533
- const signature = Buffer.from(match[3], "base64url");
37534
- if (signature.toString("base64url") !== match[3] || signature.length !== key.asymmetricKeyDetails.modulusLength / 8 || !verify("RSA-SHA256", Buffer.from(match[1] + "." + match[2]), key, signature))
37535
- invalid();
37536
- const payload = json(match[2]);
37537
- fields(payload, ["ver", "iss", "aud", "sub", "organization_id", "application_id", "environment_id", "iat", "nbf", "exp", "jti", "display_name", "email", "organization_name", "roles"]);
37538
- const time3 = now();
37539
- if (payload.ver !== 1 || payload.iss !== trust.issuer || payload.aud !== trust.audience || !uuid(payload.sub) || payload.organization_id !== expectedScope.organizationId || payload.application_id !== expectedScope.applicationId || payload.environment_id !== expectedScope.environmentId || !uuid(payload.jti) || !Number.isSafeInteger(payload.iat) || !Number.isSafeInteger(payload.nbf) || !Number.isSafeInteger(payload.exp))
37540
- invalid();
37541
- const issued = payload.iat, notBefore = payload.nbf, expires = payload.exp;
37542
- if (issued < 0 || issued > time3 || notBefore !== issued || expires <= time3 || expires <= issued || expires - issued > 300 || !text(payload.display_name, 200) || !text(payload.organization_name, 200) || payload.email !== void 0 && !text(payload.email, 320))
37543
- invalid();
37544
- return {
37545
- user: { id: payload.sub, displayName: payload.display_name, ...payload.email === void 0 ? {} : { email: payload.email }, roles: roles(payload.roles), claims: { organizationId: expectedScope.organizationId, applicationId: expectedScope.applicationId, environmentId: expectedScope.environmentId } },
37546
- organization: { id: expectedScope.organizationId, name: payload.organization_name }
37547
- };
37548
- };
37549
- return { currentUser: async () => identity()?.user ?? null, currentOrganization: async () => identity()?.organization ?? null };
37787
+ if (await native.emitAccepted(name2, accepted, options)) {
37788
+ for (const handler of handlers.get(name2) ?? []) await handler(structuredClone(accepted));
37789
+ }
37790
+ },
37791
+ on(name2, handler) {
37792
+ if (typeof name2 !== "string" || !/^[a-zA-Z][a-zA-Z0-9_.-]{0,127}$/.test(name2) || /[\r\n]/.test(name2) || typeof handler !== "function") throw new Error("Invalid local event subscription");
37793
+ handlers.set(name2, [...handlers.get(name2) ?? [], handler]);
37794
+ return () => handlers.set(name2, (handlers.get(name2) ?? []).filter((value) => value !== handler));
37795
+ },
37796
+ async receive(name2, options) {
37797
+ const retained = await local.receive(name2, options);
37798
+ return retained.length ? retained : native.receive(name2, options);
37799
+ },
37800
+ async complete(id, receipt, retry) {
37801
+ if (retry !== void 0 && typeof retry !== "boolean") throw new Error("Invalid local event retry");
37802
+ if (typeof id === "string" && id.startsWith("event_")) await local.complete(id, receipt, retry);
37803
+ else await native.complete(id, receipt, retry);
37804
+ },
37805
+ async inspect() {
37806
+ const retained = local.inspect(), durable = await native.inspect();
37807
+ const counts = { ...retained.counts };
37808
+ for (const status of Object.keys(counts)) {
37809
+ counts[status] += durable.counts[status];
37810
+ if (!Number.isSafeInteger(counts[status])) throw new Error("Local event inspection count exceeds bounds");
37811
+ }
37812
+ const total = Object.values(counts).reduce((sum, count) => sum + count, 0);
37813
+ if (!Number.isSafeInteger(total)) throw new Error("Local event inspection count exceeds bounds");
37814
+ const deliveries = [...retained.deliveries, ...durable.deliveries].sort((first, second) => Date.parse(second.emittedAt) - Date.parse(first.emittedAt) || (first.id < second.id ? 1 : first.id > second.id ? -1 : 0)).slice(0, 100);
37815
+ return { version: 1, counts, deliveries, hasMore: total > deliveries.length };
37550
37816
  }
37551
37817
  };
37552
37818
  }
37553
37819
 
37820
+ // src/local-job-executor.ts
37821
+ import { spawn as spawn2 } from "node:child_process";
37822
+ import { createHash as createHash11 } from "node:crypto";
37823
+ import { lstatSync as lstatSync12, readFileSync as readFileSync16 } from "node:fs";
37824
+ import { isAbsolute as isAbsolute8, join as join12, relative as relative3, resolve as resolve12 } from "node:path";
37825
+
37554
37826
  // ../sdk/dist/application-auth-state.js
37555
- import { createHash as createHash3, randomUUID as randomUUID4 } from "node:crypto";
37556
- import { closeSync, constants, fstatSync, fsyncSync, lstatSync as lstatSync4, openSync, readSync, renameSync as renameSync3, unlinkSync as unlinkSync2, writeFileSync as writeFileSync7 } from "node:fs";
37827
+ import { createHash as createHash4, randomUUID as randomUUID5 } from "node:crypto";
37828
+ import { closeSync, constants, fstatSync, fsyncSync, lstatSync as lstatSync5, openSync, readSync, renameSync as renameSync3, unlinkSync as unlinkSync2, writeFileSync as writeFileSync8 } from "node:fs";
37557
37829
  import { dirname as dirname6, isAbsolute as isAbsolute2, parse, resolve as resolve6, sep as sep2 } from "node:path";
37558
37830
  function unavailable2() {
37559
37831
  throw new ApplicationAuthenticationError("application_identity_unavailable");
@@ -37566,14 +37838,14 @@ function safePath(filename2) {
37566
37838
  const directory2 = dirname6(filename2);
37567
37839
  let ancestor = directory2;
37568
37840
  for (; ; ) {
37569
- const metadata = lstatSync4(ancestor);
37841
+ const metadata = lstatSync5(ancestor);
37570
37842
  if (!metadata.isDirectory() || metadata.isSymbolicLink())
37571
37843
  unavailable2();
37572
37844
  if (ancestor === parse(ancestor).root)
37573
37845
  break;
37574
37846
  ancestor = dirname6(ancestor);
37575
37847
  }
37576
- const parent = lstatSync4(directory2);
37848
+ const parent = lstatSync5(directory2);
37577
37849
  if (process.platform !== "win32" && ((parent.mode & 63) !== 0 || parent.uid !== process.getuid?.()))
37578
37850
  unavailable2();
37579
37851
  }
@@ -37592,7 +37864,7 @@ function syncDirectory(filename2) {
37592
37864
  }
37593
37865
  }
37594
37866
  function readState(filename2) {
37595
- const metadata = lstatSync4(filename2);
37867
+ const metadata = lstatSync5(filename2);
37596
37868
  safeFile(metadata);
37597
37869
  if (metadata.size > 2048)
37598
37870
  unavailable2();
@@ -37625,10 +37897,10 @@ function readState(filename2) {
37625
37897
  }
37626
37898
  }
37627
37899
  function persist(filename2, state) {
37628
- const temporary = filename2 + "." + randomUUID4() + ".tmp";
37900
+ const temporary = filename2 + "." + randomUUID5() + ".tmp";
37629
37901
  const descriptor2 = openSync(temporary, "wx", 384);
37630
37902
  try {
37631
- writeFileSync7(descriptor2, JSON.stringify(state));
37903
+ writeFileSync8(descriptor2, JSON.stringify(state));
37632
37904
  fsyncSync(descriptor2);
37633
37905
  } finally {
37634
37906
  closeSync(descriptor2);
@@ -37643,12 +37915,12 @@ function checkpoint(filename2, trust, initialize2) {
37643
37915
  filename2 = resolve6(filename2);
37644
37916
  safePath(filename2);
37645
37917
  const lock = filename2 + ".lock";
37646
- const next = { version: 1, scope: trust.scope, revision: trust.revision, digest: createHash3("sha256").update(trust.content).digest("hex") };
37918
+ const next = { version: 1, scope: trust.scope, revision: trust.revision, digest: createHash4("sha256").update(trust.content).digest("hex") };
37647
37919
  if (!initialize2) {
37648
37920
  const previous = readState(filename2);
37649
37921
  if (previous.scope.organizationId === next.scope.organizationId && previous.scope.applicationId === next.scope.applicationId && previous.scope.environmentId === next.scope.environmentId && previous.revision === next.revision && previous.digest === next.digest) {
37650
37922
  try {
37651
- lstatSync4(lock);
37923
+ lstatSync5(lock);
37652
37924
  } catch (error2) {
37653
37925
  if (error2.code === "ENOENT")
37654
37926
  return;
@@ -37659,7 +37931,7 @@ function checkpoint(filename2, trust, initialize2) {
37659
37931
  }
37660
37932
  const descriptor2 = openSync(lock, "wx", 384);
37661
37933
  try {
37662
- writeFileSync7(descriptor2, "backify-application-auth-state-v1");
37934
+ writeFileSync8(descriptor2, "backify-application-auth-state-v1");
37663
37935
  fsyncSync(descriptor2);
37664
37936
  } finally {
37665
37937
  closeSync(descriptor2);
@@ -37669,7 +37941,7 @@ function checkpoint(filename2, trust, initialize2) {
37669
37941
  try {
37670
37942
  if (initialize2) {
37671
37943
  try {
37672
- lstatSync4(filename2);
37944
+ lstatSync5(filename2);
37673
37945
  unavailable2();
37674
37946
  } catch (error2) {
37675
37947
  if (error2.code !== "ENOENT")
@@ -37706,8 +37978,8 @@ function createPersistentApplicationAuthProvider(source, options) {
37706
37978
  }
37707
37979
 
37708
37980
  // ../sdk/dist/application-auth-sync.js
37709
- import { createHash as createHash4, createPublicKey as createPublicKey2, randomUUID as randomUUID5, verify as verify2 } from "node:crypto";
37710
- import { closeSync as closeSync2, constants as constants2, fsyncSync as fsyncSync2, lstatSync as lstatSync5, openSync as openSync2, readFileSync as readFileSync9, renameSync as renameSync4, unlinkSync as unlinkSync3, writeFileSync as writeFileSync8 } from "node:fs";
37981
+ import { createHash as createHash5, createPublicKey as createPublicKey2, randomUUID as randomUUID6, verify as verify2 } from "node:crypto";
37982
+ import { closeSync as closeSync2, constants as constants2, fsyncSync as fsyncSync2, lstatSync as lstatSync6, openSync as openSync2, readFileSync as readFileSync10, renameSync as renameSync4, unlinkSync as unlinkSync3, writeFileSync as writeFileSync9 } from "node:fs";
37711
37983
  import { dirname as dirname7, isAbsolute as isAbsolute3, parse as parse2, resolve as resolve7, sep as sep3 } from "node:path";
37712
37984
  var maximumBytes = 512 * 1024;
37713
37985
  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";
@@ -37746,7 +38018,7 @@ function prepare(options) {
37746
38018
  function planApplicationAuthSynchronization(options) {
37747
38019
  try {
37748
38020
  const prepared = prepare(options);
37749
- return { schemaVersion: 1, status: "planned", scope: structuredClone(options.expectedScope), agentId: options.agentId, endpoint: prepared.endpoint.href, managementKeySha256: createHash4("sha256").update(prepared.key.export({ type: "spki", format: "der" })).digest("hex"), trustFile: prepared.trustFile, stateFile: prepared.stateFile, requiresInitializedOperatorJournal: true, workloadCredentialsRequired: false, deploymentReady: false };
38021
+ return { schemaVersion: 1, status: "planned", scope: structuredClone(options.expectedScope), agentId: options.agentId, endpoint: prepared.endpoint.href, managementKeySha256: createHash5("sha256").update(prepared.key.export({ type: "spki", format: "der" })).digest("hex"), trustFile: prepared.trustFile, stateFile: prepared.stateFile, requiresInitializedOperatorJournal: true, workloadCredentialsRequired: false, deploymentReady: false };
37750
38022
  } catch {
37751
38023
  return unavailable3();
37752
38024
  }
@@ -37754,13 +38026,13 @@ function planApplicationAuthSynchronization(options) {
37754
38026
  function directory(filename2, privateState) {
37755
38027
  const parent = dirname7(filename2);
37756
38028
  for (let ancestor = parent; ; ancestor = dirname7(ancestor)) {
37757
- const metadata2 = lstatSync5(ancestor);
38029
+ const metadata2 = lstatSync6(ancestor);
37758
38030
  if (!metadata2.isDirectory() || metadata2.isSymbolicLink())
37759
38031
  unavailable3();
37760
38032
  if (ancestor === parse2(ancestor).root)
37761
38033
  break;
37762
38034
  }
37763
- const metadata = lstatSync5(parent);
38035
+ const metadata = lstatSync6(parent);
37764
38036
  if (process.platform !== "win32" && (metadata.uid !== process.getuid?.() || (metadata.mode & (privateState ? 63 : 18)) !== 0))
37765
38037
  unavailable3();
37766
38038
  }
@@ -37776,10 +38048,10 @@ function syncDirectory2(filename2) {
37776
38048
  }
37777
38049
  function currentPublicFile(filename2) {
37778
38050
  try {
37779
- const metadata = lstatSync5(filename2);
38051
+ const metadata = lstatSync6(filename2);
37780
38052
  if (!metadata.isFile() || metadata.isSymbolicLink() || metadata.nlink !== 1 || metadata.size > 131072 || process.platform !== "win32" && (metadata.uid !== process.getuid?.() || (metadata.mode & 18) !== 0))
37781
38053
  unavailable3();
37782
- const bytes = readFileSync9(filename2);
38054
+ const bytes = readFileSync10(filename2);
37783
38055
  if (bytes.length > 131072)
37784
38056
  unavailable3();
37785
38057
  return new TextDecoder("utf8", { fatal: true }).decode(bytes);
@@ -37846,7 +38118,7 @@ async function synchronizeApplicationAuthTrustWithDigest(options) {
37846
38118
  const lock = prepared.stateFile + ".delivery.lock";
37847
38119
  const descriptor2 = openSync2(lock, "wx", 384);
37848
38120
  try {
37849
- writeFileSync8(descriptor2, "backify-application-auth-delivery-v1");
38121
+ writeFileSync9(descriptor2, "backify-application-auth-delivery-v1");
37850
38122
  fsyncSync2(descriptor2);
37851
38123
  } finally {
37852
38124
  closeSync2(descriptor2);
@@ -37857,14 +38129,14 @@ async function synchronizeApplicationAuthTrustWithDigest(options) {
37857
38129
  const current = currentPublicFile(prepared.trustFile);
37858
38130
  createPersistentApplicationAuthProvider(trust, { expectedScope: options.expectedScope, stateFile: prepared.stateFile, now: options.now });
37859
38131
  const content = JSON.stringify(trust);
37860
- const trustDigest = createHash4("sha256").update(content).digest("hex");
38132
+ const trustDigest = createHash5("sha256").update(content).digest("hex");
37861
38133
  if (current === content)
37862
38134
  return { status: "unchanged", revision: trust.revision, validUntil: trust.validUntil, trustDigest };
37863
38135
  writePending = true;
37864
- const temporary = prepared.trustFile + "." + randomUUID5() + ".tmp";
38136
+ const temporary = prepared.trustFile + "." + randomUUID6() + ".tmp";
37865
38137
  const output = openSync2(temporary, "wx", process.platform === "win32" ? 384 : 292);
37866
38138
  try {
37867
- writeFileSync8(output, content);
38139
+ writeFileSync9(output, content);
37868
38140
  fsyncSync2(output);
37869
38141
  } finally {
37870
38142
  closeSync2(output);
@@ -38475,10 +38747,10 @@ function jsonValue(value) {
38475
38747
 
38476
38748
  // src/local-services.ts
38477
38749
  import { spawn, execFile } from "node:child_process";
38478
- import { createHash as createHash6, generateKeyPairSync, randomBytes as randomBytes3, randomUUID as randomUUID7, sign } from "node:crypto";
38750
+ import { createHash as createHash7, generateKeyPairSync, randomBytes as randomBytes4, randomUUID as randomUUID8, sign } from "node:crypto";
38479
38751
  import { createServer as createServer3 } from "node:net";
38480
- import { existsSync as existsSync10, lstatSync as lstatSync7, mkdirSync as mkdirSync4, readFileSync as readFileSync11, readdirSync as readdirSync5, realpathSync, unlinkSync as unlinkSync4, writeFileSync as writeFileSync9 } from "node:fs";
38481
- import { basename as basename2, dirname as dirname9, isAbsolute as isAbsolute4, join as join10, relative, resolve as resolve8 } from "node:path";
38752
+ import { existsSync as existsSync11, lstatSync as lstatSync8, mkdirSync as mkdirSync4, readFileSync as readFileSync12, readdirSync as readdirSync5, realpathSync, unlinkSync as unlinkSync4, writeFileSync as writeFileSync10 } from "node:fs";
38753
+ import { basename as basename2, dirname as dirname9, isAbsolute as isAbsolute4, join as join11, relative, resolve as resolve8 } from "node:path";
38482
38754
 
38483
38755
  // src/local-typed-migrations.ts
38484
38756
  var object3 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
@@ -38525,10 +38797,10 @@ function typedMigrationSql(source) {
38525
38797
  }
38526
38798
 
38527
38799
  // src/local-job-services.ts
38528
- import { createHash as createHash5, randomBytes as randomBytes2, randomUUID as randomUUID6 } from "node:crypto";
38529
- import { existsSync as existsSync9, lstatSync as lstatSync6, readFileSync as readFileSync10 } from "node:fs";
38800
+ import { createHash as createHash6, randomBytes as randomBytes3, randomUUID as randomUUID7 } from "node:crypto";
38801
+ import { existsSync as existsSync10, lstatSync as lstatSync7, readFileSync as readFileSync11 } from "node:fs";
38530
38802
  import { isIP } from "node:net";
38531
- import { dirname as dirname8, join as join9 } from "node:path";
38803
+ import { dirname as dirname8, join as join10 } from "node:path";
38532
38804
  function fields3(value, names) {
38533
38805
  return !!value && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === names.length && names.every((name2) => Object.hasOwn(value, name2));
38534
38806
  }
@@ -38579,12 +38851,12 @@ function validLocalJobState(value, otherIds) {
38579
38851
  function prepareLocalJobService(hcrPath, retained, artifacts, applyMigrations) {
38580
38852
  const requested = validateLocalJobArtifacts(artifacts);
38581
38853
  const readSchema = (name2) => {
38582
- const filename2 = join9(dirname8(hcrPath), "sql", name2), info = existsSync9(filename2) ? lstatSync6(filename2) : void 0;
38854
+ const filename2 = join10(dirname8(hcrPath), "sql", name2), info = existsSync10(filename2) ? lstatSync7(filename2) : void 0;
38583
38855
  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");
38584
- return readFileSync10(filename2, "utf8");
38856
+ return readFileSync11(filename2, "utf8");
38585
38857
  };
38586
38858
  const base = readSchema("jobs-v1.sql"), producer = readSchema("jobs-producer-v1.sql");
38587
- const schemaDigests = { base: createHash5("sha256").update(base).digest("hex"), producer: createHash5("sha256").update(producer).digest("hex") };
38859
+ const schemaDigests = { base: createHash6("sha256").update(base).digest("hex"), producer: createHash6("sha256").update(producer).digest("hex") };
38588
38860
  if (retained && (retained.schemaDigests.base !== schemaDigests.base || retained.schemaDigests.producer !== schemaDigests.producer)) throw new Error("Native job schema changed; preserve its database and plan an explicit migration");
38589
38861
  if (!retained?.initialized && !applyMigrations) throw new Error("Review both HCR job SQL assets and pass --apply-migrations for explicit native job schema approval");
38590
38862
  const retainedArtifacts = retained ? validateLocalJobArtifacts(retained.artifacts) : [];
@@ -38593,20 +38865,20 @@ function prepareLocalJobService(hcrPath, retained, artifacts, applyMigrations) {
38593
38865
  if (previous && JSON.stringify(previous) !== JSON.stringify(artifact)) throw new Error("Retained local job artifact metadata cannot change; preserve the original pins and policies");
38594
38866
  if (!previous) retainedArtifacts.push(artifact);
38595
38867
  }
38596
- const state = { ...retained ?? { id: randomUUID6(), password: randomBytes2(32).toString("hex"), initialized: false }, schemaDigests, artifacts: validateLocalJobArtifacts(retainedArtifacts) };
38868
+ const state = { ...retained ?? { id: randomUUID7(), password: randomBytes3(32).toString("hex"), initialized: false }, schemaDigests, artifacts: validateLocalJobArtifacts(retainedArtifacts) };
38597
38869
  return { state, base, producer };
38598
38870
  }
38599
38871
 
38600
38872
  // src/local-services.ts
38601
38873
  function writePrivate(filename2, value) {
38602
38874
  if (isLink(filename2)) throw new Error("Local service files must not be symbolic links");
38603
- const temporary = filename2 + "." + randomUUID7() + ".tmp";
38604
- writeFileSync9(temporary, value, { flag: "wx", mode: 384 });
38875
+ const temporary = filename2 + "." + randomUUID8() + ".tmp";
38876
+ writeFileSync10(temporary, value, { flag: "wx", mode: 384 });
38605
38877
  renameLocalFile(temporary, filename2);
38606
38878
  }
38607
38879
  function isLink(filename2) {
38608
38880
  try {
38609
- return lstatSync7(filename2).isSymbolicLink();
38881
+ return lstatSync8(filename2).isSymbolicLink();
38610
38882
  } catch (error2) {
38611
38883
  if (error2.code === "ENOENT") return false;
38612
38884
  throw error2;
@@ -38627,17 +38899,17 @@ function stateValid(value) {
38627
38899
  return value?.version === 1 && value.scope && [value.scope.organizationId, value.scope.applicationId, value.scope.environmentId, value.databaseId, value.storageId].every((identifier3) => typeof identifier3 === "string" && uuid5.test(identifier3)) && 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);
38628
38900
  }
38629
38901
  function acquireLocalLease(root, relativePath2 = ".backify/dev/development.lock") {
38630
- const filename2 = join10(root, relativePath2);
38902
+ const filename2 = join11(root, relativePath2);
38631
38903
  assertLocalStatePath(root, filename2);
38632
38904
  mkdirSync4(resolve8(filename2, ".."), { recursive: true, mode: 448 });
38633
- const owner = JSON.stringify({ version: 1, pid: process.pid, id: randomUUID7() });
38905
+ const owner = JSON.stringify({ version: 1, pid: process.pid, id: randomUUID8() });
38634
38906
  try {
38635
- writeFileSync9(filename2, owner, { flag: "wx", mode: 384 });
38907
+ writeFileSync10(filename2, owner, { flag: "wx", mode: 384 });
38636
38908
  } catch {
38637
38909
  throw new Error("Local development already owns this repository, or a stale lifecycle lock requires explicit recovery");
38638
38910
  }
38639
38911
  return () => {
38640
- if (existsSync10(filename2) && readFileSync11(filename2, "utf8") === owner) unlinkSync4(filename2);
38912
+ if (existsSync11(filename2) && readFileSync12(filename2, "utf8") === owner) unlinkSync4(filename2);
38641
38913
  };
38642
38914
  }
38643
38915
  async function allocateLocalPort(requested) {
@@ -38680,42 +38952,42 @@ function command(executable, args2, options = {}) {
38680
38952
  });
38681
38953
  }
38682
38954
  function postgresExecutable(name2, bin) {
38683
- const directory2 = bin ?? process.env.BACKIFY_LOCAL_POSTGRES_BIN ?? (process.platform === "win32" ? join10(process.env.ProgramFiles ?? "C:/Program Files", "PostgreSQL", "17", "bin") : void 0);
38684
- return directory2 ? join10(directory2, name2 + (process.platform === "win32" ? ".exe" : "")) : name2;
38955
+ const directory2 = bin ?? process.env.BACKIFY_LOCAL_POSTGRES_BIN ?? (process.platform === "win32" ? join11(process.env.ProgramFiles ?? "C:/Program Files", "PostgreSQL", "17", "bin") : void 0);
38956
+ return directory2 ? join11(directory2, name2 + (process.platform === "win32" ? ".exe" : "")) : name2;
38685
38957
  }
38686
38958
  function localMigrationFiles(root, directory2) {
38687
- const typed = join10(root, "backify.migrations.json");
38959
+ const typed = join11(root, "backify.migrations.json");
38688
38960
  if (directory2 === void 0) {
38689
- if (!existsSync10(typed) && !lstatIfPresent(typed)) return [];
38961
+ if (!existsSync11(typed) && !lstatIfPresent(typed)) return [];
38690
38962
  assertLocalStatePath(root, typed);
38691
- const info = lstatSync7(typed);
38963
+ const info = lstatSync8(typed);
38692
38964
  if (!info.isFile() || info.size > 1024 * 1024) throw new Error("Typed migration manifest must be a file at most 1 MiB");
38693
- return typedMigrationSql(readFileSync11(typed, "utf8")).map((migration) => ({ ...migration, digest: createHash6("sha256").update(migration.sql).digest("hex") }));
38965
+ return typedMigrationSql(readFileSync12(typed, "utf8")).map((migration) => ({ ...migration, digest: createHash7("sha256").update(migration.sql).digest("hex") }));
38694
38966
  }
38695
- if (existsSync10(typed) || lstatIfPresent(typed)) throw new Error("Use either declared SQL migrations or the typed manifest, not both");
38967
+ if (existsSync11(typed) || lstatIfPresent(typed)) throw new Error("Use either declared SQL migrations or the typed manifest, not both");
38696
38968
  if (typeof directory2 !== "string") throw new Error("Local migrations require a repository-relative directory");
38697
38969
  const folder = resolve8(root, directory2);
38698
38970
  assertLocalStatePath(root, folder);
38699
- if (!existsSync10(folder)) throw new Error("Declared migration directory does not exist");
38971
+ if (!existsSync11(folder)) throw new Error("Declared migration directory does not exist");
38700
38972
  const entries2 = readdirSync5(folder);
38701
38973
  const filenames = entries2.filter((entry) => entry.endsWith(".sql")).sort();
38702
38974
  if (filenames.length > 100 || entries2.some((entry) => !entry.endsWith(".sql"))) throw new Error("Migrations require at most 100 flat .sql files");
38703
38975
  let total = 0;
38704
38976
  return filenames.map((name2) => {
38705
38977
  if (!/^[A-Za-z0-9_.-]{1,150}\.sql$/.test(name2)) throw new Error("Invalid migration filename");
38706
- const filename2 = join10(folder, name2);
38978
+ const filename2 = join11(folder, name2);
38707
38979
  assertLocalStatePath(root, filename2);
38708
- const info = lstatSync7(filename2);
38980
+ const info = lstatSync8(filename2);
38709
38981
  if (!info.isFile() || info.size > 1024 * 1024 || (total += info.size) > 4 * 1024 * 1024) throw new Error("Migration SQL exceeds supported limits");
38710
- const sql = readFileSync11(filename2, "utf8");
38982
+ const sql = readFileSync12(filename2, "utf8");
38711
38983
  if (!sql.trim()) throw new Error("Migration SQL must not be empty");
38712
38984
  validateLocalMigrationSql(sql);
38713
- return { name: name2, digest: createHash6("sha256").update(sql).digest("hex"), sql };
38985
+ return { name: name2, digest: createHash7("sha256").update(sql).digest("hex"), sql };
38714
38986
  });
38715
38987
  }
38716
38988
  function lstatIfPresent(filename2) {
38717
38989
  try {
38718
- return lstatSync7(filename2);
38990
+ return lstatSync8(filename2);
38719
38991
  } catch (error2) {
38720
38992
  if (error2 instanceof Error && "code" in error2 && error2.code === "ENOENT") return void 0;
38721
38993
  throw error2;
@@ -38792,19 +39064,19 @@ async function startLocalServices(root, manifest, options = {}) {
38792
39064
  const reviewedScope = options.jobIdentityScope;
38793
39065
  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");
38794
39066
  const installed = options.hcrPath || process.env.BACKIFY_LOCAL_HCR_PATH ? void 0 : installedLocalRuntime();
38795
- const hcrPath = resolve8(options.hcrPath ?? process.env.BACKIFY_LOCAL_HCR_PATH ?? installed?.path ?? join10(root, "apps/hcr/bin/Debug/net9.0/Backify.Hcr.dll"));
38796
- if (!existsSync10(hcrPath) || !lstatSync7(hcrPath).isFile() || !hcrPath.endsWith(".dll")) throw new Error("Full-fidelity mode requires a built Backify.Hcr.dll; set --hcr-path or BACKIFY_LOCAL_HCR_PATH");
38797
- const directory2 = join10(root, ".backify", "dev", "services");
39067
+ const hcrPath = resolve8(options.hcrPath ?? process.env.BACKIFY_LOCAL_HCR_PATH ?? installed?.path ?? join11(root, "apps/hcr/bin/Debug/net9.0/Backify.Hcr.dll"));
39068
+ if (!existsSync11(hcrPath) || !lstatSync8(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");
39069
+ const directory2 = join11(root, ".backify", "dev", "services");
38798
39070
  assertLocalStatePath(root, directory2);
38799
39071
  mkdirSync4(directory2, { recursive: true, mode: 448 });
38800
39072
  assertLocalStatePath(root, directory2);
38801
- const statePath = join10(directory2, "host.json");
39073
+ const statePath = join11(directory2, "host.json");
38802
39074
  assertLocalStatePath(root, statePath);
38803
39075
  let existing;
38804
- if (existsSync10(statePath)) {
38805
- if (lstatSync7(statePath).size > 16384) throw new Error("Local ownership state exceeds supported limits");
39076
+ if (existsSync11(statePath)) {
39077
+ if (lstatSync8(statePath).size > 16384) throw new Error("Local ownership state exceeds supported limits");
38806
39078
  try {
38807
- existing = JSON.parse(readFileSync11(statePath, "utf8"));
39079
+ existing = JSON.parse(readFileSync12(statePath, "utf8"));
38808
39080
  } catch {
38809
39081
  throw new Error("Invalid local service ownership state; preserve the data and repair explicitly");
38810
39082
  }
@@ -38812,31 +39084,31 @@ async function startLocalServices(root, manifest, options = {}) {
38812
39084
  }
38813
39085
  const state = existing ?? {
38814
39086
  version: 1,
38815
- scope: reviewedScope ? structuredClone(reviewedScope) : { organizationId: randomUUID7(), applicationId: randomUUID7(), environmentId: randomUUID7() },
38816
- databaseId: randomUUID7(),
38817
- storageId: randomUUID7(),
39087
+ scope: reviewedScope ? structuredClone(reviewedScope) : { organizationId: randomUUID8(), applicationId: randomUUID8(), environmentId: randomUUID8() },
39088
+ databaseId: randomUUID8(),
39089
+ storageId: randomUUID8(),
38818
39090
  configurationVersion: 0,
38819
- adminPassword: randomBytes3(32).toString("hex"),
38820
- databasePassword: randomBytes3(32).toString("hex")
39091
+ adminPassword: randomBytes4(32).toString("hex"),
39092
+ databasePassword: randomBytes4(32).toString("hex")
38821
39093
  };
38822
39094
  if (!stateValid(state)) throw new Error("Invalid local service ownership state; preserve the data and repair explicitly");
38823
39095
  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");
38824
39096
  let eventSchema;
38825
39097
  if (events) {
38826
- const filename2 = join10(dirname9(hcrPath), "sql", "events-v1.sql");
38827
- if (!existsSync10(filename2) || lstatSync7(filename2).isSymbolicLink() || !lstatSync7(filename2).isFile() || lstatSync7(filename2).size > 65536) throw new Error("Native events require the reviewed events-v1.sql asset beside the HCR host.");
38828
- eventSchema = readFileSync11(filename2, "utf8");
38829
- const digest4 = createHash6("sha256").update(eventSchema).digest("hex");
39098
+ const filename2 = join11(dirname9(hcrPath), "sql", "events-v1.sql");
39099
+ if (!existsSync11(filename2) || lstatSync8(filename2).isSymbolicLink() || !lstatSync8(filename2).isFile() || lstatSync8(filename2).size > 65536) throw new Error("Native events require the reviewed events-v1.sql asset beside the HCR host.");
39100
+ eventSchema = readFileSync12(filename2, "utf8");
39101
+ const digest4 = createHash7("sha256").update(eventSchema).digest("hex");
38830
39102
  if (state.events && state.events.schemaDigest !== digest4) throw new Error("Native event schema changed; preserve its database and plan an explicit migration.");
38831
39103
  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.");
38832
- state.events ??= { id: randomUUID7(), password: randomBytes3(32).toString("hex"), schemaDigest: digest4, initialized: false };
39104
+ state.events ??= { id: randomUUID8(), password: randomBytes4(32).toString("hex"), schemaDigest: digest4, initialized: false };
38833
39105
  }
38834
39106
  const jobSchema = jobs ? prepareLocalJobService(hcrPath, state.jobs, options.jobArtifacts, options.applyMigrations) : void 0;
38835
39107
  if (jobSchema) state.jobs = jobSchema.state;
38836
39108
  const storageNames = manifest.capabilities.storage?.buckets === void 0 ? ["default"] : manifest.capabilities.storage.buckets.map((bucket) => bucket.name);
38837
39109
  state.storageBindings ??= { default: state.storageId };
38838
39110
  if (typeof state.storageBindings !== "object" || state.storageBindings === null || Array.isArray(state.storageBindings) || Object.entries(state.storageBindings).some(([name2, identifier3]) => !/^[A-Za-z0-9_-]{1,100}$/.test(name2) || typeof identifier3 !== "string" || !/^[0-9a-f-]{36}$/i.test(identifier3))) throw new Error("Invalid local storage binding ownership state");
38839
- for (const name2 of storageNames) state.storageBindings[name2] ??= randomUUID7();
39111
+ for (const name2 of storageNames) state.storageBindings[name2] ??= randomUUID8();
38840
39112
  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");
38841
39113
  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");
38842
39114
  const migrations = database ? localMigrationFiles(root, manifest.capabilities.database?.migrations) : [];
@@ -38844,7 +39116,7 @@ async function startLocalServices(root, manifest, options = {}) {
38844
39116
  const databasePort = database || events || jobs ? await allocateLocalPort(options.databasePort) : void 0;
38845
39117
  if (databasePort !== void 0) state.retainedDatabasePort = databasePort;
38846
39118
  if (databasePort === hcrPort) throw new Error("HCR and PostgreSQL require separate ports");
38847
- const cluster = join10(directory2, "postgres");
39119
+ const cluster = join11(directory2, "postgres");
38848
39120
  assertLocalStatePath(root, cluster);
38849
39121
  const release2 = acquireLocalLease(root, ".backify/dev/services/lifecycle.lock");
38850
39122
  let postgresStarted = false;
@@ -38860,7 +39132,7 @@ async function startLocalServices(root, manifest, options = {}) {
38860
39132
  }
38861
39133
  };
38862
39134
  const runtimeUrl = "http://127.0.0.1:" + hcrPort;
38863
- const tokenPath = join10(directory2, "workload-token");
39135
+ const tokenPath = join11(directory2, "workload-token");
38864
39136
  const stop = () => stopping ??= (async () => {
38865
39137
  if (timer) clearInterval(timer);
38866
39138
  if (snapshotTimer) clearInterval(snapshotTimer);
@@ -38879,9 +39151,9 @@ async function startLocalServices(root, manifest, options = {}) {
38879
39151
  }
38880
39152
  notify("hcr", "stopped");
38881
39153
  try {
38882
- if (postgresStarted && existsSync10(join10(cluster, "postmaster.pid"))) await command(postgresExecutable("pg_ctl", options.postgresBin), ["-D", cluster, "-m", "fast", "-w", "stop"]);
39154
+ if (postgresStarted && existsSync11(join11(cluster, "postmaster.pid"))) await command(postgresExecutable("pg_ctl", options.postgresBin), ["-D", cluster, "-m", "fast", "-w", "stop"]);
38883
39155
  if (postgresStarted) notify("postgres", "stopped");
38884
- if (existsSync10(tokenPath)) unlinkSync4(tokenPath);
39156
+ if (existsSync11(tokenPath)) unlinkSync4(tokenPath);
38885
39157
  } finally {
38886
39158
  release2();
38887
39159
  }
@@ -38891,28 +39163,28 @@ async function startLocalServices(root, manifest, options = {}) {
38891
39163
  writePrivate(statePath, JSON.stringify(state));
38892
39164
  if (database || events || jobs) {
38893
39165
  notify("postgres", "starting");
38894
- if (!existsSync10(join10(cluster, "PG_VERSION"))) {
38895
- const passwordPath = join10(directory2, "init-password");
39166
+ if (!existsSync11(join11(cluster, "PG_VERSION"))) {
39167
+ const passwordPath = join11(directory2, "init-password");
38896
39168
  writePrivate(passwordPath, state.adminPassword);
38897
39169
  try {
38898
39170
  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"]);
38899
39171
  } finally {
38900
- if (existsSync10(passwordPath)) unlinkSync4(passwordPath);
39172
+ if (existsSync11(passwordPath)) unlinkSync4(passwordPath);
38901
39173
  }
38902
39174
  }
38903
- if (existsSync10(join10(cluster, "postmaster.pid"))) throw new Error("A retained local PostgreSQL server is still running; stop or recover that exact owned cluster before restarting dev");
39175
+ if (existsSync11(join11(cluster, "postmaster.pid"))) throw new Error("A retained local PostgreSQL server is still running; stop or recover that exact owned cluster before restarting dev");
38904
39176
  postgresStarted = true;
38905
- await command(postgresExecutable("pg_ctl", options.postgresBin), ["-D", cluster, "-l", join10(directory2, "postgres.log"), "-o", "-h 127.0.0.1 -p " + databasePort, "-w", "start"]);
39177
+ await command(postgresExecutable("pg_ctl", options.postgresBin), ["-D", cluster, "-l", join11(directory2, "postgres.log"), "-o", "-h 127.0.0.1 -p " + databasePort, "-w", "start"]);
38906
39178
  notify("postgres", "ready");
38907
39179
  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 } });
38908
39180
  if (database) {
38909
39181
  if ((await sql("SELECT count(*) FROM pg_roles WHERE rolname='backify_local'")).trim() === "0") {
38910
- const filename2 = join10(directory2, "role-" + randomUUID7() + ".sql");
39182
+ const filename2 = join11(directory2, "role-" + randomUUID8() + ".sql");
38911
39183
  writePrivate(filename2, "CREATE ROLE backify_local LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE PASSWORD '" + state.databasePassword + "';");
38912
39184
  try {
38913
39185
  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 } });
38914
39186
  } finally {
38915
- if (existsSync10(filename2)) unlinkSync4(filename2);
39187
+ if (existsSync11(filename2)) unlinkSync4(filename2);
38916
39188
  }
38917
39189
  }
38918
39190
  if ((await sql("SELECT count(*) FROM pg_database WHERE datname='backify_local'")).trim() === "0") await sql("CREATE DATABASE backify_local OWNER backify_local");
@@ -38927,12 +39199,12 @@ async function startLocalServices(root, manifest, options = {}) {
38927
39199
  notify("migrations", "starting");
38928
39200
  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);
38929
39201
  for (const migration of pending) {
38930
- const filename2 = join10(directory2, "apply-" + randomUUID7() + ".sql");
39202
+ const filename2 = join11(directory2, "apply-" + randomUUID8() + ".sql");
38931
39203
  writePrivate(filename2, "BEGIN;\n" + migration.sql + "\n;\nINSERT INTO public.__backify_migrations(name,digest) VALUES ('" + migration.name + "','" + migration.digest + "');\nCOMMIT;\n");
38932
39204
  try {
38933
39205
  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 } });
38934
39206
  } finally {
38935
- if (existsSync10(filename2)) unlinkSync4(filename2);
39207
+ if (existsSync11(filename2)) unlinkSync4(filename2);
38936
39208
  }
38937
39209
  applied.push(migration.name);
38938
39210
  }
@@ -38943,20 +39215,20 @@ async function startLocalServices(root, manifest, options = {}) {
38943
39215
  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 } });
38944
39216
  if (!eventState.initialized) {
38945
39217
  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.");
38946
- const roleFile = join10(directory2, "event-role-" + randomUUID7() + ".sql");
39218
+ const roleFile = join11(directory2, "event-role-" + randomUUID8() + ".sql");
38947
39219
  writePrivate(roleFile, "CREATE ROLE backify_events LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE PASSWORD '" + eventState.password + "';");
38948
39220
  try {
38949
39221
  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 } });
38950
39222
  } finally {
38951
- if (existsSync10(roleFile)) unlinkSync4(roleFile);
39223
+ if (existsSync11(roleFile)) unlinkSync4(roleFile);
38952
39224
  }
38953
39225
  await sql("CREATE DATABASE backify_events OWNER backify_events");
38954
- const schemaFile = join10(directory2, "event-schema-" + randomUUID7() + ".sql");
39226
+ const schemaFile = join11(directory2, "event-schema-" + randomUUID8() + ".sql");
38955
39227
  writePrivate(schemaFile, eventSchema);
38956
39228
  try {
38957
39229
  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 } });
38958
39230
  } finally {
38959
- if (existsSync10(schemaFile)) unlinkSync4(schemaFile);
39231
+ if (existsSync11(schemaFile)) unlinkSync4(schemaFile);
38960
39232
  }
38961
39233
  eventState.initialized = true;
38962
39234
  writePrivate(statePath, JSON.stringify(state));
@@ -38970,21 +39242,21 @@ async function startLocalServices(root, manifest, options = {}) {
38970
39242
  const adminSql = (query, databaseName = "postgres") => jobCommand("backify_admin", state.adminPassword, databaseName, ["-c", query]);
38971
39243
  if (!jobState.initialized) {
38972
39244
  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");
38973
- const roleFile = join10(directory2, "job-role-" + randomUUID7() + ".sql");
39245
+ const roleFile = join11(directory2, "job-role-" + randomUUID8() + ".sql");
38974
39246
  writePrivate(roleFile, "CREATE ROLE backify_jobs LOGIN NOINHERIT NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION NOBYPASSRLS PASSWORD '" + jobState.password + "';");
38975
39247
  try {
38976
39248
  await jobCommand("backify_admin", state.adminPassword, "postgres", ["-f", roleFile]);
38977
39249
  } finally {
38978
- if (existsSync10(roleFile)) unlinkSync4(roleFile);
39250
+ if (existsSync11(roleFile)) unlinkSync4(roleFile);
38979
39251
  }
38980
39252
  await adminSql("CREATE DATABASE backify_jobs OWNER backify_admin");
38981
39253
  for (const schema of [jobSchema.base, jobSchema.producer]) {
38982
- const filename2 = join10(directory2, "job-schema-" + randomUUID7() + ".sql");
39254
+ const filename2 = join11(directory2, "job-schema-" + randomUUID8() + ".sql");
38983
39255
  writePrivate(filename2, schema);
38984
39256
  try {
38985
39257
  await jobCommand("backify_admin", state.adminPassword, "backify_jobs", ["-f", filename2]);
38986
39258
  } finally {
38987
- if (existsSync10(filename2)) unlinkSync4(filename2);
39259
+ if (existsSync11(filename2)) unlinkSync4(filename2);
38988
39260
  }
38989
39261
  }
38990
39262
  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");
@@ -39013,7 +39285,7 @@ async function startLocalServices(root, manifest, options = {}) {
39013
39285
  ...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" }] : [],
39014
39286
  ...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" }] : []
39015
39287
  ];
39016
- const snapshotPath = join10(directory2, "snapshot.json");
39288
+ const snapshotPath = join11(directory2, "snapshot.json");
39017
39289
  const writeSnapshot = () => writePrivate(snapshotPath, JSON.stringify({ schemaVersion: 1, configurationVersion: state.configurationVersion, expiresAt: new Date(Date.now() + 7 * 864e5).toISOString(), bindings }));
39018
39290
  const renewConfiguration = () => {
39019
39291
  if (stopping) throw new Error("Stopped local services cannot renew configuration");
@@ -39023,15 +39295,15 @@ async function startLocalServices(root, manifest, options = {}) {
39023
39295
  writeSnapshot();
39024
39296
  };
39025
39297
  writeSnapshot();
39026
- const settingsPath = join10(directory2, "appsettings.json");
39298
+ const settingsPath = join11(directory2, "appsettings.json");
39027
39299
  writePrivate(settingsPath, JSON.stringify({ Hcr: {
39028
39300
  Authentication: { PublicKeyPem: publicKey.export({ type: "spki", format: "pem" }), Issuer: "backify-local", Audience: "backify-local-hcr" },
39029
39301
  SnapshotPath: snapshotPath,
39030
- SnapshotJournalPath: join10(directory2, "journal.json"),
39302
+ SnapshotJournalPath: join11(directory2, "journal.json"),
39031
39303
  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 } } : {} },
39032
39304
  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 } } : {} },
39033
39305
  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 } } : {} },
39034
- Storage: { Bindings: Object.fromEntries(Object.entries(state.storageBindings).map(([name2, identifier3]) => [identifier3, { Scope: state.scope, ResourceReference: name2, RootPath: join10(directory2, "objects", identifier3) }])) }
39306
+ Storage: { Bindings: Object.fromEntries(Object.entries(state.storageBindings).map(([name2, identifier3]) => [identifier3, { Scope: state.scope, ResourceReference: name2, RootPath: join11(directory2, "objects", identifier3) }])) }
39035
39307
  } }));
39036
39308
  issueToken();
39037
39309
  notify("hcr", "starting");
@@ -39045,7 +39317,7 @@ async function startLocalServices(root, manifest, options = {}) {
39045
39317
  while (true) {
39046
39318
  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");
39047
39319
  try {
39048
- const response = await fetch(runtimeUrl + "/v1/health", { headers: { authorization: "Bearer " + readFileSync11(tokenPath, "utf8") }, signal: AbortSignal.timeout(500), redirect: "error", credentials: "omit", cache: "no-store" });
39320
+ const response = await fetch(runtimeUrl + "/v1/health", { headers: { authorization: "Bearer " + readFileSync12(tokenPath, "utf8") }, signal: AbortSignal.timeout(500), redirect: "error", credentials: "omit", cache: "no-store" });
39049
39321
  if (response.ok) {
39050
39322
  const status = await response.json();
39051
39323
  if (status.status === "ready" && status.configurationVersion === state.configurationVersion) break;
@@ -39054,8 +39326,8 @@ async function startLocalServices(root, manifest, options = {}) {
39054
39326
  }
39055
39327
  await new Promise((resolveDelay) => setTimeout(resolveDelay, 100));
39056
39328
  }
39057
- if (events) await createHcrEventsProvider({ runtimeUrl, token: () => readFileSync11(tokenPath, "utf8") }).inspect();
39058
- if (jobs) await createHcrJobsProvider({ runtimeUrl, token: () => readFileSync11(tokenPath, "utf8") }).inspect();
39329
+ if (events) await createHcrEventsProvider({ runtimeUrl, token: () => readFileSync12(tokenPath, "utf8") }).inspect();
39330
+ if (jobs) await createHcrJobsProvider({ runtimeUrl, token: () => readFileSync12(tokenPath, "utf8") }).inspect();
39059
39331
  timer = setInterval(() => {
39060
39332
  try {
39061
39333
  issueToken();
@@ -39071,7 +39343,7 @@ async function startLocalServices(root, manifest, options = {}) {
39071
39343
  }
39072
39344
  }, 36e5);
39073
39345
  notify("hcr", "ready");
39074
- const configurationFingerprint = createHash6("sha256").update(JSON.stringify({ mode: "full", capabilities: manifest.capabilities, migrations: migrations.map(({ name: name2, digest: digest4 }) => ({ name: name2, digest: digest4 })), ...jobs ? { jobArtifacts: state.jobs.artifacts } : {} })).digest("hex");
39346
+ const configurationFingerprint = createHash7("sha256").update(JSON.stringify({ mode: "full", capabilities: manifest.capabilities, migrations: migrations.map(({ name: name2, digest: digest4 }) => ({ name: name2, digest: digest4 })), ...jobs ? { jobArtifacts: state.jobs.artifacts } : {} })).digest("hex");
39075
39347
  return { identityScope: { ...state.scope }, runtimeUrl, tokenPath, database, storage, events, jobs, databasePort, migrations: applied, configurationFingerprint, renewConfiguration, stop };
39076
39348
  } catch (error2) {
39077
39349
  await stop();
@@ -39080,15 +39352,15 @@ async function startLocalServices(root, manifest, options = {}) {
39080
39352
  }
39081
39353
 
39082
39354
  // src/local-job-auth.ts
39083
- import { createHash as createHash7 } from "node:crypto";
39084
- import { lstatSync as lstatSync8, readFileSync as readFileSync12 } from "node:fs";
39355
+ import { createHash as createHash8 } from "node:crypto";
39356
+ import { lstatSync as lstatSync9, readFileSync as readFileSync13 } from "node:fs";
39085
39357
  import { isAbsolute as isAbsolute5, resolve as resolve9 } from "node:path";
39086
39358
  function prepareLocalJobAuth(root, filename2) {
39087
39359
  const read = (path, maximum) => {
39088
39360
  assertLocalStatePath(root, path);
39089
- const metadata = lstatSync8(path);
39361
+ const metadata = lstatSync9(path);
39090
39362
  if (!metadata.isFile() || metadata.isSymbolicLink() || metadata.nlink !== 1 || metadata.size > maximum) throw new Error();
39091
- const bytes = readFileSync12(path);
39363
+ const bytes = readFileSync13(path);
39092
39364
  if (bytes.length > maximum) throw new Error();
39093
39365
  return bytes;
39094
39366
  };
@@ -39102,7 +39374,7 @@ function prepareLocalJobAuth(root, filename2) {
39102
39374
  if (trustFile === stateFile) throw new Error();
39103
39375
  const bytes = read(trustFile, 131072), trust = JSON.parse(new TextDecoder("utf8", { fatal: true }).decode(bytes));
39104
39376
  read(stateFile, 2048);
39105
- if (createHash7("sha256").update(bytes).digest("hex") !== input.trustDigest || trust.revision !== input.revision) throw new Error();
39377
+ if (createHash8("sha256").update(bytes).digest("hex") !== input.trustDigest || trust.revision !== input.revision) throw new Error();
39106
39378
  createPersistentApplicationAuthProvider(trust, { expectedScope: input.scope, stateFile });
39107
39379
  return { trustFile, stateFile, scope: structuredClone(input.scope), revision: input.revision, trustDigest: input.trustDigest };
39108
39380
  } catch {
@@ -39111,20 +39383,20 @@ function prepareLocalJobAuth(root, filename2) {
39111
39383
  }
39112
39384
 
39113
39385
  // src/local-job-trust-renewal.ts
39114
- import { createHash as createHash9 } from "node:crypto";
39115
- import { lstatSync as lstatSync10, readFileSync as readFileSync14 } from "node:fs";
39386
+ import { createHash as createHash10 } from "node:crypto";
39387
+ import { lstatSync as lstatSync11, readFileSync as readFileSync15 } from "node:fs";
39116
39388
  import { isAbsolute as isAbsolute7, relative as relative2, resolve as resolve11 } from "node:path";
39117
39389
 
39118
39390
  // src/workload-trust-sync.ts
39119
- import { lstatSync as lstatSync9, readFileSync as readFileSync13 } from "node:fs";
39391
+ import { lstatSync as lstatSync10, readFileSync as readFileSync14 } from "node:fs";
39120
39392
  import { isAbsolute as isAbsolute6, resolve as resolve10 } from "node:path";
39121
- import { createHash as createHash8 } from "node:crypto";
39393
+ import { createHash as createHash9 } from "node:crypto";
39122
39394
  function prepareWorkloadTrustSynchronization(filename2) {
39123
39395
  try {
39124
39396
  if (!isAbsolute6(filename2)) throw new Error();
39125
- const metadata = lstatSync9(filename2);
39397
+ const metadata = lstatSync10(filename2);
39126
39398
  if (!metadata.isFile() || metadata.isSymbolicLink() || metadata.nlink !== 1 || metadata.size > 65536) throw new Error();
39127
- const bytes = readFileSync13(filename2);
39399
+ const bytes = readFileSync14(filename2);
39128
39400
  if (bytes.length > 65536) throw new Error();
39129
39401
  const value = JSON.parse(new TextDecoder("utf8", { fatal: true }).decode(bytes));
39130
39402
  const allowed = ["controlPlaneUrl", "agentId", "expectedScope", "managementIssuer", "managementAudience", "managementPublicKeyPem", "credentialFile", "trustFile", "stateFile", "intervalSeconds"];
@@ -39135,15 +39407,15 @@ function prepareWorkloadTrustSynchronization(filename2) {
39135
39407
  const intervalSeconds = value.intervalSeconds ?? 30;
39136
39408
  if (!Number.isSafeInteger(intervalSeconds) || intervalSeconds < 10 || intervalSeconds > 300) throw new Error();
39137
39409
  const credential = () => {
39138
- const metadata2 = lstatSync9(credentialFile);
39410
+ const metadata2 = lstatSync10(credentialFile);
39139
39411
  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");
39140
- const bytes2 = readFileSync13(credentialFile);
39412
+ const bytes2 = readFileSync14(credentialFile);
39141
39413
  if (bytes2.length > 256) throw new Error("Management credential unavailable");
39142
39414
  return new TextDecoder("utf8", { fatal: true }).decode(bytes2).trim();
39143
39415
  };
39144
39416
  const options = { controlPlaneUrl: value.controlPlaneUrl, agentId: value.agentId, expectedScope: value.expectedScope, managementIssuer: value.managementIssuer, managementAudience: value.managementAudience, managementPublicKeyPem: value.managementPublicKeyPem, credential, trustFile, stateFile };
39145
39417
  const plan = planApplicationAuthSynchronization(options);
39146
- return { options, plan, intervalSeconds, credentialFile, configurationDigest: createHash8("sha256").update(bytes).digest("hex") };
39418
+ return { options, plan, intervalSeconds, credentialFile, configurationDigest: createHash9("sha256").update(bytes).digest("hex") };
39147
39419
  } catch {
39148
39420
  throw new Error("Invalid operator trust-sync configuration");
39149
39421
  }
@@ -39202,15 +39474,15 @@ function prepareLocalJobTrustRenewal(root, filename2, mount) {
39202
39474
  const same = (first, second) => process.platform === "win32" ? first.toLowerCase() === second.toLowerCase() : first === second;
39203
39475
  if (!same(options.trustFile, mount.trustFile) || !same(options.stateFile, mount.stateFile) || ["organizationId", "applicationId", "environmentId"].some((name2) => options.expectedScope[name2] !== mount.scope[name2])) throw new Error();
39204
39476
  assertLocalStatePath(root, configured.credentialFile);
39205
- const metadata = lstatSync10(configured.credentialFile);
39477
+ const metadata = lstatSync11(configured.credentialFile);
39206
39478
  if (!metadata.isFile() || metadata.isSymbolicLink() || metadata.nlink !== 1 || metadata.size > 256 || process.platform !== "win32" && (metadata.uid !== process.getuid?.() || (metadata.mode & 63) !== 0)) throw new Error();
39207
39479
  return { configurationFile, configurationDigest: configured.configurationDigest, credentialFile: configured.credentialFile, intervalSeconds: configured.intervalSeconds, options };
39208
39480
  } catch {
39209
39481
  throw new Error("Invalid reviewed native worker trust renewal; preserve trust and state and review explicitly");
39210
39482
  }
39211
39483
  }
39212
- function createLocalJobTrustRenewal(root, mounts, settings = {}, dependencies = { createHash: createHash9, lstatSync: lstatSync10, readFileSync: readFileSync14, isAbsolute: isAbsolute7, relative: relative2, resolve: resolve11, createPersistentApplicationAuthProvider, synchronizeApplicationAuthTrustWithDigest }) {
39213
- const { createHash: createHash17, lstatSync: lstatSync20, readFileSync: readFileSync29, isAbsolute: isAbsolute17, relative: relative11, resolve: resolve25, createPersistentApplicationAuthProvider: createPersistentApplicationAuthProvider2, synchronizeApplicationAuthTrustWithDigest: synchronizeApplicationAuthTrustWithDigest2 } = dependencies;
39484
+ function createLocalJobTrustRenewal(root, mounts, settings = {}, dependencies = { createHash: createHash10, lstatSync: lstatSync11, readFileSync: readFileSync15, isAbsolute: isAbsolute7, relative: relative2, resolve: resolve11, createPersistentApplicationAuthProvider, synchronizeApplicationAuthTrustWithDigest }) {
39485
+ const { createHash: createHash17, lstatSync: lstatSync21, readFileSync: readFileSync30, isAbsolute: isAbsolute17, relative: relative11, resolve: resolve25, createPersistentApplicationAuthProvider: createPersistentApplicationAuthProvider2, synchronizeApplicationAuthTrustWithDigest: synchronizeApplicationAuthTrustWithDigest2 } = dependencies;
39214
39486
  const key = (filename2) => process.platform === "win32" ? resolve25(filename2).toLowerCase() : resolve25(filename2);
39215
39487
  const groups = [];
39216
39488
  for (const mount of mounts) {
@@ -39230,11 +39502,11 @@ function createLocalJobTrustRenewal(root, mounts, settings = {}, dependencies =
39230
39502
  const read = (filename2, maximum, privateFile2 = false) => {
39231
39503
  for (let current = resolve25(filename2); current !== root; current = resolve25(current, "..")) {
39232
39504
  const part = relative11(root, current);
39233
- if (part === ".." || part.startsWith("../") || part.startsWith("..\\") || isAbsolute17(part) || lstatSync20(current).isSymbolicLink()) throw new Error();
39505
+ if (part === ".." || part.startsWith("../") || part.startsWith("..\\") || isAbsolute17(part) || lstatSync21(current).isSymbolicLink()) throw new Error();
39234
39506
  }
39235
- const metadata = lstatSync20(filename2);
39507
+ const metadata = lstatSync21(filename2);
39236
39508
  if (!metadata.isFile() || metadata.nlink !== 1 || metadata.size > maximum || privateFile2 && process.platform !== "win32" && (metadata.uid !== process.getuid?.() || (metadata.mode & 63) !== 0)) throw new Error();
39237
- const bytes = readFileSync29(filename2);
39509
+ const bytes = readFileSync30(filename2);
39238
39510
  if (bytes.length > maximum) throw new Error();
39239
39511
  return bytes;
39240
39512
  };
@@ -39315,14 +39587,14 @@ function prepareLocalJobWorker(root, directory2, artifacts, manifest, authFile,
39315
39587
  if (trustSyncFile !== void 0 && authFile === void 0) throw new Error("Native worker trust renewal requires explicit reviewed auth mounts");
39316
39588
  const authTrust = authFile === void 0 ? void 0 : prepareLocalJobAuth(root, authFile);
39317
39589
  if (authTrust && trustSyncFile !== void 0) authTrust.renewal = prepareLocalJobTrustRenewal(root, trustSyncFile, authTrust);
39318
- const workerFile = join11(resolve12(root, directory2), "workload.mjs"), metadataFile = join11(resolve12(root, directory2), "artifact.json");
39590
+ const workerFile = join12(resolve12(root, directory2), "workload.mjs"), metadataFile = join12(resolve12(root, directory2), "artifact.json");
39319
39591
  for (const filename2 of [workerFile, metadataFile]) assertLocalStatePath(root, filename2);
39320
- if (!lstatSync11(workerFile).isFile() || lstatSync11(workerFile).size > 16777216 || !lstatSync11(metadataFile).isFile() || lstatSync11(metadataFile).size > 65536) throw new Error("Invalid bounded native worker artifact");
39321
- const metadata = JSON.parse(readFileSync15(metadataFile, "utf8"));
39322
- const bundle = readFileSync15(workerFile);
39323
- const actual = createHash10("sha256").update(bundle).digest("hex");
39592
+ if (!lstatSync12(workerFile).isFile() || lstatSync12(workerFile).size > 16777216 || !lstatSync12(metadataFile).isFile() || lstatSync12(metadataFile).size > 65536) throw new Error("Invalid bounded native worker artifact");
39593
+ const metadata = JSON.parse(readFileSync16(metadataFile, "utf8"));
39594
+ const bundle = readFileSync16(workerFile);
39595
+ const actual = createHash11("sha256").update(bundle).digest("hex");
39324
39596
  const scheduleDiscovery = bundle.subarray(0, 100).toString("utf8").startsWith('var __backifyWorkerProtocols = ["hcr-v1","hcr-schedules-v1"];\n');
39325
- 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");
39597
+ if (!metadata || metadata.schemaVersion !== 1 || metadata.kind !== "worker" || metadata.artifactVersion !== actual || metadata.manifestVersion !== createHash11("sha256").update(JSON.stringify(manifest)).digest("hex")) throw new Error("Native worker kind, bundle or manifest pin does not match the reviewed artifact");
39326
39598
  const artifact = validateLocalJobArtifacts(artifacts).find((item) => item.artifactVersion === actual);
39327
39599
  if (!artifact) throw new Error("Native worker bundle is not an explicitly reviewed job artifact");
39328
39600
  if (metadata.workerProtocols !== void 0 && (!scheduleDiscovery || JSON.stringify(metadata.workerProtocols) !== JSON.stringify(["hcr-v1", "hcr-schedules-v1"]))) throw new Error("Invalid worker protocol admission");
@@ -39332,29 +39604,29 @@ function readLocalJobArtifacts(root, filename2) {
39332
39604
  if (!filename2 || isAbsolute8(filename2)) throw new Error("Job artifact admission requires a repository-relative reviewed JSON file");
39333
39605
  const path = resolve12(root, filename2);
39334
39606
  assertLocalStatePath(root, path);
39335
- if (!lstatSync11(path).isFile() || lstatSync11(path).size > 16384) throw new Error("Reviewed job artifact admission exceeds supported bounds");
39336
- return validateLocalJobArtifacts(JSON.parse(readFileSync15(path, "utf8")));
39607
+ if (!lstatSync12(path).isFile() || lstatSync12(path).size > 16384) throw new Error("Reviewed job artifact admission exceeds supported bounds");
39608
+ return validateLocalJobArtifacts(JSON.parse(readFileSync16(path, "utf8")));
39337
39609
  }
39338
- function createLocalJobExecutor(options, dependencies = { spawn: spawn2, createHash: createHash10, lstatSync: lstatSync11, readFileSync: readFileSync15, isAbsolute: isAbsolute8, relative: relative3, resolve: resolve12, validateWorkloadJobSchedules, createPersistentApplicationAuthProvider }) {
39339
- const { spawn: spawn6, createHash: createHash17, lstatSync: lstatSync20, readFileSync: readFileSync29, isAbsolute: isAbsolute17, relative: relative11, resolve: resolve25, validateWorkloadJobSchedules: validateWorkloadJobSchedules2, createPersistentApplicationAuthProvider: createPersistentApplicationAuthProvider2 } = dependencies;
39610
+ function createLocalJobExecutor(options, dependencies = { spawn: spawn2, createHash: createHash11, lstatSync: lstatSync12, readFileSync: readFileSync16, isAbsolute: isAbsolute8, relative: relative3, resolve: resolve12, validateWorkloadJobSchedules, createPersistentApplicationAuthProvider }) {
39611
+ const { spawn: spawn6, createHash: createHash17, lstatSync: lstatSync21, readFileSync: readFileSync30, isAbsolute: isAbsolute17, relative: relative11, resolve: resolve25, validateWorkloadJobSchedules: validateWorkloadJobSchedules2, createPersistentApplicationAuthProvider: createPersistentApplicationAuthProvider2 } = dependencies;
39340
39612
  const assertReady = () => {
39341
39613
  for (let current = resolve25(options.workerFile); current !== options.root; current = resolve25(current, "..")) {
39342
39614
  const part = relative11(options.root, current);
39343
- if (part === ".." || part.startsWith("../") || part.startsWith("..\\") || isAbsolute17(part) || lstatSync20(current).isSymbolicLink()) throw new Error("Native worker paths or pins changed");
39615
+ if (part === ".." || part.startsWith("../") || part.startsWith("..\\") || isAbsolute17(part) || lstatSync21(current).isSymbolicLink()) throw new Error("Native worker paths or pins changed");
39344
39616
  }
39345
- if (!lstatSync20(options.workerFile).isFile() || lstatSync20(options.workerFile).size > 16777216 || createHash17("sha256").update(readFileSync29(options.workerFile)).digest("hex") !== options.artifact.artifactVersion) throw new Error("Native worker paths or pins changed");
39617
+ if (!lstatSync21(options.workerFile).isFile() || lstatSync21(options.workerFile).size > 16777216 || createHash17("sha256").update(readFileSync30(options.workerFile)).digest("hex") !== options.artifact.artifactVersion) throw new Error("Native worker paths or pins changed");
39346
39618
  if (options.authTrust) {
39347
39619
  try {
39348
39620
  const mount = options.authTrust;
39349
39621
  for (const path of [mount.trustFile, mount.stateFile]) {
39350
39622
  for (let current = resolve25(path); current !== options.root; current = resolve25(current, "..")) {
39351
39623
  const part = relative11(options.root, current);
39352
- if (part === ".." || part.startsWith("../") || part.startsWith("..\\") || isAbsolute17(part) || lstatSync20(current).isSymbolicLink()) throw new Error();
39624
+ if (part === ".." || part.startsWith("../") || part.startsWith("..\\") || isAbsolute17(part) || lstatSync21(current).isSymbolicLink()) throw new Error();
39353
39625
  }
39354
- const metadata = lstatSync20(path);
39626
+ const metadata = lstatSync21(path);
39355
39627
  if (!metadata.isFile() || metadata.nlink !== 1 || metadata.size > (path === mount.trustFile ? 131072 : 2048)) throw new Error();
39356
39628
  }
39357
- const bytes = readFileSync29(mount.trustFile);
39629
+ const bytes = readFileSync30(mount.trustFile);
39358
39630
  if (bytes.length > 131072 || createHash17("sha256").update(bytes).digest("hex") !== mount.trustDigest) throw new Error();
39359
39631
  const trust = JSON.parse(new TextDecoder("utf8", { fatal: true }).decode(bytes));
39360
39632
  if (trust.revision !== mount.revision) throw new Error();
@@ -39468,9 +39740,9 @@ function createLocalJobExecutor(options, dependencies = { spawn: spawn2, createH
39468
39740
  }
39469
39741
 
39470
39742
  // src/local-native-jobs.ts
39471
- import { createHash as createHash11 } from "node:crypto";
39743
+ import { createHash as createHash12 } from "node:crypto";
39472
39744
  function createLocalNativeJobs(local, native, executor, artifact, scope, onFailure = () => {
39473
- }, hash2 = createHash11, catalog = { workloadJobSchedules, validateWorkloadJobSchedules, HcrJobsRequestError }, historical = []) {
39745
+ }, hash2 = createHash12, catalog = { workloadJobSchedules, validateWorkloadJobSchedules, HcrJobsRequestError }, historical = []) {
39474
39746
  const workers = [{ artifact, executor }, ...historical];
39475
39747
  if (historical.length > 15 || new Set(workers.map((worker) => worker.artifact.artifactVersion)).size !== workers.length) throw new Error("Historical workers require bounded unique artifact pins");
39476
39748
  const lanes = workers.flatMap((worker) => worker.artifact.jobs.map((policy) => ({ ...worker, policy })));
@@ -39609,7 +39881,7 @@ import { jobs } from "@backifydev/sdk";
39609
39881
  import { createHcrDatabaseProvider, createHcrStorageProvider, createHcrEventsProvider, createHcrJobsProvider, HcrJobsRequestError, workloadJobSchedules, validateWorkloadJobSchedules, createPersistentApplicationAuthProvider } from "@backifydev/sdk/server";
39610
39882
  import { createServer } from "node:http";
39611
39883
  import { existsSync, lstatSync, readFileSync, writeFileSync, renameSync } from "node:fs";
39612
- import { timingSafeEqual, createHash } from "node:crypto";
39884
+ import { timingSafeEqual, createHash, randomBytes, randomUUID } from "node:crypto";
39613
39885
  import { spawn } from "node:child_process";
39614
39886
  import { isAbsolute, relative, resolve } from "node:path";
39615
39887
  const statePath = process.env.BACKIFY_LOCAL_STATE;
@@ -39673,11 +39945,26 @@ async function inspectEndpoint(url) {
39673
39945
  return { url, status: "responding", httpStatus: response.status };
39674
39946
  } catch { return { url, status: "unreachable" }; }
39675
39947
  }
39948
+ const createLocalEmailAuth = __BACKIFY_LOCAL_EMAIL_AUTH__;
39949
+ const emailOrigin = process.env.BACKIFY_LOCAL_FRONTEND_URL || process.env.BACKIFY_LOCAL_BACKEND_URL;
39950
+ const localEmailAuth = runtime.localIdentity && emailOrigin ? createLocalEmailAuth({ identity: runtime.localIdentity, origin: emailOrigin }, { createHash, randomBytes, randomUUID }) : undefined;
39676
39951
  const server = createServer(async (request, response) => {
39677
39952
  response.setHeader("cache-control", "no-store"); response.setHeader("x-content-type-options", "nosniff");
39678
39953
  const send = (status, value) => { response.writeHead(status, { "content-type": "application/json" }); response.end(JSON.stringify(value)); };
39679
39954
  if (!/^((127\.0\.0\.1)|(localhost)):\d+$/.test(request.headers.host ?? "")) return send(403, { error: "Invalid host" });
39680
39955
  if (request.method === "GET" && request.url === "/") { response.writeHead(200, { "content-type": "text/html; charset=utf-8", "content-security-policy": "default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; connect-src 'self'; frame-ancestors 'none'" }); return response.end(dashboard); }
39956
+ if (request.url?.startsWith("/.backify/auth/")) {
39957
+ if (!localEmailAuth) return send(503, { error: "local_identity_unavailable" });
39958
+ try {
39959
+ let body = "";
39960
+ for await (const chunk of request) { body += chunk.toString(); if (Buffer.byteLength(body) > 8192) return send(413, { error: "request_too_large" }); }
39961
+ const headers = new Headers();
39962
+ for (const [name, value] of Object.entries(request.headers)) if (typeof value === "string" && name !== "host") headers.set(name, value);
39963
+ const result = await localEmailAuth.handle(new Request(emailOrigin + request.url, { method: request.method, headers, ...(body ? { body } : {}) }));
39964
+ response.writeHead(result.status, Object.fromEntries(result.headers));
39965
+ return response.end(Buffer.from(await result.arrayBuffer()));
39966
+ } catch { return send(400, { error: "invalid_local_auth_request" }); }
39967
+ }
39681
39968
  const provided = request.headers.authorization?.replace(/^Bearer /, "") ?? "";
39682
39969
  const bytes = /^[a-f0-9]{64}$/.test(provided) ? Buffer.from(provided, "hex") : Buffer.alloc(0);
39683
39970
  if (bytes.length !== token.length || !timingSafeEqual(bytes, token)) return send(401, { error: "Local session required" });
@@ -39685,6 +39972,7 @@ const server = createServer(async (request, response) => {
39685
39972
  if (request.method === "GET" && request.url === "/v1/status") { const inspected = runtime.inspect(); return send(200, { status: "healthy", ...inspected, events: await inspectEvents(), ...(nativeJobs ? { jobs: (await nativeJobs.inspect()).runs } : {}), tables: process.env.BACKIFY_LOCAL_DATABASE === "postgres" ? [] : inspected.tables, buckets: process.env.BACKIFY_LOCAL_STORAGE === "filesystem" ? [] : inspected.buckets, services: { mode: process.env.BACKIFY_LOCAL_HCR_URL ? "full" : "lightweight", hcrUrl: process.env.BACKIFY_LOCAL_HCR_URL, database: process.env.BACKIFY_LOCAL_DATABASE ?? "document-emulator", storage: process.env.BACKIFY_LOCAL_STORAGE ?? "snapshot-emulator", events: process.env.BACKIFY_LOCAL_EVENTS ?? "snapshot-emulator", jobs: process.env.BACKIFY_LOCAL_JOBS ?? "snapshot-emulator", frontend: await inspectEndpoint(process.env.BACKIFY_LOCAL_FRONTEND_URL), backend: await inspectEndpoint(process.env.BACKIFY_LOCAL_BACKEND_URL), inspection: process.env.BACKIFY_LOCAL_HCR_URL ? "scoped read-only provider inspection available in Data panel; status contains metadata only" : "local snapshot" } }); }
39686
39973
  if (request.method === "GET" && request.url === "/v1/logs") return send(200, runtime.inspect().logs);
39687
39974
  if (request.method === "GET" && request.url === "/v1/events") return send(200, await inspectEvents());
39975
+ if (request.method === "GET" && request.url === "/v1/identity/inbox") return localEmailAuth ? send(200, { messages: localEmailAuth.inbox() }) : send(503, { error: "local_identity_unavailable" });
39688
39976
  if (request.method === "GET" && request.url === "/v1/identity/users") return runtime.localIdentity ? send(200, { kind: "local-development", users: runtime.localIdentity.profiles() }) : send(503, { error: "local_identity_unavailable" });
39689
39977
  if (request.method === "GET" && request.url === "/v1/database/tables") return send(200, await inspector.tables());
39690
39978
  if (request.method === "GET" && request.url === "/v1/storage/buckets") return send(200, inspector.buckets());
@@ -39723,14 +40011,14 @@ process.on("SIGTERM", stop); process.on("SIGINT", stop); process.once("disconnec
39723
40011
  catch { console.error("Native worker trust renewal delivery refused; pin guards remain enforced."); }
39724
40012
  }
39725
40013
  });
39726
- `.replace("__BACKIFY_ENTRY__", JSON.stringify(entrypoint)).replace("__BACKIFY_STATE_REPLACEMENT__", replaceLocalFile.toString()).replace("__BACKIFY_INSPECTOR_FACTORY__", createLocalDataInspector.toString()).replace("__BACKIFY_DASHBOARD__", JSON.stringify(dashboardHtml)).replace("__BACKIFY_NATIVE_EVENTS__", createLocalNativeEvents.toString()).replace("__BACKIFY_NATIVE_JOB_EXECUTOR__", createLocalJobExecutor.toString()).replace("__BACKIFY_NATIVE_JOBS__", createLocalNativeJobs.toString()).replace("__BACKIFY_TRUST_RENEWAL_DELIVERY__", applyLocalJobTrustRenewal.toString());
40014
+ `.replace("__BACKIFY_LOCAL_EMAIL_AUTH__", createLocalEmailAuth.toString()).replace("__BACKIFY_ENTRY__", JSON.stringify(entrypoint)).replace("__BACKIFY_STATE_REPLACEMENT__", replaceLocalFile.toString()).replace("__BACKIFY_INSPECTOR_FACTORY__", createLocalDataInspector.toString()).replace("__BACKIFY_DASHBOARD__", JSON.stringify(dashboardHtml)).replace("__BACKIFY_NATIVE_EVENTS__", createLocalNativeEvents.toString()).replace("__BACKIFY_NATIVE_JOB_EXECUTOR__", createLocalJobExecutor.toString()).replace("__BACKIFY_NATIVE_JOBS__", createLocalNativeJobs.toString()).replace("__BACKIFY_TRUST_RENEWAL_DELIVERY__", applyLocalJobTrustRenewal.toString());
39727
40015
  }
39728
40016
 
39729
40017
  // src/local-frontend.ts
39730
40018
  import { spawn as spawn3 } from "node:child_process";
39731
- import { readFileSync as readFileSync17, realpathSync as realpathSync3, existsSync as existsSync11, statSync } from "node:fs";
40019
+ import { readFileSync as readFileSync18, realpathSync as realpathSync3, existsSync as existsSync12, statSync } from "node:fs";
39732
40020
  import { createRequire as createRequire3 } from "node:module";
39733
- import { dirname as dirname10, isAbsolute as isAbsolute10, join as join13, relative as relative5, resolve as resolve14 } from "node:path";
40021
+ import { dirname as dirname10, isAbsolute as isAbsolute10, join as join14, relative as relative5, resolve as resolve14 } from "node:path";
39734
40022
  import { pathToFileURL } from "node:url";
39735
40023
 
39736
40024
  // src/local-frontend-guard.ts
@@ -39748,6 +40036,7 @@ const guard = {
39748
40036
  config.root = settings.directory;
39749
40037
  config.server = {
39750
40038
  ...config.server, host: "127.0.0.1", port: settings.port, strictPort: true,
40039
+ ...(settings.authUrl ? { proxy: { ...config.server?.proxy, "/.backify/auth": { target: settings.authUrl, changeOrigin: true } } } : {}),
39751
40040
  fs: { ...config.server?.fs, strict: true, deny: [...new Set([...(config.server?.fs?.deny ?? []), ...settings.denied])] }
39752
40041
  };
39753
40042
  }
@@ -39797,9 +40086,9 @@ await server.listen();
39797
40086
  `;
39798
40087
 
39799
40088
  // src/local-static-frontend.ts
39800
- import { createServer as createServer4 } from "node:http";
39801
- import { lstatSync as lstatSync12, readFileSync as readFileSync16, realpathSync as realpathSync2, watch } from "node:fs";
39802
- import { extname as extname2, isAbsolute as isAbsolute9, join as join12, relative as relative4, resolve as resolve13, sep as sep4 } from "node:path";
40089
+ import { createServer as createServer4, request as proxyRequest } from "node:http";
40090
+ import { lstatSync as lstatSync13, readFileSync as readFileSync17, realpathSync as realpathSync2, watch } from "node:fs";
40091
+ import { extname as extname2, isAbsolute as isAbsolute9, join as join13, relative as relative4, resolve as resolve13, sep as sep4 } from "node:path";
39803
40092
  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" };
39804
40093
  var publicParts = (parts) => parts.every((part) => part.length > 0 && !part.startsWith(".") && !part.includes(":") && !part.includes("\\") && !part.includes("\0") && !["node_modules", "__backify"].includes(part.toLowerCase()));
39805
40094
  function publicFile(directory2, pathname) {
@@ -39809,12 +40098,12 @@ function publicFile(directory2, pathname) {
39809
40098
  const filename2 = resolve13(directory2, ...parts), part = relative4(directory2, filename2);
39810
40099
  if (part === ".." || part.startsWith(".." + sep4) || isAbsolute9(part) || !contentTypes[extname2(filename2).toLowerCase()]) throw new Error("refused");
39811
40100
  let current = directory2;
39812
- if (lstatSync12(current).isSymbolicLink() || realpathSync2(current) !== directory2) throw new Error("refused");
40101
+ if (lstatSync13(current).isSymbolicLink() || realpathSync2(current) !== directory2) throw new Error("refused");
39813
40102
  for (const segment of parts) {
39814
- current = join12(current, segment);
39815
- if (lstatSync12(current).isSymbolicLink()) throw new Error("refused");
40103
+ current = join13(current, segment);
40104
+ if (lstatSync13(current).isSymbolicLink()) throw new Error("refused");
39816
40105
  }
39817
- const stat = lstatSync12(filename2);
40106
+ const stat = lstatSync13(filename2);
39818
40107
  if (!stat.isFile() || stat.nlink !== 1 || stat.size > 5242880) throw new Error("refused");
39819
40108
  return filename2;
39820
40109
  }
@@ -39822,7 +40111,7 @@ function prepareLocalStaticFrontend(directory2) {
39822
40111
  publicFile(directory2, "/index.html");
39823
40112
  return { adapter: "static", directory: directory2 };
39824
40113
  }
39825
- async function startLocalStaticFrontend(directory2, port, backendUrl) {
40114
+ async function startLocalStaticFrontend(directory2, port, backendUrl, authUrl) {
39826
40115
  const assignedPort = await allocateLocalPort(port), url2 = "http://127.0.0.1:" + assignedPort;
39827
40116
  let revision = 0;
39828
40117
  const reload = '(()=>{let revision=new URL(document.currentScript.src).searchParams.get("revision")??undefined;setInterval(async()=>{try{const response=await fetch("/__backify/revision",{cache:"no-store"});if(!response.ok)return;const current=await response.text();if(revision!==undefined&&revision!==current)location.reload();revision=current;}catch{}},500);})();';
@@ -39835,6 +40124,18 @@ async function startLocalStaticFrontend(directory2, port, backendUrl) {
39835
40124
  response.end(request.method === "HEAD" ? void 0 : body);
39836
40125
  };
39837
40126
  if (request.headers.host !== "127.0.0.1:" + assignedPort || request.headers.origin && request.headers.origin !== url2) return send(403, "text/plain", "Development request refused");
40127
+ if (authUrl && request.url?.startsWith("/.backify/auth/")) {
40128
+ const upstream = proxyRequest(new URL(request.url, authUrl), { method: request.method, headers: { ...request.headers, host: new URL(authUrl).host } }, (incoming) => {
40129
+ response.writeHead(incoming.statusCode ?? 502, incoming.headers);
40130
+ incoming.pipe(response);
40131
+ });
40132
+ upstream.on("error", () => {
40133
+ if (!response.headersSent) send(502, "text/plain", "Local authentication unavailable");
40134
+ else response.destroy();
40135
+ });
40136
+ request.pipe(upstream);
40137
+ return;
40138
+ }
39838
40139
  if (!["GET", "HEAD"].includes(request.method ?? "")) return send(405, "text/plain", "Method not allowed");
39839
40140
  try {
39840
40141
  const pathname = decodeURIComponent((request.url ?? "/").split("?")[0]);
@@ -39842,7 +40143,7 @@ async function startLocalStaticFrontend(directory2, port, backendUrl) {
39842
40143
  if (pathname === "/__backify/revision") return send(200, "text/plain", String(revision));
39843
40144
  if (pathname === "/__backify/config.json") return send(200, "application/json", JSON.stringify({ backendUrl: backendUrl ?? null }));
39844
40145
  const filename2 = publicFile(directory2, pathname);
39845
- const content = readFileSync16(filename2);
40146
+ const content = readFileSync17(filename2);
39846
40147
  if (content.length > 5242880) throw new Error("refused");
39847
40148
  const extension = extname2(filename2).toLowerCase();
39848
40149
  const body = extension === ".html" ? content.toString("utf8") + '\n<script src="/__backify/reload.js?revision=' + revision + '"></script>\n' : content;
@@ -39892,15 +40193,15 @@ function prepareLocalFrontend(root, options, privateFiles = []) {
39892
40193
  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");
39893
40194
  return prepareLocalStaticFrontend(directory2);
39894
40195
  }
39895
- if (!existsSync11(join13(directory2, "package.json"))) throw new Error("Frontend requires an existing package.json and installed Vite");
39896
- const require3 = createRequire3(join13(directory2, "package.json"));
40196
+ if (!existsSync12(join14(directory2, "package.json"))) throw new Error("Frontend requires an existing package.json and installed Vite");
40197
+ const require3 = createRequire3(join14(directory2, "package.json"));
39897
40198
  let packagePath;
39898
40199
  try {
39899
40200
  packagePath = require3.resolve("vite/package.json");
39900
40201
  } catch {
39901
40202
  throw new Error("Frontend requires locally installed Vite; Backify does not install dependencies automatically");
39902
40203
  }
39903
- const metadata = JSON.parse(readFileSync17(packagePath, "utf8"));
40204
+ const metadata = JSON.parse(readFileSync18(packagePath, "utf8"));
39904
40205
  if (metadata.name !== "vite" || typeof metadata.bin?.vite !== "string") throw new Error("Installed Vite has no supported CLI entrypoint");
39905
40206
  const executable = realpathSync3(resolve14(dirname10(packagePath), metadata.bin.vite));
39906
40207
  const executablePart = relative5(realpathSync3(dirname10(packagePath)), executable);
@@ -39926,15 +40227,15 @@ async function stopFrontend(child) {
39926
40227
  else child.kill("SIGTERM");
39927
40228
  });
39928
40229
  }
39929
- async function startLocalFrontend(prepared, port, backendUrl, onDiagnostic) {
39930
- if (prepared.adapter === "static") return startLocalStaticFrontend(prepared.directory, port, backendUrl);
40230
+ async function startLocalFrontend(prepared, port, backendUrl, onDiagnostic, authUrl) {
40231
+ if (prepared.adapter === "static") return startLocalStaticFrontend(prepared.directory, port, backendUrl, authUrl);
39931
40232
  const assignedPort = await allocateLocalPort(port);
39932
40233
  const url2 = "http://127.0.0.1:" + assignedPort;
39933
40234
  const environment = { ...process.env };
39934
40235
  for (const name2 of Object.keys(environment)) if (name2.startsWith("BACKIFY_")) delete environment[name2];
39935
40236
  if (backendUrl) environment.VITE_BACKIFY_BACKEND_URL = backendUrl;
39936
40237
  const denied = [".env", ".env.*", "*.{crt,pem}", "**/.git/**", "**/.backify", "**/.backify/**", "**/.local-secrets", "**/.local-secrets/**", ...prepared.privateFiles.map((filename2) => filename2.replaceAll("\\", "/"))];
39937
- const settings = { moduleUrl: pathToFileURL(prepared.modulePath).href, directory: prepared.directory, port: assignedPort, denied, privateFiles: prepared.privateFiles.map((filename2) => filename2.replaceAll("\\", "/")) };
40238
+ const settings = { authUrl, moduleUrl: pathToFileURL(prepared.modulePath).href, directory: prepared.directory, port: assignedPort, denied, privateFiles: prepared.privateFiles.map((filename2) => filename2.replaceAll("\\", "/")) };
39938
40239
  const launcher = "const settings=" + JSON.stringify(settings) + ";\n" + protectedFrontendSource;
39939
40240
  const child = spawn3(process.execPath, ["--input-type=module", "--eval", launcher], { cwd: prepared.directory, windowsHide: true, stdio: ["ignore", onDiagnostic ? "pipe" : 2, onDiagnostic ? "pipe" : 2, "ipc"], env: environment });
39940
40241
  if (onDiagnostic) {
@@ -39968,107 +40269,9 @@ async function startLocalFrontend(prepared, port, backendUrl, onDiagnostic) {
39968
40269
  }
39969
40270
 
39970
40271
  // src/local-identity.ts
39971
- import { readFileSync as readFileSync18, statSync as statSync2 } from "node:fs";
40272
+ import { readFileSync as readFileSync19, statSync as statSync2 } from "node:fs";
39972
40273
  import { resolve as resolve15 } from "node:path";
39973
-
39974
- // ../sdk/dist/local-identity.js
39975
- import { createHash as createHash12, randomBytes as randomBytes4 } from "node:crypto";
39976
- function createLocalIdentityProvider(options) {
39977
- const serverOnly = () => {
39978
- if (typeof window !== "undefined")
39979
- throw new Error("Local development identities are server-only");
39980
- };
39981
- serverOnly();
39982
- if (typeof process !== "undefined" && process.env.NODE_ENV === "production")
39983
- throw new Error("Local Backify identities must not run in production");
39984
- const uuid5 = (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";
39985
- const text3 = (value, maximum) => typeof value === "string" && value.length > 0 && value.length <= maximum && !/[\x00-\x1f\x7f]/.test(value);
39986
- if (!options.scope || Object.keys(options.scope).length !== 3 || !uuid5(options.scope.organizationId) || !uuid5(options.scope.applicationId) || !uuid5(options.scope.environmentId) || !text3(options.organizationName, 200) || !Array.isArray(options.users) || options.users.length < 1 || options.users.length > 32 || !Array.isArray(options.requestOrigins) || options.requestOrigins.length < 1 || options.requestOrigins.length > 8)
39987
- throw new Error("Invalid local identity configuration");
39988
- const scope = { ...options.scope }, organizationName = options.organizationName;
39989
- const users = /* @__PURE__ */ new Map();
39990
- for (const user of options.users) {
39991
- if (!user || Object.keys(user).some((name2) => !["id", "displayName", "email", "roles"].includes(name2)) || !uuid5(user.id) || users.has(user.id) || !text3(user.displayName, 200) || user.email !== void 0 && !text3(user.email, 320))
39992
- throw new Error("Invalid local identity user");
39993
- if (user.roles !== void 0 && (!Array.isArray(user.roles) || user.roles.length > 32 || user.roles.some((role) => !role || Object.keys(role).some((name2) => !["name", "permissions"].includes(name2)) || !text3(role.name, 100) || !Array.isArray(role.permissions) || role.permissions.length > 128 || role.permissions.some((permission) => !text3(permission, 100)) || new Set(role.permissions).size !== role.permissions.length) || new Set(user.roles.map((role) => role.name)).size !== user.roles.length))
39994
- throw new Error("Invalid local identity roles");
39995
- users.set(user.id, structuredClone(user));
39996
- }
39997
- const origins = /* @__PURE__ */ new Set();
39998
- for (const value of options.requestOrigins) {
39999
- let origin;
40000
- try {
40001
- origin = new URL(value);
40002
- } catch {
40003
- throw new Error("Invalid local identity origin");
40004
- }
40005
- if (!["http:", "https:"].includes(origin.protocol) || !["localhost", "127.0.0.1", "[::1]"].includes(origin.hostname) || origin.origin !== value || origin.username || origin.password || origins.has(value))
40006
- throw new Error("Local identities require exact loopback origins");
40007
- origins.add(value);
40008
- }
40009
- const clock = options.now ?? (() => Math.floor(Date.now() / 1e3));
40010
- const now = () => {
40011
- serverOnly();
40012
- const value = clock();
40013
- if (!Number.isSafeInteger(value) || value < 0 || value > 253402300499)
40014
- throw new ApplicationAuthenticationError("application_identity_unavailable");
40015
- return value;
40016
- };
40017
- const sessions = /* @__PURE__ */ new Map();
40018
- const digest4 = (token) => createHash12("sha256").update(token).digest("hex");
40019
- const tokenPattern = /^backify-local-user_[a-zA-Z0-9_-]{43}$/;
40020
- const requestAuth = {
40021
- forRequest(request) {
40022
- serverOnly();
40023
- const authorization = request.headers.get("authorization"), origin = new URL(request.url).origin;
40024
- const identity = () => {
40025
- const time3 = now();
40026
- if (!origins.has(origin))
40027
- throw new ApplicationAuthenticationError("application_identity_invalid");
40028
- if (authorization === null)
40029
- return null;
40030
- const match = /^Bearer (backify-local-user_[a-zA-Z0-9_-]{43})$/i.exec(authorization);
40031
- const session = match && tokenPattern.test(match[1]) ? sessions.get(digest4(match[1])) : void 0;
40032
- if (!session || session.issued > time3 || session.expires <= time3)
40033
- throw new ApplicationAuthenticationError("application_identity_invalid");
40034
- const user = users.get(session.userId);
40035
- return { ...structuredClone(user), roles: structuredClone(user.roles ?? []), claims: { ...scope, localDevelopment: true } };
40036
- };
40037
- return { currentUser: async () => identity(), currentOrganization: async () => identity() ? { id: scope.organizationId, name: organizationName } : null };
40038
- }
40039
- };
40040
- return {
40041
- requestAuth,
40042
- profiles() {
40043
- serverOnly();
40044
- return [...users.values()].map((user) => structuredClone(user));
40045
- },
40046
- issue(userId, lifetimeSeconds = 300) {
40047
- const time3 = now();
40048
- if (!users.has(userId) || !Number.isInteger(lifetimeSeconds) || lifetimeSeconds < 1 || lifetimeSeconds > 300)
40049
- throw new Error("Invalid local identity issuance");
40050
- for (const [hash2, session] of sessions)
40051
- if (session.expires <= time3)
40052
- sessions.delete(hash2);
40053
- if (sessions.size >= 128)
40054
- throw new ApplicationAuthenticationError("application_identity_unavailable");
40055
- const accessToken = "backify-local-user_" + randomBytes4(32).toString("base64url"), expires = time3 + lifetimeSeconds;
40056
- sessions.set(digest4(accessToken), { userId, issued: time3, expires });
40057
- return { accessToken, tokenType: "Bearer", expiresAt: new Date(expires * 1e3).toISOString() };
40058
- },
40059
- revoke(accessToken) {
40060
- serverOnly();
40061
- return typeof accessToken === "string" && tokenPattern.test(accessToken) && sessions.delete(digest4(accessToken));
40062
- },
40063
- clear() {
40064
- serverOnly();
40065
- sessions.clear();
40066
- }
40067
- };
40068
- }
40069
-
40070
- // src/local-identity.ts
40071
- import { randomUUID as randomUUID8 } from "node:crypto";
40274
+ import { randomUUID as randomUUID9 } from "node:crypto";
40072
40275
  function prepareLocalIdentity(root, filename2) {
40073
40276
  if (filename2 === void 0) return void 0;
40074
40277
  const path = resolve15(root, filename2);
@@ -40076,19 +40279,19 @@ function prepareLocalIdentity(root, filename2) {
40076
40279
  if (!statSync2(path).isFile() || statSync2(path).size > 16384) throw new Error("Local identity profiles require a file at most 16 KiB");
40077
40280
  let input;
40078
40281
  try {
40079
- input = JSON.parse(readFileSync18(path, "utf8"));
40282
+ input = JSON.parse(readFileSync19(path, "utf8"));
40080
40283
  } catch {
40081
40284
  throw new Error("Invalid local identity profile JSON");
40082
40285
  }
40083
40286
  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");
40084
40287
  const value = input;
40085
40288
  if (value.version !== 1) throw new Error("Invalid local identity profile version");
40086
- const identity = createLocalIdentityProvider({ scope: { organizationId: randomUUID8(), applicationId: randomUUID8(), environmentId: randomUUID8() }, organizationName: value.organizationName, users: value.users, requestOrigins: ["http://127.0.0.1:3000"] });
40289
+ const identity = createLocalIdentityProvider({ scope: { organizationId: randomUUID9(), applicationId: randomUUID9(), environmentId: randomUUID9() }, organizationName: value.organizationName, users: value.users, requestOrigins: ["http://127.0.0.1:3000"] });
40087
40290
  return { organizationName: value.organizationName, users: identity.profiles() };
40088
40291
  }
40089
40292
  function localIdentityCommand(args2) {
40090
40293
  const kind = args2[0];
40091
- if (!["users", "issue", "clear"].includes(kind)) throw new Error("Use backify identity users|issue|clear --local [--json]");
40294
+ if (!["users", "inbox", "issue", "clear"].includes(kind)) throw new Error("Use backify identity users|inbox|issue|clear --local [--json]");
40092
40295
  const flags = /* @__PURE__ */ new Set();
40093
40296
  let userId;
40094
40297
  for (let index = 1; index < args2.length; index++) {
@@ -40109,7 +40312,7 @@ function localIdentityCommand(args2) {
40109
40312
  }
40110
40313
 
40111
40314
  // src/local-job-history.ts
40112
- import { lstatSync as lstatSync13, readFileSync as readFileSync19 } from "node:fs";
40315
+ import { lstatSync as lstatSync14, readFileSync as readFileSync20 } from "node:fs";
40113
40316
  import { isAbsolute as isAbsolute11, resolve as resolve16 } from "node:path";
40114
40317
  function prepareLocalJobHistory(root, filename2, artifacts, manifest, current) {
40115
40318
  if (filename2 === void 0) return [];
@@ -40117,9 +40320,9 @@ function prepareLocalJobHistory(root, filename2, artifacts, manifest, current) {
40117
40320
  if (typeof filename3 !== "string" || !filename3 || isAbsolute11(filename3)) throw new Error();
40118
40321
  const path = resolve16(root, filename3);
40119
40322
  assertLocalStatePath(root, path);
40120
- const metadata = lstatSync13(path);
40323
+ const metadata = lstatSync14(path);
40121
40324
  if (!metadata.isFile() || metadata.isSymbolicLink() || metadata.nlink !== 1 || metadata.size > maximum) throw new Error();
40122
- const bytes = readFileSync19(path);
40325
+ const bytes = readFileSync20(path);
40123
40326
  if (bytes.length > maximum) throw new Error();
40124
40327
  return new TextDecoder("utf8", { fatal: true }).decode(bytes);
40125
40328
  };
@@ -40165,14 +40368,14 @@ function prepareLocalJobHistory(root, filename2, artifacts, manifest, current) {
40165
40368
  }
40166
40369
 
40167
40370
  // src/local-secrets.ts
40168
- import { createCipheriv, createDecipheriv, randomBytes as randomBytes5, randomUUID as randomUUID9 } from "node:crypto";
40169
- import { closeSync as closeSync3, existsSync as existsSync12, fsyncSync as fsyncSync3, lstatSync as lstatSync14, mkdirSync as mkdirSync5, openSync as openSync3, readFileSync as readFileSync20, realpathSync as realpathSync4, writeFileSync as writeFileSync10 } from "node:fs";
40170
- import { dirname as dirname11, isAbsolute as isAbsolute12, join as join14, relative as relative6, resolve as resolve17 } from "node:path";
40371
+ import { createCipheriv, createDecipheriv, randomBytes as randomBytes5, randomUUID as randomUUID10 } from "node:crypto";
40372
+ import { closeSync as closeSync3, existsSync as existsSync13, fsyncSync as fsyncSync3, lstatSync as lstatSync15, mkdirSync as mkdirSync5, openSync as openSync3, readFileSync as readFileSync21, realpathSync as realpathSync4, writeFileSync as writeFileSync11 } from "node:fs";
40373
+ import { dirname as dirname11, isAbsolute as isAbsolute12, join as join15, relative as relative6, resolve as resolve17 } from "node:path";
40171
40374
  var maximumBytes2 = 1048576;
40172
40375
  var secretName = /^[A-Z][A-Z0-9_]{0,127}$/;
40173
40376
  var failure = () => new Error("Local secret vault unavailable or invalid; review the vault and external key privately");
40174
40377
  function vaultPath(root) {
40175
- return join14(realpathSync4(root), ".backify", "dev", "secrets.enc.json");
40378
+ return join15(realpathSync4(root), ".backify", "dev", "secrets.enc.json");
40176
40379
  }
40177
40380
  function inside(root, filename2) {
40178
40381
  const part = relative6(root, filename2);
@@ -40180,12 +40383,12 @@ function inside(root, filename2) {
40180
40383
  }
40181
40384
  function privateFile(filename2, limit) {
40182
40385
  for (let current = resolve17(filename2); ; current = dirname11(current)) {
40183
- if (lstatSync14(current).isSymbolicLink()) throw failure();
40386
+ if (lstatSync15(current).isSymbolicLink()) throw failure();
40184
40387
  if (dirname11(current) === current) break;
40185
40388
  }
40186
- const stat = lstatSync14(filename2);
40389
+ const stat = lstatSync15(filename2);
40187
40390
  if (!stat.isFile() || stat.size > limit || stat.nlink !== 1 || process.platform !== "win32" && (stat.mode & 63) !== 0) throw failure();
40188
- return readFileSync20(filename2);
40391
+ return readFileSync21(filename2);
40189
40392
  }
40190
40393
  function externalKey(root, filename2) {
40191
40394
  const keyFile = resolve17(filename2);
@@ -40217,22 +40420,22 @@ function encrypt(root, application, key, secrets) {
40217
40420
  function writePrivate2(filename2, value) {
40218
40421
  const descriptor2 = openSync3(filename2, "wx", 384);
40219
40422
  try {
40220
- writeFileSync10(descriptor2, value);
40423
+ writeFileSync11(descriptor2, value);
40221
40424
  fsyncSync3(descriptor2);
40222
40425
  } finally {
40223
40426
  closeSync3(descriptor2);
40224
40427
  }
40225
40428
  }
40226
40429
  function ensureIgnored(root) {
40227
- const filename2 = join14(root, ".gitignore");
40430
+ const filename2 = join15(root, ".gitignore");
40228
40431
  assertLocalStatePath(root, filename2);
40229
- const current = existsSync12(filename2) ? readFileSync20(filename2, "utf8") : "";
40230
- if (!current.split(/\r?\n/).some((line) => line.trim() === ".backify/")) writeFileSync10(filename2, current + (current && !current.endsWith("\n") ? "\n" : "") + ".backify/\n");
40432
+ const current = existsSync13(filename2) ? readFileSync21(filename2, "utf8") : "";
40433
+ if (!current.split(/\r?\n/).some((line) => line.trim() === ".backify/")) writeFileSync11(filename2, current + (current && !current.endsWith("\n") ? "\n" : "") + ".backify/\n");
40231
40434
  }
40232
40435
  function readLocalSecrets(root, application, keyFile) {
40233
40436
  const filename2 = vaultPath(root);
40234
40437
  assertLocalStatePath(root, filename2);
40235
- if (!existsSync12(filename2) && keyFile === void 0) return {};
40438
+ if (!existsSync13(filename2) && keyFile === void 0) return {};
40236
40439
  if (!keyFile) throw new Error("Encrypted local secrets require --local-secrets-key <external-key-file>");
40237
40440
  let key, plaintext;
40238
40441
  try {
@@ -40262,10 +40465,10 @@ function readLocalSecrets(root, application, keyFile) {
40262
40465
  function initializeLocalSecrets(root, application, keyFile) {
40263
40466
  const filename2 = vaultPath(root), external = resolve17(keyFile);
40264
40467
  assertLocalStatePath(root, filename2);
40265
- if (existsSync12(filename2) || existsSync12(external)) throw new Error("Local secret initialization never overwrites an existing vault or key");
40468
+ if (existsSync13(filename2) || existsSync13(external)) throw new Error("Local secret initialization never overwrites an existing vault or key");
40266
40469
  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");
40267
40470
  for (let current = dirname11(external); ; current = dirname11(current)) {
40268
- const stat = lstatSync14(current);
40471
+ const stat = lstatSync15(current);
40269
40472
  if (stat.isSymbolicLink()) throw failure();
40270
40473
  if (current === dirname11(external) && process.platform !== "win32" && (stat.mode & 63) !== 0) throw failure();
40271
40474
  if (dirname11(current) === current) break;
@@ -40274,7 +40477,7 @@ function initializeLocalSecrets(root, application, keyFile) {
40274
40477
  const release2 = acquireLocalLease(root, ".backify/dev/secrets.lock");
40275
40478
  const key = randomBytes5(32);
40276
40479
  try {
40277
- if (existsSync12(filename2)) throw failure();
40480
+ if (existsSync13(filename2)) throw failure();
40278
40481
  mkdirSync5(dirname11(filename2), { recursive: true, mode: 448 });
40279
40482
  writePrivate2(external, key.toString("hex"));
40280
40483
  writePrivate2(filename2, encrypt(root, application, key, {}));
@@ -40294,7 +40497,7 @@ function setLocalSecret(root, application, keyFile, name2, value) {
40294
40497
  const secrets = readLocalSecrets(root, application, keyFile);
40295
40498
  secrets[name2] = value;
40296
40499
  key = externalKey(root, keyFile);
40297
- const temporary = filename2 + "." + randomUUID9() + ".tmp";
40500
+ const temporary = filename2 + "." + randomUUID10() + ".tmp";
40298
40501
  assertLocalStatePath(root, temporary);
40299
40502
  writePrivate2(temporary, encrypt(root, application, key, secrets));
40300
40503
  renameLocalFile(temporary, filename2);
@@ -40331,11 +40534,11 @@ async function localSecretsCommand(args2, root, application, input = process.std
40331
40534
 
40332
40535
  // src/local-development.ts
40333
40536
  function localManifest(root = process.cwd()) {
40334
- const filename2 = join15(root, "backify.yaml");
40335
- if (!existsSync13(filename2)) throw new Error("Create backify.yaml with version, application, runtime and explicit capabilities before running backify dev");
40336
- const manifest = parseApplicationManifest(readFileSync21(filename2, "utf8"));
40537
+ const filename2 = join16(root, "backify.yaml");
40538
+ if (!existsSync14(filename2)) throw new Error("Create backify.yaml with version, application, runtime and explicit capabilities before running backify dev");
40539
+ const manifest = parseApplicationManifest(readFileSync22(filename2, "utf8"));
40337
40540
  const entry = resolve18(root, manifest.runtime.entrypoint);
40338
- if (!existsSync13(entry) || !inside2(root, realpathSync5(entry))) throw new Error("Runtime entrypoint must exist inside this repository");
40541
+ if (!existsSync14(entry) || !inside2(root, realpathSync5(entry))) throw new Error("Runtime entrypoint must exist inside this repository");
40339
40542
  const discovered = analyzeSources(repositorySources(root));
40340
40543
  const diagnostics = manifestDiagnostics(manifest, Object.keys(discovered.capabilities), discovered.capabilities.auth?.configuration);
40341
40544
  if (diagnostics.length) throw new Error(diagnostics.map((diagnostic) => diagnostic.message).join("; "));
@@ -40346,12 +40549,12 @@ function inside2(root, path) {
40346
40549
  return part !== ".." && !part.startsWith(".." + (process.platform === "win32" ? "\\" : "/")) && !isAbsolute13(part);
40347
40550
  }
40348
40551
  function sessionPath(root) {
40349
- return join15(root, ".backify", "dev", "session.json");
40552
+ return join16(root, ".backify", "dev", "session.json");
40350
40553
  }
40351
40554
  async function localRequest(path, input, root = process.cwd()) {
40352
40555
  if (!/^\/v1\/[a-z/-]+$/.test(path)) throw new Error("Invalid local command path");
40353
- if (!existsSync13(sessionPath(root))) throw new Error("Start backify dev before using local commands");
40354
- const session = JSON.parse(readFileSync21(sessionPath(root), "utf8"));
40556
+ if (!existsSync14(sessionPath(root))) throw new Error("Start backify dev before using local commands");
40557
+ const session = JSON.parse(readFileSync22(sessionPath(root), "utf8"));
40355
40558
  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");
40356
40559
  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) });
40357
40560
  if (!response.ok) {
@@ -40402,17 +40605,17 @@ async function startLocalDevelopment(options = {}) {
40402
40605
  const identityProfiles = prepareLocalIdentity(root, options.identityUsers);
40403
40606
  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");
40404
40607
  const preparedFrontend = prepareLocalFrontend(root, options, options.localSecretsKey ? [realpathSync5(resolve18(options.localSecretsKey))] : []);
40405
- const ignorePath = join15(root, ".gitignore");
40406
- if (existsSync13(ignorePath) && lstatSync15(ignorePath).isSymbolicLink()) throw new Error("Local development cannot update a symlinked .gitignore");
40407
- const ignore = existsSync13(ignorePath) ? readFileSync21(ignorePath, "utf8") : "";
40408
- if (!ignore.split(/\r?\n/).some((line) => line.trim() === ".backify/")) writeFileSync11(ignorePath, ignore + (ignore.endsWith("\n") || !ignore ? "" : "\n") + ".backify/\n");
40608
+ const ignorePath = join16(root, ".gitignore");
40609
+ if (existsSync14(ignorePath) && lstatSync16(ignorePath).isSymbolicLink()) throw new Error("Local development cannot update a symlinked .gitignore");
40610
+ const ignore = existsSync14(ignorePath) ? readFileSync22(ignorePath, "utf8") : "";
40611
+ if (!ignore.split(/\r?\n/).some((line) => line.trim() === ".backify/")) writeFileSync12(ignorePath, ignore + (ignore.endsWith("\n") || !ignore ? "" : "\n") + ".backify/\n");
40409
40612
  if (options.port !== void 0 && (!Number.isInteger(options.port) || options.port < 0 || options.port > 65535)) throw new Error("Dashboard port must be 0-65535");
40410
- const directory2 = join15(root, ".backify", "dev");
40613
+ const directory2 = join16(root, ".backify", "dev");
40411
40614
  assertLocalStatePath(root, directory2);
40412
- for (const filename2 of ["session.json", "session.json.tmp", "worker.mjs", "worker.mjs.map", "state.json", "state.json.tmp"]) assertLocalStatePath(root, join15(directory2, filename2));
40615
+ for (const filename2 of ["session.json", "session.json.tmp", "worker.mjs", "worker.mjs.map", "state.json", "state.json.tmp"]) assertLocalStatePath(root, join16(directory2, filename2));
40413
40616
  mkdirSync6(directory2, { recursive: true });
40414
40617
  if (!inside2(root, realpathSync5(directory2))) throw new Error("Local state directory must remain inside this repository");
40415
- if (existsSync13(sessionPath(root))) {
40618
+ if (existsSync14(sessionPath(root))) {
40416
40619
  try {
40417
40620
  await localRequest("/v1/status", void 0, root);
40418
40621
  throw new Error("Backify dev is already running for this repository");
@@ -40426,14 +40629,15 @@ async function startLocalDevelopment(options = {}) {
40426
40629
  if (jobWorker && mode !== "full") throw new Error("Native jobs require full-fidelity local mode");
40427
40630
  const backendPort = options.backendPort === void 0 ? void 0 : await allocateLocalPort(options.backendPort);
40428
40631
  const backendUrl = backendPort === void 0 ? void 0 : "http://127.0.0.1:" + backendPort;
40429
- const explicitPorts = [options.port, backendPort, options.frontendPort, options.hcrPort, options.databasePort].filter((port) => port !== void 0 && port !== 0);
40632
+ let dashboardPort = await allocateLocalPort(options.port);
40633
+ const explicitPorts = [dashboardPort, backendPort, options.frontendPort, options.hcrPort, options.databasePort].filter((port) => port !== void 0 && port !== 0);
40430
40634
  if (new Set(explicitPorts).size !== explicitPorts.length) throw new Error("Local service ports must be distinct");
40431
40635
  const releaseLease = acquireLocalLease(root);
40432
40636
  let services;
40433
40637
  let frontend;
40434
40638
  try {
40435
40639
  if (mode === "full") services = await startLocalServices(root, manifest, { ...options, jobArtifacts, jobIdentityScope: jobWorker?.authTrust?.scope });
40436
- if (preparedFrontend) frontend = await startLocalFrontend(preparedFrontend, options.frontendPort, backendUrl, options.onDiagnostic);
40640
+ if (preparedFrontend) frontend = await startLocalFrontend(preparedFrontend, options.frontendPort, backendUrl, options.onDiagnostic, identityProfiles ? "http://127.0.0.1:" + dashboardPort : void 0);
40437
40641
  } catch (error2) {
40438
40642
  try {
40439
40643
  await services?.stop();
@@ -40443,14 +40647,14 @@ async function startLocalDevelopment(options = {}) {
40443
40647
  throw error2;
40444
40648
  }
40445
40649
  const token = randomBytes6(32).toString("hex");
40446
- const identityScope = services?.identityScope ?? { organizationId: randomUUID10(), applicationId: randomUUID10(), environmentId: randomUUID10() };
40650
+ const identityScope = services?.identityScope ?? { organizationId: randomUUID11(), applicationId: randomUUID11(), environmentId: randomUUID11() };
40447
40651
  const workerEnvironment = (worker) => {
40448
40652
  if (!worker.authTrust) return worker;
40449
40653
  const { renewal, ...authTrust } = worker.authTrust;
40450
40654
  return { ...worker, authTrust };
40451
40655
  };
40452
40656
  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" });
40453
- const outfile = join15(directory2, "worker.mjs");
40657
+ const outfile = join16(directory2, "worker.mjs");
40454
40658
  let child;
40455
40659
  const trustRenewal = createLocalJobTrustRenewal(root, authMounts, { onFailure: () => console.error("Native worker trust renewal unavailable; existing validity and pin guards remain enforced."), onUpdate: () => {
40456
40660
  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 })) }, (error2) => {
@@ -40459,7 +40663,6 @@ async function startLocalDevelopment(options = {}) {
40459
40663
  } });
40460
40664
  let buildContext;
40461
40665
  let stopping = false;
40462
- let dashboardPort = options.port ?? 0;
40463
40666
  let dashboardOpened = false;
40464
40667
  let restarting = Promise.resolve();
40465
40668
  let resolveStartup = () => {
@@ -40488,8 +40691,8 @@ async function startLocalDevelopment(options = {}) {
40488
40691
  }
40489
40692
  await stopChild(child);
40490
40693
  if (stopping) return;
40491
- const version2 = createHash13("sha256").update(readFileSync21(outfile)).update(services?.configurationFingerprint ?? "lightweight").digest("hex");
40492
- const worker = spawn4(process.execPath, [outfile], { cwd: root, windowsHide: true, stdio: ["ignore", options.onDiagnostic ? "pipe" : 2, options.onDiagnostic ? "pipe" : 2, "ipc"], env: { ...process.env, ...identityEnvironment(), BACKIFY_LOCAL_SECRETS_IPC: "1", HOST: "127.0.0.1", ...backendPort === void 0 ? {} : { PORT: String(backendPort) }, BACKIFY_LOCAL_BACKEND_URL: backendUrl ?? "", BACKIFY_LOCAL_FRONTEND_URL: frontend?.url ?? "", BACKIFY_LOCAL_DATABASE_ENABLED: manifest.capabilities.database && manifest.capabilities.database.enabled !== false ? "1" : "0", BACKIFY_LOCAL_STORAGE_ENABLED: manifest.capabilities.storage && manifest.capabilities.storage.enabled !== false ? "1" : "0", BACKIFY_LOCAL_STORAGE_BUCKETS: JSON.stringify(manifest.capabilities.storage?.buckets?.map((bucket) => bucket.name) ?? (manifest.capabilities.storage ? ["default"] : [])), BACKIFY_LOCAL_TOKEN: token, BACKIFY_LOCAL_PORT: String(dashboardPort), BACKIFY_LOCAL_STATE: join15(directory2, "state.json"), BACKIFY_LOCAL_VERSION: version2, 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" } });
40694
+ const version2 = createHash13("sha256").update(readFileSync22(outfile)).update(services?.configurationFingerprint ?? "lightweight").digest("hex");
40695
+ const worker = spawn4(process.execPath, [outfile], { cwd: root, windowsHide: true, stdio: ["ignore", options.onDiagnostic ? "pipe" : 2, options.onDiagnostic ? "pipe" : 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: join16(directory2, "state.json"), BACKIFY_LOCAL_VERSION: version2, 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" } });
40493
40696
  if (options.onDiagnostic) {
40494
40697
  worker.stdout?.on("data", (chunk) => options.onDiagnostic(chunk.toString()));
40495
40698
  worker.stderr?.on("data", (chunk) => options.onDiagnostic(chunk.toString()));
@@ -40515,7 +40718,7 @@ async function startLocalDevelopment(options = {}) {
40515
40718
  workerReady = true;
40516
40719
  const session = { version: 1, port: message.port, token, pid: worker.pid };
40517
40720
  const temp = sessionPath(root) + ".tmp";
40518
- writeFileSync11(temp, JSON.stringify(session), { mode: 384 });
40721
+ writeFileSync12(temp, JSON.stringify(session), { mode: 384 });
40519
40722
  renameLocalFile(temp, sessionPath(root));
40520
40723
  const url2 = "http://127.0.0.1:" + message.port;
40521
40724
  options.onReady?.(url2, { frontendUrl: frontend?.url, backendUrl });
@@ -40535,9 +40738,9 @@ async function startLocalDevelopment(options = {}) {
40535
40738
  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");
40536
40739
  if (updated.runtime.entrypoint !== manifest.runtime.entrypoint) throw new Error("Runtime entrypoint changed; restart backify dev");
40537
40740
  } catch (error2) {
40538
- return { errors: [{ text: error2 instanceof Error ? error2.message : "Manifest validation failed" }], watchFiles: [join15(root, "backify.yaml")] };
40741
+ return { errors: [{ text: error2 instanceof Error ? error2.message : "Manifest validation failed" }], watchFiles: [join16(root, "backify.yaml")] };
40539
40742
  }
40540
- return { contents: readFileSync21(input.path, "utf8"), loader: input.path.endsWith(".tsx") ? "tsx" : /\.(ts|mts|cts)$/.test(input.path) ? "ts" : input.path.endsWith(".jsx") ? "jsx" : "js", watchFiles: [join15(root, "backify.yaml")] };
40743
+ return { contents: readFileSync22(input.path, "utf8"), loader: input.path.endsWith(".tsx") ? "tsx" : /\.(ts|mts|cts)$/.test(input.path) ? "ts" : input.path.endsWith(".jsx") ? "jsx" : "js", watchFiles: [join16(root, "backify.yaml")] };
40541
40744
  });
40542
40745
  build3.onEnd((result) => {
40543
40746
  if (options.onDiagnostic) {
@@ -40596,8 +40799,8 @@ async function startLocalDevelopment(options = {}) {
40596
40799
  }
40597
40800
  }
40598
40801
  }
40599
- if (existsSync13(sessionPath(root))) {
40600
- const session = JSON.parse(readFileSync21(sessionPath(root), "utf8"));
40802
+ if (existsSync14(sessionPath(root))) {
40803
+ const session = JSON.parse(readFileSync22(sessionPath(root), "utf8"));
40601
40804
  if (session.token === token) unlinkSync5(sessionPath(root));
40602
40805
  }
40603
40806
  };
@@ -40611,11 +40814,11 @@ async function startLocalDevelopment(options = {}) {
40611
40814
  }
40612
40815
  async function runLocalTests(root = process.cwd()) {
40613
40816
  const manifest = localManifest(root);
40614
- const project = JSON.parse(readFileSync21(join15(root, "package.json"), "utf8"));
40817
+ const project = JSON.parse(readFileSync22(join16(root, "package.json"), "utf8"));
40615
40818
  if (!project.scripts?.test) throw new Error("Add a test script to package.json so AI agents can run backify test");
40616
40819
  const result = await new Promise((resolveResult, reject) => {
40617
- const npmPath = process.platform === "win32" ? process.env.npm_execpath ?? join15(dirname12(process.execPath), "node_modules", "npm", "bin", "npm-cli.js") : void 0;
40618
- if (npmPath && !existsSync13(npmPath)) {
40820
+ const npmPath = process.platform === "win32" ? process.env.npm_execpath ?? join16(dirname12(process.execPath), "node_modules", "npm", "bin", "npm-cli.js") : void 0;
40821
+ if (npmPath && !existsSync14(npmPath)) {
40619
40822
  reject(new Error("Cannot locate npm-cli.js; run backify test through npx or npm"));
40620
40823
  return;
40621
40824
  }
@@ -40642,7 +40845,7 @@ function digest3(contents) {
40642
40845
  }
40643
40846
  function packageDirectory(filename2) {
40644
40847
  for (let current = dirname13(filename2); ; current = dirname13(current)) {
40645
- if (existsSync14(join16(current, "package.json"))) return current;
40848
+ if (existsSync15(join17(current, "package.json"))) return current;
40646
40849
  if (dirname13(current) === current) throw new Error("Cannot locate an installed dependency package");
40647
40850
  }
40648
40851
  }
@@ -40754,11 +40957,11 @@ async function prepareWorkload(options) {
40754
40957
  context3.onResolve({ filter: /./ }, async (input) => {
40755
40958
  if (input.pluginData?.backifyResolved) return;
40756
40959
  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" }] };
40757
- const resolved = await context3.resolve(input.path, { importer: input.namespace === "backify-workload-host" ? join16(root, input.importer) : input.importer, resolveDir: input.resolveDir, kind: input.kind, pluginData: { backifyResolved: true } });
40960
+ const resolved = await context3.resolve(input.path, { importer: input.namespace === "backify-workload-host" ? join17(root, input.importer) : input.importer, resolveDir: input.resolveDir, kind: input.kind, pluginData: { backifyResolved: true } });
40758
40961
  if (!resolved.external && !resolved.errors.length && resolved.path) {
40759
40962
  const directory2 = realpathSync6(packageDirectory(resolved.path));
40760
40963
  const target = relative8(directory2, realpathSync6(resolved.path)).replaceAll("\\", "/");
40761
- if (JSON.parse(readFileSync22(join16(directory2, "package.json"), "utf8")).name === "@backifydev/sdk") {
40964
+ if (JSON.parse(readFileSync23(join17(directory2, "package.json"), "utf8")).name === "@backifydev/sdk") {
40762
40965
  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" }] };
40763
40966
  }
40764
40967
  if (!isAbsolute14(input.path) && !input.path.startsWith(".")) trustedPackages.add(directory2);
@@ -40822,28 +41025,28 @@ async function packageWorkload(options) {
40822
41025
  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" };
40823
41026
  const output = resolve19(root, options.output ?? ".backify/artifacts/" + options.kind + "-" + plan.artifactVersion.slice(0, 16));
40824
41027
  assertLocalStatePath(root, output);
40825
- if (existsSync14(output)) {
41028
+ if (existsSync15(output)) {
40826
41029
  if (JSON.stringify(readdirSync6(output).sort()) !== JSON.stringify(Object.keys(files).sort()) || Object.entries(files).some(([name2, value]) => {
40827
- assertLocalStatePath(root, join16(output, name2));
40828
- return !readFileSync22(join16(output, name2)).equals(Buffer.from(value));
41030
+ assertLocalStatePath(root, join17(output, name2));
41031
+ return !readFileSync23(join17(output, name2)).equals(Buffer.from(value));
40829
41032
  })) throw new Error("Refusing to overwrite an existing workload artifact directory");
40830
41033
  } else {
40831
41034
  mkdirSync7(output, { recursive: true });
40832
- for (const [name2, value] of Object.entries(files)) writeFileSync12(join16(output, name2), value, { flag: "wx", mode: 384 });
41035
+ for (const [name2, value] of Object.entries(files)) writeFileSync13(join17(output, name2), value, { flag: "wx", mode: 384 });
40833
41036
  }
40834
41037
  return { ...plan, outputDirectory: relative8(root, output).replaceAll("\\", "/") };
40835
41038
  }
40836
41039
 
40837
41040
  // src/workload-provenance.ts
40838
41041
  import { execFileSync } from "node:child_process";
40839
- import { mkdirSync as mkdirSync8, mkdtempSync as mkdtempSync2, readdirSync as readdirSync7, rmSync as rmSync2, writeFileSync as writeFileSync13 } from "node:fs";
41042
+ import { mkdirSync as mkdirSync8, mkdtempSync as mkdtempSync2, readdirSync as readdirSync7, rmSync as rmSync2, writeFileSync as writeFileSync14 } from "node:fs";
40840
41043
  import { tmpdir } from "node:os";
40841
- import { basename as basename3, dirname as dirname15, isAbsolute as isAbsolute15, join as join18, relative as relative9, resolve as resolve21 } from "node:path";
41044
+ import { basename as basename3, dirname as dirname15, isAbsolute as isAbsolute15, join as join19, relative as relative9, resolve as resolve21 } from "node:path";
40842
41045
 
40843
41046
  // src/workload-provenance-oci.ts
40844
41047
  import { createHash as createHash15 } from "node:crypto";
40845
- import { createReadStream, lstatSync as lstatSync16, readFileSync as readFileSync23 } from "node:fs";
40846
- import { dirname as dirname14, join as join17, parse as parse3, resolve as resolve20 } from "node:path";
41048
+ import { createReadStream, lstatSync as lstatSync17, readFileSync as readFileSync24 } from "node:fs";
41049
+ import { dirname as dirname14, join as join18, parse as parse3, resolve as resolve20 } from "node:path";
40847
41050
  import { Transform, Writable } from "node:stream";
40848
41051
  import { pipeline } from "node:stream/promises";
40849
41052
  import { createGunzip } from "node:zlib";
@@ -40860,12 +41063,12 @@ function provenanceRef(value) {
40860
41063
  function provenanceFile(filename2, maximum) {
40861
41064
  const absolute = resolve20(filename2);
40862
41065
  for (let ancestor = absolute; ; ancestor = dirname14(ancestor)) {
40863
- if (lstatSync16(ancestor).isSymbolicLink()) throw new Error("Provenance paths must not contain links");
41066
+ if (lstatSync17(ancestor).isSymbolicLink()) throw new Error("Provenance paths must not contain links");
40864
41067
  if (ancestor === parse3(absolute).root) break;
40865
41068
  }
40866
- const stat = lstatSync16(absolute);
41069
+ const stat = lstatSync17(absolute);
40867
41070
  if (!stat.isFile() || stat.nlink !== 1 || stat.size < 1 || stat.size > maximum) throw new Error("Invalid provenance file");
40868
- const bytes = readFileSync23(absolute);
41071
+ const bytes = readFileSync24(absolute);
40869
41072
  if (bytes.length !== stat.size) throw new Error("Provenance file changed during read");
40870
41073
  return bytes;
40871
41074
  }
@@ -40874,7 +41077,7 @@ function descriptor(value) {
40874
41077
  return value;
40875
41078
  }
40876
41079
  function blobPath(root, value) {
40877
- return join17(root, "blobs", "sha256", descriptor(value).digest.slice(7));
41080
+ return join18(root, "blobs", "sha256", descriptor(value).digest.slice(7));
40878
41081
  }
40879
41082
  function jsonBlob(root, value) {
40880
41083
  const bytes = provenanceFile(blobPath(root, value), 1024 * 1024);
@@ -40883,8 +41086,8 @@ function jsonBlob(root, value) {
40883
41086
  }
40884
41087
  async function inspectProvenanceImage(root, architecture, requestedDigest) {
40885
41088
  if (!["amd64", "arm64"].includes(architecture) || requestedDigest && !digestPattern.test(requestedDigest)) throw new Error("Invalid OCI platform or digest");
40886
- if (JSON.parse(provenanceFile(join17(root, "oci-layout"), 1024).toString()).imageLayoutVersion !== "1.0.0") throw new Error("OCI layout required");
40887
- const indexBytes = provenanceFile(join17(root, "index.json"), 1024 * 1024);
41089
+ if (JSON.parse(provenanceFile(join18(root, "oci-layout"), 1024).toString()).imageLayoutVersion !== "1.0.0") throw new Error("OCI layout required");
41090
+ const indexBytes = provenanceFile(join18(root, "index.json"), 1024 * 1024);
40888
41091
  let current = JSON.parse(indexBytes.toString());
40889
41092
  let selected;
40890
41093
  let manifestDigest = provenanceHash(indexBytes);
@@ -40943,10 +41146,10 @@ async function inspectProvenanceImage(root, architecture, requestedDigest) {
40943
41146
  function provenanceFileMetadata(filename2, expectedSize) {
40944
41147
  const absolute = resolve20(filename2);
40945
41148
  for (let ancestor = absolute; ; ancestor = dirname14(ancestor)) {
40946
- if (lstatSync16(ancestor).isSymbolicLink()) throw new Error("Provenance paths must not contain links");
41149
+ if (lstatSync17(ancestor).isSymbolicLink()) throw new Error("Provenance paths must not contain links");
40947
41150
  if (ancestor === parse3(absolute).root) break;
40948
41151
  }
40949
- const stat = lstatSync16(absolute);
41152
+ const stat = lstatSync17(absolute);
40950
41153
  if (!stat.isFile() || stat.nlink !== 1 || stat.size !== expectedSize) throw new Error("Invalid OCI layer file");
40951
41154
  }
40952
41155
  function verifyBaseLineage(base, image2) {
@@ -41013,17 +41216,17 @@ async function captureWorkloadProvenance(options) {
41013
41216
  if (!sha.test(commit) || !sha.test(tree)) throw new Error("Full Git commit and tree required");
41014
41217
  const origin = git2(root, ["remote", "get-url", "origin"]);
41015
41218
  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");
41016
- const lockBytes = provenanceFile(join18(root, "package-lock.json"), 16 * 1024 * 1024);
41219
+ const lockBytes = provenanceFile(join19(root, "package-lock.json"), 16 * 1024 * 1024);
41017
41220
  const dependencies = dependencyMaterials(JSON.parse(lockBytes.toString("utf8")));
41018
41221
  const context3 = resolve21(root, options.context);
41019
41222
  if (canonical(readdirSync7(context3).sort()) !== canonical(contextNames)) throw new Error("Exact allowlisted workload context required");
41020
41223
  const contextDigests = {};
41021
- for (const name2 of contextNames) contextDigests[name2] = provenanceHash(provenanceFile(join18(context3, name2), name2 === "workload.mjs" ? 16 * 1024 * 1024 : 65536));
41022
- const plan = boundedJson(join18(context3, "artifact.json"));
41224
+ for (const name2 of contextNames) contextDigests[name2] = provenanceHash(provenanceFile(join19(context3, name2), name2 === "workload.mjs" ? 16 * 1024 * 1024 : 65536));
41225
+ const plan = boundedJson(join19(context3, "artifact.json"));
41023
41226
  const baseDigest = provenanceRef(options.baseImage);
41024
41227
  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");
41025
41228
  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");
41026
- if (!provenanceFile(join18(context3, "Dockerfile"), 65536).equals(Buffer.from(dockerfile)) || provenanceFile(join18(context3, ".dockerignore"), 65536).toString() !== "**\n!Dockerfile\n!workload.mjs\n!artifact.json\n!.dockerignore\n") throw new Error("Unreviewed workload build recipe");
41229
+ if (!provenanceFile(join19(context3, "Dockerfile"), 65536).equals(Buffer.from(dockerfile)) || provenanceFile(join19(context3, ".dockerignore"), 65536).toString() !== "**\n!Dockerfile\n!workload.mjs\n!artifact.json\n!.dockerignore\n") throw new Error("Unreviewed workload build recipe");
41027
41230
  const base = await inspectProvenanceImage(resolve21(root, options.baseLayout), options.architecture, baseDigest);
41028
41231
  const image2 = await inspectProvenanceImage(resolve21(root, options.imageLayout), options.architecture);
41029
41232
  verifyBaseLineage(base, image2);
@@ -41099,16 +41302,16 @@ function verifyWorkloadProvenance(options, now = /* @__PURE__ */ new Date()) {
41099
41302
  evidence.push({ bytes: baseSubject, bundle: provenanceFile(options.baseBundle, 4 * 1024 * 1024), identity: { ...policy, ...supplier } });
41100
41303
  }
41101
41304
  const scratchRoot = resolve21(tmpdir());
41102
- const scratch = mkdtempSync2(join18(scratchRoot, "backify-provenance-"));
41305
+ const scratch = mkdtempSync2(join19(scratchRoot, "backify-provenance-"));
41103
41306
  if (dirname15(scratch) !== scratchRoot || !basename3(scratch).startsWith("backify-provenance-")) throw new Error("Unsafe provenance evidence directory");
41104
41307
  try {
41105
- mkdirSync8(join18(scratch, "evidence"), { mode: 448 });
41106
- const trustedRoot = join18(scratch, "evidence", "trusted-root.jsonl");
41107
- writeFileSync13(trustedRoot, rootBytes, { flag: "wx", mode: 384 });
41308
+ mkdirSync8(join19(scratch, "evidence"), { mode: 448 });
41309
+ const trustedRoot = join19(scratch, "evidence", "trusted-root.jsonl");
41310
+ writeFileSync14(trustedRoot, rootBytes, { flag: "wx", mode: 384 });
41108
41311
  for (const [index, { bytes, bundle: bundleBytes, identity }] of evidence.entries()) {
41109
- const report = join18(scratch, "evidence", "report-" + index + ".json"), bundle = join18(scratch, "evidence", "bundle-" + index + ".jsonl");
41110
- writeFileSync13(report, bytes, { flag: "wx", mode: 384 });
41111
- writeFileSync13(bundle, bundleBytes, { flag: "wx", mode: 384 });
41312
+ const report = join19(scratch, "evidence", "report-" + index + ".json"), bundle = join19(scratch, "evidence", "bundle-" + index + ".jsonl");
41313
+ writeFileSync14(report, bytes, { flag: "wx", mode: 384 });
41314
+ writeFileSync14(bundle, bundleBytes, { flag: "wx", mode: 384 });
41112
41315
  try {
41113
41316
  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"] });
41114
41317
  if (!Array.isArray(JSON.parse(result)) || !JSON.parse(result).length) throw new Error();
@@ -41139,12 +41342,12 @@ async function workloadProvenanceCommand(args2) {
41139
41342
  return verifyWorkloadProvenance({ policy: required2("--policy"), firstReport: options.get("--report") ?? required2("--first-report"), firstBundle: options.get("--bundle") ?? required2("--first-bundle"), secondReport: options.get("--second-report"), secondBundle: options.get("--second-bundle"), baseSubject: options.get("--base-subject"), baseBundle: options.get("--base-bundle"), trustedRoot: required2("--trusted-root") });
41140
41343
  }
41141
41344
  const result = await captureWorkloadProvenance({ root: options.get("--root"), repository: required2("--repository"), application: required2("--application"), context: required2("--context"), baseLayout: required2("--base-layout"), imageLayout: required2("--image-layout"), baseImage: required2("--base-image"), architecture: required2("--architecture"), replica: options.get("--replica") ?? "first" });
41142
- writeFileSync13(resolve21(required2("--output")), JSON.stringify(result, null, 2) + "\n", { flag: "wx", mode: 384 });
41345
+ writeFileSync14(resolve21(required2("--output")), JSON.stringify(result, null, 2) + "\n", { flag: "wx", mode: 384 });
41143
41346
  return { schemaVersion: 1, status: "captured-unsigned", deploymentReady: false, reportDigest: provenanceHash(JSON.stringify(result, null, 2) + "\n") };
41144
41347
  }
41145
41348
 
41146
41349
  // src/workload-trust-state.ts
41147
- import { lstatSync as lstatSync17, readFileSync as readFileSync24 } from "node:fs";
41350
+ import { lstatSync as lstatSync18, readFileSync as readFileSync25 } from "node:fs";
41148
41351
  import { isAbsolute as isAbsolute16, resolve as resolve22 } from "node:path";
41149
41352
  function parseWorkloadTrustState(args2) {
41150
41353
  const action = args2[0];
@@ -41170,9 +41373,9 @@ function workloadTrustState(options) {
41170
41373
  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");
41171
41374
  let trust;
41172
41375
  try {
41173
- const metadata = lstatSync17(options.trustFile);
41376
+ const metadata = lstatSync18(options.trustFile);
41174
41377
  if (!metadata.isFile() || metadata.isSymbolicLink() || metadata.nlink !== 1 || metadata.size > 131072) throw new Error();
41175
- const bytes = readFileSync24(options.trustFile);
41378
+ const bytes = readFileSync25(options.trustFile);
41176
41379
  if (bytes.length > 131072) throw new Error();
41177
41380
  trust = JSON.parse(new TextDecoder("utf8", { fatal: true }).decode(bytes));
41178
41381
  } catch {
@@ -41188,8 +41391,8 @@ function workloadTrustState(options) {
41188
41391
  }
41189
41392
 
41190
41393
  // src/scaffold.ts
41191
- import { existsSync as existsSync15, lstatSync as lstatSync18, mkdirSync as mkdirSync9, readFileSync as readFileSync25, readdirSync as readdirSync8, realpathSync as realpathSync7, writeFileSync as writeFileSync14 } from "node:fs";
41192
- import { dirname as dirname16, join as join19, relative as relative10, resolve as resolve23 } from "node:path";
41394
+ import { existsSync as existsSync16, lstatSync as lstatSync19, mkdirSync as mkdirSync9, readFileSync as readFileSync26, readdirSync as readdirSync8, realpathSync as realpathSync7, writeFileSync as writeFileSync15 } from "node:fs";
41395
+ import { dirname as dirname16, join as join20, relative as relative10, resolve as resolve23 } from "node:path";
41193
41396
 
41194
41397
  // src/task-template.ts
41195
41398
  function json2(value) {
@@ -41597,20 +41800,20 @@ provider-readiness claim, cloud deployment or browser authentication is implied.
41597
41800
  function scaffoldFullStack(options) {
41598
41801
  const files = fullStackTemplate(options.appId, options.name, options.template);
41599
41802
  const root = resolve23(options.root ?? process.cwd());
41600
- if (!existsSync15(root) || !lstatSync18(root).isDirectory() || lstatSync18(root).isSymbolicLink()) throw new Error("Scaffold destination must be an existing non-linked directory");
41803
+ if (!existsSync16(root) || !lstatSync19(root).isDirectory() || lstatSync19(root).isSymbolicLink()) throw new Error("Scaffold destination must be an existing non-linked directory");
41601
41804
  const allowed = /* @__PURE__ */ new Set([...Object.keys(files).map((filename2) => filename2.split("/")[0]), ".git", "node_modules", "package-lock.json", ".backify"]);
41602
41805
  if (readdirSync8(root).some((filename2) => !allowed.has(filename2))) throw new Error("Scaffolding requires an empty folder or an unchanged generated starter");
41603
41806
  const canonicalRoot = realpathSync7(root);
41604
41807
  const pending = [];
41605
41808
  for (const [filename2, content] of Object.entries(files)) {
41606
- const destination = join19(root, filename2);
41809
+ const destination = join20(root, filename2);
41607
41810
  let current = destination;
41608
41811
  while (current !== root) {
41609
41812
  try {
41610
- const stat = lstatSync18(current);
41813
+ const stat = lstatSync19(current);
41611
41814
  if (stat.isSymbolicLink() || current !== destination && !stat.isDirectory()) throw new Error("Scaffolding refuses linked or invalid output paths: " + filename2);
41612
41815
  if (relative10(canonicalRoot, realpathSync7(current)).startsWith("..")) throw new Error("Scaffold output must remain inside its directory");
41613
- if (current === destination && (!stat.isFile() || readFileSync25(current, "utf8") !== content)) throw new Error("Scaffolding refuses to overwrite existing content: " + filename2);
41816
+ if (current === destination && (!stat.isFile() || readFileSync26(current, "utf8") !== content)) throw new Error("Scaffolding refuses to overwrite existing content: " + filename2);
41614
41817
  } catch (error2) {
41615
41818
  if (!(error2 instanceof Error) || !("code" in error2) || error2.code !== "ENOENT") throw error2;
41616
41819
  if (current === destination) pending.push(filename2);
@@ -41619,9 +41822,9 @@ function scaffoldFullStack(options) {
41619
41822
  }
41620
41823
  }
41621
41824
  for (const filename2 of pending) {
41622
- const destination = join19(root, filename2);
41825
+ const destination = join20(root, filename2);
41623
41826
  mkdirSync9(dirname16(destination), { recursive: true });
41624
- writeFileSync14(destination, files[filename2], { flag: "wx" });
41827
+ writeFileSync15(destination, files[filename2], { flag: "wx" });
41625
41828
  }
41626
41829
  return { template: options.template === "tasks" ? "react-vite-hono-tasks" : "react-vite-hono", created: pending, unchanged: Object.keys(files).length - pending.length, installed: false, deployed: false };
41627
41830
  }
@@ -41665,16 +41868,16 @@ function localInspectionCommand(args2) {
41665
41868
  }
41666
41869
 
41667
41870
  // src/index.ts
41668
- import { readFileSync as readFileSync28, existsSync as existsSync17, rmSync as rmSync3 } from "node:fs";
41871
+ import { readFileSync as readFileSync29, existsSync as existsSync18, rmSync as rmSync3 } from "node:fs";
41669
41872
  import { homedir as homedir3 } from "node:os";
41670
- import { join as join22 } from "node:path";
41873
+ import { join as join23 } from "node:path";
41671
41874
  import { spawn as spawn5 } from "node:child_process";
41672
41875
  var [command2, ...args] = process.argv.slice(2);
41673
- var configPath = join22(homedir3(), ".backify.json");
41674
- var userConfig = command2 !== "mcp" && existsSync17(configPath) ? JSON.parse(readFileSync28(configPath, "utf8")) : {};
41876
+ var configPath = join23(homedir3(), ".backify.json");
41877
+ var userConfig = command2 !== "mcp" && existsSync18(configPath) ? JSON.parse(readFileSync29(configPath, "utf8")) : {};
41675
41878
  async function call(path, init) {
41676
41879
  let appId = option("--app");
41677
- if (!appId && existsSync17(join22(process.cwd(), "backify.json"))) appId = projectApplication();
41880
+ if (!appId && existsSync18(join23(process.cwd(), "backify.json"))) appId = projectApplication();
41678
41881
  const session = appId ? userConfig.sessions?.[sessionKey(appId)] : void 0;
41679
41882
  const credential = session ?? { token: userConfig.token ?? "", organizationId: userConfig.organizationId ?? "", apiUrl: process.env.BACKIFY_API_URL ?? userConfig.apiUrl ?? "https://api.backify.dev/api" };
41680
41883
  return (appId ? applicationClient(credential, appId) : apiClient(credential))(path, init);
@@ -41696,7 +41899,7 @@ async function browserLogin(appId, organizationId, apiUrl) {
41696
41899
  if (args.includes("--no-browser")) throw new CliAuthenticationRequired();
41697
41900
  const address = apiAddress(apiUrl ?? process.env.BACKIFY_API_URL ?? userConfig.apiUrl ?? "https://api.backify.dev/api");
41698
41901
  return browserAuthenticate({ authUrl: process.env.BACKIFY_AUTH_URL ?? process.env.BACKIFY_PORTAL_URL ?? userConfig.portalUrl ?? "https://auth.backify.dev", apiUrl: address, applicationId: appId ? applicationGuid(appId) : void 0, organizationId, openBrowser: (url2) => {
41699
- console.error("Sign in to reconnect Backify CLI access. Choose the expiration in your browser; the CLI will continue automatically.\n" + url2);
41902
+ console.error("Sign in to authorize Backify CLI access. Choose the expiration in your browser; the CLI will continue automatically.\n" + url2);
41700
41903
  openBrowser(url2);
41701
41904
  }, save: (session) => {
41702
41905
  if (appId) {
@@ -41837,7 +42040,7 @@ async function main() {
41837
42040
  const name2 = option("--name");
41838
42041
  if (!name2) throw new Error("Specify --name <job>");
41839
42042
  const payload = option("--payload");
41840
- console.log(JSON.stringify(await localRequest("/v1/jobs/run", { name: name2, payload: payload ? JSON.parse(readFileSync28(payload, "utf8")) : null }), null, 2));
42043
+ console.log(JSON.stringify(await localRequest("/v1/jobs/run", { name: name2, payload: payload ? JSON.parse(readFileSync29(payload, "utf8")) : null }), null, 2));
41841
42044
  } else if (["retry", "cancel"].includes(args[0])) {
41842
42045
  const id = option("--id");
41843
42046
  if (!id) throw new Error("Specify --id <run>");
@@ -41860,7 +42063,7 @@ async function main() {
41860
42063
  const environmentId = option("--environment");
41861
42064
  const packagePath = option("--package");
41862
42065
  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.");
41863
- await deployFunctions(call, appId, applicationGuid(environmentId), new Uint8Array(readFileSync28(packagePath)), { progress: (message) => console.log(message) });
42066
+ await deployFunctions(call, appId, applicationGuid(environmentId), new Uint8Array(readFileSync29(packagePath)), { progress: (message) => console.log(message) });
41864
42067
  console.log("Functions deployed.");
41865
42068
  } else throw new Error("Use backify functions package or backify functions deploy");
41866
42069
  break;
@@ -41879,6 +42082,11 @@ async function main() {
41879
42082
  synchronize(process.cwd(), option("--agent"), option("--instruction-file"));
41880
42083
  console.log("Backify instructions synchronized to version " + INSTRUCTION_VERSION);
41881
42084
  break;
42085
+ case "upgrade": {
42086
+ if (args.some((value) => value !== "--json")) throw new Error("Use backify upgrade [--json]. Only stable compatible SDK releases are selected automatically.");
42087
+ console.log(JSON.stringify(upgradeSdk(), null, 2));
42088
+ break;
42089
+ }
41882
42090
  case "doctor": {
41883
42091
  if (args.includes("--environment")) {
41884
42092
  const result2 = await diagnoseEnvironment(process.cwd(), { network: args.includes("--network"), capability: option("--capability") });
@@ -41896,7 +42104,7 @@ async function main() {
41896
42104
  userConfig.token = args[0];
41897
42105
  userConfig.organizationId = args[1] ?? userConfig.organizationId;
41898
42106
  saveUserConfig(configPath, userConfig);
41899
- } else await browserLogin(args.includes("--organization-access") ? void 0 : option("--app") ?? (existsSync17(join22(process.cwd(), "backify.json")) ? projectApplication() : void 0), option("--organization"));
42107
+ } else await browserLogin(args.includes("--organization-access") ? void 0 : option("--app") ?? (existsSync18(join23(process.cwd(), "backify.json")) ? projectApplication() : void 0), option("--organization"));
41900
42108
  console.log("Logged in to Backify");
41901
42109
  break;
41902
42110
  case "logout":
@@ -41935,7 +42143,7 @@ async function main() {
41935
42143
  userConfig.sessions[key] ??= session;
41936
42144
  saveUserConfig(configPath, userConfig);
41937
42145
  if (args.includes("--clone")) await cloneProject(client, appId);
41938
- else if (existsSync17(join22(process.cwd(), ".git"))) {
42146
+ else if (existsSync18(join23(process.cwd(), ".git"))) {
41939
42147
  const update = await pullProject(client, appId);
41940
42148
  console.log(JSON.stringify(update, null, 2));
41941
42149
  if (update.status === "blocked") throw new Error(update.reason);
@@ -41998,7 +42206,7 @@ async function main() {
41998
42206
  } else if (args[0] === "install") {
41999
42207
  const version2 = option("--version"), sha256 = option("--sha256");
42000
42208
  if (!version2 || !sha256) throw new Error("Use backify runtime install --version vX.Y.Z --sha256 <reviewed-digest> [--archive <local-zip>]");
42001
- const bytes = option("--archive") ? readFileSync28(option("--archive")) : await downloadLocalRuntime(version2);
42209
+ const bytes = option("--archive") ? readFileSync29(option("--archive")) : await downloadLocalRuntime(version2);
42002
42210
  console.log(JSON.stringify(installLocalRuntime(bytes, { version: version2, sha256 }), null, 2));
42003
42211
  } else throw new Error("Use backify runtime install or backify runtime doctor");
42004
42212
  break;
@@ -42013,7 +42221,7 @@ async function main() {
42013
42221
  case "request": {
42014
42222
  const workspaceId = option("--workspace"), name2 = option("--name"), slug = option("--slug"), description = option("--description"), configurationFile = option("--configuration");
42015
42223
  if (!workspaceId || !name2 || !slug || !description) throw new Error("Use backify request --workspace <id> --name <name> --slug <slug> --description <purpose> [--configuration <json-file>]");
42016
- const configuration = configurationFile ? JSON.parse(readFileSync28(configurationFile, "utf8")) : void 0;
42224
+ const configuration = configurationFile ? JSON.parse(readFileSync29(configurationFile, "utf8")) : void 0;
42017
42225
  console.log(await call("/apps/requests", { method: "POST", body: JSON.stringify({ workspaceId, name: name2, slug, description, configuration }) }));
42018
42226
  break;
42019
42227
  }
@@ -42031,7 +42239,7 @@ async function main() {
42031
42239
  else if (args[0] === "test") {
42032
42240
  const name2 = option("--name"), payload = option("--payload");
42033
42241
  if (!name2 || !payload) throw new Error("Specify --name and --payload <json-file>. Never include secrets in event payloads.");
42034
- console.log(JSON.stringify(await call(path + "/test", { method: "POST", body: JSON.stringify({ name: name2, payload: JSON.parse(readFileSync28(payload, "utf8")), idempotencyKey: option("--idempotency-key") }) }), null, 2));
42242
+ console.log(JSON.stringify(await call(path + "/test", { method: "POST", body: JSON.stringify({ name: name2, payload: JSON.parse(readFileSync29(payload, "utf8")), idempotencyKey: option("--idempotency-key") }) }), null, 2));
42035
42243
  } else throw new Error("Use backify events environments|inspect|test");
42036
42244
  break;
42037
42245
  }
@@ -42042,7 +42250,7 @@ async function main() {
42042
42250
  console.log(await call("/apps/" + applicationGuid(args[0]) + "/deployments/preview", { method: "POST", body: JSON.stringify({ sourceRevision: args[1] ?? "latest" }) }));
42043
42251
  break;
42044
42252
  default:
42045
- console.log("backify tools configure --agent <tool> [--transport http|stdio] [--config <path>] [--dry-run] | connect | init | doctor | sync | mcp [--project <directory>] [--app <application-id>] [--allow-preview] | login | logout | disconnect | status | dev | secrets local init|set|list --key-file <external-file> | test --json | inspect tables|rows|buckets|objects|preview|events --local [--json] | identity users|issue|clear --local [--json] | jobs | pull | report [--check] | prompt record --stdin --id <UUID> | ship [--production-deploy] | request | events environments|inspect|test | integrations list|catalog|search|describe|contract|types | workload plan|package|artifact-plan|trust-state|trust-sync|provenance capture|verify | apps | deploy");
42253
+ console.log("backify tools configure --agent <tool> [--transport http|stdio] [--config <path>] [--dry-run] | connect | init | doctor | upgrade [--json] | sync | mcp [--project <directory>] [--app <application-id>] [--allow-preview] | login | logout | disconnect | status | dev | secrets local init|set|list --key-file <external-file> | test --json | inspect tables|rows|buckets|objects|preview|events --local [--json] | identity users|inbox|issue|clear --local [--json] | jobs | pull | report [--check] | prompt record --stdin --id <UUID> | ship [--production-deploy] | request | events environments|inspect|test | integrations list|catalog|search|describe|contract|types | workload plan|package|artifact-plan|trust-state|trust-sync|provenance capture|verify | apps | deploy");
42046
42254
  }
42047
42255
  }
42048
42256
  main().catch((error2) => {