@chromatic-com/vitest 1.0.1 → 1.0.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/plugin.js DELETED
@@ -1,2148 +0,0 @@
1
- var __create = Object.create;
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __getProtoOf = Object.getPrototypeOf;
6
- var __hasOwnProp = Object.prototype.hasOwnProperty;
7
- var __commonJS = (cb, mod) => function __require() {
8
- return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
19
- // If the importer is in node compatibility mode or this is not an ESM
20
- // file that has been converted to a CommonJS file using a Babel-
21
- // compatible transform (i.e. "__esModule" has not been set), then set
22
- // "default" to the CommonJS "module.exports" for node compatibility.
23
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
24
- mod
25
- ));
26
-
27
- // ../../node_modules/.pnpm/mime@3.0.0/node_modules/mime/Mime.js
28
- var require_Mime = __commonJS({
29
- "../../node_modules/.pnpm/mime@3.0.0/node_modules/mime/Mime.js"(exports, module) {
30
- "use strict";
31
- function Mime() {
32
- this._types = /* @__PURE__ */ Object.create(null);
33
- this._extensions = /* @__PURE__ */ Object.create(null);
34
- for (let i = 0; i < arguments.length; i++) {
35
- this.define(arguments[i]);
36
- }
37
- this.define = this.define.bind(this);
38
- this.getType = this.getType.bind(this);
39
- this.getExtension = this.getExtension.bind(this);
40
- }
41
- Mime.prototype.define = function(typeMap, force) {
42
- for (let type in typeMap) {
43
- let extensions = typeMap[type].map(function(t) {
44
- return t.toLowerCase();
45
- });
46
- type = type.toLowerCase();
47
- for (let i = 0; i < extensions.length; i++) {
48
- const ext = extensions[i];
49
- if (ext[0] === "*") {
50
- continue;
51
- }
52
- if (!force && ext in this._types) {
53
- throw new Error(
54
- 'Attempt to change mapping for "' + ext + '" extension from "' + this._types[ext] + '" to "' + type + '". Pass `force=true` to allow this, otherwise remove "' + ext + '" from the list of extensions for "' + type + '".'
55
- );
56
- }
57
- this._types[ext] = type;
58
- }
59
- if (force || !this._extensions[type]) {
60
- const ext = extensions[0];
61
- this._extensions[type] = ext[0] !== "*" ? ext : ext.substr(1);
62
- }
63
- }
64
- };
65
- Mime.prototype.getType = function(path3) {
66
- path3 = String(path3);
67
- let last = path3.replace(/^.*[/\\]/, "").toLowerCase();
68
- let ext = last.replace(/^.*\./, "").toLowerCase();
69
- let hasPath = last.length < path3.length;
70
- let hasDot = ext.length < last.length - 1;
71
- return (hasDot || !hasPath) && this._types[ext] || null;
72
- };
73
- Mime.prototype.getExtension = function(type) {
74
- type = /^\s*([^;\s]*)/.test(type) && RegExp.$1;
75
- return type && this._extensions[type.toLowerCase()] || null;
76
- };
77
- module.exports = Mime;
78
- }
79
- });
80
-
81
- // ../../node_modules/.pnpm/mime@3.0.0/node_modules/mime/types/standard.js
82
- var require_standard = __commonJS({
83
- "../../node_modules/.pnpm/mime@3.0.0/node_modules/mime/types/standard.js"(exports, module) {
84
- module.exports = { "application/andrew-inset": ["ez"], "application/applixware": ["aw"], "application/atom+xml": ["atom"], "application/atomcat+xml": ["atomcat"], "application/atomdeleted+xml": ["atomdeleted"], "application/atomsvc+xml": ["atomsvc"], "application/atsc-dwd+xml": ["dwd"], "application/atsc-held+xml": ["held"], "application/atsc-rsat+xml": ["rsat"], "application/bdoc": ["bdoc"], "application/calendar+xml": ["xcs"], "application/ccxml+xml": ["ccxml"], "application/cdfx+xml": ["cdfx"], "application/cdmi-capability": ["cdmia"], "application/cdmi-container": ["cdmic"], "application/cdmi-domain": ["cdmid"], "application/cdmi-object": ["cdmio"], "application/cdmi-queue": ["cdmiq"], "application/cu-seeme": ["cu"], "application/dash+xml": ["mpd"], "application/davmount+xml": ["davmount"], "application/docbook+xml": ["dbk"], "application/dssc+der": ["dssc"], "application/dssc+xml": ["xdssc"], "application/ecmascript": ["es", "ecma"], "application/emma+xml": ["emma"], "application/emotionml+xml": ["emotionml"], "application/epub+zip": ["epub"], "application/exi": ["exi"], "application/express": ["exp"], "application/fdt+xml": ["fdt"], "application/font-tdpfr": ["pfr"], "application/geo+json": ["geojson"], "application/gml+xml": ["gml"], "application/gpx+xml": ["gpx"], "application/gxf": ["gxf"], "application/gzip": ["gz"], "application/hjson": ["hjson"], "application/hyperstudio": ["stk"], "application/inkml+xml": ["ink", "inkml"], "application/ipfix": ["ipfix"], "application/its+xml": ["its"], "application/java-archive": ["jar", "war", "ear"], "application/java-serialized-object": ["ser"], "application/java-vm": ["class"], "application/javascript": ["js", "mjs"], "application/json": ["json", "map"], "application/json5": ["json5"], "application/jsonml+json": ["jsonml"], "application/ld+json": ["jsonld"], "application/lgr+xml": ["lgr"], "application/lost+xml": ["lostxml"], "application/mac-binhex40": ["hqx"], "application/mac-compactpro": ["cpt"], "application/mads+xml": ["mads"], "application/manifest+json": ["webmanifest"], "application/marc": ["mrc"], "application/marcxml+xml": ["mrcx"], "application/mathematica": ["ma", "nb", "mb"], "application/mathml+xml": ["mathml"], "application/mbox": ["mbox"], "application/mediaservercontrol+xml": ["mscml"], "application/metalink+xml": ["metalink"], "application/metalink4+xml": ["meta4"], "application/mets+xml": ["mets"], "application/mmt-aei+xml": ["maei"], "application/mmt-usd+xml": ["musd"], "application/mods+xml": ["mods"], "application/mp21": ["m21", "mp21"], "application/mp4": ["mp4s", "m4p"], "application/msword": ["doc", "dot"], "application/mxf": ["mxf"], "application/n-quads": ["nq"], "application/n-triples": ["nt"], "application/node": ["cjs"], "application/octet-stream": ["bin", "dms", "lrf", "mar", "so", "dist", "distz", "pkg", "bpk", "dump", "elc", "deploy", "exe", "dll", "deb", "dmg", "iso", "img", "msi", "msp", "msm", "buffer"], "application/oda": ["oda"], "application/oebps-package+xml": ["opf"], "application/ogg": ["ogx"], "application/omdoc+xml": ["omdoc"], "application/onenote": ["onetoc", "onetoc2", "onetmp", "onepkg"], "application/oxps": ["oxps"], "application/p2p-overlay+xml": ["relo"], "application/patch-ops-error+xml": ["xer"], "application/pdf": ["pdf"], "application/pgp-encrypted": ["pgp"], "application/pgp-signature": ["asc", "sig"], "application/pics-rules": ["prf"], "application/pkcs10": ["p10"], "application/pkcs7-mime": ["p7m", "p7c"], "application/pkcs7-signature": ["p7s"], "application/pkcs8": ["p8"], "application/pkix-attr-cert": ["ac"], "application/pkix-cert": ["cer"], "application/pkix-crl": ["crl"], "application/pkix-pkipath": ["pkipath"], "application/pkixcmp": ["pki"], "application/pls+xml": ["pls"], "application/postscript": ["ai", "eps", "ps"], "application/provenance+xml": ["provx"], "application/pskc+xml": ["pskcxml"], "application/raml+yaml": ["raml"], "application/rdf+xml": ["rdf", "owl"], "application/reginfo+xml": ["rif"], "application/relax-ng-compact-syntax": ["rnc"], "application/resource-lists+xml": ["rl"], "application/resource-lists-diff+xml": ["rld"], "application/rls-services+xml": ["rs"], "application/route-apd+xml": ["rapd"], "application/route-s-tsid+xml": ["sls"], "application/route-usd+xml": ["rusd"], "application/rpki-ghostbusters": ["gbr"], "application/rpki-manifest": ["mft"], "application/rpki-roa": ["roa"], "application/rsd+xml": ["rsd"], "application/rss+xml": ["rss"], "application/rtf": ["rtf"], "application/sbml+xml": ["sbml"], "application/scvp-cv-request": ["scq"], "application/scvp-cv-response": ["scs"], "application/scvp-vp-request": ["spq"], "application/scvp-vp-response": ["spp"], "application/sdp": ["sdp"], "application/senml+xml": ["senmlx"], "application/sensml+xml": ["sensmlx"], "application/set-payment-initiation": ["setpay"], "application/set-registration-initiation": ["setreg"], "application/shf+xml": ["shf"], "application/sieve": ["siv", "sieve"], "application/smil+xml": ["smi", "smil"], "application/sparql-query": ["rq"], "application/sparql-results+xml": ["srx"], "application/srgs": ["gram"], "application/srgs+xml": ["grxml"], "application/sru+xml": ["sru"], "application/ssdl+xml": ["ssdl"], "application/ssml+xml": ["ssml"], "application/swid+xml": ["swidtag"], "application/tei+xml": ["tei", "teicorpus"], "application/thraud+xml": ["tfi"], "application/timestamped-data": ["tsd"], "application/toml": ["toml"], "application/trig": ["trig"], "application/ttml+xml": ["ttml"], "application/ubjson": ["ubj"], "application/urc-ressheet+xml": ["rsheet"], "application/urc-targetdesc+xml": ["td"], "application/voicexml+xml": ["vxml"], "application/wasm": ["wasm"], "application/widget": ["wgt"], "application/winhlp": ["hlp"], "application/wsdl+xml": ["wsdl"], "application/wspolicy+xml": ["wspolicy"], "application/xaml+xml": ["xaml"], "application/xcap-att+xml": ["xav"], "application/xcap-caps+xml": ["xca"], "application/xcap-diff+xml": ["xdf"], "application/xcap-el+xml": ["xel"], "application/xcap-ns+xml": ["xns"], "application/xenc+xml": ["xenc"], "application/xhtml+xml": ["xhtml", "xht"], "application/xliff+xml": ["xlf"], "application/xml": ["xml", "xsl", "xsd", "rng"], "application/xml-dtd": ["dtd"], "application/xop+xml": ["xop"], "application/xproc+xml": ["xpl"], "application/xslt+xml": ["*xsl", "xslt"], "application/xspf+xml": ["xspf"], "application/xv+xml": ["mxml", "xhvml", "xvml", "xvm"], "application/yang": ["yang"], "application/yin+xml": ["yin"], "application/zip": ["zip"], "audio/3gpp": ["*3gpp"], "audio/adpcm": ["adp"], "audio/amr": ["amr"], "audio/basic": ["au", "snd"], "audio/midi": ["mid", "midi", "kar", "rmi"], "audio/mobile-xmf": ["mxmf"], "audio/mp3": ["*mp3"], "audio/mp4": ["m4a", "mp4a"], "audio/mpeg": ["mpga", "mp2", "mp2a", "mp3", "m2a", "m3a"], "audio/ogg": ["oga", "ogg", "spx", "opus"], "audio/s3m": ["s3m"], "audio/silk": ["sil"], "audio/wav": ["wav"], "audio/wave": ["*wav"], "audio/webm": ["weba"], "audio/xm": ["xm"], "font/collection": ["ttc"], "font/otf": ["otf"], "font/ttf": ["ttf"], "font/woff": ["woff"], "font/woff2": ["woff2"], "image/aces": ["exr"], "image/apng": ["apng"], "image/avif": ["avif"], "image/bmp": ["bmp"], "image/cgm": ["cgm"], "image/dicom-rle": ["drle"], "image/emf": ["emf"], "image/fits": ["fits"], "image/g3fax": ["g3"], "image/gif": ["gif"], "image/heic": ["heic"], "image/heic-sequence": ["heics"], "image/heif": ["heif"], "image/heif-sequence": ["heifs"], "image/hej2k": ["hej2"], "image/hsj2": ["hsj2"], "image/ief": ["ief"], "image/jls": ["jls"], "image/jp2": ["jp2", "jpg2"], "image/jpeg": ["jpeg", "jpg", "jpe"], "image/jph": ["jph"], "image/jphc": ["jhc"], "image/jpm": ["jpm"], "image/jpx": ["jpx", "jpf"], "image/jxr": ["jxr"], "image/jxra": ["jxra"], "image/jxrs": ["jxrs"], "image/jxs": ["jxs"], "image/jxsc": ["jxsc"], "image/jxsi": ["jxsi"], "image/jxss": ["jxss"], "image/ktx": ["ktx"], "image/ktx2": ["ktx2"], "image/png": ["png"], "image/sgi": ["sgi"], "image/svg+xml": ["svg", "svgz"], "image/t38": ["t38"], "image/tiff": ["tif", "tiff"], "image/tiff-fx": ["tfx"], "image/webp": ["webp"], "image/wmf": ["wmf"], "message/disposition-notification": ["disposition-notification"], "message/global": ["u8msg"], "message/global-delivery-status": ["u8dsn"], "message/global-disposition-notification": ["u8mdn"], "message/global-headers": ["u8hdr"], "message/rfc822": ["eml", "mime"], "model/3mf": ["3mf"], "model/gltf+json": ["gltf"], "model/gltf-binary": ["glb"], "model/iges": ["igs", "iges"], "model/mesh": ["msh", "mesh", "silo"], "model/mtl": ["mtl"], "model/obj": ["obj"], "model/step+xml": ["stpx"], "model/step+zip": ["stpz"], "model/step-xml+zip": ["stpxz"], "model/stl": ["stl"], "model/vrml": ["wrl", "vrml"], "model/x3d+binary": ["*x3db", "x3dbz"], "model/x3d+fastinfoset": ["x3db"], "model/x3d+vrml": ["*x3dv", "x3dvz"], "model/x3d+xml": ["x3d", "x3dz"], "model/x3d-vrml": ["x3dv"], "text/cache-manifest": ["appcache", "manifest"], "text/calendar": ["ics", "ifb"], "text/coffeescript": ["coffee", "litcoffee"], "text/css": ["css"], "text/csv": ["csv"], "text/html": ["html", "htm", "shtml"], "text/jade": ["jade"], "text/jsx": ["jsx"], "text/less": ["less"], "text/markdown": ["markdown", "md"], "text/mathml": ["mml"], "text/mdx": ["mdx"], "text/n3": ["n3"], "text/plain": ["txt", "text", "conf", "def", "list", "log", "in", "ini"], "text/richtext": ["rtx"], "text/rtf": ["*rtf"], "text/sgml": ["sgml", "sgm"], "text/shex": ["shex"], "text/slim": ["slim", "slm"], "text/spdx": ["spdx"], "text/stylus": ["stylus", "styl"], "text/tab-separated-values": ["tsv"], "text/troff": ["t", "tr", "roff", "man", "me", "ms"], "text/turtle": ["ttl"], "text/uri-list": ["uri", "uris", "urls"], "text/vcard": ["vcard"], "text/vtt": ["vtt"], "text/xml": ["*xml"], "text/yaml": ["yaml", "yml"], "video/3gpp": ["3gp", "3gpp"], "video/3gpp2": ["3g2"], "video/h261": ["h261"], "video/h263": ["h263"], "video/h264": ["h264"], "video/iso.segment": ["m4s"], "video/jpeg": ["jpgv"], "video/jpm": ["*jpm", "jpgm"], "video/mj2": ["mj2", "mjp2"], "video/mp2t": ["ts"], "video/mp4": ["mp4", "mp4v", "mpg4"], "video/mpeg": ["mpeg", "mpg", "mpe", "m1v", "m2v"], "video/ogg": ["ogv"], "video/quicktime": ["qt", "mov"], "video/webm": ["webm"] };
85
- }
86
- });
87
-
88
- // ../../node_modules/.pnpm/mime@3.0.0/node_modules/mime/types/other.js
89
- var require_other = __commonJS({
90
- "../../node_modules/.pnpm/mime@3.0.0/node_modules/mime/types/other.js"(exports, module) {
91
- module.exports = { "application/prs.cww": ["cww"], "application/vnd.1000minds.decision-model+xml": ["1km"], "application/vnd.3gpp.pic-bw-large": ["plb"], "application/vnd.3gpp.pic-bw-small": ["psb"], "application/vnd.3gpp.pic-bw-var": ["pvb"], "application/vnd.3gpp2.tcap": ["tcap"], "application/vnd.3m.post-it-notes": ["pwn"], "application/vnd.accpac.simply.aso": ["aso"], "application/vnd.accpac.simply.imp": ["imp"], "application/vnd.acucobol": ["acu"], "application/vnd.acucorp": ["atc", "acutc"], "application/vnd.adobe.air-application-installer-package+zip": ["air"], "application/vnd.adobe.formscentral.fcdt": ["fcdt"], "application/vnd.adobe.fxp": ["fxp", "fxpl"], "application/vnd.adobe.xdp+xml": ["xdp"], "application/vnd.adobe.xfdf": ["xfdf"], "application/vnd.ahead.space": ["ahead"], "application/vnd.airzip.filesecure.azf": ["azf"], "application/vnd.airzip.filesecure.azs": ["azs"], "application/vnd.amazon.ebook": ["azw"], "application/vnd.americandynamics.acc": ["acc"], "application/vnd.amiga.ami": ["ami"], "application/vnd.android.package-archive": ["apk"], "application/vnd.anser-web-certificate-issue-initiation": ["cii"], "application/vnd.anser-web-funds-transfer-initiation": ["fti"], "application/vnd.antix.game-component": ["atx"], "application/vnd.apple.installer+xml": ["mpkg"], "application/vnd.apple.keynote": ["key"], "application/vnd.apple.mpegurl": ["m3u8"], "application/vnd.apple.numbers": ["numbers"], "application/vnd.apple.pages": ["pages"], "application/vnd.apple.pkpass": ["pkpass"], "application/vnd.aristanetworks.swi": ["swi"], "application/vnd.astraea-software.iota": ["iota"], "application/vnd.audiograph": ["aep"], "application/vnd.balsamiq.bmml+xml": ["bmml"], "application/vnd.blueice.multipass": ["mpm"], "application/vnd.bmi": ["bmi"], "application/vnd.businessobjects": ["rep"], "application/vnd.chemdraw+xml": ["cdxml"], "application/vnd.chipnuts.karaoke-mmd": ["mmd"], "application/vnd.cinderella": ["cdy"], "application/vnd.citationstyles.style+xml": ["csl"], "application/vnd.claymore": ["cla"], "application/vnd.cloanto.rp9": ["rp9"], "application/vnd.clonk.c4group": ["c4g", "c4d", "c4f", "c4p", "c4u"], "application/vnd.cluetrust.cartomobile-config": ["c11amc"], "application/vnd.cluetrust.cartomobile-config-pkg": ["c11amz"], "application/vnd.commonspace": ["csp"], "application/vnd.contact.cmsg": ["cdbcmsg"], "application/vnd.cosmocaller": ["cmc"], "application/vnd.crick.clicker": ["clkx"], "application/vnd.crick.clicker.keyboard": ["clkk"], "application/vnd.crick.clicker.palette": ["clkp"], "application/vnd.crick.clicker.template": ["clkt"], "application/vnd.crick.clicker.wordbank": ["clkw"], "application/vnd.criticaltools.wbs+xml": ["wbs"], "application/vnd.ctc-posml": ["pml"], "application/vnd.cups-ppd": ["ppd"], "application/vnd.curl.car": ["car"], "application/vnd.curl.pcurl": ["pcurl"], "application/vnd.dart": ["dart"], "application/vnd.data-vision.rdz": ["rdz"], "application/vnd.dbf": ["dbf"], "application/vnd.dece.data": ["uvf", "uvvf", "uvd", "uvvd"], "application/vnd.dece.ttml+xml": ["uvt", "uvvt"], "application/vnd.dece.unspecified": ["uvx", "uvvx"], "application/vnd.dece.zip": ["uvz", "uvvz"], "application/vnd.denovo.fcselayout-link": ["fe_launch"], "application/vnd.dna": ["dna"], "application/vnd.dolby.mlp": ["mlp"], "application/vnd.dpgraph": ["dpg"], "application/vnd.dreamfactory": ["dfac"], "application/vnd.ds-keypoint": ["kpxx"], "application/vnd.dvb.ait": ["ait"], "application/vnd.dvb.service": ["svc"], "application/vnd.dynageo": ["geo"], "application/vnd.ecowin.chart": ["mag"], "application/vnd.enliven": ["nml"], "application/vnd.epson.esf": ["esf"], "application/vnd.epson.msf": ["msf"], "application/vnd.epson.quickanime": ["qam"], "application/vnd.epson.salt": ["slt"], "application/vnd.epson.ssf": ["ssf"], "application/vnd.eszigno3+xml": ["es3", "et3"], "application/vnd.ezpix-album": ["ez2"], "application/vnd.ezpix-package": ["ez3"], "application/vnd.fdf": ["fdf"], "application/vnd.fdsn.mseed": ["mseed"], "application/vnd.fdsn.seed": ["seed", "dataless"], "application/vnd.flographit": ["gph"], "application/vnd.fluxtime.clip": ["ftc"], "application/vnd.framemaker": ["fm", "frame", "maker", "book"], "application/vnd.frogans.fnc": ["fnc"], "application/vnd.frogans.ltf": ["ltf"], "application/vnd.fsc.weblaunch": ["fsc"], "application/vnd.fujitsu.oasys": ["oas"], "application/vnd.fujitsu.oasys2": ["oa2"], "application/vnd.fujitsu.oasys3": ["oa3"], "application/vnd.fujitsu.oasysgp": ["fg5"], "application/vnd.fujitsu.oasysprs": ["bh2"], "application/vnd.fujixerox.ddd": ["ddd"], "application/vnd.fujixerox.docuworks": ["xdw"], "application/vnd.fujixerox.docuworks.binder": ["xbd"], "application/vnd.fuzzysheet": ["fzs"], "application/vnd.genomatix.tuxedo": ["txd"], "application/vnd.geogebra.file": ["ggb"], "application/vnd.geogebra.tool": ["ggt"], "application/vnd.geometry-explorer": ["gex", "gre"], "application/vnd.geonext": ["gxt"], "application/vnd.geoplan": ["g2w"], "application/vnd.geospace": ["g3w"], "application/vnd.gmx": ["gmx"], "application/vnd.google-apps.document": ["gdoc"], "application/vnd.google-apps.presentation": ["gslides"], "application/vnd.google-apps.spreadsheet": ["gsheet"], "application/vnd.google-earth.kml+xml": ["kml"], "application/vnd.google-earth.kmz": ["kmz"], "application/vnd.grafeq": ["gqf", "gqs"], "application/vnd.groove-account": ["gac"], "application/vnd.groove-help": ["ghf"], "application/vnd.groove-identity-message": ["gim"], "application/vnd.groove-injector": ["grv"], "application/vnd.groove-tool-message": ["gtm"], "application/vnd.groove-tool-template": ["tpl"], "application/vnd.groove-vcard": ["vcg"], "application/vnd.hal+xml": ["hal"], "application/vnd.handheld-entertainment+xml": ["zmm"], "application/vnd.hbci": ["hbci"], "application/vnd.hhe.lesson-player": ["les"], "application/vnd.hp-hpgl": ["hpgl"], "application/vnd.hp-hpid": ["hpid"], "application/vnd.hp-hps": ["hps"], "application/vnd.hp-jlyt": ["jlt"], "application/vnd.hp-pcl": ["pcl"], "application/vnd.hp-pclxl": ["pclxl"], "application/vnd.hydrostatix.sof-data": ["sfd-hdstx"], "application/vnd.ibm.minipay": ["mpy"], "application/vnd.ibm.modcap": ["afp", "listafp", "list3820"], "application/vnd.ibm.rights-management": ["irm"], "application/vnd.ibm.secure-container": ["sc"], "application/vnd.iccprofile": ["icc", "icm"], "application/vnd.igloader": ["igl"], "application/vnd.immervision-ivp": ["ivp"], "application/vnd.immervision-ivu": ["ivu"], "application/vnd.insors.igm": ["igm"], "application/vnd.intercon.formnet": ["xpw", "xpx"], "application/vnd.intergeo": ["i2g"], "application/vnd.intu.qbo": ["qbo"], "application/vnd.intu.qfx": ["qfx"], "application/vnd.ipunplugged.rcprofile": ["rcprofile"], "application/vnd.irepository.package+xml": ["irp"], "application/vnd.is-xpr": ["xpr"], "application/vnd.isac.fcs": ["fcs"], "application/vnd.jam": ["jam"], "application/vnd.jcp.javame.midlet-rms": ["rms"], "application/vnd.jisp": ["jisp"], "application/vnd.joost.joda-archive": ["joda"], "application/vnd.kahootz": ["ktz", "ktr"], "application/vnd.kde.karbon": ["karbon"], "application/vnd.kde.kchart": ["chrt"], "application/vnd.kde.kformula": ["kfo"], "application/vnd.kde.kivio": ["flw"], "application/vnd.kde.kontour": ["kon"], "application/vnd.kde.kpresenter": ["kpr", "kpt"], "application/vnd.kde.kspread": ["ksp"], "application/vnd.kde.kword": ["kwd", "kwt"], "application/vnd.kenameaapp": ["htke"], "application/vnd.kidspiration": ["kia"], "application/vnd.kinar": ["kne", "knp"], "application/vnd.koan": ["skp", "skd", "skt", "skm"], "application/vnd.kodak-descriptor": ["sse"], "application/vnd.las.las+xml": ["lasxml"], "application/vnd.llamagraphics.life-balance.desktop": ["lbd"], "application/vnd.llamagraphics.life-balance.exchange+xml": ["lbe"], "application/vnd.lotus-1-2-3": ["123"], "application/vnd.lotus-approach": ["apr"], "application/vnd.lotus-freelance": ["pre"], "application/vnd.lotus-notes": ["nsf"], "application/vnd.lotus-organizer": ["org"], "application/vnd.lotus-screencam": ["scm"], "application/vnd.lotus-wordpro": ["lwp"], "application/vnd.macports.portpkg": ["portpkg"], "application/vnd.mapbox-vector-tile": ["mvt"], "application/vnd.mcd": ["mcd"], "application/vnd.medcalcdata": ["mc1"], "application/vnd.mediastation.cdkey": ["cdkey"], "application/vnd.mfer": ["mwf"], "application/vnd.mfmp": ["mfm"], "application/vnd.micrografx.flo": ["flo"], "application/vnd.micrografx.igx": ["igx"], "application/vnd.mif": ["mif"], "application/vnd.mobius.daf": ["daf"], "application/vnd.mobius.dis": ["dis"], "application/vnd.mobius.mbk": ["mbk"], "application/vnd.mobius.mqy": ["mqy"], "application/vnd.mobius.msl": ["msl"], "application/vnd.mobius.plc": ["plc"], "application/vnd.mobius.txf": ["txf"], "application/vnd.mophun.application": ["mpn"], "application/vnd.mophun.certificate": ["mpc"], "application/vnd.mozilla.xul+xml": ["xul"], "application/vnd.ms-artgalry": ["cil"], "application/vnd.ms-cab-compressed": ["cab"], "application/vnd.ms-excel": ["xls", "xlm", "xla", "xlc", "xlt", "xlw"], "application/vnd.ms-excel.addin.macroenabled.12": ["xlam"], "application/vnd.ms-excel.sheet.binary.macroenabled.12": ["xlsb"], "application/vnd.ms-excel.sheet.macroenabled.12": ["xlsm"], "application/vnd.ms-excel.template.macroenabled.12": ["xltm"], "application/vnd.ms-fontobject": ["eot"], "application/vnd.ms-htmlhelp": ["chm"], "application/vnd.ms-ims": ["ims"], "application/vnd.ms-lrm": ["lrm"], "application/vnd.ms-officetheme": ["thmx"], "application/vnd.ms-outlook": ["msg"], "application/vnd.ms-pki.seccat": ["cat"], "application/vnd.ms-pki.stl": ["*stl"], "application/vnd.ms-powerpoint": ["ppt", "pps", "pot"], "application/vnd.ms-powerpoint.addin.macroenabled.12": ["ppam"], "application/vnd.ms-powerpoint.presentation.macroenabled.12": ["pptm"], "application/vnd.ms-powerpoint.slide.macroenabled.12": ["sldm"], "application/vnd.ms-powerpoint.slideshow.macroenabled.12": ["ppsm"], "application/vnd.ms-powerpoint.template.macroenabled.12": ["potm"], "application/vnd.ms-project": ["mpp", "mpt"], "application/vnd.ms-word.document.macroenabled.12": ["docm"], "application/vnd.ms-word.template.macroenabled.12": ["dotm"], "application/vnd.ms-works": ["wps", "wks", "wcm", "wdb"], "application/vnd.ms-wpl": ["wpl"], "application/vnd.ms-xpsdocument": ["xps"], "application/vnd.mseq": ["mseq"], "application/vnd.musician": ["mus"], "application/vnd.muvee.style": ["msty"], "application/vnd.mynfc": ["taglet"], "application/vnd.neurolanguage.nlu": ["nlu"], "application/vnd.nitf": ["ntf", "nitf"], "application/vnd.noblenet-directory": ["nnd"], "application/vnd.noblenet-sealer": ["nns"], "application/vnd.noblenet-web": ["nnw"], "application/vnd.nokia.n-gage.ac+xml": ["*ac"], "application/vnd.nokia.n-gage.data": ["ngdat"], "application/vnd.nokia.n-gage.symbian.install": ["n-gage"], "application/vnd.nokia.radio-preset": ["rpst"], "application/vnd.nokia.radio-presets": ["rpss"], "application/vnd.novadigm.edm": ["edm"], "application/vnd.novadigm.edx": ["edx"], "application/vnd.novadigm.ext": ["ext"], "application/vnd.oasis.opendocument.chart": ["odc"], "application/vnd.oasis.opendocument.chart-template": ["otc"], "application/vnd.oasis.opendocument.database": ["odb"], "application/vnd.oasis.opendocument.formula": ["odf"], "application/vnd.oasis.opendocument.formula-template": ["odft"], "application/vnd.oasis.opendocument.graphics": ["odg"], "application/vnd.oasis.opendocument.graphics-template": ["otg"], "application/vnd.oasis.opendocument.image": ["odi"], "application/vnd.oasis.opendocument.image-template": ["oti"], "application/vnd.oasis.opendocument.presentation": ["odp"], "application/vnd.oasis.opendocument.presentation-template": ["otp"], "application/vnd.oasis.opendocument.spreadsheet": ["ods"], "application/vnd.oasis.opendocument.spreadsheet-template": ["ots"], "application/vnd.oasis.opendocument.text": ["odt"], "application/vnd.oasis.opendocument.text-master": ["odm"], "application/vnd.oasis.opendocument.text-template": ["ott"], "application/vnd.oasis.opendocument.text-web": ["oth"], "application/vnd.olpc-sugar": ["xo"], "application/vnd.oma.dd2+xml": ["dd2"], "application/vnd.openblox.game+xml": ["obgx"], "application/vnd.openofficeorg.extension": ["oxt"], "application/vnd.openstreetmap.data+xml": ["osm"], "application/vnd.openxmlformats-officedocument.presentationml.presentation": ["pptx"], "application/vnd.openxmlformats-officedocument.presentationml.slide": ["sldx"], "application/vnd.openxmlformats-officedocument.presentationml.slideshow": ["ppsx"], "application/vnd.openxmlformats-officedocument.presentationml.template": ["potx"], "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": ["xlsx"], "application/vnd.openxmlformats-officedocument.spreadsheetml.template": ["xltx"], "application/vnd.openxmlformats-officedocument.wordprocessingml.document": ["docx"], "application/vnd.openxmlformats-officedocument.wordprocessingml.template": ["dotx"], "application/vnd.osgeo.mapguide.package": ["mgp"], "application/vnd.osgi.dp": ["dp"], "application/vnd.osgi.subsystem": ["esa"], "application/vnd.palm": ["pdb", "pqa", "oprc"], "application/vnd.pawaafile": ["paw"], "application/vnd.pg.format": ["str"], "application/vnd.pg.osasli": ["ei6"], "application/vnd.picsel": ["efif"], "application/vnd.pmi.widget": ["wg"], "application/vnd.pocketlearn": ["plf"], "application/vnd.powerbuilder6": ["pbd"], "application/vnd.previewsystems.box": ["box"], "application/vnd.proteus.magazine": ["mgz"], "application/vnd.publishare-delta-tree": ["qps"], "application/vnd.pvi.ptid1": ["ptid"], "application/vnd.quark.quarkxpress": ["qxd", "qxt", "qwd", "qwt", "qxl", "qxb"], "application/vnd.rar": ["rar"], "application/vnd.realvnc.bed": ["bed"], "application/vnd.recordare.musicxml": ["mxl"], "application/vnd.recordare.musicxml+xml": ["musicxml"], "application/vnd.rig.cryptonote": ["cryptonote"], "application/vnd.rim.cod": ["cod"], "application/vnd.rn-realmedia": ["rm"], "application/vnd.rn-realmedia-vbr": ["rmvb"], "application/vnd.route66.link66+xml": ["link66"], "application/vnd.sailingtracker.track": ["st"], "application/vnd.seemail": ["see"], "application/vnd.sema": ["sema"], "application/vnd.semd": ["semd"], "application/vnd.semf": ["semf"], "application/vnd.shana.informed.formdata": ["ifm"], "application/vnd.shana.informed.formtemplate": ["itp"], "application/vnd.shana.informed.interchange": ["iif"], "application/vnd.shana.informed.package": ["ipk"], "application/vnd.simtech-mindmapper": ["twd", "twds"], "application/vnd.smaf": ["mmf"], "application/vnd.smart.teacher": ["teacher"], "application/vnd.software602.filler.form+xml": ["fo"], "application/vnd.solent.sdkm+xml": ["sdkm", "sdkd"], "application/vnd.spotfire.dxp": ["dxp"], "application/vnd.spotfire.sfs": ["sfs"], "application/vnd.stardivision.calc": ["sdc"], "application/vnd.stardivision.draw": ["sda"], "application/vnd.stardivision.impress": ["sdd"], "application/vnd.stardivision.math": ["smf"], "application/vnd.stardivision.writer": ["sdw", "vor"], "application/vnd.stardivision.writer-global": ["sgl"], "application/vnd.stepmania.package": ["smzip"], "application/vnd.stepmania.stepchart": ["sm"], "application/vnd.sun.wadl+xml": ["wadl"], "application/vnd.sun.xml.calc": ["sxc"], "application/vnd.sun.xml.calc.template": ["stc"], "application/vnd.sun.xml.draw": ["sxd"], "application/vnd.sun.xml.draw.template": ["std"], "application/vnd.sun.xml.impress": ["sxi"], "application/vnd.sun.xml.impress.template": ["sti"], "application/vnd.sun.xml.math": ["sxm"], "application/vnd.sun.xml.writer": ["sxw"], "application/vnd.sun.xml.writer.global": ["sxg"], "application/vnd.sun.xml.writer.template": ["stw"], "application/vnd.sus-calendar": ["sus", "susp"], "application/vnd.svd": ["svd"], "application/vnd.symbian.install": ["sis", "sisx"], "application/vnd.syncml+xml": ["xsm"], "application/vnd.syncml.dm+wbxml": ["bdm"], "application/vnd.syncml.dm+xml": ["xdm"], "application/vnd.syncml.dmddf+xml": ["ddf"], "application/vnd.tao.intent-module-archive": ["tao"], "application/vnd.tcpdump.pcap": ["pcap", "cap", "dmp"], "application/vnd.tmobile-livetv": ["tmo"], "application/vnd.trid.tpt": ["tpt"], "application/vnd.triscape.mxs": ["mxs"], "application/vnd.trueapp": ["tra"], "application/vnd.ufdl": ["ufd", "ufdl"], "application/vnd.uiq.theme": ["utz"], "application/vnd.umajin": ["umj"], "application/vnd.unity": ["unityweb"], "application/vnd.uoml+xml": ["uoml"], "application/vnd.vcx": ["vcx"], "application/vnd.visio": ["vsd", "vst", "vss", "vsw"], "application/vnd.visionary": ["vis"], "application/vnd.vsf": ["vsf"], "application/vnd.wap.wbxml": ["wbxml"], "application/vnd.wap.wmlc": ["wmlc"], "application/vnd.wap.wmlscriptc": ["wmlsc"], "application/vnd.webturbo": ["wtb"], "application/vnd.wolfram.player": ["nbp"], "application/vnd.wordperfect": ["wpd"], "application/vnd.wqd": ["wqd"], "application/vnd.wt.stf": ["stf"], "application/vnd.xara": ["xar"], "application/vnd.xfdl": ["xfdl"], "application/vnd.yamaha.hv-dic": ["hvd"], "application/vnd.yamaha.hv-script": ["hvs"], "application/vnd.yamaha.hv-voice": ["hvp"], "application/vnd.yamaha.openscoreformat": ["osf"], "application/vnd.yamaha.openscoreformat.osfpvg+xml": ["osfpvg"], "application/vnd.yamaha.smaf-audio": ["saf"], "application/vnd.yamaha.smaf-phrase": ["spf"], "application/vnd.yellowriver-custom-menu": ["cmp"], "application/vnd.zul": ["zir", "zirz"], "application/vnd.zzazz.deck+xml": ["zaz"], "application/x-7z-compressed": ["7z"], "application/x-abiword": ["abw"], "application/x-ace-compressed": ["ace"], "application/x-apple-diskimage": ["*dmg"], "application/x-arj": ["arj"], "application/x-authorware-bin": ["aab", "x32", "u32", "vox"], "application/x-authorware-map": ["aam"], "application/x-authorware-seg": ["aas"], "application/x-bcpio": ["bcpio"], "application/x-bdoc": ["*bdoc"], "application/x-bittorrent": ["torrent"], "application/x-blorb": ["blb", "blorb"], "application/x-bzip": ["bz"], "application/x-bzip2": ["bz2", "boz"], "application/x-cbr": ["cbr", "cba", "cbt", "cbz", "cb7"], "application/x-cdlink": ["vcd"], "application/x-cfs-compressed": ["cfs"], "application/x-chat": ["chat"], "application/x-chess-pgn": ["pgn"], "application/x-chrome-extension": ["crx"], "application/x-cocoa": ["cco"], "application/x-conference": ["nsc"], "application/x-cpio": ["cpio"], "application/x-csh": ["csh"], "application/x-debian-package": ["*deb", "udeb"], "application/x-dgc-compressed": ["dgc"], "application/x-director": ["dir", "dcr", "dxr", "cst", "cct", "cxt", "w3d", "fgd", "swa"], "application/x-doom": ["wad"], "application/x-dtbncx+xml": ["ncx"], "application/x-dtbook+xml": ["dtb"], "application/x-dtbresource+xml": ["res"], "application/x-dvi": ["dvi"], "application/x-envoy": ["evy"], "application/x-eva": ["eva"], "application/x-font-bdf": ["bdf"], "application/x-font-ghostscript": ["gsf"], "application/x-font-linux-psf": ["psf"], "application/x-font-pcf": ["pcf"], "application/x-font-snf": ["snf"], "application/x-font-type1": ["pfa", "pfb", "pfm", "afm"], "application/x-freearc": ["arc"], "application/x-futuresplash": ["spl"], "application/x-gca-compressed": ["gca"], "application/x-glulx": ["ulx"], "application/x-gnumeric": ["gnumeric"], "application/x-gramps-xml": ["gramps"], "application/x-gtar": ["gtar"], "application/x-hdf": ["hdf"], "application/x-httpd-php": ["php"], "application/x-install-instructions": ["install"], "application/x-iso9660-image": ["*iso"], "application/x-iwork-keynote-sffkey": ["*key"], "application/x-iwork-numbers-sffnumbers": ["*numbers"], "application/x-iwork-pages-sffpages": ["*pages"], "application/x-java-archive-diff": ["jardiff"], "application/x-java-jnlp-file": ["jnlp"], "application/x-keepass2": ["kdbx"], "application/x-latex": ["latex"], "application/x-lua-bytecode": ["luac"], "application/x-lzh-compressed": ["lzh", "lha"], "application/x-makeself": ["run"], "application/x-mie": ["mie"], "application/x-mobipocket-ebook": ["prc", "mobi"], "application/x-ms-application": ["application"], "application/x-ms-shortcut": ["lnk"], "application/x-ms-wmd": ["wmd"], "application/x-ms-wmz": ["wmz"], "application/x-ms-xbap": ["xbap"], "application/x-msaccess": ["mdb"], "application/x-msbinder": ["obd"], "application/x-mscardfile": ["crd"], "application/x-msclip": ["clp"], "application/x-msdos-program": ["*exe"], "application/x-msdownload": ["*exe", "*dll", "com", "bat", "*msi"], "application/x-msmediaview": ["mvb", "m13", "m14"], "application/x-msmetafile": ["*wmf", "*wmz", "*emf", "emz"], "application/x-msmoney": ["mny"], "application/x-mspublisher": ["pub"], "application/x-msschedule": ["scd"], "application/x-msterminal": ["trm"], "application/x-mswrite": ["wri"], "application/x-netcdf": ["nc", "cdf"], "application/x-ns-proxy-autoconfig": ["pac"], "application/x-nzb": ["nzb"], "application/x-perl": ["pl", "pm"], "application/x-pilot": ["*prc", "*pdb"], "application/x-pkcs12": ["p12", "pfx"], "application/x-pkcs7-certificates": ["p7b", "spc"], "application/x-pkcs7-certreqresp": ["p7r"], "application/x-rar-compressed": ["*rar"], "application/x-redhat-package-manager": ["rpm"], "application/x-research-info-systems": ["ris"], "application/x-sea": ["sea"], "application/x-sh": ["sh"], "application/x-shar": ["shar"], "application/x-shockwave-flash": ["swf"], "application/x-silverlight-app": ["xap"], "application/x-sql": ["sql"], "application/x-stuffit": ["sit"], "application/x-stuffitx": ["sitx"], "application/x-subrip": ["srt"], "application/x-sv4cpio": ["sv4cpio"], "application/x-sv4crc": ["sv4crc"], "application/x-t3vm-image": ["t3"], "application/x-tads": ["gam"], "application/x-tar": ["tar"], "application/x-tcl": ["tcl", "tk"], "application/x-tex": ["tex"], "application/x-tex-tfm": ["tfm"], "application/x-texinfo": ["texinfo", "texi"], "application/x-tgif": ["*obj"], "application/x-ustar": ["ustar"], "application/x-virtualbox-hdd": ["hdd"], "application/x-virtualbox-ova": ["ova"], "application/x-virtualbox-ovf": ["ovf"], "application/x-virtualbox-vbox": ["vbox"], "application/x-virtualbox-vbox-extpack": ["vbox-extpack"], "application/x-virtualbox-vdi": ["vdi"], "application/x-virtualbox-vhd": ["vhd"], "application/x-virtualbox-vmdk": ["vmdk"], "application/x-wais-source": ["src"], "application/x-web-app-manifest+json": ["webapp"], "application/x-x509-ca-cert": ["der", "crt", "pem"], "application/x-xfig": ["fig"], "application/x-xliff+xml": ["*xlf"], "application/x-xpinstall": ["xpi"], "application/x-xz": ["xz"], "application/x-zmachine": ["z1", "z2", "z3", "z4", "z5", "z6", "z7", "z8"], "audio/vnd.dece.audio": ["uva", "uvva"], "audio/vnd.digital-winds": ["eol"], "audio/vnd.dra": ["dra"], "audio/vnd.dts": ["dts"], "audio/vnd.dts.hd": ["dtshd"], "audio/vnd.lucent.voice": ["lvp"], "audio/vnd.ms-playready.media.pya": ["pya"], "audio/vnd.nuera.ecelp4800": ["ecelp4800"], "audio/vnd.nuera.ecelp7470": ["ecelp7470"], "audio/vnd.nuera.ecelp9600": ["ecelp9600"], "audio/vnd.rip": ["rip"], "audio/x-aac": ["aac"], "audio/x-aiff": ["aif", "aiff", "aifc"], "audio/x-caf": ["caf"], "audio/x-flac": ["flac"], "audio/x-m4a": ["*m4a"], "audio/x-matroska": ["mka"], "audio/x-mpegurl": ["m3u"], "audio/x-ms-wax": ["wax"], "audio/x-ms-wma": ["wma"], "audio/x-pn-realaudio": ["ram", "ra"], "audio/x-pn-realaudio-plugin": ["rmp"], "audio/x-realaudio": ["*ra"], "audio/x-wav": ["*wav"], "chemical/x-cdx": ["cdx"], "chemical/x-cif": ["cif"], "chemical/x-cmdf": ["cmdf"], "chemical/x-cml": ["cml"], "chemical/x-csml": ["csml"], "chemical/x-xyz": ["xyz"], "image/prs.btif": ["btif"], "image/prs.pti": ["pti"], "image/vnd.adobe.photoshop": ["psd"], "image/vnd.airzip.accelerator.azv": ["azv"], "image/vnd.dece.graphic": ["uvi", "uvvi", "uvg", "uvvg"], "image/vnd.djvu": ["djvu", "djv"], "image/vnd.dvb.subtitle": ["*sub"], "image/vnd.dwg": ["dwg"], "image/vnd.dxf": ["dxf"], "image/vnd.fastbidsheet": ["fbs"], "image/vnd.fpx": ["fpx"], "image/vnd.fst": ["fst"], "image/vnd.fujixerox.edmics-mmr": ["mmr"], "image/vnd.fujixerox.edmics-rlc": ["rlc"], "image/vnd.microsoft.icon": ["ico"], "image/vnd.ms-dds": ["dds"], "image/vnd.ms-modi": ["mdi"], "image/vnd.ms-photo": ["wdp"], "image/vnd.net-fpx": ["npx"], "image/vnd.pco.b16": ["b16"], "image/vnd.tencent.tap": ["tap"], "image/vnd.valve.source.texture": ["vtf"], "image/vnd.wap.wbmp": ["wbmp"], "image/vnd.xiff": ["xif"], "image/vnd.zbrush.pcx": ["pcx"], "image/x-3ds": ["3ds"], "image/x-cmu-raster": ["ras"], "image/x-cmx": ["cmx"], "image/x-freehand": ["fh", "fhc", "fh4", "fh5", "fh7"], "image/x-icon": ["*ico"], "image/x-jng": ["jng"], "image/x-mrsid-image": ["sid"], "image/x-ms-bmp": ["*bmp"], "image/x-pcx": ["*pcx"], "image/x-pict": ["pic", "pct"], "image/x-portable-anymap": ["pnm"], "image/x-portable-bitmap": ["pbm"], "image/x-portable-graymap": ["pgm"], "image/x-portable-pixmap": ["ppm"], "image/x-rgb": ["rgb"], "image/x-tga": ["tga"], "image/x-xbitmap": ["xbm"], "image/x-xpixmap": ["xpm"], "image/x-xwindowdump": ["xwd"], "message/vnd.wfa.wsc": ["wsc"], "model/vnd.collada+xml": ["dae"], "model/vnd.dwf": ["dwf"], "model/vnd.gdl": ["gdl"], "model/vnd.gtw": ["gtw"], "model/vnd.mts": ["mts"], "model/vnd.opengex": ["ogex"], "model/vnd.parasolid.transmit.binary": ["x_b"], "model/vnd.parasolid.transmit.text": ["x_t"], "model/vnd.sap.vds": ["vds"], "model/vnd.usdz+zip": ["usdz"], "model/vnd.valve.source.compiled-map": ["bsp"], "model/vnd.vtu": ["vtu"], "text/prs.lines.tag": ["dsc"], "text/vnd.curl": ["curl"], "text/vnd.curl.dcurl": ["dcurl"], "text/vnd.curl.mcurl": ["mcurl"], "text/vnd.curl.scurl": ["scurl"], "text/vnd.dvb.subtitle": ["sub"], "text/vnd.fly": ["fly"], "text/vnd.fmi.flexstor": ["flx"], "text/vnd.graphviz": ["gv"], "text/vnd.in3d.3dml": ["3dml"], "text/vnd.in3d.spot": ["spot"], "text/vnd.sun.j2me.app-descriptor": ["jad"], "text/vnd.wap.wml": ["wml"], "text/vnd.wap.wmlscript": ["wmls"], "text/x-asm": ["s", "asm"], "text/x-c": ["c", "cc", "cxx", "cpp", "h", "hh", "dic"], "text/x-component": ["htc"], "text/x-fortran": ["f", "for", "f77", "f90"], "text/x-handlebars-template": ["hbs"], "text/x-java-source": ["java"], "text/x-lua": ["lua"], "text/x-markdown": ["mkd"], "text/x-nfo": ["nfo"], "text/x-opml": ["opml"], "text/x-org": ["*org"], "text/x-pascal": ["p", "pas"], "text/x-processing": ["pde"], "text/x-sass": ["sass"], "text/x-scss": ["scss"], "text/x-setext": ["etx"], "text/x-sfv": ["sfv"], "text/x-suse-ymp": ["ymp"], "text/x-uuencode": ["uu"], "text/x-vcalendar": ["vcs"], "text/x-vcard": ["vcf"], "video/vnd.dece.hd": ["uvh", "uvvh"], "video/vnd.dece.mobile": ["uvm", "uvvm"], "video/vnd.dece.pd": ["uvp", "uvvp"], "video/vnd.dece.sd": ["uvs", "uvvs"], "video/vnd.dece.video": ["uvv", "uvvv"], "video/vnd.dvb.file": ["dvb"], "video/vnd.fvt": ["fvt"], "video/vnd.mpegurl": ["mxu", "m4u"], "video/vnd.ms-playready.media.pyv": ["pyv"], "video/vnd.uvvu.mp4": ["uvu", "uvvu"], "video/vnd.vivo": ["viv"], "video/x-f4v": ["f4v"], "video/x-fli": ["fli"], "video/x-flv": ["flv"], "video/x-m4v": ["m4v"], "video/x-matroska": ["mkv", "mk3d", "mks"], "video/x-mng": ["mng"], "video/x-ms-asf": ["asf", "asx"], "video/x-ms-vob": ["vob"], "video/x-ms-wm": ["wm"], "video/x-ms-wmv": ["wmv"], "video/x-ms-wmx": ["wmx"], "video/x-ms-wvx": ["wvx"], "video/x-msvideo": ["avi"], "video/x-sgi-movie": ["movie"], "video/x-smv": ["smv"], "x-conference/x-cooltalk": ["ice"] };
92
- }
93
- });
94
-
95
- // ../../node_modules/.pnpm/mime@3.0.0/node_modules/mime/index.js
96
- var require_mime = __commonJS({
97
- "../../node_modules/.pnpm/mime@3.0.0/node_modules/mime/index.js"(exports, module) {
98
- "use strict";
99
- var Mime = require_Mime();
100
- module.exports = new Mime(require_standard(), require_other());
101
- }
102
- });
103
-
104
- // ../../node_modules/.pnpm/srcset@4.0.0/node_modules/srcset/index.js
105
- var require_srcset = __commonJS({
106
- "../../node_modules/.pnpm/srcset@4.0.0/node_modules/srcset/index.js"(exports) {
107
- "use strict";
108
- var imageCandidateRegex = /\s*([^,]\S*[^,](?:\s+[^,]+)?)\s*(?:,|$)/;
109
- var duplicateDescriptorCheck = (allDescriptors, value, postfix) => {
110
- allDescriptors[postfix] = allDescriptors[postfix] || {};
111
- if (allDescriptors[postfix][value]) {
112
- throw new Error(`No more than one image candidate is allowed for a given descriptor: ${value}${postfix}`);
113
- }
114
- allDescriptors[postfix][value] = true;
115
- };
116
- var fallbackDescriptorDuplicateCheck = (allDescriptors) => {
117
- if (allDescriptors.fallback) {
118
- throw new Error("Only one fallback image candidate is allowed");
119
- }
120
- if (allDescriptors.x["1"]) {
121
- throw new Error("A fallback image is equivalent to a 1x descriptor, providing both is invalid.");
122
- }
123
- allDescriptors.fallback = true;
124
- };
125
- var descriptorCountCheck = (allDescriptors, currentDescriptors) => {
126
- if (currentDescriptors.length === 0) {
127
- fallbackDescriptorDuplicateCheck(allDescriptors);
128
- } else if (currentDescriptors.length > 1) {
129
- throw new Error(`Image candidate may have no more than one descriptor, found ${currentDescriptors.length}: ${currentDescriptors.join(" ")}`);
130
- }
131
- };
132
- var validDescriptorCheck = (value, postfix, descriptor) => {
133
- if (Number.isNaN(value)) {
134
- throw new TypeError(`${descriptor || value} is not a valid number`);
135
- }
136
- switch (postfix) {
137
- case "w": {
138
- if (value <= 0) {
139
- throw new Error("Width descriptor must be greater than zero");
140
- } else if (!Number.isInteger(value)) {
141
- throw new TypeError("Width descriptor must be an integer");
142
- }
143
- break;
144
- }
145
- case "x": {
146
- if (value <= 0) {
147
- throw new Error("Pixel density descriptor must be greater than zero");
148
- }
149
- break;
150
- }
151
- case "h": {
152
- throw new Error("Height descriptor is no longer allowed");
153
- }
154
- default: {
155
- throw new Error(`Invalid srcset descriptor: ${descriptor}`);
156
- }
157
- }
158
- };
159
- exports.parse = (string, { strict = false } = {}) => {
160
- const allDescriptors = strict ? {} : void 0;
161
- return string.split(imageCandidateRegex).filter((part, index) => index % 2 === 1).map((part) => {
162
- const [url, ...descriptors] = part.trim().split(/\s+/);
163
- const result = { url };
164
- if (strict) {
165
- descriptorCountCheck(allDescriptors, descriptors);
166
- }
167
- for (const descriptor of descriptors) {
168
- const postfix = descriptor[descriptor.length - 1];
169
- const value = Number.parseFloat(descriptor.slice(0, -1));
170
- if (strict) {
171
- validDescriptorCheck(value, postfix, descriptor);
172
- duplicateDescriptorCheck(allDescriptors, value, postfix);
173
- }
174
- switch (postfix) {
175
- case "w": {
176
- result.width = value;
177
- break;
178
- }
179
- case "h": {
180
- result.height = value;
181
- break;
182
- }
183
- case "x": {
184
- result.density = value;
185
- break;
186
- }
187
- }
188
- }
189
- return result;
190
- });
191
- };
192
- var knownDescriptors = /* @__PURE__ */ new Set(["width", "height", "density"]);
193
- exports.stringify = (array, { strict = false } = {}) => {
194
- const allDescriptors = strict ? {} : null;
195
- return array.map((element) => {
196
- if (!element.url) {
197
- if (strict) {
198
- throw new Error("URL is required");
199
- }
200
- return "";
201
- }
202
- const descriptorKeys = Object.keys(element).filter((key) => knownDescriptors.has(key));
203
- if (strict) {
204
- descriptorCountCheck(allDescriptors, descriptorKeys);
205
- }
206
- const result = [element.url];
207
- for (const descriptorKey of descriptorKeys) {
208
- const value = element[descriptorKey];
209
- let postfix;
210
- switch (descriptorKey) {
211
- case "width": {
212
- postfix = "w";
213
- break;
214
- }
215
- case "height": {
216
- postfix = "h";
217
- break;
218
- }
219
- case "density": {
220
- postfix = "x";
221
- break;
222
- }
223
- }
224
- const descriptor = `${value}${postfix}`;
225
- if (strict) {
226
- validDescriptorCheck(value, postfix);
227
- duplicateDescriptorCheck(allDescriptors, value, postfix);
228
- }
229
- result.push(descriptor);
230
- }
231
- return result.join(" ");
232
- }).join(", ");
233
- };
234
- }
235
- });
236
-
237
- // src/node/plugin.ts
238
- import { existsSync as existsSync4, readdirSync, rmSync as rmSync2 } from "node:fs";
239
- import { resolve as resolve8 } from "node:path";
240
- import { version as vitestVersion } from "vitest/node";
241
- import colors2 from "tinyrainbow";
242
-
243
- // ../shared/src/utils/logger.ts
244
- var logger = process.env.LOG ? console : { log: (..._args) => {
245
- }, warn: (..._args) => {
246
- } };
247
-
248
- // ../shared/src/resource-archiver/index.ts
249
- var ResourceArchiver = class {
250
- archive = {};
251
- client;
252
- /**
253
- Specifies which domains (origins) we should archive resources for (by default we only archive same-origin resources).
254
- Useful in situations where the environment running the archived storybook (e.g. in CI) may be restricted to an intranet or other domain restrictions
255
- */
256
- assetDomains;
257
- /**
258
- * We assume the first URL loaded after @watch is called is the base URL of the
259
- * page and we only save resources that are loaded from the same protocol/host/port combination.
260
- * We also skip archiving this page because we only care about resources requested by this page.
261
- */
262
- firstUrl;
263
- /**
264
- * HTTP Basic Auth credentials to use when accessing protected resources.
265
- */
266
- httpCredentials;
267
- /**
268
- * Currently active requests
269
- */
270
- pendingRequests = /* @__PURE__ */ new Set();
271
- constructor(cdpClient, allowedDomains, httpCredentials, firstUrl) {
272
- this.client = cdpClient;
273
- this.httpCredentials = httpCredentials;
274
- this.firstUrl = firstUrl;
275
- this.assetDomains = (allowedDomains || []).map((domain) => {
276
- if (domain.startsWith("http")) {
277
- return domain;
278
- }
279
- return `https://${domain}`;
280
- });
281
- }
282
- async watch() {
283
- this.client.on("Fetch.requestPaused", this.requestPaused);
284
- this.client.on("Fetch.authRequired", this.authRequired);
285
- await this.client.send("Fetch.enable", { handleAuthRequests: true });
286
- }
287
- async unwatch() {
288
- this.client.off?.("Fetch.requestPaused", this.requestPaused);
289
- this.client.off?.("Fetch.authRequired", this.authRequired);
290
- await this.client.send("Fetch.disable");
291
- this.pendingRequests.clear();
292
- }
293
- getPendingRequestsCount() {
294
- return this.pendingRequests.size;
295
- }
296
- async clientSend(request, method, params) {
297
- try {
298
- return await this.client.send(method, params);
299
- } catch (error) {
300
- logger.log("Client error", request.url, error);
301
- this.archive[request.url] = { error };
302
- return null;
303
- }
304
- }
305
- authRequired = async ({ requestId, request }) => {
306
- await this.clientSend(request, "Fetch.continueWithAuth", {
307
- requestId,
308
- authChallengeResponse: {
309
- response: "ProvideCredentials",
310
- ...this.httpCredentials
311
- }
312
- });
313
- };
314
- requestPaused = async ({
315
- requestId,
316
- request,
317
- responseStatusCode,
318
- responseStatusText,
319
- responseErrorReason,
320
- responseHeaders
321
- }) => {
322
- this.pendingRequests.delete(requestId);
323
- if (!request.method.match(/get/i)) {
324
- await this.clientSend(request, "Fetch.continueRequest", { requestId });
325
- return;
326
- }
327
- if (responseStatusCode === 304) {
328
- await this.clientSend(request, "Fetch.continueRequest", { requestId });
329
- return;
330
- }
331
- const requestUrl = new URL(request.url);
332
- this.firstUrl ??= requestUrl;
333
- const isRequestFromAllowedDomain = requestUrl.origin === this.firstUrl.origin || this.assetDomains.includes(requestUrl.origin);
334
- logger.log(
335
- "requestPaused",
336
- requestUrl.toString(),
337
- responseStatusCode || responseErrorReason ? "response" : "request",
338
- this.firstUrl.toString(),
339
- isRequestFromAllowedDomain
340
- );
341
- if (responseErrorReason) {
342
- logger.log(`Got response error: ${responseErrorReason}`);
343
- await this.clientSend(request, "Fetch.continueRequest", { requestId });
344
- return;
345
- }
346
- if (responseStatusCode) {
347
- await this.handleSuccessfulResponse(
348
- {
349
- request,
350
- requestId,
351
- responseStatusCode,
352
- responseStatusText,
353
- responseHeaders
354
- },
355
- requestUrl,
356
- isRequestFromAllowedDomain
357
- );
358
- return;
359
- }
360
- this.pendingRequests.add(requestId);
361
- await this.clientSend(request, "Fetch.continueRequest", {
362
- requestId,
363
- interceptResponse: true
364
- });
365
- };
366
- async handleSuccessfulResponse(requestPausedPayload, requestUrl, isRequestFromAllowedDomain) {
367
- const { request, requestId, responseStatusCode, responseStatusText, responseHeaders } = requestPausedPayload;
368
- if ([301, 302, 303, 307, 308].includes(responseStatusCode)) {
369
- await this.clientSend(request, "Fetch.continueRequest", {
370
- requestId,
371
- interceptResponse: true
372
- });
373
- return;
374
- }
375
- const result = await this.clientSend(request, "Fetch.getResponseBody", {
376
- requestId
377
- });
378
- if (result === null) {
379
- return;
380
- }
381
- const { body, base64Encoded } = result;
382
- const contentTypeHeader = responseHeaders.find(
383
- ({ name }) => name.toLowerCase() === "content-type"
384
- );
385
- const isFirstRequest = requestUrl.toString() === this.firstUrl.toString();
386
- if (isRequestFromAllowedDomain && !isFirstRequest) {
387
- logger.log("Archiving request", {
388
- url: request.url,
389
- statusCode: responseStatusCode,
390
- statusText: responseStatusText,
391
- contentType: contentTypeHeader?.value
392
- });
393
- this.archive[request.url] = {
394
- statusCode: responseStatusCode,
395
- statusText: responseStatusText,
396
- body: Buffer.from(body, base64Encoded ? "base64" : "utf8"),
397
- contentType: contentTypeHeader?.value
398
- };
399
- } else {
400
- logger.log("Skipping archiving of request", {
401
- url: request.url,
402
- firstUrl: this.firstUrl.toString(),
403
- isFirstRequest,
404
- isRequestFromAllowedDomain
405
- });
406
- }
407
- await this.clientSend(request, "Fetch.continueRequest", { requestId });
408
- }
409
- };
410
-
411
- // ../shared/src/write-archive/index.ts
412
- import { join } from "node:path";
413
- import { existsSync as existsSync2 } from "node:fs";
414
-
415
- // ../shared/src/utils/filePaths.ts
416
- import { existsSync, mkdirSync } from "fs";
417
- import { writeFile } from "fs/promises";
418
- import { createHash } from "node:crypto";
419
- import path from "path";
420
- function ensureDir(directory) {
421
- if (!existsSync(directory)) {
422
- mkdirSync(directory, { recursive: true });
423
- }
424
- }
425
- async function outputFile(filePath, data) {
426
- ensureDir(path.dirname(filePath));
427
- return writeFile(filePath, data, { mode: 511 });
428
- }
429
- async function outputJSONFile(filePath, data) {
430
- return outputFile(filePath, JSON.stringify(data));
431
- }
432
- function hash(data) {
433
- return createHash("shake256", { outputLength: 2 }).update(data).digest("hex");
434
- }
435
- var MAX_FILE_NAME_BYTE_LENGTH = 255;
436
- function truncateFileName(filePath, maxByteLength = MAX_FILE_NAME_BYTE_LENGTH) {
437
- const encoder = new TextEncoder();
438
- const decoder = new TextDecoder();
439
- const filePathParts = filePath.split("/");
440
- const fileName = filePathParts.pop();
441
- const fileNameByteArray = encoder.encode(fileName);
442
- if (fileNameByteArray.byteLength <= maxByteLength) {
443
- return filePath;
444
- }
445
- const hashedFileName = hash(fileName);
446
- const [baseName, ...extensions] = fileName.split(".");
447
- const baseNameByteArray = encoder.encode(baseName);
448
- const ext = extensions.join(".");
449
- const extLength = ext.length === 0 ? 0 : encoder.encode(ext).byteLength + 1;
450
- const lengthHashAndExt = encoder.encode(hashedFileName).byteLength + extLength;
451
- const truncatedBaseNameByteArray = baseNameByteArray.slice(0, maxByteLength - lengthHashAndExt);
452
- const truncatedBaseName = decoder.decode(truncatedBaseNameByteArray);
453
- const truncatedFileName = [`${truncatedBaseName}${hashedFileName}`, ext].filter(Boolean).join(".");
454
- return [...filePathParts, truncatedFileName].join("/");
455
- }
456
- var removeLocalhostFromBaseUrl = (href) => {
457
- let baseUrl;
458
- try {
459
- baseUrl = new URL(href);
460
- if (baseUrl.hostname === "localhost") {
461
- return baseUrl.pathname + baseUrl.search + baseUrl.hash;
462
- }
463
- return href;
464
- } catch {
465
- return href;
466
- }
467
- };
468
-
469
- // ../shared/src/write-archive/archive-file.ts
470
- var import_mime = __toESM(require_mime());
471
- import path2 from "path";
472
- import { createHash as createHash2 } from "node:crypto";
473
- var RESERVED_PATHNAMES = [
474
- // This is a list of filenames that are reserved for Storybook as a dev target.
475
- // If we encounter these filenames, we will rename them to avoid collisions.
476
- // If we do not rename them, the build-archive-storybook will not be able to serve the correct archives
477
- // and the tests will fail.
478
- "/index.json",
479
- "/iframe.html",
480
- "/index.html",
481
- "/main.iframe.bundle.js",
482
- "/runtime~main.iframe.bundle.js",
483
- "/sb-preview/runtime.js"
484
- ];
485
- var ArchiveFile = class {
486
- // The URL to the asset being archived.
487
- url;
488
- response;
489
- shortenedFileNameLength;
490
- // The URL to page being tested.
491
- pageUrl;
492
- constructor(url, response, pageUrl) {
493
- this.url = new URL(url);
494
- this.response = response;
495
- this.shortenedFileNameLength = 250;
496
- this.pageUrl = new URL(pageUrl);
497
- }
498
- originalSrc() {
499
- return this.url.toString();
500
- }
501
- toFileSystemPath() {
502
- let sanitizedSrc = this.url.pathname;
503
- sanitizedSrc = this.preserveExternalDomain();
504
- sanitizedSrc = this.ensureNonDirectory(sanitizedSrc);
505
- sanitizedSrc = this.encodeQueryString(sanitizedSrc);
506
- sanitizedSrc = this.truncateFileName(sanitizedSrc);
507
- sanitizedSrc = this.removeSpecialChars(sanitizedSrc);
508
- sanitizedSrc = this.renameReservedPathnames(sanitizedSrc);
509
- sanitizedSrc = this.addExtension(sanitizedSrc);
510
- return sanitizedSrc;
511
- }
512
- ensureNonDirectory(pathname) {
513
- return pathname.endsWith("/") ? `${pathname}index.html` : pathname;
514
- }
515
- encodeQueryString(pathname) {
516
- const queryString = this.url.search;
517
- if (!queryString)
518
- return pathname;
519
- const safeQueryString = this.hash(queryString);
520
- const extension = path2.extname(pathname);
521
- if (extension) {
522
- return `${pathname.substring(0, pathname.length - extension.length)}-${safeQueryString}${extension}`;
523
- }
524
- return `${pathname}-${safeQueryString}`;
525
- }
526
- truncateFileName(pathname) {
527
- const pathPieces = pathname.split("/");
528
- const rebuiltPieces = [];
529
- pathPieces.forEach((piece) => {
530
- let shortName = piece;
531
- if (piece.length > this.shortenedFileNameLength) {
532
- shortName = piece.substring(0, this.shortenedFileNameLength);
533
- logger.log(`Chunk of filename '${piece}' is too long. Shortening to '${shortName}'`);
534
- }
535
- rebuiltPieces.push(shortName);
536
- });
537
- return rebuiltPieces.join("/");
538
- }
539
- removeSpecialChars(pathname) {
540
- return pathname.replace(/[%:@]/g, "");
541
- }
542
- addExtension(pathname) {
543
- if ("error" in this.response)
544
- return pathname;
545
- let nameWithExtension = pathname;
546
- if (!path2.extname(nameWithExtension)) {
547
- const fileExtension = import_mime.default.getExtension(this.response.contentType) || "tmp";
548
- nameWithExtension = `${pathname}.${fileExtension}`;
549
- }
550
- return nameWithExtension;
551
- }
552
- preserveExternalDomain() {
553
- if (this.url.origin === this.pageUrl.origin) {
554
- return this.url.pathname;
555
- }
556
- const encodedHost = encodeURIComponent(this.url.host);
557
- return `/${encodedHost}${this.url.pathname}`;
558
- }
559
- hash(name) {
560
- return createHash2("md5").update(name).digest("hex");
561
- }
562
- renameReservedPathnames(pathname) {
563
- if (this.url.origin === this.pageUrl.origin && RESERVED_PATHNAMES.includes(pathname)) {
564
- const hash3 = this.hash(this.url.toString());
565
- const basename = path2.basename(pathname, path2.extname(pathname));
566
- return `${path2.dirname(pathname)}/${basename}-${hash3}${path2.extname(pathname)}`;
567
- }
568
- return pathname;
569
- }
570
- };
571
-
572
- // ../../node_modules/.pnpm/@rrweb+types@2.1.0/node_modules/@rrweb/types/dist/types.js
573
- var NodeType = /* @__PURE__ */ ((NodeType2) => {
574
- NodeType2[NodeType2["Document"] = 0] = "Document";
575
- NodeType2[NodeType2["DocumentType"] = 1] = "DocumentType";
576
- NodeType2[NodeType2["Element"] = 2] = "Element";
577
- NodeType2[NodeType2["Text"] = 3] = "Text";
578
- NodeType2[NodeType2["CDATA"] = 4] = "CDATA";
579
- NodeType2[NodeType2["Comment"] = 5] = "Comment";
580
- return NodeType2;
581
- })(NodeType || {});
582
-
583
- // ../shared/src/write-archive/dom-snapshot.ts
584
- var import_srcset = __toESM(require_srcset());
585
-
586
- // ../shared/src/utils/nodes.ts
587
- function isIframeSerializedNode(node) {
588
- return node.type === NodeType.Element && node.tagName === "iframe" && "contentDocument" in node && !!node.contentDocument;
589
- }
590
-
591
- // ../shared/src/write-archive/dom-snapshot.ts
592
- var CSS_URL_REGEX = /url\((?!['"]?(?:data):)['"]?([^'")]*)['"]?\)/gi;
593
- var DOMSnapshot = class {
594
- snapshot;
595
- pseudoClassIds;
596
- constructor({
597
- snapshot,
598
- pseudoClassIds
599
- }) {
600
- if (Buffer.isBuffer(snapshot)) {
601
- const bufferAsString = snapshot.toString("utf-8");
602
- this.snapshot = JSON.parse(bufferAsString);
603
- } else {
604
- this.snapshot = JSON.parse(snapshot);
605
- }
606
- this.pseudoClassIds = pseudoClassIds;
607
- }
608
- async mapAssetPaths(sourceMap) {
609
- const savedSnapshot = {
610
- snapshot: await this.mapNode(this.snapshot, sourceMap),
611
- pseudoClassIds: this.pseudoClassIds
612
- };
613
- return JSON.stringify(savedSnapshot);
614
- }
615
- async mapNode(node, sourceMap) {
616
- node = this.mapNodeAttributes(node, sourceMap);
617
- node = this.mapTextElement(node, sourceMap);
618
- if ("childNodes" in node) {
619
- node.childNodes = await Promise.all(
620
- node.childNodes.map(async (childNode) => {
621
- return this.mapNode(childNode, sourceMap);
622
- })
623
- );
624
- }
625
- if (isIframeSerializedNode(node)) {
626
- node.contentDocument = await this.mapNode(node.contentDocument, sourceMap);
627
- }
628
- return node;
629
- }
630
- mapNodeAttributes(node, sourceMap) {
631
- if (node.type === NodeType.Element) {
632
- if (node.attributes.src) {
633
- const sourceVal = node.attributes.src;
634
- if (sourceMap.has(sourceVal)) {
635
- node.attributes.src = sourceMap.get(sourceVal);
636
- }
637
- }
638
- if (node.attributes.style) {
639
- const cssText = node.attributes.style;
640
- const mappedCssText = this.mapCssUrls(cssText, sourceMap);
641
- node.attributes.style = mappedCssText;
642
- }
643
- if (node.attributes._cssText) {
644
- const cssText = node.attributes._cssText;
645
- const mappedCssText = this.mapCssUrls(cssText, sourceMap);
646
- node.attributes._cssText = mappedCssText;
647
- }
648
- if (["link", "use"].includes(node.tagName) && node.attributes.href) {
649
- const hrefVal = node.attributes.href;
650
- const hrefValAndAnchor = hrefVal.split("#");
651
- const hrefValWithoutAnchor = hrefValAndAnchor[0];
652
- if (sourceMap.has(hrefValWithoutAnchor)) {
653
- hrefValAndAnchor[0] = sourceMap.get(hrefValWithoutAnchor);
654
- node.attributes.href = hrefValAndAnchor.join("#");
655
- }
656
- }
657
- if (node.tagName === "img" && node.attributes.srcset) {
658
- const srcsetValue = node.attributes.srcset;
659
- const currentSrc = this.mapSrcsetUrls(srcsetValue, sourceMap);
660
- if (currentSrc) {
661
- node.attributes.src = currentSrc;
662
- this.removeResponsiveImageAttributes(node.attributes);
663
- }
664
- }
665
- if (node.tagName === "picture") {
666
- this.mapPictureElement(node, sourceMap);
667
- }
668
- if (node.tagName === "base" && node.attributes.href) {
669
- node.attributes.href = removeLocalhostFromBaseUrl(node.attributes.href);
670
- }
671
- }
672
- return node;
673
- }
674
- mapPictureElement(node, sourceMap) {
675
- const allSourceUrls = node.childNodes.filter(this.isSourceElement).map((childNode) => {
676
- const sourceSetValues = import_srcset.default.parse(
677
- childNode.attributes?.srcset ?? ""
678
- );
679
- return sourceSetValues.map((srcSetValue) => srcSetValue.url);
680
- }).flat();
681
- const matchingUrl = allSourceUrls.find((sourceUrl) => {
682
- return sourceMap.has(sourceUrl);
683
- });
684
- if (matchingUrl) {
685
- node.childNodes = node.childNodes.filter((childNode) => !this.isSourceElement(childNode));
686
- const imageElement = node.childNodes.find(
687
- (childNode) => childNode.type === NodeType.Element && childNode.tagName === "img"
688
- );
689
- if (imageElement && imageElement.attributes) {
690
- imageElement.attributes.src = sourceMap.get(matchingUrl);
691
- this.removeResponsiveImageAttributes(imageElement.attributes);
692
- }
693
- }
694
- }
695
- isSourceElement(childNode) {
696
- return childNode.type === NodeType.Element && childNode.tagName === "source";
697
- }
698
- mapTextElement(node, sourceMap) {
699
- if (node.type === NodeType.Text && node.isStyle) {
700
- if (node.textContent) {
701
- const mappedCssText = this.mapCssUrls(node.textContent, sourceMap);
702
- node.textContent = mappedCssText;
703
- }
704
- }
705
- return node;
706
- }
707
- mapCssUrls(cssText, sourceMap) {
708
- return cssText.replace(CSS_URL_REGEX, (match, fullUrl) => {
709
- let cssUrl = match;
710
- if (sourceMap.has(fullUrl)) {
711
- cssUrl = match.replace(fullUrl, sourceMap.get(fullUrl));
712
- }
713
- return cssUrl;
714
- });
715
- }
716
- mapSrcsetUrls(srcsetValue, sourceMap) {
717
- const parsedSrcset = import_srcset.default.parse(srcsetValue);
718
- let currentSrc;
719
- parsedSrcset.forEach((set) => {
720
- if (sourceMap.has(set.url)) {
721
- currentSrc = sourceMap.get(set.url);
722
- }
723
- });
724
- return currentSrc;
725
- }
726
- removeResponsiveImageAttributes(attributes) {
727
- delete attributes.srcset;
728
- delete attributes.sizes;
729
- }
730
- };
731
-
732
- // ../shared/src/utils/viewport.ts
733
- function viewportToString(viewport) {
734
- return `w${viewport.width}h${viewport.height}`;
735
- }
736
-
737
- // ../shared/src/write-archive/storybook-sanitize.ts
738
- var sanitize = (string) => {
739
- return string.toLowerCase().replace(/[ ’–—―′¿'`~!@#$%^&*()_|+\-=?;:'",.<>\{\}\[\]\\\/]/gi, "-").replace(/[\r\n]/g, "-").replace(/-+/g, "-").replace(/^-+/, "").replace(/-+$/, "");
740
- };
741
- var collapseNewlines = (title) => title.replace(/[\r\n]+/g, " ").trim();
742
-
743
- // ../shared/src/write-archive/snapshot-files.ts
744
- var SNAPSHOT_FILE_EXT = "snapshot.json";
745
- function snapshotId(testTitle, snapshotName) {
746
- const fullSnapshotId = `${sanitize(testTitle)}-${sanitize(snapshotName)}`;
747
- const maxByteLength = MAX_FILE_NAME_BYTE_LENGTH - 25;
748
- return truncateFileName(fullSnapshotId, maxByteLength);
749
- }
750
- function snapshotFileName(snapshotId2, viewport) {
751
- const fileNameParts = [snapshotId2, viewportToString(viewport), SNAPSHOT_FILE_EXT];
752
- return fileNameParts.join(".");
753
- }
754
-
755
- // ../shared/src/write-archive/stories-files.ts
756
- import { storyNameFromExport, toId } from "storybook/internal/csf";
757
- var STORIES_FILE_EXT = "stories.json";
758
- var uniqueId = { value: 1 };
759
- function storiesFileName(testTitle, overwriteDuplicateNames = true) {
760
- let title = sanitize(testTitle);
761
- if (!overwriteDuplicateNames) {
762
- title += "-" + uniqueId.value++;
763
- }
764
- const fileName = [title, STORIES_FILE_EXT].join(".");
765
- const maxByteLength = MAX_FILE_NAME_BYTE_LENGTH - 25;
766
- return truncateFileName(fileName, maxByteLength);
767
- }
768
- function createStories(storyTitle, domSnapshots, chromaticStorybookParams) {
769
- const title = collapseNewlines(storyTitle);
770
- return {
771
- title,
772
- stories: Object.entries(domSnapshots).map(([snapshotName, snapshotOptions]) => {
773
- const name = collapseNewlines(snapshotName);
774
- const { parameters, viewport, colorScheme } = snapshotOptions;
775
- const { chromatic: chromaticParams, ...restParameters } = parameters || {};
776
- return {
777
- name,
778
- // Viewport addon (Storybook 10+): `parameters.viewport.options` registers sizes; `globals.viewport`
779
- // selects the active one. See https://storybook.js.org/docs/essentials/viewport#defining-the-viewport-for-a-story
780
- // `defaultViewport` is not read by SB 10's types but our archive preview uses it as a fetch fallback.
781
- globals: { viewport: viewportToString(viewport) },
782
- parameters: {
783
- // Work-around for cases where "あ" in story name would cause Storybook to fail to load the story due to an invalid story ID.
784
- // See https://github.com/chromaui/chromatic-e2e/issues/365
785
- __id: toId(title, storyNameFromExport(name)),
786
- server: { id: snapshotId(title, name) },
787
- chromatic: {
788
- ...chromaticStorybookParams,
789
- ...chromaticParams,
790
- colorScheme,
791
- modes: buildStoryModesConfig([viewport])
792
- },
793
- viewport: {
794
- options: buildStoryViewportsConfig([viewport]),
795
- defaultViewport: viewportToString(findDefaultViewport([viewport]))
796
- },
797
- ...restParameters
798
- }
799
- };
800
- })
801
- };
802
- }
803
- function buildStoryModesConfig(viewports) {
804
- return viewports.reduce((modes, viewport) => {
805
- const viewportName = viewportToString(viewport);
806
- modes[viewportName] = { viewport: viewportName };
807
- return modes;
808
- }, {});
809
- }
810
- function buildStoryViewportsConfig(viewports) {
811
- return viewports.reduce((viewportsConfig, viewport) => {
812
- const viewportName = viewportToString(viewport);
813
- viewportsConfig[viewportName] = {
814
- name: viewportName,
815
- type: viewportAddonType(viewport),
816
- styles: {
817
- width: `${viewport.width}px`,
818
- height: `${viewport.height}px`
819
- }
820
- };
821
- return viewportsConfig;
822
- }, {});
823
- }
824
- function viewportAddonType(viewport) {
825
- if (viewport.width < 600) {
826
- return "mobile";
827
- }
828
- if (viewport.width < 1024) {
829
- return "tablet";
830
- }
831
- return "desktop";
832
- }
833
- function findDefaultViewport(viewports) {
834
- const compareFn = (vp1, vp2) => {
835
- if (vp1.width < vp2.width) {
836
- return 1;
837
- }
838
- if (vp1.width > vp2.width) {
839
- return -1;
840
- }
841
- return 0;
842
- };
843
- return viewports.sort(compareFn)[0];
844
- }
845
-
846
- // ../shared/src/write-archive/index.ts
847
- async function writeTestResult(e2eTestInfo, domSnapshots, archive, chromaticStorybookParams, testRunner) {
848
- const { titlePath, outputDir, pageUrl } = e2eTestInfo;
849
- const titlePathWithoutFileExtensions = titlePath.map(
850
- (pathPart) => (
851
- // make sure we remove file extensions, even if the file name doesn't have .spec or .test or.cy
852
- // possible extensions:
853
- // playwright: https://playwright.dev/docs/test-configuration#filtering-tests
854
- // cypress: https://docs.cypress.io/guides/core-concepts/writing-and-organizing-tests#Spec-files
855
- pathPart.replace(/\.(ts|js|mjs|cjs|tsx|jsx|cjsx|coffee)$/, "").replace(/\.(spec|test|cy)$/, "")
856
- )
857
- );
858
- const title = titlePathWithoutFileExtensions.join("/").replace(/\/([ ’–—―′¿'`~!@#$%^&*()_|+\-=?;:'",.<>\{\}\[\]\\]+)\//gi, "$1/");
859
- const finalOutputDir = join(outputDir, "chromatic-archives");
860
- const archiveDir = join(finalOutputDir, "archive");
861
- await ensureDir(archiveDir);
862
- logger.log(`Writing test results for "${title}"`);
863
- const sourceMap = /* @__PURE__ */ new Map();
864
- await Promise.all(
865
- Object.entries(archive).map(async ([url, response]) => {
866
- if ("error" in response)
867
- return;
868
- const archiveFile = new ArchiveFile(url, response, pageUrl);
869
- const origSrcPath = archiveFile.originalSrc();
870
- const fileSystemPath = archiveFile.toFileSystemPath();
871
- const responsePath = join(archiveDir, fileSystemPath);
872
- if (origSrcPath !== fileSystemPath) {
873
- sourceMap.set(origSrcPath, fileSystemPath);
874
- }
875
- if (!existsSync2(responsePath)) {
876
- await outputFile(responsePath, response.body);
877
- }
878
- })
879
- );
880
- await Promise.all(
881
- Object.entries(domSnapshots).map(async ([name, domSnapshot]) => {
882
- const snapshot = new DOMSnapshot(domSnapshot);
883
- const mappedSnapshot = await snapshot.mapAssetPaths(sourceMap);
884
- const snapshotFile = snapshotFileName(snapshotId(title, name), domSnapshot.viewport);
885
- await outputFile(join(archiveDir, snapshotFile), mappedSnapshot);
886
- })
887
- );
888
- const storiesFile = join(finalOutputDir, storiesFileName(title, testRunner !== "vitest"));
889
- const storiesJson = createStories(title, domSnapshots, chromaticStorybookParams);
890
- await outputJSONFile(storiesFile, storiesJson);
891
- const errors = Object.entries(archive).filter(([, r]) => "error" in r);
892
- if (errors.length > 0) {
893
- logger.log(`Encountered ${errors.length} errors archiving resources, writing to 'errors.json'`);
894
- await outputJSONFile(join(archiveDir, `errors.json`), {
895
- errors: Object.fromEntries(errors)
896
- });
897
- }
898
- return { storiesFile };
899
- }
900
-
901
- // ../shared/src/constants.ts
902
- var DEFAULT_GLOBAL_RESOURCE_ARCHIVE_TIMEOUT_MS = 1e4;
903
-
904
- // src/node/commands.ts
905
- import assert from "node:assert";
906
- import { resolve as resolve7 } from "node:path";
907
- import { storyNameFromExport as storyNameFromExport2, toId as toId2 } from "storybook/internal/csf";
908
-
909
- // src/node/telemetry/constants.ts
910
- var EVENT_TYPE_PREFIX = "vitest_";
911
- var TELEMETRY_FETCH_TIMEOUT_MS = 5e3;
912
- var TELEMETRY_URL = "https://analytics.chromatic.com";
913
- var TELEMETRY_LOG_FILE = "telemetry.jsonl";
914
- var TELEMETRY_METADATA_FILE = "telemetry-metadata.json";
915
-
916
- // src/node/telemetry/env.ts
917
- import { readFileSync } from "node:fs";
918
- import { resolve } from "node:path";
919
- import util from "node:util";
920
- import { env } from "std-env";
921
- var dotEnv = void 0;
922
- function getEnv(name) {
923
- if (dotEnv === void 0) {
924
- if (typeof util.parseEnv !== "function") {
925
- dotEnv = {};
926
- } else {
927
- try {
928
- dotEnv = util.parseEnv(readFileSync(resolve(process.cwd(), ".env"), "utf8"));
929
- } catch {
930
- dotEnv = {};
931
- }
932
- }
933
- }
934
- return env[name] ?? dotEnv[name];
935
- }
936
- function resolveTelemetryOptions() {
937
- return {
938
- // Enabled by default, disabled by env variables
939
- enabled: isTruthyEnv(getEnv("CHROMATIC_DISABLE_TELEMETRY")) === false && isTruthyEnv(getEnv("DO_NOT_TRACK")) === false,
940
- // Disabled by default, enabled by env variable
941
- logToFile: isTruthyEnv(getEnv("CHROMATIC_TELEMETRY_LOG_TO_FILE"))
942
- };
943
- }
944
- function isTruthyEnv(value) {
945
- return value !== void 0 && value !== "" && value !== "0" && value !== "false";
946
- }
947
-
948
- // src/node/telemetry/track.ts
949
- import { randomUUID as randomUUID2 } from "node:crypto";
950
- import { appendFile, mkdir } from "node:fs/promises";
951
- import { resolve as resolve4 } from "node:path";
952
- import { isCI, nodeVersion } from "std-env";
953
-
954
- // package.json
955
- var version = "1.0.1";
956
-
957
- // src/node/telemetry/metadata.ts
958
- import { createHash as createHash3 } from "node:crypto";
959
- import { writeFile as writeFile2, readFile } from "node:fs/promises";
960
- import { createRequire } from "node:module";
961
- import { join as join2, resolve as resolve2 } from "node:path";
962
- import { x } from "tinyexec";
963
- import { env as env2 } from "std-env";
964
- var userAgentMatch = env2.npm_config_user_agent?.match(/^([^/\s]+)\/(\S+)/);
965
- var packageManager = {
966
- name: userAgentMatch?.[1] || "unknown",
967
- version: userAgentMatch?.[2] || "unknown"
968
- };
969
- async function createProjectId(root) {
970
- let remote = void 0;
971
- try {
972
- const result = await x("git", ["remote", "get-url", "origin"], { nodeOptions: { cwd: root } });
973
- remote = result.exitCode === 0 ? result.stdout.trim().toLowerCase() : void 0;
974
- } catch {
975
- }
976
- if (!remote) {
977
- return hash2(root);
978
- }
979
- const hasProtocol = remote.includes("://");
980
- remote = remote.replace(/^[a-z+]+:\/\//, "").replace(/^[^@/]+@/, "");
981
- if (!hasProtocol) {
982
- remote = remote.replace(":", "/");
983
- }
984
- remote = remote.replace(/\.git$/, "").replace(/\/+$/, "");
985
- return hash2(remote);
986
- }
987
- function hash2(value) {
988
- return createHash3("sha256").update(`chromatic-vitest-telemetry-v1:${value}`).digest("hex");
989
- }
990
- function getChromaticVersion(root) {
991
- try {
992
- const require2 = createRequire(join2(root, "package.json"));
993
- return require2("chromatic/package.json").version || "unknown";
994
- } catch {
995
- return "unknown";
996
- }
997
- }
998
- async function writeTelemetryMetadata(outputDirectory, data) {
999
- await writeFile2(
1000
- resolve2(outputDirectory, TELEMETRY_METADATA_FILE),
1001
- JSON.stringify(data, null, 2),
1002
- "utf8"
1003
- );
1004
- }
1005
-
1006
- // src/node/telemetry/sanitize.ts
1007
- import { sep } from "node:path";
1008
- import { homedir } from "node:os";
1009
- function sanitizeError(error) {
1010
- if (error instanceof Error && error.stack) {
1011
- const raw = error.stack.includes(error.message) ? error.stack : `${error.message}
1012
- Stack: ${error.stack}`;
1013
- return sanitizeString(raw).slice(0, 2e3);
1014
- }
1015
- return sanitizeString(error instanceof Error ? error.message : String(error)).slice(0, 1e3);
1016
- }
1017
- function sanitizeString(value) {
1018
- return value.replaceAll(sep, "/").replace(toPathRegExp(process.cwd()), "<process-cwd>").replace(toPathRegExp(homedir()), "<homedir>");
1019
- }
1020
- function toPathRegExp(path3) {
1021
- const normalized = path3.replaceAll(sep, "/");
1022
- const escaped = normalized.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1023
- return new RegExp(escaped, "gi");
1024
- }
1025
-
1026
- // src/node/telemetry/session.ts
1027
- import { randomUUID } from "node:crypto";
1028
- import { rmSync } from "node:fs";
1029
- import { resolve as resolve3 } from "node:path";
1030
- var session = {
1031
- id: randomUUID(),
1032
- projectId: void 0,
1033
- chromaticVersion: void 0,
1034
- /**
1035
- * Directories used by `telemetry.logToFile`.
1036
- * Held in session to avoid race conditions when Vitest projects are used.
1037
- * Multiple projects could try to clean up the same directory while other one is writing there already.
1038
- */
1039
- cleanedLogFileDirectories: /* @__PURE__ */ new Set(),
1040
- /** Promises to wait before Vitest exists */
1041
- cleanups: /* @__PURE__ */ new Set(),
1042
- /** Whether cleanup hooks were already registered for this session */
1043
- cleanupRegistered: false,
1044
- /** Whether internal `.vitest/chromatic/telemetry-metadata.json` has been written */
1045
- isMetadataWritten: false,
1046
- /** Contents of `.vitest/chromatic/telemetry-metadata.json` */
1047
- telemetryMetadata: void 0
1048
- };
1049
- function cleanTelemetryLogFiles(outputDirectory) {
1050
- if (session.cleanedLogFileDirectories.has(outputDirectory)) {
1051
- return;
1052
- }
1053
- session.cleanedLogFileDirectories.add(outputDirectory);
1054
- rmSync(resolve3(outputDirectory, TELEMETRY_LOG_FILE), { force: true });
1055
- rmSync(resolve3(outputDirectory, TELEMETRY_METADATA_FILE), { force: true });
1056
- }
1057
- function setupTelemetryCleanup(vitest) {
1058
- if (session.cleanupRegistered) {
1059
- return;
1060
- }
1061
- session.cleanupRegistered = true;
1062
- vitest.onClose(async () => {
1063
- await Promise.all(Array.from(session.cleanups.values()));
1064
- session.cleanups.clear();
1065
- session.isMetadataWritten = false;
1066
- session.cleanedLogFileDirectories.clear();
1067
- session.cleanupRegistered = false;
1068
- });
1069
- }
1070
-
1071
- // src/node/telemetry/track.ts
1072
- function trackEvent(event, vitest, options) {
1073
- if (!options.telemetry.enabled) {
1074
- return;
1075
- }
1076
- const promise = _trackEvent(event, vitest, options).catch(() => {
1077
- }).finally(() => session.cleanups.delete(promise));
1078
- session.cleanups.add(promise);
1079
- }
1080
- async function _trackEvent(event, vitest, options) {
1081
- const url = getEnv("CHROMATIC_TELEMETRY_URL") || TELEMETRY_URL;
1082
- const root = vitest.config.root;
1083
- const timestamp = (/* @__PURE__ */ new Date()).toISOString();
1084
- const outputDirectory = resolve4(root, options.outputDirectory);
1085
- session.projectId ||= await createProjectId(root);
1086
- session.chromaticVersion ||= getChromaticVersion(root);
1087
- const wireEvent = {
1088
- id: randomUUID2(),
1089
- sessionId: session.id,
1090
- projectId: session.projectId,
1091
- timestamp,
1092
- eventType: `${EVENT_TYPE_PREFIX}${event.eventType}`,
1093
- level: event.level,
1094
- payload: event.payload,
1095
- metadata: {
1096
- isCI,
1097
- pluginVersion: version,
1098
- nodeVersion: nodeVersion || "unknown",
1099
- vitestVersion: vitest.version,
1100
- isVitestProjects: vitest.projects.length > 1,
1101
- packageManager: packageManager.name,
1102
- packageManagerVersion: packageManager.version,
1103
- chromaticVersion: session.chromaticVersion
1104
- }
1105
- };
1106
- if (wireEvent.level === "error" && "error" in wireEvent.payload) {
1107
- wireEvent.payload.error = sanitizeError(wireEvent.payload.error);
1108
- }
1109
- let error = void 0;
1110
- try {
1111
- await fetch(`${url}/telemetry/v1/vitest/events`, {
1112
- method: "POST",
1113
- headers: { "Content-Type": "application/json" },
1114
- body: JSON.stringify(wireEvent),
1115
- signal: AbortSignal.timeout(TELEMETRY_FETCH_TIMEOUT_MS)
1116
- });
1117
- } catch (err) {
1118
- error = err instanceof Error ? err.message : String(err);
1119
- }
1120
- if (options.telemetry.logToFile) {
1121
- const logFile = resolve4(outputDirectory, TELEMETRY_LOG_FILE);
1122
- await mkdir(outputDirectory, { recursive: true });
1123
- await appendFile(logFile, `${JSON.stringify(wireEvent)}
1124
- `, "utf8");
1125
- if (error) {
1126
- await appendFile(logFile, `${JSON.stringify({ telemetryPostError: error })}
1127
- `, "utf8");
1128
- }
1129
- }
1130
- if (!session.isMetadataWritten) {
1131
- session.isMetadataWritten = true;
1132
- await writeTelemetryMetadata(outputDirectory, {
1133
- ...wireEvent.metadata,
1134
- sessionId: wireEvent.sessionId,
1135
- projectId: wireEvent.projectId
1136
- });
1137
- }
1138
- }
1139
-
1140
- // src/node/telemetry/reporter.ts
1141
- var REPORTER_NAME = "chromatic-telemetry-reporter";
1142
- var TelemetryReporter = class _TelemetryReporter {
1143
- constructor(ctx, options) {
1144
- this.ctx = ctx;
1145
- this.options = options;
1146
- }
1147
- name = REPORTER_NAME;
1148
- snapshotCount = 0;
1149
- /**
1150
- * Add `TelemetryReporter` to Vitest reporters unless it's already included.
1151
- */
1152
- static apply(ctx, options) {
1153
- if (!options.telemetry.enabled) {
1154
- return;
1155
- }
1156
- for (const reporter of ctx.config.reporters) {
1157
- if (isTelemetryReporter(reporter)) {
1158
- return;
1159
- }
1160
- }
1161
- ctx.config.reporters.push(new _TelemetryReporter(ctx, options));
1162
- }
1163
- /**
1164
- * Custom reporter life-cycle called when `takeSnapshot()` is called.
1165
- */
1166
- static onSnapshot(ctx, payload) {
1167
- const reporter = ctx.config.reporters.find(isTelemetryReporter);
1168
- reporter?._onSnapshot(payload);
1169
- }
1170
- _onSnapshot(payload) {
1171
- this.snapshotCount++;
1172
- trackEvent({ eventType: "snapshot_captured", level: "info", payload }, this.ctx, this.options);
1173
- }
1174
- onTestRunStart() {
1175
- this.snapshotCount = 0;
1176
- trackEvent({ eventType: "run_started", level: "info", payload: {} }, this.ctx, this.options);
1177
- }
1178
- onTestRunEnd() {
1179
- trackEvent(
1180
- { eventType: "run_ended", level: "info", payload: { snapshotCount: this.snapshotCount } },
1181
- this.ctx,
1182
- this.options
1183
- );
1184
- }
1185
- };
1186
- function isTelemetryReporter(reporter) {
1187
- return "name" in reporter && reporter.name === REPORTER_NAME;
1188
- }
1189
-
1190
- // src/node/NetworkIdleTracker.ts
1191
- var NetworkIdleTimeoutError = class extends Error {
1192
- name = "NetworkIdleTimeoutError";
1193
- };
1194
- var NetworkIdleTracker = class _NetworkIdleTracker {
1195
- constructor(cdp, idleTimeout) {
1196
- this.cdp = cdp;
1197
- this.idleTimeout = idleTimeout;
1198
- }
1199
- pending = /* @__PURE__ */ new Set();
1200
- idleTimer = null;
1201
- idleResolvers = [];
1202
- static async create(cdp, idleTimeout) {
1203
- const tracker = new _NetworkIdleTracker(cdp, idleTimeout);
1204
- return tracker;
1205
- }
1206
- async watch() {
1207
- this.cdp.on("Network.requestWillBeSent", this.onRequest);
1208
- this.cdp.on("Network.loadingFinished", this.onComplete);
1209
- this.cdp.on("Network.loadingFailed", this.onComplete);
1210
- await this.cdp.send("Network.enable");
1211
- }
1212
- async unwatch() {
1213
- this.cdp.off("Network.requestWillBeSent", this.onRequest);
1214
- this.cdp.off("Network.loadingFinished", this.onComplete);
1215
- this.cdp.off("Network.loadingFailed", this.onComplete);
1216
- this.clearTimer();
1217
- this.pending.clear();
1218
- this.idleResolvers.splice(0).forEach((fn) => fn());
1219
- await this.cdp.send("Network.disable");
1220
- }
1221
- waitForIdle(rejectTimeout) {
1222
- if (this.pending.size === 0 && this.idleTimer === null) {
1223
- return Promise.resolve();
1224
- }
1225
- return new Promise((resolve9, reject) => {
1226
- const timeout = setTimeout(
1227
- () => reject(new NetworkIdleTimeoutError("Timed out waiting for network to be idle")),
1228
- rejectTimeout
1229
- );
1230
- this.idleResolvers.push(resolve9, () => clearTimeout(timeout));
1231
- });
1232
- }
1233
- onComplete = (params) => {
1234
- this.pending.delete(params.requestId);
1235
- if (this.pending.size === 0) {
1236
- this.startTimer();
1237
- }
1238
- };
1239
- onRequest = (params) => {
1240
- this.pending.add(params.requestId);
1241
- this.clearTimer();
1242
- };
1243
- startTimer() {
1244
- this.clearTimer();
1245
- this.idleTimer = setTimeout(() => {
1246
- this.idleTimer = null;
1247
- this.idleResolvers.splice(0).forEach((fn) => fn());
1248
- }, this.idleTimeout)?.unref();
1249
- }
1250
- clearTimer() {
1251
- if (this.idleTimer) {
1252
- clearTimeout(this.idleTimer);
1253
- this.idleTimer = null;
1254
- }
1255
- }
1256
- };
1257
-
1258
- // src/node/reporter.ts
1259
- import { relative, resolve as resolve5 } from "node:path";
1260
- import colors from "tinyrainbow";
1261
-
1262
- // src/constants.ts
1263
- var DEFAULT_OUTPUT_DIR = ".vitest/chromatic";
1264
-
1265
- // src/node/reporter.ts
1266
- var REPORTER_NAME2 = "chromatic-reporter";
1267
- var ChromaticReporter = class _ChromaticReporter {
1268
- constructor(ctx, options, snapshotCountPerEntity = /* @__PURE__ */ new Map(), isPluginActivated = false) {
1269
- this.ctx = ctx;
1270
- this.options = options;
1271
- this.snapshotCountPerEntity = snapshotCountPerEntity;
1272
- this.isPluginActivated = isPluginActivated;
1273
- }
1274
- name = REPORTER_NAME2;
1275
- /**
1276
- * Add `ChromaticReporter` to Vitest reporters unless it's already included.
1277
- */
1278
- static apply(ctx, pluginOptions) {
1279
- const options = {
1280
- verbose: pluginOptions.reporter.verbose,
1281
- outputDirectory: pluginOptions.outputDirectory,
1282
- turboSnap: pluginOptions.turboSnap,
1283
- logToFile: pluginOptions.telemetry.enabled && pluginOptions.telemetry.logToFile,
1284
- builtInReporter: "default"
1285
- };
1286
- for (const reporter of ctx.config.reporters) {
1287
- if (isChromaticReporter(reporter)) {
1288
- return;
1289
- }
1290
- if (!Array.isArray(reporter)) {
1291
- continue;
1292
- }
1293
- const reporterName = reporter[0];
1294
- if (reporterName === "tree" || reporterName === "default" || reporterName === "verbose") {
1295
- options.builtInReporter = reporterName;
1296
- }
1297
- }
1298
- ctx.config.reporters.push(new _ChromaticReporter(ctx, options));
1299
- }
1300
- /**
1301
- * Custom reporter life-cycle called when `takeSnapshot()` is called.
1302
- */
1303
- static onSnapshot(ctx, test) {
1304
- const reporter = ctx.config.reporters.find(isChromaticReporter);
1305
- reporter?._onSnapshot(test);
1306
- }
1307
- /**
1308
- * Custom reporter life-cycle called when plugin is activated for a project.
1309
- */
1310
- static onPluginActivated(ctx) {
1311
- const reporter = ctx.config.reporters.find(isChromaticReporter);
1312
- reporter?._onPluginActivated();
1313
- }
1314
- onTestCaseResult(testCase) {
1315
- if (this.options.builtInReporter !== "verbose") {
1316
- return;
1317
- }
1318
- this.logSnapshots({
1319
- count: this.snapshotCountPerEntity.get(testCase.id) ?? 0,
1320
- indentation: 3,
1321
- projectName: testCase.project.name
1322
- });
1323
- }
1324
- onTestModuleEnd(testModule) {
1325
- if (this.options.builtInReporter !== "default" && this.options.builtInReporter !== "tree") {
1326
- return;
1327
- }
1328
- let noSlowTests = true;
1329
- for (const testCase of testModule.children.allTests()) {
1330
- if (testCase.diagnostic()?.slow) {
1331
- noSlowTests = false;
1332
- break;
1333
- }
1334
- }
1335
- const indentProjectName = noSlowTests && this.options.builtInReporter === "default";
1336
- this.logSnapshots({
1337
- count: this.snapshotCountPerEntity.get(testModule.id) ?? 0,
1338
- indentation: indentProjectName ? 3 : 2,
1339
- projectName: indentProjectName && testModule.project.name
1340
- });
1341
- }
1342
- onTestRunEnd() {
1343
- const snapshotCount = [...this.snapshotCountPerEntity.values()].reduce((a, b) => a + b, 0);
1344
- this.snapshotCountPerEntity.clear();
1345
- const separator = colors.dim("\u2500".repeat(this.ctx.logger.getColumns()));
1346
- if (!this.isPluginActivated) {
1347
- return this.ctx.logger.log(
1348
- `${separator}`,
1349
- `
1350
- ${colors.inverse(" Chromatic Visual Regression ")}`,
1351
- `
1352
-
1353
- ${colors.red("No archives captured. Chromatic plugin requires a browser mode project with Chromium project.")}`,
1354
- `
1355
-
1356
- ${separator}
1357
- `
1358
- );
1359
- }
1360
- if (snapshotCount === 0) {
1361
- return;
1362
- }
1363
- const output = resolve5(this.ctx.config.root, this.options.outputDirectory);
1364
- let uploadCommand = "chromatic --vitest --project-token=<TOKEN>";
1365
- if (this.options.turboSnap) {
1366
- uploadCommand += " --only-changed";
1367
- }
1368
- if (this.options.outputDirectory !== DEFAULT_OUTPUT_DIR || this.ctx.config.root !== process.cwd()) {
1369
- uploadCommand = `CHROMATIC_ARCHIVE_LOCATION=${relative(process.cwd(), output)} ${uploadCommand}`;
1370
- }
1371
- const telemetryInfo = this.options.logToFile ? `
1372
- Telemetry events logged to ${colors.dim(resolve5(output, TELEMETRY_LOG_FILE))}` : "";
1373
- this.ctx.logger.log(
1374
- `${separator}`,
1375
- `
1376
- ${colors.inverse(" Chromatic Visual Regression ")}`,
1377
- `
1378
-
1379
- ${colors.green("\u2713")} ${snapshotCount} ${pluralize(snapshotCount, "archive")} captured`,
1380
- `
1381
-
1382
- Archives saved in ${colors.dim(output)}`,
1383
- telemetryInfo,
1384
- `
1385
- To upload archives into Chromatic run ${colors.green(uploadCommand)}`,
1386
- `
1387
-
1388
- ${separator}
1389
- `
1390
- );
1391
- }
1392
- logSnapshots(options) {
1393
- if (!this.options.verbose || options.count === 0) {
1394
- return;
1395
- }
1396
- const snapshots = `(${options.count} ${pluralize(options.count, "archive")} captured)`;
1397
- if (options.projectName) {
1398
- options.indentation += options.projectName.length + 2;
1399
- }
1400
- this.ctx.logger.log(`${" ".repeat(options.indentation)} ${colors.dim(snapshots)}`);
1401
- }
1402
- _onSnapshot(test) {
1403
- const key = this.options.builtInReporter === "verbose" ? test.id : test.module.id;
1404
- const previousCount = this.snapshotCountPerEntity.get(key) ?? 0;
1405
- this.snapshotCountPerEntity.set(key, previousCount + 1);
1406
- }
1407
- _onPluginActivated() {
1408
- this.isPluginActivated = true;
1409
- }
1410
- };
1411
- function isChromaticReporter(reporter) {
1412
- return "name" in reporter && reporter.name === REPORTER_NAME2;
1413
- }
1414
- function pluralize(count, text) {
1415
- return count === 1 ? text : `${text}s`;
1416
- }
1417
-
1418
- // src/node/webpack-stats-reporter.ts
1419
- import { existsSync as existsSync3, readFileSync as readFileSync2 } from "node:fs";
1420
- import { mkdir as mkdir2, readdir, readFile as readFile2, rm, writeFile as writeFile3 } from "node:fs/promises";
1421
- import { dirname, relative as relative2, resolve as resolve6, sep as sep2 } from "node:path";
1422
- import { isCSSRequest } from "vitest/node";
1423
- var REPORTER_NAME3 = "chromatic-webpack-stats-reporter";
1424
- var VIRTUAL_MODULE_PREFIX = "\0";
1425
- var WebpackStatsReporter = class _WebpackStatsReporter {
1426
- constructor(ctx, options, moduleIdsToStoryFiles = /* @__PURE__ */ new Map()) {
1427
- this.ctx = ctx;
1428
- this.options = options;
1429
- this.moduleIdsToStoryFiles = moduleIdsToStoryFiles;
1430
- }
1431
- name = REPORTER_NAME3;
1432
- /**
1433
- * Add `WebpackStatsReporter` to Vitest reporters unless it's already included.
1434
- */
1435
- static apply(ctx, pluginOptions) {
1436
- const exists = ctx.config.reporters.some(isWebpackStatsReporter);
1437
- if (!exists) {
1438
- const filename = [
1439
- "preview-stats",
1440
- ctx.config.shard && `-${ctx.config.shard.index}-${ctx.config.shard.count}`,
1441
- ".json"
1442
- ].filter(Boolean).join("");
1443
- const outputFile2 = resolve6(ctx.config.root, pluginOptions.outputDirectory, filename);
1444
- ctx.config.reporters.push(new _WebpackStatsReporter(ctx, { outputFile: outputFile2, pluginOptions }));
1445
- }
1446
- }
1447
- /**
1448
- * Custom reporter life-cycle called when `*.stories.json` is written to file system.
1449
- */
1450
- static onStoryFileWrite(ctx, testCase, storyFilePath) {
1451
- const reporter = ctx.config.reporters.find(isWebpackStatsReporter);
1452
- reporter?._onStoryFileWrite(testCase, storyFilePath);
1453
- }
1454
- /**
1455
- * Collect Story files written per each test module during test run
1456
- */
1457
- _onStoryFileWrite(testCase, storyFilePath) {
1458
- const moduleId = testCase.module.moduleId;
1459
- let entry = this.moduleIdsToStoryFiles.get(moduleId);
1460
- if (!entry) {
1461
- entry = /* @__PURE__ */ new Set();
1462
- this.moduleIdsToStoryFiles.set(moduleId, entry);
1463
- }
1464
- entry.add(storyFilePath);
1465
- }
1466
- async onTestRunStart() {
1467
- await rm(this.options.outputFile, { force: true });
1468
- this.moduleIdsToStoryFiles.clear();
1469
- }
1470
- async onTestRunEnd(testModules) {
1471
- try {
1472
- await this.writePreviewStats(testModules);
1473
- } catch (error) {
1474
- trackEvent(
1475
- {
1476
- eventType: "turbosnap_error",
1477
- level: "error",
1478
- payload: { operation: "write-stats", error }
1479
- },
1480
- this.ctx,
1481
- this.options.pluginOptions
1482
- );
1483
- throw error;
1484
- }
1485
- }
1486
- /**
1487
- * Generate `preview-stats.json` from collected Story files and their dependent test modules
1488
- */
1489
- async writePreviewStats(testModules) {
1490
- const statsMap = /* @__PURE__ */ new Map();
1491
- for (const testModule of testModules) {
1492
- const storyFiles = this.moduleIdsToStoryFiles.get(testModule.moduleId);
1493
- if (!storyFiles || storyFiles.size === 0) {
1494
- continue;
1495
- }
1496
- const vite = testModule.project.browser?.vite;
1497
- if (!vite) {
1498
- continue;
1499
- }
1500
- const id = this.normalize(testModule.moduleId);
1501
- const additionalModules = [];
1502
- statsMap.set(id, this.createStatsMapModule(id, [...storyFiles]));
1503
- if (testModule.project.config.config) {
1504
- additionalModules.push({ id: testModule.project.config.config, isInModuleGraph: false });
1505
- }
1506
- for (const setupFile of testModule.project.config.setupFiles) {
1507
- additionalModules.push({ id: setupFile, isInModuleGraph: true });
1508
- }
1509
- this.addModule(
1510
- testModule.moduleId,
1511
- statsMap,
1512
- vite.moduleGraph,
1513
- vite.config.cacheDir,
1514
- /* @__PURE__ */ new Set(),
1515
- additionalModules
1516
- );
1517
- }
1518
- if (!existsSync3(dirname(this.options.outputFile))) {
1519
- await mkdir2(dirname(this.options.outputFile), { recursive: true });
1520
- }
1521
- await writeFile3(
1522
- this.options.outputFile,
1523
- JSON.stringify({ modules: Array.from(statsMap.values()) }, null, 2),
1524
- "utf-8"
1525
- );
1526
- }
1527
- addModule(id, statsMap, moduleGraph, cacheDir, visited, additionalModules = []) {
1528
- if (visited.has(id)) {
1529
- return;
1530
- }
1531
- visited.add(id);
1532
- const mod = moduleGraph.getModuleById(id);
1533
- if (!mod) {
1534
- return this.ctx.logger.error(
1535
- `[chromatic] Could not find module for id ${id}. Excluding from TurboSnap.`
1536
- );
1537
- }
1538
- const importedModules = [...additionalModules];
1539
- for (const imported of mod.importedModules) {
1540
- if (imported.id == null) {
1541
- if (imported.file) {
1542
- if (mod.file && isCSSRequest(mod.file) && !isCSSRequest(imported.file)) {
1543
- continue;
1544
- }
1545
- importedModules.push({ id: imported.file, isInModuleGraph: false });
1546
- }
1547
- continue;
1548
- }
1549
- const isOptimizedDependency = imported.id.startsWith(cacheDir);
1550
- if (!isOptimizedDependency) {
1551
- importedModules.push({ id: imported.id, isInModuleGraph: true });
1552
- continue;
1553
- }
1554
- importedModules.push(...resolveOptimizedDependencySources(imported, cacheDir, visited));
1555
- }
1556
- for (const imported of importedModules) {
1557
- if (imported.id.startsWith(VIRTUAL_MODULE_PREFIX)) {
1558
- continue;
1559
- }
1560
- if (imported.isInModuleGraph) {
1561
- this.addModule(imported.id, statsMap, moduleGraph, cacheDir, visited);
1562
- }
1563
- const depId = this.normalize(imported.id);
1564
- const entry = statsMap.get(depId);
1565
- if (!entry) {
1566
- statsMap.set(depId, this.createStatsMapModule(depId, [mod.id]));
1567
- continue;
1568
- }
1569
- const moduleName = this.normalize(mod.id);
1570
- if (!entry.reasons.find((reason) => reason.moduleName === moduleName)) {
1571
- entry.reasons.push({ moduleName });
1572
- }
1573
- }
1574
- }
1575
- createStatsMapModule(filename, importers) {
1576
- return {
1577
- id: filename,
1578
- name: filename,
1579
- reasons: importers.map((importer) => ({ moduleName: this.normalize(importer) }))
1580
- };
1581
- }
1582
- normalize(filePath) {
1583
- return relative2(this.ctx.config.root, filePath).replaceAll(sep2, "/").split("?")[0];
1584
- }
1585
- };
1586
- function isWebpackStatsReporter(reporter) {
1587
- return "name" in reporter && reporter.name === REPORTER_NAME3;
1588
- }
1589
- function resolveOptimizedDependencySources(mod, cacheDir, visited) {
1590
- if (visited.has(mod.id)) {
1591
- return [];
1592
- }
1593
- visited.add(mod.id);
1594
- const sources = getChunkSources(mod, cacheDir).map((id) => ({
1595
- id,
1596
- // These entries are not in module graph as they were bundled
1597
- isInModuleGraph: false
1598
- }));
1599
- for (const imported of mod.importedModules) {
1600
- if (imported.id == null) {
1601
- if (imported.file) {
1602
- sources.push({ id: imported.file, isInModuleGraph: false });
1603
- }
1604
- continue;
1605
- }
1606
- if (imported.id.startsWith(VIRTUAL_MODULE_PREFIX)) {
1607
- continue;
1608
- }
1609
- if (imported.id.startsWith(cacheDir)) {
1610
- sources.push(...resolveOptimizedDependencySources(imported, cacheDir, visited));
1611
- } else {
1612
- sources.push({ id: imported.id, isInModuleGraph: true });
1613
- }
1614
- }
1615
- return sources;
1616
- }
1617
- function getChunkSources(mod, cacheDir) {
1618
- const sources = resolveMapSources(mod, mod.transformResult?.map, cacheDir);
1619
- if (sources.length) {
1620
- return sources;
1621
- }
1622
- try {
1623
- const diskMap = JSON.parse(readFileSync2(`${mod.id.split("?")[0]}.map`, "utf-8"));
1624
- return resolveMapSources(mod, diskMap, cacheDir);
1625
- } catch {
1626
- return [];
1627
- }
1628
- }
1629
- function resolveMapSources(mod, map, cacheDir) {
1630
- if (!map || typeof map !== "object" || !("sources" in map) || !Array.isArray(map.sources)) {
1631
- return [];
1632
- }
1633
- return map.sources.flatMap((source) => {
1634
- if (typeof source !== "string" || source.startsWith(VIRTUAL_MODULE_PREFIX)) {
1635
- return [];
1636
- }
1637
- const resolved = resolve6(dirname(mod.id), source).replaceAll(sep2, "/");
1638
- if (resolved.startsWith(cacheDir)) {
1639
- return [];
1640
- }
1641
- return [resolved];
1642
- });
1643
- }
1644
- async function mergePreviewStats(options) {
1645
- const outputDirectory = resolve6(options.root, options.outputDirectory);
1646
- const merged = /* @__PURE__ */ new Map();
1647
- for (const filename of await readdir(outputDirectory)) {
1648
- if (filename.startsWith("preview-stats") && filename.endsWith(".json")) {
1649
- const fullFilename = resolve6(outputDirectory, filename);
1650
- const stats = JSON.parse(await readFile2(fullFilename, "utf-8"));
1651
- for (const mod of stats.modules) {
1652
- const previous = merged.get(mod.id);
1653
- if (previous) {
1654
- for (const reason of mod.reasons) {
1655
- if (!previous.reasons.some((r) => r.moduleName === reason.moduleName)) {
1656
- previous.reasons.push(reason);
1657
- }
1658
- }
1659
- } else {
1660
- merged.set(mod.id, mod);
1661
- }
1662
- }
1663
- await rm(fullFilename);
1664
- }
1665
- }
1666
- await writeFile3(
1667
- resolve6(outputDirectory, "preview-stats.json"),
1668
- JSON.stringify({ modules: Array.from(merged.values()) }, null, 2),
1669
- "utf-8"
1670
- );
1671
- }
1672
-
1673
- // src/node/commands.ts
1674
- function createCommands(options) {
1675
- const resourceArchivers = /* @__PURE__ */ new Map();
1676
- const networkIdleTrackers = /* @__PURE__ */ new Map();
1677
- const savedResults = /* @__PURE__ */ new Set();
1678
- const trackedCommandFailures = /* @__PURE__ */ new Set();
1679
- const snapshots = /* @__PURE__ */ new Map();
1680
- const commands = {
1681
- /**
1682
- * Store a `@rrweb` generated DOM snapshot for the test.
1683
- * Can be called multiple times during a single test case.
1684
- */
1685
- async __chromatic_uploadDOMSnapshot(context, id, snapshot, pseudoClassIds, name, snapshotOptions) {
1686
- const entity = context.project.vitest.state.getReportedEntityById(id);
1687
- assert(
1688
- entity?.type === "test",
1689
- `Expected entity with id ${id} to be a test, found ${entity?.type}`
1690
- );
1691
- let sessionSnapshots = snapshots.get(id);
1692
- if (!sessionSnapshots) {
1693
- sessionSnapshots = /* @__PURE__ */ new Map();
1694
- snapshots.set(id, sessionSnapshots);
1695
- }
1696
- const isCustomName = name != void 0;
1697
- name ||= `Snapshot #${sessionSnapshots.size + 1}`;
1698
- const frame = await context.frame();
1699
- const { viewport, colorScheme } = await frame.evaluate(
1700
- () => ({
1701
- viewport: { width: window.innerWidth, height: window.innerHeight },
1702
- colorScheme: window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light"
1703
- })
1704
- );
1705
- sessionSnapshots.set(name, { snapshot, viewport, colorScheme, pseudoClassIds });
1706
- ChromaticReporter.onSnapshot(context.project.vitest, entity);
1707
- TelemetryReporter.onSnapshot(context.project.vitest, {
1708
- isCustomName,
1709
- colorScheme,
1710
- isAutomaticSnapshot: snapshotOptions?.isAutomaticSnapshot ?? false
1711
- });
1712
- },
1713
- /**
1714
- * Wait for network to be idle, meaning no new network requests for at least `idleNetworkInterval` ms.
1715
- * Use `timeout` argument to reject if network doesn't become idle within given time.
1716
- */
1717
- async __chromatic_waitForIdleNetwork(context, timeout) {
1718
- const networkIdleTracker = networkIdleTrackers.get(context.sessionId);
1719
- assert(networkIdleTracker, `No network idle tracker found for session ${context.sessionId}`);
1720
- await networkIdleTracker.waitForIdle(timeout);
1721
- },
1722
- /**
1723
- * Start recording HTTP resources and network activity for given test.
1724
- */
1725
- async __chromatic_interceptFetch(context) {
1726
- let resourceArchiver = resourceArchivers.get(context.sessionId);
1727
- let networkIdleTracker = networkIdleTrackers.get(context.sessionId);
1728
- let cdp;
1729
- if (!resourceArchiver || !networkIdleTracker) {
1730
- cdp = await context.provider.getCDPSession?.(context.sessionId);
1731
- assert(cdp, `Unable to get CDP session for session ${context.sessionId}`);
1732
- }
1733
- if (!resourceArchiver) {
1734
- const { contextOptions } = context.project.config.browser.provider?.options ?? {};
1735
- resourceArchiver = new ResourceArchiver(
1736
- cdp,
1737
- options.assetDomains,
1738
- contextOptions?.httpCredentials,
1739
- new URL(context.page.url())
1740
- );
1741
- resourceArchivers.set(context.sessionId, resourceArchiver);
1742
- }
1743
- if (!networkIdleTracker) {
1744
- networkIdleTracker = await NetworkIdleTracker.create(cdp, options.idleNetworkInterval);
1745
- networkIdleTrackers.set(context.sessionId, networkIdleTracker);
1746
- }
1747
- await networkIdleTracker.watch();
1748
- await resourceArchiver.watch();
1749
- },
1750
- /**
1751
- * Write captured snapshots and network resources to disk.
1752
- * Should be called only once per test as it also clears resources.
1753
- */
1754
- async __chromatic_writeTestResult(context, id, testOptions = {}) {
1755
- const entity = context.project.vitest.state.getReportedEntityById(id);
1756
- assert(
1757
- entity?.type === "test",
1758
- `Expected entity with id ${id} to be a test, found ${entity?.type}`
1759
- );
1760
- const { archive, sessionSnapshots } = await onTestCleanup(context, id);
1761
- assert(sessionSnapshots, `No snapshots found for test ${id}`);
1762
- const snapshotBuffers = {};
1763
- const titlePath = testOptions.title ? [testOptions.title] : getTitle(entity);
1764
- for (const [name, { snapshot, viewport, colorScheme, pseudoClassIds }] of sessionSnapshots) {
1765
- const names = generateUniqueSnapshotName({
1766
- snapshotName: getSnapshotPrefix(entity).concat(name),
1767
- titlePath
1768
- });
1769
- snapshotBuffers[names] = {
1770
- snapshot: Buffer.from(JSON.stringify(snapshot)),
1771
- viewport,
1772
- colorScheme,
1773
- pseudoClassIds,
1774
- parameters: {
1775
- chromatic: {
1776
- vitest: {
1777
- suites: getSuiteNames(entity),
1778
- test: entity.name,
1779
- snapshot: name
1780
- }
1781
- }
1782
- }
1783
- };
1784
- }
1785
- const { storiesFile } = await writeTestResult(
1786
- {
1787
- outputDir: resolve7(context.project.vitest.config.root, options.outputDirectory),
1788
- pageUrl: context.page.url(),
1789
- titlePath
1790
- },
1791
- snapshotBuffers,
1792
- archive,
1793
- {
1794
- delay: testOptions.delay ?? options.delay,
1795
- diffIncludeAntiAliasing: testOptions.diffIncludeAntiAliasing ?? options.diffIncludeAntiAliasing,
1796
- diffThreshold: testOptions.diffThreshold ?? options.diffThreshold,
1797
- forcedColors: testOptions.forcedColors ?? options.forcedColors,
1798
- pauseAnimationAtEnd: testOptions.pauseAnimationAtEnd ?? options.pauseAnimationAtEnd,
1799
- prefersReducedMotion: testOptions.prefersReducedMotion ?? options.prefersReducedMotion,
1800
- cropToViewport: testOptions.cropToViewport ?? options.cropToViewport,
1801
- ignoreSelectors: testOptions.ignoreSelectors ?? options.ignoreSelectors
1802
- },
1803
- "vitest"
1804
- );
1805
- if (options.turboSnap) {
1806
- WebpackStatsReporter.onStoryFileWrite(context.project.vitest, entity, storiesFile);
1807
- }
1808
- trackEvent(
1809
- {
1810
- eventType: "archives_created",
1811
- level: "info",
1812
- payload: { archiveCount: Object.keys(snapshotBuffers).length }
1813
- },
1814
- context.project.vitest,
1815
- options
1816
- );
1817
- },
1818
- /**
1819
- * Clear test state without writing test results.
1820
- */
1821
- async __chromatic_stopWithoutSnapshots(context, id) {
1822
- await onTestCleanup(context, id);
1823
- },
1824
- /**
1825
- * Forward a browser-side telemetry event to the Node side.
1826
- */
1827
- async __chromatic_telemetry(context, event) {
1828
- void trackEvent(event, context.project.vitest, options);
1829
- },
1830
- /**
1831
- * Reset all state of the plugin. Should be called between test runs.
1832
- */
1833
- async __chromatic_reset() {
1834
- for (const resourceArchiver of resourceArchivers.values()) {
1835
- resourceArchiver.archive = {};
1836
- }
1837
- resourceArchivers.clear();
1838
- networkIdleTrackers.clear();
1839
- snapshots.clear();
1840
- savedResults.clear();
1841
- trackedCommandFailures.clear();
1842
- },
1843
- /**
1844
- * Get currently save snapshots. Used only during testing.
1845
- * @internal
1846
- */
1847
- async __chromatic_getSnapshots(_, id) {
1848
- return Object.fromEntries(snapshots.get(id) || []);
1849
- }
1850
- };
1851
- return withErrorTracking2(commands);
1852
- function withErrorTracking2(_commands) {
1853
- return Object.fromEntries(
1854
- Object.entries(_commands).map(
1855
- ([name, command]) => [
1856
- name,
1857
- async (context, ...args) => {
1858
- try {
1859
- return await command(context, ...args);
1860
- } catch (error) {
1861
- trackCommandFailure(name, error, context);
1862
- throw error;
1863
- }
1864
- }
1865
- ]
1866
- )
1867
- );
1868
- }
1869
- function trackCommandFailure(command, error, context) {
1870
- if (command === "__chromatic_telemetry" || command === "__chromatic_getSnapshots") {
1871
- return;
1872
- }
1873
- const key = `${command}:${error instanceof Error ? error.message : String(error)}`;
1874
- if (trackedCommandFailures.has(key)) {
1875
- return;
1876
- }
1877
- trackedCommandFailures.add(key);
1878
- try {
1879
- trackEvent(
1880
- { eventType: "command_failed", level: "error", payload: { command, error } },
1881
- context.project.vitest,
1882
- options
1883
- );
1884
- } catch {
1885
- }
1886
- }
1887
- async function onTestCleanup(context, id) {
1888
- const resourceArchiver = resourceArchivers.get(context.sessionId);
1889
- assert(resourceArchiver, `No resource archiver found for test ${id}`);
1890
- const networkIdleTracker = networkIdleTrackers.get(context.sessionId);
1891
- assert(networkIdleTracker, `No network idle tracker found for test ${id}`);
1892
- await resourceArchiver.unwatch();
1893
- await networkIdleTracker.unwatch();
1894
- const sessionSnapshots = snapshots.get(id);
1895
- snapshots.delete(id);
1896
- return { archive: resourceArchiver.archive, sessionSnapshots };
1897
- }
1898
- function generateUniqueSnapshotName(options2) {
1899
- const names = options2.snapshotName.join(" / ");
1900
- const base = toId2(options2.titlePath.join(" / "), storyNameFromExport2(names));
1901
- let key = base;
1902
- let count = 1;
1903
- while (savedResults.has(key)) {
1904
- key = `${base} (${count++})`;
1905
- }
1906
- savedResults.add(key);
1907
- if (count > 1) {
1908
- return `${names} (${count})`;
1909
- }
1910
- return names;
1911
- }
1912
- }
1913
- function getTitle(test) {
1914
- const names = [removeFileExtensions(test.module.relativeModuleId)];
1915
- const hasManyProjects = test.project.vitest.projects.filter((project) => project.config.browser.name === "chromium").length > 1;
1916
- if (hasManyProjects && test.project.name) {
1917
- names.unshift(test.project.name);
1918
- }
1919
- return names;
1920
- }
1921
- function getSnapshotPrefix(test) {
1922
- const names = [test.name];
1923
- let current = test;
1924
- while ("parent" in current && current.parent) {
1925
- current = current.parent;
1926
- if ("name" in current && current.name) {
1927
- names.unshift(current.name);
1928
- }
1929
- }
1930
- return names;
1931
- }
1932
- function getSuiteNames(test) {
1933
- if (test.parent.type !== "suite") {
1934
- return [];
1935
- }
1936
- const names = [];
1937
- let current = test;
1938
- while ("parent" in current && current.parent) {
1939
- current = current.parent;
1940
- if (current.type === "suite") {
1941
- names.unshift(current.name);
1942
- }
1943
- }
1944
- return names;
1945
- }
1946
- function removeFileExtensions(filepath) {
1947
- const parts = filepath.split("/");
1948
- const filename = parts.pop() || "";
1949
- return parts.concat(
1950
- // Trim filenames like "src/components/accordion/Accordion.browser.spec.tsx" -> "src/components/accordion/Accordion"
1951
- filename.split(".")[0]
1952
- ).join("/");
1953
- }
1954
-
1955
- // src/node/plugin.ts
1956
- var DEFAULT_TAG_DESCRIPTION = "Visual Regression Tests for `@chromatic-com/vitest`";
1957
- function chromaticPlugin(userOptions = {}) {
1958
- const options = {
1959
- assetDomains: [],
1960
- disableAutoSnapshot: false,
1961
- outputDirectory: DEFAULT_OUTPUT_DIR,
1962
- resourceArchiveTimeout: DEFAULT_GLOBAL_RESOURCE_ARCHIVE_TIMEOUT_MS,
1963
- idleNetworkInterval: 100,
1964
- turboSnap: false,
1965
- ...userOptions,
1966
- reporter: resolveReporterOptions(userOptions.reporter),
1967
- telemetry: resolveTelemetryOptions()
1968
- };
1969
- const isDist = import.meta.url.includes("dist/plugin.js");
1970
- const setupFile = resolve8(
1971
- import.meta.dirname,
1972
- isDist ? "./setupFile.js" : "../browser/setupFile.ts"
1973
- );
1974
- return {
1975
- name: "vitest:chromatic",
1976
- config() {
1977
- return {
1978
- optimizeDeps: {
1979
- entries: [setupFile]
1980
- },
1981
- // vitest/suite is available in 4.0 only. Importing it in 4.1 logs error, in 5.0 it's removed.
1982
- resolve: vitestVersion.startsWith("4.0") ? void 0 : { alias: { "vitest/suite": "vitest" } },
1983
- test: {
1984
- provide: {
1985
- __chromatic_options: options
1986
- },
1987
- browser: {
1988
- commands: createCommands(options)
1989
- }
1990
- }
1991
- };
1992
- },
1993
- configureVitest: withErrorTracking(options, async (context) => {
1994
- const project = context.project;
1995
- const browser = project.config.browser;
1996
- const sequence = context.vitest.config.sequence;
1997
- const isMergeReports = project.globalConfig.mergeReports;
1998
- if (options.telemetry.enabled) {
1999
- setupTelemetryCleanup(context.vitest);
2000
- trackEvent2({
2001
- eventType: "plugin_configured",
2002
- level: "info",
2003
- payload: {
2004
- isShardedRun: project.config.shard != null,
2005
- cropToViewport: options.cropToViewport,
2006
- delay: options.delay,
2007
- diffIncludeAntiAliasing: options.diffIncludeAntiAliasing,
2008
- diffThreshold: options.diffThreshold,
2009
- disableAutoSnapshot: options.disableAutoSnapshot,
2010
- forcedColors: options.forcedColors,
2011
- idleNetworkInterval: options.idleNetworkInterval,
2012
- pauseAnimationAtEnd: options.pauseAnimationAtEnd,
2013
- prefersReducedMotion: options.prefersReducedMotion,
2014
- resourceArchiveTimeout: options.resourceArchiveTimeout,
2015
- turboSnap: options.turboSnap,
2016
- reporter: !options.reporter.enabled ? "off" : options.reporter.verbose ? "verbose" : "non-verbose",
2017
- // Don't attach any user-defined strings values:
2018
- isCustomOutputDirectory: options.outputDirectory !== DEFAULT_OUTPUT_DIR,
2019
- assetDomainsCount: options.assetDomains?.length ?? 0,
2020
- ignoreSelectorsCount: options.ignoreSelectors?.length ?? 0,
2021
- tagsCount: options.tags?.length ?? 0
2022
- }
2023
- });
2024
- }
2025
- if (options.reporter.enabled) {
2026
- ChromaticReporter.apply(context.vitest, options);
2027
- }
2028
- if (!browser.enabled || browser.name !== "chromium") {
2029
- trackEvent2({
2030
- eventType: "project_ineligible",
2031
- level: "warn",
2032
- payload: { isBrowser: browser.enabled, isChromium: browser.name === "chromium" }
2033
- });
2034
- return clean();
2035
- }
2036
- ChromaticReporter.onPluginActivated(context.vitest);
2037
- if (options.turboSnap && !isMergeReports) {
2038
- WebpackStatsReporter.apply(context.vitest, options);
2039
- }
2040
- if (options.telemetry.enabled) {
2041
- TelemetryReporter.apply(context.vitest, options);
2042
- }
2043
- if (sequence.hooks === "stack") {
2044
- project.config.setupFiles.push(setupFile);
2045
- } else if (sequence.hooks === "list") {
2046
- project.config.setupFiles.unshift(setupFile);
2047
- } else {
2048
- trackEvent2({
2049
- eventType: "setup_files_parallel",
2050
- level: "warn",
2051
- payload: { setupFileCount: project.config.setupFiles.length }
2052
- });
2053
- project.config.setupFiles.push(setupFile);
2054
- context.vitest.logger.warn(
2055
- colors2.bgYellow(colors2.black(" chromatic ")),
2056
- colors2.yellow(
2057
- `Using { sequence.hooks: 'parallel' } may cause unstable snapshots. Please set 'sequence.hooks' to 'list' or 'stack' to ensure reliable snapshot ordering.`
2058
- )
2059
- );
2060
- }
2061
- if (options.tags && context.vitest.version.startsWith("4.0")) {
2062
- context.vitest.logger.warn(
2063
- colors2.bgYellow(colors2.black(" chromatic ")),
2064
- colors2.yellow(
2065
- `Tags cannot be used with Vitest ${context.vitest.version}. Please upgrade to Vitest 4.1 or later to use this feature.`
2066
- )
2067
- );
2068
- trackEvent2({ eventType: "tags_low_version", level: "warn", payload: {} });
2069
- }
2070
- if (options.tags) {
2071
- project.config.tags ||= [];
2072
- for (const tag of options.tags) {
2073
- const exists = project.config.tags.find((userTag) => userTag.name === tag);
2074
- if (!exists) {
2075
- project.config.tags.push({ name: tag, description: DEFAULT_TAG_DESCRIPTION });
2076
- }
2077
- }
2078
- }
2079
- if (isMergeReports) {
2080
- if (options.turboSnap) {
2081
- try {
2082
- await mergePreviewStats({
2083
- root: project.vitest.config.root,
2084
- outputDirectory: options.outputDirectory
2085
- });
2086
- } catch (error) {
2087
- trackEvent2({
2088
- eventType: "turbosnap_error",
2089
- level: "error",
2090
- payload: { operation: "merge-stats", error }
2091
- });
2092
- throw error;
2093
- }
2094
- }
2095
- } else {
2096
- clean();
2097
- }
2098
- project.onTestsRerun(async () => {
2099
- clean();
2100
- await project.browser?.triggerCommand("__chromatic_reset", {});
2101
- });
2102
- function clean() {
2103
- const outputDirectory = resolve8(project.vitest.config.root, options.outputDirectory);
2104
- rmSync2(resolve8(outputDirectory, "chromatic-archives"), { recursive: true, force: true });
2105
- cleanTelemetryLogFiles(outputDirectory);
2106
- if (existsSync4(outputDirectory)) {
2107
- for (const file of readdirSync(outputDirectory)) {
2108
- if (file.startsWith("preview-stats") && file.endsWith(".json")) {
2109
- rmSync2(resolve8(outputDirectory, file), { force: true });
2110
- }
2111
- }
2112
- }
2113
- }
2114
- function trackEvent2(event) {
2115
- trackEvent(event, context.vitest, options);
2116
- }
2117
- })
2118
- };
2119
- }
2120
- function withErrorTracking(options, configureVitest) {
2121
- return async (context) => {
2122
- try {
2123
- return await configureVitest(context);
2124
- } catch (error) {
2125
- trackEvent(
2126
- { eventType: "plugin_error", level: "error", payload: { operation: "configure", error } },
2127
- context.vitest,
2128
- options
2129
- );
2130
- throw error;
2131
- }
2132
- };
2133
- }
2134
- function resolveReporterOptions(reporter) {
2135
- if (reporter == void 0 || reporter === true) {
2136
- return { enabled: true, verbose: true };
2137
- }
2138
- if (reporter === false) {
2139
- return { enabled: false, verbose: false };
2140
- }
2141
- return {
2142
- enabled: reporter.enabled ?? true,
2143
- verbose: reporter.verbose ?? true
2144
- };
2145
- }
2146
- export {
2147
- chromaticPlugin
2148
- };