@storybook/builder-vite 10.6.0 → 11.0.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,35 +1,26 @@
1
- import CJS_COMPAT_NODE_URL_mnt6r7wfqrl from 'node:url';
2
- import CJS_COMPAT_NODE_PATH_mnt6r7wfqrl from 'node:path';
3
- import CJS_COMPAT_NODE_MODULE_mnt6r7wfqrl from "node:module";
1
+ import CJS_COMPAT_NODE_URL_h8sjn8ghzhs from 'node:url';
2
+ import CJS_COMPAT_NODE_PATH_h8sjn8ghzhs from 'node:path';
3
+ import CJS_COMPAT_NODE_MODULE_h8sjn8ghzhs from "node:module";
4
4
 
5
- var __filename = CJS_COMPAT_NODE_URL_mnt6r7wfqrl.fileURLToPath(import.meta.url);
6
- var __dirname = CJS_COMPAT_NODE_PATH_mnt6r7wfqrl.dirname(__filename);
7
- var require = CJS_COMPAT_NODE_MODULE_mnt6r7wfqrl.createRequire(import.meta.url);
5
+ var __filename = CJS_COMPAT_NODE_URL_h8sjn8ghzhs.fileURLToPath(import.meta.url);
6
+ var __dirname = CJS_COMPAT_NODE_PATH_h8sjn8ghzhs.dirname(__filename);
7
+ var require = CJS_COMPAT_NODE_MODULE_h8sjn8ghzhs.createRequire(import.meta.url);
8
8
 
9
9
  // ------------------------------------------------------------
10
10
  // end of CJS compatibility banner, injected by Storybook's esbuild configuration
11
11
  // ------------------------------------------------------------
12
12
  import {
13
- SB_VIRTUAL_FILES,
14
- SB_VIRTUAL_FILE_IDS,
15
- VIRTUAL_ID,
16
13
  __commonJS,
17
14
  __toESM,
18
- genDynamicImport,
19
- genObjectFromRawEntries,
20
- getOriginalVirtualModuleId,
21
- getResolvedVirtualModuleId,
22
- getUniqueImportPaths,
23
- join,
24
- normalize,
25
- relative,
26
- viteCorePlugins
27
- } from "./_node-chunks/chunk-P2UGKA2Z.js";
15
+ bundlerOptionsKey,
16
+ commonConfig,
17
+ normalize
18
+ } from "./_node-chunks/chunk-QUB7HIJP.js";
28
19
 
29
20
  // ../../../node_modules/picocolors/picocolors.js
30
21
  var require_picocolors = __commonJS({
31
22
  "../../../node_modules/picocolors/picocolors.js"(exports, module) {
32
- var p = process || {}, argv = p.argv || [], env2 = p.env || {}, isColorSupported = !(env2.NO_COLOR || argv.includes("--no-color")) && (!!env2.FORCE_COLOR || argv.includes("--color") || p.platform === "win32" || (p.stdout || {}).isTTY && env2.TERM !== "dumb" || !!env2.CI), formatter = (open, close, replace = open) => (input) => {
23
+ var p = process || {}, argv = p.argv || [], env = p.env || {}, isColorSupported = !(env.NO_COLOR || argv.includes("--no-color")) && (!!env.FORCE_COLOR || argv.includes("--color") || p.platform === "win32" || (p.stdout || {}).isTTY && env.TERM !== "dumb" || !!env.CI), formatter = (open, close, replace = open) => (input) => {
33
24
  let string = "" + input, index = string.indexOf(close, open.length);
34
25
  return ~index ? open + replaceClose(string, close, replace, index) + close : open + string + close;
35
26
  }, replaceClose = (string, close, replace, index) => {
@@ -92,12 +83,12 @@ var require_picocolors = __commonJS({
92
83
 
93
84
  // src/index.ts
94
85
  import { readFile } from "node:fs/promises";
95
- import { fileURLToPath as fileURLToPath3 } from "node:url";
86
+ import { fileURLToPath } from "node:url";
96
87
  import { NoStatsForViteDevError } from "storybook/internal/server-errors";
97
88
 
98
89
  // src/build.ts
99
90
  import { logger as logger2 } from "storybook/internal/node-logger";
100
- import { dedent as dedent3 } from "ts-dedent";
91
+ import { dedent } from "ts-dedent";
101
92
 
102
93
  // src/logger.ts
103
94
  var import_picocolors = __toESM(require_picocolors(), 1);
@@ -122,23 +113,6 @@ async function hasVitePlugins(plugins, names) {
122
113
  return !1;
123
114
  }
124
115
 
125
- // src/utils/vite-features.ts
126
- import { version } from "vite";
127
- var shouldUseRolldownOptions = () => {
128
- try {
129
- return Number(version.split(".")[0]) >= 8;
130
- } catch {
131
- return !1;
132
- }
133
- }, bundlerOptionsKey = shouldUseRolldownOptions() ? "rolldownOptions" : "rollupOptions";
134
- function ensureRolldownOptions(config) {
135
- if (!shouldUseRolldownOptions())
136
- return;
137
- config.build ??= {};
138
- let rolldown = config.build.rolldownOptions ??= {}, output = rolldown.output ??= {};
139
- output.strictExecutionOrder = !0;
140
- }
141
-
142
116
  // src/utils/without-vite-plugins.ts
143
117
  var withoutVitePlugins = async (plugins = [], namesToRemove) => {
144
118
  let result = [], resolvedPlugins = await Promise.all(plugins);
@@ -147,1494 +121,6 @@ var withoutVitePlugins = async (plugins = [], namesToRemove) => {
147
121
  return result;
148
122
  };
149
123
 
150
- // src/vite-config.ts
151
- import { resolve as resolve3 } from "node:path";
152
- import { getBuilderOptions, resolvePathInStorybookCache } from "storybook/internal/common";
153
-
154
- // src/plugins/code-generator-plugin.ts
155
- import { readFileSync } from "node:fs";
156
- import { fileURLToPath as fileURLToPath2 } from "node:url";
157
-
158
- // ../../core/src/shared/utils/module.ts
159
- import { fileURLToPath, pathToFileURL } from "node:url";
160
-
161
- // ../../../node_modules/exsolve/dist/index.mjs
162
- import assert from "node:assert";
163
- import v8 from "node:v8";
164
- import { format, inspect } from "node:util";
165
- var own$1 = {}.hasOwnProperty, classRegExp = /^([A-Z][a-z\d]*)+$/, kTypes = /* @__PURE__ */ new Set([
166
- "string",
167
- "function",
168
- "number",
169
- "object",
170
- "Function",
171
- "Object",
172
- "boolean",
173
- "bigint",
174
- "symbol"
175
- ]), messages = /* @__PURE__ */ new Map(), nodeInternalPrefix = "__node_internal_", userStackTraceLimit;
176
- function formatList(array, type = "and") {
177
- return array.length < 3 ? array.join(` ${type} `) : `${array.slice(0, -1).join(", ")}, ${type} ${array.at(-1)}`;
178
- }
179
- function createError(sym, value, constructor) {
180
- return messages.set(sym, value), makeNodeErrorWithCode(constructor, sym);
181
- }
182
- function makeNodeErrorWithCode(Base, key) {
183
- return function(...parameters) {
184
- let limit = Error.stackTraceLimit;
185
- isErrorStackTraceLimitWritable() && (Error.stackTraceLimit = 0);
186
- let error = new Base();
187
- isErrorStackTraceLimitWritable() && (Error.stackTraceLimit = limit);
188
- let message = getMessage(key, parameters, error);
189
- return Object.defineProperties(error, {
190
- message: {
191
- value: message,
192
- enumerable: !1,
193
- writable: !0,
194
- configurable: !0
195
- },
196
- toString: {
197
- value() {
198
- return `${this.name} [${key}]: ${this.message}`;
199
- },
200
- enumerable: !1,
201
- writable: !0,
202
- configurable: !0
203
- }
204
- }), captureLargerStackTrace(error), error.code = key, error;
205
- };
206
- }
207
- function isErrorStackTraceLimitWritable() {
208
- try {
209
- if (v8.startupSnapshot.isBuildingSnapshot()) return !1;
210
- } catch {
211
- }
212
- let desc = Object.getOwnPropertyDescriptor(Error, "stackTraceLimit");
213
- return desc === void 0 ? Object.isExtensible(Error) : own$1.call(desc, "writable") && desc.writable !== void 0 ? desc.writable : desc.set !== void 0;
214
- }
215
- function hideStackFrames(wrappedFunction) {
216
- let hidden = nodeInternalPrefix + wrappedFunction.name;
217
- return Object.defineProperty(wrappedFunction, "name", { value: hidden }), wrappedFunction;
218
- }
219
- var captureLargerStackTrace = hideStackFrames(function(error) {
220
- let stackTraceLimitIsWritable = isErrorStackTraceLimitWritable();
221
- return stackTraceLimitIsWritable && (userStackTraceLimit = Error.stackTraceLimit, Error.stackTraceLimit = Number.POSITIVE_INFINITY), Error.captureStackTrace(error), stackTraceLimitIsWritable && (Error.stackTraceLimit = userStackTraceLimit), error;
222
- });
223
- function getMessage(key, parameters, self) {
224
- let message = messages.get(key);
225
- if (assert.ok(message !== void 0, "expected `message` to be found"), typeof message == "function")
226
- return assert.ok(message.length <= parameters.length, `Code: ${key}; The provided arguments length (${parameters.length}) does not match the required ones (${message.length}).`), Reflect.apply(message, self, parameters);
227
- let regex = /%[dfijoOs]/g, expectedLength = 0;
228
- for (; regex.exec(message) !== null; ) expectedLength++;
229
- return assert.ok(expectedLength === parameters.length, `Code: ${key}; The provided arguments length (${parameters.length}) does not match the required ones (${expectedLength}).`), parameters.length === 0 ? message : (parameters.unshift(message), Reflect.apply(format, null, parameters));
230
- }
231
- function determineSpecificType(value) {
232
- if (value == null) return String(value);
233
- if (typeof value == "function" && value.name) return `function ${value.name}`;
234
- if (typeof value == "object")
235
- return value.constructor && value.constructor.name ? `an instance of ${value.constructor.name}` : `${inspect(value, { depth: -1 })}`;
236
- let inspected = inspect(value, { colors: !1 });
237
- return inspected.length > 28 && (inspected = `${inspected.slice(0, 25)}...`), `type ${typeof value} (${inspected})`;
238
- }
239
- var ERR_INVALID_ARG_TYPE = createError("ERR_INVALID_ARG_TYPE", (name, expected, actual) => {
240
- assert.ok(typeof name == "string", "'name' must be a string"), Array.isArray(expected) || (expected = [expected]);
241
- let message = "The ";
242
- if (name.endsWith(" argument")) message += `${name} `;
243
- else {
244
- let type = name.includes(".") ? "property" : "argument";
245
- message += `"${name}" ${type} `;
246
- }
247
- message += "must be ";
248
- let types = [], instances = [], other = [];
249
- for (let value of expected)
250
- assert.ok(typeof value == "string", "All expected entries have to be of type string"), kTypes.has(value) ? types.push(value.toLowerCase()) : classRegExp.exec(value) === null ? (assert.ok(value !== "object", 'The value "object" should be written as "Object"'), other.push(value)) : instances.push(value);
251
- if (instances.length > 0) {
252
- let pos = types.indexOf("object");
253
- pos !== -1 && (types.slice(pos, 1), instances.push("Object"));
254
- }
255
- return types.length > 0 && (message += `${types.length > 1 ? "one of type" : "of type"} ${formatList(types, "or")}`, (instances.length > 0 || other.length > 0) && (message += " or ")), instances.length > 0 && (message += `an instance of ${formatList(instances, "or")}`, other.length > 0 && (message += " or ")), other.length > 0 && (other.length > 1 ? message += `one of ${formatList(other, "or")}` : (other[0]?.toLowerCase() !== other[0] && (message += "an "), message += `${other[0]}`)), message += `. Received ${determineSpecificType(actual)}`, message;
256
- }, TypeError), ERR_INVALID_MODULE_SPECIFIER = createError(
257
- "ERR_INVALID_MODULE_SPECIFIER",
258
- /**
259
- * @param {string} request
260
- * @param {string} reason
261
- * @param {string} [base]
262
- */
263
- (request, reason, base) => `Invalid module "${request}" ${reason}${base ? ` imported from ${base}` : ""}`,
264
- TypeError
265
- ), ERR_INVALID_PACKAGE_CONFIG = createError("ERR_INVALID_PACKAGE_CONFIG", (path$1, base, message) => `Invalid package config ${path$1}${base ? ` while importing ${base}` : ""}${message ? `. ${message}` : ""}`, Error), ERR_INVALID_PACKAGE_TARGET = createError("ERR_INVALID_PACKAGE_TARGET", (packagePath, key, target, isImport = !1, base) => {
266
- let relatedError = typeof target == "string" && !isImport && target.length > 0 && !target.startsWith("./");
267
- return key === "." ? (assert.ok(isImport === !1), `Invalid "exports" main target ${JSON.stringify(target)} defined in the package config ${packagePath}package.json${base ? ` imported from ${base}` : ""}${relatedError ? '; targets must start with "./"' : ""}`) : `Invalid "${isImport ? "imports" : "exports"}" target ${JSON.stringify(target)} defined for '${key}' in the package config ${packagePath}package.json${base ? ` imported from ${base}` : ""}${relatedError ? '; targets must start with "./"' : ""}`;
268
- }, Error), ERR_MODULE_NOT_FOUND = createError("ERR_MODULE_NOT_FOUND", (path$1, base, exactUrl = !1) => `Cannot find ${exactUrl ? "module" : "package"} '${path$1}' imported from ${base}`, Error), ERR_NETWORK_IMPORT_DISALLOWED = createError("ERR_NETWORK_IMPORT_DISALLOWED", "import of '%s' by %s is not supported: %s", Error), ERR_PACKAGE_IMPORT_NOT_DEFINED = createError("ERR_PACKAGE_IMPORT_NOT_DEFINED", (specifier, packagePath, base) => `Package import specifier "${specifier}" is not defined${packagePath ? ` in package ${packagePath || ""}package.json` : ""} imported from ${base}`, TypeError), ERR_PACKAGE_PATH_NOT_EXPORTED = createError(
269
- "ERR_PACKAGE_PATH_NOT_EXPORTED",
270
- /**
271
- * @param {string} packagePath
272
- * @param {string} subpath
273
- * @param {string} [base]
274
- */
275
- (packagePath, subpath, base) => subpath === "." ? `No "exports" main defined in ${packagePath}package.json${base ? ` imported from ${base}` : ""}` : `Package subpath '${subpath}' is not defined by "exports" in ${packagePath}package.json${base ? ` imported from ${base}` : ""}`,
276
- Error
277
- ), ERR_UNSUPPORTED_DIR_IMPORT = createError("ERR_UNSUPPORTED_DIR_IMPORT", "Directory import '%s' is not supported resolving ES modules imported from %s", Error), ERR_UNSUPPORTED_RESOLVE_REQUEST = createError("ERR_UNSUPPORTED_RESOLVE_REQUEST", 'Failed to resolve module specifier "%s" from "%s": Invalid relative URL or base scheme is not hierarchical.', TypeError), ERR_UNKNOWN_FILE_EXTENSION = createError("ERR_UNKNOWN_FILE_EXTENSION", (extension, path$1) => `Unknown file extension "${extension}" for ${path$1}`, TypeError), ERR_INVALID_ARG_VALUE = createError("ERR_INVALID_ARG_VALUE", (name, value, reason = "is invalid") => {
278
- let inspected = inspect(value);
279
- return inspected.length > 128 && (inspected = `${inspected.slice(0, 128)}...`), `The ${name.includes(".") ? "property" : "argument"} '${name}' ${reason}. Received ${inspected}`;
280
- }, TypeError), hasOwnProperty$1 = {}.hasOwnProperty;
281
- var hasOwnProperty = {}.hasOwnProperty;
282
- var RegExpPrototypeSymbolReplace = RegExp.prototype[Symbol.replace], own = {}.hasOwnProperty;
283
- var isWindows = process.platform === "win32", globalCache = globalThis.__EXSOLVE_CACHE__ ||= /* @__PURE__ */ new Map();
284
-
285
- // ../../core/src/shared/utils/module.ts
286
- var importMetaResolve = (...args) => typeof import.meta.resolve != "function" && process.env.VITEST === "true" ? (console.warn(
287
- "importMetaResolve from within Storybook is being used in a Vitest test, but it shouldn't be. Please report this at https://github.com/storybookjs/storybook/issues/new?template=bug_report.yml"
288
- ), pathToFileURL(args[0]).href) : import.meta.resolve(...args);
289
-
290
- // src/codegen-importfn-script.ts
291
- import { dedent } from "ts-dedent";
292
- function generateImportFnScriptCode(index) {
293
- let objectEntries = getUniqueImportPaths(index).map(
294
- (importPath) => {
295
- if (importPath.startsWith("virtual:"))
296
- return [importPath, genDynamicImport(importPath)];
297
- let relativePath = normalize(relative(process.cwd(), importPath)), normalizedRelativePath = relativePath.startsWith("../") ? relativePath : `./${relativePath}`, absolutePath = normalize(join(process.cwd(), importPath));
298
- return [normalizedRelativePath, genDynamicImport(absolutePath)];
299
- }
300
- );
301
- return dedent`
302
- const importers = ${genObjectFromRawEntries(objectEntries)};
303
-
304
- export async function importFn(path) {
305
- return await importers[path]();
306
- }
307
- `;
308
- }
309
-
310
- // src/codegen-modern-iframe-script.ts
311
- import { getFrameworkName } from "storybook/internal/common";
312
- import { STORY_HOT_UPDATED } from "storybook/internal/core-events";
313
- import { dedent as dedent2 } from "ts-dedent";
314
- async function generateModernIframeScriptCode(options) {
315
- let frameworkName = await getFrameworkName(options);
316
- return generateModernIframeScriptCodeFromPreviews({
317
- frameworkName
318
- });
319
- }
320
- async function generateModernIframeScriptCodeFromPreviews(options) {
321
- let { frameworkName } = options, generateHMRHandler = () => frameworkName === "@storybook/web-components-vite" ? dedent2`
322
- if (import.meta.hot) {
323
- import.meta.hot.decline();
324
- }`.trim() : dedent2`
325
- if (import.meta.hot) {
326
- import.meta.hot.on('vite:afterUpdate', () => {
327
- window.__STORYBOOK_PREVIEW__.channel.emit('${STORY_HOT_UPDATED}');
328
- });
329
-
330
- import.meta.hot.accept('${SB_VIRTUAL_FILES.VIRTUAL_STORIES_FILE}', (newModule) => {
331
- // importFn has changed so we need to patch the new one in
332
- window.__STORYBOOK_PREVIEW__.onStoriesChanged({ importFn: newModule.importFn });
333
- });
334
- }`.trim();
335
- return dedent2`
336
- import { setup } from 'storybook/internal/preview/runtime';
337
-
338
- import '${SB_VIRTUAL_FILES.VIRTUAL_ADDON_SETUP_FILE}';
339
-
340
- setup();
341
-
342
- import { PreviewWeb } from 'storybook/preview-api';
343
- import { importFn } from '${SB_VIRTUAL_FILES.VIRTUAL_STORIES_FILE}';
344
- import { getProjectAnnotations } from '${VIRTUAL_ID}';
345
-
346
- window.__STORYBOOK_PREVIEW__ = window.__STORYBOOK_PREVIEW__ || new PreviewWeb(importFn, getProjectAnnotations);
347
-
348
- window.__STORYBOOK_STORY_STORE__ = window.__STORYBOOK_STORY_STORE__ || window.__STORYBOOK_PREVIEW__.storyStore;
349
-
350
- ${generateHMRHandler()};
351
-
352
- `.trim();
353
- }
354
-
355
- // src/codegen-set-addon-channel.ts
356
- async function generateAddonSetupCode() {
357
- return `
358
- import { createBrowserChannel } from 'storybook/internal/channels';
359
- import { addons } from 'storybook/preview-api';
360
-
361
- const channel = createBrowserChannel({ page: 'preview' });
362
- addons.setChannel(channel);
363
-
364
- if (window.CONFIG_TYPE === 'DEVELOPMENT'){
365
- window.__STORYBOOK_SERVER_CHANNEL__ = channel;
366
- }
367
- `.trim();
368
- }
369
-
370
- // src/transform-iframe-html.ts
371
- import { normalizeStories } from "storybook/internal/common";
372
- async function transformIframeHtml(html, options) {
373
- let { configType, features, presets } = options, build3 = await presets.apply("build"), frameworkOptions = await presets.apply("frameworkOptions"), headHtmlSnippet = await presets.apply("previewHead"), bodyHtmlSnippet = await presets.apply("previewBody"), logLevel = await presets.apply("logLevel", void 0), docsOptions = await presets.apply("docs"), tagsOptions = await presets.apply("tags"), coreOptions = await presets.apply("core"), stories = normalizeStories(await options.presets.apply("stories", [], options), {
374
- configDir: options.configDir,
375
- workingDir: process.cwd()
376
- }).map((specifier) => ({
377
- ...specifier,
378
- importPathMatcher: specifier.importPathMatcher.source
379
- })), otherGlobals = {
380
- ...build3?.test?.disableBlocks ? { __STORYBOOK_BLOCKS_EMPTY_MODULE__: {} } : {}
381
- }, transformedHtml = html.replace("[CONFIG_TYPE HERE]", configType || "").replace("[LOGLEVEL HERE]", logLevel || "").replace("'[FRAMEWORK_OPTIONS HERE]'", JSON.stringify(frameworkOptions)).replace(
382
- "('OTHER_GLOBALS HERE');",
383
- Object.entries(otherGlobals).map(([k, v]) => `window["${k}"] = ${JSON.stringify(v)};`).join("")
384
- ).replace(
385
- "'[CHANNEL_OPTIONS HERE]'",
386
- JSON.stringify(coreOptions && coreOptions.channelOptions ? coreOptions.channelOptions : {})
387
- ).replace("'[FEATURES HERE]'", JSON.stringify(features || {})).replace("'[STORIES HERE]'", JSON.stringify(stories || {})).replace("'[DOCS_OPTIONS HERE]'", JSON.stringify(docsOptions || {})).replace("'[TAGS_OPTIONS HERE]'", JSON.stringify(tagsOptions || {})).replace("<!-- [HEAD HTML SNIPPET HERE] -->", headHtmlSnippet || "").replace("<!-- [BODY HTML SNIPPET HERE] -->", bodyHtmlSnippet || "");
388
- return configType === "DEVELOPMENT" ? transformedHtml.replace(
389
- "virtual:/@storybook/builder-vite/vite-app.js",
390
- `/@id/__x00__${SB_VIRTUAL_FILES.VIRTUAL_APP_FILE}`
391
- ) : transformedHtml;
392
- }
393
-
394
- // src/plugins/code-generator-plugin.ts
395
- function codeGeneratorPlugin(options) {
396
- let iframePath = fileURLToPath2(importMetaResolve("@storybook/builder-vite/input/iframe.html")), iframeId, storyIndexGeneratorPromise = options.presets.apply("storyIndexGenerator");
397
- return {
398
- name: "storybook:code-generator-plugin",
399
- enforce: "pre",
400
- async configureServer(server2) {
401
- (await storyIndexGeneratorPromise).onInvalidated(() => {
402
- server2.watcher.emit(
403
- "change",
404
- getResolvedVirtualModuleId(SB_VIRTUAL_FILES.VIRTUAL_STORIES_FILE)
405
- );
406
- });
407
- },
408
- config(config, { command }) {
409
- if (command === "build") {
410
- config.build || (config.build = {});
411
- let build3 = config.build;
412
- build3[bundlerOptionsKey] = {
413
- ...build3[bundlerOptionsKey],
414
- input: iframePath
415
- }, ensureRolldownOptions(config);
416
- }
417
- },
418
- configResolved(config) {
419
- iframeId = `${config.root}/iframe.html`;
420
- },
421
- resolveId(source) {
422
- if (SB_VIRTUAL_FILE_IDS.includes(source))
423
- return getResolvedVirtualModuleId(source);
424
- if (source === iframePath)
425
- return iframeId;
426
- },
427
- async load(id) {
428
- switch (id) {
429
- case getResolvedVirtualModuleId(SB_VIRTUAL_FILES.VIRTUAL_STORIES_FILE): {
430
- let index = await (await storyIndexGeneratorPromise)?.getIndex();
431
- return generateImportFnScriptCode(index);
432
- }
433
- case getResolvedVirtualModuleId(SB_VIRTUAL_FILES.VIRTUAL_ADDON_SETUP_FILE):
434
- return generateAddonSetupCode();
435
- case getResolvedVirtualModuleId(SB_VIRTUAL_FILES.VIRTUAL_APP_FILE):
436
- return generateModernIframeScriptCode(options);
437
- case iframeId:
438
- return readFileSync(
439
- fileURLToPath2(importMetaResolve("@storybook/builder-vite/input/iframe.html")),
440
- "utf-8"
441
- );
442
- }
443
- },
444
- async transformIndexHtml(html, ctx) {
445
- if (ctx.path === "/iframe.html")
446
- return transformIframeHtml(html, options);
447
- }
448
- };
449
- }
450
-
451
- // ../../../node_modules/es-module-lexer/dist/lexer.js
452
- var ImportType;
453
- (function(A2) {
454
- A2[A2.Static = 1] = "Static", A2[A2.Dynamic = 2] = "Dynamic", A2[A2.ImportMeta = 3] = "ImportMeta", A2[A2.StaticSourcePhase = 4] = "StaticSourcePhase", A2[A2.DynamicSourcePhase = 5] = "DynamicSourcePhase", A2[A2.StaticDeferPhase = 6] = "StaticDeferPhase", A2[A2.DynamicDeferPhase = 7] = "DynamicDeferPhase";
455
- })(ImportType || (ImportType = {}));
456
- var A = new Uint8Array(new Uint16Array([1]).buffer)[0] === 1;
457
- function parse2(E2, g = "@") {
458
- if (!C) return init.then((() => parse2(E2)));
459
- let I = E2.length + 1, w = (C.__heap_base.value || C.__heap_base) + 4 * I - C.memory.buffer.byteLength;
460
- w > 0 && C.memory.grow(Math.ceil(w / 65536));
461
- let K = C.sa(I - 1);
462
- if ((A ? B : Q)(E2, new Uint16Array(C.memory.buffer, K, I)), !C.parse()) throw Object.assign(new Error(`Parse error ${g}:${E2.slice(0, C.e()).split(`
463
- `).length}:${C.e() - E2.lastIndexOf(`
464
- `, C.e() - 1)}`), { idx: C.e() });
465
- let o = [], D = [];
466
- for (; C.ri(); ) {
467
- let A2 = C.is(), Q2 = C.ie(), B2 = C.it(), g2 = C.ai(), I2 = C.id(), w2 = C.ss(), K2 = C.se(), D2;
468
- C.ip() && (D2 = k(E2.slice(I2 === -1 ? A2 - 1 : A2, I2 === -1 ? Q2 + 1 : Q2))), o.push({ n: D2, t: B2, s: A2, e: Q2, ss: w2, se: K2, d: I2, a: g2 });
469
- }
470
- for (; C.re(); ) {
471
- let A2 = C.es(), Q2 = C.ee(), B2 = C.els(), g2 = C.ele(), I2 = E2.slice(A2, Q2), w2 = I2[0], K2 = B2 < 0 ? void 0 : E2.slice(B2, g2), o2 = K2 ? K2[0] : "";
472
- D.push({ s: A2, e: Q2, ls: B2, le: g2, n: w2 === '"' || w2 === "'" ? k(I2) : I2, ln: o2 === '"' || o2 === "'" ? k(K2) : K2 });
473
- }
474
- function k(A2) {
475
- try {
476
- return (0, eval)(A2);
477
- } catch {
478
- }
479
- }
480
- return [o, D, !!C.f(), !!C.ms()];
481
- }
482
- function Q(A2, Q2) {
483
- let B2 = A2.length, C2 = 0;
484
- for (; C2 < B2; ) {
485
- let B3 = A2.charCodeAt(C2);
486
- Q2[C2++] = (255 & B3) << 8 | B3 >>> 8;
487
- }
488
- }
489
- function B(A2, Q2) {
490
- let B2 = A2.length, C2 = 0;
491
- for (; C2 < B2; ) Q2[C2] = A2.charCodeAt(C2++);
492
- }
493
- var C, E = () => {
494
- return A2 = "AGFzbQEAAAABKwhgAX8Bf2AEf39/fwBgAAF/YAAAYAF/AGADf39/AX9gAn9/AX9gA39/fwADMTAAAQECAgICAgICAgICAgICAgICAgIAAwMDBAQAAAUAAAAAAAMDAwAGAAAABwAGAgUEBQFwAQEBBQMBAAEGDwJ/AUHA8gALfwBBwPIACwd6FQZtZW1vcnkCAAJzYQAAAWUAAwJpcwAEAmllAAUCc3MABgJzZQAHAml0AAgCYWkACQJpZAAKAmlwAAsCZXMADAJlZQANA2VscwAOA2VsZQAPAnJpABACcmUAEQFmABICbXMAEwVwYXJzZQAUC19faGVhcF9iYXNlAwEKzkQwaAEBf0EAIAA2AoAKQQAoAtwJIgEgAEEBdGoiAEEAOwEAQQAgAEECaiIANgKECkEAIAA2AogKQQBBADYC4AlBAEEANgLwCUEAQQA2AugJQQBBADYC5AlBAEEANgL4CUEAQQA2AuwJIAEL0wEBA39BACgC8AkhBEEAQQAoAogKIgU2AvAJQ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CsAogAC8BAiIADQAMAgsLIAAhAgsgAkH//wNxC6sBAQR/AkACQEEAKAKwCiICLwEAIgNB4QBGDQAgASEEIAAhBQwBC0EAIAJBBGo2ArAKQQEQKSECQQAoArAKIQUCQAJAIAJBIkYNACACQSdGDQAgAhAsGkEAKAKwCiEEDAELIAIQGkEAQQAoArAKQQJqIgQ2ArAKC0EBECkhA0EAKAKwCiECCwJAIAIgBUYNACAFIARBACAAIAAgAUYiAhtBACABIAIbEAILIAMLcgEEf0EAKAKwCiEAQQAoArQKIQECQAJAA0AgAEECaiECIAAgAU8NAQJAAkAgAi8BACIDQaR/ag4CAQQACyACIQAgA0F2ag4EAgEBAgELIABBBGohAAwACwtBACACNgKwChAlQQAPC0EAIAI2ArAKQd0AC0kBA39BACEDAkAgAkUNAAJAA0AgAC0AACIEIAEtAAAiBUcNASABQQFqIQEgAEEBaiEAIAJBf2oiAg0ADAILCyAEIAVrIQMLIAMLC+wBAgBBgAgLzgEAAHgAcABvAHIAdABtAHAAbwByAHQAZgBvAHIAZQB0AGEAbwB1AHIAYwBlAHIAbwBtAHUAbgBjAHQAaQBvAG4AcwBzAGUAcgB0AHYAbwB5AGkAZQBkAGUAbABlAGMAbwBuAHQAaQBuAGkAbgBzAHQAYQBuAHQAeQBiAHIAZQBhAHIAZQB0AHUAcgBkAGUAYgB1AGcAZwBlAGEAdwBhAGkAdABoAHIAdwBoAGkAbABlAGkAZgBjAGEAdABjAGYAaQBuAGEAbABsAGUAbABzAABB0AkLEAEAAAACAAAAAAQAAEA5AAA=", typeof Buffer < "u" ? Buffer.from(A2, "base64") : Uint8Array.from(atob(A2), ((A3) => A3.charCodeAt(0)));
495
- var A2;
496
- }, init = WebAssembly.compile(E()).then(WebAssembly.instantiate).then((({ exports: A2 }) => {
497
- C = A2;
498
- }));
499
-
500
- // ../../../node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs
501
- var comma = 44, semicolon = 59, chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/", intToChar = new Uint8Array(64), charToInt = new Uint8Array(128);
502
- for (let i = 0; i < chars.length; i++) {
503
- let c = chars.charCodeAt(i);
504
- intToChar[i] = c, charToInt[c] = i;
505
- }
506
- function encodeInteger(builder, num, relative4) {
507
- let delta = num - relative4;
508
- delta = delta < 0 ? -delta << 1 | 1 : delta << 1;
509
- do {
510
- let clamped = delta & 31;
511
- delta >>>= 5, delta > 0 && (clamped |= 32), builder.write(intToChar[clamped]);
512
- } while (delta > 0);
513
- return num;
514
- }
515
- var bufLength = 1024 * 16, td = typeof TextDecoder < "u" ? new TextDecoder() : typeof Buffer < "u" ? {
516
- decode(buf) {
517
- return Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength).toString();
518
- }
519
- } : {
520
- decode(buf) {
521
- let out = "";
522
- for (let i = 0; i < buf.length; i++)
523
- out += String.fromCharCode(buf[i]);
524
- return out;
525
- }
526
- }, StringWriter = class {
527
- constructor() {
528
- this.pos = 0, this.out = "", this.buffer = new Uint8Array(bufLength);
529
- }
530
- write(v) {
531
- let { buffer } = this;
532
- buffer[this.pos++] = v, this.pos === bufLength && (this.out += td.decode(buffer), this.pos = 0);
533
- }
534
- flush() {
535
- let { buffer, out, pos } = this;
536
- return pos > 0 ? out + td.decode(buffer.subarray(0, pos)) : out;
537
- }
538
- };
539
- function encode(decoded) {
540
- let writer = new StringWriter(), sourcesIndex = 0, sourceLine = 0, sourceColumn = 0, namesIndex = 0;
541
- for (let i = 0; i < decoded.length; i++) {
542
- let line = decoded[i];
543
- if (i > 0 && writer.write(semicolon), line.length === 0) continue;
544
- let genColumn = 0;
545
- for (let j = 0; j < line.length; j++) {
546
- let segment = line[j];
547
- j > 0 && writer.write(comma), genColumn = encodeInteger(writer, segment[0], genColumn), segment.length !== 1 && (sourcesIndex = encodeInteger(writer, segment[1], sourcesIndex), sourceLine = encodeInteger(writer, segment[2], sourceLine), sourceColumn = encodeInteger(writer, segment[3], sourceColumn), segment.length !== 4 && (namesIndex = encodeInteger(writer, segment[4], namesIndex)));
548
- }
549
- }
550
- return writer.flush();
551
- }
552
-
553
- // node_modules/magic-string/dist/index.mjs
554
- var BitSet = class BitSet2 {
555
- constructor(arg) {
556
- this.bits = arg instanceof BitSet2 ? arg.bits.slice() : [];
557
- }
558
- add(n2) {
559
- this.bits[n2 >> 5] |= 1 << (n2 & 31);
560
- }
561
- has(n2) {
562
- return !!(this.bits[n2 >> 5] & 1 << (n2 & 31));
563
- }
564
- }, Chunk = class Chunk2 {
565
- constructor(start2, end, content) {
566
- this.start = start2, this.end = end, this.original = content, this.intro = "", this.outro = "", this.content = content, this.storeName = !1, this.edited = !1, this.previous = null, this.next = null;
567
- }
568
- appendLeft(content) {
569
- this.outro += content;
570
- }
571
- appendRight(content) {
572
- this.intro = this.intro + content;
573
- }
574
- clone() {
575
- let chunk = new Chunk2(this.start, this.end, this.original);
576
- return chunk.intro = this.intro, chunk.outro = this.outro, chunk.content = this.content, chunk.storeName = this.storeName, chunk.edited = this.edited, chunk;
577
- }
578
- contains(index) {
579
- return this.start < index && index < this.end;
580
- }
581
- eachNext(fn) {
582
- fn(this);
583
- let chunk = this.next;
584
- for (; chunk; )
585
- fn(chunk), chunk = chunk.next;
586
- }
587
- eachPrevious(fn) {
588
- fn(this);
589
- let chunk = this.previous;
590
- for (; chunk; )
591
- fn(chunk), chunk = chunk.previous;
592
- }
593
- edit(content, storeName, contentOnly) {
594
- return this.content = content, contentOnly || (this.intro = "", this.outro = ""), this.storeName = storeName, this.edited = !0, this;
595
- }
596
- prependLeft(content) {
597
- this.outro = content + this.outro;
598
- }
599
- prependRight(content) {
600
- this.intro = content + this.intro;
601
- }
602
- reset() {
603
- this.intro = "", this.outro = "", this.edited && (this.content = this.original, this.storeName = !1, this.edited = !1);
604
- }
605
- split(index) {
606
- let sliceIndex = index - this.start, originalBefore = this.original.slice(0, sliceIndex), originalAfter = this.original.slice(sliceIndex);
607
- this.original = originalBefore;
608
- let newChunk = new Chunk2(index, this.end, originalAfter);
609
- return newChunk.outro = this.outro, this.outro = "", this.end = index, this.edited ? (newChunk.edit("", !1), this.content = "") : this.content = originalBefore, newChunk.next = this.next, newChunk.next && (newChunk.next.previous = newChunk), newChunk.previous = this, this.next = newChunk, newChunk;
610
- }
611
- toString() {
612
- return this.intro + this.content + this.outro;
613
- }
614
- trimEnd(rx) {
615
- if (this.outro = this.outro.replace(rx, ""), this.outro.length) return !0;
616
- let trimmed = this.content.replace(rx, "");
617
- if (trimmed.length)
618
- return trimmed !== this.content && (this.edited ? this.edit(trimmed, this.storeName, !0) : this.split(this.start + trimmed.length).edit("", void 0, !0)), !0;
619
- if (this.edit("", void 0, !0), this.intro = this.intro.replace(rx, ""), this.intro.length) return !0;
620
- }
621
- trimStart(rx) {
622
- if (this.intro = this.intro.replace(rx, ""), this.intro.length) return !0;
623
- let trimmed = this.content.replace(rx, "");
624
- if (trimmed.length)
625
- return trimmed !== this.content && (this.edited ? this.edit(trimmed, this.storeName, !0) : (this.split(this.end - trimmed.length), this.edit("", void 0, !0))), !0;
626
- if (this.edit("", void 0, !0), this.outro = this.outro.replace(rx, ""), this.outro.length) return !0;
627
- }
628
- };
629
- function getBtoa() {
630
- if (typeof globalThis < "u" && typeof globalThis.btoa == "function") return (str) => globalThis.btoa(unescape(encodeURIComponent(str)));
631
- let buffer = globalThis.Buffer;
632
- return buffer ? (str) => buffer.from(str, "utf-8").toString("base64") : () => {
633
- throw new Error("Unsupported environment: `window.btoa` or `Buffer` should be supported.");
634
- };
635
- }
636
- var btoa = getBtoa(), SourceMap = class {
637
- constructor(properties) {
638
- this.version = 3, this.file = properties.file, this.sources = properties.sources, this.sourcesContent = properties.sourcesContent, this.names = properties.names, this.mappings = encode(properties.mappings), typeof properties.x_google_ignoreList < "u" && (this.x_google_ignoreList = properties.x_google_ignoreList), typeof properties.debugId < "u" && (this.debugId = properties.debugId);
639
- }
640
- /**
641
- * Returns the equivalent of `JSON.stringify(map)`
642
- */
643
- toString() {
644
- return JSON.stringify(this);
645
- }
646
- /**
647
- * Returns a DataURI containing the sourcemap. Useful for doing this sort of thing:
648
- * `generateMap(options?: SourceMapOptions): SourceMap;`
649
- */
650
- toUrl() {
651
- return `data:application/json;charset=utf-8;base64,${btoa(this.toString())}`;
652
- }
653
- };
654
- function getLocator(source) {
655
- let originalLines = source.split(`
656
- `), lineOffsets = [];
657
- for (let i = 0, pos = 0; i < originalLines.length; i++)
658
- lineOffsets.push(pos), pos += originalLines[i].length + 1;
659
- return function(index) {
660
- let i = 0, j = lineOffsets.length;
661
- for (; i < j; ) {
662
- let m = i + j >> 1;
663
- index < lineOffsets[m] ? j = m : i = m + 1;
664
- }
665
- let line = i - 1;
666
- return {
667
- line,
668
- column: index - lineOffsets[line]
669
- };
670
- };
671
- }
672
- function getRelativePath(from, to) {
673
- let fromParts = from.split(/[/\\]/), toParts = to.split(/[/\\]/);
674
- for (fromParts.pop(); fromParts[0] === toParts[0]; )
675
- fromParts.shift(), toParts.shift();
676
- if (fromParts.length) {
677
- let i = fromParts.length;
678
- for (; i--; ) fromParts[i] = "..";
679
- }
680
- return fromParts.concat(toParts).join("/");
681
- }
682
- function guessIndent(code) {
683
- let lines = code.split(`
684
- `), tabbed = lines.filter((line) => /^\t+/.test(line)), spaced = lines.filter((line) => /^ {2,}/.test(line));
685
- if (tabbed.length === 0 && spaced.length === 0) return null;
686
- if (tabbed.length >= spaced.length) return " ";
687
- let min = spaced.reduce((previous, current) => {
688
- let numSpaces = /^ +/.exec(current)[0].length;
689
- return Math.min(numSpaces, previous);
690
- }, 1 / 0);
691
- return " ".repeat(min);
692
- }
693
- var toString = Object.prototype.toString;
694
- function isObject(thing) {
695
- return toString.call(thing) === "[object Object]";
696
- }
697
- var wordRegex = /\w/, Mappings = class {
698
- constructor(hires) {
699
- this.hires = hires, this.generatedCodeLine = 0, this.generatedCodeColumn = 0, this.raw = [], this.rawSegments = this.raw[this.generatedCodeLine] = [], this.pending = null;
700
- }
701
- addEdit(sourceIndex, content, loc, nameIndex) {
702
- if (content.length) {
703
- let contentLengthMinusOne = content.length - 1, contentLineEnd = content.indexOf(`
704
- `, 0), previousContentLineEnd = -1;
705
- for (; contentLineEnd >= 0 && contentLengthMinusOne > contentLineEnd; ) {
706
- let segment2 = [
707
- this.generatedCodeColumn,
708
- sourceIndex,
709
- loc.line,
710
- loc.column
711
- ];
712
- nameIndex >= 0 && segment2.push(nameIndex), this.rawSegments.push(segment2), this.generatedCodeLine += 1, this.raw[this.generatedCodeLine] = this.rawSegments = [], this.generatedCodeColumn = 0, previousContentLineEnd = contentLineEnd, contentLineEnd = content.indexOf(`
713
- `, contentLineEnd + 1);
714
- }
715
- let segment = [
716
- this.generatedCodeColumn,
717
- sourceIndex,
718
- loc.line,
719
- loc.column
720
- ];
721
- nameIndex >= 0 && segment.push(nameIndex), this.rawSegments.push(segment), this.advance(content.slice(previousContentLineEnd + 1));
722
- } else this.pending && (this.rawSegments.push(this.pending), this.advance(content));
723
- this.pending = null;
724
- }
725
- addUneditedChunk(sourceIndex, chunk, original, loc, sourcemapLocations) {
726
- let originalCharIndex = chunk.start, first = !0, charInHiresBoundary = !1;
727
- for (; originalCharIndex < chunk.end; ) {
728
- if (original[originalCharIndex] === `
729
- `)
730
- loc.line += 1, loc.column = 0, this.generatedCodeLine += 1, this.raw[this.generatedCodeLine] = this.rawSegments = [], this.generatedCodeColumn = 0, first = !0, charInHiresBoundary = !1;
731
- else {
732
- if (this.hires || first || sourcemapLocations.has(originalCharIndex)) {
733
- let segment = [
734
- this.generatedCodeColumn,
735
- sourceIndex,
736
- loc.line,
737
- loc.column
738
- ];
739
- this.hires === "boundary" ? wordRegex.test(original[originalCharIndex]) ? charInHiresBoundary || (this.rawSegments.push(segment), charInHiresBoundary = !0) : (this.rawSegments.push(segment), charInHiresBoundary = !1) : this.rawSegments.push(segment);
740
- }
741
- loc.column += 1, this.generatedCodeColumn += 1, first = !1;
742
- }
743
- originalCharIndex += 1;
744
- }
745
- this.pending = null;
746
- }
747
- advance(str) {
748
- if (!str) return;
749
- let lines = str.split(`
750
- `);
751
- if (lines.length > 1) {
752
- for (let i = 0; i < lines.length - 1; i++)
753
- this.generatedCodeLine++, this.raw[this.generatedCodeLine] = this.rawSegments = [];
754
- this.generatedCodeColumn = 0;
755
- }
756
- this.generatedCodeColumn += lines[lines.length - 1].length;
757
- }
758
- }, n = `
759
- `, NEWLINE_CHAR = 10, CR_CHAR = 13, warned = {
760
- insertLeft: !1,
761
- insertRight: !1,
762
- storeName: !1
763
- }, MagicString = class MagicString2 {
764
- constructor(string, options = {}) {
765
- let chunk = new Chunk(0, string.length, string);
766
- Object.defineProperties(this, {
767
- original: {
768
- writable: !0,
769
- value: string
770
- },
771
- outro: {
772
- writable: !0,
773
- value: ""
774
- },
775
- intro: {
776
- writable: !0,
777
- value: ""
778
- },
779
- firstChunk: {
780
- writable: !0,
781
- value: chunk
782
- },
783
- lastChunk: {
784
- writable: !0,
785
- value: chunk
786
- },
787
- lastSearchedChunk: {
788
- writable: !0,
789
- value: chunk
790
- },
791
- byStart: {
792
- writable: !0,
793
- value: {}
794
- },
795
- byEnd: {
796
- writable: !0,
797
- value: {}
798
- },
799
- filename: {
800
- writable: !0,
801
- value: options.filename
802
- },
803
- indentExclusionRanges: {
804
- writable: !0,
805
- value: options.indentExclusionRanges
806
- },
807
- sourcemapLocations: {
808
- writable: !0,
809
- value: new BitSet()
810
- },
811
- storedNames: {
812
- writable: !0,
813
- value: {}
814
- },
815
- indentStr: {
816
- writable: !0,
817
- value: void 0
818
- },
819
- ignoreList: {
820
- writable: !0,
821
- value: options.ignoreList
822
- },
823
- offset: {
824
- writable: !0,
825
- value: options.offset || 0
826
- }
827
- }), this.byStart = /* @__PURE__ */ new Map([[0, chunk]]), this.byEnd = /* @__PURE__ */ new Map([[string.length, chunk]]);
828
- }
829
- /**
830
- * Adds the specified character index (with respect to the original string) to sourcemap mappings, if `hires` is false.
831
- */
832
- addSourcemapLocation(char) {
833
- this.sourcemapLocations.add(char);
834
- }
835
- /**
836
- * Appends the specified content to the end of the string.
837
- */
838
- append(content) {
839
- if (typeof content != "string") throw new TypeError("outro content must be a string");
840
- return this.outro += content, this;
841
- }
842
- /**
843
- * Appends the specified content at the index in the original string.
844
- * If a range *ending* with index is subsequently moved, the insert will be moved with it.
845
- * See also `s.prependLeft(...)`.
846
- */
847
- appendLeft(index, content) {
848
- if (index = index + this.offset, typeof content != "string") throw new TypeError("inserted content must be a string");
849
- this._split(index);
850
- let chunk = this.byEnd.get(index);
851
- return chunk ? chunk.appendLeft(content) : this.intro += content, this;
852
- }
853
- /**
854
- * Appends the specified content at the index in the original string.
855
- * If a range *starting* with index is subsequently moved, the insert will be moved with it.
856
- * See also `s.prependRight(...)`.
857
- */
858
- appendRight(index, content) {
859
- if (index = index + this.offset, typeof content != "string") throw new TypeError("inserted content must be a string");
860
- this._split(index);
861
- let chunk = this.byStart.get(index);
862
- return chunk ? chunk.appendRight(content) : this.outro += content, this;
863
- }
864
- /**
865
- * Does what you'd expect.
866
- */
867
- clone() {
868
- let cloned = new MagicString2(this.original, {
869
- filename: this.filename,
870
- offset: this.offset
871
- }), originalChunk = this.firstChunk, clonedChunk = cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone();
872
- for (; originalChunk; ) {
873
- cloned.byStart.set(clonedChunk.start, clonedChunk), cloned.byEnd.set(clonedChunk.end, clonedChunk);
874
- let nextOriginalChunk = originalChunk.next, nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();
875
- nextClonedChunk && (clonedChunk.next = nextClonedChunk, nextClonedChunk.previous = clonedChunk, clonedChunk = nextClonedChunk), originalChunk = nextOriginalChunk;
876
- }
877
- return cloned.lastChunk = clonedChunk, this.indentExclusionRanges && (cloned.indentExclusionRanges = this.indentExclusionRanges.slice()), cloned.sourcemapLocations = new BitSet(this.sourcemapLocations), cloned.intro = this.intro, cloned.outro = this.outro, cloned;
878
- }
879
- /**
880
- * Generates a sourcemap object with raw mappings in array form, rather than encoded as a string.
881
- * Useful if you need to manipulate the sourcemap further, but most of the time you will use `generateMap` instead.
882
- */
883
- generateDecodedMap(options) {
884
- options = options || {};
885
- let sourceIndex = 0, names = Object.keys(this.storedNames), mappings = new Mappings(options.hires), locate = getLocator(this.original);
886
- return this.intro && mappings.advance(this.intro), this.firstChunk.eachNext((chunk) => {
887
- let loc = locate(chunk.start);
888
- chunk.intro.length && mappings.advance(chunk.intro), chunk.edited ? mappings.addEdit(sourceIndex, chunk.content, loc, chunk.storeName ? names.indexOf(chunk.original) : -1) : mappings.addUneditedChunk(sourceIndex, chunk, this.original, loc, this.sourcemapLocations), chunk.outro.length && mappings.advance(chunk.outro);
889
- }), this.outro && mappings.advance(this.outro), {
890
- file: options.file ? options.file.split(/[/\\]/).pop() : void 0,
891
- sources: [options.source ? getRelativePath(options.file || "", options.source) : options.file || ""],
892
- sourcesContent: options.includeContent ? [this.original] : void 0,
893
- names,
894
- mappings: mappings.raw,
895
- x_google_ignoreList: this.ignoreList ? [sourceIndex] : void 0
896
- };
897
- }
898
- /**
899
- * Generates a version 3 sourcemap.
900
- */
901
- generateMap(options) {
902
- return new SourceMap(this.generateDecodedMap(options));
903
- }
904
- /** @internal */
905
- _ensureindentStr() {
906
- this.indentStr === void 0 && (this.indentStr = guessIndent(this.original));
907
- }
908
- /** @internal */
909
- _getRawIndentString() {
910
- return this._ensureindentStr(), this.indentStr;
911
- }
912
- getIndentString() {
913
- return this._ensureindentStr(), this.indentStr === null ? " " : this.indentStr;
914
- }
915
- indent(indentStr, options) {
916
- let pattern = /^[^\r\n]/gm;
917
- if (isObject(indentStr) && (options = indentStr, indentStr = void 0), indentStr === void 0 && (this._ensureindentStr(), indentStr = this.indentStr || " "), indentStr === "") return this;
918
- let resolvedIndentStr = indentStr;
919
- options = options || {};
920
- let isExcluded = {};
921
- options.exclude && (typeof options.exclude[0] == "number" ? [options.exclude] : options.exclude).forEach((exclusion) => {
922
- for (let i = exclusion[0]; i < exclusion[1]; i += 1) isExcluded[i] = !0;
923
- });
924
- let shouldIndentNextCharacter = options.indentStart !== !1, replacer = (match) => shouldIndentNextCharacter ? `${resolvedIndentStr}${match}` : (shouldIndentNextCharacter = !0, match);
925
- this.intro = this.intro.replace(pattern, replacer);
926
- let charIndex = 0, chunk = this.firstChunk, indentAt = (index) => {
927
- shouldIndentNextCharacter = !1, index === chunk.start || (this._splitChunk(chunk, index), chunk = chunk.next), chunk.prependRight(resolvedIndentStr);
928
- };
929
- for (; chunk; ) {
930
- let end = chunk.end;
931
- if (chunk.edited)
932
- isExcluded[charIndex] || (chunk.content = chunk.content.replace(pattern, replacer), chunk.content.length && (shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === `
933
- `));
934
- else if (options.exclude)
935
- for (charIndex = chunk.start; charIndex < end; ) {
936
- if (!isExcluded[charIndex]) {
937
- let char = this.original.charCodeAt(charIndex);
938
- char === NEWLINE_CHAR ? shouldIndentNextCharacter = !0 : char !== CR_CHAR && shouldIndentNextCharacter && indentAt(charIndex);
939
- }
940
- charIndex += 1;
941
- }
942
- else
943
- for (charIndex = chunk.start; charIndex < end; ) {
944
- if (!shouldIndentNextCharacter) {
945
- let nextLine = this.original.indexOf(n, charIndex);
946
- if (nextLine === -1 || nextLine >= end) break;
947
- shouldIndentNextCharacter = !0, charIndex = nextLine + 1;
948
- continue;
949
- }
950
- let char = this.original.charCodeAt(charIndex);
951
- if (char === NEWLINE_CHAR || char === CR_CHAR) {
952
- charIndex += 1;
953
- continue;
954
- }
955
- indentAt(charIndex), charIndex += 1;
956
- }
957
- charIndex = chunk.end, chunk = chunk.next;
958
- }
959
- return this.outro = this.outro.replace(pattern, replacer), this;
960
- }
961
- /** @internal */
962
- insert() {
963
- throw new Error("magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)");
964
- }
965
- /** @internal */
966
- insertLeft(index, content) {
967
- return warned.insertLeft || (console.warn("magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead"), warned.insertLeft = !0), this.appendLeft(index, content);
968
- }
969
- /** @internal */
970
- insertRight(index, content) {
971
- return warned.insertRight || (console.warn("magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead"), warned.insertRight = !0), this.prependRight(index, content);
972
- }
973
- /**
974
- * Moves the characters from `start` and `end` to `index`.
975
- */
976
- move(start2, end, index) {
977
- if (start2 = start2 + this.offset, end = end + this.offset, index = index + this.offset, start2 === end) return this;
978
- if (index >= start2 && index <= end) throw new Error("Cannot move a selection inside itself");
979
- this._split(start2), this._split(end), this._split(index);
980
- let first = this.byStart.get(start2), last = this.byEnd.get(end), oldLeft = first.previous, oldRight = last.next, newRight = this.byStart.get(index);
981
- if (!newRight && last === this.lastChunk) return this;
982
- let newLeft = newRight ? newRight.previous : this.lastChunk;
983
- return oldLeft && (oldLeft.next = oldRight), oldRight && (oldRight.previous = oldLeft), newLeft && (newLeft.next = first), newRight && (newRight.previous = last), first.previous || (this.firstChunk = last.next), last.next || (this.lastChunk = first.previous, this.lastChunk.next = null), first.previous = newLeft, last.next = newRight || null, newLeft || (this.firstChunk = first), newRight || (this.lastChunk = last), this;
984
- }
985
- /**
986
- * Replaces the characters from `start` to `end` with `content`, along with the appended/prepended content in
987
- * that range. The same restrictions as `s.remove()` apply.
988
- *
989
- * The fourth argument is optional. It can have a storeName property - if true, the original name will be stored
990
- * for later inclusion in a sourcemap's names array - and a contentOnly property which determines whether only
991
- * the content is overwritten, or anything that was appended/prepended to the range as well.
992
- *
993
- * It may be preferred to use `s.update(...)` instead if you wish to avoid overwriting the appended/prepended content.
994
- */
995
- overwrite(start2, end, content, options) {
996
- let optionObject = typeof options == "object" && options ? options : {};
997
- return this.update(start2, end, content, {
998
- ...optionObject,
999
- overwrite: !optionObject.contentOnly
1000
- });
1001
- }
1002
- /**
1003
- * Replaces the characters from `start` to `end` with `content`. The same restrictions as `s.remove()` apply.
1004
- *
1005
- * The fourth argument is optional. It can have a storeName property - if true, the original name will be stored
1006
- * for later inclusion in a sourcemap's names array - and an overwrite property which determines whether only
1007
- * the content is overwritten, or anything that was appended/prepended to the range as well.
1008
- */
1009
- update(start2, end, content, options) {
1010
- if (start2 = start2 + this.offset, end = end + this.offset, typeof content != "string") throw new TypeError("replacement content must be a string");
1011
- if (this.original.length !== 0) {
1012
- for (; start2 < 0; ) start2 += this.original.length;
1013
- for (; end < 0; ) end += this.original.length;
1014
- }
1015
- if (end > this.original.length) throw new Error("end is out of bounds");
1016
- if (start2 === end) throw new Error("Cannot overwrite a zero-length range \u2013 use appendLeft or prependRight instead");
1017
- this._split(start2), this._split(end), options === !0 && (warned.storeName || (console.warn("The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string"), warned.storeName = !0), options = { storeName: !0 });
1018
- let optionObject = typeof options == "object" && options ? options : {}, storeName = optionObject.storeName || !1, overwrite = optionObject.overwrite || !1;
1019
- if (storeName) {
1020
- let original = this.original.slice(start2, end);
1021
- Object.defineProperty(this.storedNames, original, {
1022
- writable: !0,
1023
- value: !0,
1024
- enumerable: !0
1025
- });
1026
- }
1027
- let first = this.byStart.get(start2), last = this.byEnd.get(end);
1028
- if (first) {
1029
- let chunk = first;
1030
- for (; chunk !== last; ) {
1031
- if (chunk.next !== this.byStart.get(chunk.end)) throw new Error("Cannot overwrite across a split point");
1032
- chunk = chunk.next, chunk.edit("", !1);
1033
- }
1034
- first.edit(content, storeName, !overwrite);
1035
- } else {
1036
- let newChunk = new Chunk(start2, end, "").edit(content, storeName);
1037
- last.next = newChunk, newChunk.previous = last;
1038
- }
1039
- return this;
1040
- }
1041
- /**
1042
- * Prepends the string with the specified content.
1043
- */
1044
- prepend(content) {
1045
- if (typeof content != "string") throw new TypeError("outro content must be a string");
1046
- return this.intro = content + this.intro, this;
1047
- }
1048
- /**
1049
- * Same as `s.appendLeft(...)`, except that the inserted content will go *before* any previous appends or prepends at index
1050
- */
1051
- prependLeft(index, content) {
1052
- if (index = index + this.offset, typeof content != "string") throw new TypeError("inserted content must be a string");
1053
- this._split(index);
1054
- let chunk = this.byEnd.get(index);
1055
- return chunk ? chunk.prependLeft(content) : this.intro = content + this.intro, this;
1056
- }
1057
- /**
1058
- * Same as `s.appendRight(...)`, except that the inserted content will go *before* any previous appends or prepends at `index`
1059
- */
1060
- prependRight(index, content) {
1061
- if (index = index + this.offset, typeof content != "string") throw new TypeError("inserted content must be a string");
1062
- this._split(index);
1063
- let chunk = this.byStart.get(index);
1064
- return chunk ? chunk.prependRight(content) : this.outro = content + this.outro, this;
1065
- }
1066
- /**
1067
- * Removes the characters from `start` to `end` (of the original string, **not** the generated string).
1068
- * Removing the same content twice, or making removals that partially overlap, will cause an error.
1069
- */
1070
- remove(start2, end) {
1071
- if (start2 = start2 + this.offset, end = end + this.offset, this.original.length !== 0) {
1072
- for (; start2 < 0; ) start2 += this.original.length;
1073
- for (; end < 0; ) end += this.original.length;
1074
- }
1075
- if (start2 === end) return this;
1076
- if (start2 < 0 || end > this.original.length) throw new Error("Character is out of bounds");
1077
- if (start2 > end) throw new Error("end must be greater than start");
1078
- this._split(start2), this._split(end);
1079
- let chunk = this.byStart.get(start2);
1080
- for (; chunk; )
1081
- chunk.intro = "", chunk.outro = "", chunk.edit(""), chunk = end > chunk.end ? this.byStart.get(chunk.end) : null;
1082
- return this;
1083
- }
1084
- /**
1085
- * Reset the modified characters from `start` to `end` (of the original string, **not** the generated string).
1086
- */
1087
- reset(start2, end) {
1088
- if (start2 = start2 + this.offset, end = end + this.offset, this.original.length !== 0) {
1089
- for (; start2 < 0; ) start2 += this.original.length;
1090
- for (; end < 0; ) end += this.original.length;
1091
- }
1092
- if (start2 === end) return this;
1093
- if (start2 < 0 || end > this.original.length) throw new Error("Character is out of bounds");
1094
- if (start2 > end) throw new Error("end must be greater than start");
1095
- this._split(start2), this._split(end);
1096
- let chunk = this.byStart.get(start2);
1097
- for (; chunk; )
1098
- chunk.reset(), chunk = end > chunk.end ? this.byStart.get(chunk.end) : null;
1099
- return this;
1100
- }
1101
- lastChar() {
1102
- if (this.outro.length) return this.outro[this.outro.length - 1];
1103
- let chunk = this.lastChunk;
1104
- for (; chunk; ) {
1105
- if (chunk.outro.length) return chunk.outro[chunk.outro.length - 1];
1106
- if (chunk.content.length) return chunk.content[chunk.content.length - 1];
1107
- if (chunk.intro.length) return chunk.intro[chunk.intro.length - 1];
1108
- chunk = chunk.previous;
1109
- }
1110
- return this.intro.length ? this.intro[this.intro.length - 1] : "";
1111
- }
1112
- lastLine() {
1113
- let lineIndex = this.outro.lastIndexOf(n);
1114
- if (lineIndex !== -1) return this.outro.substr(lineIndex + 1);
1115
- let lineStr = this.outro, chunk = this.lastChunk;
1116
- for (; chunk; ) {
1117
- if (chunk.outro.length > 0) {
1118
- if (lineIndex = chunk.outro.lastIndexOf(n), lineIndex !== -1) return chunk.outro.substr(lineIndex + 1) + lineStr;
1119
- lineStr = chunk.outro + lineStr;
1120
- }
1121
- if (chunk.content.length > 0) {
1122
- if (lineIndex = chunk.content.lastIndexOf(n), lineIndex !== -1) return chunk.content.substr(lineIndex + 1) + lineStr;
1123
- lineStr = chunk.content + lineStr;
1124
- }
1125
- if (chunk.intro.length > 0) {
1126
- if (lineIndex = chunk.intro.lastIndexOf(n), lineIndex !== -1) return chunk.intro.substr(lineIndex + 1) + lineStr;
1127
- lineStr = chunk.intro + lineStr;
1128
- }
1129
- chunk = chunk.previous;
1130
- }
1131
- return lineIndex = this.intro.lastIndexOf(n), lineIndex !== -1 ? this.intro.substr(lineIndex + 1) + lineStr : this.intro + lineStr;
1132
- }
1133
- /**
1134
- * Returns the content of the generated string that corresponds to the slice between `start` and `end` of the original string.
1135
- * Throws error if the indices are for characters that were already removed.
1136
- */
1137
- slice(start2 = 0, end = this.original.length - this.offset) {
1138
- if (start2 = start2 + this.offset, end = end + this.offset, this.original.length !== 0) {
1139
- for (; start2 < 0; ) start2 += this.original.length;
1140
- for (; end < 0; ) end += this.original.length;
1141
- }
1142
- let result = "", chunk = this.firstChunk;
1143
- for (; chunk && (chunk.start > start2 || chunk.end <= start2); ) {
1144
- if (chunk.start < end && chunk.end >= end) return result;
1145
- chunk = chunk.next;
1146
- }
1147
- if (chunk && chunk.edited && chunk.start !== start2) throw new Error(`Cannot use replaced character ${start2} as slice start anchor.`);
1148
- let startChunk = chunk;
1149
- for (; chunk; ) {
1150
- chunk.intro && (startChunk !== chunk || chunk.start === start2) && (result += chunk.intro);
1151
- let containsEnd = chunk.start < end && chunk.end >= end;
1152
- if (containsEnd && chunk.edited && chunk.end !== end) throw new Error(`Cannot use replaced character ${end} as slice end anchor.`);
1153
- let sliceStart = startChunk === chunk ? start2 - chunk.start : 0, sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;
1154
- if (result += chunk.content.slice(sliceStart, sliceEnd), chunk.outro && (!containsEnd || chunk.end === end) && (result += chunk.outro), containsEnd) break;
1155
- chunk = chunk.next;
1156
- }
1157
- return result;
1158
- }
1159
- /**
1160
- * Returns a clone of `s`, with all content before the `start` and `end` characters of the original string removed.
1161
- */
1162
- snip(start2, end) {
1163
- let clone = this.clone();
1164
- return clone.remove(0, start2), clone.remove(end, clone.original.length), clone;
1165
- }
1166
- /** @internal */
1167
- _split(index) {
1168
- if (this.byStart.get(index) || this.byEnd.get(index)) return;
1169
- let chunk = this.lastSearchedChunk, previousChunk = chunk, searchForward = index > chunk.end;
1170
- for (; chunk; ) {
1171
- if (chunk.contains(index)) return this._splitChunk(chunk, index);
1172
- if (chunk = searchForward ? this.byStart.get(chunk.end) : this.byEnd.get(chunk.start), chunk === previousChunk) return;
1173
- previousChunk = chunk;
1174
- }
1175
- }
1176
- /** @internal */
1177
- _splitChunk(chunk, index) {
1178
- if (chunk.edited && chunk.content.length) {
1179
- let loc = getLocator(this.original)(index);
1180
- throw new Error(`Cannot split a chunk that has already been edited (${loc.line}:${loc.column} \u2013 "${chunk.original}")`);
1181
- }
1182
- let newChunk = chunk.split(index);
1183
- return this.byEnd.set(index, chunk), this.byStart.set(index, newChunk), this.byEnd.set(newChunk.end, newChunk), chunk === this.lastChunk && (this.lastChunk = newChunk), this.lastSearchedChunk = chunk, !0;
1184
- }
1185
- /**
1186
- * Returns the generated string.
1187
- */
1188
- toString() {
1189
- let str = this.intro, chunk = this.firstChunk;
1190
- for (; chunk; )
1191
- str += chunk.toString(), chunk = chunk.next;
1192
- return str + this.outro;
1193
- }
1194
- /**
1195
- * Returns true if the resulting source is empty (disregarding white space).
1196
- */
1197
- isEmpty() {
1198
- let chunk = this.firstChunk;
1199
- for (; chunk; ) {
1200
- if (chunk.intro.length && chunk.intro.trim() || chunk.content.length && chunk.content.trim() || chunk.outro.length && chunk.outro.trim()) return !1;
1201
- chunk = chunk.next;
1202
- }
1203
- return !0;
1204
- }
1205
- length() {
1206
- let chunk = this.firstChunk, length = 0;
1207
- for (; chunk; )
1208
- length += chunk.intro.length + chunk.content.length + chunk.outro.length, chunk = chunk.next;
1209
- return length;
1210
- }
1211
- /**
1212
- * Removes empty lines from the start and end.
1213
- */
1214
- trimLines() {
1215
- return this.trim("[\\r\\n]");
1216
- }
1217
- /**
1218
- * Trims content matching `charType` (defaults to `\s`, i.e. whitespace) from the start and end.
1219
- */
1220
- trim(charType) {
1221
- return this.trimStart(charType).trimEnd(charType);
1222
- }
1223
- /** @internal */
1224
- trimEndAborted(charType) {
1225
- let rx = new RegExp(`${charType || "\\s"}+$`);
1226
- if (this.outro = this.outro.replace(rx, ""), this.outro.length) return !0;
1227
- let chunk = this.lastChunk;
1228
- do {
1229
- let end = chunk.end, aborted = chunk.trimEnd(rx);
1230
- if (chunk.end !== end && (this.lastChunk === chunk && (this.lastChunk = chunk.next), this.byEnd.set(chunk.end, chunk), this.byStart.set(chunk.next.start, chunk.next), this.byEnd.set(chunk.next.end, chunk.next)), aborted) return !0;
1231
- chunk = chunk.previous;
1232
- } while (chunk);
1233
- return !1;
1234
- }
1235
- /**
1236
- * Trims content matching `charType` (defaults to `\s`, i.e. whitespace) from the end.
1237
- */
1238
- trimEnd(charType) {
1239
- return this.trimEndAborted(charType), this;
1240
- }
1241
- /** @internal */
1242
- trimStartAborted(charType) {
1243
- let rx = new RegExp(`^${charType || "\\s"}+`);
1244
- if (this.intro = this.intro.replace(rx, ""), this.intro.length) return !0;
1245
- let chunk = this.firstChunk;
1246
- do {
1247
- let end = chunk.end, aborted = chunk.trimStart(rx);
1248
- if (chunk.end !== end && (chunk === this.lastChunk && (this.lastChunk = chunk.next), this.byEnd.set(chunk.end, chunk), this.byStart.set(chunk.next.start, chunk.next), this.byEnd.set(chunk.next.end, chunk.next)), aborted) return !0;
1249
- chunk = chunk.next;
1250
- } while (chunk);
1251
- return !1;
1252
- }
1253
- /**
1254
- * Trims content matching `charType` (defaults to `\s`, i.e. whitespace) from the start.
1255
- */
1256
- trimStart(charType) {
1257
- return this.trimStartAborted(charType), this;
1258
- }
1259
- /**
1260
- * Indicates if the string has been changed.
1261
- */
1262
- hasChanged() {
1263
- return this.original !== this.toString();
1264
- }
1265
- /** @internal */
1266
- _replaceRegexp(searchValue, replacement) {
1267
- function getReplacement(match, str) {
1268
- return typeof replacement == "string" ? replacement.replace(/\$(\$|&|\d+)/g, (_, i) => i === "$" ? "$" : i === "&" ? match[0] : +i < match.length ? match[+i] : `$${i}`) : replacement(match[0], ...match.slice(1), match.index, str, match.groups);
1269
- }
1270
- function matchAll(re, str) {
1271
- let matches = [];
1272
- for (; ; ) {
1273
- let match = re.exec(str);
1274
- if (!match) break;
1275
- matches.push(match);
1276
- }
1277
- return matches;
1278
- }
1279
- if (searchValue.global) matchAll(searchValue, this.original).forEach((match) => {
1280
- if (match.index != null) {
1281
- let replacement2 = getReplacement(match, this.original);
1282
- replacement2 !== match[0] && this.overwrite(match.index, match.index + match[0].length, replacement2);
1283
- }
1284
- });
1285
- else {
1286
- let match = this.original.match(searchValue);
1287
- if (match && match.index != null) {
1288
- let replacement2 = getReplacement(match, this.original);
1289
- replacement2 !== match[0] && this.overwrite(match.index, match.index + match[0].length, replacement2);
1290
- }
1291
- }
1292
- return this;
1293
- }
1294
- /** @internal */
1295
- _replaceString(string, replacement) {
1296
- let { original } = this, index = original.indexOf(string);
1297
- return index !== -1 && (typeof replacement == "function" && (replacement = replacement(string, index, original)), string !== replacement && this.overwrite(index, index + string.length, replacement)), this;
1298
- }
1299
- /**
1300
- * String replacement with RegExp or string.
1301
- */
1302
- replace(searchValue, replacement) {
1303
- return typeof searchValue == "string" ? this._replaceString(searchValue, replacement) : this._replaceRegexp(searchValue, replacement);
1304
- }
1305
- /** @internal */
1306
- _replaceAllString(string, replacement) {
1307
- let { original } = this, stringLength = string.length;
1308
- for (let index = original.indexOf(string); index !== -1; index = original.indexOf(string, index + stringLength)) {
1309
- let previous = original.slice(index, index + stringLength), _replacement = typeof replacement == "function" ? replacement(previous, index, original) : replacement;
1310
- previous !== _replacement && this.overwrite(index, index + stringLength, _replacement);
1311
- }
1312
- return this;
1313
- }
1314
- /**
1315
- * Same as `s.replace`, but replace all matched strings instead of just one.
1316
- */
1317
- replaceAll(searchValue, replacement) {
1318
- if (typeof searchValue == "string") return this._replaceAllString(searchValue, replacement);
1319
- if (!searchValue.global) throw new TypeError("MagicString.prototype.replaceAll called with a non-global RegExp argument");
1320
- return this._replaceRegexp(searchValue, replacement);
1321
- }
1322
- };
1323
-
1324
- // src/plugins/inject-export-order-plugin.ts
1325
- async function injectExportOrderPlugin() {
1326
- let { createFilter } = await import("vite"), include = [/\.stories\.([tj])sx?$/, /(stories|story).mdx$/], filter = createFilter(include);
1327
- return {
1328
- name: "storybook:inject-export-order-plugin",
1329
- // This should only run after the typescript has been transpiled
1330
- enforce: "post",
1331
- transform: {
1332
- filter: { id: include },
1333
- async handler(code, id) {
1334
- if (!filter(id))
1335
- return;
1336
- let [, exports] = await parse2(code), exportNames = exports.map((e) => code.substring(e.s, e.e));
1337
- if (exportNames.includes("__namedExportsOrder"))
1338
- return;
1339
- let s = new MagicString(code), orderedExports = exportNames.filter((e) => e !== "default");
1340
- return s.append(`;export const __namedExportsOrder = ${JSON.stringify(orderedExports)};`), {
1341
- code: s.toString(),
1342
- map: s.generateMap({ hires: !0, source: id }).toString()
1343
- };
1344
- }
1345
- }
1346
- };
1347
- }
1348
-
1349
- // src/plugins/strip-story-hmr-boundaries.ts
1350
- async function stripStoryHMRBoundary() {
1351
- let { createFilter } = await import("vite"), include = /\.stories\.(tsx?|jsx?|svelte|vue)$/, filter = createFilter(include);
1352
- return {
1353
- name: "storybook:strip-hmr-boundary-plugin",
1354
- enforce: "post",
1355
- transform: {
1356
- filter: { id: include },
1357
- async handler(src, id) {
1358
- if (!filter(id))
1359
- return;
1360
- let s = new MagicString(src);
1361
- return s.replace(/import\.meta\.hot\.accept\w*/, "(function hmrBoundaryNoop(){})"), {
1362
- code: s.toString(),
1363
- map: s.generateMap({ hires: !0, source: id }).toString()
1364
- };
1365
- }
1366
- }
1367
- };
1368
- }
1369
-
1370
- // src/plugins/storybook-entry-plugin.ts
1371
- async function storybookEntryPlugin(options) {
1372
- return [
1373
- // Pre-enforcement: handles virtual module resolution and loading (must run first)
1374
- codeGeneratorPlugin(options),
1375
- // Post-enforcement: injects __namedExportsOrder after TypeScript transpilation
1376
- await injectExportOrderPlugin(),
1377
- // Post-enforcement: removes import.meta.hot.accept() from story files
1378
- await stripStoryHMRBoundary()
1379
- ];
1380
- }
1381
-
1382
- // src/plugins/webpack-stats-plugin.ts
1383
- import { relative as relative3 } from "node:path";
1384
-
1385
- // ../../../node_modules/slash/index.js
1386
- function slash(path2) {
1387
- return path2.startsWith("\\\\?\\") ? path2 : path2.replace(/\\/g, "/");
1388
- }
1389
-
1390
- // src/plugins/webpack-stats-plugin.ts
1391
- function stripQueryParams(filePath) {
1392
- return filePath.split("?")[0];
1393
- }
1394
- function isUserCode(moduleName) {
1395
- return moduleName ? Object.values(SB_VIRTUAL_FILES).includes(getOriginalVirtualModuleId(moduleName)) ? !0 : !moduleName.startsWith("vite/") && !moduleName.startsWith("\0") && moduleName !== "react/jsx-runtime" : !1;
1396
- }
1397
- function pluginWebpackStats({ workingDir }) {
1398
- function normalize3(filename) {
1399
- if (filename.startsWith("virtual:"))
1400
- return `/${filename}`;
1401
- if (Object.values(SB_VIRTUAL_FILES).includes(getOriginalVirtualModuleId(filename)))
1402
- return `/${getOriginalVirtualModuleId(filename)}`;
1403
- {
1404
- let relativePath = relative3(workingDir, stripQueryParams(filename));
1405
- return `./${slash(relativePath)}`;
1406
- }
1407
- }
1408
- function createReasons(importers) {
1409
- return (importers || []).map((i) => ({ moduleName: normalize3(i) }));
1410
- }
1411
- function createStatsMapModule(filename, importers) {
1412
- return {
1413
- id: filename,
1414
- name: filename,
1415
- reasons: createReasons(importers)
1416
- };
1417
- }
1418
- let statsMap = /* @__PURE__ */ new Map();
1419
- return {
1420
- name: "storybook:rollup-plugin-webpack-stats",
1421
- // We want this to run after the vite build plugins (https://vitejs.dev/guide/api-plugin.html#plugin-ordering)
1422
- enforce: "post",
1423
- moduleParsed: function(mod) {
1424
- isUserCode(mod.id) && mod.importedIds.concat(mod.dynamicallyImportedIds).filter((name) => isUserCode(name)).forEach((depIdUnsafe) => {
1425
- let depId = normalize3(depIdUnsafe);
1426
- if (!statsMap.has(depId)) {
1427
- statsMap.set(depId, createStatsMapModule(depId, [mod.id]));
1428
- return;
1429
- }
1430
- let m = statsMap.get(depId);
1431
- m && (m.reasons = (m.reasons ?? []).concat(createReasons([mod.id])).filter((r) => r.moduleName !== depId), statsMap.set(depId, m));
1432
- });
1433
- },
1434
- storybookGetStats() {
1435
- let stats = { modules: Array.from(statsMap.values()) };
1436
- return { ...stats, toJson: () => stats };
1437
- }
1438
- };
1439
- }
1440
-
1441
- // src/plugins/storybook-external-globals-plugin.ts
1442
- import { existsSync as existsSync3 } from "node:fs";
1443
- import { mkdir, writeFile } from "node:fs/promises";
1444
- import { dirname as dirname4, join as join6 } from "node:path";
1445
- import { globalsNameReferenceMap } from "storybook/internal/preview/globals";
1446
-
1447
- // ../../../node_modules/empathic/package.mjs
1448
- import { env } from "node:process";
1449
- import { dirname as dirname3, join as join5 } from "node:path";
1450
- import { existsSync as existsSync2, mkdirSync } from "node:fs";
1451
-
1452
- // ../../../node_modules/empathic/access.mjs
1453
- import { accessSync, constants } from "node:fs";
1454
- function ok(path2, mode) {
1455
- try {
1456
- return accessSync(path2, mode), !0;
1457
- } catch {
1458
- return !1;
1459
- }
1460
- }
1461
- function writable(path2) {
1462
- return ok(path2, constants.W_OK);
1463
- }
1464
-
1465
- // ../../../node_modules/empathic/find.mjs
1466
- import { join as join4 } from "node:path";
1467
- import { existsSync, statSync } from "node:fs";
1468
-
1469
- // ../../../node_modules/empathic/walk.mjs
1470
- import { dirname as dirname2 } from "node:path";
1471
-
1472
- // ../../../node_modules/empathic/resolve.mjs
1473
- import { isAbsolute as isAbsolute2, join as join3, resolve as resolve2 } from "node:path";
1474
- function absolute(input, root) {
1475
- return isAbsolute2(input) ? input : resolve2(root || ".", input);
1476
- }
1477
-
1478
- // ../../../node_modules/empathic/walk.mjs
1479
- function up(base, options) {
1480
- let { last, cwd } = options || {}, tmp = absolute(base, cwd), root = absolute(last || "/", cwd), prev, arr = [];
1481
- for (; prev !== root && (arr.push(tmp), tmp = dirname2(prev = tmp), tmp !== prev); )
1482
- ;
1483
- return arr;
1484
- }
1485
-
1486
- // ../../../node_modules/empathic/find.mjs
1487
- function up2(name, options) {
1488
- let dir, tmp, start2 = options && options.cwd || "";
1489
- for (dir of up(start2, options))
1490
- if (tmp = join4(dir, name), existsSync(tmp)) return tmp;
1491
- }
1492
-
1493
- // ../../../node_modules/empathic/package.mjs
1494
- function up3(options) {
1495
- return up2("package.json", options);
1496
- }
1497
- function cache(name, options) {
1498
- options = options || {};
1499
- let dir = env.CACHE_DIR;
1500
- if (!dir || /^(1|0|true|false)$/.test(dir)) {
1501
- let pkg = up3(options);
1502
- if (dir = pkg && dirname3(pkg)) {
1503
- let mods = join5(dir, "node_modules"), exists = existsSync2(mods);
1504
- if (!writable(exists ? mods : dir)) return;
1505
- dir = join5(mods, ".cache");
1506
- }
1507
- }
1508
- if (dir)
1509
- return dir = join5(dir, name), options.create && !existsSync2(dir) && mkdirSync(dir, { recursive: !0 }), dir;
1510
- }
1511
-
1512
- // src/plugins/storybook-external-globals-plugin.ts
1513
- var escapeKeys = (key) => key.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"), defaultImportRegExp = "import ([^*{}]+) from", emptyImportRegExp = /^import(?:\s*\{\s*\}\s*from)?\s*['"][^'"]+['"]\s*;?$/, replacementMap = /* @__PURE__ */ new Map([
1514
- ["import ", "const "],
1515
- ["import{", "const {"],
1516
- ["* as ", ""],
1517
- [" as ", ": "],
1518
- [" from ", " = "],
1519
- ["}from", "} ="]
1520
- ]);
1521
- async function storybookExternalGlobalsPlugin(options) {
1522
- let build3 = await options.presets.apply("build"), externals = globalsNameReferenceMap;
1523
- build3?.test?.disableBlocks && (externals["@storybook/addon-docs/blocks"] = "__STORYBOOK_BLOCKS_EMPTY_MODULE__"), await init;
1524
- let { mergeAlias } = await import("vite"), globalsList = Object.keys(externals), globalsCodeFilter = new RegExp(globalsList.map(escapeKeys).join("|"));
1525
- return {
1526
- name: "storybook:external-globals-plugin",
1527
- enforce: "post",
1528
- // In dev (serve), we set up aliases to files that we write into node_modules/.cache.
1529
- async config(config, { command }) {
1530
- if (command !== "serve")
1531
- return;
1532
- let newAlias = mergeAlias([], config.resolve?.alias), cachePath = cache("sb-vite-plugin-externals", { create: !0 }) ?? join6(process.cwd(), "node_modules", ".cache", "sb-vite-plugin-externals");
1533
- return await Promise.all(
1534
- Object.keys(externals).map(async (externalKey) => {
1535
- let externalCachePath = join6(cachePath, `${externalKey}.js`);
1536
- if (newAlias.push({ find: new RegExp(`^${externalKey}$`), replacement: externalCachePath }), !existsSync3(externalCachePath)) {
1537
- let directory = dirname4(externalCachePath);
1538
- await mkdir(directory, { recursive: !0 });
1539
- }
1540
- await writeFile(externalCachePath, `module.exports = ${externals[externalKey]};`);
1541
- })
1542
- ), {
1543
- resolve: {
1544
- alias: newAlias
1545
- }
1546
- };
1547
- },
1548
- // Replace imports with variables destructured from global scope
1549
- transform: {
1550
- filter: { code: globalsCodeFilter },
1551
- async handler(code, id) {
1552
- if (globalsList.every((glob) => !code.includes(glob)))
1553
- return;
1554
- let [imports] = parse2(code), src = new MagicString(code);
1555
- return imports.forEach(({ n: path2, ss: startPosition, se: endPosition }) => {
1556
- let packageName = path2;
1557
- if (packageName && globalsList.includes(packageName)) {
1558
- let importStatement = src.slice(startPosition, endPosition), transformedImport = rewriteImport(importStatement, externals, packageName);
1559
- src.update(startPosition, endPosition, transformedImport);
1560
- }
1561
- }), {
1562
- code: src.toString(),
1563
- map: null
1564
- };
1565
- }
1566
- }
1567
- };
1568
- }
1569
- function getDefaultImportReplacement(match) {
1570
- let matched = match.match(defaultImportRegExp);
1571
- return matched && `const {default: ${matched[1]}} =`;
1572
- }
1573
- function getEmptyImportReplacement(importStatement, globalReference) {
1574
- if (!emptyImportRegExp.test(importStatement.trim()))
1575
- return;
1576
- let statementTerminator = importStatement.trimEnd().endsWith(";") ? ";" : "";
1577
- return `void ${globalReference}${statementTerminator}`;
1578
- }
1579
- function getSearchRegExp(packageName) {
1580
- let staticKeys = [...replacementMap.keys()].map(escapeKeys), packageNameLiteral = `.${packageName}.`, dynamicImportExpression = `await import\\(.${packageName}.\\)`, lookup = [defaultImportRegExp, ...staticKeys, packageNameLiteral, dynamicImportExpression];
1581
- return new RegExp(`(${lookup.join("|")})`, "g");
1582
- }
1583
- function rewriteImport(importStatement, globs, packageName) {
1584
- let emptyImportReplacement = getEmptyImportReplacement(importStatement, globs[packageName]);
1585
- if (emptyImportReplacement)
1586
- return emptyImportReplacement;
1587
- let search = getSearchRegExp(packageName);
1588
- return importStatement.replace(
1589
- search,
1590
- (match) => replacementMap.get(match) ?? getDefaultImportReplacement(match) ?? globs[packageName]
1591
- );
1592
- }
1593
-
1594
- // src/vite-config.ts
1595
- var configEnvServe = {
1596
- mode: "development",
1597
- command: "serve",
1598
- isSsrBuild: !1
1599
- }, configEnvBuild = {
1600
- mode: "production",
1601
- command: "build",
1602
- isSsrBuild: !1
1603
- };
1604
- async function commonConfig(options, _type) {
1605
- let configEnv = _type === "development" ? configEnvServe : configEnvBuild, { loadConfigFromFile, mergeConfig } = await import("vite"), { viteConfigPath, configLoader } = await getBuilderOptions(options), projectRoot = resolve3(options.configDir, ".."), { config: { build: buildProperty = void 0, ...userConfig } = {} } = await loadConfigFromFile(
1606
- configEnv,
1607
- viteConfigPath,
1608
- projectRoot,
1609
- void 0,
1610
- void 0,
1611
- configLoader
1612
- ) ?? {}, sbConfig = {
1613
- configFile: !1,
1614
- plugins: await pluginConfig(options),
1615
- root: projectRoot,
1616
- // Allow storybook deployed as subfolder. See https://github.com/storybookjs/builder-vite/issues/238
1617
- base: "./",
1618
- ...options.cacheKey ? { cacheDir: resolvePathInStorybookCache("sb-vite", options.cacheKey) } : {},
1619
- // Pass build.target option from user's vite config
1620
- build: {
1621
- target: buildProperty?.target
1622
- }
1623
- };
1624
- return mergeConfig(userConfig, sbConfig);
1625
- }
1626
- async function pluginConfig(options) {
1627
- return [
1628
- // Shared core plugins (resolve conditions, envPrefix, fs.allow, externals, env vars, etc.)
1629
- ...await viteCorePlugins([], options),
1630
- await storybookExternalGlobalsPlugin(options),
1631
- // Entry plugin: virtual modules for stories, addon setup, and main app entry
1632
- ...await storybookEntryPlugin(options),
1633
- // Builder-specific: webpack-compatible stats for turbosnap/chromatic
1634
- pluginWebpackStats({ workingDir: process.cwd() })
1635
- ];
1636
- }
1637
-
1638
124
  // src/build.ts
1639
125
  function findPlugin(config, name) {
1640
126
  return config.plugins?.find((p) => p && "name" in p && p.name === name);
@@ -1646,6 +132,9 @@ async function build(options) {
1646
132
  outDir: options.outputDir,
1647
133
  emptyOutDir: !1,
1648
134
  // do not clean before running Vite build - Storybook has already added assets in there!
135
+ // Storybook copies the public dir itself through the `staticDirs` preset so that its own
136
+ // output files and user `staticDirs` take precedence over public assets.
137
+ copyPublicDir: !1,
1649
138
  // TODO: Remove bundlerOptionsKey and use 'rolldownOptions' directly once support for Vite < 8 is dropped
1650
139
  [bundlerOptionsKey]: {
1651
140
  external: [/\.\/sb-common-assets\/.*\.woff2/]
@@ -1660,21 +149,22 @@ async function build(options) {
1660
149
  }).build;
1661
150
  let finalConfig = await presets.apply("viteFinal", config, options);
1662
151
  finalConfig.plugins?.push({
1663
- name: "storybook:enforce-output-dir",
152
+ name: "storybook:enforce-build-options",
1664
153
  enforce: "post",
1665
154
  config: () => ({
1666
155
  build: {
156
+ emptyOutDir: !1,
1667
157
  outDir: options.outputDir
1668
158
  }
1669
159
  }),
1670
- // configEnvironment is a new method in Vite 6
1671
- // It is used to configure configs based on the environment
1672
- // E.g. Nitro uses this method to set the output directory to .output/public/
1673
- configEnvironment: () => ({
160
+ // Our builds only touch the client environment. No need to change build
161
+ // config for other environments at the expense of third-party plugins.
162
+ configEnvironment: (name) => name === "client" ? {
1674
163
  build: {
164
+ emptyOutDir: !1,
1675
165
  outDir: options.outputDir
1676
166
  }
1677
- })
167
+ } : null
1678
168
  }), options.features?.developmentModeForBuild && finalConfig.plugins?.push({
1679
169
  name: "storybook:define-env",
1680
170
  config: () => ({
@@ -1684,7 +174,7 @@ async function build(options) {
1684
174
  })
1685
175
  });
1686
176
  let turbosnapPluginName = "rollup-plugin-turbosnap";
1687
- return finalConfig.plugins && await hasVitePlugins(finalConfig.plugins, [turbosnapPluginName]) && (logger2.warn(dedent3`Found '${turbosnapPluginName}' which is now included by default in Storybook 8.
177
+ return finalConfig.plugins && await hasVitePlugins(finalConfig.plugins, [turbosnapPluginName]) && (logger2.warn(dedent`Found '${turbosnapPluginName}' which is now included by default in Storybook 8.
1688
178
  Removing from your plugins list. Ensure you pass \`--stats-json\` to generate stats.
1689
179
 
1690
180
  For more information, see https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#turbosnap-vite-plugin-is-no-longer-needed`), finalConfig.plugins = await withoutVitePlugins(finalConfig.plugins, [turbosnapPluginName])), finalConfig.customLogger ??= await createViteLogger(), await viteBuild(finalConfig), findPlugin(
@@ -1736,8 +226,8 @@ function createViteChangeDetectionAdapter(server2) {
1736
226
  };
1737
227
  },
1738
228
  onFileChange(handler) {
1739
- let FORWARDED_EVENTS = /* @__PURE__ */ new Set(["add", "change", "unlink"]), isForwardedEvent = (name) => FORWARDED_EVENTS.has(name), onAll = (eventName, path2) => {
1740
- isForwardedEvent(eventName) && handler({ kind: eventName, path: normalize(path2) });
229
+ let FORWARDED_EVENTS = /* @__PURE__ */ new Set(["add", "change", "unlink"]), isForwardedEvent = (name) => FORWARDED_EVENTS.has(name), onAll = (eventName, path) => {
230
+ isForwardedEvent(eventName) && handler({ kind: eventName, path: normalize(path) });
1741
231
  };
1742
232
  return server2.watcher.on("all", onAll), () => {
1743
233
  server2.watcher.off("all", onAll);
@@ -1772,7 +262,7 @@ async function createViteServer(options, devServer) {
1772
262
  function iframeHandler(options, server2) {
1773
263
  return async (req, res) => {
1774
264
  let indexHtml = await readFile(
1775
- fileURLToPath3(import.meta.resolve("@storybook/builder-vite/input/iframe.html")),
265
+ fileURLToPath(import.meta.resolve("@storybook/builder-vite/input/iframe.html")),
1776
266
  {
1777
267
  encoding: "utf8"
1778
268
  }