@ms-cloudpack/storybook-builder 0.5.4 → 0.5.6

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.
@@ -0,0 +1,8 @@
1
+ import { type Context } from '@ms-cloudpack/api-server';
2
+ import type { Options } from '@storybook/types';
3
+ /** Create the Cloudpack context. */
4
+ export declare function createApiContext(options: {
5
+ appPath: string;
6
+ storybookOptions: Options;
7
+ }): Promise<Context>;
8
+ //# sourceMappingURL=createApiContext.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"createApiContext.d.ts","sourceRoot":"","sources":["../src/createApiContext.ts"],"names":[],"mappings":"AAAA,OAAO,EAA2B,KAAK,OAAO,EAAE,MAAM,0BAA0B,CAAC;AAYjF,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,kBAAkB,CAAC;AAMhD,oCAAoC;AACpC,wBAAsB,gBAAgB,CAAC,OAAO,EAAE;IAAE,OAAO,EAAE,MAAM,CAAC;IAAC,gBAAgB,EAAE,OAAO,CAAA;CAAE,GAAG,OAAO,CAAC,OAAO,CAAC,CAyEhH"}
@@ -0,0 +1,71 @@
1
+ import { createPartialApiContext } from '@ms-cloudpack/api-server';
2
+ import { readConfig } from '@ms-cloudpack/config';
3
+ import { getDisplayVersion, getVersion, isExternalPackage, resolve } from '@ms-cloudpack/package-utilities';
4
+ import { bold, debugLoggingConfig, defaultLoggingConfig, noLoggingConfig, TaskReporter, verboseLoggingConfig, } from '@ms-cloudpack/task-reporter';
5
+ import { createTelemetryClient } from '@ms-cloudpack/telemetry';
6
+ import path from 'path';
7
+ import { fileURLToPath } from 'url';
8
+ const currentDir = path.dirname(fileURLToPath(import.meta.url));
9
+ /** Create the Cloudpack context. */
10
+ export async function createApiContext(options) {
11
+ const { appPath, storybookOptions } = options;
12
+ const { loglevel } = storybookOptions;
13
+ const config = await readConfig(appPath);
14
+ // TODO: Move to won package.
15
+ // runPrerequisites(config, appPath);
16
+ // This part should be almost identical to the cli start command.
17
+ const reporter = new TaskReporter({
18
+ productName: 'Storybook + Cloudpack',
19
+ version: getDisplayVersion(import.meta.url),
20
+ description: () => `Running "${bold('storybook')}"`,
21
+ helpMessage: config.helpMessage,
22
+ // TODO: Get options and enable this.
23
+ plainTextMode: storybookOptions.ci,
24
+ ...(loglevel === 'debug'
25
+ ? debugLoggingConfig
26
+ : loglevel === 'verbose'
27
+ ? verboseLoggingConfig
28
+ : storybookOptions.quiet || loglevel === 'quiet'
29
+ ? noLoggingConfig
30
+ : defaultLoggingConfig),
31
+ });
32
+ const connectionString = storybookOptions.disableTelemetry
33
+ ? undefined
34
+ : config.telemetry?.connectionString || process.env.CLOUDPACK_TELEMETRY_CONNECTION_STRING;
35
+ if (loglevel !== 'debug') {
36
+ reporter.ignoreLogMessage('ApplicationInsights:');
37
+ }
38
+ const telemetryClient = await createTelemetryClient({
39
+ productVersion: getVersion(import.meta.url),
40
+ connectionString,
41
+ logLevel: loglevel === 'verbose' ? 'VERBOSE' : loglevel === 'debug' ? 'DEBUG' : undefined,
42
+ serviceNamespace: 'cloudpack',
43
+ serviceName: 'storybook',
44
+ rootSpanName: 'storybook',
45
+ });
46
+ // Register performance observers to track performance metrics as events of CLI span.
47
+ // registerPerformanceObservers(telemetryClient);
48
+ let overlayPath = await resolve('@ms-cloudpack/overlay', currentDir);
49
+ // If overlay is an internal package, resolve the overlay from the current package's linked node modules
50
+ // to "externalize" it, so that we always use the bundled version of the overlay instead of the source.
51
+ if (overlayPath && !isExternalPackage(overlayPath)) {
52
+ overlayPath = path.resolve(currentDir, '../node_modules/@ms-cloudpack/overlay');
53
+ }
54
+ const apiContext = await createPartialApiContext({
55
+ appPath,
56
+ config,
57
+ reporter,
58
+ telemetryClient,
59
+ items: ['bus', 'watcher', 'taskRunner', 'packages', 'session', 'packageImportPaths', 'packageHashes'],
60
+ overlayPath,
61
+ });
62
+ // TODO: Get options and enable this.
63
+ // Increment the session version if caching is disabled.
64
+ // if (options.cache === false) {
65
+ // session.incrementSessionVersion();
66
+ // }
67
+ // Set shared telemetry attributes which will be sent with all telemetry events.
68
+ apiContext.telemetryClient.setSharedSpanAttribute('sessionId', apiContext.session.id);
69
+ return apiContext;
70
+ }
71
+ //# sourceMappingURL=createApiContext.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"createApiContext.js","sourceRoot":"","sources":["../src/createApiContext.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAgB,MAAM,0BAA0B,CAAC;AACjF,OAAO,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAC;AAClD,OAAO,EAAE,iBAAiB,EAAE,UAAU,EAAE,iBAAiB,EAAE,OAAO,EAAE,MAAM,iCAAiC,CAAC;AAC5G,OAAO,EACL,IAAI,EACJ,kBAAkB,EAClB,oBAAoB,EACpB,eAAe,EACf,YAAY,EACZ,oBAAoB,GACrB,MAAM,6BAA6B,CAAC;AACrC,OAAO,EAAE,qBAAqB,EAAE,MAAM,yBAAyB,CAAC;AAEhE,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAE,aAAa,EAAE,MAAM,KAAK,CAAC;AAEpC,MAAM,UAAU,GAAG,IAAI,CAAC,OAAO,CAAC,aAAa,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC;AAEhE,oCAAoC;AACpC,MAAM,CAAC,KAAK,UAAU,gBAAgB,CAAC,OAAuD;IAC5F,MAAM,EAAE,OAAO,EAAE,gBAAgB,EAAE,GAAG,OAAO,CAAC;IAC9C,MAAM,EAAE,QAAQ,EAAE,GAAG,gBAAgB,CAAC;IAEtC,MAAM,MAAM,GAAG,MAAM,UAAU,CAAC,OAAO,CAAC,CAAC;IAEzC,6BAA6B;IAC7B,qCAAqC;IAErC,iEAAiE;IACjE,MAAM,QAAQ,GAAG,IAAI,YAAY,CAAC;QAChC,WAAW,EAAE,uBAAuB;QACpC,OAAO,EAAE,iBAAiB,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG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AI,WAAW,IAAI,CAAC,iBAAiB,CAAC,WAAW,CAAC,EAAE,CAAC;QACnD,WAAW,GAAG,IAAI,CAAC,OAAO,CAAC,UAAU,EAAE,uCAAuC,CAAC,CAAC;IAClF,CAAC;IAED,MAAM,UAAU,GAAG,MAAM,uBAAuB,CAAC;QAC/C,OAAO;QACP,MAAM;QACN,QAAQ;QACR,eAAe;QACf,KAAK,EAAE,CAAC,KAAK,EAAE,SAAS,EAAE,YAAY,EAAE,UAAU,EAAE,SAAS,EAAE,oBAAoB,EAAE,eAAe,CAAC;QACrG,WAAW;KACZ,CAAC,CAAC;IAEH,qCAAqC;IACrC,wDAAwD;IACxD,iCAAiC;IACjC,uCAAuC;IACvC,IAAI;IAEJ,gFAAgF;IAChF,UAAU,CAAC,eAAe,CAAC,sBAAsB,CAAC,WAAW,EAAE,UAAU,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC;IAEtF,OAAO,UAAU,CAAC;AACpB,CAAC","sourcesContent":["import { createPartialApiContext, type Context } from '@ms-cloudpack/api-server';\nimport { readConfig } from '@ms-cloudpack/config';\nimport { getDisplayVersion, getVersion, isExternalPackage, resolve } from '@ms-cloudpack/package-utilities';\nimport {\n bold,\n debugLoggingConfig,\n defaultLoggingConfig,\n noLoggingConfig,\n TaskReporter,\n verboseLoggingConfig,\n} from '@ms-cloudpack/task-reporter';\nimport { createTelemetryClient } from '@ms-cloudpack/telemetry';\nimport type { Options } from '@storybook/types';\nimport path from 'path';\nimport { fileURLToPath } from 'url';\n\nconst currentDir = path.dirname(fileURLToPath(import.meta.url));\n\n/** Create the Cloudpack context. */\nexport async function createApiContext(options: { appPath: string; storybookOptions: Options }): Promise<Context> {\n const { appPath, storybookOptions } = options;\n const { loglevel } = storybookOptions;\n\n const config = await readConfig(appPath);\n\n // TODO: Move to won package.\n // runPrerequisites(config, appPath);\n\n // This part should be almost identical to the cli start command.\n const reporter = new TaskReporter({\n productName: 'Storybook + Cloudpack',\n version: getDisplayVersion(import.meta.url),\n description: () => `Running \"${bold('storybook')}\"`,\n helpMessage: config.helpMessage,\n // TODO: Get options and enable this.\n plainTextMode: storybookOptions.ci,\n ...(loglevel === 'debug'\n ? debugLoggingConfig\n : loglevel === 'verbose'\n ? verboseLoggingConfig\n : storybookOptions.quiet || loglevel === 'quiet'\n ? noLoggingConfig\n : defaultLoggingConfig),\n });\n\n const connectionString = storybookOptions.disableTelemetry\n ? undefined\n : config.telemetry?.connectionString || process.env.CLOUDPACK_TELEMETRY_CONNECTION_STRING;\n\n if (loglevel !== 'debug') {\n reporter.ignoreLogMessage('ApplicationInsights:');\n }\n\n const telemetryClient = await createTelemetryClient({\n productVersion: getVersion(import.meta.url),\n connectionString,\n logLevel: loglevel === 'verbose' ? 'VERBOSE' : loglevel === 'debug' ? 'DEBUG' : undefined,\n serviceNamespace: 'cloudpack',\n serviceName: 'storybook',\n rootSpanName: 'storybook',\n });\n\n // Register performance observers to track performance metrics as events of CLI span.\n // registerPerformanceObservers(telemetryClient);\n\n let overlayPath = await resolve('@ms-cloudpack/overlay', currentDir);\n\n // If overlay is an internal package, resolve the overlay from the current package's linked node modules\n // to \"externalize\" it, so that we always use the bundled version of the overlay instead of the source.\n if (overlayPath && !isExternalPackage(overlayPath)) {\n overlayPath = path.resolve(currentDir, '../node_modules/@ms-cloudpack/overlay');\n }\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,\n });\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 apiContext.telemetryClient.setSharedSpanAttribute('sessionId', apiContext.session.id);\n\n return apiContext;\n}\n"]}
@@ -1,9 +1,14 @@
1
- import type { Options } from '@storybook/types';
2
- import type { PackageDefinitionsCache } from '@ms-cloudpack/common-types';
3
- import type { Session } from '@ms-cloudpack/api-server';
1
+ import type { NormalizedStoriesSpecifier, Options } from '@storybook/types';
2
+ import type { PartialContext } from '@ms-cloudpack/api-server';
3
+ import type { PackageJson } from '@ms-cloudpack/common-types';
4
4
  export type PreviewHtml = string | undefined;
5
- export declare function generateIframeHtml(options: Options, context: {
6
- packages: PackageDefinitionsCache;
7
- session: Session;
8
- }): Promise<string>;
5
+ export declare function generateIframeHtml(options: {
6
+ storybookOptions: Options;
7
+ appDefinition: PackageJson;
8
+ storySpecifiers: NormalizedStoriesSpecifier[];
9
+ /** Actual paths to all story files, relative to `appPath` with leading `./` and forward slashes. */
10
+ resolvedStories: string[];
11
+ /** Absolute path to storybook preview or config file for the app */
12
+ previewOrConfigFile: string | undefined;
13
+ }, context: PartialContext<'packages', 'config'>): Promise<string>;
9
14
  //# sourceMappingURL=generateIFrameHtml.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"generateIFrameHtml.d.ts","sourceRoot":"","sources":["../src/generateIFrameHtml.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAA2B,OAAO,EAAE,MAAM,kBAAkB,CAAC;AAKzE,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,4BAA4B,CAAC;AAC1E,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;IAAE,QAAQ,EAAE,uBAAuB,CAAC;IAAC,OAAO,EAAE,OAAO,CAAA;CAAE,GAC/D,OAAO,CAAC,MAAM,CAAC,CAmDjB"}
1
+ {"version":3,"file":"generateIFrameHtml.d.ts","sourceRoot":"","sources":["../src/generateIFrameHtml.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAA2B,0BAA0B,EAAE,OAAO,EAAE,MAAM,kBAAkB,CAAC;AAKrG,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,0BAA0B,CAAC;AAC/D,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,4BAA4B,CAAC;AAI9D,MAAM,MAAM,WAAW,GAAG,MAAM,GAAG,SAAS,CAAC;AAE7C,wBAAsB,kBAAkB,CACtC,OAAO,EAAE;IACP,gBAAgB,EAAE,OAAO,CAAC;IAC1B,aAAa,EAAE,WAAW,CAAC;IAC3B,eAAe,EAAE,0BAA0B,EAAE,CAAC;IAC9C,oGAAoG;IACpG,eAAe,EAAE,MAAM,EAAE,CAAC;IAC1B,oEAAoE;IACpE,mBAAmB,EAAE,MAAM,GAAG,SAAS,CAAC;CACzC,EACD,OAAO,EAAE,cAAc,CAAC,UAAU,EAAE,QAAQ,CAAC,GAC5C,OAAO,CAAC,MAAM,CAAC,CAgDjB"}
@@ -1,17 +1,17 @@
1
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
2
  import { readFile } from 'fs/promises';
4
3
  import { fileURLToPath } from 'url';
5
4
  import path from 'path';
6
5
  import { generateModernIframeScriptCode } from './generateModernIframeScriptCode.js';
7
6
  let generatedIframeHtml = undefined;
8
7
  export async function generateIframeHtml(options, context) {
9
- if (options.features?.storyStoreV7 === false) {
8
+ const { storybookOptions, storySpecifiers } = options;
9
+ const { configType, features, presets, serverChannelUrl } = storybookOptions;
10
+ if (features?.storyStoreV7 === false) {
10
11
  throw new Error('Cloudpack only supports storyStoreV7');
11
12
  }
12
13
  const iFramePath = path.join(path.dirname(fileURLToPath(import.meta.url)), '../static/iframeTemplate.html');
13
14
  const iframeHtmlTemplate = await readFile(iFramePath, { encoding: 'utf-8' });
14
- const { configType, features, presets, serverChannelUrl, configDir } = options;
15
15
  const build = await presets.apply('build');
16
16
  const frameworkOptions = await presets.apply('frameworkOptions');
17
17
  const headHtmlSnippet = await presets.apply('previewHead');
@@ -19,10 +19,7 @@ export async function generateIframeHtml(options, context) {
19
19
  const logLevel = await presets.apply('logLevel', undefined);
20
20
  const docsOptions = await presets.apply('docs');
21
21
  const coreOptions = await presets.apply('core');
22
- const stories = normalizeStories(await presets.apply('stories', [], options), {
23
- configDir,
24
- workingDir: context.session.config.appPath,
25
- }).map((specifier) => ({
22
+ const stories = storySpecifiers.map((specifier) => ({
26
23
  ...specifier,
27
24
  importPathMatcher: specifier.importPathMatcher.source,
28
25
  }));
@@ -1 +1 @@
1
- {"version":3,"file":"generateIFrameHtml.js","sourceRoot":"","sources":["../src/generateIFrameHtml.ts"],"names":[],"mappings":"AAAA,wHAAwH;AAExH,OAAO,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAE1D,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AACvC,OAAO,EAAE,aAAa,EAAE,MAAM,KAAK,CAAC;AACpC,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAE,8BAA8B,EAAE,MAAM,qCAAqC,CAAC;AAIrF,IAAI,mBAAmB,GAAuB,SAAS,CAAC;AAIxD,MAAM,CAAC,KAAK,UAAU,kBAAkB,CACtC,OAAgB,EAChB,OAAgE;IAEhE,IAAI,OAAO,CAAC,QAAQ,EAAE,YAAY,KAAK,KAAK,EAAE,CAAC;QAC7C,MAAM,IAAI,KAAK,CAAC,sCAAsC,CAAC,CAAC;IAC1D,CAAC;IAED,MAAM,UAAU,GAAG,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,aAAa,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,+BAA+B,CAAC,CAAC;IAC5G,MAAM,kBAAkB,GAAG,MAAM,QAAQ,CAAC,UAAU,EAAE,EAAE,QAAQ,EAAE,OAAO,EAAE,CAAC,CAAC;IAC7E,MAAM,EAAE,UAAU,EAAE,QAAQ,EAAE,OAAO,EAAE,gBAAgB,EAAE,SAAS,EAAE,GAAG,OAAO,CAAC;IAC/E,MAAM,KAAK,GAAG,MAA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AC;SACvE,OAAO,CACN,0BAA0B,EAC1B,MAAM,CAAC,OAAO,CAAC,YAAY,CAAC;SACzB,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,WAAW,CAAC,QAAQ,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,GAAG,CAAC;SACzD,IAAI,CAAC,EAAE,CAAC,CACZ;SACA,OAAO,CACN,0BAA0B,EAC1B,IAAI,CAAC,SAAS,CAAC,WAAW,IAAI,WAAW,CAAC,cAAc,CAAC,CAAC,CAAC,WAAW,CAAC,cAAc,CAAC,CAAC,CAAC,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,CAAC,4BAA4B,EAAE,MAAM,8BAA8B,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC,CAAC;IAEjG,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 type { PackageDefinitionsCache } from '@ms-cloudpack/common-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 context: { packages: PackageDefinitionsCache; session: Session },\n): Promise<string> {\n if (options.features?.storyStoreV7 === false) {\n throw new Error('Cloudpack only supports storyStoreV7');\n }\n\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: context.session.config.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(`('[APP MODULE SRC HERE]');`, await generateModernIframeScriptCode(options, context));\n\n return generatedIframeHtml;\n}\n"]}
1
+ {"version":3,"file":"generateIFrameHtml.js","sourceRoot":"","sources":["../src/generateIFrameHtml.ts"],"names":[],"mappings":"AAAA,wHAAwH;AAGxH,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AACvC,OAAO,EAAE,aAAa,EAAE,MAAM,KAAK,CAAC;AACpC,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAE,8BAA8B,EAAE,MAAM,qCAAqC,CAAC;AAIrF,IAAI,mBAAmB,GAAuB,SAAS,CAAC;AAIxD,MAAM,CAAC,KAAK,UAAU,kBAAkB,CACtC,OAQC,EACD,OAA6C;IAE7C,MAAM,EAAE,gBAAgB,EAAE,eAAe,EAAE,GAAG,OAAO,CAAC;IACtD,MAAM,EAAE,UAAU,EAAE,QAAQ,EAAE,OAAO,EAAE,gBAAgB,EAAE,GAAG,gBAAgB,CAAC;IAC7E,IAAI,QAAQ,EAAE,YAAY,KAAK,KAAK,EAAE,CAAC;QACrC,MAAM,IAAI,KAAK,CAAC,sCAAsC,CAAC,CAAC;IAC1D,CAAC;IAED,MAAM,UAAU,GAAG,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,aAAa,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,+BAA+B,CAAC,CAAC;IAC5G,MAAM,kBAAkB,GAAG,MAAM,QAAQ,CAAC,UAAU,EAAE,EAAE,QAAQ,E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EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,WAAW,CAAC,QAAQ,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,GAAG,CAAC;SACzD,IAAI,CAAC,EAAE,CAAC,CACZ;SACA,OAAO,CACN,0BAA0B,EAC1B,IAAI,CAAC,SAAS,CAAC,WAAW,IAAI,WAAW,CAAC,cAAc,CAAC,CAAC,CAAC,WAAW,CAAC,cAAc,CAAC,CAAC,CAAC,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,CAAC,4BAA4B,EAAE,MAAM,8BAA8B,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC,CAAC;IAEjG,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 type { CoreConfig, DocsOptions, NormalizedStoriesSpecifier, Options } from '@storybook/types';\nimport { readFile } from 'fs/promises';\nimport { fileURLToPath } from 'url';\nimport path from 'path';\nimport { generateModernIframeScriptCode } from './generateModernIframeScriptCode.js';\nimport type { PartialContext } from '@ms-cloudpack/api-server';\nimport type { PackageJson } from '@ms-cloudpack/common-types';\n\nlet generatedIframeHtml: string | undefined = undefined;\n\nexport type PreviewHtml = string | undefined;\n\nexport async function generateIframeHtml(\n options: {\n storybookOptions: Options;\n appDefinition: PackageJson;\n storySpecifiers: NormalizedStoriesSpecifier[];\n /** Actual paths to all story files, relative to `appPath` with leading `./` and forward slashes. */\n resolvedStories: string[];\n /** Absolute path to storybook preview or config file for the app */\n previewOrConfigFile: string | undefined;\n },\n context: PartialContext<'packages', 'config'>,\n): Promise<string> {\n const { storybookOptions, storySpecifiers } = options;\n const { configType, features, presets, serverChannelUrl } = storybookOptions;\n if (features?.storyStoreV7 === false) {\n throw new Error('Cloudpack only supports storyStoreV7');\n }\n\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 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 const coreOptions = await presets.apply<CoreConfig>('core');\n const stories = storySpecifiers.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(`('[APP MODULE SRC HERE]');`, await generateModernIframeScriptCode(options, context));\n\n return generatedIframeHtml;\n}\n"]}
@@ -1,14 +1,13 @@
1
- import type { Options } from '@storybook/types';
2
- import type { PackageDefinitionsCache } from '@ms-cloudpack/common-types';
3
- import type { Session } from '@ms-cloudpack/api-server';
1
+ import type { PackageJson } from '@ms-cloudpack/common-types';
4
2
  /**
5
3
  * This function takes an array of stories and creates a mapping between the stories' relative paths
6
4
  * to the working directory and their dynamic imports. The import is done in an asynchronous function
7
5
  * to delay loading. It then creates a function, `importFn(path)`, which resolves a path to an import
8
6
  * function and this is called by Storybook to fetch a story dynamically when needed.
9
7
  */
10
- export declare function generateImportFnScriptCode(options: Options, context: {
11
- packages: PackageDefinitionsCache;
12
- session: Session;
13
- }): Promise<string>;
8
+ export declare function generateImportFnScriptCode(options: {
9
+ appDefinition: PackageJson;
10
+ /** Actual paths to all story files, relative to `appPath` with leading `./` and forward slashes. */
11
+ resolvedStories: string[];
12
+ }): string;
14
13
  //# sourceMappingURL=generateImportFnScriptCode.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"generateImportFnScriptCode.d.ts","sourceRoot":"","sources":["../src/generateImportFnScriptCode.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,kBAAkB,CAAC;AAKhD,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,4BAA4B,CAAC;AAC1E,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,0BAA0B,CAAC;AAYxD;;;;;GAKG;AACH,wBAAsB,0BAA0B,CAC9C,OAAO,EAAE,OAAO,EAChB,OAAO,EAAE;IAAE,QAAQ,EAAE,uBAAuB,CAAC;IAAC,OAAO,EAAE,OAAO,CAAA;CAAE,GAC/D,OAAO,CAAC,MAAM,CAAC,CA8BjB"}
1
+ {"version":3,"file":"generateImportFnScriptCode.d.ts","sourceRoot":"","sources":["../src/generateImportFnScriptCode.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,4BAA4B,CAAC;AAE9D;;;;;GAKG;AACH,wBAAgB,0BAA0B,CAAC,OAAO,EAAE;IAClD,aAAa,EAAE,WAAW,CAAC;IAC3B,oGAAoG;IACpG,eAAe,EAAE,MAAM,EAAE,CAAC;CAC3B,GAAG,MAAM,CAuBT"}
@@ -1,39 +1,23 @@
1
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
2
  import path from 'path';
5
3
  import { logger } from '@storybook/node-logger';
6
4
  import { dedent } from 'ts-dedent';
7
- /**
8
- * Paths get passed either with no leading './' - e.g. `src/Foo.stories.js`,
9
- * or with a leading `../` (etc), e.g. `../src/Foo.stories.js`.
10
- * We want to deal in importPaths relative to the working dir, so we normalize
11
- */
12
- function toImportPath(relativePath) {
13
- return relativePath.startsWith('../') ? relativePath : `./${relativePath}`;
14
- }
15
5
  /**
16
6
  * This function takes an array of stories and creates a mapping between the stories' relative paths
17
7
  * to the working directory and their dynamic imports. The import is done in an asynchronous function
18
8
  * to delay loading. It then creates a function, `importFn(path)`, which resolves a path to an import
19
9
  * function and this is called by Storybook to fetch a story dynamically when needed.
20
10
  */
21
- export async function generateImportFnScriptCode(options, context) {
22
- const { packages, session } = context;
23
- const { appPath } = session.config;
24
- const definition = await packages.get(appPath);
25
- if (!definition) {
26
- throw new Error('Could not find package definition for the current app');
27
- }
28
- const stories = await listStories(options);
29
- const objectEntries = stories.map((file) => {
30
- const ext = path.extname(file);
31
- const relativeStoryPath = slash(path.relative(appPath, file));
11
+ export function generateImportFnScriptCode(options) {
12
+ const { resolvedStories, appDefinition } = options;
13
+ const objectEntries = resolvedStories.map((story) => {
14
+ const ext = path.extname(story);
32
15
  // TODO: Add support for '.mdx',
33
16
  if (!['.js', '.jsx', '.ts', '.tsx'].includes(ext)) {
34
- logger.warn(`Cannot process ${ext} file: ${relativeStoryPath}`);
17
+ logger.warn(`Cannot process ${ext} file: ${story}`);
35
18
  }
36
- return ` '${toImportPath(relativeStoryPath)}': async () => import('${definition.name}/${relativeStoryPath}')`;
19
+ // Add the package name and remove the ./ from the story path
20
+ return ` '${story}': async () => import('${appDefinition.name}/${story.slice(2)}')`;
37
21
  });
38
22
  return dedent `
39
23
  const importers = {
@@ -1 +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;AAGhD,OAAO,EAAE,MAAM,EAAE,MAAM,WAAW,CAAC;AAEnC;;;;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;;;;;GAKG;AACH,MAAM,CAAC,KAAK,UAAU,0BAA0B,CAC9C,OAAgB,EAChB,OAAgE;IAEhE,MAAM,EAAE,QAAQ,EAAE,OAAO,EAAE,GAAG,OAAO,CAAC;IACtC,MAAM,EAAE,OAAO,EAAE,GAAG,OAAO,CAAC,MAAM,CAAC;IACnC,MAAM,UAAU,GAAG,MAAM,QAAQ,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;IAE/C,IAAI,CAAC,UAAU,EAAE,CAAC;QAChB,MAAM,IAAI,KAAK,CAAC,uDAAuD,CAAC,CAAC;IAC3E,CAAC;IAED,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,UAAU,iBAAiB,EAAE,CAAC,CAAC;QAClE,CAAC;QAED,OAAO,MAAM,YAAY,CAAC,iBAAiB,CAAC,0BAA0B,UAAU,CAAC,IAAI,IAAI,iBAAiB,IAAI,CAAC;IACjH,CAAC,CAAC,CAAC;IAEH,OAAO,MAAM,CAAA;;QAEP,aAAa,CAAC,IAAI,CAAC,KAAK,CAAC;;;;;;KAM5B,CAAC;AACN,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';\nimport type { PackageDefinitionsCache } from '@ms-cloudpack/common-types';\nimport type { Session } from '@ms-cloudpack/api-server';\nimport { dedent } from 'ts-dedent';\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 */\nexport async function generateImportFnScriptCode(\n options: Options,\n context: { packages: PackageDefinitionsCache; session: Session },\n): Promise<string> {\n const { packages, session } = context;\n const { appPath } = session.config;\n const definition = await packages.get(appPath);\n\n if (!definition) {\n throw new Error('Could not find package definition for the current app');\n }\n\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: ${relativeStoryPath}`);\n }\n\n return ` '${toImportPath(relativeStoryPath)}': async () => import('${definition.name}/${relativeStoryPath}')`;\n });\n\n return dedent`\n const importers = {\n ${objectEntries.join(',\\n')}\n };\n\n export async function importFn(path) {\n return importers[path]();\n }\n `;\n}\n"]}
1
+ {"version":3,"file":"generateImportFnScriptCode.js","sourceRoot":"","sources":["../src/generateImportFnScriptCode.ts"],"names":[],"mappings":"AAAA,0HAA0H;AAE1H,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAE,MAAM,EAAE,MAAM,wBAAwB,CAAC;AAChD,OAAO,EAAE,MAAM,EAAE,MAAM,WAAW,CAAC;AAGnC;;;;;GAKG;AACH,MAAM,UAAU,0BAA0B,CAAC,OAI1C;IACC,MAAM,EAAE,eAAe,EAAE,aAAa,EAAE,GAAG,OAAO,CAAC;IAEnD,MAAM,aAAa,GAAG,eAAe,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE;QAClD,MAAM,GAAG,GAAG,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;QAChC,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,UAAU,KAAK,EAAE,CAAC,CAAC;QACtD,CAAC;QAED,6DAA6D;QAC7D,OAAO,MAAM,KAAK,0BAA0B,aAAa,CAAC,IAAI,IAAI,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC;IACvF,CAAC,CAAC,CAAC;IAEH,OAAO,MAAM,CAAA;;QAEP,aAAa,CAAC,IAAI,CAAC,KAAK,CAAC;;;;;;KAM5B,CAAC;AACN,CAAC","sourcesContent":["// based on https://github.com/storybookjs/storybook/blob/v7.6.5/code/builders/builder-vite/src/codegen-importfn-script.ts\n\nimport path from 'path';\nimport { logger } from '@storybook/node-logger';\nimport { dedent } from 'ts-dedent';\nimport type { PackageJson } from '@ms-cloudpack/common-types';\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 */\nexport function generateImportFnScriptCode(options: {\n appDefinition: PackageJson;\n /** Actual paths to all story files, relative to `appPath` with leading `./` and forward slashes. */\n resolvedStories: string[];\n}): string {\n const { resolvedStories, appDefinition } = options;\n\n const objectEntries = resolvedStories.map((story) => {\n const ext = path.extname(story);\n // TODO: Add support for '.mdx',\n if (!['.js', '.jsx', '.ts', '.tsx'].includes(ext)) {\n logger.warn(`Cannot process ${ext} file: ${story}`);\n }\n\n // Add the package name and remove the ./ from the story path\n return ` '${story}': async () => import('${appDefinition.name}/${story.slice(2)}')`;\n });\n\n return dedent`\n const importers = {\n ${objectEntries.join(',\\n')}\n };\n\n export async function importFn(path) {\n return importers[path]();\n }\n `;\n}\n"]}
@@ -1,8 +1,12 @@
1
- import type { Session } from '@ms-cloudpack/api-server';
2
- import type { PackageDefinitionsCache } from '@ms-cloudpack/common-types';
3
1
  import type { Options } from '@storybook/types';
4
- export declare function generateModernIframeScriptCode(options: Options, context: {
5
- packages: PackageDefinitionsCache;
6
- session: Session;
7
- }): Promise<string>;
2
+ import type { PartialContext } from '@ms-cloudpack/api-server';
3
+ import type { PackageJson } from '@ms-cloudpack/common-types';
4
+ export declare function generateModernIframeScriptCode(options: {
5
+ storybookOptions: Pick<Options, 'presets'>;
6
+ appDefinition: PackageJson;
7
+ /** Actual paths to all story files, relative to `appPath` with leading `./` and forward slashes. */
8
+ resolvedStories: string[];
9
+ /** Absolute path to storybook preview or config file for the app */
10
+ previewOrConfigFile: string | undefined;
11
+ }, context: PartialContext<'packages', 'config'>): Promise<string>;
8
12
  //# sourceMappingURL=generateModernIframeScriptCode.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"generateModernIframeScriptCode.d.ts","sourceRoot":"","sources":["../src/generateModernIframeScriptCode.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,0BAA0B,CAAC;AACxD,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,4BAA4B,CAAC;AAI1E,OAAO,KAAK,EAAE,OAAO,EAAqB,MAAM,kBAAkB,CAAC;AAOnE,wBAAsB,8BAA8B,CAClD,OAAO,EAAE,OAAO,EAChB,OAAO,EAAE;IAAE,QAAQ,EAAE,uBAAuB,CAAC;IAAC,OAAO,EAAE,OAAO,CAAA;CAAE,GAC/D,OAAO,CAAC,MAAM,CAAC,CAqDjB"}
1
+ {"version":3,"file":"generateModernIframeScriptCode.d.ts","sourceRoot":"","sources":["../src/generateModernIframeScriptCode.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,OAAO,EAAqB,MAAM,kBAAkB,CAAC;AAKnE,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,0BAA0B,CAAC;AAC/D,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,4BAA4B,CAAC;AAE9D,wBAAsB,8BAA8B,CAClD,OAAO,EAAE;IACP,gBAAgB,EAAE,IAAI,CAAC,OAAO,EAAE,SAAS,CAAC,CAAC;IAC3C,aAAa,EAAE,WAAW,CAAC;IAC3B,oGAAoG;IACpG,eAAe,EAAE,MAAM,EAAE,CAAC;IAC1B,oEAAoE;IACpE,mBAAmB,EAAE,MAAM,GAAG,SAAS,CAAC;CACzC,EACD,OAAO,EAAE,cAAc,CAAC,UAAU,EAAE,QAAQ,CAAC,GAC5C,OAAO,CAAC,MAAM,CAAC,CAsCjB"}
@@ -1,50 +1,36 @@
1
1
  // based on https://github.com/storybookjs/storybook/blob/v7.6.5/code/builders/builder-vite/src/codegen-modern-iframe-script.ts
2
- import { addExportsMapEntry, getExportsMap } from '@ms-cloudpack/package-utilities';
3
- import { normalizeRelativePath } from '@ms-cloudpack/path-string-parsing';
4
- import { loadPreviewOrConfigFile } from '@storybook/core-common';
5
- import { relative } from 'path';
6
2
  import { dedent } from 'ts-dedent';
7
3
  import { generateAddonSetupCode } from './generateAddonSetupCode.js';
8
4
  import { generateImportFnScriptCode } from './generateImportFnScriptCode.js';
9
5
  import { processPreviewAnnotation } from './utils/processPreviewAnnotation.js';
10
6
  export async function generateModernIframeScriptCode(options, context) {
11
- const { presets, configDir } = options;
12
- const { session, packages } = context;
13
- const { appPath } = session.config;
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: normalizeRelativePath(relative(appPath, previewOrConfigFile)),
21
- }, { packages, config: session.config });
22
- }
7
+ const { storybookOptions, previewOrConfigFile, appDefinition } = options;
8
+ const { presets } = storybookOptions;
23
9
  const previewAnnotations = await presets.apply('previewAnnotations', [], options);
24
10
  const previewAnnotationURLs = await Promise.all([...previewAnnotations, previewOrConfigFile]
25
11
  .filter((path) => !!path)
26
- .map(async (path) => await processPreviewAnnotation(path, context)));
12
+ .map((previewPath) => processPreviewAnnotation({ previewPath, appDefinition }, context)));
27
13
  const getPreviewAnnotationsFunction = dedent `
28
- const getProjectAnnotations = async () => {
29
- const configs = await Promise.all([${previewAnnotationURLs
14
+ const getProjectAnnotations = async () => {
15
+ const configs = await Promise.all([${previewAnnotationURLs
30
16
  .map((previewAnnotation) => `import('${previewAnnotation.split('\\').join('\\\\')}')`)
31
17
  .join(',\n')}]);
32
- return composeConfigs(configs);
33
- }`;
18
+ return composeConfigs(configs);
19
+ }`;
34
20
  return dedent `
35
- import { composeConfigs, PreviewWeb, ClientApi } from '@storybook/preview-api';
21
+ import { composeConfigs, PreviewWeb, ClientApi } from '@storybook/preview-api';
36
22
 
37
- ${generateAddonSetupCode()};
23
+ ${generateAddonSetupCode()};
38
24
 
39
- ${await generateImportFnScriptCode(options, context)}
25
+ ${generateImportFnScriptCode(options)}
40
26
 
41
- ${getPreviewAnnotationsFunction}
27
+ ${getPreviewAnnotationsFunction}
42
28
 
43
- window.__STORYBOOK_PREVIEW__ = window.__STORYBOOK_PREVIEW__ || new PreviewWeb();
29
+ window.__STORYBOOK_PREVIEW__ = window.__STORYBOOK_PREVIEW__ || new PreviewWeb();
44
30
 
45
- window.__STORYBOOK_STORY_STORE__ = window.__STORYBOOK_STORY_STORE__ || window.__STORYBOOK_PREVIEW__.storyStore;
46
- window.__STORYBOOK_CLIENT_API__ = window.__STORYBOOK_CLIENT_API__ || new ClientApi({ storyStore: window.__STORYBOOK_PREVIEW__.storyStore });
47
- window.__STORYBOOK_PREVIEW__.initialize({ importFn, getProjectAnnotations });
31
+ window.__STORYBOOK_STORY_STORE__ = window.__STORYBOOK_STORY_STORE__ || window.__STORYBOOK_PREVIEW__.storyStore;
32
+ window.__STORYBOOK_CLIENT_API__ = window.__STORYBOOK_CLIENT_API__ || new ClientApi({ storyStore: window.__STORYBOOK_PREVIEW__.storyStore });
33
+ window.__STORYBOOK_PREVIEW__.initialize({ importFn, getProjectAnnotations });
48
34
 
49
35
  if (import.meta.hot) {
50
36
  // Cloudpack doesn't currently support HMR
@@ -1 +1 @@
1
- {"version":3,"file":"generateModernIframeScriptCode.js","sourceRoot":"","sources":["../src/generateModernIframeScriptCode.ts"],"names":[],"mappings":"AAAA,+HAA+H;AAI/H,OAAO,EAAE,kBAAkB,EAAE,aAAa,EAAE,MAAM,iCAAiC,CAAC;AACpF,OAAO,EAAE,qBAAqB,EAAE,MAAM,mCAAmC,CAAC;AAC1E,OAAO,EAAE,uBAAuB,EAAE,MAAM,wBAAwB,CAAC;AAEjE,OAAO,EAAE,QAAQ,EAAE,MAAM,MAAM,CAAC;AAChC,OAAO,EAAE,MAAM,EAAE,MAAM,WAAW,CAAC;AACnC,OAAO,EAAE,sBAAsB,EAAE,MAAM,6BAA6B,CAAC;AACrE,OAAO,EAAE,0BAA0B,EAAE,MAAM,iCAAiC,CAAC;AAC7E,OAAO,EAAE,wBAAwB,EAAE,MAAM,qCAAqC,CAAC;AAE/E,MAAM,CAAC,KAAK,UAAU,8BAA8B,CAClD,OAAgB,EAChB,OAAgE;IAEhE,MAAM,EAAE,OAAO,EAAE,SAAS,EAAE,GAAG,OAAO,CAAC;IACvC,MAAM,EAAE,OAAO,EAAE,QAAQ,EAAE,GAAG,OAAO,CAAC;IACtC,MAAM,EAAE,OAAO,EAAE,GAAG,OAAO,CAAC,MAAM,CAAC;IAEnC,MAAM,mBAAmB,GAAG,uBAAuB,CAAC,EAAE,SAAS,EAAE,CAAC,CAAC;IAEnE,IAAI,mBAAmB,EAAE,CAAC;QACxB,MAAM,OAAO,GAAG,MAAM,aAAa,CAAC,EAAE,WAAW,EAAE,OAAO,EAAE,EAAE,EAAE,QAAQ,EAAE,MAAM,EAAE,OAAO,CAAC,MAAM,EAAE,CAAC,CAAC;QACpG,MAAM,kBAAkB,CACtB;YACE,OAAO;YACP,WAAW,EAAE,OAAO;YACpB,UAAU,EAAE,qBAAqB,CAAC,QAAQ,CAAC,OAAO,EAAE,mBAAmB,CAAC,CAAC;SAC1E,EACD,EAAE,QAAQ,EAAE,MAAM,EAAE,OAAO,CAAC,MAAM,EAAE,CACrC,CAAC;IACJ,CAAC;IAED,MAAM,kBAAkB,GAAG,MAAM,OAAO,CAAC,KAAK,CAAsB,oBAAoB,EAAE,EAAE,EAAE,OAAO,CAAC,CAAC;IACvG,MAAM,qBAAqB,GAAG,MAAM,OAAO,CAAC,GAAG,CAC7C,CAAC,GAAG,kBAAkB,EAAE,mBAAmB,CAAC;SACzC,MAAM,CAAC,CAAC,IAAI,EAA6B,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC;SACnD,GAAG,CAAC,KAAK,EAAE,IAAuB,EAAE,EAAE,CAAC,MAAM,wBAAwB,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC,CACzF,CAAC;IAEF,MAAM,6BAA6B,GAAG,MAAM,CAAA;;yCAEL,qBAAqB;SACvD,GAAG,CAAC,CAAC,iBAAiB,EAAE,EAAE,CAAC,WAAW,iBAAiB,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC;SACrF,IAAI,CAAC,KAAK,CAAC;;IAEd,CAAC;IAEH,OAAO,MAAM,CAAA;;;IAGX,sBAAsB,EAAE;;MAEtB,MAAM,0BAA0B,CAAC,OAAO,EAAE,OAAO,CAAC;;IAEpD,6BAA6B;;;;;;;;;;;MAW3B,CAAC;AACP,CAAC","sourcesContent":["// based on https://github.com/storybookjs/storybook/blob/v7.6.5/code/builders/builder-vite/src/codegen-modern-iframe-script.ts\n\nimport type { Session } from '@ms-cloudpack/api-server';\nimport type { PackageDefinitionsCache } from '@ms-cloudpack/common-types';\nimport { addExportsMapEntry, getExportsMap } from '@ms-cloudpack/package-utilities';\nimport { normalizeRelativePath } from '@ms-cloudpack/path-string-parsing';\nimport { loadPreviewOrConfigFile } from '@storybook/core-common';\nimport type { Options, PreviewAnnotation } from '@storybook/types';\nimport { relative } from 'path';\nimport { dedent } from 'ts-dedent';\nimport { generateAddonSetupCode } from './generateAddonSetupCode.js';\nimport { generateImportFnScriptCode } from './generateImportFnScriptCode.js';\nimport { processPreviewAnnotation } from './utils/processPreviewAnnotation.js';\n\nexport async function generateModernIframeScriptCode(\n options: Options,\n context: { packages: PackageDefinitionsCache; session: Session },\n): Promise<string> {\n const { presets, configDir } = options;\n const { session, packages } = context;\n const { appPath } = session.config;\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: normalizeRelativePath(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, context)),\n );\n\n const getPreviewAnnotationsFunction = dedent`\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 return dedent`\n import { composeConfigs, PreviewWeb, ClientApi } from '@storybook/preview-api';\n\n ${generateAddonSetupCode()};\n\n ${await generateImportFnScriptCode(options, context)}\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 if (import.meta.hot) {\n // Cloudpack doesn't currently support HMR\n import.meta.hot.decline();\n }`;\n}\n"]}
1
+ {"version":3,"file":"generateModernIframeScriptCode.js","sourceRoot":"","sources":["../src/generateModernIframeScriptCode.ts"],"names":[],"mappings":"AAAA,+HAA+H;AAG/H,OAAO,EAAE,MAAM,EAAE,MAAM,WAAW,CAAC;AACnC,OAAO,EAAE,sBAAsB,EAAE,MAAM,6BAA6B,CAAC;AACrE,OAAO,EAAE,0BAA0B,EAAE,MAAM,iCAAiC,CAAC;AAC7E,OAAO,EAAE,wBAAwB,EAAE,MAAM,qCAAqC,CAAC;AAI/E,MAAM,CAAC,KAAK,UAAU,8BAA8B,CAClD,OAOC,EACD,OAA6C;IAE7C,MAAM,EAAE,gBAAgB,EAAE,mBAAmB,EAAE,aAAa,EAAE,GAAG,OAAO,CAAC;IACzE,MAAM,EAAE,OAAO,EAAE,GAAG,gBAAgB,CAAC;IAErC,MAAM,kBAAkB,GAAG,MAAM,OAAO,CAAC,KAAK,CAAsB,oBAAoB,EAAE,EAAE,EAAE,OAAO,CAAC,CAAC;IACvG,MAAM,qBAAqB,GAAG,MAAM,OAAO,CAAC,GAAG,CAC7C,CAAC,GAAG,kBAAkB,EAAE,mBAAmB,CAAC;SACzC,MAAM,CAAC,CAAC,IAAI,EAA6B,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC;SACnD,GAAG,CAAC,CAAC,WAAW,EAAE,EAAE,CAAC,wBAAwB,CAAC,EAAE,WAAW,EAAE,aAAa,EAAE,EAAE,OAAO,CAAC,CAAC,CAC3F,CAAC;IAEF,MAAM,6BAA6B,GAAG,MAAM,CAAA;;2CAEH,qBAAqB;SACvD,GAAG,CAAC,CAAC,iBAAiB,EAAE,EAAE,CAAC,WAAW,iBAAiB,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC;SACrF,IAAI,CAAC,KAAK,CAAC;;MAEd,CAAC;IAEL,OAAO,MAAM,CAAA;;;MAGT,sBAAsB,EAAE;;MAExB,0BAA0B,CAAC,OAAO,CAAC;;MAEnC,6BAA6B;;;;;;;;;;;MAW7B,CAAC;AACP,CAAC","sourcesContent":["// based on https://github.com/storybookjs/storybook/blob/v7.6.5/code/builders/builder-vite/src/codegen-modern-iframe-script.ts\n\nimport type { Options, PreviewAnnotation } from '@storybook/types';\nimport { dedent } from 'ts-dedent';\nimport { generateAddonSetupCode } from './generateAddonSetupCode.js';\nimport { generateImportFnScriptCode } from './generateImportFnScriptCode.js';\nimport { processPreviewAnnotation } from './utils/processPreviewAnnotation.js';\nimport type { PartialContext } from '@ms-cloudpack/api-server';\nimport type { PackageJson } from '@ms-cloudpack/common-types';\n\nexport async function generateModernIframeScriptCode(\n options: {\n storybookOptions: Pick<Options, 'presets'>;\n appDefinition: PackageJson;\n /** Actual paths to all story files, relative to `appPath` with leading `./` and forward slashes. */\n resolvedStories: string[];\n /** Absolute path to storybook preview or config file for the app */\n previewOrConfigFile: string | undefined;\n },\n context: PartialContext<'packages', 'config'>,\n): Promise<string> {\n const { storybookOptions, previewOrConfigFile, appDefinition } = options;\n const { presets } = storybookOptions;\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((previewPath) => processPreviewAnnotation({ previewPath, appDefinition }, context)),\n );\n\n const getPreviewAnnotationsFunction = dedent`\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 return dedent`\n import { composeConfigs, PreviewWeb, ClientApi } from '@storybook/preview-api';\n\n ${generateAddonSetupCode()};\n\n ${generateImportFnScriptCode(options)}\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 if (import.meta.hot) {\n // Cloudpack doesn't currently support HMR\n import.meta.hot.decline();\n }`;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAsBA,OAAO,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,kBAAkB,CAAC;AASzD,KAAK,gBAAgB,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;AASzC,eAAO,MAAM,IAAI,EAAE,gBAAgB,CAAC,MAAM,CAmBzC,CAAC;AAEF,eAAO,MAAM,KAAK,EAAE,gBAAgB,CAAC,OAAO,CAoK3C,CAAC;AAEF,eAAO,MAAM,KAAK,EAAE,gBAAgB,CAAC,OAAO,CAG3C,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AASA,OAAO,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,kBAAkB,CAAC;AAWzD,KAAK,gBAAgB,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;AASzC,eAAO,MAAM,IAAI,EAAE,gBAAgB,CAAC,MAAM,CAmBzC,CAAC;AAEF,eAAO,MAAM,KAAK,EAAE,gBAAgB,CAAC,OAAO,CAkH3C,CAAC;AAEF,eAAO,MAAM,KAAK,EAAE,gBAAgB,CAAC,OAAO,CAG3C,CAAC"}
package/lib/index.js CHANGED
@@ -1,18 +1,19 @@
1
- import { getLocalCachePath, createPartialApiContext, ensurePackageBundled } from '@ms-cloudpack/api-server';
1
+ import { ensurePackageBundled } from '@ms-cloudpack/api-server';
2
2
  import { startServers } from '@ms-cloudpack/app-server';
3
- import { readConfig } from '@ms-cloudpack/config';
3
+ import { getLocalCachePath } from '@ms-cloudpack/config';
4
4
  import { express } from '@ms-cloudpack/create-express-app';
5
- import { addExportsMapEntry, getDisplayVersion, getExportsMap, getVersion, isExternalPackage, resolve, } from '@ms-cloudpack/package-utilities';
6
- import { normalizeRelativePath, slash } from '@ms-cloudpack/path-string-parsing';
7
- import { TaskReporter, bold, debugLoggingConfig, defaultLoggingConfig, noLoggingConfig, verboseLoggingConfig, } from '@ms-cloudpack/task-reporter';
8
- import { createTelemetryClient } from '@ms-cloudpack/telemetry';
5
+ import { resolve } from '@ms-cloudpack/package-utilities';
6
+ import { slash } from '@ms-cloudpack/path-string-parsing';
7
+ import { findPackageRoot, normalizedPathRelativeTo } from '@ms-cloudpack/path-utilities';
8
+ import { loadPreviewOrConfigFile } from '@storybook/core-common';
9
9
  import fsExtra from 'fs-extra';
10
10
  import fsPromises from 'fs/promises';
11
11
  import path from 'path';
12
12
  import { fileURLToPath } from 'url';
13
13
  import { generateIframeHtml } from './generateIFrameHtml.js';
14
- import { getNodeModuleDir } from './getNodeModuleDir.js';
15
14
  import { listStories } from './listStories.js';
15
+ import { createApiContext } from './createApiContext.js';
16
+ const currentDir = path.dirname(fileURLToPath(import.meta.url));
16
17
  const servers = {};
17
18
  export const bail = async (error) => {
18
19
  if (error) {
@@ -33,119 +34,77 @@ export const bail = async (error) => {
33
34
  }));
34
35
  };
35
36
  export const start = async ({ options, startTime, router, server: devServer }) => {
36
- const previewResolvedDir = getNodeModuleDir('@storybook/preview');
37
+ const previewResolvedDir = await resolve('@storybook/preview', currentDir);
38
+ if (!previewResolvedDir) {
39
+ throw new Error(`Could not resolve @storybook/preview from ${currentDir}`);
40
+ }
37
41
  const previewDirOrigin = path.join(previewResolvedDir, 'dist');
38
42
  router.use('/sb-preview', express.static(previewDirOrigin, { immutable: true, maxAge: '5m' }));
39
43
  // TODO: This might be useful later on.
40
44
  // const env = await options.presets.apply<Record<string, string>>('env');
41
- // eslint-disable-next-line no-restricted-properties -- this is the one place we need cwd (for a default)
42
- const appPath = process.cwd();
43
- const config = await readConfig(appPath);
44
- // TODO: Move to won package.
45
- // runPrerequisites(config, appPath);
46
- // This part should be almost identical to the cli start command.
47
- const reporter = new TaskReporter({
48
- productName: 'Storybook + Cloudpack',
49
- version: getDisplayVersion(import.meta.url),
50
- description: () => `Running "${bold('storybook')}"`,
51
- helpMessage: config.helpMessage,
52
- // TODO: Get options and enable this.
53
- plainTextMode: options.ci,
54
- ...(options.loglevel === 'debug'
55
- ? debugLoggingConfig
56
- : options.loglevel === 'verbose'
57
- ? verboseLoggingConfig
58
- : options.quiet || options.loglevel === 'quiet'
59
- ? noLoggingConfig
60
- : defaultLoggingConfig),
61
- });
62
- const connectionString = options.disableTelemetry
63
- ? undefined
64
- : config.telemetry?.connectionString || process.env.CLOUDPACK_TELEMETRY_CONNECTION_STRING;
65
- const logLevel = options.loglevel === 'verbose' ? 'VERBOSE' : options.loglevel === 'debug' ? 'DEBUG' : undefined;
66
- if (options.loglevel !== 'debug') {
67
- reporter.ignoreLogMessage('ApplicationInsights:');
45
+ // eslint-disable-next-line no-restricted-properties -- this is where we find the appPath
46
+ const cwd = process.cwd();
47
+ const appPath = findPackageRoot(cwd);
48
+ if (!appPath) {
49
+ throw new Error(`Could not find package.json relative to ${cwd}`);
68
50
  }
69
- const telemetryClient = await createTelemetryClient({
70
- productVersion: getVersion(import.meta.url),
71
- connectionString,
72
- logLevel,
73
- serviceNamespace: 'cloudpack',
74
- serviceName: 'storybook',
75
- rootSpanName: 'storybook',
76
- });
77
- // Register performance observers to track performance metrics as events of CLI span.
78
- // registerPerformanceObservers(telemetryClient);
79
- const currentDir = path.dirname(fileURLToPath(import.meta.url));
80
- let overlayPath = await resolve('@ms-cloudpack/overlay', currentDir);
81
- // If overlay is an internal package, resolve the overlay from the current package's linked node modules
82
- // to "externalize" it, so that we always use the bundled version of the overlay instead of the source.
83
- if (overlayPath && !isExternalPackage(overlayPath)) {
84
- overlayPath = path.join(currentDir, '/../', 'node_modules', '@ms-cloudpack/overlay');
85
- }
86
- const apiContext = await createPartialApiContext({
87
- appPath,
88
- config,
89
- reporter,
90
- telemetryClient,
91
- items: ['bus', 'watcher', 'taskRunner', 'packages', 'session', 'packageImportPaths', 'packageHashes'],
92
- overlayPath,
93
- });
51
+ const apiContext = await createApiContext({ appPath, storybookOptions: options });
94
52
  const { packages, session } = apiContext;
95
- // Overwrite the exports of the app package to an empty object, since we only care about stories.
53
+ const { config } = session;
54
+ // Resolve the story files, and find the preview/config file.
55
+ const { storySpecifiers, resolvedStories } = await listStories({ storybookOptions: options, appPath });
56
+ const previewOrConfigFile = loadPreviewOrConfigFile(options);
57
+ // Overwrite the exports of the app package to just contain the stories and preview/config file.
96
58
  packages.registerTransform(() => ({ definition, packagePath }) => {
97
- if (slash(appPath) === slash(packagePath)) {
98
- return { ...definition, exports: {} };
59
+ if (slash(appPath) !== slash(packagePath)) {
60
+ return;
61
+ }
62
+ // We just need a simple path mapping for the stories, so it's not necessary to use addExportsMapEntry.
63
+ const exports = {};
64
+ for (const story of resolvedStories) {
65
+ if (!story.startsWith('./')) {
66
+ // Not sure if this is even allowed by Storybook, but check just in case...
67
+ // In theory we could handle this by either modifying the exports of the other package too,
68
+ // or possibly by enabling autoUpdateEntries so the file will be bundled on import.
69
+ throw new Error(`Cloudpack does not support stories outside of the package root: ${story}`);
70
+ }
71
+ exports[story] = story;
72
+ }
73
+ if (previewOrConfigFile) {
74
+ const normalizedPreview = normalizedPathRelativeTo(appPath, previewOrConfigFile);
75
+ if (!normalizedPreview.startsWith('./')) {
76
+ // Not sure if this is allowed by storybook either
77
+ throw new Error(`Cloudpack does not support preview/config files outside of the package root: ${previewOrConfigFile}`);
78
+ }
79
+ exports[normalizedPreview] = normalizedPreview;
99
80
  }
81
+ return { ...definition, exports };
100
82
  });
101
- // Make sure the package has a valid definition.
102
- const definition = await packages.get(appPath);
103
- if (!definition?.name || !definition.version) {
104
- throw new Error(`The package.json at "${appPath}" did not have a name and/or version.`);
105
- }
106
- // TODO: Get options and enable this.
107
- // Increment the session version if caching is disabled.
108
- // if (options.cache === false) {
109
- // session.incrementSessionVersion();
110
- // }
111
- // Set shared telemetry attributes which will be sent with all telemetry events.
112
- telemetryClient.setSharedSpanAttribute('sessionId', session.id);
113
- // TODO: Get options and enable this.
114
- // if (options.logResolveMap) {
115
- // // Write the resolve map to disk.
116
- // await writeJson(path.join(appPath, 'resolve-map.json'), session.resolveMap);
117
- // }
83
+ const appDefinition = await packages.get(appPath);
118
84
  // Storybook set up is mostly done here.
119
- const generated = await generateIframeHtml(options, { packages, session });
120
- await fsExtra.ensureDir(getLocalCachePath(appPath));
85
+ const generated = await generateIframeHtml({ storybookOptions: options, storySpecifiers, resolvedStories, appDefinition, previewOrConfigFile }, apiContext);
121
86
  // TODO: Currently saving it to disk as the config only accepts a path.
122
- const iFramePath = path.join(getLocalCachePath(appPath), 'iframe.html');
87
+ const cachePath = getLocalCachePath(appPath);
88
+ await fsExtra.ensureDir(cachePath);
89
+ const iFramePath = path.join(cachePath, 'iframe.html');
123
90
  await fsPromises.writeFile(iFramePath, generated, { encoding: 'utf-8' });
124
91
  // iFrame script is required for storybook to work.
125
- config.devServer ??= {};
126
92
  config.routes ??= [];
127
93
  config.routes.push({
128
94
  match: '/iframe.html',
129
95
  renderScript: iFramePath,
130
96
  });
131
- // Add an exports entry for each story file
132
- const exports = await getExportsMap({ packagePath: appPath }, { packages, config: session.config });
133
- const stories = await listStories(options);
134
- for (const story of stories) {
135
- const importPath = normalizeRelativePath(path.relative(appPath, story));
136
- await addExportsMapEntry({ exports, packagePath: appPath, importPath, filePath: importPath }, { packages, config: session.config });
137
- }
138
97
  const { createCloudpackServer } = await import('@ms-cloudpack/api-server');
139
98
  // Start api server for tracking status and handling remote requests.
140
99
  servers.apiServer = await createCloudpackServer(apiContext);
141
100
  // Kick off bundling app package as soon as api server is ready.
142
101
  void ensurePackageBundled({
143
- input: { name: definition.name, version: definition.version },
102
+ input: { name: appDefinition.name, version: appDefinition.version },
144
103
  ctx: apiContext,
145
104
  });
146
105
  // Start bundle and app servers for hosting the app.
147
106
  const { appServer, bundleServer } = await startServers({
148
- definition,
107
+ definition: appDefinition,
149
108
  server: devServer,
150
109
  // TODO: Get options and enable this.
151
110
  bundleServerOptions: { disableCache: false },
package/lib/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,uBAAuB,EAAE,oBAAoB,EAAE,MAAM,0BAA0B,CAAC;AAC5G,OAAO,EAAE,YAAY,EAAE,MAAM,0BAA0B,CAAC;AACxD,OAAO,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAC;AAClD,OAAO,EAAE,OAAO,EAAE,MAAM,kCAAkC,CAAC;AAC3D,OAAO,EACL,kBAAkB,EAClB,iBAAiB,EACjB,aAAa,EACb,UAAU,EACV,iBAAiB,EACjB,OAAO,GACR,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAE,qBAAqB,EAAE,KAAK,EAAE,MAAM,mCAAmC,CAAC;AACjF,OAAO,EACL,YAAY,EACZ,IAAI,EACJ,kBAAkB,EAClB,oBAAoB,EACpB,eAAe,EACf,oBAAoB,GACrB,MAAM,6BAA6B,CAAC;AACrC,OAAO,EAAE,qBAAqB,EAAE,MAAM,yBAAyB,CAAC;AAEhE,OAAO,OAAO,MAAM,UAAU,CAAC;AAC/B,OAAO,UAAU,MAAM,aAAa,CAAC;AACrC,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAE,aAAa,EAAE,MAAM,KAAK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C,SAAS,GAAG,SAAS,CAAC;IAC9B,OAAO,CAAC,YAAY,GAAG,YAAY,CAAC;IAEpC,MAAM,CAAC,GAAG,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC;IAE1B,qEAAqE;IACrE,uEAAuE;IAEvE,OAAO;QACL,IAAI;QACJ,SAAS,EAAE,OAAO,CAAC,MAAM,CAAC,SAAS,CAAC;KACrC,CAAC;AACJ,CAAC,CAAC;AAEF,MAAM,CAAC,MAAM,KAAK,GAA8B,GAAG,EAAE;IACnD,OAAO,CAAC,GAAG,CAAC,mDAAmD,CAAC,CAAC;IACjE,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AAClB,CAAC,CAAC","sourcesContent":["import { getLocalCachePath, createPartialApiContext, ensurePackageBundled } from '@ms-cloudpack/api-server';\nimport { startServers } from '@ms-cloudpack/app-server';\nimport { readConfig } from '@ms-cloudpack/config';\nimport { express } from '@ms-cloudpack/create-express-app';\nimport {\n addExportsMapEntry,\n getDisplayVersion,\n getExportsMap,\n getVersion,\n isExternalPackage,\n resolve,\n} from '@ms-cloudpack/package-utilities';\nimport { normalizeRelativePath, slash } from '@ms-cloudpack/path-string-parsing';\nimport {\n TaskReporter,\n bold,\n debugLoggingConfig,\n defaultLoggingConfig,\n noLoggingConfig,\n verboseLoggingConfig,\n} from '@ms-cloudpack/task-reporter';\nimport { createTelemetryClient } from '@ms-cloudpack/telemetry';\nimport type { Builder, Options } from '@storybook/types';\nimport fsExtra from 'fs-extra';\nimport fsPromises from 'fs/promises';\nimport path from 'path';\nimport { fileURLToPath } from 'url';\nimport { generateIframeHtml } from './generateIFrameHtml.js';\nimport { getNodeModuleDir } from './getNodeModuleDir.js';\nimport { listStories } from './listStories.js';\n\ntype CloudpackBuilder = Builder<Options>;\n\ntype ClosableServer = {\n close: () => Promise<void>;\n url: string;\n};\n\nconst servers: Record<string, ClosableServer | undefined> = {};\n\nexport const bail: CloudpackBuilder['bail'] = async (error) => {\n if (error) {\n console.error('Error:', error);\n }\n\n await Promise.all(\n Object.entries(servers).map(async ([name, server]) => {\n if (!server) return;\n\n const desc = `${name} (${server.url})`;\n console.info(`Closing ${desc}`);\n try {\n await server.close();\n console.info(`Closed ${desc}`);\n } catch (err) {\n console.warn(`Error closing ${desc}:`, err);\n }\n }),\n );\n};\n\nexport const start: CloudpackBuilder['start'] = async ({ options, startTime, router, server: devServer }) => {\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 // This part should be almost identical to the cli start command.\n const reporter = new TaskReporter({\n productName: 'Storybook + Cloudpack',\n version: getDisplayVersion(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: 'storybook',\n rootSpanName: 'storybook',\n });\n\n // Register performance observers to track performance metrics as events of CLI span.\n // registerPerformanceObservers(telemetryClient);\n\n const currentDir = path.dirname(fileURLToPath(import.meta.url));\n let overlayPath = await resolve('@ms-cloudpack/overlay', currentDir);\n\n // If overlay is an internal package, resolve the overlay from the current package's linked node modules\n // to \"externalize\" it, so that we always use the bundled version of the overlay instead of the source.\n if (overlayPath && !isExternalPackage(overlayPath)) {\n overlayPath = path.join(currentDir, '/../', 'node_modules', '@ms-cloudpack/overlay');\n }\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,\n });\n\n const { packages, session } = apiContext;\n\n // Overwrite the exports of the app package to an empty object, since we only care about stories.\n packages.registerTransform(() => ({ definition, packagePath }) => {\n if (slash(appPath) === slash(packagePath)) {\n return { ...definition, exports: {} };\n }\n });\n\n // Make sure the package has a valid definition.\n const definition = await packages.get(appPath);\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 // 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, { 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.routes ??= [];\n config.routes.push({\n match: '/iframe.html',\n renderScript: iFramePath,\n });\n\n // Add an exports entry for each story file\n const exports = await getExportsMap({ packagePath: appPath }, { packages, config: session.config });\n const stories = await listStories(options);\n\n for (const story of stories) {\n const importPath = normalizeRelativePath(path.relative(appPath, story));\n await addExportsMapEntry(\n { exports, packagePath: appPath, importPath, filePath: importPath },\n { packages, config: session.config },\n );\n }\n\n const { createCloudpackServer } = await import('@ms-cloudpack/api-server');\n\n // Start api server for tracking status and handling remote requests.\n servers.apiServer = await createCloudpackServer(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 // Start bundle and app servers for hosting the app.\n const { appServer, bundleServer } = await startServers(\n {\n definition,\n server: devServer,\n // TODO: Get options and enable this.\n bundleServerOptions: { disableCache: false },\n },\n apiContext,\n );\n servers.appServer = appServer;\n servers.bundleServer = bundleServer;\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 totalTime: process.hrtime(startTime),\n };\n};\n\nexport const build: CloudpackBuilder['build'] = () => {\n console.log('Cloudpack Storybook build is not implemented yet.');\n process.exit(1);\n};\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oBAAoB,EAAE,MAAM,0BAA0B,CAAC;AAChE,OAAO,EAAE,YAAY,EAAE,MAAM,0BAA0B,CAAC;AAExD,OAAO,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AACzD,OAAO,EAAE,OAAO,EAAE,MAAM,kCAAkC,CAAC;AAC3D,OAAO,EAAE,OAAO,EAAE,MAAM,iCAAiC,CAAC;AAC1D,OAAO,EAAE,KAAK,EAAE,MAAM,mCAAmC,CAAC;AAC1D,OAAO,EAAE,eAAe,EAAE,wBAAwB,EAAE,MAAM,8BAA8B,CAAC;AACzF,OAAO,EAAE,uBAAuB,EAAE,MAAM,wBAAwB,CAAC;AAEjE,OAAO,OAAO,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,CAAC,MAAM,CAAC,SAAS,CAAC;KACrC,CAAC;AACJ,CAAC,CAAC;AAEF,MAAM,CAAC,MAAM,KAAK,GAA8B,GAAG,EAAE;IACnD,OAAO,CAAC,GAAG,CAAC,mDAAmD,CAAC,CAAC;IACjE,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AAClB,CAAC,CAAC","sourcesContent":["import { ensurePackageBundled } from '@ms-cloudpack/api-server';\nimport { startServers } from '@ms-cloudpack/app-server';\nimport type { PackageJsonExportsObject } from '@ms-cloudpack/common-types';\nimport { getLocalCachePath } from '@ms-cloudpack/config';\nimport { express } from '@ms-cloudpack/create-express-app';\nimport { resolve } from '@ms-cloudpack/package-utilities';\nimport { slash } from '@ms-cloudpack/path-string-parsing';\nimport { findPackageRoot, normalizedPathRelativeTo } from '@ms-cloudpack/path-utilities';\nimport { loadPreviewOrConfigFile } from '@storybook/core-common';\nimport type { Builder, Options } from '@storybook/types';\nimport fsExtra from 'fs-extra';\nimport fsPromises from 'fs/promises';\nimport path from 'path';\nimport { fileURLToPath } from 'url';\nimport { generateIframeHtml } from './generateIFrameHtml.js';\nimport { listStories } from './listStories.js';\nimport { createApiContext } from './createApiContext.js';\n\nconst currentDir = path.dirname(fileURLToPath(import.meta.url));\n\ntype CloudpackBuilder = Builder<Options>;\n\ntype ClosableServer = {\n close: () => Promise<void>;\n url: string;\n};\n\nconst servers: Record<string, ClosableServer | undefined> = {};\n\nexport const bail: CloudpackBuilder['bail'] = async (error) => {\n if (error) {\n console.error('Error:', error);\n }\n\n await Promise.all(\n Object.entries(servers).map(async ([name, server]) => {\n if (!server) return;\n\n const desc = `${name} (${server.url})`;\n console.info(`Closing ${desc}`);\n try {\n await server.close();\n console.info(`Closed ${desc}`);\n } catch (err) {\n console.warn(`Error closing ${desc}:`, err);\n }\n }),\n );\n};\n\nexport const start: CloudpackBuilder['start'] = async ({ options, startTime, router, server: devServer }) => {\n const previewResolvedDir = await resolve('@storybook/preview', currentDir);\n if (!previewResolvedDir) {\n throw new Error(`Could not resolve @storybook/preview from ${currentDir}`);\n }\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 where we find the appPath\n const cwd = process.cwd();\n const appPath = findPackageRoot(cwd);\n if (!appPath) {\n throw new Error(`Could not find package.json relative to ${cwd}`);\n }\n\n const apiContext = await createApiContext({ appPath, storybookOptions: options });\n const { packages, session } = apiContext;\n const { config } = session;\n\n // Resolve the story files, and find the preview/config file.\n const { storySpecifiers, resolvedStories } = await listStories({ storybookOptions: options, appPath });\n const previewOrConfigFile = loadPreviewOrConfigFile(options);\n\n // Overwrite the exports of the app package to just contain the stories and preview/config file.\n packages.registerTransform(() => ({ definition, packagePath }) => {\n if (slash(appPath) !== slash(packagePath)) {\n return;\n }\n\n // We just need a simple path mapping for the stories, so it's not necessary to use addExportsMapEntry.\n const exports: PackageJsonExportsObject = {};\n\n for (const story of resolvedStories) {\n if (!story.startsWith('./')) {\n // Not sure if this is even allowed by Storybook, but check just in case...\n // In theory we could handle this by either modifying the exports of the other package too,\n // or possibly by enabling autoUpdateEntries so the file will be bundled on import.\n throw new Error(`Cloudpack does not support stories outside of the package root: ${story}`);\n }\n exports[story] = story;\n }\n\n if (previewOrConfigFile) {\n const normalizedPreview = normalizedPathRelativeTo(appPath, previewOrConfigFile);\n if (!normalizedPreview.startsWith('./')) {\n // Not sure if this is allowed by storybook either\n throw new Error(\n `Cloudpack does not support preview/config files outside of the package root: ${previewOrConfigFile}`,\n );\n }\n exports[normalizedPreview] = normalizedPreview;\n }\n\n return { ...definition, exports };\n });\n\n const appDefinition = await packages.get(appPath);\n\n // Storybook set up is mostly done here.\n const generated = await generateIframeHtml(\n { storybookOptions: options, storySpecifiers, resolvedStories, appDefinition, previewOrConfigFile },\n apiContext,\n );\n\n // TODO: Currently saving it to disk as the config only accepts a path.\n const cachePath = getLocalCachePath(appPath);\n await fsExtra.ensureDir(cachePath);\n const iFramePath = path.join(cachePath, 'iframe.html');\n await fsPromises.writeFile(iFramePath, generated, { encoding: 'utf-8' });\n\n // iFrame script is required for storybook to work.\n config.routes ??= [];\n config.routes.push({\n match: '/iframe.html',\n renderScript: iFramePath,\n });\n\n const { createCloudpackServer } = await import('@ms-cloudpack/api-server');\n\n // Start api server for tracking status and handling remote requests.\n servers.apiServer = await createCloudpackServer(apiContext);\n\n // Kick off bundling app package as soon as api server is ready.\n void ensurePackageBundled({\n input: { name: appDefinition.name, version: appDefinition.version },\n ctx: apiContext,\n });\n\n // Start bundle and app servers for hosting the app.\n const { appServer, bundleServer } = await startServers(\n {\n definition: appDefinition,\n server: devServer,\n // TODO: Get options and enable this.\n bundleServerOptions: { disableCache: false },\n },\n apiContext,\n );\n servers.appServer = appServer;\n servers.bundleServer = bundleServer;\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 totalTime: process.hrtime(startTime),\n };\n};\n\nexport const build: CloudpackBuilder['build'] = () => {\n console.log('Cloudpack Storybook build is not implemented yet.');\n process.exit(1);\n};\n"]}
@@ -1,3 +1,13 @@
1
- import type { Options } from '@storybook/types';
2
- export declare function listStories(options: Options): Promise<string[]>;
1
+ import type { NormalizedStoriesSpecifier, Options } from '@storybook/types';
2
+ /**
3
+ * Get the stories from the storybook config.
4
+ */
5
+ export declare function listStories(params: {
6
+ storybookOptions: Options;
7
+ appPath: string;
8
+ }): Promise<{
9
+ storySpecifiers: NormalizedStoriesSpecifier[];
10
+ /** Actual paths to all story files, relative to `appPath` with leading `./` and forward slashes. */
11
+ resolvedStories: string[];
12
+ }>;
3
13
  //# sourceMappingURL=listStories.d.ts.map
@@ -1 +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"}
1
+ {"version":3,"file":"listStories.d.ts","sourceRoot":"","sources":["../src/listStories.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,0BAA0B,EAAE,OAAO,EAAE,MAAM,kBAAkB,CAAC;AAG5E;;GAEG;AACH,wBAAsB,WAAW,CAAC,MAAM,EAAE;IAAE,gBAAgB,EAAE,OAAO,CAAC;IAAC,OAAO,EAAE,MAAM,CAAA;CAAE,GAAG,OAAO,CAAC;IACjG,eAAe,EAAE,0BAA0B,EAAE,CAAC;IAC9C,oGAAoG;IACpG,eAAe,EAAE,MAAM,EAAE,CAAC;CAC3B,CAAC,CA4BD"}
@@ -3,21 +3,29 @@ import path from 'path';
3
3
  import glob from 'fast-glob';
4
4
  import { normalizeStories, commonGlobOptions } from '@storybook/core-common';
5
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 }) => {
6
+ import { normalizedPathRelativeTo } from '@ms-cloudpack/path-utilities';
7
+ /**
8
+ * Get the stories from the storybook config.
9
+ */
10
+ export async function listStories(params) {
11
+ const { storybookOptions, appPath } = params;
12
+ const storySpecifiers = normalizeStories(await storybookOptions.presets.apply('stories', [], storybookOptions), {
13
+ configDir: storybookOptions.configDir,
14
+ workingDir: appPath,
15
+ });
16
+ const resolvedStories = (await Promise.all(storySpecifiers.map(({ directory, files }) => {
11
17
  const pattern = path.join(directory, files);
12
- const absolutePattern = path.isAbsolute(pattern) ? pattern : path.join(options.configDir, pattern);
18
+ const absolutePattern = path.isAbsolute(pattern) ? pattern : path.join(appPath, pattern);
13
19
  return glob(slash(absolutePattern), {
14
20
  ...commonGlobOptions(absolutePattern),
15
21
  followSymbolicLinks: true,
16
22
  });
17
23
  })))
18
- .reduce((carry, stories) => carry.concat(stories.map(slash)), [])
24
+ .flat()
25
+ .map((story) => normalizedPathRelativeTo(appPath, story))
19
26
  // Sort stories to prevent a non-deterministic build. The result of Glob is not sorted an may differ
20
27
  // for each invocation. This results in a different bundle file hashes from one build to the next.
21
- .sort());
28
+ .sort();
29
+ return { storySpecifiers, resolvedStories };
22
30
  }
23
31
  //# sourceMappingURL=listStories.js.map
@@ -1 +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"]}
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;AAE1D,OAAO,EAAE,wBAAwB,EAAE,MAAM,8BAA8B,CAAC;AAExE;;GAEG;AACH,MAAM,CAAC,KAAK,UAAU,WAAW,CAAC,MAAsD;IAKtF,MAAM,EAAE,gBAAgB,EAAE,OAAO,EAAE,GAAG,MAAM,CAAC;IAE7C,MAAM,eAAe,GAAG,gBAAgB,CAAC,MAAM,gBAAgB,CAAC,OAAO,CAAC,KAAK,CAAC,SAAS,EAAE,EAAE,EAAE,gBAAgB,CAAC,EAAE;QAC9G,SAAS,EAAE,gBAAgB,CAAC,SAAS;QACrC,UAAU,EAAE,OAAO;KACpB,CAAC,CAAC;IAEH,MAAM,eAAe,GAAG,CACtB,MAAM,OAAO,CAAC,GAAG,CACf,eAAe,CAAC,GAAG,CAAC,CAAC,EAAE,SAAS,EAAE,KAAK,EAAE,EAAE,EAAE;QAC3C,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,EAAE,OAAO,CAAC,CAAC;QAEzF,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,IAAI,EAAE;SACN,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,wBAAwB,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;QACzD,oGAAoG;QACpG,kGAAkG;SACjG,IAAI,EAAE,CAAC;IAEV,OAAO,EAAE,eAAe,EAAE,eAAe,EAAE,CAAC;AAC9C,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 { NormalizedStoriesSpecifier, Options } from '@storybook/types';\nimport { normalizedPathRelativeTo } from '@ms-cloudpack/path-utilities';\n\n/**\n * Get the stories from the storybook config.\n */\nexport async function listStories(params: { storybookOptions: Options; appPath: string }): Promise<{\n storySpecifiers: NormalizedStoriesSpecifier[];\n /** Actual paths to all story files, relative to `appPath` with leading `./` and forward slashes. */\n resolvedStories: string[];\n}> {\n const { storybookOptions, appPath } = params;\n\n const storySpecifiers = normalizeStories(await storybookOptions.presets.apply('stories', [], storybookOptions), {\n configDir: storybookOptions.configDir,\n workingDir: appPath,\n });\n\n const resolvedStories = (\n await Promise.all(\n storySpecifiers.map(({ directory, files }) => {\n const pattern = path.join(directory, files);\n const absolutePattern = path.isAbsolute(pattern) ? pattern : path.join(appPath, pattern);\n\n return glob(slash(absolutePattern), {\n ...commonGlobOptions(absolutePattern),\n followSymbolicLinks: true,\n });\n }),\n )\n )\n .flat()\n .map((story) => normalizedPathRelativeTo(appPath, story))\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 return { storySpecifiers, resolvedStories };\n}\n"]}
@@ -1,6 +1,6 @@
1
+ import type { PartialContext } from '@ms-cloudpack/api-server';
2
+ import type { PackageJson } from '@ms-cloudpack/common-types';
1
3
  import type { PreviewAnnotation } from '@storybook/types';
2
- import type { PackageDefinitionsCache } from '@ms-cloudpack/common-types';
3
- import type { Session } from '@ms-cloudpack/api-server';
4
4
  /**
5
5
  * Preview annotations can take several forms, and cloudpack needs them to be
6
6
  * a bit more restrained.
@@ -8,8 +8,8 @@ import type { Session } from '@ms-cloudpack/api-server';
8
8
  * For node_modules, we want bare imports (so cloudpack can process them),
9
9
  * and for files in the user's source, we want URLs absolute relative to project root.
10
10
  */
11
- export declare function processPreviewAnnotation(previewPath: PreviewAnnotation | undefined, context: {
12
- packages: PackageDefinitionsCache;
13
- session: Session;
14
- }): Promise<string>;
11
+ export declare function processPreviewAnnotation(options: {
12
+ previewPath: PreviewAnnotation;
13
+ appDefinition: PackageJson;
14
+ }, context: PartialContext<'packages', 'config'>): Promise<string>;
15
15
  //# sourceMappingURL=processPreviewAnnotation.d.ts.map
@@ -1 +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,4BAA4B,CAAC;AAC1E,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,0BAA0B,CAAC;AAExD;;;;;;GAMG;AACH,wBAAsB,wBAAwB,CAC5C,WAAW,EAAE,iBAAiB,GAAG,SAAS,EAC1C,OAAO,EAAE;IAAE,QAAQ,EAAE,uBAAuB,CAAC;IAAC,OAAO,EAAE,OAAO,CAAA;CAAE,mBAgEjE"}
1
+ {"version":3,"file":"processPreviewAnnotation.d.ts","sourceRoot":"","sources":["../../src/utils/processPreviewAnnotation.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,0BAA0B,CAAC;AAC/D,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,4BAA4B,CAAC;AAI9D,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAG1D;;;;;;GAMG;AACH,wBAAsB,wBAAwB,CAC5C,OAAO,EAAE;IACP,WAAW,EAAE,iBAAiB,CAAC;IAC/B,aAAa,EAAE,WAAW,CAAC;CAC5B,EACD,OAAO,EAAE,cAAc,CAAC,UAAU,EAAE,QAAQ,CAAC,mBA8C9C"}
@@ -1,8 +1,8 @@
1
1
  // based on https://github.com/storybookjs/storybook/blob/v7.6.5/code/builders/builder-vite/src/utils/process-preview-annotation.ts
2
- import path from 'path';
3
- import { slash } from '@ms-cloudpack/path-string-parsing';
2
+ import { normalizeRelativePath, slash } from '@ms-cloudpack/path-string-parsing';
3
+ import { findPackageRoot, normalizedPathRelativeTo } from '@ms-cloudpack/path-utilities';
4
4
  import { stripAbsNodeModulesPath } from '@storybook/core-common';
5
- import { findPackageRoot } from '@ms-cloudpack/path-utilities';
5
+ import path from 'path';
6
6
  /**
7
7
  * Preview annotations can take several forms, and cloudpack needs them to be
8
8
  * a bit more restrained.
@@ -10,62 +10,43 @@ import { findPackageRoot } from '@ms-cloudpack/path-utilities';
10
10
  * For node_modules, we want bare imports (so cloudpack can process them),
11
11
  * and for files in the user's source, we want URLs absolute relative to project root.
12
12
  */
13
- export async function processPreviewAnnotation(previewPath, context) {
13
+ export async function processPreviewAnnotation(options, context) {
14
+ let { previewPath } = options;
14
15
  const { packages, session } = context;
15
16
  const { appPath } = session.config;
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.
17
+ // If entry is an object, take the first, which is the bare (non-absolute) specifier.
18
+ // This is so that webpack can use an absolute path, and continue supporting super-addons in
19
+ // pnp/pnpm without requiring them to re-export their sub-addons as we do in addon-essentials.
22
20
  if (typeof previewPath === 'object') {
23
21
  return previewPath.bare;
24
22
  }
25
- // This should not occur, since we use `.filter(Boolean)` prior to
26
- // calling this function, but this makes typescript happy
27
- if (!previewPath) {
28
- throw new Error('Could not determine path for previewAnnotation');
29
- }
23
+ // Get rid of any extra segments
24
+ previewPath = path.normalize(previewPath);
30
25
  // For addon dependencies that use require.resolve(), we need to convert to a bare path
31
26
  // so that cloudpack will process it as a dependency (cjs -> esm, etc).
27
+ // If this is a dependency in a standard (non-store) layout, take the path after the last
28
+ // node_modules segment.
32
29
  // TODO: Evaluate if searching for node_modules in a yarn pnp environment is correct
33
30
  if (previewPath.includes('node_modules') && !previewPath.includes('.store')) {
34
31
  return stripAbsNodeModulesPath(previewPath);
35
32
  }
36
- // resolve absolute paths relative to project root
37
- const relativePath = path.isAbsolute(previewPath) ? slash(path.relative(appPath, previewPath)) : previewPath;
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(/^\.\//, '')}`);
33
+ // Resolve absolute paths relative to the project root, and normalize to start with ./
34
+ const normalizedPath = path.isAbsolute(previewPath)
35
+ ? normalizedPathRelativeTo(appPath, previewPath)
36
+ : normalizeRelativePath(previewPath);
37
+ if (normalizedPath.startsWith('./')) {
38
+ // For a path within the app package, add the package name.
39
+ return slash(`${options.appDefinition.name}/${normalizedPath.slice(2)}`);
47
40
  }
48
- // If something is outside of root, convert to absolute.
41
+ // For paths outside the app package, find which package it's in, and add that package name.
49
42
  // This can happen with a store installation layout:
50
43
  // /<repo>/node_modules/.store/@storybook-react-virtual-acd5c7bee4/package
51
- if (relativePath.startsWith('../')) {
52
- // Find package and add to root.
53
- const packagePath = findPackageRoot(path.resolve(appPath, relativePath));
54
- if (!packagePath) {
55
- throw new Error(`Could not find package root for ${relativePath}`);
56
- }
57
- const definition = await packages.get(packagePath);
58
- if (!definition) {
59
- throw new Error(`Could not find package definition for ${relativePath}`);
60
- }
61
- return slash(`${definition.name}/${path.relative(packagePath, path.resolve(appPath, relativePath))}`);
62
- }
63
- // At this point, it must be relative to the root but not start with a ./ or ../
64
- // Add package root to relative paths.
65
- const definition = await packages.get(appPath);
66
- if (!definition) {
67
- throw new Error(`Could not find package definition for ${appPath}`);
44
+ const absPath = path.resolve(appPath, normalizedPath);
45
+ const packagePath = findPackageRoot(absPath);
46
+ if (!packagePath) {
47
+ throw new Error(`Could not find package root for ${absPath}`);
68
48
  }
69
- return slash(`${definition.name}/${relativePath}`);
49
+ const definition = await packages.get(packagePath);
50
+ return slash(`${definition.name}/${path.relative(packagePath, absPath)}`);
70
51
  }
71
52
  //# sourceMappingURL=processPreviewAnnotation.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"processPreviewAnnotation.js","sourceRoot":"","sources":["../../src/utils/processPreviewAnnotation.ts"],"names":[],"mappings":"AAAA,mIAAmI;AAGnI,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAE,KAAK,EAAE,MAAM,mCAAmC,CAAC;AAC1D,OAAO,EAAE,uBAAuB,EAAE,MAAM,wBAAwB,CAAC;AACjE,OAAO,EAAE,eAAe,EAAE,MAAM,8BAA8B,CAAC;AAI/D;;;;;;GAMG;AACH,MAAM,CAAC,KAAK,UAAU,wBAAwB,CAC5C,WAA0C,EAC1C,OAAgE;IAEhE,MAAM,EAAE,QAAQ,EAAE,OAAO,EAAE,GAAG,OAAO,CAAC;IACtC,MAAM,EAAE,OAAO,EAAE,GAAG,OAAO,CAAC,MAAM,CAAC;IACnC,sDAAsD;IACtD,iCAAiC;IACjC,wDAAwD;IACxD,uDAAuD;IACvD,wDAAwD;IACxD,uBAAuB;IACvB,IAAI,OAAO,WAAW,KAAK,QAAQ,EAAE,CAAC;QACpC,OAAO,WAAW,CAAC,IAAI,CAAC;IAC1B,CAAC;IAED,kEAAkE;IAClE,yDAAyD;IACzD,IAAI,CAAC,WAAW,EAAE,CAAC;QACjB,MAAM,IAAI,KAAK,CAAC,gDAAgD,CAAC,CAAC;IACpE,CAAC;IAED,uFAAuF;IACvF,uEAAuE;IACvE,oFAAoF;IACpF,IAAI,WAAW,CAAC,QAAQ,CAAC,cAAc,CAAC,IAAI,CAAC,WAAW,CAAC,QAAQ,CAAC,QAAQ,CAAC,EAAE,CAAC;QAC5E,OAAO,uBAAuB,CAAC,WAAW,CAAC,CAAC;IAC9C,CAAC;IAED,kDAAkD;IAClD,MAAM,YAAY,GAAG,IAAI,CAAC,UAAU,CA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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 path 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/common-types';\nimport type { Session } from '@ms-cloudpack/api-server';\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 */\nexport async function processPreviewAnnotation(\n previewPath: PreviewAnnotation | undefined,\n context: { packages: PackageDefinitionsCache; session: Session },\n) {\n const { packages, session } = context;\n const { appPath } = session.config;\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 previewPath === 'object') {\n return previewPath.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 (!previewPath) {\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 (previewPath.includes('node_modules') && !previewPath.includes('.store')) {\n return stripAbsNodeModulesPath(previewPath);\n }\n\n // resolve absolute paths relative to project root\n const relativePath = path.isAbsolute(previewPath) ? slash(path.relative(appPath, previewPath)) : previewPath;\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.\n // This can happen with a store installation layout:\n // /<repo>/node_modules/.store/@storybook-react-virtual-acd5c7bee4/package\n if (relativePath.startsWith('../')) {\n // Find package and add to root.\n const packagePath = findPackageRoot(path.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}/${path.relative(packagePath, path.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"]}
1
+ {"version":3,"file":"processPreviewAnnotation.js","sourceRoot":"","sources":["../../src/utils/processPreviewAnnotation.ts"],"names":[],"mappings":"AAAA,mIAAmI;AAInI,OAAO,EAAE,qBAAqB,EAAE,KAAK,EAAE,MAAM,mCAAmC,CAAC;AACjF,OAAO,EAAE,eAAe,EAAE,wBAAwB,EAAE,MAAM,8BAA8B,CAAC;AACzF,OAAO,EAAE,uBAAuB,EAAE,MAAM,wBAAwB,CAAC;AAEjE,OAAO,IAAI,MAAM,MAAM,CAAC;AAExB;;;;;;GAMG;AACH,MAAM,CAAC,KAAK,UAAU,wBAAwB,CAC5C,OAGC,EACD,OAA6C;IAE7C,IAAI,EAAE,W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,IAAI,KAAK,CAAC,mCAAmC,OAAO,EAAE,CAAC,CAAC;IAChE,CAAC;IACD,MAAM,UAAU,GAAG,MAAM,QAAQ,CAAC,GAAG,CAAC,WAAW,CAAC,CAAC;IACnD,OAAO,KAAK,CAAC,GAAG,UAAU,CAAC,IAAI,IAAI,IAAI,CAAC,QAAQ,CAAC,WAAW,EAAE,OAAO,CAAC,EAAE,CAAC,CAAC;AAC5E,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 { PartialContext } from '@ms-cloudpack/api-server';\nimport type { PackageJson } from '@ms-cloudpack/common-types';\nimport { normalizeRelativePath, slash } from '@ms-cloudpack/path-string-parsing';\nimport { findPackageRoot, normalizedPathRelativeTo } from '@ms-cloudpack/path-utilities';\nimport { stripAbsNodeModulesPath } from '@storybook/core-common';\nimport type { PreviewAnnotation } from '@storybook/types';\nimport path from 'path';\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 */\nexport async function processPreviewAnnotation(\n options: {\n previewPath: PreviewAnnotation;\n appDefinition: PackageJson;\n },\n context: PartialContext<'packages', 'config'>,\n) {\n let { previewPath } = options;\n const { packages, session } = context;\n const { appPath } = session.config;\n\n // If entry is an object, take the first, which is the bare (non-absolute) specifier.\n // This is so that webpack can use an absolute path, and continue supporting super-addons in\n // pnp/pnpm without requiring them to re-export their sub-addons as we do in addon-essentials.\n if (typeof previewPath === 'object') {\n return previewPath.bare;\n }\n\n // Get rid of any extra segments\n previewPath = path.normalize(previewPath);\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\n // If this is a dependency in a standard (non-store) layout, take the path after the last\n // node_modules segment.\n // TODO: Evaluate if searching for node_modules in a yarn pnp environment is correct\n if (previewPath.includes('node_modules') && !previewPath.includes('.store')) {\n return stripAbsNodeModulesPath(previewPath);\n }\n\n // Resolve absolute paths relative to the project root, and normalize to start with ./\n const normalizedPath = path.isAbsolute(previewPath)\n ? normalizedPathRelativeTo(appPath, previewPath)\n : normalizeRelativePath(previewPath);\n\n if (normalizedPath.startsWith('./')) {\n // For a path within the app package, add the package name.\n return slash(`${options.appDefinition.name}/${normalizedPath.slice(2)}`);\n }\n\n // For paths outside the app package, find which package it's in, and add that package name.\n // This can happen with a store installation layout:\n // /<repo>/node_modules/.store/@storybook-react-virtual-acd5c7bee4/package\n const absPath = path.resolve(appPath, normalizedPath);\n const packagePath = findPackageRoot(absPath);\n if (!packagePath) {\n throw new Error(`Could not find package root for ${absPath}`);\n }\n const definition = await packages.get(packagePath);\n return slash(`${definition.name}/${path.relative(packagePath, absPath)}`);\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ms-cloudpack/storybook-builder",
3
- "version": "0.5.4",
3
+ "version": "0.5.6",
4
4
  "description": "A tool for building storybook bundles for the cloudpack ecosystem.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -22,15 +22,15 @@
22
22
  "lint": "cloudpack-scripts lint"
23
23
  },
24
24
  "dependencies": {
25
- "@ms-cloudpack/api-server": "^0.49.1",
26
- "@ms-cloudpack/app-server": "^0.15.1",
27
- "@ms-cloudpack/common-types": "^0.18.0",
28
- "@ms-cloudpack/config": "^0.27.0",
29
- "@ms-cloudpack/create-express-app": "^1.8.1",
30
- "@ms-cloudpack/overlay": "^0.17.54",
31
- "@ms-cloudpack/package-utilities": "^9.0.5",
25
+ "@ms-cloudpack/api-server": "^0.50.0",
26
+ "@ms-cloudpack/app-server": "^0.15.3",
27
+ "@ms-cloudpack/common-types": "^0.19.1",
28
+ "@ms-cloudpack/config": "^0.27.2",
29
+ "@ms-cloudpack/create-express-app": "^1.8.3",
30
+ "@ms-cloudpack/overlay": "^0.17.56",
31
+ "@ms-cloudpack/package-utilities": "^10.0.1",
32
32
  "@ms-cloudpack/path-string-parsing": "^1.2.4",
33
- "@ms-cloudpack/path-utilities": "^2.7.36",
33
+ "@ms-cloudpack/path-utilities": "^2.7.38",
34
34
  "@ms-cloudpack/task-reporter": "^0.14.4",
35
35
  "@ms-cloudpack/telemetry": "^0.6.1",
36
36
  "@storybook/core-common": "^7.0.0",
@@ -42,7 +42,7 @@
42
42
  "ts-dedent": "^2.2.0"
43
43
  },
44
44
  "devDependencies": {
45
- "@ms-cloudpack/common-types": "^0.18.0",
45
+ "@ms-cloudpack/common-types": "^0.19.1",
46
46
  "@ms-cloudpack/eslint-plugin-internal": "^0.0.1",
47
47
  "@ms-cloudpack/scripts": "^0.0.1",
48
48
  "@storybook/types": "^7.0.0"
@@ -1,2 +0,0 @@
1
- export declare function getNodeModuleDir(moduleName: string): string;
2
- //# sourceMappingURL=getNodeModuleDir.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"getNodeModuleDir.d.ts","sourceRoot":"","sources":["../src/getNodeModuleDir.ts"],"names":[],"mappings":"AAGA,wBAAgB,gBAAgB,CAAC,UAAU,EAAE,MAAM,GAAG,MAAM,CAG3D"}
@@ -1,7 +0,0 @@
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
@@ -1 +0,0 @@
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"]}