@gtkx/storybook 0.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.
Files changed (66) hide show
  1. package/dist/actions-panel.d.ts +7 -0
  2. package/dist/actions-panel.d.ts.map +1 -0
  3. package/dist/actions-panel.js +11 -0
  4. package/dist/actions-panel.js.map +1 -0
  5. package/dist/actions.d.ts +35 -0
  6. package/dist/actions.d.ts.map +1 -0
  7. package/dist/actions.js +161 -0
  8. package/dist/actions.js.map +1 -0
  9. package/dist/catalog.d.ts +71 -0
  10. package/dist/catalog.d.ts.map +1 -0
  11. package/dist/catalog.js +158 -0
  12. package/dist/catalog.js.map +1 -0
  13. package/dist/compose.d.ts +27 -0
  14. package/dist/compose.d.ts.map +1 -0
  15. package/dist/compose.js +67 -0
  16. package/dist/compose.js.map +1 -0
  17. package/dist/config.d.ts +13 -0
  18. package/dist/config.d.ts.map +1 -0
  19. package/dist/config.js +4 -0
  20. package/dist/config.js.map +1 -0
  21. package/dist/controls.d.ts +10 -0
  22. package/dist/controls.d.ts.map +1 -0
  23. package/dist/controls.js +94 -0
  24. package/dist/controls.js.map +1 -0
  25. package/dist/explorer-navigator.d.ts +11 -0
  26. package/dist/explorer-navigator.d.ts.map +1 -0
  27. package/dist/explorer-navigator.js +25 -0
  28. package/dist/explorer-navigator.js.map +1 -0
  29. package/dist/explorer-preview.d.ts +8 -0
  30. package/dist/explorer-preview.d.ts.map +1 -0
  31. package/dist/explorer-preview.js +89 -0
  32. package/dist/explorer-preview.js.map +1 -0
  33. package/dist/explorer-view.d.ts +15 -0
  34. package/dist/explorer-view.d.ts.map +1 -0
  35. package/dist/explorer-view.js +24 -0
  36. package/dist/explorer-view.js.map +1 -0
  37. package/dist/explorer.d.ts +22 -0
  38. package/dist/explorer.d.ts.map +1 -0
  39. package/dist/explorer.js +23 -0
  40. package/dist/explorer.js.map +1 -0
  41. package/dist/index.d.ts +5 -0
  42. package/dist/index.d.ts.map +1 -0
  43. package/dist/index.js +3 -0
  44. package/dist/index.js.map +1 -0
  45. package/dist/types.d.ts +143 -0
  46. package/dist/types.d.ts.map +1 -0
  47. package/dist/types.js +2 -0
  48. package/dist/types.js.map +1 -0
  49. package/dist/upstream.d.ts +14 -0
  50. package/dist/upstream.d.ts.map +1 -0
  51. package/dist/upstream.js +5 -0
  52. package/dist/upstream.js.map +1 -0
  53. package/package.json +86 -0
  54. package/src/actions-panel.tsx +32 -0
  55. package/src/actions.ts +234 -0
  56. package/src/catalog.ts +263 -0
  57. package/src/compose.ts +94 -0
  58. package/src/config.ts +14 -0
  59. package/src/controls.tsx +206 -0
  60. package/src/explorer-navigator.tsx +120 -0
  61. package/src/explorer-preview.tsx +207 -0
  62. package/src/explorer-view.tsx +93 -0
  63. package/src/explorer.ts +44 -0
  64. package/src/index.ts +16 -0
  65. package/src/types.ts +205 -0
  66. package/src/upstream.ts +24 -0
@@ -0,0 +1,7 @@
1
+ import type { ReactNode } from "react";
2
+ import type { ActionStore } from "./actions.js";
3
+ declare const ActionsPanel: ({ store }: {
4
+ store: ActionStore;
5
+ }) => ReactNode;
6
+ export { ActionsPanel };
7
+ //# sourceMappingURL=actions-panel.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"actions-panel.d.ts","sourceRoot":"","sources":["../src/actions-panel.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,OAAO,CAAC;AAKvC,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAEhD,QAAA,MAAM,YAAY,GAAI,WAAW;IAAE,KAAK,EAAE,WAAW,CAAA;CAAE,KAAG,SAsBzD,CAAC;AAEF,OAAO,EAAE,YAAY,EAAE,CAAC"}
@@ -0,0 +1,11 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { markupEscapeText } from "@gtkx/gi/glib";
3
+ import { AdwActionRow, AdwPreferencesGroup } from "@gtkx/jsx/adw";
4
+ import { GtkButton } from "@gtkx/jsx/gtk";
5
+ import { useSyncExternalStore } from "react";
6
+ const ActionsPanel = ({ store }) => {
7
+ const entries = useSyncExternalStore(store.subscribe, store.getSnapshot);
8
+ return (_jsx(AdwPreferencesGroup, { title: "Actions", description: entries.length === 0 ? "Interact with the story to record events." : "", headerSuffix: _jsx(GtkButton, { label: "Clear actions", sensitive: entries.length > 0, onClicked: store.clear }), children: entries.toReversed().map((entry) => (_jsx(AdwActionRow, { name: `storybook-action-${String(entry.id)}`, title: markupEscapeText(entry.name, -1), subtitle: markupEscapeText(entry.error ?? entry.args.join(", "), -1), subtitleSelectable: true, subtitleLines: 3, cssClasses: entry.error === undefined ? [] : ["error"] }, entry.id))) }));
9
+ };
10
+ export { ActionsPanel };
11
+ //# sourceMappingURL=actions-panel.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"actions-panel.js","sourceRoot":"","sources":["../src/actions-panel.tsx"],"names":[],"mappings":";AACA,OAAO,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAC;AACjD,OAAO,EAAE,YAAY,EAAE,mBAAmB,EAAE,MAAM,eAAe,CAAC;AAClE,OAAO,EAAE,SAAS,EAAE,MAAM,eAAe,CAAC;AAC1C,OAAO,EAAE,oBAAoB,EAAE,MAAM,OAAO,CAAC;AAG7C,MAAM,YAAY,GAAG,CAAC,EAAE,KAAK,EAA0B,EAAa,EAAE;IAClE,MAAM,OAAO,GAAG,oBAAoB,CAAC,KAAK,CAAC,SAAS,EAAE,KAAK,CAAC,WAAW,CAAC,CAAC;IAEzE,OAAO,CACH,KAAC,mBAAmB,IAChB,KAAK,EAAC,SAAS,EACf,WAAW,EAAE,OAAO,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC,CAAC,2CAA2C,CAAC,CAAC,CAAC,EAAE,EACpF,YAAY,EAAE,KAAC,SAAS,IAAC,KAAK,EAAC,eAAe,EAAC,SAAS,EAAE,OAAO,CAAC,MAAM,GAAG,CAAC,EAAE,SAAS,EAAE,KAAK,CAAC,KAAK,GAAI,YAEvG,OAAO,CAAC,UAAU,EAAE,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,CACjC,KAAC,YAAY,IAET,IAAI,EAAE,oBAAoB,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC,EAAE,EAC5C,KAAK,EAAE,gBAAgB,CAAC,KAAK,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,EACvC,QAAQ,EAAE,gBAAgB,CAAC,KAAK,CAAC,KAAK,IAAI,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,CAAC,EACpE,kBAAkB,QAClB,aAAa,EAAE,CAAC,EAChB,UAAU,EAAE,KAAK,CAAC,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,IANjD,KAAK,CAAC,EAAE,CAOf,CACL,CAAC,GACgB,CACzB,CAAC;AACN,CAAC,CAAC;AAEF,OAAO,EAAE,YAAY,EAAE,CAAC","sourcesContent":["import type { ReactNode } from \"react\";\nimport { markupEscapeText } from \"@gtkx/gi/glib\";\nimport { AdwActionRow, AdwPreferencesGroup } from \"@gtkx/jsx/adw\";\nimport { GtkButton } from \"@gtkx/jsx/gtk\";\nimport { useSyncExternalStore } from \"react\";\nimport type { ActionStore } from \"./actions.js\";\n\nconst ActionsPanel = ({ store }: { store: ActionStore }): ReactNode => {\n const entries = useSyncExternalStore(store.subscribe, store.getSnapshot);\n\n return (\n <AdwPreferencesGroup\n title=\"Actions\"\n description={entries.length === 0 ? \"Interact with the story to record events.\" : \"\"}\n headerSuffix={<GtkButton label=\"Clear actions\" sensitive={entries.length > 0} onClicked={store.clear} />}\n >\n {entries.toReversed().map((entry) => (\n <AdwActionRow\n key={entry.id}\n name={`storybook-action-${String(entry.id)}`}\n title={markupEscapeText(entry.name, -1)}\n subtitle={markupEscapeText(entry.error ?? entry.args.join(\", \"), -1)}\n subtitleSelectable\n subtitleLines={3}\n cssClasses={entry.error === undefined ? [] : [\"error\"]}\n />\n ))}\n </AdwPreferencesGroup>\n );\n};\n\nexport { ActionsPanel };\n"]}
@@ -0,0 +1,35 @@
1
+ import type { Args, ArgTypes } from "./types.js";
2
+ type ActionEntry = {
3
+ id: number;
4
+ name: string;
5
+ args: string[];
6
+ timestamp: number;
7
+ error?: string;
8
+ };
9
+ /** A named story callback whose arguments can be recorded by the native explorer. */
10
+ type ActionCallback = (...args: unknown[]) => void;
11
+ /**
12
+ * Creates a named action for a story's callback arguments.
13
+ * The explorer records bounded argument summaries; calls outside its action scope have no effect.
14
+ *
15
+ * @param name Nonempty label displayed in the Actions panel.
16
+ * @returns A callback to supply in story args.
17
+ * @throws If the name is empty or contains only whitespace.
18
+ */
19
+ declare const action: (name: string) => ActionCallback;
20
+ declare class ActionStore {
21
+ private entries;
22
+ private readonly listeners;
23
+ private nextId;
24
+ private readonly limit;
25
+ getSnapshot: () => ActionEntry[];
26
+ subscribe: (listener: () => void) => (() => void);
27
+ clear: () => void;
28
+ constructor(limit?: number);
29
+ private publish;
30
+ record(name: string, args: unknown[], error?: Error): void;
31
+ }
32
+ declare const bindActions: (args: Args, argTypes: ArgTypes, store: ActionStore, onError?: (error: Error) => void) => Args;
33
+ export { action, ActionStore, bindActions };
34
+ export type { ActionCallback };
35
+ //# sourceMappingURL=actions.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"actions.d.ts","sourceRoot":"","sources":["../src/actions.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,IAAI,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AAEjD,KAAK,WAAW,GAAG;IACf,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,EAAE,CAAC;IACf,SAAS,EAAE,MAAM,CAAC;IAClB,KAAK,CAAC,EAAE,MAAM,CAAC;CAClB,CAAC;AAEF,qFAAqF;AACrF,KAAK,cAAc,GAAG,CAAC,GAAG,IAAI,EAAE,OAAO,EAAE,KAAK,IAAI,CAAC;AA6CnD;;;;;;;GAOG;AACH,QAAA,MAAM,MAAM,GAAI,MAAM,MAAM,KAAG,cAW9B,CAAC;AAEF,cAAM,WAAW;IACb,OAAO,CAAC,OAAO,CAAqB;IACpC,OAAO,CAAC,QAAQ,CAAC,SAAS,CAA8B;IACxD,OAAO,CAAC,MAAM,CAAK;IACnB,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAS;IAE/B,WAAW,QAAO,WAAW,EAAE,CAAiB;IAEhD,SAAS,GAAI,UAAU,MAAM,IAAI,KAAG,CAAC,MAAM,IAAI,CAAC,CAM9C;IAEF,KAAK,QAAO,IAAI,CAEd;gBAEU,KAAK,GAAE,MAA8B;IAQjD,OAAO,CAAC,OAAO;IAQf,MAAM,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,EAAE,KAAK,CAAC,EAAE,KAAK,GAAG,IAAI;CAU7D;AAmFD,QAAA,MAAM,WAAW,GACb,MAAM,IAAI,EACV,UAAU,QAAQ,EAClB,OAAO,WAAW,EAClB,UAAU,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,KACjC,IAiBF,CAAC;AAEF,OAAO,EAAE,MAAM,EAAE,WAAW,EAAE,WAAW,EAAE,CAAC;AAC5C,YAAY,EAAE,cAAc,EAAE,CAAC"}
@@ -0,0 +1,161 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ import { inspect } from "node:util";
3
+ const actionNames = new WeakMap();
4
+ const actionScope = new AsyncLocalStorage();
5
+ const DEFAULT_HISTORY_LIMIT = 100;
6
+ const MAX_ARGUMENT_LENGTH = 400;
7
+ const objectLabel = (value) => {
8
+ if (value === null || typeof value !== "object" || Array.isArray(value)) {
9
+ return undefined;
10
+ }
11
+ const prototype = Object.getPrototypeOf(value);
12
+ if (prototype === null || typeof prototype !== "object" || prototype === Object.prototype) {
13
+ return undefined;
14
+ }
15
+ const constructor = Object.getOwnPropertyDescriptor(prototype, "constructor")?.value;
16
+ return typeof constructor === "function" ? `[${constructor.name}]` : "[Object]";
17
+ };
18
+ const formatArgument = (value) => {
19
+ try {
20
+ const label = objectLabel(value);
21
+ if (label !== undefined) {
22
+ return label;
23
+ }
24
+ return inspect(value, {
25
+ depth: 1,
26
+ maxArrayLength: 5,
27
+ maxStringLength: 120,
28
+ customInspect: false,
29
+ getters: false,
30
+ breakLength: Infinity,
31
+ }).slice(0, MAX_ARGUMENT_LENGTH);
32
+ }
33
+ catch {
34
+ return "[Unreadable value]";
35
+ }
36
+ };
37
+ /**
38
+ * Creates a named action for a story's callback arguments.
39
+ * The explorer records bounded argument summaries; calls outside its action scope have no effect.
40
+ *
41
+ * @param name Nonempty label displayed in the Actions panel.
42
+ * @returns A callback to supply in story args.
43
+ * @throws If the name is empty or contains only whitespace.
44
+ */
45
+ const action = (name) => {
46
+ if (name.trim().length === 0) {
47
+ throw new TypeError("An action needs a name");
48
+ }
49
+ const callback = (...args) => {
50
+ actionScope.getStore()?.record(name, args);
51
+ };
52
+ actionNames.set(callback, name);
53
+ return callback;
54
+ };
55
+ class ActionStore {
56
+ entries = [];
57
+ listeners = new Set();
58
+ nextId = 0;
59
+ limit;
60
+ getSnapshot = () => this.entries;
61
+ subscribe = (listener) => {
62
+ this.listeners.add(listener);
63
+ return () => {
64
+ this.listeners.delete(listener);
65
+ };
66
+ };
67
+ clear = () => {
68
+ this.publish([]);
69
+ };
70
+ constructor(limit = DEFAULT_HISTORY_LIMIT) {
71
+ if (!Number.isSafeInteger(limit) || limit < 1) {
72
+ throw new RangeError("Action history needs a positive integer limit");
73
+ }
74
+ this.limit = limit;
75
+ }
76
+ publish(entries) {
77
+ this.entries = entries;
78
+ for (const listener of this.listeners) {
79
+ listener();
80
+ }
81
+ }
82
+ record(name, args, error) {
83
+ const entry = {
84
+ id: this.nextId++,
85
+ name,
86
+ args: args.slice(0, 8).map((value) => formatArgument(value)),
87
+ timestamp: Date.now(),
88
+ ...(error !== undefined && { error: error.message.slice(0, MAX_ARGUMENT_LENGTH) }),
89
+ };
90
+ this.publish([...this.entries, entry].slice(-this.limit));
91
+ }
92
+ }
93
+ const settleCallback = async (result, succeed, fail) => {
94
+ try {
95
+ const value = await result;
96
+ succeed();
97
+ return value;
98
+ }
99
+ catch (error) {
100
+ fail(error);
101
+ return undefined;
102
+ }
103
+ };
104
+ const bindCallback = (store, options) => (...values) => {
105
+ const succeed = () => {
106
+ store.record(options.name, values);
107
+ };
108
+ const fail = (cause) => {
109
+ const error = cause instanceof Error ? cause : new Error(String(cause));
110
+ store.record(options.name, values, error);
111
+ if (options.onError === undefined) {
112
+ throw error;
113
+ }
114
+ options.onError(error);
115
+ };
116
+ try {
117
+ const result = actionScope.run(store, () => options.callback?.(...values));
118
+ if (result instanceof Promise) {
119
+ return settleCallback(result, succeed, fail);
120
+ }
121
+ succeed();
122
+ return result;
123
+ }
124
+ catch (error) {
125
+ fail(error);
126
+ return;
127
+ }
128
+ };
129
+ const actionName = (value, configuredName) => {
130
+ if (typeof configuredName === "string") {
131
+ return configuredName;
132
+ }
133
+ return typeof value === "function" ? actionNames.get(value) : undefined;
134
+ };
135
+ const isOriginalCallback = (value) => typeof value === "function" && !actionNames.has(value);
136
+ const callbackOptions = (value, name, onError) => {
137
+ if (name === undefined) {
138
+ return undefined;
139
+ }
140
+ return {
141
+ name,
142
+ ...(isOriginalCallback(value) && { callback: value }),
143
+ ...(onError !== undefined && { onError }),
144
+ };
145
+ };
146
+ const bindActions = (args, argTypes, store, onError) => {
147
+ const bound = { ...args };
148
+ const names = new Set([...Object.keys(args), ...Object.keys(argTypes)]);
149
+ for (const argument of names) {
150
+ const value = args[argument];
151
+ const name = actionName(value, argTypes[argument]?.action);
152
+ const options = callbackOptions(value, name, onError);
153
+ if (options === undefined) {
154
+ continue;
155
+ }
156
+ bound[argument] = bindCallback(store, options);
157
+ }
158
+ return bound;
159
+ };
160
+ export { action, ActionStore, bindActions };
161
+ //# sourceMappingURL=actions.js.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MAAM,IAAI,GAAG,UAAU,CAAC,KAAK,EAAE,QAAQ,CAAC,QAAQ,CAAC,EAAE,MAAM,CAAC,CAAC;QAC3D,MAAM,OAAO,GAAG,eAAe,CAAC,KAAK,EAAE,IAAI,EAAE,OAAO,CAAC,CAAC;QAEtD,IAAI,OAAO,KAAK,SAAS,EAAE,CAAC;YACxB,SAAS;QACb,CAAC;QAED,KAAK,CAAC,QAAQ,CAAC,GAAG,YAAY,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC;IACnD,CAAC;IAED,OAAO,KAAK,CAAC;AACjB,CAAC,CAAC;AAEF,OAAO,EAAE,MAAM,EAAE,WAAW,EAAE,WAAW,EAAE,CAAC","sourcesContent":["import { AsyncLocalStorage } from \"node:async_hooks\";\nimport { inspect } from \"node:util\";\nimport type { Args, ArgTypes } from \"./types.js\";\n\ntype ActionEntry = {\n id: number;\n name: string;\n args: string[];\n timestamp: number;\n error?: string;\n};\n\n/** A named story callback whose arguments can be recorded by the native explorer. */\ntype ActionCallback = (...args: unknown[]) => void;\ntype EventCallback = (...args: unknown[]) => unknown;\n\nconst actionNames: WeakMap<object, string> = new WeakMap();\nconst actionScope: AsyncLocalStorage<ActionStore> = new AsyncLocalStorage();\nconst DEFAULT_HISTORY_LIMIT = 100;\nconst MAX_ARGUMENT_LENGTH = 400;\n\nconst objectLabel = (value: unknown): string | undefined => {\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) {\n return undefined;\n }\n\n const prototype: unknown = Object.getPrototypeOf(value);\n\n if (prototype === null || typeof prototype !== \"object\" || prototype === Object.prototype) {\n return undefined;\n }\n\n const constructor: unknown = Object.getOwnPropertyDescriptor(prototype, \"constructor\")?.value;\n\n return typeof constructor === \"function\" ? `[${constructor.name}]` : \"[Object]\";\n};\n\nconst formatArgument = (value: unknown): string => {\n try {\n const label = objectLabel(value);\n\n if (label !== undefined) {\n return label;\n }\n\n return inspect(value, {\n depth: 1,\n maxArrayLength: 5,\n maxStringLength: 120,\n customInspect: false,\n getters: false,\n breakLength: Infinity,\n }).slice(0, MAX_ARGUMENT_LENGTH);\n } catch {\n return \"[Unreadable value]\";\n }\n};\n\n/**\n * Creates a named action for a story's callback arguments.\n * The explorer records bounded argument summaries; calls outside its action scope have no effect.\n *\n * @param name Nonempty label displayed in the Actions panel.\n * @returns A callback to supply in story args.\n * @throws If the name is empty or contains only whitespace.\n */\nconst action = (name: string): ActionCallback => {\n if (name.trim().length === 0) {\n throw new TypeError(\"An action needs a name\");\n }\n\n const callback: ActionCallback = (...args) => {\n actionScope.getStore()?.record(name, args);\n };\n actionNames.set(callback, name);\n\n return callback;\n};\n\nclass ActionStore {\n private entries: ActionEntry[] = [];\n private readonly listeners: Set<() => void> = new Set();\n private nextId = 0;\n private readonly limit: number;\n\n getSnapshot = (): ActionEntry[] => this.entries;\n\n subscribe = (listener: () => void): (() => void) => {\n this.listeners.add(listener);\n\n return () => {\n this.listeners.delete(listener);\n };\n };\n\n clear = (): void => {\n this.publish([]);\n };\n\n constructor(limit: number = DEFAULT_HISTORY_LIMIT) {\n if (!Number.isSafeInteger(limit) || limit < 1) {\n throw new RangeError(\"Action history needs a positive integer limit\");\n }\n\n this.limit = limit;\n }\n\n private publish(entries: ActionEntry[]): void {\n this.entries = entries;\n\n for (const listener of this.listeners) {\n listener();\n }\n }\n\n record(name: string, args: unknown[], error?: Error): void {\n const entry: ActionEntry = {\n id: this.nextId++,\n name,\n args: args.slice(0, 8).map((value) => formatArgument(value)),\n timestamp: Date.now(),\n ...(error !== undefined && { error: error.message.slice(0, MAX_ARGUMENT_LENGTH) }),\n };\n this.publish([...this.entries, entry].slice(-this.limit));\n }\n}\n\ntype CallbackOptions = { callback?: EventCallback; name: string; onError?: (error: Error) => void };\n\nconst settleCallback = async (\n result: Promise<unknown>,\n succeed: () => void,\n fail: (cause: unknown) => void,\n): Promise<unknown> => {\n try {\n const value = await result;\n succeed();\n\n return value;\n } catch (error) {\n fail(error);\n\n return undefined;\n }\n};\n\nconst bindCallback = (\n store: ActionStore,\n options: CallbackOptions,\n): EventCallback => (...values) => {\n const succeed = (): void => {\n store.record(options.name, values);\n };\n const fail = (cause: unknown): void => {\n const error = cause instanceof Error ? cause : new Error(String(cause));\n store.record(options.name, values, error);\n\n if (options.onError === undefined) {\n throw error;\n }\n\n options.onError(error);\n };\n\n try {\n const result = actionScope.run(store, () => options.callback?.(...values));\n\n if (result instanceof Promise) {\n return settleCallback(result, succeed, fail);\n }\n\n succeed();\n\n return result;\n } catch (error) {\n fail(error);\n\n return;\n }\n};\n\nconst actionName = (value: unknown, configuredName: unknown): string | undefined => {\n if (typeof configuredName === \"string\") {\n return configuredName;\n }\n\n return typeof value === \"function\" ? actionNames.get(value) : undefined;\n};\n\nconst isOriginalCallback = (value: unknown): value is EventCallback =>\n typeof value === \"function\" && !actionNames.has(value);\n\nconst callbackOptions = (\n value: unknown,\n name: string | undefined,\n onError: ((error: Error) => void) | undefined,\n): CallbackOptions | undefined => {\n if (name === undefined) {\n return undefined;\n }\n\n return {\n name,\n ...(isOriginalCallback(value) && { callback: value }),\n ...(onError !== undefined && { onError }),\n };\n};\n\nconst bindActions = (\n args: Args,\n argTypes: ArgTypes,\n store: ActionStore,\n onError?: (error: Error) => void,\n): Args => {\n const bound = { ...args };\n const names = new Set([...Object.keys(args), ...Object.keys(argTypes)]);\n\n for (const argument of names) {\n const value = args[argument];\n const name = actionName(value, argTypes[argument]?.action);\n const options = callbackOptions(value, name, onError);\n\n if (options === undefined) {\n continue;\n }\n\n bound[argument] = bindCallback(store, options);\n }\n\n return bound;\n};\n\nexport { action, ActionStore, bindActions };\nexport type { ActionCallback };\n"]}
@@ -0,0 +1,71 @@
1
+ import type { ArgTypes, ComposedStory, Preview } from "./types.js";
2
+ /** A lazily loaded CSF module discovered in a Storybook project. */
3
+ type StorySource = {
4
+ /** Stable module identifier used for caching and error reporting. */
5
+ id: string;
6
+ /** Fallback story group title when the module does not declare one. */
7
+ title: string;
8
+ /** Imports the module and resolves to its CSF exports. */
9
+ load: () => Promise<unknown>;
10
+ };
11
+ /** A composed story and the metadata used to display it in the explorer. */
12
+ type StoryEntry = {
13
+ /** Storybook identifier used to preserve the selected story across updates. */
14
+ id: string;
15
+ /** Component group title declared by the module or derived from its source. */
16
+ title: string;
17
+ /** Display name declared by the story or derived from its export name. */
18
+ name: string;
19
+ /** Name of the CSF export that defines this story. */
20
+ exportName: string;
21
+ /** Identifier of the module containing this story. */
22
+ source: string;
23
+ /** Renderable story with its metadata, decorators, and default args composed. */
24
+ story: ComposedStory;
25
+ /** Resolved arg types with explicitly configured explorer controls. */
26
+ controls: ArgTypes;
27
+ };
28
+ /** A source loading or composition failure displayed alongside healthy stories. */
29
+ type StoryLoadError = {
30
+ /** Identifier of the failed source, or Storybook for a session failure. */
31
+ source: string;
32
+ /** Normalized error raised while loading or composing the source. */
33
+ error: Error;
34
+ };
35
+ /** Current explorer contents and loading state exposed to subscribers. */
36
+ type StoryCatalogSnapshot = {
37
+ /** Successfully composed stories with duplicate identifiers excluded. */
38
+ stories: StoryEntry[];
39
+ /** Failures encountered during the latest load or reported by the session. */
40
+ errors: StoryLoadError[];
41
+ /** Whether the catalog is waiting for the latest source load to finish. */
42
+ isLoading: boolean;
43
+ };
44
+ /** Loads CSF modules and publishes subscribable explorer snapshots. */
45
+ declare class StoryCatalog {
46
+ private snapshot;
47
+ private readonly listeners;
48
+ private readonly loadFailures;
49
+ private cache;
50
+ private sessionError;
51
+ private revision;
52
+ /** Returns the current snapshot, retaining its identity until the next update. */
53
+ getSnapshot: () => StoryCatalogSnapshot;
54
+ /** Registers a snapshot listener and returns a function that unsubscribes it. */
55
+ subscribe: (listener: () => void) => (() => void);
56
+ private publish;
57
+ /**
58
+ * Replaces the catalog with stories composed from the supplied sources and preview.
59
+ * Only the latest load publishes results; unchanged module identities reuse composed stories.
60
+ * Rejects with an AggregateError after publishing healthy stories when any source fails.
61
+ */
62
+ load(sources: StorySource[], preview?: Preview): Promise<void>;
63
+ /**
64
+ * Replaces the current session failure while preserving source errors and superseding pending loads.
65
+ * Ignores aggregate failures already published by this catalog's load operation.
66
+ */
67
+ reportError(cause: unknown): void;
68
+ }
69
+ export { StoryCatalog };
70
+ export type { StoryCatalogSnapshot, StoryEntry, StoryLoadError, StorySource };
71
+ //# sourceMappingURL=catalog.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"catalog.d.ts","sourceRoot":"","sources":["../src/catalog.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAQ,QAAQ,EAAiB,aAAa,EAAE,OAAO,EAAoB,MAAM,YAAY,CAAC;AAI1G,oEAAoE;AACpE,KAAK,WAAW,GAAG;IACf,qEAAqE;IACrE,EAAE,EAAE,MAAM,CAAC;IACX,uEAAuE;IACvE,KAAK,EAAE,MAAM,CAAC;IACd,0DAA0D;IAC1D,IAAI,EAAE,MAAM,OAAO,CAAC,OAAO,CAAC,CAAC;CAChC,CAAC;AAEF,4EAA4E;AAC5E,KAAK,UAAU,GAAG;IACd,+EAA+E;IAC/E,EAAE,EAAE,MAAM,CAAC;IACX,+EAA+E;IAC/E,KAAK,EAAE,MAAM,CAAC;IACd,0EAA0E;IAC1E,IAAI,EAAE,MAAM,CAAC;IACb,sDAAsD;IACtD,UAAU,EAAE,MAAM,CAAC;IACnB,sDAAsD;IACtD,MAAM,EAAE,MAAM,CAAC;IACf,iFAAiF;IACjF,KAAK,EAAE,aAAa,CAAC;IACrB,uEAAuE;IACvE,QAAQ,EAAE,QAAQ,CAAC;CACtB,CAAC;AAEF,mFAAmF;AACnF,KAAK,cAAc,GAAG;IAClB,2EAA2E;IAC3E,MAAM,EAAE,MAAM,CAAC;IACf,qEAAqE;IACrE,KAAK,EAAE,KAAK,CAAC;CAChB,CAAC;AAEF,0EAA0E;AAC1E,KAAK,oBAAoB,GAAG;IACxB,yEAAyE;IACzE,OAAO,EAAE,UAAU,EAAE,CAAC;IACtB,8EAA8E;IAC9E,MAAM,EAAE,cAAc,EAAE,CAAC;IACzB,2EAA2E;IAC3E,SAAS,EAAE,OAAO,CAAC;CACtB,CAAC;AA0IF,uEAAuE;AACvE,cAAM,YAAY;IACd,OAAO,CAAC,QAAQ,CAAuE;IACvF,OAAO,CAAC,QAAQ,CAAC,SAAS,CAA8B;IACxD,OAAO,CAAC,QAAQ,CAAC,YAAY,CAAiC;IAC9D,OAAO,CAAC,KAAK,CAAuB;IACpC,OAAO,CAAC,YAAY,CAA6B;IACjD,OAAO,CAAC,QAAQ,CAAK;IAErB,kFAAkF;IAClF,WAAW,QAAO,oBAAoB,CAAkB;IAExD,iFAAiF;IACjF,SAAS,GAAI,UAAU,MAAM,IAAI,KAAG,CAAC,MAAM,IAAI,CAAC,CAM9C;IAEF,OAAO,CAAC,OAAO;IAQf;;;;OAIG;IACG,IAAI,CAAC,OAAO,EAAE,WAAW,EAAE,EAAE,OAAO,GAAE,OAAuB,GAAG,OAAO,CAAC,IAAI,CAAC;IAqBnF;;;OAGG;IACH,WAAW,CAAC,KAAK,EAAE,OAAO,GAAG,IAAI;CAcpC;AAED,OAAO,EAAE,YAAY,EAAE,CAAC;AACxB,YAAY,EAAE,oBAAoB,EAAE,UAAU,EAAE,cAAc,EAAE,WAAW,EAAE,CAAC"}
@@ -0,0 +1,158 @@
1
+ import { composeStories } from "./compose.js";
2
+ import { storyNameFromExport } from "./upstream.js";
3
+ const EMPTY_PREVIEW = {};
4
+ const normalizeError = (cause) => cause instanceof Error ? cause : new Error(String(cause));
5
+ const isObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
6
+ const explicitControls = (resolved, story, meta, preview) => {
7
+ const controls = {};
8
+ for (const [argument, annotation] of Object.entries(resolved)) {
9
+ const control = story?.argTypes?.[argument]?.control ??
10
+ meta.argTypes?.[argument]?.control ?? preview.argTypes?.[argument]?.control;
11
+ if (control === undefined) {
12
+ continue;
13
+ }
14
+ controls[argument] = { ...annotation, control: control === false ? false : annotation?.control ?? control };
15
+ }
16
+ return controls;
17
+ };
18
+ const displayName = (story, exportName) => {
19
+ const name = story?.name;
20
+ if (name === undefined) {
21
+ return storyNameFromExport(exportName);
22
+ }
23
+ if (typeof name !== "string") {
24
+ throw new TypeError("Expected a story display name");
25
+ }
26
+ return name;
27
+ };
28
+ const composeSource = (source, module, preview) => {
29
+ if (!isObject(module) || !isObject(module.default)) {
30
+ throw new TypeError(`Expected CSF3 component metadata in ${source.id}`);
31
+ }
32
+ const title = module.default.title ?? source.title;
33
+ if (typeof title !== "string" || title.trim().length === 0) {
34
+ throw new TypeError(`Expected a story title in ${source.id}`);
35
+ }
36
+ const annotations = {
37
+ ...module,
38
+ default: { ...module.default, title },
39
+ };
40
+ const stories = composeStories(annotations, preview);
41
+ return Object.entries(stories).map(([exportName, story]) => ({
42
+ id: story.id,
43
+ title,
44
+ name: displayName(annotations[exportName], exportName),
45
+ exportName,
46
+ source: source.id,
47
+ story,
48
+ controls: explicitControls(story.argTypes, annotations[exportName], annotations.default, preview),
49
+ }));
50
+ };
51
+ const withoutDuplicateIds = (entries, errors) => {
52
+ const counts = new Map();
53
+ for (const entry of entries) {
54
+ counts.set(entry.id, (counts.get(entry.id) ?? 0) + 1);
55
+ }
56
+ return entries.filter((entry) => {
57
+ if (counts.get(entry.id) === 1) {
58
+ return true;
59
+ }
60
+ errors.push({ source: entry.source, error: new Error(`Duplicate story ID: ${entry.id}`) });
61
+ return false;
62
+ });
63
+ };
64
+ const collectSources = (loaded) => {
65
+ const cache = new Map();
66
+ const entries = [];
67
+ const errors = [];
68
+ for (const result of loaded) {
69
+ if ("error" in result) {
70
+ errors.push(result);
71
+ }
72
+ else {
73
+ cache.set(result.source.id, result.cached);
74
+ entries.push(...result.cached.entries);
75
+ }
76
+ }
77
+ return { cache, stories: withoutDuplicateIds(entries, errors), errors };
78
+ };
79
+ const createSourceCache = () => new Map();
80
+ const loadSource = async (source, preview, getCache) => {
81
+ try {
82
+ const module = await source.load();
83
+ const previous = getCache().get(source.id);
84
+ const cached = previous !== undefined && previous.module === module &&
85
+ previous.title === source.title && previous.preview === preview
86
+ ? previous
87
+ : { module, title: source.title, preview, entries: composeSource(source, module, preview) };
88
+ return { source, cached };
89
+ }
90
+ catch (error) {
91
+ return { source: source.id, error: normalizeError(error) };
92
+ }
93
+ };
94
+ /** Loads CSF modules and publishes subscribable explorer snapshots. */
95
+ class StoryCatalog {
96
+ snapshot = { stories: [], errors: [], isLoading: false };
97
+ listeners = new Set();
98
+ loadFailures = new WeakSet();
99
+ cache = createSourceCache();
100
+ sessionError;
101
+ revision = 0;
102
+ /** Returns the current snapshot, retaining its identity until the next update. */
103
+ getSnapshot = () => this.snapshot;
104
+ /** Registers a snapshot listener and returns a function that unsubscribes it. */
105
+ subscribe = (listener) => {
106
+ this.listeners.add(listener);
107
+ return () => {
108
+ this.listeners.delete(listener);
109
+ };
110
+ };
111
+ publish(snapshot) {
112
+ this.snapshot = snapshot;
113
+ for (const listener of this.listeners) {
114
+ listener();
115
+ }
116
+ }
117
+ /**
118
+ * Replaces the catalog with stories composed from the supplied sources and preview.
119
+ * Only the latest load publishes results; unchanged module identities reuse composed stories.
120
+ * Rejects with an AggregateError after publishing healthy stories when any source fails.
121
+ */
122
+ async load(sources, preview = EMPTY_PREVIEW) {
123
+ const revision = ++this.revision;
124
+ this.publish({ ...this.snapshot, isLoading: true });
125
+ const loaded = await Promise.all(sources.map((source) => loadSource(source, preview, () => this.cache)));
126
+ if (revision !== this.revision) {
127
+ return;
128
+ }
129
+ const { cache, stories, errors } = collectSources(loaded);
130
+ this.cache = cache;
131
+ this.sessionError = undefined;
132
+ this.publish({ stories, errors, isLoading: false });
133
+ if (errors.length > 0) {
134
+ const failure = new AggregateError(errors.map(({ error }) => error), "Some stories could not be loaded");
135
+ this.loadFailures.add(failure);
136
+ throw failure;
137
+ }
138
+ }
139
+ /**
140
+ * Replaces the current session failure while preserving source errors and superseding pending loads.
141
+ * Ignores aggregate failures already published by this catalog's load operation.
142
+ */
143
+ reportError(cause) {
144
+ if (cause instanceof Error && this.loadFailures.has(cause)) {
145
+ return;
146
+ }
147
+ this.revision++;
148
+ const errors = this.snapshot.errors.filter((entry) => entry !== this.sessionError);
149
+ this.sessionError = { source: "Storybook", error: normalizeError(cause) };
150
+ this.publish({
151
+ ...this.snapshot,
152
+ isLoading: false,
153
+ errors: [...errors, this.sessionError],
154
+ });
155
+ }
156
+ }
157
+ export { StoryCatalog };
158
+ //# sourceMappingURL=catalog.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"catalog.js","sourceRoot":"","sources":["../src/catalog.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AAC9C,OAAO,EAAE,mBAAmB,EAAE,MAAM,eAAe,CAAC;AAyDpD,MAAM,aAAa,GAAY,EAAE,CAAC;AAElC,MAAM,cAAc,GAAG,CAAC,KAAc,EAAS,EAAE,CAAC,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,KAAK,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC;AAE5G,MAAM,QAAQ,GAAG,CAAC,KAAc,EAAoC,EAAE,CAClE,KAAK,KAAK,IAAI,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAEzE,MAAM,gBAAgB,GAAG,CACrB,QAAkB,EAClB,KAAyC,EACzC,IAAyB,EACzB,OAAgB,EACR,EAAE;IACV,MAAM,QAAQ,GAAa,EAAE,CAAC;IAE9B,KAAK,MAAM,CAAC,QAAQ,EAAE,UAAU,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,QAAQ,CAAC,EAAE,CAAC;QAC5D,MAAM,OAAO,GAAG,KAAK,EAAE,QAAQ,EAAE,CAAC,QAAQ,CAAC,EAAE,OAAO;YAChD,IAAI,CAAC,QAAQ,EAAE,CAAC,QAAQ,CAAC,EAAE,OAAO,IAAI,OAAO,CAAC,QAAQ,EAAE,CAAC,QAAQ,CAAC,EAAE,OAAO,CAAC;QAEh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AAC,KAAK,CAAC,EAAE,CAAC;YACzD,OAAO;QACX,CAAC;QAED,IAAI,CAAC,QAAQ,EAAE,CAAC;QAChB,MAAM,MAAM,GAAG,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,KAAK,IAAI,CAAC,YAAY,CAAC,CAAC;QACnF,IAAI,CAAC,YAAY,GAAG,EAAE,MAAM,EAAE,WAAW,EAAE,KAAK,EAAE,cAAc,CAAC,KAAK,CAAC,EAAE,CAAC;QAC1E,IAAI,CAAC,OAAO,CAAC;YACT,GAAG,IAAI,CAAC,QAAQ;YAChB,SAAS,EAAE,KAAK;YAChB,MAAM,EAAE,CAAC,GAAG,MAAM,EAAE,IAAI,CAAC,YAAY,CAAC;SACzC,CAAC,CAAC;IACP,CAAC;CACJ;AAED,OAAO,EAAE,YAAY,EAAE,CAAC","sourcesContent":["import type { Args, ArgTypes, ComponentMeta, ComposedStory, Preview, StoryAnnotations } from \"./types.js\";\nimport { composeStories } from \"./compose.js\";\nimport { storyNameFromExport } from \"./upstream.js\";\n\n/** A lazily loaded CSF module discovered in a Storybook project. */\ntype StorySource = {\n /** Stable module identifier used for caching and error reporting. */\n id: string;\n /** Fallback story group title when the module does not declare one. */\n title: string;\n /** Imports the module and resolves to its CSF exports. */\n load: () => Promise<unknown>;\n};\n\n/** A composed story and the metadata used to display it in the explorer. */\ntype StoryEntry = {\n /** Storybook identifier used to preserve the selected story across updates. */\n id: string;\n /** Component group title declared by the module or derived from its source. */\n title: string;\n /** Display name declared by the story or derived from its export name. */\n name: string;\n /** Name of the CSF export that defines this story. */\n exportName: string;\n /** Identifier of the module containing this story. */\n source: string;\n /** Renderable story with its metadata, decorators, and default args composed. */\n story: ComposedStory;\n /** Resolved arg types with explicitly configured explorer controls. */\n controls: ArgTypes;\n};\n\n/** A source loading or composition failure displayed alongside healthy stories. */\ntype StoryLoadError = {\n /** Identifier of the failed source, or Storybook for a session failure. */\n source: string;\n /** Normalized error raised while loading or composing the source. */\n error: Error;\n};\n\n/** Current explorer contents and loading state exposed to subscribers. */\ntype StoryCatalogSnapshot = {\n /** Successfully composed stories with duplicate identifiers excluded. */\n stories: StoryEntry[];\n /** Failures encountered during the latest load or reported by the session. */\n errors: StoryLoadError[];\n /** Whether the catalog is waiting for the latest source load to finish. */\n isLoading: boolean;\n};\n\ntype CachedStories = {\n module: unknown;\n title: string;\n preview: Preview;\n entries: StoryEntry[];\n};\n\ntype LoadedSource = StoryLoadError | { source: StorySource; cached: CachedStories };\n\nconst EMPTY_PREVIEW: Preview = {};\n\nconst normalizeError = (cause: unknown): Error => cause instanceof Error ? cause : new Error(String(cause));\n\nconst isObject = (value: unknown): value is Record<string, unknown> =>\n value !== null && typeof value === \"object\" && !Array.isArray(value);\n\nconst explicitControls = (\n resolved: ArgTypes,\n story: StoryAnnotations<Args> | undefined,\n meta: ComponentMeta<Args>,\n preview: Preview,\n): ArgTypes => {\n const controls: ArgTypes = {};\n\n for (const [argument, annotation] of Object.entries(resolved)) {\n const control = story?.argTypes?.[argument]?.control ??\n meta.argTypes?.[argument]?.control ?? preview.argTypes?.[argument]?.control;\n\n if (control === undefined) {\n continue;\n }\n\n controls[argument] = { ...annotation, control: control === false ? false : annotation?.control ?? control };\n }\n\n return controls;\n};\n\nconst displayName = (story: StoryAnnotations<Args> | undefined, exportName: string): string => {\n const name = story?.name;\n\n if (name === undefined) {\n return storyNameFromExport(exportName);\n }\n\n if (typeof name !== \"string\") {\n throw new TypeError(\"Expected a story display name\");\n }\n\n return name;\n};\n\nconst composeSource = (source: StorySource, module: unknown, preview: Preview): StoryEntry[] => {\n if (!isObject(module) || !isObject(module.default)) {\n throw new TypeError(`Expected CSF3 component metadata in ${source.id}`);\n }\n\n const title = module.default.title ?? source.title;\n\n if (typeof title !== \"string\" || title.trim().length === 0) {\n throw new TypeError(`Expected a story title in ${source.id}`);\n }\n\n const annotations = {\n ...module,\n default: { ...module.default, title },\n } as Record<string, StoryAnnotations<Args>> & { default: ComponentMeta<Args> };\n const stories = composeStories(annotations, preview);\n\n return Object.entries(stories).map(([exportName, story]) => ({\n id: story.id,\n title,\n name: displayName(annotations[exportName], exportName),\n exportName,\n source: source.id,\n story,\n controls: explicitControls(story.argTypes, annotations[exportName], annotations.default, preview),\n }));\n};\n\nconst withoutDuplicateIds = (entries: StoryEntry[], errors: StoryLoadError[]): StoryEntry[] => {\n const counts: Map<string, number> = new Map();\n\n for (const entry of entries) {\n counts.set(entry.id, (counts.get(entry.id) ?? 0) + 1);\n }\n\n return entries.filter((entry) => {\n if (counts.get(entry.id) === 1) {\n return true;\n }\n\n errors.push({ source: entry.source, error: new Error(`Duplicate story ID: ${entry.id}`) });\n\n return false;\n });\n};\n\nconst collectSources = (loaded: LoadedSource[]) => {\n const cache: Map<string, CachedStories> = new Map();\n const entries: StoryEntry[] = [];\n const errors: StoryLoadError[] = [];\n\n for (const result of loaded) {\n if (\"error\" in result) {\n errors.push(result);\n } else {\n cache.set(result.source.id, result.cached);\n entries.push(...result.cached.entries);\n }\n }\n\n return { cache, stories: withoutDuplicateIds(entries, errors), errors };\n};\n\nconst createSourceCache = (): Map<string, CachedStories> => new Map();\n\nconst loadSource = async (\n source: StorySource,\n preview: Preview,\n getCache: () => Map<string, CachedStories>,\n): Promise<LoadedSource> => {\n try {\n const module = await source.load();\n const previous = getCache().get(source.id);\n const cached = previous !== undefined && previous.module === module &&\n previous.title === source.title && previous.preview === preview\n ? previous\n : { module, title: source.title, preview, entries: composeSource(source, module, preview) };\n\n return { source, cached };\n } catch (error) {\n return { source: source.id, error: normalizeError(error) };\n }\n};\n\n/** Loads CSF modules and publishes subscribable explorer snapshots. */\nclass StoryCatalog {\n private snapshot: StoryCatalogSnapshot = { stories: [], errors: [], isLoading: false };\n private readonly listeners: Set<() => void> = new Set();\n private readonly loadFailures: WeakSet<Error> = new WeakSet();\n private cache = createSourceCache();\n private sessionError: StoryLoadError | undefined;\n private revision = 0;\n\n /** Returns the current snapshot, retaining its identity until the next update. */\n getSnapshot = (): StoryCatalogSnapshot => this.snapshot;\n\n /** Registers a snapshot listener and returns a function that unsubscribes it. */\n subscribe = (listener: () => void): (() => void) => {\n this.listeners.add(listener);\n\n return () => {\n this.listeners.delete(listener);\n };\n };\n\n private publish(snapshot: StoryCatalogSnapshot): void {\n this.snapshot = snapshot;\n\n for (const listener of this.listeners) {\n listener();\n }\n }\n\n /**\n * Replaces the catalog with stories composed from the supplied sources and preview.\n * Only the latest load publishes results; unchanged module identities reuse composed stories.\n * Rejects with an AggregateError after publishing healthy stories when any source fails.\n */\n async load(sources: StorySource[], preview: Preview = EMPTY_PREVIEW): Promise<void> {\n const revision = ++this.revision;\n this.publish({ ...this.snapshot, isLoading: true });\n const loaded = await Promise.all(sources.map((source) => loadSource(source, preview, () => this.cache)));\n\n if (revision !== this.revision) {\n return;\n }\n\n const { cache, stories, errors } = collectSources(loaded);\n this.cache = cache;\n this.sessionError = undefined;\n this.publish({ stories, errors, isLoading: false });\n\n if (errors.length > 0) {\n const failure = new AggregateError(errors.map(({ error }) => error), \"Some stories could not be loaded\");\n this.loadFailures.add(failure);\n throw failure;\n }\n }\n\n /**\n * Replaces the current session failure while preserving source errors and superseding pending loads.\n * Ignores aggregate failures already published by this catalog's load operation.\n */\n reportError(cause: unknown): void {\n if (cause instanceof Error && this.loadFailures.has(cause)) {\n return;\n }\n\n this.revision++;\n const errors = this.snapshot.errors.filter((entry) => entry !== this.sessionError);\n this.sessionError = { source: \"Storybook\", error: normalizeError(cause) };\n this.publish({\n ...this.snapshot,\n isLoading: false,\n errors: [...errors, this.sessionError],\n });\n }\n}\n\nexport { StoryCatalog };\nexport type { StoryCatalogSnapshot, StoryEntry, StoryLoadError, StorySource };\n"]}
@@ -0,0 +1,27 @@
1
+ import type { ComponentMeta, ComposedStories, ComposedStory, Preview, StoryAnnotations, StoryModule } from "./types.js";
2
+ /**
3
+ * Composes a CSF3 story into a native React component with resolved defaults and decorators.
4
+ * Compose outside render to preserve component identity. Rendering props override the composed args.
5
+ * This function does not create an application, window, or Storybook preview lifecycle.
6
+ *
7
+ * @param story The named story's annotations.
8
+ * @param meta The module's default component metadata.
9
+ * @param preview Shared project annotations, scoped to this composition.
10
+ * @param exportName Export name used for the story identifier and default display name.
11
+ * @returns A renderable component exposing its composed annotations.
12
+ * @throws If an annotation is not an object or no component or render function is available.
13
+ */
14
+ declare const composeStory: <TArgs extends object>(story: StoryAnnotations<NoInfer<TArgs>>, meta: ComponentMeta<TArgs>, preview?: Preview, exportName?: string) => ComposedStory<TArgs>;
15
+ /**
16
+ * Composes the selected CSF3 exports of a module into native React components.
17
+ * The default export supplies metadata; its includeStories and excludeStories select named exports.
18
+ * Returned keys retain the original export names.
19
+ *
20
+ * @param stories A story module containing default metadata and named story objects.
21
+ * @param preview Shared project annotations, scoped to the returned compositions.
22
+ * @returns Composed components keyed by the selected export names.
23
+ * @throws If metadata or a selected export is invalid, or a selected story has no renderer.
24
+ */
25
+ declare const composeStories: <TModule extends StoryModule>(stories: TModule, preview?: Preview) => ComposedStories<TModule>;
26
+ export { composeStory, composeStories };
27
+ //# sourceMappingURL=compose.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"compose.d.ts","sourceRoot":"","sources":["../src/compose.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAER,aAAa,EACb,eAAe,EACf,aAAa,EACb,OAAO,EACP,gBAAgB,EAChB,WAAW,EACd,MAAM,YAAY,CAAC;AASpB;;;;;;;;;;;GAWG;AACH,QAAA,MAAM,YAAY,GAAI,KAAK,SAAS,MAAM,EACtC,OAAO,gBAAgB,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,EACvC,MAAM,aAAa,CAAC,KAAK,CAAC,EAC1B,UAAS,OAAY,EACrB,aAAa,MAAM,KACpB,aAAa,CAAC,KAAK,CAkBrB,CAAC;AAEF;;;;;;;;;GASG;AACH,QAAA,MAAM,cAAc,GAAI,OAAO,SAAS,WAAW,EAC/C,SAAS,OAAO,EAChB,UAAS,OAAY,KACtB,eAAe,CAAC,OAAO,CAuBzB,CAAC;AAEF,OAAO,EAAE,YAAY,EAAE,cAAc,EAAE,CAAC"}
@@ -0,0 +1,67 @@
1
+ import { createElement } from "react";
2
+ import { composeStoryAnnotations, isExportStory } from "./upstream.js";
3
+ const requireObject = (value) => {
4
+ if (value === null || typeof value !== "object" || Array.isArray(value)) {
5
+ throw new TypeError("Expected a CSF3 annotation object");
6
+ }
7
+ };
8
+ /**
9
+ * Composes a CSF3 story into a native React component with resolved defaults and decorators.
10
+ * Compose outside render to preserve component identity. Rendering props override the composed args.
11
+ * This function does not create an application, window, or Storybook preview lifecycle.
12
+ *
13
+ * @param story The named story's annotations.
14
+ * @param meta The module's default component metadata.
15
+ * @param preview Shared project annotations, scoped to this composition.
16
+ * @param exportName Export name used for the story identifier and default display name.
17
+ * @returns A renderable component exposing its composed annotations.
18
+ * @throws If an annotation is not an object or no component or render function is available.
19
+ */
20
+ const composeStory = (story, meta, preview = {}, exportName) => {
21
+ requireObject(story);
22
+ requireObject(meta);
23
+ requireObject(preview);
24
+ if (!story.render && !meta.render && !preview.render && !meta.component) {
25
+ throw new TypeError("A story needs a component or render function");
26
+ }
27
+ return composeStoryAnnotations(story, { ...meta }, preview, {
28
+ render: (args) => {
29
+ if (!meta.component) {
30
+ throw new TypeError("A story needs a component or render function");
31
+ }
32
+ return createElement(meta.component, args);
33
+ },
34
+ }, exportName);
35
+ };
36
+ /**
37
+ * Composes the selected CSF3 exports of a module into native React components.
38
+ * The default export supplies metadata; its includeStories and excludeStories select named exports.
39
+ * Returned keys retain the original export names.
40
+ *
41
+ * @param stories A story module containing default metadata and named story objects.
42
+ * @param preview Shared project annotations, scoped to the returned compositions.
43
+ * @returns Composed components keyed by the selected export names.
44
+ * @throws If metadata or a selected export is invalid, or a selected story has no renderer.
45
+ */
46
+ const composeStories = (stories, preview = {}) => {
47
+ requireObject(stories);
48
+ requireObject(stories.default);
49
+ requireObject(preview);
50
+ const meta = stories.default;
51
+ const composed = {};
52
+ for (const [exportName, story] of Object.entries(stories)) {
53
+ if (exportName === "default" || exportName === "__namedExportsOrder" || !isExportStory(exportName, meta)) {
54
+ continue;
55
+ }
56
+ requireObject(story);
57
+ Object.defineProperty(composed, exportName, {
58
+ value: composeStory(story, meta, preview, exportName),
59
+ enumerable: true,
60
+ configurable: true,
61
+ writable: true,
62
+ });
63
+ }
64
+ return composed;
65
+ };
66
+ export { composeStory, composeStories };
67
+ //# sourceMappingURL=compose.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"compose.js","sourceRoot":"","sources":["../src/compose.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,OAAO,CAAC;AAUtC,OAAO,EAAE,uBAAuB,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;AAEvE,MAAM,aAAa,GAAG,CAAC,KAAc,EAAQ,EAAE;IAC3C,IAAI,KAAK,KAAK,IAAI,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC;QACtE,MAAM,IAAI,SAAS,CAAC,mCAAmC,CAAC,CAAC;IAC7D,CAAC;AACL,CAAC,CAAC;AAEF;;;;;;;;;;;GAWG;AACH,MAAM,YAAY,GAAG,CACjB,KAAuC,EACvC,IAA0B,EAC1B,UAAmB,EAAE,EACrB,UAAmB,EACC,EAAE;IACtB,aAAa,CAAC,KAAK,CAAC,CAAC;IACrB,aAAa,CAAC,IAAI,CAAC,CAAC;IACpB,aAAa,CAAC,OAAO,CAAC,CAAC;IAEvB,IAAI,CAAC,KAAK,CAAC,MAAM,IAAI,CAAC,IAAI,CAAC,MAAM,IAAI,CAAC,OAAO,CAAC,MAAM,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,CAAC;QACtE,MAAM,IAAI,SAAS,CAAC,8CAA8C,CAAC,CAAC;IACxE,CAAC;IAED,OAAO,uBAAuB,CAAC,KAAK,EAAE,EAAE,GAAG,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\"react\";\nimport type {\n Args,\n ComponentMeta,\n ComposedStories,\n ComposedStory,\n Preview,\n StoryAnnotations,\n StoryModule,\n} from \"./types.js\";\nimport { composeStoryAnnotations, isExportStory } from \"./upstream.js\";\n\nconst requireObject = (value: unknown): void => {\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) {\n throw new TypeError(\"Expected a CSF3 annotation object\");\n }\n};\n\n/**\n * Composes a CSF3 story into a native React component with resolved defaults and decorators.\n * Compose outside render to preserve component identity. Rendering props override the composed args.\n * This function does not create an application, window, or Storybook preview lifecycle.\n *\n * @param story The named story's annotations.\n * @param meta The module's default component metadata.\n * @param preview Shared project annotations, scoped to this composition.\n * @param exportName Export name used for the story identifier and default display name.\n * @returns A renderable component exposing its composed annotations.\n * @throws If an annotation is not an object or no component or render function is available.\n */\nconst composeStory = <TArgs extends object>(\n story: StoryAnnotations<NoInfer<TArgs>>,\n meta: ComponentMeta<TArgs>,\n preview: Preview = {},\n exportName?: string,\n): ComposedStory<TArgs> => {\n requireObject(story);\n requireObject(meta);\n requireObject(preview);\n\n if (!story.render && !meta.render && !preview.render && !meta.component) {\n throw new TypeError(\"A story needs a component or render function\");\n }\n\n return composeStoryAnnotations(story, { ...meta }, preview, {\n render: (args) => {\n if (!meta.component) {\n throw new TypeError(\"A story needs a component or render function\");\n }\n\n return createElement(meta.component, args);\n },\n }, exportName);\n};\n\n/**\n * Composes the selected CSF3 exports of a module into native React components.\n * The default export supplies metadata; its includeStories and excludeStories select named exports.\n * Returned keys retain the original export names.\n *\n * @param stories A story module containing default metadata and named story objects.\n * @param preview Shared project annotations, scoped to the returned compositions.\n * @returns Composed components keyed by the selected export names.\n * @throws If metadata or a selected export is invalid, or a selected story has no renderer.\n */\nconst composeStories = <TModule extends StoryModule>(\n stories: TModule,\n preview: Preview = {},\n): ComposedStories<TModule> => {\n requireObject(stories);\n requireObject(stories.default);\n requireObject(preview);\n\n const meta = stories.default as ComponentMeta<Args>;\n const composed: Partial<ComposedStories<TModule>> = {};\n\n for (const [exportName, story] of Object.entries(stories)) {\n if (exportName === \"default\" || exportName === \"__namedExportsOrder\" || !isExportStory(exportName, meta)) {\n continue;\n }\n\n requireObject(story);\n Object.defineProperty(composed, exportName, {\n value: composeStory(story as StoryAnnotations<Args>, meta, preview, exportName),\n enumerable: true,\n configurable: true,\n writable: true,\n });\n }\n\n return composed as ComposedStories<TModule>;\n};\n\nexport { composeStory, composeStories };\n"]}