@storybook/core-server 8.0.0-rc.2 → 8.0.0-rc.3
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 +4 -4
- package/dist/index.mjs +3 -3
- package/dist/{multipart-parser-HMRK3HKU.mjs → multipart-parser-ULPBLTT2.mjs} +1 -1
- package/dist/presets/common-override-preset.js +1 -1
- package/dist/presets/common-preset.js +2 -2
- package/package.json +13 -13
- /package/dist/{chunk-BJZIBL5P.mjs → chunk-OUCMVY4B.mjs} +0 -0
package/dist/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { __commonJS, __toESM, __require, FormData, formDataToBlob, fetch_blob_default } from './chunk-
|
|
1
|
+
import { __commonJS, __toESM, __require, FormData, formDataToBlob, fetch_blob_default } from './chunk-OUCMVY4B.mjs';
|
|
2
2
|
import { loadMainConfig, loadAllPresets, resolveAddonName, normalizeStories, logConfig, cache, getProjectRoot, resolvePathInStorybookCache, validateFrameworkName, serverResolve, getDirectoryFromWorkingDir, commonGlobOptions, normalizeStoryPath, getConfigInfo, JsPackageManagerFactory, versions } from '@storybook/core-common';
|
|
3
3
|
export { getPreviewBodyTemplate, getPreviewHeadTemplate } from '@storybook/core-common';
|
|
4
4
|
import chalk8 from 'chalk';
|
|
@@ -51,7 +51,7 @@ var require_eastasianwidth=__commonJS({"../../node_modules/eastasianwidth/eastas
|
|
|
51
51
|
`,pad=opts.pad||" ",widthDiffFn=align!=="right"?halfDiff:fullDiff,returnString=!1;Array.isArray(text)||(returnString=!0,text=String(text).split(split));let width,maxWidth=0;return text=text.map(function(str){return str=String(str),width=stringWidth4(str),maxWidth=Math.max(width,maxWidth),{str,width}}).map(function(obj){return new Array(widthDiffFn(maxWidth,obj.width)+1).join(pad)+obj.str}),returnString?text.join(split):text}ansiAlign2.left=function(text){return ansiAlign2(text,{align:"left"})};ansiAlign2.center=function(text){return ansiAlign2(text,{align:"center"})};ansiAlign2.right=function(text){return ansiAlign2(text,{align:"right"})};module.exports=ansiAlign2;function halfDiff(maxWidth,curWidth){return Math.floor((maxWidth-curWidth)/2)}function fullDiff(maxWidth,curWidth){return maxWidth-curWidth}}});async function outputStats(directory,previewStats,managerStats){if(previewStats){let filePath=await writeStats(directory,"preview",previewStats);logger.info(`=> preview stats written to ${chalk8.cyan(filePath)}`);}if(managerStats){let filePath=await writeStats(directory,"manager",managerStats);logger.info(`=> manager stats written to ${chalk8.cyan(filePath)}`);}}var writeStats=async(directory,name,stats)=>{let filePath=path4.join(directory,`${name}-stats.json`),{chunks,...data}=stats.toJson();return await new Promise((resolve3,reject)=>{stringifyStream(data,null,2).on("error",reject).pipe(fs4.createWriteStream(filePath)).on("error",reject).on("finish",resolve3);}),filePath};async function useStatics(router2,options){let staticDirs=await options.presets.apply("staticDirs")??[],faviconPath=await options.presets.apply("favicon"),statics=[...staticDirs.map(dir=>typeof dir=="string"?dir:`${dir.from}:${dir.to}`)];statics&&statics.length>0&&await Promise.all(statics.map(async dir=>{try{let normalizedDir=staticDirs&&!isAbsolute(dir)?getDirectoryFromWorkingDir({configDir:options.configDir,workingDir:process.cwd(),directory:dir}):dir,{staticDir,staticPath,targetEndpoint}=await parseStaticDir(normalizedDir);targetEndpoint.startsWith("/sb-")||logger.info(chalk8`=> Serving static files from {cyan ${staticDir}} at {cyan ${targetEndpoint}}`),router2.use(targetEndpoint,express.static(staticPath,{index:!1}));}catch(e){e instanceof Error&&logger.warn(e.message);}})),router2.get(`/${basename(faviconPath)}`,(req,res)=>res.sendFile(faviconPath));}var parseStaticDir=async arg=>{let lastColonIndex=arg.lastIndexOf(":"),isWindowsRawDirOnly=path4.win32.isAbsolute(arg)&&lastColonIndex===1,splitIndex=lastColonIndex!==-1&&!isWindowsRawDirOnly?lastColonIndex:arg.length,target=(arg.substring(splitIndex+1)||"/").split(path4.sep).join(path4.posix.sep),rawDir=arg.substring(0,splitIndex),staticDir=path4.isAbsolute(rawDir)?rawDir:`./${rawDir}`,staticPath=path4.resolve(staticDir),targetDir=target.replace(/^\/?/,"./"),targetEndpoint=targetDir.substring(1);if(!await pathExists(staticPath))throw new Error(dedent(chalk8`
|
|
52
52
|
Failed to load static files, no such directory: {cyan ${staticPath}}
|
|
53
53
|
Make sure this directory exists.
|
|
54
|
-
`));return {staticDir,staticPath,targetDir,targetEndpoint}};async function copyAllStaticFilesRelativeToMain(staticDirs,outputDir,configDir){let workingDir=process.cwd();return staticDirs?.reduce(async(acc,dir)=>{await acc;let staticDirAndTarget=typeof dir=="string"?dir:`${dir.from}:${dir.to}`,{staticPath:from,targetEndpoint:to}=await parseStaticDir(getDirectoryFromWorkingDir({configDir,workingDir,directory:staticDirAndTarget})),targetPath=join(outputDir,to),skipPaths=["index.html","iframe.html"].map(f=>join(targetPath,f));from.includes("node_modules")||logger.info(chalk8`=> Copying static files: {cyan ${print(from)}} at {cyan ${print(targetPath)}}`),await fs4.copy(from,targetPath,{dereference:!0,preserveTimestamps:!0,filter:(_,dest)=>!skipPaths.includes(dest)});},Promise.resolve())}function print(p){return relative(process.cwd(),p)}async function getManagerBuilder(){return import('@storybook/builder-manager')}async function getPreviewBuilder(builderName,configDir){let builderPackage=__require.resolve(["webpack5"].includes(builderName)?`@storybook/builder-${builderName}`:builderName,{paths:[configDir]});return await import(pathToFileURL(builderPackage).href)}async function getBuilders({presets,configDir}){let{builder}=await presets.apply("core",{});if(!builder)throw new MissingBuilderError;let builderName=typeof builder=="string"?builder:builder.name;return Promise.all([getPreviewBuilder(builderName,configDir),getManagerBuilder()])}function slash(path6){return path6.startsWith("\\\\?\\")?path6:path6.replace(/\\/g,"/")}var isDirectory=directory=>{try{return fs3.lstatSync(directory).isDirectory()}catch{return !1}};function toImportPath(relativePath){return relativePath.startsWith(".")?relativePath:`./${relativePath}`}function watchStorySpecifiers(specifiers,options,onInvalidate){let wp=new Watchpack({followSymlinks:!1,ignored:["**/.git","**/node_modules"]});wp.watch({directories:uniq(specifiers.map(ns=>ns.directory))});async function onChangeOrRemove(watchpackPath,removed){let importPath=slash(watchpackPath.startsWith(".")?watchpackPath:`./${watchpackPath}`),matchingSpecifier=specifiers.find(ns=>ns.importPathMatcher.exec(importPath));if(matchingSpecifier){onInvalidate(matchingSpecifier,importPath,removed);return}let absolutePath=path4.join(options.workingDir,importPath);!removed&&isDirectory(absolutePath)&&await Promise.all(specifiers.filter(specifier=>importPath.startsWith(specifier.directory)).map(async specifier=>{let dirGlob=path4.join(options.workingDir,importPath,"**",path4.basename(specifier.files));(await glob(slash(dirGlob),commonGlobOptions(dirGlob))).forEach(filePath=>{let fileImportPath=toImportPath(path4.relative(options.workingDir,filePath).replace(/\\/g,"/"));specifier.importPathMatcher.exec(fileImportPath)&&onInvalidate(specifier,fileImportPath,removed);});}));}return wp.on("change",async(filePath,mtime,explanation)=>{await onChangeOrRemove(filePath,!mtime);}),wp.on("remove",async(filePath,explanation)=>{await onChangeOrRemove(filePath,!0);}),()=>wp.close()}var DEBOUNCE=100;async function extractStoriesJson(outputFile,initializedStoryIndexGenerator,transform){let storyIndex=await(await initializedStoryIndexGenerator).getIndex();await writeJSON(outputFile,transform?transform(storyIndex):storyIndex);}function useStoriesJson({router:router2,initializedStoryIndexGenerator,workingDir=process.cwd(),serverChannel,normalizedStories}){let maybeInvalidate=debounce(()=>serverChannel.emit(STORY_INDEX_INVALIDATED),DEBOUNCE,{leading:!0});watchStorySpecifiers(normalizedStories,{workingDir},async(specifier,path6,removed)=>{(await initializedStoryIndexGenerator).invalidate(specifier,path6,removed),maybeInvalidate();}),router2.use("/index.json",async(req,res)=>{try{let index=await(await initializedStoryIndexGenerator).getIndex();res.header("Content-Type","application/json"),res.send(JSON.stringify(index));}catch(err){res.status(500),res.send(err instanceof Error?err.toString():String(err));}});}async function extractStorybookMetadata(outputFile,configDir){let storybookMetadata=await getStorybookMetadata(configDir);await writeJSON(outputFile,storybookMetadata);}function useStorybookMetadata(router2,configDir){router2.use("/project.json",async(req,res)=>{let storybookMetadata=await getStorybookMetadata(configDir);res.header("Content-Type","application/json"),res.send(JSON.stringify(storybookMetadata));});}function autoName(mdxImportPath,csfImportPath,defaultName){let mdxBasename=basename(mdxImportPath),csfBasename=basename(csfImportPath),[mdxFilename]=mdxBasename.split("."),[csfFilename]=csfBasename.split(".");return mdxFilename===csfFilename?defaultName:mdxFilename}var IndexingError=class extends Error{constructor(message,importPaths,stack){super()
|
|
54
|
+
`));return {staticDir,staticPath,targetDir,targetEndpoint}};async function copyAllStaticFilesRelativeToMain(staticDirs,outputDir,configDir){let workingDir=process.cwd();return staticDirs?.reduce(async(acc,dir)=>{await acc;let staticDirAndTarget=typeof dir=="string"?dir:`${dir.from}:${dir.to}`,{staticPath:from,targetEndpoint:to}=await parseStaticDir(getDirectoryFromWorkingDir({configDir,workingDir,directory:staticDirAndTarget})),targetPath=join(outputDir,to),skipPaths=["index.html","iframe.html"].map(f=>join(targetPath,f));from.includes("node_modules")||logger.info(chalk8`=> Copying static files: {cyan ${print(from)}} at {cyan ${print(targetPath)}}`),await fs4.copy(from,targetPath,{dereference:!0,preserveTimestamps:!0,filter:(_,dest)=>!skipPaths.includes(dest)});},Promise.resolve())}function print(p){return relative(process.cwd(),p)}async function getManagerBuilder(){return import('@storybook/builder-manager')}async function getPreviewBuilder(builderName,configDir){let builderPackage=__require.resolve(["webpack5"].includes(builderName)?`@storybook/builder-${builderName}`:builderName,{paths:[configDir]});return await import(pathToFileURL(builderPackage).href)}async function getBuilders({presets,configDir}){let{builder}=await presets.apply("core",{});if(!builder)throw new MissingBuilderError;let builderName=typeof builder=="string"?builder:builder.name;return Promise.all([getPreviewBuilder(builderName,configDir),getManagerBuilder()])}function slash(path6){return path6.startsWith("\\\\?\\")?path6:path6.replace(/\\/g,"/")}var isDirectory=directory=>{try{return fs3.lstatSync(directory).isDirectory()}catch{return !1}};function toImportPath(relativePath){return relativePath.startsWith(".")?relativePath:`./${relativePath}`}function watchStorySpecifiers(specifiers,options,onInvalidate){let wp=new Watchpack({followSymlinks:!1,ignored:["**/.git","**/node_modules"]});wp.watch({directories:uniq(specifiers.map(ns=>ns.directory))});async function onChangeOrRemove(watchpackPath,removed){let importPath=slash(watchpackPath.startsWith(".")?watchpackPath:`./${watchpackPath}`),matchingSpecifier=specifiers.find(ns=>ns.importPathMatcher.exec(importPath));if(matchingSpecifier){onInvalidate(matchingSpecifier,importPath,removed);return}let absolutePath=path4.join(options.workingDir,importPath);!removed&&isDirectory(absolutePath)&&await Promise.all(specifiers.filter(specifier=>importPath.startsWith(specifier.directory)).map(async specifier=>{let dirGlob=path4.join(options.workingDir,importPath,"**",path4.basename(specifier.files));(await glob(slash(dirGlob),commonGlobOptions(dirGlob))).forEach(filePath=>{let fileImportPath=toImportPath(path4.relative(options.workingDir,filePath).replace(/\\/g,"/"));specifier.importPathMatcher.exec(fileImportPath)&&onInvalidate(specifier,fileImportPath,removed);});}));}return wp.on("change",async(filePath,mtime,explanation)=>{await onChangeOrRemove(filePath,!mtime);}),wp.on("remove",async(filePath,explanation)=>{await onChangeOrRemove(filePath,!0);}),()=>wp.close()}var DEBOUNCE=100;async function extractStoriesJson(outputFile,initializedStoryIndexGenerator,transform){let storyIndex=await(await initializedStoryIndexGenerator).getIndex();await writeJSON(outputFile,transform?transform(storyIndex):storyIndex);}function useStoriesJson({router:router2,initializedStoryIndexGenerator,workingDir=process.cwd(),serverChannel,normalizedStories}){let maybeInvalidate=debounce(()=>serverChannel.emit(STORY_INDEX_INVALIDATED),DEBOUNCE,{leading:!0});watchStorySpecifiers(normalizedStories,{workingDir},async(specifier,path6,removed)=>{(await initializedStoryIndexGenerator).invalidate(specifier,path6,removed),maybeInvalidate();}),router2.use("/index.json",async(req,res)=>{try{let index=await(await initializedStoryIndexGenerator).getIndex();res.header("Content-Type","application/json"),res.send(JSON.stringify(index));}catch(err){res.status(500),res.send(err instanceof Error?err.toString():String(err));}});}async function extractStorybookMetadata(outputFile,configDir){let storybookMetadata=await getStorybookMetadata(configDir);await writeJSON(outputFile,storybookMetadata);}function useStorybookMetadata(router2,configDir){router2.use("/project.json",async(req,res)=>{let storybookMetadata=await getStorybookMetadata(configDir);res.header("Content-Type","application/json"),res.send(JSON.stringify(storybookMetadata));});}function autoName(mdxImportPath,csfImportPath,defaultName){let mdxBasename=basename(mdxImportPath),csfBasename=basename(csfImportPath),[mdxFilename]=mdxBasename.split("."),[csfFilename]=csfBasename.split(".");return mdxFilename===csfFilename?defaultName:mdxFilename}var IndexingError=class extends Error{constructor(message,importPaths,stack){super(),this.message=message,this.importPaths=importPaths,stack&&(this.stack=stack);}pathsString(){return this.importPaths.length===1?`${slash(this.importPaths[0])}`:`${this.importPaths.map(slash).join(",")}`}toString(){return `${this.pathsString()}: ${this.message}`}},MultipleIndexingError=class extends Error{constructor(indexingErrors){super();this.indexingErrors=indexingErrors;if(this.indexingErrors.length===0)throw new Error("Unexpected empty error list");if(this.indexingErrors.length===1){let[err]=this.indexingErrors;this.message=`Unable to index ${err.pathsString()}`;}else this.message=`Unable to index files:
|
|
55
55
|
${this.indexingErrors.map(err=>`- ${err}`).join(`
|
|
56
56
|
`)}`;}toString(){return this.indexingErrors.length===1?`${this.message}:
|
|
57
57
|
${this.indexingErrors[0].stack}`:this.message}};var AUTODOCS_TAG="autodocs",STORIES_MDX_TAG="stories-mdx",PLAY_FN_TAG="play-fn";function isMdxEntry({tags}){return !tags?.includes(AUTODOCS_TAG)&&!tags?.includes(STORIES_MDX_TAG)}var makeAbsolute=(otherImport,normalizedPath,workingDir)=>otherImport.startsWith(".")?slash(path4.resolve(workingDir,normalizeStoryPath(path4.join(path4.dirname(normalizedPath),otherImport)))):otherImport,StoryIndexGenerator=class{constructor(specifiers,options){this.specifiers=specifiers;this.options=options;this.specifierToCache=new Map;}async initialize(){(await Promise.all(this.specifiers.map(async specifier=>{let pathToSubIndex={},fullGlob=slash(path4.join(this.options.workingDir,specifier.directory,specifier.files)),files=await glob(fullGlob,commonGlobOptions(fullGlob));return files.length===0&&once.warn(`No story files found for the specified pattern: ${chalk8.blue(path4.join(specifier.directory,specifier.files))}`),files.sort().forEach(absolutePath=>{let ext=path4.extname(absolutePath);if(ext===".storyshot"){let relativePath=path4.relative(this.options.workingDir,absolutePath);logger.info(`Skipping ${ext} file ${relativePath}`);return}pathToSubIndex[absolutePath]=!1;}),[specifier,pathToSubIndex]}))).forEach(([specifier,cache3])=>this.specifierToCache.set(specifier,cache3)),await this.ensureExtracted();}async updateExtracted(updater,overwrite=!1){await Promise.all(this.specifiers.map(async specifier=>{let entry=this.specifierToCache.get(specifier);return invariant(entry,`specifier does not have a matching cache entry in specifierToCache: ${JSON.stringify(specifier)}`),Promise.all(Object.keys(entry).map(async absolutePath=>{if(!(entry[absolutePath]&&!overwrite))try{entry[absolutePath]=await updater(specifier,absolutePath,entry[absolutePath]);}catch(err){let relativePath=`.${path4.sep}${path4.relative(this.options.workingDir,absolutePath)}`;entry[absolutePath]={type:"error",err:new IndexingError(err instanceof Error?err.message:String(err),[relativePath],err instanceof Error?err.stack:void 0)};}}))}));}isDocsMdx(absolutePath){return new RegExp("(?<!\\.stories)\\.mdx$","i").test(absolutePath)}async ensureExtracted(){return await this.updateExtracted(async(specifier,absolutePath)=>this.isDocsMdx(absolutePath)?!1:this.extractStories(specifier,absolutePath)),await this.updateExtracted(async(specifier,absolutePath)=>this.extractDocs(specifier,absolutePath)),this.specifiers.flatMap(specifier=>{let cache3=this.specifierToCache.get(specifier);return invariant(cache3,`specifier does not have a matching cache entry in specifierToCache: ${JSON.stringify(specifier)}`),Object.values(cache3).flatMap(entry=>entry?entry.type==="docs"?[entry]:entry.type==="error"?[entry]:entry.entries.map(item=>{if(item.type==="docs")return item;let{metaId,...existing}=item;return existing}):[])})}findDependencies(absoluteImports){return [...this.specifierToCache.values()].flatMap(cache3=>Object.entries(cache3).filter(([fileName,cacheEntry])=>!cacheEntry||cacheEntry.type!=="stories"?!1:!!absoluteImports.find(storyImport=>fileName.match(new RegExp(`^${storyImport}(\\.[^.]+)?$`)))).map(([_,cacheEntry])=>cacheEntry))}async extractStories(specifier,absolutePath){let relativePath=path4.relative(this.options.workingDir,absolutePath),importPath=slash(normalizeStoryPath(relativePath)),defaultMakeTitle=userTitle=>{let title=userOrAutoTitleFromSpecifier(importPath,specifier,userTitle);return invariant(title,"makeTitle created an undefined title. This happens when the fileName doesn't match any specifier from main.js"),title},indexer=this.options.indexers.find(ind=>ind.test.exec(absolutePath));invariant(indexer,`No matching indexer found for ${absolutePath}`);let indexInputs=await indexer.createIndex(absolutePath,{makeTitle:defaultMakeTitle}),entries=indexInputs.map(input=>{let name=input.name??storyNameFromExport(input.exportName),title=input.title??defaultMakeTitle(),id=input.__id??toId(input.metaId??title,storyNameFromExport(input.exportName)),tags=(input.tags||[]).concat("story");return {type:"story",id,metaId:input.metaId,name,title,importPath,tags}}),{autodocs}=this.options.docs,hasAutodocsTag=entries.some(entry=>entry.tags.includes(AUTODOCS_TAG)),isStoriesMdx=entries.some(entry=>entry.tags.includes(STORIES_MDX_TAG));if((autodocs===!0||autodocs==="tag"&&hasAutodocsTag||isStoriesMdx)&&this.options.build?.test?.disableAutoDocs!==!0){let name=this.options.docs.defaultName??"Docs",{metaId}=indexInputs[0],{title}=entries[0],metaTags=indexInputs[0].metaTags||[],id=toId(metaId??title,name);entries.unshift({id,title,name,importPath,type:"docs",tags:[...metaTags,"docs",...!hasAutodocsTag&&!isStoriesMdx?[AUTODOCS_TAG]:[]],storiesImports:[]});}return {entries:entries.filter(entry=>!(entry.type==="story"&&entry.tags.includes("stories-mdx-docsOnly"))),dependents:[],type:"stories"}}async extractDocs(specifier,absolutePath){let relativePath=path4.relative(this.options.workingDir,absolutePath);try{let normalizedPath=normalizeStoryPath(relativePath),importPath=slash(normalizedPath),content=await fs4.readFile(absolutePath,"utf8"),result=analyze(content);if(result.isTemplate)return !1;let absoluteImports=result.imports.map(p=>makeAbsolute(p,normalizedPath,this.options.workingDir)),dependencies=this.findDependencies(absoluteImports),sortedDependencies=dependencies,csfEntry;if(result.of){let absoluteOf=makeAbsolute(result.of,normalizedPath,this.options.workingDir);dependencies.forEach(dep=>{if(dep.entries.length>0){let first=dep.entries.find(e=>e.type!=="docs");path4.normalize(path4.resolve(this.options.workingDir,first.importPath)).startsWith(path4.normalize(absoluteOf))&&(csfEntry=first);}sortedDependencies=[dep,...dependencies.filter(d=>d!==dep)];}),invariant(csfEntry,dedent2`Could not find or load CSF file at path "${result.of}" referenced by \`of={}\` in docs file "${relativePath}".
|
|
@@ -72,7 +72,7 @@ ${this.indexingErrors.map(err=>`- ${err}`).join(`
|
|
|
72
72
|
`).map(line=>exec(line,columns,options)).join(`
|
|
73
73
|
`)}__toESM(require_cli_boxes(),1);var NEWLINE=`
|
|
74
74
|
`,PAD=" ",NONE="none",terminalColumns=()=>{let{env,stdout,stderr}=process2;return stdout?.columns?stdout.columns:stderr?.columns?stderr.columns:env.COLUMNS?Number.parseInt(env.COLUMNS,10):80},getObject=detail=>typeof detail=="number"?{top:detail,right:detail*3,bottom:detail,left:detail*3}:{top:0,right:0,bottom:0,left:0,...detail},getBorderWidth=borderStyle=>borderStyle===NONE?0:2,getBorderChars=borderStyle=>{let sides=["topLeft","topRight","bottomRight","bottomLeft","left","right","top","bottom"],characters;if(borderStyle===NONE){borderStyle={};for(let side of sides)borderStyle[side]="";}if(typeof borderStyle=="string"){if(characters=import_cli_boxes.default[borderStyle],!characters)throw new TypeError(`Invalid border style: ${borderStyle}`)}else {typeof borderStyle?.vertical=="string"&&(borderStyle.left=borderStyle.vertical,borderStyle.right=borderStyle.vertical),typeof borderStyle?.horizontal=="string"&&(borderStyle.top=borderStyle.horizontal,borderStyle.bottom=borderStyle.horizontal);for(let side of sides)if(borderStyle[side]===null||typeof borderStyle[side]!="string")throw new TypeError(`Invalid border style: ${side}`);characters=borderStyle;}return characters},makeTitle=(text,horizontal,alignment)=>{let title="",textWidth=stringWidth(text);switch(alignment){case"left":{title=text+horizontal.slice(textWidth);break}case"right":{title=horizontal.slice(textWidth)+text;break}default:{horizontal=horizontal.slice(textWidth),horizontal.length%2===1?(horizontal=horizontal.slice(Math.floor(horizontal.length/2)),title=horizontal.slice(1)+text+horizontal):(horizontal=horizontal.slice(horizontal.length/2),title=horizontal+text+horizontal);break}}return title},makeContentText=(text,{padding,width,textAlignment,height})=>{text=(0, import_ansi_align.default)(text,{align:textAlignment});let lines=text.split(NEWLINE),textWidth=widestLine(text),max=width-padding.left-padding.right;if(textWidth>max){let newLines=[];for(let line of lines){let createdLines=wrapAnsi(line,max,{hard:!0}),alignedLinesArray=(0, import_ansi_align.default)(createdLines,{align:textAlignment}).split(`
|
|
75
|
-
`),longestLength=Math.max(...alignedLinesArray.map(s=>stringWidth(s)));for(let alignedLine of alignedLinesArray){let paddedLine;switch(textAlignment){case"center":{paddedLine=PAD.repeat((max-longestLength)/2)+alignedLine;break}case"right":{paddedLine=PAD.repeat(max-longestLength)+alignedLine;break}default:{paddedLine=alignedLine;break}}newLines.push(paddedLine);}}lines=newLines;}textAlignment==="center"&&textWidth<max?lines=lines.map(line=>PAD.repeat((max-textWidth)/2)+line):textAlignment==="right"&&textWidth<max&&(lines=lines.map(line=>PAD.repeat(max-textWidth)+line));let paddingLeft=PAD.repeat(padding.left),paddingRight=PAD.repeat(padding.right);return lines=lines.map(line=>paddingLeft+line+paddingRight),lines=lines.map(line=>{if(width-stringWidth(line)>0)switch(textAlignment){case"center":return line+PAD.repeat(width-stringWidth(line));case"right":return line+PAD.repeat(width-stringWidth(line));default:return line+PAD.repeat(width-stringWidth(line))}return line}),padding.top>0&&(lines=[...Array.from({length:padding.top}).fill(PAD.repeat(width)),...lines]),padding.bottom>0&&(lines=[...lines,...Array.from({length:padding.bottom}).fill(PAD.repeat(width))]),height&&lines.length>height?lines=lines.slice(0,height):height&&lines.length<height&&(lines=[...lines,...Array.from({length:height-lines.length}).fill(PAD.repeat(width))]),lines.join(NEWLINE)},boxContent=(content,contentWidth,options)=>{let colorizeBorder=border=>{let newBorder=options.borderColor?getColorFn(options.borderColor)(border):border;return options.dimBorder?chalk8.dim(newBorder):newBorder},colorizeContent=content2=>options.backgroundColor?getBGColorFn(options.backgroundColor)(content2):content2,chars=getBorderChars(options.borderStyle),columns=terminalColumns(),marginLeft=PAD.repeat(options.margin.left);if(options.float==="center"){let marginWidth=Math.max((columns-contentWidth-getBorderWidth(options.borderStyle))/2,0);marginLeft=PAD.repeat(marginWidth);}else if(options.float==="right"){let marginWidth=Math.max(columns-contentWidth-options.margin.right-getBorderWidth(options.borderStyle),0);marginLeft=PAD.repeat(marginWidth);}let result="";options.margin.top&&(result+=NEWLINE.repeat(options.margin.top)),(options.borderStyle!==NONE||options.title)&&(result+=colorizeBorder(marginLeft+chars.topLeft+(options.title?makeTitle(options.title,chars.top.repeat(contentWidth),options.titleAlignment):chars.top.repeat(contentWidth))+chars.topRight)+NEWLINE);let lines=content.split(NEWLINE);return result+=lines.map(line=>marginLeft+colorizeBorder(chars.left)+colorizeContent(line)+colorizeBorder(chars.right)).join(NEWLINE),options.borderStyle!==NONE&&(result+=NEWLINE+colorizeBorder(marginLeft+chars.bottomLeft+chars.bottom.repeat(contentWidth)+chars.bottomRight)),options.margin.bottom&&(result+=NEWLINE.repeat(options.margin.bottom)),result},sanitizeOptions=options=>{if(options.fullscreen&&process2?.stdout){let newDimensions=[process2.stdout.columns,process2.stdout.rows];typeof options.fullscreen=="function"&&(newDimensions=options.fullscreen(...newDimensions)),options.width||(options.width=newDimensions[0]),options.height||(options.height=newDimensions[1]);}return options.width&&(options.width=Math.max(1,options.width-getBorderWidth(options.borderStyle))),options.height&&(options.height=Math.max(1,options.height-getBorderWidth(options.borderStyle))),options},formatTitle=(title,borderStyle)=>borderStyle===NONE?title:` ${title} `,determineDimensions=(text,options)=>{options=sanitizeOptions(options);let widthOverride=options.width!==void 0,columns=terminalColumns(),borderWidth=getBorderWidth(options.borderStyle),maxWidth=columns-options.margin.left-options.margin.right-borderWidth,widest=widestLine(wrapAnsi(text,columns-borderWidth,{hard:!0,trim:!1}))+options.padding.left+options.padding.right;if(options.title&&widthOverride?(options.title=options.title.slice(0,Math.max(0,options.width-2)),options.title&&(options.title=formatTitle(options.title,options.borderStyle))):options.title&&(options.title=options.title.slice(0,Math.max(0,maxWidth-2)),options.title&&(options.title=formatTitle(options.title,options.borderStyle),stringWidth(options.title)>widest&&(options.width=stringWidth(options.title)))),options.width=options.width?options.width:widest,!widthOverride){if(options.margin.left&&options.margin.right&&options.width>maxWidth){let multiplier=(columns-options.width-borderWidth)/(options.margin.left+options.margin.right);options.margin.left=Math.max(0,Math.floor(options.margin.left*multiplier)),options.margin.right=Math.max(0,Math.floor(options.margin.right*multiplier));}options.width=Math.min(options.width,columns-borderWidth-options.margin.left-options.margin.right);}return options.width-(options.padding.left+options.padding.right)<=0&&(options.padding.left=0,options.padding.right=0),options.height&&options.height-(options.padding.top+options.padding.bottom)<=0&&(options.padding.top=0,options.padding.bottom=0),options},isHex=color=>color.match(/^#(?:[0-f]{3}){1,2}$/i),isColorValid=color=>typeof color=="string"&&(chalk8[color]??isHex(color)),getColorFn=color=>isHex(color)?chalk8.hex(color):chalk8[color],getBGColorFn=color=>isHex(color)?chalk8.bgHex(color):chalk8[camelCase(["bg",color])];function boxen(text,options){if(options={padding:0,borderStyle:"single",dimBorder:!1,textAlignment:"left",float:"left",titleAlignment:"left",...options},options.align&&(options.textAlignment=options.align),options.borderColor&&!isColorValid(options.borderColor))throw new Error(`${options.borderColor} is not a valid borderColor`);if(options.backgroundColor&&!isColorValid(options.backgroundColor))throw new Error(`${options.backgroundColor} is not a valid backgroundColor`);return options.padding=getObject(options.padding),options.margin=getObject(options.margin),options=determineDimensions(text,options),text=makeContentText(text,options),boxContent(text,options.width,options)}function dataUriToBuffer(uri){if(!/^data:/i.test(uri))throw new TypeError('`uri` does not appear to be a Data URI (must begin with "data:")');uri=uri.replace(/\r?\n/g,"");let firstComma=uri.indexOf(",");if(firstComma===-1||firstComma<=4)throw new TypeError("malformed data: URI");let meta=uri.substring(5,firstComma).split(";"),charset="",base64=!1,type=meta[0]||"text/plain",typeFull=type;for(let i=1;i<meta.length;i++)meta[i]==="base64"?base64=!0:meta[i]&&(typeFull+=`;${meta[i]}`,meta[i].indexOf("charset=")===0&&(charset=meta[i].substring(8)));!meta[0]&&!charset.length&&(typeFull+=";charset=US-ASCII",charset="US-ASCII");let encoding=base64?"base64":"ascii",data=unescape(uri.substring(firstComma+1)),buffer=Buffer.from(data,encoding);return buffer.type=type,buffer.typeFull=typeFull,buffer.charset=charset,buffer}var dist_default=dataUriToBuffer;var FetchBaseError=class extends Error{constructor(message,type){super(message),Error.captureStackTrace(this,this.constructor),this.type=type;}get name(){return this.constructor.name}get[Symbol.toStringTag](){return this.constructor.name}};var FetchError=class extends FetchBaseError{constructor(message,type,systemError){super(message,type),systemError&&(this.code=this.errno=systemError.code,this.erroredSysCall=systemError.syscall);}};var NAME=Symbol.toStringTag,isURLSearchParameters=object=>typeof object=="object"&&typeof object.append=="function"&&typeof object.delete=="function"&&typeof object.get=="function"&&typeof object.getAll=="function"&&typeof object.has=="function"&&typeof object.set=="function"&&typeof object.sort=="function"&&object[NAME]==="URLSearchParams",isBlob=object=>object&&typeof object=="object"&&typeof object.arrayBuffer=="function"&&typeof object.type=="string"&&typeof object.stream=="function"&&typeof object.constructor=="function"&&/^(Blob|File)$/.test(object[NAME]),isAbortSignal=object=>typeof object=="object"&&(object[NAME]==="AbortSignal"||object[NAME]==="EventTarget"),isDomainOrSubdomain=(destination,original)=>{let orig=new URL(original).hostname,dest=new URL(destination).hostname;return orig===dest||orig.endsWith(`.${dest}`)},isSameProtocol=(destination,original)=>{let orig=new URL(original).protocol,dest=new URL(destination).protocol;return orig===dest};var pipeline=promisify(Stream.pipeline),INTERNALS=Symbol("Body internals"),Body=class{constructor(body,{size=0}={}){let boundary=null;body===null?body=null:isURLSearchParameters(body)?body=Buffer$1.from(body.toString()):isBlob(body)||Buffer$1.isBuffer(body)||(types.isAnyArrayBuffer(body)?body=Buffer$1.from(body):ArrayBuffer.isView(body)?body=Buffer$1.from(body.buffer,body.byteOffset,body.byteLength):body instanceof Stream||(body instanceof FormData?(body=formDataToBlob(body),boundary=body.type.split("=")[1]):body=Buffer$1.from(String(body))));let stream=body;Buffer$1.isBuffer(body)?stream=Stream.Readable.from(body):isBlob(body)&&(stream=Stream.Readable.from(body.stream())),this[INTERNALS]={body,stream,boundary,disturbed:!1,error:null},this.size=size,body instanceof Stream&&body.on("error",error_=>{let error=error_ instanceof FetchBaseError?error_:new FetchError(`Invalid response body while trying to fetch ${this.url}: ${error_.message}`,"system",error_);this[INTERNALS].error=error;});}get body(){return this[INTERNALS].stream}get bodyUsed(){return this[INTERNALS].disturbed}async arrayBuffer(){let{buffer,byteOffset,byteLength}=await consumeBody(this);return buffer.slice(byteOffset,byteOffset+byteLength)}async formData(){let ct=this.headers.get("content-type");if(ct.startsWith("application/x-www-form-urlencoded")){let formData=new FormData,parameters=new URLSearchParams(await this.text());for(let[name,value]of parameters)formData.append(name,value);return formData}let{toFormData}=await import('./multipart-parser-HMRK3HKU.mjs');return toFormData(this.body,ct)}async blob(){let ct=this.headers&&this.headers.get("content-type")||this[INTERNALS].body&&this[INTERNALS].body.type||"",buf=await this.arrayBuffer();return new fetch_blob_default([buf],{type:ct})}async json(){let text=await this.text();return JSON.parse(text)}async text(){let buffer=await consumeBody(this);return new TextDecoder().decode(buffer)}buffer(){return consumeBody(this)}};Body.prototype.buffer=deprecate(Body.prototype.buffer,"Please use 'response.arrayBuffer()' instead of 'response.buffer()'","node-fetch#buffer");Object.defineProperties(Body.prototype,{body:{enumerable:!0},bodyUsed:{enumerable:!0},arrayBuffer:{enumerable:!0},blob:{enumerable:!0},json:{enumerable:!0},text:{enumerable:!0},data:{get:deprecate(()=>{},"data doesn't exist, use json(), text(), arrayBuffer(), or body instead","https://github.com/node-fetch/node-fetch/issues/1000 (response)")}});async function consumeBody(data){if(data[INTERNALS].disturbed)throw new TypeError(`body used already for: ${data.url}`);if(data[INTERNALS].disturbed=!0,data[INTERNALS].error)throw data[INTERNALS].error;let{body}=data;if(body===null)return Buffer$1.alloc(0);if(!(body instanceof Stream))return Buffer$1.alloc(0);let accum=[],accumBytes=0;try{for await(let chunk of body){if(data.size>0&&accumBytes+chunk.length>data.size){let error=new FetchError(`content size at ${data.url} over limit: ${data.size}`,"max-size");throw body.destroy(error),error}accumBytes+=chunk.length,accum.push(chunk);}}catch(error){throw error instanceof FetchBaseError?error:new FetchError(`Invalid response body while trying to fetch ${data.url}: ${error.message}`,"system",error)}if(body.readableEnded===!0||body._readableState.ended===!0)try{return accum.every(c=>typeof c=="string")?Buffer$1.from(accum.join("")):Buffer$1.concat(accum,accumBytes)}catch(error){throw new FetchError(`Could not create Buffer from response body for ${data.url}: ${error.message}`,"system",error)}else throw new FetchError(`Premature close of server response while trying to fetch ${data.url}`)}var clone=(instance,highWaterMark)=>{let p1,p2,{body}=instance[INTERNALS];if(instance.bodyUsed)throw new Error("cannot clone body after it is used");return body instanceof Stream&&typeof body.getBoundary!="function"&&(p1=new PassThrough({highWaterMark}),p2=new PassThrough({highWaterMark}),body.pipe(p1),body.pipe(p2),instance[INTERNALS].stream=p1,body=p2),body},getNonSpecFormDataBoundary=deprecate(body=>body.getBoundary(),"form-data doesn't follow the spec and requires special treatment. Use alternative package","https://github.com/node-fetch/node-fetch/issues/1167"),extractContentType=(body,request)=>body===null?null:typeof body=="string"?"text/plain;charset=UTF-8":isURLSearchParameters(body)?"application/x-www-form-urlencoded;charset=UTF-8":isBlob(body)?body.type||null:Buffer$1.isBuffer(body)||types.isAnyArrayBuffer(body)||ArrayBuffer.isView(body)?null:body instanceof FormData?`multipart/form-data; boundary=${request[INTERNALS].boundary}`:body&&typeof body.getBoundary=="function"?`multipart/form-data;boundary=${getNonSpecFormDataBoundary(body)}`:body instanceof Stream?null:"text/plain;charset=UTF-8",getTotalBytes=request=>{let{body}=request[INTERNALS];return body===null?0:isBlob(body)?body.size:Buffer$1.isBuffer(body)?body.length:body&&typeof body.getLengthSync=="function"&&body.hasKnownLength&&body.hasKnownLength()?body.getLengthSync():null},writeToStream=async(dest,{body})=>{body===null?dest.end():await pipeline(body,dest);};var validateHeaderName=typeof http2.validateHeaderName=="function"?http2.validateHeaderName:name=>{if(!/^[\^`\-\w!#$%&'*+.|~]+$/.test(name)){let error=new TypeError(`Header name must be a valid HTTP token [${name}]`);throw Object.defineProperty(error,"code",{value:"ERR_INVALID_HTTP_TOKEN"}),error}},validateHeaderValue=typeof http2.validateHeaderValue=="function"?http2.validateHeaderValue:(name,value)=>{if(/[^\t\u0020-\u007E\u0080-\u00FF]/.test(value)){let error=new TypeError(`Invalid character in header content ["${name}"]`);throw Object.defineProperty(error,"code",{value:"ERR_INVALID_CHAR"}),error}},Headers=class _Headers extends URLSearchParams{constructor(init){let result=[];if(init instanceof _Headers){let raw=init.raw();for(let[name,values]of Object.entries(raw))result.push(...values.map(value=>[name,value]));}else if(init!=null)if(typeof init=="object"&&!types.isBoxedPrimitive(init)){let method=init[Symbol.iterator];if(method==null)result.push(...Object.entries(init));else {if(typeof method!="function")throw new TypeError("Header pairs must be iterable");result=[...init].map(pair=>{if(typeof pair!="object"||types.isBoxedPrimitive(pair))throw new TypeError("Each header pair must be an iterable object");return [...pair]}).map(pair=>{if(pair.length!==2)throw new TypeError("Each header pair must be a name/value tuple");return [...pair]});}}else throw new TypeError("Failed to construct 'Headers': The provided value is not of type '(sequence<sequence<ByteString>> or record<ByteString, ByteString>)");return result=result.length>0?result.map(([name,value])=>(validateHeaderName(name),validateHeaderValue(name,String(value)),[String(name).toLowerCase(),String(value)])):void 0,super(result),new Proxy(this,{get(target,p,receiver){switch(p){case"append":case"set":return (name,value)=>(validateHeaderName(name),validateHeaderValue(name,String(value)),URLSearchParams.prototype[p].call(target,String(name).toLowerCase(),String(value)));case"delete":case"has":case"getAll":return name=>(validateHeaderName(name),URLSearchParams.prototype[p].call(target,String(name).toLowerCase()));case"keys":return ()=>(target.sort(),new Set(URLSearchParams.prototype.keys.call(target)).keys());default:return Reflect.get(target,p,receiver)}}})}get[Symbol.toStringTag](){return this.constructor.name}toString(){return Object.prototype.toString.call(this)}get(name){let values=this.getAll(name);if(values.length===0)return null;let value=values.join(", ");return /^content-encoding$/i.test(name)&&(value=value.toLowerCase()),value}forEach(callback,thisArg=void 0){for(let name of this.keys())Reflect.apply(callback,thisArg,[this.get(name),name,this]);}*values(){for(let name of this.keys())yield this.get(name);}*entries(){for(let name of this.keys())yield [name,this.get(name)];}[Symbol.iterator](){return this.entries()}raw(){return [...this.keys()].reduce((result,key)=>(result[key]=this.getAll(key),result),{})}[Symbol.for("nodejs.util.inspect.custom")](){return [...this.keys()].reduce((result,key)=>{let values=this.getAll(key);return key==="host"?result[key]=values[0]:result[key]=values.length>1?values:values[0],result},{})}};Object.defineProperties(Headers.prototype,["get","entries","forEach","values"].reduce((result,property)=>(result[property]={enumerable:!0},result),{}));function fromRawHeaders(headers=[]){return new Headers(headers.reduce((result,value,index,array)=>(index%2===0&&result.push(array.slice(index,index+2)),result),[]).filter(([name,value])=>{try{return validateHeaderName(name),validateHeaderValue(name,String(value)),!0}catch{return !1}}))}var redirectStatus=new Set([301,302,303,307,308]),isRedirect=code=>redirectStatus.has(code);var INTERNALS2=Symbol("Response internals"),Response=class _Response extends Body{constructor(body=null,options={}){super(body,options);let status=options.status!=null?options.status:200,headers=new Headers(options.headers);if(body!==null&&!headers.has("Content-Type")){let contentType=extractContentType(body,this);contentType&&headers.append("Content-Type",contentType);}this[INTERNALS2]={type:"default",url:options.url,status,statusText:options.statusText||"",headers,counter:options.counter,highWaterMark:options.highWaterMark};}get type(){return this[INTERNALS2].type}get url(){return this[INTERNALS2].url||""}get status(){return this[INTERNALS2].status}get ok(){return this[INTERNALS2].status>=200&&this[INTERNALS2].status<300}get redirected(){return this[INTERNALS2].counter>0}get statusText(){return this[INTERNALS2].statusText}get headers(){return this[INTERNALS2].headers}get highWaterMark(){return this[INTERNALS2].highWaterMark}clone(){return new _Response(clone(this,this.highWaterMark),{type:this.type,url:this.url,status:this.status,statusText:this.statusText,headers:this.headers,ok:this.ok,redirected:this.redirected,size:this.size,highWaterMark:this.highWaterMark})}static redirect(url,status=302){if(!isRedirect(status))throw new RangeError('Failed to execute "redirect" on "response": Invalid status code');return new _Response(null,{headers:{location:new URL(url).toString()},status})}static error(){let response=new _Response(null,{status:0,statusText:""});return response[INTERNALS2].type="error",response}static json(data=void 0,init={}){let body=JSON.stringify(data);if(body===void 0)throw new TypeError("data is not JSON serializable");let headers=new Headers(init&&init.headers);return headers.has("content-type")||headers.set("content-type","application/json"),new _Response(body,{...init,headers})}get[Symbol.toStringTag](){return "Response"}};Object.defineProperties(Response.prototype,{type:{enumerable:!0},url:{enumerable:!0},status:{enumerable:!0},ok:{enumerable:!0},redirected:{enumerable:!0},statusText:{enumerable:!0},headers:{enumerable:!0},clone:{enumerable:!0}});var getSearch=parsedURL=>{if(parsedURL.search)return parsedURL.search;let lastOffset=parsedURL.href.length-1,hash=parsedURL.hash||(parsedURL.href[lastOffset]==="#"?"#":"");return parsedURL.href[lastOffset-hash.length]==="?"?"?":""};function stripURLForUseAsAReferrer(url,originOnly=!1){return url==null||(url=new URL(url),/^(about|blob|data):$/.test(url.protocol))?"no-referrer":(url.username="",url.password="",url.hash="",originOnly&&(url.pathname="",url.search=""),url)}var ReferrerPolicy=new Set(["","no-referrer","no-referrer-when-downgrade","same-origin","origin","strict-origin","origin-when-cross-origin","strict-origin-when-cross-origin","unsafe-url"]),DEFAULT_REFERRER_POLICY="strict-origin-when-cross-origin";function validateReferrerPolicy(referrerPolicy){if(!ReferrerPolicy.has(referrerPolicy))throw new TypeError(`Invalid referrerPolicy: ${referrerPolicy}`);return referrerPolicy}function isOriginPotentiallyTrustworthy(url){if(/^(http|ws)s:$/.test(url.protocol))return !0;let hostIp=url.host.replace(/(^\[)|(]$)/g,""),hostIPVersion=isIP(hostIp);return hostIPVersion===4&&/^127\./.test(hostIp)||hostIPVersion===6&&/^(((0+:){7})|(::(0+:){0,6}))0*1$/.test(hostIp)?!0:url.host==="localhost"||url.host.endsWith(".localhost")?!1:url.protocol==="file:"}function isUrlPotentiallyTrustworthy(url){return /^about:(blank|srcdoc)$/.test(url)||url.protocol==="data:"||/^(blob|filesystem):$/.test(url.protocol)?!0:isOriginPotentiallyTrustworthy(url)}function determineRequestsReferrer(request,{referrerURLCallback,referrerOriginCallback}={}){if(request.referrer==="no-referrer"||request.referrerPolicy==="")return null;let policy=request.referrerPolicy;if(request.referrer==="about:client")return "no-referrer";let referrerSource=request.referrer,referrerURL=stripURLForUseAsAReferrer(referrerSource),referrerOrigin=stripURLForUseAsAReferrer(referrerSource,!0);referrerURL.toString().length>4096&&(referrerURL=referrerOrigin),referrerURLCallback&&(referrerURL=referrerURLCallback(referrerURL)),referrerOriginCallback&&(referrerOrigin=referrerOriginCallback(referrerOrigin));let currentURL=new URL(request.url);switch(policy){case"no-referrer":return "no-referrer";case"origin":return referrerOrigin;case"unsafe-url":return referrerURL;case"strict-origin":return isUrlPotentiallyTrustworthy(referrerURL)&&!isUrlPotentiallyTrustworthy(currentURL)?"no-referrer":referrerOrigin.toString();case"strict-origin-when-cross-origin":return referrerURL.origin===currentURL.origin?referrerURL:isUrlPotentiallyTrustworthy(referrerURL)&&!isUrlPotentiallyTrustworthy(currentURL)?"no-referrer":referrerOrigin;case"same-origin":return referrerURL.origin===currentURL.origin?referrerURL:"no-referrer";case"origin-when-cross-origin":return referrerURL.origin===currentURL.origin?referrerURL:referrerOrigin;case"no-referrer-when-downgrade":return isUrlPotentiallyTrustworthy(referrerURL)&&!isUrlPotentiallyTrustworthy(currentURL)?"no-referrer":referrerURL;default:throw new TypeError(`Invalid referrerPolicy: ${policy}`)}}function parseReferrerPolicyFromHeader(headers){let policyTokens=(headers.get("referrer-policy")||"").split(/[,\s]+/),policy="";for(let token of policyTokens)token&&ReferrerPolicy.has(token)&&(policy=token);return policy}var INTERNALS3=Symbol("Request internals"),isRequest=object=>typeof object=="object"&&typeof object[INTERNALS3]=="object",doBadDataWarn=deprecate(()=>{},".data is not a valid RequestInit property, use .body instead","https://github.com/node-fetch/node-fetch/issues/1000 (request)"),Request=class _Request extends Body{constructor(input,init={}){let parsedURL;if(isRequest(input)?parsedURL=new URL(input.url):(parsedURL=new URL(input),input={}),parsedURL.username!==""||parsedURL.password!=="")throw new TypeError(`${parsedURL} is an url with embedded credentials.`);let method=init.method||input.method||"GET";if(/^(delete|get|head|options|post|put)$/i.test(method)&&(method=method.toUpperCase()),!isRequest(init)&&"data"in init&&doBadDataWarn(),(init.body!=null||isRequest(input)&&input.body!==null)&&(method==="GET"||method==="HEAD"))throw new TypeError("Request with GET/HEAD method cannot have body");let inputBody=init.body?init.body:isRequest(input)&&input.body!==null?clone(input):null;super(inputBody,{size:init.size||input.size||0});let headers=new Headers(init.headers||input.headers||{});if(inputBody!==null&&!headers.has("Content-Type")){let contentType=extractContentType(inputBody,this);contentType&&headers.set("Content-Type",contentType);}let signal=isRequest(input)?input.signal:null;if("signal"in init&&(signal=init.signal),signal!=null&&!isAbortSignal(signal))throw new TypeError("Expected signal to be an instanceof AbortSignal or EventTarget");let referrer=init.referrer==null?input.referrer:init.referrer;if(referrer==="")referrer="no-referrer";else if(referrer){let parsedReferrer=new URL(referrer);referrer=/^about:(\/\/)?client$/.test(parsedReferrer)?"client":parsedReferrer;}else referrer=void 0;this[INTERNALS3]={method,redirect:init.redirect||input.redirect||"follow",headers,parsedURL,signal,referrer},this.follow=init.follow===void 0?input.follow===void 0?20:input.follow:init.follow,this.compress=init.compress===void 0?input.compress===void 0?!0:input.compress:init.compress,this.counter=init.counter||input.counter||0,this.agent=init.agent||input.agent,this.highWaterMark=init.highWaterMark||input.highWaterMark||16384,this.insecureHTTPParser=init.insecureHTTPParser||input.insecureHTTPParser||!1,this.referrerPolicy=init.referrerPolicy||input.referrerPolicy||"";}get method(){return this[INTERNALS3].method}get url(){return format(this[INTERNALS3].parsedURL)}get headers(){return this[INTERNALS3].headers}get redirect(){return this[INTERNALS3].redirect}get signal(){return this[INTERNALS3].signal}get referrer(){if(this[INTERNALS3].referrer==="no-referrer")return "";if(this[INTERNALS3].referrer==="client")return "about:client";if(this[INTERNALS3].referrer)return this[INTERNALS3].referrer.toString()}get referrerPolicy(){return this[INTERNALS3].referrerPolicy}set referrerPolicy(referrerPolicy){this[INTERNALS3].referrerPolicy=validateReferrerPolicy(referrerPolicy);}clone(){return new _Request(this)}get[Symbol.toStringTag](){return "Request"}};Object.defineProperties(Request.prototype,{method:{enumerable:!0},url:{enumerable:!0},headers:{enumerable:!0},redirect:{enumerable:!0},clone:{enumerable:!0},signal:{enumerable:!0},referrer:{enumerable:!0},referrerPolicy:{enumerable:!0}});var getNodeRequestOptions=request=>{let{parsedURL}=request[INTERNALS3],headers=new Headers(request[INTERNALS3].headers);headers.has("Accept")||headers.set("Accept","*/*");let contentLengthValue=null;if(request.body===null&&/^(post|put)$/i.test(request.method)&&(contentLengthValue="0"),request.body!==null){let totalBytes=getTotalBytes(request);typeof totalBytes=="number"&&!Number.isNaN(totalBytes)&&(contentLengthValue=String(totalBytes));}contentLengthValue&&headers.set("Content-Length",contentLengthValue),request.referrerPolicy===""&&(request.referrerPolicy=DEFAULT_REFERRER_POLICY),request.referrer&&request.referrer!=="no-referrer"?request[INTERNALS3].referrer=determineRequestsReferrer(request):request[INTERNALS3].referrer="no-referrer",request[INTERNALS3].referrer instanceof URL&&headers.set("Referer",request.referrer),headers.has("User-Agent")||headers.set("User-Agent","node-fetch"),request.compress&&!headers.has("Accept-Encoding")&&headers.set("Accept-Encoding","gzip, deflate, br");let{agent}=request;typeof agent=="function"&&(agent=agent(parsedURL));let search=getSearch(parsedURL),options={path:parsedURL.pathname+search,method:request.method,headers:headers[Symbol.for("nodejs.util.inspect.custom")](),insecureHTTPParser:request.insecureHTTPParser,agent};return {parsedURL,options}};var AbortError=class extends FetchBaseError{constructor(message,type="aborted"){super(message,type);}};var supportedSchemas=new Set(["data:","http:","https:"]);async function fetch(url,options_){return new Promise((resolve3,reject)=>{let request=new Request(url,options_),{parsedURL,options}=getNodeRequestOptions(request);if(!supportedSchemas.has(parsedURL.protocol))throw new TypeError(`node-fetch cannot load ${url}. URL scheme "${parsedURL.protocol.replace(/:$/,"")}" is not supported.`);if(parsedURL.protocol==="data:"){let data=dist_default(request.url),response2=new Response(data,{headers:{"Content-Type":data.typeFull}});resolve3(response2);return}let send=(parsedURL.protocol==="https:"?https:http2).request,{signal}=request,response=null,abort=()=>{let error=new AbortError("The operation was aborted.");reject(error),request.body&&request.body instanceof Stream.Readable&&request.body.destroy(error),!(!response||!response.body)&&response.body.emit("error",error);};if(signal&&signal.aborted){abort();return}let abortAndFinalize=()=>{abort(),finalize();},request_=send(parsedURL.toString(),options);signal&&signal.addEventListener("abort",abortAndFinalize);let finalize=()=>{request_.abort(),signal&&signal.removeEventListener("abort",abortAndFinalize);};request_.on("error",error=>{reject(new FetchError(`request to ${request.url} failed, reason: ${error.message}`,"system",error)),finalize();}),fixResponseChunkedTransferBadEnding(request_,error=>{response&&response.body&&response.body.destroy(error);}),process.version<"v14"&&request_.on("socket",s=>{let endedWithEventsCount;s.prependListener("end",()=>{endedWithEventsCount=s._eventsCount;}),s.prependListener("close",hadError=>{if(response&&endedWithEventsCount<s._eventsCount&&!hadError){let error=new Error("Premature close");error.code="ERR_STREAM_PREMATURE_CLOSE",response.body.emit("error",error);}});}),request_.on("response",response_=>{request_.setTimeout(0);let headers=fromRawHeaders(response_.rawHeaders);if(isRedirect(response_.statusCode)){let location=headers.get("Location"),locationURL=null;try{locationURL=location===null?null:new URL(location,request.url);}catch{if(request.redirect!=="manual"){reject(new FetchError(`uri requested responds with an invalid redirect URL: ${location}`,"invalid-redirect")),finalize();return}}switch(request.redirect){case"error":reject(new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${request.url}`,"no-redirect")),finalize();return;case"manual":break;case"follow":{if(locationURL===null)break;if(request.counter>=request.follow){reject(new FetchError(`maximum redirect reached at: ${request.url}`,"max-redirect")),finalize();return}let requestOptions={headers:new Headers(request.headers),follow:request.follow,counter:request.counter+1,agent:request.agent,compress:request.compress,method:request.method,body:clone(request),signal:request.signal,size:request.size,referrer:request.referrer,referrerPolicy:request.referrerPolicy};if(!isDomainOrSubdomain(request.url,locationURL)||!isSameProtocol(request.url,locationURL))for(let name of ["authorization","www-authenticate","cookie","cookie2"])requestOptions.headers.delete(name);if(response_.statusCode!==303&&request.body&&options_.body instanceof Stream.Readable){reject(new FetchError("Cannot follow redirect with body being a readable stream","unsupported-redirect")),finalize();return}(response_.statusCode===303||(response_.statusCode===301||response_.statusCode===302)&&request.method==="POST")&&(requestOptions.method="GET",requestOptions.body=void 0,requestOptions.headers.delete("content-length"));let responseReferrerPolicy=parseReferrerPolicyFromHeader(headers);responseReferrerPolicy&&(requestOptions.referrerPolicy=responseReferrerPolicy),resolve3(fetch(new Request(locationURL,requestOptions))),finalize();return}default:return reject(new TypeError(`Redirect option '${request.redirect}' is not a valid value of RequestRedirect`))}}signal&&response_.once("end",()=>{signal.removeEventListener("abort",abortAndFinalize);});let body=pipeline$1(response_,new PassThrough,error=>{error&&reject(error);});process.version<"v12.10"&&response_.on("aborted",abortAndFinalize);let responseOptions={url:request.url,status:response_.statusCode,statusText:response_.statusMessage,headers,size:request.size,counter:request.counter,highWaterMark:request.highWaterMark},codings=headers.get("Content-Encoding");if(!request.compress||request.method==="HEAD"||codings===null||response_.statusCode===204||response_.statusCode===304){response=new Response(body,responseOptions),resolve3(response);return}let zlibOptions={flush:zlib.Z_SYNC_FLUSH,finishFlush:zlib.Z_SYNC_FLUSH};if(codings==="gzip"||codings==="x-gzip"){body=pipeline$1(body,zlib.createGunzip(zlibOptions),error=>{error&&reject(error);}),response=new Response(body,responseOptions),resolve3(response);return}if(codings==="deflate"||codings==="x-deflate"){let raw=pipeline$1(response_,new PassThrough,error=>{error&&reject(error);});raw.once("data",chunk=>{(chunk[0]&15)===8?body=pipeline$1(body,zlib.createInflate(),error=>{error&&reject(error);}):body=pipeline$1(body,zlib.createInflateRaw(),error=>{error&&reject(error);}),response=new Response(body,responseOptions),resolve3(response);}),raw.once("end",()=>{response||(response=new Response(body,responseOptions),resolve3(response));});return}if(codings==="br"){body=pipeline$1(body,zlib.createBrotliDecompress(),error=>{error&&reject(error);}),response=new Response(body,responseOptions),resolve3(response);return}response=new Response(body,responseOptions),resolve3(response);}),writeToStream(request_,request).catch(reject);})}function fixResponseChunkedTransferBadEnding(request,errorCallback){let LAST_CHUNK=Buffer$1.from(`0\r
|
|
75
|
+
`),longestLength=Math.max(...alignedLinesArray.map(s=>stringWidth(s)));for(let alignedLine of alignedLinesArray){let paddedLine;switch(textAlignment){case"center":{paddedLine=PAD.repeat((max-longestLength)/2)+alignedLine;break}case"right":{paddedLine=PAD.repeat(max-longestLength)+alignedLine;break}default:{paddedLine=alignedLine;break}}newLines.push(paddedLine);}}lines=newLines;}textAlignment==="center"&&textWidth<max?lines=lines.map(line=>PAD.repeat((max-textWidth)/2)+line):textAlignment==="right"&&textWidth<max&&(lines=lines.map(line=>PAD.repeat(max-textWidth)+line));let paddingLeft=PAD.repeat(padding.left),paddingRight=PAD.repeat(padding.right);return lines=lines.map(line=>paddingLeft+line+paddingRight),lines=lines.map(line=>{if(width-stringWidth(line)>0)switch(textAlignment){case"center":return line+PAD.repeat(width-stringWidth(line));case"right":return line+PAD.repeat(width-stringWidth(line));default:return line+PAD.repeat(width-stringWidth(line))}return line}),padding.top>0&&(lines=[...Array.from({length:padding.top}).fill(PAD.repeat(width)),...lines]),padding.bottom>0&&(lines=[...lines,...Array.from({length:padding.bottom}).fill(PAD.repeat(width))]),height&&lines.length>height?lines=lines.slice(0,height):height&&lines.length<height&&(lines=[...lines,...Array.from({length:height-lines.length}).fill(PAD.repeat(width))]),lines.join(NEWLINE)},boxContent=(content,contentWidth,options)=>{let colorizeBorder=border=>{let newBorder=options.borderColor?getColorFn(options.borderColor)(border):border;return options.dimBorder?chalk8.dim(newBorder):newBorder},colorizeContent=content2=>options.backgroundColor?getBGColorFn(options.backgroundColor)(content2):content2,chars=getBorderChars(options.borderStyle),columns=terminalColumns(),marginLeft=PAD.repeat(options.margin.left);if(options.float==="center"){let marginWidth=Math.max((columns-contentWidth-getBorderWidth(options.borderStyle))/2,0);marginLeft=PAD.repeat(marginWidth);}else if(options.float==="right"){let marginWidth=Math.max(columns-contentWidth-options.margin.right-getBorderWidth(options.borderStyle),0);marginLeft=PAD.repeat(marginWidth);}let result="";options.margin.top&&(result+=NEWLINE.repeat(options.margin.top)),(options.borderStyle!==NONE||options.title)&&(result+=colorizeBorder(marginLeft+chars.topLeft+(options.title?makeTitle(options.title,chars.top.repeat(contentWidth),options.titleAlignment):chars.top.repeat(contentWidth))+chars.topRight)+NEWLINE);let lines=content.split(NEWLINE);return result+=lines.map(line=>marginLeft+colorizeBorder(chars.left)+colorizeContent(line)+colorizeBorder(chars.right)).join(NEWLINE),options.borderStyle!==NONE&&(result+=NEWLINE+colorizeBorder(marginLeft+chars.bottomLeft+chars.bottom.repeat(contentWidth)+chars.bottomRight)),options.margin.bottom&&(result+=NEWLINE.repeat(options.margin.bottom)),result},sanitizeOptions=options=>{if(options.fullscreen&&process2?.stdout){let newDimensions=[process2.stdout.columns,process2.stdout.rows];typeof options.fullscreen=="function"&&(newDimensions=options.fullscreen(...newDimensions)),options.width||(options.width=newDimensions[0]),options.height||(options.height=newDimensions[1]);}return options.width&&(options.width=Math.max(1,options.width-getBorderWidth(options.borderStyle))),options.height&&(options.height=Math.max(1,options.height-getBorderWidth(options.borderStyle))),options},formatTitle=(title,borderStyle)=>borderStyle===NONE?title:` ${title} `,determineDimensions=(text,options)=>{options=sanitizeOptions(options);let widthOverride=options.width!==void 0,columns=terminalColumns(),borderWidth=getBorderWidth(options.borderStyle),maxWidth=columns-options.margin.left-options.margin.right-borderWidth,widest=widestLine(wrapAnsi(text,columns-borderWidth,{hard:!0,trim:!1}))+options.padding.left+options.padding.right;if(options.title&&widthOverride?(options.title=options.title.slice(0,Math.max(0,options.width-2)),options.title&&(options.title=formatTitle(options.title,options.borderStyle))):options.title&&(options.title=options.title.slice(0,Math.max(0,maxWidth-2)),options.title&&(options.title=formatTitle(options.title,options.borderStyle),stringWidth(options.title)>widest&&(options.width=stringWidth(options.title)))),options.width=options.width?options.width:widest,!widthOverride){if(options.margin.left&&options.margin.right&&options.width>maxWidth){let multiplier=(columns-options.width-borderWidth)/(options.margin.left+options.margin.right);options.margin.left=Math.max(0,Math.floor(options.margin.left*multiplier)),options.margin.right=Math.max(0,Math.floor(options.margin.right*multiplier));}options.width=Math.min(options.width,columns-borderWidth-options.margin.left-options.margin.right);}return options.width-(options.padding.left+options.padding.right)<=0&&(options.padding.left=0,options.padding.right=0),options.height&&options.height-(options.padding.top+options.padding.bottom)<=0&&(options.padding.top=0,options.padding.bottom=0),options},isHex=color=>color.match(/^#(?:[0-f]{3}){1,2}$/i),isColorValid=color=>typeof color=="string"&&(chalk8[color]??isHex(color)),getColorFn=color=>isHex(color)?chalk8.hex(color):chalk8[color],getBGColorFn=color=>isHex(color)?chalk8.bgHex(color):chalk8[camelCase(["bg",color])];function boxen(text,options){if(options={padding:0,borderStyle:"single",dimBorder:!1,textAlignment:"left",float:"left",titleAlignment:"left",...options},options.align&&(options.textAlignment=options.align),options.borderColor&&!isColorValid(options.borderColor))throw new Error(`${options.borderColor} is not a valid borderColor`);if(options.backgroundColor&&!isColorValid(options.backgroundColor))throw new Error(`${options.backgroundColor} is not a valid backgroundColor`);return options.padding=getObject(options.padding),options.margin=getObject(options.margin),options=determineDimensions(text,options),text=makeContentText(text,options),boxContent(text,options.width,options)}function dataUriToBuffer(uri){if(!/^data:/i.test(uri))throw new TypeError('`uri` does not appear to be a Data URI (must begin with "data:")');uri=uri.replace(/\r?\n/g,"");let firstComma=uri.indexOf(",");if(firstComma===-1||firstComma<=4)throw new TypeError("malformed data: URI");let meta=uri.substring(5,firstComma).split(";"),charset="",base64=!1,type=meta[0]||"text/plain",typeFull=type;for(let i=1;i<meta.length;i++)meta[i]==="base64"?base64=!0:meta[i]&&(typeFull+=`;${meta[i]}`,meta[i].indexOf("charset=")===0&&(charset=meta[i].substring(8)));!meta[0]&&!charset.length&&(typeFull+=";charset=US-ASCII",charset="US-ASCII");let encoding=base64?"base64":"ascii",data=unescape(uri.substring(firstComma+1)),buffer=Buffer.from(data,encoding);return buffer.type=type,buffer.typeFull=typeFull,buffer.charset=charset,buffer}var dist_default=dataUriToBuffer;var FetchBaseError=class extends Error{constructor(message,type){super(message),Error.captureStackTrace(this,this.constructor),this.type=type;}get name(){return this.constructor.name}get[Symbol.toStringTag](){return this.constructor.name}};var FetchError=class extends FetchBaseError{constructor(message,type,systemError){super(message,type),systemError&&(this.code=this.errno=systemError.code,this.erroredSysCall=systemError.syscall);}};var NAME=Symbol.toStringTag,isURLSearchParameters=object=>typeof object=="object"&&typeof object.append=="function"&&typeof object.delete=="function"&&typeof object.get=="function"&&typeof object.getAll=="function"&&typeof object.has=="function"&&typeof object.set=="function"&&typeof object.sort=="function"&&object[NAME]==="URLSearchParams",isBlob=object=>object&&typeof object=="object"&&typeof object.arrayBuffer=="function"&&typeof object.type=="string"&&typeof object.stream=="function"&&typeof object.constructor=="function"&&/^(Blob|File)$/.test(object[NAME]),isAbortSignal=object=>typeof object=="object"&&(object[NAME]==="AbortSignal"||object[NAME]==="EventTarget"),isDomainOrSubdomain=(destination,original)=>{let orig=new URL(original).hostname,dest=new URL(destination).hostname;return orig===dest||orig.endsWith(`.${dest}`)},isSameProtocol=(destination,original)=>{let orig=new URL(original).protocol,dest=new URL(destination).protocol;return orig===dest};var pipeline=promisify(Stream.pipeline),INTERNALS=Symbol("Body internals"),Body=class{constructor(body,{size=0}={}){let boundary=null;body===null?body=null:isURLSearchParameters(body)?body=Buffer$1.from(body.toString()):isBlob(body)||Buffer$1.isBuffer(body)||(types.isAnyArrayBuffer(body)?body=Buffer$1.from(body):ArrayBuffer.isView(body)?body=Buffer$1.from(body.buffer,body.byteOffset,body.byteLength):body instanceof Stream||(body instanceof FormData?(body=formDataToBlob(body),boundary=body.type.split("=")[1]):body=Buffer$1.from(String(body))));let stream=body;Buffer$1.isBuffer(body)?stream=Stream.Readable.from(body):isBlob(body)&&(stream=Stream.Readable.from(body.stream())),this[INTERNALS]={body,stream,boundary,disturbed:!1,error:null},this.size=size,body instanceof Stream&&body.on("error",error_=>{let error=error_ instanceof FetchBaseError?error_:new FetchError(`Invalid response body while trying to fetch ${this.url}: ${error_.message}`,"system",error_);this[INTERNALS].error=error;});}get body(){return this[INTERNALS].stream}get bodyUsed(){return this[INTERNALS].disturbed}async arrayBuffer(){let{buffer,byteOffset,byteLength}=await consumeBody(this);return buffer.slice(byteOffset,byteOffset+byteLength)}async formData(){let ct=this.headers.get("content-type");if(ct.startsWith("application/x-www-form-urlencoded")){let formData=new FormData,parameters=new URLSearchParams(await this.text());for(let[name,value]of parameters)formData.append(name,value);return formData}let{toFormData}=await import('./multipart-parser-ULPBLTT2.mjs');return toFormData(this.body,ct)}async blob(){let ct=this.headers&&this.headers.get("content-type")||this[INTERNALS].body&&this[INTERNALS].body.type||"",buf=await this.arrayBuffer();return new fetch_blob_default([buf],{type:ct})}async json(){let text=await this.text();return JSON.parse(text)}async text(){let buffer=await consumeBody(this);return new TextDecoder().decode(buffer)}buffer(){return consumeBody(this)}};Body.prototype.buffer=deprecate(Body.prototype.buffer,"Please use 'response.arrayBuffer()' instead of 'response.buffer()'","node-fetch#buffer");Object.defineProperties(Body.prototype,{body:{enumerable:!0},bodyUsed:{enumerable:!0},arrayBuffer:{enumerable:!0},blob:{enumerable:!0},json:{enumerable:!0},text:{enumerable:!0},data:{get:deprecate(()=>{},"data doesn't exist, use json(), text(), arrayBuffer(), or body instead","https://github.com/node-fetch/node-fetch/issues/1000 (response)")}});async function consumeBody(data){if(data[INTERNALS].disturbed)throw new TypeError(`body used already for: ${data.url}`);if(data[INTERNALS].disturbed=!0,data[INTERNALS].error)throw data[INTERNALS].error;let{body}=data;if(body===null)return Buffer$1.alloc(0);if(!(body instanceof Stream))return Buffer$1.alloc(0);let accum=[],accumBytes=0;try{for await(let chunk of body){if(data.size>0&&accumBytes+chunk.length>data.size){let error=new FetchError(`content size at ${data.url} over limit: ${data.size}`,"max-size");throw body.destroy(error),error}accumBytes+=chunk.length,accum.push(chunk);}}catch(error){throw error instanceof FetchBaseError?error:new FetchError(`Invalid response body while trying to fetch ${data.url}: ${error.message}`,"system",error)}if(body.readableEnded===!0||body._readableState.ended===!0)try{return accum.every(c=>typeof c=="string")?Buffer$1.from(accum.join("")):Buffer$1.concat(accum,accumBytes)}catch(error){throw new FetchError(`Could not create Buffer from response body for ${data.url}: ${error.message}`,"system",error)}else throw new FetchError(`Premature close of server response while trying to fetch ${data.url}`)}var clone=(instance,highWaterMark)=>{let p1,p2,{body}=instance[INTERNALS];if(instance.bodyUsed)throw new Error("cannot clone body after it is used");return body instanceof Stream&&typeof body.getBoundary!="function"&&(p1=new PassThrough({highWaterMark}),p2=new PassThrough({highWaterMark}),body.pipe(p1),body.pipe(p2),instance[INTERNALS].stream=p1,body=p2),body},getNonSpecFormDataBoundary=deprecate(body=>body.getBoundary(),"form-data doesn't follow the spec and requires special treatment. Use alternative package","https://github.com/node-fetch/node-fetch/issues/1167"),extractContentType=(body,request)=>body===null?null:typeof body=="string"?"text/plain;charset=UTF-8":isURLSearchParameters(body)?"application/x-www-form-urlencoded;charset=UTF-8":isBlob(body)?body.type||null:Buffer$1.isBuffer(body)||types.isAnyArrayBuffer(body)||ArrayBuffer.isView(body)?null:body instanceof FormData?`multipart/form-data; boundary=${request[INTERNALS].boundary}`:body&&typeof body.getBoundary=="function"?`multipart/form-data;boundary=${getNonSpecFormDataBoundary(body)}`:body instanceof Stream?null:"text/plain;charset=UTF-8",getTotalBytes=request=>{let{body}=request[INTERNALS];return body===null?0:isBlob(body)?body.size:Buffer$1.isBuffer(body)?body.length:body&&typeof body.getLengthSync=="function"&&body.hasKnownLength&&body.hasKnownLength()?body.getLengthSync():null},writeToStream=async(dest,{body})=>{body===null?dest.end():await pipeline(body,dest);};var validateHeaderName=typeof http2.validateHeaderName=="function"?http2.validateHeaderName:name=>{if(!/^[\^`\-\w!#$%&'*+.|~]+$/.test(name)){let error=new TypeError(`Header name must be a valid HTTP token [${name}]`);throw Object.defineProperty(error,"code",{value:"ERR_INVALID_HTTP_TOKEN"}),error}},validateHeaderValue=typeof http2.validateHeaderValue=="function"?http2.validateHeaderValue:(name,value)=>{if(/[^\t\u0020-\u007E\u0080-\u00FF]/.test(value)){let error=new TypeError(`Invalid character in header content ["${name}"]`);throw Object.defineProperty(error,"code",{value:"ERR_INVALID_CHAR"}),error}},Headers=class _Headers extends URLSearchParams{constructor(init){let result=[];if(init instanceof _Headers){let raw=init.raw();for(let[name,values]of Object.entries(raw))result.push(...values.map(value=>[name,value]));}else if(init!=null)if(typeof init=="object"&&!types.isBoxedPrimitive(init)){let method=init[Symbol.iterator];if(method==null)result.push(...Object.entries(init));else {if(typeof method!="function")throw new TypeError("Header pairs must be iterable");result=[...init].map(pair=>{if(typeof pair!="object"||types.isBoxedPrimitive(pair))throw new TypeError("Each header pair must be an iterable object");return [...pair]}).map(pair=>{if(pair.length!==2)throw new TypeError("Each header pair must be a name/value tuple");return [...pair]});}}else throw new TypeError("Failed to construct 'Headers': The provided value is not of type '(sequence<sequence<ByteString>> or record<ByteString, ByteString>)");return result=result.length>0?result.map(([name,value])=>(validateHeaderName(name),validateHeaderValue(name,String(value)),[String(name).toLowerCase(),String(value)])):void 0,super(result),new Proxy(this,{get(target,p,receiver){switch(p){case"append":case"set":return (name,value)=>(validateHeaderName(name),validateHeaderValue(name,String(value)),URLSearchParams.prototype[p].call(target,String(name).toLowerCase(),String(value)));case"delete":case"has":case"getAll":return name=>(validateHeaderName(name),URLSearchParams.prototype[p].call(target,String(name).toLowerCase()));case"keys":return ()=>(target.sort(),new Set(URLSearchParams.prototype.keys.call(target)).keys());default:return Reflect.get(target,p,receiver)}}})}get[Symbol.toStringTag](){return this.constructor.name}toString(){return Object.prototype.toString.call(this)}get(name){let values=this.getAll(name);if(values.length===0)return null;let value=values.join(", ");return /^content-encoding$/i.test(name)&&(value=value.toLowerCase()),value}forEach(callback,thisArg=void 0){for(let name of this.keys())Reflect.apply(callback,thisArg,[this.get(name),name,this]);}*values(){for(let name of this.keys())yield this.get(name);}*entries(){for(let name of this.keys())yield [name,this.get(name)];}[Symbol.iterator](){return this.entries()}raw(){return [...this.keys()].reduce((result,key)=>(result[key]=this.getAll(key),result),{})}[Symbol.for("nodejs.util.inspect.custom")](){return [...this.keys()].reduce((result,key)=>{let values=this.getAll(key);return key==="host"?result[key]=values[0]:result[key]=values.length>1?values:values[0],result},{})}};Object.defineProperties(Headers.prototype,["get","entries","forEach","values"].reduce((result,property)=>(result[property]={enumerable:!0},result),{}));function fromRawHeaders(headers=[]){return new Headers(headers.reduce((result,value,index,array)=>(index%2===0&&result.push(array.slice(index,index+2)),result),[]).filter(([name,value])=>{try{return validateHeaderName(name),validateHeaderValue(name,String(value)),!0}catch{return !1}}))}var redirectStatus=new Set([301,302,303,307,308]),isRedirect=code=>redirectStatus.has(code);var INTERNALS2=Symbol("Response internals"),Response=class _Response extends Body{constructor(body=null,options={}){super(body,options);let status=options.status!=null?options.status:200,headers=new Headers(options.headers);if(body!==null&&!headers.has("Content-Type")){let contentType=extractContentType(body,this);contentType&&headers.append("Content-Type",contentType);}this[INTERNALS2]={type:"default",url:options.url,status,statusText:options.statusText||"",headers,counter:options.counter,highWaterMark:options.highWaterMark};}get type(){return this[INTERNALS2].type}get url(){return this[INTERNALS2].url||""}get status(){return this[INTERNALS2].status}get ok(){return this[INTERNALS2].status>=200&&this[INTERNALS2].status<300}get redirected(){return this[INTERNALS2].counter>0}get statusText(){return this[INTERNALS2].statusText}get headers(){return this[INTERNALS2].headers}get highWaterMark(){return this[INTERNALS2].highWaterMark}clone(){return new _Response(clone(this,this.highWaterMark),{type:this.type,url:this.url,status:this.status,statusText:this.statusText,headers:this.headers,ok:this.ok,redirected:this.redirected,size:this.size,highWaterMark:this.highWaterMark})}static redirect(url,status=302){if(!isRedirect(status))throw new RangeError('Failed to execute "redirect" on "response": Invalid status code');return new _Response(null,{headers:{location:new URL(url).toString()},status})}static error(){let response=new _Response(null,{status:0,statusText:""});return response[INTERNALS2].type="error",response}static json(data=void 0,init={}){let body=JSON.stringify(data);if(body===void 0)throw new TypeError("data is not JSON serializable");let headers=new Headers(init&&init.headers);return headers.has("content-type")||headers.set("content-type","application/json"),new _Response(body,{...init,headers})}get[Symbol.toStringTag](){return "Response"}};Object.defineProperties(Response.prototype,{type:{enumerable:!0},url:{enumerable:!0},status:{enumerable:!0},ok:{enumerable:!0},redirected:{enumerable:!0},statusText:{enumerable:!0},headers:{enumerable:!0},clone:{enumerable:!0}});var getSearch=parsedURL=>{if(parsedURL.search)return parsedURL.search;let lastOffset=parsedURL.href.length-1,hash=parsedURL.hash||(parsedURL.href[lastOffset]==="#"?"#":"");return parsedURL.href[lastOffset-hash.length]==="?"?"?":""};function stripURLForUseAsAReferrer(url,originOnly=!1){return url==null||(url=new URL(url),/^(about|blob|data):$/.test(url.protocol))?"no-referrer":(url.username="",url.password="",url.hash="",originOnly&&(url.pathname="",url.search=""),url)}var ReferrerPolicy=new Set(["","no-referrer","no-referrer-when-downgrade","same-origin","origin","strict-origin","origin-when-cross-origin","strict-origin-when-cross-origin","unsafe-url"]),DEFAULT_REFERRER_POLICY="strict-origin-when-cross-origin";function validateReferrerPolicy(referrerPolicy){if(!ReferrerPolicy.has(referrerPolicy))throw new TypeError(`Invalid referrerPolicy: ${referrerPolicy}`);return referrerPolicy}function isOriginPotentiallyTrustworthy(url){if(/^(http|ws)s:$/.test(url.protocol))return !0;let hostIp=url.host.replace(/(^\[)|(]$)/g,""),hostIPVersion=isIP(hostIp);return hostIPVersion===4&&/^127\./.test(hostIp)||hostIPVersion===6&&/^(((0+:){7})|(::(0+:){0,6}))0*1$/.test(hostIp)?!0:url.host==="localhost"||url.host.endsWith(".localhost")?!1:url.protocol==="file:"}function isUrlPotentiallyTrustworthy(url){return /^about:(blank|srcdoc)$/.test(url)||url.protocol==="data:"||/^(blob|filesystem):$/.test(url.protocol)?!0:isOriginPotentiallyTrustworthy(url)}function determineRequestsReferrer(request,{referrerURLCallback,referrerOriginCallback}={}){if(request.referrer==="no-referrer"||request.referrerPolicy==="")return null;let policy=request.referrerPolicy;if(request.referrer==="about:client")return "no-referrer";let referrerSource=request.referrer,referrerURL=stripURLForUseAsAReferrer(referrerSource),referrerOrigin=stripURLForUseAsAReferrer(referrerSource,!0);referrerURL.toString().length>4096&&(referrerURL=referrerOrigin),referrerURLCallback&&(referrerURL=referrerURLCallback(referrerURL)),referrerOriginCallback&&(referrerOrigin=referrerOriginCallback(referrerOrigin));let currentURL=new URL(request.url);switch(policy){case"no-referrer":return "no-referrer";case"origin":return referrerOrigin;case"unsafe-url":return referrerURL;case"strict-origin":return isUrlPotentiallyTrustworthy(referrerURL)&&!isUrlPotentiallyTrustworthy(currentURL)?"no-referrer":referrerOrigin.toString();case"strict-origin-when-cross-origin":return referrerURL.origin===currentURL.origin?referrerURL:isUrlPotentiallyTrustworthy(referrerURL)&&!isUrlPotentiallyTrustworthy(currentURL)?"no-referrer":referrerOrigin;case"same-origin":return referrerURL.origin===currentURL.origin?referrerURL:"no-referrer";case"origin-when-cross-origin":return referrerURL.origin===currentURL.origin?referrerURL:referrerOrigin;case"no-referrer-when-downgrade":return isUrlPotentiallyTrustworthy(referrerURL)&&!isUrlPotentiallyTrustworthy(currentURL)?"no-referrer":referrerURL;default:throw new TypeError(`Invalid referrerPolicy: ${policy}`)}}function parseReferrerPolicyFromHeader(headers){let policyTokens=(headers.get("referrer-policy")||"").split(/[,\s]+/),policy="";for(let token of policyTokens)token&&ReferrerPolicy.has(token)&&(policy=token);return policy}var INTERNALS3=Symbol("Request internals"),isRequest=object=>typeof object=="object"&&typeof object[INTERNALS3]=="object",doBadDataWarn=deprecate(()=>{},".data is not a valid RequestInit property, use .body instead","https://github.com/node-fetch/node-fetch/issues/1000 (request)"),Request=class _Request extends Body{constructor(input,init={}){let parsedURL;if(isRequest(input)?parsedURL=new URL(input.url):(parsedURL=new URL(input),input={}),parsedURL.username!==""||parsedURL.password!=="")throw new TypeError(`${parsedURL} is an url with embedded credentials.`);let method=init.method||input.method||"GET";if(/^(delete|get|head|options|post|put)$/i.test(method)&&(method=method.toUpperCase()),!isRequest(init)&&"data"in init&&doBadDataWarn(),(init.body!=null||isRequest(input)&&input.body!==null)&&(method==="GET"||method==="HEAD"))throw new TypeError("Request with GET/HEAD method cannot have body");let inputBody=init.body?init.body:isRequest(input)&&input.body!==null?clone(input):null;super(inputBody,{size:init.size||input.size||0});let headers=new Headers(init.headers||input.headers||{});if(inputBody!==null&&!headers.has("Content-Type")){let contentType=extractContentType(inputBody,this);contentType&&headers.set("Content-Type",contentType);}let signal=isRequest(input)?input.signal:null;if("signal"in init&&(signal=init.signal),signal!=null&&!isAbortSignal(signal))throw new TypeError("Expected signal to be an instanceof AbortSignal or EventTarget");let referrer=init.referrer==null?input.referrer:init.referrer;if(referrer==="")referrer="no-referrer";else if(referrer){let parsedReferrer=new URL(referrer);referrer=/^about:(\/\/)?client$/.test(parsedReferrer)?"client":parsedReferrer;}else referrer=void 0;this[INTERNALS3]={method,redirect:init.redirect||input.redirect||"follow",headers,parsedURL,signal,referrer},this.follow=init.follow===void 0?input.follow===void 0?20:input.follow:init.follow,this.compress=init.compress===void 0?input.compress===void 0?!0:input.compress:init.compress,this.counter=init.counter||input.counter||0,this.agent=init.agent||input.agent,this.highWaterMark=init.highWaterMark||input.highWaterMark||16384,this.insecureHTTPParser=init.insecureHTTPParser||input.insecureHTTPParser||!1,this.referrerPolicy=init.referrerPolicy||input.referrerPolicy||"";}get method(){return this[INTERNALS3].method}get url(){return format(this[INTERNALS3].parsedURL)}get headers(){return this[INTERNALS3].headers}get redirect(){return this[INTERNALS3].redirect}get signal(){return this[INTERNALS3].signal}get referrer(){if(this[INTERNALS3].referrer==="no-referrer")return "";if(this[INTERNALS3].referrer==="client")return "about:client";if(this[INTERNALS3].referrer)return this[INTERNALS3].referrer.toString()}get referrerPolicy(){return this[INTERNALS3].referrerPolicy}set referrerPolicy(referrerPolicy){this[INTERNALS3].referrerPolicy=validateReferrerPolicy(referrerPolicy);}clone(){return new _Request(this)}get[Symbol.toStringTag](){return "Request"}};Object.defineProperties(Request.prototype,{method:{enumerable:!0},url:{enumerable:!0},headers:{enumerable:!0},redirect:{enumerable:!0},clone:{enumerable:!0},signal:{enumerable:!0},referrer:{enumerable:!0},referrerPolicy:{enumerable:!0}});var getNodeRequestOptions=request=>{let{parsedURL}=request[INTERNALS3],headers=new Headers(request[INTERNALS3].headers);headers.has("Accept")||headers.set("Accept","*/*");let contentLengthValue=null;if(request.body===null&&/^(post|put)$/i.test(request.method)&&(contentLengthValue="0"),request.body!==null){let totalBytes=getTotalBytes(request);typeof totalBytes=="number"&&!Number.isNaN(totalBytes)&&(contentLengthValue=String(totalBytes));}contentLengthValue&&headers.set("Content-Length",contentLengthValue),request.referrerPolicy===""&&(request.referrerPolicy=DEFAULT_REFERRER_POLICY),request.referrer&&request.referrer!=="no-referrer"?request[INTERNALS3].referrer=determineRequestsReferrer(request):request[INTERNALS3].referrer="no-referrer",request[INTERNALS3].referrer instanceof URL&&headers.set("Referer",request.referrer),headers.has("User-Agent")||headers.set("User-Agent","node-fetch"),request.compress&&!headers.has("Accept-Encoding")&&headers.set("Accept-Encoding","gzip, deflate, br");let{agent}=request;typeof agent=="function"&&(agent=agent(parsedURL));let search=getSearch(parsedURL),options={path:parsedURL.pathname+search,method:request.method,headers:headers[Symbol.for("nodejs.util.inspect.custom")](),insecureHTTPParser:request.insecureHTTPParser,agent};return {parsedURL,options}};var AbortError=class extends FetchBaseError{constructor(message,type="aborted"){super(message,type);}};var supportedSchemas=new Set(["data:","http:","https:"]);async function fetch(url,options_){return new Promise((resolve3,reject)=>{let request=new Request(url,options_),{parsedURL,options}=getNodeRequestOptions(request);if(!supportedSchemas.has(parsedURL.protocol))throw new TypeError(`node-fetch cannot load ${url}. URL scheme "${parsedURL.protocol.replace(/:$/,"")}" is not supported.`);if(parsedURL.protocol==="data:"){let data=dist_default(request.url),response2=new Response(data,{headers:{"Content-Type":data.typeFull}});resolve3(response2);return}let send=(parsedURL.protocol==="https:"?https:http2).request,{signal}=request,response=null,abort=()=>{let error=new AbortError("The operation was aborted.");reject(error),request.body&&request.body instanceof Stream.Readable&&request.body.destroy(error),!(!response||!response.body)&&response.body.emit("error",error);};if(signal&&signal.aborted){abort();return}let abortAndFinalize=()=>{abort(),finalize();},request_=send(parsedURL.toString(),options);signal&&signal.addEventListener("abort",abortAndFinalize);let finalize=()=>{request_.abort(),signal&&signal.removeEventListener("abort",abortAndFinalize);};request_.on("error",error=>{reject(new FetchError(`request to ${request.url} failed, reason: ${error.message}`,"system",error)),finalize();}),fixResponseChunkedTransferBadEnding(request_,error=>{response&&response.body&&response.body.destroy(error);}),process.version<"v14"&&request_.on("socket",s=>{let endedWithEventsCount;s.prependListener("end",()=>{endedWithEventsCount=s._eventsCount;}),s.prependListener("close",hadError=>{if(response&&endedWithEventsCount<s._eventsCount&&!hadError){let error=new Error("Premature close");error.code="ERR_STREAM_PREMATURE_CLOSE",response.body.emit("error",error);}});}),request_.on("response",response_=>{request_.setTimeout(0);let headers=fromRawHeaders(response_.rawHeaders);if(isRedirect(response_.statusCode)){let location=headers.get("Location"),locationURL=null;try{locationURL=location===null?null:new URL(location,request.url);}catch{if(request.redirect!=="manual"){reject(new FetchError(`uri requested responds with an invalid redirect URL: ${location}`,"invalid-redirect")),finalize();return}}switch(request.redirect){case"error":reject(new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${request.url}`,"no-redirect")),finalize();return;case"manual":break;case"follow":{if(locationURL===null)break;if(request.counter>=request.follow){reject(new FetchError(`maximum redirect reached at: ${request.url}`,"max-redirect")),finalize();return}let requestOptions={headers:new Headers(request.headers),follow:request.follow,counter:request.counter+1,agent:request.agent,compress:request.compress,method:request.method,body:clone(request),signal:request.signal,size:request.size,referrer:request.referrer,referrerPolicy:request.referrerPolicy};if(!isDomainOrSubdomain(request.url,locationURL)||!isSameProtocol(request.url,locationURL))for(let name of ["authorization","www-authenticate","cookie","cookie2"])requestOptions.headers.delete(name);if(response_.statusCode!==303&&request.body&&options_.body instanceof Stream.Readable){reject(new FetchError("Cannot follow redirect with body being a readable stream","unsupported-redirect")),finalize();return}(response_.statusCode===303||(response_.statusCode===301||response_.statusCode===302)&&request.method==="POST")&&(requestOptions.method="GET",requestOptions.body=void 0,requestOptions.headers.delete("content-length"));let responseReferrerPolicy=parseReferrerPolicyFromHeader(headers);responseReferrerPolicy&&(requestOptions.referrerPolicy=responseReferrerPolicy),resolve3(fetch(new Request(locationURL,requestOptions))),finalize();return}default:return reject(new TypeError(`Redirect option '${request.redirect}' is not a valid value of RequestRedirect`))}}signal&&response_.once("end",()=>{signal.removeEventListener("abort",abortAndFinalize);});let body=pipeline$1(response_,new PassThrough,error=>{error&&reject(error);});process.version<"v12.10"&&response_.on("aborted",abortAndFinalize);let responseOptions={url:request.url,status:response_.statusCode,statusText:response_.statusMessage,headers,size:request.size,counter:request.counter,highWaterMark:request.highWaterMark},codings=headers.get("Content-Encoding");if(!request.compress||request.method==="HEAD"||codings===null||response_.statusCode===204||response_.statusCode===304){response=new Response(body,responseOptions),resolve3(response);return}let zlibOptions={flush:zlib.Z_SYNC_FLUSH,finishFlush:zlib.Z_SYNC_FLUSH};if(codings==="gzip"||codings==="x-gzip"){body=pipeline$1(body,zlib.createGunzip(zlibOptions),error=>{error&&reject(error);}),response=new Response(body,responseOptions),resolve3(response);return}if(codings==="deflate"||codings==="x-deflate"){let raw=pipeline$1(response_,new PassThrough,error=>{error&&reject(error);});raw.once("data",chunk=>{(chunk[0]&15)===8?body=pipeline$1(body,zlib.createInflate(),error=>{error&&reject(error);}):body=pipeline$1(body,zlib.createInflateRaw(),error=>{error&&reject(error);}),response=new Response(body,responseOptions),resolve3(response);}),raw.once("end",()=>{response||(response=new Response(body,responseOptions),resolve3(response));});return}if(codings==="br"){body=pipeline$1(body,zlib.createBrotliDecompress(),error=>{error&&reject(error);}),response=new Response(body,responseOptions),resolve3(response);return}response=new Response(body,responseOptions),resolve3(response);}),writeToStream(request_,request).catch(reject);})}function fixResponseChunkedTransferBadEnding(request,errorCallback){let LAST_CHUNK=Buffer$1.from(`0\r
|
|
76
76
|
\r
|
|
77
77
|
`),isChunkedTransfer=!1,properLastChunkReceived=!1,previousChunk;request.on("response",response=>{let{headers}=response;isChunkedTransfer=headers["transfer-encoding"]==="chunked"&&!headers["content-length"];}),request.on("socket",socket=>{let onSocketClose=()=>{if(isChunkedTransfer&&!properLastChunkReceived){let error=new Error("Premature close");error.code="ERR_STREAM_PREMATURE_CLOSE",errorCallback(error);}},onData=buf=>{properLastChunkReceived=Buffer$1.compare(buf.slice(-5),LAST_CHUNK)===0,!properLastChunkReceived&&previousChunk&&(properLastChunkReceived=Buffer$1.compare(previousChunk.slice(-3),LAST_CHUNK.slice(0,3))===0&&Buffer$1.compare(buf.slice(-2),LAST_CHUNK.slice(3))===0),previousChunk=buf;};socket.prependListener("close",onSocketClose),socket.on("data",onData),request.on("close",()=>{socket.removeListener("close",onSocketClose),socket.removeListener("data",onData);});});}var{STORYBOOK_VERSION_BASE="https://storybook.js.org",CI}=process.env,updateCheck=async version=>{let result,time=Date.now();try{let fromCache=await cache.get("lastUpdateCheck",{success:!1,time:0});time-864e5>fromCache.time&&!CI?(result={success:!0,cached:!1,data:await(await Promise.race([fetch(`${STORYBOOK_VERSION_BASE}/versions.json?current=${version}`),new Promise((res,rej)=>global.setTimeout(rej,1500))])).json(),time},await cache.set("lastUpdateCheck",result)):result={...fromCache,cached:!0};}catch(error){result={success:!1,cached:!1,error,time};}return result};function createUpdateMessage(updateInfo,version){let updateMessage;try{let upgradeCommand=`npx storybook@${semver2.prerelease(updateInfo.data.latest.version)?"next":"latest"} upgrade`;updateMessage=updateInfo.success&&semver2.lt(version,updateInfo.data.latest.version)?dedent`
|
|
78
78
|
${colors.orange(`A new version (${chalk8.bold(updateInfo.data.latest.version)}) is available!`)}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { FormData, file_default } from './chunk-
|
|
1
|
+
import { FormData, file_default } from './chunk-OUCMVY4B.mjs';
|
|
2
2
|
|
|
3
3
|
var s=0,S={START_BOUNDARY:s++,HEADER_FIELD_START:s++,HEADER_FIELD:s++,HEADER_VALUE_START:s++,HEADER_VALUE:s++,HEADER_VALUE_ALMOST_DONE:s++,HEADERS_ALMOST_DONE:s++,PART_DATA_START:s++,PART_DATA:s++,END:s++},f=1,F={PART_BOUNDARY:f,LAST_BOUNDARY:f*=2},LF=10,CR=13,SPACE=32,HYPHEN=45,COLON=58,A=97,Z=122,lower=c=>c|32,noop=()=>{},MultipartParser=class{constructor(boundary){this.index=0,this.flags=0,this.onHeaderEnd=noop,this.onHeaderField=noop,this.onHeadersEnd=noop,this.onHeaderValue=noop,this.onPartBegin=noop,this.onPartData=noop,this.onPartEnd=noop,this.boundaryChars={},boundary=`\r
|
|
4
4
|
--`+boundary;let ui8a=new Uint8Array(boundary.length);for(let i=0;i<boundary.length;i++)ui8a[i]=boundary.charCodeAt(i),this.boundaryChars[ui8a[i]]=!0;this.boundary=ui8a,this.lookbehind=new Uint8Array(this.boundary.length+8),this.state=S.START_BOUNDARY;}write(data){let i=0,length_=data.length,previousIndex=this.index,{lookbehind,boundary,boundaryChars,index,state,flags}=this,boundaryLength=this.boundary.length,boundaryEnd=boundaryLength-1,bufferLength=data.length,c,cl,mark=name=>{this[name+"Mark"]=i;},clear=name=>{delete this[name+"Mark"];},callback=(callbackSymbol,start,end,ui8a)=>{(start===void 0||start!==end)&&this[callbackSymbol](ui8a&&ui8a.subarray(start,end));},dataCallback=(name,clear2)=>{let markSymbol=name+"Mark";markSymbol in this&&(clear2?(callback(name,this[markSymbol],i,data),delete this[markSymbol]):(callback(name,this[markSymbol],data.length,data),this[markSymbol]=0));};for(i=0;i<length_;i++)switch(c=data[i],state){case S.START_BOUNDARY:if(index===boundary.length-2){if(c===HYPHEN)flags|=F.LAST_BOUNDARY;else if(c!==CR)return;index++;break}else if(index-1===boundary.length-2){if(flags&F.LAST_BOUNDARY&&c===HYPHEN)state=S.END,flags=0;else if(!(flags&F.LAST_BOUNDARY)&&c===LF)index=0,callback("onPartBegin"),state=S.HEADER_FIELD_START;else return;break}c!==boundary[index+2]&&(index=-2),c===boundary[index+2]&&index++;break;case S.HEADER_FIELD_START:state=S.HEADER_FIELD,mark("onHeaderField"),index=0;case S.HEADER_FIELD:if(c===CR){clear("onHeaderField"),state=S.HEADERS_ALMOST_DONE;break}if(index++,c===HYPHEN)break;if(c===COLON){if(index===1)return;dataCallback("onHeaderField",!0),state=S.HEADER_VALUE_START;break}if(cl=lower(c),cl<A||cl>Z)return;break;case S.HEADER_VALUE_START:if(c===SPACE)break;mark("onHeaderValue"),state=S.HEADER_VALUE;case S.HEADER_VALUE:c===CR&&(dataCallback("onHeaderValue",!0),callback("onHeaderEnd"),state=S.HEADER_VALUE_ALMOST_DONE);break;case S.HEADER_VALUE_ALMOST_DONE:if(c!==LF)return;state=S.HEADER_FIELD_START;break;case S.HEADERS_ALMOST_DONE:if(c!==LF)return;callback("onHeadersEnd"),state=S.PART_DATA_START;break;case S.PART_DATA_START:state=S.PART_DATA,mark("onPartData");case S.PART_DATA:if(previousIndex=index,index===0){for(i+=boundaryEnd;i<bufferLength&&!(data[i]in boundaryChars);)i+=boundaryLength;i-=boundaryEnd,c=data[i];}if(index<boundary.length)boundary[index]===c?(index===0&&dataCallback("onPartData",!0),index++):index=0;else if(index===boundary.length)index++,c===CR?flags|=F.PART_BOUNDARY:c===HYPHEN?flags|=F.LAST_BOUNDARY:index=0;else if(index-1===boundary.length)if(flags&F.PART_BOUNDARY){if(index=0,c===LF){flags&=~F.PART_BOUNDARY,callback("onPartEnd"),callback("onPartBegin"),state=S.HEADER_FIELD_START;break}}else flags&F.LAST_BOUNDARY&&c===HYPHEN?(callback("onPartEnd"),state=S.END,flags=0):index=0;if(index>0)lookbehind[index-1]=c;else if(previousIndex>0){let _lookbehind=new Uint8Array(lookbehind.buffer,lookbehind.byteOffset,lookbehind.byteLength);callback("onPartData",0,previousIndex,_lookbehind),previousIndex=0,mark("onPartData"),i--;}break;case S.END:break;default:throw new Error(`Unexpected state entered: ${state}`)}dataCallback("onHeaderField"),dataCallback("onHeaderValue"),dataCallback("onPartData"),this.index=index,this.state=state,this.flags=flags;}end(){if(this.state===S.HEADER_FIELD_START&&this.index===0||this.state===S.PART_DATA&&this.index===this.boundary.length)this.onPartEnd();else if(this.state!==S.END)throw new Error("MultipartParser.end(): stream ended unexpectedly")}};function _fileName(headerValue){let m=headerValue.match(/\bfilename=("(.*?)"|([^()<>@,;:\\"/[\]?={}\s\t]+))($|;\s)/i);if(!m)return;let match=m[2]||m[3]||"",filename=match.slice(match.lastIndexOf("\\")+1);return filename=filename.replace(/%22/g,'"'),filename=filename.replace(/&#(\d{4});/g,(m2,code)=>String.fromCharCode(code)),filename}async function toFormData(Body,ct){if(!/multipart/i.test(ct))throw new TypeError("Failed to fetch");let m=ct.match(/boundary=(?:"([^"]+)"|([^;]+))/i);if(!m)throw new TypeError("no or bad content-type header, no multipart boundary");let parser=new MultipartParser(m[1]||m[2]),headerField,headerValue,entryValue,entryName,contentType,filename,entryChunks=[],formData=new FormData,onPartData=ui8a=>{entryValue+=decoder.decode(ui8a,{stream:!0});},appendToFile=ui8a=>{entryChunks.push(ui8a);},appendFileToFormData=()=>{let file=new file_default(entryChunks,filename,{type:contentType});formData.append(entryName,file);},appendEntryToFormData=()=>{formData.append(entryName,entryValue);},decoder=new TextDecoder("utf-8");decoder.decode(),parser.onPartBegin=function(){parser.onPartData=onPartData,parser.onPartEnd=appendEntryToFormData,headerField="",headerValue="",entryValue="",entryName="",contentType="",filename=null,entryChunks.length=0;},parser.onHeaderField=function(ui8a){headerField+=decoder.decode(ui8a,{stream:!0});},parser.onHeaderValue=function(ui8a){headerValue+=decoder.decode(ui8a,{stream:!0});},parser.onHeaderEnd=function(){if(headerValue+=decoder.decode(),headerField=headerField.toLowerCase(),headerField==="content-disposition"){let m2=headerValue.match(/\bname=("([^"]*)"|([^()<>@,;:\\"/[\]?={}\s\t]+))/i);m2&&(entryName=m2[2]||m2[3]||""),filename=_fileName(headerValue),filename&&(parser.onPartData=appendToFile,parser.onPartEnd=appendFileToFormData);}else headerField==="content-type"&&(contentType=headerValue);headerValue="",headerField="";};for await(let chunk of Body)parser.write(chunk);return parser.end(),formData}
|