@neta-art/cohub-cli 10.26.0 → 10.27.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.
@@ -1,4 +1,4 @@
1
1
  import { m as parseBoardDocument } from "./id.js";
2
2
  import { A as boardScriptAttachments, D as boardShaderParameters, E as boardTimedMedia, S as boardTexturePixels, T as boardMediaSpans, _ as selectBoardExportAssets, a as describeBoardScriptLanes, c as boardRenderTheme, d as inspectBoardScene, f as measureBoardText, g as planBoardExport, i as createNodeBoardScriptHost, j as hasBoardScripts, l as checkBoardShader, m as boardAutoplayLoops, n as createNodeBoardRenderer, o as describeBoardExportWarning, p as createBoardRenderSampler, r as exportBoardImageBytes, s as prepareBoardExport, t as createBoardScriptHarness, u as inspectBoardItems, v as boardAssetKey, w as boardMediaRate, x as boardTextureEdge, y as boardAssetKeySource } from "./board-kernel.js";
3
- import { J as itemBounds, N as BOARD_SCRIPT_DRAWING_EXAMPLE, P as BOARD_SCRIPT_RAIN_EXAMPLE, S as createBoardAnimationSampler, c as boardPathTrack, d as boardSequencePatch, i as boardFrameRegions, k as boardAnimatesScriptParams, l as boardPlacePatch, s as boardRegionStep, tt as rectsIntersect, u as boardSequence, w as buildBoardScene } from "./themes.js";
3
+ import { A as boardAnimatesScriptParams, C as createBoardAnimationSampler, F as BOARD_SCRIPT_RAIN_EXAMPLE, P as BOARD_SCRIPT_DRAWING_EXAMPLE, T as buildBoardScene, X as itemBounds, c as boardPathTrack, d as boardSequencePatch, i as boardFrameRegions, l as boardPlacePatch, rt as rectsIntersect, s as boardRegionStep, u as boardSequence } from "./themes.js";
4
4
  export { BOARD_SCRIPT_DRAWING_EXAMPLE, BOARD_SCRIPT_RAIN_EXAMPLE, boardAnimatesScriptParams, boardAssetKey, boardAssetKeySource, boardAutoplayLoops, boardFrameRegions, boardMediaRate, boardMediaSpans, boardPathTrack, boardPlacePatch, boardRegionStep, boardRenderTheme, boardScriptAttachments, boardSequence, boardSequencePatch, boardShaderParameters, boardTextureEdge, boardTexturePixels, boardTimedMedia, buildBoardScene, checkBoardShader, createBoardAnimationSampler, createBoardRenderSampler, createBoardScriptHarness, createNodeBoardRenderer, createNodeBoardScriptHost, describeBoardExportWarning, describeBoardScriptLanes, exportBoardImageBytes, hasBoardScripts, inspectBoardItems, inspectBoardScene, itemBounds, measureBoardText, parseBoardDocument, planBoardExport, prepareBoardExport, rectsIntersect, selectBoardExportAssets };
@@ -1,5 +1,5 @@
1
1
  import { C as boardModelFormat, g as planBoardExport } from "./board-kernel.js";
2
- import { w as buildBoardScene } from "./themes.js";
2
+ import { T as buildBoardScene } from "./themes.js";
3
3
  import { i as settleBoardDocument, s as loadBoardDocument } from "./board-export-resources.js";
4
4
  import { a as findBoardGpuBrowser, r as openBoardGpu } from "./daemon.js";
5
5
  import { r as gpuResources } from "./board-export.js";
@@ -1,7 +1,7 @@
1
1
  import { t as createClient } from "./client.js";
2
2
  import { d as diffMergePatch } from "./id.js";
3
3
  import { A as boardScriptAttachments, D as boardShaderParameters, O as boardScriptSenseOf, a as describeBoardScriptLanes, g as planBoardExport, k as parseBoardScriptInputs, l as checkBoardShader, n as createNodeBoardRenderer, t as createBoardScriptHarness } from "./board-kernel.js";
4
- import { J as itemBounds, tt as rectsIntersect, w as buildBoardScene } from "./themes.js";
4
+ import { T as buildBoardScene, X as itemBounds, rt as rectsIntersect } from "./themes.js";
5
5
  import { i as settleBoardDocument, s as loadBoardDocument } from "./board-export-resources.js";
6
6
  import { a as findBoardGpuBrowser, r as openBoardGpu } from "./daemon.js";
7
7
  import { a as readSpaceFileBytes, o as resolveBundledFonts, r as gpuResources, s as runBoardExport } from "./board-export.js";
@@ -114,7 +114,35 @@ function parseStep(entry, index) {
114
114
  if (typeof step.inputs !== "string" || !step.inputs) throw new Error(`${name}.inputs must be a Space file path`);
115
115
  return { inputs: step.inputs };
116
116
  }
117
- throw new Error(`${name} must be one of wait, tool, tap, drag, move, pointer, key, select, input or inputs`);
117
+ if ("peers" in step) {
118
+ if (!Array.isArray(step.peers)) throw new Error(`${name}.peers must list viewers`);
119
+ return { peers: step.peers.map((entry, at) => parsePeer(entry, `${name}.peers[${at}]`)) };
120
+ }
121
+ if ("broadcast" in step) {
122
+ if (typeof step.broadcast !== "string" || !step.broadcast) throw new Error(`${name}.broadcast must be an event type`);
123
+ if (typeof step.to !== "string" || !step.to) throw new Error(`${name}.to must be the id of the script that receives it`);
124
+ if (step.from !== void 0 && typeof step.from !== "string") throw new Error(`${name}.from must be a viewer name`);
125
+ return {
126
+ broadcast: step.broadcast,
127
+ to: step.to,
128
+ data: step.data ?? null,
129
+ from: step.from ?? "Peer"
130
+ };
131
+ }
132
+ throw new Error(`${name} must be one of wait, tool, tap, drag, move, pointer, key, select, input, inputs, peers or broadcast`);
133
+ }
134
+ function parsePeer(entry, name) {
135
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) throw new Error(`${name} must be an object`);
136
+ const peer = entry;
137
+ if (typeof peer.name !== "string" || !peer.name) throw new Error(`${name}.name must be a viewer name`);
138
+ if (peer.pointerType !== void 0 && !POINTER_TYPES.includes(peer.pointerType)) throw new Error(`${name}.pointerType must be one of ${POINTER_TYPES.join(", ")}`);
139
+ if (peer.pressed !== void 0 && typeof peer.pressed !== "boolean") throw new Error(`${name}.pressed must be a boolean`);
140
+ return {
141
+ name: peer.name,
142
+ ...peer.at !== void 0 ? { point: point(peer.at, `${name}.at`) } : {},
143
+ ...peer.pointerType !== void 0 ? { pointerType: peer.pointerType } : {},
144
+ ...peer.pressed !== void 0 ? { pressed: peer.pressed } : {}
145
+ };
118
146
  }
119
147
  async function run(harness, steps, progress, presses, readInputs) {
120
148
  for (const [index, step] of steps.entries()) {
@@ -131,6 +159,8 @@ async function run(harness, steps, progress, presses, readInputs) {
131
159
  await harness.key("keyup", step.key);
132
160
  } else if ("input" in step) await harness.input(step.input, step.data);
133
161
  else if ("inputs" in step) await harness.replay(parseBoardScriptInputs(await readInputs(step.inputs)));
162
+ else if ("peers" in step) await harness.peers(step.peers);
163
+ else if ("broadcast" in step) await harness.broadcast(step.to, step.broadcast, step.data, { name: step.from });
134
164
  else await harness.select(step.select);
135
165
  if (press) presses.push({
136
166
  step: index,
@@ -228,6 +258,7 @@ async function runBoardSimulation(options) {
228
258
  ...early.errors
229
259
  },
230
260
  presses,
261
+ broadcasts: [],
231
262
  warnings: ["Stopped before the steps: fix the shader errors first."],
232
263
  shaders: {
233
264
  count: initial.shaders.length,
@@ -252,6 +283,7 @@ async function runBoardSimulation(options) {
252
283
  changes: diffMergePatch(document, current.document) ?? {},
253
284
  errors,
254
285
  presses,
286
+ broadcasts: [...current.broadcasts],
255
287
  warnings,
256
288
  ...shaders.length ? { shaders: {
257
289
  count: shaders.length,
@@ -10,7 +10,7 @@ function parseBoardTime(value, name = "time") {
10
10
  if (!match?.[1]) throw new Error(`${name}: expected a time such as 1500, 500ms, 12.5s or 2m`);
11
11
  return Math.round(Number(match[1]) * (UNITS[(match[2] ?? "").toLowerCase()] ?? 1) * 1e3) / 1e3;
12
12
  }
13
- function parseBoardTimes(value, name = "--at", limit = 1e4) {
13
+ function parseBoardTimes(value, name = "--at", limit = 1e4, fps) {
14
14
  if (value.includes(",")) {
15
15
  const entries = value.split(",");
16
16
  if (entries.length > limit) throw new Error(`${name}: frame count exceeds the limit of ${limit}`);
@@ -18,11 +18,13 @@ function parseBoardTimes(value, name = "--at", limit = 1e4) {
18
18
  }
19
19
  const parts = value.split(":");
20
20
  if (parts.length === 1) return [parseBoardTime(value, name)];
21
- if (parts.length !== 3) throw new Error(`${name}: expected a time or start:end:step`);
22
- const [start, end, step] = parts.map((part) => parseBoardTime(part, name));
23
- if (step <= 0) throw new Error(`${name}: step must be greater than zero`);
21
+ if (parts.length === 2 && !fps) throw new Error(`${name}: start:end needs --fps, or write start:end:step`);
22
+ if (parts.length !== 2 && parts.length !== 3) throw new Error(`${name}: expected a time or start:end:step`);
23
+ const [start, end, written] = parts.map((part) => parseBoardTime(part, name));
24
+ const step = written ?? 1e3 / fps;
25
+ if (!(step > 0)) throw new Error(`${name}: step must be greater than zero`);
24
26
  if (end < start) throw new Error(`${name}: end must not be before start`);
25
- const count = Math.floor((end - start) / step + 1e-9) + 1;
27
+ const count = Math.floor((end - start + Math.min(.5, step / 2)) / step) + 1;
26
28
  if (count > limit) throw new Error(`${name}: ${count} frames exceed the limit of ${limit}`);
27
29
  return Array.from({ length: count }, (_, index) => Math.round((start + index * step) * 1e3) / 1e3);
28
30
  }
@@ -1,7 +1,7 @@
1
1
  import { m as record, p as object, x as toJSONSchema } from "./schemas.js";
2
2
  import { C as error, D as json, E as handleHttp, O as jsonRequested, b as resolveSpace, j as table, k as ok, r as createRealtimeClient, t as createClient } from "./client.js";
3
- import { $ as BoardAnimationHeaderSchema, G as BOARD_COLOR_TOKENS, K as BOARD_EFFECT_KINDS, W as BOARD_CAMERA_TARGET, X as BOARD_ITEM_TYPES, Y as BOARD_ITEM_SCHEMAS, at as BoardSettingsSchema, bt as BOARD_TEXT_SCALE, f as listBoardProperties, g as resolveBoardProperty, ht as BOARD_DEFAULT_SIZES, it as BoardScriptSchema, lt as isBuiltinItemType, ot as BoardTrackSchema, q as BOARD_EFFECT_KIND_INFO, rt as BoardKeySchema, tt as BoardExtensionItemSchema, vt as BOARD_PAGE_SIZE } from "./id.js";
4
- import { F as BOARD_SCRIPT_SENSES_EXAMPLE, I as BOARD_SCRIPT_TILT_EXAMPLE, N as BOARD_SCRIPT_DRAWING_EXAMPLE, P as BOARD_SCRIPT_RAIN_EXAMPLE, S as createBoardAnimationSampler, c as boardPathTrack, d as boardSequencePatch, i as boardFrameRegions, l as boardPlacePatch, n as BOARD_THEME_IDS, s as boardRegionStep, w as buildBoardScene } from "./themes.js";
3
+ import { $ as BoardAnimationHeaderSchema, G as BOARD_COLOR_TOKENS, K as BOARD_EFFECT_KINDS, W as BOARD_CAMERA_TARGET, X as BOARD_ITEM_TYPES, Y as BOARD_ITEM_SCHEMAS, at as BoardSettingsSchema, f as listBoardProperties, g as resolveBoardProperty, gt as BOARD_DEFAULT_SIZES, it as BoardScriptSchema, lt as isBuiltinItemType, ot as BoardTrackSchema, q as BOARD_EFFECT_KIND_INFO, rt as BoardKeySchema, tt as BoardExtensionItemSchema, xt as BOARD_TEXT_SCALE, yt as BOARD_PAGE_SIZE } from "./id.js";
4
+ import { C as createBoardAnimationSampler, F as BOARD_SCRIPT_RAIN_EXAMPLE, I as BOARD_SCRIPT_SENSES_EXAMPLE, L as BOARD_SCRIPT_SPARKS_EXAMPLE, P as BOARD_SCRIPT_DRAWING_EXAMPLE, R as BOARD_SCRIPT_TILT_EXAMPLE, T as buildBoardScene, c as boardPathTrack, d as boardSequencePatch, i as boardFrameRegions, l as boardPlacePatch, n as BOARD_THEME_IDS, s as boardRegionStep } from "./themes.js";
5
5
  import { a as settleBoardMediaDurations, i as settleBoardDocument, o as settleBoardPatch, s as loadBoardDocument, t as BOARD_EXPORT_RENDERERS } from "./board-export-resources.js";
6
6
  import { n as parseBoardTime, r as parseBoardTimes, t as formatBoardTime } from "./board-time.js";
7
7
  import { constants, existsSync } from "node:fs";
@@ -131,6 +131,8 @@ const BOARD_SCRIPT_API = {
131
131
  scene: "scene(items, options?): replace this instance's world or screen layer of temporary Board items; never saved. IDs are unique across both layers.",
132
132
  hitRegions: "hitRegions(regions): replace the input declarations.",
133
133
  emit: "emit(id, type, data?): send a custom event to another scripted item in scope, or to any Board script by its key. Exports deliver it within the same moment, in document order. A handler may answer with emits; past 16 in a row the emit rejects, so emit from onFrame() to send on the next step.",
134
+ broadcast: "broadcast(type, data?): deliver a custom event to this script on every viewer's screen, this one included, so others see the effect of this viewer's input. The event carries peer: null here, { id, actorId, name, color } from another viewer. Fire-and-forget and lossy: data up to 1024 characters of JSON, about 10 a second per viewer, nothing while the page is hidden, nothing for viewers who join later. While a handler of another viewer's broadcast runs, it can neither commit nor broadcast; after an await it is unguarded and may save twice, so answer broadcasts with presentation only and persist with commit() from your own input. Like emit, past 16 handlers deep it rejects. Exports deliver it only here.",
135
+ peers: "Other viewers on the Board: { id, actorId, name, color, point (owner coordinates, or null), pointerType, pressed }; current after each peerschange.",
134
136
  commit: "commit(patch): save a Board patch; resolves true once written here. Within 5 s of this viewer's input, outside onFrame steps, it saves undoably; otherwise one live editor saves it and others resolve false. It may edit items in scope, add children to a scoped frame, and attach modules already running in scope. Read-only viewers cannot commit: capabilities.has(\"board.commit\") is false there.",
135
137
  layoutText: "layoutText({ text, fontSize?, fontWeight?, font?, lineHeight?, width? }): the size a native text item would take.",
136
138
  uniforms: "uniforms(values): set the shader's declared uniforms from numbers or number arrays; kept until changed.",
@@ -191,6 +193,7 @@ const BOARD_SCRIPT_API = {
191
193
  change: "data.added, data.changed, data.removed: item ids in scope; data.source: user, script or remote.",
192
194
  gesture: "data: this viewer's draw, shape, frame or arrow gesture over the owner: id, tool, phase (start | update | end | cancel), points in owner coordinates, and on end the item it created.",
193
195
  envchange: "data: the new ctx.env.",
196
+ peerschange: "data: the other viewers, as ctx.peers; their cursors move at about 25 Hz. Exports have none.",
194
197
  "browser:devicemotion": "data: the DeviceMotionEvent's acceleration, accelerationIncludingGravity, rotationRate (deg/s) and interval, in device axes, with t its timeStamp. One event per reading.",
195
198
  "browser:deviceorientation": "data: alpha, beta, gamma, absolute, and on iOS webkitCompassHeading and webkitCompassAccuracy; t.",
196
199
  "browser:deviceorientationabsolute": "As deviceorientation, relative to the Earth, where the browser offers it.",
@@ -497,7 +500,8 @@ const MODULES = {
497
500
  custom: BOARD_SCRIPT_DRAWING_EXAMPLE,
498
501
  rain: BOARD_SCRIPT_RAIN_EXAMPLE,
499
502
  tilt: BOARD_SCRIPT_TILT_EXAMPLE,
500
- senses: BOARD_SCRIPT_SENSES_EXAMPLE
503
+ senses: BOARD_SCRIPT_SENSES_EXAMPLE,
504
+ sparks: BOARD_SCRIPT_SPARKS_EXAMPLE
501
505
  };
502
506
  /**
503
507
  * Starter documents for `boards create -i` and patches for `boards apply -i`.
@@ -962,6 +966,21 @@ const BOARD_EXAMPLES = {
962
966
  },
963
967
  script: { src: "scripts/tilt.js" }
964
968
  } } }
969
+ },
970
+ sparks: {
971
+ description: "Sparks every viewer sees where anyone clicks, and halos on the others' cursors; use --module to print scripts/sparks.js.",
972
+ value: { items: { pad: {
973
+ type: "custom",
974
+ position: {
975
+ x: 0,
976
+ y: 0
977
+ },
978
+ size: {
979
+ width: 640,
980
+ height: 400
981
+ },
982
+ script: { src: "scripts/sparks.js" }
983
+ } } }
965
984
  }
966
985
  };
967
986
  function registerBoardExampleCommands(boards) {
@@ -1339,13 +1358,13 @@ function framePath(pattern, index) {
1339
1358
  return pattern.replace(/%(0?)(\d*)d/, (_match, zero, width) => String(index).padStart(Number(width || 0), zero ? "0" : " "));
1340
1359
  }
1341
1360
  function registerExportCommand(boards) {
1342
- withJson(boards.command("export <board>").description("Render a Board to an image, or an animation to a frame sequence").requiredOption("-o, --out <file>", "Output file; the extension picks the format. Sequences need %d, e.g. frames/%04d.png").option("--at <time>", "A moment, comma-separated moments, or start:end:step").option("--camera", "Follow the animation camera").option("--size <widthxheight>", "Camera output in pixels; frames keep their own size", "1600x900").option("--animation <id>", "Animation the --at times refer to").option("--frame <item-id>", "Export one frame as a page").option("--items <ids>", "Comma-separated item ids").option("--rect <rect>", "World rect as x,y,width,height").option("--scale <factor>", "Output pixels per board unit", "2").option("--padding <units>", "Padding around the content in board units").option("--theme <name>", `Cohub theme: ${BOARD_THEME_IDS.join(", ")}`, "dark").option("--paper <mode>", "Output paper: paper or transparent", "paper").option("--format <format>", `Override the format (${BOARD_EXPORT_FORMATS.join(", ")}, ${BOARD_VIDEO_FORMATS.join(", ")})`).option("--quality <q>", "JPEG/WebP quality from 0 to 1", "0.92").option("--fps <rate>", "Video frame rate; defaults to the --at step").option("--image-memory <mib>", "Decoded image memory budget in MiB", String(256)).option("--no-images", "Draw placeholders instead of downloading images").option("--renderer <renderer>", "auto draws in Node and uses local Chrome for shaders; canvas or gpu forces one", "auto").option("--force", "Replace existing output files").option("--timeout <time>", "Fail a frame that takes longer, naming the scripts still running", "2m").option("--inputs <file>", "A Space file of recorded browser input for scripts to replay from time 0").option("--async", "Run as a Task in the Space's sandbox and return at once; paths are Space paths")).addHelpText("after", `
1361
+ withJson(boards.command("export <board>").description("Render a Board to an image, or an animation to a frame sequence").requiredOption("-o, --out <file>", "Output file; the extension picks the format. Sequences need %d, e.g. frames/%04d.png").option("--at <time>", "A moment, comma-separated moments, start:end:step, or start:end with --fps").option("--camera", "Follow the animation camera").option("--size <widthxheight>", "Camera output in pixels, the animation's viewport by default; frames keep their own size").option("--animation <id>", "Animation the --at times refer to").option("--frame <item-id>", "Export one frame as a page").option("--items <ids>", "Comma-separated item ids").option("--rect <rect>", "World rect as x,y,width,height").option("--scale <factor>", "Output pixels per board unit", "2").option("--padding <units>", "Padding around the content in board units").option("--theme <name>", `Cohub theme: ${BOARD_THEME_IDS.join(", ")}`, "dark").option("--paper <mode>", "Output paper: paper or transparent", "paper").option("--format <format>", `Override the format (${BOARD_EXPORT_FORMATS.join(", ")}, ${BOARD_VIDEO_FORMATS.join(", ")})`).option("--quality <q>", "JPEG/WebP quality from 0 to 1", "0.92").option("--fps <rate>", "Frames a second for --at start:end; a video plays at it (defaults to the --at step)").option("--image-memory <mib>", "Decoded image memory budget in MiB", String(256)).option("--no-images", "Draw placeholders instead of downloading images").option("--renderer <renderer>", "auto draws in Node and uses local Chrome for shaders; canvas or gpu forces one", "auto").option("--force", "Replace existing output files").option("--timeout <time>", "Fail a frame that takes longer, naming the scripts still running", "2m").option("--inputs <file>", "A Space file of recorded browser input for scripts to replay from time 0").option("--async", "Run as a Task in the Space's sandbox and return at once; paths are Space paths")).addHelpText("after", `
1343
1362
  Shaders draw in a shared headless Chrome that stays up a few minutes between calls;
1344
1363
  Boards without shaders never start it. Set COHUB_BOARD_GPU_DAEMON=0 to start one per call.
1345
1364
 
1346
1365
  Examples:
1347
1366
  cohub boards export plan.board -o plan.png
1348
- cohub boards export plan.board --animation intro --at 0:20s:40ms -o intro.mp4 --async
1367
+ cohub boards export plan.board --animation intro --at 0:20s --fps 24 -o intro.mp4 --async
1349
1368
  cohub boards export plan.board --frame s2 -o slide-2.png
1350
1369
  cohub boards export plan.board --animation lecture --at 4.5s -o moment.png
1351
1370
  cohub boards export plan.board --animation lecture --at 0:6s:40ms -o frames/%04d.png
@@ -1360,11 +1379,15 @@ page: its fill and shaders, without its outline and label.`).action(async (targe
1360
1379
  process.once("SIGINT", cancel);
1361
1380
  try {
1362
1381
  const out = options.out;
1363
- const times = options.at ? parseBoardTimes(options.at) : void 0;
1382
+ const rate = options.fps ? parseNumber(options.fps, "--fps", {
1383
+ min: .01,
1384
+ max: 240
1385
+ }) : void 0;
1386
+ const times = options.at ? parseBoardTimes(options.at, "--at", 1e4, rate) : void 0;
1364
1387
  let camera;
1365
1388
  if (options.camera) {
1366
1389
  if (!options.animation || !times) throw new Error("--camera needs --animation and --at.");
1367
- camera = parseSize(options.size ?? "1600x900");
1390
+ camera = options.size ? parseSize(options.size) : "viewport";
1368
1391
  }
1369
1392
  const progress = (completed, total) => {
1370
1393
  if (!jsonRequested(options) && (completed === total || completed % 30 === 0)) process.stderr.write(`Rendered ${completed}/${total} frames\n`);
@@ -1388,10 +1411,7 @@ page: its fill and shaders, without its outline and label.`).action(async (targe
1388
1411
  if (videoFormat) {
1389
1412
  if (!times || times.length < 2) throw new Error("Video export needs an --at range.");
1390
1413
  const step = times[1] - times[0];
1391
- const fps = options.fps ? parseNumber(options.fps, "--fps", {
1392
- min: .01,
1393
- max: 240
1394
- }) : 1e3 / step;
1414
+ const fps = rate ?? 1e3 / step;
1395
1415
  if (existsSync(out) && !options.force) throw new Error(`${out} already exists; use --force to replace it.`);
1396
1416
  await mkdir(dirname(out), { recursive: true });
1397
1417
  const { runBoardVideoExport } = await import("./board-export2.js");
@@ -1504,11 +1524,15 @@ Steps are {"steps": [...]}, points in board coordinates, run on a virtual clock:
1504
1524
  {"wait": "500ms"} {"tool": "draw"} {"tap": [x, y]} {"drag": [[x, y], ...], "pointerType": "pen"}
1505
1525
  {"pointer": "down", "at": [x, y]} {"key": "Enter"} {"select": ["id"]}
1506
1526
  {"input": "browser:devicemotion", "data": {...}} {"inputs": "takes/flick.json"}
1527
+ {"peers": [{"name": "Ada", "at": [x, y], "pressed": true}]}
1528
+ {"broadcast": "burst", "to": "<script id>", "data": {...}, "from": "Ada"}
1507
1529
  {"tool": "play"} acts like an App visitor: drags move unlocked items, empty space pans,
1508
1530
  script regions take every press, and keys reach scripts that listen for them.
1509
1531
  Every source (motion, gamepad, microphone, camera, location) is on. An input step
1510
1532
  delivers one browser event to the scripts listening, shaped as \`cohub boards schema
1511
1533
  script\` describes; an inputs step replays a recording on the virtual clock.
1534
+ A peers step sets the other viewers scripts see in ctx.peers; a broadcast step delivers
1535
+ another viewer's ctx.broadcast() to a script. What the scripts broadcast is reported.
1512
1536
 
1513
1537
  Shaders are compiled with a local Chrome, Chromium or Edge when one is found, before
1514
1538
  the steps run; their errors join the scripts' errors and stop the run.
@@ -1558,6 +1582,7 @@ Examples:
1558
1582
  const changed = Object.keys(result.changes.items ?? {}).length;
1559
1583
  ok(`Simulated ${formatBoardTime(result.time)}: ${result.commits} commit${result.commits === 1 ? "" : "s"}, ${changed} item${changed === 1 ? "" : "s"} changed (not saved)`);
1560
1584
  for (const press of result.presses) console.log(` step ${press.step + 1}: ${describePress(press)}`);
1585
+ if (result.broadcasts.length) console.log(` ${result.broadcasts.length} broadcast${result.broadcasts.length === 1 ? "" : "s"}: ${[...new Set(result.broadcasts.map(({ owner, type }) => `${owner} "${type}"`))].join(", ")}`);
1561
1586
  for (const [id, message] of Object.entries(result.errors)) console.log(` ! ${id}: ${message.split("\n")[0]}`);
1562
1587
  for (const warning of result.warnings) console.log(` ! ${warning}`);
1563
1588
  if (result.shaders && !result.shaders.compiled) console.log(" Shaders were checked but not compiled; install Chrome, Chromium or Edge, or set COHUB_CHROME, to compile them.");
@@ -1751,7 +1776,7 @@ Times are milliseconds; 500ms, 12.5s and 2m also work on the command line.`);
1751
1776
  handleHttp(cause);
1752
1777
  }
1753
1778
  });
1754
- withJson(boards.command("apply <board> [patch]").description("Merge a patch into the Board: fields merge, null deletes").option("-i, --input <file>", "Patch JSON; - for stdin").option("--replace", "Make the document equal to the input instead of merging").option("--cascade", "Also delete children and tracks of deleted items, and tracks of deleted Board scripts").option("--dry-run", "Validate without writing").option("--base-version <n>", "Fail if the Board moved past this version").option("--mutation-id <id>", "Stable id; retries never apply twice")).addHelpText("after", `
1779
+ withJson(boards.command("apply <board> [patch]").description("Merge a patch into the Board: fields merge, null deletes").option("-i, --input <file>", "Patch JSON; - for stdin").option("--replace", "Make the document equal to the input instead of merging; a Board with items needs --base-version").option("--cascade", "Also delete children and tracks of deleted items, and tracks of deleted Board scripts").option("--dry-run", "Validate without writing").option("--base-version <n>", "Fail if the Board moved past this version").option("--mutation-id <id>", "Stable id; retries never apply twice")).addHelpText("after", `
1755
1780
  cohub boards apply plan.board '{"items":{"t1":{"type":"text","props":{"text":"Hi","fontSize":48}}}}'
1756
1781
  cohub boards apply plan.board '{"items":{"t1":{"position":{"x":200}}}}'
1757
1782
  cohub boards apply plan.board '{"items":{"t1":null}}'
@@ -1760,6 +1785,18 @@ Times are milliseconds; 500ms, 12.5s and 2m also work on the command line.`);
1760
1785
  const spaceId = await resolveSpace(boards);
1761
1786
  const board = await boardClient(boards, target, spaceId);
1762
1787
  const read = await readPatch(inline, options.input, BOARD_TRANSACTION_INPUT_MAX_BYTES);
1788
+ let baseVersion = options.baseVersion === void 0 ? void 0 : parseNumber(options.baseVersion, "--base-version", {
1789
+ min: 0,
1790
+ integer: true
1791
+ });
1792
+ if (options.replace && !options.dryRun && baseVersion === void 0) {
1793
+ const current = await board.get({
1794
+ only: ["items"],
1795
+ limit: 1
1796
+ });
1797
+ if (Object.keys(current.items ?? {}).length) throw new Error(`--replace deletes everything the input leaves out of "${current.title ?? current.id}" (${current.id}, version ${current.version}). Pass --base-version ${current.version} to replace it.`);
1798
+ baseVersion = current.version;
1799
+ }
1763
1800
  const patch = await settleBoardPatch(spaceId, read, async (items) => options.replace ? {} : board.get({
1764
1801
  only: ["items"],
1765
1802
  items
@@ -1768,10 +1805,7 @@ Times are milliseconds; 500ms, 12.5s and 2m also work on the command line.`);
1768
1805
  ...options.replace ? { replace: true } : {},
1769
1806
  ...options.cascade ? { cascade: true } : {},
1770
1807
  ...options.dryRun ? { dryRun: true } : {},
1771
- ...options.baseVersion === void 0 ? {} : { baseVersion: parseNumber(options.baseVersion, "--base-version", {
1772
- min: 0,
1773
- integer: true
1774
- }) },
1808
+ ...baseVersion === void 0 ? {} : { baseVersion },
1775
1809
  ...options.mutationId ? { mutationId: options.mutationId } : {}
1776
1810
  });
1777
1811
  if (jsonRequested(options)) return json(result);
@@ -1303,14 +1303,18 @@ var BillingApi = class {
1303
1303
  this.transport = transport;
1304
1304
  }
1305
1305
  async getCredits(input) {
1306
- const query = input?.tokenType ? `?tokenType=${encodeURIComponent(input.tokenType)}` : "";
1307
- return this.transport.request(`/api/billing/credits${query}`);
1306
+ const params = new URLSearchParams();
1307
+ if (input?.tokenType) params.set("tokenType", input.tokenType);
1308
+ if (input?.includeExhausted) params.set("include", "exhausted");
1309
+ const query = params.toString();
1310
+ return this.transport.request(`/api/billing/credits${query ? `?${query}` : ""}`);
1308
1311
  }
1309
1312
  async getBalanceActivities(input) {
1310
1313
  const params = new URLSearchParams();
1311
1314
  if (input?.tokenType) params.set("tokenType", input.tokenType);
1312
- if (input?.page) params.set("page", String(input.page));
1315
+ if (input?.cursor) params.set("cursor", input.cursor);
1313
1316
  if (input?.limit) params.set("limit", String(input.limit));
1317
+ if (input?.filter) params.set("filter", input.filter);
1314
1318
  const query = params.toString();
1315
1319
  return this.transport.request(`/api/billing/balance-activities${query ? `?${query}` : ""}`);
1316
1320
  }
@@ -2991,8 +2995,9 @@ var SpaceWalletApi = class {
2991
2995
  funding() {
2992
2996
  return this.transport.request(`/api/spaces/${this.spaceId}/wallet/funding`);
2993
2997
  }
2994
- activities(page = 1) {
2995
- return this.transport.request(`/api/spaces/${this.spaceId}/wallet/activities?page=${page}`);
2998
+ activities(cursor) {
2999
+ const query = cursor ? `?cursor=${encodeURIComponent(cursor)}` : "";
3000
+ return this.transport.request(`/api/spaces/${this.spaceId}/wallet/activities${query}`);
2996
3001
  }
2997
3002
  createOrder(input) {
2998
3003
  return this.transport.request(`/api/spaces/${this.spaceId}/wallet/orders`, {
@@ -6988,6 +6993,14 @@ var TasksApi = class {
6988
6993
  };
6989
6994
  //#endregion
6990
6995
  //#region ../sdk/src/apis/user.ts
6996
+ function userListQuery(options) {
6997
+ const params = new URLSearchParams();
6998
+ if (options.filter) params.set("filter", options.filter);
6999
+ if (options.cursor) params.set("cursor", options.cursor);
7000
+ if (options.limit !== void 0) params.set("limit", String(options.limit));
7001
+ const query = params.toString();
7002
+ return query ? `?${query}` : "";
7003
+ }
6991
7004
  const usageDate = (value) => value instanceof Date ? value.toISOString() : value;
6992
7005
  var UserApi = class {
6993
7006
  transport;
@@ -7033,6 +7046,12 @@ var UserApi = class {
7033
7046
  const query = params.toString();
7034
7047
  return this.transport.request(`/api/me/sessions${query ? `?${query}` : ""}`, { fetch });
7035
7048
  }
7049
+ listApps(options = {}) {
7050
+ return this.transport.request(`/api/me/apps${userListQuery(options)}`);
7051
+ }
7052
+ listCronJobs(options = {}) {
7053
+ return this.transport.request(`/api/me/cron-jobs${userListQuery(options)}`);
7054
+ }
7036
7055
  getSession(sessionId, customFetch) {
7037
7056
  return this.transport.request(`/api/sessions/${sessionId}`, { fetch: customFetch });
7038
7057
  }
@@ -1,4 +1,5 @@
1
1
  import { C as error, D as json, E as handleHttp, O as jsonRequested, j as table, k as ok, t as createClient } from "./client.js";
2
+ import { n as isUserCronJobFilter } from "./user-lists.js";
2
3
  import { readFileSync } from "node:fs";
3
4
  //#region src/commands/cron-jobs.ts
4
5
  function readJsonObject(pathOrJson) {
@@ -9,13 +10,50 @@ function readJsonObject(pathOrJson) {
9
10
  }
10
11
  function registerCronJobs(program) {
11
12
  const cmd = program.command("cron-jobs").description("Scheduled jobs");
12
- cmd.command("ls [spaceId]").alias("list").description("List scheduled jobs").option("--json", "Output as JSON").action(async (spaceId, opts) => {
13
+ cmd.command("ls [spaceId]").alias("list").description("List scheduled jobs in a space, or yours across spaces").option("--filter <filter>", "Without a space: mine, all, paused, or attention", "mine").option("--cursor <cursor>", "Without a space: pagination cursor").option("--json", "Output as JSON").action(async (spaceId, opts) => {
13
14
  const client = createClient();
14
15
  try {
15
- const result = await client.cronJobs.list(spaceId);
16
+ if (spaceId) {
17
+ const result = await client.cronJobs.list(spaceId);
18
+ if (jsonRequested(opts)) return json(result);
19
+ if (result.jobs.length === 0) return console.log(" (empty)");
20
+ table(result.jobs, [
21
+ {
22
+ key: "id",
23
+ label: "ID"
24
+ },
25
+ {
26
+ key: "title",
27
+ label: "Title"
28
+ },
29
+ {
30
+ key: "taskType",
31
+ label: "Type"
32
+ },
33
+ {
34
+ key: "cronExpression",
35
+ label: "Schedule"
36
+ },
37
+ {
38
+ key: "enabled",
39
+ label: "Enabled"
40
+ }
41
+ ]);
42
+ return;
43
+ }
44
+ if (!isUserCronJobFilter(opts.filter)) error("Invalid filter", "Expected mine, all, paused, or attention");
45
+ const result = await client.user.listCronJobs({
46
+ filter: opts.filter,
47
+ cursor: opts.cursor
48
+ });
16
49
  if (jsonRequested(opts)) return json(result);
17
- if (result.jobs.length === 0) return console.log(" (empty)");
18
- table(result.jobs, [
50
+ if (result.items.length === 0) return console.log(" (empty)");
51
+ table(result.items.map((job) => ({
52
+ ...job,
53
+ spaceName: job.space?.name ?? "-",
54
+ lastRunStatus: job.lastRun?.status ?? "-",
55
+ nextRun: job.nextRunAt ?? "-"
56
+ })), [
19
57
  {
20
58
  key: "id",
21
59
  label: "ID"
@@ -25,8 +63,8 @@ function registerCronJobs(program) {
25
63
  label: "Title"
26
64
  },
27
65
  {
28
- key: "taskType",
29
- label: "Type"
66
+ key: "spaceName",
67
+ label: "Space"
30
68
  },
31
69
  {
32
70
  key: "cronExpression",
@@ -37,10 +75,19 @@ function registerCronJobs(program) {
37
75
  label: "Enabled"
38
76
  },
39
77
  {
40
- key: "spaceId",
41
- label: "Space"
78
+ key: "nextRun",
79
+ label: "Next run"
80
+ },
81
+ {
82
+ key: "lastRunStatus",
83
+ label: "Last run"
84
+ },
85
+ {
86
+ key: "access",
87
+ label: "Access"
42
88
  }
43
89
  ]);
90
+ if (result.pageInfo.nextCursor) console.log(`\n More: --cursor ${result.pageInfo.nextCursor}`);
44
91
  } catch (e) {
45
92
  handleHttp(e);
46
93
  }
@@ -41,7 +41,9 @@ const PERMISSIONS = [
41
41
  "user.space.list",
42
42
  "user.session.list",
43
43
  "user.taskrun.list",
44
- "user.usage.read"
44
+ "user.usage.read",
45
+ "user.app.list",
46
+ "user.cronjob.list"
45
47
  ];
46
48
  //#endregion
47
49
  //#region ../sdk/src/environment.ts
package/dist/chunks/id.js CHANGED
@@ -6,6 +6,10 @@ const BOARD_PAGE_SIZE = {
6
6
  width: 960,
7
7
  height: 540
8
8
  };
9
+ const BOARD_CAMERA_VIEWPORT = {
10
+ width: 1600,
11
+ height: 900
12
+ };
9
13
  const BOARD_TEXT_SCALE = {
10
14
  title: 56,
11
15
  heading: 40,
@@ -827,7 +831,11 @@ const BoardAnimationHeaderSchema = object({
827
831
  delay: nonNegative.default(0),
828
832
  loop: boolean().default(false),
829
833
  end: _enum(["hold", "reset"]).default("hold").describe("hold keeps the last frame; reset returns to the start."),
830
- markers: array(BoardMarkerSchema).max(1e4).default([]).describe("Labeled points on this timeline; a nested animation's markers do not carry over.")
834
+ markers: array(BoardMarkerSchema).max(1e4).default([]).describe("Labeled points on this timeline; a nested animation's markers do not carry over."),
835
+ viewport: object({
836
+ width: number().int().positive().max(8192),
837
+ height: number().int().positive().max(8192)
838
+ }).strict().optional().describe(`Screen pixels the camera tracks are framed for, ${BOARD_CAMERA_VIEWPORT.width}x${BOARD_CAMERA_VIEWPORT.height} by default. Every screen and export shows that framing, scaled to fit.`)
831
839
  }).strict();
832
840
  BoardAnimationHeaderSchema.extend({ tracks: record(BoardKeySchema, BoardTrackSchema).default({}) }).strict();
833
841
  const BOARD_ENTER_PRESETS = [
@@ -1837,6 +1845,28 @@ function error(path, code, message) {
1837
1845
  message
1838
1846
  };
1839
1847
  }
1848
+ const OUTLINE = [
1849
+ "fill",
1850
+ "fillOpacity",
1851
+ "stroke",
1852
+ "strokeWidth",
1853
+ "dash",
1854
+ "radius",
1855
+ "trim"
1856
+ ];
1857
+ function undrawnStyle(id, item, body, created) {
1858
+ const [undrawn, reason] = item.type === "text" ? [OUTLINE.filter((key) => key !== "fill"), "text draws only its fill color"] : item.type === "file" ? [OUTLINE, "file cards follow the theme"] : item.type === "frame" && item.props.decoration === "none" ? [OUTLINE, "a frame with decoration \"none\" draws no box; put a shape inside it instead"] : [[], ""];
1859
+ const style = isRecord(body.style) ? body.style : {};
1860
+ const all = created || isRecord(body.props) && "decoration" in body.props;
1861
+ const keys = undrawn.filter((key) => item.style[key] !== void 0 && (all || key in style));
1862
+ if (!keys.length) return null;
1863
+ return {
1864
+ severity: "warning",
1865
+ code: "STYLE_NOT_DRAWN",
1866
+ path: `items.${id}.style`,
1867
+ message: `${keys.join(", ")} ${keys.length === 1 ? "has" : "have"} no effect: ${reason}.`
1868
+ };
1869
+ }
1840
1870
  function stripId(value) {
1841
1871
  if (!("id" in value)) return value;
1842
1872
  const { id: _id, ...rest } = value;
@@ -1850,6 +1880,7 @@ function applyBoardPatch(state, input, options = {}) {
1850
1880
  };
1851
1881
  const patch = parsedPatch.data;
1852
1882
  const diagnostics = [];
1883
+ const warnings = [];
1853
1884
  const keep = (existing) => options.keepUnknown ? keepAllBoardFields : existing ? keepBoardFieldsOf(existing) : void 0;
1854
1885
  const nextItems = /* @__PURE__ */ new Map();
1855
1886
  const nextAnimations = /* @__PURE__ */ new Map();
@@ -1897,6 +1928,8 @@ function applyBoardPatch(state, input, options = {}) {
1897
1928
  }
1898
1929
  if (current && boardJsonEquals(current, parsed.item)) continue;
1899
1930
  nextItems.set(id, parsed.item);
1931
+ const warning = undrawnStyle(id, parsed.item, body, replacing);
1932
+ if (warning) warnings.push(warning);
1900
1933
  }
1901
1934
  for (const [id, value] of Object.entries(patch.animations ?? {})) {
1902
1935
  if (value === null) {
@@ -2109,7 +2142,7 @@ function applyBoardPatch(state, input, options = {}) {
2109
2142
  ok: true,
2110
2143
  before: withoutEmpty(before),
2111
2144
  after: withoutEmpty(after),
2112
- diagnostics: []
2145
+ diagnostics: warnings
2113
2146
  };
2114
2147
  }
2115
2148
  function validateTrack(path, animationId, value, item, animation, track, script, state, keepUnknownProperty = false) {
@@ -2413,4 +2446,4 @@ function createBoardItemId() {
2413
2446
  return `item_${createBoardEntityId()}`;
2414
2447
  }
2415
2448
  //#endregion
2416
- export { BoardAnimationHeaderSchema as $, invertMatrix as A, taskArtifactPreviewUrl as B, clampBoardFontSize as C, estimateTextWidth as D, drawSampleRadius as E, pointsRect as F, BOARD_COLOR_TOKENS as G, isBoardPath as H, scaleVector as I, BOARD_EXTENSION_TYPE_PATTERN as J, BOARD_EFFECT_KINDS as K, setBoardTextLayouter as L, layoutBoardText as M, matrixRotation as N, fitBoardMediaSize as O, multiplyMatrix as P, BOARD_SHAPE_GEOMETRIES as Q, sideAnchor as R, bendControl as S, clampBoardStrokeSize as St, drawPointsBounds as T, parseBoardManifest as U, BOARD_CLIPBOARD_KIND as V, BOARD_CAMERA_TARGET as W, BOARD_ITEM_TYPES as X, BOARD_ITEM_SCHEMAS as Y, BOARD_SHADOW_DEFAULTS as Z, IDENTITY_MATRIX as _, BOARD_MONO_FONT_STACK as _t, isTextMime as a, BoardSettingsSchema as at, arrowBindings as b, BOARD_TEXT_SCALE as bt, normalizeMime as c, hasAuthoredSize as ct, diffMergePatch as d, parseBoardMediaSource as dt, BoardColorSchema as et, listBoardProperties as f, isPublicBoardRemoteAddress as ft, resolveBoardProperty as g, BOARD_FONT_STACK as gt, pruneBoardTrack as h, BOARD_DEFAULT_SIZES as ht, isModelMime as i, BoardScriptSchema as it, isArrowBinding as j, framePoint as k, applyBoardDelta as l, isBuiltinItemType as lt, parseBoardDocument as m, BOARD_ARROW_STROKE_SIZE as mt, createBoardItemId as n, BoardIdSchema as nt, mimeTypeForPath as o, BoardTrackSchema as ot, mergePatch as p, normalizeBoardRemoteUrl as pt, BOARD_EFFECT_KIND_INFO as q, sameJson as r, BoardKeySchema as rt, modelFormatForPath as s, boardItemPreview as st, createBoardEntityId as t, BoardExtensionItemSchema as tt, applyBoardPatchToDocument as u, parseBoardItem as ut, adoptBoardNaturalSize as v, BOARD_PAGE_SIZE as vt, createBoardLayout as w, autoAnchorSide as x, boardDefaultSize as xt, applyMatrix as y, BOARD_TEXT_FONT_FAMILY as yt, featuredTaskArtifact as z };
2449
+ export { BoardAnimationHeaderSchema as $, invertMatrix as A, taskArtifactPreviewUrl as B, clampBoardFontSize as C, clampBoardStrokeSize as Ct, estimateTextWidth as D, drawSampleRadius as E, pointsRect as F, BOARD_COLOR_TOKENS as G, isBoardPath as H, scaleVector as I, BOARD_EXTENSION_TYPE_PATTERN as J, BOARD_EFFECT_KINDS as K, setBoardTextLayouter as L, layoutBoardText as M, matrixRotation as N, fitBoardMediaSize as O, multiplyMatrix as P, BOARD_SHAPE_GEOMETRIES as Q, sideAnchor as R, bendControl as S, boardDefaultSize as St, drawPointsBounds as T, parseBoardManifest as U, BOARD_CLIPBOARD_KIND as V, BOARD_CAMERA_TARGET as W, BOARD_ITEM_TYPES as X, BOARD_ITEM_SCHEMAS as Y, BOARD_SHADOW_DEFAULTS as Z, IDENTITY_MATRIX as _, BOARD_FONT_STACK as _t, isTextMime as a, BoardSettingsSchema as at, arrowBindings as b, BOARD_TEXT_FONT_FAMILY as bt, normalizeMime as c, hasAuthoredSize as ct, diffMergePatch as d, parseBoardMediaSource as dt, BoardColorSchema as et, listBoardProperties as f, isPublicBoardRemoteAddress as ft, resolveBoardProperty as g, BOARD_DEFAULT_SIZES as gt, pruneBoardTrack as h, BOARD_CAMERA_VIEWPORT as ht, isModelMime as i, BoardScriptSchema as it, isArrowBinding as j, framePoint as k, applyBoardDelta as l, isBuiltinItemType as lt, parseBoardDocument as m, BOARD_ARROW_STROKE_SIZE as mt, createBoardItemId as n, BoardIdSchema as nt, mimeTypeForPath as o, BoardTrackSchema as ot, mergePatch as p, normalizeBoardRemoteUrl as pt, BOARD_EFFECT_KIND_INFO as q, sameJson as r, BoardKeySchema as rt, modelFormatForPath as s, boardItemPreview as st, createBoardEntityId as t, BoardExtensionItemSchema as tt, applyBoardPatchToDocument as u, parseBoardItem as ut, adoptBoardNaturalSize as v, BOARD_MONO_FONT_STACK as vt, createBoardLayout as w, autoAnchorSide as x, BOARD_TEXT_SCALE as xt, applyMatrix as y, BOARD_PAGE_SIZE as yt, featuredTaskArtifact as z };
package/dist/chunks/me.js CHANGED
@@ -9,6 +9,7 @@ function parseInteger(value, name, min) {
9
9
  }
10
10
  return parsed;
11
11
  }
12
+ const usd = (value) => `${value < 0 ? "-" : ""}$${Math.abs(value).toFixed(2)}`;
12
13
  function registerMe(program) {
13
14
  const meCmd = program.command("me").description("Account-level data across your spaces");
14
15
  meCmd.command("sessions").alias("list-sessions").description("List sessions you created across all spaces (archived sessions are hidden by default)").option("--limit <n>", "Maximum number of sessions (default 20)").option("--cursor <cursor>", "Pagination cursor from a previous result").option("--archived", "List only archived sessions").option("--all", "Include archived sessions").option("--json", "Output as JSON").action(async (opts) => {
@@ -51,34 +52,63 @@ function registerMe(program) {
51
52
  handleHttp(e);
52
53
  }
53
54
  });
54
- meCmd.command("billing-activity").description("List your personal wallet activity, including generation reserves and refunds").option("--page <n>", "Page number (default 1)").option("--json", "Output as JSON").action(async (opts) => {
55
+ meCmd.command("billing").description("Show your balance, current plan, and credits expiring soon").option("--json", "Output as JSON").action(async (opts) => {
55
56
  const client = createClient();
56
57
  try {
57
- const { activities } = await client.billing.getBalanceActivities({ page: opts.page ? parseInteger(opts.page, "page", 1) : void 0 });
58
- if (jsonRequested(opts)) return json(activities);
59
- if (activities.items.length === 0) {
60
- console.log(" (empty)");
58
+ const [credits, { catalog }] = await Promise.all([client.billing.getCredits(), client.billing.getCatalog()]);
59
+ const plan = catalog.currentSubscriptions.find((item) => item.status === "active" || item.status === "trialing") ?? catalog.currentSubscriptions.find((item) => item.status === "past_due") ?? null;
60
+ if (jsonRequested(opts)) return json({
61
+ credits,
62
+ plan
63
+ });
64
+ if (!catalog.billing.configured) {
65
+ console.log(" Billing is not enabled on this server");
61
66
  return;
62
67
  }
68
+ console.log(` Balance ${usd(credits.netUsd)}`);
69
+ const period = plan?.currentPeriodEnd ? `, ${plan.cancelAtPeriodEnd ? "ends" : "renews"} ${formatLocalDateTime(plan.currentPeriodEnd)}` : "";
70
+ console.log(` Plan ${plan ? `${plan.productName ?? plan.productKey} (${plan.status}${period})` : "Free"}`);
71
+ for (const group of credits.groups) if (group.key === "lt_7d" || group.key === "lt_30d") console.log(` Expiring ${usd(group.remainingAmountUsd)} within ${group.key === "lt_7d" ? 7 : 30} days`);
72
+ } catch (e) {
73
+ handleHttp(e);
74
+ }
75
+ });
76
+ meCmd.command("billing-activity").description("List your personal wallet activity, newest first").option("--filter <filter>", "Only show usage, grant, or refund activity").option("--limit <n>", "Activities per page (default 50, max 100)").option("--cursor <cursor>", "Pagination cursor from a previous result").option("--json", "Output as JSON").action(async (opts) => {
77
+ if (opts.filter && ![
78
+ "usage",
79
+ "grant",
80
+ "refund"
81
+ ].includes(opts.filter)) {
82
+ process.stderr.write("\n ✗ Invalid filter\n filter must be usage, grant, or refund\n\n");
83
+ process.exit(1);
84
+ }
85
+ const client = createClient();
86
+ try {
87
+ const { activities } = await client.billing.getBalanceActivities({
88
+ filter: opts.filter,
89
+ limit: opts.limit ? parseInteger(opts.limit, "limit", 1) : void 0,
90
+ cursor: opts.cursor ?? null
91
+ });
92
+ if (jsonRequested(opts)) return json(activities);
63
93
  table(activities.items, [
64
94
  {
65
95
  key: "title",
66
96
  label: "Activity"
67
97
  },
68
98
  {
69
- key: "amountUsd",
70
- label: "Amount (USD)"
99
+ key: "description",
100
+ label: "Detail"
71
101
  },
72
102
  {
73
- key: "operationId",
74
- label: "Operation"
103
+ key: "amountUsd",
104
+ label: "Amount (USD)"
75
105
  },
76
106
  {
77
107
  key: "createdAt",
78
108
  label: "Date"
79
109
  }
80
110
  ]);
81
- if (activities.pagination.hasMore) console.log(` More: --page ${activities.page + 1}`);
111
+ if (activities.nextCursor) console.log(`\n More: --cursor ${activities.nextCursor}`);
82
112
  } catch (e) {
83
113
  handleHttp(e);
84
114
  }