vite-plugin-storybook-nextjs 0.0.1--canary.1.c7603ba.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,945 @@
1
+ import path, { resolve, join } from 'node:path';
2
+ import { getDefineEnv } from 'next/dist/build/webpack/plugins/define-env-plugin';
3
+ import { loadEnvConfig } from '@next/env';
4
+ import Log from 'next/dist/build/output/log';
5
+ import { transform, loadBindings, lockfilePatchPromise } from 'next/dist/build/swc';
6
+ import loadConfig from 'next/dist/server/config';
7
+ import { PHASE_TEST, CONFIG_FILES } from 'next/dist/shared/lib/constants';
8
+ import fs from 'node:fs/promises';
9
+ import { fetchCSSFromGoogleFonts } from 'next/dist/compiled/@next/font/dist/google/fetch-css-from-google-fonts';
10
+ import { getFontAxes } from 'next/dist/compiled/@next/font/dist/google/get-font-axes';
11
+ import { getGoogleFontsUrl } from 'next/dist/compiled/@next/font/dist/google/get-google-fonts-url';
12
+ import { validateGoogleFontFunctionCall } from 'next/dist/compiled/@next/font/dist/google/validate-google-font-function-call';
13
+ import loaderUtils from 'next/dist/compiled/loader-utils3';
14
+ import { validateLocalFontFunctionCall } from 'next/dist/compiled/@next/font/dist/local/validate-local-font-function-call';
15
+ import dedent3, { dedent } from 'ts-dedent';
16
+ import loadJsConfig from 'next/dist/build/load-jsconfig';
17
+ import { findPagesDir } from 'next/dist/lib/find-pages-dir';
18
+ import { getSupportedBrowsers } from 'next/dist/build/utils';
19
+ import { getParserOptions } from 'next/dist/build/swc/options';
20
+ import fs2 from 'node:fs';
21
+ import { cpus } from 'node:os';
22
+ import { fileURLToPath, URL } from 'node:url';
23
+ import imageSizeOf from 'image-size';
24
+
25
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
26
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
27
+ }) : x)(function(x) {
28
+ if (typeof require !== "undefined") return require.apply(this, arguments);
29
+ throw Error('Dynamic require of "' + x + '" is not supported');
30
+ });
31
+ var nextDistPath = /(next[\\/]dist[\\/]shared[\\/]lib)|(next[\\/]dist[\\/]client)|(next[\\/]dist[\\/]pages)/;
32
+ async function getConfig(dir) {
33
+ const conf = await loadConfig(PHASE_TEST, dir);
34
+ return conf;
35
+ }
36
+ async function getConfigPaths(dir) {
37
+ return CONFIG_FILES.map((file) => join(dir, file));
38
+ }
39
+ async function loadEnvironmentConfig(dir) {
40
+ const dev = false;
41
+ return loadEnvConfig(dir, dev, Log);
42
+ }
43
+ async function loadSWCBindingsEagerly(nextConfig) {
44
+ await loadBindings(nextConfig?.experimental?.useWasmBinary);
45
+ if (lockfilePatchPromise.cur) {
46
+ await lockfilePatchPromise.cur;
47
+ }
48
+ }
49
+ function shouldOutputCommonJs(filename) {
50
+ return filename.endsWith(".cjs") || nextDistPath.test(filename);
51
+ }
52
+
53
+ // src/plugins/next-env/plugin.ts
54
+ function vitePluginNextConfig(rootDir) {
55
+ let nextConfig;
56
+ let envConfig;
57
+ let isDev;
58
+ const resolvedDir = resolve(rootDir);
59
+ return {
60
+ name: "vite-plugin-storybook-nextjs-swc",
61
+ async config(config, env) {
62
+ nextConfig = await getConfig(resolvedDir);
63
+ envConfig = (await loadEnvironmentConfig(resolvedDir)).combinedEnv;
64
+ isDev = env.mode === "development";
65
+ const publicNextEnvMap = Object.fromEntries(
66
+ Object.entries(envConfig).filter(([key]) => key.startsWith("NEXT_PUBLIC_")).map(([key, value]) => {
67
+ return [`process.env.${key}`, JSON.stringify(value)];
68
+ })
69
+ );
70
+ return {
71
+ ...config,
72
+ define: {
73
+ ...config.define,
74
+ ...publicNextEnvMap,
75
+ ...getDefineEnv({
76
+ isTurbopack: false,
77
+ config: nextConfig,
78
+ isClient: true,
79
+ isEdgeServer: false,
80
+ isNodeOrEdgeCompilation: false,
81
+ isNodeServer: false,
82
+ clientRouterFilters: void 0,
83
+ dev: isDev,
84
+ middlewareMatchers: void 0,
85
+ hasRewrites: false,
86
+ distDir: nextConfig.distDir,
87
+ fetchCacheKeyPrefix: nextConfig?.experimental?.fetchCacheKeyPrefix
88
+ })
89
+ }
90
+ };
91
+ }
92
+ };
93
+ }
94
+ var cssCache = /* @__PURE__ */ new Map();
95
+ async function getFontFaceDeclarations(options) {
96
+ const {
97
+ fontFamily,
98
+ weights,
99
+ styles,
100
+ selectedVariableAxes,
101
+ display,
102
+ variable
103
+ } = validateGoogleFontFunctionCall(options.fontFamily, options.props);
104
+ const fontAxes = getFontAxes(
105
+ fontFamily,
106
+ weights,
107
+ styles,
108
+ selectedVariableAxes
109
+ );
110
+ const url = getGoogleFontsUrl(fontFamily, fontAxes, display);
111
+ try {
112
+ const hasCachedCSS = cssCache.has(url);
113
+ const fontFaceCSS = hasCachedCSS ? cssCache.get(url) : await fetchCSSFromGoogleFonts(url, fontFamily, true).catch(() => null);
114
+ if (!hasCachedCSS) {
115
+ cssCache.set(url, fontFaceCSS);
116
+ } else {
117
+ cssCache.delete(url);
118
+ }
119
+ if (fontFaceCSS === null) {
120
+ throw new Error(
121
+ `Failed to fetch \`${fontFamily}\` from Google Fonts with URL: \`${url}\``
122
+ );
123
+ }
124
+ return {
125
+ id: loaderUtils.getHashDigest(url, "md5", "hex", 6),
126
+ fontFamily,
127
+ fontFaceCSS,
128
+ weights,
129
+ styles,
130
+ variable
131
+ };
132
+ } catch (error) {
133
+ throw new Error(
134
+ `Failed to fetch \`${fontFamily}\` from Google Fonts with URL: \`${url}\``
135
+ );
136
+ }
137
+ }
138
+ var getPlaceholderFontUrl = (refId) => `__%%import.meta.ROLLUP_FILE_URL_${refId}%%__`;
139
+ getPlaceholderFontUrl.regexp = /__%%import\.meta\.ROLLUP_FILE_URL_(.*?)%%__/g;
140
+ async function getFontFaceDeclarations2(options) {
141
+ const localFontSrc = options.props.metaSrc;
142
+ const {
143
+ weight,
144
+ style,
145
+ variable,
146
+ declarations = []
147
+ } = validateLocalFontFunctionCall("", options.props);
148
+ const id = `font-${loaderUtils.getHashDigest(
149
+ Buffer.from(JSON.stringify(localFontSrc)),
150
+ "md5",
151
+ "hex",
152
+ 6
153
+ )}`;
154
+ const fontDeclarations = declarations.map(
155
+ ({ prop, value }) => `${prop}: ${value};`
156
+ ).join("\n");
157
+ const getFontFaceCSS = () => {
158
+ if (localFontSrc) {
159
+ if ("fontReferenceId" in localFontSrc) {
160
+ return dedent`@font-face {
161
+ font-family: ${id};
162
+ src: url(${localFontSrc.fontReferenceId ? getPlaceholderFontUrl(localFontSrc.fontReferenceId) : `.${localFontSrc.fontPath}`})
163
+ ${fontDeclarations}
164
+ }`;
165
+ }
166
+ return localFontSrc.map((font) => {
167
+ return dedent`@font-face {
168
+ font-family: ${id};
169
+ src: url(${font.path.fontReferenceId ? getPlaceholderFontUrl(font.path.fontReferenceId) : `.${font.path.fontPath}`});
170
+ ${font.weight ? `font-weight: ${font.weight};` : ""}
171
+ ${font.style ? `font-style: ${font.style};` : ""}
172
+ ${fontDeclarations}
173
+ }`;
174
+ }).join("");
175
+ }
176
+ return "";
177
+ };
178
+ return {
179
+ id,
180
+ fontFamily: id,
181
+ fontFaceCSS: getFontFaceCSS(),
182
+ weights: weight ? [weight] : [],
183
+ styles: style ? [style] : [],
184
+ variable
185
+ };
186
+ }
187
+
188
+ // src/plugins/next-font/utils/get-css-meta.ts
189
+ function getCSSMeta(options) {
190
+ const className = getClassName(options);
191
+ const style = getStylesObj(options);
192
+ const variableClassName = `__variable_${className}`;
193
+ const classNamesCSS = `
194
+ .${className} {
195
+ font-family: ${options.fontFamily};
196
+ ${isNextCSSPropertyValid(options.styles) ? `font-style: ${options.styles[0]};` : ""}
197
+ ${isNextCSSPropertyValid(options.weights) ? `font-weight: ${options.weights[0]};` : ""}
198
+ }
199
+
200
+ ${options.variable ? `.${variableClassName} { ${options.variable}: '${options.fontFamily}'; }` : ""}
201
+ `;
202
+ const fontFaceCSS = `${changeFontDisplayToSwap(options.fontFaceCSS)}`;
203
+ return {
204
+ className,
205
+ fontFaceCSS,
206
+ classNamesCSS,
207
+ style,
208
+ ...options.variable ? { variableClassName } : {}
209
+ };
210
+ }
211
+ function getClassName({ styles, weights, fontFamily }) {
212
+ const font = fontFamily.replaceAll(" ", "-").toLowerCase();
213
+ const style = isNextCSSPropertyValid(styles) ? styles[0] : null;
214
+ const weight = isNextCSSPropertyValid(weights) ? weights[0] : null;
215
+ return `${font}${style ? `-${style}` : ""}${weight ? `-${weight}` : ""}`;
216
+ }
217
+ function getStylesObj({ styles, weights, fontFamily }) {
218
+ return {
219
+ fontFamily,
220
+ ...isNextCSSPropertyValid(styles) ? { fontStyle: styles[0] } : {},
221
+ ...isNextCSSPropertyValid(weights) ? { fontWeight: weights[0] } : {}
222
+ };
223
+ }
224
+ function isNextCSSPropertyValid(prop) {
225
+ return prop.length === 1 && prop[0] !== "variable";
226
+ }
227
+ function changeFontDisplayToSwap(css) {
228
+ return css.replaceAll("font-display: optional;", "font-display: block;");
229
+ }
230
+ function setFontDeclarationsInHead({
231
+ id,
232
+ fontFaceCSS,
233
+ classNamesCSS
234
+ }) {
235
+ const regex = new RegExp(getPlaceholderFontUrl.regexp);
236
+ const fontPaths = fontFaceCSS.matchAll(regex);
237
+ const fontPathsImportUrls = [];
238
+ if (fontPaths) {
239
+ for (const match of fontFaceCSS.matchAll(regex)) {
240
+ fontPathsImportUrls.push({
241
+ id: match[1],
242
+ path: match[0].replaceAll(/__%%|%%__/g, "")
243
+ });
244
+ }
245
+ }
246
+ return dedent3`
247
+ const fontPaths = [${fontPathsImportUrls.map((fontPath) => `{id: '${fontPath.id}', path: ${fontPath.path}}`).join(", ")}];
248
+ if (!document.getElementById('id-${id}')) {
249
+ let fontDeclarations = \`${fontFaceCSS}\`;
250
+ fontPaths.forEach((fontPath, i) => {
251
+ fontDeclarations = fontDeclarations.replace('__%%import.meta.ROLLUP_FILE_URL_' + fontPath.id + '%%__', fontPath.path.toString());
252
+ });
253
+ const style = document.createElement('style');
254
+ style.setAttribute('id', 'font-face-${id}');
255
+ style.innerHTML = fontDeclarations;
256
+ document.head.appendChild(style);
257
+
258
+ const classNamesCSS = \`${classNamesCSS}\`;
259
+ const classNamesStyle = document.createElement('style');
260
+ classNamesStyle.setAttribute('id', 'classnames-${id}');
261
+ classNamesStyle.innerHTML = classNamesCSS;
262
+ document.head.appendChild(classNamesStyle);
263
+ }
264
+ `;
265
+ }
266
+
267
+ // src/plugins/next-font/plugin.ts
268
+ var includePattern = /next(\\|\/|\\\\).*(\\|\/|\\\\)target\.css.*$/;
269
+ var virtualModuleId = "virtual:next-font";
270
+ function configureNextFont() {
271
+ let devMode = true;
272
+ const fontAssetPaths = /* @__PURE__ */ new Map();
273
+ return {
274
+ name: "configure-next-font",
275
+ async config(config, env) {
276
+ devMode = env.mode === "development";
277
+ return config;
278
+ },
279
+ configureServer(server) {
280
+ server.middlewares.use(async (req, res, next) => {
281
+ if (req.url && fontAssetPaths.has(req.url)) {
282
+ const fontAbsoluteAssetPath = fontAssetPaths.get(req.url);
283
+ const fontFileExtension = path.extname(fontAbsoluteAssetPath);
284
+ try {
285
+ const fontData = await fs.readFile(fontAbsoluteAssetPath);
286
+ switch (fontFileExtension) {
287
+ case ".woff":
288
+ res.setHeader("Content-Type", "font/woff");
289
+ break;
290
+ case ".woff2":
291
+ res.setHeader("Content-Type", "font/woff2");
292
+ break;
293
+ case ".ttf":
294
+ res.setHeader("Content-Type", "font/ttf");
295
+ break;
296
+ case ".otf":
297
+ res.setHeader("Content-Type", "font/otf");
298
+ break;
299
+ default:
300
+ res.setHeader("Content-Type", "font");
301
+ }
302
+ res.end(fontData);
303
+ } catch (e) {
304
+ console.error(
305
+ `Could not read font file ${fontAbsoluteAssetPath}:`,
306
+ e
307
+ );
308
+ res.statusCode = 404;
309
+ res.end();
310
+ }
311
+ } else {
312
+ next();
313
+ }
314
+ });
315
+ },
316
+ async resolveId(source, importer) {
317
+ if (!includePattern.test(source) || !importer) {
318
+ return null;
319
+ }
320
+ const [sourceWithoutQuery, rawQuery] = source.split("?");
321
+ const queryParams = JSON.parse(rawQuery);
322
+ const fontOptions = {
323
+ filename: queryParams.path ?? "",
324
+ fontFamily: queryParams.import ?? "",
325
+ props: queryParams.arguments?.[0] ?? {},
326
+ source: importer
327
+ };
328
+ if (fontOptions.source.endsWith("html")) {
329
+ return null;
330
+ }
331
+ let fontFaceDeclaration;
332
+ const pathSep = path.sep;
333
+ if (sourceWithoutQuery.endsWith(
334
+ ["next", "font", "google", "target.css"].join(pathSep)
335
+ )) {
336
+ fontFaceDeclaration = await getFontFaceDeclarations(fontOptions);
337
+ }
338
+ if (sourceWithoutQuery.endsWith(
339
+ ["next", "font", "local", "target.css"].join(pathSep)
340
+ )) {
341
+ const importerDirPath = path.dirname(fontOptions.filename);
342
+ const emitFont = async (importerRelativeFontPath) => {
343
+ const fontExtension = path.extname(importerRelativeFontPath);
344
+ const fontBaseName = path.basename(
345
+ importerRelativeFontPath,
346
+ fontExtension
347
+ );
348
+ const fontPath = path.join(importerDirPath, importerRelativeFontPath);
349
+ if (devMode) {
350
+ fontAssetPaths.set(importerRelativeFontPath, fontPath);
351
+ return {
352
+ fontPath: importerRelativeFontPath,
353
+ fontReferenceId: void 0
354
+ };
355
+ }
356
+ try {
357
+ const fontData = await fs.readFile(fontPath);
358
+ const fontReferenceId = this.emitFile({
359
+ name: `${fontBaseName}${fontExtension}`,
360
+ type: "asset",
361
+ source: fontData
362
+ });
363
+ return { fontReferenceId, fontPath };
364
+ } catch (err) {
365
+ console.error(`Could not read font file ${fontPath}:`, err);
366
+ return void 0;
367
+ }
368
+ };
369
+ const loaderOptions = {
370
+ ...fontOptions
371
+ };
372
+ if (loaderOptions) {
373
+ if (typeof fontOptions.props.src === "string") {
374
+ const font = await emitFont(fontOptions.props.src);
375
+ loaderOptions.props.metaSrc = font;
376
+ } else {
377
+ loaderOptions.props.metaSrc = (await Promise.all(
378
+ (fontOptions.props.src ?? []).map(async (fontSrc) => {
379
+ const font = await emitFont(fontSrc.path);
380
+ if (!font) {
381
+ return void 0;
382
+ }
383
+ return {
384
+ ...fontSrc,
385
+ path: font
386
+ };
387
+ })
388
+ )).filter((font) => font !== void 0);
389
+ }
390
+ }
391
+ fontFaceDeclaration = await getFontFaceDeclarations2(loaderOptions);
392
+ }
393
+ return {
394
+ id: `${virtualModuleId}?${rawQuery}`,
395
+ meta: {
396
+ fontFaceDeclaration
397
+ }
398
+ };
399
+ },
400
+ load(id) {
401
+ const [source] = id.split("?");
402
+ if (source !== virtualModuleId) {
403
+ return void 0;
404
+ }
405
+ const moduleInfo = this.getModuleInfo(id);
406
+ const fontFaceDeclaration = moduleInfo?.meta?.fontFaceDeclaration;
407
+ if (typeof fontFaceDeclaration !== "undefined") {
408
+ const cssMeta = getCSSMeta(fontFaceDeclaration);
409
+ return `
410
+ ${setFontDeclarationsInHead({
411
+ fontFaceCSS: cssMeta.fontFaceCSS,
412
+ id: fontFaceDeclaration.id,
413
+ classNamesCSS: cssMeta.classNamesCSS
414
+ })}
415
+
416
+ export default {
417
+ className: "${cssMeta.className}",
418
+ style: ${JSON.stringify(cssMeta.style)}
419
+ ${cssMeta.variableClassName ? `, variable: "${cssMeta.variableClassName}"` : ""}
420
+ }
421
+ `;
422
+ }
423
+ return "export default {}";
424
+ }
425
+ };
426
+ }
427
+
428
+ // src/utils/swc/styles.ts
429
+ function getStyledComponentsOptions(styledComponentsConfig, development) {
430
+ if (!styledComponentsConfig) {
431
+ return null;
432
+ }
433
+ if (typeof styledComponentsConfig === "object") {
434
+ return {
435
+ ...styledComponentsConfig,
436
+ displayName: styledComponentsConfig.displayName ?? Boolean(development)
437
+ };
438
+ }
439
+ return {
440
+ displayName: Boolean(development)
441
+ };
442
+ }
443
+ function getEmotionOptions(emotionConfig, development) {
444
+ if (!emotionConfig) {
445
+ return null;
446
+ }
447
+ let autoLabel = !!development;
448
+ switch (typeof emotionConfig === "object" && emotionConfig.autoLabel) {
449
+ case "never":
450
+ autoLabel = false;
451
+ break;
452
+ case "always":
453
+ autoLabel = true;
454
+ break;
455
+ }
456
+ return {
457
+ enabled: true,
458
+ autoLabel,
459
+ sourcemap: development,
460
+ ...typeof emotionConfig === "object" && {
461
+ importMap: emotionConfig.importMap,
462
+ labelFormat: emotionConfig.labelFormat,
463
+ sourcemap: development && emotionConfig.sourceMap
464
+ }
465
+ };
466
+ }
467
+
468
+ // src/utils/swc/options.ts
469
+ var regeneratorRuntimePath = __require.resolve(
470
+ "next/dist/compiled/regenerator-runtime"
471
+ );
472
+ function getBaseSWCOptions({
473
+ filename,
474
+ development,
475
+ hasReactRefresh,
476
+ globalWindow,
477
+ esm,
478
+ modularizeImports,
479
+ swcPlugins,
480
+ compilerOptions,
481
+ resolvedBaseUrl,
482
+ jsConfig,
483
+ swcCacheDir
484
+ }) {
485
+ const parserConfig = getParserOptions({ filename, jsConfig });
486
+ const paths = jsConfig?.compilerOptions?.paths;
487
+ const enableDecorators = Boolean(
488
+ jsConfig?.compilerOptions?.experimentalDecorators
489
+ );
490
+ const emitDecoratorMetadata = Boolean(
491
+ jsConfig?.compilerOptions?.emitDecoratorMetadata
492
+ );
493
+ const useDefineForClassFields = Boolean(
494
+ jsConfig?.compilerOptions?.useDefineForClassFields
495
+ );
496
+ const plugins = (swcPlugins ?? []).filter(Array.isArray).map(([name, options]) => [__require.resolve(name), options]);
497
+ return {
498
+ jsc: {
499
+ ...resolvedBaseUrl && paths ? {
500
+ baseUrl: resolvedBaseUrl.baseUrl,
501
+ paths
502
+ } : {},
503
+ externalHelpers: false,
504
+ parser: parserConfig,
505
+ experimental: {
506
+ keepImportAttributes: true,
507
+ emitAssertForImportAttributes: true,
508
+ plugins,
509
+ cacheRoot: swcCacheDir
510
+ },
511
+ transform: {
512
+ legacyDecorator: enableDecorators,
513
+ decoratorMetadata: emitDecoratorMetadata,
514
+ useDefineForClassFields,
515
+ react: {
516
+ importSource: jsConfig?.compilerOptions?.jsxImportSource ?? (compilerOptions?.emotion ? "@emotion/react" : "react"),
517
+ runtime: "automatic",
518
+ pragmaFrag: "React.Fragment",
519
+ throwIfNamespace: true,
520
+ development: !!development,
521
+ useBuiltins: true,
522
+ refresh: !!hasReactRefresh
523
+ },
524
+ optimizer: {
525
+ simplify: false,
526
+ // TODO: Figuring out for what globals are exactly used for
527
+ globals: {
528
+ typeofs: {
529
+ window: globalWindow ? "object" : "undefined"
530
+ },
531
+ envs: {
532
+ NODE_ENV: development ? '"development"' : '"production"'
533
+ }
534
+ }
535
+ },
536
+ regenerator: {
537
+ importPath: regeneratorRuntimePath
538
+ }
539
+ }
540
+ },
541
+ sourceMaps: "inline",
542
+ removeConsole: compilerOptions?.removeConsole,
543
+ reactRemoveProperties: false,
544
+ // Map the k-v map to an array of pairs.
545
+ modularizeImports: modularizeImports ? Object.fromEntries(
546
+ Object.entries(modularizeImports).map(([mod, config]) => [
547
+ mod,
548
+ {
549
+ ...config,
550
+ transform: typeof config.transform === "string" ? config.transform : Object.entries(config.transform).map(([key, value]) => [
551
+ key,
552
+ value
553
+ ])
554
+ }
555
+ ])
556
+ ) : void 0,
557
+ relay: compilerOptions?.relay,
558
+ // Always transform styled-jsx and error when `client-only` condition is triggered
559
+ styledJsx: {},
560
+ // Disable css-in-js libs (without client-only integration) transform on server layer for server components
561
+ emotion: getEmotionOptions(compilerOptions?.emotion, development),
562
+ // eslint-disable-next-line @typescript-eslint/no-use-before-define
563
+ styledComponents: getStyledComponentsOptions(
564
+ compilerOptions?.styledComponents,
565
+ development
566
+ ),
567
+ serverComponents: void 0,
568
+ serverActions: void 0,
569
+ // For app router we prefer to bundle ESM,
570
+ // On server side of pages router we prefer CJS.
571
+ preferEsm: esm
572
+ };
573
+ }
574
+
575
+ // src/utils/swc/transform.ts
576
+ var getVitestSWCTransformConfig = ({
577
+ filename,
578
+ inputSourceMap,
579
+ isServerEnvironment,
580
+ loadedJSConfig,
581
+ nextDirectories,
582
+ nextConfig,
583
+ rootDir,
584
+ isDev
585
+ }) => {
586
+ const esm = true;
587
+ const baseOptions = getBaseSWCOptions({
588
+ filename,
589
+ development: false,
590
+ hasReactRefresh: false,
591
+ globalWindow: !isServerEnvironment,
592
+ modularizeImports: nextConfig.modularizeImports,
593
+ jsConfig: loadedJSConfig.jsConfig,
594
+ resolvedBaseUrl: loadedJSConfig.resolvedBaseUrl,
595
+ swcPlugins: nextConfig.experimental.swcPlugins,
596
+ compilerOptions: nextConfig?.compilerOptions,
597
+ esm,
598
+ swcCacheDir: path.join(
599
+ rootDir,
600
+ nextConfig.distDir ?? ".next",
601
+ "cache",
602
+ "swc"
603
+ )
604
+ });
605
+ const useCjsModules = shouldOutputCommonJs(filename);
606
+ return {
607
+ ...baseOptions,
608
+ fontLoaders: {
609
+ fontLoaders: ["next/font/local", "next/font/google"],
610
+ relativeFilePathFromRoot: path.relative(rootDir, filename)
611
+ },
612
+ cjsRequireOptimizer: {
613
+ packages: {
614
+ "next/server": {
615
+ transforms: {
616
+ NextRequest: "next/dist/server/web/spec-extension/request",
617
+ NextResponse: "next/dist/server/web/spec-extension/response",
618
+ ImageResponse: "next/dist/server/web/spec-extension/image-response",
619
+ userAgentFromString: "next/dist/server/web/spec-extension/user-agent",
620
+ userAgent: "next/dist/server/web/spec-extension/user-agent"
621
+ }
622
+ }
623
+ }
624
+ },
625
+ ...isServerEnvironment ? {
626
+ env: {
627
+ targets: {
628
+ // Targets the current version of Node.js
629
+ node: process.versions.node
630
+ }
631
+ }
632
+ } : {
633
+ env: {
634
+ targets: getSupportedBrowsers(rootDir, isDev)
635
+ }
636
+ },
637
+ module: {
638
+ type: esm && !useCjsModules ? "es6" : "commonjs"
639
+ },
640
+ disableNextSsg: true,
641
+ disablePageConfig: true,
642
+ pagesDir: nextDirectories.pagesDir,
643
+ appDir: nextDirectories.appDir,
644
+ inputSourceMap: inputSourceMap && typeof inputSourceMap === "object" ? JSON.stringify(inputSourceMap) : void 0,
645
+ sourceFileName: filename,
646
+ filename
647
+ };
648
+ };
649
+
650
+ // src/utils/typescript.ts
651
+ var isDefined = (value) => value !== void 0;
652
+
653
+ // src/plugins/next-swc/plugin.ts
654
+ var excluded = /[\\/](cache[\\/][^\\/]+\.zip[\\/]node_modules|virtual:)[\\/]/g;
655
+ var included = /\.((c|m)?(j|t)sx?)$/;
656
+ function vitePluginNextSwc(rootDir, nextConfigResolver) {
657
+ let loadedJSConfig;
658
+ let nextDirectories;
659
+ let isServerEnvironment;
660
+ let isDev;
661
+ const resolvedDir = resolve(rootDir);
662
+ return {
663
+ name: "vite-plugin-storybook-nextjs-swc",
664
+ async config(config, env) {
665
+ const nextConfig = await nextConfigResolver.promise;
666
+ nextDirectories = findPagesDir(resolvedDir);
667
+ loadedJSConfig = await loadJsConfig(resolvedDir, nextConfig);
668
+ (await loadEnvironmentConfig(resolvedDir)).combinedEnv;
669
+ isDev = env.mode === "development";
670
+ await loadSWCBindingsEagerly(nextConfig);
671
+ const serverWatchIgnored = config.server?.watch?.ignored;
672
+ const isServerWatchIgnoredArray = Array.isArray(serverWatchIgnored);
673
+ if (config.test?.environment === "node" || config.test?.environment === "edge-runtime" || config.test?.browser?.enabled !== false) {
674
+ isServerEnvironment = true;
675
+ }
676
+ return {
677
+ resolve: {
678
+ alias: {
679
+ "@opentelemetry/api": "next/dist/compiled/@opentelemetry/api"
680
+ }
681
+ },
682
+ esbuild: {
683
+ // We will use Next.js custom SWC transpiler instead of Vite's build-in esbuild
684
+ exclude: [/node_modules/, /.m?(t|j)sx?/]
685
+ },
686
+ server: {
687
+ watch: {
688
+ ignored: [
689
+ ...isServerWatchIgnoredArray ? serverWatchIgnored : [serverWatchIgnored],
690
+ "/.next/"
691
+ ].filter(isDefined)
692
+ }
693
+ }
694
+ };
695
+ },
696
+ async transform(code, id) {
697
+ if (!excluded.test(id) && included.test(id)) {
698
+ const inputSourceMap = this.getCombinedSourcemap();
699
+ const output = await transform(
700
+ code,
701
+ getVitestSWCTransformConfig({
702
+ filename: id,
703
+ inputSourceMap,
704
+ isServerEnvironment,
705
+ loadedJSConfig,
706
+ nextConfig: await nextConfigResolver.promise,
707
+ nextDirectories,
708
+ rootDir,
709
+ isDev
710
+ })
711
+ );
712
+ return output;
713
+ }
714
+ }
715
+ };
716
+ }
717
+
718
+ // src/polyfills/promise-with-resolvers.ts
719
+ if (typeof Promise.withResolvers === "undefined") {
720
+ Promise.withResolvers = () => {
721
+ let resolve4;
722
+ let reject;
723
+ const promise = new Promise((res, rej) => {
724
+ resolve4 = res;
725
+ reject = rej;
726
+ });
727
+ return { promise, resolve: resolve4, reject };
728
+ };
729
+ }
730
+ var includePattern2 = /\.(png|jpg|jpeg|gif|webp|avif|ico|bmp|svg)$/;
731
+ var excludeImporterPattern = /\.(css|scss|sass)$/;
732
+ var virtualImage = "virtual:next-image";
733
+ var virtualNextImage = "virtual:next/image";
734
+ var virtualNextLegacyImage = "virtual:next/legacy/image";
735
+ var virtualNextImageDefaultLoader = "virtual:next/image-default-loader";
736
+ var virtualNextImageContext = "virtual:next/image-context";
737
+ var sharp;
738
+ try {
739
+ sharp = __require("sharp");
740
+ if (sharp && sharp.concurrency() > 1) {
741
+ const divisor = process.env.NODE_ENV === "development" ? 4 : 2;
742
+ sharp.concurrency(Math.floor(Math.max(cpus().length / divisor, 1)));
743
+ }
744
+ } catch (e) {
745
+ console.warn(
746
+ "You have to install sharp in order to use image optimization features in Next.js. AVIF support is also disabled."
747
+ );
748
+ }
749
+ function vitePluginNextImage(nextConfigResolver) {
750
+ return {
751
+ name: "vite-plugin-storybook-nextjs-image",
752
+ config(config, env) {
753
+ env.mode === "development";
754
+ return {
755
+ ...config,
756
+ resolve: {
757
+ ...config.resolve,
758
+ alias: {
759
+ react: "next/dist/compiled/react",
760
+ "react-dom": "next/dist/compiled/react-dom"
761
+ }
762
+ }
763
+ };
764
+ },
765
+ async resolveId(id, importer) {
766
+ if (includePattern2.test(id) && !excludeImporterPattern.test(importer ?? "") && !importer?.startsWith(virtualImage)) {
767
+ return {
768
+ id: `${virtualImage}?${id}`,
769
+ meta: {
770
+ id,
771
+ importer: importer ?? ""
772
+ }
773
+ };
774
+ }
775
+ if (id === "next/image" && importer !== virtualNextImage) {
776
+ return virtualNextImage;
777
+ }
778
+ if (id === "next/legacy/image" && importer !== virtualNextLegacyImage) {
779
+ return virtualNextLegacyImage;
780
+ }
781
+ if (id === "sb-original/image-context") {
782
+ return virtualNextImageContext;
783
+ }
784
+ if (id === "sb-original/default-loader") {
785
+ return virtualNextImageDefaultLoader;
786
+ }
787
+ return null;
788
+ },
789
+ async load(id) {
790
+ if (virtualNextImage === id) {
791
+ return (await fs2.promises.readFile(
792
+ fileURLToPath(
793
+ new URL(
794
+ "./plugins/next-image/alias/next-image.js",
795
+ import.meta.url
796
+ )
797
+ )
798
+ )).toString("utf-8");
799
+ }
800
+ if (virtualNextLegacyImage === id) {
801
+ return (await fs2.promises.readFile(
802
+ fileURLToPath(
803
+ new URL(
804
+ "./plugins/next-image/alias/next-legacy-image.js",
805
+ import.meta.url
806
+ )
807
+ )
808
+ )).toString("utf-8");
809
+ }
810
+ if (virtualNextImageDefaultLoader === id) {
811
+ return (await fs2.promises.readFile(
812
+ fileURLToPath(
813
+ new URL(
814
+ "./plugins/next-image/alias/image-default-loader.js",
815
+ import.meta.url
816
+ )
817
+ )
818
+ )).toString("utf-8");
819
+ }
820
+ if (virtualNextImageContext === id) {
821
+ return (await fs2.promises.readFile(
822
+ fileURLToPath(
823
+ new URL(
824
+ "./plugins/next-image/alias/image-context.js",
825
+ import.meta.url
826
+ )
827
+ )
828
+ )).toString("utf-8");
829
+ }
830
+ const [source] = id.split("?");
831
+ if (virtualImage === source) {
832
+ const moduleInfo = this.getModuleInfo(id);
833
+ const meta = moduleInfo?.meta;
834
+ path.basename(id);
835
+ const nextConfig = await nextConfigResolver.promise;
836
+ const extension = meta.id.split(".").pop();
837
+ const imagePath = path.join(path.dirname(meta.importer), meta.id);
838
+ try {
839
+ if (nextConfig.images?.disableStaticImages) {
840
+ return dedent3`
841
+ import image from "${imagePath}";
842
+ export default image;
843
+ `;
844
+ }
845
+ const imageData = await fs2.promises.readFile(imagePath);
846
+ let width;
847
+ let height;
848
+ if (extension === "avif" && sharp) {
849
+ const transformer = sharp(Buffer.from(imageData));
850
+ const result = await transformer.metadata();
851
+ width = result.width;
852
+ height = result.height;
853
+ } else {
854
+ const result = imageSizeOf(imageData);
855
+ width = result.width;
856
+ height = result.height;
857
+ }
858
+ return dedent3`
859
+ import src from "${imagePath}";
860
+ export default {
861
+ src,
862
+ height: ${height},
863
+ width: ${width},
864
+ blurDataURL: src
865
+ };
866
+ `;
867
+ } catch (err) {
868
+ console.error(`Could not read font file ${imagePath}:`, err);
869
+ return void 0;
870
+ }
871
+ }
872
+ return null;
873
+ }
874
+ };
875
+ }
876
+
877
+ // src/index.ts
878
+ function VitePlugin({ dir = process.cwd() } = {}) {
879
+ const resolvedDir = resolve(dir);
880
+ const nextConfigResolver = Promise.withResolvers();
881
+ const nextFontPlugin = configureNextFont();
882
+ const nextSwcPlugin = vitePluginNextSwc(dir, nextConfigResolver);
883
+ const nextEnvPlugin = vitePluginNextConfig(dir);
884
+ const nextImagePlugin = vitePluginNextImage(nextConfigResolver);
885
+ return {
886
+ name: "vite-plugin-storybook-nextjs",
887
+ async buildStart() {
888
+ for (const configPath of await getConfigPaths(resolvedDir)) {
889
+ this.addWatchFile(configPath);
890
+ }
891
+ },
892
+ enforce: "pre",
893
+ configureServer(server) {
894
+ nextFontPlugin.configureServer.call(this, server);
895
+ },
896
+ async config(config, env) {
897
+ nextConfigResolver.resolve(await getConfig(resolvedDir));
898
+ const mergedNextSwcConfig = await nextSwcPlugin.config.call(
899
+ this,
900
+ config,
901
+ env
902
+ );
903
+ const mergedNextEnvConfig = await nextEnvPlugin.config.call(
904
+ this,
905
+ mergedNextSwcConfig,
906
+ env
907
+ );
908
+ const mergedNextFontConfig = await nextFontPlugin.config.call(
909
+ this,
910
+ mergedNextEnvConfig,
911
+ env
912
+ );
913
+ const mergedNextImageConfig = await nextImagePlugin.config.call(
914
+ this,
915
+ mergedNextFontConfig,
916
+ env
917
+ );
918
+ return mergedNextImageConfig;
919
+ },
920
+ async resolveId(source, importer, options) {
921
+ const nextFontResolver = await nextFontPlugin.resolveId.call(
922
+ this,
923
+ source,
924
+ importer
925
+ );
926
+ if (nextFontResolver) {
927
+ return nextFontResolver;
928
+ }
929
+ return nextImagePlugin.resolveId.call(this, source, importer);
930
+ },
931
+ load(id) {
932
+ const nextFontLoaderResult = nextFontPlugin.load.call(this, id);
933
+ if (nextFontLoaderResult) {
934
+ return nextFontLoaderResult;
935
+ }
936
+ return nextImagePlugin.load.call(this, id);
937
+ },
938
+ transform(code, id) {
939
+ return nextSwcPlugin.transform.call(this, code, id);
940
+ }
941
+ };
942
+ }
943
+ var src_default = VitePlugin;
944
+
945
+ export { src_default as default };