123456789101112131415 |
- import { join, dirname, parse, relative, sep, basename, normalize } from 'path';
- import fs4 from 'fs-extra';
- import express from 'express';
- import { logger } from '@storybook/node-logger';
- import { globalExternals } from '@fal-works/esbuild-plugin-global-externals';
- import { pnpPlugin } from '@yarnpkg/esbuild-plugin-pnp';
- import aliasPlugin from 'esbuild-plugin-alias';
- import { stringifyProcessEnvs, getRefs } from '@storybook/core-common';
- import { globalsModuleInfoMap } from '@storybook/manager/globals-module-info';
- import { render } from 'ejs';
- import findCacheDirectory from 'find-cache-dir';
- var __require=(x=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(x,{get:(a,b)=>(typeof require<"u"?require:a)[b]}):x)(function(x){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+x+'" is not supported')});var getTemplatePath=async template=>join(dirname(__require.resolve("@storybook/builder-manager/package.json")),"templates",template),readTemplate=async template=>{let path=await getTemplatePath(template);return fs4.readFile(path,"utf8")};var renderHTML=async(template,title,favicon,customHead,cssFiles,jsFiles,features,refs,logLevel,docsOptions,{versionCheck,previewUrl,configType})=>{let titleRef=await title,templateRef=await template;return render(templateRef,{title:titleRef?`${titleRef} - Storybook`:"Storybook",files:{js:jsFiles,css:cssFiles},favicon:await favicon,globals:{FEATURES:JSON.stringify(await features,null,2),REFS:JSON.stringify(await refs,null,2),LOGLEVEL:JSON.stringify(await logLevel,null,2),DOCS_OPTIONS:JSON.stringify(await docsOptions,null,2),CONFIG_TYPE:JSON.stringify(await configType,null,2),VERSIONCHECK:JSON.stringify(JSON.stringify(versionCheck),null,2),PREVIEW_URL:JSON.stringify(previewUrl,null,2)},head:await customHead||""})};function slash(path){return path.startsWith("\\\\?\\")?path:path.replace(/\\/g,"/")}var sanitizeBase=path=>path.replaceAll(".","").replaceAll("@","").replaceAll(sep,"-").replaceAll("/","-").replaceAll(new RegExp(/^(-)+/g),""),sanitizeFinal=path=>{let sections=path.split(/-?node_modules-?/);return sections[sections.length-1].replaceAll("storybook-addon-","").replaceAll("dist-","")};async function wrapManagerEntries(entrypoints){return Promise.all(entrypoints.map(async(entry,i)=>{let{name,dir}=parse(entry),cacheLocation=findCacheDirectory({name:"sb-manager"});if(!cacheLocation)throw new Error("Could not create/find cache directory");let base=relative(process.cwd(),dir),location=join(cacheLocation,sanitizeFinal(join(`${sanitizeBase(base)}-${i}`,`${sanitizeBase(name)}-bundle.js`)));return await fs4.ensureFile(location),await fs4.writeFile(location,`import '${slash(entry)}';`),location}))}var getData=async options=>{let refs=getRefs(options),favicon=options.presets.apply("favicon").then(p=>basename(p)),features=options.presets.apply("features"),logLevel=options.presets.apply("logLevel"),title=options.presets.apply("title"),docsOptions=options.presets.apply("docs",{}),template=readTemplate("template.ejs"),customHead=options.presets.apply("managerHead"),[instance,config]=await Promise.all([executor.get(),getConfig(options)]);return {refs,features,title,docsOptions,template,customHead,instance,config,logLevel,favicon}};var safeResolve=path=>{try{return Promise.resolve(__require.resolve(path))}catch{return Promise.resolve(!1)}};async function readOrderedFiles(addonsDir,outputFiles){let files=await Promise.all(outputFiles?.map(async file=>{let{location,url}=sanitizePath(file,addonsDir);return await fs4.ensureFile(location),await fs4.writeFile(location,file.contents),url})||[]),jsFiles=files.filter(file=>file.endsWith(".js"));return {cssFiles:files.filter(file=>file.endsWith(".css")),jsFiles}}function sanitizePath(file,addonsDir){let filePath=file.path.replace(addonsDir,""),location=normalize(join(addonsDir,filePath)),url=`./sb-addons${slash(filePath).split("/").map(encodeURIComponent).join("/")}`;return {location,url}}var compilation,asyncIterator,getConfig=async options=>{let[addonsEntryPoints,customManagerEntryPoint,tsconfigPath,envs]=await Promise.all([options.presets.apply("managerEntries",[]),safeResolve(join(options.configDir,"manager")),getTemplatePath("addon.tsconfig.json"),options.presets.apply("env")]),entryPoints=customManagerEntryPoint?[...addonsEntryPoints,customManagerEntryPoint]:addonsEntryPoints;return {entryPoints:await wrapManagerEntries(entryPoints),outdir:join(options.outputDir||"./","sb-addons"),format:"iife",write:!1,ignoreAnnotations:!0,resolveExtensions:[".ts",".tsx",".mjs",".js",".jsx"],outExtension:{".js":".js"},loader:{".js":"jsx",".png":"dataurl",".gif":"dataurl",".jpg":"dataurl",".jpeg":"dataurl",".svg":"dataurl",".webp":"dataurl",".webm":"dataurl",".mp3":"dataurl",".woff2":"dataurl",".woff":"dataurl",".eot":"dataurl",".ttf":"dataurl"},target:["chrome100","safari15","firefox91"],platform:"browser",bundle:!0,minify:!0,sourcemap:!1,conditions:["browser","module","default"],jsxFactory:"React.createElement",jsxFragment:"React.Fragment",jsx:"transform",jsxImportSource:"react",tsconfig:tsconfigPath,legalComments:"external",plugins:[aliasPlugin({process:__require.resolve("process/browser.js"),util:__require.resolve("util/util.js"),assert:__require.resolve("browser-assert")}),globalExternals(globalsModuleInfoMap),pnpPlugin()],banner:{js:"try{"},footer:{js:'}catch(e){ console.error("[Storybook] One of your manager-entries failed: " + import.meta.url, e); }'},define:{"process.env":JSON.stringify(envs),...stringifyProcessEnvs(envs),global:"window",module:"{}"}}},executor={get:async()=>{let{build:build2}=await import('esbuild');return build2}},starter=async function*({startTime,options,router}){logger.info("=> Starting manager..");let{config,favicon,customHead,features,instance,refs,template,title,logLevel,docsOptions}=await getData(options);yield;let addonsDir=config.outdir;await fs4.remove(addonsDir),yield,compilation=await instance({...config}),yield;let coreDirOrigin=join(dirname(__require.resolve("@storybook/manager/package.json")),"dist");router.use("/sb-addons",express.static(addonsDir,{immutable:!0,maxAge:"5m"})),router.use("/sb-manager",express.static(coreDirOrigin,{immutable:!0,maxAge:"5m"}));let{cssFiles,jsFiles}=await readOrderedFiles(addonsDir,compilation?.outputFiles);yield;let html=await renderHTML(template,title,favicon,customHead,cssFiles,jsFiles,features,refs,logLevel,docsOptions,options);return yield,router.use("/",({path},res,next)=>{path==="/"?res.status(200).send(html):next();}),router.use("/index.html",({path},res)=>{res.status(200).send(html);}),{bail,stats:{toJson:()=>({})},totalTime:process.hrtime(startTime)}},builder=async function*({startTime,options}){if(!options.outputDir)throw new Error("outputDir is required");logger.info("=> Building manager..");let{config,customHead,favicon,features,instance,refs,template,title,logLevel,docsOptions}=await getData(options);yield;let addonsDir=config.outdir,coreDirOrigin=join(dirname(__require.resolve("@storybook/manager/package.json")),"dist"),coreDirTarget=join(options.outputDir,"sb-manager");compilation=await instance({...config,minify:!0}),yield;let managerFiles=fs4.copy(coreDirOrigin,coreDirTarget,{filter:src=>{let{ext}=parse(src);return ext?ext===".js":!0}}),{cssFiles,jsFiles}=await readOrderedFiles(addonsDir,compilation?.outputFiles);yield;let html=await renderHTML(template,title,favicon,customHead,cssFiles,jsFiles,features,refs,logLevel,docsOptions,options);return await Promise.all([fs4.writeFile(join(options.outputDir,"index.html"),html),managerFiles]),logger.trace({message:"=> Manager built",time:process.hrtime(startTime)}),{toJson:()=>({})}},bail=async()=>{if(asyncIterator)try{await asyncIterator.throw(new Error);}catch{}},start=async options=>{asyncIterator=starter(options);let result;do result=await asyncIterator.next();while(!result.done);return result.value},build=async options=>{asyncIterator=builder(options);let result;do result=await asyncIterator.next();while(!result.done);return result.value},corePresets=[],overridePresets=[];
- export { bail, build, corePresets, executor, getConfig, overridePresets, start };
|