@ms-cloudpack/storybook-builder 0.1.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 (46) hide show
  1. package/README.md +53 -0
  2. package/lib/generateAddonSetupCode.d.ts +2 -0
  3. package/lib/generateAddonSetupCode.d.ts.map +1 -0
  4. package/lib/generateAddonSetupCode.js +16 -0
  5. package/lib/generateAddonSetupCode.js.map +1 -0
  6. package/lib/generateIFrameHtml.d.ts +9 -0
  7. package/lib/generateIFrameHtml.d.ts.map +1 -0
  8. package/lib/generateIFrameHtml.js +49 -0
  9. package/lib/generateIFrameHtml.js.map +1 -0
  10. package/lib/generateIframeScriptCode.d.ts +6 -0
  11. package/lib/generateIframeScriptCode.d.ts.map +1 -0
  12. package/lib/generateIframeScriptCode.js +104 -0
  13. package/lib/generateIframeScriptCode.js.map +1 -0
  14. package/lib/generateImportFnScriptCode.d.ts +10 -0
  15. package/lib/generateImportFnScriptCode.d.ts.map +1 -0
  16. package/lib/generateImportFnScriptCode.js +42 -0
  17. package/lib/generateImportFnScriptCode.js.map +1 -0
  18. package/lib/generateModernIframeScriptCode.d.ts +8 -0
  19. package/lib/generateModernIframeScriptCode.d.ts.map +1 -0
  20. package/lib/generateModernIframeScriptCode.js +71 -0
  21. package/lib/generateModernIframeScriptCode.js.map +1 -0
  22. package/lib/generatePreviewEntryCode.d.ts +3 -0
  23. package/lib/generatePreviewEntryCode.d.ts.map +1 -0
  24. package/lib/generatePreviewEntryCode.js +9 -0
  25. package/lib/generatePreviewEntryCode.js.map +1 -0
  26. package/lib/generateVirtualStoryEntryCode.d.ts +3 -0
  27. package/lib/generateVirtualStoryEntryCode.d.ts.map +1 -0
  28. package/lib/generateVirtualStoryEntryCode.js +27 -0
  29. package/lib/generateVirtualStoryEntryCode.js.map +1 -0
  30. package/lib/getNodeModuleDir.d.ts +2 -0
  31. package/lib/getNodeModuleDir.d.ts.map +1 -0
  32. package/lib/getNodeModuleDir.js +7 -0
  33. package/lib/getNodeModuleDir.js.map +1 -0
  34. package/lib/index.d.ts +26 -0
  35. package/lib/index.d.ts.map +1 -0
  36. package/lib/index.js +213 -0
  37. package/lib/index.js.map +1 -0
  38. package/lib/listStories.d.ts +3 -0
  39. package/lib/listStories.d.ts.map +1 -0
  40. package/lib/listStories.js +23 -0
  41. package/lib/listStories.js.map +1 -0
  42. package/lib/utils/processPreviewAnnotation.d.ts +14 -0
  43. package/lib/utils/processPreviewAnnotation.d.ts.map +1 -0
  44. package/lib/utils/processPreviewAnnotation.js +69 -0
  45. package/lib/utils/processPreviewAnnotation.js.map +1 -0
  46. package/package.json +57 -0
package/README.md ADDED
@@ -0,0 +1,53 @@
1
+ # @ms-cloudpack/storybook-builder
2
+
3
+ Experimental storybook builder using Cloudpack.
4
+
5
+ ## Installation
6
+
7
+ Install the builder with npm:
8
+
9
+ ```bash
10
+ npm install @ms-cloudpack/storybook-builder --save-dev
11
+ ```
12
+
13
+ or yarn:
14
+
15
+ ```bash
16
+ yarn add @ms-cloudpack/storybook-builder --dev
17
+ ```
18
+
19
+ ## Configuration
20
+
21
+ Configure the builder in the Storybook [main configuration](https://storybook.js.org/docs/react/configure) file:
22
+
23
+ ```ts
24
+ // .storybook/main.js
25
+
26
+ const config = {
27
+ ...
28
+ framework: '@storybook/your-framework',
29
+ core: {
30
+ builder: {
31
+ name: '@ms-cloudpack/storybook-builder',
32
+ options: {
33
+ ...
34
+ },
35
+ },
36
+ ...
37
+ },
38
+ ...
39
+ };
40
+
41
+ export default config;
42
+ ```
43
+
44
+ ### Customize Cloudpack config
45
+
46
+ The builder _will_ read your `cloudpack.config.json` file, though it may add some options in order to work correctly. Ensure to have the Cloudpack config in the CWD.
47
+
48
+ ### Unsupported features
49
+
50
+ These are features that are not yet supported by the builder:
51
+
52
+ - React docgen
53
+ - MDX
@@ -0,0 +1,2 @@
1
+ export declare function generateAddonSetupCode(): string;
2
+ //# sourceMappingURL=generateAddonSetupCode.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"generateAddonSetupCode.d.ts","sourceRoot":"","sources":["../src/generateAddonSetupCode.ts"],"names":[],"mappings":"AAEA,wBAAgB,sBAAsB,WAarC"}
@@ -0,0 +1,16 @@
1
+ // based on https://github.com/storybookjs/storybook/blob/v7.6.5/code/builders/builder-vite/src/codegen-set-addon-channel.ts
2
+ export function generateAddonSetupCode() {
3
+ return `
4
+ import { createBrowserChannel } from '@storybook/channels';
5
+ import { addons } from '@storybook/preview-api';
6
+
7
+ const channel = createBrowserChannel({ page: 'preview' });
8
+ addons.setChannel(channel);
9
+ window.__STORYBOOK_ADDONS_CHANNEL__ = channel;
10
+
11
+ if (window.CONFIG_TYPE === 'DEVELOPMENT'){
12
+ window.__STORYBOOK_SERVER_CHANNEL__ = channel;
13
+ }
14
+ `.trim();
15
+ }
16
+ //# sourceMappingURL=generateAddonSetupCode.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"generateAddonSetupCode.js","sourceRoot":"","sources":["../src/generateAddonSetupCode.ts"],"names":[],"mappings":"AAAA,4HAA4H;AAE5H,MAAM,UAAU,sBAAsB;IACpC,OAAO;;;;;;;;;;;GAWN,CAAC,IAAI,EAAE,CAAC;AACX,CAAC","sourcesContent":["// based on https://github.com/storybookjs/storybook/blob/v7.6.5/code/builders/builder-vite/src/codegen-set-addon-channel.ts\n\nexport function generateAddonSetupCode() {\n return `\n import { createBrowserChannel } from '@storybook/channels';\n import { addons } from '@storybook/preview-api';\n\n const channel = createBrowserChannel({ page: 'preview' });\n addons.setChannel(channel);\n window.__STORYBOOK_ADDONS_CHANNEL__ = channel;\n\n if (window.CONFIG_TYPE === 'DEVELOPMENT'){\n window.__STORYBOOK_SERVER_CHANNEL__ = channel;\n }\n `.trim();\n}\n"]}
@@ -0,0 +1,9 @@
1
+ import type { Options } from '@storybook/types';
2
+ import type { PackageDefinitionsCache } from '@ms-cloudpack/bundler-types';
3
+ import type { Session } from '@ms-cloudpack/api-server';
4
+ export type PreviewHtml = string | undefined;
5
+ export declare function generateIframeHtml(options: Options, appPath: string, context: {
6
+ packages: PackageDefinitionsCache;
7
+ session: Session;
8
+ }): Promise<string>;
9
+ //# sourceMappingURL=generateIFrameHtml.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"generateIFrameHtml.d.ts","sourceRoot":"","sources":["../src/generateIFrameHtml.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAA2B,OAAO,EAAE,MAAM,kBAAkB,CAAC;AAMzE,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,6BAA6B,CAAC;AAC3E,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,0BAA0B,CAAC;AAIxD,MAAM,MAAM,WAAW,GAAG,MAAM,GAAG,SAAS,CAAC;AAE7C,wBAAsB,kBAAkB,CACtC,OAAO,EAAE,OAAO,EAChB,OAAO,EAAE,MAAM,EACf,OAAO,EAAE;IAAE,QAAQ,EAAE,uBAAuB,CAAC;IAAC,OAAO,EAAE,OAAO,CAAA;CAAE,GAC/D,OAAO,CAAC,MAAM,CAAC,CAoDjB"}
@@ -0,0 +1,49 @@
1
+ // based on https://github.com/storybookjs/storybook/blob/v7.6.5/code/builders/builder-vite/src/transform-iframe-html.ts
2
+ import { normalizeStories } from '@storybook/core-common';
3
+ import { readFile } from 'fs/promises';
4
+ import { fileURLToPath } from 'url';
5
+ import path from 'path';
6
+ import { generateModernIframeScriptCode } from './generateModernIframeScriptCode.js';
7
+ import { generateIframeScriptCode } from './generateIframeScriptCode.js';
8
+ let generatedIframeHtml = undefined;
9
+ export async function generateIframeHtml(options, appPath, context) {
10
+ const iFramePath = path.join(path.dirname(fileURLToPath(import.meta.url)), '../static/iframeTemplate.html');
11
+ const iframeHtmlTemplate = await readFile(iFramePath, { encoding: 'utf-8' });
12
+ const { configType, features, presets, serverChannelUrl, configDir } = options;
13
+ const build = await presets.apply('build');
14
+ const frameworkOptions = await presets.apply('frameworkOptions');
15
+ const headHtmlSnippet = await presets.apply('previewHead');
16
+ const bodyHtmlSnippet = await presets.apply('previewBody');
17
+ const logLevel = await presets.apply('logLevel', undefined);
18
+ const docsOptions = await presets.apply('docs');
19
+ const coreOptions = await presets.apply('core');
20
+ const stories = normalizeStories(await presets.apply('stories', [], options), {
21
+ configDir,
22
+ workingDir: appPath,
23
+ }).map((specifier) => ({
24
+ ...specifier,
25
+ importPathMatcher: specifier.importPathMatcher.source,
26
+ }));
27
+ const otherGlobals = {
28
+ ...(build?.test?.disableBlocks ? { __STORYBOOK_BLOCKS_EMPTY_MODULE__: {} } : {}),
29
+ };
30
+ generatedIframeHtml = iframeHtmlTemplate
31
+ .replace('[CONFIG_TYPE HERE]', configType || '')
32
+ .replace('[LOGLEVEL HERE]', logLevel || '')
33
+ .replace(`'[FRAMEWORK_OPTIONS HERE]'`, JSON.stringify(frameworkOptions))
34
+ .replace(`('OTHER_GLOBLALS HERE');`, Object.entries(otherGlobals)
35
+ .map(([k, v]) => `window["${k}"] = ${JSON.stringify(v)};`)
36
+ .join(''))
37
+ .replace(`'[CHANNEL_OPTIONS HERE]'`, JSON.stringify(coreOptions && coreOptions.channelOptions ? coreOptions.channelOptions : {}))
38
+ .replace(`'[FEATURES HERE]'`, JSON.stringify(features || {}))
39
+ .replace(`'[STORIES HERE]'`, JSON.stringify(stories || {}))
40
+ .replace(`'[DOCS_OPTIONS HERE]'`, JSON.stringify(docsOptions || {}))
41
+ .replace(`'[SERVER_CHANNEL_URL HERE]'`, JSON.stringify(serverChannelUrl))
42
+ .replace('<!-- [HEAD HTML SNIPPET HERE] -->', headHtmlSnippet || '')
43
+ .replace('<!-- [BODY HTML SNIPPET HERE] -->', bodyHtmlSnippet || '')
44
+ .replace(`('[APP MODULE SRC HERE]');`, options.features?.storyStoreV7
45
+ ? await generateModernIframeScriptCode(options, appPath, context)
46
+ : await generateIframeScriptCode(options, appPath, context));
47
+ return generatedIframeHtml;
48
+ }
49
+ //# sourceMappingURL=generateIFrameHtml.js.map
@@ -0,0 +1 @@
1
+ {"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AC,EAAE,CAAC,CAC5F;SACA,OAAO,CAAC,mBAAmB,EAAE,IAAI,CAAC,SAAS,CAAC,QAAQ,IAAI,EAAE,CAAC,CAAC;SAC5D,OAAO,CAAC,kBAAkB,EAAE,IAAI,CAAC,SAAS,CAAC,OAAO,IAAI,EAAE,CAAC,CAAC;SAC1D,OAAO,CAAC,uBAAuB,EAAE,IAAI,CAAC,SAAS,CAAC,WAAW,IAAI,EAAE,CAAC,CAAC;SACnE,OAAO,CAAC,6BAA6B,EAAE,IAAI,CAAC,SAAS,CAAC,gBAAgB,CAAC,CAAC;SACxE,OAAO,CAAC,mCAAmC,EAAE,eAAe,IAAI,EAAE,CAAC;SACnE,OAAO,CAAC,mCAAmC,EAAE,eAAe,IAAI,EAAE,CAAC;SACnE,OAAO,CACN,4BAA4B,EAC5B,OAAO,CAAC,QAAQ,EAAE,YAAY;QAC5B,CAAC,CAAC,MAAM,8BAA8B,CAAC,OAAO,EAAE,OAAO,EAAE,OAAO,CAAC;QACjE,CAAC,CAAC,MAAM,wBAAwB,CAAC,OAAO,EAAE,OAAO,EAAE,OAAO,CAAC,CAC9D,CAAC;IAEJ,OAAO,mBAAmB,CAAC;AAC7B,CAAC","sourcesContent":["// based on https://github.com/storybookjs/storybook/blob/v7.6.5/code/builders/builder-vite/src/transform-iframe-html.ts\n\nimport { normalizeStories } from '@storybook/core-common';\nimport type { CoreConfig, DocsOptions, Options } from '@storybook/types';\nimport { readFile } from 'fs/promises';\nimport { fileURLToPath } from 'url';\nimport path from 'path';\nimport { generateModernIframeScriptCode } from './generateModernIframeScriptCode.js';\nimport { generateIframeScriptCode } from './generateIframeScriptCode.js';\nimport type { PackageDefinitionsCache } from '@ms-cloudpack/bundler-types';\nimport type { Session } from '@ms-cloudpack/api-server';\n\nlet generatedIframeHtml: string | undefined = undefined;\n\nexport type PreviewHtml = string | undefined;\n\nexport async function generateIframeHtml(\n options: Options,\n appPath: string,\n context: { packages: PackageDefinitionsCache; session: Session },\n): Promise<string> {\n const iFramePath = path.join(path.dirname(fileURLToPath(import.meta.url)), '../static/iframeTemplate.html');\n const iframeHtmlTemplate = await readFile(iFramePath, { encoding: 'utf-8' });\n const { configType, features, presets, serverChannelUrl, configDir } = options;\n const build = await presets.apply('build');\n const frameworkOptions = await presets.apply<Record<string, unknown> | null>('frameworkOptions');\n const headHtmlSnippet = await presets.apply<PreviewHtml>('previewHead');\n const bodyHtmlSnippet = await presets.apply<PreviewHtml>('previewBody');\n const logLevel = await presets.apply('logLevel', undefined);\n const docsOptions = await presets.apply<DocsOptions>('docs');\n\n const coreOptions = await presets.apply<CoreConfig>('core');\n const stories = normalizeStories(await presets.apply('stories', [], options), {\n configDir,\n workingDir: appPath,\n }).map((specifier) => ({\n ...specifier,\n importPathMatcher: specifier.importPathMatcher.source,\n }));\n\n const otherGlobals = {\n ...(build?.test?.disableBlocks ? { __STORYBOOK_BLOCKS_EMPTY_MODULE__: {} } : {}),\n };\n\n generatedIframeHtml = iframeHtmlTemplate\n .replace('[CONFIG_TYPE HERE]', configType || '')\n .replace('[LOGLEVEL HERE]', logLevel || '')\n .replace(`'[FRAMEWORK_OPTIONS HERE]'`, JSON.stringify(frameworkOptions))\n .replace(\n `('OTHER_GLOBLALS HERE');`,\n Object.entries(otherGlobals)\n .map(([k, v]) => `window[\"${k}\"] = ${JSON.stringify(v)};`)\n .join(''),\n )\n .replace(\n `'[CHANNEL_OPTIONS HERE]'`,\n JSON.stringify(coreOptions && coreOptions.channelOptions ? coreOptions.channelOptions : {}),\n )\n .replace(`'[FEATURES HERE]'`, JSON.stringify(features || {}))\n .replace(`'[STORIES HERE]'`, JSON.stringify(stories || {}))\n .replace(`'[DOCS_OPTIONS HERE]'`, JSON.stringify(docsOptions || {}))\n .replace(`'[SERVER_CHANNEL_URL HERE]'`, JSON.stringify(serverChannelUrl))\n .replace('<!-- [HEAD HTML SNIPPET HERE] -->', headHtmlSnippet || '')\n .replace('<!-- [BODY HTML SNIPPET HERE] -->', bodyHtmlSnippet || '')\n .replace(\n `('[APP MODULE SRC HERE]');`,\n options.features?.storyStoreV7\n ? await generateModernIframeScriptCode(options, appPath, context)\n : await generateIframeScriptCode(options, appPath, context),\n );\n\n return generatedIframeHtml;\n}\n"]}
@@ -0,0 +1,6 @@
1
+ import type { Options } from '@storybook/types';
2
+ import type { PackageDefinitionsCache } from '@ms-cloudpack/bundler-types';
3
+ export declare function generateIframeScriptCode(options: Options, appPath: string, context: {
4
+ packages: PackageDefinitionsCache;
5
+ }): Promise<string>;
6
+ //# sourceMappingURL=generateIframeScriptCode.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"generateIframeScriptCode.d.ts","sourceRoot":"","sources":["../src/generateIframeScriptCode.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,OAAO,EAAqB,MAAM,kBAAkB,CAAC;AAInE,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,6BAA6B,CAAC;AAG3E,wBAAsB,wBAAwB,CAC5C,OAAO,EAAE,OAAO,EAChB,OAAO,EAAE,MAAM,EACf,OAAO,EAAE;IAAE,QAAQ,EAAE,uBAAuB,CAAA;CAAE,mBAwG/C"}
@@ -0,0 +1,104 @@
1
+ // based on https://github.com/storybookjs/storybook/blob/v7.6.5/code/lib/builder-vite/src/codegen-iframe-script.ts
2
+ import { getRendererName } from '@storybook/core-common';
3
+ import { processPreviewAnnotation } from './utils/processPreviewAnnotation.js';
4
+ import { generatePreviewEntryCode } from './generatePreviewEntryCode.js';
5
+ import { generateVirtualStoryEntryCode } from './generateVirtualStoryEntryCode.js';
6
+ // TODO: Work in progress, not needed right now as it is not part of storyStoreV7.
7
+ export async function generateIframeScriptCode(options, appPath, context) {
8
+ const { presets } = options;
9
+ const rendererName = await getRendererName(options);
10
+ const previewAnnotations = await presets.apply('previewAnnotations', [], options);
11
+ const configEntries = await Promise.all([...previewAnnotations].filter(Boolean).map((path) => processPreviewAnnotation(path, appPath, context)));
12
+ const filesToImport = (files, name) => files.map((el, i) => `import ${name ? `* as ${name}_${i} from ` : ''}'${el}'`).join('\n');
13
+ const importArray = (name, length) => new Array(length).fill(0).map((_, i) => `${name}_${i}`);
14
+ // noinspection UnnecessaryLocalVariableJS
15
+ /** @todo Inline variable and remove `noinspection` */
16
+ // language=JavaScript
17
+ const code = `
18
+ // Ensure that the client API is initialized by the framework before any other iframe code
19
+ // is loaded. That way our client-apis can assume the existence of the API+store
20
+ import { configure } from '${rendererName}';
21
+
22
+ import { logger } from '@storybook/client-logger';
23
+ import * as previewApi from "@storybook/preview-api";
24
+ ${filesToImport(configEntries, 'config')}
25
+
26
+ ${generatePreviewEntryCode(options)};
27
+ ${await generateVirtualStoryEntryCode(options, appPath)};
28
+
29
+ const {
30
+ addDecorator,
31
+ addParameters,
32
+ addLoader,
33
+ addArgs,
34
+ addArgTypes,
35
+ addStepRunner,
36
+ addArgTypesEnhancer,
37
+ addArgsEnhancer,
38
+ setGlobalRender,
39
+ } = previewApi;
40
+
41
+ const configs = [${importArray('config', configEntries.length).concat('preview.default').join(',')}].filter(Boolean)
42
+
43
+ configs.map(config => config.default ? config.default : config).forEach(config => {
44
+ Object.keys(config).forEach((key) => {
45
+ const value = config[key];
46
+ switch (key) {
47
+ case 'args': {
48
+ return addArgs(value);
49
+ }
50
+ case 'argTypes': {
51
+ return addArgTypes(value);
52
+ }
53
+ case 'decorators': {
54
+ return value.forEach((decorator) => addDecorator(decorator, false));
55
+ }
56
+ case 'loaders': {
57
+ return value.forEach((loader) => addLoader(loader, false));
58
+ }
59
+ case 'parameters': {
60
+ return addParameters({ ...value }, false);
61
+ }
62
+ case 'argTypesEnhancers': {
63
+ return value.forEach((enhancer) => addArgTypesEnhancer(enhancer));
64
+ }
65
+ case 'argsEnhancers': {
66
+ return value.forEach((enhancer) => addArgsEnhancer(enhancer))
67
+ }
68
+ case 'render': {
69
+ return setGlobalRender(value)
70
+ }
71
+ case 'globals':
72
+ case 'globalTypes': {
73
+ const v = {};
74
+ v[key] = value;
75
+ return addParameters(v, false);
76
+ }
77
+ case 'decorateStory':
78
+ case 'applyDecorators':
79
+ case 'renderToDOM': // deprecated
80
+ case 'renderToCanvas': {
81
+ return null; // This key is not handled directly in v6 mode.
82
+ }
83
+ case 'runStep': {
84
+ return addStepRunner(value);
85
+ }
86
+ default: {
87
+ // eslint-disable-next-line prefer-template
88
+ return console.log(key + ' was not supported :( !');
89
+ }
90
+ }
91
+ });
92
+ })
93
+
94
+ /* TODO: not quite sure what to do with this, to fix HMR
95
+ if (import.meta.hot) {
96
+ import.meta.hot.accept();
97
+ }
98
+ */
99
+
100
+ configStories(configure);
101
+ `.trim();
102
+ return code;
103
+ }
104
+ //# sourceMappingURL=generateIframeScriptCode.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"generateIframeScriptCode.js","sourceRoot":"","sources":["../src/generateIframeScriptCode.ts"],"names":[],"mappings":"AAAA,mHAAmH;AAEnH,OAAO,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC;AAEzD,OAAO,EAAE,wBAAwB,EAAE,MAAM,qCAAqC,CAAC;AAC/E,OAAO,EAAE,wBAAwB,EAAE,MAAM,+BAA+B,CAAC;AACzE,OAAO,EAAE,6BAA6B,EAAE,MAAM,oCAAoC,CAAC;AAGnF,kFAAkF;AAClF,MAAM,CAAC,KAAK,UAAU,wBAAwB,CAC5C,OAAgB,EAChB,OAAe,EACf,OAA8C;IAE9C,MAAM,EAAE,OAAO,EAAE,GAAG,OAAO,CAAC;IAC5B,MAAM,YAAY,GAAG,MAAM,eAAe,CAAC,OAAO,CAAC,CAAC;IAEpD,MAAM,kBAAkB,GAAG,MAAM,OAAO,CAAC,KAAK,CAAsB,oBAAoB,EAAE,EAAE,EAAE,OAAO,CAAC,CAAC;IACvG,MAAM,aAAa,GAAG,MAAM,OAAO,CAAC,GAAG,CACrC,CAAC,GAAG,kBAAkB,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,wBAAwB,CAAC,IAAI,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC,CACxG,CAAC;IAEF,MAAM,aAAa,GAAG,CAAC,KAAe,EAAE,IAAY,EAAE,EAAE,CACtD,KAAK,CAAC,GAAG,CAAC,CAAC,EAAE,EAAE,CAAC,EAAE,EAAE,CAAC,UAAU,IAAI,CAAC,CAAC,CAAC,QAAQ,IAAI,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,GAAG,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IAE5F,MAAM,WAAW,GAAG,CAAC,IAAY,EAAE,MAAc,EAAE,EAAE,CAAC,IAAI,KAAK,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,GAAG,IAAI,IAAI,CAAC,EAAE,CAAC,CAAC;IAE9G,0CAA0C;IAC1C,sDAAsD;IACtD,sBAAsB;IACtB,MAAM,IAAI,GAAG;;;iCAGkB,YAAY;;;;MAIvC,aAAa,CAAC,aAAa,EAAE,QAAQ,CAAC;;MAEtC,wBAAwB,CAAC,OAAO,CAAC;MACjC,MAAM,6BAA6B,CAAC,OAAO,EAAE,OAAO,CAAC;;;;;;;;;;;;;;uBAcpC,WAAW,CAAC,QAAQ,EAAE,aAAa,CAAC,MAAM,CAAC,CAAC,MAAM,CAAC,iBAAiB,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KA4DjG,CAAC,IAAI,EAAE,CAAC;IACX,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["// based on https://github.com/storybookjs/storybook/blob/v7.6.5/code/lib/builder-vite/src/codegen-iframe-script.ts\n\nimport { getRendererName } from '@storybook/core-common';\nimport type { Options, PreviewAnnotation } from '@storybook/types';\nimport { processPreviewAnnotation } from './utils/processPreviewAnnotation.js';\nimport { generatePreviewEntryCode } from './generatePreviewEntryCode.js';\nimport { generateVirtualStoryEntryCode } from './generateVirtualStoryEntryCode.js';\nimport type { PackageDefinitionsCache } from '@ms-cloudpack/bundler-types';\n\n// TODO: Work in progress, not needed right now as it is not part of storyStoreV7.\nexport async function generateIframeScriptCode(\n options: Options,\n appPath: string,\n context: { packages: PackageDefinitionsCache },\n) {\n const { presets } = options;\n const rendererName = await getRendererName(options);\n\n const previewAnnotations = await presets.apply<PreviewAnnotation[]>('previewAnnotations', [], options);\n const configEntries = await Promise.all(\n [...previewAnnotations].filter(Boolean).map((path) => processPreviewAnnotation(path, appPath, context)),\n );\n\n const filesToImport = (files: string[], name: string) =>\n files.map((el, i) => `import ${name ? `* as ${name}_${i} from ` : ''}'${el}'`).join('\\n');\n\n const importArray = (name: string, length: number) => new Array(length).fill(0).map((_, i) => `${name}_${i}`);\n\n // noinspection UnnecessaryLocalVariableJS\n /** @todo Inline variable and remove `noinspection` */\n // language=JavaScript\n const code = `\n // Ensure that the client API is initialized by the framework before any other iframe code\n // is loaded. That way our client-apis can assume the existence of the API+store\n import { configure } from '${rendererName}';\n\n import { logger } from '@storybook/client-logger';\n import * as previewApi from \"@storybook/preview-api\";\n ${filesToImport(configEntries, 'config')}\n\n ${generatePreviewEntryCode(options)};\n ${await generateVirtualStoryEntryCode(options, appPath)};\n\n const {\n addDecorator,\n addParameters,\n addLoader,\n addArgs,\n addArgTypes,\n addStepRunner,\n addArgTypesEnhancer,\n addArgsEnhancer,\n setGlobalRender,\n } = previewApi;\n\n const configs = [${importArray('config', configEntries.length).concat('preview.default').join(',')}].filter(Boolean)\n\n configs.map(config => config.default ? config.default : config).forEach(config => {\n Object.keys(config).forEach((key) => {\n const value = config[key];\n switch (key) {\n case 'args': {\n return addArgs(value);\n }\n case 'argTypes': {\n return addArgTypes(value);\n }\n case 'decorators': {\n return value.forEach((decorator) => addDecorator(decorator, false));\n }\n case 'loaders': {\n return value.forEach((loader) => addLoader(loader, false));\n }\n case 'parameters': {\n return addParameters({ ...value }, false);\n }\n case 'argTypesEnhancers': {\n return value.forEach((enhancer) => addArgTypesEnhancer(enhancer));\n }\n case 'argsEnhancers': {\n return value.forEach((enhancer) => addArgsEnhancer(enhancer))\n }\n case 'render': {\n return setGlobalRender(value)\n }\n case 'globals':\n case 'globalTypes': {\n const v = {};\n v[key] = value;\n return addParameters(v, false);\n }\n case 'decorateStory':\n case 'applyDecorators':\n case 'renderToDOM': // deprecated\n case 'renderToCanvas': {\n return null; // This key is not handled directly in v6 mode.\n }\n case 'runStep': {\n return addStepRunner(value);\n }\n default: {\n // eslint-disable-next-line prefer-template\n return console.log(key + ' was not supported :( !');\n }\n }\n });\n })\n\n /* TODO: not quite sure what to do with this, to fix HMR\n if (import.meta.hot) {\n import.meta.hot.accept();\n }\n */\n\n configStories(configure);\n `.trim();\n return code;\n}\n"]}
@@ -0,0 +1,10 @@
1
+ import type { Options } from '@storybook/types';
2
+ /**
3
+ * This function takes an array of stories and creates a mapping between the stories' relative paths
4
+ * to the working directory and their dynamic imports. The import is done in an asynchronous function
5
+ * to delay loading. It then creates a function, `importFn(path)`, which resolves a path to an import
6
+ * function and this is called by Storybook to fetch a story dynamically when needed.
7
+ * @param stories An array of absolute story paths.
8
+ */
9
+ export declare function generateImportFnScriptCode(options: Options, appPath: string): Promise<string>;
10
+ //# sourceMappingURL=generateImportFnScriptCode.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"generateImportFnScriptCode.d.ts","sourceRoot":"","sources":["../src/generateImportFnScriptCode.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,kBAAkB,CAAC;AAehD;;;;;;GAMG;AACH,wBAAsB,0BAA0B,CAAC,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAsBnG"}
@@ -0,0 +1,42 @@
1
+ // based on https://github.com/storybookjs/storybook/blob/v7.6.5/code/builders/builder-vite/src/codegen-importfn-script.ts
2
+ import { listStories } from './listStories.js';
3
+ import { slash } from '@ms-cloudpack/path-string-parsing';
4
+ import path from 'path';
5
+ import { logger } from '@storybook/node-logger';
6
+ /**
7
+ * Paths get passed either with no leading './' - e.g. `src/Foo.stories.js`,
8
+ * or with a leading `../` (etc), e.g. `../src/Foo.stories.js`.
9
+ * We want to deal in importPaths relative to the working dir, so we normalize
10
+ */
11
+ function toImportPath(relativePath) {
12
+ return relativePath.startsWith('../') ? relativePath : `./${relativePath}`;
13
+ }
14
+ /**
15
+ * This function takes an array of stories and creates a mapping between the stories' relative paths
16
+ * to the working directory and their dynamic imports. The import is done in an asynchronous function
17
+ * to delay loading. It then creates a function, `importFn(path)`, which resolves a path to an import
18
+ * function and this is called by Storybook to fetch a story dynamically when needed.
19
+ * @param stories An array of absolute story paths.
20
+ */
21
+ export async function generateImportFnScriptCode(options, appPath) {
22
+ const stories = await listStories(options);
23
+ const objectEntries = stories.map((file) => {
24
+ const ext = path.extname(file);
25
+ const relativeStoryPath = slash(path.relative(appPath, file));
26
+ // TODO: Add support for '.mdx',
27
+ if (!['.js', '.jsx', '.ts', '.tsx'].includes(ext)) {
28
+ logger.warn(`Cannot process ${ext} file with storyStoreV7: ${relativeStoryPath}`);
29
+ }
30
+ return ` '${toImportPath(relativeStoryPath)}': async () => import('@ms-cloudpack/storybook-mock/${relativeStoryPath}')`;
31
+ });
32
+ return `
33
+ const importers = {
34
+ ${objectEntries.join(',\n')}
35
+ };
36
+
37
+ export async function importFn(path) {
38
+ return importers[path]();
39
+ }
40
+ `.trim();
41
+ }
42
+ //# sourceMappingURL=generateImportFnScriptCode.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"generateImportFnScriptCode.js","sourceRoot":"","sources":["../src/generateImportFnScriptCode.ts"],"names":[],"mappings":"AAAA,0HAA0H;AAG1H,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAC/C,OAAO,EAAE,KAAK,EAAE,MAAM,mCAAmC,CAAC;AAC1D,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAE,MAAM,EAAE,MAAM,wBAAwB,CAAC;AAEhD;;;;GAIG;AACH,SAAS,YAAY,CAAC,YAAoB;IACxC,OAAO,YAAY,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC,KAAK,YAAY,EAAE,CAAC;AAC7E,CAAC;AAED;;;;;;GAMG;AACH,MAAM,CAAC,KAAK,UAAU,0BAA0B,CAAC,OAAgB,EAAE,OAAe;IAChF,MAAM,OAAO,GAAG,MAAM,WAAW,CAAC,OAAO,CAAC,CAAC;IAC3C,MAAM,aAAa,GAAG,OAAO,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE;QACzC,MAAM,GAAG,GAAG,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;QAC/B,MAAM,iBAAiB,GAAG,KAAK,CAAC,IAAI,CAAC,QAAQ,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC,CAAC;QAC9D,gCAAgC;QAChC,IAAI,CAAC,CAAC,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,CAAC,CAAC,QAAQ,CAAC,GAAG,CAAC,EAAE,CAAC;YAClD,MAAM,CAAC,IAAI,CAAC,kBAAkB,GAAG,4BAA4B,iBAAiB,EAAE,CAAC,CAAC;QACpF,CAAC;QAED,OAAO,MAAM,YAAY,CAAC,iBAAiB,CAAC,uDAAuD,iBAAiB,IAAI,CAAC;IAC3H,CAAC,CAAC,CAAC;IAEH,OAAO;;MAEH,aAAa,CAAC,IAAI,CAAC,KAAK,CAAC;;;;;;GAM5B,CAAC,IAAI,EAAE,CAAC;AACX,CAAC","sourcesContent":["// based on https://github.com/storybookjs/storybook/blob/v7.6.5/code/builders/builder-vite/src/codegen-importfn-script.ts\n\nimport type { Options } from '@storybook/types';\nimport { listStories } from './listStories.js';\nimport { slash } from '@ms-cloudpack/path-string-parsing';\nimport path from 'path';\nimport { logger } from '@storybook/node-logger';\n\n/**\n * Paths get passed either with no leading './' - e.g. `src/Foo.stories.js`,\n * or with a leading `../` (etc), e.g. `../src/Foo.stories.js`.\n * We want to deal in importPaths relative to the working dir, so we normalize\n */\nfunction toImportPath(relativePath: string) {\n return relativePath.startsWith('../') ? relativePath : `./${relativePath}`;\n}\n\n/**\n * This function takes an array of stories and creates a mapping between the stories' relative paths\n * to the working directory and their dynamic imports. The import is done in an asynchronous function\n * to delay loading. It then creates a function, `importFn(path)`, which resolves a path to an import\n * function and this is called by Storybook to fetch a story dynamically when needed.\n * @param stories An array of absolute story paths.\n */\nexport async function generateImportFnScriptCode(options: Options, appPath: string): Promise<string> {\n const stories = await listStories(options);\n const objectEntries = stories.map((file) => {\n const ext = path.extname(file);\n const relativeStoryPath = slash(path.relative(appPath, file));\n // TODO: Add support for '.mdx',\n if (!['.js', '.jsx', '.ts', '.tsx'].includes(ext)) {\n logger.warn(`Cannot process ${ext} file with storyStoreV7: ${relativeStoryPath}`);\n }\n\n return ` '${toImportPath(relativeStoryPath)}': async () => import('@ms-cloudpack/storybook-mock/${relativeStoryPath}')`;\n });\n\n return `\n const importers = {\n ${objectEntries.join(',\\n')}\n };\n\n export async function importFn(path) {\n return importers[path]();\n }\n `.trim();\n}\n"]}
@@ -0,0 +1,8 @@
1
+ import type { Options } from '@storybook/types';
2
+ import type { PackageDefinitionsCache } from '@ms-cloudpack/bundler-types';
3
+ import type { Session } from '@ms-cloudpack/api-server';
4
+ export declare function generateModernIframeScriptCode(options: Options, appPath: string, context: {
5
+ packages: PackageDefinitionsCache;
6
+ session: Session;
7
+ }): Promise<string>;
8
+ //# sourceMappingURL=generateModernIframeScriptCode.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"generateModernIframeScriptCode.d.ts","sourceRoot":"","sources":["../src/generateModernIframeScriptCode.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,OAAO,EAAqB,MAAM,kBAAkB,CAAC;AAKnE,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,6BAA6B,CAAC;AAE3E,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,0BAA0B,CAAC;AAIxD,wBAAsB,8BAA8B,CAClD,OAAO,EAAE,OAAO,EAChB,OAAO,EAAE,MAAM,EACf,OAAO,EAAE;IAAE,QAAQ,EAAE,uBAAuB,CAAC;IAAC,OAAO,EAAE,OAAO,CAAA;CAAE,GAC/D,OAAO,CAAC,MAAM,CAAC,CA2EjB"}
@@ -0,0 +1,71 @@
1
+ // based on https://github.com/storybookjs/storybook/blob/v7.6.5/code/lib/builder-vite/src/codegen-modern-iframe-script.ts
2
+ import { loadPreviewOrConfigFile, getFrameworkName } from '@storybook/core-common';
3
+ import { generateAddonSetupCode } from './generateAddonSetupCode.js';
4
+ import { processPreviewAnnotation } from './utils/processPreviewAnnotation.js';
5
+ import { generateImportFnScriptCode } from './generateImportFnScriptCode.js';
6
+ import { generateVirtualStoryEntryCode } from './generateVirtualStoryEntryCode.js';
7
+ import { addExportsMapEntry, getExportsMap } from '@ms-cloudpack/package-utilities';
8
+ import { safeRelativePath } from '@ms-cloudpack/path-string-parsing';
9
+ import { relative } from 'path';
10
+ export async function generateModernIframeScriptCode(options, appPath, context) {
11
+ const { presets, configDir } = options;
12
+ const { session, packages } = context;
13
+ const frameworkName = await getFrameworkName(options);
14
+ const previewOrConfigFile = loadPreviewOrConfigFile({ configDir });
15
+ if (previewOrConfigFile) {
16
+ const exports = await getExportsMap({ packagePath: appPath }, { packages, config: session.config });
17
+ await addExportsMapEntry({
18
+ exports,
19
+ packagePath: appPath,
20
+ importPath: safeRelativePath(relative(appPath, previewOrConfigFile)),
21
+ }, { packages, config: session.config });
22
+ }
23
+ const previewAnnotations = await presets.apply('previewAnnotations', [], options);
24
+ const previewAnnotationURLs = await Promise.all([...previewAnnotations, previewOrConfigFile]
25
+ .filter((path) => !!path)
26
+ .map(async (path) => await processPreviewAnnotation(path, appPath, context)));
27
+ // This is pulled out to a variable because it is reused in both the initial page load
28
+ // and the HMR handler. We don't use the hot.accept callback params because only the changed
29
+ // modules are provided, the rest are null. We can just re-import everything again in that case.
30
+ const getPreviewAnnotationsFunction = `
31
+ const getProjectAnnotations = async () => {
32
+ const configs = await Promise.all([${previewAnnotationURLs
33
+ .map((previewAnnotation) => `import('${previewAnnotation.split('\\').join('\\\\')}')`)
34
+ .join(',\n')}]);
35
+ return composeConfigs(configs);
36
+ }`;
37
+ const generateHMRHandler = () => {
38
+ // Web components are not compatible with HMR, so disable HMR, reload page instead.
39
+ if (frameworkName === '@ms-cloudpack/storybook-react') {
40
+ return `
41
+ if (import.meta.hot) {
42
+ import.meta.hot.decline();
43
+ };`.trim();
44
+ }
45
+ return `
46
+ if (import.meta.hot) {
47
+ alert('HMR is not supported for web components, reloading the page instead.');
48
+ window.location.reload();
49
+ };`.trim();
50
+ };
51
+ return `
52
+ import { composeConfigs, PreviewWeb, ClientApi } from '@storybook/preview-api';
53
+
54
+ ${generateAddonSetupCode()};
55
+
56
+ ${options.features?.storyStoreV7
57
+ ? await generateImportFnScriptCode(options, appPath)
58
+ : await generateVirtualStoryEntryCode(options, appPath)}
59
+
60
+ ${getPreviewAnnotationsFunction}
61
+
62
+ window.__STORYBOOK_PREVIEW__ = window.__STORYBOOK_PREVIEW__ || new PreviewWeb();
63
+
64
+ window.__STORYBOOK_STORY_STORE__ = window.__STORYBOOK_STORY_STORE__ || window.__STORYBOOK_PREVIEW__.storyStore;
65
+ window.__STORYBOOK_CLIENT_API__ = window.__STORYBOOK_CLIENT_API__ || new ClientApi({ storyStore: window.__STORYBOOK_PREVIEW__.storyStore });
66
+ window.__STORYBOOK_PREVIEW__.initialize({ importFn, getProjectAnnotations });
67
+
68
+ ${generateHMRHandler()}
69
+ `.trim();
70
+ }
71
+ //# sourceMappingURL=generateModernIframeScriptCode.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"generateModernIframeScriptCode.js","sourceRoot":"","sources":["../src/generateMod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/lib/builder-vite/src/codegen-modern-iframe-script.ts\n\nimport { loadPreviewOrConfigFile, getFrameworkName } from '@storybook/core-common';\nimport type { Options, PreviewAnnotation } from '@storybook/types';\nimport { generateAddonSetupCode } from './generateAddonSetupCode.js';\nimport { processPreviewAnnotation } from './utils/processPreviewAnnotation.js';\nimport { generateImportFnScriptCode } from './generateImportFnScriptCode.js';\nimport { generateVirtualStoryEntryCode } from './generateVirtualStoryEntryCode.js';\nimport type { PackageDefinitionsCache } from '@ms-cloudpack/bundler-types';\nimport { addExportsMapEntry, getExportsMap } from '@ms-cloudpack/package-utilities';\nimport type { Session } from '@ms-cloudpack/api-server';\nimport { safeRelativePath } from '@ms-cloudpack/path-string-parsing';\nimport { relative } from 'path';\n\nexport async function generateModernIframeScriptCode(\n options: Options,\n appPath: string,\n context: { packages: PackageDefinitionsCache; session: Session },\n): Promise<string> {\n const { presets, configDir } = options;\n const { session, packages } = context;\n const frameworkName = await getFrameworkName(options);\n\n const previewOrConfigFile = loadPreviewOrConfigFile({ configDir });\n\n if (previewOrConfigFile) {\n const exports = await getExportsMap({ packagePath: appPath }, { packages, config: session.config });\n await addExportsMapEntry(\n {\n exports,\n packagePath: appPath,\n importPath: safeRelativePath(relative(appPath, previewOrConfigFile)),\n },\n { packages, config: session.config },\n );\n }\n\n const previewAnnotations = await presets.apply<PreviewAnnotation[]>('previewAnnotations', [], options);\n const previewAnnotationURLs = await Promise.all(\n [...previewAnnotations, previewOrConfigFile]\n .filter((path): path is PreviewAnnotation => !!path)\n .map(async (path: PreviewAnnotation) => await processPreviewAnnotation(path, appPath, context)),\n );\n\n // This is pulled out to a variable because it is reused in both the initial page load\n // and the HMR handler. We don't use the hot.accept callback params because only the changed\n // modules are provided, the rest are null. We can just re-import everything again in that case.\n\n const getPreviewAnnotationsFunction = `\n const getProjectAnnotations = async () => {\n const configs = await Promise.all([${previewAnnotationURLs\n .map((previewAnnotation) => `import('${previewAnnotation.split('\\\\').join('\\\\\\\\')}')`)\n .join(',\\n')}]);\n return composeConfigs(configs);\n }`;\n\n const generateHMRHandler = (): string => {\n // Web components are not compatible with HMR, so disable HMR, reload page instead.\n if (frameworkName === '@ms-cloudpack/storybook-react') {\n return `\n if (import.meta.hot) {\n import.meta.hot.decline();\n };`.trim();\n }\n\n return `\n if (import.meta.hot) {\n alert('HMR is not supported for web components, reloading the page instead.');\n window.location.reload();\n };`.trim();\n };\n\n return `\n import { composeConfigs, PreviewWeb, ClientApi } from '@storybook/preview-api';\n\n ${generateAddonSetupCode()};\n\n ${\n options.features?.storyStoreV7\n ? await generateImportFnScriptCode(options, appPath)\n : await generateVirtualStoryEntryCode(options, appPath)\n }\n\n ${getPreviewAnnotationsFunction}\n\n window.__STORYBOOK_PREVIEW__ = window.__STORYBOOK_PREVIEW__ || new PreviewWeb();\n\n window.__STORYBOOK_STORY_STORE__ = window.__STORYBOOK_STORY_STORE__ || window.__STORYBOOK_PREVIEW__.storyStore;\n window.__STORYBOOK_CLIENT_API__ = window.__STORYBOOK_CLIENT_API__ || new ClientApi({ storyStore: window.__STORYBOOK_PREVIEW__.storyStore });\n window.__STORYBOOK_PREVIEW__.initialize({ importFn, getProjectAnnotations });\n\n ${generateHMRHandler()}\n `.trim();\n}\n"]}
@@ -0,0 +1,3 @@
1
+ import type { Options } from '@storybook/types';
2
+ export declare function generatePreviewEntryCode({ configDir }: Options): string;
3
+ //# sourceMappingURL=generatePreviewEntryCode.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"generatePreviewEntryCode.d.ts","sourceRoot":"","sources":["../src/generatePreviewEntryCode.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,kBAAkB,CAAC;AAEhD,wBAAgB,wBAAwB,CAAC,EAAE,SAAS,EAAE,EAAE,OAAO,GAAG,MAAM,CAKvE"}
@@ -0,0 +1,9 @@
1
+ import { slash } from '@ms-cloudpack/path-string-parsing';
2
+ import { loadPreviewOrConfigFile } from '@storybook/core-common';
3
+ export function generatePreviewEntryCode({ configDir }) {
4
+ const previewFile = loadPreviewOrConfigFile({ configDir });
5
+ if (!previewFile)
6
+ return '';
7
+ return `import * as preview from '${slash(previewFile)}';`;
8
+ }
9
+ //# sourceMappingURL=generatePreviewEntryCode.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"generatePreviewEntryCode.js","sourceRoot":"","sources":["../src/generatePreviewEntryCode.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,mCAAmC,CAAC;AAC1D,OAAO,EAAE,uBAAuB,EAAE,MAAM,wBAAwB,CAAC;AAGjE,MAAM,UAAU,wBAAwB,CAAC,EAAE,SAAS,EAAW;IAC7D,MAAM,WAAW,GAAG,uBAAuB,CAAC,EAAE,SAAS,EAAE,CAAC,CAAC;IAC3D,IAAI,CAAC,WAAW;QAAE,OAAO,EAAE,CAAC;IAE5B,OAAO,6BAA6B,KAAK,CAAC,WAAW,CAAC,IAAI,CAAC;AAC7D,CAAC","sourcesContent":["import { slash } from '@ms-cloudpack/path-string-parsing';\nimport { loadPreviewOrConfigFile } from '@storybook/core-common';\nimport type { Options } from '@storybook/types';\n\nexport function generatePreviewEntryCode({ configDir }: Options): string {\n const previewFile = loadPreviewOrConfigFile({ configDir });\n if (!previewFile) return '';\n\n return `import * as preview from '${slash(previewFile)}';`;\n}\n"]}
@@ -0,0 +1,3 @@
1
+ import type { Options } from '@storybook/types';
2
+ export declare function generateVirtualStoryEntryCode(options: Options, appPath: string): Promise<string>;
3
+ //# sourceMappingURL=generateVirtualStoryEntryCode.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"generateVirtualStoryEntryCode.d.ts","sourceRoot":"","sources":["../src/generateVirtualStoryEntryCode.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,kBAAkB,CAAC;AAQhD,wBAAsB,6BAA6B,CAAC,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAwBtG"}
@@ -0,0 +1,27 @@
1
+ // based on https://github.com/storybookjs/storybook/blob/v7.6.5/code/builders/builder-vite/src/codegen-entries.ts
2
+ import { listStories } from './listStories.js';
3
+ import { slash } from '@ms-cloudpack/path-string-parsing';
4
+ const absoluteFilesToImport = (files, name) => files.map((el, i) => `import ${name ? `* as ${name}_${i} from ` : ''}'/@fs/${slash(el)}'`).join('\n');
5
+ // TODO: Work in progress, not needed right now as it is not part of storyStoreV7.
6
+ export async function generateVirtualStoryEntryCode(options, appPath) {
7
+ const storyEntries = await listStories(options);
8
+ const resolveMap = storyEntries.reduce((prev, entry) => ({ ...prev, [entry]: entry.replace(slash(appPath), '.') }), {});
9
+ const modules = storyEntries.map((entry, i) => `${JSON.stringify(entry)}: story_${i}`).join(',');
10
+ return `
11
+ ${absoluteFilesToImport(storyEntries, 'story')}
12
+
13
+ function loadable(key) {
14
+ return {${modules}}[key];
15
+ }
16
+
17
+ Object.assign(loadable, {
18
+ keys: () => (${JSON.stringify(Object.keys(resolveMap))}),
19
+ resolve: (key) => (${JSON.stringify(resolveMap)}[key])
20
+ });
21
+
22
+ configStories(configure) {
23
+ configure(loadable, { hot: import.meta.hot }, false);
24
+ }
25
+ `.trim();
26
+ }
27
+ //# sourceMappingURL=generateVirtualStoryEntryCode.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"generateVirtualStoryEntryCode.js","sourceRoot":"","sources":["../src/generateVirtualStoryEntryCode.ts"],"names":[],"mappings":"AAAA,kHAAkH;AAGlH,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAC/C,OAAO,EAAE,KAAK,EAAE,MAAM,mCAAmC,CAAC;AAE1D,MAAM,qBAAqB,GAAG,CAAC,KAAe,EAAE,IAAY,EAAE,EAAE,CAC9D,KAAK,CAAC,GAAG,CAAC,CAAC,EAAE,EAAE,CAAC,EAAE,EAAE,CAAC,UAAU,IAAI,CAAC,CAAC,CAAC,QAAQ,IAAI,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC,EAAE,SAAS,KAAK,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AAExG,kFAAkF;AAClF,MAAM,CAAC,KAAK,UAAU,6BAA6B,CAAC,OAAgB,EAAE,OAAe;IACnF,MAAM,YAAY,GAAG,MAAM,WAAW,CAAC,OAAO,CAAC,CAAC;IAChD,MAAM,UAAU,GAAG,YAAY,CAAC,MAAM,CACpC,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE,CAAC,CAAC,EAAE,GAAG,IAAI,EAAE,CAAC,KAAK,CAAC,EAAE,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,OAAO,CAAC,EAAE,GAAG,CAAC,EAAE,CAAC,EAC3E,EAAE,CACH,CAAC;IACF,MAAM,OAAO,GAAG,YAAY,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,CAAC,EAAE,EAAE,CAAC,GAAG,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,WAAW,CAAC,EAAE,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;IAEjG,OAAO;MACH,qBAAqB,CAAC,YAAY,EAAE,OAAO,CAAC;;;gBAGlC,OAAO;;;;qBAIF,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;2BACjC,IAAI,CAAC,SAAS,CAAC,UAAU,CAAC;;;;;;GAMlD,CAAC,IAAI,EAAE,CAAC;AACX,CAAC","sourcesContent":["// based on https://github.com/storybookjs/storybook/blob/v7.6.5/code/builders/builder-vite/src/codegen-entries.ts\n\nimport type { Options } from '@storybook/types';\nimport { listStories } from './listStories.js';\nimport { slash } from '@ms-cloudpack/path-string-parsing';\n\nconst absoluteFilesToImport = (files: string[], name: string) =>\n files.map((el, i) => `import ${name ? `* as ${name}_${i} from ` : ''}'/@fs/${slash(el)}'`).join('\\n');\n\n// TODO: Work in progress, not needed right now as it is not part of storyStoreV7.\nexport async function generateVirtualStoryEntryCode(options: Options, appPath: string): Promise<string> {\n const storyEntries = await listStories(options);\n const resolveMap = storyEntries.reduce<Record<string, string>>(\n (prev, entry) => ({ ...prev, [entry]: entry.replace(slash(appPath), '.') }),\n {},\n );\n const modules = storyEntries.map((entry, i) => `${JSON.stringify(entry)}: story_${i}`).join(',');\n\n return `\n ${absoluteFilesToImport(storyEntries, 'story')}\n\n function loadable(key) {\n return {${modules}}[key];\n }\n\n Object.assign(loadable, {\n keys: () => (${JSON.stringify(Object.keys(resolveMap))}),\n resolve: (key) => (${JSON.stringify(resolveMap)}[key])\n });\n\n configStories(configure) {\n configure(loadable, { hot: import.meta.hot }, false);\n }\n `.trim();\n}\n"]}
@@ -0,0 +1,2 @@
1
+ export declare function getNodeModuleDir(moduleName: string): string;
2
+ //# sourceMappingURL=getNodeModuleDir.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"getNodeModuleDir.d.ts","sourceRoot":"","sources":["../src/getNodeModuleDir.ts"],"names":[],"mappings":"AAGA,wBAAgB,gBAAgB,CAAC,UAAU,EAAE,MAAM,GAAG,MAAM,CAG3D"}
@@ -0,0 +1,7 @@
1
+ import { createRequire } from 'module';
2
+ import { dirname } from 'path';
3
+ export function getNodeModuleDir(moduleName) {
4
+ const require = createRequire(import.meta.url);
5
+ return dirname(require.resolve(`${moduleName}/package.json`));
6
+ }
7
+ //# sourceMappingURL=getNodeModuleDir.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"getNodeModuleDir.js","sourceRoot":"","sources":["../src/getNodeModuleDir.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,QAAQ,CAAC;AACvC,OAAO,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AAE/B,MAAM,UAAU,gBAAgB,CAAC,UAAkB;IACjD,MAAM,OAAO,GAAG,aAAa,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;IAC/C,OAAO,OAAO,CAAC,OAAO,CAAC,OAAO,CAAC,GAAG,UAAU,eAAe,CAAC,CAAC,CAAC;AAChE,CAAC","sourcesContent":["import { createRequire } from 'module';\nimport { dirname } from 'path';\n\nexport function getNodeModuleDir(moduleName: string): string {\n const require = createRequire(import.meta.url);\n return dirname(require.resolve(`${moduleName}/package.json`));\n}\n"]}
package/lib/index.d.ts ADDED
@@ -0,0 +1,26 @@
1
+ /// <reference types="node" resolution-mode="require"/>
2
+ import type { Options } from '@storybook/types';
3
+ import { type Server } from 'http';
4
+ import { type Router } from '@ms-cloudpack/create-express-app';
5
+ export type ClosableServer = {
6
+ close: () => Promise<void>;
7
+ url: string;
8
+ };
9
+ export declare function bail(error?: Error): Promise<void>;
10
+ export declare const start: ({ options, startTime, router, server: devServer, }: {
11
+ options: Options;
12
+ startTime: [number, number];
13
+ router: Router;
14
+ server: Server;
15
+ }) => Promise<{
16
+ bail: typeof bail;
17
+ stats: {
18
+ toJson: () => null;
19
+ };
20
+ totalTime: [number, number];
21
+ }>;
22
+ export declare const build: (_arg: {
23
+ options: Options;
24
+ startTime: [number, number];
25
+ }) => void;
26
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,kBAAkB,CAAC;AAChD,OAAO,EAAE,KAAK,MAAM,EAAE,MAAM,MAAM,CAAC;AAqBnC,OAAO,EAAW,KAAK,MAAM,EAAE,MAAM,kCAAkC,CAAC;AAaxE,MAAM,MAAM,cAAc,GAAG;IAC3B,KAAK,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;IAC3B,GAAG,EAAE,MAAM,CAAC;CACb,CAAC;AAMF,wBAAsB,IAAI,CAAC,KAAK,CAAC,EAAE,KAAK,GAAG,OAAO,CAAC,IAAI,CAAC,CA0BvD;AAED,eAAO,MAAM,KAAK;aAMP,OAAO;eACL,CAAC,MAAM,EAAE,MAAM,CAAC;YACnB,MAAM;YACN,MAAM;;;;;;;EA6Mf,CAAC;AAEF,eAAO,MAAM,KAAK,SAAU;IAAE,OAAO,EAAE,OAAO,CAAC;IAAC,SAAS,EAAE,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;CAAE,KAAG,IAG/E,CAAC"}
package/lib/index.js ADDED
@@ -0,0 +1,213 @@
1
+ import {} from 'http';
2
+ import { createPartialApiContext, ensurePackageBundled } from '@ms-cloudpack/api-server/apis';
3
+ import { readConfig } from '@ms-cloudpack/config';
4
+ import path from 'path';
5
+ import { fileURLToPath } from 'url';
6
+ import { addExportsMapEntry, findResolveMapEntry, getExportsMap, getVersion, resolve, } from '@ms-cloudpack/package-utilities';
7
+ import { TaskReporter, bold, defaultLoggingConfig, verboseLoggingConfig, debugLoggingConfig, noLoggingConfig, } from '@ms-cloudpack/task-reporter';
8
+ import { createTelemetryClient } from '@ms-cloudpack/telemetry';
9
+ import { express } from '@ms-cloudpack/create-express-app';
10
+ import { startAppServer } from '@ms-cloudpack/app-server';
11
+ import { startBundleServer } from '@ms-cloudpack/bundle-server';
12
+ import { getNodeModuleDir } from './getNodeModuleDir.js';
13
+ import { generateIframeHtml } from './generateIFrameHtml.js';
14
+ import { getLocalCachePath } from '@ms-cloudpack/api-server';
15
+ import fsExtra from 'fs-extra';
16
+ import fsPromises from 'fs/promises';
17
+ import { listStories } from './listStories.js';
18
+ import { safeRelativePath } from '@ms-cloudpack/path-string-parsing';
19
+ import { readJson } from '@ms-cloudpack/json-utilities';
20
+ let appServer;
21
+ let apiServer;
22
+ let bundleServer;
23
+ export async function bail(error) {
24
+ if (error) {
25
+ console.error('Error:', error);
26
+ }
27
+ const servers = [
28
+ ['appServer', appServer],
29
+ ['apiServer', apiServer],
30
+ ['bundleServer', bundleServer],
31
+ ];
32
+ await Promise.all(servers.map(async ([name, server]) => {
33
+ if (!server || !server.url) {
34
+ console.info(`No ${name} to close.`);
35
+ return;
36
+ }
37
+ console.info(`Closing ${name}: ${server.url}`);
38
+ try {
39
+ await server?.close();
40
+ console.info(`Closed ${name}: ${server.url}`);
41
+ }
42
+ catch (err) {
43
+ console.warn('Error closing server:', err);
44
+ }
45
+ }));
46
+ }
47
+ export const start = async ({ options, startTime, router, server: devServer, }) => {
48
+ const previewResolvedDir = getNodeModuleDir('@storybook/preview');
49
+ const previewDirOrigin = path.join(previewResolvedDir, 'dist');
50
+ router.use('/sb-preview', express.static(previewDirOrigin, { immutable: true, maxAge: '5m' }));
51
+ // TODO: This might be useful later on.
52
+ // const env = await options.presets.apply<Record<string, string>>('env');
53
+ // eslint-disable-next-line no-restricted-properties -- this is the one place we need cwd (for a default)
54
+ const appPath = process.cwd();
55
+ const config = await readConfig(appPath);
56
+ // TODO: Move to won package.
57
+ // runPrerequisites(config, appPath);
58
+ // Make sure the package has a valid definition.
59
+ const definition = (await readJson(path.join(appPath, 'package.json')));
60
+ if (!definition.name || !definition.version) {
61
+ throw new Error(`The package.json at "${appPath}" did not have a name and/or version.`);
62
+ }
63
+ // This part should be almost identical to the cli start command.
64
+ const reporter = new TaskReporter({
65
+ productName: `Cloudpack`,
66
+ version: getVersion(import.meta.url),
67
+ description: () => `Running "${bold('storybook')}"`,
68
+ helpMessage: config.helpMessage,
69
+ // TODO: Get options and enable this.
70
+ plainTextMode: options.ci,
71
+ ...(options.loglevel === 'debug'
72
+ ? debugLoggingConfig
73
+ : options.loglevel === 'verbose'
74
+ ? verboseLoggingConfig
75
+ : options.quiet || options.loglevel === 'quiet'
76
+ ? noLoggingConfig
77
+ : defaultLoggingConfig),
78
+ });
79
+ const connectionString = options.disableTelemetry
80
+ ? undefined
81
+ : config.telemetry?.connectionString || process.env.CLOUDPACK_TELEMETRY_CONNECTION_STRING;
82
+ const logLevel = options.loglevel === 'verbose' ? 'VERBOSE' : options.loglevel === 'debug' ? 'DEBUG' : undefined;
83
+ if (options.loglevel !== 'debug') {
84
+ reporter.ignoreLogMessage('ApplicationInsights:');
85
+ }
86
+ const telemetryClient = await createTelemetryClient({
87
+ productVersion: getVersion(import.meta.url),
88
+ connectionString,
89
+ logLevel,
90
+ serviceNamespace: 'cloudpack',
91
+ serviceName: 'cli',
92
+ rootSpanName: 'CLI',
93
+ });
94
+ // Register performance observers to track performance metrics as events of CLI span.
95
+ // registerPerformanceObservers(telemetryClient);
96
+ const apiContext = await createPartialApiContext({
97
+ appPath,
98
+ config,
99
+ reporter,
100
+ telemetryClient,
101
+ items: ['bus', 'watcher', 'taskRunner', 'packages', 'session', 'packageImportPaths', 'packageHashes'],
102
+ overlayPath: await resolve('@ms-cloudpack/overlay', path.dirname(fileURLToPath(import.meta.url))),
103
+ });
104
+ const { packages, session, packageImportPaths } = apiContext;
105
+ // TODO: Get options and enable this.
106
+ // Increment the session version if caching is disabled.
107
+ // if (options.cache === false) {
108
+ // session.incrementSessionVersion();
109
+ // }
110
+ // Set shared telemetry attributes which will be sent with all telemetry events.
111
+ telemetryClient.setSharedSpanAttribute('sessionId', session.id);
112
+ // TODO: Get options and enable this.
113
+ // if (options.logResolveMap) {
114
+ // // Write the resolve map to disk.
115
+ // await writeJson(path.join(appPath, 'resolve-map.json'), session.resolveMap);
116
+ // }
117
+ // Storybook set up is mostly done here.
118
+ const generated = await generateIframeHtml(options, appPath, { packages, session });
119
+ await fsExtra.ensureDir(getLocalCachePath(appPath));
120
+ // TODO: Currently saving it to disk as the config only accepts a path.
121
+ const iFramePath = path.join(getLocalCachePath(appPath), 'iFrame.html');
122
+ await fsPromises.writeFile(iFramePath, generated, { encoding: 'utf-8' });
123
+ // iFrame script is required for storybook to work.
124
+ config.devServer ??= {};
125
+ config.devServer.routes ??= [];
126
+ config.devServer.routes.push({
127
+ match: '/iframe.html',
128
+ renderScript: iFramePath,
129
+ });
130
+ const stories = (await listStories(options)).map((story) => safeRelativePath(path.relative(appPath, story)));
131
+ const storyEntries = stories.reduce((acc, story) => {
132
+ acc[story] = story;
133
+ return acc;
134
+ }, {});
135
+ const additionalEntries = [
136
+ {
137
+ name: definition.name,
138
+ entries: {
139
+ ...storyEntries,
140
+ },
141
+ },
142
+ ];
143
+ for (const { name, entries } of additionalEntries) {
144
+ const packageEntry = findResolveMapEntry({ packageName: name, resolveMap: session.resolveMap });
145
+ if (!packageEntry) {
146
+ throw new Error(`Could not find package ${name} in the resolve map.`);
147
+ }
148
+ const exports = await getExportsMap({ packagePath: packageEntry.path }, { packages, config: session.config });
149
+ for (const [importPath, filePath] of Object.entries(entries)) {
150
+ await addExportsMapEntry({
151
+ exports,
152
+ packagePath: packageEntry.path,
153
+ importPath,
154
+ filePath,
155
+ }, { packages, config: session.config });
156
+ }
157
+ }
158
+ const { startApiServer } = await import('@ms-cloudpack/api-server');
159
+ // Start api server for tracking status and handling remote requests.
160
+ apiServer = await startApiServer(apiContext);
161
+ // Kick off bundling app package as soon as api server is ready.
162
+ void ensurePackageBundled({
163
+ input: { name: definition.name, version: definition.version },
164
+ ctx: apiContext,
165
+ });
166
+ // Kick off bundling some packages we know are required
167
+ const preBundlePackages = ['lodash'];
168
+ preBundlePackages.forEach((name) => {
169
+ const packageEntry = findResolveMapEntry({ packageName: name, resolveMap: session.resolveMap });
170
+ if (!packageEntry) {
171
+ throw new Error(`Could not find package ${name} in the resolve map.`);
172
+ }
173
+ void ensurePackageBundled({
174
+ input: { name, version: packageEntry.version },
175
+ ctx: apiContext,
176
+ });
177
+ });
178
+ // Then start bundle and app servers for hosting the app.
179
+ bundleServer = await startBundleServer({
180
+ context: {
181
+ ...apiContext,
182
+ apiServer,
183
+ disableCache: false, // TODO: Get options and enable this.
184
+ },
185
+ });
186
+ // Finally start the app server.
187
+ appServer = await startAppServer({
188
+ session,
189
+ definition,
190
+ bundleServer,
191
+ apiServer,
192
+ config,
193
+ reporter,
194
+ packages,
195
+ packageImportPaths,
196
+ packageHashes: apiContext.packageHashes,
197
+ middlewareMode: true,
198
+ server: devServer,
199
+ });
200
+ router.use(appServer.app);
201
+ // TODO: Figure out if it is possible to know when browser will open.
202
+ // performance.measure(PerfMeasurementOpenBrowser, PerfMarkerCliEntry);
203
+ return {
204
+ bail,
205
+ stats: { toJson: () => null },
206
+ totalTime: process.hrtime(startTime),
207
+ };
208
+ };
209
+ export const build = (_arg) => {
210
+ console.log('Cloudpack Storybook build is not implemented yet.');
211
+ process.exit(1);
212
+ };
213
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAe,MAAM,MAAM,CAAC;AACnC,OAAO,EAAE,uBAAuB,EAAE,oBAAoB,EAAE,MAAM,+BAA+B,CAAC;AAC9F,OAAO,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAC;AAClD,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAE,aAAa,EAAE,MAAM,KAAK,CAAC;AACpC,OAAO,EACL,kBAAkB,EAClB,mBAAmB,EACnB,aAAa,EACb,UAAU,EACV,OAAO,GACR,MAAM,iCAAiC,CAAC;AACzC,OAAO,EACL,YAAY,EACZ,IAAI,EACJ,oBAAoB,EACpB,oBAAoB,EACpB,kBAAkB,EAClB,eAAe,GAChB,MAAM,6BAA6B,CAAC;AACrC,OAAO,EAAE,qBAAqB,EAAE,MAAM,yBAAyB,CAAC;AAChE,OAAO,EAAE,OAAO,EAAe,MAAM,kCAAkC,CAAC;AACxE,OAAO,EAAE,cAAc,EAAkB,MAAM,0BAA0B,CAAC;AAC1E,OAAO,EAAE,iBAAiB,EAAqB,MAAM,6BAA6B,CAAC;AACnF,OAAO,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AACzD,OAAO,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;AAC7D,OAAO,EAAE,iBAAiB,EAAkB,MAAM,0BAA0B,CAAC;AAC7E,OAAO,OAAO,MAAM,UAAU,CAAC;AAC/B,OAAO,UAAU,MAAM,aAAa,CAAC;AACrC,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB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EAAE,CAAC,IAAI,EAAE;QAC7B,SAAS,EAAE,OAAO,CAAC,MAAM,CAAC,SAAS,CAAC;KACrC,CAAC;AACJ,CAAC,CAAC;AAEF,MAAM,CAAC,MAAM,KAAK,GAAG,CAAC,IAAuD,EAAQ,EAAE;IACrF,OAAO,CAAC,GAAG,CAAC,mDAAmD,CAAC,CAAC;IACjE,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AAClB,CAAC,CAAC","sourcesContent":["import type { Options } from '@storybook/types';\nimport { type Server } from 'http';\nimport { createPartialApiContext, ensurePackageBundled } from '@ms-cloudpack/api-server/apis';\nimport { readConfig } from '@ms-cloudpack/config';\nimport path from 'path';\nimport { fileURLToPath } from 'url';\nimport {\n addExportsMapEntry,\n findResolveMapEntry,\n getExportsMap,\n getVersion,\n resolve,\n} from '@ms-cloudpack/package-utilities';\nimport {\n TaskReporter,\n bold,\n defaultLoggingConfig,\n verboseLoggingConfig,\n debugLoggingConfig,\n noLoggingConfig,\n} from '@ms-cloudpack/task-reporter';\nimport { createTelemetryClient } from '@ms-cloudpack/telemetry';\nimport { express, type Router } from '@ms-cloudpack/create-express-app';\nimport { startAppServer, type AppServer } from '@ms-cloudpack/app-server';\nimport { startBundleServer, type BundleServer } from '@ms-cloudpack/bundle-server';\nimport { getNodeModuleDir } from './getNodeModuleDir.js';\nimport { generateIframeHtml } from './generateIFrameHtml.js';\nimport { getLocalCachePath, type ApiServer } from '@ms-cloudpack/api-server';\nimport fsExtra from 'fs-extra';\nimport fsPromises from 'fs/promises';\nimport { listStories } from './listStories.js';\nimport { safeRelativePath } from '@ms-cloudpack/path-string-parsing';\nimport { readJson } from '@ms-cloudpack/json-utilities';\nimport type { PackageJson } from '@ms-cloudpack/config-types';\n\nexport type ClosableServer = {\n close: () => Promise<void>;\n url: string;\n};\n\nlet appServer: AppServer;\nlet apiServer: ApiServer;\nlet bundleServer: BundleServer;\n\nexport async function bail(error?: Error): Promise<void> {\n if (error) {\n console.error('Error:', error);\n }\n\n const servers = [\n ['appServer', appServer] as const,\n ['apiServer', apiServer] as const,\n ['bundleServer', bundleServer] as const,\n ];\n\n await Promise.all(\n servers.map(async ([name, server]) => {\n if (!server || !server.url) {\n console.info(`No ${name} to close.`);\n return;\n }\n console.info(`Closing ${name}: ${server.url}`);\n try {\n await server?.close();\n console.info(`Closed ${name}: ${server.url}`);\n } catch (err) {\n console.warn('Error closing server:', err);\n }\n }),\n );\n}\n\nexport const start = async ({\n options,\n startTime,\n router,\n server: devServer,\n}: {\n options: Options;\n startTime: [number, number];\n router: Router;\n server: Server;\n}) => {\n const previewResolvedDir = getNodeModuleDir('@storybook/preview');\n const previewDirOrigin = path.join(previewResolvedDir, 'dist');\n\n router.use('/sb-preview', express.static(previewDirOrigin, { immutable: true, maxAge: '5m' }));\n\n // TODO: This might be useful later on.\n // const env = await options.presets.apply<Record<string, string>>('env');\n\n // eslint-disable-next-line no-restricted-properties -- this is the one place we need cwd (for a default)\n const appPath = process.cwd();\n\n const config = await readConfig(appPath);\n\n // TODO: Move to won package.\n // runPrerequisites(config, appPath);\n\n // Make sure the package has a valid definition.\n const definition = (await readJson(path.join(appPath, 'package.json'))) as PackageJson;\n\n if (!definition.name || !definition.version) {\n throw new Error(`The package.json at \"${appPath}\" did not have a name and/or version.`);\n }\n\n // This part should be almost identical to the cli start command.\n const reporter = new TaskReporter({\n productName: `Cloudpack`,\n version: getVersion(import.meta.url),\n description: () => `Running \"${bold('storybook')}\"`,\n helpMessage: config.helpMessage,\n // TODO: Get options and enable this.\n plainTextMode: options.ci,\n ...(options.loglevel === 'debug'\n ? debugLoggingConfig\n : options.loglevel === 'verbose'\n ? verboseLoggingConfig\n : options.quiet || options.loglevel === 'quiet'\n ? noLoggingConfig\n : defaultLoggingConfig),\n });\n\n const connectionString = options.disableTelemetry\n ? undefined\n : config.telemetry?.connectionString || process.env.CLOUDPACK_TELEMETRY_CONNECTION_STRING;\n\n const logLevel = options.loglevel === 'verbose' ? 'VERBOSE' : options.loglevel === 'debug' ? 'DEBUG' : undefined;\n if (options.loglevel !== 'debug') {\n reporter.ignoreLogMessage('ApplicationInsights:');\n }\n\n const telemetryClient = await createTelemetryClient({\n productVersion: getVersion(import.meta.url),\n connectionString,\n logLevel,\n serviceNamespace: 'cloudpack',\n serviceName: 'cli',\n rootSpanName: 'CLI',\n });\n\n // Register performance observers to track performance metrics as events of CLI span.\n // registerPerformanceObservers(telemetryClient);\n\n const apiContext = await createPartialApiContext({\n appPath,\n config,\n reporter,\n telemetryClient,\n items: ['bus', 'watcher', 'taskRunner', 'packages', 'session', 'packageImportPaths', 'packageHashes'],\n overlayPath: await resolve('@ms-cloudpack/overlay', path.dirname(fileURLToPath(import.meta.url))),\n });\n\n const { packages, session, packageImportPaths } = apiContext;\n\n // TODO: Get options and enable this.\n // Increment the session version if caching is disabled.\n // if (options.cache === false) {\n // session.incrementSessionVersion();\n // }\n\n // Set shared telemetry attributes which will be sent with all telemetry events.\n telemetryClient.setSharedSpanAttribute('sessionId', session.id);\n\n // TODO: Get options and enable this.\n // if (options.logResolveMap) {\n // // Write the resolve map to disk.\n // await writeJson(path.join(appPath, 'resolve-map.json'), session.resolveMap);\n // }\n\n // Storybook set up is mostly done here.\n const generated = await generateIframeHtml(options, appPath, { packages, session });\n await fsExtra.ensureDir(getLocalCachePath(appPath));\n\n // TODO: Currently saving it to disk as the config only accepts a path.\n const iFramePath = path.join(getLocalCachePath(appPath), 'iFrame.html');\n await fsPromises.writeFile(iFramePath, generated, { encoding: 'utf-8' });\n\n // iFrame script is required for storybook to work.\n config.devServer ??= {};\n config.devServer.routes ??= [];\n config.devServer.routes.push({\n match: '/iframe.html',\n renderScript: iFramePath,\n });\n\n const stories = (await listStories(options)).map((story) => safeRelativePath(path.relative(appPath, story)));\n const storyEntries = stories.reduce(\n (acc, story) => {\n acc[story] = story;\n return acc;\n },\n {} as Record<string, string>,\n );\n\n const additionalEntries = [\n {\n name: definition.name,\n entries: {\n ...storyEntries,\n },\n },\n ];\n\n for (const { name, entries } of additionalEntries) {\n const packageEntry = findResolveMapEntry({ packageName: name, resolveMap: session.resolveMap });\n\n if (!packageEntry) {\n throw new Error(`Could not find package ${name} in the resolve map.`);\n }\n\n const exports = await getExportsMap({ packagePath: packageEntry.path }, { packages, config: session.config });\n for (const [importPath, filePath] of Object.entries(entries)) {\n await addExportsMapEntry(\n {\n exports,\n packagePath: packageEntry.path,\n importPath,\n filePath,\n },\n { packages, config: session.config },\n );\n }\n }\n\n const { startApiServer } = await import('@ms-cloudpack/api-server');\n\n // Start api server for tracking status and handling remote requests.\n apiServer = await startApiServer(apiContext);\n\n // Kick off bundling app package as soon as api server is ready.\n void ensurePackageBundled({\n input: { name: definition.name, version: definition.version },\n ctx: apiContext,\n });\n\n // Kick off bundling some packages we know are required\n const preBundlePackages = ['lodash'];\n\n preBundlePackages.forEach((name) => {\n const packageEntry = findResolveMapEntry({ packageName: name, resolveMap: session.resolveMap });\n\n if (!packageEntry) {\n throw new Error(`Could not find package ${name} in the resolve map.`);\n }\n\n void ensurePackageBundled({\n input: { name, version: packageEntry.version },\n ctx: apiContext,\n });\n });\n\n // Then start bundle and app servers for hosting the app.\n bundleServer = await startBundleServer({\n context: {\n ...apiContext,\n apiServer,\n disableCache: false, // TODO: Get options and enable this.\n },\n });\n\n // Finally start the app server.\n appServer = await startAppServer({\n session,\n definition,\n bundleServer,\n apiServer,\n config,\n reporter,\n packages,\n packageImportPaths,\n packageHashes: apiContext.packageHashes,\n middlewareMode: true,\n server: devServer,\n });\n\n router.use(appServer.app);\n\n // TODO: Figure out if it is possible to know when browser will open.\n // performance.measure(PerfMeasurementOpenBrowser, PerfMarkerCliEntry);\n\n return {\n bail,\n stats: { toJson: () => null },\n totalTime: process.hrtime(startTime),\n };\n};\n\nexport const build = (_arg: { options: Options; startTime: [number, number] }): void => {\n console.log('Cloudpack Storybook build is not implemented yet.');\n process.exit(1);\n};\n"]}
@@ -0,0 +1,3 @@
1
+ import type { Options } from '@storybook/types';
2
+ export declare function listStories(options: Options): Promise<string[]>;
3
+ //# sourceMappingURL=listStories.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"listStories.d.ts","sourceRoot":"","sources":["../src/listStories.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,kBAAkB,CAAC;AAEhD,wBAAsB,WAAW,CAAC,OAAO,EAAE,OAAO,qBAuBjD"}
@@ -0,0 +1,23 @@
1
+ // based on https://github.com/storybookjs/storybook/blob/v7.6.5/code/lib/builder-vite/src/list-stories.ts
2
+ import path from 'path';
3
+ import glob from 'fast-glob';
4
+ import { normalizeStories, commonGlobOptions } from '@storybook/core-common';
5
+ import { slash } from '@ms-cloudpack/path-string-parsing';
6
+ export async function listStories(options) {
7
+ return ((await Promise.all(normalizeStories(await options.presets.apply('stories', [], options), {
8
+ configDir: options.configDir,
9
+ workingDir: options.configDir,
10
+ }).map(({ directory, files }) => {
11
+ const pattern = path.join(directory, files);
12
+ const absolutePattern = path.isAbsolute(pattern) ? pattern : path.join(options.configDir, pattern);
13
+ return glob(slash(absolutePattern), {
14
+ ...commonGlobOptions(absolutePattern),
15
+ followSymbolicLinks: true,
16
+ });
17
+ })))
18
+ .reduce((carry, stories) => carry.concat(stories.map(slash)), [])
19
+ // Sort stories to prevent a non-deterministic build. The result of Glob is not sorted an may differ
20
+ // for each invocation. This results in a different bundle file hashes from one build to the next.
21
+ .sort());
22
+ }
23
+ //# sourceMappingURL=listStories.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"listStories.js","sourceRoot":"","sources":["../src/listStories.ts"],"names":[],"mappings":"AAAA,0GAA0G;AAE1G,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAC7E,OAAO,EAAE,KAAK,EAAE,MAAM,mCAAmC,CAAC;AAG1D,MAAM,CAAC,KAAK,UAAU,WAAW,CAAC,OAAgB;IAChD,OAAO,CACL,CACE,MAAM,OAAO,CAAC,GAAG,CACf,gBAAgB,CAAC,MAAM,OAAO,CAAC,OAAO,CAAC,KAAK,CAAC,SAAS,EAAE,EAAE,EAAE,OAAO,CAAC,EAAE;QACpE,SAAS,EAAE,OAAO,CAAC,SAAS;QAC5B,UAAU,EAAE,OAAO,CAAC,SAAS;KAC9B,CAAC,CAAC,GAAG,CAAC,CAAC,EAAE,SAAS,EAAE,KAAK,EAAE,EAAE,EAAE;QAC9B,MAAM,OAAO,GAAG,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,KAAK,CAAC,CAAC;QAC5C,MAAM,eAAe,GAAG,IAAI,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,SAAS,EAAE,OAAO,CAAC,CAAC;QAEnG,OAAO,IAAI,CAAC,KAAK,CAAC,eAAe,CAAC,EAAE;YAClC,GAAG,iBAAiB,CAAC,eAAe,CAAC;YACrC,mBAAmB,EAAE,IAAI;SAC1B,CAAC,CAAC;IACL,CAAC,CAAC,CACH,CACF;SACE,MAAM,CAAC,CAAC,KAAK,EAAE,OAAO,EAAE,EAAE,CAAC,KAAK,CAAC,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC;QACjE,oGAAoG;QACpG,kGAAkG;SACjG,IAAI,EAAE,CACV,CAAC;AACJ,CAAC","sourcesContent":["// based on https://github.com/storybookjs/storybook/blob/v7.6.5/code/lib/builder-vite/src/list-stories.ts\n\nimport path from 'path';\nimport glob from 'fast-glob';\nimport { normalizeStories, commonGlobOptions } from '@storybook/core-common';\nimport { slash } from '@ms-cloudpack/path-string-parsing';\nimport type { Options } from '@storybook/types';\n\nexport async function listStories(options: Options) {\n return (\n (\n await Promise.all(\n normalizeStories(await options.presets.apply('stories', [], options), {\n configDir: options.configDir,\n workingDir: options.configDir,\n }).map(({ directory, files }) => {\n const pattern = path.join(directory, files);\n const absolutePattern = path.isAbsolute(pattern) ? pattern : path.join(options.configDir, pattern);\n\n return glob(slash(absolutePattern), {\n ...commonGlobOptions(absolutePattern),\n followSymbolicLinks: true,\n });\n }),\n )\n )\n .reduce((carry, stories) => carry.concat(stories.map(slash)), [])\n // Sort stories to prevent a non-deterministic build. The result of Glob is not sorted an may differ\n // for each invocation. This results in a different bundle file hashes from one build to the next.\n .sort()\n );\n}\n"]}
@@ -0,0 +1,14 @@
1
+ import type { PreviewAnnotation } from '@storybook/types';
2
+ import type { PackageDefinitionsCache } from '@ms-cloudpack/bundler-types';
3
+ /**
4
+ * Preview annotations can take several forms, and cloudpack needs them to be
5
+ * a bit more restrained.
6
+ *
7
+ * For node_modules, we want bare imports (so cloudpack can process them),
8
+ * and for files in the user's source, we want URLs absolute relative to project root.
9
+ *
10
+ */
11
+ export declare function processPreviewAnnotation(path: PreviewAnnotation | undefined, appPath: string, context: {
12
+ packages: PackageDefinitionsCache;
13
+ }): Promise<string>;
14
+ //# sourceMappingURL=processPreviewAnnotation.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"processPreviewAnnotation.d.ts","sourceRoot":"","sources":["../../src/utils/processPreviewAnnotation.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAK1D,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,6BAA6B,CAAC;AAE3E;;;;;;;GAOG;AACH,wBAAsB,wBAAwB,CAC5C,IAAI,EAAE,iBAAiB,GAAG,SAAS,EACnC,OAAO,EAAE,MAAM,EACf,OAAO,EAAE;IAAE,QAAQ,EAAE,uBAAuB,CAAA;CAAE,mBA6D/C"}
@@ -0,0 +1,69 @@
1
+ // based on https://github.com/storybookjs/storybook/blob/v7.6.5/code/builders/builder-vite/src/utils/process-preview-annotation.ts
2
+ import { resolve, isAbsolute, relative } from 'path';
3
+ import { slash } from '@ms-cloudpack/path-string-parsing';
4
+ import { stripAbsNodeModulesPath } from '@storybook/core-common';
5
+ import { findPackageRoot } from '@ms-cloudpack/path-utilities';
6
+ /**
7
+ * Preview annotations can take several forms, and cloudpack needs them to be
8
+ * a bit more restrained.
9
+ *
10
+ * For node_modules, we want bare imports (so cloudpack can process them),
11
+ * and for files in the user's source, we want URLs absolute relative to project root.
12
+ *
13
+ */
14
+ export async function processPreviewAnnotation(path, appPath, context) {
15
+ const { packages } = context;
16
+ // If entry is an object, take the first, which is the
17
+ // bare (non-absolute) specifier.
18
+ // This is so that webpack can use an absolute path, and
19
+ // continue supporting super-addons in pnp/pnpm without
20
+ // requiring them to re-export their sub-addons as we do
21
+ // in addon-essentials.
22
+ if (typeof path === 'object') {
23
+ return path.bare;
24
+ }
25
+ // This should not occur, since we use `.filter(Boolean)` prior to
26
+ // calling this function, but this makes typescript happy
27
+ if (!path) {
28
+ throw new Error('Could not determine path for previewAnnotation');
29
+ }
30
+ // For addon dependencies that use require.resolve(), we need to convert to a bare path
31
+ // so that cloudpack will process it as a dependency (cjs -> esm, etc).
32
+ // TODO: Evaluate if searching for node_modules in a yarn pnp environment is correct
33
+ if (path.includes('node_modules')) {
34
+ return stripAbsNodeModulesPath(path);
35
+ }
36
+ // resolve absolute paths relative to project root
37
+ const relativePath = isAbsolute(path) ? slash(relative(appPath, path)) : path;
38
+ // resolve relative paths into absolute urls
39
+ // note: this only works if cloudpack's appPath === cwd.
40
+ // Add package root to relative paths.
41
+ if (relativePath.startsWith('./')) {
42
+ const definition = await packages.get(appPath);
43
+ if (!definition) {
44
+ throw new Error(`Could not find package definition for ${appPath}`);
45
+ }
46
+ return slash(`${definition.name}/${relativePath.replace(/^\.\//, '')}`);
47
+ }
48
+ // If something is outside of root, convert to absolute. Uncommon?
49
+ if (relativePath.startsWith('../')) {
50
+ // Find package and add to root.
51
+ const packagePath = findPackageRoot(resolve(appPath, relativePath));
52
+ if (!packagePath) {
53
+ throw new Error(`Could not find package root for ${relativePath}`);
54
+ }
55
+ const definition = await packages.get(packagePath);
56
+ if (!definition) {
57
+ throw new Error(`Could not find package definition for ${relativePath}`);
58
+ }
59
+ return slash(`${definition.name}/${relative(packagePath, resolve(appPath, relativePath))}`);
60
+ }
61
+ // At this point, it must be relative to the root but not start with a ./ or ../
62
+ // Add package root to relative paths.
63
+ const definition = await packages.get(appPath);
64
+ if (!definition) {
65
+ throw new Error(`Could not find package definition for ${appPath}`);
66
+ }
67
+ return slash(`${definition.name}/${relativePath}`);
68
+ }
69
+ //# sourceMappingURL=processPreviewAnnotation.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"processPreviewAnnotation.js","sourceRoot":"","sources":["../../src/utils/processPreviewAnnotation.ts"],"names":[],"mappings":"AAAA,mIAAmI;AAGnI,OAAO,EAAE,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,MAAM,CAAC;AACrD,OAAO,EAAE,KAAK,EAAE,MAAM,mCAAmC,CAAC;AAC1D,OAAO,EAAE,uBAAuB,EAAE,MAAM,wBAAwB,CAAC;AACjE,OAAO,EAAE,eAAe,EAAE,MAAM,8BAA8B,CAAC;AAG/D;;;;;;;GAOG;AACH,MAAM,CAAC,KAAK,UAAU,wBAAwB,CAC5C,IAAmC,EACnC,OAAe,EACf,OAA8C;IAE9C,MAAM,EAAE,QAAQ,EAAE,GAAG,OAAO,CAAC;IAC7B,sDAAsD;IACtD,iCAAiC;IACjC,wDAAwD;IACxD,uDAAuD;IACvD,wDAAwD;IACxD,uBAAuB;IACvB,IAAI,OAAO,IAAI,KAAK,QAAQ,EAAE,CAAC;QAC7B,OAAO,IAAI,CAAC,IAAI,CAAC;IACnB,CAAC;IAED,kEAAkE;IAClE,yDAAyD;IACzD,IAAI,CAAC,IAAI,EAAE,CAAC;QACV,MAAM,IAAI,KAAK,CAAC,gDAAgD,CAAC,CAAC;IACpE,CAAC;IAED,uFAAuF;IACvF,uEAAuE;IACvE,oFAAoF;IACpF,IA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AAW,EAAE,OAAO,CAAC,OAAO,EAAE,YAAY,CAAC,CAAC,EAAE,CAAC,CAAC;IAC9F,CAAC;IAED,gFAAgF;IAChF,sCAAsC;IACtC,MAAM,UAAU,GAAG,MAAM,QAAQ,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;IAC/C,IAAI,CAAC,UAAU,EAAE,CAAC;QAChB,MAAM,IAAI,KAAK,CAAC,yCAAyC,OAAO,EAAE,CAAC,CAAC;IACtE,CAAC;IACD,OAAO,KAAK,CAAC,GAAG,UAAU,CAAC,IAAI,IAAI,YAAY,EAAE,CAAC,CAAC;AACrD,CAAC","sourcesContent":["// based on https://github.com/storybookjs/storybook/blob/v7.6.5/code/builders/builder-vite/src/utils/process-preview-annotation.ts\n\nimport type { PreviewAnnotation } from '@storybook/types';\nimport { resolve, isAbsolute, relative } from 'path';\nimport { slash } from '@ms-cloudpack/path-string-parsing';\nimport { stripAbsNodeModulesPath } from '@storybook/core-common';\nimport { findPackageRoot } from '@ms-cloudpack/path-utilities';\nimport type { PackageDefinitionsCache } from '@ms-cloudpack/bundler-types';\n\n/**\n * Preview annotations can take several forms, and cloudpack needs them to be\n * a bit more restrained.\n *\n * For node_modules, we want bare imports (so cloudpack can process them),\n * and for files in the user's source, we want URLs absolute relative to project root.\n *\n */\nexport async function processPreviewAnnotation(\n path: PreviewAnnotation | undefined,\n appPath: string,\n context: { packages: PackageDefinitionsCache },\n) {\n const { packages } = context;\n // If entry is an object, take the first, which is the\n // bare (non-absolute) specifier.\n // This is so that webpack can use an absolute path, and\n // continue supporting super-addons in pnp/pnpm without\n // requiring them to re-export their sub-addons as we do\n // in addon-essentials.\n if (typeof path === 'object') {\n return path.bare;\n }\n\n // This should not occur, since we use `.filter(Boolean)` prior to\n // calling this function, but this makes typescript happy\n if (!path) {\n throw new Error('Could not determine path for previewAnnotation');\n }\n\n // For addon dependencies that use require.resolve(), we need to convert to a bare path\n // so that cloudpack will process it as a dependency (cjs -> esm, etc).\n // TODO: Evaluate if searching for node_modules in a yarn pnp environment is correct\n if (path.includes('node_modules')) {\n return stripAbsNodeModulesPath(path);\n }\n\n // resolve absolute paths relative to project root\n const relativePath = isAbsolute(path) ? slash(relative(appPath, path)) : path;\n\n // resolve relative paths into absolute urls\n // note: this only works if cloudpack's appPath === cwd.\n // Add package root to relative paths.\n if (relativePath.startsWith('./')) {\n const definition = await packages.get(appPath);\n if (!definition) {\n throw new Error(`Could not find package definition for ${appPath}`);\n }\n return slash(`${definition.name}/${relativePath.replace(/^\\.\\//, '')}`);\n }\n\n // If something is outside of root, convert to absolute. Uncommon?\n if (relativePath.startsWith('../')) {\n // Find package and add to root.\n const packagePath = findPackageRoot(resolve(appPath, relativePath));\n if (!packagePath) {\n throw new Error(`Could not find package root for ${relativePath}`);\n }\n const definition = await packages.get(packagePath);\n if (!definition) {\n throw new Error(`Could not find package definition for ${relativePath}`);\n }\n return slash(`${definition.name}/${relative(packagePath, resolve(appPath, relativePath))}`);\n }\n\n // At this point, it must be relative to the root but not start with a ./ or ../\n // Add package root to relative paths.\n const definition = await packages.get(appPath);\n if (!definition) {\n throw new Error(`Could not find package definition for ${appPath}`);\n }\n return slash(`${definition.name}/${relativePath}`);\n}\n"]}
package/package.json ADDED
@@ -0,0 +1,57 @@
1
+ {
2
+ "name": "@ms-cloudpack/storybook-builder",
3
+ "version": "0.1.1",
4
+ "description": "A tool for building storybook bundles for the cloudpack ecosystem.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "types": "./lib/index.d.ts",
8
+ "sideEffects": false,
9
+ "exports": {
10
+ ".": {
11
+ "types": "./lib/index.d.ts",
12
+ "import": "./lib/index.js",
13
+ "default": "./lib/index.js"
14
+ },
15
+ "./input/iframe.html": "./static/iframeTemplate.html",
16
+ "./package.json": "./package.json"
17
+ },
18
+ "scripts": {
19
+ "build:watch": "cloudpack-scripts build-watch",
20
+ "build": "cloudpack-scripts build",
21
+ "lint:update": "cloudpack-scripts lint-update",
22
+ "lint": "cloudpack-scripts lint"
23
+ },
24
+ "dependencies": {
25
+ "@ms-cloudpack/api-server": "^0.30.3",
26
+ "@ms-cloudpack/app-server": "^0.1.21",
27
+ "@ms-cloudpack/bundle-server": "^0.2.18",
28
+ "@ms-cloudpack/config": "^0.17.23",
29
+ "@ms-cloudpack/config-types": "^0.4.3",
30
+ "@ms-cloudpack/create-express-app": "^1.4.0",
31
+ "@ms-cloudpack/json-utilities": "^0.1.3",
32
+ "@ms-cloudpack/package-utilities": "^5.8.3",
33
+ "@ms-cloudpack/path-string-parsing": "^1.1.3",
34
+ "@ms-cloudpack/task-reporter": "^0.11.1",
35
+ "@ms-cloudpack/telemetry": "^0.4.6",
36
+ "@ms-cloudpack/path-utilities": "^2.5.0",
37
+ "@storybook/core-common": "7.6.5",
38
+ "@storybook/node-logger": "7.6.5",
39
+ "fast-glob": "^3.2.12",
40
+ "fs-extra": "^11.2.0",
41
+ "@storybook/preview": "7.6.5"
42
+ },
43
+ "devDependencies": {
44
+ "@ms-cloudpack/bundler-types": "*",
45
+ "@storybook/types": "7.6.5",
46
+ "@ms-cloudpack/eslint-plugin-internal": "*",
47
+ "@ms-cloudpack/scripts": "*"
48
+ },
49
+ "files": [
50
+ "lib/**/!(*.test.*)"
51
+ ],
52
+ "beachball": {
53
+ "disallowedChangeTypes": [
54
+ "prerelease"
55
+ ]
56
+ }
57
+ }