vizmatic 0.3.2 → 0.5.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.
Files changed (150) hide show
  1. package/PROMPT.md +75 -525
  2. package/README.md +87 -578
  3. package/ROADMAP.md +49 -67
  4. package/SCIENCE.md +250 -0
  5. package/assets/THIRD_PARTY_LICENSES.md +40 -1
  6. package/assets/fonts/InstrumentSerif-Italic.ttf +0 -0
  7. package/assets/fonts/InstrumentSerif-Regular.ttf +0 -0
  8. package/assets/licenses/raster-codecs-MIT.txt +74 -0
  9. package/dist/chunk-3F2VQ7NW.js +1 -0
  10. package/dist/chunk-4XE64I2U.js +755 -0
  11. package/dist/chunk-JHHPLALU.js +79 -0
  12. package/dist/chunk-LTX44BAE.js +112 -0
  13. package/dist/chunk-MLKGABMK.js +9 -0
  14. package/dist/chunk-PSBF4TEK.js +1 -0
  15. package/dist/chunk-RPAHMKAR.js +605 -0
  16. package/dist/chunk-RWF4VBUL.js +3617 -0
  17. package/dist/chunk-WHT6HRMX.js +4201 -0
  18. package/dist/cli.js +371 -10
  19. package/dist/index.cjs +11129 -2922
  20. package/dist/index.d.cts +1225 -369
  21. package/dist/index.d.ts +1225 -369
  22. package/dist/index.js +6220 -3015
  23. package/dist/math-LXB4FH4E.js +7 -0
  24. package/dist/math-QVCETQDQ.js +1 -0
  25. package/dist/scene-browser-assets.d.ts +38 -0
  26. package/dist/scene-browser-assets.js +53 -0
  27. package/dist/scene-browser-chunks/chunk-5MVLYGXM.js +70 -0
  28. package/dist/scene-browser-chunks/chunk-ASXKN3NU.js +1 -0
  29. package/dist/scene-browser-chunks/chunk-CM5Y5LZP.js +1 -0
  30. package/dist/scene-browser-chunks/chunk-DP7NB4EW.js +6 -0
  31. package/dist/scene-browser-chunks/emscripten-module.browser-M5AEKJGE.js +1 -0
  32. package/dist/scene-browser-chunks/ffi-FL6ORJU3.js +1 -0
  33. package/dist/scene-browser-chunks/module-ES6BEMUI-JD5S5VKR.js +1 -0
  34. package/dist/scene-browser-chunks/module-asyncify-2EFITU5U-HWPFJFJC.js +1 -0
  35. package/dist/scene-browser-chunks/scene-browser-layout-M3XSXMV4.js +27 -0
  36. package/dist/scene-browser.d.ts +117 -0
  37. package/dist/scene-browser.js +220 -0
  38. package/dist/scene-cli.d.ts +1 -0
  39. package/dist/scene-cli.js +4 -0
  40. package/dist/scene-runtime.cjs +995 -0
  41. package/dist/scene-runtime.d.cts +81 -0
  42. package/dist/scene-runtime.d.ts +81 -0
  43. package/dist/scene-runtime.js +22 -0
  44. package/dist/server-2FYHZ4UO.js +331 -0
  45. package/dist/stage-browser/browser.d.ts +2482 -0
  46. package/dist/stage-browser/chunk-SQE76S5B.js +1 -0
  47. package/dist/stage-browser/chunk-VZNL6JY2.js +59 -0
  48. package/dist/stage-browser/dagre.esm-N2NIVIAZ.js +6 -0
  49. package/dist/stage-browser/math-4WFNHVV2.js +18 -0
  50. package/dist/stage-browser/stage.js +19 -0
  51. package/dist/stage-export.cjs +4950 -0
  52. package/dist/stage-export.d.cts +112 -0
  53. package/dist/stage-export.d.ts +112 -0
  54. package/dist/stage-export.js +544 -0
  55. package/dist/stage.cjs +9745 -0
  56. package/dist/stage.d.cts +1678 -0
  57. package/dist/stage.d.ts +1678 -0
  58. package/dist/stage.js +5404 -0
  59. package/dist/svg-import-Djj2q7Pc.d.cts +742 -0
  60. package/dist/svg-import-Djj2q7Pc.d.ts +742 -0
  61. package/dist/video-CcHW1qhV.d.cts +532 -0
  62. package/dist/video-CcHW1qhV.d.ts +532 -0
  63. package/examples/README.md +18 -0
  64. package/examples/agent-pipeline.tsx +4 -4
  65. package/examples/animated-pipeline.tsx +1 -5
  66. package/examples/attention-head.tsx +12 -12
  67. package/examples/aurora-incident.tsx +4 -3
  68. package/examples/building-blocks.tsx +8 -9
  69. package/examples/catalog-charts.tsx +4 -4
  70. package/examples/catalog-content.tsx +7 -9
  71. package/examples/catalog-convolution-kernel.tsx +116 -0
  72. package/examples/catalog-data.tsx +2 -8
  73. package/examples/catalog-dataflow.tsx +5 -9
  74. package/examples/catalog-dense.tsx +80 -0
  75. package/examples/catalog-deployment.tsx +5 -11
  76. package/examples/catalog-diagrams.tsx +13 -16
  77. package/examples/catalog-drawing.tsx +7 -7
  78. package/examples/catalog-flows.tsx +4 -4
  79. package/examples/catalog-foundations.tsx +11 -11
  80. package/examples/catalog-gaussian-blur.tsx +146 -0
  81. package/examples/catalog-image-tensors.tsx +115 -0
  82. package/examples/catalog-ml.tsx +36 -31
  83. package/examples/catalog-numeric-matrices.tsx +93 -0
  84. package/examples/catalog-photo-blur.tsx +209 -0
  85. package/examples/catalog-science-ai.tsx +130 -0
  86. package/examples/catalog-science-chemistry.tsx +103 -0
  87. package/examples/catalog-science-math.tsx +93 -0
  88. package/examples/catalog-science-physics.tsx +84 -0
  89. package/examples/catalog-sequence.tsx +59 -38
  90. package/examples/data-pipeline-lineage-presentation.tsx +5 -0
  91. package/examples/data-pipeline-lineage.tsx +85 -0
  92. package/examples/daybreak-launch.tsx +1 -0
  93. package/examples/desired-quadrant.tsx +7 -8
  94. package/examples/engineering-dashboard-presentation.tsx +13 -0
  95. package/examples/engineering-dashboard.tsx +160 -0
  96. package/examples/engineering-flow.tsx +2 -4
  97. package/examples/eval-dashboard.tsx +6 -6
  98. package/examples/films/attention.ts +278 -0
  99. package/examples/films/cache-miss.ts +431 -0
  100. package/examples/films/catalog.json +132 -0
  101. package/examples/films/central-limit.ts +269 -0
  102. package/examples/films/complex-maps.ts +273 -0
  103. package/examples/films/deck-example.ts +224 -0
  104. package/examples/films/euler-circle.ts +179 -0
  105. package/examples/films/fourier-epicycles.ts +265 -0
  106. package/examples/films/gradient-descent.ts +345 -0
  107. package/examples/films/linear-maps.ts +175 -0
  108. package/examples/films/lorenz.ts +207 -0
  109. package/examples/films/pythagoras.ts +185 -0
  110. package/examples/films/taylor-series.ts +159 -0
  111. package/examples/films/vizmatic-title.ts +117 -0
  112. package/examples/llm-serving-stack-presentation.tsx +5 -0
  113. package/examples/llm-serving-stack.tsx +94 -0
  114. package/examples/model-garden.tsx +1 -0
  115. package/examples/model-router.tsx +6 -6
  116. package/examples/nccl-all-gather.tsx +3 -3
  117. package/examples/nccl-all-reduce.tsx +3 -3
  118. package/examples/nccl-all-to-all.tsx +1 -1
  119. package/examples/nccl-broadcast.tsx +1 -1
  120. package/examples/nccl-reduce-scatter.tsx +5 -5
  121. package/examples/orthogonal-routing.tsx +4 -4
  122. package/examples/pareto-frontier.tsx +9 -10
  123. package/examples/presentation-frame.tsx +6 -6
  124. package/examples/pressure-mechanism.scene.json +14 -0
  125. package/examples/production-system-map-presentation.tsx +5 -0
  126. package/examples/production-system-map.tsx +130 -0
  127. package/examples/rag-graph.tsx +7 -7
  128. package/examples/release-card.tsx +5 -5
  129. package/examples/spec-anatomy.tsx +5 -5
  130. package/examples/system-architecture.tsx +19 -32
  131. package/examples/theme-system.tsx +1 -1
  132. package/examples/token-matrix.tsx +4 -2
  133. package/examples/transparent-badge.tsx +1 -2
  134. package/examples/videos/README.md +62 -0
  135. package/examples/videos/calculus-tangent.tsx +101 -0
  136. package/examples/videos/catalyst-pathway.tsx +56 -0
  137. package/examples/videos/causal-attention.tsx +91 -0
  138. package/examples/videos/convolution-kernel.tsx +34 -0
  139. package/examples/videos/gaussian-blur.tsx +32 -0
  140. package/examples/videos/image-to-matrix.tsx +22 -0
  141. package/examples/videos/matrix-multiplication.tsx +128 -0
  142. package/examples/videos/photo-gaussian-blur.tsx +39 -0
  143. package/examples/videos/request-lifecycle.tsx +99 -0
  144. package/examples/videos/signal-to-story.tsx +126 -0
  145. package/examples/videos/wave-interference.tsx +80 -0
  146. package/examples/vizmatic-bare.d.ts +1 -0
  147. package/examples/vizmatic-hero.tsx +9 -18
  148. package/examples/website-workflow.tsx +7 -7
  149. package/examples/weekend-field-notes.tsx +3 -2
  150. package/package.json +77 -12
@@ -0,0 +1,81 @@
1
+ declare const SCENE_RUNTIME_VERSION = "vizmatic-scene/1";
2
+ declare const SCENE_LIMITS: Readonly<{
3
+ sourceBytes: 131072;
4
+ graphBytes: 2097152;
5
+ nodes: 2000;
6
+ depth: 64;
7
+ stringLength: 65536;
8
+ canvasEdge: 1920;
9
+ canvasPixels: 2073600;
10
+ duration: 120;
11
+ frames: 3600;
12
+ memoryBytes: number;
13
+ stackBytes: number;
14
+ evaluationMs: 250;
15
+ }>;
16
+ /** All scene time values, including cues and duration, are in seconds. */
17
+ interface SceneRequest {
18
+ source: string;
19
+ width: number;
20
+ height: number;
21
+ duration: number;
22
+ fps?: number;
23
+ theme?: 'dark' | 'light';
24
+ cues?: Record<string, number>;
25
+ seed?: number;
26
+ }
27
+ interface SceneFrameRequest extends SceneRequest {
28
+ time?: number;
29
+ }
30
+ interface NormalizedSceneRequest {
31
+ source: string;
32
+ width: number;
33
+ height: number;
34
+ duration: number;
35
+ fps: number;
36
+ theme: 'dark' | 'light';
37
+ cues: Record<string, number>;
38
+ seed: number;
39
+ frameCount: number;
40
+ }
41
+ type SceneJson = null | boolean | number | string | SceneJson[] | {
42
+ [key: string]: SceneJson;
43
+ };
44
+ interface SceneElement {
45
+ kind: 'vizmatic.element';
46
+ type: string;
47
+ props: {
48
+ [key: string]: SceneJson;
49
+ };
50
+ children: SceneJson[];
51
+ }
52
+
53
+ /** Explicit names keep the editable scene language separate from the Node API. */
54
+ declare const SCENE_COMPONENT_NAMES: readonly ["Arrow", "ArrowMarkerDef", "AttentionMatrix", "AxisPlot", "Badge", "BadgePill", "BarChart", "Board", "Box", "CalloutCard", "Canvas", "CanvasItem", "Card", "ChartFrame", "CodeBlock", "Column", "Comparison", "Connector", "DashedLine", "DataTable", "DataflowDiagram", "DeploymentDiagram", "DetailList", "DiagramLegend", "DonutChart", "DotPoint", "EquationCard", "FactRows", "Flow", "FlowArrow", "FreeBodyDiagram", "GeometryDiagram", "GradientChip", "GraphDiagram", "Grid", "Heatmap", "Icon", "InlineBar", "IntervalPlot", "KeyValueList", "LayeredNetwork", "Legend", "LineChart", "MathText", "Matrix", "MetricCard", "MetricStrip", "MiniBarChart", "MoleculeDiagram", "NumberLine", "Panel", "ParetoBarChart", "ParetoChart", "PieChart", "Pipeline", "PixelGrid", "ProgressList", "ProgressRow", "QuadrantChart", "ReactionEnergyDiagram", "ReactionEquation", "Row", "ScatterPlot", "Scene", "SequenceDiagram", "SmallMultiples", "Sparkline", "Stack", "StackedBar", "StatusDot", "StatusList", "StatusRow", "StepCard", "SvgFrame", "SvgMathText", "SvgPoint", "TagList", "TextLabel", "Tile", "TileGrid", "TiledMatrix", "Timeline", "TitleBar", "ToneStrip", "TransformerTopology", "TreeDiagram", "ValuePill", "VectorArrow", "VectorSegment", "WaveDiagram", "WindowFrame"];
55
+ declare const SCENE_DOM_TAGS: readonly ["div", "span", "p", "strong", "em", "b", "i", "br", "svg", "g", "path", "rect", "circle", "ellipse", "line", "polyline", "polygon", "text", "tspan", "defs", "clipPath", "linearGradient", "radialGradient", "stop", "pattern", "marker", "mask", "title", "desc", "use"];
56
+
57
+ /** Validate after the VM boundary as well as inside it. Nothing executable crosses it. */
58
+ declare function validateSceneGraph(value: unknown): SceneJson;
59
+
60
+ interface EvaluatedSceneFrame {
61
+ graph: SceneJson;
62
+ request: NormalizedSceneRequest;
63
+ time: number;
64
+ runtimeVersion: string;
65
+ sourceSha256: string;
66
+ inputSha256: string;
67
+ }
68
+ declare function prepareSceneSource(source: string): string;
69
+ interface PreparedScene {
70
+ request: NormalizedSceneRequest;
71
+ sourceSha256: string;
72
+ inputSha256: string;
73
+ /** Each call creates a fresh bounded QuickJS runtime, including serialization. */
74
+ evaluate(time?: number): Promise<EvaluatedSceneFrame>;
75
+ }
76
+ declare function prepareScene(request: SceneFrameRequest): Promise<PreparedScene>;
77
+ /** Browser Workers and Node rendering share this exact evaluator and graph contract. */
78
+ declare function evaluateSceneSource(request: SceneFrameRequest): Promise<EvaluatedSceneFrame>;
79
+
80
+ export { SCENE_COMPONENT_NAMES, SCENE_DOM_TAGS, SCENE_LIMITS, SCENE_RUNTIME_VERSION, evaluateSceneSource, prepareScene, prepareSceneSource, validateSceneGraph };
81
+ export type { EvaluatedSceneFrame, NormalizedSceneRequest, PreparedScene, SceneElement, SceneFrameRequest, SceneJson, SceneRequest };
@@ -0,0 +1,81 @@
1
+ declare const SCENE_RUNTIME_VERSION = "vizmatic-scene/1";
2
+ declare const SCENE_LIMITS: Readonly<{
3
+ sourceBytes: 131072;
4
+ graphBytes: 2097152;
5
+ nodes: 2000;
6
+ depth: 64;
7
+ stringLength: 65536;
8
+ canvasEdge: 1920;
9
+ canvasPixels: 2073600;
10
+ duration: 120;
11
+ frames: 3600;
12
+ memoryBytes: number;
13
+ stackBytes: number;
14
+ evaluationMs: 250;
15
+ }>;
16
+ /** All scene time values, including cues and duration, are in seconds. */
17
+ interface SceneRequest {
18
+ source: string;
19
+ width: number;
20
+ height: number;
21
+ duration: number;
22
+ fps?: number;
23
+ theme?: 'dark' | 'light';
24
+ cues?: Record<string, number>;
25
+ seed?: number;
26
+ }
27
+ interface SceneFrameRequest extends SceneRequest {
28
+ time?: number;
29
+ }
30
+ interface NormalizedSceneRequest {
31
+ source: string;
32
+ width: number;
33
+ height: number;
34
+ duration: number;
35
+ fps: number;
36
+ theme: 'dark' | 'light';
37
+ cues: Record<string, number>;
38
+ seed: number;
39
+ frameCount: number;
40
+ }
41
+ type SceneJson = null | boolean | number | string | SceneJson[] | {
42
+ [key: string]: SceneJson;
43
+ };
44
+ interface SceneElement {
45
+ kind: 'vizmatic.element';
46
+ type: string;
47
+ props: {
48
+ [key: string]: SceneJson;
49
+ };
50
+ children: SceneJson[];
51
+ }
52
+
53
+ /** Explicit names keep the editable scene language separate from the Node API. */
54
+ declare const SCENE_COMPONENT_NAMES: readonly ["Arrow", "ArrowMarkerDef", "AttentionMatrix", "AxisPlot", "Badge", "BadgePill", "BarChart", "Board", "Box", "CalloutCard", "Canvas", "CanvasItem", "Card", "ChartFrame", "CodeBlock", "Column", "Comparison", "Connector", "DashedLine", "DataTable", "DataflowDiagram", "DeploymentDiagram", "DetailList", "DiagramLegend", "DonutChart", "DotPoint", "EquationCard", "FactRows", "Flow", "FlowArrow", "FreeBodyDiagram", "GeometryDiagram", "GradientChip", "GraphDiagram", "Grid", "Heatmap", "Icon", "InlineBar", "IntervalPlot", "KeyValueList", "LayeredNetwork", "Legend", "LineChart", "MathText", "Matrix", "MetricCard", "MetricStrip", "MiniBarChart", "MoleculeDiagram", "NumberLine", "Panel", "ParetoBarChart", "ParetoChart", "PieChart", "Pipeline", "PixelGrid", "ProgressList", "ProgressRow", "QuadrantChart", "ReactionEnergyDiagram", "ReactionEquation", "Row", "ScatterPlot", "Scene", "SequenceDiagram", "SmallMultiples", "Sparkline", "Stack", "StackedBar", "StatusDot", "StatusList", "StatusRow", "StepCard", "SvgFrame", "SvgMathText", "SvgPoint", "TagList", "TextLabel", "Tile", "TileGrid", "TiledMatrix", "Timeline", "TitleBar", "ToneStrip", "TransformerTopology", "TreeDiagram", "ValuePill", "VectorArrow", "VectorSegment", "WaveDiagram", "WindowFrame"];
55
+ declare const SCENE_DOM_TAGS: readonly ["div", "span", "p", "strong", "em", "b", "i", "br", "svg", "g", "path", "rect", "circle", "ellipse", "line", "polyline", "polygon", "text", "tspan", "defs", "clipPath", "linearGradient", "radialGradient", "stop", "pattern", "marker", "mask", "title", "desc", "use"];
56
+
57
+ /** Validate after the VM boundary as well as inside it. Nothing executable crosses it. */
58
+ declare function validateSceneGraph(value: unknown): SceneJson;
59
+
60
+ interface EvaluatedSceneFrame {
61
+ graph: SceneJson;
62
+ request: NormalizedSceneRequest;
63
+ time: number;
64
+ runtimeVersion: string;
65
+ sourceSha256: string;
66
+ inputSha256: string;
67
+ }
68
+ declare function prepareSceneSource(source: string): string;
69
+ interface PreparedScene {
70
+ request: NormalizedSceneRequest;
71
+ sourceSha256: string;
72
+ inputSha256: string;
73
+ /** Each call creates a fresh bounded QuickJS runtime, including serialization. */
74
+ evaluate(time?: number): Promise<EvaluatedSceneFrame>;
75
+ }
76
+ declare function prepareScene(request: SceneFrameRequest): Promise<PreparedScene>;
77
+ /** Browser Workers and Node rendering share this exact evaluator and graph contract. */
78
+ declare function evaluateSceneSource(request: SceneFrameRequest): Promise<EvaluatedSceneFrame>;
79
+
80
+ export { SCENE_COMPONENT_NAMES, SCENE_DOM_TAGS, SCENE_LIMITS, SCENE_RUNTIME_VERSION, evaluateSceneSource, prepareScene, prepareSceneSource, validateSceneGraph };
81
+ export type { EvaluatedSceneFrame, NormalizedSceneRequest, PreparedScene, SceneElement, SceneFrameRequest, SceneJson, SceneRequest };
@@ -0,0 +1,22 @@
1
+ import {
2
+ SCENE_COMPONENT_NAMES,
3
+ SCENE_DOM_TAGS,
4
+ SCENE_LIMITS,
5
+ SCENE_RUNTIME_VERSION,
6
+ evaluateSceneSource,
7
+ prepareScene,
8
+ prepareSceneSource,
9
+ validateSceneGraph
10
+ } from "./chunk-4XE64I2U.js";
11
+ import "./chunk-RPAHMKAR.js";
12
+ import "./chunk-MLKGABMK.js";
13
+ export {
14
+ SCENE_COMPONENT_NAMES,
15
+ SCENE_DOM_TAGS,
16
+ SCENE_LIMITS,
17
+ SCENE_RUNTIME_VERSION,
18
+ evaluateSceneSource,
19
+ prepareScene,
20
+ prepareSceneSource,
21
+ validateSceneGraph
22
+ };
@@ -0,0 +1,331 @@
1
+ import"./chunk-PSBF4TEK.js";import{existsSync,statSync,watch}from"fs";import{readFile}from"fs/promises";import{createRequire}from"module";import{createServer}from"http";import{basename,dirname,extname,join,relative,resolve}from"path";import{spawn}from"child_process";import{fileURLToPath}from"url";function previewPage(fileName){const safeName=fileName.replace(/[<>&"]/g,"");return`<!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1">
6
+ <title>${safeName} | vizmatic preview</title>
7
+ <style>
8
+ :root { color-scheme: dark; --bg: #0b0c10; --panel: #101218; --line: #252832; --ink: #f2efe6; --dim: #a5a7ad; --faint: #5c5f68; --accent: #ffd75e; --err: #ff8d8d; }
9
+ * { box-sizing: border-box; }
10
+ html, body { height: 100%; margin: 0; background: var(--bg); color: var(--ink); font: 13px/1.45 ui-monospace, "JetBrains Mono", SFMono-Regular, Menlo, monospace; }
11
+ body { display: grid; grid-template-rows: auto minmax(0, 1fr) auto; }
12
+ button, select { font: inherit; color: inherit; background: transparent; border: 1px solid var(--line); border-radius: 6px; padding: 3px 9px; cursor: pointer; }
13
+ button:hover, select:hover { border-color: var(--faint); }
14
+ button:focus-visible, select:focus-visible, .timeline:focus-visible { outline: 2px solid var(--accent); outline-offset: 1px; }
15
+ header { display: flex; align-items: center; gap: 14px; padding: 9px 16px; border-bottom: 1px solid var(--line); min-width: 0; }
16
+ header .title { font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
17
+ header .file { color: var(--faint); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
18
+ header .spacer { flex: 1; }
19
+ header .state { color: var(--dim); white-space: nowrap; }
20
+ header .state[data-kind="busy"] { color: var(--accent); }
21
+ header .state[data-kind="error"] { color: var(--err); }
22
+ main { position: relative; display: grid; place-items: center; min-height: 0; padding: 18px; overflow: hidden; }
23
+ .frame { position: relative; line-height: 0; box-shadow: 0 0 0 1px var(--line); }
24
+ canvas { display: block; width: 100%; height: 100%; }
25
+ .overlay { position: absolute; inset: 0; pointer-events: none; }
26
+ .overlay div { position: absolute; border: 1.5px solid var(--err); background: rgba(255, 90, 90, .08); }
27
+ .overlay div[data-severity="warning"] { border-color: var(--accent); background: rgba(255, 215, 94, .06); }
28
+ .error { position: absolute; inset: 18px; overflow: auto; padding: 18px 20px; white-space: pre-wrap; color: var(--err); background: rgba(16, 8, 10, .95); border: 1px solid #5a2a2e; border-radius: 8px; }
29
+ footer { border-top: 1px solid var(--line); background: var(--panel); padding: 10px 16px 12px; display: grid; gap: 8px; }
30
+ .row { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }
31
+ .time { font-variant-numeric: tabular-nums; min-width: 12ch; }
32
+ .chapters { display: flex; gap: 6px; flex-wrap: wrap; flex: 1; min-width: 0; }
33
+ .chapters button { border-color: transparent; color: var(--dim); padding: 2px 7px; }
34
+ .chapters button[aria-current="true"] { color: var(--ink); border-color: var(--line); }
35
+ .timeline { position: relative; height: 34px; border-radius: 4px; background: #0b0c10; box-shadow: inset 0 0 0 1px var(--line); cursor: pointer; touch-action: none; overflow: hidden; }
36
+ .clip { position: absolute; top: 5px; height: 16px; border-radius: 2px; background: #27303c; overflow: hidden; color: var(--dim); font-size: 10px; line-height: 16px; padding: 0 4px; white-space: nowrap; }
37
+ .tick { position: absolute; top: 0; bottom: 0; width: 1px; background: var(--faint); }
38
+ .issue { position: absolute; bottom: 3px; height: 4px; border-radius: 2px; background: var(--err); }
39
+ .issue[data-severity="warning"] { background: var(--accent); }
40
+ .playhead { position: absolute; top: 0; bottom: 0; width: 1.5px; background: var(--accent); }
41
+ .issues { color: var(--dim); max-height: 84px; overflow: auto; display: grid; gap: 2px; }
42
+ .issues button { all: unset; cursor: pointer; display: block; }
43
+ .issues button:hover, .issues button:focus-visible { color: var(--ink); }
44
+ .issues b { font-weight: 400; color: var(--err); }
45
+ .issues b[data-severity="warning"] { color: var(--accent); }
46
+ .keys { color: var(--faint); margin-left: auto; white-space: nowrap; }
47
+ kbd { font: inherit; color: var(--dim); }
48
+ </style>
49
+ </head>
50
+ <body>
51
+ <header>
52
+ <span class="title" id="title">Loading</span>
53
+ <span class="file">${safeName}</span>
54
+ <span class="spacer"></span>
55
+ <span class="state" id="state">Compiling</span>
56
+ </header>
57
+ <main id="main">
58
+ <div class="frame" id="frame"><canvas id="canvas" role="img" aria-label="Film preview"></canvas><div class="overlay" id="overlay"></div></div>
59
+ <div class="error" id="error" role="alert" hidden></div>
60
+ </main>
61
+ <footer>
62
+ <div class="timeline" id="timeline" tabindex="0" role="slider" aria-label="Timeline" aria-valuemin="0" aria-valuenow="0"><div class="playhead" id="playhead"></div></div>
63
+ <div class="row">
64
+ <button id="toggle" type="button">Play</button>
65
+ <span class="time" id="time">0:00.00</span>
66
+ <label>Look <select id="look"></select></label>
67
+ <label>Speed <select id="speed"><option>0.25</option><option>0.5</option><option selected>1</option><option>1.5</option><option>2</option></select></label>
68
+ <label><input type="checkbox" id="loop" checked> Loop</label>
69
+ <label><input type="checkbox" id="show-issues" checked> Issues</label>
70
+ <div class="chapters" id="chapters"></div>
71
+ <span class="keys"><kbd>space</kbd> play <kbd>left/right</kbd> 1s <kbd>,/.</kbd> frame <kbd>[/]</kbd> chapter <kbd>0-9</kbd> seek</span>
72
+ </div>
73
+ <div class="issues" id="issues" hidden></div>
74
+ </footer>
75
+ <script type="module">
76
+ import { FilmPlayer, checkFilm, isFilm, LOOKS } from '/stage/stage.js'
77
+
78
+ const el = (id) => document.getElementById(id)
79
+ const params = new URLSearchParams(location.search)
80
+ const remembered = { time: Number(params.get('t')) || 0, playing: false, look: params.get('look') || '' }
81
+ const state = { player: null, film: null, definition: null, report: null, version: 0, loading: 0 }
82
+
83
+ for (const name of Object.keys(LOOKS)) el('look').append(new Option(name, name))
84
+ el('look').prepend(new Option('Film default', ''))
85
+ el('look').value = remembered.look
86
+
87
+ function setState(text, kind) {
88
+ el('state').textContent = text
89
+ el('state').dataset.kind = kind || ''
90
+ }
91
+
92
+ function showError(message) {
93
+ el('error').textContent = message
94
+ el('error').hidden = false
95
+ setState('Error', 'error')
96
+ }
97
+
98
+ function clearError() {
99
+ el('error').hidden = true
100
+ }
101
+
102
+ function clock(t) {
103
+ const m = Math.floor(t / 60)
104
+ return m + ':' + (t - m * 60).toFixed(2).padStart(5, '0')
105
+ }
106
+
107
+ function report(kind, message) {
108
+ fetch('/log', { method: 'POST', body: JSON.stringify({ kind, message }) }).catch(() => {})
109
+ }
110
+
111
+ function sizeFrame() {
112
+ const film = state.film
113
+ if (!film) return
114
+ const box = el('main').getBoundingClientRect()
115
+ const scale = Math.min((box.width - 36) / film.width, (box.height - 36) / film.height)
116
+ el('frame').style.width = Math.max(64, Math.floor(film.width * scale)) + 'px'
117
+ el('frame').style.height = Math.max(36, Math.floor(film.height * scale)) + 'px'
118
+ state.player?.resize()
119
+ }
120
+ addEventListener('resize', sizeFrame)
121
+
122
+ function drawTimeline() {
123
+ const film = state.film
124
+ const track = el('timeline')
125
+ track.querySelectorAll('.clip,.tick,.issue').forEach((node) => node.remove())
126
+ track.setAttribute('aria-valuemax', String(film.duration))
127
+ const at = (t) => (t / film.duration) * 100 + '%'
128
+ for (const clip of film.clips) {
129
+ const block = document.createElement('div')
130
+ block.className = 'clip'
131
+ block.style.left = at(clip.t0)
132
+ block.style.width = 'calc(' + ((clip.t1 - clip.t0) / film.duration) * 100 + '% - 1px)'
133
+ block.textContent = clip.labels.join(' ')
134
+ block.title = clip.labels.join(', ') + ' ' + clip.t0.toFixed(2) + 's to ' + clip.t1.toFixed(2) + 's'
135
+ track.append(block)
136
+ }
137
+ for (const chapter of film.chapters) {
138
+ const tick = document.createElement('div')
139
+ tick.className = 'tick'
140
+ tick.style.left = at(chapter.time)
141
+ tick.title = chapter.title
142
+ track.append(tick)
143
+ }
144
+ for (const issue of state.report?.diagnostics ?? []) {
145
+ const mark = document.createElement('div')
146
+ mark.className = 'issue'
147
+ mark.dataset.severity = issue.severity
148
+ mark.style.left = at(issue.time)
149
+ mark.style.width = 'max(3px, ' + ((issue.until - issue.time) / film.duration) * 100 + '%)'
150
+ mark.title = issue.message
151
+ track.append(mark)
152
+ }
153
+ const chapters = el('chapters')
154
+ chapters.replaceChildren(...film.chapters.map((chapter) => {
155
+ const button = document.createElement('button')
156
+ button.type = 'button'
157
+ button.textContent = chapter.title
158
+ button.dataset.time = chapter.time
159
+ button.addEventListener('click', () => state.player.seek(chapter.time))
160
+ return button
161
+ }))
162
+ }
163
+
164
+ function drawIssues() {
165
+ const issues = state.report?.diagnostics ?? []
166
+ const list = el('issues')
167
+ list.hidden = issues.length === 0 || !el('show-issues').checked
168
+ list.replaceChildren(...issues.map((issue) => {
169
+ const button = document.createElement('button')
170
+ button.type = 'button'
171
+ const severity = document.createElement('b')
172
+ severity.dataset.severity = issue.severity
173
+ severity.textContent = issue.severity
174
+ button.append(severity, ' ' + clock(issue.time) + ' ' + issue.message)
175
+ button.addEventListener('click', () => state.player.seek(issue.time))
176
+ return button
177
+ }))
178
+ }
179
+
180
+ function onTime(time) {
181
+ const film = state.film
182
+ el('time').textContent = clock(time) + ' / ' + clock(film.duration)
183
+ el('playhead').style.left = (time / film.duration) * 100 + '%'
184
+ el('timeline').setAttribute('aria-valuenow', time.toFixed(2))
185
+ history.replaceState(null, '', '?t=' + time.toFixed(2) + (el('look').value ? '&look=' + el('look').value : ''))
186
+ for (const button of el('chapters').children) {
187
+ const next = button.nextElementSibling
188
+ const active = time >= Number(button.dataset.time) && (!next || time < Number(next.dataset.time))
189
+ button.setAttribute('aria-current', active ? 'true' : 'false')
190
+ }
191
+ const overlay = el('overlay')
192
+ overlay.replaceChildren()
193
+ if (!el('show-issues').checked) return
194
+ for (const issue of state.report?.diagnostics ?? []) {
195
+ if (time < issue.time - 0.05 || time > issue.until + 0.05) continue
196
+ const box = document.createElement('div')
197
+ box.dataset.severity = issue.severity
198
+ box.title = issue.message
199
+ box.style.left = (issue.box.x / film.width) * 100 + '%'
200
+ box.style.top = (issue.box.y / film.height) * 100 + '%'
201
+ box.style.width = (issue.box.width / film.width) * 100 + '%'
202
+ box.style.height = (issue.box.height / film.height) * 100 + '%'
203
+ overlay.append(box)
204
+ }
205
+ }
206
+
207
+ async function compile() {
208
+ const ticket = ++state.loading
209
+ setState('Compiling', 'busy')
210
+ const started = performance.now()
211
+ try {
212
+ const film = await state.definition.compile(el('look').value ? { look: el('look').value } : {})
213
+ if (ticket !== state.loading) return
214
+ const previous = state.player
215
+ if (previous) {
216
+ remembered.time = previous.time
217
+ remembered.playing = previous.isPlaying
218
+ previous.destroy()
219
+ }
220
+ // A canvas keeps its 2D context settings, so a replacement avoids alpha mismatches between films.
221
+ const fresh = document.createElement('canvas')
222
+ fresh.id = 'canvas'
223
+ fresh.setAttribute('role', 'img')
224
+ fresh.setAttribute('aria-label', 'Film preview')
225
+ el('canvas').replaceWith(fresh)
226
+ state.film = film
227
+ el('title').textContent = film.title || 'Untitled film'
228
+ document.title = (film.title || 'Untitled film') + ' | vizmatic preview'
229
+ sizeFrame()
230
+ state.report = await checkFilm(film)
231
+ if (ticket !== state.loading) return
232
+ drawTimeline()
233
+ drawIssues()
234
+ state.player = new FilmPlayer(fresh, film, {
235
+ loop: el('loop').checked,
236
+ speed: Number(el('speed').value),
237
+ onTime,
238
+ onState: ({ playing }) => { el('toggle').textContent = playing ? 'Pause' : 'Play' },
239
+ })
240
+ sizeFrame()
241
+ state.player.seek(Math.min(film.duration, remembered.time))
242
+ if (remembered.playing) state.player.play()
243
+ fresh.addEventListener('click', () => state.player.toggle())
244
+ clearError()
245
+ const ms = Math.round(performance.now() - started)
246
+ const errors = state.report.summary.errors, warnings = state.report.summary.warnings
247
+ const issues = errors + warnings ? ', ' + errors + ' error(s), ' + warnings + ' warning(s)' : ''
248
+ setState('Ready in ' + ms + ' ms' + issues, errors ? 'error' : '')
249
+ report('compiled', { ms, errors, warnings, duration: film.duration })
250
+ } catch (error) {
251
+ if (ticket !== state.loading) return
252
+ const message = error && error.stack ? error.stack : String(error)
253
+ showError('The film failed while compiling.\\n\\n' + message)
254
+ report('error', message)
255
+ }
256
+ }
257
+
258
+ async function load(version) {
259
+ try {
260
+ const module = await import('/film.js?v=' + version)
261
+ if (!isFilm(module.default)) throw new Error('The file must export a film as its default export: export default film({ title: "Intro" }, (s) => { ... })')
262
+ state.definition = module.default
263
+ await compile()
264
+ } catch (error) {
265
+ const message = error && error.stack ? error.stack : String(error)
266
+ showError('The film could not load.\\n\\n' + message)
267
+ report('error', message)
268
+ }
269
+ }
270
+
271
+ const events = new EventSource('/events')
272
+ events.addEventListener('build', (event) => {
273
+ const data = JSON.parse(event.data)
274
+ if (data.version === state.version) return
275
+ state.version = data.version
276
+ void load(data.version)
277
+ })
278
+ events.addEventListener('build-error', (event) => {
279
+ showError(JSON.parse(event.data).message)
280
+ })
281
+ events.onerror = () => setState('Disconnected from the preview server', 'error')
282
+
283
+ el('toggle').addEventListener('click', () => state.player?.toggle())
284
+ el('look').addEventListener('change', () => { if (state.definition) void compile() })
285
+ el('speed').addEventListener('change', () => { if (state.player) state.player.speed = Number(el('speed').value) })
286
+ el('loop').addEventListener('change', () => { if (state.definition) void compile() })
287
+ el('show-issues').addEventListener('change', () => { drawIssues(); if (state.player) onTime(state.player.time) })
288
+
289
+ const timeline = el('timeline')
290
+ const seekFrom = (event) => {
291
+ const rect = timeline.getBoundingClientRect()
292
+ state.player?.seek(((event.clientX - rect.left) / rect.width) * state.film.duration)
293
+ }
294
+ timeline.addEventListener('pointerdown', (event) => {
295
+ timeline.setPointerCapture(event.pointerId)
296
+ seekFrom(event)
297
+ const move = (next) => seekFrom(next)
298
+ timeline.addEventListener('pointermove', move)
299
+ timeline.addEventListener('pointerup', () => timeline.removeEventListener('pointermove', move), { once: true })
300
+ })
301
+
302
+ addEventListener('keydown', (event) => {
303
+ const player = state.player
304
+ if (!player || event.target.matches('select, input')) return
305
+ const frame = 1 / state.film.fps
306
+ const key = event.key
307
+ if (key === ' ' || key === 'k') player.toggle()
308
+ else if (key === 'ArrowRight') player.seek(player.time + (event.shiftKey ? 5 : 1))
309
+ else if (key === 'ArrowLeft') player.seek(player.time - (event.shiftKey ? 5 : 1))
310
+ else if (key === '.') { player.pause(); player.seek(player.time + frame) }
311
+ else if (key === ',') { player.pause(); player.seek(player.time - frame) }
312
+ else if (key === ']') player.next()
313
+ else if (key === '[') player.previous()
314
+ else if (key === 'Home') player.seek(0)
315
+ else if (key === 'End') player.seek(state.film.duration)
316
+ else if (/^[0-9]$/.test(key)) player.seek((Number(key) / 10) * state.film.duration)
317
+ else return
318
+ event.preventDefault()
319
+ })
320
+ </script>
321
+ </body>
322
+ </html>
323
+ `}var RESERVED_PORT=4173;var FIRST_PORT=4310;var PORT_ATTEMPTS=60;var REBUILD_DELAY_MS=40;function here(){return typeof __dirname!=="undefined"?__dirname:dirname(fileURLToPath(import.meta.url))}function loadEsbuild(){const from=createRequire(join(here(),"noop.js"));try{return from("esbuild")}catch{const tsx=from.resolve("tsx/package.json");return createRequire(tsx)("esbuild")}}function findUp(start,target){let directory=start;for(let depth=0;depth<8;depth++){const candidate=join(directory,target);if(existsSync(candidate))return candidate;const parent=dirname(directory);if(parent===directory)return null;directory=parent}return null}var TYPES={".js":"text/javascript; charset=utf-8",".ttf":"font/ttf",".map":"application/json"};async function loadEngine(esbuild){const files=new Map;const source=join(here(),"..","browser.ts");const built=findUp(here(),"dist/stage-browser/stage.js");if(existsSync(source)){const result=await esbuild.build({entryPoints:{stage:source},bundle:true,splitting:true,format:"esm",target:"es2022",platform:"browser",outdir:"/stage",write:false,chunkNames:"[name]-[hash]",logLevel:"silent"});for(const file of result.outputFiles??[])files.set(basename(file.path),file.contents);return files}if(!built)throw new Error("The browser engine is missing from this package. Reinstall vizmatic.");const{readdir}=await import("fs/promises");for(const name of await readdir(dirname(built))){if(extname(name)===".js")files.set(name,await readFile(join(dirname(built),name)))}return files}function formatBuildError(file,errors){return errors.map(error=>{if(!error.location)return error.text;const{file:at,line,column,lineText}=error.location;const caret=`${" ".repeat(column)}^`;return`${at}:${line}:${column+1}: ${error.text}
324
+
325
+ ${lineText}
326
+ ${caret}`}).join("\n\n")||`Could not build ${file}.`}function listen(server,port){return new Promise((done,fail)=>{const onError=error=>fail(error);server.once("error",onError);server.listen(port,"127.0.0.1",()=>{server.removeListener("error",onError);const address=server.address();done(typeof address==="object"&&address?address.port:port)})})}async function bindPort(server,requested){if(requested!==void 0){const bound=await listen(server,requested);if(requested===0&&bound===RESERVED_PORT){await new Promise(done=>server.close(done));return bindPort(server,0)}return bound}for(let port=FIRST_PORT;port<FIRST_PORT+PORT_ATTEMPTS;port++){if(port===RESERVED_PORT)continue;try{return await listen(server,port)}catch(error){if(error.code!=="EADDRINUSE")throw error}}throw new Error(`No free port from ${FIRST_PORT}. Pass one with --port.`)}async function startPreview(options){const file=resolve(options.file);if(!existsSync(file)||!statSync(file).isFile())throw new Error(`Film file not found: ${options.file}`);const log=options.log??(()=>{});const esbuild=loadEsbuild();const engine=await loadEngine(esbuild);const fonts=findUp(here(),"assets/fonts");if(!fonts)throw new Error("Bundled fonts are missing from this package. Reinstall vizmatic.");const clients=new Set;let version=0;let bundle=null;let lastError=null;const send=(client,event,data)=>{client.write(`event: ${event}
327
+ data: ${JSON.stringify(data)}
328
+
329
+ `)};const broadcast=(event,data)=>{for(const client of clients)send(client,event,data)};const context=await esbuild.context({entryPoints:[file],bundle:true,format:"esm",target:"es2022",platform:"browser",write:false,metafile:true,outfile:"/film.js",sourcemap:"inline",logLevel:"silent",jsx:"automatic",plugins:[{name:"vizmatic-preview",setup(build){build.onResolve({filter:/^vizmatic\/stage$/},()=>({path:"/stage/stage.js",external:true}));build.onResolve({filter:/^vizmatic(\/stage\/export)?$/},args=>({errors:[{text:`A film preview runs in the browser, so it can only import "vizmatic/stage", not "${args.path}".`}]}))}}]});const directories=new Map;let inputs=new Set([file]);const syncWatchers=()=>{for(const input of inputs){const directory=dirname(input);if(directories.has(directory))continue;directories.set(directory,watch(directory,(_event,name)=>{if(name&&inputs.has(join(directory,name.toString())))schedule()}))}};let timer=null;let building=false;let queued=false;const schedule=()=>{if(timer)clearTimeout(timer);timer=setTimeout(()=>void rebuild(),REBUILD_DELAY_MS)};const rebuild=async()=>{if(building){queued=true;return}building=true;const started=performance.now();try{const result=await context.rebuild().catch(error=>({errors:error.errors??[{text:error.message??String(error)}],warnings:[],outputFiles:void 0,metafile:void 0}));if(result.errors.length>0){lastError=formatBuildError(relative(process.cwd(),file),result.errors);log(`Build failed:
330
+ ${lastError}`);broadcast("build-error",{message:lastError});return}lastError=null;bundle=result.outputFiles?.find(output=>output.path.endsWith("film.js"))?.contents??result.outputFiles?.[0]?.contents??null;if(result.metafile){const cwd=process.cwd();inputs=new Set(Object.keys(result.metafile.inputs).filter(input=>!input.includes("node_modules")).map(input=>resolve(cwd,input)));inputs.add(file);syncWatchers()}version+=1;log(`Built ${relative(process.cwd(),file)} in ${Math.round(performance.now()-started)} ms`);broadcast("build",{version})}finally{building=false;if(queued){queued=false;void rebuild()}}};const respond=(response,status,type,body)=>{response.writeHead(status,{"Content-Type":type,"Cache-Control":"no-store"});response.end(body)};const handle=async(request,response)=>{const host=(request.headers.host??"").replace(/:\d+$/,"");if(host!=="127.0.0.1"&&host!=="localhost"){respond(response,403,"text/plain; charset=utf-8","Forbidden");return}const url2=new URL(request.url??"/","http://127.0.0.1");const path=url2.pathname;if(path==="/"){respond(response,200,"text/html; charset=utf-8",previewPage(basename(file)))}else if(path==="/events"){response.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-store",Connection:"keep-alive"});clients.add(response);request.on("close",()=>clients.delete(response));if(lastError)send(response,"build-error",{message:lastError});else if(bundle)send(response,"build",{version})}else if(path==="/film.js"){if(bundle)respond(response,200,TYPES[".js"],bundle);else respond(response,503,"text/plain; charset=utf-8",lastError??"The film has not been built yet.")}else if(path.includes("/assets/fonts/")){const name=basename(path);const bytes=await readFile(join(fonts,name)).catch(()=>null);if(bytes)respond(response,200,TYPES[".ttf"],bytes);else respond(response,404,"text/plain; charset=utf-8",`Font not found: ${name}`)}else if(path.startsWith("/stage/")){const bytes=engine.get(basename(path));if(bytes)respond(response,200,TYPES[".js"],bytes);else respond(response,404,"text/plain; charset=utf-8",`Not found: ${path}`)}else if(path==="/log"&&request.method==="POST"){const chunks=[];for await(const chunk of request)chunks.push(chunk);const body=JSON.parse(Buffer.concat(chunks).toString("utf8")||"{}");if(body.kind==="error")log(`Film error:
331
+ ${String(body.message)}`);else if(body.kind==="compiled"){const info=body.message;const issues=info.errors+info.warnings>0?`, check found ${info.errors} error(s) and ${info.warnings} warning(s)`:"";log(`Compiled in the browser in ${info.ms} ms (${info.duration.toFixed(1)}s long${issues})`)}respond(response,204,"text/plain; charset=utf-8","")}else{respond(response,404,"text/plain; charset=utf-8","Not found")}};const server=createServer((request,response)=>{handle(request,response).catch(error=>{log(`Preview server error: ${error instanceof Error?error.message:String(error)}`);if(!response.headersSent)respond(response,500,"text/plain; charset=utf-8","Server error");else response.end()})});const port=await bindPort(server,options.port);await rebuild();const url=`http://127.0.0.1:${port}/`;return{url,port,async open(){const command=process.platform==="darwin"?"open":process.platform==="win32"?"cmd":"xdg-open";const args=process.platform==="win32"?["/c","start","",url]:[url];spawn(command,args,{stdio:"ignore",detached:true}).unref()},async close(){if(timer)clearTimeout(timer);for(const watcher of directories.values())watcher.close();for(const client of clients)client.end();clients.clear();await context.dispose();await new Promise(done=>{server.close(()=>done());server.closeAllConnections?.()})}}}export{startPreview};