Skip to content

armgit / hypit

Public Imported from GitHub
0

Clone any viral video with AI agents. Not just a script, the whole workflow: swap the face, the words, the B-roll, ship 100 variants in one command, and get your 100M views.

refactor: compose CLI and Studio from owned capabilities

kashorin25520fecdff0
diff --git a/packages/browser-capture/README.md b/packages/browser-capture/README.md
index e23d1466..5ed9d422 100644
--- a/packages/browser-capture/README.md
+++ b/packages/browser-capture/README.md
@@ -2,10 +2,12 @@
Browser material capture for websites and authored HTML. The package owns browser lifecycle and file
capture; the task owns navigation, page state and the material worth showing. It imports Puppeteer Core,
-the upstream browser installer and Sharp directly and has no dependency on Hypit Core, Runtime,
-Providers or graph types.
+the upstream browser installer and Sharp directly. Its library does not create a Source Graph, Build,
+Result or Runtime; completed recordings reuse `@hypit/media-local`'s explicit file probe instead of
+forking a second ffprobe parser. The package's CLI contribution uses the installed Hypit CLI host.
-The Distribution supplies `hypit capture screenshot` and `hypit capture run`. See `hypit capture --help`
+This package also owns the `@hypit/browser-capture/cli` contribution used by the Distribution for
+`hypit capture screenshot` and `hypit capture run`. See `hypit capture --help`
for command options. Puppeteer Core is a pinned Distribution dependency, so a plain video project
needs no browser-library installation or private `node_modules` import path.
`hypit capture install-browser` explicitly prepares the package's tested Chrome for Testing revision
@@ -59,8 +61,9 @@ capture rate, and `maxWidth` / `maxHeight` constrain output dimensions. These op
to Puppeteer. The helper defaults those upper bounds to the viewport's device-pixel dimensions.
Chrome determines the recorded dimensions; device scale can enlarge a screenshot without enlarging
the recording. Use the returned `width` and `height` for placement. No FFmpeg encoder is involved;
-`ffprobe` reads the completed file's actual dimensions,
-duration, frame rate and audio presence. `stop()` is idempotent and waits for the file to finish.
+the `media-local` file probe invokes the selected `ffprobe` to read the completed file's actual
+dimensions, duration, frame rate and audio presence. Browser Capture does not keep a second media
+probe parser. `stop()` is idempotent and waits for the file to finish.
Both functions accept an optional second `Page` argument for scripts using several pages. Returning
finishes recordings started through `record`. Ordinary Puppeteer methods remain available; files
@@ -85,5 +88,5 @@ belong in those scripts through normal Puppeteer APIs. A simple screenshot waits
`--wait-for` and `--wait-ms` add an authored readiness condition. The package does not interpret
websites or silently rewrite page content.
-For a library import in an installed Distribution, use `@hypit/hypit/browser-capture`. The workspace package
-also exports the same API as `@hypit/browser-capture`.
+Library consumers import `@hypit/browser-capture` directly. The root Distribution selects it as an
+ordinary npm dependency; it does not republish the library through an `@hypit/hypit/*` facade.
diff --git a/packages/browser-capture/package.json b/packages/browser-capture/package.json
index 58b16cda..d9cab451 100644
--- a/packages/browser-capture/package.json
+++ b/packages/browser-capture/package.json
@@ -1,17 +1,25 @@
{
"name": "@hypit/browser-capture",
- "version": "0.0.0-dev",
+ "version": "0.1.0",
"license": "SEE LICENSE IN LICENSE",
"private": true,
"type": "module",
"exports": {
- ".": "./src/index.ts"
+ ".": "./src/index.ts",
+ "./cli": "./src/cli.ts"
},
"dependencies": {
+ "@hypit/media-local": "workspace:^",
"@puppeteer/browsers": "3.2.2",
"puppeteer-core": "25.10.0",
"sharp": "0.35.4"
},
+ "peerDependencies": {
+ "@hypit/hypit": "workspace:^"
+ },
+ "devDependencies": {
+ "@hypit/hypit": "workspace:*"
+ },
"hypit": {
"captureBrowser": {
"version": "153.0.8010.12"
diff --git a/packages/video-cli/src/capture.ts b/packages/browser-capture/src/cli.ts
similarity index 95%
rename from packages/video-cli/src/capture.ts
rename to packages/browser-capture/src/cli.ts
index 899fab20..f85785c5 100644
--- a/packages/video-cli/src/capture.ts
+++ b/packages/browser-capture/src/cli.ts
@@ -2,7 +2,7 @@ import { stat } from "node:fs/promises";
import { resolve } from "node:path";
import { pathToFileURL } from "node:url";
import { parseArgs } from "node:util";
-import type { CliIo } from "@hypit/cli";
+import type { CliCommandModule, CliIo } from "@hypit/hypit/cli";
import type { CaptureOptions, CaptureOutput, CaptureScript } from "@hypit/browser-capture";
export function writeCaptureHelp(io: CliIo): void {
@@ -187,3 +187,18 @@ export async function runCaptureCli(argv: readonly string[], io: CliIo, cwd = pr
if (values.json) io.write(`${JSON.stringify({ format: "hypit.capture@1", outputs }, null, 2)}\n`);
else io.write(`Capture complete: ${outputs.length} file${outputs.length === 1 ? "" : "s"}.\n`);
}
+
+export const cliCommandModules = [{
+ format: "hypit.cli-command@1",
+ id: "@hypit/browser-capture",
+ commands: ["capture"],
+ writeRootHelp(io) {
+ io.write("\nBrowser capture\n capture screenshot | run | install-browser\n hypit capture --help for options\n");
+ },
+ writeHelp(_argv, io) {
+ writeCaptureHelp(io);
+ },
+ async run(argv, io, context) {
+ await runCaptureCli(argv, io, context.cwd);
+ },
+}] as const satisfies readonly CliCommandModule[];
diff --git a/packages/browser-capture/src/index.ts b/packages/browser-capture/src/index.ts
index 5a567fac..161a7596 100644
--- a/packages/browser-capture/src/index.ts
+++ b/packages/browser-capture/src/index.ts
@@ -1,12 +1,13 @@
import { execFile } from "node:child_process";
import { mkdir, open, rm } from "node:fs/promises";
-import { dirname, resolve } from "node:path";
+import { dirname, extname, resolve } from "node:path";
import { Writable } from "node:stream";
import { promisify } from "node:util";
import { existsSync } from "node:fs";
import puppeteer from "puppeteer-core";
import type { Browser, LaunchOptions, Page, RecordOptions, ScreenshotOptions } from "puppeteer-core";
import sharp from "sharp";
+import { probeMedia } from "@hypit/media-local/files";
import { captureBrowserExecutablePath } from "./browser.js";
export { captureBrowserExecutablePath, installCaptureBrowser } from "./browser.js";
@@ -74,22 +75,11 @@ async function reserve(path: string) {
const exec = promisify(execFile);
async function recordingInfo(path: string, ffprobe: string): Promise<Omit<CaptureOutput, "kind" | "path" | "url">> {
- const { stdout } = await exec(ffprobe, ["-v", "error", "-show_entries",
- "format=format_name,duration:stream=codec_type,width,height,avg_frame_rate", "-of", "json", path]);
- const data = JSON.parse(stdout) as {
- format?: { format_name?: string; duration?: string };
- streams?: { codec_type?: string; width?: number; height?: number; avg_frame_rate?: string }[];
- };
- const video = data.streams?.find((stream) => stream.codec_type === "video");
- const [num, den = "1"] = (video?.avg_frame_rate ?? "0").split("/");
- const rate = Number(num) / Number(den);
- const duration = Number(data.format?.duration);
- if (!video?.width || !video.height || !Number.isFinite(duration) || duration <= 0) {
- throw new Error(`Recording ${path} has no readable video duration or dimensions`);
- }
- return { width: video.width, height: video.height, duration,
- format: data.format?.format_name ?? "unknown", hasAudio: data.streams?.some((s) => s.codec_type === "audio") ?? false,
- ...(Number.isFinite(rate) && rate > 0 ? { frameRate: rate } : {}) };
+ const media = await probeMedia(path, { ffprobePath: ffprobe });
+ if (!media.hasVideo) throw new Error(`Recording ${path} has no readable video stream`);
+ return { width: media.width, height: media.height, duration: media.duration,
+ format: extname(path).slice(1).toLowerCase(), hasAudio: media.hasAudio,
+ ...(media.frameRate > 0 ? { frameRate: media.frameRate } : {}) };
}
/**
diff --git a/packages/video-cli/test/capture.test.ts b/packages/browser-capture/test/cli.test.ts
similarity index 97%
rename from packages/video-cli/test/capture.test.ts
rename to packages/browser-capture/test/cli.test.ts
index 8b5b0cf7..accfc5fc 100644
--- a/packages/video-cli/test/capture.test.ts
+++ b/packages/browser-capture/test/cli.test.ts
@@ -7,8 +7,8 @@ import { join, resolve } from "node:path";
import test from "node:test";
import { promisify } from "node:util";
import { captureBrowserExecutablePath } from "@hypit/browser-capture";
-import { runCaptureCli } from "../src/capture.js";
-import type { CliIo } from "@hypit/cli";
+import { runCaptureCli } from "../src/cli.js";
+import type { CliIo } from "@hypit/hypit/cli";
const executablePath = process.env.HYPIT_CAPTURE_TEST_BROWSER ?? await captureBrowserExecutablePath();
const exec = promisify(execFile);
diff --git a/packages/cli/README.md b/packages/cli/README.md
index 110479c5..1548a39b 100644
--- a/packages/cli/README.md
+++ b/packages/cli/README.md
@@ -4,9 +4,35 @@ Domain neutral commands for checking, planning, building and inspecting Hypit pr
The command engine receives one explicit `CliDistribution`. A distribution supplies the compiler,
trusted bootstrap packages, source package discovery and its Runtime Host. The official video
-executable assembles the Local Runtime through `@hypit/video-cli`; another application may provide
+executable assembles the Local Runtime through `@hypit/video`; another application may provide
another Host without changing this package or pretending that a local Profile selected it.
+`CliDistribution` and the command surface are separate axes. The Distribution supplies compilation,
+Runtime and Result services; this package's root Host always owns process I/O, Help, conflict checks
+and final command dispatch. An installed Distribution declares its default `CliCommandModule`
+exports in its own `package.json`. A project may add installed command packages explicitly through
+its own `package.json`:
+
+```json
+{
+ "devDependencies": { "@someone/hypit-cloud": "1.2.3" },
+ "hypit": { "cli": { "use": ["@someone/hypit-cloud/cli"] } }
+}
+```
+
+`hypit cli use/remove/status` edits or explains only that project selection. It never installs,
+uninstalls or searches for packages. The Host resolves exactly the declared exports through the
+Distribution or project installation, while the ordinary package manager lockfile owns versions.
+Installing a project package or importing it from Source never grants CLI authority. Two modules
+cannot own the same root or replace a domain-neutral or Distribution command.
+
+Command packages can import the structural authoring types from `@hypit/hypit/cli`; the selected
+module export must expose a `cliCommandModules` array of `hypit.cli-command@1` values. That public
+surface contains no video types and does not let a contribution replace the Host.
+
+`hypit version` reports the executing Distribution independently of a project or Runtime.
+`hypit version --check` may query an explicitly selected npm registry, but never installs or updates.
+
Source imports decide which language and component packages give the source meaning. A Local Runtime
Profile separately selects Credential Stores and Endpoints allowed to execute work. The CLI does not
invent targets, candidates or Provider choices.
@@ -43,7 +69,11 @@ promising to restart failed execution or describing the interruption as a Result
| `pricing` | Requests that may incur a Provider charge and their rate material | `--verbose`: declared no-charge requests and original documents |
| `status`, `activity` | Current work, Provider-reported phases and failures | `--verbose`: individual operations; activity also includes capacity reservations |
| `inspect` | Targets and explicitly highlighted Outputs, outcome and failure evidence | `--output <name>` selects one Output; `--verbose` browses all available Outputs and receipts |
-| `doctor`, `programs` | Complete diagnostics; program discovery or the unmet result of an explicit lifecycle action | `--verbose`: successful lifecycle details; `--limit` bounds the healthy program list |
+| `doctor` | Complete project/Runtime diagnostics | `--verbose`: successful diagnostic detail |
+
+`runtime`, `programs`, `paths` and the private Worker entry belong to the selected Local Runtime
+command module, not to this generic command engine. They still appear under the one `hypit` command
+because the official Distribution explicitly selects `@hypit/runtime-local/cli`.
Run choices count explicit Candidate selections, which can supply existing work or execute an
alternative producer. They are not a count of reused files. Result output counts describe all
@@ -67,16 +97,22 @@ does not interpret model or renderer names.
## Project and Runtime context
-`--workspace` explicitly selects the project. Otherwise the nearest `package.json` above the command's
-current directory establishes its root; with none, the current directory is the root. Source and Run
-arguments locate files within that context. Relative command-line paths are resolved from the current
-directory, including when `--workspace` is supplied.
+`--project` explicitly selects the project. Otherwise the Host searches upward for a `package.json`
+whose `hypit.project` field is `true`; it never promotes an arbitrary npm package or current directory.
+Commands that need a project fail accurately when neither selection exists. Source and Run arguments
+locate files within that context. Relative command-line paths are resolved from the current directory,
+including when `--project` is supplied.
-Runtime-aware commands use an explicit `--runtime` for that invocation, or read exactly the resolved
-project's `.hypit/runtime` pointer. `runtime use` writes the pointer; a Profile filename by itself does
-not select it. The pointer is a file, separate from the Profile's `dataRoot`; a directory at that
-path is reported explicitly and preserved. Project selection is also available on `paths`, `doctor`, execution status/control,
-Runtime operations, `programs` and `auth`. Machine-wide `packages` operations have no project selector.
+The same project boundary owns `hypit.cli.use`. Distribution contributions resolve from the
+Distribution root and cannot be shadowed by project dependencies; project contributions resolve
+from that project's direct dependencies. Outside a package project, only Distribution commands are
+available.
+
+Runtime-aware generic commands use an explicit `--runtime` for that invocation, or ask the selected
+Distribution for exactly the resolved project's Runtime selection. The official Local Runtime module
+owns the `.hypit/runtime` pointer and its `runtime use` command; the generic CLI does not know its
+filesystem representation, Worker process or managed Programs. Project selection remains available on
+generic diagnosis/execution/auth commands and on the Local Runtime module's commands.
`auth status <endpoint>` reports credential presence, write access, and the Provider's declared
OAuth authorization endpoint when present. This describes how a subsequent `auth login` acquires a
@@ -93,8 +129,8 @@ diagnosis. Result repository selection and project-package resolution remain ind
For a command invoked outside the project, name both the project and its input explicitly:
```bash
-hypit paths --workspace /path/to/video-project
-hypit plan /path/to/video-project/build.svrun --workspace /path/to/video-project
+hypit paths --project /path/to/video-project
+hypit plan /path/to/video-project/build.svrun --project /path/to/video-project
```
`plan` lists every Endpoint request in the frozen Build graph. Exact-model packages expose their own
@@ -125,19 +161,18 @@ and `noChargeRequestCount` describe the whole Run, while `groups[]` holds Provid
`requests[]` with known parameters and pending inputs, and `pricingDocuments[]` with source and data.
JSON includes every group regardless of `--limit`; no-charge requests are included with `--verbose`.
-The implementation follows those same boundaries: `command.ts` defines the exact semantic command
+The implementation follows those same boundaries: `command.ts` defines the generic semantic command
union, while argument parsing and option ownership live in `arguments.ts`; project Result
-browsing/export lives under `commands/results.ts`; Runtime,
-credential, package and deployment operations live under `commands/environment.ts`; active Build
-observation is read-only code in `observation.ts`; and human rendering is separate from the explicit
-machine-view union. `main.ts` resolves project and selected Runtime context separately from parsed
-syntax, then routes these command groups. Result commands do not consult or construct a Runtime,
-and the generic CLI cannot silently choose a Result Repository or a Provider-specific login
-flow.
+browsing/export lives under `commands/results.ts`; generic diagnosis and credentials live under
+`commands/environment.ts`; active Build observation is read-only code in `observation.ts`; and human
+rendering is separate from the explicit machine-view union. `runtime-local/cli` owns local Profile
+selection, paths, Programs and Worker lifecycle. `main.ts` consumes only `CliRuntimeHost`; it never
+imports the Local Runtime implementation. Result commands do not consult or construct a Runtime,
+and the generic CLI cannot silently choose a Result Repository or a Provider-specific login flow.
## Execution logs
-`hypit logs <build-id> [--workspace <project>] [--runtime <profile>] [--lines <count>]` reads Build
+`hypit logs <build-id> [--project <project>] [--runtime <profile>] [--lines <count>]` reads Build
execution phases and Provider diagnostics. It reads a finished Result directly, without opening the
Runtime; an active Build is read through Runtime control. The selected Repository handles file access.
`--lines` limits the tail and the report states the omitted count; JSON carries records plus that count.
@@ -147,22 +182,18 @@ from a lookup that still needs the Build's Runtime or correct project selection.
`inspect` exposes an available log separately from authored Outputs. `hypit runtime logs` reads the
Worker process log instead, for Runtime startup or process-level failures.
-Project context resolution is owned by [`@hypit/project-context-node`](../project-context-node/README.md).
+Project context resolution is owned by [`@hypit/project`](../project/README.md).
History Source filters resolve existing filesystem links before comparing project-relative Result
paths. A deleted Source or directory remains queryable: only its existing ancestor is resolved and
the missing path suffix is retained. This is local argument handling, with no saved alias inventory.
CLI, Studio and creation tools call that same package; the CLI is not another environment owner.
`doctor`, `programs prepare|up|status|down`, and `runtime up` accept repeated `--endpoint <instance>` values.
-The same Endpoint scope reaches package preparation and Program operations. Omission means the whole
-Profile. Build preflight instead uses the Endpoints resolved for that Build's concrete requests.
+The same Endpoint scope reaches Program operations. Omission means the whole Profile. Build preflight
+instead uses the Endpoints resolved for that Build's concrete requests.
An unrelated offered capability does not add another credential or Program requirement.
Program rows show the configured Endpoint selector alongside an internal Program ID when they differ.
The `programs` JSON `ok` field reports whether this command succeeded; `ready` reports service
readiness for `up`/`status`, and preparation readiness for `prepare`. The latter does not start the
service. Successful stopping can therefore report `ok: true` with `ready: false`. A declined stop remains visible even
while the service is still preparing and cannot yet answer its health probe.
-
-Upstream package installation reports an `install.log` path at preparation time. Exact package
-releases coexist below the machine home, each with npm's own package.json and lockfile. `paths` shows
-the home; `packages status <name@version>` checks the requested release rather than a mutable latest copy.
diff --git a/packages/cli/package.json b/packages/cli/package.json
index 5f280c1d..17c3eba6 100644
--- a/packages/cli/package.json
+++ b/packages/cli/package.json
@@ -8,28 +8,24 @@
".": "./src/index.ts"
},
"dependencies": {
- "@hypit/build-result": "workspace:*",
- "@hypit/build-result-kit": "workspace:*",
- "@hypit/compiler-node": "workspace:*",
- "@hypit/component-kit": "workspace:*",
- "@hypit/core": "workspace:*",
- "@hypit/driver-node": "workspace:*",
- "@hypit/elaborator": "workspace:*",
- "@hypit/package-loader-node": "workspace:*",
- "@hypit/project-context-node": "workspace:*",
+ "@hypit/result": "workspace:*",
+ "@hypit/compiler": "workspace:*",
+ "@hypit/producer": "workspace:*",
+ "@hypit/kernel": "workspace:*",
+ "@hypit/executor": "workspace:*",
+ "@hypit/author": "workspace:*",
+ "@hypit/loader": "workspace:*",
+ "@hypit/project": "workspace:*",
"@hypit/protocol": "workspace:*",
"@hypit/run": "workspace:*",
"@hypit/runtime": "workspace:*",
- "@hypit/runtime-host-node": "workspace:*",
"@hypit/source": "workspace:*",
- "@hypit/validation": "workspace:*",
+ "@hypit/admission": "workspace:*",
"@hypit/workspace": "workspace:*",
"typescript": "5.9.3"
},
"devDependencies": {
- "@hypit/runtime-local": "workspace:*",
"@hypit/markup": "workspace:*",
- "@hypit/run-markup": "workspace:*",
- "@hypit/workspace-fs-node": "workspace:*"
+ "@hypit/runtime-local": "workspace:*"
}
}
diff --git a/packages/cli/src/application.ts b/packages/cli/src/application.ts
new file mode 100644
index 00000000..81bcd7f0
--- /dev/null
+++ b/packages/cli/src/application.ts
@@ -0,0 +1,132 @@
+import type { LoadedPackage } from "@hypit/loader";
+import { resolve } from "node:path";
+
+import { resolveProjectRoot as resolveMarkedProjectRoot } from "@hypit/project";
+
+import { genericCliCommandNames } from "./command.js";
+import type { CliDistribution } from "./distribution.js";
+import { runCli } from "./main.js";
+import { writeCliHelp } from "./output.js";
+import type { CliIo } from "./output.js";
+
+/**
+ * One explicitly trusted command surface selected by an application Distribution.
+ *
+ * Command modules are application assembly, not Source-package activation. Project
+ * packages never acquire CLI authority merely by being installed or imported.
+ */
+export type CliCommandModule = {
+ readonly format: "hypit.cli-command@1";
+ readonly id: string;
+ /** Root commands owned by this module. A root has exactly one owner. */
+ readonly commands: readonly string[];
+ /** Append this module's commands to the application-level help. */
+ writeRootHelp?(io: CliIo): void;
+ /** Render help for one of this module's roots. */
+ writeHelp(argv: readonly string[], io: CliIo): void | Promise<void>;
+ /** Execute one of this module's roots. */
+ run(argv: readonly string[], io: CliIo, context: CliApplicationContext): void | Promise<void>;
+};
+
+/** One immutable invocation context assembled by the executable application. */
+export type CliApplicationContext = {
+ readonly cwd: string;
+ readonly distribution: CliDistribution;
+ resolveProjectRoot(projectRoot?: string): Promise<string>;
+};
+
+/**
+ * Complete user-facing command application.
+ *
+ * CliDistribution supplies compilation/execution services. Command modules supply
+ * the chosen product surface. These axes stay separate so a video application can
+ * reuse the long-compilation CLI without moving frames or media into the Host.
+ */
+export type CliApplication = {
+ readonly distribution: CliDistribution;
+ readonly cwd?: string;
+ readonly resolveProjectRoot?: (projectRoot?: string) => Promise<string>;
+ readonly bootstrapPackages?: readonly LoadedPackage[];
+ readonly commandModules?: readonly CliCommandModule[];
+};
+
+export function indexCliCommandModules(
+ modules: readonly CliCommandModule[],
+): ReadonlyMap<string, CliCommandModule> {
+ const reserved = new Set<string>(["help", ...genericCliCommandNames]);
+ const result = new Map<string, CliCommandModule>();
+ for (const module of modules) {
+ if (module.format !== "hypit.cli-command@1") {
+ throw new Error(`CLI command module ${module.id || "<unknown>"} must use hypit.cli-command@1`);
+ }
+ if (module.id.trim().length === 0) throw new Error("CLI command module id cannot be empty");
+ if (module.commands.length === 0) throw new Error(`CLI command module ${module.id} owns no commands`);
+ for (const command of module.commands) {
+ if (command.length === 0 || command.startsWith("-")) {
+ throw new Error(`CLI command module ${module.id} declares invalid root ${JSON.stringify(command)}`);
+ }
+ if (reserved.has(command)) {
+ throw new Error(`CLI command module ${module.id} cannot replace generic command ${JSON.stringify(command)}`);
+ }
+ const existing = result.get(command);
+ if (existing !== undefined) {
+ throw new Error(`CLI command ${JSON.stringify(command)} is owned by both ${existing.id} and ${module.id}`);
+ }
+ result.set(command, module);
+ }
+ }
+ return result;
+}
+
+function helpArguments(argv: readonly string[]): readonly string[] {
+ const passthrough = argv.indexOf("--");
+ return passthrough < 0 ? argv : argv.slice(0, passthrough);
+}
+
+/** Run one statically assembled CLI application. No package scan or command auto-discovery occurs. */
+export async function runCliApplication(
+ argv: readonly string[],
+ io: CliIo,
+ application: CliApplication,
+): Promise<void> {
+ const cwd = resolve(application.cwd ?? process.cwd());
+ const context: CliApplicationContext = Object.freeze({
+ cwd,
+ distribution: application.distribution,
+ resolveProjectRoot: application.resolveProjectRoot
+ ?? (async (projectRoot?: string) => await resolveMarkedProjectRoot({
+ ...(projectRoot === undefined ? {} : { projectRoot }),
+ cwd,
+ })),
+ });
+ const modules = indexCliCommandModules(application.commandModules ?? []);
+ const visible = helpArguments(argv);
+ const asksForHelp = argv.length === 0 || argv[0] === "help" || visible.includes("--help");
+ if (asksForHelp) {
+ const topic = argv[0] === "help"
+ ? argv[1]
+ : argv[0] === "--help" || argv.length === 0 ? undefined : visible.includes("--help") ? argv[0] : undefined;
+ if (topic === undefined) {
+ writeCliHelp(io);
+ for (const module of application.commandModules ?? []) module.writeRootHelp?.(io);
+ return;
+ }
+ const module = modules.get(topic);
+ if (module !== undefined) {
+ await module.writeHelp(argv, io);
+ return;
+ }
+ writeCliHelp(io, topic);
+ return;
+ }
+
+ const module = modules.get(argv[0] ?? "");
+ if (module !== undefined) {
+ await module.run(argv, io, context);
+ return;
+ }
+ await runCli(argv, io, {
+ ...application.distribution,
+ bootstrapPackages: application.bootstrapPackages ?? application.distribution.bootstrapPackages,
+ }, context);
+}
diff --git a/packages/cli/src/arguments.ts b/packages/cli/src/arguments.ts
index 1fdc31da..d768e9a4 100644
--- a/packages/cli/src/arguments.ts
+++ b/packages/cli/src/arguments.ts
@@ -3,21 +3,17 @@ import { resolve } from "node:path";
import type {
AuthCommand,
CliCommand,
- EnvironmentCommand,
ExecutionCommand,
- ProgramsCommand,
ProjectOption,
ProjectResultCommand,
- RuntimeOperationCommand,
RuntimeOption,
- RuntimeSelectionCommand,
} from "./command.js";
import type { CliColorMode, CliOutputOptions } from "./output.js";
import { CliUsageError } from "./usage-error.js";
type RawOptions = {
readonly presentation: CliOutputOptions;
- readonly workspaceRoot?: string;
+ readonly projectRoot?: string;
readonly assetRoots: readonly string[];
readonly endpoints: readonly string[];
readonly packageRoot?: string;
@@ -36,9 +32,6 @@ type RawOptions = {
readonly before?: string;
readonly destination?: string;
readonly watch: boolean;
- readonly readyFile?: string;
- readonly workerOwner?: string;
- readonly executionRoot?: string;
readonly reason?: string;
readonly slot?: string;
readonly credentialFile?: string;
@@ -48,8 +41,8 @@ type RawOptions = {
const commonOptions = ["--json", "--color", "--no-color", "--verbose", "--debug"] as const;
-export function parseCommand(argv: readonly string[]): CliCommand {
- try { return parseArguments(argv); }
+export function parseCommand(argv: readonly string[], cwd = process.cwd()): CliCommand {
+ try { return parseArguments(argv, cwd); }
catch (error) {
if (error instanceof CliUsageError) throw error;
throw new CliUsageError(error instanceof Error ? error.message : String(error),
@@ -57,13 +50,13 @@ export function parseCommand(argv: readonly string[]): CliCommand {
}
}
-function parseArguments(argv: readonly string[]): CliCommand {
+function parseArguments(argv: readonly string[], cwd: string): CliCommand {
const [command, ...tail] = argv;
switch (command) {
case "check": {
const [source, rest] = requiredPositional(tail, "check requires one Source");
- const options = commandOptions(command, rest,
- "--package-root", "--workspace", "--asset-root", "--limit");
+ const options = commandOptions(command, rest, cwd,
+ "--package-root", "--project", "--asset-root", "--limit");
return {
command,
source,
@@ -77,8 +70,8 @@ function parseArguments(argv: readonly string[]): CliCommand {
case "plan":
case "pricing": {
const [source, rest] = requiredPositional(tail, `${command} requires one Source`);
- const options = commandOptions(command, rest,
- "--runtime", "--package-root", "--workspace", "--asset-root", "--limit");
+ const options = commandOptions(command, rest, cwd,
+ "--runtime", "--package-root", "--project", "--asset-root", "--limit");
if (command === "pricing") return {
command,
source,
@@ -102,8 +95,8 @@ function parseArguments(argv: readonly string[]): CliCommand {
}
case "build": {
const [source, rest] = requiredPositional(tail, "build requires one Run Source");
- const options = commandOptions(command, rest,
- "--runtime", "--package-root", "--workspace", "--asset-root", "--follow", "--max-wait-ms", "--title", "--limit");
+ const options = commandOptions(command, rest, cwd,
+ "--runtime", "--package-root", "--project", "--asset-root", "--follow", "--max-wait-ms", "--title", "--limit");
return {
command,
source,
@@ -119,7 +112,7 @@ function parseArguments(argv: readonly string[]): CliCommand {
};
}
case "builds": {
- const options = commandOptions(command, tail, "--workspace", "--limit", "--before");
+ const options = commandOptions(command, tail, cwd, "--project", "--limit", "--before");
return {
command,
presentation: options.presentation,
@@ -130,7 +123,7 @@ function parseArguments(argv: readonly string[]): CliCommand {
}
case "history": {
const [outputName, rest] = requiredPositional(tail, "history requires one exact Output name");
- const options = commandOptions(command, rest, "--workspace", "--source", "--limit", "--before");
+ const options = commandOptions(command, rest, cwd, "--project", "--source", "--limit", "--before");
return {
command,
outputName,
@@ -143,7 +136,7 @@ function parseArguments(argv: readonly string[]): CliCommand {
}
case "inspect": {
const [build, rest] = requiredPositional(tail, "inspect requires one Build id");
- const options = commandOptions(command, rest, "--workspace", "--output", "--limit");
+ const options = commandOptions(command, rest, cwd, "--project", "--output", "--limit");
return {
command,
build,
@@ -155,7 +148,7 @@ function parseArguments(argv: readonly string[]): CliCommand {
}
case "get": {
const [build, rest] = requiredPositional(tail, "get requires one Build id");
- const options = commandOptions(command, rest, "--workspace", "--output", "--to");
+ const options = commandOptions(command, rest, cwd, "--project", "--output", "--to");
if (options.outputName === undefined) throw new Error("get requires --output with one public Output name");
if (options.destination === undefined) throw new Error("get requires --to with the export destination");
return {
@@ -169,13 +162,13 @@ function parseArguments(argv: readonly string[]): CliCommand {
}
case "logs": {
const [build, rest] = requiredPositional(tail, "logs requires one Build id");
- const options = commandOptions(command, rest, "--runtime", "--workspace", "--lines");
+ const options = commandOptions(command, rest, cwd, "--runtime", "--project", "--lines");
return { command, build, lines: options.lines, presentation: options.presentation,
...optionalProject(options), ...optionalRuntime(options) };
}
case "status": {
const [build, rest] = requiredPositional(tail, "status requires one Build id");
- const options = commandOptions(command, rest, "--runtime", "--workspace", "--watch", "--max-wait-ms", "--limit");
+ const options = commandOptions(command, rest, cwd, "--runtime", "--project", "--watch", "--max-wait-ms", "--limit");
if (!options.watch && options.maxWaitMs !== undefined) {
throw new Error("--max-wait-ms applies to status --watch");
}
@@ -190,7 +183,7 @@ function parseArguments(argv: readonly string[]): CliCommand {
};
}
case "activity": {
- const options = commandOptions(command, tail, "--runtime", "--workspace", "--watch", "--jsonl", "--limit");
+ const options = commandOptions(command, tail, cwd, "--runtime", "--project", "--watch", "--jsonl", "--limit");
if (options.presentation.jsonl === true && !options.watch) {
throw new Error("--jsonl applies only to activity --watch");
}
@@ -207,7 +200,7 @@ function parseArguments(argv: readonly string[]): CliCommand {
}
case "cancel": {
const [build, rest] = requiredPositional(tail, "cancel requires one Build id");
- const options = commandOptions(command, rest, "--runtime", "--workspace", "--reason");
+ const options = commandOptions(command, rest, cwd, "--runtime", "--project", "--reason");
return {
command,
build,
@@ -216,14 +209,11 @@ function parseArguments(argv: readonly string[]): CliCommand {
...(options.reason === undefined ? {} : { reason: options.reason }),
};
}
- case "result": return parseResultCommand(tail);
- case "runtime": return parseRuntimeCommand(tail);
- case "programs": return parseProgramsCommand(tail);
- case "packages": return parsePackagesCommand(tail);
- case "auth": return parseAuthCommand(tail);
+ case "result": return parseResultCommand(tail, cwd);
+ case "auth": return parseAuthCommand(tail, cwd);
case "doctor": {
const [profile, rest] = optionalPositional(tail);
- const options = commandOptions(command, rest, "--workspace", "--runtime", "--limit", "--endpoint");
+ const options = commandOptions(command, rest, cwd, "--project", "--runtime", "--limit", "--endpoint");
if (profile !== undefined && options.runtimeProfile !== undefined) {
throw new Error("doctor accepts the Runtime Profile either positionally or with --runtime, not both");
}
@@ -236,43 +226,23 @@ function parseArguments(argv: readonly string[]): CliCommand {
...runtimeOption(profile ?? options.runtimeProfile),
};
}
- case "paths": {
- const options = commandOptions(command, tail, "--runtime", "--workspace");
- return { command, presentation: options.presentation, ...optionalRuntime(options) };
- }
- case "_worker": {
- const [profile, rest] = requiredPositional(tail, "internal Worker launch is incomplete");
- const options = commandOptions(command, rest, "--ready-file", "--worker-owner", "--package-root", "--execution-root");
- if (options.readyFile === undefined || options.workerOwner === undefined) {
- throw new Error("internal Worker launch is incomplete");
- }
- return {
- command,
- profile,
- readyFile: options.readyFile,
- workerOwner: options.workerOwner,
- ...(options.executionRoot === undefined ? {} : { executionRoot: options.executionRoot }),
- presentation: options.presentation,
- ...optionalPackageRoot(options),
- };
- }
default: throw new CliUsageError(command === undefined ? "A command is required"
: `Unknown command ${JSON.stringify(command)}`, "hypit help");
}
}
-function parseResultCommand(tail: readonly string[]): ProjectResultCommand | ExecutionCommand {
+function parseResultCommand(tail: readonly string[], cwd: string): ProjectResultCommand | ExecutionCommand {
const [action, ...values] = tail;
if (action !== "finish" && action !== "discard" && action !== "edit") {
throw new Error("result accepts finish, discard or edit");
}
const [build, rest] = requiredPositional(values, `result ${action} requires one Build id`);
if (action === "finish" || action === "discard") {
- const options = commandOptions(`result ${action}`, rest, "--runtime", "--workspace");
+ const options = commandOptions(`result ${action}`, rest, cwd, "--runtime", "--project");
return { command: "result", action, build, presentation: options.presentation, ...optionalRuntime(options) };
}
- const options = commandOptions("result edit", rest,
- "--workspace", "--title", "--note", "--highlight", "--clear-title", "--clear-note", "--clear-highlights", "--limit");
+ const options = commandOptions("result edit", rest, cwd,
+ "--project", "--title", "--note", "--highlight", "--clear-title", "--clear-note", "--clear-highlights", "--limit");
if (options.title !== undefined && options.clearTitle) throw new Error("--title and --clear-title are mutually exclusive");
if (options.note !== undefined && options.clearNote) throw new Error("--note and --clear-note are mutually exclusive");
if (options.highlightedOutputs.length > 0 && options.clearHighlights) {
@@ -298,98 +268,14 @@ function parseResultCommand(tail: readonly string[]): ProjectResultCommand | Exe
};
}
-function parseRuntimeCommand(tail: readonly string[]): RuntimeSelectionCommand | RuntimeOperationCommand {
- const [action, ...values] = tail;
- if (action !== "init" && action !== "use" && action !== "unset" && action !== "up" && action !== "down"
- && action !== "status" && action !== "logs") {
- throw new Error("runtime takes init, use, unset, up, down, status or logs");
- }
- if (action === "init") {
- const [profile, rest] = optionalPositional(values);
- const options = commandOptions("runtime init", rest, "--workspace");
- return {
- command: "runtime",
- action,
- presentation: options.presentation,
- ...optionalProject(options),
- ...(profile === undefined ? {} : { profile }),
- };
- }
- if (action === "use") {
- const [profile, rest] = requiredPositional(values, "runtime use requires a Runtime Profile");
- const options = commandOptions("runtime use", rest, "--workspace");
- return { command: "runtime", action, profile, presentation: options.presentation, ...optionalProject(options) };
- }
- if (action === "unset") {
- const options = commandOptions("runtime unset", values, "--workspace");
- return { command: "runtime", action, presentation: options.presentation, ...optionalProject(options) };
- }
- const [profile, rest] = optionalPositional(values);
- const allowed = action === "up" || action === "down"
- ? action === "up" ? ["--runtime", "--max-wait-ms", "--endpoint"] as const : ["--runtime", "--max-wait-ms"] as const
- : action === "status"
- ? ["--runtime", "--limit"] as const
- : ["--runtime", "--lines"] as const;
- const options = commandOptions(`runtime ${action}`, rest, "--workspace", ...allowed);
- rejectDuplicateProfile("runtime", profile, options.runtimeProfile);
- const runtime = runtimeOption(profile ?? options.runtimeProfile);
- const common = {
- command: "runtime" as const,
- action,
- presentation: options.presentation,
- ...runtime,
- ...optionalProject(options),
- };
- if (action === "up" || action === "down") {
- return { ...common, action, ...(action === "up" && options.endpoints.length > 0 ? { endpoints: options.endpoints } : {}), ...(options.maxWaitMs === undefined ? {} : { maxWaitMs: options.maxWaitMs }) };
- }
- if (action === "status") return { ...common, action, limit: options.limit };
- return { ...common, action, lines: options.lines };
-}
-
-function parseProgramsCommand(tail: readonly string[]): ProgramsCommand {
- const [action, ...values] = tail;
- if (action !== "prepare" && action !== "up" && action !== "down" && action !== "status") {
- throw new Error("programs takes prepare, up, down or status");
- }
- const [profile, rest] = optionalPositional(values);
- const options = commandOptions(`programs ${action}`, rest,
- "--runtime", "--workspace", "--limit", "--max-wait-ms", "--endpoint");
- if (action !== "up" && options.maxWaitMs !== undefined) {
- throw new Error("--max-wait-ms applies to programs up");
- }
- rejectDuplicateProfile("programs", profile, options.runtimeProfile);
- const runtime = runtimeOption(profile ?? options.runtimeProfile);
- const common = {
- command: "programs" as const,
- ...(options.endpoints.length === 0 ? {} : { endpoints: options.endpoints }),
- action,
- presentation: options.presentation,
- limit: options.limit,
- ...runtime,
- ...optionalProject(options),
- };
- return action === "up"
- ? { ...common, action, ...(options.maxWaitMs === undefined ? {} : { maxWaitMs: options.maxWaitMs }) }
- : { ...common, action };
-}
-
-function parsePackagesCommand(tail: readonly string[]): EnvironmentCommand {
- const [action, ...values] = tail;
- if (action !== "install" && action !== "status") throw new Error("packages takes install or status");
- const [specifier, rest] = requiredPositional(values, `packages ${action} requires package@exact-version`);
- const options = commandOptions(`packages ${action}`, rest);
- return { command: "packages", action, package: specifier, presentation: options.presentation };
-}
-
-function parseAuthCommand(tail: readonly string[]): AuthCommand {
+function parseAuthCommand(tail: readonly string[], cwd: string): AuthCommand {
const [action, ...values] = tail;
if (action !== "status" && action !== "login" && action !== "logout") {
throw new Error("auth takes status, login or logout");
}
const [endpoint, rest] = requiredPositional(values, `auth ${action} requires one Endpoint instance`);
- const options = commandOptions(`auth ${action}`, rest,
- "--runtime", "--workspace", "--slot", ...(action === "login" ? ["--from"] as const : []),
+ const options = commandOptions(`auth ${action}`, rest, cwd,
+ "--runtime", "--project", "--slot", ...(action === "login" ? ["--from"] as const : []),
...(action === "status" ? ["--limit"] as const : []));
const common = {
command: "auth" as const,
@@ -410,16 +296,16 @@ function parseAuthCommand(tail: readonly string[]): AuthCommand {
return { ...common, action };
}
-function commandOptions(label: string, values: readonly string[], ...allowed: readonly string[]): RawOptions {
- const options = parseOptions(values);
+function commandOptions(label: string, values: readonly string[], cwd: string, ...allowed: readonly string[]): RawOptions {
+ const options = parseOptions(values, cwd);
const accepted = new Set<string>([...commonOptions, ...allowed]);
const invalid = options.seenOptions.find((item) => !accepted.has(item));
if (invalid !== undefined) throw new Error(`${invalid} does not apply to ${label}`);
return options;
}
-function parseOptions(values: readonly string[]): RawOptions {
- let workspaceRoot: string | undefined;
+function parseOptions(values: readonly string[], cwd: string): RawOptions {
+ let projectRoot: string | undefined;
const assetRoots: string[] = [];
let packageRoot: string | undefined;
let runtimeProfile: string | undefined;
@@ -442,9 +328,6 @@ function parseOptions(values: readonly string[]): RawOptions {
let color: CliColorMode = "auto";
let verbose = false;
let watch = false;
- let readyFile: string | undefined;
- let workerOwner: string | undefined;
- let executionRoot: string | undefined;
let reason: string | undefined;
let slot: string | undefined;
let credentialFile: string | undefined;
@@ -475,17 +358,17 @@ function parseOptions(values: readonly string[]): RawOptions {
continue;
}
if (item === "--endpoint") { endpoints.push(optionValue(values, index, "--endpoint requires an Endpoint name")); index += 1; continue; }
- if (item === "--workspace") {
- workspaceRoot = resolve(optionValue(values, index, "--workspace requires a directory")); index += 1; continue;
+ if (item === "--project") {
+ projectRoot = resolve(cwd, optionValue(values, index, "--project requires a directory")); index += 1; continue;
}
if (item === "--asset-root") {
- assetRoots.push(resolve(optionValue(values, index, "--asset-root requires a directory"))); index += 1; continue;
+ assetRoots.push(resolve(cwd, optionValue(values, index, "--asset-root requires a directory"))); index += 1; continue;
}
if (item === "--package-root") {
- packageRoot = resolve(optionValue(values, index, "--package-root requires a directory")); index += 1; continue;
+ packageRoot = resolve(cwd, optionValue(values, index, "--package-root requires a directory")); index += 1; continue;
}
if (item === "--runtime") {
- runtimeProfile = resolve(optionValue(values, index, "--runtime requires a Runtime Profile")); index += 1; continue;
+ runtimeProfile = resolve(cwd, optionValue(values, index, "--runtime requires a Runtime Profile")); index += 1; continue;
}
if (item === "--out") {
throw new Error("--out does not apply to Build submission; use `get <build-id> --output <name> --to <path>` to export one Result Output");
@@ -517,7 +400,7 @@ function parseOptions(values: readonly string[]): RawOptions {
before = optionValue(values, index, "--before requires a Build id"); index += 1; continue;
}
if (item === "--to") {
- destination = resolve(optionValue(values, index, "--to requires a file path")); index += 1; continue;
+ destination = resolve(cwd, optionValue(values, index, "--to requires a file path")); index += 1; continue;
}
if (item === "--follow") { follow = true; continue; }
if (item === "--max-wait-ms") {
@@ -525,15 +408,6 @@ function parseOptions(values: readonly string[]): RawOptions {
if (!Number.isSafeInteger(value) || value < 0) throw new Error("--max-wait-ms must be a non-negative safe integer");
maxWaitMs = value; index += 1; continue;
}
- if (item === "--ready-file") {
- readyFile = resolve(optionValue(values, index, "--ready-file requires a path")); index += 1; continue;
- }
- if (item === "--worker-owner") {
- workerOwner = optionValue(values, index, "--worker-owner requires an identity"); index += 1; continue;
- }
- if (item === "--execution-root") {
- executionRoot = resolve(optionValue(values, index, "--execution-root requires a path")); index += 1; continue;
- }
if (item === "--reason") {
reason = optionValue(values, index, "--reason requires text"); index += 1; continue;
}
@@ -541,10 +415,10 @@ function parseOptions(values: readonly string[]): RawOptions {
slot = optionValue(values, index, "--slot requires a credential slot"); index += 1; continue;
}
if (item === "--from") {
- credentialFile = resolve(optionValue(values, index, "--from requires a credential file")); index += 1; continue;
+ credentialFile = resolve(cwd, optionValue(values, index, "--from requires a credential file")); index += 1; continue;
}
if (item === "--source") {
- source = resolve(optionValue(values, index, "--source requires a source path")); index += 1; continue;
+ source = resolve(cwd, optionValue(values, index, "--source requires a source path")); index += 1; continue;
}
throw new Error(`unknown option ${item}`);
}
@@ -564,7 +438,7 @@ function parseOptions(values: readonly string[]): RawOptions {
lines,
watch,
seenOptions: [...seenOptions],
- ...(workspaceRoot === undefined ? {} : { workspaceRoot }),
+ ...(projectRoot === undefined ? {} : { projectRoot }),
...(packageRoot === undefined ? {} : { packageRoot }),
...(runtimeProfile === undefined ? {} : { runtimeProfile }),
...(maxWaitMs === undefined ? {} : { maxWaitMs }),
@@ -573,9 +447,6 @@ function parseOptions(values: readonly string[]): RawOptions {
...(note === undefined ? {} : { note }),
...(before === undefined ? {} : { before }),
...(destination === undefined ? {} : { destination }),
- ...(readyFile === undefined ? {} : { readyFile }),
- ...(workerOwner === undefined ? {} : { workerOwner }),
- ...(executionRoot === undefined ? {} : { executionRoot }),
...(reason === undefined ? {} : { reason }),
...(slot === undefined ? {} : { slot }),
...(credentialFile === undefined ? {} : { credentialFile }),
@@ -607,7 +478,7 @@ function positiveInteger(value: string, option: string): number {
}
function optionalProject(options: RawOptions): ProjectOption {
- return options.workspaceRoot === undefined ? {} : { workspaceRoot: options.workspaceRoot };
+ return options.projectRoot === undefined ? {} : { projectRoot: options.projectRoot };
}
function optionalRuntime(options: RawOptions): RuntimeOption {
diff --git a/packages/cli/src/build-planning.ts b/packages/cli/src/build-planning.ts
index a678a930..9aa1f261 100644
--- a/packages/cli/src/build-planning.ts
+++ b/packages/cli/src/build-planning.ts
@@ -1,26 +1,32 @@
import { resolve } from "node:path";
-import type { NodeCompiledSourceClosure } from "@hypit/compiler-node";
-import { registerProducerFacets, registerTypeValidatorFacets } from "@hypit/component-kit";
+import type { CompiledAuthorSource } from "@hypit/compiler";
+import {
+ producerPackagesFromFacets,
+ registerProducerFacets,
+} from "@hypit/producer";
import type {
PlannedNeedFacet,
PlannedNeedPresentation,
PlannedNeedSpecification,
-} from "@hypit/component-kit";
-import { evaluateProducerPlan, ProducerRegistry } from "@hypit/driver-node";
-import type { NodePackageContribution } from "@hypit/package-loader-node";
+} from "@hypit/producer";
+import { evaluateProducerPlan, ProducerRegistry } from "@hypit/executor";
+import type { PackageContribution } from "@hypit/loader";
import type { BuildDefinition, BuildState, CanonicalValue, CapabilityRef } from "@hypit/protocol";
-import type { NodeRuntimeHost } from "@hypit/runtime-host-node";
-import { plannedNeeds } from "@hypit/runtime";
-import type { BuildCatalogDescriptor } from "@hypit/runtime";
-import { TypeValidatorRegistry } from "@hypit/validation";
+import type { CliBuildCatalogDescriptor, CliProviderQuery, CliRuntimeHost } from "./runtime-port.js";
+import { plannedNeeds } from "@hypit/kernel";
+import {
+ admissionPackagesFromFacets,
+ registerTypeValidatorFacets,
+ TypeValidatorRegistry,
+} from "@hypit/admission";
export function createCatalogDescriptor(options: {
readonly source: string;
- readonly compilation: NodeCompiledSourceClosure;
+ readonly compilation: CompiledAuthorSource;
readonly run?: { readonly path: string };
readonly targets?: readonly { readonly output: string }[];
-}): BuildCatalogDescriptor {
+}): CliBuildCatalogDescriptor {
const publishedOutputs = options.compilation.exports.flatMap((item) => {
if (item.ref.kind === "operation-result") {
throw new Error(`public output ${item.name} was not lowered to a stable Record or Logical Output`);
@@ -125,6 +131,11 @@ export type EvaluatedPlanNeed = {
export type EvaluatedPlan = {
readonly state: BuildState;
readonly needs: ReadonlyMap<string, EvaluatedPlanNeed>;
+ /** Every deterministic Producer failure, independent of whether that Step declares a Need. */
+ readonly producerFailures: readonly {
+ readonly step: string;
+ readonly message: string;
+ }[];
};
export type PlanNeedView = {
@@ -210,9 +221,9 @@ function summarizePresentation(presentation: PlannedNeedPresentation): NeedSumma
return { fields, references: structuredClone(presentation.references) };
}
-function plannedNeedFacets(contributions: readonly NodePackageContribution[]): readonly PlannedNeedFacet[] {
+function plannedNeedFacets(contributions: readonly PackageContribution[]): readonly PlannedNeedFacet[] {
return contributions.flatMap((contribution) =>
- (contribution.components ?? []).flatMap((component) => component.plannedNeeds ?? []));
+ producerPackagesFromFacets(contribution.facets ?? []).flatMap((item) => item.plannedNeeds ?? []));
}
function plannedNeedFacetFor(
@@ -235,14 +246,17 @@ function plannedNeedFacetFor(
*/
export async function evaluatePlanNeeds(
definition: BuildDefinition,
- contributions: readonly NodePackageContribution[],
+ contributions: readonly PackageContribution[],
): Promise<EvaluatedPlan> {
const producers = new ProducerRegistry();
const validators = new TypeValidatorRegistry();
for (const contribution of contributions) {
- for (const component of contribution.components ?? []) {
- registerProducerFacets(producers, component.producers ?? []);
- registerTypeValidatorFacets(validators, component.validators ?? []);
+ const facets = contribution.facets ?? [];
+ for (const item of producerPackagesFromFacets(facets)) {
+ registerProducerFacets(producers, item.producers ?? []);
+ }
+ for (const item of admissionPackagesFromFacets(facets)) {
+ registerTypeValidatorFacets(validators, item.validators ?? []);
}
}
const evaluation = await evaluateProducerPlan(definition, producers, validators);
@@ -280,7 +294,6 @@ export async function evaluatePlanNeeds(
kind: item.role === "image" || item.role === "video" || item.role === "audio" ? item.role : "other",
}),
}));
- const issue = evaluation.failures.get(planned.step);
result.set(planned.need, {
constraints: specification.constraints,
pendingInputs: specification.pendingInputs,
@@ -288,7 +301,6 @@ export async function evaluatePlanNeeds(
? summarizeConstraints(specification.constraints)
: summarizePresentation(facet.present(specification)),
pending,
- ...(issue === undefined ? {} : { issue }),
});
continue;
}
@@ -300,23 +312,24 @@ export async function evaluatePlanNeeds(
const sourceStep = producedBy.get(record);
return { input, record, ...(sourceStep === undefined ? {} : { sourceStep }) };
});
- const issue = evaluation.failures.get(planned.step);
result.set(planned.need, {
pendingInputs: [],
pending,
- issue: issue === undefined
- ? `Package does not describe the complete request for ${capabilityName(planned.capability)} before Build`
- : `${issue}; package also does not describe the complete request for ${capabilityName(planned.capability)} before Build`,
+ issue: `Package does not describe the complete request for ${capabilityName(planned.capability)} before Build`,
});
}
- return { state, needs: result };
+ return {
+ state,
+ needs: result,
+ producerFailures: [...evaluation.failures].map(([step, message]) => ({ step, message })),
+ };
}
/** The complete pre-Build requests shared by Endpoint selection and Provider pricing reads. */
export function plannedProviderQueries(
state: BuildState,
evaluated: EvaluatedPlan,
-): readonly import("@hypit/runtime-host-node").RuntimeHostProviderQuery[] {
+): readonly CliProviderQuery[] {
const planned = plannedNeeds(state);
return planned.flatMap((item) => {
const plannedRequest = evaluated.needs.get(item.need);
@@ -339,7 +352,7 @@ export function plannedProviderQueries(
/** Resolve every planned request independently; concrete constraints exercise Endpoint `supports`. */
export async function describePlanProviders(
- host: NodeRuntimeHost,
+ host: CliRuntimeHost,
state: BuildState,
evaluated: EvaluatedPlan,
): Promise<readonly PlanProviderView[]> {
@@ -365,7 +378,7 @@ export async function describePlanProviders(
/** Read Provider-owned pricing material relevant to each planned request. */
export async function describePlanPricing(
- host: NodeRuntimeHost,
+ host: CliRuntimeHost,
state: BuildState,
evaluated: EvaluatedPlan,
): Promise<readonly PlanPricingView[]> {
@@ -425,7 +438,7 @@ export function assertPlannedRequests(
}
}
-export async function preflightPlan(host: NodeRuntimeHost, state: BuildState, providers: readonly PlanProviderView[]) {
+export async function preflightPlan(host: CliRuntimeHost, state: BuildState, providers: readonly PlanProviderView[]) {
const capabilities = demandedCapabilities(state);
const endpoints = [...new Set(providers.flatMap((item) => item.status === "resolved" && item.endpoint !== undefined ? [item.endpoint] : []))];
const result = await host.preflight({ endpoints });
diff --git a/packages/cli/src/command-hint.ts b/packages/cli/src/command-hint.ts
index dce4305d..a73fb559 100644
--- a/packages/cli/src/command-hint.ts
+++ b/packages/cli/src/command-hint.ts
@@ -14,7 +14,7 @@ export function commandHint(
? value
: `'${value.replaceAll("'", shell === "powershell" ? "''" : "'\"'\"'")}'`;
return ["hypit", ...args,
- ...(scope.projectRoot === undefined ? [] : ["--workspace", scope.projectRoot]),
+ ...(scope.projectRoot === undefined ? [] : ["--project", scope.projectRoot]),
...(scope.runtimeProfile === undefined ? [] : ["--runtime", scope.runtimeProfile]),
].map(quote).join(" ");
}
diff --git a/packages/cli/src/command.ts b/packages/cli/src/command.ts
index ed116428..7d9025f3 100644
--- a/packages/cli/src/command.ts
+++ b/packages/cli/src/command.ts
@@ -1,5 +1,32 @@
import type { CliOutputOptions } from "./output.js";
+/**
+ * Root command names owned by the domain-neutral long-compilation CLI.
+ *
+ * Application command modules may add other roots, but cannot shadow these.
+ * Keeping the names beside the command union makes command ownership explicit
+ * without teaching Core or the package loader about CLI presentation.
+ */
+export const genericCliCommandNames = [
+ "version",
+ "cli",
+ "check",
+ "plan",
+ "pricing",
+ "build",
+ "builds",
+ "history",
+ "inspect",
+ "get",
+ "logs",
+ "status",
+ "activity",
+ "cancel",
+ "result",
+ "auth",
+ "doctor",
+] as const;
+
type CommandBase = {
readonly presentation: CliOutputOptions;
};
@@ -9,7 +36,7 @@ export type RuntimeOption = ProjectOption & {
};
export type ProjectOption = {
- readonly workspaceRoot?: string;
+ readonly projectRoot?: string;
};
type SourceOptions = ProjectOption & {
@@ -96,60 +123,6 @@ export type ExecutionCommand =
readonly build: string;
});
-export type RuntimeSelectionCommand =
- | (CommandBase & ProjectOption & {
- readonly command: "runtime";
- readonly action: "init";
- readonly profile?: string;
- })
- | (CommandBase & ProjectOption & {
- readonly command: "runtime";
- readonly action: "use";
- readonly profile: string;
- })
- | (CommandBase & ProjectOption & {
- readonly command: "runtime";
- readonly action: "unset";
- });
-
-export type RuntimeOperationCommand =
- | (CommandBase & RuntimeOption & {
- readonly command: "runtime";
- readonly action: "up";
- readonly endpoints?: readonly string[];
- readonly maxWaitMs?: number;
- })
- | (CommandBase & RuntimeOption & {
- readonly command: "runtime";
- readonly action: "down";
- readonly maxWaitMs?: number;
- })
- | (CommandBase & RuntimeOption & {
- readonly command: "runtime";
- readonly action: "status";
- readonly limit: number;
- })
- | (CommandBase & RuntimeOption & {
- readonly command: "runtime";
- readonly action: "logs";
- readonly lines: number;
- });
-
-export type ProgramsCommand =
- | (CommandBase & RuntimeOption & {
- readonly command: "programs";
- readonly endpoints?: readonly string[];
- readonly action: "up";
- readonly maxWaitMs?: number;
- readonly limit: number;
- })
- | (CommandBase & RuntimeOption & {
- readonly command: "programs";
- readonly endpoints?: readonly string[];
- readonly action: "prepare" | "down" | "status";
- readonly limit: number;
- });
-
export type AuthCommand =
| (CommandBase & RuntimeOption & {
readonly command: "auth";
@@ -173,36 +146,16 @@ export type AuthCommand =
});
export type EnvironmentCommand =
- | RuntimeOperationCommand
- | ProgramsCommand
| AuthCommand
- | (CommandBase & RuntimeOption & {
- readonly command: "paths";
- })
- | (CommandBase & {
- readonly command: "packages";
- readonly action: "install" | "status";
- readonly package: string;
- })
| (CommandBase & ProjectOption & RuntimeOption & {
readonly command: "doctor";
readonly endpoints?: readonly string[];
readonly limit: number;
});
-export type WorkerCommand = CommandBase & {
- readonly command: "_worker";
- readonly profile: string;
- readonly readyFile: string;
- readonly workerOwner: string;
- readonly executionRoot?: string;
- readonly packageRoot?: string;
-};
-
export type CliCommand =
| AuthorCommand
| ProjectResultCommand
| ExecutionCommand
- | RuntimeSelectionCommand
| EnvironmentCommand
- | WorkerCommand;
+ ;
diff --git a/packages/cli/src/commands/environment.ts b/packages/cli/src/commands/environment.ts
index e6751aff..f9f5ec60 100644
--- a/packages/cli/src/commands/environment.ts
+++ b/packages/cli/src/commands/environment.ts
@@ -1,235 +1,38 @@
import { readFile } from "node:fs/promises";
-import { join, resolve } from "node:path";
-
-import { distributionPackageDeclaring, locateNodePackage } from "@hypit/package-loader-node";
-import type { NodeRuntimeHost } from "@hypit/runtime-host-node";
-import { hypitHostPackageRoot, inspectHostPackage, parseRegistryPackageSpec, prepareHostPackages } from "@hypit/runtime-host-node";
+import { resolve } from "node:path";
import type { CliCommand, EnvironmentCommand } from "../command.js";
-import { commandHint } from "../command-hint.js";
import type { CliDistribution } from "../distribution.js";
import { acquireOAuthCredential } from "../oauth.js";
import { writeCliOutput } from "../output.js";
import type { CliIo } from "../output.js";
-import { hypitHostStateRoot, hypitProjectStateRoot } from "../paths.js";
-import type { CliManagedProgramProgress, CliManagedProgramReport, CliRuntimeController } from "../runtime-port.js";
+import type { CliRuntimeHost } from "../runtime-port.js";
import type { OperationalWriter } from "./types.js";
-type PackageStatus = {
- readonly ready: boolean;
- readonly declaredBy?: string;
- readonly installation?: string;
- readonly installedVersion?: string;
- readonly detail?: string;
-};
-
-/**
- * Whether `specifier` will resolve when a Build needs it.
- *
- * The loader finds an external package in two places — the node_modules chain above whoever
- * requires it, and the machine home addressed by the version that requirer declares — and both
- * start from the requiring package. So the requirer is located first and the loader asked once,
- * rather than reimplementing either half here: a second opinion is exactly how this command came
- * to disagree with the thing it reports on.
- *
- * Without a Distribution on disk there is no requirer to find, and the machine home remains the
- * only place this command can speak about.
- */
-async function packageStatus(
- specifier: string,
- hostRoot: string,
- distributionRoot: string | undefined,
-): Promise<PackageStatus> {
- const required = parseRegistryPackageSpec(specifier);
- if (distributionRoot === undefined) {
- const existing = await inspectHostPackage(specifier, hostRoot);
- return existing === undefined
- ? { ready: false, detail: "not installed in the machine package home" }
- : { ready: true, installation: existing.root, installedVersion: required.version };
- }
- const declaring = distributionPackageDeclaring(distributionRoot, required.name, required.version);
- if (declaring === undefined) {
- return { ready: false, detail: `no Distribution package declares ${specifier}` };
- }
- try {
- const located = locateNodePackage(required.name, {
- from: join(declaring, "__hypit_package_status__.mjs"),
- distributionRoots: [distributionRoot],
- externalRoots: [hostRoot],
- allowExternal: true,
- });
- const installed = located.manifest.version;
- return installed === required.version
- ? { ready: true, declaredBy: declaring, installation: located.root, installedVersion: installed }
- : {
- ready: false,
- declaredBy: declaring,
- installation: located.root,
- ...(installed === undefined ? {} : { installedVersion: installed }),
- detail: `resolved version is ${installed ?? "unknown"}`,
- };
- } catch (error) {
- return {
- ready: false,
- declaredBy: declaring,
- detail: error instanceof Error ? error.message : String(error),
- };
- }
-}
-
-function programRecord(item: CliManagedProgramReport) {
- return {
- ...item,
- state: item.state.state,
- ...(item.state.state === "ready" ? {} : { stateDetail: item.state.detail }),
- };
-}
-
-function programDescription(item: CliManagedProgramReport): string {
- const details = [...new Set([
- ...(item.state.state === "ready" ? [] : [item.state.detail]),
- ...(item.detail === undefined ? [] : [item.detail]),
- ])];
- return `${item.id}: ${item.state.state}${details.length === 0 ? "" : ` — ${details.join("; ")}`}`
- + (item.endpoint === item.id ? "" : ` · endpoint ${item.endpoint}`)
- + (item.pid === undefined ? "" : ` · PID ${item.pid}`)
- + (item.logPath === undefined ? "" : ` · log ${item.logPath}`)
- + (item.installationLogPath === undefined || item.installationLogPath === item.logPath
- ? "" : ` · installation log ${item.installationLogPath}`)
- + (item.errorLogPath === undefined ? "" : ` · stderr ${item.errorLogPath}`);
-}
-
export function isEnvironmentCommand(args: CliCommand): args is EnvironmentCommand {
- return args.command === "paths" || args.command === "packages" || args.command === "doctor"
- || args.command === "programs" || args.command === "auth"
- || (args.command === "runtime"
- && (args.action === "up" || args.action === "down" || args.action === "status" || args.action === "logs"));
+ return args.command === "doctor" || args.command === "auth";
}
export async function runEnvironmentCommand(input: {
readonly args: EnvironmentCommand;
readonly runtimeProfile: string | undefined;
- readonly runtimeSelectionFile: string | undefined;
+ readonly runtimeFromProject: boolean;
readonly io: CliIo;
readonly distribution: CliDistribution;
readonly projectRoot: string;
readonly packageRootForProject: () => Promise<string>;
- readonly runtimeHost: (profile: string, packageRoot?: string) => Promise<NodeRuntimeHost>;
- readonly runtimeController: (profile: string) => Promise<CliRuntimeController>;
+ readonly runtimeHost: (profile: string, packageRoot?: string) => Promise<CliRuntimeHost>;
readonly write: OperationalWriter;
}): Promise<void> {
const {
- args, runtimeProfile, runtimeSelectionFile, io, distribution, projectRoot, packageRootForProject, runtimeHost, runtimeController, write,
+ args, runtimeProfile, runtimeFromProject, io, distribution, projectRoot, packageRootForProject, runtimeHost, write,
} = input;
const profileSource: "none" | "argument" | "project" = runtimeProfile === undefined
- ? "none" : runtimeSelectionFile === undefined ? "argument" : "project";
- const selectionDescription = profileSource === "argument"
- ? "command argument (this invocation only)"
- : runtimeSelectionFile ?? "none";
- const progressWriter = args.presentation.json ? io.writeProgress : io.writeProgress ?? io.write;
- const reportProgramProgress = progressWriter === undefined
- ? undefined
- : (event: CliManagedProgramProgress): void => {
- if (!args.presentation.verbose && event.detail === undefined && event.phase !== "installing" && event.phase !== "starting") return;
- const verb = {
- checking: "Checking",
- installing: "Installing",
- starting: "Starting",
- waiting: "Waiting for",
- ready: "Ready",
- }[event.phase];
- progressWriter(` · ${verb} ${event.id}${event.detail === undefined ? "" : ` — ${event.detail}`}${event.logPath === undefined ? "" : ` · log ${event.logPath}`}\n`);
- };
- const reportPackageProgress = progressWriter === undefined
- ? undefined
- : (event: { readonly specifier: string; readonly phase: "checking" | "installing" | "ready"; readonly logPath?: string }): void => {
- if (event.phase === "installing") progressWriter(` · Installing ${event.specifier}${event.logPath === undefined ? "" : ` · log ${event.logPath}`}\n`);
- };
+ ? "none" : runtimeFromProject ? "project" : "argument";
const reportCredentialProgress = args.presentation.json
? io.writeProgress
: io.writeProgress ?? io.write;
- if (args.command === "paths") {
- const runtimePaths = runtimeProfile === undefined
- ? undefined
- : await (await runtimeHost(runtimeProfile)).resolvePaths();
- const machine = {
- format: "hypit.cli-paths@1" as const,
- project: projectRoot,
- profileSource,
- selectionFile: resolve(projectRoot, ".hypit/runtime"),
- projectState: hypitProjectStateRoot(projectRoot),
- ...(runtimeProfile === undefined ? {} : { profile: runtimeProfile }),
- ...(runtimePaths === undefined ? {} : { runtimeData: runtimePaths.runtimeDataRoot }),
- hostState: hypitHostStateRoot(),
- machinePackages: hypitHostPackageRoot(),
- ...(distribution.packageRoot === undefined ? {} : { distribution: distribution.packageRoot }),
- };
- write(machine, "Hypit paths", "info", [
- ["Project", machine.project],
- ["Project state", machine.projectState],
- ["Runtime Profile", machine.profile ?? "not selected"],
- ["Runtime selection", selectionDescription],
- ["Runtime data", machine.runtimeData ?? "not selected"],
- ["Host state", machine.hostState],
- ["Machine packages", machine.machinePackages],
- ["Distribution", machine.distribution ?? "embedded"],
- ], runtimeProfile === undefined
- ? ["Select an existing Profile with hypit runtime use <profile> --workspace <project>, or create one with hypit runtime init."]
- : []);
- return;
- }
-
- if (args.command === "packages") {
- const root = hypitHostPackageRoot();
- if (args.action === "install") {
- const reports = await prepareHostPackages([args.package], {
- root,
- ...(reportPackageProgress === undefined ? {} : { onProgress: reportPackageProgress }),
- });
- const ready = reports.length === 1;
- write({
- format: "hypit.cli-package@1",
- action: args.action,
- package: args.package,
- ready,
- ...(reports[0] === undefined ? {} : { installation: reports[0].root }),
- ...(reports[0]?.logPath === undefined ? {} : { logPath: reports[0].logPath }),
- }, "Machine package is ready", ready ? "success" : "warning", [
- ["Package", args.package],
- ["Ready", String(ready)],
- ...(args.presentation.verbose && reports[0] !== undefined ? [["Installation", reports[0].root] as const] : []),
- ]);
- if (!ready) io.setExitCode?.(1);
- return;
- }
-
- // Status answers the question a Build asks: will the dependency resolve, at
- // the declared version? It therefore asks the loader rather than checking
- // one of the places the loader looks. Reading only the machine home called a
- // package that resolves perfectly well from the Distribution's own
- // node_modules "Ready false", and exited 1 saying so.
- const status = await packageStatus(args.package, root, distribution.packageRoot);
- write({
- format: "hypit.cli-package@1",
- action: args.action,
- package: args.package,
- ready: status.ready,
- ...(status.installation === undefined ? {} : { installation: status.installation }),
- ...(status.declaredBy === undefined ? {} : { declaredBy: status.declaredBy }),
- ...(status.installedVersion === undefined ? {} : { installedVersion: status.installedVersion }),
- ...(status.detail === undefined ? {} : { detail: status.detail }),
- }, "Machine package status", status.ready ? "success" : "warning", [
- ["Package", args.package],
- ["Ready", String(status.ready)],
- ...(status.declaredBy === undefined ? [] : [["Required by", status.declaredBy] as const]),
- ...(status.detail === undefined ? [] : [["Detail", status.detail] as const]),
- ...(status.installation === undefined ? [] : [["Installation", status.installation] as const]),
- ]);
- if (!status.ready) io.setExitCode?.(1);
- return;
- }
-
if (args.command === "doctor") {
const profile = runtimeProfile === undefined ? undefined : resolve(runtimeProfile);
const [runtimeResult, projectResult] = await Promise.all([
@@ -247,7 +50,6 @@ export async function runEnvironmentCommand(input: {
ok: !diagnostics.some((item) => item.severity === "error"),
project: projectRoot,
profileSource,
- ...(runtimeSelectionFile === undefined ? {} : { selectionFile: runtimeSelectionFile }),
...(profile === undefined ? {} : { profile }),
diagnosticCount: diagnostics.length,
diagnostics,
@@ -257,300 +59,94 @@ export async function runEnvironmentCommand(input: {
return;
}
- if (args.command === "programs") {
- if (runtimeProfile === undefined) {
- throw new Error("programs requires a Runtime; run hypit runtime init, select one with runtime use, or pass --runtime <profile>");
- }
- const profile = resolve(runtimeProfile);
- const host = await runtimeHost(profile);
- if (args.action === "up" || args.action === "prepare") {
- await host.prepare({ ...(args.endpoints === undefined ? {} : { endpoints: args.endpoints }), ...(reportPackageProgress === undefined ? {} : { onProgress: reportPackageProgress }) });
- }
- const controller = await runtimeController(profile);
- const result = args.action === "up"
- ? await controller.programs.up({
- ...(args.endpoints === undefined ? {} : { endpoints: args.endpoints }),
- ...(args.maxWaitMs === undefined ? {} : { maxWaitMs: args.maxWaitMs }),
- ...(reportProgramProgress === undefined ? {} : { onProgress: reportProgramProgress }),
- })
- : args.action === "prepare"
- ? await controller.programs.prepare({
- ...(args.endpoints === undefined ? {} : { endpoints: args.endpoints }),
- ...(reportProgramProgress === undefined ? {} : { onProgress: reportProgramProgress }),
- })
- : args.action === "down"
- ? await controller.programs.down(args.endpoints === undefined ? {} : { endpoints: args.endpoints })
- : await controller.programs.report(args.endpoints === undefined ? {} : { endpoints: args.endpoints });
- const ready = result.programs.every((item) => item.state.state === "ready");
- const needsAttention = (item: typeof result.programs[number]) => args.action === "down"
- ? item.action !== "nothing-to-stop"
- && (item.state.state !== "down" || item.action !== "stopped")
- : item.state.state !== "ready";
- // Readiness describes the service, not whether a stop was performed. An owned process can
- // still be loading, and another command may have declined a concurrent stop during preparation.
- const lifecycleOk = args.action === "status" || !result.programs.some(needsAttention);
- const stoppedAny = result.programs.some((item) => item.action === "stopped");
- const relevant = result.programs.filter((item) => args.presentation.verbose || args.action === "status" || needsAttention(item));
- const urgent = relevant.filter(needsAttention);
- const shownPrograms = [...urgent, ...relevant.filter((item) => !needsAttention(item)).slice(0, Math.max(0, args.limit - urgent.length))];
- const omittedPrograms = relevant.length - shownPrograms.length;
- const title = args.action === "prepare"
- ? lifecycleOk ? "External program resources prepared" : "External program preparation needs attention"
- : args.action === "up"
- ? lifecycleOk ? "External programs ready" : "External programs need attention"
- : args.action === "down"
- ? lifecycleOk ? stoppedAny ? "External programs stopped" : "No external programs to stop"
- : "External program stop needs attention"
- : "External program status";
- write({
- format: "hypit.cli-programs@1",
- action: args.action,
- ok: lifecycleOk,
- ready,
- programCount: result.programs.length,
- readyCount: result.programs.filter((item) => item.state.state === "ready").length,
- programs: shownPrograms.map(programRecord),
- ...(omittedPrograms === 0 ? {} : { omittedPrograms }),
- }, title,
- args.action === "status" ? ready ? "success" : "info" : lifecycleOk ? "success" : "warning", [
- ...(!args.presentation.verbose && lifecycleOk && args.action !== "status" ? [] : [
- ["Programs", String(result.programs.length)] as const,
- ["Ready", String(result.programs.filter((item) => item.state.state === "ready").length)] as const,
- ]),
- ], shownPrograms.map(programDescription).concat(omittedPrograms === 0 ? [] : [`${omittedPrograms} more programs · use --limit <count>`]));
- if (!lifecycleOk) io.setExitCode?.(1);
- return;
+ if (runtimeProfile === undefined) {
+ throw new Error("auth requires a Runtime; run hypit runtime init, select one with runtime use, or pass --runtime <profile>");
}
-
- if (args.command === "runtime") {
- if (runtimeProfile === undefined) {
- throw new Error("runtime requires a Runtime; run hypit runtime init, select one with runtime use, or pass --runtime <profile>");
- }
- const profile = resolve(runtimeProfile);
- const controller = await runtimeController(profile);
- if (args.action === "up") {
- const packageRoot = await packageRootForProject();
- const host = await runtimeHost(profile, packageRoot);
- const prepared = await host.prepare(
- { ...(args.endpoints === undefined ? {} : { endpoints: args.endpoints }), ...(reportPackageProgress === undefined ? {} : { onProgress: reportPackageProgress }) },
- );
- const validated = await host.createRuntime(args.endpoints === undefined ? {} : { endpoints: args.endpoints });
- await validated.close();
- const external = await controller.programs.up({
- ...(args.endpoints === undefined ? {} : { endpoints: args.endpoints }),
- ...(args.maxWaitMs === undefined ? {} : { maxWaitMs: args.maxWaitMs }),
- ...(reportProgramProgress === undefined ? {} : { onProgress: reportProgramProgress }),
- });
- const processState = await controller.worker.up({
- ...(args.maxWaitMs === undefined ? {} : { maxWaitMs: args.maxWaitMs }),
- });
- const ok = processState.state === "running"
- && external.programs.every((item) => item.state.state === "ready");
- write({
- format: "hypit.cli-runtime-up@1",
- ready: ok,
- worker: processState.state,
- preparedPackages: prepared.length,
- programs: {
- total: external.programs.length,
- ready: external.programs.filter((item) => item.state.state === "ready").length,
- items: external.programs.filter((item) => args.presentation.verbose || item.state.state !== "ready").map(programRecord),
- },
- }, ok ? "Local Runtime ready" : "Local Runtime needs attention", ok ? "success" : "warning", [
- ...(!args.presentation.verbose && ok ? [] : [
- ["Machine packages", String(prepared.length)] as const,
- ["Worker", processState.state] as const,
- ["Managed programs", `${external.programs.filter((item) => item.state.state === "ready").length}/${external.programs.length} ready`] as const,
- ]),
- ], external.programs.filter((item) => args.presentation.verbose || item.state.state !== "ready")
- .map(programDescription));
- if (!ok) io.setExitCode?.(1);
- return;
- }
- if (args.action === "logs") {
- const logs = await controller.worker.logs();
- const lines = logs.text.length === 0 ? [] : logs.text.replace(/\n$/u, "").split("\n");
- const shown = lines.slice(-args.lines);
+ const credentialsControl = await (await runtimeHost(runtimeProfile)).openCredentials(args.endpoint);
+ try {
+ if (args.action === "status") {
+ let credentials = await credentialsControl.credentials(args.endpoint);
+ if (args.slot !== undefined) credentials = credentials.filter((item) => item.slot === args.slot);
+ if (credentials.length === 0) throw new Error(`Endpoint ${args.endpoint} has no matching credential`);
+ const view = credentials.slice(0, args.limit).map((item) => ({
+ endpoint: item.endpoint,
+ slot: item.slot,
+ label: item.label,
+ kind: item.kind,
+ configured: item.configured,
+ writable: item.writable,
+ ...(item.acquisition === undefined ? {} : { acquisition: {
+ kind: item.acquisition.kind,
+ authorizationEndpoint: item.acquisition.authorizationEndpoint,
+ } }),
+ }));
write({
- format: "hypit.cli-runtime-logs@1",
- lines: shown,
- totalLines: lines.length,
- omittedLines: Math.max(0, lines.length - shown.length),
- ...(args.presentation.verbose ? { path: logs.path } : {}),
- }, "Runtime logs", "info", [
- ["Lines", `${shown.length}/${lines.length}`],
- ...(args.presentation.verbose ? [["Path", logs.path] as const] : []),
- ], shown.length === 0 ? ["No log output."] : shown);
- return;
- }
- if (args.action === "down") {
- const worker = await controller.worker.down({
- ...(args.maxWaitMs === undefined ? {} : { maxWaitMs: args.maxWaitMs }),
- });
- const stopped = worker.state === "stopped";
- write({ format: "hypit.cli-runtime-down@1", worker: worker.state },
- stopped ? "Runtime Worker is down" : "Runtime Worker is still running",
- stopped ? "success" : "warning", [["Worker", worker.state]],
- [`Managed Programs are unchanged. To stop processes started by Hypit: ${commandHint(["programs", "down"], { projectRoot, runtimeProfile: resolve(profile) })}`]);
- if (!stopped) io.setExitCode?.(1);
+ format: "hypit.cli-auth-status@1",
+ endpoint: args.endpoint,
+ credentials: view,
+ ...(credentials.length <= args.limit ? {} : { omittedCredentials: credentials.length - args.limit }),
+ }, "Credential status", "info", [
+ ["Endpoint", args.endpoint],
+ ["Configured", `${credentials.filter((item) => item.configured).length}/${credentials.length}`],
+ ], credentials.slice(0, args.limit).map((item) => {
+ const entry = !item.writable ? "managed by its external credential source"
+ : item.acquisition === undefined ? "login uses secure secret input"
+ : `login opens OAuth: ${item.acquisition.authorizationEndpoint}`;
+ return `${item.slot}: ${item.configured ? "configured" : "missing"} · ${item.writable ? "writable" : "read-only"} · ${entry}`;
+ }));
return;
}
-
- const runtimeLoading = (await runtimeHost(profile)).openControl({ readOnly: true });
- let runtime: Awaited<typeof runtimeLoading> | undefined;
- try {
- const [worker, external, selectedRuntime] = await Promise.all([
- controller.worker.status(),
- controller.programs.report(),
- runtimeLoading,
- ]);
- runtime = selectedRuntime;
- const activity = await runtime.activity();
- const counts = Object.fromEntries([
- ["submitting", activity.builds.filter((item) => item.activity === "submitting").length],
- ["working", activity.builds.filter((item) =>
- item.activity === "ready" || item.activity === "running" || item.activity === "waiting").length],
- ["savingResult", activity.builds.filter((item) => item.activity === "saving-result").length],
- ]);
- const ready = worker.state === "running"
- && external.programs.every((item) => item.state.state === "ready");
- const active = activity.builds.length;
- const attention = activity.builds.some((item) => item.issue !== undefined) || (active > 0 && !ready);
- const unavailable = external.programs.filter((item) => item.state.state !== "ready");
- const machine = {
- format: "hypit.cli-runtime-status@1" as const,
- ready,
- attention,
- worker: {
- state: worker.state,
- },
- builds: counts,
- programs: {
- total: external.programs.length,
- ready: external.programs.length - unavailable.length,
- unavailable: unavailable.map(programRecord),
- },
- capacity: {
- active: activity.capacity.length,
- },
- };
- write(machine, attention
- ? "Local Runtime needs attention"
- : ready ? "Local Runtime ready" : worker.state === "running"
- ? "Runtime Worker running; Programs not ready" : "Runtime Worker stopped",
- attention ? "warning" : ready ? "success" : "info", [
- ["Worker", worker.state],
- ["Active Builds", String(activity.builds.length)],
- ["Programs", `${external.programs.length - unavailable.length}/${external.programs.length} ready`],
- ...(args.presentation.verbose ? [
- ["Submitting", String(counts.submitting ?? 0)] as const,
- ["Working", String(counts.working ?? 0)] as const,
- ["Saving Result", String(counts.savingResult ?? 0)] as const,
- ["Capacity in use", String(activity.capacity.length)] as const,
- ] : []),
- ], [
- ...unavailable.map(programDescription),
- ]);
- } finally {
- if (runtime !== undefined) await runtime.close();
- else await runtimeLoading.then(async (loaded) => await loaded.close(), () => undefined);
- }
- return;
- }
-
- if (args.command === "auth") {
- if (runtimeProfile === undefined) {
- throw new Error("auth requires a Runtime; run hypit runtime init, select one with runtime use, or pass --runtime <profile>");
+ let credentials = await credentialsControl.describeCredentials(args.endpoint);
+ if (args.slot !== undefined) credentials = credentials.filter((item) => item.slot === args.slot);
+ if (credentials.length === 0) throw new Error(`Endpoint ${args.endpoint} has no matching credential`);
+ if (args.slot === undefined && credentials.length > 1) {
+ throw new Error(`Endpoint ${args.endpoint} has several credentials; select one with --slot`);
}
- const credentialsControl = await (await runtimeHost(runtimeProfile)).openCredentials(args.endpoint);
- try {
- if (args.action === "status") {
- let credentials = await credentialsControl.credentials(args.endpoint);
- if (args.slot !== undefined) credentials = credentials.filter((item) => item.slot === args.slot);
- if (credentials.length === 0) throw new Error(`Endpoint ${args.endpoint} has no matching credential`);
- const view = credentials.slice(0, args.limit).map((item) => ({
- endpoint: item.endpoint,
- slot: item.slot,
- label: item.label,
- kind: item.kind,
- configured: item.configured,
- writable: item.writable,
- ...(item.acquisition === undefined ? {} : { acquisition: {
- kind: item.acquisition.kind,
- authorizationEndpoint: item.acquisition.authorizationEndpoint,
- } }),
- }));
- write({
- format: "hypit.cli-auth-status@1",
- endpoint: args.endpoint,
- credentials: view,
- ...(credentials.length <= args.limit ? {} : { omittedCredentials: credentials.length - args.limit }),
- }, "Credential status", "info", [
- ["Endpoint", args.endpoint],
- ["Configured", `${credentials.filter((item) => item.configured).length}/${credentials.length}`],
- ], credentials.slice(0, args.limit).map((item) => {
- const entry = !item.writable ? "managed by its external credential source"
- : item.acquisition === undefined ? "login uses secure secret input"
- : `login opens OAuth: ${item.acquisition.authorizationEndpoint}`;
- return `${item.slot}: ${item.configured ? "configured" : "missing"} · ${item.writable ? "writable" : "read-only"} · ${entry}`;
- }));
- return;
+ const [item] = credentials;
+ if (item === undefined) throw new Error(`Endpoint ${args.endpoint} has no matching credential`);
+ if (args.action === "login") {
+ if (!item.writable) {
+ const source = item.ref.store === "env"
+ ? `set ${item.ref.key} in the environment`
+ : "select a writable credential source in the Runtime Profile";
+ throw new Error(`${item.label} cannot be written by this command; ${source}`);
}
- let credentials = await credentialsControl.describeCredentials(args.endpoint);
- if (args.slot !== undefined) credentials = credentials.filter((item) => item.slot === args.slot);
- if (credentials.length === 0) throw new Error(`Endpoint ${args.endpoint} has no matching credential`);
- if (args.slot === undefined && credentials.length > 1) {
- throw new Error(`Endpoint ${args.endpoint} has several credentials; select one with --slot`);
- }
- if (args.action === "login") {
- const [item] = credentials;
- if (item === undefined) throw new Error(`Endpoint ${args.endpoint} has no matching credential`);
- if (!item.writable) {
- const source = item.ref.store === "env"
- ? `set ${item.ref.key} in the environment`
- : "select a writable credential source in the Runtime Profile";
- throw new Error(`${item.label} cannot be written by this command; ${source}`);
- }
- const raw = item.acquisition !== undefined && args.credentialFile === undefined
- ? await acquireOAuthCredential(item.acquisition, {
- ...(reportCredentialProgress === undefined ? {} : {
- onProgress: (message) => reportCredentialProgress(` · ${message}\n`),
- }),
- })
- : args.credentialFile === undefined
- ? await io.readSecret?.(`${item.label}: `)
- : await readFile(args.credentialFile, "utf8");
- if (raw === undefined) throw new Error("interactive credential input is unavailable; use --from <file>");
- const secret = raw.trim();
- if (secret.length === 0) throw new Error("credential input is empty");
- if (item.kind === "json") {
- try { JSON.parse(secret); } catch { throw new Error(`${item.label} is not valid JSON`); }
- }
- const stored = await credentialsControl.putCredential(item.endpoint, item.slot, secret);
- write({
- format: "hypit.cli-auth-change@1",
- endpoint: args.endpoint,
- slot: stored.slot,
- configured: true,
- }, "Credential stored", "success", [["Endpoint", args.endpoint], ["Slot", stored.slot]]);
- } else {
- const [item] = credentials;
- if (item === undefined) throw new Error(`Endpoint ${args.endpoint} has no matching credential`);
- const removed = await credentialsControl.deleteCredential(item.endpoint, item.slot);
- write({
- format: "hypit.cli-auth-change@1",
- endpoint: args.endpoint,
- slot: removed.credential.slot,
- configured: false,
- changed: removed.deleted,
- }, removed.deleted ? "Credential removed" : "Credential was absent",
- removed.deleted ? "success" : "warning", [
- ["Endpoint", args.endpoint], ["Slot", removed.credential.slot],
- ]);
+ const raw = item.acquisition !== undefined && args.credentialFile === undefined
+ ? await acquireOAuthCredential(item.acquisition, {
+ ...(reportCredentialProgress === undefined ? {} : {
+ onProgress: (message) => reportCredentialProgress(` · ${message}\n`),
+ }),
+ })
+ : args.credentialFile === undefined
+ ? await io.readSecret?.(`${item.label}: `)
+ : await readFile(args.credentialFile, "utf8");
+ if (raw === undefined) throw new Error("interactive credential input is unavailable; use --from <file>");
+ const secret = raw.trim();
+ if (secret.length === 0) throw new Error("credential input is empty");
+ if (item.kind === "json") {
+ try { JSON.parse(secret); } catch { throw new Error(`${item.label} is not valid JSON`); }
}
- } finally {
- await credentialsControl.close();
+ const stored = await credentialsControl.putCredential(item.endpoint, item.slot, secret);
+ write({
+ format: "hypit.cli-auth-change@1",
+ endpoint: args.endpoint,
+ slot: stored.slot,
+ configured: true,
+ }, "Credential stored", "success", [["Endpoint", args.endpoint], ["Slot", stored.slot]]);
+ return;
}
- return;
+ const removed = await credentialsControl.deleteCredential(item.endpoint, item.slot);
+ write({
+ format: "hypit.cli-auth-change@1",
+ endpoint: args.endpoint,
+ slot: removed.credential.slot,
+ configured: false,
+ changed: removed.deleted,
+ }, removed.deleted ? "Credential removed" : "Credential was absent",
+ removed.deleted ? "success" : "warning", [
+ ["Endpoint", args.endpoint], ["Slot", removed.credential.slot],
+ ]);
+ } finally {
+ await credentialsControl.close();
}
}
diff --git a/packages/cli/src/commands/execution.ts b/packages/cli/src/commands/execution.ts
index cadf2835..ce584fee 100644
--- a/packages/cli/src/commands/execution.ts
+++ b/packages/cli/src/commands/execution.ts
@@ -1,14 +1,13 @@
import { resolve } from "node:path";
import { readExecutionLog } from "@hypit/runtime";
-import type { BuildResultManifest, BuildResultRepository } from "@hypit/build-result";
-import type { NodeRuntimeHost } from "@hypit/runtime-host-node";
+import type { BuildResultManifest, BuildResultRepository } from "@hypit/result";
import type { CliCommand, ExecutionCommand } from "../command.js";
import { commandHint } from "../command-hint.js";
import { activityObservationKey, buildProgressLines, buildProgressView, observeBuildView } from "../observation.js";
import type { CliIo } from "../output.js";
-import type { CliRuntimeController } from "../runtime-port.js";
+import type { CliRuntimeHost } from "../runtime-port.js";
import { formatOperationProgress } from "../runtime-view.js";
import { buildStatusView } from "../view.js";
import type { CliBuildStatusView } from "../view.js";
@@ -44,12 +43,11 @@ export async function runExecutionCommand(input: {
readonly runtimeProfile: string | undefined;
readonly resolveProjectRuntime?: () => Promise<string | undefined>;
readonly io: CliIo;
- readonly runtimeHost: (profile: string) => Promise<NodeRuntimeHost>;
- readonly runtimeController: (profile: string) => Promise<CliRuntimeController>;
+ readonly runtimeHost: (profile: string) => Promise<CliRuntimeHost>;
readonly openProjectResults: OpenProjectResults;
readonly write: OperationalWriter;
}): Promise<void> {
- const { args, runtimeProfile, io, runtimeHost, runtimeController, openProjectResults, write } = input;
+ const { args, runtimeProfile, io, runtimeHost, openProjectResults, write } = input;
const commandScope = {
projectRoot: input.projectRoot,
...(runtimeProfile === undefined ? {} : { runtimeProfile: resolve(runtimeProfile) }),
@@ -164,12 +162,11 @@ export async function runExecutionCommand(input: {
const runtime = await selectedHost.openControl({ readOnly: args.command !== "cancel" });
try {
if (args.command === "activity") {
- const controller = await runtimeController(runtimeProfile);
let previous: string | undefined;
const writeActivity = async (): Promise<void> => {
- const [activity, worker] = await Promise.all([
+ const [activity, execution] = await Promise.all([
runtime.activity(),
- controller.worker.status(),
+ selectedHost.executionStatus(),
]);
const builds = activity.builds.slice(0, args.limit).map((item) => {
const status = buildStatusView({ id: item.id, runtime: item, commandScope });
@@ -181,13 +178,13 @@ export async function runExecutionCommand(input: {
};
});
const currentView = JSON.stringify([activity.builds.length,
- activityObservationKey(worker.state, activity.builds.slice(0, args.limit))]);
+ activityObservationKey(execution.state, activity.builds.slice(0, args.limit))]);
if (args.watch && currentView === previous) return;
previous = currentView;
const value = {
format: "hypit.cli-activity@1" as const,
at: Date.now(),
- worker: worker.state,
+ execution: execution.state,
builds,
...(activity.builds.length <= args.limit ? {} : { omittedBuilds: activity.builds.length - args.limit }),
...(args.presentation.verbose ? { capacity: activity.capacity } : {}),
@@ -208,7 +205,7 @@ export async function runExecutionCommand(input: {
: [];
write(value, "Runtime activity", activity.builds.length === 0 ? "success" : "info", [
["Active Builds", String(activity.builds.length)],
- ["Worker", worker.state],
+ ["Execution", execution.state],
], [
...buildLines,
...(operationLines.length === 0 ? [] : ["Operations:", ...operationLines]),
@@ -228,10 +225,9 @@ export async function runExecutionCommand(input: {
let resultReadError: string | undefined;
let openedResults: Awaited<ReturnType<OpenProjectResults>> | undefined;
if (args.watch && view !== undefined && view.issue === undefined) {
- const controller = await runtimeController(runtimeProfile);
view = await observeBuildView(runtime, args.build, view, {
...(args.maxWaitMs === undefined ? {} : { maxWaitMs: args.maxWaitMs }),
- controller,
+ executionStatus: async () => await selectedHost.executionStatus(),
commandScope,
onProgress: (progress) => {
const report = io.writeProgress ?? (args.presentation.json ? undefined : io.write);
@@ -318,8 +314,8 @@ export async function runExecutionCommand(input: {
throw new Error(`Build ${args.build} is still ${before.activity}; there is no Result write to finish`);
}
if (before !== undefined && before.issue === undefined) {
- const worker = await (await selectedHost.controller()).worker.status();
- if (worker.state === "running") {
+ const execution = await selectedHost.executionStatus();
+ if (execution.state === "running") {
throw new Error(`Build ${args.build} Result is currently being written by the Runtime Worker`);
}
}
diff --git a/packages/cli/src/commands/results.ts b/packages/cli/src/commands/results.ts
index 3c98892a..d0a721f5 100644
--- a/packages/cli/src/commands/results.ts
+++ b/packages/cli/src/commands/results.ts
@@ -1,7 +1,7 @@
import { realpath } from "node:fs/promises";
import { basename, dirname, resolve } from "node:path";
-import type { BuildResultRepository } from "@hypit/build-result";
+import type { BuildResultRepository } from "@hypit/result";
import type { CliCommand, ProjectResultCommand } from "../command.js";
import { exportBuildResultOutput } from "../result-export.js";
@@ -54,7 +54,7 @@ export async function runProjectResultCommand(input: {
createdAt: buildCreatedAtIso(manifest.id),
...(manifest.title === undefined ? {} : { title: manifest.title }),
outcome: manifest.outcome,
- ...(manifest.run === undefined ? {} : { run: projectPath(manifest.run.path, projectRoot) }),
+ ...(manifest.run === undefined ? {} : { run: projectPath(manifest.run.id, projectRoot) }),
targetCount: manifest.targets.length,
...(args.presentation.verbose ? {
targets: manifest.targets.slice(0, args.limit),
diff --git a/packages/cli/src/commands/types.ts b/packages/cli/src/commands/types.ts
index cf46f054..e8325c35 100644
--- a/packages/cli/src/commands/types.ts
+++ b/packages/cli/src/commands/types.ts
@@ -1,7 +1,7 @@
-import type { CliMachineView } from "../output.js";
+import type { OperationalMachineView } from "../machine-view.js";
export type OperationalWriter = (
- machine: CliMachineView,
+ machine: OperationalMachineView,
title: string,
status?: "success" | "warning" | "error" | "info",
facts?: readonly (readonly [string, string])[],
diff --git a/packages/cli/src/distribution.ts b/packages/cli/src/distribution.ts
index 4a1c7b3b..72e20a00 100644
--- a/packages/cli/src/distribution.ts
+++ b/packages/cli/src/distribution.ts
@@ -1,10 +1,8 @@
-import type { NodeCompiler } from "@hypit/compiler-node";
-import type { LoadedPackage, NodePackageContribution } from "@hypit/package-loader-node";
-import type { NodeRuntimeHost } from "@hypit/runtime-host-node";
-import type { BuildResultRepository } from "@hypit/build-result";
-import type { BuildResultRepositoryLocation } from "@hypit/build-result-kit";
-import type { BuildResultRepositoryDiagnostic } from "@hypit/build-result-kit";
-import type { CanonicalValue } from "@hypit/protocol";
+import type { Compiler } from "@hypit/compiler";
+import type { LoadedPackage, LogicalPackageAddress, PackageContribution } from "@hypit/loader";
+import type { BuildResultRepository } from "@hypit/result";
+import type { Workspace } from "@hypit/workspace";
+import type { CliDiagnostic, CliResultRepositoryLocation, CliRuntimeHost } from "./runtime-port.js";
export type CliCompilerOptions = {
/** Canonical containment boundary for Author and Run Sources plus source assets. */
@@ -13,9 +11,9 @@ export type CliCompilerOptions = {
readonly assetRoots?: readonly string[];
/** Project-owned package resolution boundary for package Source imports. */
readonly packageRoot?: string;
- /** Read-only application Distribution that owns the reserved @hypit namespace. */
+ /** Read-only application Distribution containing protected Host packages and extension fallbacks. */
readonly distributionPackageRoot?: string;
- readonly packageContributions: readonly NodePackageContribution[];
+ readonly packageContributions: readonly PackageContribution[];
};
/**
@@ -29,9 +27,12 @@ export type CliDistribution = {
readonly packageRoot?: string;
/** Explicit Host bootstrap packages; never inferred from Source contents. */
readonly bootstrapPackages: readonly LoadedPackage[];
- /** Product-owned starter Profile. The generic CLI only writes this explicit value. */
- readonly initialRuntimeProfile?: CanonicalValue;
- createCompiler(options: CliCompilerOptions): NodeCompiler;
+ /** Resolve the execution environment explicitly selected for this project, if the Distribution supports one. */
+ resolveProjectRuntime?(projectRoot: string): Promise<{ readonly profile: string } | undefined>;
+ /** Open the definition environment selected by this product Distribution. */
+ createWorkspace(options: Pick<CliCompilerOptions,
+ "workspaceRoot" | "assetRoots" | "packageRoot" | "distributionPackageRoot">): Workspace;
+ createCompiler(options: CliCompilerOptions): Compiler;
/**
* Read the self-described Run Source and its Author Source closure, then return
* only the installed package roots those sources explicitly select.
@@ -47,19 +48,19 @@ export type CliDistribution = {
readonly packages?: readonly LoadedPackage[];
}): Promise<{
readonly selected: readonly string[];
- readonly logical?: readonly import("@hypit/package-loader-node").LogicalPackageAddress[];
+ readonly logical?: readonly LogicalPackageAddress[];
}>;
/** Open the Runtime Profile with this application's Runtime implementation. */
openRuntimeHost(path: string, options: {
readonly packageRoot: string;
readonly distributionPackageRoot?: string;
- }): Promise<NodeRuntimeHost>;
+ }): Promise<CliRuntimeHost>;
/** Open project-owned Result history even when no Runtime Profile is selected. */
openProjectResults(projectRoot: string, options: {
readonly packageRoot: string;
readonly distributionPackageRoot?: string;
}): Promise<{
- readonly location: BuildResultRepositoryLocation;
+ readonly location: CliResultRepositoryLocation;
readonly repository: BuildResultRepository;
close(): void | Promise<void>;
}>;
@@ -68,7 +69,7 @@ export type CliDistribution = {
readonly packageRoot: string;
readonly distributionPackageRoot?: string;
}): Promise<{
- readonly location?: BuildResultRepositoryLocation;
- readonly diagnostics: readonly BuildResultRepositoryDiagnostic[];
+ readonly location?: CliResultRepositoryLocation;
+ readonly diagnostics: readonly CliDiagnostic[];
}>;
};
diff --git a/packages/cli/src/immediate.ts b/packages/cli/src/immediate.ts
new file mode 100644
index 00000000..707ce092
--- /dev/null
+++ b/packages/cli/src/immediate.ts
@@ -0,0 +1,84 @@
+import { resolve } from "node:path";
+
+import { MemoryResourceStore } from "@hypit/executor";
+import type { Need } from "@hypit/protocol";
+import type { ResourceStore } from "@hypit/runtime";
+
+import type { CliApplicationContext } from "./application.js";
+import type { CliCapabilityProvider, CliRuntimeHost } from "./runtime-port.js";
+
+function assert(condition: unknown, message: string): asserts condition {
+ if (!condition) throw new Error(message);
+}
+
+/** Ephemeral resources for one immediate CLI request; no Build or Result state is created. */
+export function createCliScratchResources(): ResourceStore {
+ return new MemoryResourceStore();
+}
+
+/** Open the Runtime Profile explicitly named by a command, or the one selected by its project. */
+export async function openCliRuntimeHost(
+ application: CliApplicationContext,
+ runtime: string | undefined,
+ project: string | undefined,
+): Promise<{ readonly profile: string; readonly host: CliRuntimeHost; readonly projectRoot: string }> {
+ const projectRoot = await application.resolveProjectRoot(
+ project === undefined ? undefined : resolve(application.cwd, project),
+ );
+ const profile = runtime === undefined
+ ? (await application.distribution.resolveProjectRuntime?.(projectRoot))?.profile
+ : resolve(application.cwd, runtime);
+ assert(profile !== undefined,
+ `No Runtime Profile is selected for ${projectRoot}; run hypit runtime use <profile> there, or pass --runtime <profile>`);
+ const host = await application.distribution.openRuntimeHost(profile, {
+ packageRoot: projectRoot,
+ ...(application.distribution.packageRoot === undefined
+ ? {}
+ : { distributionPackageRoot: application.distribution.packageRoot }),
+ });
+ return { profile, host, projectRoot };
+}
+
+function capabilityName(need: Need): string {
+ return `${need.capability.module.name}@${need.capability.module.version}#${need.capability.name}`;
+}
+
+/** Resolve one immediate request before spending, preserving the selected Endpoint's explanation. */
+export async function selectCliProvider(
+ host: Pick<CliRuntimeHost, "providers">,
+ need: Need,
+ profile: string,
+): Promise<CliCapabilityProvider> {
+ const [provider] = await host.providers([{
+ request: need.id,
+ capability: need.capability,
+ returns: need.returns,
+ constraints: need.constraints,
+ }]);
+ const subject = capabilityName(need);
+ assert(provider !== undefined && provider.status !== "unresolved",
+ `No Endpoint in ${profile} serves ${subject}; configure an Endpoint that supports this capability and check its binding in that Profile`);
+ assert(provider.status !== "ambiguous",
+ `Several Endpoints in ${profile} serve ${subject}: ${(provider.endpoints ?? []).join(", ")}; select one with bindings[${JSON.stringify(subject)}] in that Profile`);
+ assert(provider.status !== "unsupported",
+ `The configured Endpoints in ${profile} do not support this request for ${subject}`
+ + (provider.binding === undefined ? "" : ` (binding: ${provider.binding})`)
+ + `: ${(provider.rejections ?? []).map((item) => `${item.endpoint}: ${item.message}`).join("; ") || "no support reason supplied"}`
+ + "; adjust the request or select a compatible Endpoint in that Profile");
+ return provider;
+}
+
+export function cliProviderView(provider: CliCapabilityProvider) {
+ return {
+ endpoint: provider.endpoint ?? null,
+ use: provider.use ?? null,
+ pricing: provider.pricing ?? null,
+ };
+}
+
+export function cliProviderLine(provider: CliCapabilityProvider): string {
+ const price = provider.pricing === undefined
+ ? "price source unknown"
+ : provider.pricing.kind === "local" ? "local, no Provider charge" : provider.pricing.url;
+ return `${provider.endpoint} (${provider.use}) · ${price}`;
+}
diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts
index 9b39e90b..64b878d0 100644
--- a/packages/cli/src/index.ts
+++ b/packages/cli/src/index.ts
@@ -1,11 +1,22 @@
export { runCli } from "./main.js";
+export { indexCliCommandModules, runCliApplication } from "./application.js";
+export type { CliApplication, CliApplicationContext, CliCommandModule } from "./application.js";
+export { runNodeCli, runNodeCliApplication } from "./node-application.js";
+export type { NodeCliRunner } from "./node-application.js";
+export { acceptSecretBytes } from "./secret-input.js";
+export { genericCliCommandNames } from "./command.js";
+export { commandHint } from "./command-hint.js";
+export { cliProviderLine, cliProviderView, createCliScratchResources, openCliRuntimeHost, selectCliProvider } from "./immediate.js";
+export { runVersionCli, writeVersionHelp } from "./version.js";
+export type { VersionEnvironment } from "./version.js";
+export { runInstalledCliApplication, writeCliCompositionHelp } from "./installed-application.js";
+export type { InstalledCliApplicationOptions, LoadedCliCommandSelection } from "./installed-application.js";
export { discoverSourcePackages } from "./source-discovery.js";
export { loadDiscoveredSourcePackages } from "./source-packages.js";
export { collectRunFrontends, loadRunFile, resolveBuildResultValue } from "./run-file.js";
export type { LoadedRunFile } from "./run-file.js";
export { hypitHostStateRoot, hypitProjectStateRoot } from "./paths.js";
-export { resolvePackageRoot, resolveProjectRoot } from "@hypit/project-context-node";
-export { findRuntimeProfile } from "@hypit/project-context-node";
+export { resolveProjectRoot } from "@hypit/project";
export { renderCliError, writeCliHelp, writeCliOutput } from "./output.js";
export type {
CliColorMode,
@@ -22,7 +33,6 @@ export type {
CliOutputView,
PublicOutputKind,
} from "./view.js";
-export type { OperationalMachineView } from "./machine-view.js";
export type {
CliCompilerOptions,
CliDistribution,
diff --git a/packages/cli/src/installed-application.ts b/packages/cli/src/installed-application.ts
new file mode 100644
index 00000000..79d5f37c
--- /dev/null
+++ b/packages/cli/src/installed-application.ts
@@ -0,0 +1,320 @@
+import { readFile, writeFile } from "node:fs/promises";
+import { resolve } from "node:path";
+import { pathToFileURL } from "node:url";
+
+import { resolveNodePackageModule } from "@hypit/loader/node";
+import { findProjectRoot, resolveProjectRoot } from "@hypit/project";
+
+import { indexCliCommandModules, runCliApplication } from "./application.js";
+import type { CliApplication, CliCommandModule } from "./application.js";
+import type { CliDistribution } from "./distribution.js";
+import type { CliIo } from "./output.js";
+import { runVersionCli, writeVersionHelp } from "./version.js";
+
+type JsonObject = Record<string, unknown>;
+
+type PackageManifest = JsonObject & {
+ readonly name?: unknown;
+ readonly version?: unknown;
+ readonly dependencies?: unknown;
+ readonly devDependencies?: unknown;
+ readonly optionalDependencies?: unknown;
+ readonly hypit?: unknown;
+};
+
+export type InstalledCliApplicationOptions = {
+ readonly distribution: CliDistribution;
+ readonly distributionRoot: string;
+ readonly launcher?: string;
+ readonly cwd?: string;
+};
+
+export type LoadedCliCommandSelection = {
+ readonly origin: "distribution" | "project";
+ readonly specifier: string;
+ readonly package: string;
+ readonly version?: string;
+ readonly modules: readonly CliCommandModule[];
+};
+
+function object(value: unknown, subject: string): JsonObject {
+ if (value === null || typeof value !== "object" || Array.isArray(value)) {
+ throw new Error(`${subject} must be an object`);
+ }
+ return value as JsonObject;
+}
+
+async function readManifest(root: string, required: boolean): Promise<PackageManifest | undefined> {
+ const path = resolve(root, "package.json");
+ try {
+ return object(JSON.parse(await readFile(path, "utf8")), path) as PackageManifest;
+ } catch (error) {
+ if (!required && error instanceof Error && "code" in error && error.code === "ENOENT") return undefined;
+ throw error;
+ }
+}
+
+function declaredUses(manifest: PackageManifest | undefined, subject: string): readonly string[] {
+ if (manifest?.hypit === undefined) return [];
+ const hypit = object(manifest.hypit, `${subject}.hypit`);
+ if (hypit.cli === undefined) return [];
+ const cli = object(hypit.cli, `${subject}.hypit.cli`);
+ if (cli.use === undefined) return [];
+ if (!Array.isArray(cli.use) || cli.use.some((value) => typeof value !== "string" || value.length === 0)) {
+ throw new Error(`${subject}.hypit.cli.use must be an array of npm package export strings`);
+ }
+ const values = cli.use as string[];
+ if (new Set(values).size !== values.length) throw new Error(`${subject}.hypit.cli.use contains a duplicate`);
+ return values;
+}
+
+function packageName(specifier: string): string {
+ if (specifier.startsWith(".") || specifier.startsWith("/") || specifier.includes(":")) {
+ throw new Error(`${specifier} must be an npm package export`);
+ }
+ const parts = specifier.split("/");
+ const name = specifier.startsWith("@") ? `${parts[0] ?? ""}/${parts[1] ?? ""}` : parts[0] ?? "";
+ if (name.length === 0 || name === "@/" || (specifier.startsWith("@") && parts.length < 2)) {
+ throw new Error(`${specifier} must be an npm package export`);
+ }
+ return name;
+}
+
+function dependencyMap(value: unknown): Readonly<Record<string, unknown>> {
+ return value === undefined ? {} : object(value, "package dependency map");
+}
+
+function requireDirectDependency(manifest: PackageManifest, specifier: string): void {
+ const name = packageName(specifier);
+ const declared = dependencyMap(manifest.dependencies)[name]
+ ?? dependencyMap(manifest.devDependencies)[name]
+ ?? dependencyMap(manifest.optionalDependencies)[name];
+ if (typeof declared !== "string" || declared.length === 0) {
+ throw new Error(`${specifier} is not a direct dependency of this project; install ${name} with the project's package manager first`);
+ }
+}
+
+function commandModules(value: unknown, subject: string): readonly CliCommandModule[] {
+ const exports = object(value, subject);
+ if (!Array.isArray(exports.cliCommandModules)) {
+ throw new Error(`${subject} must export cliCommandModules`);
+ }
+ const modules = exports.cliCommandModules as unknown[];
+ if (modules.length === 0) throw new Error(`${subject}.cliCommandModules cannot be empty`);
+ for (const [index, module] of modules.entries()) {
+ const candidate = object(module, `${subject}.cliCommandModules[${index}]`);
+ if (candidate.format !== "hypit.cli-command@1" || typeof candidate.id !== "string"
+ || !Array.isArray(candidate.commands)
+ || candidate.commands.some(command => typeof command !== "string")
+ || typeof candidate.writeHelp !== "function"
+ || typeof candidate.run !== "function") {
+ throw new Error(`${subject}.cliCommandModules[${index}] is not a hypit.cli-command@1 module`);
+ }
+ }
+ return modules as unknown as readonly CliCommandModule[];
+}
+
+async function loadSelection(
+ specifier: string,
+ origin: "distribution" | "project",
+ root: string,
+ distributionRoot: string,
+): Promise<LoadedCliCommandSelection> {
+ const located = resolveNodePackageModule(specifier, {
+ from: resolve(root, "package.json"),
+ workspaceRoots: [root],
+ distributionRoots: origin === "distribution" ? [distributionRoot] : [],
+ });
+ const imported = await import(pathToFileURL(located.module).href);
+ const manifest = await readManifest(located.root, true);
+ return {
+ origin,
+ specifier,
+ package: located.package,
+ ...(typeof manifest?.version === "string" ? { version: manifest.version } : {}),
+ modules: commandModules(imported, specifier),
+ };
+}
+
+async function loadSelections(
+ distributionRoot: string,
+ projectRoot?: string,
+ projectUses?: readonly string[],
+): Promise<readonly LoadedCliCommandSelection[]> {
+ const distributionManifest = await readManifest(distributionRoot, true);
+ const projectManifest = projectRoot === undefined || projectRoot === distributionRoot
+ ? undefined
+ : await readManifest(projectRoot, false);
+ const distributionUses = declaredUses(distributionManifest, resolve(distributionRoot, "package.json"));
+ const selectedProjectUses = projectUses
+ ?? declaredUses(projectManifest, resolve(projectRoot ?? distributionRoot, "package.json"));
+ for (const specifier of selectedProjectUses) {
+ if (projectManifest === undefined) throw new Error(`Project has no package.json for CLI selection ${specifier}`);
+ requireDirectDependency(projectManifest, specifier);
+ }
+ const result: LoadedCliCommandSelection[] = [];
+ for (const specifier of distributionUses) {
+ result.push(await loadSelection(specifier, "distribution", distributionRoot, distributionRoot));
+ }
+ for (const specifier of selectedProjectUses) {
+ if (projectRoot === undefined) throw new Error(`No Hypit project is available for CLI selection ${specifier}`);
+ result.push(await loadSelection(specifier, "project", projectRoot, distributionRoot));
+ }
+ return result;
+}
+
+function projectArgument(argv: readonly string[], cwd: string): string | undefined {
+ const end = argv.indexOf("--");
+ const visible = end < 0 ? argv : argv.slice(0, end);
+ for (let index = 0; index < visible.length; index++) {
+ const value = visible[index]!;
+ if (value === "--project") {
+ const selected = visible[index + 1];
+ if (selected === undefined || selected.startsWith("--")) throw new Error("--project requires a directory");
+ return resolve(cwd, selected);
+ }
+ if (value.startsWith("--project=")) return resolve(cwd, value.slice("--project=".length));
+ }
+ return undefined;
+}
+
+export function writeCliCompositionHelp(io: Pick<CliIo, "write">): void {
+ io.write("hypit cli\nManage this project's explicit CLI command contributions.\n\n"
+ + " hypit cli status [--project <directory>] [--json]\n"
+ + " hypit cli use <installed-package/cli> [--project <directory>]\n"
+ + " hypit cli remove <installed-package/cli> [--project <directory>]\n\n"
+ + "use/remove only edit package.json hypit.cli.use. Install and remove packages with the project's package manager.\n");
+}
+
+function cliAction(argv: readonly string[]): { action: string; specifier?: string; json: boolean } {
+ const positional: string[] = [];
+ let json = false;
+ for (let index = 1; index < argv.length; index++) {
+ const value = argv[index]!;
+ if (value === "--project") { index++; continue; }
+ if (value.startsWith("--project=")) continue;
+ if (value === "--json") { json = true; continue; }
+ if (["--debug", "--no-color"].includes(value)) continue;
+ if (value === "--color") { index++; continue; }
+ if (value === "--help" || value === "-h") return { action: "help", json };
+ if (value.startsWith("-")) throw new Error(`Unknown cli option: ${value}`);
+ positional.push(value);
+ }
+ if (positional.length > 2) throw new Error("hypit cli accepts one action and at most one package export");
+ return { action: positional[0] ?? "status", ...(positional[1] === undefined ? {} : { specifier: positional[1] }), json };
+}
+
+function replaceProjectUses(manifest: PackageManifest, uses: readonly string[]): PackageManifest {
+ const existingHypit = manifest.hypit === undefined ? {} : object(manifest.hypit, "package.json.hypit");
+ const existingCli = existingHypit.cli === undefined ? {} : object(existingHypit.cli, "package.json.hypit.cli");
+ return {
+ ...manifest,
+ hypit: {
+ ...existingHypit,
+ cli: { ...existingCli, use: [...uses] },
+ },
+ };
+}
+
+async function runCliComposition(
+ argv: readonly string[],
+ io: CliIo,
+ options: InstalledCliApplicationOptions,
+ projectRoot: string | undefined,
+): Promise<void> {
+ const parsed = cliAction(argv);
+ if (parsed.action === "help") { writeCliCompositionHelp(io); return; }
+ const projectManifest = projectRoot === undefined ? undefined : await readManifest(projectRoot, false);
+ const projectPath = projectRoot === undefined ? undefined : resolve(projectRoot, "package.json");
+ const uses = [...declaredUses(projectManifest, projectPath ?? "Project package.json")];
+ if (parsed.action === "use") {
+ if (projectRoot === undefined) throw new Error("cli use requires a Hypit project; run inside one or pass --project <directory>");
+ if (projectManifest === undefined) throw new Error(`No package.json exists at project ${projectRoot}`);
+ if (parsed.specifier === undefined) throw new Error("hypit cli use requires one installed package export");
+ requireDirectDependency(projectManifest, parsed.specifier);
+ const next = uses.includes(parsed.specifier) ? uses : [...uses, parsed.specifier];
+ const selections = await loadSelections(options.distributionRoot, projectRoot, next);
+ indexCliCommandModules(selections.flatMap(selection => selection.modules));
+ if (!uses.includes(parsed.specifier)) {
+ await writeFile(resolve(projectRoot, "package.json"), `${JSON.stringify(replaceProjectUses(projectManifest, next), null, 2)}\n`);
+ }
+ io.write(`CLI command contribution selected: ${parsed.specifier}\nProject: ${projectRoot}\n`);
+ return;
+ }
+ if (parsed.action === "remove") {
+ if (projectRoot === undefined) throw new Error("cli remove requires a Hypit project; run inside one or pass --project <directory>");
+ if (projectManifest === undefined) throw new Error(`No package.json exists at project ${projectRoot}`);
+ if (parsed.specifier === undefined) throw new Error("hypit cli remove requires one package export");
+ const next = uses.filter(value => value !== parsed.specifier);
+ if (next.length === uses.length) throw new Error(`${parsed.specifier} is not selected by this project`);
+ await writeFile(resolve(projectRoot, "package.json"), `${JSON.stringify(replaceProjectUses(projectManifest, next), null, 2)}\n`);
+ io.write(`CLI command contribution removed: ${parsed.specifier}\nProject: ${projectRoot}\nThe npm package was not uninstalled.\n`);
+ return;
+ }
+ if (parsed.action !== "status") throw new Error(`Unknown hypit cli action: ${parsed.action}`);
+ const selections = await loadSelections(options.distributionRoot, projectRoot);
+ indexCliCommandModules(selections.flatMap(selection => selection.modules));
+ const report = {
+ format: "hypit.cli-composition@1",
+ ...(projectRoot === undefined ? {} : { project: projectRoot }),
+ contributions: selections.map(selection => ({
+ origin: selection.origin,
+ specifier: selection.specifier,
+ package: selection.package,
+ ...(selection.version === undefined ? {} : { version: selection.version }),
+ commands: selection.modules.flatMap(module => module.commands),
+ })),
+ };
+ if (parsed.json) { io.write(`${JSON.stringify(report, null, 2)}\n`); return; }
+ io.write(`Hypit CLI\nProject: ${projectRoot ?? "none"}\n`);
+ for (const contribution of report.contributions) {
+ io.write(`\n${contribution.origin === "distribution" ? "Distribution" : "Project"} ${contribution.specifier}`
+ + `${contribution.version === undefined ? "" : ` @ ${contribution.version}`}\n`
+ + ` ${contribution.commands.join("\n ")}\n`);
+ }
+}
+
+/** Run the root Hypit CLI Host and compose only explicitly selected command contributions. */
+export async function runInstalledCliApplication(
+ argv: readonly string[],
+ io: CliIo,
+ options: InstalledCliApplicationOptions,
+): Promise<void> {
+ const distributionRoot = resolve(options.distributionRoot);
+ if (argv[0] === "version" || (argv[0] === "help" && argv[1] === "version")) {
+ if (argv[0] === "help") { writeVersionHelp(io); return; }
+ await runVersionCli(argv, io, {
+ packageRoot: distributionRoot,
+ ...(options.launcher === undefined ? {} : { launcher: options.launcher }),
+ fetch: globalThis.fetch,
+ });
+ return;
+ }
+ if (argv[0] === "cli" || (argv[0] === "help" && argv[1] === "cli")) {
+ if (argv[0] === "help") { writeCliCompositionHelp(io); return; }
+ const cwd = resolve(options.cwd ?? process.cwd());
+ const requestedProject = projectArgument(argv, cwd);
+ const projectRoot = requestedProject === undefined
+ ? await findProjectRoot({ cwd })
+ : await resolveProjectRoot({ projectRoot: requestedProject, cwd });
+ await runCliComposition(argv, io, { ...options, distributionRoot }, projectRoot);
+ return;
+ }
+ const cwd = resolve(options.cwd ?? process.cwd());
+ const requestedProject = projectArgument(argv, cwd);
+ const projectRoot = requestedProject === undefined
+ ? await findProjectRoot({ cwd })
+ : await resolveProjectRoot({ projectRoot: requestedProject, cwd });
+ const selections = await loadSelections(distributionRoot, projectRoot);
+ const application: CliApplication = {
+ distribution: options.distribution,
+ cwd,
+ resolveProjectRoot: async (explicit?: string) => {
+ if (explicit !== undefined) return await resolveProjectRoot({ projectRoot: explicit, cwd });
+ if (projectRoot !== undefined) return projectRoot;
+ return await resolveProjectRoot({ cwd });
+ },
+ commandModules: selections.flatMap(selection => selection.modules),
+ };
+ await runCliApplication(argv, io, application);
+}
diff --git a/packages/cli/src/machine-view.ts b/packages/cli/src/machine-view.ts
index e5783b4a..bf1c3e42 100644
--- a/packages/cli/src/machine-view.ts
+++ b/packages/cli/src/machine-view.ts
@@ -1,30 +1,9 @@
import type { CliBuildResultView, CliBuildStatusView, CliOutputView } from "./view.js";
-type ProgramStateView = {
- readonly id: string;
- readonly state: string;
- readonly action?: string;
- readonly endpoint?: string;
- readonly stateDetail?: string;
- readonly detail?: string;
- readonly pid?: number;
- readonly logPath?: string;
- readonly installationLogPath?: string;
- readonly errorLogPath?: string;
-};
type AttentionView = { readonly message: string; readonly action?: string };
export type OperationalMachineView =
| { readonly format: "hypit.cli-logs@1"; readonly build: string; readonly source: "runtime" | "result" | "unavailable"; readonly records: readonly import("@hypit/runtime").ExecutionLogRecord[]; readonly omittedRecords: number }
- | { readonly format: "hypit.cli-runtime-init@1"; readonly profile: string; readonly project: string; readonly selected: true }
- | { readonly format: "hypit.cli-runtime-selection@1"; readonly selected: boolean; readonly removed?: boolean; readonly profile?: string; readonly project?: string }
- | { readonly format: "hypit.cli-paths@1"; readonly project: string; readonly projectState: string; readonly profileSource: "argument" | "project" | "none"; readonly selectionFile: string; readonly profile?: string; readonly runtimeData?: string; readonly hostState: string; readonly machinePackages: string; readonly distribution?: string }
- | { readonly format: "hypit.cli-package@1"; readonly action: "install" | "status"; readonly package: string; readonly ready: boolean }
- | { readonly format: "hypit.cli-programs@1"; readonly action: "prepare" | "up" | "down" | "status"; readonly ok: boolean; readonly ready: boolean; readonly programCount: number; readonly readyCount: number; readonly programs: readonly ProgramStateView[]; readonly omittedPrograms?: number }
- | { readonly format: "hypit.cli-runtime-up@1"; readonly ready: boolean; readonly worker: string; readonly preparedPackages: number; readonly programs: { readonly total: number; readonly ready: number; readonly items: readonly ProgramStateView[] } }
- | { readonly format: "hypit.cli-runtime-logs@1"; readonly lines: readonly string[]; readonly totalLines: number; readonly omittedLines: number; readonly path?: string }
- | { readonly format: "hypit.cli-runtime-down@1"; readonly worker: string }
- | { readonly format: "hypit.cli-runtime-status@1"; readonly ready: boolean; readonly attention: boolean; readonly worker: { readonly state: string; readonly configuration?: string }; readonly builds: Readonly<Record<string, number>>; readonly programs: { readonly total: number; readonly ready: number; readonly unavailable: readonly ProgramStateView[] }; readonly capacity: { readonly active: number } }
| { readonly format: "hypit.cli-auth-status@1"; readonly endpoint: string; readonly credentials: readonly { readonly endpoint: string; readonly slot: string; readonly label: string; readonly kind: string; readonly configured: boolean; readonly writable: boolean; readonly acquisition?: { readonly kind: string; readonly authorizationEndpoint: string } }[]; readonly omittedCredentials?: number }
| { readonly format: "hypit.cli-auth-change@1"; readonly endpoint: string; readonly slot: string; readonly configured: boolean; readonly changed?: boolean }
| { readonly format: "hypit.cli-builds@1"; readonly builds: readonly { readonly id: string; readonly createdAt: string; readonly title?: string; readonly outcome: string; readonly run?: string; readonly targetCount: number; readonly targets?: readonly string[]; readonly omittedTargets?: number; readonly outputCount: number }[]; readonly next?: string }
@@ -33,7 +12,7 @@ export type OperationalMachineView =
| { readonly format: "hypit.cli-result-edit@1"; readonly build: string; readonly title: string | null; readonly note: string | null; readonly highlightedOutputCount: number; readonly highlightedOutputs: readonly string[]; readonly omittedHighlightedOutputs?: number }
| { readonly format: "hypit.cli-get@1"; readonly build: string; readonly output: string; readonly type: string; readonly kind: "scalar" | "resource" | "composite"; readonly path: string }
| { readonly format: "hypit.cli-status@1"; readonly build: CliBuildStatusView | null }
- | { readonly format: "hypit.cli-activity@1"; readonly at: number; readonly worker: string; readonly builds: readonly { readonly id: string; readonly work: CliBuildStatusView["work"]; readonly phases: Readonly<Record<string, number>>; readonly attention?: AttentionView }[]; readonly omittedBuilds?: number; readonly capacity?: readonly import("@hypit/runtime").CapacityReservation[] }
+ | { readonly format: "hypit.cli-activity@1"; readonly at: number; readonly execution: string; readonly builds: readonly { readonly id: string; readonly work: CliBuildStatusView["work"]; readonly phases: Readonly<Record<string, number>>; readonly attention?: AttentionView }[]; readonly omittedBuilds?: number; readonly capacity?: readonly import("@hypit/runtime").CapacityReservation[] }
| { readonly format: "hypit.cli-result-discard@1"; readonly build: string; readonly discarded: boolean }
| { readonly format: "hypit.cli-result-finish@1"; readonly build: string; readonly found?: false; readonly outcome?: string; readonly attention?: AttentionView }
| { readonly format: "hypit.cli-cancel@1"; readonly requested: boolean; readonly build: CliBuildStatusView | null }
diff --git a/packages/cli/src/main.ts b/packages/cli/src/main.ts
index 212ed542..a3e79e23 100644
--- a/packages/cli/src/main.ts
+++ b/packages/cli/src/main.ts
@@ -1,20 +1,17 @@
import { randomBytes } from "node:crypto";
-import { writeFile } from "node:fs/promises";
import { resolve } from "node:path";
-import type { NodeRuntimeHost } from "@hypit/runtime-host-node";
import { orderedBuildId } from "@hypit/protocol";
-import { parseSourceHeader } from "@hypit/source";
+import { parseSourceHeader } from "@hypit/source/text";
import { unreachedGenerations } from "./reachability.js";
import { checkRunFile, collectRunFrontends, loadRunFile } from "./run-file.js";
import type { CliDistribution } from "./distribution.js";
-import type {
- CliRuntime,
- CliRuntimeController,
-} from "./runtime-port.js";
+import type { CliApplicationContext } from "./application.js";
+import type { CliRuntime, CliRuntimeHost } from "./runtime-port.js";
import { createPlanOutput, createPricingOutput, writeCliHelp, writeCliOutput } from "./output.js";
-import type { CliIo, CliMachineView } from "./output.js";
+import type { CliIo } from "./output.js";
+import type { OperationalMachineView } from "./machine-view.js";
import { parseCommand } from "./arguments.js";
import type { CliCommand, RuntimeOption } from "./command.js";
import { commandHint } from "./command-hint.js";
@@ -24,13 +21,8 @@ import { isProjectResultCommand, runProjectResultCommand } from "./commands/resu
import { isEnvironmentCommand, runEnvironmentCommand } from "./commands/environment.js";
import { isExecutionCommand, runExecutionCommand } from "./commands/execution.js";
import { inlineValuePreview } from "./runtime-view.js";
-import { resolvePackageRoot, resolveProjectRoot } from "@hypit/project-context-node";
+import { resolveProjectRoot } from "@hypit/project";
import { loadDiscoveredSourcePackages } from "./source-packages.js";
-import {
- clearRuntimeProfile,
- findRuntimeProfile,
- selectRuntimeProfile,
-} from "@hypit/project-context-node";
import {
buildStatusView,
cliTypeName,
@@ -41,12 +33,12 @@ function createPublicBuildId(now = Date.now()): string {
return orderedBuildId(now, randomBytes(5).toString("hex").toUpperCase());
}
-async function loadRuntime(host: NodeRuntimeHost, endpoints: readonly string[]): Promise<CliRuntime> {
+async function loadRuntime(host: CliRuntimeHost, endpoints: readonly string[]): Promise<CliRuntime> {
return await host.createRuntime({ endpoints });
}
-function commandWorkspaceRoot(command: CliCommand): string | undefined {
- return "workspaceRoot" in command ? command.workspaceRoot : undefined;
+function commandProjectRootOption(command: CliCommand): string | undefined {
+ return "projectRoot" in command ? command.projectRoot : undefined;
}
function commandPackageRoot(command: CliCommand): string | undefined {
@@ -61,6 +53,7 @@ export async function runCli(
argv: readonly string[],
io: CliIo,
distribution: CliDistribution,
+ context?: Pick<CliApplicationContext, "cwd" | "resolveProjectRoot">,
): Promise<void> {
if (argv.length === 0 || argv[0] === "help" || argv.includes("--help")) {
const topic = argv[0] === "help" ? argv[1] : argv[0] === "--help" ? undefined
@@ -68,20 +61,20 @@ export async function runCli(
writeCliHelp(io, topic);
return;
}
- const args = parseCommand(argv);
+ const cwd = context?.cwd ?? process.cwd();
+ const args = parseCommand(argv, cwd);
let resolvedProject: Promise<string> | undefined;
const commandProjectRoot = async (): Promise<string> => {
- const workspaceRoot = commandWorkspaceRoot(args);
- resolvedProject ??= resolveProjectRoot({
- ...(workspaceRoot === undefined ? {} : { workspaceRoot }),
- cwd: process.cwd(),
- });
+ const projectRoot = commandProjectRootOption(args);
+ resolvedProject ??= context === undefined
+ ? resolveProjectRoot({ ...(projectRoot === undefined ? {} : { projectRoot }), cwd })
+ : context.resolveProjectRoot(projectRoot);
return await resolvedProject;
};
const packageRootForProject = async (projectRoot?: string): Promise<string> =>
- commandPackageRoot(args) ?? await resolvePackageRoot(projectRoot ?? await commandProjectRoot());
+ commandPackageRoot(args) ?? projectRoot ?? await commandProjectRoot();
const writeOperational = (
- machine: CliMachineView,
+ machine: OperationalMachineView,
title: string,
status: "success" | "warning" | "error" | "info" = "info",
facts: readonly (readonly [string, string])[] = [],
@@ -89,8 +82,8 @@ export async function runCli(
): void => writeCliOutput(io, {
...args.presentation,
}, { kind: "operational", machine, title, status, facts, lines });
- const runtimeHosts = new Map<string, Promise<NodeRuntimeHost>>();
- const runtimeHost = async (path: string, requestedPackageRoot?: string): Promise<NodeRuntimeHost> => {
+ const runtimeHosts = new Map<string, Promise<CliRuntimeHost>>();
+ const runtimeHost = async (path: string, requestedPackageRoot?: string): Promise<CliRuntimeHost> => {
const profile = resolve(path);
const packageRoot = requestedPackageRoot ?? await packageRootForProject();
const key = `${profile}\u0000${packageRoot}`;
@@ -114,98 +107,25 @@ export async function runCli(
...(distribution.packageRoot === undefined ? {} : { distributionPackageRoot: distribution.packageRoot }),
});
};
- if (args.command === "_worker") {
- await (await runtimeHost(
- args.profile,
- args.packageRoot ?? await packageRootForProject(),
- )).runWorker(args.readyFile, args.workerOwner,
- args.executionRoot === undefined ? undefined : { dataRoot: args.executionRoot });
- return;
- }
- if (args.command === "runtime" && args.action === "init") {
- if (distribution.initialRuntimeProfile === undefined) {
- throw new Error("This Hypit Distribution does not provide an initial Runtime Profile");
- }
- const projectRoot = await commandProjectRoot();
- const profile = resolve(args.profile ?? resolve(projectRoot, "hypit.runtime.json"));
- try {
- await writeFile(profile, `${JSON.stringify(distribution.initialRuntimeProfile, undefined, 2)}\n`, {
- encoding: "utf8",
- flag: "wx",
- });
- } catch (error) {
- if (error instanceof Error && "code" in error && error.code === "EEXIST") {
- throw new Error(`Runtime Profile already exists: ${profile}; select it with hypit runtime use or choose another path`);
- }
- throw error;
- }
- const selected = await selectRuntimeProfile(projectRoot, profile);
- writeOperational({
- format: "hypit.cli-runtime-init@1",
- profile: selected.profile,
- project: selected.projectRoot,
- selected: true,
- }, "Runtime Profile created", "success", [
- ["Profile", selected.profile],
- ["Project", selected.projectRoot],
- ], ["Review the Profile’s credential stores and Endpoint settings before login or runtime up.",
- "No package was installed, no service was contacted and no Worker was started."]);
- return;
- }
- if (args.command === "runtime" && args.action === "use") {
- const profile = resolve(args.profile);
- const selected = await selectRuntimeProfile(await commandProjectRoot(), profile);
- writeOperational({
- format: "hypit.cli-runtime-selection@1",
- selected: true,
- profile: selected.profile,
- project: selected.projectRoot,
- }, "Runtime selected", "success", [
- ["Profile", selected.profile],
- ["Project", selected.projectRoot],
- ]);
- return;
- }
- if (args.command === "runtime" && args.action === "unset") {
- const cleared = await clearRuntimeProfile(await commandProjectRoot());
- writeOperational({
- format: "hypit.cli-runtime-selection@1",
- selected: false,
- removed: cleared !== undefined,
- ...(cleared === undefined ? {} : { profile: cleared.profile, project: cleared.projectRoot }),
- }, cleared === undefined ? "No Runtime was selected" : "Runtime selection removed",
- cleared === undefined ? "info" : "success", cleared === undefined ? [] : [
- ["Profile", cleared.profile], ["Project", cleared.projectRoot],
- ]);
- return;
- }
-
let runtimeProfile = acceptsRuntimeContext(args) ? args.runtimeProfile : undefined;
- let runtimeSelectionFile: string | undefined;
+ let runtimeFromProject = false;
if (acceptsRuntimeContext(args) && runtimeProfile === undefined && args.command !== "logs") {
- const selected = await findRuntimeProfile(await commandProjectRoot());
+ const selected = await distribution.resolveProjectRuntime?.(await commandProjectRoot());
if (selected !== undefined) {
runtimeProfile = selected.profile;
- runtimeSelectionFile = selected.selectionFile;
+ runtimeFromProject = true;
}
}
- const runtimeController = async (profile: string): Promise<CliRuntimeController> => {
- const packageRoot = await packageRootForProject();
- return await (await runtimeHost(profile, packageRoot)).controller({
- packageRoot,
- });
- };
if (isEnvironmentCommand(args)) {
await runEnvironmentCommand({
args,
runtimeProfile,
- runtimeSelectionFile,
+ runtimeFromProject,
io,
distribution,
projectRoot: await commandProjectRoot(),
packageRootForProject,
runtimeHost,
- runtimeController,
write: writeOperational,
});
return;
@@ -231,16 +151,15 @@ export async function runCli(
runtimeProfile,
io,
runtimeHost,
- runtimeController,
openProjectResults: projectResults,
- resolveProjectRuntime: async () => (await findRuntimeProfile(await commandProjectRoot()))?.profile,
+ resolveProjectRuntime: async () => (await distribution.resolveProjectRuntime?.(await commandProjectRoot()))?.profile,
write: writeOperational,
});
return;
}
const effectiveWorkspaceRoot = await commandProjectRoot();
const projectResultsRoot = effectiveWorkspaceRoot;
- const sourcePackageRoot = args.packageRoot ?? await resolvePackageRoot(effectiveWorkspaceRoot);
+ const sourcePackageRoot = args.packageRoot ?? effectiveWorkspaceRoot;
const loadedPackageSet = distribution.discoverSourcePackages === undefined
? undefined
: await loadDiscoveredSourcePackages(distribution, {
@@ -263,14 +182,14 @@ export async function runCli(
: { distributionPackageRoot: distribution.packageRoot }),
packageContributions,
});
- const workspace = await compiler.openFile(args.source);
- const sourceHeader = parseSourceHeader(workspace.entry.name, workspace.entry.text);
- const runMode = runFrontends.some((frontend) => frontend.id === sourceHeader.using);
- const authorMode = compiler.supportsFrontend(sourceHeader.using);
+ const workspace = await compiler.openEntry(args.source);
+ const selectedFrontend = workspace.entry.frontend;
+ const runMode = runFrontends.some((frontend) => frontend.id === selectedFrontend);
+ const authorMode = compiler.supportsFrontend(selectedFrontend);
if (runMode === authorMode) {
const message = runMode
- ? `Frontend ${sourceHeader.using} is ambiguously registered as Author and Run`
- : `No trusted Author or Run compiler accepts Frontend ${sourceHeader.using}`;
+ ? `Frontend ${selectedFrontend} is ambiguously registered as Author and Run`
+ : `No trusted Author or Run compiler accepts Frontend ${selectedFrontend}`;
throw new Error(message);
}
if ((args.command === "plan" || args.command === "pricing" || args.command === "build") && !runMode) {
@@ -290,7 +209,7 @@ export async function runCli(
ok: true,
run: projectPath(loaded.source, effectiveWorkspaceRoot),
author: projectPath(loaded.authorSource, effectiveWorkspaceRoot),
- frontend: sourceHeader.using,
+ frontend: selectedFrontend,
targetCount: loaded.document.targets.length,
targets: loaded.document.targets.map((item) => item.output),
candidates: loaded.document.candidates.length,
@@ -312,7 +231,7 @@ export async function runCli(
return;
}
{
- const result = await compiler.compileSource(workspace.entry, workspace);
+ const result = await compiler.compileResolvedSource(workspace.entry, workspace);
const authorFacing = result.exports.filter((item) =>
!item.name.includes(".__") && !/\.binding-\d+$/u.test(item.name) && !item.name.endsWith(".bindings"));
const outputs = authorFacing.filter((item) => item.ref.kind === "logical-output");
@@ -322,8 +241,8 @@ export async function runCli(
format: "hypit.cli-check@1" as const,
sourceKind: "author" as const,
ok: true,
- source: projectPath(workspace.entry.name, effectiveWorkspaceRoot),
- frontend: sourceHeader.using,
+ source: projectPath(workspace.entry.unit.name, effectiveWorkspaceRoot),
+ frontend: selectedFrontend,
units: result.closure.units.length,
assets: result.attachments.length,
modules: modules.length,
@@ -388,8 +307,9 @@ export async function runCli(
id: createPublicBuildId(),
definition: result.definition,
...(loadedPackageSet === undefined ? {} : {
- componentPackages: loadedPackageSet
- .filter((item) => (item.contribution.components?.length ?? 0) > 0)
+ executionPackages: loadedPackageSet
+ .filter((item) => (item.contribution.facets?.some((facet) =>
+ facet.abi === "hypit.producer-package@1" || facet.abi === "hypit.admission-package@1") ?? false))
.map((item) => item.specifier),
}),
catalog,
@@ -403,9 +323,6 @@ export async function runCli(
},
} as const;
const host = await runtimeHost(runtimeProfile);
- const controller = await host.controller({
- packageRoot: sourcePackageRoot,
- });
const evaluated = await evaluatePlanNeeds(result.definition, packageContributions);
const providers = await describePlanProviders(host, evaluated.state, evaluated);
assertPlannedRequests(evaluated.state, evaluated, providers);
@@ -415,7 +332,7 @@ export async function runCli(
// installing or starting declared programs.
assertPreflight(preflight);
try {
- await controller.worker.up({
+ await host.ensureExecution({
...(args.maxWaitMs === undefined ? {} : { maxWaitMs: args.maxWaitMs }),
});
} catch (error) {
@@ -453,7 +370,7 @@ export async function runCli(
if (args.follow && runtime !== undefined) {
built = await observeBuild(runtime, built, {
...(args.maxWaitMs === undefined ? {} : { maxWaitMs: args.maxWaitMs }),
- controller,
+ executionStatus: async () => await host.executionStatus(),
commandScope,
readResult: async () => await buildResults.repository.read(built.id),
onProgress: (progress) => {
@@ -621,18 +538,23 @@ export async function runCli(
const localRequestCount = providers?.filter((item) => item.status === "resolved" && item.pricing?.kind === "local").length ?? 0;
const providerRequestCount = providers?.filter((item) => item.status === "resolved" && item.pricing?.kind !== "local").length;
const requestIssueCount = needs.filter((item) => item.issue !== undefined).length;
+ const producerFailures = evaluated.producerFailures;
+ const producerFailureCount = producerFailures.length;
writeCliOutput(io, args.presentation, {
kind: "plan",
machine: createPlanOutput({
format: "hypit.cli-plan@1",
ok: (preflight?.ok ?? true) && unresolvedRequestCount === 0
- && unsupportedRequestCount === 0 && requestIssueCount === 0,
+ && unsupportedRequestCount === 0 && requestIssueCount === 0
+ && producerFailureCount === 0,
run: projectPath(loaded.path, effectiveWorkspaceRoot),
targetCount: targets.length,
targets,
steps: result.definition.plan.steps.length,
requestCount: needs.length,
requestIssueCount,
+ producerFailureCount,
+ producerFailures,
...(providerRequestCount === undefined ? {} : { providerRequestCount }),
...(providers === undefined ? {} : { localRequestCount, unresolvedRequestCount, unsupportedRequestCount }),
choiceCount: allChoices.length,
@@ -650,7 +572,8 @@ export async function runCli(
}, { verbose: args.presentation.verbose, limit: args.limit }),
});
if ((preflight !== undefined && !preflight.ok) || unresolvedRequestCount > 0
- || unsupportedRequestCount > 0 || requestIssueCount > 0) io.setExitCode?.(1);
+ || unsupportedRequestCount > 0 || requestIssueCount > 0
+ || producerFailureCount > 0) io.setExitCode?.(1);
} finally {
await planResults?.close();
}
diff --git a/packages/cli/src/node-application.ts b/packages/cli/src/node-application.ts
new file mode 100644
index 00000000..9778423f
--- /dev/null
+++ b/packages/cli/src/node-application.ts
@@ -0,0 +1,84 @@
+import { runCliApplication } from "./application.js";
+import type { CliApplication } from "./application.js";
+import { renderCliError } from "./output.js";
+import type { CliIo } from "./output.js";
+import { acceptSecretBytes } from "./secret-input.js";
+
+export type NodeCliRunner = (argv: readonly string[], io: CliIo) => void | Promise<void>;
+
+async function readSecret(prompt: string): Promise<string> {
+ if (process.stdin.isTTY !== true || typeof process.stdin.setRawMode !== "function") {
+ const chunks: Buffer[] = [];
+ for await (const chunk of process.stdin) chunks.push(Buffer.from(chunk));
+ return Buffer.concat(chunks).toString("utf8");
+ }
+ process.stderr.write(prompt);
+ return await new Promise<string>((resolve, reject) => {
+ const raw: number[] = [];
+ const finish = (error?: Error): void => {
+ process.stdin.off("data", input);
+ process.stdin.setRawMode(false);
+ process.stdin.pause();
+ process.stderr.write("\n");
+ if (error === undefined) resolve(Buffer.from(raw).toString("utf8"));
+ else reject(error);
+ };
+ const input = (chunk: Buffer): void => {
+ const result = acceptSecretBytes(raw, chunk);
+ if (result === "cancelled") finish(new Error("credential input cancelled"));
+ if (result === "done") finish();
+ };
+ process.stdin.setRawMode(true);
+ process.stdin.resume();
+ process.stdin.on("data", input);
+ });
+}
+
+/** Node terminal adapter shared by every assembled CLI application. */
+export async function runNodeCli(
+ argv: readonly string[],
+ run: NodeCliRunner,
+): Promise<void> {
+ const json = argv.includes("--json");
+ const debug = argv.includes("--debug");
+ const colorIndex = argv.indexOf("--color");
+ const colorMode = argv.includes("--no-color")
+ ? "never"
+ : colorIndex >= 0 ? argv[colorIndex + 1] : "auto";
+ const color = !json && colorMode !== "never" && process.env.TERM !== "dumb"
+ && (colorMode === "always" || (process.env.NO_COLOR === undefined && process.stdout.isTTY === true));
+ const unicode = process.env.TERM !== "dumb";
+ const io: CliIo = {
+ write: (text) => process.stdout.write(text),
+ writeProgress: (text) => process.stderr.write(text),
+ setExitCode: (code) => { process.exitCode = code; },
+ readSecret,
+ terminal: {
+ isTTY: process.stdout.isTTY === true,
+ color,
+ unicode,
+ columns: process.stdout.columns ?? 100,
+ },
+ };
+ try {
+ await run(argv, io);
+ } catch (error) {
+ const rendered = renderCliError(error, {
+ json,
+ color: !json && colorMode !== "never" && process.env.TERM !== "dumb"
+ && (colorMode === "always" || (process.env.NO_COLOR === undefined && process.stderr.isTTY === true)),
+ unicode,
+ debug,
+ });
+ (json ? process.stdout : process.stderr).write(rendered);
+ process.exitCode = 1;
+ }
+}
+
+/** Convenience entry for an already assembled application. */
+export async function runNodeCliApplication(
+ argv: readonly string[],
+ application: CliApplication,
+): Promise<void> {
+ await runNodeCli(argv, async (args, io) => await runCliApplication(args, io, application));
+}
diff --git a/packages/cli/src/oauth.ts b/packages/cli/src/oauth.ts
index 4c39d13b..cbd16071 100644
--- a/packages/cli/src/oauth.ts
+++ b/packages/cli/src/oauth.ts
@@ -76,7 +76,7 @@ function openAuthorizeUrl(url: string): void {
child.unref();
}
-/** Acquire one OAuth credential from the exact data declared by its Endpoint package. */
+/** Acquire one OAuth credential from the exact data declared by its Endpoint instance. */
export async function acquireOAuthCredential(
acquisition: CredentialAcquisition,
options: OAuthAcquisitionOptions = {},
diff --git a/packages/cli/src/observation.ts b/packages/cli/src/observation.ts
index a03e84de..07442352 100644
--- a/packages/cli/src/observation.ts
+++ b/packages/cli/src/observation.ts
@@ -1,6 +1,6 @@
-import type { BuildResultManifest } from "@hypit/build-result";
+import type { BuildResultManifest } from "@hypit/result";
-import type { CliBuildSubmission, CliBuildView, CliRuntimeControl, CliRuntimeController } from "./runtime-port.js";
+import type { CliBuildSubmission, CliBuildView, CliRuntimeControl } from "./runtime-port.js";
import { commandHint } from "./command-hint.js";
import type { CommandScope } from "./command-hint.js";
import { formatOperationProgress } from "./runtime-view.js";
@@ -122,7 +122,7 @@ export async function observeBuildView(
initial: CliBuildView,
options: {
readonly maxWaitMs?: number;
- readonly controller?: CliRuntimeController;
+ readonly executionStatus?: () => Promise<{ readonly state: "running" | "stopped" }>;
readonly onProgress?: (value: BuildProgressView) => void;
readonly commandScope?: CommandScope;
} = {},
@@ -157,11 +157,11 @@ export async function observeBuildView(
const elapsedMs = Date.now() - startedAt;
const remainingMs = options.maxWaitMs === undefined ? undefined : options.maxWaitMs - elapsedMs;
if (remainingMs !== undefined && remainingMs <= 0) break;
- if (options.controller !== undefined) {
- const worker = await options.controller.worker.status();
- if (worker.state !== "running") {
+ if (options.executionStatus !== undefined) {
+ const execution = await options.executionStatus();
+ if (execution.state !== "running") {
throw new Error(
- `Runtime Worker is ${worker.state}; stopped watching Build ${build}. `
+ `Runtime execution is ${execution.state}; stopped watching Build ${build}. `
+ `Inspect the Runtime with ${commandHint(["runtime", "status"], options.commandScope)}; `
+ `read execution evidence with ${commandHint(["logs", build], options.commandScope)}`,
);
@@ -185,7 +185,7 @@ export async function observeBuild(
initial: CliBuildSubmission,
options: {
readonly maxWaitMs?: number;
- readonly controller?: CliRuntimeController;
+ readonly executionStatus?: () => Promise<{ readonly state: "running" | "stopped" }>;
readonly readResult: () => Promise<BuildResultManifest | undefined>;
readonly onProgress?: (value: BuildProgressView) => void;
readonly commandScope?: CommandScope;
diff --git a/packages/cli/src/output.ts b/packages/cli/src/output.ts
index 897651fa..c88c4982 100644
--- a/packages/cli/src/output.ts
+++ b/packages/cli/src/output.ts
@@ -124,6 +124,12 @@ export type PlanOutput = {
readonly steps?: number;
readonly requestCount: number;
readonly requestIssueCount: number;
+ readonly producerFailureCount: number;
+ /** Complete deterministic Producer failures; errors are never hidden by the detail limit. */
+ readonly producerFailures: readonly {
+ readonly step: string;
+ readonly message: string;
+ }[];
/** Present when a Runtime Profile was selected. */
readonly providerRequestCount?: number;
readonly localRequestCount?: number;
@@ -209,7 +215,16 @@ export type PlanNeed = {
readonly issue?: string;
};
-export type CliMachineView = OperationalMachineView;
+/**
+ * Stable machine-output envelope shared by built-in and contributed commands.
+ *
+ * The generic CLI keeps its own outputs precise in `OperationalMachineView`, but
+ * must not enumerate every application module's payload in a central union.
+ */
+export type CliMachineView = {
+ readonly format: string;
+ readonly [field: string]: unknown;
+};
export type CliPresentation =
| {
@@ -518,6 +533,7 @@ function renderPlan(
["Requests", String(view.machine.requestCount)],
...(view.machine.choiceCount === 0 ? [] : [["Run choices", String(view.machine.choiceCount)] as const]),
...(view.machine.requestIssueCount === 0 ? [] : [["Request issues", String(view.machine.requestIssueCount)] as const]),
+ ...(view.machine.producerFailureCount === 0 ? [] : [["Producer failures", String(view.machine.producerFailureCount)] as const]),
...((view.machine.providerRequestCount ?? 0) === 0 ? [] : [["Provider requests", String(view.machine.providerRequestCount)] as const]),
...((view.machine.localRequestCount ?? 0) === 0 ? [] : [["Local requests", String(view.machine.localRequestCount)] as const]),
...((view.machine.unsupportedRequestCount ?? 0) === 0 ? [] : [["Unsupported", String(view.machine.unsupportedRequestCount)] as const]),
@@ -527,6 +543,12 @@ function renderPlan(
] as const]),
...(!verbose || view.machine.steps === undefined ? [] : [["Steps", String(view.machine.steps)] as const]),
], colors));
+ if (view.machine.producerFailures.length > 0) {
+ lines.push("", colors.strong("Producer failures"));
+ for (const failure of view.machine.producerFailures) {
+ lines.push(` ${colors.error(glyph(io, "×", "x"))} ${colors.accent(stepLabel(failure.step))}: ${failure.message}`);
+ }
+ }
if (view.machine.providers !== undefined) {
if (view.machine.providers.length > 0) lines.push("", colors.strong("Providers and price pages"));
const groups = new Map<string, PlanProvider[]>();
@@ -798,14 +820,14 @@ function commandHelp(topic: string, colors: Palette): readonly string[] | undefi
colors.accent(colors.strong("hypit check")),
colors.dim("Validate one self-described Author Source or Run Source without executing it."),
"",
- " hypit check <source> [--workspace <workspace>] [--asset-root <directory>]",
+ " hypit check <source> [--project <workspace>] [--asset-root <directory>]",
" --verbose lists exported names/types and historical references.",
],
doctor: [
colors.accent(colors.strong("hypit doctor")),
colors.dim("Diagnose project Results and, when selected or supplied, one Runtime Profile."),
"",
- " hypit doctor [--runtime <profile>] [--workspace <project>] [--endpoint <instance>]",
+ " hypit doctor [--runtime <profile>] [--project <project>] [--endpoint <instance>]",
" A positional Profile is also accepted in place of --runtime.",
" Repeat --endpoint <instance> to limit the operation to chosen services; omission covers the Profile.",
" Without a Runtime Profile, checks only the project's selected Result Store.",
@@ -814,7 +836,7 @@ function commandHelp(topic: string, colors: Palette): readonly string[] | undefi
colors.accent(colors.strong("hypit plan")),
colors.dim("Show targets, demanded requests and their readiness without executing them."),
"",
- " hypit plan <run-source> [--runtime <profile>] [--workspace <workspace>] [--asset-root <directory>]",
+ " hypit plan <run-source> [--runtime <profile>] [--project <workspace>] [--asset-root <directory>]",
"",
"With --runtime, plan also preflights only the demanded deployment slice and names the Provider",
"and price page behind each external request.",
@@ -826,7 +848,7 @@ function commandHelp(topic: string, colors: Palette): readonly string[] | undefi
colors.accent(colors.strong("hypit pricing")),
colors.dim("Read current pricing material from the selected Providers for the requests in one Run."),
"",
- " hypit pricing <run-source> [--runtime <profile>] [--workspace <workspace>] [--asset-root <directory>]",
+ " hypit pricing <run-source> [--runtime <profile>] [--project <workspace>] [--asset-root <directory>]",
"",
"Pricing is an explicit read-only network operation. It starts no Build and submits no generation.",
"Matching requests share their parameters and Provider rates, with source URLs.",
@@ -839,87 +861,37 @@ function commandHelp(topic: string, colors: Palette): readonly string[] | undefi
colors.accent(colors.strong("hypit build")),
colors.dim("Submit one durable Build and ensure its selected Runtime Worker is available."),
"",
- " hypit build <run-source> [--title <text>] [--runtime <profile>] [--workspace <workspace>] [--asset-root <directory>] [--follow]",
+ " hypit build <run-source> [--title <text>] [--runtime <profile>] [--project <workspace>] [--asset-root <directory>] [--follow]",
"",
" --title <text> give this Result a human-facing title",
" --follow observe the Build; the Worker still owns execution",
" --max-wait-ms <ms> bound startup or follow waiting",
],
- runtime: [
- colors.accent(colors.strong("hypit runtime")),
- colors.dim("Select a project Runtime Profile, then operate the local Build Worker."),
- "",
- " hypit runtime init [<profile>] [--workspace <project>] create and select a starter Profile",
- " hypit runtime use <profile> [--workspace <project>] select the project Profile",
- " hypit runtime unset [--workspace <project>] remove only that selection",
- " hypit runtime up [<profile>] [--endpoint <instance>] prepare helpers, then start the Worker",
- " hypit runtime status [<profile>] inspect the local Worker, active Builds and programs",
- " hypit runtime logs [<profile>] [--lines <count>]",
- " hypit runtime down [<profile>] stop the Worker; external programs keep running",
- "",
- "The project is resolved first. Selection is read only from that project's .hypit/runtime.",
- "All runtime actions accept --workspace <project>; operational actions also accept --runtime <profile>.",
- "For up, repeat --endpoint <instance> to prepare only chosen services; omission prepares the Profile.",
- "No Profile filename discovery or parent-project inheritance is performed.",
- "Remote Endpoints such as HypiHub are not started by this command; use doctor to test them.",
- ],
- packages: [
- colors.accent(colors.strong("hypit packages")),
- colors.dim("Inspect or install one pinned upstream npm package in the shared machine home."),
- "",
- " hypit packages status <package@exact-version>",
- " hypit packages install <package@exact-version>",
- "",
- "The package is reused by every project and later session on this machine.",
- "Each exact version has its own installation; npm owns package.json and package-lock.json.",
- "Preparation reports its install.log for live output and later diagnosis.",
- ],
- programs: [
- colors.accent(colors.strong("hypit programs")),
- colors.dim("Prepare and operate external programs declared by Endpoints in one Runtime Profile."),
- "",
- " hypit programs prepare [--runtime <profile>] [--endpoint <instance>] # resources only; does not start services",
- " hypit programs up [--runtime <profile>] [--workspace <project>] [--max-wait-ms <ms>]",
- " hypit programs status [--runtime <profile>] [--workspace <project>]",
- " hypit programs down [--runtime <profile>] [--workspace <project>]",
- " A positional Profile is also accepted in place of --runtime.",
- " Repeat --endpoint <instance> to limit the operation to chosen services; omission covers the Profile.",
- ],
activity: [
colors.accent(colors.strong("hypit activity")),
colors.dim("Inspect active Builds and Provider pool capacity."),
"",
- " hypit activity [--workspace <project>] [--runtime <profile>] [--watch]",
- " hypit activity [--workspace <project>] [--runtime <profile>] --watch --jsonl",
- ],
- paths: [
- colors.accent(colors.strong("hypit paths")),
- colors.dim("Show project, Runtime and host state locations without creating them."),
- "",
- " hypit paths [--workspace <project>] [--runtime <profile>]",
- " Shows whether Runtime selection comes from a command argument or the project's .hypit/runtime.",
- " Without --workspace, the nearest package.json above cwd defines the project (otherwise cwd).",
- " Relative command-line paths start at cwd, including when --workspace is supplied.",
+ " hypit activity [--project <project>] [--runtime <profile>] [--watch]",
+ " hypit activity [--project <project>] [--runtime <profile>] --watch --jsonl",
],
builds: [
colors.accent(colors.strong("hypit builds")),
colors.dim("List project-owned Build Results without opening a Runtime."),
"",
- " hypit builds [--workspace <project>] [--limit <count>] [--before <build-id>]",
+ " hypit builds [--project <project>] [--limit <count>] [--before <build-id>]",
],
logs: [
colors.accent(colors.strong("hypit logs")),
colors.dim("Read Build execution evidence; finished logs need only the project Result Repository."),
"",
- " hypit logs <build-id> [--workspace <project>] [--runtime <profile>] [--lines <count>]",
+ " hypit logs <build-id> [--project <project>] [--runtime <profile>] [--lines <count>]",
" --lines <count> show the last N records (default 50)",
- " runtime logs reads the Worker process log instead",
],
status: [
colors.accent(colors.strong("hypit status")),
colors.dim("Show one Build now, or keep watching it without owning execution."),
"",
- " hypit status <build-id> [--workspace <project>] [--runtime <profile>] [--watch]",
+ " hypit status <build-id> [--project <project>] [--runtime <profile>] [--watch]",
" --watch observe until a Result outcome or operator attention",
" --max-wait-ms <ms> stop watching after a bounded wait",
],
@@ -927,7 +899,7 @@ function commandHelp(topic: string, colors: Palette): readonly string[] | undefi
colors.accent(colors.strong("hypit inspect")),
colors.dim("Inspect one project-owned Build Result and its public Outputs."),
"",
- " hypit inspect <build-id> [--output <name>] [--limit <count>] [--workspace <project>]",
+ " hypit inspect <build-id> [--output <name>] [--limit <count>] [--project <project>]",
" Defaults to targets and highlighted Outputs. --verbose expands other available Outputs.",
" --output selects one exact name; --limit bounds expanded lists.",
],
@@ -935,7 +907,7 @@ function commandHelp(topic: string, colors: Palette): readonly string[] | undefi
colors.accent(colors.strong("hypit get")),
colors.dim("Export one exact named Build Output to an explicit local destination."),
"",
- " hypit get <build-id> --output <name> --to <path> [--workspace <project>]",
+ " hypit get <build-id> --output <name> --to <path> [--project <project>]",
"",
"Scalar and Resource Outputs become files. A Composite Output becomes a directory",
"containing value.json and every Resource referenced by that value.",
@@ -944,21 +916,21 @@ function commandHelp(topic: string, colors: Palette): readonly string[] | undefi
colors.accent(colors.strong("hypit history")),
colors.dim("Find one named Output across project-owned Build Results."),
"",
- " hypit history <output-name> [--workspace <project>] [--source <author-source>] [--limit <count>] [--before <build-id>]",
+ " hypit history <output-name> [--project <project>] [--source <author-source>] [--limit <count>] [--before <build-id>]",
],
cancel: [
colors.accent(colors.strong("hypit cancel")),
colors.dim("Stop one Build and request cancellation of submitted work when supported."),
"",
- " hypit cancel <build-id> [--workspace <project>] [--runtime <profile>] [--reason <text>]",
+ " hypit cancel <build-id> [--project <project>] [--runtime <profile>] [--reason <text>]",
],
result: [
colors.accent(colors.strong("hypit result")),
colors.dim("Edit one Result, finish an interrupted Result write, or discard an incomplete submission."),
"",
- " hypit result finish <build-id> [--workspace <project>] [--runtime <profile>]",
- " hypit result discard <build-id> [--workspace <project>] [--runtime <profile>]",
- " hypit result edit <build-id> [--workspace <project>] [--title <text>] [--note <text>]",
+ " hypit result finish <build-id> [--project <project>] [--runtime <profile>]",
+ " hypit result discard <build-id> [--project <project>] [--runtime <profile>]",
+ " hypit result edit <build-id> [--project <project>] [--title <text>] [--note <text>]",
" [--highlight <output> ...]",
" --clear-title remove the Result's human title",
" --clear-note remove its note",
@@ -971,7 +943,7 @@ function commandHelp(topic: string, colors: Palette): readonly string[] | undefi
" hypit auth status <endpoint-instance> [--runtime <profile>] [--slot <name>]",
" hypit auth login <endpoint-instance> [--runtime <profile>] [--slot <name>] [--from <secret-file>]",
" hypit auth logout <endpoint-instance> [--runtime <profile>] [--slot <name>]",
- " All auth actions accept --workspace <project> to use that project's selection.",
+ " All auth actions accept --project <project> to use that project's selection.",
" status shows credential presence and the Provider's declared browser login, if any.",
" login opens that browser flow or securely prompts for the secret; --from imports a secret instead.",
" Configure the service's Endpoint first. Storing a key does not install a Provider or select bindings.",
@@ -1013,15 +985,14 @@ export function writeCliHelp(io: CliIo, topic?: string): void {
"",
colors.strong("Runtime"),
row("doctor [profile]", "diagnose selected external setup"),
- row("runtime init|use|unset", "create or select this project's Runtime Profile"),
- row("runtime up|status|logs|down", "prepare and manage the local Build Runtime"),
- row("programs prepare|up|status|down", "manage declared external programs only"),
- row("packages install|status", "manage pinned upstream packages in the machine home"),
row("activity [--watch]", "show active Builds and their current phases"),
row("cancel <build-id>", "withdraw one active Build"),
- row("paths", "show physical state locations"),
row("auth status|login|logout", "manage Endpoint credentials"),
"",
+ colors.strong("Installation"),
+ row("version [--check]", "show this installed Hypit Distribution"),
+ row("cli status|use|remove", "manage explicit project CLI contributions"),
+ "",
colors.strong("Output"),
row("--json", "stable machine view"),
row("--verbose", "add bounded operational detail"),
diff --git a/packages/cli/src/paths.ts b/packages/cli/src/paths.ts
index 8ccddae6..83f371df 100644
--- a/packages/cli/src/paths.ts
+++ b/packages/cli/src/paths.ts
@@ -1,7 +1,30 @@
-import { resolve } from "node:path";
-
-export { hypitHostStateRoot } from "@hypit/runtime-host-node";
+import { homedir } from "node:os";
+import { join, resolve } from "node:path";
export function hypitProjectStateRoot(projectRoot: string): string {
return resolve(projectRoot, ".hypit");
}
+
+/** Persistent state owned by the installed Host, outside every author project and Runtime Profile. */
+export function hypitHostStateRoot(options: {
+ readonly env?: NodeJS.ProcessEnv;
+ readonly platform?: NodeJS.Platform;
+ readonly home?: string;
+} = {}): string {
+ const env = options.env ?? process.env;
+ const override = env.HYPIT_STATE_HOME;
+ if (override !== undefined && override.trim().length > 0) return resolve(override);
+ const platform = options.platform ?? process.platform;
+ const home = options.home ?? homedir();
+ if (platform === "darwin") return join(home, "Library", "Application Support", "Hypit");
+ if (platform === "win32") {
+ const local = env.LOCALAPPDATA;
+ return join(local === undefined || local.trim().length === 0
+ ? join(home, "AppData", "Local")
+ : local, "Hypit");
+ }
+ const state = env.XDG_STATE_HOME;
+ return join(state === undefined || state.trim().length === 0
+ ? join(home, ".local", "state")
+ : state, "hypit");
+}
diff --git a/packages/cli/src/public.ts b/packages/cli/src/public.ts
new file mode 100644
index 00000000..2578f136
--- /dev/null
+++ b/packages/cli/src/public.ts
@@ -0,0 +1,12 @@
+/** Public structural ABI for packages that contribute commands to the root Hypit CLI Host. */
+export type { CliApplicationContext, CliCommandModule } from "./application.js";
+export { commandHint } from "./command-hint.js";
+export { cliProviderLine, cliProviderView, createCliScratchResources, openCliRuntimeHost, selectCliProvider } from "./immediate.js";
+export { hypitHostStateRoot, hypitProjectStateRoot } from "./paths.js";
+export { writeCliOutput } from "./output.js";
+export { loadDiscoveredSourcePackages } from "./source-packages.js";
+export { discoverSourcePackages } from "./source-discovery.js";
+export { resolveBuildResultValue } from "./run-file.js";
+export type { CliCompilerOptions, CliDistribution } from "./distribution.js";
+export type { CliIo, CliMachineView, CliOutputOptions, CliTerminal } from "./output.js";
+export type * from "./runtime-port.js";
diff --git a/packages/cli/src/result-export.ts b/packages/cli/src/result-export.ts
index aaa04c73..8e65a54d 100644
--- a/packages/cli/src/result-export.ts
+++ b/packages/cli/src/result-export.ts
@@ -1,4 +1,4 @@
-import { fileReferenceIdentity } from "@hypit/build-result";
+import { fileReferenceIdentity } from "@hypit/result/node";
import { randomUUID } from "node:crypto";
import { lstat, mkdir, rename, rm, writeFile } from "node:fs/promises";
import { basename, dirname, join, relative, resolve, sep } from "node:path";
@@ -7,7 +7,7 @@ import type {
BuildResultFileRef,
BuildResultRepository,
RepositoryBuildResultOutput,
-} from "@hypit/build-result";
+} from "@hypit/result/node";
export type BuildResultExport = {
readonly build: string;
diff --git a/packages/cli/src/result-query.ts b/packages/cli/src/result-query.ts
index 83dc7f50..9367caf4 100644
--- a/packages/cli/src/result-query.ts
+++ b/packages/cli/src/result-query.ts
@@ -1,6 +1,6 @@
import { resolve } from "node:path";
-import type { BuildResultRepository, FinishedBuildResultManifest } from "@hypit/build-result";
+import type { BuildResultRepository, FinishedBuildResultManifest } from "@hypit/result";
export type BuildOutputHistoryPage = {
readonly results: readonly FinishedBuildResultManifest[];
@@ -32,7 +32,7 @@ export async function browseBuildOutputHistory(
for (let index = 0; index < page.results.length; index += 1) {
const manifest = page.results[index]!;
const sameSource = source === undefined
- || resolve(request.projectRoot, manifest.source.path) === source;
+ || resolve(request.projectRoot, manifest.source.id) === source;
if (sameSource && manifest.outputs[request.output] !== undefined) matches.push(manifest);
if (matches.length === request.limit) {
const hasOlder = index < page.results.length - 1 || page.next !== undefined;
diff --git a/packages/cli/src/run-file.ts b/packages/cli/src/run-file.ts
index 087c106b..d3a00b1d 100644
--- a/packages/cli/src/run-file.ts
+++ b/packages/cli/src/run-file.ts
@@ -1,35 +1,35 @@
-import { fileReferenceIdentity, locateRepositoryBuildResultOutput, ownedFileReference } from "@hypit/build-result";
+import { fileReferenceIdentity, locateRepositoryBuildResultOutput, ownedFileReference } from "@hypit/result/node";
import { randomUUID } from "node:crypto";
import type {
BuildResultRepository,
BuildResultFileRef,
BuildResultValuePath,
RepositoryBuildResultOutput,
-} from "@hypit/build-result";
-import { NodeRunCompiler } from "@hypit/compiler-node";
+} from "@hypit/result/node";
+import { RunCompiler } from "@hypit/compiler";
import type {
- NodeCompiledRun,
- NodeCompiler,
-} from "@hypit/compiler-node";
-import type { NodePackageContribution } from "@hypit/package-loader-node";
-import type { ArtifactAttachment, WorkspaceSession } from "@hypit/workspace";
+ CompiledRun,
+ Compiler,
+} from "@hypit/compiler";
+import type { PackageContribution } from "@hypit/loader";
+import type { BlobAttachment, WorkspaceSession } from "@hypit/workspace";
import type { BlobRef, CanonicalValue, StoredValue } from "@hypit/protocol";
import {
- installRunFragmentHostFacets,
- runFrontendsFromHostFacets,
+ installRunFragmentFacets,
+ runFrontendsFromFacets,
RunFragmentRegistry,
RunFrontendRegistry,
} from "@hypit/run";
import type { RunFrontend } from "@hypit/run";
-export type LoadedRunFile = NodeCompiledRun & {
+export type LoadedRunFile = CompiledRun & {
readonly path: string;
- readonly compiler: NodeRunCompiler;
+ readonly compiler: RunCompiler;
readonly resultResourceReferences: Readonly<Record<string, BuildResultFileRef>>;
};
type BuildResultResolutionSession = {
- readonly files: Map<string, ArtifactAttachment>;
+ readonly files: Map<string, BlobAttachment>;
readonly references: Map<string, BuildResultFileRef>;
readonly outputs: Map<string, Promise<RepositoryBuildResultOutput | undefined>>;
};
@@ -40,12 +40,12 @@ function createBuildResultResolutionSession(): BuildResultResolutionSession {
export async function checkRunFile(options: {
readonly workspace: WorkspaceSession;
- readonly authorCompiler: NodeCompiler;
+ readonly authorCompiler: Compiler;
readonly frontends: readonly RunFrontend[];
- readonly packageContributions: readonly NodePackageContribution[];
+ readonly packageContributions: readonly PackageContribution[];
}) {
const compiler = createRunCompiler(options);
- return await compiler.checkSource(options.workspace.entry, options.workspace);
+ return await compiler.checkResolvedSource(options.workspace.entry, options.workspace);
}
type ResultValueBindingTree = {
@@ -117,11 +117,11 @@ export async function resolveBuildResultValue(
): Promise<{
readonly type: RepositoryBuildResultOutput["type"];
readonly value: StoredValue;
- readonly attachments?: readonly ArtifactAttachment[];
+ readonly attachments?: readonly BlobAttachment[];
} | undefined> {
const manifest = await repository.read(build);
if (manifest?.outcome === undefined) return undefined;
- const resultAttachment = async (owner: string, file: BuildResultFileRef): Promise<ArtifactAttachment> => {
+ const resultAttachment = async (owner: string, file: BuildResultFileRef): Promise<BlobAttachment> => {
const address = fileReferenceIdentity(owner, file);
const existing = session.files.get(address);
if (existing !== undefined) return existing;
@@ -144,7 +144,7 @@ export async function resolveBuildResultValue(
session.references.set(artifact.resource, ownedFileReference(owner, file));
return attachment;
};
- const attachments = new Map<string, ArtifactAttachment>();
+ const attachments = new Map<string, BlobAttachment>();
const address = `${build}\u0000${output}`;
let pending = session.outputs.get(address);
if (pending === undefined) {
@@ -180,18 +180,18 @@ export async function resolveBuildResultValue(
}
function createRunCompiler(options: {
- readonly authorCompiler: NodeCompiler;
+ readonly authorCompiler: Compiler;
readonly frontends: readonly RunFrontend[];
- readonly packageContributions: readonly NodePackageContribution[];
+ readonly packageContributions: readonly PackageContribution[];
readonly results?: BuildResultRepository;
-}, resultSession = createBuildResultResolutionSession()): NodeRunCompiler {
+}, resultSession = createBuildResultResolutionSession()): RunCompiler {
const fragments = new RunFragmentRegistry();
for (const item of options.packageContributions) {
- installRunFragmentHostFacets(item.hostFacets ?? [], fragments);
+ installRunFragmentFacets(item.facets ?? [], fragments);
}
const frontends = new RunFrontendRegistry();
for (const frontend of options.frontends) frontends.register(frontend);
- return new NodeRunCompiler({
+ return new RunCompiler({
authorCompiler: options.authorCompiler,
frontends,
fragments,
@@ -207,26 +207,26 @@ function createRunCompiler(options: {
}
export function collectRunFrontends(
- packages: readonly NodePackageContribution[],
+ packages: readonly PackageContribution[],
): readonly RunFrontend[] {
- return packages.flatMap((item) => runFrontendsFromHostFacets(item.hostFacets ?? []));
+ return packages.flatMap((item) => runFrontendsFromFacets(item.facets ?? []));
}
export async function loadRunFile(options: {
readonly workspace: WorkspaceSession;
- readonly authorCompiler: NodeCompiler;
+ readonly authorCompiler: Compiler;
readonly frontends: readonly RunFrontend[];
- readonly packageContributions: readonly NodePackageContribution[];
+ readonly packageContributions: readonly PackageContribution[];
readonly results?: BuildResultRepository;
}): Promise<LoadedRunFile> {
const resultSession = createBuildResultResolutionSession();
const compiler = createRunCompiler(options, resultSession);
- const compiled = await compiler.compileSource(options.workspace.entry, options.workspace);
+ const compiled = await compiler.compileResolvedSource(options.workspace.entry, options.workspace);
const references = new Map<string, BuildResultFileRef>(compiled.attachments.flatMap((attachment) =>
attachment.location === undefined ? [] : [[attachment.artifact.resource, {
kind: "external-file" as const, uri: attachment.location,
size: attachment.artifact.size, mediaType: attachment.artifact.mediaType,
}]]));
for (const [resource, file] of resultSession.references) references.set(resource, file);
- return { path: options.workspace.entry.id, compiler, ...compiled, resultResourceReferences: Object.fromEntries(references) };
+ return { path: options.workspace.entry.unit.id, compiler, ...compiled, resultResourceReferences: Object.fromEntries(references) };
}
diff --git a/packages/cli/src/runtime-port.ts b/packages/cli/src/runtime-port.ts
index cac2e9cf..a7cc1f28 100644
--- a/packages/cli/src/runtime-port.ts
+++ b/packages/cli/src/runtime-port.ts
@@ -1,13 +1,199 @@
-export type {
- ManagedProgramProgress as CliManagedProgramProgress,
- ManagedProgramReport as CliManagedProgramReport,
- RuntimeController as CliRuntimeController,
- RuntimeHostControl as CliRuntimeControl,
- RuntimeHostBuildSubmission as CliBuildSubmission,
- RuntimeHostCredentialControl as CliCredentialControl,
- RuntimeHostCredentialStatus as CliCredentialStatus,
- RuntimeHostDoctorResult as CliRuntimeDoctorResult,
- RuntimeHostExecution as CliRuntime,
- BuildView as CliBuildView,
- RuntimeWorkerState as CliRuntimeWorkerState,
-} from "@hypit/runtime-host-node";
+import type { BlobAttachment } from "@hypit/workspace";
+import type { BuildResultForward } from "@hypit/result";
+import type { ExecutorOptions, ExecutorRunResult, ProducerRegistry } from "@hypit/executor";
+import type {
+ BuildDefinition,
+ BuildState,
+ CanonicalValue,
+ CapabilityRef,
+ LogicalOutputRef,
+ Need,
+ StoredValue,
+} from "@hypit/protocol";
+import type {
+ CapacityReservation,
+ CredentialAcquisition,
+ CredentialRef,
+ OperationSnapshot,
+ ResourceStore,
+} from "@hypit/runtime";
+
+export type CliResultRepositoryLocation = { readonly root: string; readonly path: string };
+
+export type CliDiagnostic = {
+ readonly severity: "error" | "warning" | "info";
+ readonly code: string;
+ readonly message: string;
+ readonly subject?: string;
+};
+
+export type CliBuildCatalogDescriptor = {
+ readonly source: { readonly path: string };
+ readonly run?: { readonly path: string };
+ readonly targets?: readonly LogicalOutputRef[];
+ readonly publishedOutputs: readonly {
+ readonly displayName?: string;
+ readonly name: string;
+ readonly ref: LogicalOutputRef;
+ }[];
+};
+
+export type CliBuildView = {
+ readonly id: string;
+ readonly createdAt: number;
+ readonly activity: "submitting" | "ready" | "running" | "waiting" | "saving-result";
+ readonly outcome?: "complete" | "failed" | "cancelled";
+ readonly issue?: { readonly scope: "result" | "cleanup"; readonly message: string };
+ readonly cancellationRequested: boolean;
+ readonly stop?: { readonly cause: "user-cancelled" | "execution-failed"; readonly reason?: string };
+ readonly source?: { readonly path: string };
+ readonly run?: { readonly path: string };
+ readonly targets: readonly string[];
+ readonly requests?: { readonly total: number; readonly completed: number };
+ readonly acceptedRecords: number;
+ readonly outstandingCommands: number;
+ readonly operations: readonly {
+ readonly id?: string;
+ readonly receipt?: import("@hypit/runtime").OperationReceipt;
+ readonly wakeAt?: number;
+ readonly endpoint: string;
+ readonly status: OperationSnapshot["status"];
+ readonly progress?: OperationSnapshot["progress"];
+ readonly failure?: OperationSnapshot["failure"];
+ }[];
+ readonly commands?: readonly {
+ readonly id: string;
+ readonly endpoint: string;
+ readonly progress: NonNullable<OperationSnapshot["progress"]>;
+ }[];
+};
+
+export type CliBuildSubmission = {
+ readonly id: string;
+ readonly state: BuildState;
+} & ({ readonly view: CliBuildView } | {
+ readonly completion: {
+ readonly build: string;
+ readonly outcome: "complete" | "failed" | "cancelled";
+ readonly reason?: string;
+ };
+});
+
+export type CliCredentialStatus = {
+ readonly endpoint: string;
+ readonly slot: string;
+ readonly label: string;
+ readonly kind: "secret" | "json";
+ readonly ref: CredentialRef;
+ readonly acquisition?: CredentialAcquisition;
+ readonly writable: boolean;
+ readonly configured: boolean;
+};
+
+export type CliRuntimeControl = {
+ logs?(build: string, lines: number): Promise<import("@hypit/runtime").ExecutionLogView | undefined>;
+ inspect(build: string): Promise<CliBuildView | undefined>;
+ activity(): Promise<{ readonly builds: readonly CliBuildView[]; readonly capacity: readonly CapacityReservation[] }>;
+ cancel(build: string, reason?: string): Promise<CliBuildView | undefined>;
+ close(): void | Promise<void>;
+};
+
+export type CliResultControl = {
+ finishResult(build: string): Promise<{
+ readonly id: string;
+ readonly outcome: "complete" | "failed" | "cancelled";
+ readonly issue?: { readonly scope: "result" | "cleanup"; readonly message: string };
+ } | undefined>;
+ discardSubmission(build: string): Promise<boolean>;
+ close(): void | Promise<void>;
+};
+
+export type CliCredentialControl = {
+ describeCredentials(endpoint?: string): Promise<readonly Omit<CliCredentialStatus, "configured">[]>;
+ credentials(endpoint?: string): Promise<readonly CliCredentialStatus[]>;
+ putCredential(endpoint: string, slot: string, secret: string): Promise<CliCredentialStatus>;
+ deleteCredential(endpoint: string, slot: string): Promise<{ readonly deleted: boolean; readonly credential: CliCredentialStatus }>;
+ close(): void | Promise<void>;
+};
+
+export type CliRuntime = CliRuntimeControl & CliCredentialControl & CliResultControl & {
+ build(request: {
+ readonly id: string;
+ readonly definition: BuildDefinition;
+ readonly executionPackages?: readonly string[];
+ readonly catalog: CliBuildCatalogDescriptor;
+ readonly attachments?: readonly BlobAttachment[];
+ readonly result: {
+ readonly repository: CliResultRepositoryLocation;
+ readonly title?: string;
+ readonly forwards?: readonly BuildResultForward[];
+ readonly resourceReferences?: Readonly<Record<string, import("@hypit/result").BuildResultFileRef>>;
+ };
+ }, options?: {
+ readonly follow?: boolean;
+ readonly pollIntervalMs?: number;
+ readonly maxWaitMs?: number;
+ readonly signal?: AbortSignal;
+ }): Promise<CliBuildSubmission>;
+};
+
+export type CliRuntimeDoctorResult = { readonly dataRoot: string; readonly diagnostics: readonly CliDiagnostic[] };
+
+export type CliTransientExecution = {
+ evaluate(input: {
+ readonly state: BuildState;
+ readonly producers: ProducerRegistry;
+ readonly validators: NonNullable<ExecutorOptions["validators"]>;
+ readonly resources: ResourceStore;
+ }): Promise<ExecutorRunResult>;
+ close(): void | Promise<void>;
+};
+
+export type CliCapabilityProvider = {
+ readonly request: string;
+ readonly capability: CapabilityRef;
+ readonly status: "resolved" | "unresolved" | "unsupported" | "ambiguous";
+ readonly endpoint?: string;
+ readonly use?: string;
+ readonly pricing?: { readonly kind: "page"; readonly url: string } | { readonly kind: "local" };
+ readonly endpoints?: readonly string[];
+ readonly rejections?: readonly { readonly endpoint: string; readonly message: string }[];
+ readonly binding?: string;
+};
+
+export type CliCapabilityPricing = CliCapabilityProvider & {
+ readonly pricingDocuments?: readonly { readonly source: string; readonly data: CanonicalValue; readonly summary?: string }[];
+ readonly pricingError?: string;
+};
+
+export type CliProviderQuery = {
+ readonly request: string;
+ readonly capability: CapabilityRef;
+ readonly returns: import("@hypit/protocol").TypeRef;
+ readonly constraints: CanonicalValue;
+ readonly pendingInputs?: readonly { readonly input: string; readonly role?: string }[];
+};
+
+export type CliInvocationObservation = {
+ readonly reportProgress?: (progress: import("@hypit/runtime").OperationProgress) => Promise<void>;
+ readonly reportDiagnostic?: (diagnostic: import("@hypit/runtime").ExecutionDiagnostic) => Promise<void>;
+};
+
+/** Runtime services consumed by the generic long-compilation command engine. */
+export type CliRuntimeHost = {
+ readonly profile: string;
+ /** Availability of the execution service selected by this Runtime implementation. */
+ executionStatus(): Promise<{ readonly state: "running" | "stopped" }>;
+ /** Make the selected execution service available before accepting durable work. */
+ ensureExecution(options?: { readonly maxWaitMs?: number }): Promise<{ readonly state: "running" | "stopped" }>;
+ createRuntime(options?: { readonly endpoints?: readonly string[] }): Promise<CliRuntime>;
+ openControl(options?: { readonly readOnly?: boolean }): Promise<CliRuntimeControl>;
+ openResultControl(): Promise<CliResultControl>;
+ openCredentials(endpoint: string): Promise<CliCredentialControl>;
+ preflight(options?: { readonly capabilities?: readonly CapabilityRef[]; readonly endpoints?: readonly string[] }): Promise<CliRuntimeDoctorResult>;
+ doctor(options?: { readonly capabilities?: readonly CapabilityRef[]; readonly endpoints?: readonly string[] }): Promise<CliRuntimeDoctorResult>;
+ providers(requests: readonly CliProviderQuery[]): Promise<readonly CliCapabilityProvider[]>;
+ pricing(requests: readonly CliProviderQuery[]): Promise<readonly CliCapabilityPricing[]>;
+ invoke(need: Need, resources: ResourceStore, observation?: CliInvocationObservation): Promise<{ readonly value: StoredValue }>;
+ openTransientExecution(): Promise<CliTransientExecution>;
+};
diff --git a/packages/cli/src/secret-input.ts b/packages/cli/src/secret-input.ts
new file mode 100644
index 00000000..c2da4ff6
--- /dev/null
+++ b/packages/cli/src/secret-input.ts
@@ -0,0 +1,20 @@
+function removeLastCodePoint(raw: number[]): void {
+ if (raw.length === 0) return;
+ let start = raw.length - 1;
+ while (start > 0 && (raw[start]! & 0xc0) === 0x80) start--;
+ raw.splice(start);
+}
+
+/** Consume terminal bytes for one hidden UTF-8 secret without echoing them. */
+export function acceptSecretBytes(
+ raw: number[],
+ chunk: Uint8Array,
+): "continue" | "done" | "cancelled" {
+ for (const byte of chunk) {
+ if (byte === 3) return "cancelled";
+ if (byte === 10 || byte === 13) return "done";
+ if (byte === 8 || byte === 127) removeLastCodePoint(raw);
+ else raw.push(byte);
+ }
+ return "continue";
+}
diff --git a/packages/cli/src/source-discovery.ts b/packages/cli/src/source-discovery.ts
index 17e65e8d..ef372d20 100644
--- a/packages/cli/src/source-discovery.ts
+++ b/packages/cli/src/source-discovery.ts
@@ -1,14 +1,15 @@
import { readFile, realpath } from "node:fs/promises";
import { dirname, isAbsolute, relative, resolve, sep } from "node:path";
-import { authorFrontendsFromHostFacets, prepareAuthorSource } from "@hypit/elaborator";
-import type { AuthorFrontend } from "@hypit/elaborator";
-import { physicalPackageName, resolveNodePackageSource } from "@hypit/package-loader-node";
-import type { LogicalPackageAddress, LoadedPackage } from "@hypit/package-loader-node";
+import { authorFrontendsFromFacets } from "@hypit/author";
+import type { AuthorFrontend } from "@hypit/author";
+import { physicalPackageName, resolveNodePackageSource } from "@hypit/loader/node";
+import type { LogicalPackageAddress, LoadedPackage } from "@hypit/loader";
import { modulePackageAbi } from "@hypit/protocol";
-import { prepareRunSource, runFragmentHostAbi, runFrontendsFromHostFacets } from "@hypit/run";
+import { runFragmentFacetAbi, runFrontendsFromFacets } from "@hypit/run";
import type { RunFrontend } from "@hypit/run";
-import { parseSourceHeader, sourceFrontendPackageAbi } from "@hypit/source";
+import { sourceFrontendPackageAbi } from "@hypit/source";
+import { resolveSelfDescribedTextSource } from "@hypit/source/text";
function isWithin(root: string, path: string): boolean {
const relation = relative(root, path);
@@ -49,12 +50,12 @@ export async function discoverSourcePackages(
const packages = options.packages ?? [];
const authorFrontends = [
...(options.bootstrapAuthorFrontends ?? []).map((frontend) => ({ frontend, physical: undefined as string | undefined })),
- ...packages.flatMap((item) => authorFrontendsFromHostFacets(item.contribution.hostFacets ?? [])
+ ...packages.flatMap((item) => authorFrontendsFromFacets(item.contribution.facets ?? [])
.map((frontend) => ({ frontend, physical: item.specifier as string | undefined }))),
];
const runFrontends = [
...(options.bootstrapRunFrontends ?? []).map((frontend) => ({ frontend, physical: undefined as string | undefined })),
- ...packages.flatMap((item) => runFrontendsFromHostFacets(item.contribution.hostFacets ?? [])
+ ...packages.flatMap((item) => runFrontendsFromFacets(item.contribution.facets ?? [])
.map((frontend) => ({ frontend, physical: item.specifier as string | undefined }))),
];
const selected = new Set<string>();
@@ -68,8 +69,8 @@ export async function discoverSourcePackages(
moduleOwners.set(request, item.specifier);
}
}
- for (const facet of item.contribution.hostFacets ?? []) {
- if (facet.abi !== runFragmentHostAbi) continue;
+ for (const facet of item.contribution.facets ?? []) {
+ if (facet.abi !== runFragmentFacetAbi) continue;
for (const request of facet.offers ?? []) fragmentOwners.set(request, item.specifier);
}
}
@@ -92,8 +93,6 @@ export async function discoverSourcePackages(
...(options.distributionPackageRoot === undefined
? {}
: { distributionRoots: [options.distributionPackageRoot] }),
- externalRoots: [],
- allowExternal: false,
});
return { source: located.source, root: located.root };
};
@@ -107,12 +106,12 @@ export async function discoverSourcePackages(
visited.add(canonical);
const text = await readFile(canonical, "utf8");
const name = relative(canonicalRoot, canonical);
- const header = parseSourceHeader(name, text);
- const authors = authorFrontends.filter((item) => item.frontend.id === header.using);
- const runs = runFrontends.filter((item) => item.frontend.id === header.using);
- if (authors.length + runs.length > 1) throw new Error(`Source Frontend ${header.using} is ambiguously provided`);
+ const resolved = resolveSelfDescribedTextSource({ id: canonical, name, text });
+ const authors = authorFrontends.filter((item) => item.frontend.id === resolved.frontend);
+ const runs = runFrontends.filter((item) => item.frontend.id === resolved.frontend);
+ if (authors.length + runs.length > 1) throw new Error(`Source Frontend ${resolved.frontend} is ambiguously provided`);
if (authors.length + runs.length === 0) {
- requireLogical({ abi: sourceFrontendPackageAbi, name: header.using }, undefined);
+ requireLogical({ abi: sourceFrontendPackageAbi, name: resolved.frontend }, undefined);
return;
}
if (authors.length === 1) {
@@ -120,7 +119,7 @@ export async function discoverSourcePackages(
if (owner.physical !== undefined) {
requireLogical({ abi: sourceFrontendPackageAbi, name: owner.frontend.id }, owner.physical);
}
- const discovery = await owner.frontend.discover(prepareAuthorSource({ id: canonical, name, text }));
+ const discovery = await owner.frontend.discover(resolved.unit);
for (const request of discovery.modules) {
requireLogical({ abi: modulePackageAbi, name: request }, moduleOwners.get(request));
}
@@ -134,9 +133,9 @@ export async function discoverSourcePackages(
if (owner.physical !== undefined) {
requireLogical({ abi: sourceFrontendPackageAbi, name: owner.frontend.id }, owner.physical);
}
- const discovery = await owner.frontend.discover(prepareRunSource({ id: canonical, name, text }));
+ const discovery = await owner.frontend.discover(resolved.unit);
for (const item of discovery.imports) {
- requireLogical({ abi: runFragmentHostAbi, name: item.from }, fragmentOwners.get(item.from));
+ requireLogical({ abi: runFragmentFacetAbi, name: item.from }, fragmentOwners.get(item.from));
}
const imported = resolveImportedSource(canonical, canonicalRoot, discovery.author.source);
await discover(imported.source, imported.root);
diff --git a/packages/cli/src/source-packages.ts b/packages/cli/src/source-packages.ts
index 77ecdee1..30abc3c0 100644
--- a/packages/cli/src/source-packages.ts
+++ b/packages/cli/src/source-packages.ts
@@ -1,11 +1,11 @@
import {
loadNodePackageSelection,
-} from "@hypit/package-loader-node";
+} from "@hypit/loader/node";
import type {
LoadedPackage,
LogicalPackageAddress,
- NodePackageSelectionRequest,
-} from "@hypit/package-loader-node";
+} from "@hypit/loader";
+import type { NodePackageSelectionRequest } from "@hypit/loader/node";
import { modulePackageAbi } from "@hypit/protocol";
import type { CliDistribution } from "./distribution.js";
@@ -48,7 +48,7 @@ function offerCounts(packages: readonly LoadedPackage[]): ReadonlyMap<string, nu
`${module.manifest.name}@${module.manifest.version}`,
...(module.specifiers ?? []),
].map((name) => ({ abi: modulePackageAbi, name }))),
- ...(item.contribution.hostFacets ?? []).flatMap((facet) =>
+ ...(item.contribution.facets ?? []).flatMap((facet) =>
(facet.offers ?? []).map((name) => ({ abi: facet.abi, name }))),
];
for (const address of new Set(offers.map((offer) => `${offer.abi}\u0000${offer.name}`))) {
diff --git a/packages/video-cli/src/version.ts b/packages/cli/src/version.ts
similarity index 73%
rename from packages/video-cli/src/version.ts
rename to packages/cli/src/version.ts
index 4894662c..1115e317 100644
--- a/packages/video-cli/src/version.ts
+++ b/packages/cli/src/version.ts
@@ -1,28 +1,47 @@
import { readFile } from "node:fs/promises";
import { resolve } from "node:path";
-import type { CliIo } from "@hypit/cli";
-import { requestDeadline } from "@hypit/runtime-kit";
-type VersionEnvironment = {
+import type { CliIo } from "./output.js";
+
+export type VersionEnvironment = {
readonly packageRoot: string;
readonly launcher?: string;
readonly fetch: typeof globalThis.fetch;
readonly timeoutMs?: number;
};
-export function writeVersionHelp(io: CliIo): void {
+export function writeVersionHelp(io: Pick<CliIo, "write">): void {
io.write("Usage: hypit version [--check] [--registry <url>] [--json]\n\n"
+ "Show the executing Distribution and launcher without opening a project or Runtime.\n"
+ "--check queries npm latest (registry.npmjs.org by default); --registry selects a mirror.\n"
+ "No packages or Skills are updated. hypit --version remains a local version-only query.\n");
}
-/** Installation discovery belongs to the executable, independent of video execution and Skill installers. */
-export async function runVersionCli(argv: readonly string[], io: CliIo, environment: VersionEnvironment = {
- packageRoot: resolve(import.meta.dirname, "../../.."),
- launcher: resolve(import.meta.dirname, "../../../bin/hypit.mjs"),
- fetch: globalThis.fetch,
-}): Promise<void> {
+function deadline(timeoutMs: number): {
+ readonly signal: AbortSignal;
+ wait<T>(value: Promise<T>): Promise<T>;
+ finish(): void;
+} {
+ const controller = new AbortController();
+ let rejectTimeout: ((reason: Error) => void) | undefined;
+ const timeout = new Promise<never>((_resolve, reject) => { rejectTimeout = reject; });
+ const timer = setTimeout(() => {
+ controller.abort();
+ rejectTimeout?.(new Error("Registry version query timed out; latest version is unknown"));
+ }, timeoutMs);
+ return {
+ signal: controller.signal,
+ async wait<T>(value: Promise<T>): Promise<T> { return await Promise.race([value, timeout]); },
+ finish() { clearTimeout(timer); },
+ };
+}
+
+/** Installation discovery belongs to the root CLI Host, never to one domain contribution. */
+export async function runVersionCli(
+ argv: readonly string[],
+ io: CliIo,
+ environment: VersionEnvironment,
+): Promise<void> {
let check = false;
let json = false;
let registry = "https://registry.npmjs.org/";
@@ -52,14 +71,13 @@ export async function runVersionCli(argv: readonly string[], io: CliIo, environm
let latest: { registry: string; version?: string; matchesInstalled?: boolean; error?: string } | undefined;
if (check) {
latest = { registry };
- const deadline = requestDeadline(environment.timeoutMs ?? 10_000,
- () => new Error("Registry version query timed out; latest version is unknown"));
+ const request = deadline(environment.timeoutMs ?? 10_000);
try {
- const response = await deadline.wait(environment.fetch(new URL(`${encodeURIComponent(manifest.name)}/latest`, registry), {
- signal: deadline.signal, headers: { accept: "application/json" },
+ const response = await request.wait(environment.fetch(new URL(`${encodeURIComponent(manifest.name)}/latest`, registry), {
+ signal: request.signal, headers: { accept: "application/json" },
}));
if (!response.ok) throw new Error(`Registry returned HTTP ${response.status}; latest version is unknown`);
- const body = await deadline.wait(response.json()) as { name?: unknown; version?: unknown };
+ const body = await request.wait(response.json()) as { name?: unknown; version?: unknown };
if (body.name !== manifest.name || typeof body.version !== "string" || body.version.length === 0) {
throw new Error("Registry returned no matching package version; latest version is unknown");
}
@@ -68,7 +86,7 @@ export async function runVersionCli(argv: readonly string[], io: CliIo, environm
} catch (error) {
latest.error = error instanceof Error ? error.message : String(error);
io.setExitCode?.(1);
- } finally { deadline.finish(); }
+ } finally { request.finish(); }
}
const report = {
format: "hypit.cli-version@1", package: manifest.name, version: manifest.version,
diff --git a/packages/cli/src/view.ts b/packages/cli/src/view.ts
index 1864ae9c..dfa4e02a 100644
--- a/packages/cli/src/view.ts
+++ b/packages/cli/src/view.ts
@@ -4,10 +4,10 @@ import type {
BuildResultManifest,
BuildResultRepository,
RepositoryBuildResultOutputDescription,
-} from "@hypit/build-result";
+} from "@hypit/result";
import { buildIdCreatedAt } from "@hypit/protocol";
import type { TypeRef } from "@hypit/protocol";
-import type { BuildView } from "@hypit/runtime-host-node";
+import type { CliBuildView as BuildView } from "./runtime-port.js";
import { commandHint } from "./command-hint.js";
import type { CommandScope } from "./command-hint.js";
@@ -258,8 +258,8 @@ export async function buildResultView(
createdAt: buildCreatedAtIso(manifest.id),
...(manifest.finishedAt === undefined ? {} : { finishedAt: new Date(manifest.finishedAt).toISOString() }),
outcome: manifest.outcome ?? "open",
- source: projectPath(manifest.source.path, options.projectRoot),
- ...(manifest.run === undefined ? {} : { run: projectPath(manifest.run.path, options.projectRoot) }),
+ source: projectPath(manifest.source.id, options.projectRoot),
+ ...(manifest.run === undefined ? {} : { run: projectPath(manifest.run.id, options.projectRoot) }),
targetCount: manifest.targets.length,
targets: manifest.targets,
outputCount: available.length,
diff --git a/packages/cli/test/application.test.ts b/packages/cli/test/application.test.ts
new file mode 100644
index 00000000..3db13d38
--- /dev/null
+++ b/packages/cli/test/application.test.ts
@@ -0,0 +1,97 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { runCliApplication } from "../src/application.js";
+import type { CliApplication, CliCommandModule } from "../src/application.js";
+import type { CliDistribution } from "../src/distribution.js";
+
+const unusedDistribution = {
+ bootstrapPackages: [],
+ createCompiler() { throw new Error("compiler must not open in command-module tests"); },
+ async openRuntimeHost() { throw new Error("runtime must not open in command-module tests"); },
+ async openProjectResults() { throw new Error("results must not open in command-module tests"); },
+ async diagnoseProjectResults() { throw new Error("results must not open in command-module tests"); },
+} as unknown as CliDistribution;
+
+function application(commandModules: readonly CliCommandModule[]): CliApplication {
+ return { distribution: unusedDistribution, commandModules };
+}
+
+test("application dispatches one explicitly assembled command module", async () => {
+ const calls: string[][] = [];
+ let receivedContext: Parameters<CliCommandModule["run"]>[2] | undefined;
+ const module: CliCommandModule = {
+ format: "hypit.cli-command@1",
+ id: "test.tools",
+ commands: ["probe", "inspect-tool"],
+ writeHelp(argv, io) { io.write(`help:${argv.join(" ")}`); },
+ run(argv, io, context) { calls.push([...argv]); receivedContext = context; io.write("ran"); },
+ };
+ let output = "";
+ await runCliApplication(["probe", "asset.bin"], { write: text => { output += text; } }, application([module]));
+ assert.equal(output, "ran");
+ assert.deepEqual(calls, [["probe", "asset.bin"]]);
+ assert.equal(receivedContext?.distribution, unusedDistribution);
+ assert.equal(typeof receivedContext?.cwd, "string");
+ assert.equal(typeof receivedContext?.resolveProjectRoot, "function");
+});
+
+test("application composes root and topic help without teaching generic CLI the module", async () => {
+ const module: CliCommandModule = {
+ format: "hypit.cli-command@1",
+ id: "test.frames",
+ commands: ["frames"],
+ writeRootHelp(io) { io.write("\nFrames\n frames <source>\n"); },
+ writeHelp(_argv, io) { io.write("frames help\n"); },
+ run() { throw new Error("help cannot execute the command"); },
+ };
+ let root = "";
+ await runCliApplication([], { write: text => { root += text; } }, application([module]));
+ assert.match(root, /check <source>/u);
+ assert.match(root, /Frames\n frames <source>/u);
+
+ let topic = "";
+ await runCliApplication(["help", "frames"], { write: text => { topic += text; } }, application([module]));
+ assert.equal(topic, "frames help\n");
+});
+
+test("the generic Host has no second package installation command", async () => {
+ let help = "";
+ await runCliApplication([], { write: text => { help += text; } }, application([]));
+ assert.doesNotMatch(help, /packages install|packages status/u);
+ await assert.rejects(
+ runCliApplication(["packages", "status", "[email protected]"], { write() {} }, application([])),
+ /Unknown command/u,
+ );
+});
+
+test("arguments after passthrough do not become application help", async () => {
+ let ran = false;
+ const module: CliCommandModule = {
+ format: "hypit.cli-command@1",
+ id: "test.capture",
+ commands: ["capture"],
+ writeHelp() { throw new Error("script --help must remain script input"); },
+ run() { ran = true; },
+ };
+ await runCliApplication(["capture", "run", "script.mjs", "--", "--help"], { write() {} }, application([module]));
+ assert.equal(ran, true);
+});
+
+test("application rejects command shadowing instead of silently choosing an owner", async () => {
+ const command = (id: string, name: string): CliCommandModule => ({
+ format: "hypit.cli-command@1",
+ id,
+ commands: [name],
+ writeHelp() {},
+ run() {},
+ });
+ await assert.rejects(
+ runCliApplication(["tool"], { write() {} }, application([command("one", "tool"), command("two", "tool")])),
+ /owned by both one and two/u,
+ );
+ await assert.rejects(
+ runCliApplication(["build"], { write() {} }, application([command("video", "build")])),
+ /cannot replace generic command "build"/u,
+ );
+});
diff --git a/packages/cli/test/build-programs.test.ts b/packages/cli/test/build-programs.test.ts
index 581929a9..c607056e 100644
--- a/packages/cli/test/build-programs.test.ts
+++ b/packages/cli/test/build-programs.test.ts
@@ -4,15 +4,19 @@ import { tmpdir } from "node:os";
import { dirname, join, resolve } from "node:path";
import test from "node:test";
-import { FileBuildResultRepository } from "@hypit/build-result";
-import { createRunFrontendHostFacet } from "@hypit/run";
+import { FileBuildResultRepository } from "@hypit/result/node";
+import { createRunFrontendFacet } from "@hypit/run";
-import { runCli } from "../src/main.js";
+import { runCli as runCliEngine } from "../src/main.js";
import { commandHint } from "../src/command-hint.js";
import type { CliDistribution } from "../src/distribution.js";
-import type { RuntimeDoctorDiagnostic } from "@hypit/runtime-kit";
+import type { CliDiagnostic as RuntimeDoctorDiagnostic } from "../src/runtime-port.js";
const io = { write: () => {} };
+const runCli: typeof runCliEngine = async (argv, output, selected) => await runCliEngine(argv, output, selected, {
+ cwd: tmpdir(),
+ resolveProjectRoot: async (explicit) => await realpath(explicit ?? tmpdir()),
+});
/**
* Enough of a Distribution to reach the build handler: a Run Frontend the
@@ -29,9 +33,9 @@ function distribution(
bootstrapPackages: [{
specifier: "@example/run-frontend",
contribution: {
- format: "hypit.node-package@1",
- hostFacets: [createRunFrontendHostFacet({
- id: "@hypit/run-markup@1",
+ format: "hypit.package@1",
+ facets: [createRunFrontendFacet({
+ id: "@hypit/markup/run@1",
discover: () => ({ author: { source: authorSource }, imports: [] }),
decode: () => ({ document: {
format: "hypit.run-document@1",
@@ -45,8 +49,11 @@ function distribution(
},
}],
createCompiler: () => ({
- openFile: async (path: string) => {
- const source = async (name: string) => ({ id: name, name, text: await readFile(name, "utf8") });
+ openEntry: async (path: string) => {
+ const source = async (name: string) => ({
+ unit: { id: name, name, bytes: new TextEncoder().encode(await readFile(name, "utf8")) },
+ frontend: name.endsWith(".svrun") ? "@hypit/markup/run@1" : "@hypit/markup@1",
+ });
return {
entry: await source(path),
resolveSource: async (_importer: unknown, request: { readonly from: string }) =>
@@ -55,8 +62,8 @@ function distribution(
};
},
supportsFrontend: () => false,
- compileSource: async (entry: { readonly id: string }) => ({
- closure: { entry: entry.id, units: [] },
+ compileResolvedSource: async (entry: { readonly unit: { readonly id: string } }) => ({
+ closure: { entry: entry.unit.id, units: [] },
provenance: { format: "hypit.author-provenance@1", elements: [] },
program: { closure: { format: "hypit.closure@1", modules: [{ manifest: {
format: "hypit.module@1",
@@ -104,6 +111,8 @@ function distribution(
diagnoseProjectResults: async () => ({ diagnostics: [] }),
openRuntimeHost: async (path: string) => ({
profile: path,
+ ensureExecution: async () => ({ state: "running" as const }),
+ executionStatus: async () => ({ state: "running" as const }),
resolvePaths: async () => ({}),
controller: async () => ({
profile: path,
@@ -139,7 +148,7 @@ function distribution(
async function runSource(): Promise<string> {
const root = await mkdtemp(join(tmpdir(), "hypit-build-programs-"));
const path = join(root, "build.svrun");
- await writeFile(path, '<?svml using="@hypit/run-markup@1"?>\n<svrun/>\n', "utf8");
+ await writeFile(path, '<?svml using="@hypit/markup/run@1"?>\n<svrun/>\n', "utf8");
await writeFile(join(root, "main.svml"), "author", "utf8");
return path;
}
@@ -227,7 +236,7 @@ test("Build confirms durable submission before following stable work progress",
const projectRoot = await realpath(dirname(source));
const runtimeProfile = resolve("/p/a selected runtime.json");
await runCli([
- "build", source, "--workspace", projectRoot, "--runtime", runtimeProfile,
+ "build", source, "--project", projectRoot, "--runtime", runtimeProfile,
"--follow", "--max-wait-ms", "0", "--json",
], {
write(text) { output += text; }, writeProgress(text) { progress += text; },
@@ -238,7 +247,7 @@ test("Build confirms durable submission before following stable work progress",
output = "";
await runCli([
- "build", source, "--workspace", projectRoot, "--runtime", runtimeProfile,
+ "build", source, "--project", projectRoot, "--runtime", runtimeProfile,
], { write(text) { output += text; } }, distribution(calls, [], "./main.svml", execution));
const id = /Watch\s+hypit status (\S+)/u.exec(output)?.[1];
assert.ok(id);
diff --git a/packages/cli/test/build-results.test.ts b/packages/cli/test/build-results.test.ts
index e6417aae..868a2770 100644
--- a/packages/cli/test/build-results.test.ts
+++ b/packages/cli/test/build-results.test.ts
@@ -11,13 +11,13 @@ import {
FileBuildResult,
FileBuildResultRepository,
ownedFileReference,
-} from "@hypit/build-result";
-import { ModulePackageRegistry, NodeCompiler } from "@hypit/compiler-node";
-import { AuthorFrontendRegistry, sealGraphFragment } from "@hypit/elaborator";
+} from "@hypit/result/node";
+import { ModulePackageRegistry, Compiler } from "@hypit/compiler";
+import { AuthorFrontendRegistry, sealGraphFragment } from "@hypit/author";
import { createMarkupAuthorFrontend, MarkupSurfaceRegistry } from "@hypit/markup";
import type { BuildState, ModuleManifest, ProducerRef, TypeRef } from "@hypit/protocol";
-import { runMarkupFrontend } from "@hypit/run-markup";
-import { NodeFilesystemWorkspace } from "@hypit/workspace-fs-node";
+import { runMarkupFrontend } from "@hypit/markup/run";
+import { NodeFilesystemWorkspace } from "@hypit/workspace/node";
import type { CliDistribution } from "../src/distribution.js";
import { createCatalogDescriptor } from "../src/build-planning.js";
@@ -43,8 +43,8 @@ async function fixture(root: string, id = "bld_20260902T110000000Z_0000000001",
const result = await FileBuildResult.create(join(root, ".hypit", "results"), {
id,
title: "episode-stage",
- source: { path: source },
- run: { path: "build.svrun" },
+ source: { id: source },
+ run: { id: "build.svrun" },
targets: ["stage.value"],
publishedOutputs: [{ name: "stage.value", output: "logical:stage" }],
});
@@ -73,7 +73,7 @@ function resultDistribution(): CliDistribution {
async function jsonCommand(args: readonly string[], root: string): Promise<unknown> {
let output = "";
- await runCli([...args, "--workspace", root, "--json"], {
+ await runCli([...args, "--project", root, "--json"], {
write(text) { output += text; },
}, resultDistribution());
return JSON.parse(output);
@@ -81,7 +81,7 @@ async function jsonCommand(args: readonly string[], root: string): Promise<unkno
async function humanCommand(args: readonly string[], root: string): Promise<string> {
let output = "";
- await runCli([...args, "--workspace", root], {
+ await runCli([...args, "--project", root], {
write(text) { output += text; },
}, resultDistribution());
return output;
@@ -169,7 +169,7 @@ test("history scans older pages for matches and compares project-relative source
]) {
const writer = await repository.create({
id,
- source: { path: "other.svml" },
+ source: { id: "other.svml" },
targets: [],
publishedOutputs: [],
});
@@ -204,7 +204,7 @@ test("get exports Resource bytes and a self-contained Composite directory", asyn
try {
const result = await FileBuildResult.create(join(root, ".hypit", "results"), {
id: build,
- source: { path: join(root, "main.svml") },
+ source: { id: join(root, "main.svml") },
targets: ["final.video"],
publishedOutputs: [
{ name: "final.video", output: "logical:video" },
@@ -281,22 +281,22 @@ test("get requires an exact Output name and an explicit destination", async () =
try {
const silent = { write() {} };
await assert.rejects(
- runCli(["get", "bld_20260902T110000000Z_0000000001", "--workspace", root], silent, resultDistribution()),
+ runCli(["get", "bld_20260902T110000000Z_0000000001", "--project", root], silent, resultDistribution()),
/get requires --output/u,
);
await assert.rejects(
runCli([
- "get", "bld_20260902T110000000Z_0000000001", "--output", "stage.value", "--workspace", root,
+ "get", "bld_20260902T110000000Z_0000000001", "--output", "stage.value", "--project", root,
], silent, resultDistribution()),
/get requires --to/u,
);
await assert.rejects(
- runCli(["history", "--source", join(root, "main.svml"), "--workspace", root], silent,
+ runCli(["history", "--source", join(root, "main.svml"), "--project", root], silent,
resultDistribution()),
/history requires one exact Output name/u,
);
await assert.rejects(
- runCli(["history", "stage.value", "--pin", "--workspace", root], silent, resultDistribution()),
+ runCli(["history", "stage.value", "--pin", "--project", root], silent, resultDistribution()),
/unknown option --pin/u,
);
} finally {
@@ -411,7 +411,7 @@ test("build-record selects one exact Result Output without leaking its storage a
return resolved;
},
}));
- const authorCompiler = new NodeCompiler({
+ const authorCompiler = new Compiler({
modules,
frontends: authorFrontends,
workspace: new NodeFilesystemWorkspace({ root }),
@@ -420,8 +420,8 @@ test("build-record selects one exact Result Output without leaking its storage a
const resultsRoot = join(root, ".hypit", "results");
const result = await FileBuildResult.create(resultsRoot, {
id: "bld_20260902T110000001Z_0000000001",
- source: { path: join(root, "main.svml") },
- run: { path: join(root, "prior.svrun") },
+ source: { id: join(root, "main.svml") },
+ run: { id: join(root, "prior.svrun") },
targets: ["shot.video"],
publishedOutputs: [{ name: "shot.video", output: "logical:video" }],
});
@@ -456,7 +456,7 @@ test("build-record selects one exact Result Output without leaking its storage a
<import as="media" from="example.result-reuse@1"/>
<media:Video id="shot"/>
</svml>`, "utf8");
- await writeFile(runFile, `<?svml using="@hypit/run-markup@1"?>
+ await writeFile(runFile, `<?svml using="@hypit/markup/run@1"?>
<svrun version="1">
<author source="./main.svml"/>
<target output="shot.video"/>
@@ -464,7 +464,7 @@ test("build-record selects one exact Result Output without leaking its storage a
<satisfy output="shot.video" candidate="prior"/>
</svrun>`, "utf8");
- const workspace = await authorCompiler.openFile(runFile);
+ const workspace = await authorCompiler.openEntry(runFile);
const repository = new FileBuildResultRepository(resultsRoot);
let opens = 0;
let resolves = 0;
@@ -557,7 +557,7 @@ test("build-record selects one exact Result Output without leaking its storage a
if (rootValue.kind !== "value") throw new Error("expected value");
const extra = { kind: "blob" as const, resource: `res_${id}`, size: 1, mediaType: "image/png" };
const current = await repository.create({
- id, source: { path: authorFile }, targets: ["shot.video"],
+ id, source: { id: authorFile }, targets: ["shot.video"],
publishedOutputs: [{ name: "shot.video", output: "wrapped" }],
resourceReferences: imported.resultResourceReferences,
});
@@ -582,14 +582,14 @@ test("build-record selects one exact Result Output without leaking its storage a
for await (const chunk of (await repository.openFile(id, original.file))!) received.push(...chunk);
assert.deepEqual(Uint8Array.from(received), bytes);
await writeFile(runFile, (await readFile(runFile, "utf8")).replace(/build="[^"]+"/, `build="${id}"`));
- imported = await materializeImport(await loadRunFile({ workspace: await authorCompiler.openFile(runFile), authorCompiler,
+ imported = await materializeImport(await loadRunFile({ workspace: await authorCompiler.openEntry(runFile), authorCompiler,
frontends: [runMarkupFrontend], packageContributions: [], results: repository }), id);
}
// Explicit export collects a standalone bundle, including same-named files with different owners.
const bundle = join(root, "exported-layout");
await jsonCommand(["get", "bld_20260902T110000003Z_0000000001", "--output", "shot.video", "--to", bundle], root);
- const exported = JSON.parse(await readFile(join(bundle, "value.json"), "utf8")) as import("@hypit/build-result").BuildResultValueDocument;
+ const exported = JSON.parse(await readFile(join(bundle, "value.json"), "utf8")) as import("@hypit/result").BuildResultValueDocument;
assert.equal(exported.resources.length, 3);
const exportedPaths = new Set<string>();
for (const binding of exported.resources) {
@@ -605,17 +605,17 @@ test("build-record selects one exact Result Output without leaking its storage a
// A file Candidate is a live address, even when republished by separate Builds.
const externalPath = join(root, "selected.mp4");
await writeFile(externalPath, bytes);
- await writeFile(runFile, `<?svml using="@hypit/run-markup@1"?>
+ await writeFile(runFile, `<?svml using="@hypit/markup/run@1"?>
<svrun version="1"><author source="./main.svml"/><target output="shot.video"/>
<file id="selected" type="example.result-reuse@1#Video" from="./selected.mp4" media-type="video/mp4"/>
<satisfy output="shot.video" candidate="selected"/></svrun>`);
- const externalRun = await loadRunFile({ workspace: await authorCompiler.openFile(runFile), authorCompiler,
+ const externalRun = await loadRunFile({ workspace: await authorCompiler.openEntry(runFile), authorCompiler,
frontends: [runMarkupFrontend], packageContributions: [], results: repository });
assert.deepEqual(Object.values(externalRun.resultResourceReferences), [{
kind: "external-file", uri: pathToFileURL(await realpath(externalPath)).href, size: bytes.length, mediaType: "video/mp4",
}]);
for (const id of ["bld_20260902T110000004Z_0000000001", "bld_20260902T110000005Z_0000000001"]) {
- const current = await repository.create({ id, source: { path: authorFile }, targets: ["shot.video"],
+ const current = await repository.create({ id, source: { id: authorFile }, targets: ["shot.video"],
publishedOutputs: [{ name: "shot.video", output: logicalOutput!.id }],
resourceReferences: externalRun.resultResourceReferences });
await current.sync({ state: externalRun.compiler.planCompilation(externalRun).state,
@@ -663,7 +663,7 @@ test("Composite Result resources rebuild each shared container once", async () =
} }),
describeFile: async () => file,
openFile: async () => undefined,
- } as unknown as import("@hypit/build-result").BuildResultRepository;
+ } as unknown as import("@hypit/result").BuildResultRepository;
const resolved = await resolveBuildResultValue(repository, "owner", "composite");
assert.equal(resolved?.value.kind, "inline");
assert.equal(visited, count, "the root array is rebuilt once rather than once per Resource binding");
@@ -675,7 +675,7 @@ test("a failed Result exposes task receipts and credential references without a
const id = "bld_20260906T110000000Z_0000000001";
try {
const result = await FileBuildResult.create(join(root, ".hypit", "results"), {
- id, source: { path: "main.svml" }, targets: [], publishedOutputs: [],
+ id, source: { id: "main.svml" }, targets: [], publishedOutputs: [],
});
const operation = {
operation: "op-1", command: "need-1", endpoint: "selected-account", pool: "my-pool",
@@ -707,7 +707,7 @@ test("logs reads finished evidence without a Runtime and clearly limits the tail
try {
const id = "bld_20260913T130000000Z_0000000001";
const result = await FileBuildResult.create(join(root, ".hypit/results"), {
- id, source: { path: "main.svml" }, targets: [], publishedOutputs: [],
+ id, source: { id: "main.svml" }, targets: [], publishedOutputs: [],
});
const records = ["started", "completed"].map((kind, time) => ({ format: "hypit.execution-log@1", time, kind, endpoint: "renderer", command: "c1" }));
await result.finish({ outcome: "complete", executionLog: (async function* () {
@@ -768,13 +768,13 @@ test("logs reports unavailable evidence as unsuccessful, while an existing empty
if (state === "no-log") await fixture(root);
if (state === "empty-log") {
const result = await FileBuildResult.create(join(root, ".hypit/results"), {
- id: "bld_20260902T110000001Z_0000000001", source: { path: "main.svml" }, targets: [], publishedOutputs: [],
+ id: "bld_20260902T110000001Z_0000000001", source: { id: "main.svml" }, targets: [], publishedOutputs: [],
});
await result.finish({ outcome: "complete", executionLog: (async function* () {})() });
}
let exit = 0;
let output = "";
- await runCli(["logs", state === "empty-log" ? "bld_20260902T110000001Z_0000000001" : id, "--workspace", root, "--json"], {
+ await runCli(["logs", state === "empty-log" ? "bld_20260902T110000001Z_0000000001" : id, "--project", root, "--json"], {
write: (text) => { output += text; }, setExitCode: (code) => { exit = code; },
}, resultDistribution());
assert.equal(exit, state === "empty-log" ? 0 : 1);
diff --git a/packages/cli/test/command-hint.test.ts b/packages/cli/test/command-hint.test.ts
index 45b745c5..72dfd1f7 100644
--- a/packages/cli/test/command-hint.test.ts
+++ b/packages/cli/test/command-hint.test.ts
@@ -12,11 +12,11 @@ test("POSIX command hints preserve selectors and literal path characters when co
const output = execFileSync("/bin/sh", ["-c",
`hypit() { "$HINT_TEST_NODE" -e 'process.stdout.write(JSON.stringify(process.argv.slice(1)))' -- "$@"; }; ${command}`,
], { encoding: "utf8", env: { ...process.env, HINT_TEST_NODE: process.execPath } });
- assert.deepEqual(JSON.parse(output), [...args, "--workspace", projectRoot, "--runtime", runtimeProfile]);
+ assert.deepEqual(JSON.parse(output), [...args, "--project", projectRoot, "--runtime", runtimeProfile]);
});
test("PowerShell command hints quote paths as literal strings", () => {
assert.equal(commandHint(["status", "build-1", "--watch"], {
projectRoot: "C:\\Films\\director's cut", runtimeProfile: "C:\\$profiles\\voice`new.json",
- }, "powershell"), "hypit status build-1 --watch --workspace 'C:\\Films\\director''s cut' --runtime 'C:\\$profiles\\voice`new.json'");
+ }, "powershell"), "hypit status build-1 --watch --project 'C:\\Films\\director''s cut' --runtime 'C:\\$profiles\\voice`new.json'");
});
diff --git a/packages/cli/test/control-commands.test.ts b/packages/cli/test/control-commands.test.ts
index 0e8e0d56..89ea120a 100644
--- a/packages/cli/test/control-commands.test.ts
+++ b/packages/cli/test/control-commands.test.ts
@@ -5,11 +5,30 @@ import { join, resolve } from "node:path";
import test from "node:test";
import type { CliDistribution } from "../src/distribution.js";
-import { runCli } from "../src/main.js";
+import { runCliApplication } from "../src/application.js";
+import type { CliIo } from "../src/output.js";
import type { CliCredentialControl, CliRuntimeControl } from "../src/runtime-port.js";
import { createLocalCredentialControl } from "@hypit/runtime-local";
+import { cliCommandModules } from "../../runtime-local/src/cli.js";
import { commandHint } from "../src/command-hint.js";
+const runCli = async (argv: readonly string[], output: CliIo, selected: CliDistribution) => await runCliApplication(
+ argv,
+ output,
+ {
+ // The real video application assembles both generic and Local Runtime Host
+ // ports. These focused doubles do the same when mounting Local commands.
+ distribution: {
+ ...selected,
+ openLocalRuntimeHost: async (path: string, options: Parameters<CliDistribution["openRuntimeHost"]>[1]) =>
+ await selected.openRuntimeHost(path, options),
+ } as CliDistribution,
+ commandModules: cliCommandModules,
+ cwd: tmpdir(),
+ resolveProjectRoot: async (explicit) => await realpath(explicit ?? tmpdir()),
+ },
+);
+
test("activity opens Runtime control without constructing execution Providers", async () => {
const calls: string[] = [];
const control = {
@@ -28,6 +47,7 @@ test("activity opens Runtime control without constructing execution Providers",
calls.push("control.create");
return control;
},
+ executionStatus: async () => ({ state: "stopped" as const }),
controller: async () => ({
worker: { status: async () => ({ state: "stopped", profile: path, logPath: "/tmp/worker.log" }) },
}),
@@ -65,7 +85,7 @@ test("doctor retains later errors even with a small display limit", async () =>
] }) } as unknown as CliDistribution;
let output = "";
let exitCode = 0;
- await runCli(["doctor", "--workspace", tmpdir(), "--limit", "1", "--json"], {
+ await runCli(["doctor", "--project", tmpdir(), "--limit", "1", "--json"], {
write(text) { output += text; }, setExitCode(code) { exitCode = code; },
}, selected);
assert.equal(exitCode, 1);
@@ -79,7 +99,7 @@ test("finished status reports failure details and a nonzero exit without a Runti
}) } as unknown as CliDistribution;
let output = "";
let exitCode = 0;
- await runCli(["status", "failed", "--workspace", tmpdir()], {
+ await runCli(["status", "failed", "--project", tmpdir()], {
write(text) { output += text; }, setExitCode(code) { exitCode = code; },
}, selected);
assert.equal(exitCode, 1);
@@ -90,7 +110,7 @@ test("status --watch follows active execution, then reads its finished Result",
const calls: string[] = [];
const resultLocation = {
root: "/project",
- selection: { use: "@hypit/build-result-fs", config: { path: ".hypit/results" } },
+ path: ".hypit/results",
} as const;
const view = () => ({
id: "build-watch",
@@ -115,6 +135,7 @@ test("status --watch follows active execution, then reads its finished Result",
openRuntimeHost: async (path: string) => ({
profile: path,
openControl: async () => control,
+ executionStatus: async () => ({ state: "running" as const }),
controller: async () => ({
worker: { status: async () => ({ state: "running", profile: path, pid: 1, logPath: "/tmp/worker.log" }) },
}),
@@ -296,7 +317,7 @@ test("status preserves Runtime decision and attention when its Result Store is u
let exitCode = 0;
await runCli([
- "status", view.id, "--workspace", tmpdir(), "--runtime", "/tmp/runtime with space.json", "--json",
+ "status", view.id, "--project", tmpdir(), "--runtime", "/tmp/runtime with space.json", "--json",
], { write: (text) => { output += text; }, setExitCode: (code) => { exitCode = code; } }, distribution);
const result = JSON.parse(output) as {
@@ -319,7 +340,7 @@ test("status preserves Runtime decision and attention when its Result Store is u
view.issue = { scope: "cleanup", message: "temporary resource cleanup unavailable" };
output = "";
await runCli([
- "status", view.id, "--workspace", tmpdir(), "--runtime", "/tmp/runtime with space.json", "--json",
+ "status", view.id, "--project", tmpdir(), "--runtime", "/tmp/runtime with space.json", "--json",
], { write: (text) => { output += text; } }, distribution);
const cleanup = JSON.parse(output).build.attention;
assert.equal(cleanup.message, "temporary resource cleanup unavailable");
@@ -429,7 +450,7 @@ test("command options fail closed instead of being silently ignored", async () =
);
await assert.rejects(
async () => await runCli([
- "doctor", "/tmp/runtime.json", "--workspace", tmpdir(),
+ "doctor", "/tmp/runtime.json", "--project", tmpdir(),
], io, distribution),
/profile delegated: .*runtime\.json/u,
);
@@ -456,7 +477,7 @@ test("doctor diagnoses project Results without requiring a Runtime Profile", asy
},
} as unknown as CliDistribution;
let output = "";
- await runCli(["doctor", "--workspace", projectRoot, "--json"], {
+ await runCli(["doctor", "--project", projectRoot, "--json"], {
write(text) { output += text; },
}, distribution);
assert.deepEqual(calls, [`results:${projectRoot}`]);
@@ -709,16 +730,14 @@ test("a stopped Worker ends observation with scoped evidence commands, not a Res
}),
close() { closed = true; },
}),
- controller: async () => ({ worker: {
- status: async () => ({ state: "stopped", profile: runtimeProfile, logPath: "/tmp/worker.log" }),
- } }),
+ executionStatus: async () => ({ state: "stopped" as const }),
}),
openProjectResults: async () => { resultOpened = true; throw new Error("must not be mistaken for result storage"); },
} as unknown as CliDistribution;
await assert.rejects(runCli([
- "status", "waiting-build", "--workspace", projectRoot, "--runtime", runtimeProfile, "--watch", "--json",
+ "status", "waiting-build", "--project", projectRoot, "--runtime", runtimeProfile, "--watch", "--json",
], { write() {} }, selected), (error: Error) => {
- assert.match(error.message, /Runtime Worker is stopped; stopped watching Build waiting-build/u);
+ assert.match(error.message, /Runtime execution is stopped; stopped watching Build waiting-build/u);
assert.ok(error.message.includes(commandHint(["runtime", "status"], { projectRoot, runtimeProfile })));
assert.ok(error.message.includes(commandHint(["logs", "waiting-build"], { projectRoot, runtimeProfile })));
return true;
diff --git a/packages/cli/test/installed-application.test.ts b/packages/cli/test/installed-application.test.ts
new file mode 100644
index 00000000..abef1729
--- /dev/null
+++ b/packages/cli/test/installed-application.test.ts
@@ -0,0 +1,112 @@
+import assert from "node:assert/strict";
+import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import test from "node:test";
+
+import { runInstalledCliApplication } from "../src/installed-application.js";
+import type { CliDistribution } from "../src/distribution.js";
+
+const unusedDistribution = {
+ bootstrapPackages: [],
+ createCompiler() { throw new Error("compiler must not open in command contribution tests"); },
+ async openRuntimeHost() { throw new Error("runtime must not open in command contribution tests"); },
+ async openProjectResults() { throw new Error("results must not open in command contribution tests"); },
+ async diagnoseProjectResults() { throw new Error("results must not open in command contribution tests"); },
+} as unknown as CliDistribution;
+
+async function fixture(command = "greet"): Promise<{
+ readonly root: string;
+ readonly distribution: string;
+ readonly project: string;
+}> {
+ const root = await mkdtemp(join(tmpdir(), "hypit-cli-composition-"));
+ const distribution = join(root, "distribution");
+ const project = join(root, "project");
+ const extension = join(project, "node_modules", "@acme", "tools");
+ await mkdir(distribution, { recursive: true });
+ await mkdir(extension, { recursive: true });
+ await writeFile(join(distribution, "package.json"), JSON.stringify({
+ name: "@hypit/hypit", version: "0.3.0", hypit: { cli: { use: [] } },
+ }));
+ await writeFile(join(project, "package.json"), JSON.stringify({
+ name: "example", private: true, devDependencies: { "@acme/tools": "1.2.3" },
+ hypit: { project: true },
+ }));
+ await writeFile(join(extension, "package.json"), JSON.stringify({
+ name: "@acme/tools", version: "1.2.3", type: "module", exports: { "./cli": "./cli.mjs" },
+ }));
+ await writeFile(join(extension, "cli.mjs"), `export const cliCommandModules = [{
+ format: "hypit.cli-command@1",
+ id: "@acme/tools",
+ commands: [${JSON.stringify(command)}],
+ writeRootHelp(io) { io.write("\\nAcme\\n ${command} <name>\\n"); },
+ writeHelp(_argv, io) { io.write("${command} help\\n"); },
+ run(argv, io) { io.write("hello " + (argv[1] ?? "world") + "\\n"); }
+ }];\n`);
+ return { root, distribution, project };
+}
+
+test("the root Host enables and removes one installed project command contribution", async () => {
+ const value = await fixture();
+ try {
+ const options = { distribution: unusedDistribution, distributionRoot: value.distribution, cwd: value.project };
+ let selected = "";
+ await runInstalledCliApplication(["cli", "use", "@acme/tools/cli"], {
+ write: text => { selected += text; },
+ }, options);
+ assert.match(selected, /selected: @acme\/tools\/cli/u);
+ const manifest = JSON.parse(await readFile(join(value.project, "package.json"), "utf8"));
+ assert.deepEqual(manifest.hypit.cli.use, ["@acme/tools/cli"]);
+
+ let output = "";
+ await runInstalledCliApplication(["greet", "Hypit"], { write: text => { output += text; } }, options);
+ assert.equal(output, "hello Hypit\n");
+
+ let status = "";
+ await runInstalledCliApplication(["cli", "status", "--json"], {
+ write: text => { status += text; },
+ }, options);
+ assert.deepEqual(JSON.parse(status).contributions[0], {
+ origin: "project", specifier: "@acme/tools/cli", package: "@acme/tools",
+ version: "1.2.3", commands: ["greet"],
+ });
+
+ await runInstalledCliApplication(["cli", "remove", "@acme/tools/cli"], { write() {} }, options);
+ await assert.rejects(
+ runInstalledCliApplication(["greet"], { write() {} }, options),
+ /Unknown command/u,
+ );
+ } finally { await rm(value.root, { recursive: true, force: true }); }
+});
+
+test("installing a package does not grant commands before explicit project selection", async () => {
+ const value = await fixture();
+ try {
+ await assert.rejects(runInstalledCliApplication(["greet"], { write() {} }, {
+ distribution: unusedDistribution, distributionRoot: value.distribution, cwd: value.project,
+ }), /Unknown command/u);
+ } finally { await rm(value.root, { recursive: true, force: true }); }
+});
+
+test("a project command contribution cannot replace a root command", async () => {
+ const value = await fixture("build");
+ try {
+ await assert.rejects(runInstalledCliApplication(["cli", "use", "@acme/tools/cli"], { write() {} }, {
+ distribution: unusedDistribution, distributionRoot: value.distribution, cwd: value.project,
+ }), /cannot replace generic command "build"/u);
+ const manifest = JSON.parse(await readFile(join(value.project, "package.json"), "utf8"));
+ assert.deepEqual(manifest.hypit, { project: true });
+ } finally { await rm(value.root, { recursive: true, force: true }); }
+});
+
+test("a project cannot select a package that its package.json does not own", async () => {
+ const value = await fixture();
+ try {
+ const manifestPath = join(value.project, "package.json");
+ await writeFile(manifestPath, JSON.stringify({ name: "example", private: true, hypit: { project: true } }));
+ await assert.rejects(runInstalledCliApplication(["cli", "use", "@acme/tools/cli"], { write() {} }, {
+ distribution: unusedDistribution, distributionRoot: value.distribution, cwd: value.project,
+ }), /not a direct dependency/u);
+ } finally { await rm(value.root, { recursive: true, force: true }); }
+});
diff --git a/packages/cli/test/output.test.ts b/packages/cli/test/output.test.ts
index 762b07a2..c2015217 100644
--- a/packages/cli/test/output.test.ts
+++ b/packages/cli/test/output.test.ts
@@ -82,6 +82,8 @@ test("plan presents useful choices and readable requests without default graph i
steps: 2,
requestCount: 1,
requestIssueCount: 0,
+ producerFailureCount: 0,
+ producerFailures: [],
preflight: {
ok: true,
capabilityCount: 1,
@@ -118,6 +120,8 @@ test("plan names the Provider and price page behind each request, and points at
steps: 3,
requestCount: 2,
requestIssueCount: 0,
+ producerFailureCount: 0,
+ producerFailures: [],
choiceCount: 0,
choices: [],
} as const;
@@ -134,7 +138,7 @@ test("plan names the Provider and price page behind each request, and points at
use: "@hypit/provider-hypihub",
pricing: { kind: "page", url: "https://hypit.ai/commercial/pricing/" },
},
- { request: "media:one", capability: "@hypit/media@1#inspect", status: "resolved", endpoint: "media.local", use: "@hypit/provider-media-local", pricing: { kind: "local" } },
+ { request: "media:one", capability: "@hypit/media@1#inspect", status: "resolved", endpoint: "media.local", use: "@hypit/media-local", pricing: { kind: "local" } },
{ request: "whisper:one", capability: "@hypit/whisperx@1#whisperx-alignment", status: "resolved", endpoint: "whisperx.remote", use: "@hypit/provider-example" },
{
request: "image:one",
@@ -301,7 +305,7 @@ test("run check treats historical reuse as a normal summary", () => {
ok: true,
run: "/project/build.svrun",
author: "/project/main.svml",
- frontend: "@hypit/run-markup@1",
+ frontend: "@hypit/markup/run@1",
targetCount: 1,
targets: ["final.video"],
candidates: 1,
@@ -323,6 +327,8 @@ test("plan scope omits unused branches while retaining every demanded request an
const plan = {
format: "hypit.cli-plan@1" as const, ok: false, run: "build.svrun", targetCount: 2,
targets: ["final.video", "poster.image"], steps: 400, requestCount: needs.length, requestIssueCount: 1,
+ producerFailureCount: 1,
+ producerFailures: [{ step: "source::component::timeline.resolve", message: "Timeline end must be after its start" }],
choiceCount: 35, choices: Array.from({ length: 35 }, (_, i) => ({ output: `old-${i}`, candidate: `selected-${i}` })),
unreached: Array.from({ length: 125 }, (_, i) => ({ output: `unused-${i}`, operation: "old-producer" })),
needs, providers: needs.map((need) => ({ request: need.request, capability: need.capability, status: "resolved" as const, endpoint: "local" })),
@@ -342,6 +348,7 @@ test("plan scope omits unused branches while retaining every demanded request an
assert.deepEqual(parsed.preflight.diagnostics, plan.preflight.diagnostics);
const rendered = capture(human, { kind: "plan", machine });
assert.match(rendered, /missing source/u);
+ assert.match(rendered, /timeline\.resolve: Timeline end must be after its start/u);
assert.match(rendered, /last required error/u);
assert.doesNotMatch(rendered, /old-\d|unused-\d/u);
assert.match(rendered, /request summary unavailable/u);
@@ -362,7 +369,7 @@ test("help is concise and describes stable rather than complete output", () => {
assert.match(output, /^Hypit\n/u);
assert.match(output, /Results/u);
assert.match(output, /stable machine view/u);
- assert.match(output, /programs prepare\|up\|status\|down/u);
+ assert.doesNotMatch(output, /programs prepare\|up\|status\|down/u);
assert.doesNotMatch(output, /Typical flow|complete machine-readable|image --prompt/u);
});
diff --git a/packages/cli/test/plan-needs.test.ts b/packages/cli/test/plan-needs.test.ts
index 55d2b79b..b25decf8 100644
--- a/packages/cli/test/plan-needs.test.ts
+++ b/packages/cli/test/plan-needs.test.ts
@@ -1,7 +1,38 @@
import assert from "node:assert/strict";
import test from "node:test";
-import { summarizeConstraints } from "../src/build-planning.js";
+import { createProducerPackageFacet } from "@hypit/producer";
+
+import { createGreetingBuild, producers } from "../../kernel/test/greeting-fixture.js";
+import { evaluatePlanNeeds, summarizeConstraints } from "../src/build-planning.js";
+
+test("Plan retains a deterministic Producer failure even when the Build has no external Need", async () => {
+ const state = createGreetingBuild({ targetOutputs: ["prompt"] });
+ const authored = new Set(state.program.records.map((record) => record.id));
+ const definition = {
+ format: "hypit.build-definition@1" as const,
+ program: state.program,
+ initialRecords: state.records.filter((record) => !authored.has(record.id)),
+ plan: state.plan,
+ targets: state.targets,
+ };
+ const evaluated = await evaluatePlanNeeds(definition, [{
+ format: "hypit.package@1",
+ facets: [createProducerPackageFacet({
+ producers: [{
+ producer: producers.makePrompt,
+ handler() {
+ throw new Error("Timeline end must be after its start");
+ },
+ }],
+ })],
+ }]);
+
+ assert.equal(evaluated.needs.size, 0);
+ assert.equal(evaluated.producerFailures.length, 1);
+ assert.equal(evaluated.producerFailures[0]?.step, state.plan.steps[0]?.id);
+ assert.match(evaluated.producerFailures[0]?.message ?? "", /Timeline end must be after its start/u);
+});
test("a generic request summary reads only declared top-level fields and counts references by kind", () => {
const summary = summarizeConstraints({
diff --git a/packages/cli/test/programs-command.test.ts b/packages/cli/test/programs-command.test.ts
index e1ce04fd..a4d72bc5 100644
--- a/packages/cli/test/programs-command.test.ts
+++ b/packages/cli/test/programs-command.test.ts
@@ -4,12 +4,29 @@ import { tmpdir } from "node:os";
import { resolve } from "node:path";
import test from "node:test";
-import { runCli } from "../src/main.js";
+import { runCliApplication } from "../src/application.js";
import { commandHint } from "../src/command-hint.js";
import type { CliDistribution } from "../src/distribution.js";
-import type { CliManagedProgramProgress, CliManagedProgramReport, CliRuntimeController } from "../src/runtime-port.js";
+import type { CliIo } from "../src/output.js";
+import { cliCommandModules } from "../../runtime-local/src/cli.js";
+import type { ManagedProgramProgress as CliManagedProgramProgress, ManagedProgramReport as CliManagedProgramReport } from "../../runtime-local/src/programs.js";
+import type { RuntimeController as CliRuntimeController } from "../../runtime-local/src/host-api.js";
const io = { write: () => {} };
+const runCli = async (argv: readonly string[], output: CliIo, selected: CliDistribution) =>
+ await runCliApplication(argv, output, {
+ // This suite mounts the Local Runtime command contribution onto deliberately
+ // small Distribution doubles. Assemble its product-specific Host port just
+ // as the real video executable does; the generic CLI port remains separate.
+ distribution: {
+ ...selected,
+ openLocalRuntimeHost: async (path: string, options: Parameters<CliDistribution["openRuntimeHost"]>[1]) =>
+ await selected.openRuntimeHost(path, options),
+ } as CliDistribution,
+ commandModules: cliCommandModules,
+ cwd: tmpdir(),
+ resolveProjectRoot: async (explicit) => await realpath(explicit ?? tmpdir()),
+ });
function controller(
path: string,
@@ -43,7 +60,6 @@ function distribution(calls: string[], reports: readonly CliManagedProgramReport
bootstrapPackages: [],
openRuntimeHost: async (path: string) => ({
profile: path,
- prepare: async () => [],
createRuntime: async () => ({ close: async () => {} }),
controller: async () => controller(path, calls, reports),
}),
@@ -68,7 +84,7 @@ test("programs dispatches lifecycle through the selected Runtime Controller", as
test("programs without a Runtime Profile explains how to select one", async () => {
const projectRoot = await realpath(tmpdir());
await assert.rejects(
- runCli(["programs", "status", "--workspace", projectRoot], io, distribution([])),
+ runCli(["programs", "status", "--project", projectRoot], io, distribution([])),
/programs requires a Runtime; run hypit runtime init, select one with runtime use, or pass --runtime <profile>/u,
);
});
@@ -80,19 +96,13 @@ test("programs accepts prepare, up, down and status", async () => {
);
});
-test("scoped preparation and startup receive the same explicit Endpoint set", async () => {
+test("scoped Program startup receives the explicit Endpoint set", async () => {
const calls: string[] = [];
- let prepared: unknown;
- const selected = distribution(calls);
- const base = selected.openRuntimeHost!;
- await runCli(["programs", "up", "/p/hypit.runtime.json", "--endpoint", "chosen", "--endpoint", "media"], io, {
- ...selected,
- openRuntimeHost: async (...args) => {
- const host = await base(...args);
- return { ...host, prepare: async (scope) => { prepared = scope?.endpoints; return []; } };
- },
- });
- assert.deepEqual(prepared, ["chosen", "media"]);
+ await runCli(
+ ["programs", "up", "/p/hypit.runtime.json", "--endpoint", "chosen", "--endpoint", "media"],
+ io,
+ distribution(calls),
+ );
assert.match(calls[0]!, /"endpoints":\["chosen","media"\]/u);
});
@@ -233,7 +243,6 @@ test("program startup reports actions, not no-op checks", async () => {
bootstrapPackages: [],
openRuntimeHost: async (path: string) => ({
profile: path,
- prepare: async () => [],
controller: async () => ({
worker: {},
programs: {
@@ -309,7 +318,6 @@ test("JSON startup keeps live preparation evidence on stderr and one result on s
const selected = {
bootstrapPackages: [],
openRuntimeHost: async () => ({
- prepare: async () => [],
controller: async () => ({
programs: {
async up(options: { onProgress?: (event: CliManagedProgramProgress) => void }) {
@@ -336,7 +344,6 @@ test("runtime up validates the Runtime before it starts Programs", async () => {
...base,
openRuntimeHost: async (path: string) => ({
profile: path,
- prepare: async () => [],
controller: async () => controller(path, calls),
createRuntime: async () => { throw new Error("Runtime Profile conflict"); },
}),
@@ -381,7 +388,7 @@ test("Worker stop suggests Program control in the same project and Profile", asy
const projectRoot = await realpath(tmpdir());
const runtimeProfile = resolve("/tmp/a selected profile.json");
let output = "";
- await runCli(["runtime", "down", "--workspace", projectRoot, "--runtime", runtimeProfile], {
+ await runCli(["runtime", "down", "--project", projectRoot, "--runtime", runtimeProfile], {
write(text) { output += text; },
}, distribution([]));
assert.ok(output.includes(commandHint(["programs", "down"], { projectRoot, runtimeProfile })));
diff --git a/packages/cli/test/runtime-selection.test.ts b/packages/cli/test/runtime-selection.test.ts
index a5d8efb2..d9a711a7 100644
--- a/packages/cli/test/runtime-selection.test.ts
+++ b/packages/cli/test/runtime-selection.test.ts
@@ -6,10 +6,29 @@ import test from "node:test";
import type { CliDistribution } from "../src/distribution.js";
import { parseCommand } from "../src/arguments.js";
-import { runCli } from "../src/main.js";
-import { resolveProjectRoot } from "@hypit/project-context-node";
+import { runCliApplication } from "../src/application.js";
+import type { CliIo } from "../src/output.js";
+import { resolveProjectRoot } from "@hypit/project";
import type { CliRuntimeControl } from "../src/runtime-port.js";
-import { findRuntimeProfile, selectRuntimeProfile } from "@hypit/project-context-node";
+import { findRuntimeProfile, selectRuntimeProfile } from "@hypit/runtime-local";
+import { cliCommandModules } from "../../runtime-local/src/cli.js";
+import type { LocalRuntimeCliDistribution } from "../../runtime-local/src/cli.js";
+
+const runCli = async (argv: readonly string[], io: CliIo, distribution: CliDistribution): Promise<void> =>
+ await runCliApplication(argv, io, {
+ distribution: {
+ ...distribution,
+ // Local Runtime commands own the stronger Local Host API; mounting that
+ // contribution in a test must provide the same explicit product port.
+ openLocalRuntimeHost: async (path: string, options: Parameters<CliDistribution["openRuntimeHost"]>[1]) =>
+ await distribution.openRuntimeHost(path, options),
+ resolveProjectRuntime: async (projectRoot) => {
+ const selected = await findRuntimeProfile(projectRoot);
+ return selected === undefined ? undefined : { profile: selected.profile };
+ },
+ } as CliDistribution & LocalRuntimeCliDistribution,
+ commandModules: cliCommandModules,
+ });
test("check has no Runtime context", () => {
assert.throws(
@@ -21,20 +40,28 @@ test("check has no Runtime context", () => {
test("Runtime-aware commands accept an explicit project without changing relative argument paths", () => {
const project = resolve("another-project");
for (const command of [
- ["paths"], ["doctor"], ["status", "build-id"], ["activity"], ["cancel", "build-id"],
+ ["doctor"], ["status", "build-id"], ["activity"], ["cancel", "build-id"],
["result", "finish", "build-id"], ["result", "discard", "build-id"],
- ["runtime", "up"], ["runtime", "down"], ["runtime", "status"], ["runtime", "logs"],
- ["programs", "up"], ["programs", "down"], ["programs", "status"],
["auth", "status", "endpoint"], ["auth", "login", "endpoint"], ["auth", "logout", "endpoint"],
]) {
- const parsed = parseCommand([...command, "--workspace", project, "--runtime", "chosen.json"]);
- assert.ok("workspaceRoot" in parsed && "runtimeProfile" in parsed, command.join(" "));
- assert.equal(parsed.workspaceRoot, project);
+ const parsed = parseCommand([...command, "--project", project, "--runtime", "chosen.json"]);
+ assert.ok("projectRoot" in parsed && "runtimeProfile" in parsed, command.join(" "));
+ assert.equal(parsed.projectRoot, project);
assert.equal(parsed.runtimeProfile, resolve("chosen.json"));
}
assert.throws(() => parseCommand(["doctor", "one.json", "--runtime", "two.json"]), /not both/u);
});
+test("argument paths resolve from the application working directory", () => {
+ const cwd = resolve("alternate-cwd");
+ const parsed = parseCommand([
+ "build", "build.svrun", "--project", "film", "--runtime", "profiles/local.json",
+ ], cwd);
+ assert.ok("projectRoot" in parsed && "runtimeProfile" in parsed);
+ assert.equal(parsed.projectRoot, join(cwd, "film"));
+ assert.equal(parsed.runtimeProfile, join(cwd, "profiles", "local.json"));
+});
+
test("paths reports project selection, invocation override and no selection without changing the pointer", async () => {
const root = await mkdtemp(join(tmpdir(), "hypit-path-context-"));
try {
@@ -47,7 +74,7 @@ test("paths reports project selection, invocation override and no selection with
} as unknown as CliDistribution;
const readPaths = async (options: string[] = []) => {
let output = "";
- await runCli(["paths", "--workspace", root, "--json", ...options],
+ await runCli(["paths", "--project", root, "--json", ...options],
{ write(text) { output += text; } }, distribution);
return JSON.parse(output);
};
@@ -76,7 +103,7 @@ test("project resolution precedes exact project Runtime selection", async () =>
const profile = join(root, "runtime", "local.json");
await mkdir(nested, { recursive: true });
await mkdir(join(root, "runtime"), { recursive: true });
- await writeFile(join(root, "package.json"), "{}\n", "utf8");
+ await writeFile(join(root, "package.json"), '{"hypit":{"project":true}}\n', "utf8");
await writeFile(profile, "{}\n", "utf8");
const selected = await selectRuntimeProfile(root, profile);
@@ -100,7 +127,7 @@ test("a parent Runtime selection never becomes a child project's selection", asy
const child = join(parent, "child");
const profile = join(parent, "runtime.json");
await mkdir(child, { recursive: true });
- await writeFile(join(child, "package.json"), "{}\n", "utf8");
+ await writeFile(join(child, "package.json"), '{"hypit":{"project":true}}\n', "utf8");
await writeFile(profile, "{}\n", "utf8");
await selectRuntimeProfile(parent, profile);
@@ -120,13 +147,30 @@ test("project discovery chooses the caller's parent before resolving directory a
const target = join(targetParent, "nested");
await mkdir(caller);
await mkdir(target, { recursive: true });
- await writeFile(join(caller, "package.json"), "{}");
- await writeFile(join(targetParent, "package.json"), "{}");
+ await writeFile(join(caller, "package.json"), '{"hypit":{"project":true}}');
+ await writeFile(join(targetParent, "package.json"), '{"hypit":{"project":true}}');
const alias = join(caller, "linked");
await symlink(target, alias, "junction");
assert.equal(await resolveProjectRoot({ cwd: alias }), await realpath(caller));
- assert.equal(await resolveProjectRoot({ workspaceRoot: alias }), await realpath(target));
- await assert.rejects(resolveProjectRoot({ workspaceRoot: join(root, "missing") }), { code: "ENOENT" });
+ assert.equal(await resolveProjectRoot({ projectRoot: alias }), await realpath(target));
+ await assert.rejects(resolveProjectRoot({ projectRoot: join(root, "missing") }), { code: "ENOENT" });
+ } finally { await rm(root, { recursive: true, force: true }); }
+});
+
+test("project discovery skips nested component manifests and never invents a project", async () => {
+ const root = await mkdtemp(join(tmpdir(), "hypit-project-marker-"));
+ try {
+ const project = join(root, "film");
+ const component = join(project, "packages", "scene");
+ await mkdir(component, { recursive: true });
+ await writeFile(join(project, "package.json"), '{"hypit":{"project":true}}');
+ await writeFile(join(component, "package.json"), '{"name":"@film/scene"}');
+ assert.equal(await resolveProjectRoot({ cwd: component }), await realpath(project));
+
+ const unrelated = join(root, "ordinary-package");
+ await mkdir(unrelated);
+ await writeFile(join(unrelated, "package.json"), '{"name":"ordinary"}');
+ await assert.rejects(resolveProjectRoot({ cwd: unrelated }), /No Hypit project was found/u);
} finally { await rm(root, { recursive: true, force: true }); }
});
@@ -136,6 +180,7 @@ test("runtime use lets later CLI commands reuse the selected Profile", async ()
try {
const profile = join(root, "hypit.runtime.json");
const otherProfile = join(root, "other.runtime.json");
+ await writeFile(join(root, "package.json"), '{"hypit":{"project":true}}\n', "utf8");
await writeFile(profile, "{}\n", "utf8");
await writeFile(otherProfile, "{}\n", "utf8");
const calls: string[] = [];
@@ -151,6 +196,7 @@ test("runtime use lets later CLI commands reuse the selected Profile", async ()
calls.push(`activity:${resolve(path)}`);
return control;
},
+ executionStatus: async () => ({ state: "stopped" as const }),
controller: async () => ({
worker: { status: async () => ({ state: "stopped", profile: path, logPath: "/tmp/worker.log" }) },
}),
@@ -158,10 +204,10 @@ test("runtime use lets later CLI commands reuse the selected Profile", async ()
} as unknown as CliDistribution;
process.chdir(root);
- await runCli(["runtime", "use", profile, "--workspace", root, "--json"], { write() {} }, distribution);
+ await runCli(["runtime", "use", profile, "--project", root, "--json"], { write() {} }, distribution);
await runCli(["activity", "--json"], { write() {} }, distribution);
await runCli(["activity", "--runtime", otherProfile, "--json"], { write() {} }, distribution);
- await runCli(["runtime", "unset", "--workspace", root, "--json"], { write() {} }, distribution);
+ await runCli(["runtime", "unset", "--project", root, "--json"], { write() {} }, distribution);
assert.deepEqual(calls, [
`activity:${await realpath(profile)}`,
@@ -178,7 +224,7 @@ test("runtime init writes and selects the Distribution starter without opening a
const root = await mkdtemp(join(tmpdir(), "hypit-runtime-init-"));
const previous = process.cwd();
try {
- await writeFile(join(root, "package.json"), "{}\n", "utf8");
+ await writeFile(join(root, "package.json"), '{"hypit":{"project":true}}\n', "utf8");
process.chdir(root);
let opened = false;
const starter = {
@@ -195,7 +241,7 @@ test("runtime init writes and selects the Distribution starter without opening a
},
} as unknown as CliDistribution;
let output = "";
- await runCli(["runtime", "init", "--workspace", root], {
+ await runCli(["runtime", "init", "--project", root], {
write(text) { output += text; },
}, distribution);
@@ -206,7 +252,7 @@ test("runtime init writes and selects the Distribution starter without opening a
assert.match(output, /No package was installed, no service was contacted and no Worker was started/u);
await assert.rejects(
- runCli(["runtime", "init", "--workspace", root], { write() {} }, distribution),
+ runCli(["runtime", "init", "--project", root], { write() {} }, distribution),
/Runtime Profile already exists/u,
);
assert.deepEqual(JSON.parse(await readFile(profile, "utf8")), starter);
@@ -220,6 +266,7 @@ test("runtime status without a selected Profile reports the missing context inst
const root = await mkdtemp(join(tmpdir(), "hypit-runtime-missing-"));
const previous = process.cwd();
try {
+ await writeFile(join(root, "package.json"), '{"hypit":{"project":true}}\n', "utf8");
process.chdir(root);
await assert.rejects(
async () => await runCli(["runtime", "status"], { write() {} }, {} as CliDistribution),
diff --git a/packages/video-cli/test/secret-input.test.ts b/packages/cli/test/secret-input.test.ts
similarity index 100%
rename from packages/video-cli/test/secret-input.test.ts
rename to packages/cli/test/secret-input.test.ts
diff --git a/packages/cli/test/source-discovery.test.ts b/packages/cli/test/source-discovery.test.ts
index 2082d63d..e0117cfa 100644
--- a/packages/cli/test/source-discovery.test.ts
+++ b/packages/cli/test/source-discovery.test.ts
@@ -5,8 +5,8 @@ import { join } from "node:path";
import test from "node:test";
import { modulePackageAbi } from "@hypit/protocol";
-import { createAuthorFrontendHostFacet } from "@hypit/elaborator";
-import { createRunFrontendHostFacet, runFragmentHostAbi } from "@hypit/run";
+import { createAuthorFrontendFacet } from "@hypit/author";
+import { createRunFrontendFacet, runFragmentFacetAbi } from "@hypit/run";
import { sourceFrontendPackageAbi } from "@hypit/source";
import { discoverSourcePackages } from "../src/source-discovery.js";
@@ -20,7 +20,7 @@ test("third-party Frontends discover same-named ABI requirements through physica
const packages = [
{
specifier: "@physical/run-suite",
- contribution: { format: "hypit.node-package@1" as const, hostFacets: [createRunFrontendHostFacet({
+ contribution: { format: "hypit.package@1" as const, facets: [createRunFrontendFacet({
id: "@logical/run@1",
discover: () => ({
author: { source: "./main.story" },
@@ -31,7 +31,7 @@ test("third-party Frontends discover same-named ABI requirements through physica
},
{
specifier: "@physical/story-suite",
- contribution: { format: "hypit.node-package@1" as const, hostFacets: [createAuthorFrontendHostFacet({
+ contribution: { format: "hypit.package@1" as const, facets: [createAuthorFrontendFacet({
id: "@logical/story@1",
discover: () => ({
modules: ["@logical/shared@1"],
@@ -42,7 +42,7 @@ test("third-party Frontends discover same-named ABI requirements through physica
},
{
specifier: "@physical/module-suite",
- contribution: { format: "hypit.node-package@1" as const, modules: [{
+ contribution: { format: "hypit.package@1" as const, modules: [{
manifest: {
format: "hypit.module@1" as const,
name: "@logical/shared",
@@ -54,8 +54,8 @@ test("third-party Frontends discover same-named ABI requirements through physica
},
{
specifier: "@physical/fragment-suite",
- contribution: { format: "hypit.node-package@1" as const, hostFacets: [{
- abi: runFragmentHostAbi,
+ contribution: { format: "hypit.package@1" as const, facets: [{
+ abi: runFragmentFacetAbi,
offers: ["@logical/shared@1"],
implementation: {},
}] },
@@ -74,7 +74,7 @@ test("third-party Frontends discover same-named ABI requirements through physica
]);
assert.deepEqual(discovered.logical, [
{ abi: modulePackageAbi, name: "@logical/shared@1" },
- { abi: runFragmentHostAbi, name: "@logical/shared@1" },
+ { abi: runFragmentFacetAbi, name: "@logical/shared@1" },
{ abi: sourceFrontendPackageAbi, name: "@logical/run@1" },
{ abi: sourceFrontendPackageAbi, name: "@logical/story@1" },
{ abi: sourceFrontendPackageAbi, name: "@unknown/child@1" },
diff --git a/packages/video-cli/test/version.test.ts b/packages/cli/test/version.test.ts
similarity index 98%
rename from packages/video-cli/test/version.test.ts
rename to packages/cli/test/version.test.ts
index f1c2c066..3fa0ead9 100644
--- a/packages/video-cli/test/version.test.ts
+++ b/packages/cli/test/version.test.ts
@@ -3,7 +3,7 @@ import { mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import test from "node:test";
-import { runVersionCli } from "../src/version.js";
+import { runVersionCli } from "@hypit/cli";
import { spawnSync } from "node:child_process";
import { fileURLToPath } from "node:url";
diff --git a/packages/cli/test/view.test.ts b/packages/cli/test/view.test.ts
index c4b0677b..5dd9c5ab 100644
--- a/packages/cli/test/view.test.ts
+++ b/packages/cli/test/view.test.ts
@@ -1,14 +1,14 @@
import assert from "node:assert/strict";
import test from "node:test";
-import type { BuildResultManifest, BuildResultRepository } from "@hypit/build-result";
-import type { BuildView } from "@hypit/runtime-host-node";
+import type { BuildResultManifest, BuildResultRepository } from "@hypit/result";
+import type { CliBuildView as BuildView } from "../src/runtime-port.js";
import { buildResultView, buildStatusView } from "../src/view.js";
test("inspection chooses its scope before following any Output reference", async () => {
const names = ["final", "important", ...Array.from({ length: 50 }, (_, i) => `unused-${i}`)];
const manifest = {
- id: "bld_20260913T093030369Z_55907CDA9E", source: { path: "main.svml" },
+ id: "bld_20260913T093030369Z_55907CDA9E", source: { id: "main.svml" },
targets: ["final"], highlightedOutputs: ["important"],
outputs: Object.fromEntries(names.map((name) => [name, {}])),
} as unknown as BuildResultManifest;
diff --git a/packages/estimate/package.json b/packages/estimate/package.json
deleted file mode 100644
index b8aa80bf..00000000
--- a/packages/estimate/package.json
+++ /dev/null
@@ -1,20 +0,0 @@
-{
- "name": "@hypit/estimate",
- "version": "0.0.0-dev",
- "license": "SEE LICENSE IN LICENSE",
- "private": true,
- "type": "module",
- "exports": {
- ".": "./src/index.ts"
- },
- "hypit": {
- "activation": "./src/activation.ts"
- },
- "dependencies": {
- "@hypit/protocol": "workspace:*",
- "@hypit/speech": "workspace:*",
- "@hypit/svs": "workspace:*",
- "@hypit/text": "workspace:*",
- "cmu-pronouncing-dictionary": "3.0.0"
- }
-}
diff --git a/packages/estimate/src/activation.ts b/packages/estimate/src/activation.ts
deleted file mode 100644
index 0bd8b4c2..00000000
--- a/packages/estimate/src/activation.ts
+++ /dev/null
@@ -1,11 +0,0 @@
-import { estimateManifest } from "./index.js";
-
-/** The package declares one graph type and no Surface, Producer or Need: measuring is creation-time work. */
-export const hypitPackage = {
- format: "hypit.node-package@1" as const,
- modules: [{ manifest: estimateManifest }],
- components: [],
- hostFacets: [],
-};
-
-export default hypitPackage;
diff --git a/packages/estimate/src/manifest.ts b/packages/estimate/src/manifest.ts
deleted file mode 100644
index ac9b60c8..00000000
--- a/packages/estimate/src/manifest.ts
+++ /dev/null
@@ -1,34 +0,0 @@
-import type { ModuleManifest, TypeRef, ValueSchema } from "@hypit/protocol";
-
-export const estimateModuleRef = { name: "@hypit/estimate", version: "1" } as const;
-
-/**
- * The one graph value this package still declares: the delivery policy an estimated speech result
- * weights its Tokens with. Durations themselves are author literals; measuring a script happens at
- * creation time with `hypit measure`, never inside a Build.
- */
-export const estimateTypes = {
- speechPolicy: { module: estimateModuleRef, name: "SpeechEstimatePolicy" },
-} satisfies Record<string, TypeRef>;
-
-const number = { kind: "number" } as const satisfies ValueSchema;
-export const speechEstimatePolicySchema: ValueSchema = {
- kind: "object",
- fields: {
- language: { schema: { kind: "string", enum: ["auto", "en", "zh", "ja", "es"] } },
- pace: { schema: { kind: "string", enum: ["slow", "normal", "fast"] }, optional: true },
- rate: { schema: { kind: "number", minimum: 0.000001 }, optional: true },
- rounding: { schema: { kind: "string", enum: ["none", "round", "ceil"] } },
- paddingSec: { schema: number, optional: true },
- },
-};
-
-export const estimateManifest: ModuleManifest = {
- format: "hypit.module@1",
- name: estimateModuleRef.name,
- version: estimateModuleRef.version,
- dependencies: [],
- types: [{ name: estimateTypes.speechPolicy.name }],
- capabilities: [],
- producers: [],
-};
diff --git a/packages/fonts-open/README.md b/packages/fonts-open/README.md
deleted file mode 100644
index c7be6678..00000000
--- a/packages/fonts-open/README.md
+++ /dev/null
@@ -1,82 +0,0 @@
-# `@hypit/fonts-open`
-
-The optional `@hypit/fonts-open/studio` export supplies data-only catalog choices for Companions.
-`openFontStudioFields(owner)` returns the explicit nested font binding and Inspector fields for a
-Style reference such as `program` or `style`. It edits the referenced catalog face's family, keeping
-its authored weight, style and fallback faces. Ordinary font validation still applies.
-
-Workspace package exposing 109 redistributable open font families as exact,
-Resource-backed `FontArtifactRef` values. The installed packages carry their font bytes and license
-files. Author compilation and rendering never download fonts or inspect system font directories.
-
-A developer who pulls this repository gets the catalog with the ordinary `pnpm install`; importing
-`@hypit/fonts-open@1` selects it. Nothing is installed globally and this package has not been
-published to npm.
-
-## One exact face
-
-```svml
-<import as="fonts" from="@hypit/fonts-open@1"/>
-
-<fonts:Face id="headline" family="archivo-black" weight="400" style="normal"/>
-```
-
-`family` is a finite catalog identifier. Weight and style must exist in that family; the package
-never snaps to a nearby weight and never silently substitutes an italic face.
-
-## A convenient multilingual and Emoji stack
-
-Emoji is normally a fallback of the chosen text face, not a separate style. `Stack` packages that
-intent into one reusable Author Graph value:
-
-```svml
-<fonts:Stack id="caption-fonts"
- family="inter" weight="700" style="normal" emoji="color">
- <fonts:Fallback family="noto-sans-sc" weight="700" style="normal"/>
-</fonts:Stack>
-
-<caption-fine:Style id="caption" recipe={recipes.caption.primary}
- font={caption-fonts}/>
-```
-
-The resulting order is Inter, Noto Sans SC, then Noto Color Emoji. `emoji="color"` selects the
-pinned COLRv1 face verified in HyperFrames' Chromium renderer; `emoji="mono"` selects the
-weight-400 monochrome Noto Emoji face. Emoji stays explicit—omitting `emoji` adds no bytes. Extra
-`Fallback` children can select Arabic, Hebrew, Devanagari, Thai, Japanese, Korean or any other
-catalog family with their own honest weight/style.
-
-The package does not rewrite author text to force presentation. For characters that have both text
-and Emoji forms, write the real Unicode Emoji sequence (normally the character followed by VS16,
-for example `☎️`) when color presentation is intended. Ordinary pictographic Emoji such as `🌐`
-already have Emoji presentation. This preserves the author's exact display text while avoiding
-platform-font guesses.
-
-`Stack` is only authoring convenience. Its output is the generic `FontStackRef` media contract, so
-other packages may produce or consume the same ordered exact-face value. Caption Fine does not know
-about Fontsource, Noto or COLRv1.
-
-## Catalog
-
-The exported `openFontFamilies` map includes `label`, `category`, `intendedUse`, exact availability
-and license metadata; `openFontFamiliesByCategory` is suitable for a frontend picker.
-
-| Category | Count | Families |
-|---|---:|---|
-| Handwriting | 11 | `architects-daughter`, `caveat`, `coming-soon`, `handlee`, `kalam`, `patrick-hand`, `permanent-marker`, `playpen-sans`, `shadows-into-light`, `shantell-sans`, `short-stack` |
-| Script | 3 | `pacifico`, `pinyon-script`, `satisfy` |
-| Display | 16 | `abril-fatface`, `alfa-slab-one`, `anton`, `archivo-black`, `bangers`, `bebas-neue`, `black-ops-one`, `bungee`, `dm-serif-display`, `fredoka`, `league-spartan`, `lilita-one`, `luckiest-guy`, `oswald`, `righteous`, `unbounded` |
-| Sans | 35 | `archivo`, `barlow`, `barlow-condensed`, `cabin`, `dm-sans`, `figtree`, `fira-sans-condensed`, `geist`, `instrument-sans`, `inter`, `josefin-sans`, `jost`, `kanit`, `lato`, `lexend`, `manrope`, `montserrat`, `mulish`, `noto-sans`, `nunito-sans`, `onest`, `open-sans`, `outfit`, `plus-jakarta-sans`, `poppins`, `quicksand`, `raleway`, `rethink-sans`, `roboto`, `roboto-condensed`, `rubik`, `sora`, `space-grotesk`, `urbanist`, `work-sans` |
-| Serif | 16 | `bodoni-moda`, `cinzel`, `cormorant-garamond`, `crimson-pro`, `eb-garamond`, `fraunces`, `gloock`, `instrument-serif`, `libre-baskerville`, `lora`, `merriweather`, `newsreader`, `playfair-display`, `roboto-slab`, `source-serif-4`, `vollkorn` |
-| Monospace | 6 | `fira-code`, `geist-mono`, `ibm-plex-mono`, `jetbrains-mono`, `roboto-mono`, `space-mono` |
-| CJK | 15 | `liu-jian-mao-cao`, `long-cang`, `ma-shan-zheng`, `noto-sans-hk`, `noto-sans-jp`, `noto-sans-kr`, `noto-sans-sc`, `noto-sans-tc`, `noto-serif-jp`, `noto-serif-kr`, `noto-serif-sc`, `noto-serif-tc`, `zcool-kuaile`, `zcool-qingke-huangyou`, `zcool-xiaowei` |
-| World scripts | 5 | `noto-naskh-arabic`, `noto-sans-arabic`, `noto-sans-devanagari`, `noto-sans-hebrew`, `noto-sans-thai` |
-| Emoji | 2 | `noto-color-emoji`, `noto-emoji` |
-
-Latin variable faces intentionally load the compact Latin subset. CJK, world-script and Emoji
-families preserve every Unicode-range shard from their installed CSS as one logical face. Only
-faces referenced by the Author Graph enter a Build transfer bundle and ResourceStore.
-
-Every catalog entry is either SIL OFL 1.1 or Apache 2.0. Tests compare the declared license against
-the installed package's own metadata. Private local fonts are not bundled: public redistribution
-requires an independently verified license, and brand fonts remain
-explicit `<media:Font>` author assets.
diff --git a/packages/fonts-open/package.json b/packages/fonts-open/package.json
deleted file mode 100644
index dc876ff4..00000000
--- a/packages/fonts-open/package.json
+++ /dev/null
@@ -1,132 +0,0 @@
-{
- "name": "@hypit/fonts-open",
- "version": "0.0.0-dev",
- "license": "SEE LICENSE IN LICENSE",
- "private": true,
- "type": "module",
- "exports": {
- ".": "./src/index.ts",
- "./studio": "./src/studio.ts"
- },
- "hypit": {
- "activation": "./src/activation.ts"
- },
- "optionalDependencies": {
- "@fontsource-variable/archivo": "5.3.0",
- "@fontsource-variable/bodoni-moda": "5.3.0",
- "@fontsource-variable/cabin": "5.3.0",
- "@fontsource-variable/caveat": "5.3.0",
- "@fontsource-variable/cinzel": "5.3.0",
- "@fontsource-variable/cormorant-garamond": "5.3.0",
- "@fontsource-variable/crimson-pro": "5.3.0",
- "@fontsource-variable/dm-sans": "5.3.0",
- "@fontsource-variable/eb-garamond": "5.3.0",
- "@fontsource-variable/figtree": "5.3.0",
- "@fontsource-variable/fira-code": "5.3.0",
- "@fontsource-variable/fraunces": "5.3.0",
- "@fontsource-variable/fredoka": "5.3.0",
- "@fontsource-variable/geist": "5.3.0",
- "@fontsource-variable/geist-mono": "5.3.0",
- "@fontsource-variable/instrument-sans": "5.3.0",
- "@fontsource-variable/inter": "5.3.0",
- "@fontsource-variable/jetbrains-mono": "5.3.0",
- "@fontsource-variable/josefin-sans": "5.3.0",
- "@fontsource-variable/jost": "5.3.0",
- "@fontsource-variable/league-spartan": "5.3.0",
- "@fontsource-variable/lexend": "5.3.0",
- "@fontsource-variable/libre-baskerville": "5.3.0",
- "@fontsource-variable/lora": "5.3.0",
- "@fontsource-variable/manrope": "5.3.0",
- "@fontsource-variable/merriweather": "5.3.0",
- "@fontsource-variable/montserrat": "5.3.0",
- "@fontsource-variable/mulish": "5.3.0",
- "@fontsource-variable/newsreader": "5.3.0",
- "@fontsource-variable/noto-emoji": "5.3.0",
- "@fontsource-variable/noto-naskh-arabic": "5.3.0",
- "@fontsource-variable/noto-sans": "5.3.0",
- "@fontsource-variable/noto-sans-arabic": "5.3.0",
- "@fontsource-variable/noto-sans-devanagari": "5.3.0",
- "@fontsource-variable/noto-sans-hebrew": "5.3.0",
- "@fontsource-variable/noto-sans-hk": "5.3.0",
- "@fontsource-variable/noto-sans-jp": "5.3.0",
- "@fontsource-variable/noto-sans-kr": "5.3.0",
- "@fontsource-variable/noto-sans-sc": "5.3.0",
- "@fontsource-variable/noto-sans-tc": "5.3.0",
- "@fontsource-variable/noto-sans-thai": "5.3.0",
- "@fontsource-variable/noto-serif-jp": "5.3.0",
- "@fontsource-variable/noto-serif-kr": "5.3.0",
- "@fontsource-variable/noto-serif-sc": "5.3.0",
- "@fontsource-variable/noto-serif-tc": "5.3.0",
- "@fontsource-variable/nunito-sans": "5.3.0",
- "@fontsource-variable/onest": "5.3.0",
- "@fontsource-variable/open-sans": "5.3.0",
- "@fontsource-variable/oswald": "5.3.0",
- "@fontsource-variable/outfit": "5.3.0",
- "@fontsource-variable/playfair-display": "5.3.0",
- "@fontsource-variable/playpen-sans": "5.3.0",
- "@fontsource-variable/plus-jakarta-sans": "5.3.0",
- "@fontsource-variable/quicksand": "5.3.0",
- "@fontsource-variable/raleway": "5.3.0",
- "@fontsource-variable/rethink-sans": "5.3.0",
- "@fontsource-variable/roboto": "5.3.0",
- "@fontsource-variable/roboto-condensed": "5.3.0",
- "@fontsource-variable/roboto-mono": "5.3.0",
- "@fontsource-variable/roboto-slab": "5.3.0",
- "@fontsource-variable/rubik": "5.3.0",
- "@fontsource-variable/shantell-sans": "5.3.0",
- "@fontsource-variable/sora": "5.3.0",
- "@fontsource-variable/source-serif-4": "5.3.0",
- "@fontsource-variable/space-grotesk": "5.3.0",
- "@fontsource-variable/unbounded": "5.3.0",
- "@fontsource-variable/urbanist": "5.3.0",
- "@fontsource-variable/vollkorn": "5.3.0",
- "@fontsource-variable/work-sans": "5.3.0",
- "@fontsource/abril-fatface": "5.3.0",
- "@fontsource/alfa-slab-one": "5.3.0",
- "@fontsource/anton": "5.3.0",
- "@fontsource/architects-daughter": "5.3.0",
- "@fontsource/archivo-black": "5.3.0",
- "@fontsource/bangers": "5.3.0",
- "@fontsource/barlow": "5.3.0",
- "@fontsource/barlow-condensed": "5.3.0",
- "@fontsource/bebas-neue": "5.3.0",
- "@fontsource/black-ops-one": "5.3.0",
- "@fontsource/bungee": "5.3.0",
- "@fontsource/coming-soon": "5.3.0",
- "@fontsource/dm-serif-display": "5.3.0",
- "@fontsource/fira-sans-condensed": "5.3.0",
- "@fontsource/gloock": "5.3.0",
- "@fontsource/handlee": "5.3.0",
- "@fontsource/ibm-plex-mono": "5.3.0",
- "@fontsource/instrument-serif": "5.3.0",
- "@fontsource/kalam": "5.3.0",
- "@fontsource/kanit": "5.3.0",
- "@fontsource/lato": "5.3.0",
- "@fontsource/lilita-one": "5.3.0",
- "@fontsource/liu-jian-mao-cao": "5.3.0",
- "@fontsource/long-cang": "5.3.0",
- "@fontsource/luckiest-guy": "5.3.0",
- "@fontsource/ma-shan-zheng": "5.3.0",
- "@fontsource/pacifico": "5.3.0",
- "@fontsource/patrick-hand": "5.3.0",
- "@fontsource/permanent-marker": "5.3.0",
- "@fontsource/pinyon-script": "5.3.0",
- "@fontsource/poppins": "5.3.0",
- "@fontsource/righteous": "5.3.0",
- "@fontsource/satisfy": "5.3.0",
- "@fontsource/shadows-into-light": "5.3.0",
- "@fontsource/short-stack": "5.3.0",
- "@fontsource/space-mono": "5.3.0",
- "@fontsource/zcool-kuaile": "5.3.0",
- "@fontsource/zcool-qingke-huangyou": "5.3.0",
- "@fontsource/zcool-xiaowei": "5.3.0",
- "@infolektuell/noto-color-emoji": "0.2.0"
- },
- "dependencies": {
- "@hypit/media": "workspace:*",
- "@hypit/package-loader-node": "workspace:*",
- "@hypit/protocol": "workspace:*",
- "@hypit/markup": "workspace:*",
- "@hypit/studio-adapter": "workspace:*"
- }
-}
diff --git a/packages/fonts-open/src/activation.ts b/packages/fonts-open/src/activation.ts
deleted file mode 100644
index 6c0dec74..00000000
--- a/packages/fonts-open/src/activation.ts
+++ /dev/null
@@ -1,30 +0,0 @@
-import { createMarkupSurfaceHostFacet } from "@hypit/markup";
-
-import {
- decodeOpenFontFaceSurface,
- decodeOpenFontStackSurface,
- fontsOpenManifest,
- fontsOpenModuleRef,
- fontsOpenMarkupSurfaces,
-} from "./index.js";
-
-export const hypitPackage = {
- format: "hypit.node-package@1" as const,
- modules: [{
- manifest: fontsOpenManifest,
- }],
- hostFacets: [
- createMarkupSurfaceHostFacet({
- module: fontsOpenModuleRef,
- declaration: fontsOpenMarkupSurfaces.find((item) => item.name === "face")!,
- handler: decodeOpenFontFaceSurface,
- }),
- createMarkupSurfaceHostFacet({
- module: fontsOpenModuleRef,
- declaration: fontsOpenMarkupSurfaces.find((item) => item.name === "stack")!,
- handler: decodeOpenFontStackSurface,
- }),
- ],
-};
-
-export default hypitPackage;
diff --git a/packages/fonts-open/src/catalog.ts b/packages/fonts-open/src/catalog.ts
deleted file mode 100644
index 4c35cb3c..00000000
--- a/packages/fonts-open/src/catalog.ts
+++ /dev/null
@@ -1,317 +0,0 @@
-export type OpenFontStyle = "normal" | "italic";
-
-export type OpenFontCategory =
- | "handwriting"
- | "script"
- | "display"
- | "sans"
- | "serif"
- | "monospace"
- | "cjk"
- | "world"
- | "emoji";
-
-type FamilyMetadata = {
- readonly label: string;
- readonly category: OpenFontCategory;
- readonly intendedUse: string;
- readonly license: "OFL-1.1" | "Apache-2.0";
-};
-
-type VariableSingleFamily = FamilyMetadata & {
- readonly kind: "variable-single";
- readonly packageName: string;
- readonly fileStem: string;
- readonly minimumWeight: number;
- readonly maximumWeight: number;
- readonly styles: readonly OpenFontStyle[];
-};
-
-type VariableSplitFamily = FamilyMetadata & {
- readonly kind: "variable-split";
- readonly packageName: string;
- readonly css: string;
- readonly minimumWeight: number;
- readonly maximumWeight: number;
- readonly styles: readonly ["normal"];
-};
-
-type StaticFamily = FamilyMetadata & {
- readonly kind: "static";
- readonly packageName: string;
- readonly fileStem: string;
- readonly weights: readonly number[];
- readonly styles: readonly OpenFontStyle[];
-};
-
-type StaticSplitFamily = FamilyMetadata & {
- readonly kind: "static-split";
- readonly packageName: string;
- readonly weights: readonly number[];
- readonly styles: readonly OpenFontStyle[];
-};
-
-type ExternalSplitFamily = FamilyMetadata & {
- readonly kind: "external-split";
- readonly packageName: string;
- readonly css: string;
- readonly weights: readonly number[];
- readonly styles: readonly OpenFontStyle[];
-};
-
-export type OpenFontFamily =
- | VariableSingleFamily
- | VariableSplitFamily
- | StaticFamily
- | StaticSplitFamily
- | ExternalSplitFamily;
-
-const variable = (
- id: string,
- label: string,
- category: OpenFontCategory,
- minimumWeight: number,
- maximumWeight: number,
- styles: readonly OpenFontStyle[],
- intendedUse: string,
- license: FamilyMetadata["license"] = "OFL-1.1",
-): VariableSingleFamily => ({
- kind: "variable-single",
- packageName: `@fontsource-variable/${id}`,
- fileStem: `${id}-latin-wght`,
- minimumWeight,
- maximumWeight,
- styles,
- label,
- category,
- intendedUse,
- license,
-});
-
-const variableSplit = (
- id: string,
- label: string,
- category: OpenFontCategory,
- minimumWeight: number,
- maximumWeight: number,
- intendedUse: string,
-): VariableSplitFamily => ({
- kind: "variable-split",
- packageName: `@fontsource-variable/${id}`,
- css: "wght.css",
- minimumWeight,
- maximumWeight,
- styles: ["normal"],
- label,
- category,
- intendedUse,
- license: "OFL-1.1",
-});
-
-const staticFont = (
- id: string,
- label: string,
- category: OpenFontCategory,
- weights: readonly number[],
- styles: readonly OpenFontStyle[],
- intendedUse: string,
- license: FamilyMetadata["license"] = "OFL-1.1",
-): StaticFamily => ({
- kind: "static",
- packageName: `@fontsource/${id}`,
- fileStem: `${id}-latin`,
- weights,
- styles,
- label,
- category,
- intendedUse,
- license,
-});
-
-const staticSplit = (
- id: string,
- label: string,
- category: OpenFontCategory,
- weights: readonly number[],
- styles: readonly OpenFontStyle[],
- intendedUse: string,
-): StaticSplitFamily => ({
- kind: "static-split",
- packageName: `@fontsource/${id}`,
- weights,
- styles,
- label,
- category,
- intendedUse,
- license: "OFL-1.1",
-});
-
-const externalSplit = (
- packageName: string,
- css: string,
- label: string,
- category: OpenFontCategory,
- weights: readonly number[],
- styles: readonly OpenFontStyle[],
- intendedUse: string,
-): ExternalSplitFamily => ({
- kind: "external-split",
- packageName,
- css,
- weights,
- styles,
- label,
- category,
- intendedUse,
- license: "OFL-1.1",
-});
-
-const normal = ["normal"] as const;
-const romanItalic = ["normal", "italic"] as const;
-
-/**
- * Reproducible open faces intended for video typography. Latin variable faces load their compact
- * Latin subset. Script-complete CJK, world-script and emoji faces preserve Fontsource's complete
- * Unicode-range shards as one logical face.
- */
-export const openFontFamilies = {
- // Handwriting and casual lettering.
- "architects-daughter": staticFont("architects-daughter", "Architects Daughter", "handwriting", [400], normal, "casual annotations"),
- caveat: variable("caveat", "Caveat", "handwriting", 400, 700, normal, "warm handwritten captions"),
- "coming-soon": staticFont("coming-soon", "Coming Soon", "handwriting", [400], normal, "informal notes", "Apache-2.0"),
- handlee: staticFont("handlee", "Handlee", "handwriting", [400], normal, "light handwritten copy"),
- kalam: staticFont("kalam", "Kalam", "handwriting", [300, 400, 700], normal, "confident handwritten copy"),
- "patrick-hand": staticFont("patrick-hand", "Patrick Hand", "handwriting", [400], normal, "friendly handwritten captions"),
- "permanent-marker": staticFont("permanent-marker", "Permanent Marker", "handwriting", [400], normal, "marker headlines", "Apache-2.0"),
- "playpen-sans": variable("playpen-sans", "Playpen Sans", "handwriting", 100, 800, normal, "playful product and education video"),
- "shadows-into-light": staticFont("shadows-into-light", "Shadows Into Light", "handwriting", [400], normal, "airy handwritten notes"),
- "shantell-sans": variable("shantell-sans", "Shantell Sans", "handwriting", 300, 800, romanItalic, "expressive informal captions"),
- "short-stack": staticFont("short-stack", "Short Stack", "handwriting", [400], normal, "compact handwritten labels"),
-
- // Formal and brush scripts.
- pacifico: staticFont("pacifico", "Pacifico", "script", [400], normal, "friendly brush titles"),
- "pinyon-script": staticFont("pinyon-script", "Pinyon Script", "script", [400], normal, "formal editorial titles"),
- satisfy: staticFont("satisfy", "Satisfy", "script", [400], normal, "casual brush titles", "Apache-2.0"),
-
- // High-impact display faces.
- "abril-fatface": staticFont("abril-fatface", "Abril Fatface", "display", [400], normal, "editorial headlines"),
- "alfa-slab-one": staticFont("alfa-slab-one", "Alfa Slab One", "display", [400], normal, "heavy slab headlines"),
- anton: staticFont("anton", "Anton", "display", [400], normal, "dense vertical-video headlines"),
- "archivo-black": staticFont("archivo-black", "Archivo Black", "display", [400], normal, "ranking cards and bold labels"),
- bangers: staticFont("bangers", "Bangers", "display", [400], normal, "comic impact titles"),
- "bebas-neue": staticFont("bebas-neue", "Bebas Neue", "display", [400], normal, "condensed headlines"),
- "black-ops-one": staticFont("black-ops-one", "Black Ops One", "display", [400], normal, "stencil and gaming titles"),
- bungee: staticFont("bungee", "Bungee", "display", [400], normal, "poster-like display copy"),
- "dm-serif-display": staticFont("dm-serif-display", "DM Serif Display", "display", [400], romanItalic, "high-contrast editorial display"),
- fredoka: variable("fredoka", "Fredoka", "display", 300, 700, normal, "rounded playful headlines"),
- "league-spartan": variable("league-spartan", "League Spartan", "display", 100, 900, normal, "geometric all-purpose display"),
- "lilita-one": staticFont("lilita-one", "Lilita One", "display", [400], normal, "friendly heavy titles"),
- "luckiest-guy": staticFont("luckiest-guy", "Luckiest Guy", "display", [400], normal, "energetic comic titles", "Apache-2.0"),
- oswald: variable("oswald", "Oswald", "display", 200, 700, normal, "compact headlines and lower thirds"),
- righteous: staticFont("righteous", "Righteous", "display", [400], normal, "retro geometric titles"),
- unbounded: variable("unbounded", "Unbounded", "display", 200, 900, normal, "futuristic brand headlines"),
-
- // Sans-serif workhorses and contemporary brand faces.
- archivo: variable("archivo", "Archivo", "sans", 100, 900, romanItalic, "dense information layouts"),
- barlow: staticFont("barlow", "Barlow", "sans", [100, 200, 300, 400, 500, 600, 700, 800, 900], romanItalic, "neutral product and UI copy"),
- "barlow-condensed": staticFont("barlow-condensed", "Barlow Condensed", "sans", [100, 200, 300, 400, 500, 600, 700, 800, 900], romanItalic, "narrow social captions"),
- cabin: variable("cabin", "Cabin", "sans", 400, 700, romanItalic, "humanist dialogue"),
- "dm-sans": variable("dm-sans", "DM Sans", "sans", 100, 1_000, romanItalic, "friendly product video"),
- figtree: variable("figtree", "Figtree", "sans", 300, 900, romanItalic, "clean modern captions"),
- "fira-sans-condensed": staticFont("fira-sans-condensed", "Fira Sans Condensed", "sans", [100, 200, 300, 400, 500, 600, 700, 800, 900], romanItalic, "compact explanatory copy"),
- geist: variable("geist", "Geist", "sans", 100, 900, romanItalic, "minimal technology branding"),
- "instrument-sans": variable("instrument-sans", "Instrument Sans", "sans", 400, 700, romanItalic, "refined modern branding"),
- inter: variable("inter", "Inter", "sans", 100, 900, romanItalic, "neutral UI and dialogue"),
- jost: variable("jost", "Jost", "sans", 100, 900, romanItalic, "geometric brand copy"),
- "josefin-sans": variable("josefin-sans", "Josefin Sans", "sans", 100, 700, romanItalic, "fashion and lifestyle titles"),
- kanit: staticFont("kanit", "Kanit", "sans", [100, 200, 300, 400, 500, 600, 700, 800, 900], romanItalic, "technical condensed captions"),
- lato: staticFont("lato", "Lato", "sans", [100, 300, 400, 700, 900], romanItalic, "humanist general-purpose copy"),
- lexend: variable("lexend", "Lexend", "sans", 100, 900, normal, "high-legibility captions"),
- manrope: variable("manrope", "Manrope", "sans", 200, 800, normal, "compact modern captions"),
- montserrat: variable("montserrat", "Montserrat", "sans", 100, 900, romanItalic, "geometric social captions"),
- mulish: variable("mulish", "Mulish", "sans", 200, 900, romanItalic, "soft readable captions"),
- "noto-sans": variable("noto-sans", "Noto Sans", "sans", 100, 900, romanItalic, "broad Latin, Greek and Cyrillic coverage"),
- "nunito-sans": variable("nunito-sans", "Nunito Sans", "sans", 200, 900, romanItalic, "rounded friendly dialogue"),
- onest: variable("onest", "Onest", "sans", 100, 900, normal, "clean product storytelling"),
- "open-sans": variable("open-sans", "Open Sans", "sans", 300, 800, romanItalic, "highly readable general copy"),
- outfit: variable("outfit", "Outfit", "sans", 100, 900, normal, "geometric creator captions"),
- "plus-jakarta-sans": variable("plus-jakarta-sans", "Plus Jakarta Sans", "sans", 200, 800, romanItalic, "polished startup branding"),
- poppins: staticFont("poppins", "Poppins", "sans", [100, 200, 300, 400, 500, 600, 700, 800, 900], romanItalic, "rounded geometric display"),
- quicksand: variable("quicksand", "Quicksand", "sans", 300, 700, normal, "soft lifestyle captions"),
- raleway: variable("raleway", "Raleway", "sans", 100, 900, romanItalic, "elegant brand copy"),
- "rethink-sans": variable("rethink-sans", "Rethink Sans", "sans", 400, 800, romanItalic, "contemporary brand captions"),
- roboto: variable("roboto", "Roboto", "sans", 100, 900, romanItalic, "neutral general-purpose video"),
- "roboto-condensed": variable("roboto-condensed", "Roboto Condensed", "sans", 100, 900, romanItalic, "space-efficient captions"),
- rubik: variable("rubik", "Rubik", "sans", 300, 900, romanItalic, "friendly rounded interfaces"),
- sora: variable("sora", "Sora", "sans", 100, 800, normal, "technology and product video"),
- "space-grotesk": variable("space-grotesk", "Space Grotesk", "sans", 300, 700, normal, "editorial technology branding"),
- urbanist: variable("urbanist", "Urbanist", "sans", 100, 900, romanItalic, "modern lifestyle video"),
- "work-sans": variable("work-sans", "Work Sans", "sans", 100, 900, romanItalic, "screen-first explanatory copy"),
-
- // Serif and editorial faces.
- "bodoni-moda": variable("bodoni-moda", "Bodoni Moda", "serif", 400, 900, romanItalic, "fashion editorial titles"),
- cinzel: variable("cinzel", "Cinzel", "serif", 400, 900, normal, "classical display titles"),
- "cormorant-garamond": variable("cormorant-garamond", "Cormorant Garamond", "serif", 300, 700, romanItalic, "literary editorial copy"),
- "crimson-pro": variable("crimson-pro", "Crimson Pro", "serif", 200, 900, romanItalic, "readable editorial captions"),
- "eb-garamond": variable("eb-garamond", "EB Garamond", "serif", 400, 800, romanItalic, "classic editorial copy"),
- fraunces: variable("fraunces", "Fraunces", "serif", 100, 900, romanItalic, "expressive editorial titles"),
- gloock: staticFont("gloock", "Gloock", "serif", [400], normal, "dramatic high-contrast titles"),
- "instrument-serif": staticFont("instrument-serif", "Instrument Serif", "serif", [400], romanItalic, "contemporary editorial titles"),
- "libre-baskerville": variable("libre-baskerville", "Libre Baskerville", "serif", 400, 700, romanItalic, "traditional readable copy"),
- lora: variable("lora", "Lora", "serif", 400, 700, romanItalic, "warm narrative captions"),
- merriweather: variable("merriweather", "Merriweather", "serif", 300, 900, romanItalic, "screen-readable long copy"),
- newsreader: variable("newsreader", "Newsreader", "serif", 200, 800, romanItalic, "news and documentary editorial"),
- "playfair-display": variable("playfair-display", "Playfair Display", "serif", 400, 900, romanItalic, "editorial display"),
- "roboto-slab": variable("roboto-slab", "Roboto Slab", "serif", 100, 900, normal, "sturdy explanatory titles", "Apache-2.0"),
- "source-serif-4": variable("source-serif-4", "Source Serif 4", "serif", 200, 900, romanItalic, "readable serif"),
- vollkorn: variable("vollkorn", "Vollkorn", "serif", 400, 900, romanItalic, "bookish narrative copy"),
-
- // Monospaced faces.
- "fira-code": variable("fira-code", "Fira Code", "monospace", 300, 700, normal, "code and technical overlays"),
- "geist-mono": variable("geist-mono", "Geist Mono", "monospace", 100, 900, romanItalic, "minimal technical labels"),
- "ibm-plex-mono": staticFont("ibm-plex-mono", "IBM Plex Mono", "monospace", [100, 200, 300, 400, 500, 600, 700], romanItalic, "editorial technical overlays"),
- "jetbrains-mono": variable("jetbrains-mono", "JetBrains Mono", "monospace", 100, 800, romanItalic, "code demonstrations"),
- "roboto-mono": variable("roboto-mono", "Roboto Mono", "monospace", 100, 700, romanItalic, "neutral measurements and code"),
- "space-mono": staticFont("space-mono", "Space Mono", "monospace", [400, 700], romanItalic, "retro technical titles"),
-
- // Complete CJK faces and display lettering. These retain all Unicode-range shards.
- "long-cang": staticSplit("long-cang", "龙藏体 / Long Cang", "cjk", [400], normal, "expressive Chinese brush copy"),
- "liu-jian-mao-cao": staticSplit("liu-jian-mao-cao", "刘建毛草 / Liu Jian Mao Cao", "cjk", [400], normal, "Chinese cursive display"),
- "ma-shan-zheng": staticSplit("ma-shan-zheng", "马善政毛笔体", "cjk", [400], normal, "Chinese brush titles"),
- "noto-sans-hk": variableSplit("noto-sans-hk", "Noto Sans HK", "cjk", 100, 900, "Hong Kong Traditional Chinese"),
- "noto-sans-jp": variableSplit("noto-sans-jp", "Noto Sans JP", "cjk", 100, 900, "Japanese sans-serif"),
- "noto-sans-kr": variableSplit("noto-sans-kr", "Noto Sans KR", "cjk", 100, 900, "Korean sans-serif"),
- "noto-sans-sc": variableSplit("noto-sans-sc", "Noto Sans SC", "cjk", 100, 900, "Simplified Chinese sans-serif"),
- "noto-sans-tc": variableSplit("noto-sans-tc", "Noto Sans TC", "cjk", 100, 900, "Traditional Chinese sans-serif"),
- "noto-serif-jp": variableSplit("noto-serif-jp", "Noto Serif JP", "cjk", 200, 900, "Japanese serif"),
- "noto-serif-kr": variableSplit("noto-serif-kr", "Noto Serif KR", "cjk", 200, 900, "Korean serif"),
- "noto-serif-sc": variableSplit("noto-serif-sc", "Noto Serif SC", "cjk", 200, 900, "Simplified Chinese serif"),
- "noto-serif-tc": variableSplit("noto-serif-tc", "Noto Serif TC", "cjk", 200, 900, "Traditional Chinese serif"),
- "zcool-kuaile": staticSplit("zcool-kuaile", "站酷快乐体", "cjk", [400], normal, "playful Chinese display"),
- "zcool-qingke-huangyou": staticSplit("zcool-qingke-huangyou", "站酷庆科黄油体", "cjk", [400], normal, "geometric Chinese display"),
- "zcool-xiaowei": staticSplit("zcool-xiaowei", "站酷小薇体", "cjk", [400], normal, "Chinese editorial display"),
-
- // Complete non-Latin script faces.
- "noto-naskh-arabic": variableSplit("noto-naskh-arabic", "Noto Naskh Arabic", "world", 400, 700, "Arabic serif and traditional copy"),
- "noto-sans-arabic": variableSplit("noto-sans-arabic", "Noto Sans Arabic", "world", 100, 900, "Arabic sans-serif"),
- "noto-sans-devanagari": variableSplit("noto-sans-devanagari", "Noto Sans Devanagari", "world", 100, 900, "Devanagari sans-serif"),
- "noto-sans-hebrew": variableSplit("noto-sans-hebrew", "Noto Sans Hebrew", "world", 100, 900, "Hebrew sans-serif"),
- "noto-sans-thai": variableSplit("noto-sans-thai", "Noto Sans Thai", "world", 100, 900, "Thai sans-serif"),
-
- // Emoji. Color is fixed at 400; monochrome remains variable for typographic treatments.
- "noto-color-emoji": externalSplit("@infolektuell/noto-color-emoji", "index.css", "Noto Color Emoji", "emoji", [400], normal, "full-color COLRv1 emoji fallback"),
- "noto-emoji": variableSplit("noto-emoji", "Noto Emoji", "emoji", 300, 700, "monochrome emoji and symbols"),
-} as const satisfies Readonly<Record<string, OpenFontFamily>>;
-
-export type OpenFontFamilyName = keyof typeof openFontFamilies;
-
-export const openFontFamilyNames = Object.freeze(
- Object.keys(openFontFamilies).sort() as OpenFontFamilyName[],
-);
-
-export const openFontFamiliesByCategory = Object.freeze(Object.fromEntries(
- (["handwriting", "script", "display", "sans", "serif", "monospace", "cjk", "world", "emoji"] as const)
- .map((category) => [category, Object.freeze(openFontFamilyNames.filter(
- (name) => openFontFamilies[name].category === category,
- ))]),
-) as Readonly<Record<OpenFontCategory, readonly OpenFontFamilyName[]>>);
diff --git a/packages/fonts-open/src/index.ts b/packages/fonts-open/src/index.ts
deleted file mode 100644
index a47364c3..00000000
--- a/packages/fonts-open/src/index.ts
+++ /dev/null
@@ -1,13 +0,0 @@
-export {
- openFontFamilies,
- openFontFamiliesByCategory,
- openFontFamilyNames,
-} from "./catalog.js";
-export type {
- OpenFontFamily,
- OpenFontCategory,
- OpenFontFamilyName,
- OpenFontStyle,
-} from "./catalog.js";
-export { fontsOpenManifest, fontsOpenMarkupSurfaces, fontsOpenModuleRef } from "./manifest.js";
-export { decodeOpenFontFaceSurface, decodeOpenFontStackSurface } from "./surface.js";
diff --git a/packages/fonts-open/src/manifest.ts b/packages/fonts-open/src/manifest.ts
deleted file mode 100644
index 1ece8dc2..00000000
--- a/packages/fonts-open/src/manifest.ts
+++ /dev/null
@@ -1,83 +0,0 @@
-import { mediaDependency, mediaTypes } from "@hypit/media";
-import type { ModuleManifest } from "@hypit/protocol";
-
-import { openFontFamilyNames } from "./catalog.js";
-
-export const fontsOpenModuleRef = { name: "@hypit/fonts-open", version: "1" } as const;
-
-export const fontsOpenMarkupSurfaces = [{
- name: "face",
- tag: "Face",
- mode: "structured",
- outputs: [mediaTypes.fontArtifact],
- vocabulary: {
- summary: "Materializes one exact catalog face as a FontArtifact Resource.",
- attributes: [
- { name: "id", kind: "identifier", required: true,
- summary: "Names the FontArtifact Record this element publishes." },
- { name: "family", kind: "literal", required: true, values: openFontFamilyNames,
- summary: "Chooses the catalog family the face is taken from." },
- { name: "weight", kind: "literal", required: true,
- summary: "Chooses the exact weight, which the family must publish." },
- { name: "style", kind: "literal", required: true, values: ["normal", "italic"],
- summary: "Chooses the exact style, which the family must publish." },
- ],
- example: `<fonts:Face id="headline" family="archivo-black" weight="400" style="normal"/>`,
- notes: [
- "The element is empty; it accepts no children and no text.",
- "A static family accepts only a weight it ships; a variable family accepts any whole weight inside its range.",
- "The FontArtifact is published under the bare `id`, and an unavailable family, weight or style fails before any bytes are read.",
- ],
- },
- }, {
- name: "stack",
- tag: "Stack",
- mode: "structured",
- outputs: [mediaTypes.fontStack],
- vocabulary: {
- summary: "Orders one primary catalog face, its written fallbacks and an optional Emoji face into one reusable FontStack.",
- attributes: [
- { name: "id", kind: "identifier", required: true,
- summary: "Names the FontStack Record this element publishes." },
- { name: "family", kind: "literal", required: true, values: openFontFamilyNames,
- summary: "Chooses the catalog family the primary face is taken from." },
- { name: "weight", kind: "literal", required: true,
- summary: "Chooses the primary face's exact weight, which the family must publish." },
- { name: "style", kind: "literal", required: true, values: ["normal", "italic"],
- summary: "Chooses the primary face's exact style, which the family must publish." },
- { name: "emoji", kind: "literal", required: false, values: ["color", "mono"],
- summary: "Appends a pinned Emoji face after every other face in the stack." },
- ],
- children: [
- { tag: "Fallback", cardinality: "many",
- summary: "Appends one more exact catalog face after the primary one, in the order written.",
- attributes: [
- { name: "family", kind: "literal", required: true, values: openFontFamilyNames,
- summary: "Chooses the catalog family this fallback face is taken from." },
- { name: "weight", kind: "literal", required: true,
- summary: "Chooses the fallback face's exact weight, which the family must publish." },
- { name: "style", kind: "literal", required: true, values: ["normal", "italic"],
- summary: "Chooses the fallback face's exact style, which the family must publish." },
- ] },
- ],
- example: `<fonts:Stack id="caption-fonts" family="inter" weight="700" style="normal" emoji="color">
- <fonts:Fallback family="noto-sans-sc" weight="700" style="normal"/>
-</fonts:Stack>`,
- notes: [
- "A `<Fallback>` is empty; it accepts no children and no text.",
- "`emoji=\"color\"` selects the COLRv1 face and `emoji=\"mono\"` the weight-400 monochrome face; omitting `emoji` adds no bytes.",
- "The FontStack is published under the bare `id`, and the element carries no text content.",
- ],
- },
- }] as const;
-
-
-export const fontsOpenManifest: ModuleManifest = {
- format: "hypit.module@1",
- name: fontsOpenModuleRef.name,
- version: fontsOpenModuleRef.version,
- dependencies: [mediaDependency],
- types: [],
- capabilities: [],
- producers: [],
-};
diff --git a/packages/fonts-open/src/studio.ts b/packages/fonts-open/src/studio.ts
deleted file mode 100644
index d77c7722..00000000
--- a/packages/fonts-open/src/studio.ts
+++ /dev/null
@@ -1,21 +0,0 @@
-import type { StudioInspectorFieldDeclaration, StudioSourceBindingDeclaration } from "@hypit/studio-adapter";
-import { openFontFamilies } from "./catalog.js";
-
-/** Optional Companion declarations for the primary catalog face reached through a Style's font. */
-export function openFontStudioFields(owner: string): {
- readonly binding: StudioSourceBindingDeclaration;
- readonly fields: readonly StudioInspectorFieldDeclaration[];
-} {
- return {
- binding: { name: "font", referenced: [{ name: "family", writable: true }] },
- fields: [{
- binding: `${owner}.font.family`, label: "Font Family", domain: "how",
- page: { id: "font", label: "Font" }, section: { id: "face", label: "Primary Face" },
- summary: "Changes the shared catalog face. Its authored weight and style must be available in the selected family.",
- control: "select",
- options: Object.entries(openFontFamilies).map(([value, family]) => ({
- value, label: family.label, description: `${family.category} · ${family.intendedUse}`,
- })),
- }],
- };
-}
diff --git a/packages/fonts-open/src/surface.ts b/packages/fonts-open/src/surface.ts
deleted file mode 100644
index 19a95c71..00000000
--- a/packages/fonts-open/src/surface.ts
+++ /dev/null
@@ -1,245 +0,0 @@
-import { readFileSync } from "node:fs";
-import { readFile } from "node:fs/promises";
-import { basename as fileName } from "node:path";
-
-import {
- assertFontArtifactRef,
- assertFontStackRef,
- mediaTypes,
-} from "@hypit/media";
-import type { FontArtifactRef, FontStackRef } from "@hypit/media";
-import type { StructuredElement, StructuredSurfaceHandler } from "@hypit/markup";
-import { NodePackageNotFoundError, resolveNodePackageResource } from "@hypit/package-loader-node";
-
-import {
- openFontFamilies,
- openFontFamilyNames,
-} from "./catalog.js";
-import type {
- OpenFontFamily,
- OpenFontFamilyName,
- OpenFontStyle,
-} from "./catalog.js";
-
-const fontDependencies = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")) as {
- readonly optionalDependencies: Readonly<Record<string, string>>;
-};
-
-function resolveFontPackageFile(packageName: string, path: string): string {
- try {
- return resolveNodePackageResource(packageName, path, { from: import.meta.url });
- } catch (error) {
- if (!(error instanceof NodePackageNotFoundError)) throw error;
- const version = fontDependencies.optionalDependencies[packageName];
- if (version === undefined) throw error;
- throw new Error(
- `${packageName} is needed by this authored font. Install it once with: hypit packages install ${packageName}@${version}`,
- { cause: error },
- );
- }
-}
-
-function attributes(
- element: StructuredElement,
- required: readonly string[],
- optional: readonly string[] = [],
-): void {
- const names = Object.keys(element.attributes);
- const allowed = new Set([...required, ...optional]);
- if (required.some((name) => element.attributes[name] === undefined)
- || names.some((name) => !allowed.has(name))) {
- const suffix = optional.length === 0 ? "" : `, with optional ${optional.join(", ")}`;
- throw new Error(`${element.name} requires exactly ${required.join(", ")}${suffix}`);
- }
-}
-
-function stringAttribute(element: StructuredElement, name: string): string {
- const value = element.attributes[name];
- if (typeof value !== "string" || !value.trim()) throw new Error(`${element.name}.${name} must be a string`);
- return value.trim();
-}
-
-type RequestedFace = {
- readonly familyName: OpenFontFamilyName;
- readonly family: OpenFontFamily;
- readonly weight: number;
- readonly style: OpenFontStyle;
-};
-
-function requestedFace(element: StructuredElement): RequestedFace {
- const familyName = stringAttribute(element, "family") as OpenFontFamilyName;
- if (!openFontFamilyNames.includes(familyName)) {
- throw new Error(`${element.name}.family must be one of ${openFontFamilyNames.join(", ")}`);
- }
- const family: OpenFontFamily = openFontFamilies[familyName];
- const weight = Number(stringAttribute(element, "weight"));
- const validWeight = family.kind === "static" || family.kind === "static-split" || family.kind === "external-split"
- ? family.weights.includes(weight)
- : Number.isSafeInteger(weight) && weight >= family.minimumWeight && weight <= family.maximumWeight;
- if (!validWeight) throw new Error(`${element.name}.weight is unavailable for ${familyName}`);
- const style = stringAttribute(element, "style") as OpenFontStyle;
- if (!(family.styles as readonly OpenFontStyle[]).includes(style)) {
- throw new Error(`${element.name}.style is unavailable for ${familyName}`);
- }
- return { familyName, family, weight, style };
-}
-
-function oneFile(
- family: OpenFontFamily & { readonly fileStem: string },
- weight: number,
- style: OpenFontStyle,
-): string {
- const filename = family.kind === "static"
- ? `${family.fileStem}-${weight}-${style}.woff2`
- : `${family.fileStem}-${style}.woff2`;
- return resolveFontPackageFile(family.packageName, `files/${filename}`);
-}
-
-function splitFiles(
- family: OpenFontFamily & { readonly kind: "variable-split" | "static-split" | "external-split" },
- weight: number,
- style: OpenFontStyle,
-): readonly { readonly path: string; readonly unicodeRange: string }[] {
- const css = family.kind === "variable-split"
- ? family.css
- : family.kind === "external-split"
- ? family.css
- : `${weight}${style === "italic" ? "-italic" : ""}.css`;
- const cssPath = resolveFontPackageFile(family.packageName, css);
- const contents = readFileSync(cssPath, "utf8");
- return [...contents.matchAll(/@font-face\s*\{([\s\S]*?)\}/gu)].map((match) => {
- const body = match[1]!;
- const file = /src:\s*url\((?:['"])?\.\/files\/([^)'";]+\.woff2)(?:['"])?\)/u.exec(body)?.[1];
- const unicodeRange = /unicode-range:\s*([^;]+);/u.exec(body)?.[1]?.replace(/\s+/gu, "");
- if (file === undefined || unicodeRange === undefined) {
- throw new Error(`${family.packageName}/${css} contains an unsupported @font-face`);
- }
- return { path: resolveFontPackageFile(family.packageName, `files/${file}`), unicodeRange };
- });
-}
-
-async function materializeFace(
- request: RequestedFace,
- element: StructuredElement,
- resolveAsset: Parameters<StructuredSurfaceHandler>[0]["resolveAsset"],
-): Promise<FontArtifactRef> {
- const files = request.family.kind === "variable-split" || request.family.kind === "static-split"
- || request.family.kind === "external-split"
- ? splitFiles(request.family, request.weight, request.style)
- : [{ path: oneFile(request.family, request.weight, request.style) }];
- const resolvedSources: FontArtifactRef["sources"] = await Promise.all(files.map(async (file) => {
- const bytes = Uint8Array.from(await readFile(file.path));
- // `require.resolve` answers in the platform's own separator, and this name goes into the
- // asset's provenance. Splitting on "/" left the whole absolute path standing in for the file
- // name wherever that separator is a backslash, which put a machine's directory layout inside
- // an identity that is supposed to name a font file and nothing else.
- const basename = fileName(file.path);
- const resolved = await resolveAsset({
- from: `package:@hypit/fonts-open/${request.familyName}/${basename}`,
- mediaType: "font/woff2",
- bytes,
- range: element.range,
- });
- return {
- artifact: resolved.artifact,
- ...("unicodeRange" in file ? { unicodeRange: file.unicodeRange } : {}),
- };
- }));
- const byArtifact = new Map<string, FontArtifactRef["sources"][number]>();
- for (const source of resolvedSources) {
- const existing = byArtifact.get(source.artifact.resource);
- if (existing === undefined) {
- byArtifact.set(source.artifact.resource, source);
- continue;
- }
- if (existing.unicodeRange === undefined || source.unicodeRange === undefined) continue;
- byArtifact.set(source.artifact.resource, {
- artifact: existing.artifact,
- unicodeRange: `${existing.unicodeRange},${source.unicodeRange}`,
- });
- }
- const font: FontArtifactRef = {
- sources: [...byArtifact.values()],
- weight: request.weight,
- style: request.style,
- };
- assertFontArtifactRef(font, `${element.name}.${request.familyName}`);
- return font;
-}
-
-function localName(name: string): string {
- const colon = name.lastIndexOf(":");
- return colon < 0 ? name : name.slice(colon + 1);
-}
-
-function emptyChildren(element: StructuredElement): void {
- if (element.children.some((child) => child.kind === "element" || child.value.trim())) {
- throw new Error(`${element.name} does not accept children`);
- }
-}
-
-export const decodeOpenFontFaceSurface: StructuredSurfaceHandler = async ({ element, resolveAsset }) => {
- attributes(element, ["id", "family", "weight", "style"]);
- emptyChildren(element);
- const id = stringAttribute(element, "id");
- const font = await materializeFace(requestedFace(element), element, resolveAsset);
- return {
- records: [{
- id,
- type: mediaTypes.fontArtifact,
- value: { kind: "inline", value: font },
- range: element.range,
- }],
- components: [],
- fragments: [],
- };
-};
-
-/**
- * Compact exact-font-stack authoring. Emoji stays explicit but no longer requires a separate Face
- * declaration and Fallback reference for every Style.
- */
-export const decodeOpenFontStackSurface: StructuredSurfaceHandler = async ({ element, resolveAsset }) => {
- attributes(element, ["id", "family", "weight", "style"], ["emoji"]);
- const id = stringAttribute(element, "id");
- const faces: FontArtifactRef[] = [await materializeFace(requestedFace(element), element, resolveAsset)];
-
- for (const child of element.children) {
- if (child.kind === "text") {
- if (child.value.trim()) throw new Error(`${element.name} accepts only Fallback children`);
- continue;
- }
- if (localName(child.name) !== "Fallback") throw new Error(`${element.name} accepts only Fallback children`);
- attributes(child, ["family", "weight", "style"]);
- emptyChildren(child);
- faces.push(await materializeFace(requestedFace(child), child, resolveAsset));
- }
-
- const emoji = element.attributes.emoji;
- if (emoji !== undefined) {
- if (emoji !== "color" && emoji !== "mono") {
- throw new Error(`${element.name}.emoji must be color or mono`);
- }
- const familyName: OpenFontFamilyName = emoji === "color" ? "noto-color-emoji" : "noto-emoji";
- const family = openFontFamilies[familyName];
- faces.push(await materializeFace({
- familyName,
- family,
- weight: 400,
- style: "normal",
- }, element, resolveAsset));
- }
-
- const stack: FontStackRef = { faces };
- assertFontStackRef(stack, `${element.name}.${id}`);
- return {
- records: [{
- id,
- type: mediaTypes.fontStack,
- value: { kind: "inline", value: stack },
- range: element.range,
- }],
- components: [],
- fragments: [],
- };
-};
diff --git a/packages/fonts-open/test/fonts-open.test.ts b/packages/fonts-open/test/fonts-open.test.ts
deleted file mode 100644
index 40ad48e3..00000000
--- a/packages/fonts-open/test/fonts-open.test.ts
+++ /dev/null
@@ -1,147 +0,0 @@
-import assert from "node:assert/strict";
-import test from "node:test";
-
-import {
- decodeOpenFontFaceSurface,
- decodeOpenFontStackSurface,
-} from "@hypit/fonts-open";
-import type { FontArtifactRef, FontStackRef } from "@hypit/media";
-import type { StructuredElement, StructuredSurfaceHandler } from "@hypit/markup";
-
-const range = { start: 0, end: 80 };
-
-async function decode(
- handler: StructuredSurfaceHandler,
- element: StructuredElement,
-) {
- const requests: { readonly from: string; readonly bytes: Uint8Array }[] = [];
- const output = await handler({
- sourceName: "main.svml",
- element,
- resolveReference: () => undefined,
- resolveAsset(request) {
- assert.ok(request.bytes);
- const bytes = Uint8Array.from(request.bytes);
- requests.push({ from: request.from, bytes });
- return {
- artifact: {
- kind: "blob",
- resource: `res_font-${requests.length}`,
- size: bytes.byteLength,
- mediaType: request.mediaType,
- },
- };
- },
- });
- const stored = output.records[0]!.value;
- assert.equal(stored.kind, "inline");
- return { value: stored.kind === "inline" ? stored.value : undefined!, requests, output };
-}
-
-async function decodeFace(family: string, weight: string, style: string) {
- const result = await decode(decodeOpenFontFaceSurface, {
- kind: "element",
- name: "fonts:Face",
- attributes: { id: "selected", family, weight, style },
- children: [],
- range,
- });
- return { ...result, font: result.value as unknown as FontArtifactRef };
-}
-
-test("one Latin variable face contributes one exact installed source", async () => {
- const { font, requests } = await decodeFace("inter", "700", "italic");
- assert.equal(font.weight, 700);
- assert.equal(font.style, "italic");
- assert.equal(font.sources.length, 1);
- assert.equal(requests[0]!.from.endsWith("/inter-latin-wght-italic.woff2"), true);
- assert.ok(requests[0]!.bytes.byteLength > 10_000);
-});
-
-test("one CJK face preserves every Fontsource Unicode-range source", async () => {
- const { font, requests } = await decodeFace("noto-sans-sc", "700", "normal");
- assert.equal(font.sources.length, 101);
- assert.equal(requests.length, 101);
- assert.equal(font.sources.every((source) => source.unicodeRange?.startsWith("U+") === true), true);
- assert.ok(requests.reduce((total, request) => total + request.bytes.byteLength, 0) > 4_000_000);
-});
-
-test("static split CJK and color emoji faces retain their complete installed shards", async () => {
- const cjk = await decodeFace("zcool-kuaile", "400", "normal");
- assert.ok(cjk.font.sources.length > 10);
- const color = await decodeFace("noto-color-emoji", "400", "normal");
- assert.equal(color.font.sources.length, 11);
- assert.ok(color.requests.reduce((total, request) => total + request.bytes.byteLength, 0) > 1_500_000);
-});
-
-test("Stack makes exact CJK and emoji fallback a single reusable author edge", async () => {
- const result = await decode(decodeOpenFontStackSurface, {
- kind: "element",
- name: "fonts:Stack",
- attributes: { id: "caption-fonts", family: "inter", weight: "700", style: "normal", emoji: "color" },
- children: [{
- kind: "element",
- name: "fonts:Fallback",
- attributes: { family: "noto-sans-sc", weight: "700", style: "normal" },
- children: [],
- range,
- }],
- range,
- });
- const stack = result.value as unknown as FontStackRef;
- assert.equal(stack.faces.length, 3);
- assert.equal(stack.faces[0]!.weight, 700);
- assert.equal(stack.faces[1]!.sources.length, 101);
- assert.equal(stack.faces[2]!.sources.length, 11);
- assert.equal(stack.faces[2]!.weight, 400);
-});
-
-test("unavailable family, weight, style and emoji combinations fail before reading bytes", async () => {
- await assert.rejects(async () => await decodeFace("comic-sans", "700", "normal"), /family must be one of/u);
- await assert.rejects(async () => await decodeFace("bebas-neue", "700", "normal"), /weight is unavailable/u);
- await assert.rejects(async () => await decodeFace("manrope", "700", "italic"), /style is unavailable/u);
- await assert.rejects(async () => await decode(decodeOpenFontStackSurface, {
- kind: "element", name: "fonts:Stack",
- attributes: { id: "bad", family: "inter", weight: "700", style: "normal", emoji: "surprise" },
- children: [], range,
- }), /emoji must be color or mono/u);
-});
-
-test("font installation guidance applies only to absent packages and uses the owning manifest", async (t) => {
- const { cp, mkdir, mkdtemp, readFile, rm, writeFile } = await import("node:fs/promises");
- const { tmpdir } = await import("node:os");
- const { join } = await import("node:path");
- const { pathToFileURL } = await import("node:url");
- const directory = await mkdtemp(join(tmpdir(), "hypit-font-installation-"));
- t.after(() => rm(directory, { recursive: true, force: true }));
- const installed = join(directory, "node_modules", "@hypit", "fonts-open");
- await mkdir(join(installed, "src"), { recursive: true });
- const manifest = JSON.parse(await readFile(new URL("../package.json", import.meta.url), "utf8"));
- manifest.optionalDependencies["@fontsource-variable/inter"] = "9.8.7";
- await writeFile(join(installed, "package.json"), JSON.stringify(manifest));
- for (const name of ["surface.ts", "catalog.ts"]) {
- await cp(new URL(`../src/${name}`, import.meta.url), join(installed, "src", name));
- }
- for (const name of ["media", "package-loader-node"]) {
- const root = join(directory, "node_modules", "@hypit", name);
- await mkdir(root, { recursive: true });
- await writeFile(join(root, "package.json"), JSON.stringify({ name: `@hypit/${name}`, type: "module", exports: "./index.mjs" }));
- await writeFile(join(root, "index.mjs"), `export * from ${JSON.stringify(import.meta.resolve(`@hypit/${name}`))};`);
- }
- const module = await import(pathToFileURL(join(installed, "src", "surface.ts")).href);
- const face = () => decode(module.decodeOpenFontFaceSurface, {
- kind: "element", name: "fonts:Face", attributes: { id: "selected", family: "inter", weight: "700", style: "normal" },
- children: [], range,
- });
- await assert.rejects(face(), /hypit packages install @fontsource-variable\/inter@9\.8\.7/u);
- const font = join(directory, "node_modules", "@fontsource-variable", "inter");
- await mkdir(font, { recursive: true });
- await writeFile(join(font, "package.json"), JSON.stringify({ name: "@fontsource-variable/inter", version: "9.8.7" }));
- await assert.rejects(face(), error => {
- assert.match(String(error), /does not contain files/u);
- assert.doesNotMatch(String(error), /Install it once/u);
- return true;
- });
- await writeFile(join(font, "package.json"), "broken manifest");
- await assert.rejects(face(), SyntaxError);
-});
diff --git a/packages/fontsource/README.md b/packages/fontsource/README.md
new file mode 100644
index 00000000..4768e235
--- /dev/null
+++ b/packages/fontsource/README.md
@@ -0,0 +1,21 @@
+# `@hypit/fontsource`
+
+This package adapts font packages already selected by an authored project's ordinary
+`package.json` and lockfile into Hypit's generic `FontArtifactRef` value.
+
+```xml
+<import module="@hypit/fontsource@1" as="fontsource"/>
+<fontsource:Face
+ id="inter"
+ package="@fontsource-variable/inter"
+ weight="700"
+ style="normal"
+/>
+```
+
+The official `@hypit/hypit` Distribution supplies this adapter as an ordinary versioned dependency.
+A custom Distribution can depend on it the same way. Install only the font families the project
+actually uses in that project's `package.json`; its lockfile owns their versions. The adapter contains
+no font catalog and no bundled family dependencies. It reads `metadata.json`, CSS and font files from
+installed packages without executing their code. Other npm font packages and project-owned files can
+be declared directly through `@hypit/media@1` `Font` and `FontStack` surfaces.
diff --git a/packages/fontsource/package.json b/packages/fontsource/package.json
new file mode 100644
index 00000000..ed1bde3e
--- /dev/null
+++ b/packages/fontsource/package.json
@@ -0,0 +1,25 @@
+{
+ "name": "@hypit/fontsource",
+ "version": "0.1.0",
+ "license": "SEE LICENSE IN LICENSE",
+ "private": true,
+ "type": "module",
+ "exports": {
+ ".": "./src/index.ts"
+ },
+ "files": [
+ "dist",
+ "README.md"
+ ],
+ "hypit": {
+ "activation": "./src/activation.ts"
+ },
+ "peerDependencies": {
+ "@hypit/hypit": "workspace:^",
+ "@hypit/studio-companion": "workspace:^"
+ },
+ "devDependencies": {
+ "@hypit/hypit": "workspace:^",
+ "@hypit/studio-companion": "workspace:*"
+ }
+}
diff --git a/packages/fontsource/src/activation.ts b/packages/fontsource/src/activation.ts
new file mode 100644
index 00000000..ee97ea2f
--- /dev/null
+++ b/packages/fontsource/src/activation.ts
@@ -0,0 +1,22 @@
+import { createMarkupSurfaceFacet } from "@hypit/hypit/markup";
+import { createStudioCompanionFacet } from "@hypit/studio-companion";
+import {
+ decodeFontsourceFaceSurface,
+ fontsourceManifest,
+ fontsourceMarkupSurfaces,
+ fontsourceModuleRef,
+ fontsourceStudioParameterCompanions,
+} from "./index.js";
+
+export default {
+ format: "hypit.package@1" as const,
+ modules: [{ manifest: fontsourceManifest }],
+ facets: [
+ createMarkupSurfaceFacet({
+ module: fontsourceModuleRef,
+ declaration: fontsourceMarkupSurfaces[0]!,
+ handler: decodeFontsourceFaceSurface,
+ }),
+ createStudioCompanionFacet({ parameters: fontsourceStudioParameterCompanions }),
+ ],
+};
diff --git a/packages/fontsource/src/index.ts b/packages/fontsource/src/index.ts
new file mode 100644
index 00000000..d83d7da8
--- /dev/null
+++ b/packages/fontsource/src/index.ts
@@ -0,0 +1,3 @@
+export { fontsourceManifest, fontsourceMarkupSurfaces, fontsourceModuleRef } from "./manifest.js";
+export { decodeFontsourceFaceSurface } from "./surface.js";
+export { fontsourceStudioParameterCompanions } from "./studio.js";
diff --git a/packages/fontsource/src/manifest.ts b/packages/fontsource/src/manifest.ts
new file mode 100644
index 00000000..95c73472
--- /dev/null
+++ b/packages/fontsource/src/manifest.ts
@@ -0,0 +1,40 @@
+import { mediaDependency, mediaTypes } from "@hypit/hypit/media";
+import type { ModuleManifest } from "@hypit/hypit/protocol";
+
+export const fontsourceModuleRef = { name: "@hypit/fontsource", version: "1" } as const;
+
+export const fontsourceMarkupSurfaces = [{
+ name: "face",
+ tag: "Face",
+ mode: "structured",
+ outputs: [mediaTypes.fontArtifact],
+ vocabulary: {
+ summary: "Materializes one exact face from an installed Fontsource npm package.",
+ attributes: [
+ { name: "id", kind: "identifier", required: true,
+ summary: "Names the FontArtifact Record this element publishes." },
+ { name: "package", kind: "literal", required: true,
+ summary: "Names one installed @fontsource or @fontsource-variable package selected by the project lockfile." },
+ { name: "weight", kind: "literal", required: true,
+ summary: "Chooses an exact integer weight supported by the installed package." },
+ { name: "style", kind: "literal", required: true, values: ["normal", "italic"],
+ summary: "Chooses an exact style supported by the installed package." },
+ ],
+ example: `<fontsource:Face id="headline" package="@fontsource-variable/inter" weight="700" style="normal"/>`,
+ notes: [
+ "The active Distribution or project selects the adapter version; the project package.json and lockfile own the selected font package version.",
+ "This adapter reads package metadata and CSS as data. It does not import or execute upstream package code.",
+ "Changing package selects a dependency; it is not a family dropdown backed by a Hypit-maintained catalog.",
+ ],
+ },
+}] as const;
+
+export const fontsourceManifest: ModuleManifest = {
+ format: "hypit.module@1",
+ name: fontsourceModuleRef.name,
+ version: fontsourceModuleRef.version,
+ dependencies: [mediaDependency],
+ types: [],
+ capabilities: [],
+ producers: [],
+};
diff --git a/packages/fontsource/src/studio.ts b/packages/fontsource/src/studio.ts
new file mode 100644
index 00000000..93f987b2
--- /dev/null
+++ b/packages/fontsource/src/studio.ts
@@ -0,0 +1,21 @@
+import type { StudioParameterCompanion } from "@hypit/studio-companion";
+import { fontsourceModuleRef } from "./manifest.js";
+
+export const fontsourceStudioParameterCompanions: readonly StudioParameterCompanion[] = [{
+ id: "face",
+ match: { module: fontsourceModuleRef, surface: "face" },
+ bindings: [
+ { name: "package" },
+ { name: "weight", writable: true },
+ { name: "style", writable: true },
+ ],
+ inspector: [
+ { binding: "package", label: "Font Package", domain: "how", section: { id: "face", label: "Face" },
+ summary: "The installed npm dependency selected by the project lockfile.", control: "text" },
+ { binding: "weight", label: "Weight", domain: "how", section: { id: "face", label: "Face" },
+ summary: "An exact weight supported by the installed package.", control: "number",
+ number: { minimum: 1, maximum: 1_000, step: 1 } },
+ { binding: "style", label: "Style", domain: "how", section: { id: "face", label: "Face" },
+ control: "select", options: ["normal", "italic"] },
+ ],
+}];
diff --git a/packages/fontsource/src/surface.ts b/packages/fontsource/src/surface.ts
new file mode 100644
index 00000000..0eaec657
--- /dev/null
+++ b/packages/fontsource/src/surface.ts
@@ -0,0 +1,148 @@
+import { readFile } from "node:fs/promises";
+
+import type { StructuredElement, StructuredSurfaceHandler } from "@hypit/hypit/markup";
+import { assertAttributes, assertEmptyElement } from "@hypit/hypit/markup";
+import { assertFontArtifactRef, mediaTypes } from "@hypit/hypit/media";
+import type { FontArtifactRef } from "@hypit/hypit/media";
+import {
+ NodePackageNotFoundError,
+ resolveNodePackageResource,
+} from "@hypit/hypit/loader/node";
+
+type FontsourceMetadata = {
+ readonly id: string;
+ readonly family: string;
+ readonly weights: readonly number[];
+ readonly styles: readonly string[];
+ readonly variable: false | Readonly<Record<string, {
+ readonly min: string;
+ readonly max: string;
+ readonly step: string;
+ }>>;
+};
+
+function textAttribute(element: StructuredElement, name: string): string {
+ const value = element.attributes[name];
+ if (typeof value !== "string" || value.trim().length === 0) {
+ throw new Error(`${element.name}.${name} must be a non-empty string`);
+ }
+ return value.trim();
+}
+
+function fontsourcePackage(element: StructuredElement): string {
+ const value = textAttribute(element, "package");
+ if (!/^@fontsource(?:-variable)?\/[a-z0-9][a-z0-9-]*$/u.test(value)) {
+ throw new Error(`${element.name}.package must name one @fontsource or @fontsource-variable package`);
+ }
+ return value;
+}
+
+function resolveResource(packageName: string, path: string, sourceId: string): string {
+ try {
+ return resolveNodePackageResource(packageName, path, {
+ from: sourceId,
+ workspaceRoots: [],
+ });
+ } catch (error) {
+ if (!(error instanceof NodePackageNotFoundError)) throw error;
+ throw new Error(
+ `${packageName} is not installed for the Source that selected it. Add it to that project's package.json and install the lockfile.`,
+ { cause: error },
+ );
+ }
+}
+
+function faceFiles(css: string, packageName: string, cssName: string): readonly {
+ readonly path: string;
+ readonly unicodeRange?: string;
+}[] {
+ const result = [...css.matchAll(/@font-face\s*\{([\s\S]*?)\}/gu)].map((match) => {
+ const body = match[1]!;
+ const file = /src:\s*url\((?:['"])?\.\/files\/([^)'";]+\.woff2)(?:['"])?\)/u.exec(body)?.[1];
+ const unicodeRange = /unicode-range:\s*([^;]+);/u.exec(body)?.[1]?.replace(/\s+/gu, "");
+ if (file === undefined) throw new Error(`${packageName}/${cssName} contains an unsupported @font-face source`);
+ return {
+ path: `files/${file}`,
+ ...(unicodeRange === undefined ? {} : { unicodeRange }),
+ };
+ });
+ if (result.length === 0) throw new Error(`${packageName}/${cssName} contains no @font-face rules`);
+ return result;
+}
+
+function numberAttribute(element: StructuredElement, name: string): number {
+ const value = Number(textAttribute(element, name));
+ if (!Number.isSafeInteger(value) || value < 1 || value > 1_000) {
+ throw new Error(`${element.name}.${name} must be an integer from 1 to 1000`);
+ }
+ return value;
+}
+
+function validateMetadata(value: unknown, packageName: string): FontsourceMetadata {
+ if (value === null || typeof value !== "object" || Array.isArray(value)) {
+ throw new Error(`${packageName}/metadata.json must be an object`);
+ }
+ const metadata = value as Partial<FontsourceMetadata>;
+ if (typeof metadata.id !== "string" || typeof metadata.family !== "string"
+ || !Array.isArray(metadata.weights) || !metadata.weights.every(Number.isSafeInteger)
+ || !Array.isArray(metadata.styles) || !metadata.styles.every((style) => typeof style === "string")
+ || (metadata.variable !== false && (metadata.variable === null || typeof metadata.variable !== "object"))) {
+ throw new Error(`${packageName}/metadata.json has an unsupported shape`);
+ }
+ return metadata as FontsourceMetadata;
+}
+
+export const decodeFontsourceFaceSurface: StructuredSurfaceHandler = async ({
+ element,
+ sourceId,
+ resolveAsset,
+}) => {
+ assertAttributes(element, ["id", "package", "weight", "style"]);
+ assertEmptyElement(element);
+ if (sourceId === undefined) throw new Error(`${element.name} requires a canonical Source identity from its Host`);
+ const id = textAttribute(element, "id");
+ const packageName = fontsourcePackage(element);
+ const weight = numberAttribute(element, "weight");
+ const styleValue = textAttribute(element, "style");
+ if (styleValue !== "normal" && styleValue !== "italic") {
+ throw new Error(`${element.name}.style must be normal or italic`);
+ }
+ const style: "normal" | "italic" = styleValue;
+ const metadataPath = resolveResource(packageName, "metadata.json", sourceId);
+ const metadata = validateMetadata(JSON.parse(await readFile(metadataPath, "utf8")), packageName);
+ if (!metadata.styles.includes(style)) throw new Error(`${packageName} does not publish style ${style}`);
+ let cssName: string;
+ if (metadata.variable === false) {
+ if (!metadata.weights.includes(weight)) throw new Error(`${packageName} does not publish weight ${weight}`);
+ cssName = `${weight}${style === "italic" ? "-italic" : ""}.css`;
+ } else {
+ const axis = metadata.variable.wght;
+ if (axis === undefined || weight < Number(axis.min) || weight > Number(axis.max)) {
+ throw new Error(`${packageName} does not publish weight ${weight}`);
+ }
+ cssName = `wght${style === "italic" ? "-italic" : ""}.css`;
+ }
+ const cssPath = resolveResource(packageName, cssName, sourceId);
+ const files = faceFiles(await readFile(cssPath, "utf8"), packageName, cssName);
+ const sources: FontArtifactRef["sources"][number][] = [];
+ for (const file of files) {
+ // Validate the CSS path against the located package before asking the Host to stage it.
+ resolveResource(packageName, file.path, sourceId);
+ const resolved = await resolveAsset({
+ from: `package:${packageName}/${file.path}`,
+ mediaType: "font/woff2",
+ range: element.range,
+ });
+ sources.push({
+ artifact: resolved.artifact,
+ ...(file.unicodeRange === undefined ? {} : { unicodeRange: file.unicodeRange }),
+ });
+ }
+ const font: FontArtifactRef = { sources, weight, style };
+ assertFontArtifactRef(font, `${element.name}.${id}`);
+ return {
+ records: [{ id, type: mediaTypes.fontArtifact, value: { kind: "inline", value: font }, range: element.range }],
+ components: [],
+ fragments: [],
+ };
+};
diff --git a/packages/fontsource/test/fontsource.test.ts b/packages/fontsource/test/fontsource.test.ts
new file mode 100644
index 00000000..ae1d2e82
--- /dev/null
+++ b/packages/fontsource/test/fontsource.test.ts
@@ -0,0 +1,61 @@
+import assert from "node:assert/strict";
+import { fileURLToPath } from "node:url";
+import test from "node:test";
+
+import { fixtureResource } from "../../../test/fixture-resource.js";
+import { mediaTypes } from "@hypit/hypit/media";
+import { decodeFontsourceFaceSurface } from "../src/index.js";
+
+const range = { start: 0, end: 120 };
+
+test("Fontsource Face reads an installed package as data and preserves every Unicode shard", async () => {
+ const requests: string[] = [];
+ const result = await decodeFontsourceFaceSurface({
+ sourceName: "fontsource.test.ts",
+ sourceId: fileURLToPath(import.meta.url),
+ element: {
+ kind: "element",
+ name: "fontsource:Face",
+ attributes: {
+ id: "inter",
+ package: "@fontsource-variable/inter",
+ weight: "700",
+ style: "normal",
+ },
+ children: [],
+ range,
+ },
+ resolveReference: () => undefined,
+ resolveAsset: (request) => {
+ requests.push(request.from);
+ return { artifact: {
+ kind: "blob",
+ resource: fixtureResource(`fontsource:${request.from}`),
+ size: 2_048,
+ mediaType: request.mediaType,
+ } };
+ },
+ });
+ assert.deepEqual(result.records[0]!.type, mediaTypes.fontArtifact);
+ assert.equal(requests.length, 7);
+ assert.ok(requests.every((request) => request.startsWith("package:@fontsource-variable/inter/files/")));
+ const value = (result.records[0]!.value as unknown as { value: { sources: unknown[]; weight: number } }).value;
+ assert.equal(value.sources.length, 7);
+ assert.equal(value.weight, 700);
+});
+
+test("Fontsource Face rejects a package prefix instead of treating npm as a global catalog", async () => {
+ await assert.rejects(async () => await decodeFontsourceFaceSurface({
+ sourceName: "fontsource.test.ts",
+ sourceId: fileURLToPath(import.meta.url),
+ element: {
+ kind: "element",
+ name: "fontsource:Face",
+ attributes: { id: "bad", package: "some-font", weight: "400", style: "normal" },
+ children: [],
+ range,
+ },
+ resolveReference: () => undefined,
+ resolveAsset: () => { throw new Error("invalid package must fail before assets"); },
+ }), /must name one @fontsource/u);
+});
diff --git a/packages/estimate/README.md b/packages/speech-estimate/README.md
similarity index 71%
rename from packages/estimate/README.md
rename to packages/speech-estimate/README.md
index 18064dfd..ea8bff51 100644
--- a/packages/estimate/README.md
+++ b/packages/speech-estimate/README.md
@@ -1,17 +1,18 @@
-# `@hypit/estimate`
+# `@hypit/speech-estimate`
-Provider-free speech-duration measurement, used at creation time.
+Provider-free speech-duration estimation, used at creation time. The `hypit estimate` command performs
+this deterministic calculation; it does not observe generated audio.
A duration is the author's decision, written as a literal on the element that needs it:
-`<seedance:TextVideo … duration="8"/>`, `<media:StillVideo … duration="6"/>`. This package is how the
+`<seedance:TextVideo … duration="8"/>`, `<media:StillVideo … duration="6s"/>`. This package is how the
author arrives at that number before writing it. It counts pronunciation units of a Text with a
language-aware delivery density (English dictionary words use CMUdict; unknown words use a
deterministic spelling fallback), then applies optional padding and the selected rounding. The Text remains
authoritative: the estimator never invents how numbers, names or acronyms are pronounced.
```bash
-hypit measure main.svml --segment opening --language en --pace normal
-hypit measure --text "Video editing begins with meaning." --language en --pace normal --rounding ceil
+hypit estimate main.svml --segment opening --language en --pace normal
+hypit estimate --text "Video editing begins with meaning." --language en --pace normal --rounding ceil
```
## Units and delivery
@@ -23,7 +24,7 @@ adding units. This remains an approximation: connected English speech can reduce
and Mandarin erhua can combine written characters into one syllable. An explicit `--language zh`
keeps a Chinese passage with many English names under its intended delivery policy.
-Measure the spoken wording. `--segment` reads the Script's pronunciation side of Dual Text;
+Estimate from the spoken wording. `--segment` reads the Script's pronunciation side of Dual Text;
`--text` reads literal speech, so spell numbers and letter names as they will be said. A count
cannot resolve an unspecified pronunciation.
@@ -31,6 +32,8 @@ cannot resolve an unspecified pronunciation.
| --- | ---: | ---: | ---: | --- |
| English (`en`) | 4.2 | 4.6 | 5.6 | syllables/s |
| Mandarin Chinese (`zh`) | 4.2 | 5.25 | 6.5625 | approximate syllables/s |
+| Japanese (`ja`) | 6 | 7.5 | 9.375 | approximate written mora-like units/s |
+| Spanish (`es`) | 4.72 | 5.9 | 7.375 | approximate syllables/s |
These are authoring starting points for whole-passage delivery, including ordinary speech pauses.
`normal` suits conversational explanation; `fast` gives brisk, tightly delivered copy less time.
@@ -40,9 +43,17 @@ does not establish that it is systematically too slow for whole passages. Neithe
calibration of a particular video or voice model. For a specific delivery, a positive numeric
`--rate` replaces the preset, including rates outside this table.
+Japanese currently counts each Han or kana code point as one approximate unit and applies the English
+fallback to embedded Latin words. This is intentionally a writing-based estimate, not a morphological
+or pronunciation analysis: small kana, long-vowel marks and context-dependent readings can make the
+count differ from spoken morae. Spanish uses a deterministic vowel-nucleus approximation; hiatus,
+diphthongs and dialectal delivery can differ. Unlike the English and Mandarin discussion below, the
+Japanese and Spanish presets are inherited authoring heuristics rather than values validated by the
+cited studies. Use an explicit numeric `--rate` when the production has better delivery evidence.
+
```bash
-hypit measure main.svml --segment opening --language zh --pace fast --rounding round
-hypit measure main.svml --segment opening --language zh --rate 6 --rounding none
+hypit estimate main.svml --segment opening --language zh --pace fast --rounding round
+hypit estimate main.svml --segment opening --language zh --rate 6 --rounding none
```
`seconds = pronunciation units / rate + padding`, followed by rounding. Add `--padding` for extra
@@ -60,12 +71,12 @@ needs merging, fuller wording, tightening, or splitting, then choose the request
selected model's supported values in mind.
`SpeechEstimatePolicy` holds the language, pace or rate, rounding and optional padding used by the
-measurement API. `speechEstimatePolicyFromRecipe` reads those values from a Recipe for package authors.
-The measurement produces a duration estimate for authoring; actual word positions come from the
+estimation API. `speechEstimatePolicyFromRecipe` reads those values from a Recipe for package authors.
+The calculation produces a duration estimate for authoring; actual word positions come from the
performed media's semantic preparation.
```ts
-import { estimateSpeechDuration, sealSpeechEstimatePolicy, speechEstimatePolicyFromRecipe } from "@hypit/estimate";
+import { estimateSpeechDuration, sealSpeechEstimatePolicy, speechEstimatePolicyFromRecipe } from "@hypit/speech-estimate";
```
## Research basis and limits
diff --git a/packages/speech-estimate/package.json b/packages/speech-estimate/package.json
new file mode 100644
index 00000000..806afda6
--- /dev/null
+++ b/packages/speech-estimate/package.json
@@ -0,0 +1,22 @@
+{
+ "name": "@hypit/speech-estimate",
+ "version": "0.1.0",
+ "license": "SEE LICENSE IN LICENSE",
+ "private": true,
+ "type": "module",
+ "exports": {
+ ".": "./src/index.ts",
+ "./cli": "./src/cli.ts"
+ },
+ "dependencies": {
+ "cmu-pronouncing-dictionary": "3.0.0"
+ },
+ "peerDependencies": {
+ "@hypit/hypit": "workspace:^"
+ },
+ "devDependencies": {
+ "@hypit/hypit": "workspace:*",
+ "@hypit/recipe": "workspace:*",
+ "@hypit/text": "workspace:*"
+ }
+}
diff --git a/packages/speech-estimate/src/cli.ts b/packages/speech-estimate/src/cli.ts
new file mode 100644
index 00000000..11200ebf
--- /dev/null
+++ b/packages/speech-estimate/src/cli.ts
@@ -0,0 +1,147 @@
+import { readFile, stat } from "node:fs/promises";
+import { resolve } from "node:path";
+
+import { loadDiscoveredSourcePackages } from "@hypit/hypit/cli";
+import type { CliApplicationContext, CliCommandModule, CliIo } from "@hypit/hypit/cli";
+import { sealText } from "@hypit/hypit/text";
+
+import {
+ countSpeechEstimateUnits,
+ estimateSpeechDuration,
+ resolveSpeechEstimateLanguage,
+ resolveSpeechEstimateRate,
+} from "./program.js";
+import { speechEstimatePolicyFromAttributes } from "./policy.js";
+
+function assert(condition: unknown, message: string): asserts condition {
+ if (!condition) throw new Error(message);
+}
+
+type Parsed = {
+ readonly positionals: readonly string[];
+ readonly options: ReadonlyMap<string, string>;
+ readonly json: boolean;
+};
+
+function parse(argv: readonly string[]): Parsed {
+ const allowed = new Set(["--text", "--segment", "--language", "--pace", "--rate", "--rounding", "--padding", "--project"]);
+ const positionals: string[] = [];
+ const options = new Map<string, string>();
+ let json = false;
+ for (let index = 1; index < argv.length; index++) {
+ const item = argv[index]!;
+ if (item === "--json") { json = true; continue; }
+ if (["--debug", "--verbose", "--no-color"].includes(item)) continue;
+ if (item === "--color") { index += 1; continue; }
+ if (!item.startsWith("--")) { positionals.push(item); continue; }
+ assert(allowed.has(item), `unknown option ${item}`);
+ assert(!options.has(item), `${item} cannot be repeated`);
+ const value = argv[++index];
+ assert(value !== undefined && !value.startsWith("--"), `${item} requires a value`);
+ options.set(item, value);
+ }
+ return { positionals, options, json };
+}
+
+async function textOrFile(value: string, cwd: string): Promise<string> {
+ const path = resolve(cwd, value);
+ const isFile = await stat(path).then((item) => item.isFile(), () => false);
+ const text = (isFile ? await readFile(path, "utf8") : value).trim();
+ assert(text.length > 0, isFile ? `--text file ${path} is empty` : "--text is empty");
+ return text;
+}
+
+async function segmentSpeech(
+ source: string,
+ segment: string,
+ projectRoot: string,
+ application: CliApplicationContext,
+): Promise<string> {
+ const distribution = application.distribution;
+ const loaded = await loadDiscoveredSourcePackages({ ...distribution, bootstrapPackages: [] }, {
+ source,
+ workspaceRoot: projectRoot,
+ packageRoot: projectRoot,
+ ...(distribution.packageRoot === undefined ? {} : { distributionPackageRoot: distribution.packageRoot }),
+ });
+ const compiler = distribution.createCompiler({
+ workspaceRoot: projectRoot,
+ packageRoot: projectRoot,
+ ...(distribution.packageRoot === undefined ? {} : { distributionPackageRoot: distribution.packageRoot }),
+ packageContributions: loaded.map((item) => item.contribution),
+ });
+ const workspace = await compiler.openEntry(source);
+ const compiled = await compiler.compileResolvedSource(workspace.entry, workspace);
+ const suffix = `.segment.${segment}.speech`;
+ const record = compiled.program.records.find((item) =>
+ item.type.module.name === "@hypit/text" && item.type.name === "Text" && item.id.endsWith(suffix));
+ assert(record !== undefined, `${source} declares no Segment ${segment} with speech; Segments are named by the Script's <segment id>`);
+ assert(record.value.kind === "inline", `Segment ${segment} speech is not an inline Text`);
+ const text = (record.value.value as { readonly value?: unknown } | null)?.value;
+ assert(typeof text === "string", `Segment ${segment} speech is not Text`);
+ return text;
+}
+
+export function writeEstimateHelp(io: CliIo): void {
+ io.write("hypit estimate\nEstimate authored speech before choosing a literal duration. Pure local work.\n\n"
+ + " hypit estimate <source.svml> --segment <id> [--language auto|en|zh|ja|es] [--pace slow|normal|fast | --rate <units/s>]\n"
+ + " [--rounding none|round|ceil] [--padding <s>] [--project <directory>]\n"
+ + " hypit estimate --text <text|file> [same speech options]\n");
+}
+
+export async function runEstimateCli(
+ argv: readonly string[],
+ io: CliIo,
+ application: CliApplicationContext,
+): Promise<void> {
+ if (argv.includes("--help")) { writeEstimateHelp(io); return; }
+ const parsed = parse(argv);
+ const inlineText = parsed.options.get("--text");
+ const segment = parsed.options.get("--segment");
+ let text: string;
+ let where: { readonly source: string; readonly segment: string } | { readonly text: true };
+ if (inlineText !== undefined) {
+ assert(segment === undefined && parsed.positionals.length === 0, "--text cannot be combined with a source or --segment");
+ text = await textOrFile(inlineText, application.cwd);
+ where = { text: true };
+ } else {
+ assert(parsed.positionals.length === 1 && segment !== undefined,
+ "estimate takes either --text <text|file>, or a source .svml with --segment <id>");
+ const source = resolve(application.cwd, parsed.positionals[0]!);
+ const project = parsed.options.get("--project");
+ const projectRoot = await application.resolveProjectRoot(
+ project === undefined ? undefined : resolve(application.cwd, project),
+ );
+ text = await segmentSpeech(source, segment, projectRoot, application);
+ where = { source, segment };
+ }
+ const pace = parsed.options.get("--pace");
+ const rate = parsed.options.get("--rate");
+ assert(pace === undefined || rate === undefined, "estimate takes either --pace or --rate, not both");
+ const policy = speechEstimatePolicyFromAttributes({
+ language: parsed.options.get("--language") ?? "auto",
+ ...(rate === undefined ? { pace: pace ?? "normal" } : { rate }),
+ rounding: parsed.options.get("--rounding") ?? "none",
+ ...(parsed.options.get("--padding") === undefined ? {} : { padding: parsed.options.get("--padding") }),
+ }, "hypit estimate");
+ const language = resolveSpeechEstimateLanguage(text, policy.language);
+ const units = countSpeechEstimateUnits(text, language);
+ const seconds = estimateSpeechDuration(sealText(text), policy);
+ const resolvedRate = resolveSpeechEstimateRate(policy, language);
+ const view = { format: "hypit.speech-estimate@1", ...where, characters: text.length,
+ units, language, policy, rate: resolvedRate, seconds };
+ if (parsed.json) { io.write(`${JSON.stringify(view, null, 2)}\n`); return; }
+ io.write(`${Number(seconds.toFixed(3))}s\n\n ${units} pronunciation units · ${language} · ${resolvedRate} units/s${
+ policy.pace === undefined ? "" : ` (${policy.pace})`}\n padding ${policy.paddingSec ?? 0}s · rounding ${policy.rounding}\n ${
+ "segment" in where ? `${where.segment} in ${where.source}` : `${text.length} characters`}\n`
+ + " Choose the request duration from this estimate, the intended performance, and the selected model's supported values.\n");
+}
+
+export const cliCommandModules = [{
+ format: "hypit.cli-command@1",
+ id: "@hypit/speech-estimate",
+ commands: ["estimate"],
+ writeRootHelp(io) { io.write("\nSpeech estimation\n estimate\n hypit estimate --help for inputs and delivery options\n"); },
+ writeHelp(_argv, io) { writeEstimateHelp(io); },
+ async run(argv, io, context) { await runEstimateCli(argv, io, context); },
+}] as const satisfies readonly CliCommandModule[];
diff --git a/packages/estimate/src/index.ts b/packages/speech-estimate/src/index.ts
similarity index 78%
rename from packages/estimate/src/index.ts
rename to packages/speech-estimate/src/index.ts
index 28bb7394..4320ec91 100644
--- a/packages/estimate/src/index.ts
+++ b/packages/speech-estimate/src/index.ts
@@ -1,4 +1,3 @@
-export { estimateManifest, estimateModuleRef, estimateTypes, speechEstimatePolicySchema } from "./manifest.js";
export {
speechEstimatePolicyFromAttributes,
speechEstimatePolicyFromRecipe,
diff --git a/packages/estimate/src/policy.ts b/packages/speech-estimate/src/policy.ts
similarity index 96%
rename from packages/estimate/src/policy.ts
rename to packages/speech-estimate/src/policy.ts
index 1c2e57ed..6f5030ab 100644
--- a/packages/estimate/src/policy.ts
+++ b/packages/speech-estimate/src/policy.ts
@@ -1,4 +1,4 @@
-import type { SvsRecipe } from "@hypit/svs";
+import type { Recipe } from "@hypit/hypit/recipe";
import { sealSpeechEstimatePolicy } from "./program.js";
import type {
@@ -52,9 +52,9 @@ function policyFrom(
: sealSpeechEstimatePolicy({ ...common, rate: finite("rate") });
}
-/** One reusable estimate policy written as an SVS Recipe; it configures a measurement, nothing executable. */
+/** One reusable estimate policy written as an SVS Recipe; it configures an estimate, nothing executable. */
export function speechEstimatePolicyFromRecipe(
- recipe: SvsRecipe,
+ recipe: Recipe,
subject = `SVS Recipe ${recipe.path}`,
): SpeechEstimatePolicy {
return policyFrom(recipe.properties, subject);
diff --git a/packages/estimate/src/program.ts b/packages/speech-estimate/src/program.ts
similarity index 94%
rename from packages/estimate/src/program.ts
rename to packages/speech-estimate/src/program.ts
index de58d6d0..a762393e 100644
--- a/packages/estimate/src/program.ts
+++ b/packages/speech-estimate/src/program.ts
@@ -1,6 +1,4 @@
-import type { Text } from "@hypit/text";
-import { assertSpeechDurationIdentity, sealSpeechDuration } from "@hypit/speech";
-import type { SpeechDuration } from "@hypit/speech";
+import type { Text } from "@hypit/hypit/text";
import { dictionary as cmuPronouncingDictionary } from "cmu-pronouncing-dictionary";
import type {
@@ -173,7 +171,7 @@ function rounded(value: number, mode: SpeechEstimatePolicy["rounding"]): number
export function estimateSpeechDuration(
text: Text,
policy: SpeechEstimatePolicy,
-): SpeechDuration {
+): number {
assertSpeechText(text);
assertSpeechEstimatePolicy(policy);
const language = policy.language === "auto" ? detectSpeechEstimateLanguage(text.value) : policy.language;
@@ -181,10 +179,9 @@ export function estimateSpeechDuration(
if (units < 1) throw new Error("Speech Text contains no countable speech units");
const raw = units / resolveSpeechEstimateRate(policy, language) + (policy.paddingSec ?? 0);
const durationSec = rounded(raw, policy.rounding);
- if (durationSec === 0) throw new Error("Speech estimate rounds to zero seconds; use rounding none or ceil.");
- const duration = sealSpeechDuration(durationSec);
- assertSpeechDurationIdentity(duration);
- return duration;
+ if (durationSec <= 0) throw new Error("Speech estimate rounds to zero seconds; use rounding none or ceil.");
+ if (!Number.isFinite(durationSec)) throw new Error("Speech estimate is outside finite numeric range.");
+ return durationSec;
}
export function resolveSpeechEstimateLanguage(
diff --git a/packages/estimate/src/types.ts b/packages/speech-estimate/src/types.ts
similarity index 100%
rename from packages/estimate/src/types.ts
rename to packages/speech-estimate/src/types.ts
diff --git a/packages/speech-estimate/test/cli.test.ts b/packages/speech-estimate/test/cli.test.ts
new file mode 100644
index 00000000..55654610
--- /dev/null
+++ b/packages/speech-estimate/test/cli.test.ts
@@ -0,0 +1,29 @@
+import assert from "node:assert/strict";
+import { mkdtemp, rm } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import test from "node:test";
+
+import { runEstimateCli } from "../src/cli.js";
+
+test("estimate presents the deterministic speech estimate without opening a Runtime", async () => {
+ const root = await mkdtemp(join(tmpdir(), "hypit-estimate-"));
+ let output = "";
+ try {
+ await runEstimateCli([
+ "estimate", "--text", "Video editing begins with meaning, not a pile of clips on a timeline.",
+ "--language", "en", "--pace", "normal", "--rounding", "round", "--json",
+ ], { write: (text) => { output += text; } }, {
+ cwd: root,
+ distribution: {} as never,
+ resolveProjectRoot: async () => { throw new Error("inline estimation does not resolve a project"); },
+ });
+ const view = JSON.parse(output) as { readonly format: string; readonly seconds: number; readonly units: number; readonly rate: number };
+ assert.equal(view.format, "hypit.speech-estimate@1");
+ assert.equal(view.units, 20);
+ assert.equal(view.seconds, 4);
+ assert.equal(view.rate, 4.6);
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
diff --git a/packages/estimate/test/estimate.test.ts b/packages/speech-estimate/test/estimate.test.ts
similarity index 90%
rename from packages/estimate/test/estimate.test.ts
rename to packages/speech-estimate/test/estimate.test.ts
index a8d39b9b..dba3e849 100644
--- a/packages/estimate/test/estimate.test.ts
+++ b/packages/speech-estimate/test/estimate.test.ts
@@ -9,7 +9,7 @@ import {
sealSpeechEstimatePolicy,
speechEstimatePolicyFromAttributes,
speechEstimatePolicyFromRecipe,
-} from "@hypit/estimate";
+} from "@hypit/speech-estimate";
const normal = sealSpeechEstimatePolicy({
language: "en",
@@ -142,3 +142,11 @@ test("Chinese mixed-language punctuation preserves English word boundaries", ()
language: "zh", rate: 5, rounding: "none", paddingSec: 0.5,
}), 2.5);
});
+
+test("Japanese and Spanish expose their documented writing-based approximations", () => {
+ assert.equal(detectSpeechEstimateLanguage("こんにちは世界"), "ja");
+ assert.equal(countSpeechEstimateUnits("こんにちは世界", "ja"), 7);
+ assert.equal(countSpeechEstimateUnits("今日は video です", "ja"), 8);
+ assert.equal(detectSpeechEstimateLanguage("La edición de video comienza con significado."), "es");
+ assert.equal(countSpeechEstimateUnits("La edición de video comienza con significado.", "es"), 17);
+});
diff --git a/packages/studio-adapter/package.json b/packages/studio-adapter/package.json
deleted file mode 100644
index 0241ab5f..00000000
--- a/packages/studio-adapter/package.json
+++ /dev/null
@@ -1,14 +0,0 @@
-{
- "name": "@hypit/studio-adapter",
- "version": "0.0.0-dev",
- "license": "SEE LICENSE IN LICENSE",
- "private": true,
- "type": "module",
- "exports": {
- ".": "./src/index.ts"
- },
- "dependencies": {
- "@hypit/host": "workspace:*",
- "@hypit/protocol": "workspace:*"
- }
-}
diff --git a/packages/studio-adapter/README.md b/packages/studio-companion/README.md
similarity index 91%
rename from packages/studio-adapter/README.md
rename to packages/studio-companion/README.md
index 82c94ef4..5178088e 100644
--- a/packages/studio-adapter/README.md
+++ b/packages/studio-companion/README.md
@@ -1,12 +1,13 @@
-# `@hypit/hypit/studio-adapter`
+# `@hypit/studio-companion`
The stable companion-package ABI understood by Hypit Studio. It carries only
presentation, lineage, inspector and interaction DTOs plus helpers that do not
encode the official video UI policy. Domain computation and manifests do not depend on it;
package activation can combine domain facets with a separate Companion implementation.
-External packages use the public imports below with `@hypit/hypit` as a development dependency, then ship
-compiled JavaScript. The active Distribution supplies these APIs when Studio loads the component.
+External packages peer-depend on both `@hypit/hypit` and `@hypit/studio-companion`, use the public imports
+below, then ship compiled JavaScript. The active Distribution supplies both packages when Studio loads the
+component.
## A minimal project Track Companion
@@ -16,7 +17,7 @@ adding package-specific presentation and one Inspector field:
```ts
import { compositionTypes } from "@hypit/hypit/composition";
-import type { StudioTrackCompanion } from "@hypit/hypit/studio-adapter";
+import type { StudioTrackCompanion } from "@hypit/studio-companion";
export const companions: readonly StudioTrackCompanion[] = [{
id: "score-strip",
@@ -68,15 +69,15 @@ Merge the facet into the package's existing activation. In this example `authorC
exports its existing modules, deterministic component and Markup facets:
```ts
-import { createStudioTrackCompanionHostFacet } from "@hypit/hypit/studio-adapter";
+import { createStudioTrackCompanionFacet } from "@hypit/studio-companion";
import authorContribution from "./author-activation.js";
import { companions } from "./studio.js";
export default {
...authorContribution,
- hostFacets: [
- ...(authorContribution.hostFacets ?? []),
- createStudioTrackCompanionHostFacet(companions),
+ facets: [
+ ...(authorContribution.facets ?? []),
+ createStudioTrackCompanionFacet(companions),
],
};
```
@@ -123,17 +124,19 @@ a short child interval. Expose that distinction rather than making a long rectan
entrance animation. Qualify child ids across Track instances; never use an array index as authored
identity merely because it currently lines up.
-Read [Ranking's Companion](../ranking-studio/src/index.ts) for board/reveal lanes,
-[Caption Fine's](../caption-fine-studio/src/index.ts) for Cue text and Style selection, and
-[Visual Track's](../visual-track-studio/src/index.ts) for material and occupancy.
+Read [Ranking's Companion](https://github.com/hypit-ai/hypit/blob/main/packages/ranking/src/studio.ts) for board/reveal lanes,
+Caption Fine's `@hypit/caption-fine/studio` facet for Cue text and Style selection, and
+[Visual Track's](../visual-track/src/studio.ts) for material and occupancy.
## Preserve executed temporal lineage
`StudioTrackCompanionContext.temporalBindings` exposes the executed Instant/Window records in the selected
Track closure, including projection expressions, source identity and direct consumer inputs.
`temporalLineageFor()` joins a domain entity to those edges through the identity of a value consumed
-beside the projection; it does not inspect author attribute names. No match is read-only, one match
-is used, and several matches are an error rather than a first-result guess. The generic terminal
+beside the projection. No match is read-only, one match is used, and several matches are an error rather
+than a first-result guess. Endpoint authority is already part of that executed lineage: an author syntax
+may declare a parameter inverse on the Spec it creates, while a domain projector declares its own source
+and boundary. Common Studio never maps attribute names such as `from`, `for`, `until` or `during`. The generic terminal
fallback tries only the terminal object's exact `subjectId`/`authoredId`; renderer ids and marker ids
are not alternate guesses.
@@ -149,12 +152,12 @@ was omitted, a Companion may name the exact domain Spec Type whose public `id` o
Studio then recovers the Source range from the typed observed Record, without ordinal matching.
A project companion contributes package-local Track Companion ids through
-`createStudioTrackCompanionHostFacet()`. The Host qualifies them with the selected
+`createStudioTrackCompanionFacet()`. The Host qualifies them with the selected
physical package identity, so executable package code cannot impersonate an
official Companion. The Source closure selects project packages; Studio does not
scan `node_modules` for plugins or use Runtime Profiles to select Companions.
-The same host facet can contribute Film, temporal-domain and parameter Companions. A Film Companion
+The same Studio Companion facet can contribute Film, temporal-domain and parameter Companions. A Film Companion
identifies its Timeline and terminal Tracks. The Timeline supplies only the program range. A
temporal-domain Companion owns source observation, requests the domain values it needs, projects
generic anchors plus point/span items onto that Timeline, and receives inverse point/span edits.
@@ -196,7 +199,7 @@ preview hints. Text may be multiline; colors may offer package-chosen swatches.
[Inspector presentation and conversion](../studio/INSPECTOR.md) for examples and ownership.
Structured controls keep a local draft and commit one complete canonical value.
-Their codec is the author language (`@hypit/svs` for Recipe values), not a
+Their codec is the author language (`@hypit/recipe` for Recipe values), not a
Companion callback. Companions cannot inject DOM, CSS, parsing code or filesystem
mutations. Official companions also use explicit field tables: an undeclared
new domain property fails Companion loading instead of inheriting UI from its name.
@@ -268,7 +271,7 @@ bindings: [{ name: "style", companion: true }]
```
The package that authors the referenced object contributes through
-`createStudioCompanionHostFacet({ parameters: [...] })`:
+`createStudioCompanionFacet({ parameters: [...] })`:
```ts
{
diff --git a/packages/studio-companion/package.json b/packages/studio-companion/package.json
new file mode 100644
index 00000000..e56aff22
--- /dev/null
+++ b/packages/studio-companion/package.json
@@ -0,0 +1,20 @@
+{
+ "name": "@hypit/studio-companion",
+ "version": "0.1.0",
+ "license": "SEE LICENSE IN LICENSE",
+ "private": true,
+ "type": "module",
+ "exports": {
+ ".": "./src/index.ts"
+ },
+ "files": [
+ "dist",
+ "README.md"
+ ],
+ "peerDependencies": {
+ "@hypit/hypit": "workspace:^"
+ },
+ "devDependencies": {
+ "@hypit/hypit": "workspace:*"
+ }
+}
diff --git a/packages/studio-adapter/src/index.ts b/packages/studio-companion/src/index.ts
similarity index 91%
rename from packages/studio-adapter/src/index.ts
rename to packages/studio-companion/src/index.ts
index cdf7f8d5..468acbad 100644
--- a/packages/studio-adapter/src/index.ts
+++ b/packages/studio-companion/src/index.ts
@@ -1,8 +1,8 @@
-import type { HostFacet } from "@hypit/host";
-import { sameType } from "@hypit/protocol";
-import type { CanonicalValue, ModuleRef, TypeRef, ValueSchema } from "@hypit/protocol";
+import type { Facet } from "@hypit/hypit/facet";
+import { sameType } from "@hypit/hypit/protocol";
+import type { CanonicalValue, ModuleRef, TypeRef, ValueSchema } from "@hypit/hypit/protocol";
-export const studioCompanionHostAbi = "hypit.studio-adapter@1";
+export const studioCompanionFacetAbi = "hypit.studio-companion@1";
/** UTF-16 offsets into the exact author source. */
export type Range = { readonly start: number; readonly end: number };
@@ -81,17 +81,8 @@ export type StudioTemporalWindowProjection = {
export type StudioTemporalProjection = StudioTemporalInstantProjection | StudioTemporalWindowProjection;
-export type StudioTemporalPhase = {
- readonly id: string;
- readonly label: string;
- readonly role: "preferred" | "active" | "settled" | "enter" | "body" | "exit";
- readonly startFrame: number;
- readonly endFrameExclusive: number;
-};
-
export type StudioTemporalLineage = {
readonly projection: StudioTemporalProjection;
- readonly phases: readonly StudioTemporalPhase[];
};
export type StudioTemporalConsumerInput = {
@@ -551,7 +542,7 @@ export type StudioEntityDraft = {
readonly elementRange?: Range;
readonly markerId?: string;
readonly presentId?: string;
- /** Rendered parts belonging to this entity, including phases beyond its editable timeline interval. */
+ /** Rendered parts belonging to this entity. */
readonly renderIds?: readonly string[];
/** Resolved author references that differ per derived entity, such as one Cue's actual Style. */
readonly parameterReferences?: Readonly<Record<string, string>>;
@@ -706,26 +697,26 @@ export type StudioTemporalDomainCompanion = {
}) => string;
};
-export type StudioCompanionHostFacet = HostFacet & {
- readonly abi: typeof studioCompanionHostAbi;
+export type StudioCompanionFacet = Facet & {
+ readonly abi: typeof studioCompanionFacetAbi;
readonly implementation: StudioCompanionContribution;
};
-export function createStudioTrackCompanionHostFacet(tracks: readonly StudioTrackCompanion[]): StudioCompanionHostFacet {
+export function createStudioTrackCompanionFacet(tracks: readonly StudioTrackCompanion[]): StudioCompanionFacet {
return {
- abi: studioCompanionHostAbi,
+ abi: studioCompanionFacetAbi,
implementation: { format: "hypit.studio-companions@1", tracks },
};
}
-export function createStudioCompanionHostFacet(input: {
+export function createStudioCompanionFacet(input: {
readonly tracks?: readonly StudioTrackCompanion[];
readonly films?: readonly StudioFilmCompanion[];
readonly temporalDomains?: readonly StudioTemporalDomainCompanion[];
readonly parameters?: readonly StudioParameterCompanion[];
-}): StudioCompanionHostFacet {
+}): StudioCompanionFacet {
return {
- abi: studioCompanionHostAbi,
+ abi: studioCompanionFacetAbi,
implementation: {
format: "hypit.studio-companions@1",
tracks: input.tracks ?? [],
@@ -752,7 +743,7 @@ function qualify(owner: string, local: string, subject: string): string {
export function studioContributionFromPackage(
owner: string,
- facets: readonly HostFacet[],
+ facets: readonly Facet[],
): StudioPackageContribution {
if (owner.length === 0 || owner.includes("#")) throw new Error(`Invalid Studio companion package identity: ${owner}`);
const tracks: StudioTrackCompanion[] = [];
@@ -760,7 +751,7 @@ export function studioContributionFromPackage(
const temporalDomains: StudioTemporalDomainCompanion[] = [];
const parameters: StudioParameterCompanion[] = [];
for (const facet of facets) {
- if (facet.abi !== studioCompanionHostAbi) continue;
+ if (facet.abi !== studioCompanionFacetAbi) continue;
const contribution = facet.implementation as Partial<StudioCompanionContribution>;
if (contribution.format !== "hypit.studio-companions@1" || !Array.isArray(contribution.tracks)) {
throw new Error(`Studio companion facet from ${owner} has an invalid contribution`);
@@ -790,7 +781,7 @@ export function studioContributionFromPackage(
*/
export function studioTrackCompanionsFromPackage(
owner: string,
- facets: readonly HostFacet[],
+ facets: readonly Facet[],
): readonly StudioTrackCompanion[] {
return studioContributionFromPackage(owner, facets).tracks;
}
@@ -911,52 +902,7 @@ export function temporalLineageFor(
throw new Error(`Studio Temporal lineage is ambiguous for ${subjectId}${input === undefined ? "" : ` at ${input}`}.`);
}
const binding = found[0];
- const authored = context.placement?.id === subjectId
- ? context.placement
- : context.placement?.children.find((child) => child.id === subjectId);
- const authority = (
- endpoint: StudioTemporalInstantProjection,
- role: "instant" | "start" | "end",
- ): StudioTemporalInstantProjection => {
- if (authored === undefined) return { ...endpoint, authority: { kind: "fixed" } };
- const attributes = authored.attributes;
- const references = authored.referenceAttributes;
- const parameter = (binding: string, relation: "direct" | "after-start" | "before-end" = "direct") =>
- ({ kind: "parameter" as const, binding, relation });
- const domain = endpoint.authority.kind === "domain" ? endpoint.authority : undefined;
- if (role === "instant") {
- if (attributes.instant !== undefined) return { ...endpoint, authority: parameter("instant") };
- if (references.at !== undefined && domain !== undefined && domain.source.kind !== "segment") return endpoint;
- if (attributes.at !== undefined) return { ...endpoint, authority: parameter("at") };
- return { ...endpoint, authority: { kind: "fixed" } };
- }
- if (attributes.start !== undefined || attributes.end !== undefined) {
- return { ...endpoint, authority: parameter(role) };
- }
- if (attributes.for !== undefined && (attributes.at !== undefined || references.at !== undefined)) {
- if (role === "end") return { ...endpoint, authority: parameter("for", "after-start") };
- if (references.at !== undefined && domain !== undefined) return endpoint;
- return { ...endpoint, authority: parameter("at") };
- }
- if (attributes.for !== undefined && (attributes.until !== undefined || references.until !== undefined)) {
- if (role === "start") return { ...endpoint, authority: parameter("for", "before-end") };
- if (references.until !== undefined && domain !== undefined) return endpoint;
- return { ...endpoint, authority: parameter("until") };
- }
- if (references.during !== undefined && domain?.source.kind === "selection") return endpoint;
- return { ...endpoint, authority: { kind: "fixed" } };
- };
- const projection = binding?.projection.kind === "instant"
- ? authority(binding.projection, "instant")
- : binding === undefined ? undefined : {
- ...binding.projection,
- start: authority(binding.projection.start, "start"),
- end: authority(binding.projection.end, "end"),
- };
- return binding === undefined ? undefined : {
- projection: projection!,
- phases: [],
- };
+ return binding === undefined ? undefined : { projection: binding.projection };
}
/** Unique domain-owned author identity carried by one projection, when there is one. */
diff --git a/packages/studio-adapter/test/identity.test.ts b/packages/studio-companion/test/identity.test.ts
similarity index 100%
rename from packages/studio-adapter/test/identity.test.ts
rename to packages/studio-companion/test/identity.test.ts
diff --git a/packages/studio/INSPECTOR.md b/packages/studio/INSPECTOR.md
index efd600a4..fe9d3e31 100644
--- a/packages/studio/INSPECTOR.md
+++ b/packages/studio/INSPECTOR.md
@@ -72,7 +72,7 @@ pixels or seconds into frames. `scale` is positive; displayed value = authored m
Limits and step in `number` refer to displayed values. A number schema's limits and integer setting
also inform the input when no presentation override is provided. Empty input is not silently zero.
-SVML strings escape attribute delimiters and entity characters. SVS values use `formatSvsValue`.
+SVML strings escape attribute delimiters and entity characters. SVS values use `formatRecipeValue`.
Neither the UI nor a Companion writes source text through an arbitrary callback. Timeline temporal
gestures are separate from Inspector field conversion; see the temporal author forms for their
domain-anchor and local-offset editing behavior.
@@ -95,11 +95,11 @@ the selected value, not its display label, is validated and written. Preview hin
Options remain named keyboard-operable choices. Font hints use a family available to the Studio
document; declaring a hint does not install or load a font or change the composition's font bytes.
-The optional `@hypit/fonts-open/studio` helper owns its catalog labels and descriptions. Caption,
-Typography and Ranking Companions use it to reach a Style's referenced font and edit its `family`
-attribute. It appears for an actual writable family attribute; a `media:Font` file has no such
-attribute. The family still has to supply the authored weight and style. A local font keeps its exact
-file binding. Changing a shared font changes every consumer; this is visible Source reuse.
+Font consumers opt into the referenced font producer's own Parameter Companion. The
+`@hypit/fontsource` Companion exposes the installed package as read-only context and edits only the
+weight and style supported by that package; it does not synthesize a global family dropdown. A
+`media:Font` file has no package Companion. Changing a shared font still changes every consumer;
+this is visible Source reuse.
Nested `referenced` declarations follow explicit author references, such as Style → Font → family.
They neither scan for candidates nor replace whole-value references with strings. Project components
@@ -107,7 +107,7 @@ can declare their own option values and binding paths through the same ABI.
## Implementation owners
-- `studio-adapter` owns the data-only declarations and snapshot types.
+- `studio-companion` owns the data-only declarations and snapshot types.
- Component Companions own grouping, choices, units and references to writable author facts.
- Studio resolves endpoints, renders controls, converts display values and commits source edits.
- SVML/SVS and the component's ordinary compilation remain the authority for valid authored work.
diff --git a/packages/studio/README.md b/packages/studio/README.md
index 91645ba4..1f133f95 100644
--- a/packages/studio/README.md
+++ b/packages/studio/README.md
@@ -1,7 +1,7 @@
# Hypit Studio
For direct picture inspection, `hypit snapshot --studio <studio-url>` reads the current compiled
-`HyperframesDocument` from `GET /__studio/document` and its existing `/__studio/material/<resource>`
+`HtmlProgram` from `GET /__studio/document` and its existing `/__studio/material/<resource>`
resources. `GET /__studio/visual.html` exposes the same materialized picture without the interactive
Studio playback shim or audio. Both representations come from the same compilation as the displayed
preview. The snapshot invocation uses the selected Runtime Profile's frame Provider and creates no
@@ -11,7 +11,10 @@ reports its error instead of returning the previous picture as current.
The single official Web Studio for SVML. It opens an explicit Run Source,
traces its Film or Render target back to the semantic and visual projections
Studio can edit, runs deterministic Producers and explicitly permitted transient Needs, and composites the
-resulting Tracks with HyperFrames.
+resulting Tracks with HTML renderer.
+
+`@hypit/studio/cli` exports Studio's `hypit.cli-command@1` contribution. The root CLI Host selects it
+through the installed Distribution manifest; Studio does not own or wrap the Hypit executable.
```bash
cd /path/to/external-video-project
@@ -20,11 +23,11 @@ hypit studio --run build.svrun
When `--runtime` is omitted, Studio reads the resolved project's `.hypit/runtime`
selection made by `hypit runtime use`. It does not search parent projects for a
-Profile. `--workspace` explicitly selects the project boundary; `--package-root`
+Profile. `--project` explicitly selects the project boundary; `--package-root`
overrides the author package resolution root when those locations intentionally differ.
Startup prints the project, Run, Profile and whether the Profile came from the command argument or
the project's selection file. Relative command-line paths start at the invoking directory;
-`--workspace` selects the project without rebasing `--run` or `--runtime`.
+`--project` selects the project without rebasing `--run` or `--runtime`.
The upper-left library is intentionally not a filesystem browser:
- Source is the exact Run + Author closure and writes back only the selected file;
@@ -189,7 +192,7 @@ An Instant reference expression edits only its offset; a bare reference has an i
frame delta. Edited clock values and offsets are written in frames at the current Timeline rate.
The domain-item Inspector exposes exact anchor identities and, where a declared handle supports it,
offers choices among coincident anchors. Their meaning and writeback remain package-owned.
-See [temporal author forms](../temporal-markup/EDITING.md) for the complete behavior.
+See [temporal author forms](../temporal/EDITING.md) for the complete behavior.
Tasks and Artifacts are inspection surfaces; selecting an Artifact does not write a
Run Candidate. Use `build-record`/`satisfy` in the Run for explicit Output reuse.
@@ -208,10 +211,10 @@ Studio profile, package scan or replacement map.
Project packages live at `<project>/packages/<package-basename>/`. Neither the
project nor its packages are added to the Hypit Distribution or contributor workspace.
-The Host resolves selected project packages from the project first and official
-`@hypit/*` imports from the read-only tool Distribution. The `@hypit/*`
-namespace is Distribution-owned and cannot be shadowed by a project install.
-External Companions compile against `@hypit/hypit/studio-adapter` and the other public `@hypit/hypit/*`
+The Host protects exact packages physically embedded in the read-only tool Distribution.
+Other selected packages, including independently released official `@hypit/*` extensions,
+resolve from the project first and use the Distribution installation only as a fallback.
+External Companions compile against `@hypit/studio-companion` and the other public `@hypit/hypit/*`
subpaths, with `@hypit/hypit` as a development dependency. The active Distribution supplies those APIs
at runtime. Ship the Companion's compiled JavaScript with its component package.
@@ -257,12 +260,12 @@ ordinary Run Candidates selected with `satisfy`.
Studio and an encoded review use the same ordinary Run. Studio evaluates its
transient display closure in the browser; building that Run evaluates the
-full target closure and sends the resulting HyperFrames document to the chosen
+full target closure and sends the resulting HTML renderer document to the chosen
render Endpoint. A separate review Run is useful only when the author wants a
different Candidate selection. Its path and filename carry no execution
semantics.
-Read [`@hypit/studio-adapter`](../studio-adapter/README.md) for the Companion ABI,
+Read [`@hypit/studio-companion`](../studio-companion/README.md) for the Companion ABI,
project activation example, value projection and Inspector declarations.
## Composition audio preview
diff --git a/packages/studio/package.json b/packages/studio/package.json
index c872be42..12deb016 100644
--- a/packages/studio/package.json
+++ b/packages/studio/package.json
@@ -1,49 +1,46 @@
{
"name": "@hypit/studio",
- "version": "0.0.1",
+ "version": "0.1.0",
"private": true,
"type": "module",
"exports": {
- "./start": "./start.ts",
- "./src/*": "./src/*"
+ "./cli": "./src/cli.ts",
+ "./start": "./src/start.ts"
},
+ "files": [
+ "dist",
+ "src",
+ "index.html",
+ "locales",
+ "README.md",
+ "INSPECTOR.md",
+ "LOCALIZATION.md"
+ ],
"dependencies": {
- "@hypit/audio-track-studio": "workspace:*",
- "@hypit/build-result": "workspace:*",
- "@hypit/caption-fine-studio": "workspace:*",
+ "@hypit/media-operations": "workspace:^",
+ "@hypit/media-local": "workspace:^",
+ "@hypit/studio-companion": "workspace:^",
+ "vite": "8.2.2"
+ },
+ "peerDependencies": {
+ "@hypit/hypit": "workspace:^"
+ },
+ "devDependencies": {
+ "@hypit/audio-track": "workspace:*",
+ "@hypit/caption": "workspace:*",
"@hypit/cli": "workspace:*",
- "@hypit/comment-sticker-studio": "workspace:*",
- "@hypit/compiler-node": "workspace:*",
- "@hypit/component-kit": "workspace:*",
+ "@hypit/compiler": "workspace:*",
"@hypit/composition": "workspace:*",
- "@hypit/core": "workspace:*",
- "@hypit/depth-stack-studio": "workspace:*",
- "@hypit/driver-node": "workspace:*",
- "@hypit/elaborator": "workspace:*",
- "@hypit/film-studio": "workspace:*",
- "@hypit/hyperframes": "workspace:*",
+ "@hypit/html-program": "workspace:*",
+ "@hypit/hypit": "workspace:*",
"@hypit/markup": "workspace:*",
- "@hypit/media-pipeline": "workspace:*",
- "@hypit/visual-track-studio": "workspace:*",
- "@hypit/package-loader-node": "workspace:*",
- "@hypit/project-context-node": "workspace:*",
"@hypit/protocol": "workspace:*",
- "@hypit/ranking-studio": "workspace:*",
- "@hypit/run": "workspace:*",
- "@hypit/runtime": "workspace:*",
- "@hypit/runtime-host-node": "workspace:*",
- "@hypit/screen-overlay-studio": "workspace:*",
- "@hypit/script-studio": "workspace:*",
- "@hypit/speech": "workspace:*",
- "@hypit/studio-adapter": "workspace:*",
- "@hypit/svs": "workspace:*",
+ "@hypit/result": "workspace:*",
+ "@hypit/script": "workspace:*",
"@hypit/temporal": "workspace:*",
"@hypit/timeline": "workspace:*",
- "@hypit/text-fine-studio": "workspace:*",
- "@hypit/validation": "workspace:*",
- "@hypit/video-cli": "workspace:*",
- "@hypit/workspace": "workspace:*",
- "@hypit/workspace-fs-node": "workspace:*",
- "vite": "8.2.2"
+ "@hypit/video": "workspace:*",
+ "@hypit/visual-track": "workspace:*",
+ "sharp": "0.35.4"
}
}
diff --git a/packages/studio/src/build-library.ts b/packages/studio/src/build-library.ts
index de0222cf..c273b0c2 100644
--- a/packages/studio/src/build-library.ts
+++ b/packages/studio/src/build-library.ts
@@ -1,42 +1,41 @@
-import { fileReferenceIdentity, locateRepositoryBuildResultOutput } from "@hypit/build-result";
+import { fileReferenceIdentity, locateRepositoryBuildResultOutput } from "@hypit/hypit/result/node";
import { isAbsolute, relative, resolve, sep } from "node:path";
-import { buildIdCreatedAt } from "@hypit/protocol";
-import type { BuildView, NodeRuntimeHost, RuntimeHostTransientExecution } from "@hypit/runtime-host-node";
-import type { StoredValue, TypeRef } from "@hypit/protocol";
+import { buildIdCreatedAt } from "@hypit/hypit/protocol";
+import type { StoredValue, TypeRef } from "@hypit/hypit/protocol";
import type {
BuildResultFileRange,
BuildResultManifest,
BuildResultRepository,
FinishedBuildResultManifest,
-} from "@hypit/build-result";
+} from "@hypit/hypit/result/node";
-import { resolveBuildResultValue } from "@hypit/cli";
-import { videoCliDistribution } from "@hypit/video-cli";
+import { resolveBuildResultValue } from "@hypit/hypit/cli";
+import type { CliBuildView as BuildView, CliDistribution, CliRuntimeHost, CliTransientExecution } from "@hypit/hypit/cli";
import type { StudioArtifactView, StudioLibraryRequest, StudioLibraryView, StudioTaskView } from "./shared.js";
import { mergeStudioArtifacts } from "./library-media.js";
-type RuntimeControl = Awaited<ReturnType<NodeRuntimeHost["openControl"]>>;
+type RuntimeControl = Awaited<ReturnType<CliRuntimeHost["openControl"]>>;
export type StudioBuildLibrary = {
readonly profile?: string;
readonly runtime?: Pick<RuntimeControl, "activity">;
/** Runtime-owned, disposable execution for the current authoring session. */
- readonly transientExecution?: RuntimeHostTransientExecution;
+ readonly transientExecution?: CliTransientExecution;
readonly library: (request: StudioLibraryRequest) => Promise<StudioLibraryView>;
readonly renameArtifact: (build: string, output: string, displayName: string | null) => Promise<string | undefined>;
readonly locateHistoricalOutput: (
build: string,
output: string,
- ) => Promise<import("@hypit/build-result").RepositoryBuildResultOutputLocation | undefined>;
+ ) => Promise<import("@hypit/hypit/result").RepositoryBuildResultOutputLocation | undefined>;
readonly resolveHistoricalOutput: (
build: string,
output: string,
) => Promise<{
readonly type: TypeRef;
readonly value: StoredValue;
- readonly attachments?: readonly import("@hypit/workspace").ArtifactAttachment[];
+ readonly attachments?: readonly import("@hypit/hypit/workspace").BlobAttachment[];
} | undefined>;
readonly openArtifact: (
build: string,
@@ -116,8 +115,8 @@ function resultTaskView(root: string, result: FinishedBuildResultManifest): Stud
ongoing: false,
status: result.outcome,
...(result.failure === undefined ? {} : { detail: result.failure }),
- source: presentedPath(root, result.source.path),
- ...(result.run === undefined ? {} : { run: presentedPath(root, result.run.path) }),
+ source: presentedPath(root, result.source.id),
+ ...(result.run === undefined ? {} : { run: presentedPath(root, result.run.id) }),
targets: result.targets,
operations: [],
};
@@ -147,8 +146,8 @@ async function artifactsForResults(
: await repository.resolve(manifest.id, output);
if (resolved === undefined || (resolved.value.kind !== "build-file" && resolved.value.kind !== "external-file")) return [];
const file = resolved.value;
- const source = presentedPath(root, manifest.source.path);
- const run = manifest.run === undefined ? undefined : presentedPath(root, manifest.run.path);
+ const source = presentedPath(root, manifest.source.id);
+ const run = manifest.run === undefined ? undefined : presentedPath(root, manifest.run.id);
return [{
id: fileReferenceIdentity(resolved.build, file),
build: manifest.id,
@@ -179,23 +178,32 @@ export async function readStudioLibrary(input: StudioLibraryRequest & {
readonly runtime?: Pick<RuntimeControl, "activity">;
readonly results: BuildResultRepository;
}): Promise<StudioLibraryView> {
- const matches = (item: { readonly id: string; readonly source: { readonly path: string }; readonly run?: { readonly path: string } }) =>
- (isWithin(input.workspaceRoot, item.run?.path ?? item.source.path) || isWithin(input.workspaceRoot, item.source.path))
+ const matches = (item: { readonly id: string; readonly source: string; readonly run?: string }) =>
+ (isWithin(input.workspaceRoot, item.run ?? item.source) || isWithin(input.workspaceRoot, item.source))
&& (input.build === undefined || item.id === input.build)
&& (input.run === undefined || (item.run !== undefined
- && projectPath(input.workspaceRoot, item.run.path) === projectPath(input.workspaceRoot, input.run)));
+ && projectPath(input.workspaceRoot, item.run) === projectPath(input.workspaceRoot, input.run)));
// Read activity before Results so a Build that finishes during this query is still represented.
const active = input.runtime === undefined || input.before !== undefined
? [] : (await input.runtime.activity()).builds;
- const views = active.filter((view) => view.source !== undefined && matches({ ...view, source: view.source }));
+ const views = active.filter((view) => view.source !== undefined && matches({
+ id: view.id,
+ source: view.source.path,
+ ...(view.run === undefined ? {} : { run: view.run.path }),
+ }));
let page = input.build === undefined
? await input.results.browse({ limit: 25, ...(input.before === undefined ? {} : { before: input.before }) })
: { results: [await input.results.read(input.build)].filter((item): item is BuildResultManifest => item !== undefined) };
- const manifests = page.results.filter(matches);
+ const manifests = page.results.filter((manifest) => matches({
+ id: manifest.id,
+ source: manifest.source.id,
+ ...(manifest.run === undefined ? {} : { run: manifest.run.id }),
+ }));
const resultsByBuild = new Map(manifests.map((manifest) => [manifest.id, manifest]));
await Promise.all(views.filter((view) => !resultsByBuild.has(view.id)).map(async (view) => {
const result = await input.results.read(view.id);
- if (result !== undefined && matches(result)) resultsByBuild.set(view.id, result);
+ if (result !== undefined && matches({ id: result.id, source: result.source.id,
+ ...(result.run === undefined ? {} : { run: result.run.id }) })) resultsByBuild.set(view.id, result);
}));
let artifacts: readonly StudioArtifactView[] = [];
if (input.section === "artifacts") {
@@ -207,7 +215,11 @@ export async function readStudioLibrary(input: StudioLibraryRequest & {
page = await input.results.browse({ limit: 25, before: cursor });
if ("next" in page && page.next === cursor) throw new Error("Result pagination did not advance");
artifacts = mergeStudioArtifacts([...artifacts,
- ...await artifactsForResults(input.workspaceRoot, input.results, page.results.filter(matches), input.media)]);
+ ...await artifactsForResults(input.workspaceRoot, input.results, page.results.filter((manifest) => matches({
+ id: manifest.id,
+ source: manifest.source.id,
+ ...(manifest.run === undefined ? {} : { run: manifest.run.id }),
+ })), input.media)]);
}
}
return {
@@ -228,6 +240,7 @@ export async function readStudioLibrary(input: StudioLibraryRequest & {
/** Open a Runtime profile read-only; Studio never creates or mutates a Build. */
export async function openStudioBuildLibrary(
+ distribution: CliDistribution,
profile: string | undefined,
packageRoot: string,
workspaceRoot: string,
@@ -236,16 +249,16 @@ export async function openStudioBuildLibrary(
const resolvedProfile = profile === undefined ? undefined : resolve(profile);
const host = resolvedProfile === undefined
? undefined
- : await videoCliDistribution.openRuntimeHost(resolvedProfile, {
+ : await distribution.openRuntimeHost(resolvedProfile, {
packageRoot,
...(distributionPackageRoot === undefined ? {} : { distributionPackageRoot }),
});
const runtime = await host?.openControl({ readOnly: true });
- let transientExecution: RuntimeHostTransientExecution | undefined;
- let openedResults: Awaited<ReturnType<typeof videoCliDistribution.openProjectResults>>;
+ let transientExecution: CliTransientExecution | undefined;
+ let openedResults: Awaited<ReturnType<CliDistribution["openProjectResults"]>>;
try {
transientExecution = await host?.openTransientExecution();
- openedResults = await videoCliDistribution.openProjectResults(workspaceRoot, {
+ openedResults = await distribution.openProjectResults(workspaceRoot, {
packageRoot,
...(distributionPackageRoot === undefined ? {} : { distributionPackageRoot }),
});
diff --git a/packages/studio/src/cli.ts b/packages/studio/src/cli.ts
new file mode 100644
index 00000000..b01f0904
--- /dev/null
+++ b/packages/studio/src/cli.ts
@@ -0,0 +1,28 @@
+import type { CliCommandModule } from "@hypit/hypit/cli";
+
+export const cliCommandModules = [{
+ format: "hypit.cli-command@1",
+ id: "@hypit/studio",
+ commands: ["studio", "snapshot"],
+ writeRootHelp(io) {
+ io.write("\nStudio\n studio --run <build.svrun>\n snapshot --studio <url> ...\n hypit studio --help or hypit snapshot --help\n");
+ },
+ async writeHelp(argv, io) {
+ if ((argv[0] === "help" ? argv[1] : argv[0]) === "snapshot") {
+ const { writeSnapshotHelp } = await import("./snapshot-cli.js");
+ writeSnapshotHelp(io);
+ } else {
+ const { writeStudioHelp } = await import("./start.js");
+ writeStudioHelp(io);
+ }
+ },
+ async run(argv, io, context) {
+ if (argv[0] === "snapshot") {
+ const { runSnapshotCli } = await import("./snapshot-cli.js");
+ await runSnapshotCli(argv, io, context);
+ } else {
+ const { runStudio } = await import("./start.js");
+ await runStudio(argv.slice(1).filter((arg) => arg !== "--debug"), io, context);
+ }
+ },
+}] as const satisfies readonly CliCommandModule[];
diff --git a/packages/studio/src/companion-assembly.ts b/packages/studio/src/companion-assembly.ts
index 41eaaef6..d9640ca4 100644
--- a/packages/studio/src/companion-assembly.ts
+++ b/packages/studio/src/companion-assembly.ts
@@ -1,6 +1,6 @@
-import { installDistributionPackageResolution, loadNodePackageSelection } from "@hypit/package-loader-node";
-import type { LoadedPackage } from "@hypit/package-loader-node";
-import { studioContributionFromPackage } from "@hypit/studio-adapter";
+import { installDistributionPackageResolution } from "@hypit/hypit/loader/node";
+import type { LoadedPackage } from "@hypit/hypit/loader";
+import { studioContributionFromPackage } from "@hypit/studio-companion";
import { fallbackStudioTrackCompanions } from "./fallback-companions.js";
import { StudioCompanionRegistry } from "./studio-registry.js";
@@ -8,27 +8,21 @@ import { StudioCompanionRegistry } from "./studio-registry.js";
/**
* Assemble the immutable Companion Registry for one Source closure.
*
- * The distribution contributes its normal video vocabulary. Every package
- * actually selected by the Source may contribute its own Companion through the
- * same package host-facet boundary. There is no second project profile and no
+ * Every package actually selected by the Source may contribute its own Companion through the
+ * same package host-facet boundary. There is no second project profile, central Companion list or
* replacement table.
*/
export async function loadStudioCompanionRegistry(input: {
readonly distributionPackageRoot: string;
- readonly distributionPackages: readonly string[];
readonly sourcePackages: readonly LoadedPackage[];
}): Promise<StudioCompanionRegistry> {
installDistributionPackageResolution([input.distributionPackageRoot]);
- const distribution = await loadNodePackageSelection(
- input.distributionPackages,
- input.distributionPackageRoot,
- );
const selected = new Map<string, LoadedPackage>();
- for (const item of [...distribution, ...input.sourcePackages]) {
+ for (const item of input.sourcePackages) {
if (!selected.has(item.specifier)) selected.set(item.specifier, item);
}
const contributions = [...selected.values()].map((item) =>
- studioContributionFromPackage(item.specifier, item.contribution.hostFacets ?? []));
+ studioContributionFromPackage(item.specifier, item.contribution.facets ?? []));
return new StudioCompanionRegistry(
[...fallbackStudioTrackCompanions, ...contributions.flatMap((item) => item.tracks)],
{
diff --git a/packages/studio/src/compile.ts b/packages/studio/src/compile.ts
index 899adc52..c054f54a 100644
--- a/packages/studio/src/compile.ts
+++ b/packages/studio/src/compile.ts
@@ -1,7 +1,7 @@
-import type { NodeCompiledSourceClosure } from "@hypit/compiler-node";
-import type { AuthorElementProvenance, AuthorValueRef } from "@hypit/elaborator";
-import type { ArtifactAttachment } from "@hypit/workspace";
-import type { TypeRef } from "@hypit/protocol";
+import type { CompiledAuthorSource } from "@hypit/hypit/compiler";
+import type { AuthorElementProvenance, AuthorValueRef } from "@hypit/hypit/author";
+import type { BlobAttachment } from "@hypit/hypit/workspace";
+import type { TypeRef } from "@hypit/hypit/protocol";
import type { Observations } from "./observe.js";
import type { Placement } from "./observe.js";
@@ -13,7 +13,7 @@ export type ServedFile = {
};
export type CompiledSource = {
- readonly compiled: NodeCompiledSourceClosure;
+ readonly compiled: CompiledAuthorSource;
readonly observations: Observations;
readonly served: ReadonlyMap<string, ServedFile>;
readonly exports: readonly {
@@ -30,7 +30,7 @@ export type CompiledSource = {
* Studio share one Author graph instead of compiling two look-alike graphs.
*/
export async function observedCompiledSource(
- compiled: NodeCompiledSourceClosure,
+ compiled: CompiledAuthorSource,
observations: Observations,
): Promise<CompiledSource> {
const served = new Map<string, ServedFile>();
@@ -66,7 +66,7 @@ function sameRange(
}
function exactElement(
- compiled: NodeCompiledSourceClosure,
+ compiled: CompiledAuthorSource,
sourcePath: string,
range: { readonly start: number; readonly end: number },
): AuthorElementProvenance | undefined {
@@ -74,14 +74,14 @@ function exactElement(
element.sourceName === sourcePath && sameRange(element.range, range));
}
-function resolvedRef(compiled: NodeCompiledSourceClosure, ref: AuthorValueRef): string | undefined {
+function resolvedRef(compiled: CompiledAuthorSource, ref: AuthorValueRef): string | undefined {
if (ref.kind === "record") return ref.id;
return compiled.provenance.elements.flatMap((element) => element.outputs)
.find((output) => output.component === ref.component && output.name === ref.output)?.id;
}
function decorate(
- compiled: NodeCompiledSourceClosure,
+ compiled: CompiledAuthorSource,
sourcePath: string,
range: { readonly start: number; readonly end: number },
): {
@@ -110,7 +110,7 @@ function decorate(
/** Join Studio presentation to compiler-owned identities without re-matching authored names. */
function normalizeObservations(
- compiled: NodeCompiledSourceClosure,
+ compiled: CompiledAuthorSource,
observations: Observations,
): Observations {
const placements: Placement[] = observations.placements.map((placement) => {
@@ -148,7 +148,7 @@ function normalizeObservations(
return { placements, temporalDomains: observations.temporalDomains };
}
-async function bytesOf(attachment: ArtifactAttachment): Promise<Uint8Array> {
+async function bytesOf(attachment: BlobAttachment): Promise<Uint8Array> {
const chunks: Uint8Array[] = [];
let size = 0;
for await (const chunk of await attachment.open()) {
diff --git a/packages/studio/src/domain.ts b/packages/studio/src/domain.ts
index d9c390e9..817e02d6 100644
--- a/packages/studio/src/domain.ts
+++ b/packages/studio/src/domain.ts
@@ -1,28 +1,28 @@
-import { loadDiscoveredSourcePackages } from "@hypit/cli";
-import { registerProducerFacets, registerTypeValidatorFacets } from "@hypit/component-kit";
-import { createResolvedClosure } from "@hypit/core";
-import { ProducerRegistry } from "@hypit/driver-node";
+import { loadDiscoveredSourcePackages } from "@hypit/hypit/cli";
+import type { CliDistribution } from "@hypit/hypit/cli";
+import { producerPackagesFromFacets, registerProducerFacets } from "@hypit/hypit/producer";
+import { createResolvedClosure } from "@hypit/hypit/kernel";
+import { ProducerRegistry } from "@hypit/hypit/executor";
import {
AuthorFrontendRegistry,
- installAuthorFrontendHostFacets,
-} from "@hypit/elaborator";
+ installAuthorFrontendFacets,
+} from "@hypit/hypit/author";
import {
createMarkupAuthorFrontend,
- installMarkupSurfaceHostFacets,
+ installMarkupSurfaceFacets,
MarkupSurfaceRegistry,
-} from "@hypit/markup";
-import type { MarkupSurfaceRegistryLike } from "@hypit/markup";
-import type { LoadedPackage, NodePackageContribution } from "@hypit/package-loader-node";
-import { ModulePackageRegistry, NodeCompiler } from "@hypit/compiler-node";
-import type { ModuleRef, ResolvedModuleClosure } from "@hypit/protocol";
-import { TypeValidatorRegistry } from "@hypit/validation";
-import { createVideoCompiler, createVideoWorkspace, videoCliDistribution } from "@hypit/video-cli";
+} from "@hypit/hypit/markup";
+import type { MarkupSurfaceRegistryLike } from "@hypit/hypit/markup";
+import type { LoadedPackage, PackageContribution } from "@hypit/hypit/loader";
+import { ModulePackageRegistry, Compiler } from "@hypit/hypit/compiler";
+import type { ModuleRef, ResolvedModuleClosure } from "@hypit/hypit/protocol";
+import { admissionPackagesFromFacets, registerTypeValidatorFacets, TypeValidatorRegistry } from "@hypit/hypit/admission";
export type StudioDomain = {
readonly packages: readonly LoadedPackage[];
- readonly contributions: readonly NodePackageContribution[];
- readonly compiler: NodeCompiler;
- readonly createCompiler: (surfaces?: MarkupSurfaceRegistryLike) => NodeCompiler;
+ readonly contributions: readonly PackageContribution[];
+ readonly compiler: Compiler;
+ readonly createCompiler: (surfaces?: MarkupSurfaceRegistryLike) => Compiler;
readonly closure: ResolvedModuleClosure;
readonly surfaces: MarkupSurfaceRegistry;
readonly producers: ProducerRegistry;
@@ -33,20 +33,21 @@ export type StudioDomain = {
/**
* Assemble Studio from the same recursive package selection as the official CLI.
- * The application assembles the video-domain view; selected packages contribute Studio Companions through host facets.
+ * The application assembles the video-domain view; selected packages contribute Studio Companions through facets.
*/
export async function loadStudioDomain(input: {
readonly run: string;
readonly workspaceRoot: string;
readonly packageRoot: string;
+ readonly distribution: CliDistribution;
}): Promise<StudioDomain> {
- const packages = await loadDiscoveredSourcePackages(videoCliDistribution, {
+ const packages = await loadDiscoveredSourcePackages(input.distribution, {
source: input.run,
workspaceRoot: input.workspaceRoot,
packageRoot: input.packageRoot,
- ...(videoCliDistribution.packageRoot === undefined
+ ...(input.distribution.packageRoot === undefined
? {}
- : { distributionPackageRoot: videoCliDistribution.packageRoot }),
+ : { distributionPackageRoot: input.distribution.packageRoot }),
});
const contributions = packages.map((item) => item.contribution);
const manifests = contributions.flatMap((item) =>
@@ -67,9 +68,9 @@ export async function loadStudioDomain(input: {
}
}
const resolveModule = (specifier: string): ModuleRef | undefined => modules.get(specifier);
- const facets = contributions.flatMap((item) => item.hostFacets ?? []);
+ const facets = contributions.flatMap((item) => item.facets ?? []);
const surfaces = new MarkupSurfaceRegistry();
- installMarkupSurfaceHostFacets(facets, surfaces);
+ installMarkupSurfaceFacets(facets, surfaces);
const domainFrontends = (registry: MarkupSurfaceRegistryLike): AuthorFrontendRegistry => {
const frontends = new AuthorFrontendRegistry();
frontends.register(createMarkupAuthorFrontend({
@@ -80,52 +81,51 @@ export async function loadStudioDomain(input: {
return found;
},
}));
- installAuthorFrontendHostFacets(facets, frontends);
+ installAuthorFrontendFacets(facets, frontends);
return frontends;
};
const producers = new ProducerRegistry();
const validators = new TypeValidatorRegistry();
for (const contribution of contributions) {
- for (const component of contribution.components ?? []) {
- registerProducerFacets(producers, component.producers ?? []);
- registerTypeValidatorFacets(validators, component.validators ?? []);
- }
+ const facets = contribution.facets ?? [];
+ for (const item of producerPackagesFromFacets(facets)) registerProducerFacets(producers, item.producers ?? []);
+ for (const item of admissionPackagesFromFacets(facets)) registerTypeValidatorFacets(validators, item.validators ?? []);
}
return {
packages,
contributions,
- compiler: createVideoCompiler({
+ compiler: input.distribution.createCompiler({
workspaceRoot: input.workspaceRoot,
packageRoot: input.packageRoot,
- ...(videoCliDistribution.packageRoot === undefined
+ ...(input.distribution.packageRoot === undefined
? {}
- : { distributionPackageRoot: videoCliDistribution.packageRoot }),
+ : { distributionPackageRoot: input.distribution.packageRoot }),
packageContributions: contributions,
}),
createCompiler(registry) {
if (registry === undefined) {
- return createVideoCompiler({
+ return input.distribution.createCompiler({
workspaceRoot: input.workspaceRoot,
packageRoot: input.packageRoot,
- ...(videoCliDistribution.packageRoot === undefined
+ ...(input.distribution.packageRoot === undefined
? {}
- : { distributionPackageRoot: videoCliDistribution.packageRoot }),
+ : { distributionPackageRoot: input.distribution.packageRoot }),
packageContributions: contributions,
});
}
const frontends = domainFrontends(registry);
- return new NodeCompiler({
+ return new Compiler({
modules: moduleRegistry,
frontends,
validators,
- workspace: createVideoWorkspace({
+ workspace: input.distribution.createWorkspace({
workspaceRoot: input.workspaceRoot,
packageRoot: input.packageRoot,
- ...(videoCliDistribution.packageRoot === undefined
+ ...(input.distribution.packageRoot === undefined
? {}
- : { distributionPackageRoot: videoCliDistribution.packageRoot }),
+ : { distributionPackageRoot: input.distribution.packageRoot }),
}),
});
},
diff --git a/packages/studio/src/execute.ts b/packages/studio/src/execute.ts
index cbc53684..f10869c7 100644
--- a/packages/studio/src/execute.ts
+++ b/packages/studio/src/execute.ts
@@ -1,7 +1,7 @@
-import { MemoryResourceStore, NodeDriver } from "@hypit/driver-node";
-import type { ResourceStore } from "@hypit/runtime";
-import type { BuildState } from "@hypit/protocol";
-import type { RuntimeHostTransientExecution } from "@hypit/runtime-host-node";
+import { MemoryResourceStore, Executor } from "@hypit/hypit/executor";
+import type { ResourceStore } from "@hypit/hypit/runtime";
+import type { BuildState } from "@hypit/hypit/protocol";
+import type { CliTransientExecution as RuntimeHostTransientExecution } from "@hypit/hypit/cli";
import type { StudioDomain } from "./domain.js";
@@ -24,7 +24,7 @@ export async function executeStudioProjection(
execution?: RuntimeHostTransientExecution,
): Promise<Executed> {
const result = execution === undefined
- ? await new NodeDriver({
+ ? await new Executor({
producers: domain.producers,
validators: domain.validators,
resources,
diff --git a/packages/studio/src/fallback-companions.ts b/packages/studio/src/fallback-companions.ts
index eeed636b..0ceda5a9 100644
--- a/packages/studio/src/fallback-companions.ts
+++ b/packages/studio/src/fallback-companions.ts
@@ -1,7 +1,7 @@
-import type { StudioTrackCompanion, StudioTrackCompanionContext, StudioEntityDraft } from "@hypit/studio-adapter";
-import { artifactPreview, previewLayer, temporalLineageFor, temporalDomainSource } from "@hypit/studio-adapter";
-import { compositionTypes } from "@hypit/composition";
-import { timelineTypes } from "@hypit/timeline";
+import type { StudioTrackCompanion, StudioTrackCompanionContext, StudioEntityDraft } from "@hypit/studio-companion";
+import { artifactPreview, previewLayer, temporalLineageFor, temporalDomainSource } from "@hypit/studio-companion";
+import { compositionTypes } from "@hypit/hypit/composition";
+import { timelineTypes } from "@hypit/hypit/timeline";
type TerminalVisualTrack = {
readonly presents?: readonly {
diff --git a/packages/studio/src/observe.ts b/packages/studio/src/observe.ts
index eb21d401..02466d93 100644
--- a/packages/studio/src/observe.ts
+++ b/packages/studio/src/observe.ts
@@ -9,9 +9,9 @@
*/
import type {
MarkupSurfaceRegistryLike, RegisteredSurface, StructuredElement, StructuredSurfaceInput, SurfaceDecodeOutput,
-} from "@hypit/markup";
-import type { ModuleRef } from "@hypit/protocol";
-import type { StudioObservedValue, StudioPlacement, StudioTemporalDomainSourceMap } from "@hypit/studio-adapter";
+} from "@hypit/hypit/markup";
+import type { ModuleRef } from "@hypit/hypit/protocol";
+import type { StudioObservedValue, StudioPlacement, StudioTemporalDomainSourceMap } from "@hypit/studio-companion";
import type { Range } from "./shared.js";
import type { StudioCompanionRegistry } from "./studio-registry.js";
diff --git a/packages/studio/src/parameter-values.ts b/packages/studio/src/parameter-values.ts
index e86b6830..5fa61390 100644
--- a/packages/studio/src/parameter-values.ts
+++ b/packages/studio/src/parameter-values.ts
@@ -1,6 +1,6 @@
-import type { CanonicalValue, ValueSchema } from "@hypit/protocol";
-import { formatSvsValue } from "@hypit/svs";
-import type { StudioInspectorField, StudioParameterControl, StudioParameterOption, StudioNumberPresentation } from "@hypit/studio-adapter";
+import type { CanonicalValue, ValueSchema } from "@hypit/hypit/protocol";
+import { formatRecipeValue } from "@hypit/hypit/recipe";
+import type { StudioInspectorField, StudioParameterControl, StudioParameterOption, StudioNumberPresentation } from "@hypit/studio-companion";
export const parameterOption = (option: StudioParameterOption): Exclude<StudioParameterOption, string> =>
typeof option === "string" ? { value: option, label: option } : option;
@@ -114,7 +114,7 @@ export function validateParameterValue(value: CanonicalValue, schema: ValueSchem
}
export function serializeParameterValue(value: CanonicalValue, language: "svml" | "svs" | "svrun"): string {
- if (language === "svs") return formatSvsValue(value);
+ if (language === "svs") return formatRecipeValue(value);
if (typeof value === "string") return value.replaceAll("&", "&amp;").replaceAll('"', "&quot;").replaceAll("'", "&apos;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
if (typeof value === "number" || typeof value === "boolean") return String(value);
throw new Error(`${language.toUpperCase()} parameter bindings currently accept scalar values only.`);
diff --git a/packages/studio/src/parameters.ts b/packages/studio/src/parameters.ts
index b7c260e7..e260f517 100644
--- a/packages/studio/src/parameters.ts
+++ b/packages/studio/src/parameters.ts
@@ -14,13 +14,13 @@ import type {
StudioTemporalInstantProjection,
StudioTemporalLineage,
StudioTimelineGesture,
-} from "@hypit/studio-adapter";
-import { parseSvs } from "@hypit/svs";
-import { parseOpeningTag } from "@hypit/markup";
-import { prepareAuthorSource } from "@hypit/elaborator";
+} from "@hypit/studio-companion";
+import { parseRecipe } from "@hypit/hypit/recipe";
+import { parseOpeningTag } from "@hypit/hypit/markup";
+import { maskSourceHeader, parseSourceHeader } from "@hypit/hypit/source/text";
import { parameterControlForSchema, parameterRecordSchema } from "./parameter-values.js";
-import { sameType } from "@hypit/protocol";
-import type { CanonicalValue } from "@hypit/protocol";
+import { sameType } from "@hypit/hypit/protocol";
+import type { CanonicalValue } from "@hypit/hypit/protocol";
import type { StudioCompanionRegistry } from "./studio-registry.js";
@@ -172,8 +172,8 @@ function recipeParameters(input: {
const source = sourceFor(input.root, imported.source, input.files, input.current.path);
if (source === undefined || source.language !== "svs") return [];
const recipePath = parts.join(".");
- const prepared = prepareAuthorSource({ id: source.path, name: source.path, text: source.text });
- const parsed = parseSvs(source.path, prepared.text);
+ const header = parseSourceHeader(source.path, source.text);
+ const parsed = parseRecipe(source.path, maskSourceHeader(source.text, header));
const recipe = parsed.recipes.find((item) => item.value.path === recipePath);
if (recipe === undefined) return [];
return input.recipe.bindings.flatMap((declaration): readonly StudioSourceBinding[] => {
diff --git a/packages/studio/src/preview/render.ts b/packages/studio/src/preview/render.ts
index 95d2610f..95781338 100644
--- a/packages/studio/src/preview/render.ts
+++ b/packages/studio/src/preview/render.ts
@@ -1,8 +1,8 @@
-import type { Composition } from "@hypit/composition";
-import { compileHyperframesDocument, materializeHyperframesHtml } from "@hypit/hyperframes";
-import type { HyperframesDocument } from "@hypit/hyperframes";
-import { compileAudioProgramPlan } from "@hypit/media-pipeline";
-import type { Timeline } from "@hypit/timeline";
+import type { Composition } from "@hypit/hypit/composition";
+import { compileHtmlProgram, materializeHtmlProgram } from "@hypit/hypit/html-program";
+import type { HtmlProgram } from "@hypit/hypit/html-program";
+import { compileAudioProgramPlan } from "@hypit/media-operations";
+import type { Timeline } from "@hypit/hypit/timeline";
import { injectRuntimeShim } from "./runtime-shim.js";
@@ -14,20 +14,20 @@ export type RenderInput = {
};
/**
- * Compile the interpreted Tracks into the same HyperFrames document the real
+ * Compile the interpreted Tracks into the same HTML renderer document the real
* renderer photographs frame by frame, and hand it back as an `iframe` srcdoc.
*
* Nothing is approximated here: placement, stacking, clipping, motion and
* material all come from the projection selected by the Run.
*/
export function renderPreview(input: RenderInput): string {
- return renderStudioProgramme(input).preview;
+ return renderStudioHtmlProgram(input).preview;
}
/** The same compiled picture serves immediate frame capture and interactive playback. */
-export function renderStudioProgramme(input: RenderInput): { readonly document: HyperframesDocument; readonly html: string; readonly preview: string } {
- const document = compileHyperframesDocument(input.composition, input.timeline);
- const html = materializeHyperframesHtml(document, (artifact) => {
+export function renderStudioHtmlProgram(input: RenderInput): { readonly document: HtmlProgram; readonly html: string; readonly preview: string } {
+ const document = compileHtmlProgram(input.composition, input.timeline);
+ const html = materializeHtmlProgram(document, (artifact) => {
// The only Artifacts a preview can reference are files the author already
// has. Anything else would be a Provider's output, which does not exist yet,
// and failing loudly beats serving a picture with holes in it.
diff --git a/packages/studio/src/preview/runtime-shim.ts b/packages/studio/src/preview/runtime-shim.ts
index 183d7dff..3e4836bb 100644
--- a/packages/studio/src/preview/runtime-shim.ts
+++ b/packages/studio/src/preview/runtime-shim.ts
@@ -1,9 +1,9 @@
-import { audioEnvelopeGainAt } from "@hypit/composition";
+import { audioEnvelopeGainAt } from "@hypit/hypit/composition";
/**
- * Studio's frame driver for a compiled HyperFrames document.
+ * Studio's frame driver for a compiled HTML renderer document.
*
- * HyperFrames remains the owner of layout and animation. Studio only supplies
+ * HTML renderer remains the owner of layout and animation. Studio only supplies
* an absolute Program frame, places every timed Present/material at that
* instant, and waits until a discrete media seek is actually decoded.
*/
@@ -12,27 +12,25 @@ function shim(): string {
<script>
(function () {
var muted = false;
- var root = document.querySelector('[data-composition-id]');
- var fpsAttr = (root && root.getAttribute('data-fps')) || '30';
- var slash = fpsAttr.indexOf('/');
- var fps = slash === -1
- ? parseFloat(fpsAttr)
- : parseFloat(fpsAttr.slice(0, slash)) / parseFloat(fpsAttr.slice(slash + 1));
+ var root = document.querySelector('[data-hypit-program-root]');
+ var numerator = Number(root && root.getAttribute('data-hypit-frame-numerator')) || 30;
+ var denominator = Number(root && root.getAttribute('data-hypit-frame-denominator')) || 1;
+ var fps = numerator / denominator;
var frameSeconds = 1 / fps;
var currentSeconds = 0;
var playing = false;
var seekRevision = 0;
if (root) {
- root.style.width = (root.getAttribute('data-width') || '0') + 'px';
- root.style.height = (root.getAttribute('data-height') || '0') + 'px';
+ root.style.width = (root.getAttribute('data-hypit-width') || '0') + 'px';
+ root.style.height = (root.getAttribute('data-hypit-height') || '0') + 'px';
}
var visualClips = [];
for (var clip of document.querySelectorAll('.hypit-visual-present')) {
visualClips.push({
element: clip,
- start: parseFloat(clip.getAttribute('data-start') || '0') || 0,
- duration: parseFloat(clip.getAttribute('data-duration') || '0') || 0
+ startFrame: Number(clip.getAttribute('data-hypit-present-start-frame')),
+ endFrame: Number(clip.getAttribute('data-hypit-present-end-frame'))
});
}
// Sampling runs are separate video elements with their own absolute spans.
@@ -44,10 +42,6 @@ function shim(): string {
var ownDuration = element.getAttribute('data-duration');
media.push({
element: element,
- start: parseFloat(ownStart || (present && present.getAttribute('data-start')) || '0') || 0,
- duration: parseFloat(ownDuration || (present && present.getAttribute('data-duration')) || '0') || 0,
- mediaStart: parseFloat(element.getAttribute('data-media-start') || '0') || 0,
- rate: parseFloat(element.getAttribute('data-playback-rate') || '1') || 1,
startFrame: Number(element.getAttribute('data-hypit-start-frame')),
endFrame: Number(element.getAttribute('data-hypit-end-frame')),
sourceFrame: element.getAttribute('data-hypit-source-frame').split('/').map(BigInt),
@@ -56,9 +50,9 @@ function shim(): string {
});
}
var audioContext;
- var programmeAudio = [];
+ var programAudio = [];
for (var element of document.querySelectorAll('.hypit-studio-audio')) {
- programmeAudio.push({
+ programAudio.push({
element: element,
start: parseFloat(element.getAttribute('data-start') || '0') || 0,
duration: parseFloat(element.getAttribute('data-duration') || '0') || 0,
@@ -128,38 +122,21 @@ function shim(): string {
});
}
- function placeHyperframes(seconds) {
- var pending = [];
- var event = new CustomEvent('hf-seek', { detail: {
- time: seconds,
- waitUntil: function (promise) { pending.push(Promise.resolve(promise)); }
- }});
- window.dispatchEvent(event);
- var compositionId = root && root.getAttribute('data-composition-id');
- var timeline = compositionId && window.__timelines && window.__timelines[compositionId];
- if (timeline) {
- if (typeof timeline.pause === 'function') timeline.pause();
- if (typeof timeline.totalTime === 'function') timeline.totalTime(seconds);
- else if (typeof timeline.seek === 'function') timeline.seek(seconds);
- }
- return Promise.all(pending);
+ function placeHTML(frame) {
+ if (!window.__hypitFrameProgram) return Promise.reject(new Error('HTML Program page ABI is missing'));
+ return window.__hypitFrameProgram.applyFrame(frame);
}
function apply(seconds, scrubbing) {
currentSeconds = Math.max(0, seconds);
var revision = ++seekRevision;
var waits = [];
- for (var record of visualClips) {
- var local = currentSeconds - record.start;
- record.element.style.visibility = local >= 0 && local < record.duration ? 'visible' : 'hidden';
- }
+ var programFrame = Math.max(0, Math.round(currentSeconds * fps));
for (var record of media) {
- var local = currentSeconds - record.start;
- var programFrame = Math.round(currentSeconds * fps);
var inside = programFrame >= record.startFrame && programFrame < record.endFrame;
var element = record.element;
element.style.visibility = inside ? 'visible' : 'hidden';
- // Normalized picture Artifacts are deliberately silent. Programme sound
+ // Normalized picture Artifacts are deliberately silent. Program sound
// comes from the exact AudioTrack below rather than from a video sidecar.
element.muted = true;
if (!inside) { element.pause(); continue; }
@@ -176,22 +153,13 @@ function shim(): string {
waits.push(seekDecoded(element, heldTarget));
continue;
}
- var target = record.mediaStart + (local + frameSeconds / 2) * record.rate;
- // Browsers do not provide portable negative-rate playback. Reverse remains
- // an ordinary source-time function: preview it through the same absolute
- // frame seek used by scrubbing instead of weakening the author model.
- var discrete = record.sourceRate[0] < 0n || scrubbing || programFrame === record.endFrame - 1;
- if (discrete) {
- // The renderer floors exact source-frame coordinates. The midpoint of a
- // programme frame can cross that source boundary at fractional speeds.
- var a = record.sourceFrame, r = record.sourceRate;
- var sourceFrame = Number((a[0] * r[1] + BigInt(programFrame - record.startFrame) * r[0] * a[1]) / (a[1] * r[1]));
- target = (sourceFrame + 0.5) * record.sourceFps[1] / record.sourceFps[0];
- }
+ var a = record.sourceFrame, r = record.sourceRate;
+ var sourceFrame = Number((a[0] * r[1] + BigInt(programFrame - record.startFrame) * r[0] * a[1]) / (a[1] * r[1]));
+ var target = (sourceFrame + 0.5) * record.sourceFps[1] / record.sourceFps[0];
if (Number.isFinite(element.duration) && element.duration > 0) {
target = Math.min(target, Math.max(0, element.duration - 0.001));
}
- if (discrete) {
+ if (scrubbing || record.sourceRate[0] <= 0n || programFrame === record.endFrame - 1) {
element.pause();
waits.push(seekDecoded(element, target));
} else {
@@ -199,14 +167,14 @@ function shim(): string {
// only corrects visible drift; making every refresh a media seek is what
// previously froze the preview between frames.
if (Math.abs(element.currentTime - target) > 0.08) element.currentTime = target;
- element.playbackRate = record.rate;
+ element.playbackRate = Number(record.sourceRate[0]) / Number(record.sourceRate[1]) * fps * record.sourceFps[1] / record.sourceFps[0];
if (element.paused) {
var started = element.play();
if (started) started.catch(function () {});
}
}
}
- for (var record of programmeAudio) {
+ for (var record of programAudio) {
var local = currentSeconds - record.start;
var inside = local >= 0 && local < record.duration;
var element = record.element;
@@ -230,7 +198,7 @@ function shim(): string {
}
}
}
- waits.push(placeHyperframes(currentSeconds));
+ waits.push(placeHTML(programFrame));
return Promise.all(waits).then(function () { return revision === seekRevision; });
}
@@ -244,7 +212,7 @@ function shim(): string {
};
window.__hypitPlayFrame = function (frame) {
playing = true;
- if (programmeAudio.length && !audioContext) audioContext = new AudioContext();
+ if (programAudio.length && !audioContext) audioContext = new AudioContext();
if (audioContext && audioContext.state === 'suspended') audioContext.resume();
return apply(frame / fps, false);
};
diff --git a/packages/studio/src/programme.ts b/packages/studio/src/projection.ts
similarity index 92%
rename from packages/studio/src/programme.ts
rename to packages/studio/src/projection.ts
index c2d8608c..7157c220 100644
--- a/packages/studio/src/programme.ts
+++ b/packages/studio/src/projection.ts
@@ -1,12 +1,12 @@
-import type { ArtifactAttachment } from "@hypit/workspace";
-import type { BlobRef, ResourceId, StoredValue } from "@hypit/protocol";
-import { sameType } from "@hypit/protocol";
-import type { Composition } from "@hypit/composition";
-import { compositionTypes } from "@hypit/composition";
-import { timelineTypes, assertTimelineIdentity } from "@hypit/timeline";
-import type { Timeline } from "@hypit/timeline";
-import type { StudioObservedValue, StudioResolvedTrack, StudioTemporalBinding } from "@hypit/studio-adapter";
-import type { RuntimeHostTransientExecution } from "@hypit/runtime-host-node";
+import type { BlobAttachment } from "@hypit/hypit/workspace";
+import type { BlobRef, ResourceId, StoredValue } from "@hypit/hypit/protocol";
+import { sameType } from "@hypit/hypit/protocol";
+import type { Composition } from "@hypit/hypit/composition";
+import { compositionTypes } from "@hypit/hypit/composition";
+import { timelineTypes, assertTimelineIdentity } from "@hypit/hypit/timeline";
+import type { Timeline } from "@hypit/hypit/timeline";
+import type { StudioObservedValue, StudioResolvedTrack, StudioTemporalBinding } from "@hypit/studio-companion";
+import type { CliTransientExecution as RuntimeHostTransientExecution } from "@hypit/hypit/cli";
import type { CompiledSource, ServedFile } from "./compile.js";
import type { StudioDomain } from "./domain.js";
@@ -17,13 +17,13 @@ import { studioSurfacePreview } from "./surface-preview.js";
import { executedTemporalBindings } from "./temporal-graph.js";
import type { StudioCompanionRegistry } from "./studio-registry.js";
-function playable(type: import("@hypit/protocol").TypeRef): boolean {
+function playable(type: import("@hypit/hypit/protocol").TypeRef): boolean {
return sameType(type, compositionTypes.visualTrack) || sameType(type, compositionTypes.audioTrack);
}
export type BuiltTrack = StudioResolvedTrack;
-export type Preview = {
+export type StudioProjection = {
readonly source: CompiledSource;
readonly tracks: readonly BuiltTrack[];
/** Resolved Companion realizations keyed by exact graph output ref. */
@@ -40,7 +40,7 @@ export type Preview = {
readonly timeline: Timeline;
};
-async function bytesOf(attachment: ArtifactAttachment): Promise<Uint8Array> {
+async function bytesOf(attachment: BlobAttachment): Promise<Uint8Array> {
const chunks: Uint8Array[] = [];
let size = 0;
for await (const chunk of await attachment.open()) {
@@ -92,7 +92,7 @@ function compositionArtifacts(composition: Composition): readonly BlobRef[] {
}
/** Build only the Studio-approved deterministic projection of one explicit Run. */
-export async function preview(input: {
+export async function resolveStudioProjection(input: {
readonly source: CompiledSource;
readonly registry: StudioCompanionRegistry;
readonly run: RunPlan;
@@ -103,7 +103,7 @@ export async function preview(input: {
readonly projections: readonly StudioViewRequirement[];
/** Runtime-owned execution for capabilities explicitly safe outside a Build. */
readonly transientExecution?: RuntimeHostTransientExecution;
-}): Promise<Preview> {
+}): Promise<StudioProjection> {
const exportsByRef = new Map(input.source.exports.map((item) => [item.ref, item] as const));
const targets = input.outputRefs.flatMap((ref) => {
const found = exportsByRef.get(ref);
diff --git a/packages/studio/src/run.ts b/packages/studio/src/run.ts
index f8bcaa97..b5c58ae0 100644
--- a/packages/studio/src/run.ts
+++ b/packages/studio/src/run.ts
@@ -1,13 +1,13 @@
-import type { PlannedBuild } from "@hypit/compiler-node";
-import { NodeRunCompiler } from "@hypit/compiler-node";
-import type { Candidate, OperationNode, Satisfaction, BuildTarget } from "@hypit/protocol";
-import type { ArtifactAttachment } from "@hypit/workspace";
+import type { PlannedBuild } from "@hypit/hypit/compiler";
+import { RunCompiler } from "@hypit/hypit/compiler";
+import type { Candidate, OperationNode, Satisfaction, BuildTarget } from "@hypit/hypit/protocol";
+import type { BlobAttachment } from "@hypit/hypit/workspace";
import {
- installRunFragmentHostFacets,
- runFrontendsFromHostFacets,
+ installRunFragmentFacets,
+ runFrontendsFromFacets,
RunFragmentRegistry,
RunFrontendRegistry,
-} from "@hypit/run";
+} from "@hypit/hypit/run";
import type { StudioBuildLibrary } from "./build-library.js";
import { observedCompiledSource } from "./compile.js";
@@ -31,7 +31,7 @@ export type RunPlan = {
readonly source: CompiledSource;
readonly run: RunCompilation;
readonly targets: readonly string[];
- readonly attachments: readonly ArtifactAttachment[];
+ readonly attachments: readonly BlobAttachment[];
readonly plan: (run: RunCompilation, targets: readonly string[]) => PlannedBuild;
};
@@ -45,13 +45,13 @@ export async function loadStudioRun(input: {
const fragments = new RunFragmentRegistry();
const frontends = new RunFrontendRegistry();
for (const contribution of input.domain.contributions) {
- installRunFragmentHostFacets(contribution.hostFacets ?? [], fragments);
- for (const frontend of runFrontendsFromHostFacets(contribution.hostFacets ?? [])) {
+ installRunFragmentFacets(contribution.facets ?? [], fragments);
+ for (const frontend of runFrontendsFromFacets(contribution.facets ?? [])) {
frontends.register(frontend);
}
}
const observer = createObserver(input.domain.surfaces, input.registry);
- const compiler = new NodeRunCompiler({
+ const compiler = new RunCompiler({
authorCompiler: input.domain.createCompiler(observer.surfaces),
fragments,
frontends,
@@ -60,7 +60,7 @@ export async function loadStudioRun(input: {
resolveHistoricalOutput: input.buildLibrary.resolveHistoricalOutput,
}),
});
- const compiled = await compiler.compileFile(input.run);
+ const compiled = await compiler.compileEntry(input.run);
const source = await observedCompiledSource(compiled.author, observer.observations());
const targets = compiled.run.graph.targets.map((target) => target.output);
return {
diff --git a/packages/studio/src/server.ts b/packages/studio/src/server.ts
index ab850187..183aa13d 100644
--- a/packages/studio/src/server.ts
+++ b/packages/studio/src/server.ts
@@ -7,9 +7,9 @@ import { Readable } from "node:stream";
import { pipeline } from "node:stream/promises";
import type { Plugin, ViteDevServer } from "vite";
-import type { BuildResultFileRange } from "@hypit/build-result";
-import type { StudioTemporalInstantProjection } from "@hypit/studio-adapter";
-import { sameType } from "@hypit/protocol";
+import type { BuildResultFileRange } from "@hypit/hypit/result";
+import type { StudioTemporalInstantProjection } from "@hypit/studio-companion";
+import { sameType } from "@hypit/hypit/protocol";
import type { StudioBuildLibrary } from "./build-library.js";
import type { ServedFile } from "./compile.js";
@@ -83,7 +83,7 @@ class StudioMutationRejected extends Error {}
export function studioPlugin(options: StudioPluginOptions): Plugin {
let snapshot: StudioSnapshot | undefined;
let visualHtml: string | undefined;
- let visualDocument: import("@hypit/hyperframes").HyperframesDocument | undefined;
+ let visualDocument: import("@hypit/hypit/html-program").HtmlProgram | undefined;
let failure: StudioFailure | undefined;
let material: ReadonlyMap<string, ServedFile> = new Map();
let revision = 0;
diff --git a/packages/studio/src/session.ts b/packages/studio/src/session.ts
index cb8286e6..db6031e9 100644
--- a/packages/studio/src/session.ts
+++ b/packages/studio/src/session.ts
@@ -1,15 +1,15 @@
import { existsSync, readFileSync } from "node:fs";
import { relative } from "node:path";
-import { markupAuthorFrontendId } from "@hypit/markup";
-import type { RuntimeHostTransientExecution } from "@hypit/runtime-host-node";
-import { svsFrontendId } from "@hypit/svs";
+import { markupAuthorFrontendId } from "@hypit/hypit/markup";
+import type { CliTransientExecution as RuntimeHostTransientExecution } from "@hypit/hypit/cli";
+import { recipeFrontendId } from "@hypit/hypit/recipe";
import type { ServedFile } from "./compile.js";
import type { StudioDomain } from "./domain.js";
import type { Observations } from "./observe.js";
-import { preview } from "./programme.js";
-import { renderStudioProgramme } from "./preview/render.js";
+import { resolveStudioProjection } from "./projection.js";
+import { renderStudioHtmlProgram } from "./preview/render.js";
import type { RunPlan } from "./run.js";
import type { StudioSnapshot } from "./shared.js";
import type { StudioCompanionRegistry } from "./studio-registry.js";
@@ -26,7 +26,7 @@ function sourceFiles(run: RunPlan): readonly StudioSourceFile[] {
const unit = run.source.compiled.closure.units.find((candidate) => candidate.id === path);
const language = path === run.runPath
? "svrun" as const
- : unit?.frontend === svsFrontendId
+ : unit?.frontend === recipeFrontendId
? "svs" as const
: unit?.frontend === markupAuthorFrontendId
? "svml" as const
@@ -47,7 +47,7 @@ function sourceFiles(run: RunPlan): readonly StudioSourceFile[] {
export type StudioSession = {
readonly snapshot: StudioSnapshot;
- readonly document: import("@hypit/hyperframes").HyperframesDocument;
+ readonly document: import("@hypit/hypit/html-program").HtmlProgram;
readonly visualHtml: string;
readonly material: ReadonlyMap<string, ServedFile>;
readonly observations: Observations;
@@ -69,7 +69,7 @@ export async function readStudioSession(input: {
inspection.filmComposition,
...inspection.projections.map((projection) => projection.ref),
];
- const built = await preview({
+ const built = await resolveStudioProjection({
source,
registry: input.registry,
run: input.run,
@@ -80,7 +80,7 @@ export async function readStudioSession(input: {
projections: inspection.projections,
...(input.transientExecution === undefined ? {} : { transientExecution: input.transientExecution }),
});
- const rendered = renderStudioProgramme({
+ const rendered = renderStudioHtmlProgram({
composition: built.composition,
timeline: built.timeline,
served: new Set(built.served.keys()),
@@ -104,7 +104,7 @@ export async function readStudioSession(input: {
},
canvas: built.canvas,
frameRate: built.frameRate,
- preview: { kind: "hyperframes", srcdoc: rendered.preview },
+ preview: { kind: "html-program", srcdoc: rendered.preview },
workspaceRoot: input.workspaceRoot,
sourceFiles: files,
surfaces: input.domain.surfaces,
diff --git a/packages/studio/src/shared.ts b/packages/studio/src/shared.ts
index 041f34b2..c4375984 100644
--- a/packages/studio/src/shared.ts
+++ b/packages/studio/src/shared.ts
@@ -17,15 +17,14 @@ import type {
StudioTemporalDomainItem,
StudioTemporalDomainView,
StudioTemporalLineage,
- StudioTemporalPhase,
StudioTemporalProjection,
StudioTemporalSource,
StudioTimelineGesture,
StudioTimelinePresentation,
StudioTimelineTone,
StudioTrackFamily,
-} from "@hypit/studio-adapter";
-import type { CanonicalValue } from "@hypit/protocol";
+} from "@hypit/studio-companion";
+import type { CanonicalValue } from "@hypit/hypit/protocol";
export type {
Range,
@@ -37,13 +36,12 @@ export type {
StudioInspectorField,
StudioInspectorDomain,
StudioTemporalLineage,
- StudioTemporalPhase,
StudioTemporalProjection,
StudioTemporalSource,
StudioTimelinePresentation,
StudioTimelineTone,
StudioTrackFamily,
-} from "@hypit/studio-adapter";
+} from "@hypit/studio-companion";
export type CandidateOrigin = "run" | "source" | "none";
export type CandidateStatus = "resolved" | "unresolved";
@@ -235,7 +233,7 @@ export type StudioSnapshot = {
/** Package-contributed temporal views projected onto the same absolute ruler. */
readonly temporalDomains: readonly TemporalDomainView[];
/** The Tracks, compiled into the document the renderer photographs. */
- readonly preview: { readonly kind: "hyperframes"; readonly srcdoc: string };
+ readonly preview: { readonly kind: "html-program"; readonly srcdoc: string };
readonly provenance: {
readonly picture: "resolved";
/** What the badges above are standing for, in one sentence. */
@@ -254,13 +252,13 @@ export type StudioMutation =
| {
readonly kind: "instant";
readonly frame: number;
- readonly domain?: import("@hypit/studio-adapter").StudioTemporalDomainEditTarget;
+ readonly domain?: import("@hypit/studio-companion").StudioTemporalDomainEditTarget;
}
| {
readonly kind: "window";
readonly startFrame: number;
readonly endFrameExclusive: number;
- readonly domain?: import("@hypit/studio-adapter").StudioTemporalDomainEditTarget;
+ readonly domain?: import("@hypit/studio-companion").StudioTemporalDomainEditTarget;
};
}
| {
diff --git a/packages/studio/src/snapshot-cli.ts b/packages/studio/src/snapshot-cli.ts
new file mode 100644
index 00000000..b9c7dd53
--- /dev/null
+++ b/packages/studio/src/snapshot-cli.ts
@@ -0,0 +1,140 @@
+import { mkdir, mkdtemp, rename, rm, stat, writeFile } from "node:fs/promises";
+import { dirname, join, resolve } from "node:path";
+import {
+ cliProviderLine,
+ cliProviderView,
+ createCliScratchResources,
+ openCliRuntimeHost,
+ selectCliProvider,
+} from "@hypit/hypit/cli";
+import type { CliApplicationContext, CliIo } from "@hypit/hypit/cli";
+import { assertHtmlProgram, selectHtmlArtifacts } from "@hypit/hypit/html-program";
+import type { HtmlProgram } from "@hypit/hypit/html-program";
+import { htmlFrameRequest, htmlProgramCapabilities, htmlProgramTypes, verifyHtmlFrameImages } from "@hypit/hypit/html-program";
+import type { Need } from "@hypit/hypit/protocol";
+import { snapshotFrameLabel, writeFrameGrid } from "@hypit/media-local";
+
+const OPTIONS = ["--studio", "--to", "--at-frame", "--start-frame", "--end-frame-exclusive", "--step-frames", "--grid", "--cell", "--runtime", "--project"];
+
+/** `--studio` is a base URL, not a host:port token. `new URL` otherwise throws TypeError. */
+export function studioDocumentUrl(studio: string): string {
+ try {
+ return new URL("/__studio/document", studio).href;
+ } catch {
+ throw new Error(`--studio needs an http(s) Studio URL, got ${studio}`);
+ }
+}
+
+export function writeSnapshotHelp(io: CliIo): void {
+ io.write(`hypit snapshot\nCapture exact frames from Studio's current compiled HTML Program through the selected Runtime Profile.\n\n`
+ + ` hypit snapshot --studio <studio-url> --at-frame <n[,n,…]> --to <directory>\n`
+ + ` hypit snapshot --studio <studio-url> --start-frame <n> --end-frame-exclusive <n> [--step-frames <n>] --to <directory>\n`
+ + ` [--grid <columns>x<rows>] [--cell <pixels>] [--runtime <profile>] [--project <directory>] [--json]\n\n`
+ + `Frame indices are zero-based on the current HtmlProgram clock. Ranges exclude the end.\n`
+ + `Writes full-size PNGs and optional paginated grids. --cell controls grid image width (default 480).\n`
+ + `Uses rasterize-frames in one immediate request. Browser preparation belongs to the selected Provider.\n`
+ + `Studio supplies the typed HTML Program and its declared Artifacts; raw HTML is not reverse-compiled.\n`);
+}
+
+export async function runSnapshotCli(argv: readonly string[], io: CliIo, application: CliApplicationContext): Promise<void> {
+ if (argv.includes("--help")) { writeSnapshotHelp(io); return; }
+ const options = new Map<string, string>();
+ const positionals = [];
+ const json = argv.includes("--json");
+ for (let index = 1; index < argv.length; index++) {
+ const arg = argv[index]!;
+ if (["--json", "--debug", "--verbose", "--no-color"].includes(arg)) continue;
+ if (arg === "--color") { index++; continue; }
+ if (!arg.startsWith("--")) { positionals.push(arg); continue; }
+ if (!OPTIONS.includes(arg)) throw new Error(`Unknown snapshot option ${arg}`);
+ if (options.has(arg)) throw new Error(`${arg} cannot be repeated`);
+ const value = argv[++index];
+ if (!value || value.startsWith("--")) throw new Error(`${arg} requires a value`);
+ options.set(arg, value);
+ }
+ const studio = options.get("--studio");
+ if (positionals.length !== 0 || studio === undefined || !options.has("--to")) throw new Error("snapshot requires --studio <url> and --to <directory>");
+ const integer = (raw: string | undefined, label: string, minimum = 0): number => {
+ if (raw === undefined || !/^\d+$/u.test(raw) || !Number.isSafeInteger(Number(raw)) || Number(raw) < minimum) throw new Error(`${label} needs an integer >= ${minimum}`);
+ return Number(raw);
+ };
+ const source = studioDocumentUrl(studio);
+ const response = await fetch(source);
+ if (!response.ok) throw new Error(`Studio HtmlProgram: HTTP ${response.status} ${await response.text()}`);
+ const document = await response.json() as HtmlProgram;
+ assertHtmlProgram(document);
+ const domain = document;
+ const explicit = options.get("--at-frame");
+ let frames: number[];
+ if (explicit !== undefined) {
+ if (["--start-frame", "--end-frame-exclusive", "--step-frames"].some(key => options.has(key))) throw new Error("Choose --at-frame or a frame range");
+ frames = explicit.split(",").map(value => integer(value, "--at-frame"));
+ } else {
+ const start = integer(options.get("--start-frame"), "--start-frame");
+ const end = integer(options.get("--end-frame-exclusive"), "--end-frame-exclusive");
+ const step = integer(options.get("--step-frames") ?? "1", "--step-frames", 1);
+ if (end <= start || end > domain.frameCount) throw new Error(`The frame range must satisfy 0 <= start < end <= ${domain.frameCount}`);
+ frames = Array.from({ length: Math.ceil((end - start) / step) }, (_, index) => start + index * step);
+ }
+ const grid = options.get("--grid")?.split("x");
+ if (grid !== undefined && grid.length !== 2) throw new Error("--grid needs columns x rows, for example 4x3");
+ const columns = grid === undefined ? undefined : integer(grid[0], "grid columns", 1);
+ const rows = grid === undefined ? undefined : integer(grid[1], "grid rows", 1);
+ if (options.has("--cell") && grid === undefined) throw new Error("--cell requires --grid");
+ const cell = integer(options.get("--cell") ?? "480", "--cell", 32);
+ const to = resolve(application.cwd, options.get("--to")!);
+ if (await stat(to).then(() => true, () => false)) throw new Error(`Destination ${to} already exists`);
+ let staging: string | undefined;
+ try {
+ const resources = createCliScratchResources();
+ const selection = frames.map((frame) => ({ startFrame: frame, endFrameExclusive: frame + 1 }));
+ for (const { artifact } of selectHtmlArtifacts(document, selection)) {
+ const response = await fetch(new URL(`/__studio/material/${artifact.resource}`, studio));
+ if (!response.ok) throw new Error(`Studio material ${artifact.resource}: HTTP ${response.status}`);
+ await resources.write(artifact, new Uint8Array(await response.arrayBuffer()));
+ }
+ const need: Need = { id: "need:hypit-snapshot", capability: htmlProgramCapabilities.rasterizeFrames,
+ returns: htmlProgramTypes.frameImages, result: "record:hypit-snapshot", constraints: htmlFrameRequest({ program: document, frames }) };
+ const { host, profile } = await openCliRuntimeHost(application, options.get("--runtime"), options.get("--project"));
+ const provider = await selectCliProvider(host, need, profile);
+ if (!json) io.write(`Capturing ${frames.length} frames through ${cliProviderLine(provider)}\n`);
+ const report = json ? io.writeProgress : io.writeProgress ?? io.write;
+ const fulfilled = await host.invoke(need, resources, {
+ reportProgress: async progress => { report?.(` · ${progress.phase}\n`); },
+ reportDiagnostic: async diagnostic => { report?.(` · ${diagnostic.message}\n`); },
+ });
+ if (fulfilled.value.kind !== "inline") throw new Error("The frame list came back by reference");
+ verifyHtmlFrameImages(fulfilled.value.value);
+ const images = fulfilled.value.value;
+ if (images.length !== frames.length) throw new Error(`Requested ${frames.length} frames, received ${images.length}`);
+ await mkdir(dirname(to), { recursive: true });
+ staging = await mkdtemp(join(dirname(to), ".hypit-snapshot-"));
+ const files = [];
+ for (const [index, image] of images.entries()) {
+ const frame = frames[index]!;
+ const name = `frame-${String(frame).padStart(9, "0")}.png`;
+ const bytes = await resources.get(image.resource);
+ if (bytes === undefined) throw new Error(`Snapshot frame ${frame} is unavailable`);
+ await writeFile(join(staging, name), bytes, { flag: "wx" });
+ files.push({ frame, seconds: frame * domain.frameRate.denominator / domain.frameRate.numerator, path: join(to, name) });
+ }
+ const grids: string[] = [];
+ if (columns !== undefined && rows !== undefined) {
+ const count = columns * rows;
+ for (let offset = 0; offset < files.length; offset += count) {
+ const page = [];
+ for (const file of files.slice(offset, offset + count)) page.push({ path: join(staging, `frame-${String(file.frame).padStart(9, "0")}.png`),
+ label: await snapshotFrameLabel(file.frame, file.seconds, cell) });
+ const name = `grid-${String(grids.length + 1).padStart(3, "0")}.jpg`;
+ await writeFrameGrid(page, join(staging, name), cell, columns);
+ grids.push(join(to, name));
+ }
+ }
+ await rename(staging, to);
+ staging = undefined;
+ if (json) io.write(`${JSON.stringify({ format: "hypit.studio-snapshot@1", source, ...cliProviderView(provider), frames: files, grids }, null, 2)}\n`);
+ else io.write(`Captured ${files.length} PNGs${grids.length === 0 ? "" : ` and ${grids.length} grid${grids.length === 1 ? "" : "s"}`}\n ${to}\n`);
+ } finally {
+ if (staging !== undefined) await rm(staging, { recursive: true, force: true });
+ }
+}
diff --git a/packages/studio/src/snapshot.ts b/packages/studio/src/snapshot.ts
index 05e8f0a5..3884ddcb 100644
--- a/packages/studio/src/snapshot.ts
+++ b/packages/studio/src/snapshot.ts
@@ -1,16 +1,16 @@
import { composeParameterDeclarations } from "./parameters.js";
/**
- * Turn a built programme into what the panels read.
+ * Turn the resolved Studio projection into what the panels read.
*
* The Timeline owns the work range. Companions project selectable entities onto
* that range without extending it or requiring component-specific editor code.
*/
import { relative } from "node:path";
-import type { MarkupSurfaceRegistryLike } from "@hypit/markup";
-import { compositionTypes } from "@hypit/composition";
-import { timelineFrameCount } from "@hypit/timeline";
-import { sameModule, sameType } from "@hypit/protocol";
+import type { MarkupSurfaceRegistryLike } from "@hypit/hypit/markup";
+import { compositionTypes } from "@hypit/hypit/composition";
+import { timelineFrameCount } from "@hypit/hypit/timeline";
+import { sameModule, sameType } from "@hypit/hypit/protocol";
import type {
CandidateProvenance,
@@ -21,7 +21,7 @@ import type {
Track,
} from "./shared.js";
import type { Placement } from "./observe.js";
-import type { Preview } from "./programme.js";
+import type { StudioProjection } from "./projection.js";
import {
sealStudioClip,
} from "./studio-registry.js";
@@ -96,7 +96,7 @@ function authored(placements: readonly Placement[]): readonly Located[] {
/** Package Companions project their own temporal facts onto Studio's absolute ruler. */
function temporalDomains(
registry: StudioCompanionRegistry,
- built: Preview,
+ built: StudioProjection,
): readonly TemporalDomainView[] {
const provenance: CandidateProvenance = {
output: built.timingOutput?.name ?? "Timeline",
@@ -115,7 +115,7 @@ function temporalDomains(
});
}
-export function snapshot(registry: StudioCompanionRegistry, built: Preview, input: {
+export function snapshot(registry: StudioCompanionRegistry, built: StudioProjection, input: {
readonly revision: number;
readonly path: string;
readonly text: string;
@@ -268,6 +268,6 @@ export function snapshot(registry: StudioCompanionRegistry, built: Preview, inpu
};
}
-function note(_built: Preview): string {
+function note(_built: StudioProjection): string {
return "Composition and timing are resolved from the selected Run Source.";
}
diff --git a/packages/studio/start.ts b/packages/studio/src/start.ts
similarity index 72%
rename from packages/studio/start.ts
rename to packages/studio/src/start.ts
index 81739f4b..5532be9e 100644
--- a/packages/studio/start.ts
+++ b/packages/studio/src/start.ts
@@ -1,15 +1,15 @@
import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";
-import type { CliIo } from "@hypit/cli";
+import type { CliApplicationContext, CliIo } from "@hypit/hypit/cli";
-const here = dirname(fileURLToPath(import.meta.url));
+const here = resolve(dirname(fileURLToPath(import.meta.url)), "..");
export function writeStudioHelp(io: Pick<CliIo, "write">): void {
io.write(`hypit studio
Open a Run in the browser to inspect its composition, Sources and Results.
hypit studio --run <build.svrun> [--runtime <hypit.runtime.json>]
- [--port <number>] [--workspace <directory>] [--package-root <directory>]
+ [--port <number>] [--project <directory>] [--package-root <directory>]
[--locale-pack <./language.json | installed-package/language.json>]...
hypit studio --check-locale <./language.json | installed-package/language.json>
@@ -19,9 +19,9 @@ Language packs are explicit JSON data. Relative files use the current directory;
package exports resolve from --package-root (the project by default).
--check-locale lists missing translations and unknown IDs without opening a Run.
-Relative command-line paths start at the current directory; --workspace selects
+Relative command-line paths start at the current directory; --project selects
the project, without rebasing those paths. Otherwise the nearest package.json
-above the current directory defines the project (or the current directory if none).
+whose hypit.project is true defines the project.
Without --runtime, Studio uses that project's .hypit/runtime selection.
The server prints its project, Run, Runtime selection and browser URL.
Press Ctrl+C to stop it.
@@ -33,7 +33,7 @@ function invalidArguments(message: string): never {
}
function argumentsByName(argv: readonly string[]): ReadonlyMap<string, readonly string[]> {
- const accepted = new Set(["run", "runtime", "port", "workspace", "package-root", "locale-pack", "check-locale"]);
+ const accepted = new Set(["run", "runtime", "port", "project", "package-root", "locale-pack", "check-locale"]);
const result = new Map<string, string[]>();
for (let index = 0; index < argv.length; index += 2) {
const flag = argv[index];
@@ -48,30 +48,29 @@ function argumentsByName(argv: readonly string[]): ReadonlyMap<string, readonly
return result;
}
-export async function runStudio(argv: readonly string[], io: Pick<CliIo, "write">): Promise<void> {
+export async function runStudio(
+ argv: readonly string[],
+ io: Pick<CliIo, "write">,
+ application: CliApplicationContext,
+): Promise<void> {
if (argv.includes("--help") || argv.includes("-h")) {
writeStudioHelp(io);
return;
}
const values = argumentsByName(argv[0] === "--" ? argv.slice(1) : argv);
- const invokedFrom = process.env.INIT_CWD ?? process.cwd();
+ const invokedFrom = process.env.INIT_CWD ?? application.cwd;
const runArgument = values.get("run")?.at(-1);
- const { findRuntimeProfile, resolveProjectRoot } = await import("@hypit/project-context-node");
-
const packageRootArgument = values.get("package-root")?.at(-1);
- const workspaceArgument = values.get("workspace")?.at(-1);
- const requestedWorkspaceRoot = workspaceArgument === undefined
+ const projectArgument = values.get("project")?.at(-1);
+ const requestedProjectRoot = projectArgument === undefined
? undefined
- : resolve(invokedFrom, workspaceArgument);
- const workspaceRoot = await resolveProjectRoot({
- ...(requestedWorkspaceRoot === undefined ? {} : { workspaceRoot: requestedWorkspaceRoot }),
- cwd: invokedFrom,
- });
+ : resolve(invokedFrom, projectArgument);
+ const workspaceRoot = await application.resolveProjectRoot(requestedProjectRoot);
const packageRoot = packageRootArgument === undefined
? workspaceRoot
: resolve(invokedFrom, packageRootArgument);
- const { describeLanguagePack, loadLanguagePack, studioLanguages, studioLocalizationPlugin } = await import("./src/localization-node.js");
+ const { describeLanguagePack, loadLanguagePack, studioLanguages, studioLocalizationPlugin } = await import("./localization-node.js");
const checkLocale = values.get("check-locale")?.at(-1);
if (checkLocale !== undefined) {
io.write(describeLanguagePack(await loadLanguagePack(checkLocale, invokedFrom, packageRoot)) + "\n");
@@ -80,19 +79,18 @@ export async function runStudio(argv: readonly string[], io: Pick<CliIo, "write"
if (runArgument === undefined || runArgument.trim().length === 0) invalidArguments("Missing --run");
const runPath = resolve(invokedFrom, runArgument);
const { createServer } = await import("vite");
- const { resolveDistributionPackageImport } = await import("@hypit/package-loader-node");
- const { videoCliDistribution, videoStudioCompanionPackages } = await import("@hypit/video-cli");
- const { openStudioBuildLibrary } = await import("./src/build-library.js");
- const { loadStudioCompanionRegistry } = await import("./src/companion-assembly.js");
- const { loadStudioDomain } = await import("./src/domain.js");
- const { loadStudioRun } = await import("./src/run.js");
- const { studioPlugin } = await import("./src/server.js");
- const { studioFeedbackPlugin } = await import("./src/feedback-server.js");
- const { inspectStudioRun } = await import("./src/studio-preflight.js");
+ const { resolveDistributionPackageImport } = await import("@hypit/hypit/loader/node");
+ const { openStudioBuildLibrary } = await import("./build-library.js");
+ const { loadStudioCompanionRegistry } = await import("./companion-assembly.js");
+ const { loadStudioDomain } = await import("./domain.js");
+ const { loadStudioRun } = await import("./run.js");
+ const { studioPlugin } = await import("./server.js");
+ const { studioFeedbackPlugin } = await import("./feedback-server.js");
+ const { inspectStudioRun } = await import("./studio-preflight.js");
const languages = await studioLanguages(values.get("locale-pack") ?? [], invokedFrom, packageRoot);
const runtimeArgument = values.get("runtime")?.at(-1);
const selectedRuntime = runtimeArgument === undefined
- ? await findRuntimeProfile(workspaceRoot)
+ ? await application.distribution.resolveProjectRuntime?.(workspaceRoot)
: undefined;
const runtimePath = runtimeArgument === undefined
? selectedRuntime?.profile
@@ -102,21 +100,26 @@ export async function runStudio(argv: readonly string[], io: Pick<CliIo, "write"
` Run ${runPath}`,
` Runtime Profile ${runtimePath ?? "not selected"}`,
` Runtime selection ${runtimeArgument !== undefined
- ? "command argument (this session only)" : selectedRuntime?.selectionFile ?? "none"}`,
+ ? "command argument (this session only)" : selectedRuntime === undefined ? "none" : "project selection"}`,
...(packageRoot === workspaceRoot ? [] : [` Package root ${packageRoot}`]),
"",
].join("\n"));
const port = Number(values.get("port")?.at(-1) ?? "5179");
if (!Number.isSafeInteger(port) || port <= 0) invalidArguments("--port must be a positive integer");
- const distributionPackageRoot = videoCliDistribution.packageRoot ?? resolve(here, "../..");
- const domain = await loadStudioDomain({ run: runPath, workspaceRoot, packageRoot });
+ const distributionPackageRoot = application.distribution.packageRoot ?? resolve(here, "../..");
+ const domain = await loadStudioDomain({ run: runPath, workspaceRoot, packageRoot, distribution: application.distribution });
const registry = await loadStudioCompanionRegistry({
distributionPackageRoot,
- distributionPackages: videoStudioCompanionPackages,
sourcePackages: domain.packages,
});
- const buildLibrary = await openStudioBuildLibrary(runtimePath, packageRoot, workspaceRoot, distributionPackageRoot);
+ const buildLibrary = await openStudioBuildLibrary(
+ application.distribution,
+ runtimePath,
+ packageRoot,
+ workspaceRoot,
+ distributionPackageRoot,
+ );
let run;
try {
run = await loadStudioRun({
diff --git a/packages/studio/src/studio-preflight.ts b/packages/studio/src/studio-preflight.ts
index 80c53413..9b72da7a 100644
--- a/packages/studio/src/studio-preflight.ts
+++ b/packages/studio/src/studio-preflight.ts
@@ -1,7 +1,7 @@
-import type { Candidate } from "@hypit/protocol";
-import { sameType } from "@hypit/protocol";
-import type { StudioFilmCompanion } from "@hypit/studio-adapter";
-import { timelineTypes } from "@hypit/timeline";
+import type { Candidate } from "@hypit/hypit/protocol";
+import { sameType } from "@hypit/hypit/protocol";
+import type { StudioFilmCompanion } from "@hypit/studio-companion";
+import { timelineTypes } from "@hypit/hypit/timeline";
import type { CompiledSource } from "./compile.js";
import type { Placement } from "./observe.js";
diff --git a/packages/studio/src/studio-registry.ts b/packages/studio/src/studio-registry.ts
index 54ab8e79..61647bf8 100644
--- a/packages/studio/src/studio-registry.ts
+++ b/packages/studio/src/studio-registry.ts
@@ -14,17 +14,17 @@ import type {
StudioTemporalDomainSourceMap,
StudioSourceBindingDeclaration,
StudioSpan,
-} from "@hypit/studio-adapter";
-import { studioParameterControls } from "@hypit/studio-adapter";
+} from "@hypit/studio-companion";
+import { studioParameterControls } from "@hypit/studio-companion";
import { parameterOption } from "./parameter-values.js";
-import { compositionTypes } from "@hypit/composition";
-import { sameModule, sameType } from "@hypit/protocol";
-import type { ModuleRef, TypeRef } from "@hypit/protocol";
+import { compositionTypes } from "@hypit/hypit/composition";
+import { sameModule, sameType } from "@hypit/hypit/protocol";
+import type { ModuleRef, TypeRef } from "@hypit/hypit/protocol";
import type { Placement } from "./observe.js";
import type { Clip, StudioTrackBinding } from "./shared.js";
-export type { StudioEntityDraft, StudioViewRole, StudioSpan } from "@hypit/studio-adapter";
+export type { StudioEntityDraft, StudioViewRole, StudioSpan } from "@hypit/studio-companion";
const flatLane = {
heightPx: 52,
diff --git a/packages/studio/src/studio-trace.ts b/packages/studio/src/studio-trace.ts
index 1b566bc3..36b9b301 100644
--- a/packages/studio/src/studio-trace.ts
+++ b/packages/studio/src/studio-trace.ts
@@ -1,10 +1,10 @@
import type { CompiledSource } from "./compile.js";
import type { Placement } from "./observe.js";
import type { StudioCompanionRegistry } from "./studio-registry.js";
-import type { StudioViewRole, StudioTrackTrace } from "@hypit/studio-adapter";
-import type { TypeRef } from "@hypit/protocol";
+import type { StudioViewRole, StudioTrackTrace } from "@hypit/studio-companion";
+import type { TypeRef } from "@hypit/hypit/protocol";
-export type { StudioViewRole } from "@hypit/studio-adapter";
+export type { StudioViewRole } from "@hypit/studio-companion";
export type StudioTraceDependency = {
readonly name: string;
diff --git a/packages/studio/src/style.css b/packages/studio/src/style.css
index 435b3d9c..fa27ce23 100644
--- a/packages/studio/src/style.css
+++ b/packages/studio/src/style.css
@@ -1450,7 +1450,6 @@ button:focus-visible, textarea:focus-visible {
text-overflow: clip;
white-space: nowrap;
}
-.clip-phases { position: absolute; z-index: 3; inset: 0; overflow: hidden; pointer-events: none; }
.clip-phase { position: absolute; bottom: 0; height: 3px; border-left: 1px solid light-dark(rgba(0, 0, 0, .14), rgba(255, 255, 255, .17)); }
.clip-phase-active, .clip-phase-enter, .clip-phase-exit { background: light-dark(rgba(0, 0, 0, .2), rgba(255, 255, 255, .24)); }
.clip-phase-settled, .clip-phase-body { background: light-dark(rgba(0, 0, 0, .08), rgba(255, 255, 255, .10)); }
diff --git a/packages/studio/src/surface-preview.ts b/packages/studio/src/surface-preview.ts
index d69bb241..8c3e5896 100644
--- a/packages/studio/src/surface-preview.ts
+++ b/packages/studio/src/surface-preview.ts
@@ -1,4 +1,4 @@
-import type { SurfacePreview } from "@hypit/markup";
+import type { SurfacePreview } from "@hypit/hypit/markup";
import type { StudioDomain } from "./domain.js";
import type { StudioMaterialPreview } from "./shared.js";
diff --git a/packages/studio/src/temporal-edit.ts b/packages/studio/src/temporal-edit.ts
index db861a45..4a14a252 100644
--- a/packages/studio/src/temporal-edit.ts
+++ b/packages/studio/src/temporal-edit.ts
@@ -1,4 +1,4 @@
-import type { StudioEditHandle, StudioTemporalDomainAnchor, StudioTemporalDomainEditTarget, StudioTemporalInstantProjection } from "@hypit/studio-adapter";
+import type { StudioEditHandle, StudioTemporalDomainAnchor, StudioTemporalDomainEditTarget, StudioTemporalInstantProjection } from "@hypit/studio-companion";
export type DomainTarget = StudioTemporalDomainEditTarget;
diff --git a/packages/studio/src/temporal-graph.ts b/packages/studio/src/temporal-graph.ts
index 6b2baf2a..5c569610 100644
--- a/packages/studio/src/temporal-graph.ts
+++ b/packages/studio/src/temporal-graph.ts
@@ -1,11 +1,11 @@
-import { sameType } from "@hypit/protocol";
-import type { BuildState, ProducerStep, StoredValue, TypeRef, TypedRecord } from "@hypit/protocol";
-import { temporalModuleRef, temporalTypes } from "@hypit/temporal";
+import { sameType } from "@hypit/hypit/protocol";
+import type { BuildState, ProducerStep, StoredValue, TypeRef, TypedRecord } from "@hypit/hypit/protocol";
+import { temporalModuleRef, temporalTypes } from "@hypit/hypit/temporal";
import type {
StudioTemporalBinding,
StudioTemporalInstantProjection,
StudioTemporalProjection,
-} from "@hypit/studio-adapter";
+} from "@hypit/studio-companion";
type PointExpression = {
readonly ref?: string;
@@ -77,7 +77,14 @@ function instant(
readonly reference?: unknown;
readonly boundary?: unknown;
readonly offset?: unknown;
+ readonly author?: { readonly binding?: unknown; readonly relation?: unknown };
} | undefined;
+ const parameterAuthority = spec?.author !== undefined
+ && typeof spec.author.binding === "string"
+ && ["direct", "after-start", "before-end"].includes(String(spec.author.relation))
+ ? { kind: "parameter" as const, binding: spec.author.binding,
+ relation: spec.author.relation as "direct" | "after-start" | "before-end" }
+ : undefined;
if (step?.producer.module.name === temporalModuleRef.name
&& step.producer.module.version === temporalModuleRef.version
&& step.producer.name === "project-program-instant"
@@ -93,7 +100,21 @@ function instant(
frame: held.frame as number,
source: { timelineId: held.timelineId, type: timelineRecord?.type ?? record!.type,
kind: "timeline", id: typeof timeline?.id === "string" ? timeline.id : held.timelineId },
- authority: { kind: "fixed" },
+ authority: parameterAuthority ?? { kind: "fixed" },
+ };
+ }
+ if (step?.producer.module.name === temporalModuleRef.name
+ && step.producer.module.version === temporalModuleRef.version
+ && step.producer.name === "shift-instant"
+ && parameterAuthority !== undefined) {
+ return {
+ kind: "instant",
+ expression: `${held.frame as number}f`,
+ reference: "absolute",
+ frame: held.frame as number,
+ source: { timelineId: held.timelineId, type: record?.type ?? temporalTypes.instant,
+ kind: "resolved", id: held.id },
+ authority: parameterAuthority,
};
}
if (step !== undefined) {
diff --git a/packages/studio/src/ui/main.ts b/packages/studio/src/ui/main.ts
index 207cea44..019b7c4e 100644
--- a/packages/studio/src/ui/main.ts
+++ b/packages/studio/src/ui/main.ts
@@ -1,7 +1,7 @@
import { bindDropdown } from "./dropdown.js";
import { uiLabel, uiAttribute, uiText, uiAttr, userText, languageMenu, initializeI18n, type Message } from "./i18n.js";
import type { Clip, StudioFailure, StudioInspectorDomain, StudioSnapshot } from "../shared.js";
-import type { CanonicalValue, ValueSchema } from "@hypit/protocol";
+import type { CanonicalValue, ValueSchema } from "@hypit/hypit/protocol";
import { parameterAuthorValue, parameterControlForSchema, parameterNumber, parameterOption, parameterRecordSchema, parameterRecordVariants, validateParameterValue } from "../parameter-values.js";
import { createCodePane } from "./code.js";
import { icon } from "./icons.js";
diff --git a/packages/studio/src/ui/stage.ts b/packages/studio/src/ui/stage.ts
index 56a8cb08..57c12ed2 100644
--- a/packages/studio/src/ui/stage.ts
+++ b/packages/studio/src/ui/stage.ts
@@ -22,7 +22,7 @@ export type Stage = {
/**
* The picture.
*
- * The synthetic preview is the real HyperFrames document in an iframe, scrubbed
+ * The synthetic preview is the real HTML Program document in an iframe, scrubbed
* by pausing its animations and setting their time. The transport therefore
* drives frames, not seconds, and lands on exactly the frame the renderer would
* photograph.
diff --git a/packages/studio/src/ui/timeline.ts b/packages/studio/src/ui/timeline.ts
index c809fa71..ca01972f 100644
--- a/packages/studio/src/ui/timeline.ts
+++ b/packages/studio/src/ui/timeline.ts
@@ -1,6 +1,6 @@
import { userText, uiAttribute, uiText, uiAttr } from "./i18n.js";
import type { StudioSnapshot } from "../shared.js";
-import type { StudioEditHandle } from "@hypit/studio-adapter";
+import type { StudioEditHandle } from "@hypit/studio-companion";
import { icon, setIcon } from "./icons.js";
import { mountMaterialPreview } from "./material-preview.js";
import type { State, Store } from "./selection.js";
@@ -663,7 +663,7 @@ export function createTimeline(store: Store): Timeline {
const visibleWidthPx = visibleItemWidth(from, to, laneWidth);
node.classList.toggle("clip-preview-wide", visibleWidthPx >= 92);
node.title = `${clip.display.title} · ${clip.startFrame}-${clip.endFrameExclusive}f`;
- node.innerHTML = `<span class="clip-head"><span class="clip-name"></span><span class="clip-meta"></span></span><span class="clip-body"><span class="clip-layers" aria-hidden="true"></span><span class="clip-phases"></span></span><span class="clip-boundary" aria-hidden="true"></span><span class="clip-selection" aria-hidden="true"></span>`;
+ node.innerHTML = `<span class="clip-head"><span class="clip-name"></span><span class="clip-meta"></span></span><span class="clip-body"><span class="clip-layers" aria-hidden="true"></span></span><span class="clip-boundary" aria-hidden="true"></span><span class="clip-selection" aria-hidden="true"></span>`;
const layers = node.querySelector<HTMLElement>(".clip-layers")!;
clip.display.layers.forEach((layer, index) => {
const layerNode = document.createElement("span");
@@ -677,15 +677,6 @@ export function createTimeline(store: Store): Timeline {
}
layers.append(layerNode);
});
- const phaseLayer = node.querySelector<HTMLElement>(".clip-phases")!;
- for (const phase of clip.temporal?.phases ?? []) {
- if (phase.endFrameExclusive <= clip.startFrame || phase.startFrame >= clip.endFrameExclusive) continue;
- const phaseNode = document.createElement("span");
- phaseNode.className = `clip-phase clip-phase-${phase.role}`;
- phaseNode.style.left = `${(phase.startFrame - clip.startFrame) / Math.max(1, clip.endFrameExclusive - clip.startFrame) * 100}%`;
- phaseNode.style.width = `${(phase.endFrameExclusive - phase.startFrame) / Math.max(1, clip.endFrameExclusive - clip.startFrame) * 100}%`;
- phaseLayer.append(phaseNode);
- }
const metaText = clip.presentation.chrome === "point"
? `${(clip.startFrame / fps(snapshot)).toFixed(2)}s`
: `${((clip.endFrameExclusive - clip.startFrame) / fps(snapshot)).toFixed(2)}s`;
diff --git a/packages/studio/src/ui/zoom.ts b/packages/studio/src/ui/zoom.ts
index 11a15cf4..52fcddbf 100644
--- a/packages/studio/src/ui/zoom.ts
+++ b/packages/studio/src/ui/zoom.ts
@@ -1,9 +1,9 @@
/**
- * How much of the programme the timeline shows.
+ * How much of the composition the timeline shows.
*
* A sixteen-second Source fits; a three-minute one does not, and reading a
* cutaway that lasts twelve frames out of five thousand is not possible at one
- * pixel per forty frames. So the whole programme is drawn as a bar, and the
+ * pixel per forty frames. So the whole composition is drawn as a bar, and the
* part currently on the timeline is a window inside it - dragged to move, or
* taken by either edge to widen and narrow.
*/
@@ -12,16 +12,16 @@ export type Window = { readonly start: number; readonly end: number };
export type Zoom = {
readonly element: HTMLElement;
- /** The visible fraction of the programme, from 0 to 1. */
+ /** The visible fraction of the composition, from 0 to 1. */
window(): Window;
subscribe(listen: (window: Window) => void): void;
/** Zoom about a point, given as a fraction across the visible window. */
pinch(at: number, factor: number): void;
/** Slide the window by a fraction of its own width. */
slide(by: number): void;
- /** Show a particular programme interval, keeping it inside the strip. */
+ /** Show a particular composition interval, keeping it inside the strip. */
focus(start: number, end: number): void;
- /** Show the whole programme. */
+ /** Show the whole composition. */
fit(): void;
};
@@ -95,7 +95,7 @@ export function createZoom(): Zoom {
drag(endGrip, (at, began) => settle(began.start, Math.max(at, began.start + NARROWEST)));
// Clicking the bar outside the window centres the window there, which is the
- // fastest way across a long programme.
+ // fastest way across a long composition.
element.addEventListener("pointerdown", (event) => {
const width = window_.end - window_.start;
const at = fraction(event);
diff --git a/packages/studio/test/attribute-groups.test.ts b/packages/studio/test/attribute-groups.test.ts
index ae71cbf3..1d283b4e 100644
--- a/packages/studio/test/attribute-groups.test.ts
+++ b/packages/studio/test/attribute-groups.test.ts
@@ -2,8 +2,8 @@ import assert from "node:assert/strict";
import test from "node:test";
import { parseStructuredElement } from "@hypit/markup";
import { audioTrackModuleRef } from "@hypit/audio-track";
-import type { StudioPlacement, StudioEntityDraft, StudioTrackCompanion } from "@hypit/studio-adapter";
-import { audioTrackStudioTrackCompanions } from "../../audio-track-studio/src/index.js";
+import type { StudioPlacement, StudioEntityDraft, StudioTrackCompanion } from "@hypit/studio-companion";
+import { audioTrackStudioTrackCompanions } from "../../audio-track/src/studio.js";
import { sourceBindingsForDraft, inspectorFieldsForBindings } from "../src/parameters.js";
import { serializeAttributeGroup, validateParameterValue } from "../src/parameter-values.js";
diff --git a/packages/studio/test/audio-preview.test.ts b/packages/studio/test/audio-preview.test.ts
index a8617368..8efa4cb4 100644
--- a/packages/studio/test/audio-preview.test.ts
+++ b/packages/studio/test/audio-preview.test.ts
@@ -19,7 +19,8 @@ function player(gain: number, levelAutomation: object = {}) {
paused: true, volume: 0, muted: false, pause() { this.paused = true; },
play() { this.paused = false; return Promise.resolve(); }, addEventListener() {}, removeEventListener() {} };
const root = { style: {}, getAttribute: (name: string) => ({ "data-fps": "30", "data-composition-id": "test" })[name] ?? null };
- const window: Record<string, any> = { addEventListener() {}, dispatchEvent() {} };
+ const window: Record<string, any> = { addEventListener() {}, dispatchEvent() {},
+ __hypitFrameProgram: { async applyFrame() {} } };
const html = injectRuntimeShim("").trim();
vm.runInNewContext(html.slice("<script>".length, -"</script>".length), {
window, document: { querySelector: () => root, querySelectorAll: (selector: string) => selector === ".hypit-studio-audio" ? [audio] : [] },
diff --git a/packages/studio/test/build-library.test.ts b/packages/studio/test/build-library.test.ts
index 8e40bac5..2c1f0c3d 100644
--- a/packages/studio/test/build-library.test.ts
+++ b/packages/studio/test/build-library.test.ts
@@ -5,13 +5,16 @@ import { join } from "node:path";
import { pathToFileURL } from "node:url";
import test from "node:test";
-import { buildResultDirectory, FileBuildResultRepository } from "@hypit/build-result";
-import type { BuildResultRepository } from "@hypit/build-result";
-import type { BuildView } from "@hypit/runtime-host-node";
+import { buildResultDirectory, FileBuildResultRepository } from "@hypit/result/node";
+import type { BuildResultRepository } from "@hypit/result/node";
+import type { CliBuildView as BuildView } from "@hypit/cli";
import { buildIdCreatedAt } from "@hypit/protocol";
+import { createVideoDistribution } from "@hypit/video";
import { openStudioBuildLibrary, readStudioLibrary } from "../src/build-library.js";
+const videoDistribution = createVideoDistribution();
+
function activeBuild(id: string, root: string): BuildView {
return {
id,
@@ -34,8 +37,8 @@ test("Studio library joins this environment's Builds with project Build Result f
const manifests = [relevant, unrelated].map((entry) => ({
format: "hypit.build-result@1" as const,
id: entry.id,
- source: entry.source!,
- ...(entry.run === undefined ? {} : { run: entry.run }),
+ source: { id: entry.source!.path },
+ ...(entry.run === undefined ? {} : { run: { id: entry.run.path } }),
targets: ["final.video"],
finishedAt: entry.createdAt,
outcome: "complete" as const,
@@ -146,8 +149,8 @@ test("Studio opens project Build Results without a Runtime or ResourceStore", as
await writeFile(join(directory, "result.json"), `${JSON.stringify({
format: "hypit.build-result@1",
title: "First cut",
- source: { path: join(root, "main.svml") },
- run: { path: join(root, "build.svrun") },
+ source: { id: join(root, "main.svml") },
+ run: { id: join(root, "build.svrun") },
targets: ["final.video"],
finishedAt: 200,
outcome: "complete",
@@ -159,7 +162,7 @@ test("Studio opens project Build Results without a Runtime or ResourceStore", as
},
}, null, 2)}\n`, "utf8");
- const buildLibrary = await openStudioBuildLibrary(undefined, root, root);
+ const buildLibrary = await openStudioBuildLibrary(videoDistribution, undefined, root, root);
assert(buildLibrary !== undefined);
const view = await buildLibrary.library({ section: "tasks" });
assert.equal(view.runtime, undefined);
@@ -197,9 +200,9 @@ test("media listing includes active files, follows file references and leaves Co
const owner = "bld_20260902T130000010Z_0000000001";
const active = "bld_20260902T130000011Z_0000000001";
const image = { type: mediaTypeRef, value: { kind: "build-file" as const, path: "files/portrait.png", mediaType: "image/png", size: 100 } };
- const manifests: import("@hypit/build-result").BuildResultManifest[] = [{
- format: "hypit.build-result@1", id: owner, source: { path: "/project/main.svml" },
- run: { path: "/project/earlier.svrun" }, targets: ["portrait.image"], outcome: "failed", finishedAt: 300,
+ const manifests: import("@hypit/result").BuildResultManifest[] = [{
+ format: "hypit.build-result@1", id: owner, source: { id: "/project/main.svml" },
+ run: { id: "/project/earlier.svrun" }, targets: ["portrait.image"], outcome: "failed", finishedAt: 300,
failure: "Rendering failed", highlightedOutputs: ["portrait.image"],
outputs: {
"portrait.image": image,
@@ -208,8 +211,8 @@ test("media listing includes active files, follows file references and leaves Co
"semantic.take": { type: mediaTypeRef, value: { kind: "value", path: "values/semantic.json" } },
},
}, {
- format: "hypit.build-result@1", id: active, source: { path: "/project/main.svml" },
- run: { path: "/project/current.svrun" }, targets: ["final.video"],
+ format: "hypit.build-result@1", id: active, source: { id: "/project/main.svml" },
+ run: { id: "/project/current.svrun" }, targets: ["final.video"],
outputs: {
"reused.image": { type: mediaTypeRef, value: { kind: "build-output", build: owner, output: "portrait.image" } },
"voice.audio": { type: mediaTypeRef, value: { kind: "build-file", path: "files/voice.wav", mediaType: "audio/wav", size: 80 } },
@@ -224,7 +227,7 @@ test("media listing includes active files, follows file references and leaves Co
async removeIncomplete() { throw new Error("read-only"); },
async updatePresentation() { throw new Error("read-only"); },
async read(build) { return manifests.find((item) => item.id === build); },
- async browse() { return { results: [manifests[0] as import("@hypit/build-result").FinishedBuildResultManifest] }; },
+ async browse() { return { results: [manifests[0] as import("@hypit/result").FinishedBuildResultManifest] }; },
async describeOutput(_build, output) {
described.push(output);
if (output === "reused.take") return { kind: "composite", type: mediaTypeRef };
@@ -280,7 +283,7 @@ test("Studio groups repeated external file references and retains both Build use
const results = new FileBuildResultRepository(join(root, "results"));
const type = { module: { name: "example", version: "1" }, name: "Image" };
for (const id of ["bld_20260902T130000000Z_0000000001", "bld_20260902T130000001Z_0000000001"]) {
- const writer = await results.create({ id, source: { path: join(root, "main.svml") },
+ const writer = await results.create({ id, source: { id: join(root, "main.svml") },
targets: ["portrait"], publishedOutputs: [{ name: "portrait", output: "portrait" }],
resourceReferences: { res_image: { kind: "external-file", uri: pathToFileURL(imagePath).href,
size: 2, mediaType: "image/png" } } });
diff --git a/packages/studio/test/companion-assembly.test.ts b/packages/studio/test/companion-assembly.test.ts
index 2e60522a..fc1104d7 100644
--- a/packages/studio/test/companion-assembly.test.ts
+++ b/packages/studio/test/companion-assembly.test.ts
@@ -2,7 +2,7 @@ import assert from "node:assert/strict";
import test from "node:test";
import { compositionTypes } from "@hypit/composition";
-import { createStudioTrackCompanionHostFacet } from "@hypit/studio-adapter";
+import { createStudioTrackCompanionFacet } from "@hypit/studio-companion";
import { loadStudioCompanionRegistry } from "../src/companion-assembly.js";
@@ -10,12 +10,11 @@ test("a Source-selected package contributes its Companion without a second Studi
const module = { name: "@project/cards", version: "1" } as const;
const registry = await loadStudioCompanionRegistry({
distributionPackageRoot: process.cwd(),
- distributionPackages: [],
sourcePackages: [{
specifier: "@project/cards",
contribution: {
- format: "hypit.node-package@1",
- hostFacets: [createStudioTrackCompanionHostFacet([{
+ format: "hypit.package@1",
+ facets: [createStudioTrackCompanionFacet([{
id: "cards",
role: "track",
family: "cards",
diff --git a/packages/studio/test/material-companions.test.ts b/packages/studio/test/material-companions.test.ts
index 0aaa4144..92f6a532 100644
--- a/packages/studio/test/material-companions.test.ts
+++ b/packages/studio/test/material-companions.test.ts
@@ -3,9 +3,9 @@ import test from "node:test";
import { compositionTypes } from "@hypit/composition";
import { audioTrackTypes } from "@hypit/audio-track";
import { visualTrackTypes } from "@hypit/visual-track";
-import type { StudioTrackCompanionContext } from "@hypit/studio-adapter";
-import { audioTrackStudioTrackCompanions } from "../../audio-track-studio/src/index.js";
-import { visualTrackStudioTrackCompanions } from "../../visual-track-studio/src/index.js";
+import type { StudioTrackCompanionContext } from "@hypit/studio-companion";
+import { audioTrackStudioTrackCompanions } from "../../audio-track/src/studio.js";
+import { visualTrackStudioTrackCompanions } from "../../visual-track/src/studio.js";
for (const kind of ["audio", "visual"] as const) {
test(`${kind} Clip titles use explicit author names or exact source references without changing identity`, () => {
diff --git a/packages/studio/test/parameter-companions.test.ts b/packages/studio/test/parameter-companions.test.ts
index 65d3500f..0b62005c 100644
--- a/packages/studio/test/parameter-companions.test.ts
+++ b/packages/studio/test/parameter-companions.test.ts
@@ -1,7 +1,7 @@
import assert from "node:assert/strict";
import test from "node:test";
-import type { StudioPlacement, StudioEntityDraft, StudioParameterCompanion } from "@hypit/studio-adapter";
-import { studioContributionFromPackage, createStudioCompanionHostFacet } from "@hypit/studio-adapter";
+import type { StudioPlacement, StudioEntityDraft, StudioParameterCompanion } from "@hypit/studio-companion";
+import { studioContributionFromPackage, createStudioCompanionFacet } from "@hypit/studio-companion";
import { composeParameterDeclarations, sourceBindingsForDraft, inspectorFieldsForBindings } from "../src/parameters.js";
import { StudioCompanionRegistry } from "../src/studio-registry.js";
import { parameterAuthorValue, serializeParameterValue } from "../src/parameter-values.js";
@@ -20,7 +20,7 @@ function placement(id: string, start: number, end: number): StudioPlacement {
attributes: { id }, attributeValueRanges: {}, references: [], referenceAttributes: {}, referenceTypes: {} };
}
test("a project object contributes its own parameters to a consumer and inserts an omitted scalar on first edit", () => {
- const contribution = studioContributionFromPackage("@project/pan", [createStudioCompanionHostFacet({ parameters: [companion] })]);
+ const contribution = studioContributionFromPackage("@project/pan", [createStudioCompanionFacet({ parameters: [companion] })]);
const registry = new StudioCompanionRegistry([], { parameters: contribution.parameters });
const split = text.indexOf('<p:Pan');
const owner = { ...placement("view", 0, split), referenceAttributes: { style: "pan" }, resolvedReferenceAttributes: { style: "pan" } };
diff --git a/packages/studio/test/parameter-values.test.ts b/packages/studio/test/parameter-values.test.ts
index ac65e9d8..dcaf6535 100644
--- a/packages/studio/test/parameter-values.test.ts
+++ b/packages/studio/test/parameter-values.test.ts
@@ -1,6 +1,6 @@
import assert from "node:assert/strict";
import test from "node:test";
-import type { StudioInspectorField } from "@hypit/studio-adapter";
+import type { StudioInspectorField } from "@hypit/studio-companion";
import { parameterAuthorValue, parameterControlForSchema, parameterNumber, parameterOption, serializeParameterValue, validateParameterValue } from "../src/parameter-values.js";
const field = (overrides: Partial<StudioInspectorField>): StudioInspectorField => ({
diff --git a/packages/studio/test/parameters.test.ts b/packages/studio/test/parameters.test.ts
index 1610c9d5..001bb690 100644
--- a/packages/studio/test/parameters.test.ts
+++ b/packages/studio/test/parameters.test.ts
@@ -5,7 +5,7 @@ import type {
StudioPlacement,
StudioTemporalDomainView,
StudioTemporalLineage,
-} from "@hypit/studio-adapter";
+} from "@hypit/studio-companion";
import type { MarkupSurfaceRegistryLike, RegisteredSurface } from "@hypit/markup";
import { inspectorFieldsForBindings, resolveTimelineEditHandles, sourceBindingsForDraft } from "../src/parameters.js";
@@ -68,7 +68,6 @@ test("timeline gestures resolve through the shared Selection identity", () => {
startFrame: 0,
endFrameExclusive: 12,
},
- phases: [],
};
const handles = resolveTimelineEditHandles([], temporal, [temporalDomain]);
@@ -91,7 +90,6 @@ test("moving a Moment projection resolves to the shared Moment identity", () =>
source: { ...narrativeSourceIdentity, kind: "moment", id: "beat" },
authority: { kind: "domain", source: { ...narrativeSourceIdentity, kind: "moment", id: "beat" }, boundary: "cue" },
},
- phases: [],
}, [withMoment]);
assert.deepEqual(handles.map((handle) => [handle.gesture, handle.enabled]), [["move", true]]);
@@ -122,7 +120,7 @@ test("at/for and until/for derive complementary semantic and duration inverses",
authority: { kind: "parameter" as const, binding: "for", relation: "before-end" as const },
};
const atFor = resolveTimelineEditHandles([duration], {
- projection: { kind: "window", start: moment, end: after, startFrame: 12, endFrameExclusive: 20 }, phases: [],
+ projection: { kind: "window", start: moment, end: after, startFrame: 12, endFrameExclusive: 20 },
}, [withMoment]);
assert.deepEqual(atFor.map((handle) => [handle.gesture, handle.domain?.kind, handle.sources?.map((source) => source.role)]), [
["move", "point", undefined],
@@ -130,7 +128,7 @@ test("at/for and until/for derive complementary semantic and duration inverses",
]);
const untilFor = resolveTimelineEditHandles([duration], {
- projection: { kind: "window", start: before, end: moment, startFrame: 4, endFrameExclusive: 12 }, phases: [],
+ projection: { kind: "window", start: before, end: moment, startFrame: 4, endFrameExclusive: 12 },
}, [withMoment]);
assert.deepEqual(untilFor.map((handle) => [handle.gesture, handle.domain?.kind, handle.sources?.map((source) => source.role)]), [
["move", "point", undefined],
@@ -170,7 +168,6 @@ test("absolute Window edits work without a semantic lane and use the Companion's
},
startFrame: 1, endFrameExclusive: 20,
},
- phases: [],
},
undefined,
);
@@ -202,7 +199,7 @@ test("independent reference endpoints expose local edits without claiming their
}));
const handles = resolveTimelineEditHandles(bindings, { projection: {
kind: "window", start: endpoints[0]!, end: endpoints[1]!, startFrame: 2, endFrameExclusive: 20,
- }, phases: [] }, [temporalDomain]);
+ } }, [temporalDomain]);
assert.deepEqual(handles.map(({ gesture, enabled, domain, sources }) => ({ gesture, enabled, domain, roles: sources?.map(source => source.role) })), [
{ gesture: "move", enabled: true, domain: undefined, roles: ["start", "end"] },
{ gesture: "trim-start", enabled: true, domain: undefined, roles: ["start"] },
@@ -272,7 +269,7 @@ test("nested declared references reach the font attribute, not the referring Sty
test("a derived entity follows its actual Style and Companion-owned Recipe presentation", () => {
const main = "<scene:Track id=\"captions\" layout={baseline-layout}/>";
- const sheet = `<?svml using="@hypit/svs@1"?>
+ const sheet = `<?svml using="@hypit/recipe@1"?>
<sheet version="1">
caption.alt { x: 0.4; handoff: overlap; colors: ["#FF3F56", "#FFA72D"]; }
</sheet>`;
diff --git a/packages/studio/test/preflight.test.ts b/packages/studio/test/preflight.test.ts
index 3959b7e4..ed7b9379 100644
--- a/packages/studio/test/preflight.test.ts
+++ b/packages/studio/test/preflight.test.ts
@@ -3,7 +3,7 @@ import assert from "node:assert/strict";
import test from "node:test";
import { compositionTypes } from "@hypit/composition";
-import type { StudioFilmCompanion, StudioPlacement } from "@hypit/studio-adapter";
+import type { StudioFilmCompanion, StudioPlacement } from "@hypit/studio-companion";
import type { CompiledSource } from "../src/compile.js";
import type { RunPlan } from "../src/run.js";
diff --git a/packages/studio/test/provenance.test.ts b/packages/studio/test/provenance.test.ts
index 925ccfa7..4f7ce4bf 100644
--- a/packages/studio/test/provenance.test.ts
+++ b/packages/studio/test/provenance.test.ts
@@ -1,8 +1,8 @@
import assert from "node:assert/strict";
import test from "node:test";
-import type { NodeCompiledSourceClosure } from "@hypit/compiler-node";
-import type { StudioPlacement } from "@hypit/studio-adapter";
+import type { CompiledAuthorSource } from "@hypit/compiler";
+import type { StudioPlacement } from "@hypit/studio-companion";
import { observedCompiledSource } from "../src/compile.js";
import { outputFor, placementFor } from "../src/studio-trace.js";
@@ -53,7 +53,7 @@ test("Studio joins repeated local names through compiler-owned provenance", asyn
element("b.svml", "b::output::visual"),
] },
attachments: [],
- } as unknown as NodeCompiledSourceClosure;
+ } as unknown as CompiledAuthorSource;
const source = await observedCompiledSource(compiled, {
placements: [placement("a.svml"), placement("b.svml")],
temporalDomains: [],
diff --git a/packages/studio/test/registry.test.ts b/packages/studio/test/registry.test.ts
index 9ad038dd..7426f924 100644
--- a/packages/studio/test/registry.test.ts
+++ b/packages/studio/test/registry.test.ts
@@ -2,7 +2,7 @@ import assert from "node:assert/strict";
import test from "node:test";
import { compositionTypes } from "@hypit/composition";
-import type { StudioTrackCompanion } from "@hypit/studio-adapter";
+import type { StudioTrackCompanion } from "@hypit/studio-companion";
import { StudioCompanionRegistry } from "../src/studio-registry.js";
diff --git a/packages/studio/test/semantic-gesture.test.ts b/packages/studio/test/semantic-gesture.test.ts
index 58d099c4..434c48d0 100644
--- a/packages/studio/test/semantic-gesture.test.ts
+++ b/packages/studio/test/semantic-gesture.test.ts
@@ -1,9 +1,9 @@
import assert from "node:assert/strict";
import test from "node:test";
-import type { StudioEditHandle, StudioTemporalDomainAnchor, StudioTemporalInstantProjection } from "@hypit/studio-adapter";
+import type { StudioEditHandle, StudioTemporalDomainAnchor, StudioTemporalInstantProjection } from "@hypit/studio-companion";
import { adjustScriptSelection, parseScript } from "@hypit/script";
import { projectProgramInstant } from "@hypit/temporal";
-import { parseTemporalInstant } from "@hypit/temporal-markup";
+import { parseTemporalInstant } from "@hypit/temporal/markup";
import { chooseDomainGesture, formatTemporalPointEdit, domainGestureSpan } from "../src/temporal-edit.js";
const source = '<one><HOST>@{proof} One two @{/proof} three.</one>';
diff --git a/packages/studio/test/snapshot-cli.test.ts b/packages/studio/test/snapshot-cli.test.ts
new file mode 100644
index 00000000..05c71970
--- /dev/null
+++ b/packages/studio/test/snapshot-cli.test.ts
@@ -0,0 +1,65 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import { mkdtemp, readFile, readdir, rm } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import sharp from "sharp";
+import { canonicalize } from "@hypit/protocol";
+import { verifyHtmlFrameRequest } from "@hypit/html-program";
+import type { CliApplicationContext, CliRuntimeHost } from "@hypit/cli";
+import { runSnapshotCli, studioDocumentUrl } from "../src/snapshot-cli.js";
+
+test("snapshot --studio requires an absolute HTTP URL", () => {
+ assert.equal(studioDocumentUrl("http://localhost:5191"), "http://localhost:5191/__studio/document");
+ assert.throws(() => studioDocumentUrl("localhost:5191"), /--studio needs an http\(s\) Studio URL/u);
+});
+
+test("Studio snapshots pass one typed HTML Program and only its selected Artifacts", async t => {
+ const directory = await mkdtemp(join(tmpdir(), "hypit-studio-snapshot-"));
+ const bytes = await sharp({ create: { width: 96, height: 64, channels: 3, background: "red" } }).png().toBuffer();
+ const artifact = { kind: "blob" as const, resource: "res_program_image" as const, size: bytes.length, mediaType: "image/png" };
+ const late = { kind: "blob" as const, resource: "res_late_image" as const, size: 123, mediaType: "image/png" };
+ const program = { visualIr: "hypit.visual-ir@1", frameRate: { numerator: 30000, denominator: 1001 }, frameCount: 12,
+ canvas: { width: 96, height: 64 }, artifacts: [
+ { artifact: late, usage: { kind: "frames" as const, spans: [{ startFrame: 10, endFrameExclusive: 12 }] } },
+ { artifact, usage: { kind: "always" as const } },
+ ], surfaces: [], frameSources: [],
+ html: '<!doctype html><div data-hypit-program-root data-hypit-frame-count="12"><script>const input="hypit-resource://res_program_image";</script><img data-hypit-resource-src="hypit-resource://res_late_image"></div>' };
+ const fetched: string[] = [];
+ t.mock.method(globalThis, "fetch", async (input: string | URL) => {
+ const url = String(input);
+ fetched.push(url);
+ if (url.endsWith("/__studio/document")) return Response.json(program);
+ if (url.endsWith("/__studio/material/res_program_image")) return new Response(bytes);
+ throw new Error(`Unexpected read ${url}`);
+ });
+ try {
+ const host = {
+ providers: async requests => requests.map(request => ({ request: request.request, capability: request.capability,
+ status: "resolved", endpoint: "frames", use: "@example/frames" })),
+ invoke: async (need, resources) => {
+ assert.equal(need.capability.name, "rasterize-frames");
+ verifyHtmlFrameRequest(need.constraints);
+ assert.deepEqual(need.constraints.program, program);
+ assert.deepEqual(need.constraints.frames, [3]);
+ assert.deepEqual(Buffer.from((await resources.get(artifact.resource))!), bytes);
+ return { value: { kind: "inline", value: canonicalize([await resources.put(bytes, "image/png")]) } };
+ },
+ } as Pick<CliRuntimeHost, "providers" | "invoke">;
+ const application = {
+ cwd: directory,
+ resolveProjectRoot: async () => directory,
+ distribution: {
+ resolveProjectRuntime: async () => ({ profile: "selected.json" }),
+ openRuntimeHost: async () => host as CliRuntimeHost,
+ },
+ } as unknown as CliApplicationContext;
+ let output = "";
+ await runSnapshotCli(["snapshot", "--studio", "http://studio.example:5191/#comments", "--at-frame", "3", "--to", "evidence"],
+ { write(text) { output += text; } }, application);
+ assert.deepEqual(fetched, ["http://studio.example:5191/__studio/document", "http://studio.example:5191/__studio/material/res_program_image"]);
+ assert.deepEqual(await readFile(join(directory, "evidence", "frame-000000003.png")), bytes);
+ assert.deepEqual(await readdir(join(directory, "evidence")), ["frame-000000003.png"]);
+ assert.match(output, /Captured 1 PNG/u);
+ } finally { await rm(directory, { recursive: true, force: true }); }
+});
diff --git a/packages/studio/test/snapshot-range.test.ts b/packages/studio/test/snapshot-range.test.ts
index 51eb176a..e2bc1aa1 100644
--- a/packages/studio/test/snapshot-range.test.ts
+++ b/packages/studio/test/snapshot-range.test.ts
@@ -2,7 +2,7 @@ import assert from "node:assert/strict";
import test from "node:test";
import { compositionTypes } from "@hypit/composition";
import { snapshot } from "../src/snapshot.js";
-import type { Preview } from "../src/programme.js";
+import type { StudioProjection } from "../src/projection.js";
import { StudioCompanionRegistry } from "../src/studio-registry.js";
import { fallbackStudioTrackCompanions } from "../src/fallback-companions.js";
@@ -12,11 +12,11 @@ test("a pure-MG work keeps its declared extent even when an editor entity extend
trace: { outputPorts: [], references: [] }, candidateOrigin: "source", value: { presents: [{ id: "scene", order: 0, z: 0, span: { startFrame: 0, endFrameExclusive: 150 } }] } }],
timeline: { id: "work", frameCount: 90, frameRate: { numerator: 30, denominator: 1 } },
values: new Map(), temporalBindings: new Map(),
- } as unknown as Preview;
+ } as unknown as StudioProjection;
const result = snapshot(new StudioCompanionRegistry(fallbackStudioTrackCompanions), built, {
revision: 1, path: "main.svml", text: "", run: { path: "main.svrun", targets: [], satisfactions: [] },
canvas: { width: 1080, height: 1920, clearColor: "#000000" }, frameRate: built.timeline.frameRate,
- preview: { kind: "hyperframes", srcdoc: "" }, workspaceRoot: "/project", sourceFiles: [], surfaces: {} as never,
+ preview: { kind: "html-program", srcdoc: "" }, workspaceRoot: "/project", sourceFiles: [], surfaces: {} as never,
});
assert.equal(result.timeline.frameCount, 90); assert.equal(result.timeline.durationSec, 3);
assert.equal(result.tracks[0]!.clips[0]!.endFrameExclusive, 150);
diff --git a/packages/studio/test/temporal-graph.test.ts b/packages/studio/test/temporal-graph.test.ts
index ae6ee524..29968b5e 100644
--- a/packages/studio/test/temporal-graph.test.ts
+++ b/packages/studio/test/temporal-graph.test.ts
@@ -75,3 +75,57 @@ test("Studio reads Instant lineage and author authority from executed graph edge
}],
});
});
+
+test("Studio reads author parameter authority declared by the Temporal Spec", () => {
+ const program = [
+ record("timeline", "@hypit/timeline", "Timeline", {
+ id: "main", frameRate: { numerator: 30, denominator: 1 }, frameCount: 100,
+ }),
+ record("point-spec", "@hypit/temporal", "TemporalInstantSpec", {
+ id: "card.activation", subjectId: "card",
+ projection: { ref: "absolute", at: { unit: "frames", value: 42 } },
+ author: { binding: "at", relation: "direct" },
+ }),
+ record("card-spec", "@hypit/depth-stack", "DepthStackCardSpec", { id: "card" }),
+ ];
+ const executed = [
+ record("point", "@hypit/temporal", "TemporalInstant", {
+ id: "card.activation", subjectId: "card", timelineId: "main", frame: 42,
+ }),
+ record("cards", "@hypit/depth-stack", "DepthStackCardSet", { cards: [{ id: "card", activationFrame: 42 }] }),
+ record("track", "@hypit/composition", "VisualTrack", { presents: [] }),
+ ];
+ const steps = [
+ step("project", "@hypit/temporal", "project-program-instant", { timeline: "timeline", spec: "point-spec" }, { instant: "point" }),
+ step("append", "@hypit/depth-stack", "append-depth-stack-card", { set: "empty", spec: "card-spec", activation: "point" }, { set: "cards" }),
+ step("render", "@hypit/depth-stack", "render-depth-stack", { program: "cards" }, { track: "track" }),
+ ];
+ const state = {
+ format: "hypit.build@1",
+ program: { closure: { modules: [] }, records: program },
+ targets: [{ output: "visual" }],
+ plan: {
+ format: "hypit.plan@1", steps,
+ goals: [{ record: "track", type: type("@hypit/composition", "VisualTrack") }],
+ outputBindings: [{ output: "visual", record: "track", type: type("@hypit/composition", "VisualTrack") }],
+ },
+ status: "complete", records: executed, steps: steps.map(({ id }) => ({ id, status: "complete" as const })),
+ needs: [], outstanding: [], diagnostics: [],
+ } as unknown as BuildState;
+
+ const bindings = executedTemporalBindings(state, "visual");
+ assert.equal(bindings.length, 1);
+ assert.deepEqual(bindings[0]?.projection, {
+ kind: "instant",
+ expression: "42f",
+ reference: "absolute",
+ frame: 42,
+ source: {
+ timelineId: "main",
+ type: type("@hypit/timeline", "Timeline"),
+ kind: "timeline",
+ id: "main",
+ },
+ authority: { kind: "parameter", binding: "at", relation: "direct" },
+ });
+});
diff --git a/packages/studio/test/video-preview.test.ts b/packages/studio/test/video-preview.test.ts
index 8ac62dfd..5766852b 100644
--- a/packages/studio/test/video-preview.test.ts
+++ b/packages/studio/test/video-preview.test.ts
@@ -20,7 +20,8 @@ test("preview scrubs to the same source frame as rendering at fractional sample
removeEventListener(name: string) { listeners.delete(name); },
};
const root = { style: {}, getAttribute: (name: string) => ({ "data-fps": "30", "data-composition-id": "test" })[name] ?? null };
- const window: Record<string, any> = { addEventListener() {}, dispatchEvent() {} };
+ const window: Record<string, any> = { addEventListener() {}, dispatchEvent() {},
+ __hypitFrameProgram: { async applyFrame() {} } };
const html = injectRuntimeShim("").trim();
vm.runInNewContext(html.slice("<script>".length, -"</script>".length), {
window, document: { querySelector: () => root,
@@ -54,7 +55,8 @@ test("preview keeps a compact zero-rate sampling interval paused on its source f
removeEventListener(name: string) { listeners.delete(name); },
};
const root = { style: {}, getAttribute: (name: string) => ({ "data-fps": "30", "data-composition-id": "test" })[name] ?? null };
- const window: Record<string, any> = { addEventListener() {}, dispatchEvent() {} };
+ const window: Record<string, any> = { addEventListener() {}, dispatchEvent() {},
+ __hypitFrameProgram: { async applyFrame() {} } };
const html = injectRuntimeShim("").trim();
vm.runInNewContext(html.slice("<script>".length, -"</script>".length), {
window, document: { querySelector: () => root,
@@ -89,7 +91,8 @@ test("preview evaluates reverse source time by absolute frame without assigning
removeEventListener(name: string) { listeners.delete(name); },
};
const root = { style: {}, getAttribute: (name: string) => ({ "data-fps": "30", "data-composition-id": "test" })[name] ?? null };
- const window: Record<string, any> = { addEventListener() {}, dispatchEvent() {} };
+ const window: Record<string, any> = { addEventListener() {}, dispatchEvent() {},
+ __hypitFrameProgram: { async applyFrame() {} } };
const html = injectRuntimeShim("").trim();
vm.runInNewContext(html.slice("<script>".length, -"</script>".length), {
window, document: { querySelector: () => root,
diff --git a/packages/video-cli/README.md b/packages/video-cli/README.md
deleted file mode 100644
index f7c1b061..00000000
--- a/packages/video-cli/README.md
+++ /dev/null
@@ -1,273 +0,0 @@
-# `@hypit/video-cli`
-
-Official video command application. It selects the Markup compiler Host and supplies one editable
-starter Runtime Profile. Execution Endpoints are selected by Profile `use` entries; Source imports
-activate author packages. Immediate tools own their temporary input/output resource storage.
-
-Every Frontend, Surface, deterministic Producer and Validator is activated from Source imports.
-Installing a new author package therefore does not require a video CLI or Core release. Source
-imports never grant network, credential or process authority. A data-only package can also export a
-reusable Source directly, for example
-`<import as="ugc" source="@hypit/gpt-image-kits/phone-ugc-v1"/>`; resolving that Source does not
-activate package code.
-
-`hypit version` reports the Distribution version, physical root and launcher independently of a
-project or Runtime. `hypit version --check` also reads the package's `latest` tag at
-`https://registry.npmjs.org/`; `--registry <url>` explicitly selects another registry. `--json`
-returns `hypit.cli-version@1`. A failed check retains local facts, leaves the remote version unknown
-and exits nonzero. A different version is not automatically newer: the launcher may be a newer
-checkout or the mirror may lag. The command links release notes and never installs or updates.
-Skill installers own their separate installed copies; this command does not scan Agent directories.
-`hypit --version` remains a local version-only query.
-
-Commands below serve independent authoring decisions. Start with the current project's material;
-local inspection and estimation need no generation account:
-
-```bash
-cd path/to/project
-hypit check main.svml
-hypit measure main.svml --segment hook --language en
-```
-
-When the work needs execution, the project selects a Runtime Profile. `hypit runtime init` creates
-an editable starter; its Endpoint entries describe available routes, not choices made by the user.
-Keep an existing chosen service, or configure the chosen local or hosted Provider and its capability
-bindings. HypiHub is the recommended integrated hosted route in the official Distribution; other
-services use project Provider packages. If the user chooses HypiHub,
-`hypit auth login hypihub.default` connects that account after choosing its CredentialStore.
-The starter selects the [platform CredentialStore](../credential-store-platform/README.md#select-it):
-macOS Keychain or Windows Credential Locker on those two platforms, and an owner-private file on
-Linux, so the Profile it writes needs no edit on any of them. Name another Store in `credentials` and
-in the Endpoint's credential reference — as the
-[file CredentialStore](../credential-store-file/README.md#select-it-before-login) shows — to choose it
-explicitly. This selection is configuration; execution never switches stores automatically.
-`hypit doctor --endpoint <name>` checks a selected Endpoint;
-`hypit runtime up --endpoint <name>` prepares that Endpoint and starts the Worker. Repeat the flag
-for several chosen Endpoints; omitting it prepares the whole Profile. `hypit programs up --endpoint
-<name>` prepares and starts a local helper independently of the Worker. `hypit programs prepare
---endpoint <name>` only prepares its selected resources, including for a service already running.
-
-With the selected execution environment:
-
-```bash
-hypit plan build.svrun
-hypit build build.svrun --follow
-hypit status <build-id> --watch
-hypit activity
-hypit builds
-hypit history <source-output-name> [--source ./main.svml]
-hypit inspect <build-id> [--output <source-output-name>]
-hypit get <build-id> --output final.video --to ./final.mp4
-hypit cancel <build-id>
-```
-
-`transcribe` runs one immediate request through the selected Runtime Profile, with no Build,
-Result or state. It names the Endpoint and its price page before it runs, and writes the transcript
-to the chosen file. `measure` estimates a passage locally:
-
-```bash
-hypit transcribe reference.mp4 --to notes/reference.transcript.json --language en
-hypit transcribe assets/recorded-voice.wav --to notes/voice.transcript.json --language en
-hypit measure main.svml --segment hook --language en --pace normal --rounding round
-```
-
-`snapshot` follows the same immediate invocation model for picture inspection. Prefer it for
-existing production states and motion sequences, keeping Studio for playback with sound and Builds
-for encoded delivery:
-
-```bash
-hypit snapshot --studio http://localhost:5191 --at-frame 240,255,269 --to evidence/states
-hypit snapshot --studio http://localhost:5191 --start-frame 240 --end-frame-exclusive 270 \
- --grid 4x3 --cell 480 --to evidence/motion
-hypit snapshot ./picture/index.html --at-frame 240 --to evidence/detail
-```
-
-`--studio` reads Studio's current compiled document and its declared resources; a path or HTML URL
-reads materialized HTML with inline scripts/styles and directly addressed media/fonts. The Profile's
-`@hypit/render-hyperframes@1#render-frames` Endpoint returns PNGs in selected-frame order.
-`--runtime` and `--workspace` select the environment just as for `transcribe`. The call streams
-resources through a temporary `FileResourceStore`, writes full-size PNGs and optional grid pages,
-then releases that temporary storage. `--to` names a new directory. `--json` reports paths and original
-frame positions. Grid labels remain outside the picture. No Build, Worker receipt or video encoding
-is created. Provider-owned browser preparation is unchanged.
-
-`media frames --every-frame` and `media tiles --every-frame` decode every source frame in a selected
-half-open seconds interval once. Native timestamps, including variable frame rate, are read from
-decoder PTS and time base. `tiles --ranges <json> --every-frame` decodes each listed interval and
-paginates its images. `--transcript` adds word context. This native path uses no FPS resampling.
-
-For `transcribe`, set `--language` to an explicit lowercase two- or three-letter spoken language code,
-such as `en`, `zh` or `ko`. The selected service owns which languages it can align. Chinese speech uses `zh`, including
-Chinese speech containing English names. The request selects the recognition language and
-language-specific aligner; ASR size remains a deployment choice. Caption font and Script's
-simplified/traditional characters are independent authoring choices.
-
-`transcribe` uses the Profile's `whisperx-alignment` Endpoint (after
-extracting 16 kHz mono speech audio with ffmpeg). Direct invocation forwards the Provider's progress
-and diagnostic callbacks; the CLI reports phase changes while waiting, with JSON progress on the
-separate progress stream when supplied. Immediate invocation has no durable remote task receipt and
-does not become resumable merely because it reports progress. `measure` counts a Segment's pronunciation units at a
-delivery policy and prints estimated seconds, the resolved rate, padding and rounding. Choose the
-literal `duration` from that estimate and the intended performance. `measure` opens no Profile and
-spends nothing. It accepts `--pace slow|normal|fast` or `--rate <units/s>`; JSON includes the resolved
-`rate` even when using a named pace. [Estimate](../estimate/README.md#units-and-delivery) explains
-Chinese/English units and choosing a whole-passage density.
-
-For `transcribe`, `--runtime <profile>` names the Profile; otherwise the project's `hypit runtime use`
-selection is read. Anything the Author Graph declares as an output is a Build, however quickly it
-comes back: pictures, clips and accepted voice references (`@hypit/mimo-speech`) carry the identity of the Source
-that produced them, so they are declared in the Source and go through `plan` and `build`. To hear a
-voice or learn a passage's real length before authoring the rest, build a Run whose target is that
-speech output and reuse it as a Candidate.
-
-Provider selection is checked before `transcribe` invokes the service. Multiple matching Endpoints
-can remain in the Profile: `bindings` chooses one for the capability. An unsupported request reports
-the selected binding and Provider-owned rejection reasons so the author can adjust the request or
-choose a compatible Endpoint. It does not imply that an account needs payment or login.
-
-Two more families are local, stateless and spend nothing. `hypit media` exposes the source at chosen
-times and scales, and `hypit vocabulary`
-prints what a Source may write:
-
-```bash
-hypit media probe reference.mp4
-hypit media cut reference.mp4 --start 12 --end 19.5 --label-time --to notes/hook.mp4
-hypit media cut assets/talk.mp4 --start 12 --end 19.5 --to assets/opening.mp4
-hypit media cut assets/talk.mp4 --keep 12:15.5 --keep 16:19.5 --to assets/opening-edited.mp4
-hypit media cut assets/narration.wav --keep 0.3:4.1 --keep 4.6:9.2 --to assets/narration-edited.wav
-hypit media frames reference.mp4 --at 12.4,13.1 --label-time --to notes/hook-frames
-hypit media tile reference.mp4 --start 12 --end 19.5 --to notes/hook-grid.jpg
-hypit media tile reference.mp4 --at 12.4,13.1,14.8 --columns 3 --to notes/exact-grid.jpg
-hypit media tile reference.mp4 --start 12 --end 14 --every 0.1 --transcript notes/reference.transcript.json --to notes/detail.jpg
-hypit media tiles reference.mp4 --around "your next idea" --transcript notes/reference.transcript.json --every 0.1 --columns 3 --rows 2 --to notes/phrase
-hypit media tiles reference.mp4 --ranges notes/ranges.json --to notes/grids
-hypit media boundaries reference.mp4
-hypit media fetch https://… --to reference/source.mp4
-hypit vocabulary
-hypit vocabulary @hypit/media-pipeline --tag StillVideo
-hypit vocabulary --visual text
-```
-
-`probe` accepts audio-only files as well as video. `cut` keeps one interval using `--start` and
-`--end`, or joins explicitly retained, ordered, non-overlapping intervals using repeated
-`--keep start:end` in source seconds. The latter is useful for removing gaps inside one recorded
-performance; it does not decide where Script Segments belong. Video retains its available picture
-and sound together (MP4 is a useful output container); audio-only outputs PCM WAV. A silent source
-video stays silent. The
-`--json` reports the source intervals, their nominal positions on the new local clock, and the
-measured output duration; actual frame and sample boundaries can differ slightly from the nominal
-positions. It writes a new file and refuses to
-overwrite an existing one. `--label-time` retains its single-video-interval role: it visibly
-overlays source time on an inspection copy, not on the clean production media.
-
-`transcribe` also accepts audio or video. Its transcript refers to the *input file's* clock. A
-cut or joined file has a new clock; use the final recorded performance and its Script in the
-Build's semantic preparation rather than treating source transcript timestamps as final timing.
-`frames` writes one JPEG per requested time, selecting the first decoded frame at or after it.
-Visible frame labels use that frame's actual timestamp, as do the labels below each `tile` cell.
-Sampling is shared by `frames`, `tile` and `tiles`:
-
-- `--at` names exact sample times; `--start` and `--end` choose a range in seconds.
-- `--every` samples from the start at that interval, excluding the end. Times use millisecond precision.
-- Grids can instead use `--frames` evenly spaced bin midpoints. Without a sampling option they provide
- a compact overview; choose the interval explicitly when inspecting fast motion.
-- `--transcript` reads `hypit.transcript@1` from `hypit transcribe`. The transcript and input media must
- share the same clock. Labels show source time, active words with their start/end, and nearby words.
- Active spans use `[start, end)`; overlapping words are all shown. Missing times stay missing, and a
- frame without a timed word is identified without inferring silence. Text is rendered below the
- source picture using Sharp/Pango and the machine's fonts, including font fallback for multilingual text.
-- `--around "a phrase"` with `--transcript` selects that phrase's word boundaries plus `--padding`
- seconds on either side (0.3 by default), clipped to the input duration. Matching uses whole consecutive
- words, ignoring case, whitespace and punctuation. Repeated matches list their times and require an
- explicit `--occurrence` (one-based), or a numeric range. This locates evidence; it does not interpret it.
-- `tiles` accepts the same selection as `tile`, or `--ranges` with a JSON array of
- `{ start, end, id?, frames?, every? }`. A range's sampling choice overrides the command default.
- It paginates into `--columns` × `--rows` cells (3 × 3 by default); the final page may have fewer cells.
- `--cell` chooses picture width. `tile` keeps all requested samples in one image.
-
-`--json` reports each frame's `requestedAt` and actual `at`, plus its active/context words when supplied.
-Grid `samples` retain the requested times; `frames` contain the actual extracted-frame information.
-It also reports every page path for `tiles`. The media layer reads existing timed text; transcription
-and its Endpoint remain separate. `boundaries` reports adjacent-frame
-change candidates and their measured scores; it does not suppress short changes or call them shots.
-`prepare-fetch` explicitly prepares the locked downloader environment; `fetch` requires it and
-turns a link into a file with the pinned yt-dlp; [the downloader package](../yt-dlp/README.md)
-owns its dependencies, download choices and file handling. Commands that create files write only
-what `--to` names and refuse to overwrite. `vocabulary` reads the installed
-manifests: every package with its tags and models, or one package's Surfaces with their attributes,
-children and example, or the value shapes a drawing Producer must emit.
-
-Install the `@hypit/hypit` Distribution globally once. It resolves its own TypeScript loader and CLI, so it
-neither invokes npm per command nor requires a project to contain Hypit's `package.json`.
-
-`hypit capture screenshot <url-or-file> --to <image>` saves browser material, and
-`hypit capture run <script.mjs> [-- arguments]` runs ordinary project interactions with a prepared
-Puppeteer page and screenshot/recording helpers. `hypit capture --help` lists viewport, region,
-readiness and browser options. `hypit capture install-browser` prepares the package's tested browser
-revision; an already installed compatible browser can be selected explicitly. The independently maintained `@hypit/browser-capture` package owns
-browser lifecycle and capture; Video CLI owns command presentation. This preparation tool outputs
-ordinary project files and opens no Runtime Profile or Build. The package README owns the script API.
-
-`--workspace` is only the Source Workspace containment boundary. `--asset-root` may additionally admit
-explicit asset bytes without widening Source imports. `--package-root` is only the Host
-override used to resolve installed packages. By default, a project with
-`package.json` owns package resolution; a plain creative folder falls back to this Distribution's
-installation. Keeping that separate from Source containment lets a video project live outside the
-Distribution without weakening canonical-path source and asset boundaries. Runtime Profiles do not
-contain either Workspace or package-installation overrides.
-
-`check` is usable for an Author Source or a complete Run Source. `plan` and `build` require a Run
-Source because an Author Graph without execution intent is not a Build. The live example executes
-the deterministic CaptionDocument produced by Script alongside real local/remote Endpoints; the CLI never
-fabricates a Target, Candidate or missing fact.
-
-`build` compiles one immutable Build Definition and submits it to the configured Local Runtime with a
-fresh, automatically assigned Build id. The id begins with its UTC creation time, so repository order is both
-stable and visible; its random suffix prevents same-millisecond collisions and says nothing about content.
-Source or Plan identity never reclaims an earlier Build; reuse
-across Builds exists only through explicit Run Source Candidates. JSON Profiles resolve only adapters in their separately
-selected `use` fields and contain no executable callback. The CLI imports no Provider. A TypeScript config
-module remains trusted deployment code with normal Node authority. Neither form is discovered from
-a source import.
-
-Without `--follow`, `build` returns after durable submission and the detached Worker continues.
-With `--follow`, the CLI observes Build activity and Operation facts until a Result outcome or
-`--max-wait-ms`; Ctrl-C only detaches that observer. `status` reads durable verified state, and
-`status --watch` reattaches the same kind of observer to an existing Build. The CLI
-controls Builds, not individual Operations. Cancelling a Build atomically withdraws it before claim,
-or marks running work for one best-effort Provider cancellation call after claim. It never selects
-another Candidate. None of these commands creates or stores a ready-Command queue.
-
-The Result saves every public Author Output completed on the demanded route, including structured
-values such as semantic takes. Each Logical Output has exactly one public name in `publishedOutputs`;
-there are no Record, Artifact or alias selectors. `inspect` shows those Outputs. `get` requires one
-exact `--output` name and one explicit `--to` destination: a Scalar becomes a JSON file, a Resource
-streams to one file, and a Composite becomes a self-contained directory with `value.json` plus every
-referenced Resource. The destination must not already exist. This is Host egress only and never
-changes Build identity or retention; large media does not need to be loaded into CLI memory.
-
-`builds` and `history` browse project-owned Result manifests newest first. `--before <build-id>` moves
-the cursor to older Results without a central history table. Presentation titles, notes and highlights
-live in the Result manifest and may be edited without changing the Build id or the saved Outputs.
-`history` always asks for one exact Output name; it never chooses a Result or writes reuse markup.
-Use the returned Build id and Output name explicitly in a Run Source when reusing that value.
-
-Human output is compact and organized around author-facing names. `--json` returns a stable, bounded
-command view rather than Repository manifests or Runtime persistence objects. `--verbose` adds bounded
-operational detail; physical state locations remain the job of `paths`, while `get --to` and
-`runtime logs --verbose` expose the paths those commands explicitly operate on.
-
-Historical Records, fixed files and generated previews are declared as ordinary Candidates in the
-Run Source and selected by explicit Satisfaction edges. The Host verifies a referenced prior Build
-only to extract the declared typed Record; it does not prove a semantic relationship with the current
-output. Upstream work behind the selected Candidate is pruned by reverse reachability, while every
-unbound reachable output follows the ordinary graph. This is a new Build identity and never resumes
-or copies the prior Build's outstanding Commands.
-
-`@hypit/package-loader-node` loads explicitly selected installed implementation packages and checks
-their Module, Host-facet, Producer and Validator contributions. Frontends are ordinary
-`hypit.source-frontend@1` Host facets, so the Loader does not
-select a syntax; each Source Header selects among installed Frontends. Run Fragment libraries enter
-only through the `hypit.run-fragment-host@1` facet. Source cannot
-install a package or activate Provider/Runtime authority. Arbitrary untrusted community execution
-remains absent until an isolated Worker and real permission boundary exist.
diff --git a/packages/video-cli/package.json b/packages/video-cli/package.json
deleted file mode 100644
index 530471bf..00000000
--- a/packages/video-cli/package.json
+++ /dev/null
@@ -1,47 +0,0 @@
-{
- "name": "@hypit/video-cli",
- "version": "0.0.0-dev",
- "license": "SEE LICENSE IN LICENSE",
- "private": true,
- "type": "module",
- "exports": {
- ".": "./src/index.ts",
- "./cli": "./src/cli.ts"
- },
- "dependencies": {
- "@hypit/browser-capture": "workspace:*",
- "@hypit/cli": "workspace:*",
- "@hypit/compiler-markup-node": "workspace:*",
- "@hypit/composition": "workspace:*",
- "@hypit/credential-store-file": "workspace:*",
- "@hypit/credential-store-os": "workspace:*",
- "@hypit/driver-node": "workspace:*",
- "@hypit/estimate": "workspace:*",
- "@hypit/generation": "workspace:*",
- "@hypit/hyperframes": "workspace:*",
- "@hypit/markup": "workspace:*",
- "@hypit/model-kit": "workspace:*",
- "@hypit/package-loader-node": "workspace:*",
- "@hypit/project-context-node": "workspace:*",
- "@hypit/protocol": "workspace:*",
- "@hypit/provider-hiapi": "workspace:*",
- "@hypit/provider-hypihub": "workspace:*",
- "@hypit/provider-monid": "workspace:*",
- "@hypit/provider-pollo": "workspace:*",
- "@hypit/provider-tokendance": "workspace:*",
- "@hypit/render-hyperframes": "workspace:*",
- "@hypit/resource-store-fs": "workspace:*",
- "@hypit/runtime": "workspace:*",
- "@hypit/runtime-kit": "workspace:*",
- "@hypit/runtime-host-node": "workspace:*",
- "@hypit/runtime-local": "workspace:*",
- "@hypit/speech": "workspace:*",
- "@hypit/speech-evidence": "workspace:*",
- "@hypit/text": "workspace:*",
- "@hypit/visual-ir": "workspace:*",
- "@hypit/whisperx": "workspace:*",
- "@hypit/workspace-fs-node": "workspace:*",
- "@hypit/yt-dlp": "workspace:*",
- "sharp": "0.35.4"
- }
-}
diff --git a/packages/video-cli/src/cli.ts b/packages/video-cli/src/cli.ts
deleted file mode 100644
index da2b0e21..00000000
--- a/packages/video-cli/src/cli.ts
+++ /dev/null
@@ -1,112 +0,0 @@
-#!/usr/bin/env node
-import { renderCliError, writeCliHelp } from "@hypit/cli";
-import type { CliIo } from "@hypit/cli";
-import { creationCommands, isCreationCommand, writeCreationHelp } from "./creation.js";
-import { isMediaCommand, mediaCommands, writeMediaHelp } from "./media.js";
-import { writeVocabularyHelp } from "./vocabulary.js";
-import { writeSnapshotHelp } from "./snapshot.js";
-import { writeCaptureHelp } from "./capture.js";
-import { runVersionCli, writeVersionHelp } from "./version.js";
-import { acceptSecretBytes } from "./secret-input.js";
-
-const argv = process.argv.slice(2);
-const json = argv.includes("--json");
-const debug = argv.includes("--debug");
-const colorIndex = argv.indexOf("--color");
-const colorMode = argv.includes("--no-color")
- ? "never"
- : colorIndex >= 0 ? argv[colorIndex + 1] : "auto";
-const color = !json && colorMode !== "never" && process.env.TERM !== "dumb"
- && (colorMode === "always" || (process.env.NO_COLOR === undefined && process.stdout.isTTY === true));
-const unicode = process.env.TERM !== "dumb";
-
-async function readSecret(prompt: string): Promise<string> {
- if (process.stdin.isTTY !== true || typeof process.stdin.setRawMode !== "function") {
- const chunks: Buffer[] = [];
- for await (const chunk of process.stdin) chunks.push(Buffer.from(chunk));
- return Buffer.concat(chunks).toString("utf8");
- }
- process.stderr.write(prompt);
- return await new Promise<string>((resolve, reject) => {
- const raw: number[] = [];
- const finish = (error?: Error): void => {
- process.stdin.off("data", input);
- process.stdin.setRawMode(false);
- process.stdin.pause();
- process.stderr.write("\n");
- if (error === undefined) resolve(Buffer.from(raw).toString("utf8"));
- else reject(error);
- };
- const input = (chunk: Buffer): void => {
- const result = acceptSecretBytes(raw, chunk);
- if (result === "cancelled") finish(new Error("credential input cancelled"));
- if (result === "done") finish();
- };
- process.stdin.setRawMode(true);
- process.stdin.resume();
- process.stdin.on("data", input);
- });
-}
-
-const io: CliIo = {
- write: (text) => process.stdout.write(text),
- writeProgress: (text) => process.stderr.write(text),
- setExitCode: (code) => { process.exitCode = code; },
- readSecret,
- terminal: {
- isTTY: process.stdout.isTTY === true,
- color,
- unicode,
- columns: process.stdout.columns ?? 100,
- },
-};
-
-async function main(): Promise<void> {
- const commandArgs = argv[0] === "capture" && argv.includes("--") ? argv.slice(0, argv.indexOf("--")) : argv;
- if (argv.length === 0 || argv[0] === "help" || commandArgs.includes("--help")) {
- const topic = argv[0] === "help" ? argv[1]
- : argv[0] === "--help" ? undefined
- : argv.includes("--help") ? argv[0] : undefined;
- if (topic === "snapshot") { writeSnapshotHelp(io); return; }
- if (topic === "version") { writeVersionHelp(io); return; }
- if (isCreationCommand(topic)) {
- writeCreationHelp(io, topic);
- return;
- }
- if (topic === "media") {
- const sub = argv[0] === "help" ? argv[2] : argv[1];
- writeMediaHelp(io, isMediaCommand(sub) ? sub : undefined);
- return;
- }
- if (topic === "vocabulary") {
- writeVocabularyHelp(io);
- return;
- }
- if (topic === "capture") {
- writeCaptureHelp(io);
- return;
- }
- writeCliHelp(io, topic);
- if (topic === undefined) {
- io.write(`\nInstallation\n version [--check] [--registry <url>] [--json]\n\nCreation tools (one request through the selected Runtime Profile, no Build)\n${
- [...creationCommands, "snapshot"].map((item) => ` ${item}`).join("\n")}\n hypit help <tool> for each\n`
- + `\nStudio\n studio --run <build.svrun>\n hypit studio --help for session options\n\nPreparation (local tools and project files)\n media ${mediaCommands.join(" | ")}\n capture screenshot | run | install-browser\n vocabulary\n hypit help media, hypit help capture, hypit help vocabulary\n`);
- }
- return;
- }
- if (argv[0] === "version") { await runVersionCli(argv, io); return; }
- const { runVideoCli } = await import("./index.js");
- await runVideoCli(argv, io);
-}
-
-main().catch((error: unknown) => {
- const rendered = renderCliError(error, {
- json,
- color: !json && colorMode !== "never" && process.env.TERM !== "dumb"
- && (colorMode === "always" || (process.env.NO_COLOR === undefined && process.stderr.isTTY === true)),
- unicode,
- debug,
- });
- (json ? process.stdout : process.stderr).write(rendered);
- process.exitCode = 1;
-});
diff --git a/packages/video-cli/src/compiler.ts b/packages/video-cli/src/compiler.ts
deleted file mode 100644
index 23588a0d..00000000
--- a/packages/video-cli/src/compiler.ts
+++ /dev/null
@@ -1,32 +0,0 @@
-import type { CliCompilerOptions } from "@hypit/cli";
-import { createMarkupNodeCompiler } from "@hypit/compiler-markup-node";
-import { resolveNodePackageSource } from "@hypit/package-loader-node";
-import { NodeFilesystemWorkspace } from "@hypit/workspace-fs-node";
-
-export function createVideoWorkspace(options: Pick<CliCompilerOptions,
- "workspaceRoot" | "assetRoots" | "packageRoot" | "distributionPackageRoot">) {
- const packageRoot = options.packageRoot ?? options.workspaceRoot ?? process.cwd();
- return new NodeFilesystemWorkspace({
- ...(options.workspaceRoot === undefined ? {} : { root: options.workspaceRoot }),
- ...(options.assetRoots === undefined ? {} : { assetRoots: options.assetRoots }),
- externalSourceResolver(importer, request) {
- const located = resolveNodePackageSource(request.from, {
- from: importer.id,
- workspaceRoots: [packageRoot],
- ...(options.distributionPackageRoot === undefined
- ? {}
- : { distributionRoots: [options.distributionPackageRoot] }),
- externalRoots: [],
- allowExternal: false,
- });
- return { root: located.root, source: located.source };
- },
- });
-}
-
-/** Assemble the Markup compiler Host from only the packages selected for this invocation. */
-export function createVideoCompiler(options: CliCompilerOptions) {
- return createMarkupNodeCompiler(options.packageContributions, {
- workspace: createVideoWorkspace(options),
- });
-}
diff --git a/packages/video-cli/src/creation.ts b/packages/video-cli/src/creation.ts
deleted file mode 100644
index 86932f7c..00000000
--- a/packages/video-cli/src/creation.ts
+++ /dev/null
@@ -1,467 +0,0 @@
-import { mkdir, mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises";
-import { tmpdir } from "node:os";
-import { dirname, join, resolve } from "node:path";
-
-import { loadDiscoveredSourcePackages } from "@hypit/cli";
-import { findRuntimeProfile, resolveProjectRoot } from "@hypit/project-context-node";
-import type { CliIo } from "@hypit/cli";
-import { MemoryResourceStore } from "@hypit/driver-node";
-import {
- countSpeechEstimateUnits,
- estimateSpeechDuration,
- resolveSpeechEstimateLanguage,
- resolveSpeechEstimateRate,
- speechEstimatePolicyFromAttributes,
-} from "@hypit/estimate";
-import type { CanonicalValue, CapabilityRef, Need, StoredValue } from "@hypit/protocol";
-import type { ResourceStore } from "@hypit/runtime";
-import type { RuntimeHostCapabilityProvider, RuntimeHostProviderQuery, RuntimeInvocationObservation } from "@hypit/runtime-host-node";
-import { sealSpeechEvidenceAudio, speechEvidenceTypes } from "@hypit/speech-evidence";
-import type { AlignedTranscriptEvidence } from "@hypit/speech-evidence";
-import { sealText } from "@hypit/text";
-import { whisperXCapabilities, whisperXRequestForEvidenceAudio } from "@hypit/whisperx";
-import { parseWhisperXLanguage } from "@hypit/whisperx";
-
-import { videoCliDistribution } from "./distribution.js";
-import { runProcess } from "./process.js";
-
-/** Transcribe source media through a selected Endpoint, or estimate authored speech locally. */
-export const creationCommands = ["transcribe", "measure"] as const;
-export type CreationCommand = typeof creationCommands[number];
-
-/** The slice of the Runtime host these commands use; tests hand in a fake. */
-export type CreationHost = {
- providers(requests: readonly RuntimeHostProviderQuery[]): Promise<readonly RuntimeHostCapabilityProvider[]>;
- invoke(need: Need, resources: ResourceStore, observation?: RuntimeInvocationObservation): Promise<{ readonly value: StoredValue }>;
-};
-
-export type CreationEnvironment = {
- /** Open the host behind `--runtime`, or behind the project's own selection when none is named. */
- readonly openHost: (
- runtime: string | undefined,
- workspaceRoot?: string,
- ) => Promise<{ readonly profile: string; readonly host: CreationHost }>;
- readonly cwd: string;
-};
-
-function assert(condition: unknown, message: string): asserts condition {
- if (!condition) throw new Error(message);
-}
-
-export function isCreationCommand(value: string | undefined): value is CreationCommand {
- return (creationCommands as readonly string[]).includes(value ?? "");
-}
-
-/** The default environment: the project's Profile, opened through this Distribution's Runtime. */
-export function creationEnvironment(cwd = process.cwd()): CreationEnvironment {
- return {
- cwd,
- openHost: async (runtime, workspace) => {
- const projectRoot = await resolveProjectRoot({
- ...(workspace === undefined ? {} : { workspaceRoot: resolve(cwd, workspace) }),
- cwd,
- });
- let profile: string;
- if (runtime !== undefined) {
- profile = resolve(cwd, runtime);
- } else {
- const selected = await findRuntimeProfile(projectRoot);
- assert(selected !== undefined,
- `No Runtime Profile is selected for ${projectRoot}; run hypit runtime use <profile> there, or pass --runtime <profile>`);
- profile = selected.profile;
- }
- const host = await videoCliDistribution.openRuntimeHost(profile, {
- packageRoot: projectRoot,
- ...(videoCliDistribution.packageRoot === undefined ? {} : { distributionPackageRoot: videoCliDistribution.packageRoot }),
- });
- return { profile, host };
- },
- };
-}
-
-// ---------------------------------------------------------------------------------------------------
-// Arguments
-
-type Parsed = {
- readonly positionals: readonly string[];
- readonly options: ReadonlyMap<string, string>;
- readonly json: boolean;
-};
-
-function parseArguments(argv: readonly string[], allowed: readonly string[]): Parsed {
- const positionals: string[] = [];
- const options = new Map<string, string>();
- let json = false;
- for (let index = 1; index < argv.length; index += 1) {
- const item = argv[index]!;
- if (item === "--json") { json = true; continue; }
- if (item === "--debug" || item === "--verbose" || item === "--no-color") continue;
- if (item === "--color") { index += 1; continue; }
- if (!item.startsWith("--")) { positionals.push(item); continue; }
- if (!allowed.includes(item)) throw new Error(`unknown option ${item}`);
- if (options.has(item)) throw new Error(`${item} cannot be repeated`);
- const value = argv[index + 1];
- if (value === undefined || value.startsWith("--")) throw new Error(`${item} requires a value`);
- options.set(item, value);
- index += 1;
- }
- return { positionals, options, json };
-}
-
-function required(parsed: Parsed, option: string, hint: string): string {
- const value = parsed.options.get(option);
- if (value === undefined) throw new Error(`${option} is required: ${hint}`);
- return value;
-}
-
-/** An option that takes prose: the text itself, or the path of a file holding it. */
-async function textOrFile(value: string, option: string, cwd: string): Promise<string> {
- const path = resolve(cwd, value);
- const isFile = await stat(path).then((item) => item.isFile(), () => false);
- const text = (isFile ? await readFile(path, "utf8") : value).trim();
- if (text.length === 0) throw new Error(isFile ? `${option} file ${path} is empty` : `${option} is empty`);
- return text;
-}
-
-async function destination(parsed: Parsed, cwd: string): Promise<string> {
- const to = resolve(cwd, required(parsed, "--to", "the file to write"));
- if (await stat(to).then(() => true, () => false)) throw new Error(`Destination ${to} already exists`);
- return to;
-}
-
-async function writeNew(path: string, content: string | Uint8Array): Promise<void> {
- await mkdir(dirname(path), { recursive: true });
- try {
- await writeFile(path, content, { flag: "wx" });
- } catch (error) {
- if (error instanceof Error && "code" in error && error.code === "EEXIST") {
- throw new Error(`Destination ${path} already exists`);
- }
- throw error;
- }
-}
-
-// ---------------------------------------------------------------------------------------------------
-// Provider and price page
-
-function capabilityName(capability: CapabilityRef): string {
- return `${capability.module.name}@${capability.module.version}#${capability.name}`;
-}
-
-/** Which Endpoint will serve this call and where its Provider publishes prices, before spending. */
-export async function selectedProvider(host: CreationHost, need: Need, profile: string): Promise<RuntimeHostCapabilityProvider> {
- const [provider] = await host.providers([{
- request: need.id,
- capability: need.capability,
- returns: need.returns,
- constraints: need.constraints,
- }]);
- const subject = capabilityName(need.capability);
- assert(provider !== undefined && provider.status !== "unresolved",
- `No Endpoint in ${profile} serves ${subject}; configure an Endpoint that supports this capability and check its binding in that Profile`);
- assert(provider.status !== "ambiguous",
- `Several Endpoints in ${profile} serve ${subject}: ${(provider.endpoints ?? []).join(", ")}; select one with bindings[${JSON.stringify(subject)}] in that Profile`);
- assert(provider.status !== "unsupported",
- `The configured Endpoints in ${profile} do not support this request for ${subject}`
- + (provider.binding === undefined ? "" : ` (binding: ${provider.binding})`)
- + `: ${(provider.rejections ?? []).map((item) => `${item.endpoint}: ${item.message}`).join("; ") || "no support reason supplied"}`
- + "; adjust the request or select a compatible Endpoint in that Profile");
- return provider;
-}
-
-function priceLine(provider: RuntimeHostCapabilityProvider): string {
- return provider.pricing === undefined
- ? "price source unknown"
- : provider.pricing.kind === "local" ? "local, no Provider charge" : provider.pricing.url;
-}
-
-export function providerView(provider: RuntimeHostCapabilityProvider) {
- return {
- endpoint: provider.endpoint ?? null,
- use: provider.use ?? null,
- pricing: provider.pricing ?? null,
- };
-}
-
-export function providerLine(provider: RuntimeHostCapabilityProvider): string {
- return `${provider.endpoint} (${provider.use}) · ${priceLine(provider)}`;
-}
-
-// ---------------------------------------------------------------------------------------------------
-// Media
-
-async function run(executable: string, args: readonly string[]): Promise<string> {
- return (await runProcess(executable, args)).toString("utf8");
-}
-
-const EVIDENCE_SAMPLE_RATE = 16_000;
-
-type WavShape = { readonly sampleRate: number; readonly channels: number; readonly bits: number; readonly codec: number; readonly dataBytes: number };
-
-/** Read a RIFF WAV header; undefined when the bytes are not a WAV file. */
-function wavShape(bytes: Uint8Array): WavShape | undefined {
- const fourCc = (offset: number) => String.fromCharCode(...bytes.subarray(offset, offset + 4));
- if (bytes.byteLength < 44 || fourCc(0) !== "RIFF" || fourCc(8) !== "WAVE") return undefined;
- const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
- let offset = 12;
- let format: Omit<WavShape, "dataBytes"> | undefined;
- let dataBytes: number | undefined;
- while (offset + 8 <= bytes.byteLength) {
- const name = fourCc(offset);
- const size = view.getUint32(offset + 4, true);
- const body = offset + 8;
- if (body + size > bytes.byteLength) return undefined;
- if (name === "fmt " && size >= 16) {
- format = { codec: view.getUint16(body, true), channels: view.getUint16(body + 2, true), sampleRate: view.getUint32(body + 4, true), bits: view.getUint16(body + 14, true) };
- } else if (name === "data") {
- dataBytes = size;
- }
- offset = body + size + (size % 2);
- }
- return format === undefined || dataBytes === undefined ? undefined : { ...format, dataBytes };
-}
-
-function canonicalEvidence(shape: WavShape | undefined): shape is WavShape {
- return shape !== undefined && shape.codec === 1 && shape.channels === 1 && shape.sampleRate === EVIDENCE_SAMPLE_RATE && shape.bits === 16;
-}
-
-/** The 16 kHz mono PCM WAV WhisperX measures; extracted with ffmpeg unless the file already is one. */
-async function speechEvidenceBytes(path: string): Promise<{ readonly bytes: Uint8Array; readonly sampleFrames: number; readonly extracted: boolean }> {
- const original = new Uint8Array(await readFile(path));
- const shape = wavShape(original);
- if (canonicalEvidence(shape)) return { bytes: original, sampleFrames: shape.dataBytes / 2, extracted: false };
- const scratch = await mkdtemp(join(tmpdir(), "hypit-transcribe-"));
- try {
- const target = join(scratch, "speech.wav");
- await run("ffmpeg", ["-hide_banner", "-loglevel", "error", "-y", "-i", path, "-map", "0:a:0", "-vn", "-ac", "1", "-ar", String(EVIDENCE_SAMPLE_RATE), "-c:a", "pcm_s16le", "-bitexact", target]);
- const bytes = new Uint8Array(await readFile(target));
- const extracted = wavShape(bytes);
- assert(canonicalEvidence(extracted), "ffmpeg did not produce 16 kHz mono PCM audio");
- return { bytes, sampleFrames: extracted.dataBytes / 2, extracted: true };
- } finally {
- await rm(scratch, { recursive: true, force: true });
- }
-}
-
-function round(value: number): number { return Number(value.toFixed(3)); }
-function seconds(sample: number | undefined): number | undefined {
- return sample === undefined ? undefined : round(sample / EVIDENCE_SAMPLE_RATE);
-}
-
-// ---------------------------------------------------------------------------------------------------
-// transcribe
-
-type TranscriptWord = { readonly text: string; readonly start_seconds?: number; readonly end_seconds?: number; readonly score?: number };
-type TranscriptPassage = { readonly text: string; readonly start_seconds?: number; readonly end_seconds?: number; readonly words: readonly TranscriptWord[] };
-
-function passagesInSeconds(aligned: AlignedTranscriptEvidence): readonly TranscriptPassage[] {
- return aligned.passages.map((passage) => {
- const words = passage.words.map((word): TranscriptWord => {
- const start = seconds(word.startSample);
- const end = seconds(word.endSampleExclusive);
- return {
- text: word.text,
- ...(start === undefined ? {} : { start_seconds: start }),
- ...(end === undefined ? {} : { end_seconds: end }),
- ...(word.score === undefined ? {} : { score: word.score }),
- };
- });
- const start = seconds(passage.startSample);
- const end = seconds(passage.endSampleExclusive);
- return {
- text: words.map((word) => word.text).join(" "),
- ...(start === undefined ? {} : { start_seconds: start }),
- ...(end === undefined ? {} : { end_seconds: end }),
- words,
- };
- });
-}
-
-async function transcribe(argv: readonly string[], io: CliIo, environment: CreationEnvironment): Promise<void> {
- const parsed = parseArguments(argv, ["--language", "--to", "--runtime", "--workspace"]);
- assert(parsed.positionals.length === 1, "transcribe takes exactly one audio or video file");
- const source = resolve(environment.cwd, parsed.positionals[0]!);
- const language = parseWhisperXLanguage(parsed.options.get("--language"), "transcribe --language");
- const to = await destination(parsed, environment.cwd);
- const { profile, host } = await environment.openHost(
- parsed.options.get("--runtime"),
- parsed.options.get("--workspace"),
- );
- const evidence = await speechEvidenceBytes(source);
- const resources = new MemoryResourceStore();
- const artifact = await resources.put(evidence.bytes, "audio/wav");
- const audio = sealSpeechEvidenceAudio({ domainId: "cli-transcribe", artifact, sampleFrames: evidence.sampleFrames });
- const need: Need = {
- id: "need:hypit-transcribe",
- capability: whisperXCapabilities.alignment,
- returns: speechEvidenceTypes.alignedTranscript,
- constraints: whisperXRequestForEvidenceAudio(audio, { language }),
- result: "record:hypit-transcribe",
- };
- const provider = await selectedProvider(host, need, profile);
- if (!parsed.json) io.write(`Transcribing through ${providerLine(provider)}\n`);
- const report = parsed.json ? io.writeProgress : io.writeProgress ?? io.write;
- let previousPhase: string | undefined;
- const fulfillment = await host.invoke(need, resources, {
- reportProgress: async (progress) => {
- if (progress.phase === previousPhase) return;
- previousPhase = progress.phase;
- report?.(` · ${progress.phase}\n`);
- },
- reportDiagnostic: async (diagnostic) => { report?.(` · ${diagnostic.message}\n`); },
- });
- assert(fulfillment.value.kind === "inline", "the transcript came back by reference");
- const passages = passagesInSeconds(fulfillment.value.value as unknown as AlignedTranscriptEvidence);
- const words = passages.reduce((total, passage) => total + passage.words.length, 0);
- const file = {
- format: "hypit.transcript@1",
- source,
- language,
- audio_seconds: round(evidence.sampleFrames / EVIDENCE_SAMPLE_RATE),
- passages,
- };
- await writeNew(to, `${JSON.stringify(file, null, 2)}\n`);
- const view = {
- format: "hypit.video-cli-transcribe@1",
- source,
- language,
- audio_seconds: file.audio_seconds,
- extracted: evidence.extracted,
- ...providerView(provider),
- passages: passages.length,
- words,
- path: to,
- };
- if (parsed.json) io.write(`${JSON.stringify(view, null, 2)}\n`);
- else io.write(`✓ Transcript written\n\n ${words} words in ${passages.length} passage${passages.length === 1 ? "" : "s"} over ${file.audio_seconds}s\n ${to}\n`);
-}
-
-// ---------------------------------------------------------------------------------------------------
-// measure
-
-/** The spoken Text of one Script Segment, read from the compiled author source without a Build. */
-async function segmentSpeech(source: string, segment: string, projectRoot: string): Promise<string> {
- const loaded = await loadDiscoveredSourcePackages({ ...videoCliDistribution, bootstrapPackages: [] }, {
- source,
- workspaceRoot: projectRoot,
- packageRoot: projectRoot,
- ...(videoCliDistribution.packageRoot === undefined ? {} : { distributionPackageRoot: videoCliDistribution.packageRoot }),
- });
- const compiler = videoCliDistribution.createCompiler({
- workspaceRoot: projectRoot,
- packageRoot: projectRoot,
- ...(videoCliDistribution.packageRoot === undefined
- ? {}
- : { distributionPackageRoot: videoCliDistribution.packageRoot }),
- packageContributions: loaded.map((item) => item.contribution),
- });
- const workspace = await compiler.openFile(source);
- const compiled = await compiler.compileSource(workspace.entry, workspace);
- const suffix = `.segment.${segment}.speech`;
- const record = compiled.program.records.find((item) =>
- item.type.module.name === "@hypit/text" && item.type.name === "Text" && item.id.endsWith(suffix));
- assert(record !== undefined, `${source} declares no Segment ${segment} with speech; Segments are named by the Script's <segment id>`);
- assert(record.value.kind === "inline", `Segment ${segment} speech is not an inline Text`);
- const text = (record.value.value as { readonly value?: unknown } | null)?.value;
- assert(typeof text === "string", `Segment ${segment} speech is not Text`);
- return text;
-}
-
-/**
- * Measure a script before writing a duration: pronunciation units of the words, at the delivery
- * policy and rounding the author chooses. Pure local work.
- */
-async function measure(argv: readonly string[], io: CliIo, environment: CreationEnvironment): Promise<void> {
- const parsed = parseArguments(argv, ["--text", "--segment", "--language", "--pace", "--rate", "--rounding", "--padding", "--workspace"]);
- const inlineText = parsed.options.get("--text");
- const segment = parsed.options.get("--segment");
- assert((inlineText === undefined) !== (parsed.positionals.length === 0 && segment === undefined) || (inlineText !== undefined && parsed.positionals.length === 0),
- "measure takes either --text <text|file>, or a source .svml with --segment <id>");
- let text: string;
- let where: { readonly source: string; readonly segment: string } | { readonly text: true };
- if (inlineText !== undefined) {
- assert(segment === undefined && parsed.positionals.length === 0, "--text cannot be combined with a source or --segment");
- text = await textOrFile(inlineText, "--text", environment.cwd);
- where = { text: true };
- } else {
- assert(parsed.positionals.length === 1 && segment !== undefined, "measure a Segment with: hypit measure <source.svml> --segment <id>");
- const source = resolve(environment.cwd, parsed.positionals[0]!);
- const workspace = parsed.options.get("--workspace");
- const projectRoot = await resolveProjectRoot({
- ...(workspace === undefined ? {} : { workspaceRoot: resolve(environment.cwd, workspace) }),
- cwd: environment.cwd,
- });
- text = await segmentSpeech(source, segment, projectRoot);
- where = { source, segment };
- }
- const pace = parsed.options.get("--pace");
- const rate = parsed.options.get("--rate");
- assert(pace === undefined || rate === undefined, "measure takes either --pace or --rate, not both");
- const policy = speechEstimatePolicyFromAttributes({
- language: parsed.options.get("--language") ?? "auto",
- ...(rate === undefined ? { pace: pace ?? "normal" } : { rate }),
- rounding: parsed.options.get("--rounding") ?? "none",
- ...(parsed.options.get("--padding") === undefined ? {} : { padding: parsed.options.get("--padding") }),
- }, "hypit measure");
- const language = resolveSpeechEstimateLanguage(text, policy.language);
- const units = countSpeechEstimateUnits(text, language);
- const seconds = estimateSpeechDuration(sealText(text), policy);
- const resolvedRate = resolveSpeechEstimateRate(policy, language);
- const view = {
- format: "hypit.video-cli-measure@1",
- ...where,
- characters: text.length,
- units,
- language,
- policy,
- rate: resolvedRate,
- seconds,
- };
- if (parsed.json) { io.write(`${JSON.stringify(view, null, 2)}\n`); return; }
- const delivery = `${resolvedRate} units/s${policy.pace === undefined ? "" : ` (${policy.pace})`}`;
- io.write(`${Number(seconds.toFixed(3))}s\n\n ${units} pronunciation units · ${language} · ${delivery}\n`
- + ` padding ${policy.paddingSec ?? 0}s · rounding ${policy.rounding}\n`
- + ` ${"segment" in where ? `${where.segment} in ${where.source}` : `${text.length} characters`}\n`
- + " Choose the request duration from this estimate, the intended performance, and the selected model's supported values.\n");
-}
-
-// ---------------------------------------------------------------------------------------------------
-// Entry
-
-export function writeCreationHelp(io: CliIo, topic?: CreationCommand): void {
- const sections: Record<CreationCommand, readonly string[]> = {
- transcribe: [
- "hypit transcribe",
- "Establish word times with the whisperx-alignment Endpoint of the selected Runtime Profile.",
- "",
- " hypit transcribe <audio|video> --to <transcript.json> --language <code> [--runtime <profile>] [--workspace <project>]",
- "",
- "Extracts 16 kHz mono speech audio with ffmpeg and writes every word with its start and end in",
- "seconds. One immediate request; no Build, Result or state.",
- ],
- measure: [
- "hypit measure",
- "Measure a script before writing a duration. Pure local work; no Runtime Profile, no request.",
- "",
- " hypit measure <source.svml> --segment <id> [--language auto|en|zh|ja|es] [--pace slow|normal|fast | --rate <units/s>]",
- " [--rounding none|round|ceil] [--padding <s>]",
- " [--workspace <project>]",
- " hypit measure --text <text|file> [same options]",
- "",
- "Prints the estimated seconds at that delivery. Use them to shape the passage and choose a",
- "literal duration for the intended performance and selected model.",
- ],
- };
- const chosen = topic === undefined ? creationCommands : [topic];
- io.write(`${chosen.map((item) => sections[item].join("\n")).join("\n\n")}\n\n`
- + "transcribe names the Endpoint and its price page before it runs; the Profile\n"
- + "comes from --runtime or the project's `hypit runtime use` selection. measure spends nothing.\n");
-}
-
-export async function runCreationCli(argv: readonly string[], io: CliIo, environment: CreationEnvironment = creationEnvironment()): Promise<void> {
- const command = argv[0];
- assert(isCreationCommand(command), `unknown creation command ${command}`);
- if (argv.includes("--help")) { writeCreationHelp(io, command); return; }
- if (command === "transcribe") await transcribe(argv, io, environment);
- else await measure(argv, io, environment);
-}
diff --git a/packages/video-cli/src/distribution.ts b/packages/video-cli/src/distribution.ts
deleted file mode 100644
index a6774785..00000000
--- a/packages/video-cli/src/distribution.ts
+++ /dev/null
@@ -1,84 +0,0 @@
-import type { CliDistribution } from "@hypit/cli";
-import {
- doctorProjectBuildResultRepository,
- openLocalRuntimeHost,
- openProjectBuildResultRepository,
-} from "@hypit/runtime-local";
-import { fileURLToPath } from "node:url";
-import { resolve } from "node:path";
-import {
- createVideoCompiler,
-} from "./compiler.js";
-
-// The Distribution root is the replaceable Hypit tool checkout, not this
-// package's source directory and never the author's project.
-const packageRoot = resolve(import.meta.dirname, "../../..");
-const defaultBuildResultRepository = {
- use: "@hypit/build-result-fs",
- config: { path: ".hypit/results" },
-} as const;
-
-/** Official video authoring assembly for the generic CLI engine. */
-export const videoCliDistribution: CliDistribution = {
- packageRoot,
- bootstrapPackages: [],
- initialRuntimeProfile: {
- format: "hypit.runtime-local@1",
- dataRoot: ".hypit/runtimes/local",
- // The starter selects the portable Store, so the Profile it writes is openable and writable on
- // Linux as well: macOS and Windows keep the platform locker, and a Linux host uses an
- // owner-private file. `os` and `file` stay selectable by name for one explicit backend.
- credentials: {
- platform: { use: "@hypit/credential-store-platform" },
- },
- endpoints: {
- "hypihub.default": {
- use: "@hypit/provider-hypihub",
- config: {
- baseUrl: "https://hypit.ai",
- apiKey: { store: "platform", key: "hypihub.oauth" },
- },
- },
- "media.local": {
- use: "@hypit/provider-media-local",
- },
- "hyperframes.local": {
- use: "@hypit/provider-hyperframes-local",
- },
- },
- },
- createCompiler: createVideoCompiler,
- discoverSourcePackages: async (path, options) => {
- const { discoverVideoSourcePackages } = await import("./package-selection.js");
- return await discoverVideoSourcePackages(path, options);
- },
- openRuntimeHost: async (path, options) => await openLocalRuntimeHost(path, {
- packageRoot: options.packageRoot,
- ...(options.distributionPackageRoot === undefined
- ? {}
- : { distributionPackageRoot: options.distributionPackageRoot }),
- workerLaunch: {
- command: process.execPath,
- // The loaded Distribution owns its Worker entry and TypeScript/package resolution.
- args: [fileURLToPath(new URL("../../../bin/hypit.mjs", import.meta.url))],
- },
- }),
- openProjectResults: async (projectRoot, options) => {
- const opened = await openProjectBuildResultRepository(projectRoot, {
- ...options,
- distributionPackageRoot: options.distributionPackageRoot ?? packageRoot,
- defaultSelection: defaultBuildResultRepository,
- });
- return {
- location: opened.location,
- repository: opened.repository,
- close: async () => await opened.close?.(),
- };
- },
- diagnoseProjectResults: async (projectRoot, options) =>
- await doctorProjectBuildResultRepository(projectRoot, {
- ...options,
- distributionPackageRoot: options.distributionPackageRoot ?? packageRoot,
- defaultSelection: defaultBuildResultRepository,
- }),
-};
diff --git a/packages/video-cli/src/frame-grid.ts b/packages/video-cli/src/frame-grid.ts
deleted file mode 100644
index 6c997606..00000000
--- a/packages/video-cli/src/frame-grid.ts
+++ /dev/null
@@ -1,34 +0,0 @@
-import sharp from "sharp";
-
-/** Arrange already captured evidence. Decoding and time selection belong to the caller. */
-export async function writeFrameGrid(
- frames: readonly { readonly path: string; readonly label: Buffer }[],
- target: string, cellWidth: number, columns: number,
-): Promise<void> {
- if (frames.length === 0) throw new Error("A frame grid needs at least one image");
- const cells = [];
- for (const frame of frames) {
- const picture = await sharp(frame.path).resize({ width: cellWidth }).png().toBuffer({ resolveWithObject: true });
- const labelHeight = (await sharp(frame.label).metadata()).height!;
- cells.push({ picture: picture.data, height: picture.info.height, label: frame.label, labelHeight });
- }
- const pictureHeight = Math.max(...cells.map(cell => cell.height));
- const rowHeight = pictureHeight + Math.max(...cells.map(cell => cell.labelHeight));
- const rows = Math.ceil(cells.length / columns);
- await sharp({ create: {
- width: columns * (cellWidth + 8) + 8, height: rows * (rowHeight + 8) + 8,
- channels: 3, background: "#0c0c0c",
- } }).composite(cells.flatMap((cell, index) => {
- const left = 8 + index % columns * (cellWidth + 8);
- const top = 8 + Math.floor(index / columns) * (rowHeight + 8);
- return [{ input: cell.picture, left, top }, { input: cell.label, left, top: top + pictureHeight }];
- })).toFile(target);
-}
-
-export async function snapshotFrameLabel(frame: number, seconds: number, width: number): Promise<Buffer> {
- const text = await sharp({ text: { text: `<span foreground="#f5f5f5">Frame ${frame} · ${seconds.toFixed(6)} s</span>`,
- font: `sans ${Math.max(12, Math.round(width / 28))}`, width: width - 16, rgba: true,
- } }).png().toBuffer({ resolveWithObject: true });
- return sharp({ create: { width, height: text.info.height + 16, channels: 3, background: "#0c0c0c" } })
- .composite([{ input: text.data, left: 8, top: 8 }]).png().toBuffer();
-}
diff --git a/packages/video-cli/src/index.ts b/packages/video-cli/src/index.ts
deleted file mode 100644
index 6629487e..00000000
--- a/packages/video-cli/src/index.ts
+++ /dev/null
@@ -1,56 +0,0 @@
-import { runCli } from "@hypit/cli";
-import type { CliIo } from "@hypit/cli";
-import {
- installDistributionPackageResolution,
- installExternalPackageResolution,
-} from "@hypit/package-loader-node";
-import { hypitHostPackageRoot } from "@hypit/runtime-host-node";
-import type { LoadedPackage } from "@hypit/package-loader-node";
-
-import { isCreationCommand, runCreationCli } from "./creation.js";
-import { videoCliDistribution } from "./distribution.js";
-import { runMediaCli } from "./media.js";
-import { runVocabularyCli } from "./vocabulary.js";
-import { runCaptureCli } from "./capture.js";
-import { runSnapshotCli } from "./snapshot.js";
-import { runVersionCli } from "./version.js";
-
-export {
- createVideoCompiler,
- createVideoWorkspace,
-} from "./compiler.js";
-export { videoCliDistribution } from "./distribution.js";
-export { videoStudioCompanionPackages } from "./studio-distribution.js";
-export { discoverVideoSourcePackages } from "./package-selection.js";
-export { creationCommands, isCreationCommand, runCreationCli, writeCreationHelp } from "./creation.js";
-export type { CreationCommand, CreationEnvironment, CreationHost } from "./creation.js";
-export { isMediaCommand, mediaCommands, runMediaCli, writeMediaHelp } from "./media.js";
-export type { MediaCommand, MediaProbe } from "./media.js";
-export { runCaptureCli, writeCaptureHelp } from "./capture.js";
-export { listPackages, listSurfaces, runVocabularyCli, visualSchema, writeVocabularyHelp } from "./vocabulary.js";
-export type { PackageListing, SurfaceListing } from "./vocabulary.js";
-/** The project's selected Runtime Profile, read the way `hypit` reads it, for tools that run beside the CLI. */
-export { findRuntimeProfile } from "@hypit/project-context-node";
-
-export function runVideoCli(
- argv: readonly string[],
- io: CliIo,
- packages: readonly LoadedPackage[] = [],
-): Promise<void> {
- if (argv[0] === "version") return runVersionCli(argv, io);
- installDistributionPackageResolution(videoCliDistribution.packageRoot === undefined
- ? []
- : [videoCliDistribution.packageRoot]);
- installExternalPackageResolution([hypitHostPackageRoot()]);
- if (isCreationCommand(argv[0])) return runCreationCli(argv, io);
- if (argv[0] === "snapshot") return runSnapshotCli(argv, io);
- if (argv[0] === "media") return runMediaCli(argv, io);
- if (argv[0] === "capture") return runCaptureCli(argv, io);
- if (argv[0] === "vocabulary") return runVocabularyCli(argv, io);
- return runCli(argv, io, {
- ...videoCliDistribution,
- bootstrapPackages: packages,
- });
-}
-
-export { runSnapshotCli, writeSnapshotHelp } from "./snapshot.js";
diff --git a/packages/video-cli/src/media-frames.ts b/packages/video-cli/src/media-frames.ts
deleted file mode 100644
index c20ad5e4..00000000
--- a/packages/video-cli/src/media-frames.ts
+++ /dev/null
@@ -1,25 +0,0 @@
-import { mkdir } from "node:fs/promises";
-import { join } from "node:path";
-import { runProcessOutput } from "./process.js";
-
-export type DecodedFrame = { readonly at: number; readonly path: string };
-
-/** Decode a source interval once, retaining each decoded frame and its actual source timestamp. */
-export async function decodeMediaFrames(source: string, start: number, end: number, directory: string): Promise<readonly DecodedFrame[]> {
- if (!Number.isFinite(start) || start < 0 || !Number.isFinite(end) || end <= start) throw new Error("Native frames need 0 <= start < end");
- await mkdir(directory, { recursive: true });
- const times: number[] = [];
- let numerator = 0, denominator = 0;
- await runProcessOutput("ffmpeg", ["-hide_banner", "-loglevel", "info", "-nostdin", "-copyts", "-start_at_zero",
- ...(start > 0 ? ["-ss", String(start)] : []), "-i", source,
- "-map", "0:v:0", "-an", "-vf", `trim=start=${start}:end=${end},showinfo=checksum=0`,
- "-fps_mode", "passthrough", "-pix_fmt", "yuvj420p", "-q:v", "3", "-start_number", "0", join(directory, "%09d.jpg"),
- ], 300_000, line => {
- const base = /config in time_base:\s*(\d+)\/(\d+)/u.exec(line);
- if (base !== null) { numerator = Number(base[1]); denominator = Number(base[2]); }
- const pts = /\bn:\s*\d+\s+pts:\s*(-?\d+)/u.exec(line);
- if (pts !== null && denominator > 0) times.push(Number(pts[1]) * numerator / denominator);
- });
- if (times.length === 0) throw new Error(`No video frames in [${start}, ${end}) s`);
- return times.map((at, index) => ({ at, path: join(directory, `${String(index).padStart(9, "0")}.jpg`) }));
-}
diff --git a/packages/video-cli/src/media.ts b/packages/video-cli/src/media.ts
deleted file mode 100644
index 5f53a7f0..00000000
--- a/packages/video-cli/src/media.ts
+++ /dev/null
@@ -1,863 +0,0 @@
-import { copyFile, link, mkdir, mkdtemp, readFile, rename, rm, stat } from "node:fs/promises";
-import { tmpdir } from "node:os";
-import { dirname, extname, join, resolve } from "node:path";
-
-import type { CliIo } from "@hypit/cli";
-import { downloadVideo, isVideoUrl, prepareVideoDownload } from "@hypit/yt-dlp";
-import sharp from "sharp";
-
-import { decodeMediaFrames } from "./media-frames.js";
-import { writeFrameGrid } from "./frame-grid.js";
-import { runProcess, runProcessOutput, runProcessWithInput } from "./process.js";
-import { phraseRanges, readTranscript, wordsAt } from "./transcript.js";
-import type { FrameWords, TranscriptWord } from "./transcript.js";
-
-/**
- * Local views of media at chosen times and scales. Transcript annotations use the same seconds as
- * the input media. These commands expose evidence; editorial interpretation belongs to the author.
- */
-
-export const mediaCommands = ["probe", "cut", "frames", "tile", "tiles", "boundaries", "fetch", "prepare-fetch"] as const;
-export type MediaCommand = typeof mediaCommands[number];
-
-function assert(condition: unknown, message: string): asserts condition {
- if (!condition) throw new Error(message);
-}
-
-export function isMediaCommand(value: string | undefined): value is MediaCommand {
- return (mediaCommands as readonly string[]).includes(value ?? "");
-}
-
-function round(value: number): number { return Number(value.toFixed(3)); }
-function clamp(value: number, low: number, high: number): number { return Math.max(low, Math.min(high, value)); }
-
-// ---------------------------------------------------------------------------------------------------
-// Arguments
-
-type Parsed = {
- readonly positionals: readonly string[];
- readonly options: ReadonlyMap<string, string>;
- readonly repeated: ReadonlyMap<string, readonly string[]>;
- readonly flags: ReadonlySet<string>;
- readonly json: boolean;
-};
-
-function parseArguments(
- argv: readonly string[], allowed: readonly string[], allowedFlags: readonly string[] = [], repeatable: readonly string[] = [],
-): Parsed {
- const positionals: string[] = [];
- const options = new Map<string, string>();
- const repeated = new Map<string, string[]>();
- const flags = new Set<string>();
- let json = false;
- for (let index = 0; index < argv.length; index += 1) {
- const item = argv[index]!;
- if (item === "--json") { json = true; continue; }
- if (item === "--debug" || item === "--verbose" || item === "--no-color") continue;
- if (item === "--color") { index += 1; continue; }
- if (!item.startsWith("--")) { positionals.push(item); continue; }
- if (allowedFlags.includes(item)) {
- if (flags.has(item)) throw new Error(`${item} cannot be repeated`);
- flags.add(item);
- continue;
- }
- if (!allowed.includes(item)) throw new Error(`unknown option ${item}`);
- if (!repeatable.includes(item) && options.has(item)) throw new Error(`${item} cannot be repeated`);
- const value = argv[index + 1];
- if (value === undefined || (value.startsWith("--") && value.length > 2)) throw new Error(`${item} requires a value`);
- if (repeatable.includes(item)) repeated.set(item, [...(repeated.get(item) ?? []), value]);
- else options.set(item, value);
- index += 1;
- }
- return { positionals, options, repeated, flags, json };
-}
-
-function required(parsed: Parsed, option: string, hint: string): string {
- const value = parsed.options.get(option);
- if (value === undefined) throw new Error(`${option} is required: ${hint}`);
- return value;
-}
-
-function secondsOption(parsed: Parsed, option: string, fallback?: number): number {
- const raw = parsed.options.get(option);
- if (raw === undefined) {
- if (fallback !== undefined) return fallback;
- throw new Error(`${option} is required: a time in seconds`);
- }
- const value = Number(raw);
- assert(Number.isFinite(value) && value >= 0, `${option} must be a non-negative number of seconds, got ${raw}`);
- return value;
-}
-
-function integerOption(parsed: Parsed, option: string, fallback: number, low: number): number {
- const raw = parsed.options.get(option);
- if (raw === undefined) return fallback;
- const value = Number(raw);
- assert(Number.isSafeInteger(value) && value >= low, `${option} must be a whole number of at least ${low}, got ${raw}`);
- return value;
-}
-
-function numberOption(parsed: Parsed, option: string, fallback: number, low: number, high: number): number {
- const raw = parsed.options.get(option);
- if (raw === undefined) return fallback;
- const value = Number(raw);
- assert(Number.isFinite(value) && value >= low && value <= high, `${option} must be between ${low} and ${high}, got ${raw}`);
- return value;
-}
-
-function secondsList(raw: string, option: string, minimum: number): number[] {
- const parts = raw.split(",").map((item) => item.trim());
- assert(parts.length >= minimum && parts.every((item) => item.length > 0), `${option} must list at least ${minimum} seconds, got ${raw}`);
- const values = parts.map(Number);
- assert(values.every((value) => Number.isFinite(value) && value >= 0), `${option} must list non-negative seconds, got ${raw}`);
- return values;
-}
-
-async function sourceFile(parsed: Parsed, cwd: string): Promise<string> {
- const [source] = parsed.positionals;
- assert(source !== undefined, "name the media file first");
- assert(parsed.positionals.length === 1, "media commands take exactly one media file");
- const path = resolve(cwd, source);
- assert(await stat(path).then((item) => item.isFile(), () => false), `cannot read ${path}`);
- return path;
-}
-
-async function destination(parsed: Parsed, cwd: string, hint: string): Promise<string> {
- const to = resolve(cwd, required(parsed, "--to", hint));
- assert(!(await stat(to).then(() => true, () => false)), `Destination ${to} already exists`);
- await mkdir(dirname(to), { recursive: true });
- return to;
-}
-
-async function destinationDirectory(parsed: Parsed, cwd: string, hint: string): Promise<string> {
- const to = resolve(cwd, required(parsed, "--to", hint));
- assert(!(await stat(to).then(() => true, () => false)), `Destination ${to} already exists`);
- await mkdir(dirname(to), { recursive: true });
- return to;
-}
-
-// ---------------------------------------------------------------------------------------------------
-// ffmpeg
-
-type VideoProbe = {
- readonly hasVideo: true;
- readonly width: number;
- readonly height: number;
- readonly frameRate: number;
-};
-
-export type MediaProbe = {
- readonly duration: number;
- readonly hasAudio: boolean;
-} & (VideoProbe | { readonly hasVideo: false });
-
-function requireVideo(info: MediaProbe, path: string): asserts info is MediaProbe & VideoProbe {
- assert(info.hasVideo, `${path}: no video stream`);
-}
-
-export async function probeMedia(path: string): Promise<MediaProbe> {
- const raw = await runProcess("ffprobe", [
- "-v", "error", "-show_entries", "format=duration:stream=codec_type,width,height,r_frame_rate:stream_disposition=attached_pic", "-of", "json", path,
- ]);
- const parsed = JSON.parse(raw.toString("utf8")) as {
- format?: { duration?: string };
- streams?: readonly {
- codec_type?: string; width?: number; height?: number; r_frame_rate?: string;
- disposition?: { attached_pic?: number };
- }[];
- };
- const video = parsed.streams?.find((item) => item.codec_type === "video" && item.disposition?.attached_pic !== 1);
- const duration = Number(parsed.format?.duration);
- assert(Number.isFinite(duration) && duration > 0, `${path}: duration is unavailable`);
- const hasAudio = parsed.streams?.some((item) => item.codec_type === "audio") ?? false;
- assert(video !== undefined || hasAudio, `${path}: no audio or video stream`);
- if (video === undefined) return { duration: round(duration), hasVideo: false, hasAudio };
- assert(video.width !== undefined && video.height !== undefined, `${path}: video dimensions are unavailable`);
- // ffprobe reports the rate as a ratio; a still image reports none.
- const ratio = (video.r_frame_rate ?? "").split("/");
- const rate = Number(ratio[0]) / Number(ratio[1] ?? 1);
- return {
- duration: round(duration),
- hasVideo: true,
- width: video.width,
- height: video.height,
- frameRate: Number.isFinite(rate) && rate > 0 ? round(rate) : 0,
- hasAudio,
- };
-}
-
-/**
- * Open `source` on the frame at `at` seconds.
- *
- * `-ss` after `-i` alone decodes every frame up to the mark; `-ss` before `-i` alone lands on the
- * keyframe before it. Jumping to two seconds early and decoding the short run-up lands on the exact
- * frame: measured on a 1080p source nine minutes in, the same JPEG to the byte, 11.6 s to 0.2 s.
- */
-const SEEK_RUN_UP = 2;
-function openAt(source: string, at: number): readonly string[] {
- const jump = Math.max(0, at - SEEK_RUN_UP);
- const runUp = at - jump;
- return [...(jump > 0 ? ["-ss", String(round(jump))] : []), "-i", source, ...(runUp > 0 ? ["-ss", String(round(runUp))] : [])];
-}
-
-// JPEG is a full-range format; web video is routinely full-range YUV and the encoder refuses it
-// unless told which it is writing (`Non full-range YUV is non-standard`).
-const JPEG = ["-pix_fmt", "yuvj420p", "-q:v", "3"] as const;
-
-const GLYPHS: Readonly<Record<string, readonly string[]>> = {
- "0": ["11111", "10001", "10011", "10101", "11001", "10001", "11111"],
- "1": ["00100", "01100", "00100", "00100", "00100", "00100", "01110"],
- "2": ["11110", "00001", "00001", "11110", "10000", "10000", "11111"],
- "3": ["11110", "00001", "00001", "01110", "00001", "00001", "11110"],
- "4": ["10010", "10010", "10010", "11111", "00010", "00010", "00010"],
- "5": ["11111", "10000", "10000", "11110", "00001", "00001", "11110"],
- "6": ["01111", "10000", "10000", "11110", "10001", "10001", "01110"],
- "7": ["11111", "00001", "00010", "00100", "01000", "01000", "01000"],
- "8": ["01110", "10001", "10001", "01110", "10001", "10001", "01110"],
- "9": ["01110", "10001", "10001", "01111", "00001", "00001", "11110"],
- ":": ["00000", "00100", "00100", "00000", "00100", "00100", "00000"],
- ".": ["00000", "00000", "00000", "00000", "00000", "00100", "00100"],
-};
-
-function timecode(seconds: number): string {
- const milliseconds = Math.max(0, Math.round(seconds * 1_000));
- const hours = Math.floor(milliseconds / 3_600_000);
- const minutes = Math.floor(milliseconds / 60_000) % 60;
- const wholeSeconds = Math.floor(milliseconds / 1_000) % 60;
- const remainder = milliseconds % 1_000;
- return `${String(hours).padStart(2, "0")}:${String(minutes).padStart(2, "0")}:${String(wholeSeconds).padStart(2, "0")}.${String(remainder).padStart(3, "0")}`;
-}
-
-type RasterLabel = {
- readonly width: number;
- readonly height: number;
- readonly bytes: Buffer;
-};
-
-/** A tiny built-in numeric face keeps evidence labels available even when ffmpeg lacks drawtext. */
-function rasterLabel(text: string, requestedWidth?: number): RasterLabel {
- const scale = requestedWidth === undefined
- ? 3
- : clamp(Math.min(Math.floor((requestedWidth - 8) / (text.length * 6)), Math.floor(requestedWidth / 240) + 1), 1, 3);
- const padding = scale * 2;
- const naturalWidth = padding * 2 + text.length * 6 * scale - scale;
- const width = Math.max(requestedWidth ?? naturalWidth, naturalWidth);
- const rawHeight = padding * 2 + 7 * scale;
- const height = rawHeight + rawHeight % 2;
- const bytes = Buffer.alloc(width * height * 3, 12);
- let left = padding;
- for (const character of text) {
- const glyph = GLYPHS[character];
- assert(glyph !== undefined, `cannot draw time label character ${character}`);
- for (let row = 0; row < glyph.length; row += 1) {
- for (let column = 0; column < glyph[row]!.length; column += 1) {
- if (glyph[row]![column] !== "1") continue;
- for (let y = 0; y < scale; y += 1) {
- for (let x = 0; x < scale; x += 1) {
- const pixel = ((padding + row * scale + y) * width + left + column * scale + x) * 3;
- bytes[pixel] = 245;
- bytes[pixel + 1] = 245;
- bytes[pixel + 2] = 245;
- }
- }
- }
- }
- left += 6 * scale;
- }
- return { width, height, bytes };
-}
-
-function rawVideoInput(label: RasterLabel, frameRate: number): readonly string[] {
- return [
- "-f", "rawvideo", "-pixel_format", "rgb24", "-video_size", `${label.width}x${label.height}`,
- "-framerate", String(frameRate), "-i", "pipe:0",
- ];
-}
-
-export async function cutClip(
- source: string,
- start: number,
- end: number,
- target: string,
- labelInfo?: Pick<VideoProbe, "frameRate">,
-): Promise<void> {
- assert(end > start, `the clip must end after it starts (${start} to ${end})`);
- const seconds = round(end - start);
- const common = ["-c:v", "libx264", "-preset", "veryfast", "-crf", "23", "-c:a", "aac", "-b:a", "96k", "-movflags", "+faststart"];
- if (labelInfo === undefined) {
- await runProcess("ffmpeg", [
- "-hide_banner", "-loglevel", "error", "-y", ...openAt(source, start), "-t", String(seconds), ...common, target,
- ]);
- return;
- }
- const temporary = await mkdtemp(join(tmpdir(), "hypit-labeled-clip-"));
- const clean = join(temporary, "clean.mp4");
- try {
- await cutClip(source, start, end, clean);
- const rate = clamp(Math.ceil(labelInfo.frameRate || 10), 1, 30);
- const count = Math.max(1, Math.ceil(seconds * rate));
- const first = rasterLabel(timecode(start));
- function* labels(): Iterable<Uint8Array> {
- yield first.bytes;
- for (let index = 1; index < count; index += 1) yield rasterLabel(timecode(start + index / rate)).bytes;
- }
- await runProcessWithInput("ffmpeg", [
- "-hide_banner", "-loglevel", "error", "-y", "-i", clean, ...rawVideoInput(first, rate),
- "-t", String(seconds), "-filter_complex", "[0:v][1:v]overlay=8:8:eof_action=repeat[v]",
- "-map", "[v]", "-map", "0:a?", ...common, target,
- ], labels());
- } finally {
- await rm(temporary, { recursive: true, force: true });
- }
-}
-
-type CutSpan = { readonly start: number; readonly end: number };
-
-function keptSpan(raw: string, duration: number): CutSpan {
- const parts = raw.split(":");
- assert(parts.length === 2 && parts.every((part) => part.trim().length > 0), `--keep needs start:end in seconds, got ${raw}`);
- const [start, end] = parts.map(Number);
- assert(Number.isFinite(start) && Number.isFinite(end) && start! >= 0 && end! > start! && end! <= duration + 0.001,
- `--keep ${raw} must satisfy 0 <= start < end <= ${duration} s`);
- return { start: start!, end: end! };
-}
-
-/** Decode the selected parts once, join them on a new local clock, and preserve only existing streams. */
-async function cutProduction(source: string, spans: readonly CutSpan[], target: string, info: MediaProbe): Promise<void> {
- const seek = Math.max(0, spans[0]!.start - SEEK_RUN_UP);
- const labels: string[] = [];
- const filters: string[] = [];
- const videoInputs = spans.map((_, index) => `vsrc${index}`);
- const audioInputs = spans.map((_, index) => `asrc${index}`);
- if (info.hasVideo && spans.length > 1) filters.push(`[0:v:0]split=${spans.length}${videoInputs.map((item) => `[${item}]`).join("")}`);
- if (info.hasAudio && spans.length > 1) filters.push(`[0:a:0]asplit=${spans.length}${audioInputs.map((item) => `[${item}]`).join("")}`);
- for (const [index, span] of spans.entries()) {
- const start = round(span.start - seek);
- const end = round(span.end - seek);
- if (info.hasVideo) filters.push(`[${spans.length === 1 ? "0:v:0" : videoInputs[index]}]trim=start=${start}:end=${end},setpts=PTS-STARTPTS[v${index}]`);
- if (info.hasAudio) filters.push(`[${spans.length === 1 ? "0:a:0" : audioInputs[index]}]atrim=start=${start}:end=${end},asetpts=PTS-STARTPTS[a${index}]`);
- labels.push(`${info.hasVideo ? `[v${index}]` : ""}${info.hasAudio ? `[a${index}]` : ""}`);
- }
- if (spans.length > 1) filters.push(`${labels.join("")}concat=n=${spans.length}:v=${info.hasVideo ? 1 : 0}:a=${info.hasAudio ? 1 : 0}${info.hasVideo ? "[v]" : ""}${info.hasAudio ? "[a]" : ""}`);
- const videoLabel = spans.length === 1 ? "[v0]" : "[v]";
- const audioLabel = spans.length === 1 ? "[a0]" : "[a]";
- await runProcess("ffmpeg", [
- "-hide_banner", "-loglevel", "error", "-y",
- ...(seek > 0 ? ["-ss", String(round(seek))] : []), "-i", source,
- "-filter_complex", filters.join(";"),
- ...(info.hasVideo ? ["-map", videoLabel, "-c:v", "libx264", "-preset", "medium", "-crf", "17", "-pix_fmt", "yuv420p", "-fps_mode", "vfr",
- ...([".mp4", ".mov"].includes(extname(target).toLowerCase()) ? ["-movflags", "+faststart"] : [])] : []),
- ...(info.hasAudio ? ["-map", audioLabel, "-c:a", ...(info.hasVideo ? ["aac", "-b:a", "192k"] : ["pcm_s24le"])] : []),
- target,
- ]);
-}
-
-/** Publish a completed cut without overwriting a file another process may have created meanwhile. */
-async function writeCut(
- source: string, spans: readonly CutSpan[], target: string, info: MediaProbe, labeled: boolean,
-): Promise<void> {
- const work = await mkdtemp(join(dirname(target), ".hypit-cut-"));
- const staged = join(work, `cut${extname(target)}`);
- try {
- if (labeled) {
- requireVideo(info, source);
- await cutClip(source, spans[0]!.start, spans[0]!.end, staged, info);
- } else await cutProduction(source, spans, staged, info);
- await link(staged, target);
- } finally {
- await rm(work, { recursive: true, force: true });
- }
-}
-
-export async function cutFrame(source: string, at: number, target: string, labelTime = false): Promise<number> {
- if (!labelTime) {
- const jump = Math.max(0, at - SEEK_RUN_UP);
- const output = await runProcessOutput("ffmpeg", [
- "-hide_banner", "-loglevel", "info", "-y", "-copyts", "-start_at_zero",
- ...(jump > 0 ? ["-ss", String(jump)] : []), "-i", source,
- "-vf", `trim=start=${at},showinfo`, "-frames:v", "1", "-fps_mode", "passthrough", ...JPEG, target,
- ]);
- const base = /config in time_base:\s*(\d+)\/(\d+)/u.exec(output.stderr);
- const pts = /\bn:\s*0\s+pts:\s*(-?\d+)/u.exec(output.stderr);
- assert(base !== null && pts !== null, `no video frame exists at or after ${at} s`);
- return Number(pts[1]) * Number(base[1]) / Number(base[2]);
- }
- const temporary = await mkdtemp(join(tmpdir(), "hypit-labeled-frame-"));
- const clean = join(temporary, "clean.jpg");
- try {
- const actual = await cutFrame(source, at, clean);
- const label = rasterLabel(timecode(actual));
- await runProcessWithInput("ffmpeg", [
- "-hide_banner", "-loglevel", "error", "-y", "-i", clean, ...rawVideoInput(label, 1),
- "-filter_complex", "[0:v][1:v]overlay=8:8[out]", "-map", "[out]", "-frames:v", "1", ...JPEG, target,
- ], label.bytes);
- return actual;
- } finally {
- await rm(temporary, { recursive: true, force: true });
- }
-}
-
-const TILE_COLUMNS = 3;
-const TILE_CELL_WIDTH = 480;
-/** A compact overview default. Callers choose denser samples for fast changes. */
-export function tileFrameCount(seconds: number): number { return clamp(Math.round(seconds * 1.5), 4, 9); }
-
-export function tileSampleTimes(start: number, end: number, frameCount: number): readonly number[] {
- assert(end > start, `the stretch must end after it starts (${start} to ${end})`);
- assert(Number.isSafeInteger(frameCount) && frameCount >= 2, "a grid needs at least two frames");
- return Array.from({ length: frameCount }, (_, index) => round(start + (index + 0.5) * (end - start) / frameCount));
-}
-
-function escapeMarkup(value: string): string {
- return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
-}
-
-async function frameLabel(at: number, width: number, words?: FrameWords): Promise<Buffer> {
- const lines = [timecode(at)];
- if (words !== undefined) {
- lines.push(words.active.length === 0 ? "No timed word at this frame" : words.active.map((word) =>
- `<b>${escapeMarkup(word.text)}</b> ${word.start!.toFixed(3)}–${word.end!.toFixed(3)} s`).join("\n"));
- if (words.context.length > 0) lines.push(words.context.map((word) => words.active.includes(word)
- ? `<span foreground="#ffdc80"><b>${escapeMarkup(word.text)}</b></span>` : escapeMarkup(word.text)).join(" "));
- }
- const text = await sharp({ text: {
- text: `<span foreground="#f5f5f5">${lines.join("\n")}</span>`,
- font: `sans ${Math.max(12, Math.round(width / 28))}`, width: width - 16, rgba: true, wrap: "word-char",
- } }).png().toBuffer({ resolveWithObject: true });
- return sharp({ create: { width, height: text.info.height + 16, channels: 3, background: "#0c0c0c" } })
- .composite([{ input: text.data, left: 8, top: 8 }]).png().toBuffer();
-}
-
-type SampledFrame = { readonly requestedAt: number; readonly at: number; readonly words?: FrameWords };
-
-export async function tileFrames(
- source: string,
- times: readonly number[],
- target: string,
- cellWidth: number,
- columns: number,
- words?: readonly TranscriptWord[],
-): Promise<readonly SampledFrame[]> {
- assert(times.length >= 1, "a grid needs at least one frame");
- const temporary = await mkdtemp(join(tmpdir(), "hypit-tile-"));
- try {
- const frames: SampledFrame[] = [];
- const cells: { path: string; label: Buffer }[] = [];
- for (let index = 0; index < times.length; index += 1) {
- const at = times[index]!;
- const path = join(temporary, `${index}.jpg`);
- const actual = await cutFrame(source, at, path);
- const frameWords = words === undefined ? undefined : wordsAt(words, actual);
- frames.push({ requestedAt: at, at: actual, ...(frameWords === undefined ? {} : { words: frameWords }) });
- cells.push({ path, label: await frameLabel(actual, cellWidth, frameWords) });
- }
- await writeFrameGrid(cells, target, cellWidth, columns);
- return frames;
- } finally {
- await rm(temporary, { recursive: true, force: true });
- }
-}
-
-/**
- * Adjacent-frame visual change candidates. Scores are mechanical evidence, not editorial shots.
- */
-const DEFAULT_BOUNDARY_RATE = 12;
-const DEFAULT_BOUNDARY_THRESHOLD = 0.1;
-export type VisualBoundary = { readonly at: number; readonly score: number };
-export async function visualBoundaries(
- source: string,
- sampleRate = DEFAULT_BOUNDARY_RATE,
- threshold = DEFAULT_BOUNDARY_THRESHOLD,
-): Promise<readonly VisualBoundary[]> {
- const bytes = await runProcess("ffmpeg", [
- "-hide_banner", "-loglevel", "error", "-i", source, "-vf", `fps=${sampleRate},scale=32:32,format=rgb24`, "-f", "rawvideo", "-",
- ]);
- const stride = 32 * 32 * 3;
- const frames: Uint8Array[] = [];
- for (let index = 0; index + stride <= bytes.byteLength; index += stride) frames.push(bytes.subarray(index, index + stride));
- const candidates: VisualBoundary[] = [];
- for (let index = 1; index < frames.length; index += 1) {
- const before = frames[index - 1]!;
- const after = frames[index]!;
- let total = 0;
- for (let byte = 0; byte < after.length; byte += 1) total += Math.abs(after[byte]! - before[byte]!);
- const score = total / after.length / 255;
- if (score >= threshold) candidates.push({ at: round(index / sampleRate), score: round(score) });
- }
- return candidates;
-}
-
-// ---------------------------------------------------------------------------------------------------
-// Commands
-
-const SAMPLE_OPTIONS = ["--start", "--end", "--at", "--every", "--transcript", "--around", "--occurrence", "--padding"];
-
-async function transcriptOption(parsed: Parsed, cwd: string): Promise<readonly TranscriptWord[] | undefined> {
- const path = parsed.options.get("--transcript");
- return path === undefined ? undefined : readTranscript(resolve(cwd, path));
-}
-
-export function intervalSamples(start: number, end: number, every: number): readonly number[] {
- assert(Number.isFinite(start) && start >= 0 && Number.isFinite(end) && end > start, "a sample range needs 0 <= start < end");
- assert(Number.isFinite(every) && every >= 0.001, "--every must be at least 0.001 seconds");
- return Array.from({ length: Math.ceil((end - start) / every) }, (_, index) => round(start + index * every))
- .filter((time) => time < end);
-}
-
-function sampleRange(parsed: Parsed, duration: number, words?: readonly TranscriptWord[]): { start: number; end: number } {
- const around = parsed.options.get("--around");
- if (around !== undefined) {
- assert(words !== undefined, "--around requires --transcript");
- assert(!parsed.options.has("--start") && !parsed.options.has("--end"), "choose --around or --start/--end");
- const matches = phraseRanges(words, around);
- assert(matches.length > 0, `No timed phrase matches ${JSON.stringify(around)}`);
- assert(matches.length === 1 || parsed.options.has("--occurrence"),
- `The phrase occurs ${matches.length} times: ${matches.map((match, index) => `${index + 1}: ${match.start}–${match.end}s`).join(", ")}. Choose --occurrence <n> or --start/--end.`);
- const occurrence = integerOption(parsed, "--occurrence", 1, 1);
- const match = matches[occurrence - 1];
- assert(match !== undefined, `--occurrence ${occurrence} is beyond the ${matches.length} matches`);
- const padding = secondsOption(parsed, "--padding", 0.3);
- const start = Math.max(0, round(match.start - padding));
- const end = Math.min(duration, round(match.end + padding));
- assert(end > start, "the phrase lies outside the input media; use its matching transcript");
- return { start, end };
- }
- assert(!parsed.options.has("--occurrence") && !parsed.options.has("--padding"), "--occurrence and --padding apply to --around");
- const start = secondsOption(parsed, "--start", 0);
- const end = secondsOption(parsed, "--end", duration);
- assert(end > start && end <= duration, `range must satisfy 0 <= start < end <= ${duration} s`);
- return { start, end };
-}
-
-function sampleTimes(parsed: Parsed, duration: number, words?: readonly TranscriptWord[], requireEvery = false): readonly number[] {
- const at = parsed.options.get("--at");
- if (at !== undefined) {
- for (const key of ["--start", "--end", "--every", "--frames", "--around", "--occurrence", "--padding"]) {
- assert(!parsed.options.has(key), `--at cannot be combined with ${key}`);
- }
- const times = secondsList(at, "--at", 1);
- assert(times.every((time) => time < duration), `a frame time must be before the end of the file (${duration} s)`);
- assert(times.every((time, index) => index === 0 || time > times[index - 1]!), "sample times must be strictly increasing");
- return times;
- }
- const { start, end } = sampleRange(parsed, duration, words);
- const every = parsed.options.get("--every");
- assert(every === undefined || !parsed.options.has("--frames"), "choose --every or --frames");
- assert(!requireEvery || every !== undefined, "frames requires --at <s,s,…> or --every <seconds>");
- const times = every === undefined
- ? tileSampleTimes(start, end, integerOption(parsed, "--frames", tileFrameCount(end - start), 2))
- : intervalSamples(start, end, Number(every));
- assert(times.length > 0 && times.every((time) => time < duration), "the range needs sample times before the media ends");
- assert(times.every((time, index) => index === 0 || time > times[index - 1]!), "sample times must be distinct to the nearest millisecond");
- return times;
-}
-
-async function probe(argv: readonly string[], io: CliIo, cwd: string): Promise<void> {
- const parsed = parseArguments(argv, []);
- const source = await sourceFile(parsed, cwd);
- const info = await probeMedia(source);
- if (parsed.json) { io.write(`${JSON.stringify({ path: source, ...info }, null, 2)}\n`); return; }
- io.write(`${source}\n ${info.duration} s ${info.hasVideo
- ? `${info.width}×${info.height} ${info.frameRate > 0 ? `${info.frameRate} fps` : "still"} ${info.hasAudio ? "with audio" : "no audio"}`
- : "audio only"}\n`);
-}
-
-async function cut(argv: readonly string[], io: CliIo, cwd: string): Promise<void> {
- const parsed = parseArguments(argv, ["--start", "--end", "--keep", "--to"], ["--label-time"], ["--keep"]);
- const source = await sourceFile(parsed, cwd);
- const info = await probeMedia(source);
- const kept = parsed.repeated.get("--keep") ?? [];
- assert(kept.length === 0 || (!parsed.options.has("--start") && !parsed.options.has("--end")),
- "choose --keep intervals or --start/--end");
- const spans = kept.length > 0 ? kept.map((item) => keptSpan(item, info.duration)) : [{
- start: secondsOption(parsed, "--start", 0), end: secondsOption(parsed, "--end", info.duration),
- }];
- for (const [index, span] of spans.entries()) {
- assert(span.end > span.start && span.end <= info.duration + 0.001,
- `range must satisfy 0 <= start < end <= ${info.duration} s`);
- if (index > 0) assert(span.start >= spans[index - 1]!.end, "--keep intervals must be ordered and non-overlapping");
- }
- const labeled = parsed.flags.has("--label-time");
- assert(!labeled || (info.hasVideo && spans.length === 1), "--label-time needs one video interval");
- const target = await destination(parsed, cwd, "the clip to write, for example notes/hook.mp4");
- if (!info.hasVideo) assert(extname(target).toLowerCase() === ".wav", "--to must end in .wav for audio-only media");
- await writeCut(source, spans, target, info, labeled);
- const output = await probeMedia(target);
- const requestedSeconds = round(spans.reduce((total, span) => total + span.end - span.start, 0));
- if (parsed.json) {
- let outputAt = 0;
- const mapping = spans.map((span) => {
- const item = { sourceStart: span.start, sourceEnd: span.end,
- nominalOutputStart: round(outputAt), nominalOutputEnd: round(outputAt + span.end - span.start) };
- outputAt += span.end - span.start;
- return item;
- });
- io.write(`${JSON.stringify({ path: target, ...(spans.length === 1 ? { start: spans[0]!.start, end: spans[0]!.end } : {}),
- spans, mapping, seconds: requestedSeconds, actualSeconds: output.duration, hasVideo: output.hasVideo, hasAudio: output.hasAudio, labeled }, null, 2)}\n`);
- return;
- }
- io.write(`${target}\n ${spans.map((span) => `${span.start}–${span.end} s`).join(" + ")} (${output.duration} s output)${labeled ? ", source time visible" : ""}\n`);
-}
-
-async function frames(argv: readonly string[], io: CliIo, cwd: string): Promise<void> {
- const parsed = parseArguments(argv, [...SAMPLE_OPTIONS, "--to"], ["--label-time", "--every-frame"]);
- if (parsed.flags.has("--every-frame")) { await nativeFrames(parsed, io, cwd, false); return; }
- const source = await sourceFile(parsed, cwd);
- const info = await probeMedia(source);
- requireVideo(info, source);
- const words = await transcriptOption(parsed, cwd);
- const times = sampleTimes(parsed, info.duration, words, true);
- const to = await destinationDirectory(parsed, cwd, "the new directory to write the frames into");
- const staging = await mkdtemp(join(dirname(to), ".hypit-frames-"));
- const labeled = parsed.flags.has("--label-time") || words !== undefined;
- const written: (SampledFrame & { readonly path: string })[] = [];
- try {
- for (const time of times) {
- const name = `frame-${time.toFixed(3).replace(".", "_")}s.jpg`;
- const frame = words === undefined
- ? { requestedAt: time, at: await cutFrame(source, time, join(staging, name), labeled) }
- : (await tileFrames(source, [time], join(staging, name), info.width, 1, words))[0]!;
- written.push({ ...frame, path: join(to, name) });
- }
- await rename(staging, to);
- } catch (error) {
- await rm(staging, { recursive: true, force: true });
- throw error;
- }
- if (parsed.json) { io.write(`${JSON.stringify({ directory: to, labeled, frames: written }, null, 2)}\n`); return; }
- io.write(`${to}\n ${written.length} ${labeled ? "time-labeled " : ""}${written.length === 1 ? "frame" : "frames"} from ${written[0]!.at} s to ${written.at(-1)!.at} s\n`);
-}
-
-async function tile(argv: readonly string[], io: CliIo, cwd: string): Promise<void> {
- const parsed = parseArguments(argv, [...SAMPLE_OPTIONS, "--frames", "--cell", "--columns", "--to"]);
- const source = await sourceFile(parsed, cwd);
- const info = await probeMedia(source);
- requireVideo(info, source);
- const words = await transcriptOption(parsed, cwd);
- const times = sampleTimes(parsed, info.duration, words);
- // Preserve source width unless an exceptionally tiny input needs room for a legible timecode.
- const cell = integerOption(parsed, "--cell", Math.max(80, Math.min(TILE_CELL_WIDTH, info.width)), 80);
- const columns = integerOption(parsed, "--columns", TILE_COLUMNS, 1);
- const target = await destination(parsed, cwd, "the grid image to write, for example notes/hook-grid.jpg");
- const frames = await tileFrames(source, times, target, cell, columns, words);
- const rows = Math.ceil(times.length / columns);
- if (parsed.json) { io.write(`${JSON.stringify({ path: target, samples: times, columns, rows, cellWidth: cell, frames }, null, 2)}\n`); return; }
- io.write(`${target}\n ${times.length} labeled frames, ${columns}×${rows}, ${cell} px cells\n ${times.map((at) => `${at} s`).join(" ")}\n`);
-}
-
-type TileRange = {
- readonly id?: string;
- readonly start: number;
- readonly end: number;
- readonly frames?: number;
- readonly every?: number;
-};
-
-function tileRange(value: unknown, index: number, duration: number): TileRange {
- assert(typeof value === "object" && value !== null && !Array.isArray(value), `range ${index + 1} must be an object`);
- const raw = value as Record<string, unknown>;
- assert(typeof raw.start === "number" && Number.isFinite(raw.start) && raw.start >= 0, `range ${index + 1}.start must be non-negative seconds`);
- assert(typeof raw.end === "number" && Number.isFinite(raw.end) && raw.end > raw.start, `range ${index + 1}.end must be after its start`);
- assert(raw.end <= duration, `range ${index + 1}.end is past the end of the file (${duration} s)`);
- assert(raw.id === undefined || (typeof raw.id === "string" && /^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(raw.id)), `range ${index + 1}.id must be a safe file name`);
- assert(raw.frames === undefined || (Number.isSafeInteger(raw.frames) && (raw.frames as number) >= 2), `range ${index + 1}.frames must be a whole number of at least 2`);
- assert(raw.every === undefined || (typeof raw.every === "number" && Number.isFinite(raw.every) && raw.every >= 0.001), `range ${index + 1}.every must be at least 0.001 seconds`);
- assert(raw.frames === undefined || raw.every === undefined, `range ${index + 1} must choose frames or every`);
- return { start: raw.start, end: raw.end, ...(raw.id === undefined ? {} : { id: raw.id as string }),
- ...(raw.frames === undefined ? {} : { frames: raw.frames as number }), ...(raw.every === undefined ? {} : { every: raw.every as number }) };
-}
-
-async function tiles(argv: readonly string[], io: CliIo, cwd: string): Promise<void> {
- const parsed = parseArguments(argv, [...SAMPLE_OPTIONS, "--ranges", "--frames", "--cell", "--columns", "--rows", "--to"], ["--every-frame"]);
- if (parsed.flags.has("--every-frame")) { await nativeFrames(parsed, io, cwd, true); return; }
- const source = await sourceFile(parsed, cwd);
- const info = await probeMedia(source);
- requireVideo(info, source);
- const words = await transcriptOption(parsed, cwd);
- const rangesPath = parsed.options.get("--ranges");
- let ranges: { id?: string; start: number; end: number; times: readonly number[] }[];
- if (rangesPath === undefined) {
- const times = sampleTimes(parsed, info.duration, words);
- const range = parsed.options.has("--at")
- ? { start: times[0]!, end: times.at(-1)! }
- : sampleRange(parsed, info.duration, words);
- ranges = [{ ...range, times }];
- } else {
- for (const key of ["--start", "--end", "--at", "--around", "--padding", "--occurrence"]) {
- assert(!parsed.options.has(key), `--ranges cannot be combined with ${key}`);
- }
- assert(!parsed.options.has("--frames") || !parsed.options.has("--every"), "choose --frames or --every");
- const raw = JSON.parse(await readFile(resolve(cwd, rangesPath), "utf8")) as unknown;
- assert(Array.isArray(raw) && raw.length > 0, `${rangesPath} must contain a non-empty JSON array`);
- ranges = raw.map((value, index) => {
- const range = tileRange(value, index, info.duration);
- const options = new Map(parsed.options);
- options.set("--start", String(range.start)); options.set("--end", String(range.end));
- if (range.frames !== undefined) { options.delete("--every"); options.set("--frames", String(range.frames)); }
- if (range.every !== undefined) { options.delete("--frames"); options.set("--every", String(range.every)); }
- return { ...range, times: sampleTimes({ ...parsed, options }, info.duration, words) };
- });
- const ids = ranges.flatMap((range) => range.id === undefined ? [] : [range.id]);
- assert(new Set(ids).size === ids.length, "range ids must be unique");
- }
- const cell = integerOption(parsed, "--cell", Math.max(80, Math.min(TILE_CELL_WIDTH, info.width)), 80);
- const columns = integerOption(parsed, "--columns", TILE_COLUMNS, 1);
- const rows = integerOption(parsed, "--rows", 3, 1);
- const perPage = columns * rows;
- const to = await destinationDirectory(parsed, cwd, "the new directory to write the grids into");
- const staging = await mkdtemp(join(dirname(to), ".hypit-tiles-"));
- const written: { id?: string; start: number; end: number; samples: readonly number[]; path: string; frames: readonly SampledFrame[] }[] = [];
- try {
- for (const [index, range] of ranges.entries()) {
- const stem = range.id ?? `${range.start.toFixed(3).replace(".", "_")}s-${range.end.toFixed(3).replace(".", "_")}s`;
- for (let offset = 0; offset < range.times.length; offset += perPage) {
- const times = range.times.slice(offset, offset + perPage);
- const page = range.times.length > perPage ? `-p${String(offset / perPage + 1).padStart(3, "0")}` : "";
- const name = `${String(index + 1).padStart(3, "0")}-${stem}${page}.jpg`;
- const frames = await tileFrames(source, times, join(staging, name), cell, columns, words);
- written.push({ ...(range.id === undefined ? {} : { id: range.id }), start: range.start, end: range.end,
- samples: times, path: join(to, name), frames });
- }
- }
- await rename(staging, to);
- } catch (error) {
- await rm(staging, { recursive: true, force: true });
- throw error;
- }
- if (parsed.json) { io.write(`${JSON.stringify({ directory: to, columns, rows, cellWidth: cell, grids: written }, null, 2)}\n`); return; }
- io.write(`${to}\n ${written.length} time-labeled ${written.length === 1 ? "grid" : "grids"}\n`);
-}
-
-/** Native-frame observation: each requested interval is decoded once, then paginated. */
-async function nativeFrames(parsed: Parsed, io: CliIo, cwd: string, grid: boolean): Promise<void> {
- for (const key of ["--at", "--every", "--frames"]) assert(!parsed.options.has(key), `--every-frame cannot be combined with ${key}`);
- const source = await sourceFile(parsed, cwd);
- const info = await probeMedia(source);
- requireVideo(info, source);
- const words = await transcriptOption(parsed, cwd);
- let ranges: TileRange[];
- const rangeFile = parsed.options.get("--ranges");
- if (rangeFile === undefined) ranges = [sampleRange(parsed, info.duration, words)];
- else {
- for (const key of ["--start", "--end", "--around", "--padding", "--occurrence"]) assert(!parsed.options.has(key), `--ranges cannot be combined with ${key}`);
- const raw = JSON.parse(await readFile(resolve(cwd, rangeFile), "utf8"));
- assert(Array.isArray(raw) && raw.length > 0, "--ranges needs a non-empty JSON array");
- ranges = raw.map((value, index) => tileRange(value, index, info.duration));
- assert(ranges.every(range => range.frames === undefined && range.every === undefined), "Native ranges cannot specify frames or every");
- }
- const cell = integerOption(parsed, "--cell", Math.max(80, Math.min(TILE_CELL_WIDTH, info.width)), 80);
- const columns = integerOption(parsed, "--columns", TILE_COLUMNS, 1);
- const rows = integerOption(parsed, "--rows", 3, 1);
- const to = await destinationDirectory(parsed, cwd, "the new directory for native frame evidence");
- const staging = await mkdtemp(join(dirname(to), ".hypit-native-"));
- const written: { at: number; path: string }[] = [];
- const grids: { path: string; frames: readonly { at: number }[] }[] = [];
- try {
- for (const [rangeIndex, range] of ranges.entries()) {
- const decodedDirectory = join(staging, "decoded");
- const decoded = await decodeMediaFrames(source, range.start, range.end, decodedDirectory);
- if (grid) {
- const perPage = columns * rows;
- for (let offset = 0; offset < decoded.length; offset += perPage) {
- const page = decoded.slice(offset, offset + perPage);
- const cells = [];
- for (const frame of page) cells.push({ path: frame.path, label: await frameLabel(frame.at, cell,
- words === undefined ? undefined : wordsAt(words, frame.at)) });
- const name = `${String(rangeIndex + 1).padStart(3, "0")}-${range.id ?? "frames"}-p${String(offset / perPage + 1).padStart(3, "0")}.jpg`;
- await writeFrameGrid(cells, join(staging, name), cell, columns);
- grids.push({ path: join(to, name), frames: page.map(frame => ({ at: frame.at })) });
- }
- } else for (const [index, frame] of decoded.entries()) {
- const name = `frame-${String(index).padStart(9, "0")}.jpg`;
- const target = join(staging, name);
- if (parsed.flags.has("--label-time") || words !== undefined) await writeFrameGrid([{ path: frame.path,
- label: await frameLabel(frame.at, info.width, words === undefined ? undefined : wordsAt(words, frame.at)) }], target, info.width, 1);
- else await copyFile(frame.path, target);
- written.push({ at: frame.at, path: join(to, name) });
- }
- await rm(decodedDirectory, { recursive: true, force: true });
- }
- await rename(staging, to);
- } catch (error) { await rm(staging, { recursive: true, force: true }); throw error; }
- if (parsed.json) io.write(`${JSON.stringify({ directory: to, ...(grid ? { grids } : { frames: written }) }, null, 2)}\n`);
- else io.write(`${to}\n ${grid ? `${grids.length} grids` : `${written.length} frames`} from continuous source decoding\n`);
-}
-
-async function boundaries(argv: readonly string[], io: CliIo, cwd: string): Promise<void> {
- const parsed = parseArguments(argv, ["--rate", "--threshold"]);
- const source = await sourceFile(parsed, cwd);
- requireVideo(await probeMedia(source), source);
- const rate = numberOption(parsed, "--rate", DEFAULT_BOUNDARY_RATE, 1, 120);
- const threshold = numberOption(parsed, "--threshold", DEFAULT_BOUNDARY_THRESHOLD, 0, 1);
- const candidates = await visualBoundaries(source, rate, threshold);
- if (parsed.json) { io.write(`${JSON.stringify({ path: source, sampleRate: rate, threshold, candidates }, null, 2)}\n`); return; }
- const shown = candidates.slice(0, 40);
- const remaining = candidates.length - shown.length;
- io.write(`${source}\n ${candidates.length} visual-change ${candidates.length === 1 ? "candidate" : "candidates"} at ${rate} samples/s; scores are not shot labels\n${
- shown.map((candidate) => ` ${candidate.at} s score ${candidate.score}`).join("\n")}${remaining > 0 ? `\n … ${remaining} more; --json returns all candidates` : ""}\n`);
-}
-
-async function fetch(argv: readonly string[], io: CliIo, cwd: string): Promise<void> {
- const parsed = parseArguments(argv, ["--to"]);
- const [url] = parsed.positionals;
- assert(url !== undefined && isVideoUrl(url), "name an http or https link first");
- assert(parsed.positionals.length === 1, "fetch takes exactly one link");
- const target = await destination(parsed, cwd, "the video file to write, for example reference/source.mp4");
- assert([".mp4", ".mkv", ".webm", ".mov"].includes(extname(target).toLowerCase()), "--to must end in .mp4, .mkv, .webm or .mov");
- await downloadVideo(url, target);
- const info = await probeMedia(target);
- requireVideo(info, target);
- if (parsed.json) { io.write(`${JSON.stringify({ path: target, url, ...info }, null, 2)}\n`); return; }
- io.write(`${target}\n ${info.duration} s ${info.width}×${info.height} ${info.hasAudio ? "with audio" : "no audio"}\n`);
-}
-
-// ---------------------------------------------------------------------------------------------------
-// Entry
-
-export function writeMediaHelp(io: CliIo, topic?: MediaCommand): void {
- const sections: Record<MediaCommand, readonly string[]> = {
- probe: [" hypit media probe <file>", " Duration and available audio/video streams; video adds size and frame rate."],
- cut: [" hypit media cut <file> [--start <s> --end <s> | --keep <start:end> ...] [--label-time] --to <clip.mp4|clip.wav>",
- " Keep one stretch or join ordered stretches from one source. Audio-only outputs WAV; MP4 is a useful video target.",
- " --label-time overlays source time on a single video evidence copy."],
- frames: [" hypit media frames <file> (--at <s,s,…> | --every <s> | --every-frame) [--start <s> --end <s>] [--label-time] [--transcript <json>] --to <dir>",
- " Individual frames named by source time; --transcript adds word times and context below each picture."],
- tile: [" hypit media tile <file> [--start <s> --end <s> | --at <s,s,…>] [--every <s> | --frames <n>] [--transcript <json>] [--cell <px>] [--columns <n>] --to <grid.jpg>",
- " One grid. --every samples from start, excluding end; --frames chooses evenly spaced midpoints."],
- tiles: [" hypit media tiles <file> [--start <s> --end <s> | --at <s,s,…> | --ranges <json>] [--every <s> | --frames <n> | --every-frame] [--transcript <json>] [--cell <px>] [--columns <n>] [--rows <n>] --to <dir>",
- " Paginated grids (3 rows by default). --every-frame decodes every original frame once per interval, preserving actual timestamps. Range files contain { start, end, id?, frames?, every? }."],
- boundaries: [" hypit media boundaries <file> [--rate <samples/s>] [--threshold <0..1>]",
- " Mechanical adjacent-frame change candidates with scores; never editorial shot labels."],
- "prepare-fetch": [" hypit media prepare-fetch", " Explicitly prepare the pinned yt-dlp environment; does not fetch media."],
- fetch: [" hypit media fetch <url> --to <video.mp4>", " A link turned into a file with the pinned yt-dlp, video and audio together."],
- };
- const chosen = topic === undefined ? mediaCommands : [topic];
- io.write(`hypit media\nInspect and prepare media locally. No Runtime Profile, network request or project state.\n\n${
- chosen.map((item) => sections[item].join("\n")).join("\n\n")}\n\nFrames and grids accept --around <phrase> with --transcript instead of --start/--end.\n`
- + "Use --occurrence <n> for a repeated phrase; --padding <s> adds time on each side (default 0.3).\n"
- + "Transcript times must share the input media's clock. An untimed gap is labeled as such, without inferring silence.\n"
- + "Commands write only what --to names and refuse to overwrite. Add --json for the complete machine view.\n");
-}
-
-export async function runMediaCli(argv: readonly string[], io: CliIo, cwd = process.cwd()): Promise<void> {
- const command = argv[1];
- if (command === undefined || command === "--help" || argv.includes("--help")) {
- writeMediaHelp(io, isMediaCommand(command) ? command : undefined);
- return;
- }
- assert(isMediaCommand(command), `unknown media command ${command}; one of ${mediaCommands.join(", ")}`);
- const rest = argv.slice(2);
- if (command === "probe") await probe(rest, io, cwd);
- else if (command === "cut") await cut(rest, io, cwd);
- else if (command === "frames") await frames(rest, io, cwd);
- else if (command === "tile") await tile(rest, io, cwd);
- else if (command === "tiles") await tiles(rest, io, cwd);
- else if (command === "boundaries") await boundaries(rest, io, cwd);
- else if (command === "prepare-fetch") {
- const parsed = parseArguments(rest, []);
- assert(parsed.positionals.length === 0, "prepare-fetch takes no positional arguments");
- io.writeProgress?.("Preparing the selected yt-dlp environment…\n");
- const executable = prepareVideoDownload();
- io.write(parsed.json ? `${JSON.stringify({ executable })}\n` : `yt-dlp ready: ${executable}\n`);
- } else await fetch(rest, io, cwd);
-}
diff --git a/packages/video-cli/src/process.ts b/packages/video-cli/src/process.ts
deleted file mode 100644
index 669ec9d0..00000000
--- a/packages/video-cli/src/process.ts
+++ /dev/null
@@ -1,81 +0,0 @@
-import { spawn } from "node:child_process";
-import { once } from "node:events";
-
-type ProcessInput = Uint8Array | Iterable<Uint8Array> | AsyncIterable<Uint8Array>;
-type ProcessOutput = { readonly stdout: Buffer; readonly stderr: string };
-
-function run(
- executable: string,
- args: readonly string[],
- input: ProcessInput | undefined,
- timeoutMs: number,
- onStderrLine?: (line: string) => void,
-): Promise<ProcessOutput> {
- return new Promise((resolveRun, reject) => {
- const child = spawn(executable, [...args], { stdio: [input === undefined ? "ignore" : "pipe", "pipe", "pipe"], windowsHide: true });
- const out: Buffer[] = [];
- let err = "";
- let settled = false;
- const finish = (error?: Error): void => {
- if (settled) return;
- settled = true;
- clearTimeout(timer);
- if (error === undefined) resolveRun({ stdout: Buffer.concat(out), stderr: err });
- else reject(error);
- };
- const timer = setTimeout(() => { child.kill("SIGKILL"); finish(new Error(`${executable} timed out after ${timeoutMs} ms`)); }, timeoutMs);
- child.stdout?.on("data", (chunk: Buffer) => out.push(chunk));
- let pendingLine = "";
- child.stderr?.on("data", (chunk: Buffer) => {
- const text = chunk.toString("utf8");
- err = `${err}${text}`.slice(-100_000);
- if (onStderrLine !== undefined) {
- const lines = `${pendingLine}${text}`.split(/\r?\n/u);
- pendingLine = lines.pop()!;
- for (const line of lines) onStderrLine(line);
- }
- });
- child.on("error", (error) => finish(new Error(`${executable} could not start: ${error.message}`)));
- child.on("close", (code) => {
- if (code === 0) finish();
- else finish(new Error(`${executable} exited with ${code}: ${err.trim()}`));
- });
- if (input !== undefined && child.stdin !== null) {
- child.stdin.on("error", (error: NodeJS.ErrnoException) => {
- if (error.code !== "EPIPE") finish(new Error(`${executable} input failed: ${error.message}`));
- });
- void (async () => {
- const chunks: Iterable<Uint8Array> | AsyncIterable<Uint8Array> = input instanceof Uint8Array ? [input] : input;
- for await (const chunk of chunks) {
- if (!child.stdin!.write(chunk)) await once(child.stdin!, "drain");
- }
- child.stdin!.end();
- })().catch((error: unknown) => {
- if (!(error instanceof Error && "code" in error && error.code === "EPIPE")) {
- child.kill("SIGKILL");
- finish(error instanceof Error ? error : new Error(String(error)));
- }
- });
- }
- });
-}
-
-/** Run one external program to completion and return its stdout; stderr becomes the error text. */
-export async function runProcess(executable: string, args: readonly string[], timeoutMs = 300_000): Promise<Buffer> {
- return (await run(executable, args, undefined, timeoutMs)).stdout;
-}
-
-/** Successful stderr can carry tool metadata, such as the timestamp of an extracted frame. */
-export function runProcessOutput(executable: string, args: readonly string[], timeoutMs = 300_000, onStderrLine?: (line: string) => void): Promise<ProcessOutput> {
- return run(executable, args, undefined, timeoutMs, onStderrLine);
-}
-
-/** The same process boundary when a deterministic byte stream is one of the program's inputs. */
-export async function runProcessWithInput(
- executable: string,
- args: readonly string[],
- input: ProcessInput,
- timeoutMs = 300_000,
-): Promise<Buffer> {
- return (await run(executable, args, input, timeoutMs)).stdout;
-}
diff --git a/packages/video-cli/src/secret-input.ts b/packages/video-cli/src/secret-input.ts
deleted file mode 100644
index 2c8c14c8..00000000
--- a/packages/video-cli/src/secret-input.ts
+++ /dev/null
@@ -1,14 +0,0 @@
-/** Keep terminal input as bytes until a complete UTF-8 secret can be decoded. */
-export function acceptSecretBytes(raw: number[], chunk: Uint8Array): "continue" | "done" | "cancelled" {
- for (const byte of chunk) {
- if (byte === 3) return "cancelled";
- if (byte === 10 || byte === 13) return "done";
- if (byte === 8 || byte === 127) {
- while (raw.length > 0 && (raw.at(-1)! & 0xc0) === 0x80) raw.pop();
- raw.pop();
- continue;
- }
- raw.push(byte);
- }
- return "continue";
-}
diff --git a/packages/video-cli/src/snapshot.ts b/packages/video-cli/src/snapshot.ts
deleted file mode 100644
index bf939b4e..00000000
--- a/packages/video-cli/src/snapshot.ts
+++ /dev/null
@@ -1,201 +0,0 @@
-import { createReadStream, createWriteStream } from "node:fs";
-import { mkdir, mkdtemp, readFile, rename, rm, stat } from "node:fs/promises";
-import { tmpdir } from "node:os";
-import { dirname, extname, join, resolve } from "node:path";
-import { fileURLToPath, pathToFileURL } from "node:url";
-import { Readable } from "node:stream";
-import type { ReadableStream as NodeReadableStream } from "node:stream/web";
-import { pipeline } from "node:stream/promises";
-import type { CliIo } from "@hypit/cli";
-import { assertHyperframesDocument, hyperframesHtmlAssetUrls, hyperframesHtmlDomain, selectHyperframesArtifacts } from "@hypit/hyperframes";
-import type { HyperframesDocument, HyperframesHtmlProject } from "@hypit/hyperframes";
-import { FileResourceStore } from "@hypit/resource-store-fs";
-import { hyperframesFramesRequest, renderHyperframesCapabilities, renderHyperframesTypes, verifyHyperframesFrames } from "@hypit/render-hyperframes";
-import type { Need } from "@hypit/protocol";
-import { creationEnvironment, selectedProvider, providerLine, providerView } from "./creation.js";
-import type { CreationEnvironment } from "./creation.js";
-import { snapshotFrameLabel, writeFrameGrid } from "./frame-grid.js";
-
-const MEDIA_TYPES: Readonly<Record<string, string>> = {
- ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".webp": "image/webp",
- ".mp4": "video/mp4", ".webm": "video/webm", ".woff": "font/woff", ".woff2": "font/woff2", ".ttf": "font/ttf", ".otf": "font/otf",
-};
-
-async function readProject(source: string, html: string, resources: FileResourceStore): Promise<HyperframesHtmlProject> {
- const assets = [];
- const base = isSnapshotHtmlUrl(source) ? new URL(source) : pathToFileURL(source);
- for (const url of hyperframesHtmlAssetUrls(html)) {
- const address = new URL(url, base);
- let mediaType: string | undefined;
- let stream: Readable;
- if (address.protocol === "file:") {
- if (base.protocol !== "file:") throw new Error(`Network HTML cannot read local asset ${url}`);
- const path = fileURLToPath(address);
- mediaType = MEDIA_TYPES[extname(path).toLowerCase()];
- if (mediaType === undefined) throw new Error(`Unsupported snapshot asset ${url}; use compiled HTML with inline scripts and styles`);
- stream = createReadStream(path);
- } else if (address.protocol === "http:" || address.protocol === "https:") {
- const response = await fetch(address);
- if (!response.ok || response.body === null) throw new Error(`Snapshot asset ${url}: HTTP ${response.status}`);
- mediaType = response.headers.get("content-type")?.split(";")[0]?.trim();
- if (mediaType === undefined || !Object.values(MEDIA_TYPES).includes(mediaType)) {
- await response.body.cancel();
- throw new Error(`Unsupported snapshot asset ${url} (${mediaType}); use compiled HTML with inline scripts and styles`);
- }
- stream = Readable.fromWeb(response.body as NodeReadableStream<Uint8Array>);
- } else throw new Error(`Unsupported snapshot asset protocol ${address.protocol}`);
- try { assets.push({ url, artifact: await resources.putStream(stream, mediaType) }); }
- finally { stream.destroy(); }
- }
- return { html, assets };
-}
-
-const OPTIONS = ["--studio", "--to", "--at-frame", "--start-frame", "--end-frame-exclusive", "--step-frames", "--grid", "--cell", "--runtime", "--workspace"];
-
-/** Capture already treats HTTP(S) case-insensitively; snapshot must not turn HTTPS:// into a local path. */
-export function isSnapshotHtmlUrl(value: string): boolean {
- return /^https?:\/\//iu.test(value);
-}
-
-/** `--studio` is a base URL, not a host:port token. `new URL` otherwise throws TypeError. */
-export function studioDocumentUrl(studio: string): string {
- try {
- return new URL("/__studio/document", studio).href;
- } catch {
- throw new Error(`--studio needs an http(s) Studio URL, got ${studio}`);
- }
-}
-
-export function writeSnapshotHelp(io: CliIo): void {
- io.write(`hypit snapshot\nCapture exact frames from an existing compiled HyperFrames HTML programme through the selected Runtime Profile.\n\n`
- + ` hypit snapshot --studio <studio-url> --at-frame <n[,n,…]> --to <directory>\n`
- + ` hypit snapshot <index.html|HTML-URL> --at-frame <n[,n,…]> --to <directory>\n`
- + ` hypit snapshot <index.html|HTML-URL> --start-frame <n> --end-frame-exclusive <n> [--step-frames <n>] --to <directory>\n`
- + ` [--grid <columns>x<rows>] [--cell <pixels>] [--runtime <profile>] [--workspace <project>] [--json]\n\n`
- + `Frame indices are zero-based on the original programme clock. Ranges exclude the end.\n`
- + `Writes full-size PNGs and optional paginated grids. --cell controls grid image width (default 480).\n`
- + `Uses render-frames, one immediate request. Browser preparation belongs to the selected Provider.\n`
- + `HTML carries the compiled frame clock and media/font URLs; scripts and styles are inline.\nStudio exposes its current programme at http://<host>:<port>/__studio/visual.html.\n`);
-}
-
-export async function runSnapshotCli(argv: readonly string[], io: CliIo, environment: CreationEnvironment = creationEnvironment()): Promise<void> {
- if (argv.includes("--help")) { writeSnapshotHelp(io); return; }
- const options = new Map<string, string>();
- const positionals = [];
- const json = argv.includes("--json");
- for (let index = 1; index < argv.length; index++) {
- const arg = argv[index]!;
- if (["--json", "--debug", "--verbose", "--no-color"].includes(arg)) continue;
- if (arg === "--color") { index++; continue; }
- if (!arg.startsWith("--")) { positionals.push(arg); continue; }
- if (!OPTIONS.includes(arg)) throw new Error(`Unknown snapshot option ${arg}`);
- if (options.has(arg)) throw new Error(`${arg} cannot be repeated`);
- const value = argv[++index];
- if (!value || value.startsWith("--")) throw new Error(`${arg} requires a value`);
- options.set(arg, value);
- }
- const studio = options.get("--studio");
- if (positionals.length !== (studio === undefined ? 1 : 0) || !options.has("--to")) throw new Error("snapshot takes one HTML input or --studio <url>, and --to <directory>");
- const integer = (raw: string | undefined, label: string, minimum = 0): number => {
- if (raw === undefined || !/^\d+$/u.test(raw) || !Number.isSafeInteger(Number(raw)) || Number(raw) < minimum) throw new Error(`${label} needs an integer >= ${minimum}`);
- return Number(raw);
- };
- const source = studio === undefined
- ? isSnapshotHtmlUrl(positionals[0]!) ? positionals[0]! : resolve(environment.cwd, positionals[0]!)
- : studioDocumentUrl(studio);
- let document: HyperframesDocument | undefined;
- let html: string;
- if (studio !== undefined) {
- const response = await fetch(source);
- if (!response.ok) throw new Error(`Studio programme: HTTP ${response.status} ${await response.text()}`);
- document = await response.json() as HyperframesDocument;
- assertHyperframesDocument(document);
- html = document.html;
- } else if (isSnapshotHtmlUrl(source)) {
- const response = await fetch(source);
- if (!response.ok) throw new Error(`Snapshot HTML: HTTP ${response.status} ${await response.text()}`);
- html = await response.text();
- } else html = await readFile(source, "utf8");
- const domain = document ?? hyperframesHtmlDomain(html);
- const explicit = options.get("--at-frame");
- let frames: number[];
- if (explicit !== undefined) {
- if (["--start-frame", "--end-frame-exclusive", "--step-frames"].some(key => options.has(key))) throw new Error("Choose --at-frame or a frame range");
- frames = explicit.split(",").map(value => integer(value, "--at-frame"));
- } else {
- const start = integer(options.get("--start-frame"), "--start-frame");
- const end = integer(options.get("--end-frame-exclusive"), "--end-frame-exclusive");
- const step = integer(options.get("--step-frames") ?? "1", "--step-frames", 1);
- if (end <= start || end > domain.frameCount) throw new Error(`The frame range must satisfy 0 <= start < end <= ${domain.frameCount}`);
- frames = Array.from({ length: Math.ceil((end - start) / step) }, (_, index) => start + index * step);
- }
- const grid = options.get("--grid")?.split("x");
- if (grid !== undefined && grid.length !== 2) throw new Error("--grid needs columns x rows, for example 4x3");
- const columns = grid === undefined ? undefined : integer(grid[0], "grid columns", 1);
- const rows = grid === undefined ? undefined : integer(grid[1], "grid rows", 1);
- if (options.has("--cell") && grid === undefined) throw new Error("--cell requires --grid");
- const cell = integer(options.get("--cell") ?? "480", "--cell", 32);
- const to = resolve(environment.cwd, options.get("--to")!);
- if (await stat(to).then(() => true, () => false)) throw new Error(`Destination ${to} already exists`);
- const temporary = await mkdtemp(join(tmpdir(), "hypit-snapshot-"));
- let staging: string | undefined;
- try {
- const resources = new FileResourceStore(temporary);
- let input: { document: HyperframesDocument } | { project: HyperframesHtmlProject };
- if (document !== undefined) {
- const selection = frames.map((frame) => ({ startFrame: frame, endFrameExclusive: frame + 1 }));
- for (const { artifact } of selectHyperframesArtifacts(document, selection)) {
- const response = await fetch(new URL(`/__studio/material/${artifact.resource}`, studio));
- if (!response.ok || response.body === null) throw new Error(`Studio material ${artifact.resource}: HTTP ${response.status}`);
- const stream = Readable.fromWeb(response.body as NodeReadableStream<Uint8Array>);
- try { await resources.writeStream(artifact, stream); }
- finally { stream.destroy(); }
- }
- input = { document };
- } else input = { project: await readProject(source, html, resources) };
- const need: Need = { id: "need:hypit-snapshot", capability: renderHyperframesCapabilities.renderFrames,
- returns: renderHyperframesTypes.frames, result: "record:hypit-snapshot", constraints: hyperframesFramesRequest({ ...input, frames }) };
- const { host, profile } = await environment.openHost(options.get("--runtime"), options.get("--workspace"));
- const provider = await selectedProvider(host, need, profile);
- if (!json) io.write(`Capturing ${frames.length} frames through ${providerLine(provider)}\n`);
- const report = json ? io.writeProgress : io.writeProgress ?? io.write;
- const fulfilled = await host.invoke(need, resources, {
- reportProgress: async progress => { report?.(` · ${progress.phase}\n`); },
- reportDiagnostic: async diagnostic => { report?.(` · ${diagnostic.message}\n`); },
- });
- if (fulfilled.value.kind !== "inline") throw new Error("The frame list came back by reference");
- verifyHyperframesFrames(fulfilled.value.value);
- const images = fulfilled.value.value;
- if (images.length !== frames.length) throw new Error(`Requested ${frames.length} frames, received ${images.length}`);
- await mkdir(dirname(to), { recursive: true });
- staging = await mkdtemp(join(dirname(to), ".hypit-snapshot-"));
- const files = [];
- for (const [index, image] of images.entries()) {
- const frame = frames[index]!;
- const name = `frame-${String(frame).padStart(9, "0")}.png`;
- const stream = await resources.open(image.resource);
- if (stream === undefined) throw new Error(`Snapshot frame ${frame} is unavailable`);
- await pipeline(stream, createWriteStream(join(staging, name), { flags: "wx" }));
- files.push({ frame, seconds: frame * domain.frameRate.denominator / domain.frameRate.numerator, path: join(to, name) });
- }
- const grids: string[] = [];
- if (columns !== undefined && rows !== undefined) {
- const count = columns * rows;
- for (let offset = 0; offset < files.length; offset += count) {
- const page = [];
- for (const file of files.slice(offset, offset + count)) page.push({ path: join(staging, `frame-${String(file.frame).padStart(9, "0")}.png`),
- label: await snapshotFrameLabel(file.frame, file.seconds, cell) });
- const name = `grid-${String(grids.length + 1).padStart(3, "0")}.jpg`;
- await writeFrameGrid(page, join(staging, name), cell, columns);
- grids.push(join(to, name));
- }
- }
- await rename(staging, to);
- staging = undefined;
- if (json) io.write(`${JSON.stringify({ format: "hypit.video-cli-snapshot@1", source, ...providerView(provider), frames: files, grids }, null, 2)}\n`);
- else io.write(`Captured ${files.length} PNGs${grids.length === 0 ? "" : ` and ${grids.length} grid${grids.length === 1 ? "" : "s"}`}\n ${to}\n`);
- } finally {
- await rm(temporary, { recursive: true, force: true });
- if (staging !== undefined) await rm(staging, { recursive: true, force: true });
- }
-}
diff --git a/packages/video-cli/src/studio-distribution.ts b/packages/video-cli/src/studio-distribution.ts
deleted file mode 100644
index 0f016127..00000000
--- a/packages/video-cli/src/studio-distribution.ts
+++ /dev/null
@@ -1,18 +0,0 @@
-/**
- * Studio Companions carried by the official video distribution.
- *
- * This is distribution policy, not Studio discovery policy: a different video
- * distribution may assemble a different set without changing Studio itself.
- */
-export const videoStudioCompanionPackages = [
- "@hypit/audio-track-studio",
- "@hypit/caption-fine-studio",
- "@hypit/comment-sticker-studio",
- "@hypit/depth-stack-studio",
- "@hypit/film-studio",
- "@hypit/visual-track-studio",
- "@hypit/ranking-studio",
- "@hypit/screen-overlay-studio",
- "@hypit/script-studio",
- "@hypit/text-fine-studio",
-] as const;
diff --git a/packages/video-cli/src/transcript.ts b/packages/video-cli/src/transcript.ts
deleted file mode 100644
index 578450ce..00000000
--- a/packages/video-cli/src/transcript.ts
+++ /dev/null
@@ -1,71 +0,0 @@
-import { readFile } from "node:fs/promises";
-
-/** The seconds-based file written by `hypit transcribe`. Missing word times stay missing. */
-export type TranscriptWord = {
- readonly text: string;
- readonly start?: number;
- readonly end?: number;
-};
-export type FrameWords = {
- readonly active: readonly TranscriptWord[];
- readonly context: readonly TranscriptWord[];
-};
-
-function assert(condition: unknown, message: string): asserts condition {
- if (!condition) throw new Error(message);
-}
-
-export async function readTranscript(path: string): Promise<readonly TranscriptWord[]> {
- const raw = JSON.parse(await readFile(path, "utf8"));
- assert(raw?.format === "hypit.transcript@1" && Array.isArray(raw.passages), `${path}: expected hypit.transcript@1`);
- return raw.passages.flatMap((passage: { words?: unknown }) => {
- assert(passage !== null && Array.isArray(passage.words), `${path}: each passage needs words`);
- return passage.words.map((word: Record<string, unknown>) => {
- assert(word !== null && typeof word.text === "string", `${path}: each word needs text`);
- const start = word.start_seconds;
- const end = word.end_seconds;
- assert(start === undefined || (typeof start === "number" && Number.isFinite(start) && start >= 0), `${path}: invalid word start`);
- assert(end === undefined || (typeof end === "number" && Number.isFinite(end) && end >= 0), `${path}: invalid word end`);
- assert(start === undefined || end === undefined || end >= start, `${path}: word end precedes start`);
- return { text: word.text, ...(start === undefined ? {} : { start }), ...(end === undefined ? {} : { end }) };
- });
- });
-}
-
-export function wordsAt(words: readonly TranscriptWord[], at: number): FrameWords {
- const active = words.filter((word) => word.start !== undefined && word.end !== undefined && word.start <= at && at < word.end);
- let anchor = active.length > 0 ? words.indexOf(active[0]!) : -1;
- if (anchor < 0) {
- let distance = Infinity;
- for (const [index, word] of words.entries()) {
- const time = word.start ?? word.end;
- if (time !== undefined && Math.abs(time - at) < distance) { anchor = index; distance = Math.abs(time - at); }
- }
- }
- const last = active.length > 0 ? words.indexOf(active.at(-1)!) : anchor;
- return { active, context: anchor < 0 ? [] : words.slice(Math.max(0, anchor - 3), last + 4) };
-}
-
-function searchable(text: string): string {
- return text.normalize("NFKC").toLowerCase().replace(/[\p{P}\p{Z}\s]/gu, "");
-}
-
-/** Find whole, consecutive transcript words; punctuation and case do not affect matching. */
-export function phraseRanges(words: readonly TranscriptWord[], text: string): readonly { start: number; end: number }[] {
- const query = searchable(text);
- assert(query.length > 0, "--around needs a word or phrase");
- const matches: { start: number; end: number }[] = [];
- for (let first = 0; first < words.length; first += 1) {
- if (searchable(words[first]!.text).length === 0) continue;
- let joined = "";
- for (let last = first; last < words.length && joined.length < query.length; last += 1) {
- joined += searchable(words[last]!.text);
- if (joined !== query) continue;
- const start = words[first]!.start;
- const end = words[last]!.end;
- assert(start !== undefined && end !== undefined, `The phrase ${JSON.stringify(text)} has missing boundary times; inspect its passage and choose --start/--end`);
- matches.push({ start, end });
- }
- }
- return matches;
-}
diff --git a/packages/video-cli/test/file-credentials.test.ts b/packages/video-cli/test/file-credentials.test.ts
deleted file mode 100644
index e9afb8f0..00000000
--- a/packages/video-cli/test/file-credentials.test.ts
+++ /dev/null
@@ -1,53 +0,0 @@
-import assert from "node:assert/strict";
-import { execFile } from "node:child_process";
-import { mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises";
-import { tmpdir } from "node:os";
-import { join } from "node:path";
-import { fileURLToPath } from "node:url";
-import { promisify } from "node:util";
-import test from "node:test";
-
-const exec = promisify(execFile);
-const launcher = fileURLToPath(new URL("../../../bin/hypit.mjs", import.meta.url));
-
-test("an explicitly selected file Store supports CLI login, repair and logout without starting execution", async (t) => {
- const root = await mkdtemp(join(tmpdir(), "hypit-cli-file-credentials-"));
- t.after(() => rm(root, { recursive: true, force: true }));
- const state = join(root, "host");
- const run = (...args: string[]) => exec(process.execPath, [launcher, ...args, "--json"], {
- cwd: root, env: { ...process.env, HYPIT_STATE_HOME: state }, timeout: 30_000, windowsHide: true,
- });
- await run("runtime", "init", "--workspace", root);
- const profilePath = join(root, "hypit.runtime.json");
- const profile = JSON.parse(await readFile(profilePath, "utf8"));
- assert.equal(profile.credentials.platform.use, "@hypit/credential-store-platform", "initialization preserves the existing starter choice");
- const directory = join(root, "chosen-credentials");
- profile.credentials = { file: { use: "@hypit/credential-store-file", config: { path: directory } } };
- profile.endpoints = { "hypihub.default": { ...profile.endpoints["hypihub.default"], config: {
- ...profile.endpoints["hypihub.default"].config,
- apiKey: { store: "file", key: "test.oauth" },
- } } };
- await writeFile(profilePath, JSON.stringify(profile));
- const auth = (action: string, ...args: string[]) => run("auth", action, "hypihub.default", "--runtime", profilePath, ...args);
- assert.equal(JSON.parse((await auth("status")).stdout).credentials[0].configured, false);
- const input = join(root, "input.txt");
- await writeFile(input, "test-secret-never-display");
- await auth("login", "--from", input);
- const status = (await auth("status")).stdout;
- assert.equal(JSON.parse(status).credentials[0].configured, true);
- assert.doesNotMatch(status, /test-secret-never-display/u);
- const path = join(directory, (await readdir(directory))[0]!);
- await writeFile(path, "corrupt-secret-never-display");
- await assert.rejects(auth("status"), error => {
- const output = String((error as { stdout?: string }).stdout);
- assert.match(JSON.parse(output).error.message, /Cannot decode credential file/u);
- assert.doesNotMatch(output, /corrupt-secret-never-display/u);
- return true;
- });
- await auth("login", "--from", input);
- assert.equal(JSON.parse((await auth("status")).stdout).credentials[0].configured, true);
- await writeFile(path, "corrupt-again");
- await auth("logout");
- assert.equal(JSON.parse((await auth("status")).stdout).credentials[0].configured, false);
- assert.deepEqual(await readdir(directory), []);
-});
diff --git a/packages/video-cli/test/media-frames.test.ts b/packages/video-cli/test/media-frames.test.ts
deleted file mode 100644
index 06556ce0..00000000
--- a/packages/video-cli/test/media-frames.test.ts
+++ /dev/null
@@ -1,34 +0,0 @@
-import assert from "node:assert/strict";
-import test from "node:test";
-import { spawnSync } from "node:child_process";
-import { mkdtemp, readdir, rm } from "node:fs/promises";
-import { tmpdir } from "node:os";
-import { join } from "node:path";
-import { decodeMediaFrames } from "../src/media-frames.js";
-import { runMediaCli } from "../src/media.js";
-
-test("native evidence preserves variable-rate timestamps and half-open bounds across grid pages", async () => {
- const directory = await mkdtemp(join(tmpdir(), "hypit-native-frames-test-"));
- try {
- const source = join(directory, "vfr.mkv");
- const encoded = spawnSync("ffmpeg", ["-v", "error", "-f", "lavfi", "-i", "testsrc2=size=96x64:rate=10:duration=0.4",
- "-vf", "setpts=if(lt(N\\,2)\\,N\\,N*2-1)/(10*TB)", "-fps_mode", "vfr", "-c:v", "libx264", source], { encoding: "utf8" });
- assert.equal(encoded.status, 0, encoded.stderr);
- const all = await decodeMediaFrames(source, 0, 0.6, join(directory, "all"));
- assert.deepEqual(all.map(frame => frame.at), [0, 0.1, 0.3, 0.5]);
- const selected = await decodeMediaFrames(source, 0.05, 0.5, join(directory, "selected"));
- assert.deepEqual(selected.map(frame => frame.at), [0.1, 0.3]);
- assert.equal((await readdir(join(directory, "selected"))).length, 2);
- let output = "";
- await runMediaCli(["media", "tiles", source, "--start", "0", "--end", "0.6", "--every-frame", "--columns", "2", "--rows", "1",
- "--to", "grids", "--json"], { write: text => { output += text; } }, directory);
- const grids = JSON.parse(output).grids;
- assert.deepEqual(grids.map((grid: { frames: { at: number }[] }) => grid.frames.map(frame => frame.at)), [[0, 0.1], [0.3, 0.5]]);
- assert.equal((await readdir(join(directory, "grids"))).length, 2);
- output = "";
- await runMediaCli(["media", "frames", source, "--start", "0.05", "--end", "0.5", "--every-frame", "--to", "files", "--json"],
- { write: text => { output += text; } }, directory);
- assert.deepEqual(JSON.parse(output).frames.map((frame: { at: number }) => frame.at), [0.1, 0.3]);
- await assert.rejects(runMediaCli(["media", "tiles", source, "--every-frame", "--every", "0.1", "--to", "bad"], { write() {} }, directory), /cannot be combined/u);
- } finally { await rm(directory, { recursive: true, force: true }); }
-});
diff --git a/packages/video-cli/test/media.test.ts b/packages/video-cli/test/media.test.ts
deleted file mode 100644
index 6d6f81a0..00000000
--- a/packages/video-cli/test/media.test.ts
+++ /dev/null
@@ -1,286 +0,0 @@
-import assert from "node:assert/strict";
-import { spawnSync } from "node:child_process";
-import { mkdtemp, readdir, rm, stat, writeFile } from "node:fs/promises";
-import { tmpdir } from "node:os";
-import { join } from "node:path";
-import test from "node:test";
-import sharp from "sharp";
-
-import type { CliIo } from "@hypit/cli";
-
-import { cutFrame, probeMedia, runMediaCli, tileFrameCount, tileSampleTimes, visualBoundaries } from "../src/media.js";
-
-const ffmpeg = spawnSync("ffmpeg", ["-version"], { stdio: "ignore" }).status === 0
- && spawnSync("ffprobe", ["-version"], { stdio: "ignore" }).status === 0;
-
-function io(): { readonly io: CliIo; text: () => string } {
- let out = "";
- return {
- io: {
- write: (chunk) => { out += chunk; },
- setExitCode: () => {},
- readSecret: async () => "",
- terminal: { isTTY: false, color: false, unicode: false, columns: 100 },
- },
- text: () => out,
- };
-}
-
-/** Three seconds with three sub-second cuts, 24 fps and no audio. */
-async function sample(directory: string): Promise<string> {
- const path = join(directory, "sample.mp4");
- const result = spawnSync("ffmpeg", [
- "-hide_banner", "-loglevel", "error", "-y",
- "-f", "lavfi", "-i", "color=c=red:s=320x240:r=24:d=0.5",
- "-f", "lavfi", "-i", "color=c=blue:s=320x240:r=24:d=0.5",
- "-f", "lavfi", "-i", "color=c=green:s=320x240:r=24:d=0.5",
- "-f", "lavfi", "-i", "color=c=white:s=320x240:r=24:d=1.5",
- "-filter_complex", "[0:v][1:v][2:v][3:v]concat=n=4:v=1:a=0",
- "-c:v", "libx264", "-preset", "veryfast", "-pix_fmt", "yuv420p", path,
- ], { encoding: "utf8" });
- assert.equal(result.status, 0, result.stderr);
- return path;
-}
-
-test("tile frame counts follow the measured bounds", () => {
- assert.equal(tileFrameCount(0.5), 4);
- assert.equal(tileFrameCount(4), 6);
- assert.equal(tileFrameCount(30), 9);
- assert.deepEqual(tileSampleTimes(1, 2, 4), [1.125, 1.375, 1.625, 1.875]);
-});
-
-test("media help names the available commands and both cut forms", () => {
- const out = io();
- runMediaCli(["media"], out.io);
- for (const name of ["probe", "cut", "frames", "tile", "tiles", "boundaries", "fetch"]) assert.match(out.text(), new RegExp(`hypit media ${name}`));
- assert.match(out.text(), /--start <s> --end <s> \| --keep <start:end>/);
- assert.match(out.text(), /--label-time/);
-});
-
-test("media evidence keeps source times and sub-second visual changes", { skip: !ffmpeg && "ffmpeg is not installed" }, async () => {
- const work = await mkdtemp(join(tmpdir(), "hypit-media-"));
- try {
- const source = await sample(work);
- const info = await probeMedia(source);
- assert.equal(info.hasVideo, true);
- if (!info.hasVideo) throw new Error("sample has no video stream");
- assert.equal(info.width, 320);
- assert.equal(info.height, 240);
- assert.equal(info.hasAudio, false);
- assert.ok(Math.abs(info.duration - 3) < 0.1, `duration ${info.duration}`);
-
- const probe = io();
- await runMediaCli(["media", "probe", source, "--json"], probe.io, work);
- assert.equal((JSON.parse(probe.text()) as { width: number }).width, 320);
-
- const cut = io();
- await runMediaCli(["media", "cut", source, "--start", "0.5", "--end", "2", "--to", "out/piece.mp4"], cut.io, work);
- const piece = await probeMedia(join(work, "out", "piece.mp4"));
- assert.ok(Math.abs(piece.duration - 1.5) < 0.15, `cut duration ${piece.duration}`);
- await assert.rejects(
- runMediaCli(["media", "cut", source, "--start", "0", "--end", "1", "--to", "out/piece.mp4"], io().io, work),
- /already exists/,
- );
- const labeledCut = io();
- await runMediaCli(["media", "cut", source, "--start", "0.5", "--end", "1", "--label-time", "--to", "out/labeled.mp4", "--json"], labeledCut.io, work);
- assert.equal((JSON.parse(labeledCut.text()) as { labeled: boolean }).labeled, true);
-
- const frames = io();
- await runMediaCli(["media", "frames", source, "--at", "0.2,2.5", "--to", "out/frames"], frames.io, work);
- const written = (await readdir(join(work, "out", "frames"))).sort();
- assert.deepEqual(written, ["frame-0_200s.jpg", "frame-2_500s.jpg"]);
-
- const every = io();
- await runMediaCli(["media", "frames", source, "--every", "1", "--label-time", "--to", "out/every", "--json"], every.io, work);
- const everyView = JSON.parse(every.text()) as { labeled: boolean; frames: unknown[] };
- assert.equal(everyView.frames.length, 3);
- assert.equal(everyView.labeled, true);
-
- const tile = io();
- await runMediaCli(["media", "tile", source, "--at", "0.2,1.1,2.5", "--columns", "2", "--to", "out/grid.jpg", "--json"], tile.io, work);
- const grid = JSON.parse(tile.text()) as { samples: number[]; columns: number; rows: number; cellWidth: number };
- assert.deepEqual(grid.samples, [0.2, 1.1, 2.5]);
- assert.equal(grid.columns, 2);
- assert.equal(grid.rows, 2);
- assert.equal(grid.cellWidth, 320, "a grid never enlarges a small source");
- assert.ok((await stat(join(work, "out", "grid.jpg"))).size > 0);
-
- const ranges = join(work, "ranges.json");
- await writeFile(ranges, JSON.stringify([
- { id: "opening", start: 0, end: 0.8, frames: 3 },
- { start: 1.5, end: 3 },
- ]));
- const tiles = io();
- await runMediaCli(["media", "tiles", source, "--ranges", ranges, "--to", "out/grids", "--json"], tiles.io, work);
- const grids = (JSON.parse(tiles.text()) as { grids: { samples: number[]; path: string }[] }).grids;
- assert.equal(grids.length, 2);
- assert.equal(grids[0]!.samples.length, 3);
- assert.deepEqual((await readdir(join(work, "out", "grids"))).sort(), ["001-opening.jpg", "002-1_500s-3_000s.jpg"]);
-
- const changes = await visualBoundaries(source);
- assert.ok(changes.some((item) => Math.abs(item.at - 0.5) < 0.1), JSON.stringify(changes));
- assert.ok(changes.some((item) => Math.abs(item.at - 1) < 0.1), JSON.stringify(changes));
- assert.ok(changes.some((item) => Math.abs(item.at - 1.5) < 0.1), JSON.stringify(changes));
- const boundaries = io();
- await runMediaCli(["media", "boundaries", source], boundaries.io, work);
- assert.match(boundaries.text(), /visual-change candidates/);
- assert.match(boundaries.text(), /scores are not shot labels/);
- } finally {
- await rm(work, { recursive: true, force: true });
- }
-});
-
-test("fetch refuses anything but an http link and an explicit video destination", async () => {
- await assert.rejects(runMediaCli(["media", "fetch", "./local.mp4", "--to", "x.mp4"], io().io), /http or https link/);
- await assert.rejects(runMediaCli(["media", "fetch", "https://example.com/v", "--to", "x.txt"], io().io, tmpdir()), /must end in/);
-});
-
-test("album artwork does not turn an audio cut into video", { skip: !ffmpeg && "ffmpeg is not installed" }, async () => {
- const work = await mkdtemp(join(tmpdir(), "hypit-covered-audio-"));
- try {
- const audio = join(work, "plain.mp3");
- const artwork = join(work, "cover.jpg");
- const covered = join(work, "covered.mp3");
- const tone = spawnSync("ffmpeg", [
- "-hide_banner", "-loglevel", "error", "-y", "-f", "lavfi", "-i",
- "sine=frequency=440:duration=1", "-c:a", "libmp3lame", audio,
- ], { encoding: "utf8" });
- assert.equal(tone.status, 0, tone.stderr);
- await sharp({ create: { width: 32, height: 32, channels: 3, background: "#ee3344" } }).jpeg().toFile(artwork);
- const attach = spawnSync("ffmpeg", [
- "-hide_banner", "-loglevel", "error", "-y", "-i", audio, "-i", artwork,
- "-map", "0:a:0", "-map", "1:v:0", "-c", "copy", "-id3v2_version", "3",
- "-disposition:v:0", "attached_pic", covered,
- ], { encoding: "utf8" });
- assert.equal(attach.status, 0, attach.stderr);
-
- for (const [index, source] of [audio, covered].entries()) {
- const info = await probeMedia(source);
- assert.equal(info.hasAudio, true);
- assert.equal(info.hasVideo, false, "album artwork is not a timed video stream");
- const output = join(work, `cut-${index}.wav`);
- const cut = io();
- await runMediaCli(["media", "cut", source, "--start", "0", "--end", "0.5", "--to", output, "--json"], cut.io, work);
- const result = JSON.parse(cut.text()) as { hasVideo: boolean; hasAudio: boolean; actualSeconds: number };
- assert.equal(result.hasVideo, false);
- assert.equal(result.hasAudio, true);
- assert.ok(Math.abs(result.actualSeconds - 0.5) < 0.01);
- const probe = spawnSync("ffprobe", [
- "-v", "error", "-show_entries", "stream=codec_type,codec_name", "-of", "json", output,
- ], { encoding: "utf8" });
- assert.equal(probe.status, 0, probe.stderr);
- assert.deepEqual(JSON.parse(probe.stdout).streams, [{ codec_name: "pcm_s24le", codec_type: "audio" }]);
- }
- } finally {
- await rm(work, { recursive: true, force: true });
- }
-});
-
-test("cut prepares recorded audio and joined video without changing the existing evidence cut", { skip: !ffmpeg && "ffmpeg is not installed" }, async () => {
- const work = await mkdtemp(join(tmpdir(), "hypit-recorded-cut-"));
- try {
- const silentVideo = await sample(work);
- const audio = join(work, "source.wav");
- const tone = spawnSync("ffmpeg", ["-hide_banner", "-loglevel", "error", "-y", "-f", "lavfi", "-i", "sine=frequency=440:duration=4", "-c:a", "pcm_s16le", audio], { encoding: "utf8" });
- assert.equal(tone.status, 0, tone.stderr);
- const audioProbe = await probeMedia(audio);
- assert.equal(audioProbe.hasVideo, false);
- assert.equal(audioProbe.hasAudio, true);
- const probe = io();
- await runMediaCli(["media", "probe", audio], probe.io, work);
- assert.match(probe.text(), /audio only/);
-
- const audioCut = io();
- await runMediaCli(["media", "cut", audio, "--keep", "0.25:1", "--keep", "2.5:3", "--to", "spoken.wav", "--json"], audioCut.io, work);
- const audioResult = JSON.parse(audioCut.text()) as { spans: { start: number; end: number }[];
- mapping: { nominalOutputStart: number; nominalOutputEnd: number }[]; actualSeconds: number; hasVideo: boolean; hasAudio: boolean };
- assert.deepEqual(audioResult.spans, [{ start: 0.25, end: 1 }, { start: 2.5, end: 3 }]);
- assert.deepEqual(audioResult.mapping.map((item) => [item.nominalOutputStart, item.nominalOutputEnd]), [[0, 0.75], [0.75, 1.25]]);
- assert.ok(Math.abs(audioResult.actualSeconds - 1.25) < 0.03, `audio duration ${audioResult.actualSeconds}`);
- assert.equal(audioResult.hasVideo, false);
- assert.equal(audioResult.hasAudio, true);
- await runMediaCli(["media", "cut", audio, "--start", "2.5", "--end", "3", "--to", "late.wav"], io().io, work);
- assert.ok(Math.abs((await probeMedia(join(work, "late.wav"))).duration - 0.5) < 0.03,
- "a late single interval lands on the requested audio time");
- await assert.rejects(runMediaCli(["media", "cut", audio, "--start", "0", "--end", "1", "--to", "spoken.wav"], io().io, work), /already exists/);
- await assert.rejects(runMediaCli(["media", "cut", audio, "--start", "0", "--end", "1", "--label-time", "--to", "labeled.wav"], io().io, work), /needs one video interval/);
-
- const withAudio = join(work, "source-av.mp4");
- const mux = spawnSync("ffmpeg", ["-hide_banner", "-loglevel", "error", "-y", "-i", silentVideo, "-i", audio,
- "-map", "0:v:0", "-map", "1:a:0", "-c:v", "copy", "-c:a", "aac", "-shortest", withAudio], { encoding: "utf8" });
- assert.equal(mux.status, 0, mux.stderr);
- const videoCut = io();
- await runMediaCli(["media", "cut", withAudio, "--keep", "0:0.5", "--keep", "1:1.5", "--to", "joined.mp4", "--json"], videoCut.io, work);
- const joined = await probeMedia(join(work, "joined.mp4"));
- assert.equal(joined.hasVideo, true);
- assert.equal(joined.hasAudio, true);
- assert.ok(Math.abs(joined.duration - 1) < 0.08, `joined duration ${joined.duration}`);
- const first = join(work, "first.jpg");
- const second = join(work, "second.jpg");
- await cutFrame(join(work, "joined.mp4"), 0.2, first);
- await cutFrame(join(work, "joined.mp4"), 0.7, second);
- const firstPixel = await sharp(first).extract({ left: 160, top: 120, width: 1, height: 1 }).raw().toBuffer();
- const secondPixel = await sharp(second).extract({ left: 160, top: 120, width: 1, height: 1 }).raw().toBuffer();
- assert.ok(firstPixel[0]! > firstPixel[1]! * 2, `first frame should be red: ${firstPixel}`);
- assert.ok(secondPixel[1]! > secondPixel[0]! * 2, `second frame should be green: ${secondPixel}`);
-
- await runMediaCli(["media", "cut", withAudio, "--start", "2.1", "--end", "2.8", "--to", "late.mp4"], io().io, work);
- const lateVideo = await probeMedia(join(work, "late.mp4"));
- assert.equal(lateVideo.hasAudio, true);
- assert.ok(Math.abs(lateVideo.duration - 0.7) < 0.08, `late video duration ${lateVideo.duration}`);
- await runMediaCli(["media", "cut", withAudio, "--start", "0", "--end", "0.5", "--to", "clip.mov"], io().io, work);
- assert.equal((await probeMedia(join(work, "clip.mov"))).hasAudio, true);
-
- const silentCut = join(work, "silent-cut.mp4");
- await runMediaCli(["media", "cut", silentVideo, "--keep", "0:0.5", "--keep", "1:1.5", "--to", silentCut], io().io, work);
- assert.equal((await probeMedia(silentCut)).hasAudio, false);
- } finally {
- await rm(work, { recursive: true, force: true });
- }
-});
-
-test("word-located grids paginate dense samples without covering the source picture", { skip: !ffmpeg && "ffmpeg is not installed" }, async () => {
- const work = await mkdtemp(join(tmpdir(), "hypit-word-grids-"));
- try {
- const source = await sample(work);
- const transcript = join(work, "words.json");
- await writeFile(transcript, JSON.stringify({ format: "hypit.transcript@1", passages: [{ words: [
- { text: "Hello", start_seconds: 0.1, end_seconds: 0.4 },
- { text: "world!", start_seconds: 0.4, end_seconds: 0.8 },
- { text: "<你好 & café>" },
- { text: "Hello", start_seconds: 2.1, end_seconds: 2.4 },
- { text: "world!", start_seconds: 2.4, end_seconds: 2.8 },
- ] }] }));
- await assert.rejects(runMediaCli(["media", "tile", source, "--around", "hello world", "--transcript", transcript,
- "--to", "ambiguous.jpg"], io().io, work), /occurs 2 times.*--occurrence/);
- const around = io();
- await runMediaCli(["media", "tile", source, "--around", "hello world", "--occurrence", "2", "--padding", "0.1",
- "--every", "0.2", "--transcript", transcript, "--to", "around.jpg", "--json"], around.io, work);
- const located = JSON.parse(around.text());
- assert.deepEqual(located.samples, [2, 2.2, 2.4, 2.6, 2.8]);
- assert.deepEqual(located.frames[0].words.active, []);
- assert.equal(located.frames[1].words.active[0].text, "Hello");
- assert.equal(located.frames[1].requestedAt, 2.2);
- assert.ok(Math.abs(located.frames[1].at - 53 / 24) < 0.000001, "labels use the decoded frame time, not the requested seek time");
- assert.equal(located.frames[2].words.active[0].text, "world!");
-
- const pages = io();
- await runMediaCli(["media", "tiles", source, "--start", "0", "--end", "3", "--every", "0.6",
- "--transcript", transcript, "--columns", "2", "--rows", "1", "--to", "pages", "--json"], pages.io, work);
- const grids = JSON.parse(pages.text()).grids;
- assert.deepEqual(grids.map((grid: { samples: number[] }) => grid.samples), [[0, 0.6], [1.2, 1.8], [2.4]]);
- assert.ok(grids.every((grid: { start: number; end: number }) => grid.start === 0 && grid.end === 3));
- assert.equal((await readdir(join(work, "pages"))).length, 3);
- const image = await sharp(grids[0].path).raw().toBuffer({ resolveWithObject: true });
- const center = (128 * image.info.width + 168) * image.info.channels;
- assert.ok(image.data[center]! > 220 && image.data[center + 1]! < 20, "the first source frame stays red and unobscured");
- assert.ok(image.info.height > 240 + 32, "word annotations have their own space beneath the picture");
-
- const frames = io();
- await runMediaCli(["media", "frames", source, "--start", "0.5", "--end", "1.5", "--every", "0.4",
- "--transcript", transcript, "--to", "frames", "--json"], frames.io, work);
- assert.deepEqual(JSON.parse(frames.text()).frames.map((frame: { requestedAt: number }) => frame.requestedAt), [0.5, 0.9, 1.3]);
- } finally {
- await rm(work, { recursive: true, force: true });
- }
-});
diff --git a/packages/video-cli/test/platform-credentials.test.ts b/packages/video-cli/test/platform-credentials.test.ts
deleted file mode 100644
index 33967f9f..00000000
--- a/packages/video-cli/test/platform-credentials.test.ts
+++ /dev/null
@@ -1,79 +0,0 @@
-import assert from "node:assert/strict";
-import { execFile } from "node:child_process";
-import { mkdir, mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises";
-import { tmpdir } from "node:os";
-import { join } from "node:path";
-import { fileURLToPath } from "node:url";
-import { promisify } from "node:util";
-import test from "node:test";
-
-const exec = promisify(execFile);
-const launcher = fileURLToPath(new URL("../../../bin/hypit.mjs", import.meta.url));
-
-/**
- * The examples select the `platform` Store so one committed Profile works on Linux, macOS and Windows.
- * On macOS and Windows it would use the real keychain or Credential Locker of whoever runs the
- * suite, so this test covers Linux and skips other platforms.
- */
-const isLinux = process.platform === "linux";
-
-test("the interview example authenticates on Linux, without editing its Profile",
- { skip: !isLinux, timeout: 120_000 }, async (t) => {
- const root = await mkdtemp(join(tmpdir(), "hypit-platform-example-"));
- t.after(() => rm(root, { recursive: true, force: true }));
- const project = join(root, "project");
- const state = join(root, "host");
- await mkdir(project, { recursive: true });
- const profile = fileURLToPath(new URL("../../../examples/interview/hypit.runtime.json", import.meta.url));
- const run = (...args: string[]) => exec(process.execPath, [launcher, ...args, "--json"], {
- cwd: project, env: { ...process.env, HYPIT_STATE_HOME: state }, timeout: 60_000, windowsHide: true,
- });
- const auth = (action: string, ...args: string[]) =>
- run("auth", action, "hypihub.default", "--runtime", profile, ...args);
-
- const before = JSON.parse((await auth("status")).stdout).credentials[0];
- assert.equal(before.configured, false, "the committed Profile opens, so nothing here rewrites it");
- assert.equal(before.writable, true, "the Linux policy accepts a credential");
- const input = join(root, "secret.txt");
- await writeFile(input, "example-secret-never-displayed");
- const login = await auth("login", "--from", input);
- assert.doesNotMatch(login.stdout, /example-secret-never-displayed/u);
- assert.equal(JSON.parse((await auth("status")).stdout).credentials[0].configured, true);
-
- // Linux uses the file Store's own directory, so switching Stores there finds it.
- assert.equal((await readdir(join(state, "credentials"))).length, 1);
-
- await auth("logout");
- assert.equal(JSON.parse((await auth("status")).stdout).credentials[0].configured, false);
- assert.deepEqual(await readdir(join(state, "credentials")), []);
- });
-
-test("the Profile runtime init writes authenticates on Linux, without editing it",
- { skip: !isLinux, timeout: 120_000 }, async (t) => {
- const root = await mkdtemp(join(tmpdir(), "hypit-platform-init-"));
- t.after(() => rm(root, { recursive: true, force: true }));
- const project = join(root, "project");
- const state = join(root, "host");
- await mkdir(project, { recursive: true });
- const run = (...args: string[]) => exec(process.execPath, [launcher, ...args, "--json"], {
- cwd: project, env: { ...process.env, HYPIT_STATE_HOME: state }, timeout: 60_000, windowsHide: true,
- });
- await run("runtime", "init");
- const starter = JSON.parse(await readFile(join(project, "hypit.runtime.json"), "utf8"));
- assert.deepEqual(starter.credentials, { platform: { use: "@hypit/credential-store-platform" } },
- "a starter that selects a Store Linux cannot open fails every command that follows");
-
- // Everything below resolves the Profile the starter just wrote and selected, with no flags.
- const status = async () => JSON.parse((await run("auth", "status", "hypihub.default")).stdout).credentials[0];
- assert.equal((await status()).configured, false);
- assert.equal((await status()).writable, true);
- const input = join(root, "secret.txt");
- await writeFile(input, "starter-secret-never-displayed");
- const login = await run("auth", "login", "hypihub.default", "--from", input);
- assert.doesNotMatch(login.stdout, /starter-secret-never-displayed/u);
- assert.equal((await status()).configured, true);
- assert.equal((await readdir(join(state, "credentials"))).length, 1);
- await run("auth", "logout", "hypihub.default");
- assert.equal((await status()).configured, false);
- assert.deepEqual(await readdir(join(state, "credentials")), []);
- });
diff --git a/packages/video-cli/test/snapshot.test.ts b/packages/video-cli/test/snapshot.test.ts
deleted file mode 100644
index d943d83e..00000000
--- a/packages/video-cli/test/snapshot.test.ts
+++ /dev/null
@@ -1,139 +0,0 @@
-import assert from "node:assert/strict";
-import test from "node:test";
-import { mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises";
-import { tmpdir } from "node:os";
-import { join } from "node:path";
-import sharp from "sharp";
-import { canonicalize } from "@hypit/protocol";
-import { verifyHyperframesFramesRequest } from "@hypit/render-hyperframes";
-import { isSnapshotHtmlUrl, runSnapshotCli, studioDocumentUrl } from "../src/snapshot.js";
-import type { CreationEnvironment } from "../src/creation.js";
-
-const html = '<!doctype html><div data-composition-id="test" data-fps="30000/1001" data-hypit-frame-count="12" data-width="96" data-height="64"><img src="still.png"></div>';
-
-test("snapshot invokes the selected Profile once and writes original-frame PNGs and paginated grids", async () => {
- const directory = await mkdtemp(join(tmpdir(), "hypit-snapshot-cli-"));
- const bytes = await sharp({ create: { width: 96, height: 64, channels: 3, background: "#264a71" } }).png().toBuffer();
- let calls = 0;
- let output = "";
- try {
- await writeFile(join(directory, "index.html"), html);
- await writeFile(join(directory, "still.png"), bytes);
- const environment: CreationEnvironment = { cwd: directory, openHost: async (profile, workspace) => {
- assert.equal(profile, "selected.json");
- assert.equal(workspace, "project");
- return { profile: "selected.json", host: {
- providers: async requests => requests.map(request => ({ request: request.request, capability: request.capability,
- status: "resolved", endpoint: "chosen.frames", use: "@example/frames", pricing: { kind: "local" } })),
- invoke: async (need, resources) => {
- calls++;
- assert.equal(need.capability.name, "render-frames");
- verifyHyperframesFramesRequest(need.constraints);
- assert.deepEqual(need.constraints.frames, [3, 5, 7, 9, 11]);
- assert.ok("project" in need.constraints);
- const asset = need.constraints.project.assets[0]!;
- assert.deepEqual(Buffer.from((await resources.get(asset.artifact.resource))!), bytes);
- return { value: { kind: "inline", value: canonicalize(await Promise.all(need.constraints.frames.map(() => resources.put(bytes, "image/png")))) } };
- },
- } };
- } };
- await runSnapshotCli(["snapshot", "index.html", "--start-frame", "3", "--end-frame-exclusive", "12", "--step-frames", "2",
- "--grid", "2x2", "--cell", "96", "--to", "evidence", "--runtime", "selected.json", "--workspace", "project", "--json"], {
- write: text => { output += text; },
- }, environment);
- assert.equal(calls, 1);
- const view = JSON.parse(output);
- assert.equal(view.endpoint, "chosen.frames");
- assert.equal(view.frames[0].seconds, 3 * 1001 / 30000);
- assert.equal(view.grids.length, 2);
- assert.equal((await readdir(join(directory, "evidence"))).length, 7);
- assert.deepEqual(await readFile(view.frames[0].path), bytes);
- assert.equal((await sharp(view.grids[0]).metadata()).width, 216);
- await assert.rejects(runSnapshotCli(["snapshot", "index.html", "--at-frame", "12", "--to", "bad"], { write() {} }, environment), /\[0, 12\)/u);
- await assert.rejects(runSnapshotCli(["snapshot", "index.html", "--at-frame", "3,3", "--to", "bad"], { write() {} }, environment), /strictly increasing/u);
- assert.equal(calls, 1);
- } finally { await rm(directory, { recursive: true, force: true }); }
-});
-
-test("snapshot --studio without a URL scheme is a usage error, not TypeError", async () => {
- assert.equal(studioDocumentUrl("http://localhost:5191"), "http://localhost:5191/__studio/document");
- assert.throws(() => studioDocumentUrl("localhost:5191"), /--studio needs an http\(s\) Studio URL/u);
- const environment: CreationEnvironment = { cwd: "/tmp", openHost: async () => ({ profile: "empty.json", host: {
- providers: async () => [], invoke: async () => { throw new Error("must not run"); },
- } }) };
- await assert.rejects(
- runSnapshotCli(["snapshot", "--studio", "localhost:5191", "--at-frame", "0", "--to", "out"], { write() {} }, environment),
- (error: unknown) => error instanceof Error && error.name === "Error" && /--studio needs an http\(s\) Studio URL/u.test(error.message),
- );
-});
-
-test("snapshot treats HTTPS HTML URLs as network inputs, matching capture", async (t) => {
- assert.equal(isSnapshotHtmlUrl("HTTPS://example.test/picture/index.html"), true);
- assert.equal(isSnapshotHtmlUrl("https://example.test/picture/index.html"), true);
- assert.equal(isSnapshotHtmlUrl("index.html"), false);
- const directory = await mkdtemp(join(tmpdir(), "hypit-snapshot-https-"));
- const fetched: string[] = [];
- t.mock.method(globalThis, "fetch", async (input: string | URL) => {
- fetched.push(String(input));
- return new Response(html.replace('<img src="still.png">', ""));
- });
- try {
- const environment: CreationEnvironment = { cwd: directory, openHost: async () => ({ profile: "empty.json", host: {
- providers: async () => [], invoke: async () => { throw new Error("must not run"); },
- } }) };
- await assert.rejects(runSnapshotCli(
- ["snapshot", "HTTPS://example.test/picture/index.html", "--at-frame", "0", "--to", "out"],
- { write() {} }, environment,
- ), /No Endpoint/u);
- assert.deepEqual(fetched, ["HTTPS://example.test/picture/index.html"]);
- } finally { await rm(directory, { recursive: true, force: true }); }
-});
-
-test("snapshot reports a missing binding before invocation and preserves existing output", async () => {
- const directory = await mkdtemp(join(tmpdir(), "hypit-snapshot-error-"));
- try {
- await writeFile(join(directory, "index.html"), html.replace('<img src="still.png">', ""));
- const environment: CreationEnvironment = { cwd: directory, openHost: async () => ({ profile: "empty.json", host: {
- providers: async () => [], invoke: async () => { throw new Error("must not run"); },
- } }) };
- await assert.rejects(runSnapshotCli(["snapshot", "index.html", "--at-frame", "0", "--to", "new"], { write() {} }, environment), /No Endpoint/u);
- await assert.rejects(runSnapshotCli(["snapshot", "index.html", "--at-frame", "0", "--to", "index.html"], { write() {} }, environment), /already exists/u);
- assert.deepEqual(await readdir(directory), ["index.html"]);
- } finally { await rm(directory, { recursive: true, force: true }); }
-});
-
-test("Studio snapshots carry declared resources used only inside JavaScript data", async t => {
- const directory = await mkdtemp(join(tmpdir(), "hypit-studio-snapshot-"));
- const bytes = await sharp({ create: { width: 96, height: 64, channels: 3, background: "red" } }).png().toBuffer();
- const artifact = { kind: "blob" as const, resource: "res_program_image" as const, size: bytes.length, mediaType: "image/png" };
- const late = { kind: "blob" as const, resource: "res_late_image" as const, size: 123, mediaType: "image/png" };
- const document = { visualIr: "hypit.visual-ir@1", frameRate: { numerator: 30000, denominator: 1001 }, frameCount: 12,
- canvas: { width: 96, height: 64 }, artifacts: [
- { artifact: late, usage: { kind: "frames" as const, spans: [{ startFrame: 10, endFrameExclusive: 12 }] } },
- { artifact, usage: { kind: "always" as const } },
- ], surfaces: [],
- html: html.replace('<img src="still.png">', '<script>const input="hypit-resource://res_program_image";</script><img data-hypit-resource-src="hypit-resource://res_late_image">') };
- const fetched: string[] = [];
- t.mock.method(globalThis, "fetch", async (input: string | URL) => {
- const url = String(input);
- fetched.push(url);
- if (url.endsWith("/__studio/document")) return Response.json(document);
- if (url.endsWith("/__studio/material/res_program_image")) return new Response(bytes);
- throw new Error(`Unexpected read ${url}`);
- });
- try {
- const environment: CreationEnvironment = { cwd: directory, openHost: async () => ({ profile: "selected.json", host: {
- providers: async requests => requests.map(request => ({ request: request.request, capability: request.capability,
- status: "resolved", endpoint: "frames", use: "@example/frames" })),
- invoke: async (need, resources) => {
- verifyHyperframesFramesRequest(need.constraints);
- assert.ok("document" in need.constraints);
- assert.deepEqual(need.constraints.document, document);
- assert.deepEqual(Buffer.from((await resources.get(artifact.resource))!), bytes);
- return { value: { kind: "inline", value: canonicalize([await resources.put(bytes, "image/png")]) } };
- },
- } }) };
- await runSnapshotCli(["snapshot", "--studio", "http://studio.example:5191/#comments", "--at-frame", "3", "--to", "evidence"], { write() {} }, environment);
- assert.deepEqual(fetched, ["http://studio.example:5191/__studio/document", "http://studio.example:5191/__studio/material/res_program_image"]);
- } finally { await rm(directory, { recursive: true, force: true }); }
-});
diff --git a/packages/video-cli/test/transcript.test.ts b/packages/video-cli/test/transcript.test.ts
deleted file mode 100644
index a4b9e7b7..00000000
--- a/packages/video-cli/test/transcript.test.ts
+++ /dev/null
@@ -1,26 +0,0 @@
-import assert from "node:assert/strict";
-import test from "node:test";
-import { phraseRanges, wordsAt } from "../src/transcript.js";
-
-test("word annotations retain missing times and distinguish word boundaries, overlap and gaps", () => {
- const words = [
- { text: "hello", start: 0, end: 0.4 }, { text: "world", start: 0.4, end: 0.8 },
- { text: "yes", start: 0.6, end: 0.9 }, { text: "untimed" }, { text: "again", start: 1.2, end: 1.5 },
- ];
- assert.deepEqual(wordsAt(words, 0.4).active.map((word) => word.text), ["world"]);
- assert.deepEqual(wordsAt(words, 0.7).active.map((word) => word.text), ["world", "yes"]);
- assert.deepEqual(wordsAt(words, 1).active, []);
- assert.ok(wordsAt(words, 1).context.some((word) => word.text === "untimed" && word.start === undefined));
-});
-
-test("phrase location preserves repeated occurrences and multilingual word boundaries", () => {
- const words = [
- { text: "Hello,", start: 0.1, end: 0.3 }, { text: "world!", start: 0.3, end: 0.8 },
- { text: "hello", start: 2.1, end: 2.4 }, { text: "world", start: 2.4, end: 2.8 },
- { text: "你好", start: 3, end: 3.2 }, { text: "世界。", start: 3.2, end: 3.5 },
- ];
- assert.deepEqual(phraseRanges(words, "HELLO world"), [{ start: 0.1, end: 0.8 }, { start: 2.1, end: 2.8 }]);
- assert.deepEqual(phraseRanges(words, "你好世界"), [{ start: 3, end: 3.5 }]);
- assert.deepEqual(phraseRanges(words, "hell"), []);
- assert.throws(() => phraseRanges([{ text: "hello" }], "hello"), /missing boundary times/);
-});
diff --git a/packages/video/README.md b/packages/video/README.md
new file mode 100644
index 00000000..5c945378
--- /dev/null
+++ b/packages/video/README.md
@@ -0,0 +1,59 @@
+# `@hypit/video`
+
+Assembly for the official Hypit video application. This package chooses the Markup author language,
+the filesystem Workspace, Source-package discovery and the starter Runtime Profile. It also owns the
+`hypit vocabulary` view because that view describes the author packages selected by this video
+Distribution.
+
+It is deliberately **not** a general video utility package. Browser capture, local media inspection,
+speech measurement, WhisperX transcription and Studio snapshots are owned by their respective
+packages and contribute their own CLI roots:
+
+| Command | Owner |
+| --- | --- |
+| `capture` | `@hypit/browser-capture/cli` |
+| `media` | `@hypit/media-local/cli` |
+| `measure` | `@hypit/speech-estimate/cli` |
+| `transcribe` | `@hypit/whisperx/cli` |
+| `studio`, `snapshot` | `@hypit/studio/cli` |
+| `vocabulary` | `@hypit/video/cli` |
+
+The root executable is the composition root. Its explicit `hypit.cli.use` list installs these command
+contributions under one `hypit` command; `@hypit/video/cli` does not forward or rediscover them.
+Installing or importing an arbitrary Source package never grants it CLI or process authority.
+
+## Application assembly
+
+`createVideoDistribution()` supplies the generic CLI Host with video-product choices:
+
+- `createVideoCompiler()` assembles the selected Author Frontends, Markup Surfaces, Modules and
+ validators for one invocation;
+- `createVideoWorkspace()` resolves Source and asset imports from the project and selected
+ Distribution without treating arbitrary package directories as projects;
+- `discoverVideoSourcePackages()` discovers the closure named by explicit Run and Author imports;
+- the starter Runtime Profile selects ordinary independently distributed Providers and Credential
+ Stores by package name;
+- Local Runtime and Result Repository adapters remain Host concerns and do not enter Author values.
+
+These are replaceable product-assembly decisions, not new Core concepts. A different application may
+reuse the generic compiler and CLI contracts with another Frontend or Workspace.
+
+## Vocabulary
+
+```bash
+hypit vocabulary
+hypit vocabulary @hypit/media-operations --tag StillVideo
+hypit vocabulary --visual text
+```
+
+The command reports installed Author-package manifests and their declared Surfaces. It does not keep
+a registry, scan the network, install packages or make creative choices. Package managers and the
+project lockfile own physical package versions; Source imports own which logical Modules participate
+in a compilation.
+
+## Boundary
+
+The package may depend on compiler, loader, workspace and product assembly APIs. It must not become a
+place to put functionality merely because that functionality is useful while making a video. A
+capability belongs with the behavior and authority it implements; its optional CLI is only another
+port of that owner.
diff --git a/packages/video/package.json b/packages/video/package.json
new file mode 100644
index 00000000..1f0bf2a2
--- /dev/null
+++ b/packages/video/package.json
@@ -0,0 +1,27 @@
+{
+ "name": "@hypit/video",
+ "version": "0.1.0",
+ "license": "SEE LICENSE IN LICENSE",
+ "private": true,
+ "type": "module",
+ "exports": {
+ ".": "./src/index.ts",
+ "./cli": "./src/commands.ts"
+ },
+ "files": [
+ "dist",
+ "README.md"
+ ],
+ "dependencies": {
+ "@hypit/runtime-local": "workspace:^"
+ },
+ "peerDependencies": {
+ "@hypit/hypit": "workspace:^"
+ },
+ "devDependencies": {
+ "@hypit/cli": "workspace:*",
+ "@hypit/hypit": "workspace:*",
+ "@hypit/loader": "workspace:*",
+ "@hypit/markup": "workspace:*"
+ }
+}
diff --git a/packages/video/src/commands.ts b/packages/video/src/commands.ts
new file mode 100644
index 00000000..cdd4c772
--- /dev/null
+++ b/packages/video/src/commands.ts
@@ -0,0 +1,19 @@
+import type { CliCommandModule } from "@hypit/hypit/cli";
+
+import { runVocabularyCli, writeVocabularyHelp } from "./vocabulary.js";
+
+/** The Video application owns only its installed author-vocabulary view. */
+export const cliCommandModules = [{
+ format: "hypit.cli-command@1",
+ id: "@hypit/video",
+ commands: ["vocabulary"],
+ writeRootHelp(io) {
+ io.write("\nVideo author vocabulary\n vocabulary\n hypit vocabulary --help for package and Surface inspection\n");
+ },
+ writeHelp(_argv, io) {
+ writeVocabularyHelp(io);
+ },
+ async run(argv, io, context) {
+ await runVocabularyCli(argv, io, context.cwd, context.distribution.packageRoot);
+ },
+}] as const satisfies readonly CliCommandModule[];
diff --git a/packages/video/src/compiler.ts b/packages/video/src/compiler.ts
new file mode 100644
index 00000000..77dd6ffa
--- /dev/null
+++ b/packages/video/src/compiler.ts
@@ -0,0 +1,74 @@
+import type { CliCompilerOptions } from "@hypit/hypit/cli";
+import { admissionPackagesFromFacets, registerTypeValidatorFacets, TypeValidatorRegistry } from "@hypit/hypit/admission";
+import { ModulePackageRegistry, Compiler } from "@hypit/hypit/compiler";
+import { AuthorFrontendRegistry, installAuthorFrontendFacets } from "@hypit/hypit/author";
+import {
+ createMarkupAuthorFrontend,
+ installMarkupSurfaceFacets,
+ MarkupSurfaceRegistry,
+} from "@hypit/hypit/markup";
+import {
+ resolveNodePackageResourceSpecifier,
+ resolveNodePackageSource,
+} from "@hypit/hypit/loader/node";
+import { NodeFilesystemWorkspace } from "@hypit/hypit/workspace/node";
+
+export function createVideoWorkspace(options: Pick<CliCompilerOptions,
+ "workspaceRoot" | "assetRoots" | "packageRoot" | "distributionPackageRoot">) {
+ const packageRoot = options.packageRoot ?? options.workspaceRoot ?? process.cwd();
+ return new NodeFilesystemWorkspace({
+ ...(options.workspaceRoot === undefined ? {} : { root: options.workspaceRoot }),
+ ...(options.assetRoots === undefined ? {} : { assetRoots: options.assetRoots }),
+ externalSourceResolver(importer, request) {
+ const located = resolveNodePackageSource(request.from, {
+ from: importer.id,
+ workspaceRoots: [packageRoot],
+ ...(options.distributionPackageRoot === undefined
+ ? {}
+ : { distributionRoots: [options.distributionPackageRoot] }),
+ });
+ return { root: located.root, source: located.source };
+ },
+ externalAssetResolver(importer, request) {
+ const located = resolveNodePackageResourceSpecifier(request.from, {
+ from: importer.id,
+ workspaceRoots: [packageRoot],
+ ...(options.distributionPackageRoot === undefined
+ ? {}
+ : { distributionRoots: [options.distributionPackageRoot] }),
+ });
+ return { root: located.root, asset: located.resource };
+ },
+ });
+}
+
+/** Assemble the Markup compiler Host from only the packages selected for this invocation. */
+export function createVideoCompiler(options: CliCompilerOptions) {
+ const modules = new ModulePackageRegistry();
+ const surfaces = new MarkupSurfaceRegistry();
+ const frontends = new AuthorFrontendRegistry();
+ const validators = new TypeValidatorRegistry();
+ for (const item of options.packageContributions) {
+ for (const module of item.modules ?? []) modules.register(module);
+ const facets = item.facets ?? [];
+ installMarkupSurfaceFacets(facets, surfaces);
+ installAuthorFrontendFacets(facets, frontends);
+ for (const pack of admissionPackagesFromFacets(facets)) {
+ registerTypeValidatorFacets(validators, pack.validators ?? []);
+ }
+ }
+ frontends.register(createMarkupAuthorFrontend({
+ registry: surfaces,
+ resolveModule(request) {
+ const resolved = modules.resolve(request.from);
+ if (resolved === undefined) throw new Error(`No selected author package satisfies ${request.from}`);
+ return resolved;
+ },
+ }));
+ return new Compiler({
+ modules,
+ frontends,
+ validators,
+ workspace: createVideoWorkspace(options),
+ });
+}
diff --git a/packages/video/src/distribution.ts b/packages/video/src/distribution.ts
new file mode 100644
index 00000000..93c7a8fe
--- /dev/null
+++ b/packages/video/src/distribution.ts
@@ -0,0 +1,95 @@
+import type { CliDistribution } from "@hypit/hypit/cli";
+import {
+ doctorProjectBuildResultRepository,
+ findRuntimeProfile,
+ openLocalRuntimeHost,
+ openProjectBuildResultRepository,
+} from "@hypit/runtime-local";
+import type { LocalRuntimeCliDistribution } from "@hypit/runtime-local/cli";
+import { fileURLToPath } from "node:url";
+import { resolve } from "node:path";
+import {
+ createVideoCompiler,
+ createVideoWorkspace,
+} from "./compiler.js";
+
+// The Distribution root is the replaceable Hypit tool checkout, not this
+// package's source directory and never the author's project.
+export type VideoDistributionOptions = {
+ /** Physical root of the installed Hypit video Distribution. */
+ readonly packageRoot?: string;
+ /** Exact executable the Local Runtime Worker must re-enter. */
+ readonly launcher?: string;
+};
+
+/** Assemble the official video application once at its executable composition root. */
+export function createVideoDistribution(options: VideoDistributionOptions = {}): CliDistribution & LocalRuntimeCliDistribution {
+ const packageRoot = resolve(options.packageRoot ?? resolve(import.meta.dirname, "../../.."));
+ const launcher = options.launcher ?? fileURLToPath(new URL("../../../bin/hypit.mjs", import.meta.url));
+ const openVideoLocalRuntime = async (path: string, runtimeOptions: {
+ readonly packageRoot: string;
+ readonly distributionPackageRoot?: string;
+ }) => await openLocalRuntimeHost(path, {
+ packageRoot: runtimeOptions.packageRoot,
+ ...(runtimeOptions.distributionPackageRoot === undefined
+ ? {}
+ : { distributionPackageRoot: runtimeOptions.distributionPackageRoot }),
+ workerLaunch: {
+ command: process.execPath,
+ args: [launcher],
+ },
+ });
+ return {
+ packageRoot,
+ bootstrapPackages: [],
+ initialRuntimeProfile: {
+ format: "hypit.runtime-local@1",
+ dataRoot: ".hypit/runtimes/local",
+ // The starter selects the portable Store, so the Profile it writes is openable and writable on
+ // Linux as well: macOS and Windows keep the platform locker, and a Linux host uses an
+ // owner-private file. An explicit file backend remains available inside the same local Store.
+ credentials: {
+ local: { use: "@hypit/credential-store-local" },
+ },
+ endpoints: {
+ "hypihub.default": {
+ use: "@hypit/provider-hypihub",
+ config: {
+ baseUrl: "https://hypit.ai",
+ apiKey: { store: "local", key: "hypihub.oauth" },
+ },
+ },
+ "media.local": {
+ use: "@hypit/media-local",
+ },
+ "html.local": {
+ use: "@hypit/provider-html-local",
+ },
+ "image.opencv.local": {
+ use: "@hypit/provider-image-opencv-local",
+ },
+ },
+ },
+ createWorkspace: createVideoWorkspace,
+ resolveProjectRuntime: async (projectRoot) => {
+ const selected = await findRuntimeProfile(projectRoot);
+ return selected === undefined ? undefined : { profile: selected.profile };
+ },
+ createCompiler: createVideoCompiler,
+ discoverSourcePackages: async (path, options) => {
+ const { discoverVideoSourcePackages } = await import("./package-selection.js");
+ return await discoverVideoSourcePackages(path, options);
+ },
+ openLocalRuntimeHost: openVideoLocalRuntime,
+ openRuntimeHost: openVideoLocalRuntime,
+ openProjectResults: async (projectRoot, options) => {
+ const opened = await openProjectBuildResultRepository(projectRoot);
+ return {
+ location: opened.location,
+ repository: opened.repository,
+ close() {},
+ };
+ },
+ diagnoseProjectResults: async (projectRoot) => await doctorProjectBuildResultRepository(projectRoot),
+ };
+}
diff --git a/packages/video/src/index.ts b/packages/video/src/index.ts
new file mode 100644
index 00000000..5993196a
--- /dev/null
+++ b/packages/video/src/index.ts
@@ -0,0 +1,10 @@
+export {
+ createVideoCompiler,
+ createVideoWorkspace,
+} from "./compiler.js";
+export { createVideoDistribution } from "./distribution.js";
+export type { VideoDistributionOptions } from "./distribution.js";
+export { cliCommandModules as videoCommandModules } from "./commands.js";
+export { discoverVideoSourcePackages } from "./package-selection.js";
+export { listPackages, listSurfaces, runVocabularyCli, visualSchema, writeVocabularyHelp } from "./vocabulary.js";
+export type { PackageListing, SurfaceListing } from "./vocabulary.js";
diff --git a/packages/video-cli/src/package-selection.ts b/packages/video/src/package-selection.ts
similarity index 88%
rename from packages/video-cli/src/package-selection.ts
rename to packages/video/src/package-selection.ts
index ba4f8f75..0936cf12 100644
--- a/packages/video-cli/src/package-selection.ts
+++ b/packages/video/src/package-selection.ts
@@ -1,9 +1,9 @@
-import { discoverSourcePackages } from "@hypit/cli";
+import { discoverSourcePackages } from "@hypit/hypit/cli";
import {
createMarkupAuthorFrontend,
MarkupSurfaceRegistry,
-} from "@hypit/markup";
-import type { LoadedPackage } from "@hypit/package-loader-node";
+} from "@hypit/hypit/markup";
+import type { LoadedPackage } from "@hypit/hypit/loader";
const markupFrontend = createMarkupAuthorFrontend({
registry: new MarkupSurfaceRegistry(),
diff --git a/packages/video-cli/src/vocabulary.ts b/packages/video/src/vocabulary.ts
similarity index 75%
rename from packages/video-cli/src/vocabulary.ts
rename to packages/video/src/vocabulary.ts
index 69cc0090..9c8414cd 100644
--- a/packages/video-cli/src/vocabulary.ts
+++ b/packages/video/src/vocabulary.ts
@@ -1,27 +1,24 @@
-import { readdir, readFile, stat } from "node:fs/promises";
-import { dirname, join, resolve } from "node:path";
+import { readdir, readFile } from "node:fs/promises";
+import { join, resolve } from "node:path";
-import type { CliIo } from "@hypit/cli";
+import type { CliIo } from "@hypit/hypit/cli";
import {
animatableLocalStyles,
- visualProgramSchema, visualBoxSchema, visualElementSchema, visualImageSchema, visualMaskSchema, visualPathCommandSchema,
- visualSurfaceSchema, visualTextDocumentSchema, visualTextFlowSchema, visualTextPaintSchema,
- visualTextSchema, visualTextTypographySchema, visualTrackSchema, visualVideoSchema,
-} from "@hypit/composition";
-import { markupSurfaceHostFacetAbi } from "@hypit/markup";
+ visualCompositionVocabulary,
+} from "@hypit/hypit/composition";
+import { markupSurfaceFacetAbi } from "@hypit/hypit/markup";
import type {
RegisteredSurface,
SurfaceAttributeVocabulary,
SurfacePortVocabulary,
SurfaceVocabulary,
-} from "@hypit/markup";
-import { exactModelHostAbi } from "@hypit/model-kit";
-import { loadNodePackageSelection, locateNodePackage } from "@hypit/package-loader-node";
-import type { NodePackageLoadOptions } from "@hypit/package-loader-node";
-import type { ValueSchema } from "@hypit/protocol";
-import { VISUAL_STYLE_ENUM_VALUES_V1, VISUAL_STYLE_NAMES_V1 } from "@hypit/visual-ir";
-
-import { videoCliDistribution } from "./distribution.js";
+} from "@hypit/hypit/markup";
+import { exactModelFacetAbi } from "@hypit/hypit/generation/model";
+import { loadNodePackageSelection, locateNodePackage } from "@hypit/hypit/loader/node";
+import type { NodePackageLoadOptions } from "@hypit/hypit/loader/node";
+import type { ValueSchema } from "@hypit/hypit/protocol";
+import { findProjectRoot } from "@hypit/hypit/project";
+import { VISUAL_STYLE_ENUM_VALUES_V1, VISUAL_STYLE_NAMES_V1 } from "@hypit/hypit/composition";
/**
* What a Source may write: the installed packages, and the Surfaces each one declares.
@@ -35,18 +32,8 @@ function assert(condition: unknown, message: string): asserts condition {
if (!condition) throw new Error(message);
}
-async function nearestPackageRoot(start: string): Promise<string> {
- let directory = resolve(start);
- while (true) {
- if (await stat(resolve(directory, "package.json")).then((item) => item.isFile(), () => false)) return directory;
- const parent = dirname(directory);
- if (parent === directory) return resolve(start);
- directory = parent;
- }
-}
-
-function loading(): NodePackageLoadOptions {
- return videoCliDistribution.packageRoot === undefined ? {} : { fallbackRoots: [videoCliDistribution.packageRoot] };
+function loading(distributionRoot?: string): NodePackageLoadOptions {
+ return distributionRoot === undefined ? {} : { fallbackRoots: [distributionRoot] };
}
async function readJson<T>(path: string): Promise<T | undefined> {
@@ -64,11 +51,11 @@ export type PackageListing = {
readonly unreadable?: string;
};
-export async function listPackages(projectRoot: string): Promise<readonly PackageListing[]> {
+export async function listPackages(projectRoot: string, distributionRoot?: string): Promise<readonly PackageListing[]> {
// Discover installed scopes and unlinked packages in both the project and the Distribution.
const roots = [...new Set([
projectRoot,
- ...(videoCliDistribution.packageRoot === undefined ? [] : [videoCliDistribution.packageRoot]),
+ ...(distributionRoot === undefined ? [] : [distributionRoot]),
])];
const candidates: { readonly name: string; readonly directory: string }[] = [];
for (const root of roots) {
@@ -101,10 +88,10 @@ export async function listPackages(projectRoot: string): Promise<readonly Packag
const models: string[] = [];
let unreadable: string | undefined;
try {
- for (const pack of await loadNodePackageSelection([name], projectRoot, loading())) {
- for (const facet of pack.contribution.hostFacets ?? []) {
- if (facet.abi === markupSurfaceHostFacetAbi) tags.push((facet.implementation as RegisteredSurface).tag);
- else if (facet.abi === exactModelHostAbi) models.push(...(facet as { readonly offers?: readonly string[] }).offers ?? []);
+ for (const pack of await loadNodePackageSelection([name], projectRoot, loading(distributionRoot))) {
+ for (const facet of pack.contribution.facets ?? []) {
+ if (facet.abi === markupSurfaceFacetAbi) tags.push((facet.implementation as RegisteredSurface).tag);
+ else if (facet.abi === exactModelFacetAbi) models.push(...(facet as { readonly offers?: readonly string[] }).offers ?? []);
}
}
} catch (error) { unreadable = error instanceof Error ? error.message : String(error); }
@@ -139,31 +126,36 @@ function printableVocabulary(value: SurfaceVocabulary | undefined): unknown {
return { ...value, ...(value.preview === undefined ? {} : { preview: { mediaType: value.preview.mediaType, path: value.preview.path } }) };
}
-function readmePath(name: string, projectRoot: string): string | undefined {
+function readmePath(name: string, projectRoot: string, distributionRoot?: string): string | undefined {
try {
const located = locateNodePackage(name, {
from: join(projectRoot, "__hypit_vocabulary__.mjs"),
workspaceRoots: [projectRoot],
- ...(videoCliDistribution.packageRoot === undefined ? {} : { distributionRoots: [videoCliDistribution.packageRoot] }),
+ ...(distributionRoot === undefined ? {} : { distributionRoots: [distributionRoot] }),
});
return join(located.root, "README.md");
} catch { return undefined; }
}
-export async function listSurfaces(projectRoot: string, packages: readonly string[], tags?: readonly string[]): Promise<readonly SurfaceListing[]> {
+export async function listSurfaces(
+ projectRoot: string,
+ packages: readonly string[],
+ tags?: readonly string[],
+ distributionRoot?: string,
+): Promise<readonly SurfaceListing[]> {
assert(packages.length > 0, "name at least one package");
- const loaded = await loadNodePackageSelection(packages, projectRoot, loading());
+ const loaded = await loadNodePackageSelection(packages, projectRoot, loading(distributionRoot));
const named = new Set(packages);
const wanted = tags === undefined ? undefined : new Set(tags);
const surfaces: SurfaceListing[] = [];
for (const pack of loaded) {
// Loading a package brings its dependencies with it; the answer is about the ones named.
if (!named.has(pack.specifier)) continue;
- for (const facet of pack.contribution.hostFacets ?? []) {
- if (facet.abi !== markupSurfaceHostFacetAbi) continue;
+ for (const facet of pack.contribution.facets ?? []) {
+ if (facet.abi !== markupSurfaceFacetAbi) continue;
const surface = facet.implementation as RegisteredSurface;
if (wanted !== undefined && !wanted.has(surface.tag) && !wanted.has(surface.surface)) continue;
- const readme = readmePath(pack.specifier, projectRoot);
+ const readme = readmePath(pack.specifier, projectRoot, distributionRoot);
surfaces.push({
package: pack.specifier,
module: surface.module,
@@ -218,36 +210,6 @@ export function describeSchema(schema: ValueSchema, indent = ""): string[] {
}
}
-const VISUAL_SHAPES: Readonly<Record<string, ValueSchema>> = {
- "visual-track": visualTrackSchema,
- "visual-element": visualElementSchema,
- program: visualProgramSchema,
- box: visualBoxSchema,
- mask: visualMaskSchema,
- text: visualTextSchema,
- image: visualImageSchema,
- video: visualVideoSchema,
- surface: visualSurfaceSchema,
- "text-flow": visualTextFlowSchema,
- "text-typography": visualTextTypographySchema,
- "text-paint": visualTextPaintSchema,
- "text-document": visualTextDocumentSchema,
- "path-command": visualPathCommandSchema,
-};
-
-// Each of these is refused somewhere in composition, or follows from how the emitted CSS is written.
-const VISUAL_RULES = [
- "A Present holds exactly one element with no `parent`; every other element names one, and it must be a box, mask or program.",
- "`order` is unique across the whole Present, not among siblings.",
- "A child's position is measured from its parent's box, not from the Canvas.",
- "An animation carries at least two keyframes, and every keyframe of one animation declares the same properties; `atFrame` is Present-relative.",
- "A plain text element provides exact ordered font artifacts and cannot combine them with raw `font`, `font-family`, `font-style`, `font-synthesis` or `font-weight` styles.",
- "A text element using glyph Paint cannot also declare raw stroke or paint-order styles.",
- "A media element's artifact media type must match image/video, and still images cannot carry sampling.",
- "A Surface with still timing cannot carry sampling; frame-based Surface sampling must match its typed timing.",
- "Mask roots must be direct children of one Present and both mask/content references must resolve to owned elements.",
-] as const;
-
export function visualSchema(shape?: string): {
readonly shapes: readonly { readonly shape: string; readonly describes: string }[];
readonly animatableLocalStyles: readonly string[];
@@ -256,14 +218,15 @@ export function visualSchema(shape?: string): {
readonly rules: readonly string[];
} {
const asked = shape?.trim();
- assert(asked === undefined || asked.length === 0 || Object.hasOwn(VISUAL_SHAPES, asked), `shape must be one of ${Object.keys(VISUAL_SHAPES).join(", ")}`);
- const chosen = asked === undefined || asked.length === 0 ? Object.keys(VISUAL_SHAPES) : [asked];
+ const shapes = visualCompositionVocabulary.shapes;
+ assert(asked === undefined || asked.length === 0 || Object.hasOwn(shapes, asked), `shape must be one of ${Object.keys(shapes).join(", ")}`);
+ const chosen = asked === undefined || asked.length === 0 ? Object.keys(shapes) : [asked];
return {
- shapes: chosen.map((name) => ({ shape: name, describes: describeSchema(VISUAL_SHAPES[name]!).join("\n") })),
+ shapes: chosen.map((name) => ({ shape: name, describes: describeSchema(shapes[name]!).join("\n") })),
animatableLocalStyles: [...animatableLocalStyles],
styleNames: [...VISUAL_STYLE_NAMES_V1],
styleEnumValues: VISUAL_STYLE_ENUM_VALUES_V1,
- rules: VISUAL_RULES,
+ rules: visualCompositionVocabulary.rules,
};
}
@@ -333,12 +296,17 @@ export function writeVocabularyHelp(io: CliIo): void {
].join("\n"));
}
-export async function runVocabularyCli(argv: readonly string[], io: CliIo, cwd = process.cwd()): Promise<void> {
+export async function runVocabularyCli(
+ argv: readonly string[],
+ io: CliIo,
+ cwd = process.cwd(),
+ distributionRoot?: string,
+): Promise<void> {
const rest = argv.slice(1);
if (rest.includes("--help")) { writeVocabularyHelp(io); return; }
const json = rest.includes("--json");
const words = rest.filter((item) => item !== "--json" && item !== "--debug" && item !== "--verbose" && item !== "--no-color");
- const projectRoot = await nearestPackageRoot(cwd);
+ const projectRoot = await findProjectRoot({ cwd }) ?? distributionRoot ?? resolve(cwd);
if (words[0] === "--visual") {
const shape = words[1];
@@ -367,7 +335,7 @@ export async function runVocabularyCli(argv: readonly string[], io: CliIo, cwd =
if (packages.length === 0) {
assert(tags.length === 0, "--tag narrows a named package; name the package first");
- const listing = await listPackages(projectRoot);
+ const listing = await listPackages(projectRoot, distributionRoot);
if (json) { io.write(`${JSON.stringify({ projectRoot, packages: listing }, null, 2)}\n`); return; }
assert(listing.length > 0, `no Hypit packages installed under ${projectRoot} or the Distribution`);
io.write(`${listing.map((item) => {
@@ -380,7 +348,7 @@ export async function runVocabularyCli(argv: readonly string[], io: CliIo, cwd =
return;
}
- const surfaces = await listSurfaces(projectRoot, packages, tags.length === 0 ? undefined : tags);
+ const surfaces = await listSurfaces(projectRoot, packages, tags.length === 0 ? undefined : tags, distributionRoot);
if (json) { io.write(`${JSON.stringify({ projectRoot, packages, surfaces }, null, 2)}\n`); return; }
assert(surfaces.length > 0, `${packages.join(", ")} ${packages.length === 1 ? "declares" : "declare"} no Markup Surface${tags.length === 0 ? "" : ` tagged ${tags.join(", ")}`}`);
io.write(`${surfaces.map(surfaceText).join("\n\n")}\n`);
diff --git a/packages/video-cli/test/cli.test.ts b/packages/video/test/cli.test.ts
similarity index 82%
rename from packages/video-cli/test/cli.test.ts
rename to packages/video/test/cli.test.ts
index c18db93c..76ca360f 100644
--- a/packages/video-cli/test/cli.test.ts
+++ b/packages/video/test/cli.test.ts
@@ -4,20 +4,30 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import test from "node:test";
-import { runVideoCli, videoCliDistribution } from "@hypit/video-cli";
-import { runCli as runCommand } from "@hypit/cli";
+import { createVideoDistribution, videoCommandModules } from "@hypit/video";
+import { runCli as runCommand, runCliApplication } from "@hypit/cli";
+import { installDistributionPackageResolution } from "@hypit/loader/node";
import { videoTestPackages } from "./packages.js";
+const videoDistribution = createVideoDistribution();
+
const runCli = (
argv: readonly string[],
io: { readonly write: (text: string) => void },
-) => runVideoCli([...argv, "--json"], io, videoTestPackages);
+) => {
+ installDistributionPackageResolution(videoDistribution.packageRoot === undefined
+ ? [] : [videoDistribution.packageRoot]);
+ return runCliApplication([...argv, "--json"], io, {
+ distribution: { ...videoDistribution, bootstrapPackages: videoTestPackages },
+ commandModules: videoCommandModules,
+ });
+};
test("source package selection follows Run and Author imports", async () => {
const root = await mkdtemp(join(tmpdir(), "hypit-cli-package-selection-"));
try {
- await writeFile(join(root, "style.svs"), `<?svml using="@hypit/svs@1"?>\n<sheet version="1"/>`, "utf8");
+ await writeFile(join(root, "style.svs"), `<?svml using="@hypit/recipe@1"?>\n<sheet version="1"/>`, "utf8");
await writeFile(join(root, "main.svml"), `<?svml using="@hypit/markup@1"?>
<svml>
<import from="@hypit/script@1"/>
@@ -25,16 +35,16 @@ test("source package selection follows Run and Author imports", async () => {
<script id="story"><line><HOST>Hello.</line></script>
</svml>`, "utf8");
const run = join(root, "build.svrun");
- await writeFile(run, `<?svml using="@hypit/run-markup@1"?>
+ await writeFile(run, `<?svml using="@hypit/markup/run@1"?>
<svrun version="1">
<author source="./main.svml"/>
<target output="story"/>
</svrun>`, "utf8");
- const discovered = await videoCliDistribution.discoverSourcePackages!(run, {
+ const discovered = await videoDistribution.discoverSourcePackages!(run, {
workspaceRoot: root,
packages: videoTestPackages,
});
- assert.deepEqual(discovered.selected, ["@hypit/run-markup", "@hypit/script", "@hypit/svs"]);
+ assert.deepEqual(discovered.selected, ["@hypit/markup", "@hypit/recipe", "@hypit/script"]);
} finally {
await rm(root, { recursive: true, force: true });
}
@@ -48,7 +58,7 @@ test("provider-free example plans from installed Source packages", async () => {
await runCli([
"plan",
join(fixture, "build.svrun"),
- "--workspace",
+ "--project",
process.cwd(),
], { write: (text) => { output += text; } });
const plan = JSON.parse(output) as {
@@ -90,7 +100,7 @@ test("check compiles a data-only package Source export without a project copy",
</text:Render>
</svml>`, "utf8");
let output = "";
- await runCli(["check", source, "--workspace", root], {
+ await runCli(["check", source, "--project", root], {
write: (text) => { output += text; },
});
const checked = JSON.parse(output) as { readonly sourceKind: string; readonly units: number };
@@ -113,18 +123,18 @@ test("pricing keeps every planned generation after the old 20-request cutoff and
<gpt:Image id="${id}" prompt={${id}-prompt} aspect-ratio="9:16" resolution="2K"/>`).join("\n")}
</svml>`);
const source = join(root, "build.svrun");
- await writeFile(source, `<?svml using="@hypit/run-markup@1"?>
+ await writeFile(source, `<?svml using="@hypit/markup/run@1"?>
<svrun version="1"><author source="./main.svml"/>
${ids.map((id) => `<target output="${id}.image"/>`).join("\n")}
</svrun>`);
let queried = 0;
let output = "";
- await runCommand(["pricing", source, "--workspace", root, "--runtime", join(root, "runtime.json"),
+ await runCommand(["pricing", source, "--project", root, "--runtime", join(root, "runtime.json"),
"--json", "--limit", "1"], { write: (text) => { output += text; } }, {
- ...videoCliDistribution,
+ ...videoDistribution,
bootstrapPackages: videoTestPackages,
openRuntimeHost: async (path, options) => ({
- ...await videoCliDistribution.openRuntimeHost(path, options),
+ ...await videoDistribution.openRuntimeHost(path, options),
pricing: async (requests) => {
queried = requests.length;
return requests.map((request) => ({
diff --git a/packages/video-cli/test/packages.ts b/packages/video/test/packages.ts
similarity index 60%
rename from packages/video-cli/test/packages.ts
rename to packages/video/test/packages.ts
index 41346cad..cb36518d 100644
--- a/packages/video-cli/test/packages.ts
+++ b/packages/video/test/packages.ts
@@ -1,63 +1,57 @@
-import artifact from "../../artifact/src/activation.js";
+import artifact from "../../blob/src/activation.js";
import captionFine from "../../caption-fine/src/activation.js";
import caption from "../../caption/src/activation.js";
import composition from "../../composition/src/activation.js";
-import estimate from "../../estimate/src/activation.js";
import film from "../../film/src/activation.js";
-import fontsOpen from "../../fonts-open/src/activation.js";
+import fontsource from "../../fontsource/src/activation.js";
import generation from "../../generation/src/activation.js";
-import renderHyperframes from "../../render-hyperframes/src/activation.js";
-import hyperframes from "../../hyperframes/src/activation.js";
-import mediaPipeline from "../../media-pipeline/src/activation.js";
+import renderHTML from "../../html-video/src/activation.js";
+import htmlProgram from "../../html-program/src/activation.js";
+import mediaOperations from "../../media-operations/src/activation.js";
import mediaTrack from "../../visual-track/src/activation.js";
import media from "../../media/src/activation.js";
import narrative from "../../narrative/src/activation.js";
import narrativeCaption from "../../narrative-caption/src/activation.js";
import narrativeTemporal from "../../narrative-temporal/src/activation.js";
import text from "../../text/src/activation.js";
-import runMarkup from "../../run-markup/src/activation.js";
+import runMarkup from "../../markup/src/run/activation.js";
import script from "../../script/src/activation.js";
import seedance from "../../seedance/src/activation.js";
-import speechAlignment from "../../speech-alignment/src/activation.js";
+import speechAlignment from "../../narrative-speech-alignment/src/activation.js";
import timelineAuthor from "../../timeline-author/src/activation.js";
-import speech from "../../speech/src/activation.js";
import speechEvidence from "../../speech-evidence/src/activation.js";
import timeline from "../../timeline/src/activation.js";
import spatial from "../../spatial/src/activation.js";
import temporal from "../../temporal/src/activation.js";
-import visualIr from "../../visual-ir/src/activation.js";
-import svs from "../../svs/src/activation.js";
+import svs from "../../recipe/src/activation.js";
import textFine from "../../text-fine/src/activation.js";
import whisperX from "../../whisperx/src/activation.js";
-import type { NodePackageContribution } from "@hypit/package-loader-node";
+import type { PackageContribution } from "@hypit/loader";
-const bind = (specifier: string, contribution: NodePackageContribution) => ({
+const bind = (specifier: string, contribution: PackageContribution) => ({
specifier,
contribution,
});
-/** Test-only explicit environment; production video CLI starts with no author packages. */
+/** Test-only explicit environment; the production Video application starts with no author packages. */
export const videoTestPackages = [
- bind("@hypit/artifact", artifact),
+ bind("@hypit/blob", artifact),
bind("@hypit/narrative", narrative),
bind("@hypit/narrative-caption", narrativeCaption),
bind("@hypit/narrative-temporal", narrativeTemporal),
bind("@hypit/media", media),
- bind("@hypit/speech", speech),
bind("@hypit/speech-evidence", speechEvidence),
bind("@hypit/timeline", timeline),
- bind("@hypit/visual-ir", visualIr),
bind("@hypit/composition", composition),
- bind("@hypit/svs", svs),
+ bind("@hypit/recipe", svs),
bind("@hypit/script", script),
- bind("@hypit/estimate", estimate),
- bind("@hypit/fonts-open", fontsOpen),
+ bind("@hypit/fontsource", fontsource),
bind("@hypit/text", text),
bind("@hypit/generation", generation),
bind("@hypit/seedance", seedance),
bind("@hypit/caption", caption),
bind("@hypit/caption-fine", captionFine),
- bind("@hypit/speech-alignment", speechAlignment),
+ bind("@hypit/narrative-speech-alignment", speechAlignment),
bind("@hypit/timeline-author", timelineAuthor),
bind("@hypit/whisperx", whisperX),
bind("@hypit/spatial", spatial),
@@ -65,8 +59,8 @@ export const videoTestPackages = [
bind("@hypit/visual-track", mediaTrack),
bind("@hypit/text-fine", textFine),
bind("@hypit/film", film),
- bind("@hypit/hyperframes", hyperframes),
- bind("@hypit/media-pipeline", mediaPipeline),
- bind("@hypit/render-hyperframes", renderHyperframes),
- bind("@hypit/run-markup", runMarkup),
+ bind("@hypit/html-program", htmlProgram),
+ bind("@hypit/media-operations", mediaOperations),
+ bind("@hypit/html-video", renderHTML),
+ bind("@hypit/markup", runMarkup),
] as const;
diff --git a/packages/video-cli/test/vocabulary.test.ts b/packages/video/test/vocabulary.test.ts
similarity index 84%
rename from packages/video-cli/test/vocabulary.test.ts
rename to packages/video/test/vocabulary.test.ts
index 6c93a148..d7807bc8 100644
--- a/packages/video-cli/test/vocabulary.test.ts
+++ b/packages/video/test/vocabulary.test.ts
@@ -6,9 +6,8 @@ import { fileURLToPath } from "node:url";
import test from "node:test";
import type { CliIo } from "@hypit/cli";
-import { markupSurfaceHostFacetAbi } from "@hypit/markup";
+import { markupSurfaceFacetAbi } from "@hypit/markup";
-import { videoCliDistribution } from "../src/distribution.js";
import { listPackages, listSurfaces, runVocabularyCli, visualSchema } from "../src/vocabulary.js";
const repositoryRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..", "..", "..");
@@ -29,8 +28,8 @@ function io(): { readonly io: CliIo; text: () => string } {
test("the listing sees every activatable package from the repository root", async () => {
const listing = await listPackages(repositoryRoot);
assert.equal(new Set(listing.map((item) => item.name)).size, listing.length);
- const pipeline = listing.find((item) => item.name === "@hypit/media-pipeline");
- assert.ok(pipeline !== undefined, "media-pipeline is listed");
+ const pipeline = listing.find((item) => item.name === "@hypit/media-operations");
+ assert.ok(pipeline !== undefined, "media-operations is listed");
assert.ok(pipeline.tags.includes("StillVideo"), `tags: ${pipeline.tags.join(", ")}`);
assert.equal(pipeline.unreadable, undefined);
});
@@ -39,7 +38,6 @@ test("vocabulary discovers bundled packages from a separate project without node
const root = await mkdtemp(join(tmpdir(), "hypit-vocabulary-"));
const project = join(root, "project");
const distribution = join(root, "distribution");
- const originalRoot = Object.getOwnPropertyDescriptor(videoCliDistribution, "packageRoot")!;
async function packageAt(directory: string, name: string, description = name): Promise<void> {
await mkdir(directory, { recursive: true });
await writeFile(join(directory, "package.json"), JSON.stringify({
@@ -47,9 +45,9 @@ test("vocabulary discovers bundled packages from a separate project without node
hypit: { activation: "./activation.mjs" },
}));
await writeFile(join(directory, "activation.mjs"), `export default {
- format: "hypit.node-package@1",
- hostFacets: [{
- abi: ${JSON.stringify(markupSurfaceHostFacetAbi)},
+ format: "hypit.package@1",
+ facets: [{
+ abi: ${JSON.stringify(markupSurfaceFacetAbi)},
implementation: {
module: { name: ${JSON.stringify(name)}, version: "1" },
surface: "card", tag: "Card", mode: "raw", outputs: [], handler: () => [],
@@ -65,19 +63,18 @@ test("vocabulary discovers bundled packages from a separate project without node
await writeFile(join(bundled, "README.md"), "Example bundled component.\n");
await mkdir(join(distribution, "packages", "inactive"), { recursive: true });
await writeFile(join(distribution, "packages", "inactive", "package.json"), JSON.stringify({ name: "@hypit/inactive" }));
- Object.defineProperty(videoCliDistribution, "packageRoot", { value: distribution });
const human = io();
- await runVocabularyCli(["vocabulary"], human.io, project);
+ await runVocabularyCli(["vocabulary"], human.io, project, distribution);
assert.match(human.text(), /@hypit\/bundled\n\s+tags: Card/u);
const json = io();
- await runVocabularyCli(["vocabulary", "--json"], json.io, project);
+ await runVocabularyCli(["vocabulary", "--json"], json.io, project, distribution);
assert.deepEqual(JSON.parse(json.text()).packages, [{
name: "@hypit/bundled", description: "@hypit/bundled", tags: ["Card"],
}]);
const named = io();
- await runVocabularyCli(["vocabulary", "@hypit/bundled", "--tag", "Card", "--json"], named.io, project);
+ await runVocabularyCli(["vocabulary", "@hypit/bundled", "--tag", "Card", "--json"], named.io, project, distribution);
const surfaces = JSON.parse(named.text()).surfaces;
assert.equal(surfaces.length, 1);
assert.equal(surfaces[0].package, "@hypit/bundled");
@@ -89,27 +86,26 @@ test("vocabulary discovers bundled packages from a separate project without node
await packageAt(join(project, "packages", "local"), "@studio/local");
await packageAt(join(project, "node_modules", "@studio", "custom"), "@studio/custom", "project package");
await packageAt(join(distribution, "packages", "custom"), "@studio/custom", "distribution fallback");
- const listing = await listPackages(project);
+ const listing = await listPackages(project, distribution);
assert.deepEqual(listing.map((item) => item.name).sort(), ["@hypit/bundled", "@studio/custom", "@studio/local"]);
assert.equal(listing.find((item) => item.name === "@studio/custom")!.description, "project package");
assert.ok(listing.every((item) => item.unreadable === undefined && item.tags.includes("Card")));
} finally {
- Object.defineProperty(videoCliDistribution, "packageRoot", originalRoot);
await rm(root, { recursive: true, force: true });
}
});
test("a named package answers with its own Surfaces only", async () => {
- const surfaces = await listSurfaces(repositoryRoot, ["@hypit/media-pipeline"], ["StillVideo"]);
+ const surfaces = await listSurfaces(repositoryRoot, ["@hypit/media-operations"], ["StillVideo"]);
assert.equal(surfaces.length, 1);
const [still] = surfaces;
- assert.equal(still!.package, "@hypit/media-pipeline");
+ assert.equal(still!.package, "@hypit/media-operations");
assert.equal(still!.tag, "StillVideo");
const vocabulary = still!.vocabulary as { attributes: readonly { name: string }[] };
assert.ok(vocabulary.attributes.some((attribute) => attribute.name === "duration"));
assert.ok(still!.readme !== undefined);
assert.equal(basename(still!.readme), "README.md");
- assert.equal(basename(dirname(still!.readme)), "media-pipeline");
+ assert.equal(basename(dirname(still!.readme)), "media-operations");
});
test("the visual schema prints every shape and refuses an unknown one", () => {
@@ -122,14 +118,14 @@ test("the visual schema prints every shape and refuses an unknown one", () => {
test("the command prints human and JSON views", async () => {
const human = io();
- await runVocabularyCli(["vocabulary", "@hypit/media-pipeline", "--tag", "StillVideo"], human.io, repositoryRoot);
+ await runVocabularyCli(["vocabulary", "@hypit/media-operations", "--tag", "StillVideo"], human.io, repositoryRoot);
assert.match(human.text(), /<StillVideo>/);
assert.match(human.text(), /duration/);
const json = io();
await runVocabularyCli(["vocabulary", "--json"], json.io, repositoryRoot);
const parsed = JSON.parse(json.text()) as { packages: readonly { name: string }[] };
- assert.ok(parsed.packages.some((item) => item.name === "@hypit/media-pipeline"));
+ assert.ok(parsed.packages.some((item) => item.name === "@hypit/media-operations"));
await assert.rejects(runVocabularyCli(["vocabulary", "--tag", "x"], io().io, repositoryRoot), /name the package first/);
});
@@ -142,6 +138,6 @@ test("the human view distinguishes logical Modules contributed by one physical p
assert.match(human.text(), /import <import as="gpt" from="@hypit\/gpt-image@1"\/>/u);
assert.match(human.text(), /module @hypit\/gpt-image\/clean@1/u);
assert.match(human.text(), /import <import as="gpt" from="@hypit\/gpt-image\/clean@1"\/>/u);
- assert.match(human.text(), /image BlobArtifact \(@hypit\/artifact@1\)/u);
+ assert.match(human.text(), /image Blob \(@hypit\/blob@1\)/u);
assert.doesNotMatch(human.text(), /\{"name":"image"/u);
});
diff --git a/packages/whisperx/README.md b/packages/whisperx/README.md
index 224c9a4d..a0742027 100644
--- a/packages/whisperx/README.md
+++ b/packages/whisperx/README.md
@@ -4,12 +4,36 @@ Explicit WhisperX model-family capability for speech alignment. Importing this p
WhisperX; Runtime registration binds the resulting evidence Need to a concrete Endpoint. The package
contains no credentials, Python environment or queue.
+The package implementation consumes only public `@hypit/hypit/*` author/domain APIs and can be
+released independently from the Host. Providers that interpret this exact capability may declare a
+normal compatible dependency or peer range on this package; npm/pnpm and the project lockfile own the
+resolved physical version. The logical capability remains `@hypit/whisperx@1`.
+
+The official Distribution currently obtains this package as a default npm dependency because its CLI
+and default HypiHub Provider use the capability contract. Its source is not embedded in the root
+tarball, and its npm version can advance independently.
+
+The package also owns `@hypit/whisperx/cli` and therefore `hypit transcribe`. That command projects an
+explicit audio or video file to canonical evidence audio through `@hypit/media-local`, invokes the
+selected WhisperX alignment Endpoint, and writes an ordinary `hypit.transcript@1` file. It is an
+immediate authoring operation: it creates no Author Graph, Build or Result, and its transcript stays
+on the input file's local clock.
+
+```bash
+hypit transcribe reference.mp4 --language en --to notes/reference.transcript.json
+```
+
+The reusable transcript document and phrase-range operations belong to `@hypit/speech-evidence`.
+WhisperX owns only how evidence is obtained through this model family; media decoding remains with
+the local-media executor.
+
`<whisperx:Alignment>` consumes one normalized `SynchronizedMedia`, its `LocalTemporalDomain`, one
authored Script Segment and the owning Narrative. For a Segment containing Tokens it also requires an
explicit lowercase two- or three-letter language code. The provider receives canonical evidence audio
tagged with the selected local domain identity and returns provider-neutral
-`AlignedTranscriptEvidence` preserving that identity and exact sample span; deterministic local alignment publishes one
-`NarrativeAlignment`:
+`AlignedTranscriptEvidence` preserving that identity and exact sample span. The ordinary dependency
+`@hypit/narrative-speech-alignment` then performs the deterministic authored-Narrative mapping and
+publishes one `NarrativeAlignment`:
```svml
<whisperx:Alignment id="opening" narrative={story}
diff --git a/packages/whisperx/package.json b/packages/whisperx/package.json
index 1a74c6e9..8a071c85 100644
--- a/packages/whisperx/package.json
+++ b/packages/whisperx/package.json
@@ -1,29 +1,39 @@
{
"name": "@hypit/whisperx",
- "version": "0.0.0-dev",
+ "version": "0.1.0",
"license": "SEE LICENSE IN LICENSE",
"private": true,
"type": "module",
"exports": {
- ".": "./src/index.ts"
+ ".": "./src/index.ts",
+ "./cli": "./src/cli.ts"
},
+ "files": [
+ "dist",
+ "README.md"
+ ],
"hypit": {
"activation": "./src/activation.ts"
},
+ "peerDependencies": {
+ "@hypit/hypit": "workspace:^"
+ },
"dependencies": {
- "@hypit/component-kit": "workspace:*",
- "@hypit/elaborator": "workspace:*",
- "@hypit/media-pipeline": "workspace:*",
+ "@hypit/media-local": "workspace:^",
+ "@hypit/narrative-speech-alignment": "workspace:^"
+ },
+ "devDependencies": {
+ "@hypit/hypit": "workspace:*",
+ "@hypit/producer": "workspace:*",
+ "@hypit/author": "workspace:*",
"@hypit/media": "workspace:*",
"@hypit/narrative": "workspace:*",
"@hypit/narrative-temporal": "workspace:*",
"@hypit/protocol": "workspace:*",
- "@hypit/speech-alignment": "workspace:*",
"@hypit/speech-evidence": "workspace:*",
"@hypit/markup": "workspace:*",
- "@hypit/temporal": "workspace:*"
- },
- "devDependencies": {
+ "@hypit/temporal": "workspace:*",
+ "typescript": "5.9.3",
"@hypit/timeline": "workspace:*"
}
}
diff --git a/packages/whisperx/src/activation.ts b/packages/whisperx/src/activation.ts
index dcf13646..b8446945 100644
--- a/packages/whisperx/src/activation.ts
+++ b/packages/whisperx/src/activation.ts
@@ -1,4 +1,6 @@
-import { createMarkupSurfaceHostFacet } from "@hypit/markup";
+import { createAdmissionPackageFacet } from "@hypit/hypit/admission";
+import { createProducerPackageFacet } from "@hypit/hypit/producer";
+import { createMarkupSurfaceFacet } from "@hypit/hypit/markup";
import {
decodeWhisperXAlignmentSurface, whisperXComponent,
whisperXManifest, whisperXModuleRef,
@@ -6,10 +8,10 @@ import {
} from "./index.js";
export const hypitPackage = {
- format: "hypit.node-package@1" as const,
+ format: "hypit.package@1" as const,
modules: [{ manifest: whisperXManifest }],
- components: [whisperXComponent],
- hostFacets: [createMarkupSurfaceHostFacet({
+ facets: [
+ ...[whisperXComponent].flatMap((component) => [createProducerPackageFacet(component), createAdmissionPackageFacet(component)]),createMarkupSurfaceFacet({
module: whisperXModuleRef,
declaration: whisperXMarkupSurfaces.find((item) => item.name === "alignment")!,
handler: decodeWhisperXAlignmentSurface,
diff --git a/packages/whisperx/src/cli.ts b/packages/whisperx/src/cli.ts
new file mode 100644
index 00000000..e723e0ac
--- /dev/null
+++ b/packages/whisperx/src/cli.ts
@@ -0,0 +1,147 @@
+import { mkdir, stat, writeFile } from "node:fs/promises";
+import { dirname, resolve } from "node:path";
+
+import {
+ cliProviderLine,
+ cliProviderView,
+ createCliScratchResources,
+ openCliRuntimeHost,
+ selectCliProvider,
+} from "@hypit/hypit/cli";
+import type { CliApplicationContext, CliCommandModule, CliIo, CliRuntimeHost } from "@hypit/hypit/cli";
+import { speechEvidenceFile } from "@hypit/media-local";
+import type { Need } from "@hypit/hypit/protocol";
+import { sealSpeechEvidenceAudio, speechEvidenceTypes, transcriptDocumentFromEvidence } from "@hypit/hypit/speech-evidence";
+import type { AlignedTranscriptEvidence } from "@hypit/hypit/speech-evidence";
+
+import { whisperXRequestForEvidenceAudio } from "./evidence.js";
+import { whisperXCapabilities } from "./manifest.js";
+import { parseWhisperXLanguage } from "./types.js";
+
+function assert(condition: unknown, message: string): asserts condition {
+ if (!condition) throw new Error(message);
+}
+
+type Parsed = {
+ readonly positionals: readonly string[];
+ readonly options: ReadonlyMap<string, string>;
+ readonly json: boolean;
+};
+
+function parse(argv: readonly string[]): Parsed {
+ const allowed = new Set(["--language", "--to", "--runtime", "--project"]);
+ const positionals: string[] = [];
+ const options = new Map<string, string>();
+ let json = false;
+ for (let index = 1; index < argv.length; index++) {
+ const item = argv[index]!;
+ if (item === "--json") { json = true; continue; }
+ if (["--debug", "--verbose", "--no-color"].includes(item)) continue;
+ if (item === "--color") { index += 1; continue; }
+ if (!item.startsWith("--")) { positionals.push(item); continue; }
+ assert(allowed.has(item), `unknown option ${item}`);
+ assert(!options.has(item), `${item} cannot be repeated`);
+ const value = argv[++index];
+ assert(value !== undefined && !value.startsWith("--"), `${item} requires a value`);
+ options.set(item, value);
+ }
+ return { positionals, options, json };
+}
+
+async function destination(parsed: Parsed, cwd: string): Promise<string> {
+ const named = parsed.options.get("--to");
+ assert(named !== undefined, "--to is required: the transcript file to write");
+ const path = resolve(cwd, named);
+ assert(!await stat(path).then(() => true, () => false), `Destination ${path} already exists`);
+ return path;
+}
+
+async function writeNew(path: string, content: string): Promise<void> {
+ await mkdir(dirname(path), { recursive: true });
+ try { await writeFile(path, content, { flag: "wx" }); }
+ catch (error) {
+ if (error instanceof Error && "code" in error && error.code === "EEXIST") {
+ throw new Error(`Destination ${path} already exists`);
+ }
+ throw error;
+ }
+}
+
+export type TranscribeEnvironment = {
+ readonly cwd: string;
+ openHost(runtime: string | undefined, project: string | undefined): Promise<{
+ readonly profile: string;
+ readonly host: Pick<CliRuntimeHost, "providers" | "invoke">;
+ }>;
+};
+
+export function transcribeEnvironment(application: CliApplicationContext): TranscribeEnvironment {
+ return {
+ cwd: application.cwd,
+ openHost: async (runtime, project) => await openCliRuntimeHost(application, runtime, project),
+ };
+}
+
+export function writeTranscribeHelp(io: CliIo): void {
+ io.write("hypit transcribe\nEstablish word times with the WhisperX alignment Endpoint selected by the Runtime Profile.\n\n"
+ + " hypit transcribe <audio|video> --to <transcript.json> --language <code> [--runtime <profile>] [--project <directory>]\n\n"
+ + "The local media capability projects 16 kHz mono evidence; WhisperX owns alignment and the transcript view.\n"
+ + "This is one immediate request: no Build or Result state is created.\n");
+}
+
+export async function runTranscribeCli(
+ argv: readonly string[],
+ io: CliIo,
+ environment: TranscribeEnvironment,
+): Promise<void> {
+ if (argv.includes("--help")) { writeTranscribeHelp(io); return; }
+ const parsed = parse(argv);
+ assert(parsed.positionals.length === 1, "transcribe takes exactly one audio or video file");
+ const source = resolve(environment.cwd, parsed.positionals[0]!);
+ const language = parseWhisperXLanguage(parsed.options.get("--language"), "transcribe --language");
+ const to = await destination(parsed, environment.cwd);
+ const { profile, host } = await environment.openHost(parsed.options.get("--runtime"), parsed.options.get("--project"));
+ const evidence = await speechEvidenceFile(source);
+ const resources = createCliScratchResources();
+ const artifact = await resources.put(evidence.bytes, "audio/wav");
+ const audio = sealSpeechEvidenceAudio({ domainId: "cli-transcribe", artifact, sampleFrames: evidence.sampleFrames });
+ const need: Need = {
+ id: "need:hypit-transcribe",
+ capability: whisperXCapabilities.alignment,
+ returns: speechEvidenceTypes.alignedTranscript,
+ constraints: whisperXRequestForEvidenceAudio(audio, { language }),
+ result: "record:hypit-transcribe",
+ };
+ const provider = await selectCliProvider(host, need, profile);
+ if (!parsed.json) io.write(`Transcribing through ${cliProviderLine(provider)}\n`);
+ const report = parsed.json ? io.writeProgress : io.writeProgress ?? io.write;
+ let previousPhase: string | undefined;
+ const fulfillment = await host.invoke(need, resources, {
+ reportProgress: async (progress) => {
+ if (progress.phase === previousPhase) return;
+ previousPhase = progress.phase;
+ report?.(` · ${progress.phase}\n`);
+ },
+ reportDiagnostic: async (diagnostic) => { report?.(` · ${diagnostic.message}\n`); },
+ });
+ assert(fulfillment.value.kind === "inline", "the transcript came back by reference");
+ const aligned = fulfillment.value.value as unknown as AlignedTranscriptEvidence;
+ const file = transcriptDocumentFromEvidence(aligned, { source, language });
+ const words = file.passages.reduce((total, passage) => total + passage.words.length, 0);
+ await writeNew(to, `${JSON.stringify(file, null, 2)}\n`);
+ const view = { format: "hypit.whisperx-transcribe@1", source, language,
+ audio_seconds: file.audio_seconds, extracted: evidence.extracted, ...cliProviderView(provider),
+ passages: file.passages.length, words, path: to };
+ if (parsed.json) io.write(`${JSON.stringify(view, null, 2)}\n`);
+ else io.write(`✓ Transcript written\n\n ${words} words in ${file.passages.length} passage${
+ file.passages.length === 1 ? "" : "s"} over ${file.audio_seconds}s\n ${to}\n`);
+}
+
+export const cliCommandModules = [{
+ format: "hypit.cli-command@1",
+ id: "@hypit/whisperx",
+ commands: ["transcribe"],
+ writeRootHelp(io) { io.write("\nSpeech alignment\n transcribe\n hypit transcribe --help for inputs and Runtime selection\n"); },
+ writeHelp(_argv, io) { writeTranscribeHelp(io); },
+ async run(argv, io, context) { await runTranscribeCli(argv, io, transcribeEnvironment(context)); },
+}] as const satisfies readonly CliCommandModule[];
diff --git a/packages/whisperx/src/component.ts b/packages/whisperx/src/component.ts
index 27f2b62f..0c335272 100644
--- a/packages/whisperx/src/component.ts
+++ b/packages/whisperx/src/component.ts
@@ -1,8 +1,9 @@
-import { plannedNeedInputs } from "@hypit/component-kit";
-import type { ComponentPackage } from "@hypit/component-kit";
-import type { SpeechEvidenceAudio } from "@hypit/speech-evidence";
-import type { CanonicalValue, StoredValue } from "@hypit/protocol";
-import { canonicalize } from "@hypit/protocol";
+import { canonicalize } from "@hypit/hypit/protocol";
+import { plannedNeedInputs } from "@hypit/hypit/producer";
+import type { CanonicalValue, StoredValue } from "@hypit/hypit/protocol";
+import type { ProducerPackage } from "@hypit/hypit/producer";
+import type { AdmissionPackage } from "@hypit/hypit/admission";
+import type { SpeechEvidenceAudio } from "@hypit/hypit/speech-evidence";
import { whisperXRequestForEvidenceAudio } from "./evidence.js";
import { whisperXCapabilities, whisperXProducers } from "./manifest.js";
@@ -58,4 +59,4 @@ export const whisperXComponent = {
};
},
}],
-} satisfies ComponentPackage;
+} satisfies ProducerPackage & AdmissionPackage;
diff --git a/packages/whisperx/src/evidence.ts b/packages/whisperx/src/evidence.ts
index 59e4096b..b333a013 100644
--- a/packages/whisperx/src/evidence.ts
+++ b/packages/whisperx/src/evidence.ts
@@ -1,5 +1,5 @@
-import { assertSpeechEvidenceAudioIdentity } from "@hypit/speech-evidence";
-import type { SpeechEvidenceAudio } from "@hypit/speech-evidence";
+import { assertSpeechEvidenceAudioIdentity } from "@hypit/hypit/speech-evidence";
+import type { SpeechEvidenceAudio } from "@hypit/hypit/speech-evidence";
import type { WhisperXAlignmentRequest, WhisperXLanguage } from "./types.js";
import { parseWhisperXLanguage } from "./types.js";
diff --git a/packages/whisperx/src/fragment.ts b/packages/whisperx/src/fragment.ts
index a2135352..37a0d7af 100644
--- a/packages/whisperx/src/fragment.ts
+++ b/packages/whisperx/src/fragment.ts
@@ -1,10 +1,10 @@
-import { narrativeTypes } from "@hypit/narrative";
-import { narrativeTemporalProducers, narrativeTemporalTypes } from "@hypit/narrative-temporal";
-import { mediaTypes } from "@hypit/media";
-import { sealGraphFragment } from "@hypit/elaborator";
-import { mediaPipelineProducers } from "@hypit/media-pipeline";
-import { speechAlignmentProducers } from "@hypit/speech-alignment";
-import { temporalTypes } from "@hypit/temporal";
+import { narrativeTypes } from "@hypit/hypit/narrative";
+import { narrativeTemporalProducers, narrativeTemporalTypes } from "@hypit/hypit/narrative-temporal";
+import { mediaTypes } from "@hypit/hypit/media";
+import { sealGraphFragment } from "@hypit/hypit/author";
+import { speechEvidenceProducers } from "@hypit/hypit/speech-evidence";
+import { speechAlignmentProducers } from "@hypit/narrative-speech-alignment";
+import { temporalTypes } from "@hypit/hypit/temporal";
import { whisperXProducers, whisperXTypes } from "./manifest.js";
@@ -16,7 +16,7 @@ export const whisperXAlignmentFragment = sealGraphFragment({
{ name: "media", type: mediaTypes.synchronized }, { name: "domain", type: temporalTypes.localDomain },
{ name: "language", type: whisperXTypes.language }],
operations: [
- { id: "prepare-evidence-audio", producer: mediaPipelineProducers.projectSpeechEvidenceAudio,
+ { id: "prepare-evidence-audio", producer: speechEvidenceProducers.projectAudio,
inputs: { media: input("media"), domain: input("domain") }, result: { kind: "need", name: "evidenceAudio" } },
{ id: "request-whisperx", producer: whisperXProducers.request,
inputs: { evidence: operation("prepare-evidence-audio"), language: input("language") }, result: { kind: "need", name: "alignment" } },
diff --git a/packages/whisperx/src/manifest.ts b/packages/whisperx/src/manifest.ts
index d69fd3d6..bd943893 100644
--- a/packages/whisperx/src/manifest.ts
+++ b/packages/whisperx/src/manifest.ts
@@ -1,11 +1,10 @@
-import { mediaDependency, mediaTypes } from "@hypit/media";
-import { narrativeDependency, narrativeTypes } from "@hypit/narrative";
-import { narrativeTemporalDependency, narrativeTemporalTypes } from "@hypit/narrative-temporal";
-import { speechEvidenceDependency, speechEvidenceTypes } from "@hypit/speech-evidence";
-import type { CapabilityRef, ModuleManifest, ProducerRef, TypeRef } from "@hypit/protocol";
-import { mediaPipelineManifest, mediaPipelineModuleRef } from "@hypit/media-pipeline";
-import { speechAlignmentModuleRef } from "@hypit/speech-alignment";
-import { temporalDependency, temporalTypes } from "@hypit/temporal";
+import { mediaDependency, mediaTypes } from "@hypit/hypit/media";
+import { narrativeDependency, narrativeTypes } from "@hypit/hypit/narrative";
+import { narrativeTemporalDependency, narrativeTemporalTypes } from "@hypit/hypit/narrative-temporal";
+import { speechEvidenceDependency, speechEvidenceTypes } from "@hypit/hypit/speech-evidence";
+import type { CapabilityRef, ModuleManifest, ProducerRef, TypeRef } from "@hypit/hypit/protocol";
+import { speechAlignmentModuleRef } from "@hypit/narrative-speech-alignment";
+import { temporalDependency, temporalTypes } from "@hypit/hypit/temporal";
export const whisperXModuleRef = { name: "@hypit/whisperx", version: "1" } as const;
export const whisperXTypes = {
@@ -70,7 +69,6 @@ export const whisperXManifest: ModuleManifest = {
mediaDependency,
narrativeDependency,
narrativeTemporalDependency,
- { module: mediaPipelineModuleRef },
{ module: speechAlignmentModuleRef },
temporalDependency,
],
diff --git a/packages/whisperx/src/surface.ts b/packages/whisperx/src/surface.ts
index d371b540..c5a0d8ec 100644
--- a/packages/whisperx/src/surface.ts
+++ b/packages/whisperx/src/surface.ts
@@ -1,10 +1,9 @@
-import { assertExactAttributes as exactAttributes, textAttribute as stringAttribute,
- type StructuredElement, type StructuredSurfaceHandler, type SurfaceResolvedReference, type SurfaceRecordDraft, type MarkupAttributeValue } from "@hypit/markup";
-import { sameType } from "@hypit/protocol";
-import { narrativeTypes } from "@hypit/narrative";
-import type { NarrativeSegmentRef } from "@hypit/narrative";
-import { mediaTypes } from "@hypit/media";
-import { temporalTypes } from "@hypit/temporal";
+import { assertExactAttributes as exactAttributes, textAttribute as stringAttribute, type StructuredElement, type StructuredSurfaceHandler, type SurfaceResolvedReference, type SurfaceRecordDraft, type MarkupAttributeValue } from "@hypit/hypit/markup";
+import { sameType } from "@hypit/hypit/protocol";
+import { narrativeTypes } from "@hypit/hypit/narrative";
+import type { NarrativeSegmentRef } from "@hypit/hypit/narrative";
+import { mediaTypes } from "@hypit/hypit/media";
+import { temporalTypes } from "@hypit/hypit/temporal";
import { whisperXAlignmentFragment, whisperXBoundaryAlignmentFragment } from "./fragment.js";
import { whisperXTypes } from "./manifest.js";
diff --git a/packages/whisperx/src/transcript.ts b/packages/whisperx/src/transcript.ts
index 73a65bb3..31ac35a4 100644
--- a/packages/whisperx/src/transcript.ts
+++ b/packages/whisperx/src/transcript.ts
@@ -1,4 +1,4 @@
-import type { SpeechTranscriptPassage } from "@hypit/speech-evidence";
+import type { SpeechTranscriptPassage } from "@hypit/hypit/speech-evidence";
type RawWord = {
readonly text?: unknown;
diff --git a/packages/whisperx/src/types.ts b/packages/whisperx/src/types.ts
index f8d7c323..6a6cb4ca 100644
--- a/packages/whisperx/src/types.ts
+++ b/packages/whisperx/src/types.ts
@@ -1,4 +1,4 @@
-import type { SpeechEvidenceAudio } from "@hypit/speech-evidence";
+import type { SpeechEvidenceAudio } from "@hypit/hypit/speech-evidence";
/** Explicit language code. Executable language support belongs to the selected service. */
export type WhisperXLanguage = string;
diff --git a/packages/video-cli/test/creation.test.ts b/packages/whisperx/test/cli.test.ts
similarity index 69%
rename from packages/video-cli/test/creation.test.ts
rename to packages/whisperx/test/cli.test.ts
index 6ea2c7de..c41a1f5c 100644
--- a/packages/video-cli/test/creation.test.ts
+++ b/packages/whisperx/test/cli.test.ts
@@ -4,15 +4,14 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import test from "node:test";
-import { canonicalize } from "@hypit/protocol";
-import type { Need } from "@hypit/protocol";
-import type { ResourceStore } from "@hypit/runtime";
-import { sealAlignedTranscriptEvidence } from "@hypit/speech-evidence";
+import { canonicalize } from "@hypit/hypit/protocol";
+import type { Need } from "@hypit/hypit/protocol";
+import { sealAlignedTranscriptEvidence } from "@hypit/hypit/speech-evidence";
import { interpretWhisperXTranscript } from "@hypit/whisperx";
import type { WhisperXAlignmentRequest } from "@hypit/whisperx";
-import { runCreationCli } from "../src/creation.js";
-import type { CreationEnvironment, CreationHost } from "../src/creation.js";
+import { runTranscribeCli } from "../src/cli.js";
+import type { TranscribeEnvironment } from "../src/cli.js";
/** 16 kHz mono PCM s16 WAV: the canonical evidence shape, so no ffmpeg runs in these tests. */
function wav(sampleFrames: number): Uint8Array {
@@ -31,7 +30,7 @@ function wav(sampleFrames: number): Uint8Array {
const page = { kind: "page" as const, url: "https://prices.example/models" };
/** A host whose Profile serves everything through one paid Endpoint, answering each Need in kind. */
-function host(seen: Need[]): CreationHost {
+function host(seen: Need[]): Awaited<ReturnType<TranscribeEnvironment["openHost"]>>["host"] {
return {
providers: async (requests) => requests.map((request) => ({
request: request.request,
@@ -60,7 +59,7 @@ function host(seen: Need[]): CreationHost {
};
}
-function environment(cwd: string, seen: Need[]): CreationEnvironment {
+function environment(cwd: string, seen: Need[]): TranscribeEnvironment {
return { cwd, openHost: async () => ({ profile: join(cwd, "hypit.runtime.json"), host: host(seen) }) };
}
@@ -75,7 +74,7 @@ test("transcribe writes every word in seconds from the Profile's alignment Endpo
try {
await writeFile(join(root, "speech.wav"), wav(32_000));
const out = capture();
- await runCreationCli(["transcribe", "speech.wav", "--to", "speech.json", "--language", "en"], out.io, environment(root, seen));
+ await runTranscribeCli(["transcribe", "speech.wav", "--to", "speech.json", "--language", "en"], out.io, environment(root, seen));
assert.match(out.text(), /paid\.default \(@hypit\/provider-example\) · https:\/\/prices\.example\/models/u);
assert.match(out.text(), /2 words in 1 passage over 2s/u);
assert.equal(out.text().match(/Aligning words/gu)?.length, 1);
@@ -92,52 +91,12 @@ test("transcribe writes every word in seconds from the Profile's alignment Endpo
}
});
-test("measure prints the seconds a line takes so the author can write the literal, without any Profile", async () => {
- const root = await mkdtemp(join(tmpdir(), "hypit-measure-"));
- try {
- const noHost: CreationEnvironment = { cwd: root, openHost: async () => { throw new Error("measure must not open a host"); } };
- const out = capture();
- await runCreationCli([
- "measure", "--text", "Video editing begins with meaning, not a pile of clips on a timeline.",
- "--language", "en", "--pace", "normal", "--rounding", "round", "--json",
- ], out.io, noHost);
- const view = JSON.parse(out.text()) as { readonly seconds: number; readonly units: number; readonly language: string; readonly rate: number };
- assert.equal(view.units, 20);
- assert.equal(view.language, "en");
- assert.equal(view.seconds, 4);
- assert.equal(view.rate, 4.6);
-
- const human = capture();
- await runCreationCli(["measure", "--text", "hello world"], human.io, noHost);
- assert.match(human.text(), /^\d+(\.\d+)?s\n/u);
- assert.match(human.text(), /Choose the request duration/u);
- assert.match(human.text(), /4\.6 units\/s \(normal\)/u);
-
- const chinese = capture();
- await runCreationCli(["measure", "--text", "这段中文有节奏", "--language", "zh", "--rate", "6", "--padding", "0.5"], chinese.io, noHost);
- assert.match(chinese.text(), /^1\.667s/u);
- assert.match(chinese.text(), /7 pronunciation units · zh · 6 units\/s/u);
- assert.match(chinese.text(), /padding 0\.5s/u);
- await assert.rejects(runCreationCli(["measure", "--text", "Hello", "--pace", "fast", "--rate", "6"], capture().io, noHost), /either --pace or --rate/u);
-
- for (const [text, seconds] of [["Hello.", 2 / 4.6], [Array.from({ length: 460 }, () => "day").join(" "), 100]] as const) {
- const measured = capture();
- await runCreationCli(["measure", "--text", text, "--language", "en", "--rounding", "none", "--json"], measured.io, noHost);
- assert.ok(Math.abs(JSON.parse(measured.text()).seconds - seconds) < 1e-9);
- }
-
- await assert.rejects(runCreationCli(["measure"], capture().io, noHost), /--text|--segment/u);
- } finally {
- await rm(root, { recursive: true, force: true });
- }
-});
-
test("a Profile that does not serve the capability stops before anything is spent", async () => {
const root = await mkdtemp(join(tmpdir(), "hypit-creation-unserved-"));
try {
await writeFile(join(root, "speech.wav"), wav(16_000));
let invoked = false;
- const unserved: CreationEnvironment = {
+ const unserved: TranscribeEnvironment = {
cwd: root,
openHost: async () => ({ profile: join(root, "hypit.runtime.json"), host: {
providers: async (requests) => requests.map((request) => ({
@@ -149,7 +108,7 @@ test("a Profile that does not serve the capability stops before anything is spen
} }),
};
await assert.rejects(
- runCreationCli(["transcribe", "speech.wav", "--to", "speech.json", "--language", "en"], capture().io, unserved),
+ runTranscribeCli(["transcribe", "speech.wav", "--to", "speech.json", "--language", "en"], capture().io, unserved),
/No Endpoint in .*hypit\.runtime\.json serves @hypit\/whisperx@1#whisperx-alignment; configure an Endpoint/u,
);
assert.equal(invoked, false);
@@ -159,8 +118,8 @@ test("a Profile that does not serve the capability stops before anything is spen
});
test("transcribe requires a spoken language before opening a host", async () => {
- const noHost: CreationEnvironment = { cwd: "/tmp", openHost: async () => { throw new Error("host must not open"); } };
- await assert.rejects(runCreationCli(["transcribe", "speech.wav", "--to", "speech.json"], capture().io, noHost),
+ const noHost: TranscribeEnvironment = { cwd: "/tmp", openHost: async () => { throw new Error("host must not open"); } };
+ await assert.rejects(runTranscribeCli(["transcribe", "speech.wav", "--to", "speech.json"], capture().io, noHost),
/transcribe --language must be an explicit/u);
});
@@ -169,7 +128,7 @@ test("transcribe passes Korean to the selected endpoint", async () => {
try {
await writeFile(join(root, "speech.wav"), wav(32_000));
const seen: Need[] = [];
- await runCreationCli(["transcribe", "speech.wav", "--language", "ko", "--to", "speech.json"], capture().io, {
+ await runTranscribeCli(["transcribe", "speech.wav", "--language", "ko", "--to", "speech.json"], capture().io, {
cwd: root, openHost: async () => ({ profile: join(root, "runtime.json"), host: host(seen) }),
});
assert.equal((seen[0]!.constraints as unknown as WhisperXAlignmentRequest).language, "ko");
@@ -182,7 +141,7 @@ test("Chinese transcription explicitly sends zh and retains individual character
try {
await writeFile(join(root, "speech.wav"), wav(32_000));
const selected = host([]);
- const env: CreationEnvironment = { cwd: root, openHost: async () => ({ profile: join(root, "runtime.json"), host: {
+ const env: TranscribeEnvironment = { cwd: root, openHost: async () => ({ profile: join(root, "runtime.json"), host: {
...selected,
invoke: async (need) => {
const request = need.constraints as unknown as WhisperXAlignmentRequest;
@@ -195,7 +154,7 @@ test("Chinese transcription explicitly sends zh and retains individual character
}, request.sampleFrames) }) } };
},
} }) };
- await runCreationCli(["transcribe", "speech.wav", "--language", "zh", "--to", "speech.json"], capture().io, env);
+ await runTranscribeCli(["transcribe", "speech.wav", "--language", "zh", "--to", "speech.json"], capture().io, env);
const result = JSON.parse(await readFile(join(root, "speech.json"), "utf8"));
assert.equal(result.language, "zh");
assert.deepEqual(result.passages[0].words, [
@@ -215,7 +174,7 @@ test("transcription explains ambiguous selection and preserves unsupported reque
rejections: [{ endpoint: "hosted.words", message: "This deployment does not support zh alignment" }] },
]) {
let invoked = false;
- const env: CreationEnvironment = { cwd: root, openHost: async () => ({
+ const env: TranscribeEnvironment = { cwd: root, openHost: async () => ({
profile: join(root, "runtime.json"), host: {
providers: async (requests) => requests.map((request) => ({
request: request.request, capability: request.capability, ...selection,
@@ -223,7 +182,7 @@ test("transcription explains ambiguous selection and preserves unsupported reque
invoke: async () => { invoked = true; throw new Error("must not invoke rejected selection"); },
},
}) };
- await assert.rejects(runCreationCli([
+ await assert.rejects(runTranscribeCli([
"transcribe", "speech.wav", "--to", "speech.json", "--language", "zh",
], capture().io, env), (error: Error) => {
if (selection.status === "ambiguous") {
diff --git a/packages/yt-dlp/README.md b/packages/yt-dlp/README.md
index 42f2c118..eed77670 100644
--- a/packages/yt-dlp/README.md
+++ b/packages/yt-dlp/README.md
@@ -1,10 +1,10 @@
# Fetching video with yt-dlp
-`@hypit/yt-dlp` owns video download for the Hypit Distribution. Video CLI exposes it as:
+`@hypit/yt-dlp` owns video download and its CLI contribution for the Hypit Distribution:
```bash
-hypit media prepare-fetch
-hypit media fetch "https://example.com/watch?v=VIDEO_ID" --to references/source.mp4
+hypit download prepare
+hypit download "https://example.com/watch?v=VIDEO_ID" --to references/source.mp4
```
The CLI creates destination directories, refuses existing output paths and probes the completed
@@ -18,11 +18,11 @@ Runtime Profile and creates no Build.
- `downloadVideo(url, target)` downloads one video to the given path. Its caller owns destination
preparation and overwrite policy. The target extension must be `.mp4`, `.mkv`, `.webm` or `.mov`.
-The downloader locates its declared `@hypit/yt-dlp-service-runtime` package through the active
-Distribution/package resolver. `prepareVideoDownload()` (`media prepare-fetch`) explicitly runs
+The downloader reads the locked `runtime/pyproject.toml` and `runtime/uv.lock` shipped by this same
+package. `prepareVideoDownload()` (`download prepare`) explicitly runs
`uv sync --frozen` into `<hostState>/programs/yt-dlp/<version>/.venv`. `downloadVideo()` only invokes
-that prepared executable and refuses a missing environment. Ship `pyproject.toml` and `uv.lock`;
-the caller's location and a `services/` ancestor are irrelevant. `uv` is needed for preparation;
+that prepared executable and refuses a missing environment. The caller's location and a repository
+`services/` ancestor are irrelevant. `uv` is needed for preparation;
`ffmpeg` must be on PATH for fetching, and the CLI uses `ffprobe` to report the saved media.
The default upstream extras include the EJS solver in that locked environment. Fetch explicitly
selects the calling Node executable, ignores user yt-dlp configuration/plugins, and disables updates
@@ -33,6 +33,8 @@ Available source streams determine the result. It stages the download in the OS
then moves the completed file to the target, copying on a cross-volume `EXDEV` error. Temporary
files are removed when the operation ends. Download errors retain the tool's diagnostic output.
-The package supplies download behavior; the CLI owns command arguments and reporting. Production
-use is described in the Hypit Skill's **Downloading a video from a link** page. The installed
-`services/yt-dlp/README.md` covers direct invocation when a source needs additional yt-dlp options.
+The package supplies download behavior, locked material, command arguments and reporting. It uses
+`media-local` only to inspect the finished ordinary file; local media no longer owns network acquisition.
+Production use is described in the Hypit Skill's **Downloading a video
+from a link** page. [`runtime/README.md`](runtime/README.md) covers direct invocation when a source
+needs additional yt-dlp options.
diff --git a/packages/yt-dlp/package.json b/packages/yt-dlp/package.json
index df52c903..6683341f 100644
--- a/packages/yt-dlp/package.json
+++ b/packages/yt-dlp/package.json
@@ -1,15 +1,25 @@
{
"name": "@hypit/yt-dlp",
- "version": "0.0.0-dev",
+ "version": "0.1.0",
"license": "SEE LICENSE IN LICENSE",
"private": true,
"type": "module",
"exports": {
- ".": "./src/index.ts"
+ ".": "./src/index.ts",
+ "./cli": "./src/cli.ts"
+ },
+ "files": [
+ "dist",
+ "runtime",
+ "README.md"
+ ],
+ "peerDependencies": {
+ "@hypit/hypit": "workspace:^"
},
"dependencies": {
- "@hypit/package-loader-node": "workspace:*",
- "@hypit/yt-dlp-service-runtime": "workspace:*",
- "@hypit/runtime-host-node": "workspace:*"
+ "@hypit/media-local": "workspace:^"
+ },
+ "devDependencies": {
+ "@hypit/hypit": "workspace:*"
}
}
diff --git a/services/yt-dlp/README.md b/packages/yt-dlp/runtime/README.md
similarity index 66%
rename from services/yt-dlp/README.md
rename to packages/yt-dlp/runtime/README.md
index 752da236..9e3b30f3 100644
--- a/services/yt-dlp/README.md
+++ b/packages/yt-dlp/runtime/README.md
@@ -1,16 +1,18 @@
# Pinned yt-dlp
This project owns the locked downloader and its EJS solver dependencies. Prepare it explicitly with
-`hypit media prepare-fetch`; `hypit media fetch` only uses the resulting executable and never runs uv.
+`hypit download prepare`; `hypit download` only uses the resulting executable and never runs uv.
The preparation command reports the executable path under the machine Host state. Use that exact
path for `--version`, `--help` or deliberately chosen site-specific options. On Windows it is an
`.exe` inside the virtual environment's `Scripts` directory.
-For a contributor-managed environment, run `uv sync --project services/yt-dlp --frozen` explicitly,
+For a contributor-managed environment, run `uv sync --project packages/yt-dlp/runtime --frozen` explicitly,
then invoke `.venv/bin/yt-dlp` (Windows: `.venv\Scripts\yt-dlp.exe`) from that project.
-Direct invocation accepts upstream options and config; the Hypit fetch wrapper instead ignores
+Direct invocation accepts upstream options and config; the Hypit download command instead ignores
user config/plugins, disables updates and remote components, and uses its calling Node executable
-for JavaScript challenges. The locked extras supply the solver before fetching begins.
+for JavaScript challenges. The locked extras supply both that solver and yt-dlp's `curl-cffi`
+browser-impersonation transport before fetching begins. This keeps the transport in the same pinned
+Python environment as yt-dlp; it does not add site rules or TLS policy to Hypit.
`ffmpeg` on PATH merges separate video and audio streams; the CLI also requires `ffprobe` for the
saved-file report. These tools are supplied by the operator's package manager, never installed by
diff --git a/services/yt-dlp/pyproject.toml b/packages/yt-dlp/runtime/pyproject.toml
similarity index 89%
rename from services/yt-dlp/pyproject.toml
rename to packages/yt-dlp/runtime/pyproject.toml
index a3f5c92c..2ea3ee6d 100644
--- a/services/yt-dlp/pyproject.toml
+++ b/packages/yt-dlp/runtime/pyproject.toml
@@ -6,7 +6,7 @@ readme = "README.md"
requires-python = ">=3.10,<3.14"
license = { text = "Hypit Open Source License (Apache-2.0 with additional conditions); see LICENSE at the repository root" }
dependencies = [
- "yt-dlp[default]==2026.8.19",
+ "yt-dlp[default,curl-cffi]==2026.8.19",
]
[tool.uv]
diff --git a/services/yt-dlp/uv.lock b/packages/yt-dlp/runtime/uv.lock
similarity index 95%
rename from services/yt-dlp/uv.lock
rename to packages/yt-dlp/runtime/uv.lock
index f06a92a6..33cbf139 100644
--- a/services/yt-dlp/uv.lock
+++ b/packages/yt-dlp/runtime/uv.lock
@@ -240,16 +240,40 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/cc/61/d01fc49b8dea277640b55a9e15960dbca9fdc8c9fde18e572d39c59f4019/charset_normalizer-3.5.1-py3-none-any.whl", hash = "sha256:6df0ec430f9a831772c23ca5a224cba36517a58a84bb32c32bb59a9fa67c47f6", size = 68658, upload-time = "2026-08-15T08:20:43.306Z" },
]
+[[package]]
+name = "curl-cffi"
+version = "0.16.3"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "certifi" },
+ { name = "cffi" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/82/e1/730125c43e3e331d98e17af3cb310ba526b3f1101b7635ca23d976ebfcf5/curl_cffi-0.16.3.tar.gz", hash = "sha256:d15d0c2a35f2d75bec430c28946c2a833f421c85773bdb0795182cc5c515665b", size = 239020, upload-time = "2026-09-02T11:58:23.266Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/79/7a/ec08ef0665c4ef4ea76b47042eb1c043e4afb374d8b9218e00272c9e73a2/curl_cffi-0.16.3-cp310-abi3-macosx_10_9_x86_64.whl", hash = "sha256:0f1f6878863fba393801e4d59b2f2766d1983b5c9d9dfa11d4becfd6a74cc937", size = 3025646, upload-time = "2026-09-02T11:57:39.326Z" },
+ { url = "https://files.pythonhosted.org/packages/4c/86/e21b8ed384db26401a4438f20f01c7bcd9c3a6f8ceede458344e2d62775c/curl_cffi-0.16.3-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:f3b63da797912bc82911e34dfe449725514e4281527fb516931fc457087cfb44", size = 2784023, upload-time = "2026-09-02T11:57:40.986Z" },
+ { url = "https://files.pythonhosted.org/packages/97/2d/25b106e64178829be1ce171b6cd45ba354ab7a2a5169001866b38d4c440f/curl_cffi-0.16.3-cp310-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:d5a4103f2baa1fcf619ec3101b419827d367044ba106b206228137cc71a5a9c5", size = 12834219, upload-time = "2026-09-02T11:57:42.711Z" },
+ { url = "https://files.pythonhosted.org/packages/e7/dd/db27a521777d0cf00f9a1554453ae730539dd134bca108d8df256a85c91e/curl_cffi-0.16.3-cp310-abi3-manylinux2014_i686.manylinux_2_17_i686.whl", hash = "sha256:f2795f0ef2e8cc0e6d702e52367af6600f5bcf10e44d683e256254adc7e3589f", size = 12655304, upload-time = "2026-09-02T11:57:45.334Z" },
+ { url = "https://files.pythonhosted.org/packages/72/01/2bbf141baa0fc3921d31a90de5465b7a94188845a8fe84dee86bf7bd90f1/curl_cffi-0.16.3-cp310-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:a875a661e2f9a949be29454880bbb9553307a487c4c08819738298cf5c1622e2", size = 13484311, upload-time = "2026-09-02T11:57:47.58Z" },
+ { url = "https://files.pythonhosted.org/packages/bb/d4/745ca299a2a223ee18574ec7cff75de620a92ce69b3cb09490db8fba614b/curl_cffi-0.16.3-cp310-abi3-manylinux_2_28_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:0851e710608122a2716bdee35788bbd7e9d4a0fd42899b2bca9181277095af8e", size = 12840616, upload-time = "2026-09-02T11:57:50.016Z" },
+ { url = "https://files.pythonhosted.org/packages/5e/bf/98d72d7a081cc155a71ab66bde6a18640d4ac5d4f6766f729a92cb4257c0/curl_cffi-0.16.3-cp310-abi3-manylinux_2_34_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:1d7e553442cefec100dfd1fca4ae7035ab6c094457244bf60a38670b8ac8185d", size = 12612602, upload-time = "2026-09-02T11:57:52.584Z" },
+ { url = "https://files.pythonhosted.org/packages/36/cf/2fdaff71fd6f39c5994495af8378e6e26bca8e447d94d2f75a76337908c8/curl_cffi-0.16.3-cp310-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:60621b3f561346046dd62be33abfb50c8b88a8007699d6b11d39ad4755312c4a", size = 12588697, upload-time = "2026-09-02T11:57:55.138Z" },
+ { url = "https://files.pythonhosted.org/packages/74/55/68c399019bc24ea6ac783c98139a2555f88589631f3d127fe6b9073f019b/curl_cffi-0.16.3-cp310-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:20a7b1b473371cfaf2118958034977e457c6fa279fbd11543c9e0ab58be9eedd", size = 13253555, upload-time = "2026-09-02T11:57:57.524Z" },
+ { url = "https://files.pythonhosted.org/packages/9b/72/1732a24ef4a2aeba994b80ec163debe8deda403c07e4abbc0443bca078b8/curl_cffi-0.16.3-cp310-abi3-win_amd64.whl", hash = "sha256:fe87b66e324ed7318166698e02169f3208dbda32b872a27d2bc61a9c19b335eb", size = 1978602, upload-time = "2026-09-02T11:58:00.033Z" },
+ { url = "https://files.pythonhosted.org/packages/45/bb/67bec3132aeabac99dfe2f299a9b43dcb5de23ad96219ee98516d177fc9c/curl_cffi-0.16.3-cp310-abi3-win_arm64.whl", hash = "sha256:5a2ba880019f9e5a9e8f38ae22de6e4ea4c8d34a51ae4f1a2fce962c7b632006", size = 1713140, upload-time = "2026-09-02T11:58:01.558Z" },
+ { url = "https://files.pythonhosted.org/packages/49/e3/b88f9b1a60a1e29b42e9371c1b3f4fdd83bf8177fcf863df67438da12693/curl_cffi-0.16.3-cp313-cp313-android_24_arm64_v8a.whl", hash = "sha256:01c31369b1c8063c7e459152c508c90de7a4218aa66ee3a1f575ae37ce44bc5a", size = 8607348, upload-time = "2026-09-02T11:58:03.095Z" },
+]
+
[[package]]
name = "hypit-yt-dlp"
version = "0.1.0"
source = { virtual = "." }
dependencies = [
- { name = "yt-dlp", extra = ["default"] },
+ { name = "yt-dlp", extra = ["curl-cffi", "default"] },
]
[package.metadata]
-requires-dist = [{ name = "yt-dlp", extras = ["default"], specifier = "==2026.8.19" }]
+requires-dist = [{ name = "yt-dlp", extras = ["default", "curl-cffi"], specifier = "==2026.8.19" }]
[[package]]
name = "idna"
@@ -328,6 +352,15 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/a0/f4/c67b0b3f1b9245e8d266f0f112c500d50e5b4e83cb6f3b71b6528104182a/requests-2.34.2-py3-none-any.whl", hash = "sha256:2a0d60c172f83ac6ab31e4554906c0f3b3588d37b5cb939b1c061f4907e278e0", size = 73075, upload-time = "2026-05-14T19:25:26.443Z" },
]
+[[package]]
+name = "typing-extensions"
+version = "4.16.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/f6/cc/6253133b5bb138fc3306cebfbda2c520f545d36b5be2c7255cc528bb45d6/typing_extensions-4.16.0.tar.gz", hash = "sha256:dc983d19a509c94dba722ee6abd33940f7c05a89e243c47e907eb4db6f1a43e5", size = 113555, upload-time = "2026-07-02T08:40:05.92Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/49/d3/b8441a820a491ddfc024b0b0cf0393375b75ea13866d9c66727e54c2fc80/typing_extensions-4.16.0-py3-none-any.whl", hash = "sha256:481caa481374e813c1b176ada14e97f1f67a4539ce9cfeb3f350d78d6370c2e8", size = 45571, upload-time = "2026-07-02T08:40:04.659Z" },
+]
+
[[package]]
name = "urllib3"
version = "2.8.0"
@@ -511,6 +544,10 @@ wheels = [
]
[package.optional-dependencies]
+curl-cffi = [
+ { name = "curl-cffi", marker = "implementation_name == 'cpython'" },
+ { name = "typing-extensions", marker = "python_full_version < '3.11'" },
+]
default = [
{ name = "brotli", marker = "implementation_name == 'cpython' and sys_platform != 'ios'" },
{ name = "brotlicffi", marker = "implementation_name != 'cpython'" },
diff --git a/packages/yt-dlp/src/cli.ts b/packages/yt-dlp/src/cli.ts
new file mode 100644
index 00000000..9c919c5a
--- /dev/null
+++ b/packages/yt-dlp/src/cli.ts
@@ -0,0 +1,85 @@
+import { mkdir, stat } from "node:fs/promises";
+import { dirname, resolve } from "node:path";
+
+import type { CliCommandModule, CliIo } from "@hypit/hypit/cli";
+import { probeMedia } from "@hypit/media-local/files";
+
+import { downloadVideo, isVideoUrl } from "./download.js";
+import { prepareVideoDownload } from "./environment.js";
+
+function assert(condition: unknown, message: string): asserts condition {
+ if (!condition) throw new Error(message);
+}
+
+type Parsed = {
+ readonly positionals: readonly string[];
+ readonly to?: string;
+ readonly json: boolean;
+};
+
+function parse(argv: readonly string[]): Parsed {
+ const positionals: string[] = [];
+ let to: string | undefined;
+ let json = false;
+ for (let index = 1; index < argv.length; index += 1) {
+ const item = argv[index]!;
+ if (item === "--json") { json = true; continue; }
+ if (["--debug", "--verbose", "--no-color"].includes(item)) continue;
+ if (item === "--color") { index += 1; continue; }
+ if (item === "--to") {
+ assert(to === undefined, "--to cannot be repeated");
+ const value = argv[++index];
+ assert(value !== undefined && !value.startsWith("--"), "--to requires a destination file");
+ to = value;
+ continue;
+ }
+ assert(!item.startsWith("--"), `unknown download option ${item}`);
+ positionals.push(item);
+ }
+ return { positionals, ...(to === undefined ? {} : { to }), json };
+}
+
+export function writeDownloadHelp(io: CliIo): void {
+ io.write("hypit download\nAcquire one network video through the pinned yt-dlp environment.\n\n"
+ + " hypit download <http-or-https-url> --to <video.mp4>\n"
+ + " hypit download prepare\n\n"
+ + "Preparation installs the package's locked environment explicitly. Download never prepares, updates,\n"
+ + "overwrites an existing destination or creates Runtime/Build state. Add --json for the machine view.\n");
+}
+
+export async function runDownloadCli(argv: readonly string[], io: CliIo, cwd = process.cwd()): Promise<void> {
+ if (argv[1] === undefined || argv.includes("--help")) { writeDownloadHelp(io); return; }
+ const parsed = parse(argv);
+ if (parsed.positionals[0] === "prepare") {
+ assert(parsed.positionals.length === 1 && parsed.to === undefined, "download prepare takes no URL or --to");
+ io.writeProgress?.("Preparing the selected yt-dlp environment…\n");
+ const executable = prepareVideoDownload();
+ io.write(parsed.json ? `${JSON.stringify({ executable })}\n` : `yt-dlp ready: ${executable}\n`);
+ return;
+ }
+
+ const [url] = parsed.positionals;
+ assert(url !== undefined && isVideoUrl(url), "download needs one http or https URL");
+ assert(parsed.positionals.length === 1, "download takes exactly one URL");
+ assert(parsed.to !== undefined, "download requires --to <video.mp4>");
+ const target = resolve(cwd, parsed.to);
+ assert(!(await stat(target).then(() => true, () => false)), `Destination ${target} already exists`);
+ await mkdir(dirname(target), { recursive: true });
+ await downloadVideo(url, target);
+ const info = await probeMedia(target);
+ assert(info.hasVideo, `${target}: downloaded media has no video stream`);
+ if (parsed.json) {
+ io.write(`${JSON.stringify({ path: target, url, ...info }, null, 2)}\n`);
+ return;
+ }
+ io.write(`${target}\n ${info.duration} s ${info.width}×${info.height} ${info.hasAudio ? "with audio" : "no audio"}\n`);
+}
+
+export const cliCommandModules = [{
+ format: "hypit.cli-command@1",
+ id: "@hypit/yt-dlp",
+ commands: ["download"],
+ writeRootHelp(io) { io.write("\nNetwork media\n download\n hypit download --help for preparation and destination options\n"); },
+ writeHelp(_argv, io) { writeDownloadHelp(io); },
+ async run(argv, io, context) { await runDownloadCli(argv, io, context.cwd); },
+}] as const satisfies readonly CliCommandModule[];
diff --git a/packages/yt-dlp/src/download.ts b/packages/yt-dlp/src/download.ts
index 52110428..8724c74a 100644
--- a/packages/yt-dlp/src/download.ts
+++ b/packages/yt-dlp/src/download.ts
@@ -5,7 +5,7 @@
* rather than in a folder. `yt-dlp` is what turns one into a file; everything after that reads the
* file and never learns where it came from.
*
- * The tool is a pinned Python dependency prepared explicitly by `hypit media prepare-fetch`, not a
+ * The tool is a pinned Python dependency prepared explicitly by `hypit download prepare`, not a
* binary the machine happens to carry. `yt-dlp` releases constantly because it is chasing sites that
* keep changing, so an unpinned copy makes the same link fetch differently on two machines. This is
* the same shape WhisperX and OpenCV already use for their Python programs.
diff --git a/packages/yt-dlp/src/environment.ts b/packages/yt-dlp/src/environment.ts
index 00dfa2f6..a23f2398 100644
--- a/packages/yt-dlp/src/environment.ts
+++ b/packages/yt-dlp/src/environment.ts
@@ -1,12 +1,17 @@
import { spawnSync } from "node:child_process";
import { readFileSync } from "node:fs";
-import { dirname, join } from "node:path";
-import { resolveNodePackageResource } from "@hypit/package-loader-node";
-import { hypitHostStateRoot, pythonEnvironmentCommand } from "@hypit/runtime-host-node";
+import { join, resolve } from "node:path";
+import { hypitHostStateRoot } from "@hypit/hypit/cli";
+
+function pythonEnvironmentCommand(environment: string, name: string): string {
+ return process.platform === "win32"
+ ? resolve(environment, "Scripts", `${name}.exe`)
+ : resolve(environment, "bin", name);
+}
/** One selected, locked environment. Fetching media never invokes its installer. */
export function videoDownloadEnvironment() {
- const project = dirname(resolveNodePackageResource("@hypit/yt-dlp-service-runtime", "pyproject.toml", { from: import.meta.url }));
+ const project = resolve(import.meta.dirname, "../runtime");
const version = /"yt-dlp(?:\[[^\]]+\])?==([^"]+)"/u.exec(readFileSync(join(project, "pyproject.toml"), "utf8"))?.[1];
if (version === undefined) throw new Error("yt-dlp runtime must declare its exact upstream version");
const environment = join(hypitHostStateRoot(), "programs", "yt-dlp", version, ".venv");
@@ -19,7 +24,7 @@ export function requireVideoDownload(): string {
// PyPI normalizes date-version leading zeroes; the executable retains them.
const release = (value: string) => value.trim().split(".").map((part) => part.replace(/^0+(?=\d)/u, "")).join(".");
if (result.status !== 0 || release(result.stdout ?? "") !== release(selected.version)) {
- throw new Error(`yt-dlp ${selected.version} is not ready at ${selected.executable}; run hypit media prepare-fetch. ${result.error?.message ?? result.stderr?.trim() ?? ""}`);
+ throw new Error(`yt-dlp ${selected.version} is not ready at ${selected.executable}; run hypit download prepare. ${result.error?.message ?? result.stderr?.trim() ?? ""}`);
}
return selected.executable;
}
diff --git a/packages/yt-dlp/test/cli.test.ts b/packages/yt-dlp/test/cli.test.ts
new file mode 100644
index 00000000..a0af7c4b
--- /dev/null
+++ b/packages/yt-dlp/test/cli.test.ts
@@ -0,0 +1,39 @@
+import assert from "node:assert/strict";
+import { mkdtemp, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import test from "node:test";
+
+import type { CliIo } from "@hypit/hypit/cli";
+
+import { cliCommandModules, runDownloadCli } from "../src/cli.js";
+
+function output(): { readonly io: CliIo; readonly text: () => string } {
+ let value = "";
+ return {
+ io: {
+ write: (chunk) => { value += chunk; },
+ setExitCode: () => {},
+ readSecret: async () => "",
+ terminal: { isTTY: false, color: false, unicode: false, columns: 100 },
+ },
+ text: () => value,
+ };
+}
+
+test("yt-dlp owns one download CLI root", async () => {
+ assert.deepEqual(cliCommandModules[0]!.commands, ["download"]);
+ const shown = output();
+ await runDownloadCli(["download", "--help"], shown.io);
+ assert.match(shown.text(), /hypit download <http-or-https-url>/u);
+ assert.match(shown.text(), /hypit download prepare/u);
+});
+
+test("download validates URL and overwrite policy before invoking yt-dlp", async (t) => {
+ const directory = await mkdtemp(join(tmpdir(), "hypit-download-cli-"));
+ t.after(() => rm(directory, { recursive: true, force: true }));
+ await assert.rejects(runDownloadCli(["download", "not-a-url", "--to", "clip.mp4"], output().io, directory), /http or https URL/u);
+ await assert.rejects(runDownloadCli(["download", "https://example.test/video", "--to", "clip.txt"], output().io, directory), /must end in/u);
+ await writeFile(join(directory, "clip.mp4"), "existing");
+ await assert.rejects(runDownloadCli(["download", "https://example.test/video", "--to", "clip.mp4"], output().io, directory), /already exists/u);
+});
diff --git a/packages/yt-dlp/test/download.test.ts b/packages/yt-dlp/test/download.test.ts
index b276c869..7d5c3db6 100644
--- a/packages/yt-dlp/test/download.test.ts
+++ b/packages/yt-dlp/test/download.test.ts
@@ -2,14 +2,12 @@ import assert from "node:assert/strict";
import { existsSync, writeFileSync } from "node:fs";
import { cp, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
-import { pathToFileURL } from "node:url";
+import { fileURLToPath, pathToFileURL } from "node:url";
import childProcess from "node:child_process";
import { syncBuiltinESMExports } from "node:module";
-import { dirname, join } from "node:path";
+import { join } from "node:path";
import test from "node:test";
-import { resolveNodePackageResource } from "@hypit/package-loader-node";
-
import { downloadVideo, isVideoUrl } from "../src/download.js";
test("only http and https links are fetched; Windows paths stay files", () => {
@@ -21,7 +19,7 @@ test("only http and https links are fetched; Windows paths stay files", () => {
assert.equal(isVideoUrl("/tmp/clip.mp4"), false);
});
-test("fetch with a missing environment reports preparation without installing or fetching", async (t) => {
+test("download with a missing environment reports preparation without installing anything", async (t) => {
let calls = 0;
t.mock.method(childProcess, "spawnSync", (command: string, args: string[]) => {
calls++;
@@ -31,36 +29,32 @@ test("fetch with a missing environment reports preparation without installing or
});
syncBuiltinESMExports();
t.after(() => { t.mock.restoreAll(); syncBuiltinESMExports(); });
- await assert.rejects(downloadVideo("https://example.invalid/video", join(tmpdir(), "never-fetched.mp4")), /media prepare-fetch/u);
+ await assert.rejects(downloadVideo("https://example.invalid/video", join(tmpdir(), "never-fetched.mp4")), /download prepare/u);
assert.equal(calls, 1);
});
-test("download resolves its declared service from an installed package outside the checkout", async (t) => {
+test("download resolves its locked runtime from an installed package outside the checkout", async (t) => {
const directory = await mkdtemp(join(tmpdir(), "hypit-installed-yt-dlp-"));
t.after(() => rm(directory, { recursive: true, force: true }));
const modules = join(directory, "node_modules", "@hypit");
const installed = join(modules, "yt-dlp");
- const service = join(modules, "yt-dlp-service-runtime");
- const loader = join(modules, "package-loader-node");
await mkdir(join(installed, "src"), { recursive: true });
- await mkdir(service, { recursive: true });
- await mkdir(loader, { recursive: true });
+ await mkdir(join(installed, "runtime"), { recursive: true });
await cp(new URL("../package.json", import.meta.url), join(installed, "package.json"));
await cp(new URL("../src/download.ts", import.meta.url), join(installed, "src", "download.ts"));
await cp(new URL("../src/environment.ts", import.meta.url), join(installed, "src", "environment.ts"));
- const host = join(modules, "runtime-host-node");
+ const host = join(modules, "hypit");
await mkdir(host, { recursive: true });
- await writeFile(join(host, "package.json"), JSON.stringify({ name: "@hypit/runtime-host-node", type: "module", exports: "./index.mjs" }));
- await writeFile(join(host, "index.mjs"), `export { hypitHostStateRoot, pythonEnvironmentCommand } from ${JSON.stringify(import.meta.resolve("@hypit/runtime-host-node"))};`);
- const sourceService = dirname(resolveNodePackageResource("@hypit/yt-dlp-service-runtime", "pyproject.toml", { from: import.meta.url }));
- for (const name of ["package.json", "pyproject.toml", "uv.lock"]) await cp(join(sourceService, name), join(service, name));
- // Forward only the real locator implementation; no workspace links or services/ ancestor exists.
- await writeFile(join(loader, "package.json"), JSON.stringify({ name: "@hypit/package-loader-node", type: "module", exports: "./index.mjs" }));
- await writeFile(join(loader, "index.mjs"), `export { resolveNodePackageResource } from ${JSON.stringify(import.meta.resolve("@hypit/package-loader-node"))};`);
+ await writeFile(join(host, "package.json"), JSON.stringify({
+ name: "@hypit/hypit", type: "module", exports: { "./cli": "./cli.mjs" },
+ }));
+ await writeFile(join(host, "cli.mjs"), `export { hypitHostStateRoot } from ${JSON.stringify(import.meta.resolve("@hypit/hypit/cli"))};`);
+ const sourceRuntime = fileURLToPath(new URL("../runtime", import.meta.url));
+ for (const name of ["pyproject.toml", "uv.lock"]) await cp(join(sourceRuntime, name), join(installed, "runtime", name));
let calls = 0;
t.mock.method(childProcess, "spawnSync", (command: string, args: string[]) => {
calls++;
- assert.notEqual(command, "uv", "fetch must not run the environment installer");
+ assert.notEqual(command, "uv", "download must not run the environment installer");
if (args.includes("--version")) return { status: 0, stderr: "", stdout: "2026.08.19\n" };
return { status: 0, stderr: "", stdout: "" };
});
@@ -89,12 +83,18 @@ test("download resolves its declared service from an installed package outside t
assert.equal(calls, 3);
});
-test("the pinned yt-dlp project is a Distribution package asset", () => {
- const project = dirname(resolveNodePackageResource(
- "@hypit/yt-dlp-service-runtime",
- "pyproject.toml",
- { from: import.meta.url },
- ));
+test("the pinned yt-dlp project belongs to its behavior package", () => {
+ const project = fileURLToPath(new URL("../runtime", import.meta.url));
assert.ok(existsSync(join(project, "pyproject.toml")));
assert.ok(existsSync(join(project, "uv.lock")));
});
+
+test("the pinned yt-dlp environment includes its browser-impersonation transport", async () => {
+ const project = fileURLToPath(new URL("../runtime", import.meta.url));
+ const [declaration, lock] = await Promise.all([
+ readFile(join(project, "pyproject.toml"), "utf8"),
+ readFile(join(project, "uv.lock"), "utf8"),
+ ]);
+ assert.match(declaration, /yt-dlp\[default,curl-cffi\]==2026\.8\.19/u);
+ assert.match(lock, /name = "curl-cffi"/u);
+});
diff --git a/services/yt-dlp/package.json b/services/yt-dlp/package.json
deleted file mode 100644
index 2357bdb9..00000000
--- a/services/yt-dlp/package.json
+++ /dev/null
@@ -1,14 +0,0 @@
-{
- "name": "@hypit/yt-dlp-service-runtime",
- "version": "0.1.0",
- "license": "SEE LICENSE IN LICENSE",
- "type": "module",
- "exports": {
- "./pyproject.toml": "./pyproject.toml"
- },
- "files": [
- "pyproject.toml",
- "uv.lock",
- "README.md"
- ]
-}