@codegrowers/storybook-jaspr-vite 1.0.1 → 2.0.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,13 @@
1
1
  # Changelog
2
2
 
3
+ ## 2.0.0-beta.0
4
+
5
+ - Require Storybook 11.0.0-beta.3; retain CSF 3 authoring and the v1 Dart bridge.
6
+ - Provide headless Dart component and story docs through Storybook provider hooks.
7
+ - Trace Dart imports, exports, parts, conditional and deferred dependencies for native affected-story tools.
8
+ - Support controlled argument updates in portable Vitest stories and surface nested Jaspr build failures.
9
+ - Fix managerHead configuration typing, package a Jaspr workflow skill, and verify native CLI component/a11y tests including a deliberate failing render.
10
+
3
11
  ## 1.0.1
4
12
 
5
13
  - Keep the parts dart2js emits for deferred imports. Development serves them
package/README.md CHANGED
@@ -6,11 +6,12 @@ Controls, record Actions and run TypeScript play functions against the DOM.
6
6
 
7
7
  MIT licensed. Requires the companion
8
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.
9
+ Beta `2.0.0-beta.0` supports Storybook `11.0.0-beta.3` and
10
+ `jaspr_storybook 1.1.0-beta.1` on Jaspr 0.24.
10
11
 
11
12
  ```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
13
+ bun add --dev @codegrowers/storybook-jaspr-vite@2.0.0-beta.0 storybook@11.0.0-beta.3 vite@8.3.5 @storybook/addon-docs@11.0.0-beta.3
14
+ dart pub add --dev jaspr_storybook:1.1.0-beta.1
14
15
  ```
15
16
 
16
17
  Register builders with `registerStorybook` in a Dart client entrypoint, configure
@@ -38,15 +39,22 @@ Docs can show actual Dart builders selected with `#docregion` markers, with Dart
38
39
  syntax highlighting. See [STORYBOOK.md](STORYBOOK.md) for Dart registration, CSF, controls, actions,
39
40
  watch options, styling, examples and release instructions.
40
41
 
41
- Tested with Jaspr 0.23.3 and 0.23.5, Storybook 10.6.5, Vite 8.3.5,
42
+ Tested with Jaspr 0.24.0-beta.1, Storybook 11.0.0-beta.3, Vite 8.3.5,
42
43
  Bun 1.4.2 and Dart 3.13.5. The Dart SDK must be on `PATH`, or set
43
44
  `framework.options.dartExecutable`. Node execution has not been verified.
44
45
 
45
46
  Styles and assets belong to the consumer. Argument values must be compatible
46
47
  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.
48
+ provide SSR/hydration testing, Wasm output or automatic Dart story discovery.
49
+ Optional generated metadata supplies resolved Dart constructor documentation.
49
50
 
50
51
  To develop: run `bun install`, `bun run build`, `bun run format:check`,
51
52
  `bun run lint`, `bun run typecheck` and `bun test`. Run `dart pub get` in
52
53
  `example/`, then `bun run build:example` and `bun run preview` from the root.
54
+
55
+ ## Headless agent workflow
56
+
57
+ Storybook 11 CLI documentation, Dart dependency tracing, Vitest component tests
58
+ and local review tools are supported by the native Jaspr providers. The package
59
+ includes `skills/jaspr-storybook-workflow`. See [STORYBOOK.md](STORYBOOK.md)
60
+ for metadata generation, browser setup, limitations and paired release checks.
package/STORYBOOK.md CHANGED
@@ -1,192 +1,140 @@
1
- # Storybook for Jaspr
1
+ # Storybook 11 for Jaspr
2
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:
3
+ The beta pair is `jaspr_storybook 1.1.0-beta.1` and
4
+ `@codegrowers/storybook-jaspr-vite 2.0.0-beta.0`, tested with Storybook
5
+ `11.0.0-beta.3`, Jaspr `0.24.0-beta.1`, Vite `8.3.5`, Bun `1.4.2`,
6
+ TypeScript `6.0.3`, and Vitest `4.1.12`. Keep all Storybook packages on the same
7
+ exact beta. The stable npm 1.x line supports Storybook 10; Dart 1.0.x supports
8
+ Jaspr 0.23. Node execution has not been verified.
5
9
 
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:
10
+ ## Install
16
11
 
17
12
  ```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;
13
+ dart pub add --dev jaspr_storybook:1.1.0-beta.1
14
+ bun add --dev @codegrowers/storybook-jaspr-vite@2.0.0-beta.0 storybook@11.0.0-beta.3 @storybook/addon-docs@11.0.0-beta.3 vite@8.3.5
50
15
  ```
51
16
 
52
- Write normal CSF stories, using the Dart registry key as `component`:
17
+ Register client-side Dart builders with `registerStorybook`, and use their keys
18
+ as `component` in TypeScript CSF 3 stories. Import `Meta`, `StoryObj` and
19
+ `StorybookConfig` from the npm framework. The framework config requires
20
+ `options.entrypoint`, relative to the Storybook config directory. Optional
21
+ `sourceFiles` selects additional Dart snippet files, and `watchPaths` includes
22
+ external Dart sources. Consumer CSS and fonts stay in the consumer project.
53
23
 
54
- ```ts
55
- import type { Meta, StoryObj } from '@codegrowers/storybook-jaspr-vite';
24
+ Wrap Dart examples in `// #docregion <builder-key>` and matching
25
+ `// #enddocregion <builder-key>` markers. The renderer exposes these examples in
26
+ Docs, the Code panel and the headless CLI. Story-specific
27
+ `parameters.docs.source.code` takes precedence. Snippets show the fixture as
28
+ written; they are not reconstructed from control values.
56
29
 
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>;
30
+ ## Headless documentation and change detection
68
31
 
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
32
+ ```sh
33
+ bun run --bun storybook tools --no-attach docs list --withStoryIds true --json
34
+ bun run --bun storybook tools --no-attach docs show --id <component-id>
35
+ bun run --bun storybook tools --no-attach stories find-by-component --componentPaths '["lib/controls.dart"]' --json
121
36
  ```
122
37
 
123
- ```ts
124
- options: {
125
- entrypoint: '../lib/storybook.client.dart',
126
- sourceFiles: ['../lib/component_stories.dart'],
38
+ Run from the Storybook project directory. For another config location, put
39
+ `--config-dir <directory>` after `tools`, before `docs` or `stories`.
40
+ The framework contributes Storybook 11 docgen, story-docs and import-parser
41
+ providers. They do not compile or execute Dart to read documentation. The import
42
+ parser maps CSF registration keys to Dart files and follows imports, exports,
43
+ parts, conditional and deferred imports. Shared fixtures intentionally produce
44
+ conservative affected sets. CSS, tokens and dynamically loaded assets may require
45
+ explicit consumer selection.
46
+
47
+ For constructor documentation, create a metadata configuration:
48
+
49
+ ```json
50
+ {
51
+ "schemaVersion": 1,
52
+ "root": "..",
53
+ "components": {
54
+ "button": {
55
+ "name": "AppButton",
56
+ "library": "lib/controls.dart",
57
+ "symbols": ["AppButton"],
58
+ "import": "import 'package:my_app/controls.dart';",
59
+ "description": "Primary action control",
60
+ "contract": "Use the shared button for application actions.",
61
+ "example": {"file": "lib/stories.dart", "region": "button"}
62
+ }
63
+ }
127
64
  }
128
65
  ```
129
66
 
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.
67
+ Paths are relative to `root`, which is relative to the config file. Symbols must
68
+ be exported from the specified library. Optional `example.supportRegions` includes
69
+ supporting definitions before the main region. Generate with:
136
70
 
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.
71
+ ```sh
72
+ dart run jaspr_storybook:metadata --config .storybook/metadata.config.json --output .storybook/components.json
73
+ # CI freshness check:
74
+ dart run jaspr_storybook:metadata --config .storybook/metadata.config.json --output .storybook/components.json --check
75
+ ```
141
76
 
142
- ## Examples and development
77
+ Set `framework.options.componentManifest: './components.json'`. The extractor
78
+ uses resolved Dart types, constructor defaults and documentation. It is a VM-only
79
+ library (`package:jaspr_storybook/metadata.dart`); the browser runtime never imports
80
+ analyzer. Story args remain explicit fixture controls, separate from constructor
81
+ parameters. Regenerate after source changes. Manifest schema v1 belongs to this
82
+ package; the translation to Storybook's experimental provider APIs is isolated
83
+ inside the npm framework and tested against the pinned beta.
143
84
 
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.
85
+ ## Tests and review
148
86
 
149
- In the Dart runtime repository:
87
+ Add the matching `@storybook/addon-vitest`, `@storybook/addon-a11y`, Vitest 4 and
88
+ `@vitest/browser-playwright`. Configure a nested `test.projects` entry with
89
+ `storybookTest({configDir: <absolute-directory>})` and browser mode. See the npm
90
+ repository's `vitest.config.ts`; it uses an installed Chrome channel and does not
91
+ download browsers. The example is verified using both Vitest and the native CLI.
150
92
 
151
93
  ```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
94
+ bun run --bun storybook tools --no-attach test run --json
95
+ bun run --bun storybook tools --port 6006 review create --help
160
96
  ```
161
97
 
162
- In the npm framework repository:
98
+ Inspect nonzero `totalTestCount`, component/a11y failure counts and unhandled
99
+ errors. Failed story tests return a nonzero exit status. Preview URLs and review
100
+ creation require a running Storybook dev server. Review creation replaces the
101
+ active local review; use IDs returned by discovery tools.
163
102
 
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
- ```
103
+ Controlled Dart `updateArgs` updates work in portable tests as well as the
104
+ manager. Mount/update promises settle before play functions. Nested Jaspr 0.24
105
+ build failures are reported through its console-error path; the renderer observes
106
+ that specific message and fails active previews conservatively, preserving the
107
+ original console output and restoring its observer on teardown. Concurrent
108
+ previews cannot attribute such errors to one instance because Jaspr exposes no
109
+ instance-specific callback.
177
110
 
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.
111
+ This is a client renderer. Source edits recompile Dart and reload the preview;
112
+ there is no stateful hot reload, server-only rendering, or SSR/hydration testing.
113
+ Component tests do not replace application authentication or backend tests.
181
114
 
182
- ## Release
115
+ ## Agent skills
183
116
 
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.
117
+ Both package archives contain `skills/jaspr-storybook-workflow/SKILL.md`.
118
+ In Dart consumers install the version from the resolved package:
119
+
120
+ ```sh
121
+ dart run skills@ get --package jaspr_storybook --agent codex --all
122
+ ```
187
123
 
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.
124
+ npm consumers can copy that skill directory from the installed package into their
125
+ agent's project skill directory. The Dart repository owns the skill; synchronize
126
+ its identical copy into the npm package for paired releases. Project-specific
127
+ component selection, design tokens, localization and verification rules take
128
+ precedence over generic examples. The integration uses Storybook's native CLI;
129
+ no additional Storybook MCP server is required.
130
+
131
+ ## Release verification
132
+
133
+ Run Dart format, analysis, tests and `dart pub publish --dry-run`. In the npm
134
+ repository run format:check, lint, typecheck, test, test:integration and
135
+ build:example, inspect `bun pm pack --dry-run`, and verify the example in a browser.
136
+ The integration script checks headless source, transitive Dart dependencies,
137
+ nonempty passing component/a11y tests and a deliberately failing nested build.
138
+ Publish the Dart prerelease first, then `bun publish --access public --tag beta`.
139
+ Never move npm latest to this beta. Test clean registry installations and tag
140
+ both source repositories after successful publication.
@@ -0,0 +1,4 @@
1
+ type Listener = (error: Error) => void;
2
+ /** Jaspr 0.24's binding has no error callback and reports nested failures here. */
3
+ export declare function observeBuildErrors(listener: Listener): () => void;
4
+ export {};
@@ -0,0 +1,32 @@
1
+ const listeners = new Set();
2
+ let original;
3
+ let intercepted;
4
+ /** Jaspr 0.24's binding has no error callback and reports nested failures here. */
5
+ export function observeBuildErrors(listener) {
6
+ if (!original) {
7
+ original = console.error;
8
+ const forward = original;
9
+ intercepted = (...args) => {
10
+ forward.apply(console, args);
11
+ if (typeof args[0] !== "string" ||
12
+ !args[0].startsWith("Error while building "))
13
+ return;
14
+ const error = new Error(args[0]);
15
+ // The binding does not identify a story instance. Fail active previews
16
+ // conservatively rather than silently accepting a fallback as a render.
17
+ for (const report of [...listeners])
18
+ report(error);
19
+ };
20
+ console.error = intercepted;
21
+ }
22
+ listeners.add(listener);
23
+ return () => {
24
+ listeners.delete(listener);
25
+ if (listeners.size === 0 && original) {
26
+ if (console.error === intercepted)
27
+ console.error = original;
28
+ original = undefined;
29
+ intercepted = undefined;
30
+ }
31
+ };
32
+ }
@@ -0,0 +1,3 @@
1
+ import type { DocgenWorkerModule } from "storybook/internal/types";
2
+ import { type MetadataOptions } from "./metadata.js";
3
+ export declare const createDocgenProvider: DocgenWorkerModule<MetadataOptions>["createDocgenProvider"];
package/dist/docgen.js ADDED
@@ -0,0 +1,31 @@
1
+ import { readComponent } from "./metadata.js";
2
+ export const createDocgenProvider = (options) => {
3
+ if (!options)
4
+ throw new Error("Jaspr docgen requires framework options.");
5
+ return (next) => async (input) => {
6
+ const component = await readComponent(input.entry, options);
7
+ if (!component)
8
+ return next(input);
9
+ const { metadata, key, id, meta } = component;
10
+ const description = meta?.getValue([
11
+ "parameters",
12
+ "docs",
13
+ "description",
14
+ "component",
15
+ ]);
16
+ return {
17
+ ...(await next(input)),
18
+ id,
19
+ name: metadata?.name ?? key,
20
+ path: input.entry.importPath,
21
+ renderer: "jaspr",
22
+ description: metadata?.description ??
23
+ (typeof description === "string" ? description : undefined),
24
+ apiDescription: metadata?.apiDescription ??
25
+ "Dart builder registered as `" +
26
+ key +
27
+ "`. Story controls are fixture inputs; read the Dart source for the component constructor API.",
28
+ jsDocTags: {},
29
+ };
30
+ };
31
+ };
@@ -0,0 +1,5 @@
1
+ import type { StorybookConfigRaw } from "storybook/internal/types";
2
+ import { type MetadataOptions } from "./metadata.js";
3
+ type Parsers = Exclude<NonNullable<StorybookConfigRaw["experimental_importParsers"]>, (...args: never[]) => unknown>;
4
+ export declare function importParsers(options: MetadataOptions): Parsers;
5
+ export {};
@@ -0,0 +1,86 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import { dirname, resolve } from "node:path";
3
+ import { fileURLToPath, pathToFileURL } from "node:url";
4
+ import { loadCsf } from "storybook/internal/csf-tools";
5
+ import { readMetadata } from "./metadata.js";
6
+ const edge = (specifier) => ({
7
+ specifier,
8
+ kind: "static",
9
+ importedNames: null,
10
+ });
11
+ async function resolveDartImport(specifier, file) {
12
+ if (specifier.startsWith("dart:"))
13
+ return undefined;
14
+ if (!specifier.startsWith("package:"))
15
+ return resolve(dirname(file), specifier);
16
+ const [name, ...segments] = specifier.slice(8).split("/");
17
+ let directory = dirname(file);
18
+ while (true) {
19
+ const config = resolve(directory, ".dart_tool/package_config.json");
20
+ try {
21
+ const data = JSON.parse(await readFile(config, "utf8"));
22
+ const pkg = data.packages.find((pkg) => pkg.name === name);
23
+ if (!pkg)
24
+ throw new Error(`Dart package ${name} is missing from ${config}`);
25
+ const root = new URL(pkg.rootUri, pathToFileURL(config));
26
+ return fileURLToPath(new URL(segments.join("/"), new URL(pkg.packageUri ?? "lib/", root)));
27
+ }
28
+ catch (error) {
29
+ if (error.code !== "ENOENT")
30
+ throw error;
31
+ const parent = dirname(directory);
32
+ if (parent === directory)
33
+ throw new Error(`Run dart pub get before tracing ${file}`);
34
+ directory = parent;
35
+ }
36
+ }
37
+ }
38
+ export function importParsers(options) {
39
+ return [
40
+ {
41
+ extensions: [".ts", ".tsx", ".js", ".jsx", ".mts", ".mjs"],
42
+ async parse({ filePath, source }, context) {
43
+ const edges = await context.parseScriptWithOxc(source, filePath);
44
+ if (!/\.stories\.[cm]?[jt]sx?$/.test(filePath))
45
+ return edges;
46
+ const csf = loadCsf(source, {
47
+ fileName: filePath,
48
+ makeTitle: (title) => title,
49
+ }).parse();
50
+ const key = csf.objects({ stories: false })[0]?.getValue(["component"]);
51
+ if (typeof key !== "string")
52
+ return edges;
53
+ const metadata = (await readMetadata(options))[key];
54
+ const sources = metadata?.sourceFiles ?? [
55
+ resolve(options.configDir, options.entrypoint),
56
+ ...(options.sourceFiles ?? []).map((file) => resolve(options.configDir, file)),
57
+ ];
58
+ return [
59
+ ...edges,
60
+ ...sources.map(edge),
61
+ ...(options.componentManifest
62
+ ? [edge(resolve(options.configDir, options.componentManifest))]
63
+ : []),
64
+ ];
65
+ },
66
+ },
67
+ {
68
+ extensions: [".dart"],
69
+ async parse({ filePath, source }) {
70
+ // Include every conditional branch and deferred import conservatively.
71
+ const directives = source
72
+ .replace(/\/\*[\s\S]*?\*\//g, "")
73
+ .matchAll(/^\s*(?:import|export|part)\s+(['"])[\s\S]*?;/gm);
74
+ const imports = new Set();
75
+ for (const directive of directives) {
76
+ for (const literal of directive[0].matchAll(/(['"])([^'"\n]+)\1/g)) {
77
+ const resolved = await resolveDartImport(literal[2] ?? "", filePath);
78
+ if (resolved)
79
+ imports.add(resolved);
80
+ }
81
+ }
82
+ return [...imports].map(edge);
83
+ },
84
+ },
85
+ ];
86
+ }
@@ -0,0 +1,23 @@
1
+ import type { IndexEntry } from "storybook/internal/types";
2
+ import type { FrameworkOptions } from "./types.js";
3
+ export interface ComponentMetadata {
4
+ name: string;
5
+ description?: string;
6
+ apiDescription?: string;
7
+ import?: string;
8
+ sourceFiles?: string[];
9
+ exampleCode?: string;
10
+ }
11
+ export interface MetadataOptions extends FrameworkOptions {
12
+ configDir: string;
13
+ workingDir: string;
14
+ }
15
+ export declare function readMetadata(options: MetadataOptions): Promise<Record<string, ComponentMetadata>>;
16
+ export declare function readComponent(entry: IndexEntry, options: MetadataOptions): Promise<{
17
+ csf: import("storybook/internal/csf-tools").CsfFile & import("storybook/internal/types").IndexedCSFFile;
18
+ meta: import("storybook/internal/csf-tools").CsfObject | undefined;
19
+ key: string;
20
+ metadata: ComponentMetadata | undefined;
21
+ id: string;
22
+ } | undefined>;
23
+ export declare function readExamples(options: MetadataOptions): Promise<Record<string, string>>;
@@ -0,0 +1,47 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import { dirname, resolve } from "node:path";
3
+ import { readCsf } from "storybook/internal/csf-tools";
4
+ import { readSourceRegions } from "./sources.js";
5
+ export async function readMetadata(options) {
6
+ if (!options.componentManifest)
7
+ return {};
8
+ const path = resolve(options.configDir, options.componentManifest);
9
+ const data = JSON.parse(await readFile(path, "utf8"));
10
+ if (data.schemaVersion !== 1 ||
11
+ !data.components ||
12
+ Array.isArray(data.components))
13
+ throw new Error(`Invalid Jaspr component manifest: ${path}`);
14
+ const root = resolve(dirname(path), data.root ?? ".");
15
+ for (const component of Object.values(data.components)) {
16
+ if (typeof component.name !== "string")
17
+ throw new Error(`Missing component name in ${path}`);
18
+ component.sourceFiles = component.sourceFiles?.map((file) => resolve(root, file));
19
+ }
20
+ return data.components;
21
+ }
22
+ export async function readComponent(entry, options) {
23
+ const csf = (await readCsf(resolve(options.workingDir, entry.importPath), {
24
+ makeTitle: () => entry.title,
25
+ })).parse();
26
+ const meta = csf.objects({ stories: false })[0];
27
+ const key = meta?.getValue(["component"]);
28
+ if (typeof key !== "string")
29
+ return undefined;
30
+ const metadata = (await readMetadata(options))[key];
31
+ return {
32
+ csf,
33
+ meta,
34
+ key,
35
+ metadata,
36
+ id: csf.meta.id ??
37
+ csf.stories[0]?.id.split("--")[0] ??
38
+ entry.id.split("--")[0] ??
39
+ key,
40
+ };
41
+ }
42
+ export async function readExamples(options) {
43
+ return readSourceRegions([
44
+ resolve(options.configDir, options.entrypoint),
45
+ ...(options.sourceFiles ?? []).map((path) => resolve(options.configDir, path)),
46
+ ]);
47
+ }
package/dist/preset.d.ts CHANGED
@@ -1,5 +1,11 @@
1
1
  import type { PresetProperty } from "storybook/internal/types";
2
2
  import type { ViteFinal } from "@storybook/builder-vite";
3
+ import type { Options, StoryDocsProviderPreset } from "storybook/internal/types";
4
+ import { importParsers } from "./import-parsers.js";
5
+ export declare const features: PresetProperty<"features">;
6
+ export declare const experimental_docgenProvider: PresetProperty<"experimental_docgenProvider">;
7
+ export declare const experimental_storyDocsProvider: StoryDocsProviderPreset;
8
+ export declare const experimental_importParsers: (parsers: ReturnType<typeof importParsers> | undefined, options: Options) => Promise<import("storybook/internal/core-server").ImportParser[]>;
3
9
  export declare const core: PresetProperty<"core">;
4
10
  export declare const managerEntries: (entries?: string[]) => string[];
5
11
  export declare const viteFinal: ViteFinal;
package/dist/preset.js CHANGED
@@ -2,6 +2,29 @@ import { fileURLToPath } from "node:url";
2
2
  import { dirname } from "node:path";
3
3
  import { mergeConfig, searchForWorkspaceRoot } from "vite";
4
4
  import { dartPreviewPlugin } from "./vite-plugin.js";
5
+ import { storyDocsProvider } from "./story-docs.js";
6
+ import { importParsers } from "./import-parsers.js";
7
+ async function metadataOptions(options) {
8
+ const framework = await options.presets.apply("framework");
9
+ return {
10
+ ...framework.options,
11
+ configDir: options.configDir,
12
+ workingDir: process.cwd(),
13
+ };
14
+ }
15
+ export const features = (features) => ({
16
+ ...features,
17
+ docgenServer: true,
18
+ });
19
+ export const experimental_docgenProvider = async (providers = [], options) => [
20
+ ...providers,
21
+ {
22
+ moduleSpecifier: fileURLToPath(import.meta.resolve("./docgen.js")),
23
+ options: await metadataOptions(options),
24
+ },
25
+ ];
26
+ export const experimental_storyDocsProvider = async (next, options) => storyDocsProvider(next, await metadataOptions(options));
27
+ export const experimental_importParsers = async (parsers = [], options) => [...parsers, ...importParsers(await metadataOptions(options))];
5
28
  export const core = {
6
29
  builder: import.meta.resolve("@storybook/builder-vite"),
7
30
  renderer: import.meta.resolve("./renderer-preset.js"),
package/dist/preview.js CHANGED
@@ -6,6 +6,7 @@ import { bundleUrl, dartSources } from "virtual:jaspr-storybook-runtime";
6
6
  import "./dart-highlighting.js";
7
7
  import { checkRecord } from "./protocol.js";
8
8
  import { loadRuntime } from "./runtime.js";
9
+ import { observeBuildErrors } from "./build-errors.js";
9
10
  export const parameters = {
10
11
  renderer: "jaspr",
11
12
  docs: {
@@ -44,6 +45,8 @@ export async function renderToCanvas(context, canvas) {
44
45
  !previous.disposed &&
45
46
  previous.component === story.component &&
46
47
  !context.forceRemount) {
48
+ previous.args = args;
49
+ previous.globals = globals;
47
50
  previous.ready = previous.ready
48
51
  .catch(() => { })
49
52
  .then(() => {
@@ -51,6 +54,8 @@ export async function renderToCanvas(context, canvas) {
51
54
  return runtime.update(previous.host.id, args, globals);
52
55
  });
53
56
  await previous.ready;
57
+ if (previous.failure)
58
+ throw previous.failure;
54
59
  if (!previous.disposed)
55
60
  emitSource();
56
61
  context.showMain();
@@ -61,16 +66,21 @@ export async function renderToCanvas(context, canvas) {
61
66
  const host = document.createElement("div");
62
67
  host.id = `jaspr-storybook-${++nextInstance}`;
63
68
  canvas.appendChild(host);
69
+ let rendering = true;
70
+ let stopObserving = () => { };
64
71
  const session = {
65
72
  component: story.component,
66
73
  runtime,
67
74
  host,
68
75
  disposed: false,
69
76
  ready: Promise.resolve(),
77
+ args,
78
+ globals,
70
79
  dispose() {
71
80
  if (session.disposed)
72
81
  return;
73
82
  session.disposed = true;
83
+ stopObserving();
74
84
  try {
75
85
  runtime.unmount(host.id);
76
86
  }
@@ -84,6 +94,11 @@ export async function renderToCanvas(context, canvas) {
84
94
  },
85
95
  };
86
96
  sessions.set(canvas, session);
97
+ stopObserving = observeBuildErrors((error) => {
98
+ session.failure = error;
99
+ if (!rendering)
100
+ context.showException(error);
101
+ });
87
102
  session.ready = runtime.mount(host.id, story.component, host.id, args, globals, (type, payload) => {
88
103
  if (session.disposed)
89
104
  return;
@@ -92,6 +107,7 @@ export async function renderToCanvas(context, canvas) {
92
107
  const error = new Error(String(failure.message));
93
108
  if (typeof failure.stack === "string")
94
109
  error.stack = failure.stack;
110
+ session.failure = error;
95
111
  context.showException(error);
96
112
  return;
97
113
  }
@@ -102,14 +118,29 @@ export async function renderToCanvas(context, canvas) {
102
118
  action(event.name)(event.value);
103
119
  }
104
120
  else if (type === "args") {
121
+ const patch = checkRecord(payload, "updatedArgs");
122
+ session.args = { ...session.args, ...patch };
123
+ // Portable stories have no manager listening to UPDATE_STORY_ARGS.
124
+ // Apply controlled input locally as well as publishing it to Controls.
125
+ const updatedArgs = session.args;
126
+ session.ready = session.ready.then(async () => {
127
+ if (!session.disposed)
128
+ await runtime.update(host.id, updatedArgs, session.globals);
129
+ if (session.failure)
130
+ throw session.failure;
131
+ });
132
+ void session.ready.catch((error) => context.showException(error));
105
133
  addons.getChannel().emit(UPDATE_STORY_ARGS, {
106
134
  storyId: context.storyContext.id,
107
- updatedArgs: checkRecord(payload, "updatedArgs"),
135
+ updatedArgs: patch,
108
136
  });
109
137
  }
110
138
  });
111
139
  try {
112
140
  await session.ready;
141
+ if (session.failure)
142
+ throw session.failure;
143
+ rendering = false;
113
144
  if (!session.disposed) {
114
145
  emitSource();
115
146
  context.showMain();
@@ -0,0 +1,3 @@
1
+ import type { StoryDocsProvider } from "storybook/internal/types";
2
+ import { type MetadataOptions } from "./metadata.js";
3
+ export declare function storyDocsProvider(next: StoryDocsProvider, options: MetadataOptions): StoryDocsProvider;
@@ -0,0 +1,46 @@
1
+ import { readComponent, readExamples, } from "./metadata.js";
2
+ export function storyDocsProvider(next, options) {
3
+ return async (input) => {
4
+ const component = await readComponent(input.entry, options);
5
+ if (!component)
6
+ return next(input);
7
+ const { csf, metadata, key, id, meta } = component;
8
+ const examples = await readExamples(options);
9
+ const stories = {};
10
+ for (const story of csf.stories) {
11
+ const found = csf.storyObject(story.exportName);
12
+ const object = found?.ok ? found.object : undefined;
13
+ const override = object?.getValue(["parameters", "docs", "source", "code"]) ??
14
+ meta?.getValue(["parameters", "docs", "source", "code"]);
15
+ const description = object?.getValue([
16
+ "parameters",
17
+ "docs",
18
+ "description",
19
+ "story",
20
+ ]);
21
+ const code = typeof override === "string"
22
+ ? override
23
+ : (metadata?.exampleCode ?? examples[key]);
24
+ stories[story.id] = {
25
+ id: story.id,
26
+ name: story.name,
27
+ snippet: code
28
+ ? [metadata?.import, code].filter(Boolean).join("\n\n")
29
+ : undefined,
30
+ description: typeof description === "string" ? description : undefined,
31
+ warning: typeof override === "string"
32
+ ? undefined
33
+ : code
34
+ ? "Dart fixture source; story args select this variant. StorybookContext is a fixture adapter, not application state."
35
+ : "No Dart source region or explicit source example is configured.",
36
+ };
37
+ }
38
+ return {
39
+ ...(await next(input)),
40
+ id,
41
+ name: metadata?.name ?? key,
42
+ path: input.entry.importPath,
43
+ stories,
44
+ };
45
+ };
46
+ }
package/dist/types.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { Args, ComponentAnnotations, StoryAnnotations, WebRenderer, StorybookConfigRaw } from "storybook/internal/types";
1
+ import type { Args, ComponentAnnotations, StoryAnnotations, WebRenderer, StorybookConfig as BaseStorybookConfig } from "storybook/internal/types";
2
2
  import type { StorybookConfigVite } from "@storybook/builder-vite";
3
3
  export interface JasprStory {
4
4
  component: string;
@@ -19,8 +19,10 @@ export interface FrameworkOptions {
19
19
  watchPaths?: string[];
20
20
  /** Dart files with #docregion markers keyed by registered component name. */
21
21
  sourceFiles?: string[];
22
+ /** Generated Jaspr component metadata JSON, relative to the config directory. */
23
+ componentManifest?: string;
22
24
  }
23
- export type StorybookConfig = Omit<StorybookConfigRaw, "framework"> & StorybookConfigVite & {
25
+ export type StorybookConfig = Omit<BaseStorybookConfig, "framework"> & StorybookConfigVite & {
24
26
  framework: {
25
27
  name: string;
26
28
  options: FrameworkOptions;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@codegrowers/storybook-jaspr-vite",
3
- "version": "1.0.1",
3
+ "version": "2.0.0-beta.0",
4
4
  "description": "A native Storybook renderer and Vite framework for Jaspr components written in Dart.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -27,37 +27,44 @@
27
27
  "README.md",
28
28
  "STORYBOOK.md",
29
29
  "CHANGELOG.md",
30
- "LICENSE"
30
+ "LICENSE",
31
+ "skills"
31
32
  ],
32
33
  "scripts": {
33
- "dev": "bun run build && bun run --bun storybook dev --config-dir example/storybook --port 6006 --no-open --disable-telemetry",
34
+ "dev": "bun run build && bun run --bun storybook dev --config-dir example/storybook --port 6006 --disable-telemetry",
34
35
  "build": "bun run --bun tsc -p tsconfig.build.json",
35
36
  "build:example": "bun run build && bun run --bun storybook build --config-dir example/storybook --output-dir storybook-static --disable-telemetry",
36
37
  "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",
38
+ "format": "biome format --write src test tool example/storybook example/stories package.json tsconfig.json tsconfig.build.json biome.json preset.js vitest.config.ts",
39
+ "format:check": "biome format src test tool example/storybook example/stories package.json tsconfig.json tsconfig.build.json biome.json preset.js vitest.config.ts",
40
+ "lint": "biome lint src test tool example/storybook example/stories vitest.config.ts",
40
41
  "typecheck": "tsc --noEmit",
41
42
  "test": "bun test",
42
43
  "prepublishOnly": "bun run build && bun run format:check && bun run lint && bun run typecheck && bun test",
43
- "prepack": "bun run build"
44
+ "prepack": "bun run build",
45
+ "test:integration": "bun run build && bun tool/verify-cli.ts",
46
+ "test:stories": "bun run --bun vitest run"
44
47
  },
45
48
  "dependencies": {
46
- "@storybook/builder-vite": "10.6.5",
49
+ "@storybook/builder-vite": "11.0.0-beta.3",
47
50
  "refractor": "^5.0.0"
48
51
  },
49
52
  "peerDependencies": {
50
- "storybook": "^10.6.5",
53
+ "storybook": "^11.0.0-beta.3",
51
54
  "vite": "^8.3.5"
52
55
  },
53
56
  "devDependencies": {
54
57
  "@biomejs/biome": "2.6.4",
55
- "@storybook/addon-docs": "10.6.5",
58
+ "@storybook/addon-a11y": "11.0.0-beta.3",
59
+ "@storybook/addon-docs": "11.0.0-beta.3",
60
+ "@storybook/addon-vitest": "11.0.0-beta.3",
56
61
  "@types/bun": "1.3.11",
57
62
  "@types/node": "24.10.1",
58
- "storybook": "10.6.5",
63
+ "@vitest/browser-playwright": "4.1.12",
64
+ "storybook": "11.0.0-beta.3",
59
65
  "typescript": "6.0.3",
60
- "vite": "8.3.5"
66
+ "vite": "8.3.5",
67
+ "vitest": "4.1.12"
61
68
  },
62
69
  "repository": {
63
70
  "type": "git",
@@ -0,0 +1,84 @@
1
+ ---
2
+ name: jaspr-storybook-workflow
3
+ description: Discover, document, test and review Dart/Jaspr components with the Storybook 11 CLI and the Code Growers Jaspr renderer. Use for Jaspr stories and component-library work; application SSR and authentication still require application tests.
4
+ ---
5
+
6
+ # Jaspr Storybook workflow
7
+
8
+ Read the project's AGENTS.md and Storybook configuration. Use the locally pinned
9
+ Storybook and package manager; these examples use Bun from the Storybook project
10
+ directory. Put CLI connection options before the toolset. For a nonstandard
11
+ configuration directory add `--config-dir <directory>` after `tools`.
12
+
13
+ ## Discover before implementing
14
+
15
+ Use the project's component catalogue first when present: it owns composition,
16
+ layout, accessibility and localization rules. Then inspect native Storybook docs:
17
+
18
+ ```sh
19
+ bun run --bun storybook tools --no-attach docs list --withStoryIds true --json
20
+ bun run --bun storybook tools --no-attach docs show --id <returned-component-id>
21
+ bun run --bun storybook tools --no-attach docs show-story --storyId <returned-story-id>
22
+ ```
23
+
24
+ These commands read Dart examples without running the preview. Component IDs,
25
+ Dart registration keys and story IDs are distinct; always use returned IDs.
26
+ The optional `componentManifest` supplies resolved Dart constructor documentation.
27
+ Without it, source examples and explicit story documentation remain available,
28
+ but controls are not a complete Dart API reference. Do not infer constructors
29
+ from story args or invent unavailable metadata.
30
+
31
+ ## Author paired examples
32
+
33
+ Register a real Dart builder with `registerStorybook` and use its exact key as
34
+ CSF 3 `component`. Import Meta/StoryObj from @codegrowers/storybook-jaspr-vite.
35
+ Keep existing meta IDs and export names stable. Supply explicit args/argTypes;
36
+ arguments and globals must be JSON-compatible, never closures or components.
37
+ Use StorybookContext.action/updateArgs for fixture events and controlled state.
38
+ Namespace DOM IDs with instanceId for concurrent Docs previews.
39
+
40
+ Keep Dart source inside #docregion/#enddocregion markers matching the builder key.
41
+ Include supporting definitions in generated metadata where required. Explicit
42
+ parameters.docs.source.code overrides the region for a story-specific example.
43
+ Examples show fixture source, not code rewritten for each control value. Replace
44
+ fixture context with real state and localization when composing application UI.
45
+
46
+ After public API changes, regenerate the project's metadata and catalogue and
47
+ run their freshness checks. `dart run jaspr_storybook:metadata --help` describes
48
+ the generic extractor. Do not import its analyzer library into browser code.
49
+
50
+ ## Verify affected behavior
51
+
52
+ ```sh
53
+ bun run --bun storybook tools --no-attach stories changed --json
54
+ bun run --bun storybook tools --no-attach stories find-by-component --componentPaths '["path/to/component.dart"]' --json
55
+ bun run --bun storybook tools --no-attach test run --stories '[{"storyId":"returned-story-id"}]' --json
56
+ ```
57
+
58
+ Dart imports, exports, parts, conditional branches and deferred imports are traced.
59
+ Shared fixture files can conservatively select multiple stories. Check every file
60
+ you changed is represented; CSS/tokens and dynamic relationships may need explicit
61
+ consumer selection. Never interpret an empty affected set as proof of no impact.
62
+
63
+ CLI tests need @storybook/addon-vitest, a Vitest browser project with storybookTest,
64
+ and an available browser. Run browser suites sequentially to avoid competing
65
+ compiler/browser processes hitting the beta runner startup timeout. Use a nested test.projects configuration and an absolute
66
+ configDir. The package example demonstrates the setup. Do not install browser
67
+ binaries when repository rules prohibit it. Report unavailable execution.
68
+
69
+ Require nonzero totalTestCount and inspect componentTestCount, a11yCount and
70
+ unhandledErrors. A completed command with zero tests is not verification. Failures
71
+ can accompany a nonzero CLI exit code. Keep unit, analyzer and application tests.
72
+ Nested Jaspr build errors fail active previews conservatively because the Jaspr
73
+ binding does not expose an instance-specific error callback.
74
+
75
+ ## Review
76
+
77
+ Reuse or start the project's Storybook server, then use `tools --port <port>
78
+ stories preview` or `review create`. Read each tool's --help for the current beta's
79
+ input schema. Use returned story IDs, include changed states and affected consumer
80
+ examples, and pass accurate changedFiles. Creating a review replaces the active
81
+ local review. Return the actual review URL after checking the page.
82
+
83
+ Source edits trigger Dart recompilation and a full preview reload. This renderer
84
+ does not implement Jaspr stateful hot reload or SSR/hydration verification.