chunk-runtime-chain.0ab05798.mjs 74 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373
  1. import util$1 from 'util';
  2. import { i as isObject, b as getCallLastIndex, s as slash, g as getWorkerState, c as getNames, d as assertTypes, e as getFullName, f as isRunningInTest, n as noop, h as isRunningInBenchmark } from './chunk-mock-date.2917be60.mjs';
  3. import * as chai$2 from 'chai';
  4. import { expect, AssertionError, util } from 'chai';
  5. import { c as commonjsGlobal } from './vendor-_commonjsHelpers.4da45ef5.mjs';
  6. import { r as rpc } from './chunk-runtime-rpc.00a890d2.mjs';
  7. import fs, { promises } from 'fs';
  8. import { j as join, d as dirname, p as picocolors } from './chunk-constants.71e8a211.mjs';
  9. import { a as plugins_1, f as format_1, g as getOriginalPos, b as posToNumber, n as numberToPos, l as lineSplitRE, p as parseStacktrace, u as unifiedDiff, s as stringify, m as matcherUtils } from './chunk-utils-source-map.2be5aa48.mjs';
  10. import { isMockFunction } from './spy.mjs';
  11. import { s as safeSetTimeout, a as safeClearTimeout } from './chunk-utils-timers.b48455ed.mjs';
  12. function createChainable(keys, fn) {
  13. function create(context) {
  14. const chain2 = function(...args) {
  15. return fn.apply(context, args);
  16. };
  17. Object.assign(chain2, fn);
  18. chain2.withContext = () => chain2.bind(context);
  19. for (const key of keys) {
  20. Object.defineProperty(chain2, key, {
  21. get() {
  22. return create({ ...context, [key]: true });
  23. }
  24. });
  25. }
  26. return chain2;
  27. }
  28. const chain = create({});
  29. chain.fn = fn;
  30. return chain;
  31. }
  32. function commonjsRequire(path) {
  33. throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');
  34. }
  35. var chaiSubset = {exports: {}};
  36. (function (module, exports) {
  37. (function() {
  38. (function(chaiSubset) {
  39. if (typeof commonjsRequire === 'function' && 'object' === 'object' && 'object' === 'object') {
  40. return module.exports = chaiSubset;
  41. } else {
  42. return chai.use(chaiSubset);
  43. }
  44. })(function(chai, utils) {
  45. var Assertion = chai.Assertion;
  46. var assertionPrototype = Assertion.prototype;
  47. Assertion.addMethod('containSubset', function (expected) {
  48. var actual = utils.flag(this, 'object');
  49. var showDiff = chai.config.showDiff;
  50. assertionPrototype.assert.call(this,
  51. compare(expected, actual),
  52. 'expected #{act} to contain subset #{exp}',
  53. 'expected #{act} to not contain subset #{exp}',
  54. expected,
  55. actual,
  56. showDiff
  57. );
  58. });
  59. chai.assert.containSubset = function(val, exp, msg) {
  60. new chai.Assertion(val, msg).to.be.containSubset(exp);
  61. };
  62. function compare(expected, actual) {
  63. if (expected === actual) {
  64. return true;
  65. }
  66. if (typeof(actual) !== typeof(expected)) {
  67. return false;
  68. }
  69. if (typeof(expected) !== 'object' || expected === null) {
  70. return expected === actual;
  71. }
  72. if (!!expected && !actual) {
  73. return false;
  74. }
  75. if (Array.isArray(expected)) {
  76. if (typeof(actual.length) !== 'number') {
  77. return false;
  78. }
  79. var aa = Array.prototype.slice.call(actual);
  80. return expected.every(function (exp) {
  81. return aa.some(function (act) {
  82. return compare(exp, act);
  83. });
  84. });
  85. }
  86. if (expected instanceof Date) {
  87. if (actual instanceof Date) {
  88. return expected.getTime() === actual.getTime();
  89. } else {
  90. return false;
  91. }
  92. }
  93. return Object.keys(expected).every(function (key) {
  94. var eo = expected[key];
  95. var ao = actual[key];
  96. if (typeof(eo) === 'object' && eo !== null && ao !== null) {
  97. return compare(eo, ao);
  98. }
  99. if (typeof(eo) === 'function') {
  100. return eo(ao);
  101. }
  102. return ao === eo;
  103. });
  104. }
  105. });
  106. }).call(commonjsGlobal);
  107. } (chaiSubset));
  108. var Subset = chaiSubset.exports;
  109. function equals(a, b, customTesters, strictCheck) {
  110. customTesters = customTesters || [];
  111. return eq(a, b, [], [], customTesters, strictCheck ? hasKey : hasDefinedKey);
  112. }
  113. function isAsymmetric(obj) {
  114. return !!obj && isA("Function", obj.asymmetricMatch);
  115. }
  116. function asymmetricMatch(a, b) {
  117. const asymmetricA = isAsymmetric(a);
  118. const asymmetricB = isAsymmetric(b);
  119. if (asymmetricA && asymmetricB)
  120. return void 0;
  121. if (asymmetricA)
  122. return a.asymmetricMatch(b);
  123. if (asymmetricB)
  124. return b.asymmetricMatch(a);
  125. }
  126. function eq(a, b, aStack, bStack, customTesters, hasKey2) {
  127. let result = true;
  128. const asymmetricResult = asymmetricMatch(a, b);
  129. if (asymmetricResult !== void 0)
  130. return asymmetricResult;
  131. for (let i = 0; i < customTesters.length; i++) {
  132. const customTesterResult = customTesters[i](a, b);
  133. if (customTesterResult !== void 0)
  134. return customTesterResult;
  135. }
  136. if (a instanceof Error && b instanceof Error)
  137. return a.message === b.message;
  138. if (Object.is(a, b))
  139. return true;
  140. if (a === null || b === null)
  141. return a === b;
  142. const className = Object.prototype.toString.call(a);
  143. if (className !== Object.prototype.toString.call(b))
  144. return false;
  145. switch (className) {
  146. case "[object Boolean]":
  147. case "[object String]":
  148. case "[object Number]":
  149. if (typeof a !== typeof b) {
  150. return false;
  151. } else if (typeof a !== "object" && typeof b !== "object") {
  152. return Object.is(a, b);
  153. } else {
  154. return Object.is(a.valueOf(), b.valueOf());
  155. }
  156. case "[object Date]":
  157. return +a === +b;
  158. case "[object RegExp]":
  159. return a.source === b.source && a.flags === b.flags;
  160. }
  161. if (typeof a !== "object" || typeof b !== "object")
  162. return false;
  163. if (isDomNode(a) && isDomNode(b))
  164. return a.isEqualNode(b);
  165. let length = aStack.length;
  166. while (length--) {
  167. if (aStack[length] === a)
  168. return bStack[length] === b;
  169. else if (bStack[length] === b)
  170. return false;
  171. }
  172. aStack.push(a);
  173. bStack.push(b);
  174. if (className === "[object Array]" && a.length !== b.length)
  175. return false;
  176. const aKeys = keys(a, hasKey2);
  177. let key;
  178. let size = aKeys.length;
  179. if (keys(b, hasKey2).length !== size)
  180. return false;
  181. while (size--) {
  182. key = aKeys[size];
  183. result = hasKey2(b, key) && eq(a[key], b[key], aStack, bStack, customTesters, hasKey2);
  184. if (!result)
  185. return false;
  186. }
  187. aStack.pop();
  188. bStack.pop();
  189. return result;
  190. }
  191. function keys(obj, hasKey2) {
  192. const keys2 = [];
  193. for (const key in obj) {
  194. if (hasKey2(obj, key))
  195. keys2.push(key);
  196. }
  197. return keys2.concat(
  198. Object.getOwnPropertySymbols(obj).filter(
  199. (symbol) => Object.getOwnPropertyDescriptor(obj, symbol).enumerable
  200. )
  201. );
  202. }
  203. function hasDefinedKey(obj, key) {
  204. return hasKey(obj, key) && obj[key] !== void 0;
  205. }
  206. function hasKey(obj, key) {
  207. return Object.prototype.hasOwnProperty.call(obj, key);
  208. }
  209. function isA(typeName, value) {
  210. return Object.prototype.toString.apply(value) === `[object ${typeName}]`;
  211. }
  212. function isDomNode(obj) {
  213. return obj !== null && typeof obj === "object" && typeof obj.nodeType === "number" && typeof obj.nodeName === "string" && typeof obj.isEqualNode === "function";
  214. }
  215. const IS_KEYED_SENTINEL = "@@__IMMUTABLE_KEYED__@@";
  216. const IS_SET_SENTINEL = "@@__IMMUTABLE_SET__@@";
  217. const IS_ORDERED_SENTINEL = "@@__IMMUTABLE_ORDERED__@@";
  218. function isImmutableUnorderedKeyed(maybeKeyed) {
  219. return !!(maybeKeyed && maybeKeyed[IS_KEYED_SENTINEL] && !maybeKeyed[IS_ORDERED_SENTINEL]);
  220. }
  221. function isImmutableUnorderedSet(maybeSet) {
  222. return !!(maybeSet && maybeSet[IS_SET_SENTINEL] && !maybeSet[IS_ORDERED_SENTINEL]);
  223. }
  224. const IteratorSymbol = Symbol.iterator;
  225. const hasIterator = (object) => !!(object != null && object[IteratorSymbol]);
  226. const iterableEquality = (a, b, aStack = [], bStack = []) => {
  227. if (typeof a !== "object" || typeof b !== "object" || Array.isArray(a) || Array.isArray(b) || !hasIterator(a) || !hasIterator(b))
  228. return void 0;
  229. if (a.constructor !== b.constructor)
  230. return false;
  231. let length = aStack.length;
  232. while (length--) {
  233. if (aStack[length] === a)
  234. return bStack[length] === b;
  235. }
  236. aStack.push(a);
  237. bStack.push(b);
  238. const iterableEqualityWithStack = (a2, b2) => iterableEquality(a2, b2, [...aStack], [...bStack]);
  239. if (a.size !== void 0) {
  240. if (a.size !== b.size) {
  241. return false;
  242. } else if (isA("Set", a) || isImmutableUnorderedSet(a)) {
  243. let allFound = true;
  244. for (const aValue of a) {
  245. if (!b.has(aValue)) {
  246. let has = false;
  247. for (const bValue of b) {
  248. const isEqual = equals(aValue, bValue, [iterableEqualityWithStack]);
  249. if (isEqual === true)
  250. has = true;
  251. }
  252. if (has === false) {
  253. allFound = false;
  254. break;
  255. }
  256. }
  257. }
  258. aStack.pop();
  259. bStack.pop();
  260. return allFound;
  261. } else if (isA("Map", a) || isImmutableUnorderedKeyed(a)) {
  262. let allFound = true;
  263. for (const aEntry of a) {
  264. if (!b.has(aEntry[0]) || !equals(aEntry[1], b.get(aEntry[0]), [iterableEqualityWithStack])) {
  265. let has = false;
  266. for (const bEntry of b) {
  267. const matchedKey = equals(aEntry[0], bEntry[0], [
  268. iterableEqualityWithStack
  269. ]);
  270. let matchedValue = false;
  271. if (matchedKey === true) {
  272. matchedValue = equals(aEntry[1], bEntry[1], [
  273. iterableEqualityWithStack
  274. ]);
  275. }
  276. if (matchedValue === true)
  277. has = true;
  278. }
  279. if (has === false) {
  280. allFound = false;
  281. break;
  282. }
  283. }
  284. }
  285. aStack.pop();
  286. bStack.pop();
  287. return allFound;
  288. }
  289. }
  290. const bIterator = b[IteratorSymbol]();
  291. for (const aValue of a) {
  292. const nextB = bIterator.next();
  293. if (nextB.done || !equals(aValue, nextB.value, [iterableEqualityWithStack]))
  294. return false;
  295. }
  296. if (!bIterator.next().done)
  297. return false;
  298. aStack.pop();
  299. bStack.pop();
  300. return true;
  301. };
  302. const hasPropertyInObject = (object, key) => {
  303. const shouldTerminate = !object || typeof object !== "object" || object === Object.prototype;
  304. if (shouldTerminate)
  305. return false;
  306. return Object.prototype.hasOwnProperty.call(object, key) || hasPropertyInObject(Object.getPrototypeOf(object), key);
  307. };
  308. const isObjectWithKeys = (a) => isObject(a) && !(a instanceof Error) && !Array.isArray(a) && !(a instanceof Date);
  309. const subsetEquality = (object, subset) => {
  310. const subsetEqualityWithContext = (seenReferences = /* @__PURE__ */ new WeakMap()) => (object2, subset2) => {
  311. if (!isObjectWithKeys(subset2))
  312. return void 0;
  313. return Object.keys(subset2).every((key) => {
  314. if (isObjectWithKeys(subset2[key])) {
  315. if (seenReferences.has(subset2[key]))
  316. return equals(object2[key], subset2[key], [iterableEquality]);
  317. seenReferences.set(subset2[key], true);
  318. }
  319. const result = object2 != null && hasPropertyInObject(object2, key) && equals(object2[key], subset2[key], [
  320. iterableEquality,
  321. subsetEqualityWithContext(seenReferences)
  322. ]);
  323. seenReferences.delete(subset2[key]);
  324. return result;
  325. });
  326. };
  327. return subsetEqualityWithContext()(object, subset);
  328. };
  329. const typeEquality = (a, b) => {
  330. if (a == null || b == null || a.constructor === b.constructor)
  331. return void 0;
  332. return false;
  333. };
  334. const arrayBufferEquality = (a, b) => {
  335. if (!(a instanceof ArrayBuffer) || !(b instanceof ArrayBuffer))
  336. return void 0;
  337. const dataViewA = new DataView(a);
  338. const dataViewB = new DataView(b);
  339. if (dataViewA.byteLength !== dataViewB.byteLength)
  340. return false;
  341. for (let i = 0; i < dataViewA.byteLength; i++) {
  342. if (dataViewA.getUint8(i) !== dataViewB.getUint8(i))
  343. return false;
  344. }
  345. return true;
  346. };
  347. const sparseArrayEquality = (a, b) => {
  348. if (!Array.isArray(a) || !Array.isArray(b))
  349. return void 0;
  350. const aKeys = Object.keys(a);
  351. const bKeys = Object.keys(b);
  352. return equals(a, b, [iterableEquality, typeEquality], true) && equals(aKeys, bKeys);
  353. };
  354. const generateToBeMessage = (deepEqualityName, expected = "#{this}", actual = "#{exp}") => {
  355. const toBeMessage = `expected ${expected} to be ${actual} // Object.is equality`;
  356. if (["toStrictEqual", "toEqual"].includes(deepEqualityName))
  357. return `${toBeMessage}
  358. If it should pass with deep equality, replace "toBe" with "${deepEqualityName}"
  359. Expected: ${expected}
  360. Received: serializes to the same string
  361. `;
  362. return toBeMessage;
  363. };
  364. var naturalCompare$1 = {exports: {}};
  365. /*
  366. * @version 1.4.0
  367. * @date 2015-10-26
  368. * @stability 3 - Stable
  369. * @author Lauri Rooden (https://github.com/litejs/natural-compare-lite)
  370. * @license MIT License
  371. */
  372. var naturalCompare = function(a, b) {
  373. var i, codeA
  374. , codeB = 1
  375. , posA = 0
  376. , posB = 0
  377. , alphabet = String.alphabet;
  378. function getCode(str, pos, code) {
  379. if (code) {
  380. for (i = pos; code = getCode(str, i), code < 76 && code > 65;) ++i;
  381. return +str.slice(pos - 1, i)
  382. }
  383. code = alphabet && alphabet.indexOf(str.charAt(pos));
  384. return code > -1 ? code + 76 : ((code = str.charCodeAt(pos) || 0), code < 45 || code > 127) ? code
  385. : code < 46 ? 65 // -
  386. : code < 48 ? code - 1
  387. : code < 58 ? code + 18 // 0-9
  388. : code < 65 ? code - 11
  389. : code < 91 ? code + 11 // A-Z
  390. : code < 97 ? code - 37
  391. : code < 123 ? code + 5 // a-z
  392. : code - 63
  393. }
  394. if ((a+="") != (b+="")) for (;codeB;) {
  395. codeA = getCode(a, posA++);
  396. codeB = getCode(b, posB++);
  397. if (codeA < 76 && codeB < 76 && codeA > 66 && codeB > 66) {
  398. codeA = getCode(a, posA, posA);
  399. codeB = getCode(b, posB, posA = i);
  400. posB = i;
  401. }
  402. if (codeA != codeB) return (codeA < codeB) ? -1 : 1
  403. }
  404. return 0
  405. };
  406. try {
  407. naturalCompare$1.exports = naturalCompare;
  408. } catch (e) {
  409. String.naturalCompare = naturalCompare;
  410. }
  411. const serialize$1 = (val, config, indentation, depth, refs, printer) => {
  412. const name = val.getMockName();
  413. const nameString = name === "vi.fn()" ? "" : ` ${name}`;
  414. let callsString = "";
  415. if (val.mock.calls.length !== 0) {
  416. const indentationNext = indentation + config.indent;
  417. callsString = ` {${config.spacingOuter}${indentationNext}"calls": ${printer(val.mock.calls, config, indentationNext, depth, refs)}${config.min ? ", " : ","}${config.spacingOuter}${indentationNext}"results": ${printer(val.mock.results, config, indentationNext, depth, refs)}${config.min ? "" : ","}${config.spacingOuter}${indentation}}`;
  418. }
  419. return `[MockFunction${nameString}]${callsString}`;
  420. };
  421. const test$1 = (val) => val && !!val._isMockFunction;
  422. const plugin = { serialize: serialize$1, test: test$1 };
  423. const {
  424. DOMCollection,
  425. DOMElement,
  426. Immutable,
  427. ReactElement,
  428. ReactTestComponent,
  429. AsymmetricMatcher: AsymmetricMatcher$1
  430. } = plugins_1;
  431. let PLUGINS = [
  432. ReactTestComponent,
  433. ReactElement,
  434. DOMElement,
  435. DOMCollection,
  436. Immutable,
  437. AsymmetricMatcher$1,
  438. plugin
  439. ];
  440. const addSerializer = (plugin) => {
  441. PLUGINS = [plugin].concat(PLUGINS);
  442. };
  443. const getSerializers = () => PLUGINS;
  444. const SNAPSHOT_VERSION = "1";
  445. const writeSnapshotVersion = () => `// Vitest Snapshot v${SNAPSHOT_VERSION}`;
  446. const testNameToKey = (testName, count) => `${testName} ${count}`;
  447. const keyToTestName = (key) => {
  448. if (!/ \d+$/.test(key))
  449. throw new Error("Snapshot keys must end with a number.");
  450. return key.replace(/ \d+$/, "");
  451. };
  452. const getSnapshotData = (snapshotPath, update) => {
  453. const data = /* @__PURE__ */ Object.create(null);
  454. let snapshotContents = "";
  455. let dirty = false;
  456. if (fs.existsSync(snapshotPath)) {
  457. try {
  458. snapshotContents = fs.readFileSync(snapshotPath, "utf8");
  459. const populate = new Function("exports", snapshotContents);
  460. populate(data);
  461. } catch {
  462. }
  463. }
  464. const isInvalid = snapshotContents;
  465. if ((update === "all" || update === "new") && isInvalid)
  466. dirty = true;
  467. return { data, dirty };
  468. };
  469. const addExtraLineBreaks = (string) => string.includes("\n") ? `
  470. ${string}
  471. ` : string;
  472. const removeExtraLineBreaks = (string) => string.length > 2 && string.startsWith("\n") && string.endsWith("\n") ? string.slice(1, -1) : string;
  473. const escapeRegex = true;
  474. const printFunctionName = false;
  475. function serialize(val, indent = 2, formatOverrides = {}) {
  476. return normalizeNewlines(
  477. format_1(val, {
  478. escapeRegex,
  479. indent,
  480. plugins: getSerializers(),
  481. printFunctionName,
  482. ...formatOverrides
  483. })
  484. );
  485. }
  486. function escapeBacktickString(str) {
  487. return str.replace(/`|\\|\${/g, "\\$&");
  488. }
  489. function printBacktickString(str) {
  490. return `\`${escapeBacktickString(str)}\``;
  491. }
  492. function ensureDirectoryExists(filePath) {
  493. try {
  494. fs.mkdirSync(join(dirname(filePath)), { recursive: true });
  495. } catch {
  496. }
  497. }
  498. function normalizeNewlines(string) {
  499. return string.replace(/\r\n|\r/g, "\n");
  500. }
  501. async function saveSnapshotFile(snapshotData, snapshotPath) {
  502. var _a, _b;
  503. const snapshots = Object.keys(snapshotData).sort(naturalCompare$1.exports).map(
  504. (key) => `exports[${printBacktickString(key)}] = ${printBacktickString(normalizeNewlines(snapshotData[key]))};`
  505. );
  506. const content = `${writeSnapshotVersion()}
  507. ${snapshots.join("\n\n")}
  508. `;
  509. const skipWriting = fs.existsSync(snapshotPath) && await ((_a = fs) == null ? void 0 : _a.promises.readFile(snapshotPath, "utf8")) === content;
  510. if (skipWriting)
  511. return;
  512. ensureDirectoryExists(snapshotPath);
  513. await ((_b = fs) == null ? void 0 : _b.promises.writeFile(
  514. snapshotPath,
  515. content,
  516. "utf-8"
  517. ));
  518. }
  519. function prepareExpected(expected) {
  520. function findStartIndent() {
  521. var _a, _b;
  522. const matchObject = /^( +)}\s+$/m.exec(expected || "");
  523. const objectIndent = (_a = matchObject == null ? void 0 : matchObject[1]) == null ? void 0 : _a.length;
  524. if (objectIndent)
  525. return objectIndent;
  526. const matchText = /^\n( +)"/.exec(expected || "");
  527. return ((_b = matchText == null ? void 0 : matchText[1]) == null ? void 0 : _b.length) || 0;
  528. }
  529. const startIndent = findStartIndent();
  530. let expectedTrimmed = expected == null ? void 0 : expected.trim();
  531. if (startIndent) {
  532. expectedTrimmed = expectedTrimmed == null ? void 0 : expectedTrimmed.replace(new RegExp(`^${" ".repeat(startIndent)}`, "gm"), "").replace(/ +}$/, "}");
  533. }
  534. return expectedTrimmed;
  535. }
  536. function deepMergeArray(target = [], source = []) {
  537. const mergedOutput = Array.from(target);
  538. source.forEach((sourceElement, index) => {
  539. const targetElement = mergedOutput[index];
  540. if (Array.isArray(target[index])) {
  541. mergedOutput[index] = deepMergeArray(target[index], sourceElement);
  542. } else if (isObject(targetElement)) {
  543. mergedOutput[index] = deepMergeSnapshot(target[index], sourceElement);
  544. } else {
  545. mergedOutput[index] = sourceElement;
  546. }
  547. });
  548. return mergedOutput;
  549. }
  550. function deepMergeSnapshot(target, source) {
  551. if (isObject(target) && isObject(source)) {
  552. const mergedOutput = { ...target };
  553. Object.keys(source).forEach((key) => {
  554. if (isObject(source[key]) && !source[key].$$typeof) {
  555. if (!(key in target))
  556. Object.assign(mergedOutput, { [key]: source[key] });
  557. else
  558. mergedOutput[key] = deepMergeSnapshot(target[key], source[key]);
  559. } else if (Array.isArray(source[key])) {
  560. mergedOutput[key] = deepMergeArray(target[key], source[key]);
  561. } else {
  562. Object.assign(mergedOutput, { [key]: source[key] });
  563. }
  564. });
  565. return mergedOutput;
  566. } else if (Array.isArray(target) && Array.isArray(source)) {
  567. return deepMergeArray(target, source);
  568. }
  569. return target;
  570. }
  571. async function saveInlineSnapshots(snapshots) {
  572. const MagicString = (await import('./chunk-magic-string.56b2b543.mjs')).default;
  573. const files = new Set(snapshots.map((i) => i.file));
  574. await Promise.all(Array.from(files).map(async (file) => {
  575. const map = await rpc().getSourceMap(file);
  576. const snaps = snapshots.filter((i) => i.file === file);
  577. const code = await promises.readFile(file, "utf8");
  578. const s = new MagicString(code);
  579. for (const snap of snaps) {
  580. const pos = await getOriginalPos(map, snap);
  581. const index = posToNumber(code, pos);
  582. replaceInlineSnap(code, s, index, snap.snapshot);
  583. }
  584. const transformed = s.toString();
  585. if (transformed !== code)
  586. await promises.writeFile(file, transformed, "utf-8");
  587. }));
  588. }
  589. const startObjectRegex = /(?:toMatchInlineSnapshot|toThrowErrorMatchingInlineSnapshot)\s*\(\s*({)/m;
  590. function replaceObjectSnap(code, s, index, newSnap) {
  591. code = code.slice(index);
  592. const startMatch = startObjectRegex.exec(code);
  593. if (!startMatch)
  594. return false;
  595. code = code.slice(startMatch.index);
  596. const charIndex = getCallLastIndex(code);
  597. if (charIndex === null)
  598. return false;
  599. s.appendLeft(index + startMatch.index + charIndex, `, ${prepareSnapString(newSnap, code, index)}`);
  600. return true;
  601. }
  602. function prepareSnapString(snap, source, index) {
  603. const lineIndex = numberToPos(source, index).line;
  604. const line = source.split(lineSplitRE)[lineIndex - 1];
  605. const indent = line.match(/^\s*/)[0] || "";
  606. const indentNext = indent.includes(" ") ? `${indent} ` : `${indent} `;
  607. const lines = snap.trim().replace(/\\/g, "\\\\").split(/\n/g);
  608. const isOneline = lines.length <= 1;
  609. const quote = isOneline ? "'" : "`";
  610. if (isOneline)
  611. return `'${lines.join("\n").replace(/'/g, "\\'")}'`;
  612. else
  613. return `${quote}
  614. ${lines.map((i) => i ? indentNext + i : "").join("\n").replace(/`/g, "\\`").replace(/\${/g, "\\${")}
  615. ${indent}${quote}`;
  616. }
  617. const startRegex = /(?:toMatchInlineSnapshot|toThrowErrorMatchingInlineSnapshot)\s*\(\s*[\w_$]*(['"`\)])/m;
  618. function replaceInlineSnap(code, s, index, newSnap) {
  619. const startMatch = startRegex.exec(code.slice(index));
  620. if (!startMatch)
  621. return replaceObjectSnap(code, s, index, newSnap);
  622. const quote = startMatch[1];
  623. const startIndex = index + startMatch.index + startMatch[0].length;
  624. const snapString = prepareSnapString(newSnap, code, index);
  625. if (quote === ")") {
  626. s.appendRight(startIndex - 1, snapString);
  627. return true;
  628. }
  629. const quoteEndRE = new RegExp(`(?:^|[^\\\\])${quote}`);
  630. const endMatch = quoteEndRE.exec(code.slice(startIndex));
  631. if (!endMatch)
  632. return false;
  633. const endIndex = startIndex + endMatch.index + endMatch[0].length;
  634. s.overwrite(startIndex - 1, endIndex, snapString);
  635. return true;
  636. }
  637. const INDENTATION_REGEX = /^([^\S\n]*)\S/m;
  638. function stripSnapshotIndentation(inlineSnapshot) {
  639. const match = inlineSnapshot.match(INDENTATION_REGEX);
  640. if (!match || !match[1]) {
  641. return inlineSnapshot;
  642. }
  643. const indentation = match[1];
  644. const lines = inlineSnapshot.split(/\n/g);
  645. if (lines.length <= 2) {
  646. return inlineSnapshot;
  647. }
  648. if (lines[0].trim() !== "" || lines[lines.length - 1].trim() !== "") {
  649. return inlineSnapshot;
  650. }
  651. for (let i = 1; i < lines.length - 1; i++) {
  652. if (lines[i] !== "") {
  653. if (lines[i].indexOf(indentation) !== 0) {
  654. return inlineSnapshot;
  655. }
  656. lines[i] = lines[i].substring(indentation.length);
  657. }
  658. }
  659. lines[lines.length - 1] = "";
  660. inlineSnapshot = lines.join("\n");
  661. return inlineSnapshot;
  662. }
  663. class SnapshotState {
  664. constructor(testFilePath, snapshotPath, options) {
  665. this.testFilePath = testFilePath;
  666. this.snapshotPath = snapshotPath;
  667. const { data, dirty } = getSnapshotData(
  668. this.snapshotPath,
  669. options.updateSnapshot
  670. );
  671. this._initialData = data;
  672. this._snapshotData = data;
  673. this._dirty = dirty;
  674. this._inlineSnapshots = [];
  675. this._uncheckedKeys = new Set(Object.keys(this._snapshotData));
  676. this._counters = /* @__PURE__ */ new Map();
  677. this.expand = options.expand || false;
  678. this.added = 0;
  679. this.matched = 0;
  680. this.unmatched = 0;
  681. this._updateSnapshot = options.updateSnapshot;
  682. this.updated = 0;
  683. this._snapshotFormat = {
  684. printBasicPrototype: false,
  685. ...options.snapshotFormat
  686. };
  687. }
  688. markSnapshotsAsCheckedForTest(testName) {
  689. this._uncheckedKeys.forEach((uncheckedKey) => {
  690. if (keyToTestName(uncheckedKey) === testName)
  691. this._uncheckedKeys.delete(uncheckedKey);
  692. });
  693. }
  694. _inferInlineSnapshotStack(stacks) {
  695. const promiseIndex = stacks.findIndex((i) => i.method.match(/__VITEST_(RESOLVES|REJECTS)__/));
  696. if (promiseIndex !== -1)
  697. return stacks[promiseIndex + 3];
  698. const stackIndex = stacks.findIndex((i) => i.method.includes("__VITEST_INLINE_SNAPSHOT__"));
  699. return stackIndex !== -1 ? stacks[stackIndex + 2] : null;
  700. }
  701. _addSnapshot(key, receivedSerialized, options) {
  702. this._dirty = true;
  703. if (options.isInline) {
  704. const error = options.error || new Error("Unknown error");
  705. const stacks = parseStacktrace(error, true);
  706. stacks.forEach((i) => i.file = slash(i.file));
  707. const stack = this._inferInlineSnapshotStack(stacks);
  708. if (!stack) {
  709. throw new Error(
  710. `Vitest: Couldn't infer stack frame for inline snapshot.
  711. ${JSON.stringify(stacks)}`
  712. );
  713. }
  714. stack.column--;
  715. this._inlineSnapshots.push({
  716. snapshot: receivedSerialized,
  717. ...stack
  718. });
  719. } else {
  720. this._snapshotData[key] = receivedSerialized;
  721. }
  722. }
  723. clear() {
  724. this._snapshotData = this._initialData;
  725. this._counters = /* @__PURE__ */ new Map();
  726. this.added = 0;
  727. this.matched = 0;
  728. this.unmatched = 0;
  729. this.updated = 0;
  730. this._dirty = false;
  731. }
  732. async save() {
  733. const hasExternalSnapshots = Object.keys(this._snapshotData).length;
  734. const hasInlineSnapshots = this._inlineSnapshots.length;
  735. const isEmpty = !hasExternalSnapshots && !hasInlineSnapshots;
  736. const status = {
  737. deleted: false,
  738. saved: false
  739. };
  740. if ((this._dirty || this._uncheckedKeys.size) && !isEmpty) {
  741. if (hasExternalSnapshots)
  742. await saveSnapshotFile(this._snapshotData, this.snapshotPath);
  743. if (hasInlineSnapshots)
  744. await saveInlineSnapshots(this._inlineSnapshots);
  745. status.saved = true;
  746. } else if (!hasExternalSnapshots && fs.existsSync(this.snapshotPath)) {
  747. if (this._updateSnapshot === "all")
  748. fs.unlinkSync(this.snapshotPath);
  749. status.deleted = true;
  750. }
  751. return status;
  752. }
  753. getUncheckedCount() {
  754. return this._uncheckedKeys.size || 0;
  755. }
  756. getUncheckedKeys() {
  757. return Array.from(this._uncheckedKeys);
  758. }
  759. removeUncheckedKeys() {
  760. if (this._updateSnapshot === "all" && this._uncheckedKeys.size) {
  761. this._dirty = true;
  762. this._uncheckedKeys.forEach((key) => delete this._snapshotData[key]);
  763. this._uncheckedKeys.clear();
  764. }
  765. }
  766. match({
  767. testName,
  768. received,
  769. key,
  770. inlineSnapshot,
  771. isInline,
  772. error
  773. }) {
  774. this._counters.set(testName, (this._counters.get(testName) || 0) + 1);
  775. const count = Number(this._counters.get(testName));
  776. if (!key)
  777. key = testNameToKey(testName, count);
  778. if (!(isInline && this._snapshotData[key] !== void 0))
  779. this._uncheckedKeys.delete(key);
  780. const receivedSerialized = addExtraLineBreaks(serialize(received, void 0, this._snapshotFormat));
  781. const expected = isInline ? inlineSnapshot : this._snapshotData[key];
  782. const expectedTrimmed = prepareExpected(expected);
  783. const pass = expectedTrimmed === prepareExpected(receivedSerialized);
  784. const hasSnapshot = expected !== void 0;
  785. const snapshotIsPersisted = isInline || fs.existsSync(this.snapshotPath);
  786. if (pass && !isInline) {
  787. this._snapshotData[key] = receivedSerialized;
  788. }
  789. if (hasSnapshot && this._updateSnapshot === "all" || (!hasSnapshot || !snapshotIsPersisted) && (this._updateSnapshot === "new" || this._updateSnapshot === "all")) {
  790. if (this._updateSnapshot === "all") {
  791. if (!pass) {
  792. if (hasSnapshot)
  793. this.updated++;
  794. else
  795. this.added++;
  796. this._addSnapshot(key, receivedSerialized, { error, isInline });
  797. } else {
  798. this.matched++;
  799. }
  800. } else {
  801. this._addSnapshot(key, receivedSerialized, { error, isInline });
  802. this.added++;
  803. }
  804. return {
  805. actual: "",
  806. count,
  807. expected: "",
  808. key,
  809. pass: true
  810. };
  811. } else {
  812. if (!pass) {
  813. this.unmatched++;
  814. return {
  815. actual: removeExtraLineBreaks(receivedSerialized),
  816. count,
  817. expected: expectedTrimmed !== void 0 ? removeExtraLineBreaks(expectedTrimmed) : void 0,
  818. key,
  819. pass: false
  820. };
  821. } else {
  822. this.matched++;
  823. return {
  824. actual: "",
  825. count,
  826. expected: "",
  827. key,
  828. pass: true
  829. };
  830. }
  831. }
  832. }
  833. async pack() {
  834. const snapshot = {
  835. filepath: this.testFilePath,
  836. added: 0,
  837. fileDeleted: false,
  838. matched: 0,
  839. unchecked: 0,
  840. uncheckedKeys: [],
  841. unmatched: 0,
  842. updated: 0
  843. };
  844. const uncheckedCount = this.getUncheckedCount();
  845. const uncheckedKeys = this.getUncheckedKeys();
  846. if (uncheckedCount)
  847. this.removeUncheckedKeys();
  848. const status = await this.save();
  849. snapshot.fileDeleted = status.deleted;
  850. snapshot.added = this.added;
  851. snapshot.matched = this.matched;
  852. snapshot.unmatched = this.unmatched;
  853. snapshot.updated = this.updated;
  854. snapshot.unchecked = !status.deleted ? uncheckedCount : 0;
  855. snapshot.uncheckedKeys = Array.from(uncheckedKeys);
  856. return snapshot;
  857. }
  858. }
  859. class SnapshotClient {
  860. constructor() {
  861. this.snapshotStateMap = /* @__PURE__ */ new Map();
  862. }
  863. async setTest(test) {
  864. var _a;
  865. this.test = test;
  866. if (((_a = this.snapshotState) == null ? void 0 : _a.testFilePath) !== this.test.file.filepath) {
  867. this.saveCurrent();
  868. const filePath = this.test.file.filepath;
  869. if (!this.getSnapshotState(test)) {
  870. this.snapshotStateMap.set(
  871. filePath,
  872. new SnapshotState(
  873. filePath,
  874. await rpc().resolveSnapshotPath(filePath),
  875. getWorkerState().config.snapshotOptions
  876. )
  877. );
  878. }
  879. this.snapshotState = this.getSnapshotState(test);
  880. }
  881. }
  882. getSnapshotState(test) {
  883. return this.snapshotStateMap.get(test.file.filepath);
  884. }
  885. clearTest() {
  886. this.test = void 0;
  887. }
  888. skipTestSnapshots(test) {
  889. var _a;
  890. (_a = this.snapshotState) == null ? void 0 : _a.markSnapshotsAsCheckedForTest(test.name);
  891. }
  892. assert(options) {
  893. const {
  894. test = this.test,
  895. message,
  896. isInline = false,
  897. properties,
  898. inlineSnapshot,
  899. error,
  900. errorMessage
  901. } = options;
  902. let { received } = options;
  903. if (!test)
  904. throw new Error("Snapshot cannot be used outside of test");
  905. if (typeof properties === "object") {
  906. if (typeof received !== "object" || !received)
  907. throw new Error("Received value must be an object when the matcher has properties");
  908. try {
  909. const pass2 = equals(received, properties, [iterableEquality, subsetEquality]);
  910. if (!pass2)
  911. expect(received).equals(properties);
  912. else
  913. received = deepMergeSnapshot(received, properties);
  914. } catch (err) {
  915. err.message = errorMessage || "Snapshot mismatched";
  916. throw err;
  917. }
  918. }
  919. const testName = [
  920. ...getNames(test).slice(1),
  921. ...message ? [message] : []
  922. ].join(" > ");
  923. const snapshotState = this.getSnapshotState(test);
  924. const { actual, expected, key, pass } = snapshotState.match({
  925. testName,
  926. received,
  927. isInline,
  928. error,
  929. inlineSnapshot
  930. });
  931. if (!pass) {
  932. try {
  933. expect(actual.trim()).equals(expected ? expected.trim() : "");
  934. } catch (error2) {
  935. error2.message = errorMessage || `Snapshot \`${key || "unknown"}\` mismatched`;
  936. throw error2;
  937. }
  938. }
  939. }
  940. async saveCurrent() {
  941. if (!this.snapshotState)
  942. return;
  943. const result = await this.snapshotState.pack();
  944. await rpc().snapshotSaved(result);
  945. this.snapshotState = void 0;
  946. }
  947. clear() {
  948. this.snapshotStateMap.clear();
  949. }
  950. }
  951. let _client;
  952. function getSnapshotClient() {
  953. if (!_client)
  954. _client = new SnapshotClient();
  955. return _client;
  956. }
  957. const getErrorMessage = (err) => {
  958. if (err instanceof Error)
  959. return err.message;
  960. return err;
  961. };
  962. const getErrorString = (expected, promise) => {
  963. if (typeof expected !== "function") {
  964. if (!promise)
  965. throw new Error(`expected must be a function, received ${typeof expected}`);
  966. return getErrorMessage(expected);
  967. }
  968. try {
  969. expected();
  970. } catch (e) {
  971. return getErrorMessage(e);
  972. }
  973. throw new Error("snapshot function didn't throw");
  974. };
  975. const SnapshotPlugin = (chai, utils) => {
  976. for (const key of ["matchSnapshot", "toMatchSnapshot"]) {
  977. utils.addMethod(
  978. chai.Assertion.prototype,
  979. key,
  980. function(properties, message) {
  981. const expected = utils.flag(this, "object");
  982. const test = utils.flag(this, "vitest-test");
  983. if (typeof properties === "string" && typeof message === "undefined") {
  984. message = properties;
  985. properties = void 0;
  986. }
  987. const errorMessage = utils.flag(this, "message");
  988. getSnapshotClient().assert({
  989. received: expected,
  990. test,
  991. message,
  992. isInline: false,
  993. properties,
  994. errorMessage
  995. });
  996. }
  997. );
  998. }
  999. utils.addMethod(
  1000. chai.Assertion.prototype,
  1001. "toMatchInlineSnapshot",
  1002. function __VITEST_INLINE_SNAPSHOT__(properties, inlineSnapshot, message) {
  1003. const expected = utils.flag(this, "object");
  1004. const error = utils.flag(this, "error");
  1005. const test = utils.flag(this, "vitest-test");
  1006. if (typeof properties === "string") {
  1007. message = inlineSnapshot;
  1008. inlineSnapshot = properties;
  1009. properties = void 0;
  1010. }
  1011. if (inlineSnapshot)
  1012. inlineSnapshot = stripSnapshotIndentation(inlineSnapshot);
  1013. const errorMessage = utils.flag(this, "message");
  1014. getSnapshotClient().assert({
  1015. received: expected,
  1016. test,
  1017. message,
  1018. isInline: true,
  1019. properties,
  1020. inlineSnapshot,
  1021. error,
  1022. errorMessage
  1023. });
  1024. }
  1025. );
  1026. utils.addMethod(
  1027. chai.Assertion.prototype,
  1028. "toThrowErrorMatchingSnapshot",
  1029. function(message) {
  1030. const expected = utils.flag(this, "object");
  1031. const test = utils.flag(this, "vitest-test");
  1032. const promise = utils.flag(this, "promise");
  1033. const errorMessage = utils.flag(this, "message");
  1034. getSnapshotClient().assert({
  1035. received: getErrorString(expected, promise),
  1036. test,
  1037. message,
  1038. errorMessage
  1039. });
  1040. }
  1041. );
  1042. utils.addMethod(
  1043. chai.Assertion.prototype,
  1044. "toThrowErrorMatchingInlineSnapshot",
  1045. function __VITEST_INLINE_SNAPSHOT__(inlineSnapshot, message) {
  1046. const expected = utils.flag(this, "object");
  1047. const error = utils.flag(this, "error");
  1048. const test = utils.flag(this, "vitest-test");
  1049. const promise = utils.flag(this, "promise");
  1050. const errorMessage = utils.flag(this, "message");
  1051. getSnapshotClient().assert({
  1052. received: getErrorString(expected, promise),
  1053. test,
  1054. message,
  1055. inlineSnapshot,
  1056. isInline: true,
  1057. error,
  1058. errorMessage
  1059. });
  1060. }
  1061. );
  1062. };
  1063. var chai$1 = /*#__PURE__*/Object.freeze({
  1064. __proto__: null,
  1065. getSnapshotClient: getSnapshotClient,
  1066. SnapshotPlugin: SnapshotPlugin
  1067. });
  1068. const GLOBAL_EXPECT = Symbol.for("expect-global");
  1069. const MATCHERS_OBJECT = Symbol.for("matchers-object");
  1070. const JEST_MATCHERS_OBJECT = Symbol.for("$$jest-matchers-object");
  1071. if (!Object.prototype.hasOwnProperty.call(globalThis, MATCHERS_OBJECT)) {
  1072. const globalState = /* @__PURE__ */ new WeakMap();
  1073. const matchers = /* @__PURE__ */ Object.create(null);
  1074. Object.defineProperty(globalThis, MATCHERS_OBJECT, {
  1075. get: () => globalState
  1076. });
  1077. Object.defineProperty(globalThis, JEST_MATCHERS_OBJECT, {
  1078. configurable: true,
  1079. get: () => ({
  1080. state: globalState.get(globalThis[GLOBAL_EXPECT]),
  1081. matchers
  1082. })
  1083. });
  1084. }
  1085. const getState = (expect) => globalThis[MATCHERS_OBJECT].get(expect);
  1086. const setState = (state, expect) => {
  1087. const map = globalThis[MATCHERS_OBJECT];
  1088. const current = map.get(expect) || {};
  1089. Object.assign(current, state);
  1090. map.set(expect, current);
  1091. };
  1092. const JestChaiExpect = (chai, utils) => {
  1093. function def(name, fn) {
  1094. const addMethod = (n) => {
  1095. utils.addMethod(chai.Assertion.prototype, n, fn);
  1096. utils.addMethod(globalThis[JEST_MATCHERS_OBJECT].matchers, n, fn);
  1097. };
  1098. if (Array.isArray(name))
  1099. name.forEach((n) => addMethod(n));
  1100. else
  1101. addMethod(name);
  1102. }
  1103. ["throw", "throws", "Throw"].forEach((m) => {
  1104. utils.overwriteMethod(chai.Assertion.prototype, m, (_super) => {
  1105. return function(...args) {
  1106. const promise = utils.flag(this, "promise");
  1107. const object = utils.flag(this, "object");
  1108. const isNot = utils.flag(this, "negate");
  1109. if (promise === "rejects") {
  1110. utils.flag(this, "object", () => {
  1111. throw object;
  1112. });
  1113. } else if (promise === "resolves" && typeof object !== "function") {
  1114. if (!isNot) {
  1115. const message = utils.flag(this, "message") || "expected promise to throw an error, but it didn't";
  1116. const error = {
  1117. showDiff: false
  1118. };
  1119. throw new AssertionError(message, error, utils.flag(this, "ssfi"));
  1120. } else {
  1121. return;
  1122. }
  1123. }
  1124. _super.apply(this, args);
  1125. };
  1126. });
  1127. });
  1128. def("withTest", function(test) {
  1129. utils.flag(this, "vitest-test", test);
  1130. return this;
  1131. });
  1132. def("toEqual", function(expected) {
  1133. const actual = utils.flag(this, "object");
  1134. const equal = equals(
  1135. actual,
  1136. expected,
  1137. [iterableEquality]
  1138. );
  1139. return this.assert(
  1140. equal,
  1141. "expected #{this} to deeply equal #{exp}",
  1142. "expected #{this} to not deeply equal #{exp}",
  1143. expected,
  1144. actual
  1145. );
  1146. });
  1147. def("toStrictEqual", function(expected) {
  1148. const obj = utils.flag(this, "object");
  1149. const equal = equals(
  1150. obj,
  1151. expected,
  1152. [
  1153. iterableEquality,
  1154. typeEquality,
  1155. sparseArrayEquality,
  1156. arrayBufferEquality
  1157. ],
  1158. true
  1159. );
  1160. return this.assert(
  1161. equal,
  1162. "expected #{this} to strictly equal #{exp}",
  1163. "expected #{this} to not strictly equal #{exp}",
  1164. expected,
  1165. obj
  1166. );
  1167. });
  1168. def("toBe", function(expected) {
  1169. const actual = this._obj;
  1170. const pass = Object.is(actual, expected);
  1171. let deepEqualityName = "";
  1172. if (!pass) {
  1173. const toStrictEqualPass = equals(
  1174. actual,
  1175. expected,
  1176. [
  1177. iterableEquality,
  1178. typeEquality,
  1179. sparseArrayEquality,
  1180. arrayBufferEquality
  1181. ],
  1182. true
  1183. );
  1184. if (toStrictEqualPass) {
  1185. deepEqualityName = "toStrictEqual";
  1186. } else {
  1187. const toEqualPass = equals(
  1188. actual,
  1189. expected,
  1190. [iterableEquality]
  1191. );
  1192. if (toEqualPass)
  1193. deepEqualityName = "toEqual";
  1194. }
  1195. }
  1196. return this.assert(
  1197. pass,
  1198. generateToBeMessage(deepEqualityName),
  1199. "expected #{this} not to be #{exp} // Object.is equality",
  1200. expected,
  1201. actual
  1202. );
  1203. });
  1204. def("toMatchObject", function(expected) {
  1205. const actual = this._obj;
  1206. return this.assert(
  1207. equals(actual, expected, [iterableEquality, subsetEquality]),
  1208. "expected #{this} to match object #{exp}",
  1209. "expected #{this} to not match object #{exp}",
  1210. expected,
  1211. actual
  1212. );
  1213. });
  1214. def("toMatch", function(expected) {
  1215. if (typeof expected === "string")
  1216. return this.include(expected);
  1217. else
  1218. return this.match(expected);
  1219. });
  1220. def("toContain", function(item) {
  1221. return this.contain(item);
  1222. });
  1223. def("toContainEqual", function(expected) {
  1224. const obj = utils.flag(this, "object");
  1225. const index = Array.from(obj).findIndex((item) => {
  1226. return equals(item, expected);
  1227. });
  1228. this.assert(
  1229. index !== -1,
  1230. "expected #{this} to deep equally contain #{exp}",
  1231. "expected #{this} to not deep equally contain #{exp}",
  1232. expected
  1233. );
  1234. });
  1235. def("toBeTruthy", function() {
  1236. const obj = utils.flag(this, "object");
  1237. this.assert(
  1238. Boolean(obj),
  1239. "expected #{this} to be truthy",
  1240. "expected #{this} to not be truthy",
  1241. obj
  1242. );
  1243. });
  1244. def("toBeFalsy", function() {
  1245. const obj = utils.flag(this, "object");
  1246. this.assert(
  1247. !obj,
  1248. "expected #{this} to be falsy",
  1249. "expected #{this} to not be falsy",
  1250. obj
  1251. );
  1252. });
  1253. def("toBeGreaterThan", function(expected) {
  1254. const actual = this._obj;
  1255. assertTypes(actual, "actual", ["number", "bigint"]);
  1256. assertTypes(expected, "expected", ["number", "bigint"]);
  1257. return this.assert(
  1258. actual > expected,
  1259. `expected ${actual} to be greater than ${expected}`,
  1260. `expected ${actual} to be not greater than ${expected}`,
  1261. actual,
  1262. expected
  1263. );
  1264. });
  1265. def("toBeGreaterThanOrEqual", function(expected) {
  1266. const actual = this._obj;
  1267. assertTypes(actual, "actual", ["number", "bigint"]);
  1268. assertTypes(expected, "expected", ["number", "bigint"]);
  1269. return this.assert(
  1270. actual >= expected,
  1271. `expected ${actual} to be greater than or equal to ${expected}`,
  1272. `expected ${actual} to be not greater than or equal to ${expected}`,
  1273. actual,
  1274. expected
  1275. );
  1276. });
  1277. def("toBeLessThan", function(expected) {
  1278. const actual = this._obj;
  1279. assertTypes(actual, "actual", ["number", "bigint"]);
  1280. assertTypes(expected, "expected", ["number", "bigint"]);
  1281. return this.assert(
  1282. actual < expected,
  1283. `expected ${actual} to be less than ${expected}`,
  1284. `expected ${actual} to be not less than ${expected}`,
  1285. actual,
  1286. expected
  1287. );
  1288. });
  1289. def("toBeLessThanOrEqual", function(expected) {
  1290. const actual = this._obj;
  1291. assertTypes(actual, "actual", ["number", "bigint"]);
  1292. assertTypes(expected, "expected", ["number", "bigint"]);
  1293. return this.assert(
  1294. actual <= expected,
  1295. `expected ${actual} to be less than or equal to ${expected}`,
  1296. `expected ${actual} to be not less than or equal to ${expected}`,
  1297. actual,
  1298. expected
  1299. );
  1300. });
  1301. def("toBeNaN", function() {
  1302. return this.be.NaN;
  1303. });
  1304. def("toBeUndefined", function() {
  1305. return this.be.undefined;
  1306. });
  1307. def("toBeNull", function() {
  1308. return this.be.null;
  1309. });
  1310. def("toBeDefined", function() {
  1311. const negate = utils.flag(this, "negate");
  1312. utils.flag(this, "negate", false);
  1313. if (negate)
  1314. return this.be.undefined;
  1315. return this.not.be.undefined;
  1316. });
  1317. def("toBeTypeOf", function(expected) {
  1318. const actual = typeof this._obj;
  1319. const equal = expected === actual;
  1320. return this.assert(
  1321. equal,
  1322. "expected #{this} to be type of #{exp}",
  1323. "expected #{this} not to be type of #{exp}",
  1324. expected,
  1325. actual
  1326. );
  1327. });
  1328. def("toBeInstanceOf", function(obj) {
  1329. return this.instanceOf(obj);
  1330. });
  1331. def("toHaveLength", function(length) {
  1332. return this.have.length(length);
  1333. });
  1334. def("toHaveProperty", function(...args) {
  1335. if (Array.isArray(args[0]))
  1336. args[0] = args[0].map((key) => key.replace(/([.[\]])/g, "\\$1")).join(".");
  1337. const actual = this._obj;
  1338. const [propertyName, expected] = args;
  1339. const getValue = () => {
  1340. const hasOwn = Object.prototype.hasOwnProperty.call(actual, propertyName);
  1341. if (hasOwn)
  1342. return { value: actual[propertyName], exists: true };
  1343. return utils.getPathInfo(actual, propertyName);
  1344. };
  1345. const { value, exists } = getValue();
  1346. const pass = exists && (args.length === 1 || equals(expected, value));
  1347. const valueString = args.length === 1 ? "" : ` with value ${utils.objDisplay(expected)}`;
  1348. return this.assert(
  1349. pass,
  1350. `expected #{this} to have property "${propertyName}"${valueString}`,
  1351. `expected #{this} to not have property "${propertyName}"${valueString}`,
  1352. actual
  1353. );
  1354. });
  1355. def("toBeCloseTo", function(received, precision = 2) {
  1356. const expected = this._obj;
  1357. let pass = false;
  1358. let expectedDiff = 0;
  1359. let receivedDiff = 0;
  1360. if (received === Infinity && expected === Infinity) {
  1361. pass = true;
  1362. } else if (received === -Infinity && expected === -Infinity) {
  1363. pass = true;
  1364. } else {
  1365. expectedDiff = 10 ** -precision / 2;
  1366. receivedDiff = Math.abs(expected - received);
  1367. pass = receivedDiff < expectedDiff;
  1368. }
  1369. return this.assert(
  1370. pass,
  1371. `expected #{this} to be close to #{exp}, received difference is ${receivedDiff}, but expected ${expectedDiff}`,
  1372. `expected #{this} to not be close to #{exp}, received difference is ${receivedDiff}, but expected ${expectedDiff}`,
  1373. received,
  1374. expected
  1375. );
  1376. });
  1377. const assertIsMock = (assertion) => {
  1378. if (!isMockFunction(assertion._obj))
  1379. throw new TypeError(`${utils.inspect(assertion._obj)} is not a spy or a call to a spy!`);
  1380. };
  1381. const getSpy = (assertion) => {
  1382. assertIsMock(assertion);
  1383. return assertion._obj;
  1384. };
  1385. const ordinalOf = (i) => {
  1386. const j = i % 10;
  1387. const k = i % 100;
  1388. if (j === 1 && k !== 11)
  1389. return `${i}st`;
  1390. if (j === 2 && k !== 12)
  1391. return `${i}nd`;
  1392. if (j === 3 && k !== 13)
  1393. return `${i}rd`;
  1394. return `${i}th`;
  1395. };
  1396. const formatCalls = (spy, msg, actualCall) => {
  1397. msg += picocolors.exports.gray(`
  1398. Received:
  1399. ${spy.mock.calls.map((callArg, i) => {
  1400. let methodCall = picocolors.exports.bold(` ${ordinalOf(i + 1)} ${spy.getMockName()} call:
  1401. `);
  1402. if (actualCall)
  1403. methodCall += unifiedDiff(stringify(callArg), stringify(actualCall), { showLegend: false });
  1404. else
  1405. methodCall += stringify(callArg).split("\n").map((line) => ` ${line}`).join("\n");
  1406. methodCall += "\n";
  1407. return methodCall;
  1408. }).join("\n")}`);
  1409. msg += picocolors.exports.gray(`
  1410. Number of calls: ${picocolors.exports.bold(spy.mock.calls.length)}
  1411. `);
  1412. return msg;
  1413. };
  1414. def(["toHaveBeenCalledTimes", "toBeCalledTimes"], function(number) {
  1415. const spy = getSpy(this);
  1416. const spyName = spy.getMockName();
  1417. const callCount = spy.mock.calls.length;
  1418. return this.assert(
  1419. callCount === number,
  1420. `expected "${spyName}" to be called #{exp} times`,
  1421. `expected "${spyName}" to not be called #{exp} times`,
  1422. number,
  1423. callCount
  1424. );
  1425. });
  1426. def("toHaveBeenCalledOnce", function() {
  1427. const spy = getSpy(this);
  1428. const spyName = spy.getMockName();
  1429. const callCount = spy.mock.calls.length;
  1430. return this.assert(
  1431. callCount === 1,
  1432. `expected "${spyName}" to be called once`,
  1433. `expected "${spyName}" to not be called once`,
  1434. 1,
  1435. callCount
  1436. );
  1437. });
  1438. def(["toHaveBeenCalled", "toBeCalled"], function() {
  1439. const spy = getSpy(this);
  1440. const spyName = spy.getMockName();
  1441. const called = spy.mock.calls.length > 0;
  1442. const isNot = utils.flag(this, "negate");
  1443. let msg = utils.getMessage(
  1444. this,
  1445. [
  1446. called,
  1447. `expected "${spyName}" to be called at least once`,
  1448. `expected "${spyName}" to not be called at all`,
  1449. true,
  1450. called
  1451. ]
  1452. );
  1453. if (called && isNot)
  1454. msg += formatCalls(spy, msg);
  1455. if (called && isNot || !called && !isNot) {
  1456. const err = new Error(msg);
  1457. err.name = "AssertionError";
  1458. throw err;
  1459. }
  1460. });
  1461. def(["toHaveBeenCalledWith", "toBeCalledWith"], function(...args) {
  1462. const spy = getSpy(this);
  1463. const spyName = spy.getMockName();
  1464. const pass = spy.mock.calls.some((callArg) => equals(callArg, args, [iterableEquality]));
  1465. const isNot = utils.flag(this, "negate");
  1466. let msg = utils.getMessage(
  1467. this,
  1468. [
  1469. pass,
  1470. `expected "${spyName}" to be called with arguments: #{exp}`,
  1471. `expected "${spyName}" to not be called with arguments: #{exp}`,
  1472. args
  1473. ]
  1474. );
  1475. if (pass && isNot || !pass && !isNot) {
  1476. msg += formatCalls(spy, msg, args);
  1477. const err = new Error(msg);
  1478. err.name = "AssertionError";
  1479. throw err;
  1480. }
  1481. });
  1482. def(["toHaveBeenNthCalledWith", "nthCalledWith"], function(times, ...args) {
  1483. const spy = getSpy(this);
  1484. const spyName = spy.getMockName();
  1485. const nthCall = spy.mock.calls[times - 1];
  1486. this.assert(
  1487. equals(nthCall, args, [iterableEquality]),
  1488. `expected ${ordinalOf(times)} "${spyName}" call to have been called with #{exp}`,
  1489. `expected ${ordinalOf(times)} "${spyName}" call to not have been called with #{exp}`,
  1490. args,
  1491. nthCall
  1492. );
  1493. });
  1494. def(["toHaveBeenLastCalledWith", "lastCalledWith"], function(...args) {
  1495. const spy = getSpy(this);
  1496. const spyName = spy.getMockName();
  1497. const lastCall = spy.mock.calls[spy.calls.length - 1];
  1498. this.assert(
  1499. equals(lastCall, args, [iterableEquality]),
  1500. `expected last "${spyName}" call to have been called with #{exp}`,
  1501. `expected last "${spyName}" call to not have been called with #{exp}`,
  1502. args,
  1503. lastCall
  1504. );
  1505. });
  1506. def(["toThrow", "toThrowError"], function(expected) {
  1507. if (typeof expected === "string" || typeof expected === "undefined" || expected instanceof RegExp)
  1508. return this.throws(expected);
  1509. const obj = this._obj;
  1510. const promise = utils.flag(this, "promise");
  1511. const isNot = utils.flag(this, "negate");
  1512. let thrown = null;
  1513. if (promise === "rejects") {
  1514. thrown = obj;
  1515. } else if (promise === "resolves" && typeof obj !== "function") {
  1516. if (!isNot) {
  1517. const message = utils.flag(this, "message") || "expected promise to throw an error, but it didn't";
  1518. const error = {
  1519. showDiff: false
  1520. };
  1521. throw new AssertionError(message, error, utils.flag(this, "ssfi"));
  1522. } else {
  1523. return;
  1524. }
  1525. } else {
  1526. try {
  1527. obj();
  1528. } catch (err) {
  1529. thrown = err;
  1530. }
  1531. }
  1532. if (typeof expected === "function") {
  1533. const name = expected.name || expected.prototype.constructor.name;
  1534. return this.assert(
  1535. thrown && thrown instanceof expected,
  1536. `expected error to be instance of ${name}`,
  1537. `expected error not to be instance of ${name}`,
  1538. expected,
  1539. thrown
  1540. );
  1541. }
  1542. if (expected instanceof Error) {
  1543. return this.assert(
  1544. thrown && expected.message === thrown.message,
  1545. `expected error to have message: ${expected.message}`,
  1546. `expected error not to have message: ${expected.message}`,
  1547. expected.message,
  1548. thrown && thrown.message
  1549. );
  1550. }
  1551. if (typeof expected.asymmetricMatch === "function") {
  1552. const matcher = expected;
  1553. return this.assert(
  1554. thrown && matcher.asymmetricMatch(thrown),
  1555. "expected error to match asymmetric matcher",
  1556. "expected error not to match asymmetric matcher",
  1557. matcher.toString(),
  1558. thrown
  1559. );
  1560. }
  1561. throw new Error(`"toThrow" expects string, RegExp, function, Error instance or asymmetric matcher, got "${typeof expected}"`);
  1562. });
  1563. def(["toHaveReturned", "toReturn"], function() {
  1564. const spy = getSpy(this);
  1565. const spyName = spy.getMockName();
  1566. const calledAndNotThrew = spy.mock.calls.length > 0 && !spy.mock.results.some(({ type }) => type === "throw");
  1567. this.assert(
  1568. calledAndNotThrew,
  1569. `expected "${spyName}" to be successfully called at least once`,
  1570. `expected "${spyName}" to not be successfully called`,
  1571. calledAndNotThrew,
  1572. !calledAndNotThrew
  1573. );
  1574. });
  1575. def(["toHaveReturnedTimes", "toReturnTimes"], function(times) {
  1576. const spy = getSpy(this);
  1577. const spyName = spy.getMockName();
  1578. const successfulReturns = spy.mock.results.reduce((success, { type }) => type === "throw" ? success : ++success, 0);
  1579. this.assert(
  1580. successfulReturns === times,
  1581. `expected "${spyName}" to be successfully called ${times} times`,
  1582. `expected "${spyName}" to not be successfully called ${times} times`,
  1583. `expected number of returns: ${times}`,
  1584. `received number of returns: ${successfulReturns}`
  1585. );
  1586. });
  1587. def(["toHaveReturnedWith", "toReturnWith"], function(value) {
  1588. const spy = getSpy(this);
  1589. const spyName = spy.getMockName();
  1590. const pass = spy.mock.results.some(({ type, value: result }) => type === "return" && equals(value, result));
  1591. this.assert(
  1592. pass,
  1593. `expected "${spyName}" to be successfully called with #{exp}`,
  1594. `expected "${spyName}" to not be successfully called with #{exp}`,
  1595. value
  1596. );
  1597. });
  1598. def(["toHaveLastReturnedWith", "lastReturnedWith"], function(value) {
  1599. const spy = getSpy(this);
  1600. const spyName = spy.getMockName();
  1601. const { value: lastResult } = spy.mock.results[spy.returns.length - 1];
  1602. const pass = equals(lastResult, value);
  1603. this.assert(
  1604. pass,
  1605. `expected last "${spyName}" call to return #{exp}`,
  1606. `expected last "${spyName}" call to not return #{exp}`,
  1607. value,
  1608. lastResult
  1609. );
  1610. });
  1611. def(["toHaveNthReturnedWith", "nthReturnedWith"], function(nthCall, value) {
  1612. const spy = getSpy(this);
  1613. const spyName = spy.getMockName();
  1614. const isNot = utils.flag(this, "negate");
  1615. const { type: callType, value: callResult } = spy.mock.results[nthCall - 1];
  1616. const ordinalCall = `${ordinalOf(nthCall)} call`;
  1617. if (!isNot && callType === "throw")
  1618. chai.assert.fail(`expected ${ordinalCall} to return #{exp}, but instead it threw an error`);
  1619. const nthCallReturn = equals(callResult, value);
  1620. this.assert(
  1621. nthCallReturn,
  1622. `expected ${ordinalCall} "${spyName}" call to return #{exp}`,
  1623. `expected ${ordinalCall} "${spyName}" call to not return #{exp}`,
  1624. value,
  1625. callResult
  1626. );
  1627. });
  1628. def("toSatisfy", function(matcher, message) {
  1629. return this.be.satisfy(matcher, message);
  1630. });
  1631. utils.addProperty(chai.Assertion.prototype, "resolves", function __VITEST_RESOLVES__() {
  1632. utils.flag(this, "promise", "resolves");
  1633. utils.flag(this, "error", new Error("resolves"));
  1634. const obj = utils.flag(this, "object");
  1635. if (typeof (obj == null ? void 0 : obj.then) !== "function")
  1636. throw new TypeError(`You must provide a Promise to expect() when using .resolves, not '${typeof obj}'.`);
  1637. const proxy = new Proxy(this, {
  1638. get: (target, key, receiver) => {
  1639. const result = Reflect.get(target, key, receiver);
  1640. if (typeof result !== "function")
  1641. return result instanceof chai.Assertion ? proxy : result;
  1642. return async (...args) => {
  1643. return obj.then(
  1644. (value) => {
  1645. utils.flag(this, "object", value);
  1646. return result.call(this, ...args);
  1647. },
  1648. (err) => {
  1649. throw new Error(`promise rejected "${toString(err)}" instead of resolving`);
  1650. }
  1651. );
  1652. };
  1653. }
  1654. });
  1655. return proxy;
  1656. });
  1657. utils.addProperty(chai.Assertion.prototype, "rejects", function __VITEST_REJECTS__() {
  1658. utils.flag(this, "promise", "rejects");
  1659. utils.flag(this, "error", new Error("rejects"));
  1660. const obj = utils.flag(this, "object");
  1661. const wrapper = typeof obj === "function" ? obj() : obj;
  1662. if (typeof (wrapper == null ? void 0 : wrapper.then) !== "function")
  1663. throw new TypeError(`You must provide a Promise to expect() when using .rejects, not '${typeof wrapper}'.`);
  1664. const proxy = new Proxy(this, {
  1665. get: (target, key, receiver) => {
  1666. const result = Reflect.get(target, key, receiver);
  1667. if (typeof result !== "function")
  1668. return result instanceof chai.Assertion ? proxy : result;
  1669. return async (...args) => {
  1670. return wrapper.then(
  1671. (value) => {
  1672. throw new Error(`promise resolved "${toString(value)}" instead of rejecting`);
  1673. },
  1674. (err) => {
  1675. utils.flag(this, "object", err);
  1676. return result.call(this, ...args);
  1677. }
  1678. );
  1679. };
  1680. }
  1681. });
  1682. return proxy;
  1683. });
  1684. utils.addMethod(
  1685. chai.expect,
  1686. "addSnapshotSerializer",
  1687. addSerializer
  1688. );
  1689. };
  1690. function toString(value) {
  1691. try {
  1692. return `${value}`;
  1693. } catch (_error) {
  1694. return "unknown";
  1695. }
  1696. }
  1697. class AsymmetricMatcher {
  1698. constructor(sample, inverse = false) {
  1699. this.sample = sample;
  1700. this.inverse = inverse;
  1701. this.$$typeof = Symbol.for("jest.asymmetricMatcher");
  1702. }
  1703. getMatcherContext(expect) {
  1704. return {
  1705. ...getState(expect || globalThis[GLOBAL_EXPECT]),
  1706. equals,
  1707. isNot: this.inverse,
  1708. utils: matcherUtils
  1709. };
  1710. }
  1711. }
  1712. class StringContaining extends AsymmetricMatcher {
  1713. constructor(sample, inverse = false) {
  1714. if (!isA("String", sample))
  1715. throw new Error("Expected is not a string");
  1716. super(sample, inverse);
  1717. }
  1718. asymmetricMatch(other) {
  1719. const result = isA("String", other) && other.includes(this.sample);
  1720. return this.inverse ? !result : result;
  1721. }
  1722. toString() {
  1723. return `String${this.inverse ? "Not" : ""}Containing`;
  1724. }
  1725. getExpectedType() {
  1726. return "string";
  1727. }
  1728. }
  1729. class Anything extends AsymmetricMatcher {
  1730. asymmetricMatch(other) {
  1731. return other != null;
  1732. }
  1733. toString() {
  1734. return "Anything";
  1735. }
  1736. toAsymmetricMatcher() {
  1737. return "Anything";
  1738. }
  1739. }
  1740. class ObjectContaining extends AsymmetricMatcher {
  1741. constructor(sample, inverse = false) {
  1742. super(sample, inverse);
  1743. }
  1744. getPrototype(obj) {
  1745. if (Object.getPrototypeOf)
  1746. return Object.getPrototypeOf(obj);
  1747. if (obj.constructor.prototype === obj)
  1748. return null;
  1749. return obj.constructor.prototype;
  1750. }
  1751. hasProperty(obj, property) {
  1752. if (!obj)
  1753. return false;
  1754. if (Object.prototype.hasOwnProperty.call(obj, property))
  1755. return true;
  1756. return this.hasProperty(this.getPrototype(obj), property);
  1757. }
  1758. asymmetricMatch(other) {
  1759. if (typeof this.sample !== "object") {
  1760. throw new TypeError(
  1761. `You must provide an object to ${this.toString()}, not '${typeof this.sample}'.`
  1762. );
  1763. }
  1764. let result = true;
  1765. for (const property in this.sample) {
  1766. if (!this.hasProperty(other, property) || !equals(this.sample[property], other[property])) {
  1767. result = false;
  1768. break;
  1769. }
  1770. }
  1771. return this.inverse ? !result : result;
  1772. }
  1773. toString() {
  1774. return `Object${this.inverse ? "Not" : ""}Containing`;
  1775. }
  1776. getExpectedType() {
  1777. return "object";
  1778. }
  1779. }
  1780. class ArrayContaining extends AsymmetricMatcher {
  1781. constructor(sample, inverse = false) {
  1782. super(sample, inverse);
  1783. }
  1784. asymmetricMatch(other) {
  1785. if (!Array.isArray(this.sample)) {
  1786. throw new TypeError(
  1787. `You must provide an array to ${this.toString()}, not '${typeof this.sample}'.`
  1788. );
  1789. }
  1790. const result = this.sample.length === 0 || Array.isArray(other) && this.sample.every(
  1791. (item) => other.some((another) => equals(item, another))
  1792. );
  1793. return this.inverse ? !result : result;
  1794. }
  1795. toString() {
  1796. return `Array${this.inverse ? "Not" : ""}Containing`;
  1797. }
  1798. getExpectedType() {
  1799. return "array";
  1800. }
  1801. }
  1802. class Any extends AsymmetricMatcher {
  1803. constructor(sample) {
  1804. if (typeof sample === "undefined") {
  1805. throw new TypeError(
  1806. "any() expects to be passed a constructor function. Please pass one or use anything() to match any object."
  1807. );
  1808. }
  1809. super(sample);
  1810. }
  1811. fnNameFor(func) {
  1812. if (func.name)
  1813. return func.name;
  1814. const functionToString = Function.prototype.toString;
  1815. const matches = functionToString.call(func).match(/^(?:async)?\s*function\s*\*?\s*([\w$]+)\s*\(/);
  1816. return matches ? matches[1] : "<anonymous>";
  1817. }
  1818. asymmetricMatch(other) {
  1819. if (this.sample === String)
  1820. return typeof other == "string" || other instanceof String;
  1821. if (this.sample === Number)
  1822. return typeof other == "number" || other instanceof Number;
  1823. if (this.sample === Function)
  1824. return typeof other == "function" || other instanceof Function;
  1825. if (this.sample === Boolean)
  1826. return typeof other == "boolean" || other instanceof Boolean;
  1827. if (this.sample === BigInt)
  1828. return typeof other == "bigint" || other instanceof BigInt;
  1829. if (this.sample === Symbol)
  1830. return typeof other == "symbol" || other instanceof Symbol;
  1831. if (this.sample === Object)
  1832. return typeof other == "object";
  1833. return other instanceof this.sample;
  1834. }
  1835. toString() {
  1836. return "Any";
  1837. }
  1838. getExpectedType() {
  1839. if (this.sample === String)
  1840. return "string";
  1841. if (this.sample === Number)
  1842. return "number";
  1843. if (this.sample === Function)
  1844. return "function";
  1845. if (this.sample === Object)
  1846. return "object";
  1847. if (this.sample === Boolean)
  1848. return "boolean";
  1849. return this.fnNameFor(this.sample);
  1850. }
  1851. toAsymmetricMatcher() {
  1852. return `Any<${this.fnNameFor(this.sample)}>`;
  1853. }
  1854. }
  1855. class StringMatching extends AsymmetricMatcher {
  1856. constructor(sample, inverse = false) {
  1857. if (!isA("String", sample) && !isA("RegExp", sample))
  1858. throw new Error("Expected is not a String or a RegExp");
  1859. super(new RegExp(sample), inverse);
  1860. }
  1861. asymmetricMatch(other) {
  1862. const result = isA("String", other) && this.sample.test(other);
  1863. return this.inverse ? !result : result;
  1864. }
  1865. toString() {
  1866. return `String${this.inverse ? "Not" : ""}Matching`;
  1867. }
  1868. getExpectedType() {
  1869. return "string";
  1870. }
  1871. }
  1872. const JestAsymmetricMatchers = (chai, utils) => {
  1873. utils.addMethod(
  1874. chai.expect,
  1875. "anything",
  1876. () => new Anything()
  1877. );
  1878. utils.addMethod(
  1879. chai.expect,
  1880. "any",
  1881. (expected) => new Any(expected)
  1882. );
  1883. utils.addMethod(
  1884. chai.expect,
  1885. "stringContaining",
  1886. (expected) => new StringContaining(expected)
  1887. );
  1888. utils.addMethod(
  1889. chai.expect,
  1890. "objectContaining",
  1891. (expected) => new ObjectContaining(expected)
  1892. );
  1893. utils.addMethod(
  1894. chai.expect,
  1895. "arrayContaining",
  1896. (expected) => new ArrayContaining(expected)
  1897. );
  1898. utils.addMethod(
  1899. chai.expect,
  1900. "stringMatching",
  1901. (expected) => new StringMatching(expected)
  1902. );
  1903. chai.expect.not = {
  1904. stringContaining: (expected) => new StringContaining(expected, true),
  1905. objectContaining: (expected) => new ObjectContaining(expected, true),
  1906. arrayContaining: (expected) => new ArrayContaining(expected, true),
  1907. stringMatching: (expected) => new StringMatching(expected, true)
  1908. };
  1909. };
  1910. const isAsyncFunction = (fn) => typeof fn === "function" && fn[Symbol.toStringTag] === "AsyncFunction";
  1911. const getMatcherState = (assertion, expect) => {
  1912. const obj = assertion._obj;
  1913. const isNot = util.flag(assertion, "negate");
  1914. const promise = util.flag(assertion, "promise") || "";
  1915. const jestUtils = {
  1916. ...matcherUtils,
  1917. iterableEquality,
  1918. subsetEquality
  1919. };
  1920. const matcherState = {
  1921. ...getState(expect),
  1922. isNot,
  1923. utils: jestUtils,
  1924. promise,
  1925. equals,
  1926. suppressedErrors: [],
  1927. snapshotState: getSnapshotClient().snapshotState
  1928. };
  1929. return {
  1930. state: matcherState,
  1931. isNot,
  1932. obj
  1933. };
  1934. };
  1935. class JestExtendError extends Error {
  1936. constructor(message, actual, expected) {
  1937. super(message);
  1938. this.actual = actual;
  1939. this.expected = expected;
  1940. }
  1941. }
  1942. function JestExtendPlugin(expect, matchers) {
  1943. return (c, utils) => {
  1944. Object.entries(matchers).forEach(([expectAssertionName, expectAssertion]) => {
  1945. function expectSyncWrapper(...args) {
  1946. const { state, isNot, obj } = getMatcherState(this, expect);
  1947. const { pass, message, actual, expected } = expectAssertion.call(state, obj, ...args);
  1948. if (pass && isNot || !pass && !isNot)
  1949. throw new JestExtendError(message(), actual, expected);
  1950. }
  1951. async function expectAsyncWrapper(...args) {
  1952. const { state, isNot, obj } = getMatcherState(this, expect);
  1953. const { pass, message, actual, expected } = await expectAssertion.call(state, obj, ...args);
  1954. if (pass && isNot || !pass && !isNot)
  1955. throw new JestExtendError(message(), actual, expected);
  1956. }
  1957. const expectAssertionWrapper = isAsyncFunction(expectAssertion) ? expectAsyncWrapper : expectSyncWrapper;
  1958. utils.addMethod(globalThis[JEST_MATCHERS_OBJECT].matchers, expectAssertionName, expectAssertionWrapper);
  1959. utils.addMethod(c.Assertion.prototype, expectAssertionName, expectAssertionWrapper);
  1960. class CustomMatcher extends AsymmetricMatcher {
  1961. constructor(inverse = false, ...sample) {
  1962. super(sample, inverse);
  1963. }
  1964. asymmetricMatch(other) {
  1965. const { pass } = expectAssertion.call(
  1966. this.getMatcherContext(expect),
  1967. other,
  1968. ...this.sample
  1969. );
  1970. return this.inverse ? !pass : pass;
  1971. }
  1972. toString() {
  1973. return `${this.inverse ? "not." : ""}${expectAssertionName}`;
  1974. }
  1975. getExpectedType() {
  1976. return "any";
  1977. }
  1978. toAsymmetricMatcher() {
  1979. return `${this.toString()}<${this.sample.map(String).join(", ")}>`;
  1980. }
  1981. }
  1982. Object.defineProperty(expect, expectAssertionName, {
  1983. configurable: true,
  1984. enumerable: true,
  1985. value: (...sample) => new CustomMatcher(false, ...sample),
  1986. writable: true
  1987. });
  1988. Object.defineProperty(expect.not, expectAssertionName, {
  1989. configurable: true,
  1990. enumerable: true,
  1991. value: (...sample) => new CustomMatcher(true, ...sample),
  1992. writable: true
  1993. });
  1994. });
  1995. };
  1996. }
  1997. const JestExtend = (chai, utils) => {
  1998. utils.addMethod(chai.expect, "extend", (expect, expects) => {
  1999. chai.use(JestExtendPlugin(expect, expects));
  2000. });
  2001. };
  2002. chai$2.use(JestExtend);
  2003. chai$2.use(JestChaiExpect);
  2004. chai$2.use(Subset);
  2005. chai$2.use(SnapshotPlugin);
  2006. chai$2.use(JestAsymmetricMatchers);
  2007. const workerState$1 = getWorkerState();
  2008. function createExpect(test) {
  2009. var _a;
  2010. const expect = (value, message) => {
  2011. const { assertionCalls } = getState(expect);
  2012. setState({ assertionCalls: assertionCalls + 1 }, expect);
  2013. const assert2 = chai$2.expect(value, message);
  2014. if (test)
  2015. return assert2.withTest(test);
  2016. else
  2017. return assert2;
  2018. };
  2019. Object.assign(expect, chai$2.expect);
  2020. expect.getState = () => getState(expect);
  2021. expect.setState = (state) => setState(state, expect);
  2022. setState({
  2023. assertionCalls: 0,
  2024. isExpectingAssertions: false,
  2025. isExpectingAssertionsError: null,
  2026. expectedAssertionsNumber: null,
  2027. expectedAssertionsNumberErrorGen: null,
  2028. environment: workerState$1.config.environment,
  2029. testPath: (_a = test == null ? void 0 : test.suite.file) == null ? void 0 : _a.filepath,
  2030. currentTestName: test ? getFullName(test) : void 0
  2031. }, expect);
  2032. expect.extend = (matchers) => chai$2.expect.extend(expect, matchers);
  2033. function assertions(expected) {
  2034. const errorGen = () => new Error(`expected number of assertions to be ${expected}, but got ${expect.getState().assertionCalls}`);
  2035. if (Error.captureStackTrace)
  2036. Error.captureStackTrace(errorGen(), assertions);
  2037. expect.setState({
  2038. expectedAssertionsNumber: expected,
  2039. expectedAssertionsNumberErrorGen: errorGen
  2040. });
  2041. }
  2042. function hasAssertions() {
  2043. const error = new Error("expected any number of assertion, but got none");
  2044. if (Error.captureStackTrace)
  2045. Error.captureStackTrace(error, hasAssertions);
  2046. expect.setState({
  2047. isExpectingAssertions: true,
  2048. isExpectingAssertionsError: error
  2049. });
  2050. }
  2051. chai$2.util.addMethod(expect, "assertions", assertions);
  2052. chai$2.util.addMethod(expect, "hasAssertions", hasAssertions);
  2053. return expect;
  2054. }
  2055. const globalExpect = createExpect();
  2056. Object.defineProperty(globalThis, GLOBAL_EXPECT, {
  2057. value: globalExpect,
  2058. writable: true,
  2059. configurable: true
  2060. });
  2061. const collectorContext = {
  2062. tasks: [],
  2063. currentSuite: null
  2064. };
  2065. function collectTask(task) {
  2066. var _a;
  2067. (_a = collectorContext.currentSuite) == null ? void 0 : _a.tasks.push(task);
  2068. }
  2069. async function runWithSuite(suite, fn) {
  2070. const prev = collectorContext.currentSuite;
  2071. collectorContext.currentSuite = suite;
  2072. await fn();
  2073. collectorContext.currentSuite = prev;
  2074. }
  2075. function getDefaultTestTimeout() {
  2076. return getWorkerState().config.testTimeout;
  2077. }
  2078. function getDefaultHookTimeout() {
  2079. return getWorkerState().config.hookTimeout;
  2080. }
  2081. function withTimeout(fn, timeout = getDefaultTestTimeout(), isHook = false) {
  2082. if (timeout <= 0 || timeout === Infinity)
  2083. return fn;
  2084. return (...args) => {
  2085. return Promise.race([fn(...args), new Promise((resolve, reject) => {
  2086. var _a;
  2087. const timer = safeSetTimeout(() => {
  2088. safeClearTimeout(timer);
  2089. reject(new Error(makeTimeoutMsg(isHook, timeout)));
  2090. }, timeout);
  2091. (_a = timer.unref) == null ? void 0 : _a.call(timer);
  2092. })]);
  2093. };
  2094. }
  2095. function createTestContext(test) {
  2096. const context = function() {
  2097. throw new Error("done() callback is deprecated, use promise instead");
  2098. };
  2099. context.meta = test;
  2100. let _expect;
  2101. Object.defineProperty(context, "expect", {
  2102. get() {
  2103. if (!_expect)
  2104. _expect = createExpect(test);
  2105. return _expect;
  2106. }
  2107. });
  2108. Object.defineProperty(context, "_local", {
  2109. get() {
  2110. return _expect != null;
  2111. }
  2112. });
  2113. return context;
  2114. }
  2115. function makeTimeoutMsg(isHook, timeout) {
  2116. return `${isHook ? "Hook" : "Test"} timed out in ${timeout}ms.
  2117. If this is a long-running test, pass a timeout value as the last argument or configure it globally with "${isHook ? "hookTimeout" : "testTimeout"}".`;
  2118. }
  2119. const fnMap = /* @__PURE__ */ new WeakMap();
  2120. const hooksMap = /* @__PURE__ */ new WeakMap();
  2121. function setFn(key, fn) {
  2122. fnMap.set(key, fn);
  2123. }
  2124. function getFn(key) {
  2125. return fnMap.get(key);
  2126. }
  2127. function setHooks(key, hooks) {
  2128. hooksMap.set(key, hooks);
  2129. }
  2130. function getHooks(key) {
  2131. return hooksMap.get(key);
  2132. }
  2133. const suite = createSuite();
  2134. const test = createTest(
  2135. function(name, fn, options) {
  2136. getCurrentSuite().test.fn.call(this, name, fn, options);
  2137. }
  2138. );
  2139. const bench = createBenchmark(
  2140. function(name, fn, options) {
  2141. getCurrentSuite().benchmark.fn.call(this, name, fn, options);
  2142. }
  2143. );
  2144. function formatTitle(template, items, idx) {
  2145. if (template.includes("%#")) {
  2146. template = template.replace(/%%/g, "__vitest_escaped_%__").replace(/%#/g, `${idx}`).replace(/__vitest_escaped_%__/g, "%%");
  2147. }
  2148. const count = template.split("%").length - 1;
  2149. let formatted = util$1.format(template, ...items.slice(0, count));
  2150. if (isObject(items[0])) {
  2151. formatted = formatted.replace(/\$([$\w_]+)/g, (_, key) => {
  2152. return items[0][key];
  2153. });
  2154. }
  2155. return formatted;
  2156. }
  2157. const describe = suite;
  2158. const it = test;
  2159. const workerState = getWorkerState();
  2160. const defaultSuite = workerState.config.sequence.shuffle ? suite.shuffle("") : suite("");
  2161. function clearCollectorContext() {
  2162. collectorContext.tasks.length = 0;
  2163. defaultSuite.clear();
  2164. collectorContext.currentSuite = defaultSuite;
  2165. }
  2166. function getCurrentSuite() {
  2167. return collectorContext.currentSuite || defaultSuite;
  2168. }
  2169. function createSuiteHooks() {
  2170. return {
  2171. beforeAll: [],
  2172. afterAll: [],
  2173. beforeEach: [],
  2174. afterEach: []
  2175. };
  2176. }
  2177. function createSuiteCollector(name, factory = () => {
  2178. }, mode, concurrent, shuffle, suiteOptions) {
  2179. const tasks = [];
  2180. const factoryQueue = [];
  2181. let suite2;
  2182. initSuite();
  2183. const test2 = createTest(function(name2, fn = noop, options = suiteOptions) {
  2184. if (!isRunningInTest())
  2185. throw new Error("`test()` and `it()` is only available in test mode.");
  2186. const mode2 = this.only ? "only" : this.skip ? "skip" : this.todo ? "todo" : "run";
  2187. if (typeof options === "number")
  2188. options = { timeout: options };
  2189. const test3 = {
  2190. id: "",
  2191. type: "test",
  2192. name: name2,
  2193. mode: mode2,
  2194. suite: void 0,
  2195. fails: this.fails,
  2196. retry: options == null ? void 0 : options.retry
  2197. };
  2198. if (this.concurrent || concurrent)
  2199. test3.concurrent = true;
  2200. if (shuffle)
  2201. test3.shuffle = true;
  2202. const context = createTestContext(test3);
  2203. Object.defineProperty(test3, "context", {
  2204. value: context,
  2205. enumerable: false
  2206. });
  2207. setFn(test3, withTimeout(
  2208. () => fn(context),
  2209. options == null ? void 0 : options.timeout
  2210. ));
  2211. tasks.push(test3);
  2212. });
  2213. const benchmark = createBenchmark(function(name2, fn = noop, options) {
  2214. const mode2 = this.only ? "only" : this.skip ? "skip" : "run";
  2215. if (!isRunningInBenchmark())
  2216. throw new Error("`bench()` is only available in benchmark mode. Run with `vitest bench` instead.");
  2217. const benchmark2 = {
  2218. type: "benchmark",
  2219. id: "",
  2220. name: name2,
  2221. mode: mode2,
  2222. options,
  2223. suite: void 0
  2224. };
  2225. setFn(benchmark2, fn);
  2226. tasks.push(benchmark2);
  2227. });
  2228. const collector = {
  2229. type: "collector",
  2230. name,
  2231. mode,
  2232. test: test2,
  2233. tasks,
  2234. benchmark,
  2235. collect,
  2236. clear,
  2237. on: addHook
  2238. };
  2239. function addHook(name2, ...fn) {
  2240. getHooks(suite2)[name2].push(...fn);
  2241. }
  2242. function initSuite() {
  2243. suite2 = {
  2244. id: "",
  2245. type: "suite",
  2246. name,
  2247. mode,
  2248. shuffle,
  2249. tasks: []
  2250. };
  2251. setHooks(suite2, createSuiteHooks());
  2252. }
  2253. function clear() {
  2254. tasks.length = 0;
  2255. factoryQueue.length = 0;
  2256. initSuite();
  2257. }
  2258. async function collect(file) {
  2259. factoryQueue.length = 0;
  2260. if (factory)
  2261. await runWithSuite(collector, () => factory(test2));
  2262. const allChildren = [];
  2263. for (const i of [...factoryQueue, ...tasks])
  2264. allChildren.push(i.type === "collector" ? await i.collect(file) : i);
  2265. suite2.file = file;
  2266. suite2.tasks = allChildren;
  2267. allChildren.forEach((task) => {
  2268. task.suite = suite2;
  2269. if (file)
  2270. task.file = file;
  2271. });
  2272. return suite2;
  2273. }
  2274. collectTask(collector);
  2275. return collector;
  2276. }
  2277. function createSuite() {
  2278. function suiteFn(name, factory, options) {
  2279. const mode = this.only ? "only" : this.skip ? "skip" : this.todo ? "todo" : "run";
  2280. return createSuiteCollector(name, factory, mode, this.concurrent, this.shuffle, options);
  2281. }
  2282. suiteFn.each = function(cases) {
  2283. const suite2 = this.withContext();
  2284. return (name, fn, options) => {
  2285. cases.forEach((i, idx) => {
  2286. const items = Array.isArray(i) ? i : [i];
  2287. suite2(formatTitle(name, items, idx), () => fn(...items), options);
  2288. });
  2289. };
  2290. };
  2291. suiteFn.skipIf = (condition) => condition ? suite.skip : suite;
  2292. suiteFn.runIf = (condition) => condition ? suite : suite.skip;
  2293. return createChainable(
  2294. ["concurrent", "shuffle", "skip", "only", "todo"],
  2295. suiteFn
  2296. );
  2297. }
  2298. function createTest(fn) {
  2299. const testFn = fn;
  2300. testFn.each = function(cases) {
  2301. const test2 = this.withContext();
  2302. return (name, fn2, options) => {
  2303. cases.forEach((i, idx) => {
  2304. const items = Array.isArray(i) ? i : [i];
  2305. test2(formatTitle(name, items, idx), () => fn2(...items), options);
  2306. });
  2307. };
  2308. };
  2309. testFn.skipIf = (condition) => condition ? test.skip : test;
  2310. testFn.runIf = (condition) => condition ? test : test.skip;
  2311. return createChainable(
  2312. ["concurrent", "skip", "only", "todo", "fails"],
  2313. testFn
  2314. );
  2315. }
  2316. function createBenchmark(fn) {
  2317. const benchmark = createChainable(
  2318. ["skip", "only"],
  2319. fn
  2320. );
  2321. benchmark.skipIf = (condition) => condition ? benchmark.skip : benchmark;
  2322. benchmark.runIf = (condition) => condition ? benchmark : benchmark.skip;
  2323. return benchmark;
  2324. }
  2325. export { GLOBAL_EXPECT as G, getDefaultHookTimeout as a, bench as b, createExpect as c, describe as d, globalExpect as e, clearCollectorContext as f, getCurrentSuite as g, defaultSuite as h, it as i, setHooks as j, getHooks as k, collectorContext as l, getFn as m, setState as n, getState as o, createSuiteHooks as p, chai$1 as q, suite as s, test as t, withTimeout as w };