@openbone/cli 0.0.0-stage → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 UX Century and OpenBone contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,207 @@
1
- # Temporary Holding Version
1
+ # @openbone/cli
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The OpenBone command line: validate, inspect, render, simulate, export and edit `.obone` files, and start the MCP server.
4
+
5
+ [![npm](https://img.shields.io/npm/v/@openbone/cli)](https://www.npmjs.com/package/@openbone/cli)
6
+ [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/UXCentury/open-bone/blob/main/LICENSE)
7
+
8
+ [OpenBone](https://github.com/UXCentury/open-bone) is open-source 2D skeletal animation: Spine-style rigging, Rive-style
9
+ interactive state machines and native runtimes for many engines. This package installs the `openbone` command. It runs
10
+ the same code as the editor's Export dialog and the MCP server, so all three produce the same files. Use it in build
11
+ scripts and CI, or to check an animation without opening the editor.
12
+
13
+ It is also published unscoped as [`openbone`](https://www.npmjs.com/package/openbone), so `npx openbone` works.
14
+
15
+ ## Install
16
+
17
+ Needs Node.js 20 or newer.
18
+
19
+ ```bash
20
+ npm install -g @openbone/cli # then: openbone <command>
21
+ npm install -D @openbone/cli # per project, for npm scripts
22
+ npx openbone <command> # no install
23
+ ```
24
+
25
+ ## Quick start
26
+
27
+ ```bash
28
+ openbone validate hero.obone
29
+ openbone render hero.obone --animation walk --time 0.5 --out frame.png
30
+ openbone export "art/*.obone" --format gif --animation walk --out build/
31
+ ```
32
+
33
+ Run `openbone --help` for the full usage text, or `openbone <command> --help` for one command.
34
+
35
+ ## Commands
36
+
37
+ | Command | What it does |
38
+ |---|---|
39
+ | `validate <file>` | Check for broken references and other problems. Prints each issue, or `OK`. Exits with 1 if there is an error. |
40
+ | `summary <file>` | Print an outline: artboard, bones, slots, images, events, animations, state machines (inputs, states, transitions, listeners), audio and scripts. |
41
+ | `render <file>` | Render one frame to a PNG. |
42
+ | `gif <file>` | Render an animation, or a state machine run, to an animated GIF. |
43
+ | `simulate <file>` | Run a state machine headlessly and print a log of state changes, inputs, events and audio commands. |
44
+ | `export <files or globs>...` | Export one or more files in any [export format](#export-formats). |
45
+ | `apply <file> <op> '<json>'` | Apply one edit op to a file and save it in place. Prints the op's result. |
46
+ | `ops` | List every edit op with its group and description. |
47
+ | `mcp` | Start the MCP server (see [`@openbone/mcp`](https://www.npmjs.com/package/@openbone/mcp)). |
48
+
49
+ ### validate, summary
50
+
51
+ ```bash
52
+ openbone validate hero.obone
53
+ openbone summary hero.obone
54
+ ```
55
+
56
+ ### render
57
+
58
+ ```bash
59
+ openbone render hero.obone --out setup.png # setup pose
60
+ openbone render hero.obone --animation walk --time 0.5 --out frame.png
61
+ openbone render hero.obone --bones --scale 0.5 --out rig.png # draw bones on top
62
+ openbone render hero.obone --state-machine main --out sm.png # state machine's first frame
63
+ ```
64
+
65
+ Options: `--animation`, `--time` (seconds), `--scale` (default 1), `--bones`, `--bounding-boxes` (outline click and
66
+ hit areas), `--state-machine`, `--out` (default `frame.png`).
67
+
68
+ ### gif
69
+
70
+ ```bash
71
+ openbone gif hero.obone --animation walk --duration 1 --fps 15 --out walk.gif
72
+ openbone gif button.obone --state-machine ui \
73
+ --steps '[{"setInputs":{"hover":true},"advance":1},{"fire":["press"],"advance":1}]' --out button.gif
74
+ ```
75
+
76
+ Options: `--animation` or `--state-machine`, `--steps`, `--duration` (default 2 s), `--fps` (default 20), `--scale`
77
+ (default 0.5), `--out` (default `out.gif`).
78
+
79
+ ### simulate
80
+
81
+ ```bash
82
+ openbone simulate walker.obone --state-machine character \
83
+ --steps '[{"setInputs":{"walk":true,"speed":1},"advance":1},{"fire":["jump"],"advance":1}]'
84
+ ```
85
+
86
+ `--steps` is a JSON array. Each step can set inputs (`setInputs`), fire triggers (`fire`), send a pointer event
87
+ (`pointer: {"type":"down","x":200,"y":100}`, in artboard pixels, y down) and then advance time (`advance`, in seconds).
88
+ Without `--state-machine`, the first state machine runs. The output ends with the final states and input values:
89
+
90
+ ```text
91
+ t=0.000 [Layer 1] ∅ → locomotion
92
+ t=0.000 input walk = true
93
+ t=0.017 event footstep (from walk) int=0 float=0 "front"
94
+ t=1.000 [Layer 1] locomotion → jump
95
+ ...
96
+ final states: {"Layer 1":"jump"}; inputs: {"walk":true,"speed":1,"jump":false}
97
+ ```
98
+
99
+ ### export
100
+
101
+ ```bash
102
+ openbone export hero.obone --format obonb --out build/
103
+ openbone export "art/*.obone" --format gif --animation idle --out previews/
104
+ openbone export button.obone --format web --single-file --state-machine ui --out site/
105
+ openbone export hero.obone --format spritesheet --engine godot --animations walk,idle --scale 0.5 --out sheets/
106
+ openbone export hero.obone --format atlas --binary --atlas-scale auto --max-size 1024 --out build/
107
+ openbone export hero.obone --format atlas --scales 1,0.5 --suffixes ,@0.5x --filter-min mipmap --out build/
108
+ ```
109
+
110
+ Quote globs so the shell does not expand them. Each output is named after its source file and written to `--out`
111
+ (default: the current folder). ZIPs carry the format in their name (`hero-atlas.zip`, `hero-web.zip`,
112
+ `hero-png.zip`, `hero-spritesheet-godot.zip`), so several formats can share one folder. If some files fail, the others are still written, and the
113
+ command exits with 1.
114
+
115
+ ### apply, ops
116
+
117
+ ```bash
118
+ openbone ops # every op, e.g. addBone [rig] ...
119
+ openbone apply hero.obone addBone '{"name":"tail","parent":"root"}'
120
+ ```
121
+
122
+ `apply` takes op names in camel case (`addBone`), as `ops` lists them. The MCP server exposes the same ops as tools in
123
+ snake case (`add_bone`).
124
+
125
+ ### mcp
126
+
127
+ ```bash
128
+ openbone mcp # stdio, plus the editor bridge on ws://127.0.0.1:7717
129
+ openbone mcp --project hero.obone --no-bridge
130
+ openbone mcp --http 7718 # Streamable HTTP at http://127.0.0.1:7718/mcp
131
+ ```
132
+
133
+ The options are those of [`@openbone/mcp`](https://github.com/UXCentury/open-bone/blob/main/packages/mcp/README.md).
134
+
135
+ ## Export formats
136
+
137
+ | Format | Output |
138
+ |---|---|
139
+ | `obone` | The whole project as an `.obone` file (`--embed` puts every image and sound inside it, so it opens on its own anywhere) |
140
+ | `json` | Runtime data as JSON: the animations and state machines marked for export (`--pack` embeds a texture atlas) |
141
+ | `obonb` | The same runtime data in the binary format (`--pack` embeds a texture atlas) |
142
+ | `atlas` | ZIP: runtime data (JSON, or `.obonb` with `--binary`) plus the atlas pages as PNG (or JPEG) files; with `--scales`, one data file and page set per scale (`hero.json` + `hero.png`, `hero@0.5x.json` + `hero@0.5x.png`) |
143
+ | `png`, `jpeg` | One frame (`--time`), or every frame in a ZIP with `--sequence` |
144
+ | `apng` | Animated PNG (`<name>.apng.png`) |
145
+ | `gif` | Animated GIF |
146
+ | `psd` | Photoshop file, one layer per frame |
147
+ | `avi`, `mov` | Motion-JPEG video, with the sound the animation or state machine run plays (`--no-audio` leaves it out) |
148
+ | `mp4`, `webm` | H.264 + AAC MP4 / VP9 + Opus WebM with sound, encoded by `ffmpeg` from the PATH (or `OPENBONE_FFMPEG`); `--quality 0.85`. ffmpeg also decodes MP3/OGG/FLAC sounds for every video format; WAV decodes without it |
149
+ | `spritesheet` | ZIP of sprite sheets for `--engine unity`, `godot`, `flutter` or `generic` (the default), one clip per animation |
150
+ | `web` | ZIP with the `<openbone-player>` web player, the animation and a demo page, or one self-contained HTML file with `--single-file` |
151
+
152
+ Frames come from `--animation` (default: the first animation) or from a state machine run (`--state-machine` and
153
+ `--steps`).
154
+
155
+ | Option | Applies to |
156
+ |---|---|
157
+ | `--animation <name>`, `--state-machine <name>`, `--steps '<json>'` | frame formats (`png`, `jpeg`, `apng`, `gif`, `psd`, `avi`, `mov`) |
158
+ | `--animation <name>`, `--state-machine <name>` | `web`: what the demo page plays (default: the first state machine) |
159
+ | `--animations a,b` | `json`, `obonb`, `atlas` (animations to keep), `spritesheet` (clips; default: all marked for export) |
160
+ | `--skin <name>` | frame formats, `spritesheet` |
161
+ | `--scale`, `--fps`, `--duration`, `--time` | frame formats, `spritesheet` |
162
+ | `--transparent` | `png`, `apng`, `gif`, `psd`, `spritesheet`, `web` (`jpeg`, `avi` and `mov` are always opaque) |
163
+ | `--sequence` | `png`, `jpeg` |
164
+ | `--engine unity\|godot\|flutter\|generic` | `spritesheet` |
165
+ | `--single-file`, `--no-minify` | `web` |
166
+ | `--binary` | `atlas` |
167
+ | `--pack` | `json`, `obonb`, `web` |
168
+ | `--embed` | `obone`, `json`, `obonb` |
169
+ | `--padding 2`, `--max-size 2048`, `--no-pot`, `--rotate`, `--atlas-scale 0.5\|auto`, `--strip-whitespace`, `--polygons`, `--premultiplied` | atlas packing (`atlas`, and `--pack`) |
170
+ | `--scales 1,0.5 --suffixes ,@0.5x` | `atlas`: several scales in one pack (suffixes default to `""` for 1 and `@<scale>x` otherwise) |
171
+
172
+ ### Texture packer options
173
+
174
+ | Option | Default | Meaning |
175
+ |---|---|---|
176
+ | `--padding <px>` | 2 | Empty pixels around each image |
177
+ | `--max-size <px>`, `--max-width`, `--max-height` | 2048 | Largest page (`--max-size` sets both axes) |
178
+ | `--min-width <px>`, `--min-height <px>` | 0 | Smallest page |
179
+ | `--no-pot`, `--square`, `--multiple-of-4` | power of two | Page size rules (multiples of 4 suit block-compressed formats) |
180
+ | `--rotate` | off | Turn images 90° when that packs tighter |
181
+ | `--atlas-scale 0.5\|auto` | 1 | Store images smaller; `auto` shrinks just enough to fit one page |
182
+ | `--strip-whitespace`, `--polygons` | off | Pack by visible bounds; draw tight outlines |
183
+ | `--alpha-threshold 0-255` | 0 | Alpha at or below this counts as transparent (trimming, polygons, blank images) |
184
+ | `--no-alias` | aliases on | Identical images (same pixels after trimming) are normally stored once |
185
+ | `--keep-blank` | blank ignored | Fully transparent images normally take no space (their regions are marked `empty`) |
186
+ | `--no-edge-padding` | on | Edge padding repeats each image's edge pixels into half its padding |
187
+ | `--no-duplicate-padding` | on | Without it, opaque edges are repeated as colour only (alpha 0): they fade into the padding |
188
+ | `--bleed`, `--no-bleed` | on unless `--premultiplied` | Transparent pixels take the nearest visible colour (alpha stays 0): no dark fringes |
189
+ | `--premultiplied` | off | Store pages premultiplied |
190
+ | `--filter-min`, `--filter-mag` | `linear` | `nearest`, `linear`, `mipmap`, `mipmapNearestNearest`, `mipmapLinearNearest`, `mipmapNearestLinear`, `mipmapLinearLinear` (written for runtimes) |
191
+ | `--wrap-x`, `--wrap-y` | `clamp` | `clamp`, `repeat`, `mirroredRepeat` (written for runtimes) |
192
+ | `--pixel-format` | `RGBA8888` | `RGBA8888`, `RGB888`, `RGBA4444`, `RGB565`, `Alpha` (a hint for runtimes) |
193
+ | `--page-format png\|jpeg`, `--jpeg-quality 90` | `png` | JPEG pages are opaque; a warning says when the art had transparency |
194
+ | `--resample bilinear\|bicubic\|nearest` | `bilinear` | Resampling for scaled packs (bicubic is the canvas's high-quality smoothing) |
195
+ | `--debug` | off | Outline every region on the pages in magenta |
196
+
197
+ ## Documentation
198
+
199
+ - [OpenBone README](https://github.com/UXCentury/open-bone/blob/main/README.md)
200
+ - [MCP guide](https://github.com/UXCentury/open-bone/blob/main/docs/mcp.md)
201
+ - [File format](https://github.com/UXCentury/open-bone/blob/main/docs/format.md)
202
+ - [Engine and platform exports](https://github.com/UXCentury/open-bone/blob/main/docs/engine-exports.md)
203
+ - [Changelog](https://github.com/UXCentury/open-bone/blob/main/CHANGELOG.md)
204
+
205
+ ## License
206
+
207
+ [MIT](https://github.com/UXCentury/open-bone/blob/main/LICENSE) © UX Century and OpenBone contributors
package/dist/bin.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env -S npx tsx
2
+ export {};
package/dist/bin.js ADDED
@@ -0,0 +1,277 @@
1
+ #!/usr/bin/env node
2
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { ATLAS_FILTERS, ATLAS_PIXEL_FORMATS, ATLAS_WRAPS, DocumentStore, deserialize, registry, serialize, summarize, validate } from "@openbone/core";
5
+ import { parseScaleVariants } from "@openbone/mcp";
6
+ import { EXPORT_FORMATS, ProjectSession, exportBaseName, exportFile, pose, renderGif, renderPng } from "@openbone/mcp";
7
+ import { expandGlob } from "./glob.js";
8
+ import { createQuickJsHost } from "@openbone/scripting";
9
+ const HELP = `openbone — OpenBone command line
10
+
11
+ Usage:
12
+ openbone validate <file.obone>
13
+ openbone summary <file.obone>
14
+ openbone render <file.obone> [--animation walk] [--time 0.5] [--scale 1] [--bones] [--bounding-boxes] --out frame.png
15
+ openbone gif <file.obone> (--animation walk | --state-machine ui) [--duration 2] [--fps 20] [--scale 0.5] --out out.gif
16
+ openbone simulate <file.obone> --steps '[{"setInputs":{"speed":1},"advance":1},{"fire":["jump"],"advance":1}]' [--state-machine name]
17
+ openbone export <file or glob>... --format <format> --out <dir> [options]
18
+ formats: ${EXPORT_FORMATS.join(" | ")}
19
+ options: --animation walk --animations walk,run (spritesheet, json, obonb) --skin name
20
+ --scale 1 --fps 30 --duration 2 --time 0 --state-machine ui --steps '<json>'
21
+ --transparent --sequence (png/jpeg: every frame, ZIP)
22
+ --engine unity|godot|flutter|generic (spritesheet) --single-file (web) --binary
23
+ --pack (json/obonb/web: embed an atlas)
24
+ --embed (obone/json/obonb: put every image and sound inside the file, so it opens on its own)
25
+ --no-audio (avi/mov/mp4/webm: leave the sound out) --quality 0.85 (mp4/webm)
26
+ mp4 and webm, and MP3/OGG sound in videos, use ffmpeg from the PATH (or OPENBONE_FFMPEG)
27
+ atlas packing (atlas, and --pack):
28
+ --padding 2 --max-size 2048 (or --max-width / --max-height) --min-width 0 --min-height 0
29
+ --no-pot --square --multiple-of-4 --rotate --atlas-scale 0.5|auto
30
+ --scales 1,0.5 --suffixes ,@0.5x (atlas: one data file + page set per scale)
31
+ --strip-whitespace --polygons --premultiplied --alpha-threshold 0
32
+ --no-alias (store identical images twice) --keep-blank (blank images get space)
33
+ --no-edge-padding --no-duplicate-padding (opaque edges fade into the padding)
34
+ --bleed | --no-bleed (default: on unless --premultiplied)
35
+ --filter-min linear --filter-mag linear (nearest | linear | mipmap | mipmapNearestNearest |
36
+ mipmapLinearNearest | mipmapNearestLinear | mipmapLinearLinear)
37
+ --wrap-x clamp --wrap-y clamp (clamp | repeat | mirroredRepeat)
38
+ --pixel-format RGBA8888 (RGBA8888 | RGB888 | RGBA4444 | RGB565 | Alpha)
39
+ --page-format png|jpeg --jpeg-quality 90 --resample bilinear|bicubic|nearest --debug
40
+ openbone apply <file.obone> <op> '<json args>' (edit a file with any op, e.g. addBone)
41
+ openbone ops (list every edit op with its description)
42
+ openbone mcp [--project file.obone] [--http 7718] (start the MCP server)
43
+ openbone <command> --help (usage for one command)
44
+ `;
45
+ const argv = process.argv.slice(2);
46
+ const cmd = argv[0];
47
+ /** `openbone <command> --help` (or -h): that command's usage lines; the MCP server handles its own flags. */
48
+ const wantsHelp = cmd !== "mcp" && (argv.includes("--help") || argv.includes("-h"));
49
+ const file = argv[1];
50
+ const opt = (name) => {
51
+ const i = argv.indexOf(`--${name}`);
52
+ return i >= 0 ? argv[i + 1] : undefined;
53
+ };
54
+ const num = (name, d) => (opt(name) !== undefined ? Number(opt(name)) : d);
55
+ async function session() {
56
+ if (!file)
57
+ throw new Error("Missing <file.obone>");
58
+ const s = new ProjectSession();
59
+ await s.open(file);
60
+ s.autosave = false;
61
+ return s;
62
+ }
63
+ /** Flags that take no value (everything else starting with -- takes the next argument). */
64
+ const SWITCHES = new Set([
65
+ "bones", "bounding-boxes", "transparent", "sequence", "single-file", "binary", "pack", "embed", "no-audio", "no-pot", "rotate", "strip-whitespace", "polygons", "premultiplied", "no-minify",
66
+ "square", "multiple-of-4", "no-alias", "keep-blank", "no-edge-padding", "no-duplicate-padding", "bleed", "no-bleed", "debug",
67
+ ]);
68
+ /** `--name value` that must be one of `allowed` (undefined when absent). */
69
+ function choice(name, allowed) {
70
+ const v = opt(name);
71
+ if (v === undefined)
72
+ return undefined;
73
+ if (!allowed.includes(v))
74
+ throw new Error(`--${name} must be one of: ${allowed.join(", ")}`);
75
+ return v;
76
+ }
77
+ /** The atlas packer settings from the command line (the same settings as the Export dialog and the MCP tools). */
78
+ function atlasSettings() {
79
+ const flag = (n) => argv.includes(`--${n}`);
80
+ const atlasScale = opt("atlas-scale");
81
+ const scales = opt("scales");
82
+ return {
83
+ padding: num("padding"),
84
+ maxSize: num("max-size"),
85
+ maxWidth: num("max-width"),
86
+ maxHeight: num("max-height"),
87
+ minWidth: num("min-width"),
88
+ minHeight: num("min-height"),
89
+ powerOfTwo: !flag("no-pot"),
90
+ square: flag("square"),
91
+ multipleOf4: flag("multiple-of-4"),
92
+ rotate: flag("rotate"),
93
+ scale: atlasScale === "auto" ? "auto" : atlasScale ? Number(atlasScale) : undefined,
94
+ ...(scales ? { scales: parseScaleVariants(scales, opt("suffixes")) } : {}),
95
+ stripWhitespace: flag("strip-whitespace"),
96
+ polygons: flag("polygons"),
97
+ premultipliedAlpha: flag("premultiplied"),
98
+ alias: !flag("no-alias"),
99
+ ignoreBlank: !flag("keep-blank"),
100
+ alphaThreshold: num("alpha-threshold"),
101
+ edgePadding: !flag("no-edge-padding"),
102
+ duplicatePadding: !flag("no-duplicate-padding"),
103
+ bleed: flag("bleed") ? true : flag("no-bleed") ? false : undefined,
104
+ filterMin: choice("filter-min", ATLAS_FILTERS),
105
+ filterMag: choice("filter-mag", ATLAS_FILTERS),
106
+ wrapX: choice("wrap-x", ATLAS_WRAPS),
107
+ wrapY: choice("wrap-y", ATLAS_WRAPS),
108
+ pixelFormat: choice("pixel-format", ATLAS_PIXEL_FORMATS),
109
+ pageFormat: choice("page-format", ["png", "jpeg"]),
110
+ jpegQuality: num("jpeg-quality"),
111
+ resample: choice("resample", ["bilinear", "bicubic", "nearest"]),
112
+ debug: flag("debug"),
113
+ };
114
+ }
115
+ /** Positional arguments after the command (files and globs), skipping option values. */
116
+ function positionals() {
117
+ const out = [];
118
+ for (let i = 1; i < argv.length; i++) {
119
+ const a = argv[i];
120
+ if (a.startsWith("--")) {
121
+ if (!SWITCHES.has(a.slice(2)))
122
+ i++;
123
+ }
124
+ else
125
+ out.push(a);
126
+ }
127
+ return out;
128
+ }
129
+ /** A path relative to the working folder when it is inside it, else absolute. */
130
+ const shortPath = (p) => {
131
+ const r = path.relative(process.cwd(), p);
132
+ return r && !r.startsWith("..") ? r : p;
133
+ };
134
+ async function exportCommand() {
135
+ const format = opt("format");
136
+ if (!format || !EXPORT_FORMATS.includes(format))
137
+ throw new Error(`--format must be one of: ${EXPORT_FORMATS.join(", ")}`);
138
+ const patterns = positionals();
139
+ if (!patterns.length)
140
+ throw new Error("Usage: openbone export <file or glob>... --format <format> --out <dir>");
141
+ const files = [...new Set((await Promise.all(patterns.map((p) => expandGlob(p)))).flat())].filter((f) => /\.(obone|obonb)$/i.test(f));
142
+ if (!files.length)
143
+ throw new Error(`No .obone files match ${patterns.join(" ")}`);
144
+ const outDir = path.resolve(opt("out") ?? ".");
145
+ await mkdir(outDir, { recursive: true });
146
+ const flag = (n) => argv.includes(`--${n}`);
147
+ const atlas = atlasSettings();
148
+ if (atlas.scales && format !== "atlas")
149
+ throw new Error("--scales needs --format atlas (embedded atlases hold one scale)");
150
+ const host = (() => {
151
+ let h = null;
152
+ return () => (h ??= createQuickJsHost());
153
+ })();
154
+ let failed = 0;
155
+ for (const file of files) {
156
+ try {
157
+ const s = new ProjectSession();
158
+ await s.open(file);
159
+ s.autosave = false;
160
+ const r = await exportFile(s, {
161
+ format,
162
+ animation: opt("animation"),
163
+ animations: opt("animations")?.split(","),
164
+ stateMachine: opt("state-machine"),
165
+ steps: opt("steps") ? JSON.parse(opt("steps")) : undefined,
166
+ skin: opt("skin"),
167
+ scale: num("scale"),
168
+ fps: num("fps"),
169
+ duration: num("duration"),
170
+ time: num("time"),
171
+ transparent: flag("transparent"),
172
+ sequence: flag("sequence"),
173
+ engine: opt("engine"),
174
+ singleFile: flag("single-file"),
175
+ minify: !flag("no-minify"),
176
+ binary: flag("binary") ? true : undefined,
177
+ pack: flag("pack"),
178
+ embed: flag("embed"),
179
+ audio: !flag("no-audio"),
180
+ quality: num("quality"),
181
+ atlas,
182
+ }, host);
183
+ const out = path.join(outDir, `${exportBaseName(s)}${r.suffix}.${r.ext}`);
184
+ await writeFile(out, r.bytes);
185
+ console.log(`wrote ${shortPath(out)} (${(r.bytes.length / 1024).toFixed(1)} KB)${r.note}`);
186
+ }
187
+ catch (e) {
188
+ failed++;
189
+ console.error(`error: ${shortPath(file)}: ${e.message}`);
190
+ }
191
+ }
192
+ if (failed) {
193
+ console.error(`${failed} of ${files.length} file(s) failed`);
194
+ process.exitCode = 1;
195
+ }
196
+ }
197
+ /** The usage lines for one command (the line naming it plus its indented continuation lines). */
198
+ function commandHelp(name) {
199
+ const lines = HELP.split("\n");
200
+ const start = lines.findIndex((l) => l.startsWith(` openbone ${name} `) || l === ` openbone ${name}`);
201
+ if (start < 0)
202
+ return undefined;
203
+ let end = start + 1;
204
+ while (end < lines.length && lines[end].startsWith(" "))
205
+ end++;
206
+ return ["Usage:", ...lines.slice(start, end)].join("\n");
207
+ }
208
+ async function main() {
209
+ if (wantsHelp || cmd === "help" || cmd === "--help" || cmd === "-h") {
210
+ const name = cmd === "help" ? argv[1] : wantsHelp ? cmd : undefined;
211
+ console.log((name && commandHelp(name)) ?? HELP);
212
+ return;
213
+ }
214
+ switch (cmd) {
215
+ case "export":
216
+ await exportCommand();
217
+ break;
218
+ case "validate": {
219
+ const s = await session();
220
+ const issues = validate(s.doc);
221
+ for (const i of issues)
222
+ console.log(`${i.level.toUpperCase()} ${i.path}: ${i.message}`);
223
+ console.log(issues.length ? `${issues.length} issue(s)` : "OK");
224
+ process.exitCode = issues.some((i) => i.level === "error") ? 1 : 0;
225
+ break;
226
+ }
227
+ case "summary":
228
+ console.log(summarize((await session()).doc));
229
+ break;
230
+ case "render": {
231
+ const s = await session();
232
+ const { png } = await renderPng(s, { animation: opt("animation"), time: num("time"), scale: num("scale", 1), showBones: argv.includes("--bones"), showBoundingBoxes: argv.includes("--bounding-boxes"), stateMachine: opt("state-machine") }, await createQuickJsHost());
233
+ const out = opt("out") ?? "frame.png";
234
+ await writeFile(out, png);
235
+ console.log(`wrote ${out}`);
236
+ break;
237
+ }
238
+ case "gif": {
239
+ const s = await session();
240
+ const gif = await renderGif(s, { animation: opt("animation"), stateMachine: opt("state-machine"), duration: num("duration", 2), fps: num("fps", 20), scale: num("scale", 0.5), steps: opt("steps") ? JSON.parse(opt("steps")) : undefined }, await createQuickJsHost());
241
+ const out = opt("out") ?? "out.gif";
242
+ await writeFile(out, gif);
243
+ console.log(`wrote ${out} (${(gif.length / 1024).toFixed(0)} KB)`);
244
+ break;
245
+ }
246
+ case "simulate": {
247
+ const s = await session();
248
+ const { log } = pose(s.doc, { stateMachine: opt("state-machine") ?? "", steps: JSON.parse(opt("steps") ?? "[{}]") }, await createQuickJsHost());
249
+ console.log(log.join("\n"));
250
+ break;
251
+ }
252
+ case "apply": {
253
+ if (!file || !argv[2])
254
+ throw new Error("Usage: openbone apply <file> <op> '<json>'");
255
+ const store = new DocumentStore(deserialize(await readFile(file, "utf8")));
256
+ const result = store.apply(argv[2], JSON.parse(argv[3] ?? "{}"));
257
+ await writeFile(file, serialize(store.doc));
258
+ console.log(JSON.stringify(result));
259
+ break;
260
+ }
261
+ case "ops":
262
+ for (const d of registry.values())
263
+ console.log(`${d.name.padEnd(24)} [${d.group}] ${d.description}`);
264
+ break;
265
+ case "mcp": {
266
+ process.argv = [process.argv[0], process.argv[1], ...argv.slice(1)];
267
+ await import("@openbone/mcp/bin");
268
+ break;
269
+ }
270
+ default:
271
+ console.log(HELP);
272
+ }
273
+ }
274
+ main().catch((e) => {
275
+ console.error(`error: ${e.message}`);
276
+ process.exit(1);
277
+ });
package/dist/glob.d.ts ADDED
@@ -0,0 +1,4 @@
1
+ /** Glob pattern → RegExp for one path segment or a whole path (`**` matches any number of folders). */
2
+ export declare function globToRegExp(pattern: string): RegExp;
3
+ /** Expand a file path or glob (`*`, `**`, `?`, `[ab]`, `{a,b}`) into existing files, sorted. */
4
+ export declare function expandGlob(pattern: string, cwd?: string): Promise<string[]>;
package/dist/glob.js ADDED
@@ -0,0 +1,86 @@
1
+ import { readdir, stat } from "node:fs/promises";
2
+ import path from "node:path";
3
+ const MAGIC = /[*?[{]/;
4
+ /** Glob pattern → RegExp for one path segment or a whole path (`**` matches any number of folders). */
5
+ export function globToRegExp(pattern) {
6
+ let re = "";
7
+ for (let i = 0; i < pattern.length; i++) {
8
+ const c = pattern[i];
9
+ if (c === "*") {
10
+ if (pattern[i + 1] === "*") {
11
+ // "**/" matches zero or more folders; a trailing "**" matches anything.
12
+ const slash = pattern[i + 2] === "/";
13
+ re += slash ? "(?:.*/)?" : ".*";
14
+ i += slash ? 2 : 1;
15
+ }
16
+ else
17
+ re += "[^/]*";
18
+ }
19
+ else if (c === "?")
20
+ re += "[^/]";
21
+ else if (c === "{") {
22
+ const end = pattern.indexOf("}", i);
23
+ if (end < 0)
24
+ re += "\\{";
25
+ else {
26
+ re += `(?:${pattern
27
+ .slice(i + 1, end)
28
+ .split(",")
29
+ .map((p) => p.replace(/[.+^$()|\\]/g, "\\$&").replace(/\*/g, "[^/]*"))
30
+ .join("|")})`;
31
+ i = end;
32
+ }
33
+ }
34
+ else if (c === "[") {
35
+ const end = pattern.indexOf("]", i);
36
+ if (end < 0)
37
+ re += "\\[";
38
+ else {
39
+ re += pattern.slice(i, end + 1).replace("[!", "[^");
40
+ i = end;
41
+ }
42
+ }
43
+ else
44
+ re += c.replace(/[.+^$()|\\/]/g, "\\$&");
45
+ }
46
+ return new RegExp(`^${re}$`);
47
+ }
48
+ async function walk(dir, deep, out) {
49
+ let entries;
50
+ try {
51
+ entries = await readdir(dir, { withFileTypes: true });
52
+ }
53
+ catch {
54
+ return;
55
+ }
56
+ for (const e of entries) {
57
+ if (e.name === "node_modules" || e.name.startsWith("."))
58
+ continue;
59
+ const p = path.join(dir, e.name);
60
+ if (e.isDirectory()) {
61
+ if (deep)
62
+ await walk(p, deep, out);
63
+ }
64
+ else
65
+ out.push(p);
66
+ }
67
+ }
68
+ /** Expand a file path or glob (`*`, `**`, `?`, `[ab]`, `{a,b}`) into existing files, sorted. */
69
+ export async function expandGlob(pattern, cwd = process.cwd()) {
70
+ const norm = pattern.split(path.sep).join("/");
71
+ if (!MAGIC.test(norm)) {
72
+ const abs = path.resolve(cwd, pattern);
73
+ return (await stat(abs).catch(() => null))?.isFile() ? [abs] : [];
74
+ }
75
+ // Walk from the longest folder prefix without wildcards.
76
+ const parts = norm.split("/");
77
+ const fixed = [];
78
+ while (parts.length > 1 && !MAGIC.test(parts[0]))
79
+ fixed.push(parts.shift());
80
+ const root = path.resolve(cwd, fixed.join("/") || ".");
81
+ const rest = parts.join("/");
82
+ const re = globToRegExp(rest);
83
+ const files = [];
84
+ await walk(root, rest.includes("**") || parts.length > 1, files);
85
+ return files.filter((f) => re.test(path.relative(root, f).split(path.sep).join("/"))).sort();
86
+ }
package/package.json CHANGED
@@ -1,6 +1,49 @@
1
1
  {
2
2
  "name": "@openbone/cli",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.3.0",
4
+ "description": "OpenBone command line: validate, render, export and edit .obone files, and start the MCP server",
5
+ "keywords": [
6
+ "openbone",
7
+ "skeletal-animation",
8
+ "2d-animation",
9
+ "animation",
10
+ "cli"
11
+ ],
12
+ "homepage": "https://github.com/UXCentury/open-bone/tree/main/packages/cli#readme",
13
+ "bugs": {
14
+ "url": "https://github.com/UXCentury/open-bone/issues"
15
+ },
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "git+https://github.com/UXCentury/open-bone.git",
19
+ "directory": "packages/cli"
20
+ },
21
+ "license": "MIT",
22
+ "type": "module",
23
+ "exports": {
24
+ "./bin": {
25
+ "types": "./dist/bin.d.ts",
26
+ "default": "./dist/bin.js"
27
+ }
28
+ },
29
+ "bin": {
30
+ "openbone": "./dist/bin.js"
31
+ },
32
+ "files": [
33
+ "dist"
34
+ ],
35
+ "engines": {
36
+ "node": ">=20"
37
+ },
38
+ "publishConfig": {
39
+ "access": "public"
40
+ },
41
+ "dependencies": {
42
+ "@openbone/core": "0.3.0",
43
+ "@openbone/mcp": "0.3.0",
44
+ "@openbone/scripting": "0.3.0"
45
+ },
46
+ "scripts": {
47
+ "build": "node ../build.mjs"
48
+ }
6
49
  }