@codegrowers/storybook-jaspr-vite 0.0.0-stage → 1.0.1

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/CHANGELOG.md ADDED
@@ -0,0 +1,16 @@
1
+ # Changelog
2
+
3
+ ## 1.0.1
4
+
5
+ - Keep the parts dart2js emits for deferred imports. Development serves them
6
+ next to the preview, and static builds emit them with the preview into one
7
+ content-hashed directory, so `loadLibrary()` works in Storybook.
8
+
9
+ ## 1.0.0
10
+
11
+ - Initial MIT-licensed release of the Jaspr Storybook integration.
12
+ - Render Jaspr components with controls, globals, actions and argument updates.
13
+ - Preserve component state on argument updates and isolate concurrent Docs previews.
14
+ - Dispose component trees on teardown and surface render errors in Storybook.
15
+ - Compile Dart through Vite for development and static Storybook builds.
16
+ - Display actual Dart source regions in Docs with Dart syntax highlighting.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Electree 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,52 @@
1
- # Temporary Holding Version
1
+ # @codegrowers/storybook-jaspr-vite
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
+ A native Storybook renderer and Vite framework for Jaspr components written in
4
+ Dart. Mount real Jaspr components in Canvas and Docs, edit arguments with
5
+ Controls, record Actions and run TypeScript play functions against the DOM.
6
+
7
+ MIT licensed. Requires the companion
8
+ [`jaspr_storybook`](https://pub.dev/packages/jaspr_storybook) Dart runtime.
9
+ This framework is released at `1.0.1` and works with the `1.x` runtime.
10
+
11
+ ```sh
12
+ bun add --dev @codegrowers/storybook-jaspr-vite@^1.0.0 storybook@10.6.5 vite@8.3.5 @storybook/addon-docs@10.6.5
13
+ dart pub add --dev jaspr_storybook:^1.0.0
14
+ ```
15
+
16
+ Register builders with `registerStorybook` in a Dart client entrypoint, configure
17
+ the framework in `.storybook/main.ts`, and write normal CSF stories with the
18
+ registered component key. The framework compiles Dart through Vite for both the
19
+ development server and static Storybook output.
20
+
21
+ ```ts
22
+ import type { StorybookConfig } from '@codegrowers/storybook-jaspr-vite';
23
+ import { createRequire } from 'node:module';
24
+ import { dirname } from 'node:path';
25
+
26
+ const require = createRequire(import.meta.url);
27
+
28
+ export default {
29
+ framework: {
30
+ name: dirname(require.resolve('@codegrowers/storybook-jaspr-vite/package.json')),
31
+ options: { entrypoint: '../lib/storybook.client.dart' },
32
+ },
33
+ stories: ['../stories/**/*.stories.ts'],
34
+ } satisfies StorybookConfig;
35
+ ```
36
+
37
+ Docs can show actual Dart builders selected with `#docregion` markers, with Dart
38
+ syntax highlighting. See [STORYBOOK.md](STORYBOOK.md) for Dart registration, CSF, controls, actions,
39
+ watch options, styling, examples and release instructions.
40
+
41
+ Tested with Jaspr 0.23.3 and 0.23.5, Storybook 10.6.5, Vite 8.3.5,
42
+ Bun 1.4.2 and Dart 3.13.5. The Dart SDK must be on `PATH`, or set
43
+ `framework.options.dartExecutable`. Node execution has not been verified.
44
+
45
+ Styles and assets belong to the consumer. Argument values must be compatible
46
+ with JSON. This version previews client-side Jaspr components; it does not
47
+ provide SSR/hydration testing, Wasm output, Dart constructor introspection or
48
+ automatic Dart story discovery.
49
+
50
+ To develop: run `bun install`, `bun run build`, `bun run format:check`,
51
+ `bun run lint`, `bun run typecheck` and `bun test`. Run `dart pub get` in
52
+ `example/`, then `bun run build:example` and `bun run preview` from the root.
package/STORYBOOK.md ADDED
@@ -0,0 +1,192 @@
1
+ # Storybook for Jaspr
2
+
3
+ Two MIT-licensed packages provide the integration. The npm framework is at
4
+ `1.0.1` and works with the `1.x` Dart runtime:
5
+
6
+ | Registry | Package | Source |
7
+ | --- | --- | --- |
8
+ | pub.dev | [`jaspr_storybook`](https://pub.dev/packages/jaspr_storybook) | [Dart runtime](https://github.com/Code-Growers/jaspr_storybook) |
9
+ | npm | [`@codegrowers/storybook-jaspr-vite`](https://www.npmjs.com/package/@codegrowers/storybook-jaspr-vite) | [Storybook framework](https://github.com/Code-Growers/storybook-jaspr-vite) |
10
+
11
+ ## Consumer setup
12
+
13
+ Add `jaspr_storybook` to your Dart application's development
14
+ dependencies and the matching npm framework plus Storybook/Vite to its JavaScript
15
+ development dependencies. For example, using Bun:
16
+
17
+ ```sh
18
+ dart pub add --dev jaspr_storybook:^1.0.0
19
+ bun add --dev @codegrowers/storybook-jaspr-vite@^1.0.0 storybook@10.6.5 vite@8.3.5 @storybook/addon-docs@10.6.5
20
+ ```
21
+
22
+ The current tested targets are Jaspr 0.23.3 and 0.23.5, Storybook 10.6.5, Vite
23
+ 8.3.5, Bun 1.4.2 and Dart 3.13.5. The Jaspr constraint allows 0.23.x, but other patch versions
24
+ still need compatibility verification before extending the advertised matrix.
25
+ Node support has not been verified; the development and release scripts use Bun.
26
+
27
+ Register components in a Dart client entrypoint as shown in README.md. Configure
28
+ `.storybook/main.ts`:
29
+
30
+ ```ts
31
+ import type { StorybookConfig } from '@codegrowers/storybook-jaspr-vite';
32
+ import { createRequire } from 'node:module';
33
+ import { dirname } from 'node:path';
34
+
35
+ const require = createRequire(import.meta.url);
36
+
37
+ export default {
38
+ framework: {
39
+ name: dirname(require.resolve('@codegrowers/storybook-jaspr-vite/package.json')),
40
+ options: {
41
+ entrypoint: '../lib/storybook.client.dart',
42
+ // Optional directories outside the entrypoint directory:
43
+ // watchPaths: ['../../shared_widgets/lib'],
44
+ // dartExecutable: '/path/to/dart',
45
+ },
46
+ },
47
+ stories: ['../stories/**/*.stories.ts'],
48
+ addons: [dirname(require.resolve('@storybook/addon-docs/package.json'))],
49
+ } satisfies StorybookConfig;
50
+ ```
51
+
52
+ Write normal CSF stories, using the Dart registry key as `component`:
53
+
54
+ ```ts
55
+ import type { Meta, StoryObj } from '@codegrowers/storybook-jaspr-vite';
56
+
57
+ type Args = { label: string; disabled: boolean };
58
+ export default {
59
+ title: 'Components/Button',
60
+ component: 'button',
61
+ tags: ['autodocs'],
62
+ args: { label: 'Save', disabled: false },
63
+ argTypes: {
64
+ label: { control: 'text' },
65
+ disabled: { control: 'boolean' },
66
+ },
67
+ } satisfies Meta<Args>;
68
+
69
+ export const Default: StoryObj<Args> = {};
70
+ ```
71
+
72
+ Run `dart pub get`, then `bun --bun storybook dev` or `bun --bun storybook build`.
73
+ The preset invokes the configured Dart SDK to compile the entrypoint. It serves
74
+ the result during development and emits it as a local asset in static builds.
75
+ No remote Dart or Jaspr server is required to view a built Storybook.
76
+
77
+ ## Features and boundaries
78
+
79
+ - The renderer mounts actual Jaspr component trees directly into the Canvas.
80
+ It does not depend on the HTML renderer or embed a second iframe.
81
+ - Controls and globals update the root while retaining descendant state. Dart
82
+ can update controlled arguments through `story.updateArgs`.
83
+ - Actions cross the Dart/JavaScript boundary through a named event channel.
84
+ - Optional `undefined` object properties are omitted; array entries become
85
+ `null`, following JSON conventions. Functions and opaque objects are rejected.
86
+ - Inline Docs can mount multiple independent previews. Use `story.instanceId`
87
+ when assigning DOM ids.
88
+ - Story teardown disposes the Jaspr tree and removes the renderer-owned DOM.
89
+ Builder errors reject rendering so Storybook can show its error UI.
90
+ - Play functions run after the Dart mount/update promise completes. They are
91
+ authored in TypeScript against the preview's regular DOM.
92
+ - Deferred imports work. The parts dart2js emits are served next to the
93
+ preview during development and emitted with it into one content-hashed
94
+ asset directory in static builds.
95
+ - Changes to Dart files under the entrypoint directory or `watchPaths` trigger
96
+ recompilation and a full preview reload. Dart state resets on source changes;
97
+ this is not Jaspr hot reload. Compilation failures show the Vite error overlay.
98
+ - Styling remains in the application. Import CSS in `.storybook/preview.ts`
99
+ and serve fonts/images with Storybook `staticDirs`. Jaspr-generated CSS or
100
+ code generation must be prepared with the application's normal tooling.
101
+ - Dart constructor introspection, automatic Dart story discovery, server-only
102
+ components, SSR/hydration verification and Wasm output are outside this version.
103
+ Controls metadata is explicit. JSON-compatible arguments are required. To show
104
+ Dart source in Docs, supply `parameters.docs.source.code` and `language: 'dart'`.
105
+
106
+ ## Dart source in Docs
107
+
108
+ The renderer shows real Dart source regions in Docs and the optional Code panel,
109
+ with Dart syntax highlighting. In the Dart entrypoint or files listed in
110
+ `framework.options.sourceFiles`, surround a builder or component expression with
111
+ markers matching its registered component key:
112
+
113
+ ```dart
114
+ // #docregion button
115
+ Component buttonStory(StorybookContext story) => button(
116
+ disabled: story.arg<bool>('disabled'),
117
+ onClick: () => story.action('onClick'),
118
+ [.text(story.arg<String>('label'))],
119
+ );
120
+ // #enddocregion button
121
+ ```
122
+
123
+ ```ts
124
+ options: {
125
+ entrypoint: '../lib/storybook.client.dart',
126
+ sourceFiles: ['../lib/component_stories.dart'],
127
+ }
128
+ ```
129
+
130
+ Paths are relative to the Storybook configuration directory. The entrypoint is
131
+ always scanned. Source files are watched automatically. Each region has one
132
+ unique name; nested, duplicate, empty or unclosed regions fail the build.
133
+ Only marked code is embedded in the static build. Snippets show the Dart builder
134
+ as written, including `story.arg` calls; changing controls does not rewrite Dart
135
+ source. The TypeScript `play` function continues to run independently.
136
+
137
+ For a hand-written example or a story-specific variant, use standard Storybook
138
+ `parameters.docs.source.code` with `language: 'dart'`. `docs.source.transform`
139
+ is also supported by the Docs source block. Without a matching region or an
140
+ explicit source override, the code panel indicates that Dart source is unconfigured.
141
+
142
+ ## Examples and development
143
+
144
+ Each repository includes a small `example/` with a button, a controlled switch
145
+ and stateful counters. The npm example also loads a deferred library. No
146
+ backend or application-specific assets are needed. The example configuration lives in `example/storybook/` so pub.dev includes it;
147
+ consumer applications can use the conventional `.storybook/` directory.
148
+
149
+ In the Dart runtime repository:
150
+
151
+ ```sh
152
+ dart pub get
153
+ dart format .
154
+ dart analyze
155
+ dart test
156
+ cd example
157
+ dart pub get
158
+ bun install
159
+ bun run dev
160
+ ```
161
+
162
+ In the npm framework repository:
163
+
164
+ ```sh
165
+ bun install
166
+ bun run build
167
+ bun run format:check
168
+ bun run lint
169
+ bun run typecheck
170
+ bun test
171
+ cd example
172
+ dart pub get
173
+ cd ..
174
+ bun run build:example
175
+ bun run preview
176
+ ```
177
+
178
+ The Dart example uses the local runtime and the published npm framework. The
179
+ npm example uses the local framework and the published Dart runtime. Changes
180
+ to the shared browser protocol must be verified across both repositories.
181
+
182
+ ## Release
183
+
184
+ Keep the paired package versions compatible. Run the checks above, review
185
+ `dart pub publish --dry-run` in the Dart repository and `bun pm pack --dry-run`
186
+ in the npm repository, and verify the examples in a browser.
187
+
188
+ Publish the Dart runtime with `dart pub publish`, and the public scoped npm
189
+ framework with `bun publish --access public`. The npm publish lifecycle builds
190
+ the distribution and runs its checks. Registry credentials belong in the local
191
+ authentication environment and must never be committed. Tag releases in both
192
+ source repositories after successful publication.
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,3 @@
1
+ import dart from "refractor/dart";
2
+ import { SyntaxHighlighter } from "storybook/internal/components";
3
+ SyntaxHighlighter.registerLanguage("dart", dart);
@@ -0,0 +1 @@
1
+ export type { FrameworkOptions, JasprRenderer, JasprStory, Meta, StorybookConfig, StoryObj, } from "./types.js";
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,5 @@
1
+ import type { PresetProperty } from "storybook/internal/types";
2
+ import type { ViteFinal } from "@storybook/builder-vite";
3
+ export declare const core: PresetProperty<"core">;
4
+ export declare const managerEntries: (entries?: string[]) => string[];
5
+ export declare const viteFinal: ViteFinal;
package/dist/preset.js ADDED
@@ -0,0 +1,33 @@
1
+ import { fileURLToPath } from "node:url";
2
+ import { dirname } from "node:path";
3
+ import { mergeConfig, searchForWorkspaceRoot } from "vite";
4
+ import { dartPreviewPlugin } from "./vite-plugin.js";
5
+ export const core = {
6
+ builder: import.meta.resolve("@storybook/builder-vite"),
7
+ renderer: import.meta.resolve("./renderer-preset.js"),
8
+ };
9
+ export const managerEntries = (entries = []) => [
10
+ ...entries,
11
+ fileURLToPath(import.meta.resolve("./dart-highlighting.js")),
12
+ ];
13
+ export const viteFinal = async (config, options) => {
14
+ const framework = await options.presets.apply("framework");
15
+ if (!framework.options?.entrypoint) {
16
+ throw new Error("Jaspr Storybook requires framework.options.entrypoint relative to the config directory.");
17
+ }
18
+ return mergeConfig(config, {
19
+ plugins: [dartPreviewPlugin(framework.options, options.configDir)],
20
+ server: {
21
+ fs: {
22
+ // Bun may install Storybook outside a nested consumer workspace. Its
23
+ // injected mock bootstrap still needs to pass Vite's strict file checks.
24
+ allow: [
25
+ ...(config.server?.fs?.allow ?? [
26
+ searchForWorkspaceRoot(config.root ?? process.cwd()),
27
+ ]),
28
+ dirname(fileURLToPath(import.meta.resolve("storybook/package.json"))),
29
+ ],
30
+ },
31
+ },
32
+ });
33
+ };
@@ -0,0 +1,18 @@
1
+ import type { ArgsStoryFn, RenderContext } from "storybook/internal/types";
2
+ import "./dart-highlighting.js";
3
+ import type { JasprRenderer } from "./types.js";
4
+ export declare const parameters: {
5
+ renderer: string;
6
+ docs: {
7
+ story: {
8
+ inline: boolean;
9
+ };
10
+ source: {
11
+ language: string;
12
+ type: string;
13
+ };
14
+ };
15
+ };
16
+ export declare const argTypesEnhancers: (<TRenderer extends import("storybook/internal/types").Renderer>(context: import("storybook/internal/types").StoryContextForEnhancers<TRenderer>) => import("storybook/internal/types").Parameters)[];
17
+ export declare const render: ArgsStoryFn<JasprRenderer>;
18
+ export declare function renderToCanvas(context: RenderContext<JasprRenderer>, canvas: HTMLElement): Promise<() => void>;
@@ -0,0 +1,125 @@
1
+ import { action } from "storybook/actions";
2
+ import { UPDATE_STORY_ARGS } from "storybook/internal/core-events";
3
+ import { enhanceArgTypes, SNIPPET_RENDERED, } from "storybook/internal/docs-tools";
4
+ import { addons } from "storybook/preview-api";
5
+ import { bundleUrl, dartSources } from "virtual:jaspr-storybook-runtime";
6
+ import "./dart-highlighting.js";
7
+ import { checkRecord } from "./protocol.js";
8
+ import { loadRuntime } from "./runtime.js";
9
+ export const parameters = {
10
+ renderer: "jaspr",
11
+ docs: {
12
+ story: { inline: true },
13
+ source: { language: "dart", type: "dynamic" },
14
+ },
15
+ };
16
+ export const argTypesEnhancers = [enhanceArgTypes];
17
+ export const render = (args, context) => ({
18
+ component: context.component ?? "",
19
+ args,
20
+ });
21
+ const sessions = new WeakMap();
22
+ let nextInstance = 0;
23
+ export async function renderToCanvas(context, canvas) {
24
+ const story = context.storyFn();
25
+ if (!story ||
26
+ typeof story.component !== "string" ||
27
+ !story.component.trim()) {
28
+ throw new Error("Set component to a registered Jaspr builder key in your story metadata.");
29
+ }
30
+ const args = checkRecord(story.args, "args");
31
+ const globals = checkRecord(context.storyContext.globals, "globals");
32
+ const runtime = await loadRuntime(bundleUrl);
33
+ const emitSource = () => {
34
+ addons.getChannel().emit(SNIPPET_RENDERED, {
35
+ id: context.storyContext.id,
36
+ args: context.storyContext.unmappedArgs ?? context.storyContext.args,
37
+ source: dartSources[story.component] ??
38
+ "// No Dart source region is configured for this component.",
39
+ format: false,
40
+ });
41
+ };
42
+ const previous = sessions.get(canvas);
43
+ if (previous &&
44
+ !previous.disposed &&
45
+ previous.component === story.component &&
46
+ !context.forceRemount) {
47
+ previous.ready = previous.ready
48
+ .catch(() => { })
49
+ .then(() => {
50
+ if (!previous.disposed)
51
+ return runtime.update(previous.host.id, args, globals);
52
+ });
53
+ await previous.ready;
54
+ if (!previous.disposed)
55
+ emitSource();
56
+ context.showMain();
57
+ return previous.dispose;
58
+ }
59
+ previous?.dispose();
60
+ canvas.replaceChildren();
61
+ const host = document.createElement("div");
62
+ host.id = `jaspr-storybook-${++nextInstance}`;
63
+ canvas.appendChild(host);
64
+ const session = {
65
+ component: story.component,
66
+ runtime,
67
+ host,
68
+ disposed: false,
69
+ ready: Promise.resolve(),
70
+ dispose() {
71
+ if (session.disposed)
72
+ return;
73
+ session.disposed = true;
74
+ try {
75
+ runtime.unmount(host.id);
76
+ }
77
+ finally {
78
+ // Jaspr disposal releases component state. The renderer owns DOM removal.
79
+ host.replaceChildren();
80
+ host.remove();
81
+ if (sessions.get(canvas) === session)
82
+ sessions.delete(canvas);
83
+ }
84
+ },
85
+ };
86
+ sessions.set(canvas, session);
87
+ session.ready = runtime.mount(host.id, story.component, host.id, args, globals, (type, payload) => {
88
+ if (session.disposed)
89
+ return;
90
+ if (type === "error") {
91
+ const failure = checkRecord(payload, "error");
92
+ const error = new Error(String(failure.message));
93
+ if (typeof failure.stack === "string")
94
+ error.stack = failure.stack;
95
+ context.showException(error);
96
+ return;
97
+ }
98
+ if (type === "action") {
99
+ const event = checkRecord(payload, "action");
100
+ if (typeof event.name !== "string")
101
+ throw new Error("A Jaspr action must have a name.");
102
+ action(event.name)(event.value);
103
+ }
104
+ else if (type === "args") {
105
+ addons.getChannel().emit(UPDATE_STORY_ARGS, {
106
+ storyId: context.storyContext.id,
107
+ updatedArgs: checkRecord(payload, "updatedArgs"),
108
+ });
109
+ }
110
+ });
111
+ try {
112
+ await session.ready;
113
+ if (!session.disposed) {
114
+ emitSource();
115
+ context.showMain();
116
+ }
117
+ }
118
+ catch (error) {
119
+ session.dispose();
120
+ if (sessions.get(canvas) && sessions.get(canvas) !== session)
121
+ return () => { };
122
+ throw error;
123
+ }
124
+ return session.dispose;
125
+ }
@@ -0,0 +1,14 @@
1
+ export interface JasprRuntime {
2
+ protocolVersion: 1;
3
+ mount(instanceId: string, component: string, hostId: string, args: Record<string, unknown>, globals: Record<string, unknown>, emit: (type: string, payload: unknown) => void): Promise<unknown>;
4
+ update(instanceId: string, args: Record<string, unknown>, globals: Record<string, unknown>): Promise<unknown>;
5
+ unmount(instanceId: string): void;
6
+ }
7
+ declare global {
8
+ interface Window {
9
+ __jasprStorybook?: JasprRuntime;
10
+ }
11
+ }
12
+ export declare function checkRuntime(value: unknown): JasprRuntime;
13
+ /** Normalize optional values and reject callbacks, cycles and opaque objects. */
14
+ export declare function checkRecord(value: unknown, label: string): Record<string, unknown>;
@@ -0,0 +1,47 @@
1
+ export function checkRuntime(value) {
2
+ if (typeof value !== "object" ||
3
+ value === null ||
4
+ !("protocolVersion" in value) ||
5
+ value.protocolVersion !== 1 ||
6
+ !("mount" in value) ||
7
+ typeof value.mount !== "function" ||
8
+ !("update" in value) ||
9
+ typeof value.update !== "function" ||
10
+ !("unmount" in value) ||
11
+ typeof value.unmount !== "function") {
12
+ throw new Error("Incompatible Jaspr Storybook runtime. Use matching Dart and npm package versions.");
13
+ }
14
+ return value;
15
+ }
16
+ /** Normalize optional values and reject callbacks, cycles and opaque objects. */
17
+ export function checkRecord(value, label) {
18
+ const ancestors = new Set();
19
+ const visit = (item, path) => {
20
+ if (item === null || typeof item === "string" || typeof item === "boolean")
21
+ return item;
22
+ if (typeof item === "number" && Number.isFinite(item))
23
+ return item;
24
+ if (typeof item !== "object" || item === null) {
25
+ throw new Error(`${path} must contain JSON-compatible values. Send callbacks through story.action().`);
26
+ }
27
+ if (ancestors.has(item))
28
+ throw new Error(`${path} contains a circular reference.`);
29
+ if (!Array.isArray(item) &&
30
+ Object.getPrototypeOf(item) !== Object.prototype &&
31
+ Object.getPrototypeOf(item) !== null) {
32
+ throw new Error(`${path} must contain plain objects and arrays.`);
33
+ }
34
+ ancestors.add(item);
35
+ const result = Array.isArray(item)
36
+ ? Array.from(item, (child, index) => child === undefined ? null : visit(child, `${path}.${index}`))
37
+ : Object.fromEntries(Object.entries(item)
38
+ .filter(([, child]) => child !== undefined)
39
+ .map(([key, child]) => [key, visit(child, `${path}.${key}`)]));
40
+ ancestors.delete(item);
41
+ return result;
42
+ };
43
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
44
+ throw new Error(`${label} must be an object.`);
45
+ }
46
+ return visit(value, label);
47
+ }
@@ -0,0 +1,2 @@
1
+ import type { PresetProperty } from "storybook/internal/types";
2
+ export declare const previewAnnotations: PresetProperty<"previewAnnotations">;
@@ -0,0 +1,2 @@
1
+ import { fileURLToPath } from "node:url";
2
+ export const previewAnnotations = (entries = []) => [...entries, fileURLToPath(import.meta.resolve("./preview.js"))];
@@ -0,0 +1,2 @@
1
+ import { type JasprRuntime } from "./protocol.js";
2
+ export declare function loadRuntime(url: string): Promise<JasprRuntime>;
@@ -0,0 +1,28 @@
1
+ import { checkRuntime } from "./protocol.js";
2
+ let loading;
3
+ export function loadRuntime(url) {
4
+ if (loading)
5
+ return loading;
6
+ loading = new Promise((resolve, reject) => {
7
+ const script = document.createElement("script");
8
+ script.src = url;
9
+ script.onload = () => {
10
+ try {
11
+ resolve(checkRuntime(window.__jasprStorybook));
12
+ }
13
+ catch (error) {
14
+ script.remove();
15
+ reject(error);
16
+ }
17
+ };
18
+ script.onerror = () => {
19
+ script.remove();
20
+ reject(new Error(`Could not load the compiled Jaspr preview: ${url}`));
21
+ };
22
+ document.head.appendChild(script);
23
+ }).catch((error) => {
24
+ loading = undefined;
25
+ throw error;
26
+ });
27
+ return loading;
28
+ }
@@ -0,0 +1,3 @@
1
+ /** Extract explicitly selected Dart code without trying to parse Dart as JavaScript. */
2
+ export declare function extractSourceRegions(source: string, filename?: string): Record<string, string>;
3
+ export declare function readSourceRegions(files: string[]): Promise<Record<string, string>>;
@@ -0,0 +1,54 @@
1
+ import { readFile } from "node:fs/promises";
2
+ /** Extract explicitly selected Dart code without trying to parse Dart as JavaScript. */
3
+ export function extractSourceRegions(source, filename = "Dart source") {
4
+ const regions = Object.create(null);
5
+ let current;
6
+ for (const [index, line] of source.split(/\r?\n/).entries()) {
7
+ const marker = /^\s*\/\/\s*#(end)?docregion\s+([^\s,]+)\s*$/.exec(line);
8
+ if (!marker) {
9
+ current?.lines.push(line);
10
+ continue;
11
+ }
12
+ const name = marker[2] ?? "";
13
+ const fail = (message) => {
14
+ throw new Error(`${filename}:${index + 1}: ${message}`);
15
+ };
16
+ if (!marker[1]) {
17
+ if (current)
18
+ fail("Dart source regions must not be nested.");
19
+ if (Object.hasOwn(regions, name))
20
+ fail(`Duplicate Dart source region: ${name}`);
21
+ current = { name, lines: [] };
22
+ }
23
+ else {
24
+ if (!current || current.name !== name)
25
+ return fail(`Unmatched #enddocregion ${name}`);
26
+ const lines = current.lines;
27
+ const indentation = Math.min(...lines
28
+ .filter((value) => value.trim())
29
+ .map((value) => /^\s*/.exec(value)?.[0].length ?? 0));
30
+ const code = lines
31
+ .map((value) => value.slice(indentation))
32
+ .join("\n")
33
+ .trim();
34
+ if (!code)
35
+ fail(`Empty Dart source region: ${name}`);
36
+ regions[name] = code;
37
+ current = undefined;
38
+ }
39
+ }
40
+ if (current)
41
+ throw new Error(`${filename}: Unclosed #docregion ${current.name}`);
42
+ return regions;
43
+ }
44
+ export async function readSourceRegions(files) {
45
+ const sources = Object.create(null);
46
+ for (const file of new Set(files)) {
47
+ for (const [name, code] of Object.entries(extractSourceRegions(await readFile(file, "utf8"), file))) {
48
+ if (Object.hasOwn(sources, name))
49
+ throw new Error(`${file}: Duplicate Dart source region across files: ${name}`);
50
+ sources[name] = code;
51
+ }
52
+ }
53
+ return sources;
54
+ }
@@ -0,0 +1,28 @@
1
+ import type { Args, ComponentAnnotations, StoryAnnotations, WebRenderer, StorybookConfigRaw } from "storybook/internal/types";
2
+ import type { StorybookConfigVite } from "@storybook/builder-vite";
3
+ export interface JasprStory {
4
+ component: string;
5
+ args: Args;
6
+ }
7
+ export interface JasprRenderer extends WebRenderer {
8
+ component: string;
9
+ storyResult: JasprStory;
10
+ }
11
+ export type Meta<TArgs extends Args = Args> = ComponentAnnotations<JasprRenderer, TArgs>;
12
+ export type StoryObj<TArgs extends Args = Args> = StoryAnnotations<JasprRenderer, TArgs>;
13
+ export interface FrameworkOptions {
14
+ /** Dart client entrypoint, relative to the Storybook config directory. */
15
+ entrypoint: string;
16
+ /** SDK executable. Defaults to dart on PATH. */
17
+ dartExecutable?: string;
18
+ /** Additional Dart directories to watch, relative to the config directory. */
19
+ watchPaths?: string[];
20
+ /** Dart files with #docregion markers keyed by registered component name. */
21
+ sourceFiles?: string[];
22
+ }
23
+ export type StorybookConfig = Omit<StorybookConfigRaw, "framework"> & StorybookConfigVite & {
24
+ framework: {
25
+ name: string;
26
+ options: FrameworkOptions;
27
+ };
28
+ };
package/dist/types.js ADDED
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,13 @@
1
+ import type { Plugin } from "vite";
2
+ import type { FrameworkOptions } from "./types.js";
3
+ export type CompiledPreview = ReadonlyMap<string, Buffer>;
4
+ export interface PreviewAssets {
5
+ entry: string;
6
+ files: {
7
+ fileName: string;
8
+ source: Buffer;
9
+ }[];
10
+ }
11
+ export declare function compilePreview(entrypoint: string, dartExecutable: string, production: boolean): Promise<CompiledPreview>;
12
+ export declare function previewAssets(preview: CompiledPreview, assetsDir: string): PreviewAssets;
13
+ export declare function dartPreviewPlugin(options: FrameworkOptions, configDir: string): Plugin;
@@ -0,0 +1,178 @@
1
+ import { execFile } from "node:child_process";
2
+ import { createHash } from "node:crypto";
3
+ import { access, mkdtemp, readdir, readFile, rm } from "node:fs/promises";
4
+ import { tmpdir } from "node:os";
5
+ import { dirname, isAbsolute, join, posix, relative, resolve, sep, } from "node:path";
6
+ import { promisify } from "node:util";
7
+ import { readSourceRegions } from "./sources.js";
8
+ const exec = promisify(execFile);
9
+ const virtualId = "virtual:jaspr-storybook-runtime";
10
+ const resolvedId = `\0${virtualId}`;
11
+ const previewName = "preview.js";
12
+ const previewOutput = /^preview\.js(?:_\d+\.part\.js)?$/;
13
+ const devPrefix = "/@jaspr-storybook";
14
+ const devUrl = `${devPrefix}/${previewName}`;
15
+ async function packageConfig(entrypoint) {
16
+ let directory = dirname(entrypoint);
17
+ while (true) {
18
+ const candidate = join(directory, ".dart_tool", "package_config.json");
19
+ try {
20
+ await access(candidate);
21
+ return candidate;
22
+ }
23
+ catch {
24
+ const parent = dirname(directory);
25
+ if (directory === parent)
26
+ throw new Error("Run dart pub get before starting Jaspr Storybook.");
27
+ directory = parent;
28
+ }
29
+ }
30
+ }
31
+ export async function compilePreview(entrypoint, dartExecutable, production) {
32
+ const packages = await packageConfig(entrypoint);
33
+ const scratch = await mkdtemp(join(tmpdir(), "jaspr-storybook-"));
34
+ try {
35
+ const output = join(scratch, previewName);
36
+ await exec(dartExecutable, [
37
+ "compile",
38
+ "js",
39
+ "--no-source-maps",
40
+ `--packages=${packages}`,
41
+ production ? "-O2" : "-O1",
42
+ "-o",
43
+ output,
44
+ entrypoint,
45
+ ], { cwd: dirname(entrypoint), maxBuffer: 8 * 1024 * 1024 });
46
+ const names = (await readdir(scratch))
47
+ .filter((name) => previewOutput.test(name))
48
+ .sort();
49
+ return new Map(await Promise.all(names.map(async (name) => [name, await readFile(join(scratch, name))])));
50
+ }
51
+ catch (error) {
52
+ const output = error;
53
+ throw new Error(`Jaspr Storybook could not compile ${entrypoint}.\n${output.stdout ?? ""}${output.stderr ?? ""}${output.message ?? ""}`, { cause: error });
54
+ }
55
+ finally {
56
+ await rm(scratch, { recursive: true, force: true });
57
+ }
58
+ }
59
+ export function previewAssets(preview, assetsDir) {
60
+ const hash = createHash("sha256");
61
+ for (const [name, source] of preview)
62
+ hash.update(`${name}\0${source.length}\0`).update(source);
63
+ const directory = posix.join(assetsDir, `jaspr-preview-${hash.digest("hex").slice(0, 12)}`);
64
+ return {
65
+ entry: posix.join(directory, previewName),
66
+ files: [...preview].map(([name, source]) => ({
67
+ fileName: posix.join(directory, name),
68
+ source,
69
+ })),
70
+ };
71
+ }
72
+ export function dartPreviewPlugin(options, configDir) {
73
+ const entrypoint = resolve(configDir, options.entrypoint);
74
+ const sourceFiles = [
75
+ entrypoint,
76
+ ...(options.sourceFiles ?? []).map((path) => resolve(configDir, path)),
77
+ ];
78
+ const watchPaths = [
79
+ dirname(entrypoint),
80
+ ...sourceFiles.map(dirname),
81
+ ...(options.watchPaths ?? []).map((path) => resolve(configDir, path)),
82
+ ];
83
+ let production = false;
84
+ let assetsDir = "assets";
85
+ let bundle = new Map();
86
+ let sources = {};
87
+ let queued = Promise.resolve();
88
+ let timer;
89
+ let server;
90
+ const recompile = () => {
91
+ queued = queued.then(async () => {
92
+ try {
93
+ const next = await compilePreview(entrypoint, options.dartExecutable ?? "dart", production);
94
+ const nextSources = await readSourceRegions(sourceFiles);
95
+ bundle = next;
96
+ sources = nextSources;
97
+ const module = server?.moduleGraph.getModuleById(resolvedId);
98
+ if (module)
99
+ server?.moduleGraph.invalidateModule(module);
100
+ server?.ws.send({ type: "full-reload" });
101
+ }
102
+ catch (error) {
103
+ const message = error instanceof Error ? error.message : String(error);
104
+ server?.config.logger.error(message);
105
+ server?.ws.send({ type: "error", err: { message, stack: "" } });
106
+ }
107
+ });
108
+ };
109
+ return {
110
+ name: "jaspr-storybook",
111
+ configResolved(config) {
112
+ production = config.command === "build";
113
+ assetsDir = config.build.assetsDir;
114
+ },
115
+ async buildStart() {
116
+ sources = await readSourceRegions(sourceFiles);
117
+ bundle = await compilePreview(entrypoint, options.dartExecutable ?? "dart", production);
118
+ },
119
+ resolveId(id) {
120
+ if (id === virtualId)
121
+ return resolvedId;
122
+ },
123
+ load(id) {
124
+ if (id !== resolvedId)
125
+ return;
126
+ const sourceExport = `export const dartSources = ${JSON.stringify(sources)};`;
127
+ if (!production)
128
+ return `${sourceExport} export const bundleUrl = ${JSON.stringify(devUrl)};`;
129
+ const assets = previewAssets(bundle, assetsDir);
130
+ let reference = "";
131
+ for (const file of assets.files) {
132
+ const emitted = this.emitFile({ type: "asset", ...file });
133
+ if (file.fileName === assets.entry)
134
+ reference = emitted;
135
+ }
136
+ return `${sourceExport} export const bundleUrl = import.meta.ROLLUP_FILE_URL_${reference};`;
137
+ },
138
+ configureServer(devServer) {
139
+ server = devServer;
140
+ server.middlewares.use(devPrefix, (request, response, next) => {
141
+ const name = new URL(request.url ?? "/", "http://localhost").pathname;
142
+ const source = bundle.get(name.slice(1));
143
+ if (!source)
144
+ return next();
145
+ response.setHeader("Content-Type", "application/javascript; charset=utf-8");
146
+ response.setHeader("Cache-Control", "no-store");
147
+ response.end(source);
148
+ });
149
+ server.watcher.add(watchPaths);
150
+ const onChange = (path) => {
151
+ const absolute = resolve(path);
152
+ if (!absolute.endsWith(".dart") ||
153
+ !watchPaths.some((directory) => {
154
+ const pathFromDirectory = relative(directory, absolute);
155
+ return (pathFromDirectory !== ".." &&
156
+ !pathFromDirectory.startsWith(`..${sep}`) &&
157
+ !isAbsolute(pathFromDirectory));
158
+ }))
159
+ return;
160
+ if (timer)
161
+ clearTimeout(timer);
162
+ timer = setTimeout(recompile, 150);
163
+ };
164
+ server.watcher
165
+ .on("add", onChange)
166
+ .on("change", onChange)
167
+ .on("unlink", onChange);
168
+ server.httpServer?.once("close", () => {
169
+ if (timer)
170
+ clearTimeout(timer);
171
+ server?.watcher
172
+ .off("add", onChange)
173
+ .off("change", onChange)
174
+ .off("unlink", onChange);
175
+ });
176
+ },
177
+ };
178
+ }
package/package.json CHANGED
@@ -1,6 +1,78 @@
1
1
  {
2
2
  "name": "@codegrowers/storybook-jaspr-vite",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.1",
4
+ "description": "A native Storybook renderer and Vite framework for Jaspr components written in Dart.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "keywords": [
8
+ "storybook",
9
+ "jaspr",
10
+ "dart",
11
+ "vite",
12
+ "renderer"
13
+ ],
14
+ "exports": {
15
+ ".": {
16
+ "types": "./dist/index.d.ts",
17
+ "default": "./dist/index.js"
18
+ },
19
+ "./preset": "./dist/preset.js",
20
+ "./renderer-preset": "./dist/renderer-preset.js",
21
+ "./preview": "./dist/preview.js",
22
+ "./package.json": "./package.json"
23
+ },
24
+ "files": [
25
+ "dist",
26
+ "preset.js",
27
+ "README.md",
28
+ "STORYBOOK.md",
29
+ "CHANGELOG.md",
30
+ "LICENSE"
31
+ ],
32
+ "scripts": {
33
+ "dev": "bun run build && bun run --bun storybook dev --config-dir example/storybook --port 6006 --no-open --disable-telemetry",
34
+ "build": "bun run --bun tsc -p tsconfig.build.json",
35
+ "build:example": "bun run build && bun run --bun storybook build --config-dir example/storybook --output-dir storybook-static --disable-telemetry",
36
+ "preview": "bun ./tool/serve-example.ts",
37
+ "format": "biome format --write src test tool example/storybook example/stories package.json tsconfig.json tsconfig.build.json biome.json preset.js",
38
+ "format:check": "biome format src test tool example/storybook example/stories package.json tsconfig.json tsconfig.build.json biome.json preset.js",
39
+ "lint": "biome lint src test tool example/storybook example/stories",
40
+ "typecheck": "tsc --noEmit",
41
+ "test": "bun test",
42
+ "prepublishOnly": "bun run build && bun run format:check && bun run lint && bun run typecheck && bun test",
43
+ "prepack": "bun run build"
44
+ },
45
+ "dependencies": {
46
+ "@storybook/builder-vite": "10.6.5",
47
+ "refractor": "^5.0.0"
48
+ },
49
+ "peerDependencies": {
50
+ "storybook": "^10.6.5",
51
+ "vite": "^8.3.5"
52
+ },
53
+ "devDependencies": {
54
+ "@biomejs/biome": "2.6.4",
55
+ "@storybook/addon-docs": "10.6.5",
56
+ "@types/bun": "1.3.11",
57
+ "@types/node": "24.10.1",
58
+ "storybook": "10.6.5",
59
+ "typescript": "6.0.3",
60
+ "vite": "8.3.5"
61
+ },
62
+ "repository": {
63
+ "type": "git",
64
+ "url": "git+https://github.com/Code-Growers/storybook-jaspr-vite.git"
65
+ },
66
+ "homepage": "https://github.com/Code-Growers/storybook-jaspr-vite#readme",
67
+ "bugs": {
68
+ "url": "https://github.com/Code-Growers/storybook-jaspr-vite/issues"
69
+ },
70
+ "publishConfig": {
71
+ "access": "public",
72
+ "registry": "https://registry.npmjs.org/"
73
+ },
74
+ "engines": {
75
+ "bun": ">=1.4.2"
76
+ },
77
+ "packageManager": "bun@1.4.2"
78
+ }
package/preset.js ADDED
@@ -0,0 +1 @@
1
+ export * from "./dist/preset.js";