zebra 0.0.1-preview.1

Zebra: an incremental build orchestrator for Zena and standalone workspaces

Readme Files Dependencies Versions

zebra#

An incremental script and service runner for Zena (zena-package.json), standalone Zebra (zebra.json), and Wireit (package.json) workspaces, built on zena-lang:workflow.

Zebra runs a dependency graph of scripts and long-running services with declared inputs, outputs, and dependencies, rerunning only what changed. For each script, Zebra content-hashes the declared inputs and asks the workflow engine what to do: nothing (when the previous run recorded the same fingerprints and declared outputs are intact), restore from the local content-addressed cache, or execute the command (sh -c in the package directory with node_modules/.bin on PATH).

Installation#

zebra is built into the zena CLI (zena build <target>). To use it as a library or standalone runner:

zena pkg add zena-lang:zebra

CLI Usage#

zena build [-j <jobs>] [-w|--watch] [-f|--force] [--no-cache] [-v|--verbose] [<target>] [-- <args>...]
zena run [-j <jobs>] [-w|--watch] [-f|--force] [--no-cache] [-v|--verbose] <target> [-- <args>...]
zena test [-j <jobs>] [-w|--watch] [--force] [--no-cache] [-v|--verbose] [-- <args>...]
zena build --migrate [--dry-run] [-f|--force] [<package-dir>...]
  • <target> can be a script name in the current package (zena build test, zena run check), a package directory (zena build ./packages/app, which runs build), or <package-dir>:<script> (zena build ./packages/app:test). With no <target>, zena build runs the current package's build script and zena test runs its test script.
  • -- <args>... appends shell-quoted arguments to the entry target's command only, running that entry step uncached without overwriting its saved freshness record.
  • -j / --jobs <n> bounds parallel command execution (defaulting to ZEBRA_PARALLEL, WIREIT_PARALLEL, or ZENA_AVAILABLE_PARALLELISM).
  • -w / --watch watches input globs, lockfiles, and package manifests for changes, re-running affected steps incrementally while keeping unchanged services alive in a ServicePool across rebuilds.
  • -f / --force bypasses freshness and cached outputs to rerun scripts unconditionally.
  • --no-cache disables restoring outputs from .zebra/blobs/ when a step is not fresh.
  • -v / --verbose prints every step (including fresh and skipped) and any captured stdout/stderr on the rail.
  • --migrate converts Wireit blocks in package.json into zena-package.json (when present) or zebra.json.

Programmatic Usage#

import { buildTarget, reportBuild } from 'zena-lang:zebra/runner';
import { ScriptRef } from 'zena-lang:zebra/wireit-config';

let outcome = await buildTarget('.', new ScriptRef('packages/app', 'build'), {
  parallelism: 4,
});
let exitCode = reportBuild(outcome);

Configuration (zena-package.json and zebra.json)#

Zena packages configure scripts and filesets directly in zena-package.json. Non-Zena projects can use a standalone zebra.json (with an optional "workspace": {"packages": [...]} at the workspace root). Both support // and /* ... */ comments:

{
  "name": "app",
  "dependencies": {
    "lib": {"path": "../lib"},
  },
  "filesets": {
    "assets": ["assets/**"],
  },
  "scripts": {
    "build": {
      "command": "zena build src/main.zena -o out/app.wasm",
      "output": ["out/app.wasm"],
      "dependencies": ["source", "assets"],
    },
    "test": {
      "type": "zena:test",
      "tests": "test/*_test.zena",
    },
    "fmt": "zena fmt --check .",
  },
}
  • Declarative zena:test steps and default test target: Scripts in zena-package.json and zebra.json can set "type": "zena:test" (with optional "tests": true, "tests": "test/*_test.zena", or "tests": ["test/*_test.zena", ...] — defaulting to ["test/**/*_test.zena", "tests/**/*_test.zena"] when omitted — and optional "debug": true for -g) to run Zena tests in-process through TestStepRunner. Test pattern globs merge into files, and zena-package.json "zena:test" steps automatically depend on source. When a zena-package.json omits a test script (and no fallback package.json defines test), Zebra synthesizes a "type": "zena:test" target over test/**/*_test.zena and tests/**/*_test.zena.
  • Automatic source fileset: Every package with zena-package.json exposes an automatic source fileset covering its library .zena files (from "source", defaulting to "src" and excluding *_test.zena, test/**, and tests/**), zena-package.json, any "wit" dependencies, and the source filesets of all "path" dependencies. Scripts opt into it via "dependencies": ["source"] (or "../pkg:source").
  • Named filesets: Entries accept either a glob array shorthand ("wit": ["wit/**/*.wit"]) or {"files": [...], "dependencies": [...]} and compose transitively without spawning commands.
  • Caching and tracking: Task scripts cache automatically whenever files, output, or a fileset dependency is declared, defaulting output to [] when omitted. Setting "cache": false opts a step out of freshness and caching while keeping its files globs active in --watch mode. Omitting files, output, and fileset dependencies on a command step leaves it untracked so it runs every time. String entries ("fmt": "zena fmt --check .") are shorthands for always-run commands.
  • Locks: locks defaults to ["zena-lock.json"] and may be set at the package root or overridden per script ("locks": [] disables lockfile hashing).
  • Services: Scripts with "service": true or "service": {"readyWhen": {"lineMatches": "..."}} start on demand when a dependent executes, wait for readiness when configured, are shared across dependents, and are stopped as a Unix process group (SIGTERM then SIGKILL) when dependents finish. Invoking a service directly as the top-level target runs its dependencies and streams the service in the foreground.
  • Wireit fallback: When a package directory has no zebra.json and no "scripts" block in zena-package.json, Zebra falls back to package.json Wireit scripts while still serving filesets from zena-package.json. Dependencies can cross freely between zena-package.json, zebra.json, and package.json packages.

Cache Layout (.zebra/)#

Each package's <pkg>/.zebra/ directory stores:

  • state.json — freshness records for that package's scripts (the last cache key and output manifest).
  • cache/<key>.json — cache key to output manifest.
  • blobs/ — content-addressed output bytes (sha256).

The workspace root's .zebra/ directory stores:

  • hashes.json — the (mtime, size) to sha256 file hash memo shared across packages (with a 20ms racy-timestamp guard).
  • plans/<hash>.plan — stat-verified cached ScriptConfig closures keyed by target entry.

A dependency contributes the digest of its outputs to dependents' cache keys rather than its input fingerprint, giving early cutoff when a dependency reruns and produces identical outputs.

GitHub Actions Remote Cache#

Setting ZEBRA_CACHE=github layers GitHubActionsCache behind the local .zebra/ DiskCache (TieredCache). On a local cache miss, Zebra queries the GitHub Actions v2 CacheService Twirp JSON API, verifies downloaded blob sha256 digests, populates <pkg>/.zebra/, and materializes outputs into the workspace. On a build step execution, Zebra writes <pkg>/.zebra/ first and uploads the step's entry to GitHub Actions Cache (ZEBRA_CACHE_READ_ONLY=1 disables uploads; ZEBRA_CACHE=none disables both local and remote caching).

In GitHub Actions workflows, run .github/actions/setup-zebra-cache before build steps so ACTIONS_RESULTS_URL and ACTIONS_RUNTIME_TOKEN are served to run: steps over a 127.0.0.1 token custodian (ZEBRA_GITHUB_CUSTODIAN_URL).

Libraries#

  • zebra (zebra/main) — CLI entry point (main).
  • zebra/runner — buildTarget, watchTarget, BuildOptions, WatchOptions, reportBuild, reportMigration, formatBuildReport, and BuildOutcome.
  • zebra/zebra-config — zena-package.json and zebra.json parsing (ZebraWorkspace), synthesized source filesets, and Wireit migration (migrateWorkspaceToZebra, convertPackageJsonToZebraJson, mergeWireitIntoZenaPackageJson).
  • zebra/wireit-config — package.json Wireit parsing (WireitWorkspace) and shared script configuration types (ScriptConfig, ScriptRef, DependencySpec, ServiceConfig, EnvBinding, ConfigError, refKey, resolveDependency).
  • zebra/plan-cache — .zebra/plans/ snapshot serialization and stat-verified warm plan loading (loadOrCollectConfigs, PlanLoadStats, ConfigProbe).
  • zebra/builder — Translates ScriptConfig closures into workflow steps and execution callbacks (planScripts, StepExecution, lockfileCandidates).
  • zebra/disk-cache, zebra/github-cache, and zebra/state-json — .zebra/ blob/manifest storage (DiskCache, TieredCache, stateDirOf), GitHub Actions remote caching (GitHubActionsCache, GitHubCacheConfig, CacheMode, resolveCacheMode, resolveGitHubCacheConfig), and JSON serialization for state, manifests, and hash memos.
  • zebra/fs-walk and zebra/fs-util — Input glob discovery (FileHasher, expandGlobs, hashFile, validateGlobs, splitBase) and workspace path utilities.
  • zebra/shell — POSIX shell argument quoting (shellQuote, appendShellArgs). Zebra's terminal output uses zena-lang:terminal (packages/terminal): colors, the Clack-style rail layout and the spinner.

License#

MIT

17.1 KiB Raw
import {Box} from 'zena:core';
import { HashSet } from 'zena:collections';
import {
  JsonArray,
  JsonObject,
  JsonValue,
  parseJson,
} from 'zena:json';
import {compareStrings, sortBy} from 'workflow/canonical';
import {joinWorkspace} from './fs-util.zena';

/** Rule `type` identifier for native Zena `*_test.zena` test suites. */
export let ZENA_TEST_RULE_TYPE = 'zena:test';

/** Raised for malformed or unsupported build configuration. */
export class ConfigError extends Error {
  new(message: String) : super(message);
}

/** A script in a package, both repo-relative ('' is the root package). */
export class ScriptRef(packageDir: String, script: String)

/** The key steps derived from this script use, 'dir:script'. */
export function refKey(ref: ScriptRef): String {
  return `${ref.packageDir}:${ref.script}`;
}

/** A resolved dependency edge, with wireit's `cascade` flag (default true). */
export class DependencySpec(ref: ScriptRef, cascade: boolean)

/**
 * Service configuration: `readyWhenLineMatches` is null for `service: true`
 * (ready on spawn) or a regex pattern string for `readyWhen.lineMatches`.
 */
export class ServiceConfig(readyWhenLineMatches: String?)

/** One entry in a script's `env` map. */
export sealed class EnvBinding {
  case EnvLiteral, EnvExternal
}

/** Sets the environment variable to a fixed string value. */
export final class EnvLiteral(value: String) extends EnvBinding

/**
 * Fingerprints an environment variable from the caller's environment,
 * optionally falling back to `defaultValue` when unset.
 */
export final class EnvExternal(defaultValue: String?) extends EnvBinding

/**
 * One script's configuration. For a wireit script the fields come from
 * the wireit block; a bare npm script has only a command and always
 * runs.
 */
export class ScriptConfig {
  ref: ScriptRef;
  isWireit: boolean;
  command: String?;
  /** Globs relative to the package directory. */
  files: Array<String>;
  output: Array<String>;
  /**
   * Whether the config declared the key at all. Omitting `files` or
   * `output` on a task script means the inputs or outputs are unknown
   * (wireit semantics): the script is never fresh, never cached, and
   * its cascading dependents cannot be either. An explicit empty array
   * means "declared none" and tracks fully. Services forbid `output`
   * and track their identity whenever `files` is declared.
   */
  filesDeclared: boolean;
  outputDeclared: boolean;
  dependencies: Array<DependencySpec>;
  /** 'true', 'false', or 'if-file-deleted'. */
  clean: String;
  service: ServiceConfig?;
  /** Sorted by variable name. */
  env: Array<(String, EnvBinding)>;
  /**
   * Lockfile filenames searched upward from `ref.packageDir` to the
   * workspace root (wireit defaults to `['package-lock.json']` when
   * omitted; `[]` disables lockfile tracking).
   */
  packageLocks: Array<String>;
  /**
   * Explicit opt-out from freshness and caching (`"cache": false` in
   * `zebra.json` or `zena-package.json`). Defaults to `true`.
   */
  cacheEnabled: boolean;
  /**
   * True when this step is a pure fileset rule (`"filesets"` or the
   * synthesized `"source"` fileset of a `zena-package.json`) rather than
   * a runnable script.
   */
  isFileset: boolean;
  /**
   * Zena test file patterns (relative to `ref.packageDir`) for a
   * `"type": "zena:test"` step, or `null` for command/group/service/fileset steps.
   */
  tests: Array<String>?;
  /** Run `"type": "zena:test"` modules with debug names and inlining disabled (`-g`). */
  testDebug: boolean;
  /** Extra CLI arguments after `--` passed to an entry `"type": "zena:test"` step. */
  testExtraArgs: Array<String>?;
  /** Explicit rule discriminator (such as `'zena:test'`), or `null` for standard scripts. */
  ruleType: String?;

  /**
   * True when freshness and caching apply to this script at all. A
   * command-less script, `"type": "zena:test"` step, or fileset always tracks
   * (unless `cacheEnabled` is false); a service tracks when `files` (or a
   * fileset dependency) is declared; a command task needs both `files` and
   * `output` declared.
   */
  fingerprintable: boolean {
    get {
      if (!this.isWireit || !this.cacheEnabled) {
        return false;
      }
      if (this.service != null) {
        return this.filesDeclared;
      }
      if (this.command == null) {
        return true;
      }
      return this.filesDeclared && this.outputDeclared;
    }
  }

  new(
    this.ref,
    this.isWireit,
    this.command,
    this.files,
    this.output,
    this.filesDeclared,
    this.outputDeclared,
    this.dependencies,
    this.clean,
    this.service,
    this.env,
    this.packageLocks,
    this.cacheEnabled = true,
    this.isFileset = false,
    this.tests = null,
    this.testDebug = false,
    this.testExtraArgs = null,
    this.ruleType = null,
  );
}

export function isCommentKey(key: String): boolean {
  return key == '//' || key.startsWith('#');
}

function isRecognizedKey(key: String) {
  return key == 'command' || key == 'files' || key == 'output' ||
    key == 'dependencies' || key == 'clean' || key == 'service' ||
    key == 'env' || key == 'packageLocks' || isCommentKey(key);
}

export function stringList(value: JsonValue, what: String): Array<String> {
  if (value == null) {
    return new GrowableArray<String>();
  }
  if (value is JsonArray) {
    let out = new GrowableArray<String>();
    for (var i = 0; i < value.length; i += 1) {
      let item = value[i];
      if (item is String) {
        out.push(item);
      } else {
        throw new ConfigError(what + ' must contain only strings');
      }
    }
    return out;
  }
  throw new ConfigError(what + ' must be an array');
}

/**
 * Resolves a wireit dependency string. A dependency starting with '.'
 * is '<path>:<script>' with the path relative to the referring
 * package; anything else is a script in the same package (script
 * names themselves may contain ':').
 */
export function resolveDependency(from: String, dep: String): ScriptRef {
  if (dep.startsWith('.')) {
    var colon = -1;
    for (var i = 0; i < dep.length; i += 1) {
      if (dep.getByteAt(i) == 58) {
        colon = i;
        break;
      }
    }
    if (colon < 0) {
      throw new ConfigError(
        `dependency "${dep}" of ${from} has a path but no script name`,
      );
    }
    let target = joinWorkspace(from, dep.sliceBytes(0, colon));
    if (target.startsWith('..')) {
      throw new ConfigError(
        `dependency "${dep}" of ${from} escapes the workspace`,
      );
    }
    return new ScriptRef(target, dep.sliceBytes(colon + 1, dep.length));
  }
  return new ScriptRef(from, dep);
}

export function parseDependency(
  packageDir: String,
  where: String,
  dep: JsonValue,
): DependencySpec {
  if (dep is String) {
    return new DependencySpec(resolveDependency(packageDir, dep), true);
  }
  if (dep is JsonObject) {
    dep.forEach((key, value) => {
      if (key != 'script' && key != 'cascade' && !isCommentKey(key)) {
        throw new ConfigError(
          `script "${where}": dependency object has unsupported key "${key}"`,
        );
      }
    });
    let rawScript = dep['script'];
    if (!(rawScript is String)) {
      throw new ConfigError(
        `script "${where}": dependency object requires a string "script"`,
      );
    }
    var cascade = true;
    let rawCascade = dep['cascade'];
    if (rawCascade != null) {
      if (rawCascade is Box<boolean>) {
        cascade = rawCascade.value;
      } else {
        throw new ConfigError(
          `script "${where}": dependency "cascade" must be a boolean`,
        );
      }
    }
    return new DependencySpec(resolveDependency(packageDir, rawScript), cascade);
  }
  throw new ConfigError(
    `script "${where}": dependencies entries must be strings or {script, cascade} objects`,
  );
}

export function parseService(where: String, rawService: JsonValue): ServiceConfig? {
  if (rawService == null) {
    return null;
  }
  if (rawService is Box<boolean>) {
    return if (rawService.value) new ServiceConfig(null) else null;
  }
  if (rawService is JsonObject) {
    rawService.forEach((key, value) => {
      if (key != 'readyWhen' && !isCommentKey(key)) {
        throw new ConfigError(
          `script "${where}": service has unsupported key "${key}"`,
        );
      }
    });
    let rawReady = rawService['readyWhen'];
    if (rawReady == null) {
      return new ServiceConfig(null);
    }
    if (!(rawReady is JsonObject)) {
      throw new ConfigError(
        `script "${where}": service.readyWhen must be an object`,
      );
    }
    rawReady.forEach((key, value) => {
      if (key != 'lineMatches' && !isCommentKey(key)) {
        throw new ConfigError(
          `script "${where}": service.readyWhen has unsupported key "${key}"`,
        );
      }
    });
    let lineMatches = rawReady['lineMatches'];
    if (!(lineMatches is String) || lineMatches == '') {
      throw new ConfigError(
        `script "${where}": service.readyWhen.lineMatches must be a non-empty string`,
      );
    }
    return new ServiceConfig(lineMatches);
  }
  throw new ConfigError(
    `script "${where}": service must be a boolean or an object`,
  );
}

export function parseEnv(
  where: String,
  rawEnv: JsonValue,
): Array<(String, EnvBinding)> {
  let out = new GrowableArray<(String, EnvBinding)>();
  if (rawEnv == null) {
    return out;
  }
  if (!(rawEnv is JsonObject)) {
    throw new ConfigError(`script "${where}": env must be an object`);
  }
  rawEnv.forEach((name, value) => {
    if (isCommentKey(name)) {
      return;
    }
    if (value is String) {
      out.push((name, new EnvLiteral(value)));
    } else if (value is JsonObject) {
      value.forEach((key, v) => {
        if (key != 'external' && key != 'default' && !isCommentKey(key)) {
          throw new ConfigError(
            `script "${where}": env.${name} has unsupported key "${key}"`,
          );
        }
      });
      let ext = value['external'];
      if (!(ext is Box<boolean>) || !ext.value) {
        throw new ConfigError(
          `script "${where}": env.${name} object must specify "external": true`,
        );
      }
      var defaultValue: String? = null;
      let rawDefault = value['default'];
      if (rawDefault != null) {
        if (rawDefault is String) {
          defaultValue = rawDefault;
        } else {
          throw new ConfigError(
            `script "${where}": env.${name}.default must be a string`,
          );
        }
      }
      out.push((name, new EnvExternal(defaultValue)));
    } else {
      throw new ConfigError(
        `script "${where}": env.${name} must be a string or {"external": true}`,
      );
    }
  });
  sortBy(
    out,
    (a: (String, EnvBinding), b: (String, EnvBinding)) => compareStrings(a[0], b[0]),
  );
  return out;
}

export function parseClean(where: String, rawClean: JsonValue): String {
  if (rawClean == null) {
    return 'true';
  }
  if (rawClean is Box<boolean>) {
    return if (rawClean.value) 'true' else 'false';
  }
  if (rawClean is String) {
    if (rawClean != 'if-file-deleted') {
      throw new ConfigError(
        `script "${where}": unsupported clean value "${rawClean}"`,
      );
    }
    return rawClean;
  }
  throw new ConfigError(`script "${where}": invalid clean value`);
}

export function validateLockFilenames(
  where: String,
  fieldName: String,
  locks: Array<String>,
): void {
  for (let lock in locks) {
    if (lock == '' || lock.contains('/')) {
      throw new ConfigError(
        `${where}: ${fieldName} entries must be filenames, got "${lock}"`,
      );
    }
  }
}

export function parseJsonObject(path: String, content: String): JsonObject {
  var parsed: JsonValue = null;
  try {
    parsed = parseJson(content, {allowComments: true, trackLocations: false});
  } catch (e) {
    throw new ConfigError(`${path}: ${e.message}`);
  }
  if (!(parsed is JsonObject)) {
    throw new ConfigError(`${path} is not a JSON object`);
  }
  return parsed;
}

/**
 * Extracts one `ScriptConfig` from a parsed `package.json` object using
 * Wireit's rules (`wireit[script]` or bare `scripts[script]`).
 */
export function parseWireitScriptFromPackage(
  ref: ScriptRef,
  pkg: JsonObject,
): ScriptConfig {
  let where = refKey(ref);

  var wireitEntry: JsonValue = null;
  let wireit = pkg['wireit'];
  if (wireit is JsonObject) {
    wireitEntry = wireit[ref.script];
  }
  var scriptsEntry: JsonValue = null;
  let scripts = pkg['scripts'];
  if (scripts is JsonObject) {
    scriptsEntry = scripts[ref.script];
  }

  if (wireitEntry is JsonObject) {
    // A script run via npm needs a "wireit" scripts entry; one that
    // exists only as a dependency of other wireit scripts has none.
    if (scriptsEntry != null && (!(scriptsEntry is String) || scriptsEntry != 'wireit')) {
      throw new ConfigError(
        `script "${where}" has a wireit config but its scripts entry is not "wireit"`,
      );
    }
    wireitEntry.forEach((key, value) => {
      if (!isRecognizedKey(key)) {
        throw new ConfigError(
          `script "${where}" has unsupported wireit key "${key}"`,
        );
      }
    });

    var command: String? = null;
    let rawCommand = wireitEntry['command'];
    if (rawCommand != null) {
      if (rawCommand is String) {
        command = rawCommand;
      } else {
        throw new ConfigError(`script "${where}": command must be a string`);
      }
    }

    let deps = new GrowableArray<DependencySpec>();
    let rawDeps = wireitEntry['dependencies'];
    if (rawDeps != null) {
      if (!(rawDeps is JsonArray)) {
        throw new ConfigError(`script "${where}": dependencies must be an array`);
      }
      for (var i = 0; i < rawDeps.length; i += 1) {
        deps.push(parseDependency(ref.packageDir, where, rawDeps[i]));
      }
    }

    let clean = parseClean(where, wireitEntry['clean']);

    let service = parseService(where, wireitEntry['service']);
    if (command == null && service != null) {
      throw new ConfigError(`script "${where}": a service needs a command`);
    }
    if (service != null && wireitEntry['output'] != null) {
      throw new ConfigError(`script "${where}": a service cannot declare output`);
    }

    let rawLocks = wireitEntry['packageLocks'];
    var packageLocks: Array<String> = ['package-lock.json'];
    if (rawLocks != null) {
      packageLocks = stringList(rawLocks, `script "${where}": packageLocks`);
      validateLockFilenames(`script "${where}"`, 'packageLocks', packageLocks);
    }

    return new ScriptConfig(
      ref,
      true,
      command,
      stringList(wireitEntry['files'], `script "${where}": files`),
      stringList(wireitEntry['output'], `script "${where}": output`),
      wireitEntry['files'] != null,
      wireitEntry['output'] != null,
      deps,
      clean,
      service,
      parseEnv(where, wireitEntry['env']),
      packageLocks,
    );
  }

  if (scriptsEntry is String) {
    if (scriptsEntry == 'wireit') {
      throw new ConfigError(
        `script "${where}" says "wireit" but has no wireit config`,
      );
    }
    // A bare npm script: always runs, produces nothing cacheable.
    return new ScriptConfig(
      ref,
      false,
      scriptsEntry,
      new GrowableArray<String>(),
      new GrowableArray<String>(),
      false,
      false,
      new GrowableArray<DependencySpec>(),
      'false',
      null,
      new GrowableArray<(String, EnvBinding)>(),
      new GrowableArray<String>(),
      false,
    );
  }

  let pkgLabel = if (ref.packageDir == '') 'the root package' else ref.packageDir;
  throw new ConfigError(`no script "${ref.script}" in ${pkgLabel}`);
}

/**
 * Reads wireit build configuration from package.json files, resolving
 * cross-package references. File access goes through the callback
 * (repo-relative path to content, or null when absent), so tests run
 * on in-memory fixtures.
 */
export class WireitWorkspace {
  #readFile: (path: String) => Future<String?>;
  #packages = new HashMap<String, JsonObject>();

  new(readFile: (path: String) => Future<String?>) : #readFile = readFile;

  async #packageJson(packageDir: String): Future<JsonObject> {
    if (let (true, cached) = this.#packages.get(packageDir)) {
      return cached;
    }
    let path = joinWorkspace(packageDir, 'package.json');
    let readFile = this.#readFile;
    let content = await readFile(path);
    if (content == null) {
      throw new ConfigError('no package.json at ' + path);
    }
    let parsed = parseJsonObject(path, content);
    this.#packages[packageDir] = parsed;
    return parsed;
  }

  async scriptConfig(ref: ScriptRef): Future<ScriptConfig> {
    let pkg = await this.#packageJson(ref.packageDir);
    return parseWireitScriptFromPackage(ref, pkg);
  }

  /** The transitive dependency closure, in discovery (BFS) order. */
  async collect(entries: Array<ScriptRef>): Future<Array<ScriptConfig>> {
    let seen = new HashSet<String>();
    let queue = new GrowableArray<ScriptRef>();
    let out = new GrowableArray<ScriptConfig>();
    for (let entry in entries) {
      queue.push(entry);
    }
    var next = 0;
    while (next < queue.length) {
      let ref = queue[next];
      next += 1;
      if (!seen.add(refKey(ref))) {
        continue;
      }
      let config = await this.scriptConfig(ref);
      out.push(config);
      for (let dep in config.dependencies) {
        queue.push(dep.ref);
      }
    }
    return out;
  }
}
  • terminal terminal.zena-lang.pkg.zena-lang.dev ~0.0.1-preview.1
  • workflow workflow.zena-lang.pkg.zena-lang.dev ~0.0.1-preview.1
VersionPublishedDependenciesApproved by
0.0.1-preview.1 2026-11-19
  • terminal terminal.zena-lang.pkg.zena-lang.dev ~0.0.1-preview.1
  • workflow workflow.zena-lang.pkg.zena-lang.dev ~0.0.1-preview.1