vitest 0.0.60 → 0.0.64
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/LICENSE +2 -1
- package/README.gh.md +10 -14
- package/dist/{chunk-BC6SKI3B.js → chunk-3P4SNPBT.js} +1 -1
- package/dist/chunk-3VLG4URE.js +1 -0
- package/dist/{chunk-64PJVUUV.js → chunk-CNY47EZT.js} +1 -1
- package/dist/chunk-H3VLV7UP.js +1 -0
- package/dist/general-39d52683.d.ts +43 -0
- package/dist/global-E2TE3466.js +1 -0
- package/dist/index.d.ts +39 -8
- package/dist/index.js +1 -1
- package/dist/node/cli.d.ts +3 -3
- package/dist/node/cli.js +10 -10
- package/dist/{types-c52fcc81.d.ts → options-654578ef.d.ts} +129 -146
- package/dist/runtime/entry.d.ts +2 -4
- package/dist/runtime/entry.js +19 -1
- package/dist/{node → runtime}/worker.d.ts +7 -6
- package/dist/runtime/worker.js +5 -0
- package/package.json +33 -18
- package/dist/chunk-2AYT2TPD.js +0 -1
- package/dist/chunk-2PVIVCXM.js +0 -1
- package/dist/chunk-4STHXS4C.js +0 -1
- package/dist/chunk-SLHZBXI2.js +0 -1
- package/dist/global-PPDEK7CI.js +0 -1
- package/dist/happy-dom-EZVJENUI.js +0 -1
- package/dist/jsdom-VHB26LUJ.js +0 -1
- package/dist/node/worker.js +0 -4
package/LICENSE
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
MIT License
|
|
2
2
|
|
|
3
|
-
Copyright (c) 2021 Anthony Fu <https://github.com/antfu>
|
|
3
|
+
Copyright (c) 2021-Present Anthony Fu <https://github.com/antfu>
|
|
4
|
+
Copyright (c) 2021-Present Matias Capeletto <https://github.com/patak-dev>
|
|
4
5
|
|
|
5
6
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
7
|
of this software and associated documentation files (the "Software"), to deal
|
package/README.gh.md
CHANGED
|
@@ -29,7 +29,7 @@ A blazing fast unit test framework powered by Vite.
|
|
|
29
29
|
- [Smart & instant watch mode](#watch-mode), like HMR for tests!
|
|
30
30
|
- [Native code coverage](#coverage) via [c8](https://github.com/bcoe/c8)
|
|
31
31
|
- [Sinon](https://sinonjs.org/) built-in for mocking, stubbing, and spies.
|
|
32
|
-
- [JSDOM](https://github.com/jsdom/jsdom) and [happy-dom](https://github.com/capricorn86/happy-dom)
|
|
32
|
+
- [JSDOM](https://github.com/jsdom/jsdom) and [happy-dom](https://github.com/capricorn86/happy-dom) for DOM and browser API mocking
|
|
33
33
|
- Components testing ([Vue](./test/vue), [React](./test/react), [Lit](./test/lit), [Vitesse](./test/vitesse))
|
|
34
34
|
- Workers multi-threading via [Piscina](https://github.com/piscinajs/piscina)
|
|
35
35
|
- ESM first, top level await
|
|
@@ -80,7 +80,7 @@ $ npx vitest
|
|
|
80
80
|
|
|
81
81
|
- Create `vitest.config.ts`, which will have the higher priority
|
|
82
82
|
- Pass `--config` option to CLI, e.g. `vitest --config ./path/to/vitest.config.ts`
|
|
83
|
-
- Use `process.env.VITEST` to conditionally apply
|
|
83
|
+
- Use `process.env.VITEST` to conditionally apply different configuration in `vite.config.ts`
|
|
84
84
|
|
|
85
85
|
To configure `vitest` itself, add `test` property in your Vite config
|
|
86
86
|
|
|
@@ -142,20 +142,15 @@ export default defineConfig({
|
|
|
142
142
|
|
|
143
143
|
## Browser Mocking
|
|
144
144
|
|
|
145
|
-
|
|
145
|
+
Vitest supports both [happy-dom](https://github.com/capricorn86/happy-dom) or [jsdom](https://github.com/jsdom/jsdom) for mocking DOM and browser APIs. They don't come with Vitest, you might need to install them:
|
|
146
146
|
|
|
147
|
-
```
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
export default defineConfig({
|
|
152
|
-
test: {
|
|
153
|
-
dom: true
|
|
154
|
-
}
|
|
155
|
-
})
|
|
147
|
+
```bash
|
|
148
|
+
$ npm i -D happy-dom
|
|
149
|
+
# or
|
|
150
|
+
$ npm i -D jsdom
|
|
156
151
|
```
|
|
157
152
|
|
|
158
|
-
|
|
153
|
+
After that, change the `environment` option in your config file:
|
|
159
154
|
|
|
160
155
|
```ts
|
|
161
156
|
// vite.config.ts
|
|
@@ -163,7 +158,7 @@ import { defineConfig } from 'vite'
|
|
|
163
158
|
|
|
164
159
|
export default defineConfig({
|
|
165
160
|
test: {
|
|
166
|
-
|
|
161
|
+
environment: 'happy-dom' // or 'jsdom', 'node'
|
|
167
162
|
}
|
|
168
163
|
})
|
|
169
164
|
```
|
|
@@ -181,6 +176,7 @@ Vitest smartly searches the module graph and only rerun the related tests (just
|
|
|
181
176
|
Vitest works perfectly with [c8](https://github.com/bcoe/c8)
|
|
182
177
|
|
|
183
178
|
```bash
|
|
179
|
+
$ npm i -D c8
|
|
184
180
|
$ c8 vitest
|
|
185
181
|
```
|
|
186
182
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{afterAll,afterEach,beforeAll,beforeEach,clearContext,createSuiteHooks,defaultSuite,describe,it,suite,test}from"./chunk-
|
|
1
|
+
import{afterAll,afterEach,beforeAll,beforeEach,clearContext,createSuiteHooks,defaultSuite,describe,it,suite,test}from"./chunk-3VLG4URE.js";import{__export,init_esm_shims}from"./chunk-CNY47EZT.js";var src_exports={};__export(src_exports,{afterAll:()=>afterAll,afterEach:()=>afterEach,assert:()=>assert,beforeAll:()=>beforeAll,beforeEach:()=>beforeEach,chai:()=>chai,clearContext:()=>clearContext,createSuiteHooks:()=>createSuiteHooks,defaultSuite:()=>defaultSuite,describe:()=>describe,expect:()=>expect,it:()=>it,mock:()=>mock,should:()=>should,sinon:()=>sinon,spy:()=>spy,stub:()=>stub,suite:()=>suite,test:()=>test});init_esm_shims();init_esm_shims();init_esm_shims();init_esm_shims();init_esm_shims();init_esm_shims();init_esm_shims();init_esm_shims();init_esm_shims();import chai from"chai";import{assert,should,expect}from"chai";init_esm_shims();import sinon from"sinon";var{mock,spy,stub}=sinon;sinon.fn=sinon.spy;export{chai,assert,should,expect,sinon,mock,spy,stub,src_exports};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{defaultHookTimeout,defaultTestTimeout,init_esm_shims}from"./chunk-CNY47EZT.js";init_esm_shims();import{nanoid}from"nanoid";init_esm_shims();var context={tasks:[],currentSuite:null};init_esm_shims();var fnMap=new WeakMap,hooksMap=new WeakMap;function setFn(key,fn){fnMap.set(key,fn)}function getFn(key){return fnMap.get(key)}function setHooks(key,hooks){hooksMap.set(key,hooks)}function getHooks(key){return hooksMap.get(key)}var suite=createSuite(),defaultSuite=suite("");function getCurrentSuite(){return context.currentSuite||defaultSuite}function createSuiteHooks(){return{beforeAll:[],afterAll:[],beforeEach:[],afterEach:[]}}function createSuiteCollector(name,factory=()=>{},mode,suiteComputeMode){var _a;let tasks=[],factoryQueue=[],suite2;initSuite();let test2=createTestCollector((name2,fn,mode2,computeMode)=>{let test3={id:nanoid(),type:"test",name:name2,mode:mode2,computeMode:computeMode??suiteComputeMode??"serial",suite:void 0};setFn(test3,fn),tasks.push(test3)}),collector={type:"collector",name,mode,test:test2,tasks,collect,clear,on:addHook};function addHook(name2,...fn){getHooks(suite2)[name2].push(...fn)}function initSuite(){suite2={id:nanoid(),type:"suite",computeMode:"serial",name,mode,tasks:[]},setHooks(suite2,createSuiteHooks())}function clear(){tasks.length=0,factoryQueue.length=0,initSuite()}async function collect(file){if(factoryQueue.length=0,factory){let prev=context.currentSuite;context.currentSuite=collector,await factory(test2),context.currentSuite=prev}let allChildren=await Promise.all([...factoryQueue,...tasks].map(i=>i.type==="collector"?i.collect(file):i));return suite2.file=file,suite2.tasks=allChildren,allChildren.forEach(task=>{task.suite=suite2,file&&(task.file=file)}),suite2}return(_a=context.currentSuite)==null||_a.tasks.push(collector),collector}function createTestCollector(collectTest){function test2(name,fn,timeout){collectTest(name,withTimeout(fn,timeout),"run")}test2.concurrent=concurrent,test2.skip=skip,test2.only=only,test2.todo=todo;function concurrent(name,fn,timeout){collectTest(name,withTimeout(fn,timeout),"run","concurrent")}concurrent.skip=(name,fn,timeout)=>collectTest(name,withTimeout(fn,timeout),"skip","concurrent"),concurrent.only=(name,fn,timeout)=>collectTest(name,withTimeout(fn,timeout),"only","concurrent"),concurrent.todo=todo;function skip(name,fn,timeout){collectTest(name,withTimeout(fn,timeout),"skip")}skip.concurrent=concurrent.skip;function only(name,fn,timeout){collectTest(name,withTimeout(fn,timeout),"only")}only.concurrent=concurrent.only;function todo(name){collectTest(name,()=>{},"todo")}return todo.concurrent=todo,test2}var test=function(){function test2(name,fn,timeout){return getCurrentSuite().test(name,fn,timeout)}function concurrent(name,fn,timeout){return getCurrentSuite().test.concurrent(name,fn,timeout)}concurrent.skip=(name,fn,timeout)=>getCurrentSuite().test.concurrent.skip(name,fn,timeout),concurrent.only=(name,fn,timeout)=>getCurrentSuite().test.concurrent.only(name,fn,timeout),concurrent.todo=name=>getCurrentSuite().test.concurrent.todo(name);function skip(name,fn,timeout){return getCurrentSuite().test.skip(name,fn,timeout)}skip.concurrent=(name,fn,timeout)=>getCurrentSuite().test.skip.concurrent(name,fn,timeout);function only(name,fn,timeout){return getCurrentSuite().test.only(name,fn,timeout)}only.concurrent=(name,fn,timeout)=>getCurrentSuite().test.only.concurrent(name,fn,timeout);function todo(name){return getCurrentSuite().test.todo(name)}return todo.concurrent=name=>getCurrentSuite().test.todo.concurrent(name),test2.concurrent=concurrent,test2.skip=skip,test2.only=only,test2.todo=todo,test2}();function createSuite(){function suite2(suiteName,factory){return createSuiteCollector(suiteName,factory,"run")}function concurrent(suiteName,factory){return createSuiteCollector(suiteName,factory,"run","concurrent")}concurrent.skip=(suiteName,factory)=>createSuiteCollector(suiteName,factory,"skip","concurrent"),concurrent.only=(suiteName,factory)=>createSuiteCollector(suiteName,factory,"only","concurrent"),concurrent.todo=suiteName=>createSuiteCollector(suiteName,void 0,"todo");function skip(suiteName,factory){return createSuiteCollector(suiteName,factory,"skip")}skip.concurrent=concurrent.skip;function only(suiteName,factory){return createSuiteCollector(suiteName,factory,"only")}only.concurrent=concurrent.only;function todo(suiteName){return createSuiteCollector(suiteName,void 0,"todo")}return todo.concurrent=concurrent.todo,suite2.concurrent=concurrent,suite2.skip=skip,suite2.only=only,suite2.todo=todo,suite2}var describe=suite,it=test,beforeAll=(fn,timeout=defaultHookTimeout)=>getCurrentSuite().on("beforeAll",withTimeout(fn,timeout)),afterAll=(fn,timeout=defaultHookTimeout)=>getCurrentSuite().on("afterAll",withTimeout(fn,timeout)),beforeEach=(fn,timeout=defaultHookTimeout)=>getCurrentSuite().on("beforeEach",withTimeout(fn,timeout)),afterEach=(fn,timeout=defaultHookTimeout)=>getCurrentSuite().on("afterEach",withTimeout(fn,timeout));function clearContext(){context.tasks.length=0,defaultSuite.clear(),context.currentSuite=defaultSuite}function withTimeout(fn,timeout=defaultTestTimeout){return timeout<=0||timeout===1/0?fn:(...args)=>Promise.race([fn(...args),new Promise((resolve,reject)=>{let timer=setTimeout(()=>{clearTimeout(timer),reject(new Error(`Test timed out in ${timeout}ms.`))},timeout);timer.unref()})])}export{context,getFn,setHooks,getHooks,suite,defaultSuite,createSuiteHooks,test,describe,it,beforeAll,afterAll,beforeEach,afterEach,clearContext};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var __create=Object.create;var __defProp=Object.defineProperty,__defProps=Object.defineProperties,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__getOwnPropDescs=Object.getOwnPropertyDescriptors,__getOwnPropNames=Object.getOwnPropertyNames,__getOwnPropSymbols=Object.getOwnPropertySymbols,__getProtoOf=Object.getPrototypeOf,__hasOwnProp=Object.prototype.hasOwnProperty,__propIsEnum=Object.prototype.propertyIsEnumerable;var __defNormalProp=(obj,key,value)=>key in obj?__defProp(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value,__spreadValues=(a,b)=>{for(var prop in b||(b={}))__hasOwnProp.call(b,prop)&&__defNormalProp(a,prop,b[prop]);if(__getOwnPropSymbols)for(var prop of __getOwnPropSymbols(b))__propIsEnum.call(b,prop)&&__defNormalProp(a,prop,b[prop]);return a},__spreadProps=(a,b)=>__defProps(a,__getOwnPropDescs(b)),__markAsModule=target=>__defProp(target,"__esModule",{value:!0});var __esm=(fn,res)=>function(){return fn&&(res=(0,fn[Object.keys(fn)[0]])(fn=0)),res};var __commonJS=(cb,mod)=>function(){return mod||(0,cb[Object.keys(cb)[0]])((mod={exports:{}}).exports,mod),mod.exports};var __export=(target,all)=>{__markAsModule(target);for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__reExport=(target,module,desc)=>{if(module&&typeof module=="object"||typeof module=="function")for(let key of __getOwnPropNames(module))!__hasOwnProp.call(target,key)&&key!=="default"&&__defProp(target,key,{get:()=>module[key],enumerable:!(desc=__getOwnPropDesc(module,key))||desc.enumerable});return target},__toModule=module=>__reExport(__markAsModule(__defProp(module!=null?__create(__getProtoOf(module)):{},"default",module&&module.__esModule&&"default"in module?{get:()=>module.default,enumerable:!0}:{value:module,enumerable:!0})),module);import{fileURLToPath}from"url";import path from"path";var
|
|
1
|
+
var __create=Object.create;var __defProp=Object.defineProperty,__defProps=Object.defineProperties,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__getOwnPropDescs=Object.getOwnPropertyDescriptors,__getOwnPropNames=Object.getOwnPropertyNames,__getOwnPropSymbols=Object.getOwnPropertySymbols,__getProtoOf=Object.getPrototypeOf,__hasOwnProp=Object.prototype.hasOwnProperty,__propIsEnum=Object.prototype.propertyIsEnumerable;var __defNormalProp=(obj,key,value)=>key in obj?__defProp(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value,__spreadValues=(a,b)=>{for(var prop in b||(b={}))__hasOwnProp.call(b,prop)&&__defNormalProp(a,prop,b[prop]);if(__getOwnPropSymbols)for(var prop of __getOwnPropSymbols(b))__propIsEnum.call(b,prop)&&__defNormalProp(a,prop,b[prop]);return a},__spreadProps=(a,b)=>__defProps(a,__getOwnPropDescs(b)),__markAsModule=target=>__defProp(target,"__esModule",{value:!0});var __esm=(fn,res)=>function(){return fn&&(res=(0,fn[Object.keys(fn)[0]])(fn=0)),res};var __commonJS=(cb,mod)=>function(){return mod||(0,cb[Object.keys(cb)[0]])((mod={exports:{}}).exports,mod),mod.exports};var __export=(target,all)=>{__markAsModule(target);for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__reExport=(target,module,desc)=>{if(module&&typeof module=="object"||typeof module=="function")for(let key of __getOwnPropNames(module))!__hasOwnProp.call(target,key)&&key!=="default"&&__defProp(target,key,{get:()=>module[key],enumerable:!(desc=__getOwnPropDesc(module,key))||desc.enumerable});return target},__toModule=module=>__reExport(__markAsModule(__defProp(module!=null?__create(__getProtoOf(module)):{},"default",module&&module.__esModule&&"default"in module?{get:()=>module.default,enumerable:!0}:{value:module,enumerable:!0})),module);import{fileURLToPath}from"url";import path from"path";var init_esm_shims=__esm({"node_modules/.pnpm/tsup@5.11.1_typescript@4.5.3/node_modules/tsup/assets/esm_shims.js"(){}});init_esm_shims();import{resolve}from"path";import{fileURLToPath as fileURLToPath2}from"url";var distDir=resolve(fileURLToPath2(import.meta.url),"../../dist"),defaultTestTimeout=5e3,defaultHookTimeout=5e3,defaultIncludes=["**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}"],defaultExcludes=["**/node_modules/**","**/dist/**"],globalApis=["suite","test","describe","it","chai","expect","assert","sinon","spy","mock","stub","beforeAll","afterAll","beforeEach","afterEach"];export{__spreadValues,__spreadProps,__commonJS,__export,__toModule,init_esm_shims,distDir,defaultTestTimeout,defaultHookTimeout,defaultIncludes,defaultExcludes,globalApis};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{init_esm_shims}from"./chunk-CNY47EZT.js";init_esm_shims();import{toArray}from"@antfu/utils";function partitionSuiteChildren(suite){let tasksGroup=[],tasksGroups=[];for(let c of suite.tasks)tasksGroup.length===0||c.computeMode===tasksGroup[0].computeMode?tasksGroup.push(c):(tasksGroups.push(tasksGroup),tasksGroup=[c]);return tasksGroup.length>0&&tasksGroups.push(tasksGroup),tasksGroups}function interpretOnlyMode(items){items.some(i=>i.mode==="only")&&items.forEach(i=>{i.mode==="run"?i.mode="skip":i.mode==="only"&&(i.mode="run")})}function getTests(suite){return toArray(suite).flatMap(s=>s.tasks.flatMap(c=>c.type==="test"?[c]:getTests(c)))}function getSuites(suite){return toArray(suite).flatMap(s=>s.type==="suite"?[s,...getSuites(s.tasks)]:[])}function hasTests(suite){return toArray(suite).some(s=>s.tasks.some(c=>c.type==="test"||hasTests(c)))}function hasFailed(suite){return toArray(suite).some(s=>{var _a;return((_a=s.result)==null?void 0:_a.state)==="fail"||s.type==="suite"&&hasFailed(s.tasks)})}function getNames(task){let names=[task.name],current=task;for(;(current==null?void 0:current.suite)||(current==null?void 0:current.file);)current=current.suite||current.file,(current==null?void 0:current.name)&&names.unshift(current.name);return names}init_esm_shims();var emptySummary=options=>({added:0,failure:!1,filesAdded:0,filesRemoved:0,filesRemovedList:[],filesUnmatched:0,filesUpdated:0,matched:0,total:0,unchecked:0,uncheckedKeysByFile:[],unmatched:0,updated:0,didUpdate:options.updateSnapshot==="all"}),packSnapshotState=(filepath,state)=>{let snapshot={filepath,added:0,fileDeleted:!1,matched:0,unchecked:0,uncheckedKeys:[],unmatched:0,updated:0},uncheckedCount=state.getUncheckedCount(),uncheckedKeys=state.getUncheckedKeys();uncheckedCount&&state.removeUncheckedKeys();let status=state.save();return snapshot.fileDeleted=status.deleted,snapshot.added=state.added,snapshot.matched=state.matched,snapshot.unmatched=state.unmatched,snapshot.updated=state.updated,snapshot.unchecked=status.deleted?0:uncheckedCount,snapshot.uncheckedKeys=Array.from(uncheckedKeys),snapshot},addSnapshotResult=(summary,result)=>{result.added&&summary.filesAdded++,result.fileDeleted&&summary.filesRemoved++,result.unmatched&&summary.filesUnmatched++,result.updated&&summary.filesUpdated++,summary.added+=result.added,summary.matched+=result.matched,summary.unchecked+=result.unchecked,result.uncheckedKeys&&result.uncheckedKeys.length>0&&summary.uncheckedKeysByFile.push({filePath:result.filepath,keys:result.uncheckedKeys}),summary.unmatched+=result.unmatched,summary.updated+=result.updated,summary.total+=result.added+result.matched+result.unmatched+result.updated};export{partitionSuiteChildren,interpretOnlyMode,getTests,getSuites,hasTests,hasFailed,getNames,emptySummary,packSnapshotState,addSnapshotResult};
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { Awaitable } from '@antfu/utils';
|
|
2
|
+
import { TransformResult, ViteDevServer } from 'vite';
|
|
3
|
+
import { F as File, l as Task, T as TaskResultPack, R as ResolvedConfig, t as SnapshotSummary, S as SnapshotResult, n as Reporter } from './options-654578ef';
|
|
4
|
+
|
|
5
|
+
declare class StateManager {
|
|
6
|
+
filesMap: Record<string, File>;
|
|
7
|
+
idMap: Record<string, Task>;
|
|
8
|
+
taskFileMap: WeakMap<Task, File>;
|
|
9
|
+
getFiles(keys?: string[]): File[];
|
|
10
|
+
collectFiles(files: File[]): void;
|
|
11
|
+
updateId(task: Task): void;
|
|
12
|
+
updateTasks(packs: TaskResultPack[]): void;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
declare class SnapshotManager {
|
|
16
|
+
config: ResolvedConfig;
|
|
17
|
+
summary: SnapshotSummary;
|
|
18
|
+
constructor(config: ResolvedConfig);
|
|
19
|
+
clear(): void;
|
|
20
|
+
add(result: SnapshotResult): void;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
interface ModuleCache {
|
|
24
|
+
promise?: Promise<any>;
|
|
25
|
+
exports?: any;
|
|
26
|
+
transformResult?: TransformResult;
|
|
27
|
+
}
|
|
28
|
+
interface EnvironmentReturn {
|
|
29
|
+
teardown: (global: any) => Awaitable<void>;
|
|
30
|
+
}
|
|
31
|
+
interface Environment {
|
|
32
|
+
name: string;
|
|
33
|
+
setup(global: any): Awaitable<EnvironmentReturn>;
|
|
34
|
+
}
|
|
35
|
+
interface VitestContext {
|
|
36
|
+
config: ResolvedConfig;
|
|
37
|
+
server: ViteDevServer;
|
|
38
|
+
state: StateManager;
|
|
39
|
+
snapshot: SnapshotManager;
|
|
40
|
+
reporter: Reporter;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export { EnvironmentReturn as E, ModuleCache as M, VitestContext as V, Environment as a };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{src_exports}from"./chunk-3P4SNPBT.js";import"./chunk-3VLG4URE.js";import{globalApis,init_esm_shims}from"./chunk-CNY47EZT.js";init_esm_shims();function registerApiGlobally(){globalApis.forEach(api=>{globalThis[api]=src_exports[api]})}export{registerApiGlobally};
|
package/dist/index.d.ts
CHANGED
|
@@ -1,12 +1,37 @@
|
|
|
1
|
-
import { T as
|
|
2
|
-
export { C as CliOptions,
|
|
1
|
+
import { R as ResolvedConfig, F as File, T as TaskResultPack, S as SnapshotResult, a as TestFactory, b as SuiteCollector, c as TestFunction, d as SuiteHooks, U as UserOptions } from './options-654578ef';
|
|
2
|
+
export { C as CliOptions, g as ComputeMode, F as File, G as GlobalContext, H as HookListener, n as Reporter, R as ResolvedConfig, e as RunMode, o as SnapshotData, r as SnapshotMatchOptions, S as SnapshotResult, q as SnapshotStateOptions, t as SnapshotSummary, p as SnapshotUpdateState, j as Suite, b as SuiteCollector, d as SuiteHooks, l as Task, h as TaskBase, i as TaskResult, T as TaskResultPack, f as TaskState, k as Test, m as TestCollector, a as TestFactory, c as TestFunction, s as UncheckedSnapshot, U as UserOptions } from './options-654578ef';
|
|
3
|
+
import { MessagePort } from 'worker_threads';
|
|
4
|
+
import { TransformResult } from 'vite';
|
|
5
|
+
export { a as Environment, E as EnvironmentReturn, M as ModuleCache, V as VitestContext } from './general-39d52683';
|
|
3
6
|
export { assert, default as chai, expect, should } from 'chai';
|
|
4
7
|
import sinon from 'sinon';
|
|
5
8
|
export { default as sinon } from 'sinon';
|
|
6
|
-
import 'worker_threads';
|
|
7
9
|
import '@antfu/utils';
|
|
8
|
-
import '
|
|
9
|
-
|
|
10
|
+
import 'pretty-format';
|
|
11
|
+
|
|
12
|
+
interface WorkerContext {
|
|
13
|
+
port: MessagePort;
|
|
14
|
+
config: ResolvedConfig;
|
|
15
|
+
files: string[];
|
|
16
|
+
invalidates?: string[];
|
|
17
|
+
}
|
|
18
|
+
interface RpcMap {
|
|
19
|
+
workerReady: [[], void];
|
|
20
|
+
fetch: [[id: string], TransformResult | null | undefined];
|
|
21
|
+
onCollected: [[files: File[]], void];
|
|
22
|
+
onFinished: [[], void];
|
|
23
|
+
onTaskUpdate: [[pack: TaskResultPack], void];
|
|
24
|
+
onWatcherStart: [[], void];
|
|
25
|
+
onWatcherRerun: [[files: string[], trigger: string], void];
|
|
26
|
+
snapshotSaved: [[snapshot: SnapshotResult], void];
|
|
27
|
+
}
|
|
28
|
+
declare type RpcCall = <T extends keyof RpcMap>(method: T, ...args: RpcMap[T][0]) => Promise<RpcMap[T][1]>;
|
|
29
|
+
declare type RpcSend = <T extends keyof RpcMap>(method: T, ...args: RpcMap[T][0]) => void;
|
|
30
|
+
declare type RpcPayload<T extends keyof RpcMap = keyof RpcMap> = {
|
|
31
|
+
id: string;
|
|
32
|
+
method: T;
|
|
33
|
+
args: RpcMap[T][0];
|
|
34
|
+
};
|
|
10
35
|
|
|
11
36
|
declare const suite: {
|
|
12
37
|
(suiteName: string, factory?: TestFactory | undefined): SuiteCollector;
|
|
@@ -141,14 +166,20 @@ declare global {
|
|
|
141
166
|
toBeDefined(): void;
|
|
142
167
|
toBeInstanceOf(c: any): void;
|
|
143
168
|
toBeCalledTimes(n: number): void;
|
|
169
|
+
toHaveLength(l: number): void;
|
|
170
|
+
toBeCloseTo(number: number, numDigits?: number): void;
|
|
144
171
|
toHaveBeenCalledTimes(n: number): void;
|
|
145
172
|
toHaveBeenCalledOnce(): void;
|
|
146
173
|
toHaveBeenCalled(): void;
|
|
147
174
|
toBeCalled(): void;
|
|
148
175
|
toHaveBeenCalledWith(...args: any[]): void;
|
|
149
176
|
toBeCalledWith(...args: any[]): void;
|
|
150
|
-
|
|
151
|
-
|
|
177
|
+
toHaveBeenNthCalledWith(n: number, ...args: any[]): void;
|
|
178
|
+
nthCalledWith(n: number, ...args: any[]): void;
|
|
179
|
+
toHaveBeenLastCalledWith(...args: any[]): void;
|
|
180
|
+
lastCalledWith(...args: any[]): void;
|
|
181
|
+
toThrow(expected?: string | RegExp): void;
|
|
182
|
+
toThrowError(expected?: string | RegExp): void;
|
|
152
183
|
toReturn(): void;
|
|
153
184
|
toHaveReturned(): void;
|
|
154
185
|
toReturnTimes(times: number): void;
|
|
@@ -163,4 +194,4 @@ declare global {
|
|
|
163
194
|
}
|
|
164
195
|
}
|
|
165
196
|
|
|
166
|
-
export { afterAll, afterEach, beforeAll, beforeEach, clearContext, createSuiteHooks, defaultSuite, describe, it, mock, spy, stub, suite, test };
|
|
197
|
+
export { RpcCall, RpcMap, RpcPayload, RpcSend, WorkerContext, afterAll, afterEach, beforeAll, beforeEach, clearContext, createSuiteHooks, defaultSuite, describe, it, mock, spy, stub, suite, test };
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{assert,chai,expect,mock,should,sinon,spy,stub}from"./chunk-
|
|
1
|
+
import{assert,chai,expect,mock,should,sinon,spy,stub}from"./chunk-3P4SNPBT.js";import{afterAll,afterEach,beforeAll,beforeEach,clearContext,createSuiteHooks,defaultSuite,describe,it,suite,test}from"./chunk-3VLG4URE.js";import"./chunk-CNY47EZT.js";export{afterAll,afterEach,assert,beforeAll,beforeEach,chai,clearContext,createSuiteHooks,defaultSuite,describe,expect,it,mock,should,sinon,spy,stub,suite,test};
|
package/dist/node/cli.d.ts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { V as VitestContext } from '../
|
|
2
|
-
import 'worker_threads';
|
|
1
|
+
import { V as VitestContext } from '../general-39d52683';
|
|
3
2
|
import '@antfu/utils';
|
|
4
3
|
import 'vite';
|
|
5
|
-
import '
|
|
4
|
+
import '../options-654578ef';
|
|
5
|
+
import 'pretty-format';
|
|
6
6
|
|
|
7
7
|
declare global {
|
|
8
8
|
namespace NodeJS {
|
package/dist/node/cli.js
CHANGED
|
@@ -1,22 +1,22 @@
|
|
|
1
|
-
import{addSnapshotResult,emptySummary,getNames,getSuites,getTests,hasFailed}from"../chunk-
|
|
1
|
+
import{addSnapshotResult,emptySummary,getNames,getSuites,getTests,hasFailed}from"../chunk-H3VLV7UP.js";import{__spreadProps,__spreadValues,defaultExcludes,defaultIncludes,distDir,init_esm_shims}from"../chunk-CNY47EZT.js";init_esm_shims();import sade from"sade";import c4 from"picocolors";import{install as installSourceMapSupport}from"source-map-support";var version="0.0.64";init_esm_shims();import{performance}from"perf_hooks";import{relative as relative2}from"path";import c3 from"picocolors";init_esm_shims();import{promises as fs,existsSync}from"fs";import c from"picocolors";import*as diff from"diff";import{notNullish}from"@antfu/utils";import{SourceMapConsumer}from"source-map";import cliTruncate from"cli-truncate";init_esm_shims();var F_RIGHT="\u2192",F_DOWN="\u2193",F_UP="\u2191",F_DOWN_RIGHT="\u21B3",F_POINTER="\u276F",F_DOT="\xB7",F_CHECK="\u221A",F_CROSS="\xD7";async function printError(error){let{server}=process.__vitest__,e=error;typeof error=="string"&&(e={message:error.split(/\n/g)[0],stack:error});let codeFramePrinted=!1,nearest=parseStack(e.stack||e.stackStr||"").find(stack=>server.moduleGraph.getModuleById(stack.file));if(nearest){let mod=server.moduleGraph.getModuleById(nearest.file),transformResult=mod==null?void 0:mod.ssrTransformResult,pos=await getOriginalPos(transformResult==null?void 0:transformResult.map,nearest);if(pos&&existsSync(nearest.file)){let sourceCode=await fs.readFile(nearest.file,"utf-8");displayErrorMessage(e),displayFilePath(nearest.file,pos),displayCodeFrame(sourceCode,pos),codeFramePrinted=!0}}codeFramePrinted||console.error(e),e.showDiff&&displayDiff(e.actual,e.expected)}function displayDiff(actual,expected){console.error(c.gray(generateDiff(stringify(actual),stringify(expected))))}function displayErrorMessage(error){let errorName=error.name||error.nameStr||"Unknown Error";console.error(c.red(cliTruncate(`${c.bold(errorName)}: ${error.message}`,process.stdout.columns)))}function displayFilePath(filePath,pos){console.log(c.gray(`${filePath}:${pos.line}:${pos.column}`))}function displayCodeFrame(sourceCode,pos){console.log(c.yellow(generateCodeFrame(sourceCode,pos)))}function getOriginalPos(map,{line,column}){return new Promise(resolve2=>{if(!map)return resolve2(null);SourceMapConsumer.with(map,null,consumer=>{let pos=consumer.originalPositionFor({line,column});pos.line!=null&&pos.column!=null?resolve2(pos):resolve2(null)})})}var splitRE=/\r?\n/;function posToNumber(source,pos){if(typeof pos=="number")return pos;let lines=source.split(splitRE),{line,column}=pos,start2=0;for(let i=0;i<line-1;i++)start2+=lines[i].length+1;return start2+column}function generateCodeFrame(source,start2=0,end,range=2){start2=posToNumber(source,start2),end=end||start2;let lines=source.split(splitRE),count=0,res=[];function lineNo(no=""){return c.gray(`${String(no).padStart(3," ")}| `)}for(let i=0;i<lines.length;i++)if(count+=lines[i].length+1,count>=start2){for(let j=i-range;j<=i+range||end>count;j++){if(j<0||j>=lines.length)continue;let lineLength=lines[j].length;if(lineLength>200)return"";if(res.push(lineNo(j+1)+cliTruncate(lines[j],process.stdout.columns-5)),j===i){let pad=start2-(count-lineLength),length=Math.max(1,end>count?lineLength-pad:end-start2);res.push(lineNo()+" ".repeat(pad)+F_UP.repeat(length))}else if(j>i){if(end>count){let length=Math.max(1,Math.min(end-count,lineLength));res.push(lineNo()+F_UP.repeat(length))}count+=lineLength+1}}break}return res.join(`
|
|
2
2
|
`)}function stringify(obj){return String(obj)}var stackFnCallRE=/at (.*) \((.+):(\d+):(\d+)\)$/,stackBarePathRE=/at ()(.+):(\d+):(\d+)$/;function parseStack(stack){return stack.split(`
|
|
3
|
-
`).map(raw=>{let line=raw.trim(),match=line.match(stackFnCallRE)||line.match(stackBarePathRE);if(!match)return null;let file=match[2];return file.startsWith("file://")&&(file=file.slice(7)),{method:match[1],file:match[2],line:parseInt(match[3]),column:parseInt(match[4])}}).filter(notNullish)}function generateDiff(actual,expected){let diffSize=2048;return actual.length>diffSize&&(actual=`${actual.substring(0,diffSize)} ... Lines skipped`),expected.length>diffSize&&(expected=`${expected.substring(0,diffSize)} ... Lines skipped`),unifiedDiff(actual,expected)}function unifiedDiff(actual,expected){let indent=" ";function cleanUp(line){return line[0]==="+"?indent+c.green(`${line[0]}
|
|
3
|
+
`).map(raw=>{let line=raw.trim(),match=line.match(stackFnCallRE)||line.match(stackBarePathRE);if(!match)return null;let file=match[2];return file.startsWith("file://")&&(file=file.slice(7)),{method:match[1],file:match[2],line:parseInt(match[3]),column:parseInt(match[4])}}).filter(notNullish)}function generateDiff(actual,expected){let diffSize=2048;return actual.length>diffSize&&(actual=`${actual.substring(0,diffSize)} ... Lines skipped`),expected.length>diffSize&&(expected=`${expected.substring(0,diffSize)} ... Lines skipped`),unifiedDiff(actual,expected)}function unifiedDiff(actual,expected){let indent=" ";function cleanUp(line){return line[0]==="+"?indent+c.green(`${line[0]}${line.slice(1)}`):line[0]==="-"?indent+c.red(`${line[0]}${line.slice(1)}`):line.match(/@@/)?"--":line.match(/\\ No newline/)?null:indent+line}let lines=diff.createPatch("string",actual,expected).split(`
|
|
4
4
|
`).splice(5);return`
|
|
5
5
|
${indent}${c.red("- actual")}
|
|
6
6
|
${indent}${c.green("+ expected")}
|
|
7
7
|
|
|
8
8
|
${lines.map(cleanUp).filter(notBlank).join(`
|
|
9
|
-
`)}`}function notBlank(line){return typeof line!="undefined"&&line!==null}init_esm_shims();
|
|
10
|
-
`).filter(Boolean).pop()),data===""&&(data=void 0)),data!=null){let out
|
|
11
|
-
`)}var createRenderer=_tasks=>{let tasks=_tasks,timer,log=createLogUpdate(process.stdout);function update(){log(renderTree(tasks))}return{start(){return timer?this:(timer=setInterval(update,200),this)},update(_tasks2){return tasks=_tasks2,update(),this},async stop(){return timer&&(clearInterval(timer),timer=void 0),log.clear(),console.log(renderTree(tasks)),this}}};function getFullName(task){return getNames(task).join(c2.gray(" > "))}var isTTY=process.stdout.isTTY&&!process.env.CI,DefaultReporter=class{constructor(ctx){this.ctx=ctx;console.log(c3.green(`Running tests at ${c3.gray(this.ctx.config.root)}
|
|
12
|
-
`)),this.start=performance.now()}start=0;end=0;renderer;watchFilters;relative(path){return relative2(this.ctx.config.root,path)}onStart(){if(isTTY){let files=this.ctx.state.getFiles(this.watchFilters);this.renderer?this.renderer.update(files):this.renderer=createRenderer(files).start()}}onTaskUpdate(pack){var _a,_b,_c;if(isTTY)return;let task=this.ctx.state.idMap[pack[0]];task.type==="test"&&((_a=task.result)==null?void 0:_a.state)&&((_b=task.result)==null?void 0:_b.state)!=="run"&&(console.log(` ${getStateSymbol(task)} ${getFullName(task)}`),task.result.state==="fail"&&console.log(c3.red(` ${
|
|
9
|
+
`)}`}function notBlank(line){return typeof line!="undefined"&&line!==null}init_esm_shims();import{basename,dirname,isAbsolute,relative}from"path";import{createLogUpdate}from"log-update";import c2 from"picocolors";import cliTruncate2 from"cli-truncate";import stripAnsi from"strip-ansi";import{slash}from"@antfu/utils";var DURATION_LONG=300,MAX_HEIGHT=20,spinnerMap=new WeakMap,outputMap=new WeakMap,pointer=c2.yellow(F_POINTER),skipped=c2.yellow(F_DOWN);function formatTestPath(root,path){var _a;isAbsolute(path)&&(path=relative(root,path));let dir=dirname(path),ext=((_a=path.match(/(\.(spec|test)\.[cm]?[tj]sx?)$/))==null?void 0:_a[0])||"",base=basename(path,ext);return slash(c2.dim(`${dir}/`)+c2.bold(base))+c2.dim(ext)}function renderSnapshotSummary(rootDir,snapshots){let summary=[];if(snapshots.added&&summary.push(c2.bold(c2.green(`${snapshots.added} written`))),snapshots.unmatched&&summary.push(c2.bold(c2.red(`${snapshots.unmatched} failed`))),snapshots.updated&&summary.push(c2.bold(c2.green(`${snapshots.updated} updated `))),snapshots.filesRemoved&&(snapshots.didUpdate?summary.push(c2.bold(c2.green(`${snapshots.filesRemoved} files removed `))):summary.push(c2.bold(c2.yellow(`${snapshots.filesRemoved} files obsolete `)))),snapshots.filesRemovedList&&snapshots.filesRemovedList.length){let[head,...tail]=snapshots.filesRemovedList;summary.push(`${c2.gray(F_DOWN_RIGHT)} ${formatTestPath(rootDir,head)}`),tail.forEach(key=>{summary.push(` ${c2.gray(F_DOT)} ${formatTestPath(rootDir,key)}`)})}return snapshots.unchecked&&(snapshots.didUpdate?summary.push(c2.bold(c2.green(`${snapshots.unchecked} removed`))):summary.push(c2.bold(c2.yellow(`${snapshots.unchecked} obsolete`))),snapshots.uncheckedKeysByFile.forEach(uncheckedFile=>{summary.push(`${c2.gray(F_DOWN_RIGHT)} ${formatTestPath(rootDir,uncheckedFile.filePath)}`),uncheckedFile.keys.forEach(key=>summary.push(` ${c2.gray(F_DOT)} ${key}`))})),summary}function getStateString(tasks,name="tests"){if(tasks.length===0)return c2.dim(`no ${name}`);let passed=tasks.filter(i=>{var _a;return((_a=i.result)==null?void 0:_a.state)==="pass"}),failed=tasks.filter(i=>{var _a;return((_a=i.result)==null?void 0:_a.state)==="fail"}),skipped2=tasks.filter(i=>i.mode==="skip"),todo=tasks.filter(i=>i.mode==="todo");return[failed.length?c2.bold(c2.red(`${failed.length} failed`)):null,passed.length?c2.bold(c2.green(`${passed.length} passed`)):null,skipped2.length?c2.yellow(`${skipped2.length} skipped`):null,todo.length?c2.gray(`${todo.length} todo`):null].filter(Boolean).join(c2.dim(" | "))+c2.gray(` (${tasks.length})`)}function getStateSymbol(task){if(task.mode==="skip"||task.mode==="todo")return skipped;if(!task.result)return c2.gray("\xB7");if(task.result.state==="run"){if(task.type==="suite")return pointer;let spinner=spinnerMap.get(task);return spinner||(spinner=elegantSpinner(),spinnerMap.set(task,spinner)),c2.yellow(spinner())}return task.result.state==="pass"?c2.green(F_CHECK):task.result.state==="fail"?task.type==="suite"?pointer:c2.red(F_CROSS):" "}function renderTree(tasks,level=0){var _a,_b,_c,_d;let output=[];for(let task of tasks){let delta=1,suffix=task.mode==="skip"||task.mode==="todo"?` ${c2.dim("[skipped]")}`:"",prefix=` ${getStateSymbol(task)} `;if(task.type==="suite"&&(suffix+=c2.dim(` (${getTests(task).length})`)),(_a=task.result)==null?void 0:_a.end){let duration=task.result.end-task.result.start;duration>DURATION_LONG&&(suffix+=c2.yellow(` ${Math.round(duration)}${c2.dim("ms")}`))}if(task.name?output.push(" ".repeat(level)+prefix+task.name+suffix):delta=0,((_b=task.result)==null?void 0:_b.state)!=="pass"&&outputMap.get(task)!=null){let data=outputMap.get(task);if(typeof data=="string"&&(data=stripAnsi(data.trim().split(`
|
|
10
|
+
`).filter(Boolean).pop()),data===""&&(data=void 0)),data!=null){let out=`${" ".repeat(level)}${F_RIGHT} ${data}`;output.push(` ${c2.gray(cliTruncate2(out,process.stdout.columns-3))}`)}}(((_c=task.result)==null?void 0:_c.state)==="fail"||((_d=task.result)==null?void 0:_d.state)==="run")&&task.type==="suite"&&task.tasks.length>0&&(output=output.concat(renderTree(task.tasks,level+delta)))}return output.slice(0,MAX_HEIGHT).join(`
|
|
11
|
+
`)}var createRenderer=_tasks=>{let tasks=_tasks,timer,log=createLogUpdate(process.stdout);function update(){log(renderTree(tasks))}return{start(){return timer?this:(timer=setInterval(update,200),this)},update(_tasks2){return tasks=_tasks2,update(),this},async stop(){return timer&&(clearInterval(timer),timer=void 0),log.clear(),console.log(renderTree(tasks)),this}}};function getFullName(task){return getNames(task).join(c2.gray(" > "))}var spinnerFrames=process.platform==="win32"?["-","\\","|","/"]:["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"];function elegantSpinner(){let index=0;return()=>(index=++index%spinnerFrames.length,spinnerFrames[index])}var isTTY=process.stdout.isTTY&&!process.env.CI,DefaultReporter=class{constructor(ctx){this.ctx=ctx;console.log(c3.green(`Running tests at ${c3.gray(this.ctx.config.root)}
|
|
12
|
+
`)),this.start=performance.now()}start=0;end=0;renderer;watchFilters;relative(path){return relative2(this.ctx.config.root,path)}onStart(){if(isTTY){let files=this.ctx.state.getFiles(this.watchFilters);this.renderer?this.renderer.update(files):this.renderer=createRenderer(files).start()}}onTaskUpdate(pack){var _a,_b,_c;if(isTTY)return;let task=this.ctx.state.idMap[pack[0]];task.type==="test"&&((_a=task.result)==null?void 0:_a.state)&&((_b=task.result)==null?void 0:_b.state)!=="run"&&(console.log(` ${getStateSymbol(task)} ${getFullName(task)}`),task.result.state==="fail"&&console.log(c3.red(` ${F_RIGHT} ${(_c=task.result.error)==null?void 0:_c.message}`)))}async onFinished(files=this.ctx.state.getFiles()){var _a,_b;this.end=performance.now(),await this.stopListRender(),console.log();let suites=getSuites(files),tests=getTests(files),failedSuites=suites.filter(i=>{var _a2;return(_a2=i.result)==null?void 0:_a2.error}),failedTests=tests.filter(i=>{var _a2;return((_a2=i.result)==null?void 0:_a2.state)==="fail"});if(failedSuites.length){console.error(c3.bold(c3.red(`
|
|
13
13
|
Failed to run ${failedSuites.length} suites:`)));for(let suite of failedSuites)console.error(c3.red(`
|
|
14
14
|
- ${getFullName(suite)}`)),await printError((_a=suite.result)==null?void 0:_a.error),console.log()}if(failedTests.length){console.error(c3.bold(c3.red(`
|
|
15
15
|
Failed Tests (${failedTests.length})`)));for(let test of failedTests)console.error(`${c3.red(`
|
|
16
|
-
${c3.inverse(" FAIL ")}`)} ${getFullName(test)}`),await printError((_b=test.result)==null?void 0:_b.error),console.log()}let executionTime=this.end-this.start,threadTime=tests.reduce((acc,test)=>{var _a2;return acc+(((_a2=test.result)==null?void 0:_a2.end)?test.result.end-test.result.start:0)},0),
|
|
17
|
-
`)),console.log()),console.log(
|
|
16
|
+
${c3.inverse(" FAIL ")}`)} ${getFullName(test)}`),await printError((_b=test.result)==null?void 0:_b.error),console.log()}let executionTime=this.end-this.start,threadTime=tests.reduce((acc,test)=>{var _a2;return acc+(((_a2=test.result)==null?void 0:_a2.end)?test.result.end-test.result.start:0)},0),padTitle=str=>c3.dim(`${str.padStart(10)} `),time=time2=>time2>1e3?`${(time2/1e3).toFixed(2)}s`:`${Math.round(time2)}ms`,snapshotOutput=renderSnapshotSummary(this.ctx.config.root,this.ctx.snapshot.summary);snapshotOutput.length&&(console.log(snapshotOutput.map((t,i)=>i===0?`${padTitle("Snapshots")} ${t}`:`${padTitle("")} ${t}`).join(`
|
|
17
|
+
`)),snapshotOutput.length>1&&console.log()),console.log(padTitle("Test Files"),getStateString(files)),console.log(padTitle("Tests"),getStateString(tests)),this.watchFilters?console.log(padTitle("Time"),time(threadTime)):console.log(padTitle("Time"),time(executionTime)+c3.gray(` (in thread ${time(threadTime)}, ${(executionTime/threadTime*100).toFixed(2)}%)`)),console.log()}async onWatcherStart(){await this.stopListRender();let failed=getTests(this.ctx.state.getFiles()).filter(i=>{var _a;return((_a=i.result)==null?void 0:_a.state)==="fail"});failed.length?console.log(`
|
|
18
18
|
${c3.bold(c3.inverse(c3.red(" FAIL ")))}${c3.red(` ${failed.length} tests failed. Watching for file changes...`)}`):console.log(`
|
|
19
19
|
${c3.bold(c3.inverse(c3.green(" PASS ")))}${c3.green(" Watching for file changes...")}`)}async onWatcherRerun(files,trigger){await this.stopListRender(),this.watchFilters=files,console.clear(),console.log(c3.blue("Re-running tests...")+c3.dim(` [ ${this.relative(trigger)} ]
|
|
20
|
-
`))}async stopListRender(){var _a;(_a=this.renderer)==null||_a.stop(),this.renderer=void 0,await new Promise(resolve2=>setTimeout(resolve2,100))}};init_esm_shims();var SnapshotManager=class{constructor(config){this.config=config;this.clear()}summary=void 0;clear(){this.summary=emptySummary(this.config.snapshotOptions)}add(result){addSnapshotResult(this.summary,result)}};init_esm_shims();import{resolve}from"path";import{findUp}from"find-up";import{createServer}from"vite";import{toArray}from"@antfu/utils";var configFiles=["vitest.config.ts","vitest.config.js","vitest.config.mjs","vite.config.ts","vite.config.js","vite.config.mjs"];async function initViteServer(options={}){var _a,_b
|
|
20
|
+
`))}async stopListRender(){var _a;(_a=this.renderer)==null||_a.stop(),this.renderer=void 0,await new Promise(resolve2=>setTimeout(resolve2,100))}};init_esm_shims();var SnapshotManager=class{constructor(config){this.config=config;this.clear()}summary=void 0;clear(){this.summary=emptySummary(this.config.snapshotOptions)}add(result){addSnapshotResult(this.summary,result)}};init_esm_shims();import{resolve}from"path";import{findUp}from"find-up";import{createServer}from"vite";import{toArray}from"@antfu/utils";var configFiles=["vitest.config.ts","vitest.config.js","vitest.config.mjs","vite.config.ts","vite.config.js","vite.config.mjs"];async function initViteServer(options={}){var _a,_b;let root=resolve(options.root||process.cwd());process.chdir(root);let configPath=options.config?resolve(root,options.config):await findUp(configFiles,{cwd:root}),resolved=__spreadValues({},options);resolved.config=configPath,resolved.root=root,options.cliFilters&&(resolved.cliFilters=toArray(options.cliFilters));let server=await createServer({root,logLevel:"error",clearScreen:!1,configFile:resolved.config,optimizeDeps:{exclude:["vitest"]}});await server.pluginContainer.buildStart({}),Object.assign(resolved,server.config.test),resolved.depsInline=((_a=resolved.deps)==null?void 0:_a.inline)||[],resolved.depsExternal=((_b=resolved.deps)==null?void 0:_b.external)||[],resolved.environment=resolved.environment||"node",resolved.threads=resolved.threads??!0,resolved.interpretDefault=resolved.interpretDefault??!0,resolved.includes=resolved.includes??defaultIncludes,resolved.excludes=resolved.excludes??defaultExcludes;let CI=!!process.env.CI,UPDATE_SNAPSHOT=resolved.update||process.env.UPDATE_SNAPSHOT;return resolved.snapshotOptions={updateSnapshot:CI&&!UPDATE_SNAPSHOT?"none":UPDATE_SNAPSHOT?"all":"new"},process.env.VITEST_MAX_THREADS&&(resolved.maxThreads=parseInt(process.env.VITEST_MAX_THREADS)),process.env.VITEST_MIN_THREADS&&(resolved.minThreads=parseInt(process.env.VITEST_MIN_THREADS)),{server,config:resolved}}init_esm_shims();init_esm_shims();import{MessageChannel}from"worker_threads";import{pathToFileURL}from"url";import Piscina from"piscina";init_esm_shims();async function transformRequest(server,id){if(id.match(/\.(?:[cm]?[jt]sx?|json)$/))return await server.transformRequest(id,{ssr:!0});{let result=await server.transformRequest(id);return result?await server.ssrTransform(result.code,result.map,id):void 0}}function createPool(ctx){return ctx.config.threads?createWorkerPool(ctx):createFakePool(ctx)}var workerPath=new URL("./dist/runtime/worker.js",pathToFileURL(distDir)).href;function createFakePool(ctx){return{runTestFiles:async(files,invalidates)=>{let{default:run}=await import(workerPath),{workerPort,port}=createChannel(ctx),data={port:workerPort,config:ctx.config,files,invalidates};await run(data,{transferList:[workerPort]}),port.close(),workerPort.close()},close:async()=>{}}}function createWorkerPool(ctx){let options={filename:workerPath};ctx.config.maxThreads!=null&&(options.maxThreads=ctx.config.maxThreads),ctx.config.minThreads!=null&&(options.minThreads=ctx.config.minThreads);let piscina=new Piscina(options);return{runTestFiles:async(files,invalidates)=>{await Promise.all(files.map(async file=>{let{workerPort,port}=createChannel(ctx),data={port:workerPort,config:ctx.config,files:[file],invalidates};await piscina.run(data,{transferList:[workerPort]}),port.close(),workerPort.close()}))},close:()=>piscina.destroy()}}function createChannel(ctx){let channel=new MessageChannel,port=channel.port2,workerPort=channel.port1;return port.on("message",async({id,method,args=[]})=>{var _a,_b,_c,_d;async function send(fn){try{port.postMessage({id,result:await fn()})}catch(e){port.postMessage({id,error:e})}}switch(method){case"snapshotSaved":return send(()=>ctx.snapshot.add(args[0]));case"fetch":return send(()=>transformRequest(ctx.server,...args));case"onCollected":ctx.state.collectFiles(args[0]),(_b=(_a=ctx.reporter).onStart)==null||_b.call(_a,args[0].map(i=>i.filepath));return;case"onTaskUpdate":ctx.state.updateTasks([args[0]]),(_d=(_c=ctx.reporter).onTaskUpdate)==null||_d.call(_c,args[0]);return}console.error("Unhandled message",method,args)}),{workerPort,port}}init_esm_shims();import fg from"fast-glob";import mm from"micromatch";function isTargetFile(id,config){return mm.isMatch(id,config.excludes)?!1:mm.isMatch(id,config.includes)}async function globTestFiles(config){var _a;let testFilepaths=await fg(config.includes,{absolute:!0,cwd:config.root,ignore:config.excludes});return((_a=config.cliFilters)==null?void 0:_a.length)&&(testFilepaths=testFilepaths.filter(i=>config.cliFilters.some(f=>i.includes(f)))),testFilepaths}init_esm_shims();import{slash as slash2}from"@antfu/utils";var WATCHER_DEBOUNCE=50;async function startWatcher(ctx,pool){var _a;let{reporter,server}=ctx;(_a=reporter.onWatcherStart)==null||_a.call(reporter);let timer,changedTests=new Set,seen=new Set,promise;server.watcher.on("change",id=>{id=slash2(id),getAffectedTests(ctx,id,changedTests,seen),changedTests.size!==0&&rerunFile(id)}),server.watcher.on("unlink",id=>{id=slash2(id),seen.add(id),id in ctx.state.filesMap&&(delete ctx.state.filesMap[id],changedTests.delete(id))}),server.watcher.on("add",async id=>{id=slash2(id),isTargetFile(id,ctx.config)&&(changedTests.add(id),rerunFile(id))});async function rerunFile(id){await promise,clearTimeout(timer),timer=setTimeout(async()=>{if(changedTests.size===0){seen.clear();return}ctx.state.getFiles().forEach(file=>{var _a2;((_a2=file.result)==null?void 0:_a2.state)==="fail"&&changedTests.add(file.filepath)});let invalidates=Array.from(seen),tests=Array.from(changedTests);changedTests.clear(),seen.clear(),promise=start2(tests,id,invalidates),await promise},WATCHER_DEBOUNCE)}async function start2(tests,id,invalidates){var _a2,_b,_c;await((_a2=reporter.onWatcherRerun)==null?void 0:_a2.call(reporter,tests,id)),await pool.runTestFiles(tests,invalidates),await((_b=reporter.onFinished)==null?void 0:_b.call(reporter,ctx.state.getFiles(tests))),await((_c=reporter.onWatcherStart)==null?void 0:_c.call(reporter))}await new Promise(()=>{})}function getAffectedTests(ctx,id,set=new Set,seen=new Set){if(seen.has(id)||set.has(id)||id.includes("/node_modules/")||id.includes("/vitest/dist/"))return set;if(seen.add(id),id in ctx.state.filesMap)return set.add(id),set;let mod=ctx.server.moduleGraph.getModuleById(id);return mod&&mod.importers.forEach(i=>{i.id&&getAffectedTests(ctx,i.id,set,seen)}),set}async function start(ctx){var _a,_b;let{config}=ctx,testFilepaths=await globTestFiles(config);if(!testFilepaths.length){console.error("No test files found"),process.exitCode=1;return}let pool=createPool(ctx);await pool.runTestFiles(testFilepaths),hasFailed(ctx.state.getFiles())&&(process.exitCode=1),await((_b=(_a=ctx.reporter).onFinished)==null?void 0:_b.call(_a,ctx.state.getFiles())),config.watch?await startWatcher(ctx,pool):await pool.close()}init_esm_shims();var StateManager=class{filesMap={};idMap={};taskFileMap=new WeakMap;getFiles(keys){return keys?keys.map(key=>this.filesMap[key]):Object.values(this.filesMap)}collectFiles(files){files.forEach(file=>{this.filesMap[file.filepath]=file,this.updateId(file)})}updateId(task){this.idMap[task.id]!==task&&(this.idMap[task.id]=task,task.type==="suite"&&task.tasks.forEach(task2=>{this.updateId(task2)}))}updateTasks(packs){for(let[id,result]of packs)this.idMap[id]&&(this.idMap[id].result=result)}};sade("vitest [filter]",!0).version(version).describe("A blazing fast unit test framework powered by Vite.").option("-r, --root","root path",process.cwd()).option("-c, --config","path to config file").option("-w, --watch","watch mode",!1).option("-u, --update","update snapshot",!1).option("--global","inject apis globally",!1).option("--dom","mock browser api happy-dom",!1).option("--environment","runner environment","").action(async(cliFilters,argv)=>{process.env.VITEST="true",console.log(c4.magenta(c4.bold(`
|
|
21
21
|
Vitest is in closed beta exclusively for Sponsors`))),console.log(c4.yellow(`Learn more at https://vitest.dev
|
|
22
|
-
`));let{config,server}=await initViteServer(__spreadProps(__spreadValues({},argv),{cliFilters})),ctx=process.__vitest__={server,config,state:new StateManager,snapshot:new SnapshotManager(config),reporter:config.reporter};installSourceMapSupport({environment:"node",hookRequire:!0,handleUncaughtExceptions:!0,retrieveSourceMap:id=>{var _a,_b;let map=(_b=(_a=ctx.server.moduleGraph.getModuleById(id))==null?void 0:_a.ssrTransformResult)==null?void 0:_b.map;return map?{url:id,map}:null}}),ctx.reporter=ctx.reporter||new DefaultReporter(ctx);try{await start(ctx)}catch(e){throw process.exitCode=1,e}finally{config.watch||await server.close()}}).parse(process.argv);
|
|
22
|
+
`)),argv.dom&&(argv.environment="happy-dom");let{config,server}=await initViteServer(__spreadProps(__spreadValues({},argv),{cliFilters})),ctx=process.__vitest__={server,config,state:new StateManager,snapshot:new SnapshotManager(config),reporter:config.reporter};installSourceMapSupport({environment:"node",hookRequire:!0,handleUncaughtExceptions:!0,retrieveSourceMap:id=>{var _a,_b;let map=(_b=(_a=ctx.server.moduleGraph.getModuleById(id))==null?void 0:_a.ssrTransformResult)==null?void 0:_b.map;return map?{url:id,map}:null}}),ctx.reporter=ctx.reporter||new DefaultReporter(ctx);try{await start(ctx)}catch(e){throw process.exitCode=1,e}finally{config.watch||await server.close()}}).parse(process.argv);
|
|
@@ -1,18 +1,111 @@
|
|
|
1
|
-
import { MessagePort } from 'worker_threads';
|
|
2
1
|
import { Awaitable } from '@antfu/utils';
|
|
3
|
-
import {
|
|
4
|
-
import { SnapshotStateOptions } from 'jest-snapshot/build/State';
|
|
2
|
+
import { OptionsReceived } from 'pretty-format';
|
|
5
3
|
|
|
6
|
-
declare
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
4
|
+
declare type RunMode = 'run' | 'skip' | 'only' | 'todo';
|
|
5
|
+
declare type TaskState = RunMode | 'pass' | 'fail';
|
|
6
|
+
declare type ComputeMode = 'serial' | 'concurrent';
|
|
7
|
+
interface TaskBase {
|
|
8
|
+
id: string;
|
|
9
|
+
name: string;
|
|
10
|
+
mode: RunMode;
|
|
11
|
+
computeMode: ComputeMode;
|
|
12
|
+
suite?: Suite;
|
|
13
|
+
file?: File;
|
|
14
|
+
result?: TaskResult;
|
|
15
|
+
}
|
|
16
|
+
interface TaskResult {
|
|
17
|
+
state: TaskState;
|
|
18
|
+
start: number;
|
|
19
|
+
end?: number;
|
|
20
|
+
error?: unknown;
|
|
21
|
+
}
|
|
22
|
+
declare type TaskResultPack = [id: string, result: TaskResult | undefined];
|
|
23
|
+
interface Suite extends TaskBase {
|
|
24
|
+
type: 'suite';
|
|
25
|
+
tasks: Task[];
|
|
26
|
+
}
|
|
27
|
+
interface File extends Suite {
|
|
28
|
+
filepath: string;
|
|
29
|
+
}
|
|
30
|
+
interface Test extends TaskBase {
|
|
31
|
+
type: 'test';
|
|
32
|
+
suite: Suite;
|
|
33
|
+
result?: TaskResult;
|
|
34
|
+
}
|
|
35
|
+
declare type Task = Test | Suite | File;
|
|
36
|
+
declare type TestFunction = () => Awaitable<void>;
|
|
37
|
+
declare type TestCollectorFn = (name: string, fn: TestFunction, timeout?: number) => void;
|
|
38
|
+
interface ConcurrentCollector {
|
|
39
|
+
(name: string, fn: TestFunction, timeout?: number): void;
|
|
40
|
+
only: TestCollectorFn;
|
|
41
|
+
skip: TestCollectorFn;
|
|
42
|
+
todo: (name: string) => void;
|
|
43
|
+
}
|
|
44
|
+
interface OnlyCollector {
|
|
45
|
+
(name: string, fn: TestFunction, timeout?: number): void;
|
|
46
|
+
concurrent: TestCollectorFn;
|
|
47
|
+
}
|
|
48
|
+
interface SkipCollector {
|
|
49
|
+
(name: string, fn: TestFunction, timeout?: number): void;
|
|
50
|
+
concurrent: TestCollectorFn;
|
|
51
|
+
}
|
|
52
|
+
interface TodoCollector {
|
|
53
|
+
(name: string): void;
|
|
54
|
+
concurrent: (name: string) => void;
|
|
55
|
+
}
|
|
56
|
+
interface TestCollector {
|
|
57
|
+
(name: string, fn: TestFunction, timeout?: number): void;
|
|
58
|
+
concurrent: ConcurrentCollector;
|
|
59
|
+
only: OnlyCollector;
|
|
60
|
+
skip: SkipCollector;
|
|
61
|
+
todo: TodoCollector;
|
|
62
|
+
}
|
|
63
|
+
declare type HookListener<T extends any[]> = (...args: T) => Awaitable<void>;
|
|
64
|
+
interface SuiteHooks {
|
|
65
|
+
beforeAll: HookListener<[Suite]>[];
|
|
66
|
+
afterAll: HookListener<[Suite]>[];
|
|
67
|
+
beforeEach: HookListener<[Test, Suite]>[];
|
|
68
|
+
afterEach: HookListener<[Test, Suite]>[];
|
|
69
|
+
}
|
|
70
|
+
interface SuiteCollector {
|
|
71
|
+
readonly name: string;
|
|
72
|
+
readonly mode: RunMode;
|
|
73
|
+
type: 'collector';
|
|
74
|
+
test: TestCollector;
|
|
75
|
+
tasks: (Suite | Test | SuiteCollector)[];
|
|
76
|
+
collect: (file?: File) => Promise<Suite>;
|
|
77
|
+
clear: () => void;
|
|
78
|
+
on: <T extends keyof SuiteHooks>(name: T, ...fn: SuiteHooks[T]) => void;
|
|
79
|
+
}
|
|
80
|
+
declare type TestFactory = (test: (name: string, fn: TestFunction) => void) => Awaitable<void>;
|
|
81
|
+
interface GlobalContext {
|
|
82
|
+
tasks: (SuiteCollector | Test)[];
|
|
83
|
+
currentSuite: SuiteCollector | null;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
interface Reporter {
|
|
87
|
+
onStart?: (files?: string[]) => Awaitable<void>;
|
|
88
|
+
onFinished?: (files?: File[]) => Awaitable<void>;
|
|
89
|
+
onTaskUpdate?: (pack: TaskResultPack) => Awaitable<void>;
|
|
90
|
+
onWatcherStart?: () => Awaitable<void>;
|
|
91
|
+
onWatcherRerun?: (files: string[], trigger: string) => Awaitable<void>;
|
|
14
92
|
}
|
|
15
93
|
|
|
94
|
+
declare type SnapshotData = Record<string, string>;
|
|
95
|
+
declare type SnapshotUpdateState = 'all' | 'new' | 'none';
|
|
96
|
+
declare type SnapshotStateOptions = {
|
|
97
|
+
updateSnapshot: SnapshotUpdateState;
|
|
98
|
+
expand?: boolean;
|
|
99
|
+
snapshotFormat?: OptionsReceived;
|
|
100
|
+
};
|
|
101
|
+
declare type SnapshotMatchOptions = {
|
|
102
|
+
testName: string;
|
|
103
|
+
received: unknown;
|
|
104
|
+
key?: string;
|
|
105
|
+
inlineSnapshot?: string;
|
|
106
|
+
isInline: boolean;
|
|
107
|
+
error?: Error;
|
|
108
|
+
};
|
|
16
109
|
interface SnapshotResult {
|
|
17
110
|
filepath: string;
|
|
18
111
|
added: number;
|
|
@@ -44,14 +137,6 @@ interface SnapshotSummary {
|
|
|
44
137
|
updated: number;
|
|
45
138
|
}
|
|
46
139
|
|
|
47
|
-
declare class SnapshotManager {
|
|
48
|
-
config: ResolvedConfig;
|
|
49
|
-
summary: SnapshotSummary;
|
|
50
|
-
constructor(config: ResolvedConfig);
|
|
51
|
-
clear(): void;
|
|
52
|
-
add(result: SnapshotResult): void;
|
|
53
|
-
}
|
|
54
|
-
|
|
55
140
|
interface UserOptions {
|
|
56
141
|
/**
|
|
57
142
|
* Include globs for test files
|
|
@@ -91,11 +176,13 @@ interface UserOptions {
|
|
|
91
176
|
*/
|
|
92
177
|
global?: boolean;
|
|
93
178
|
/**
|
|
94
|
-
*
|
|
179
|
+
* Running environment
|
|
95
180
|
*
|
|
96
|
-
*
|
|
181
|
+
* Supports 'node', 'jsdom', 'happy-dom'
|
|
182
|
+
*
|
|
183
|
+
* @default 'node'
|
|
97
184
|
*/
|
|
98
|
-
|
|
185
|
+
environment?: 'node' | 'jsdom' | 'happy-dom';
|
|
99
186
|
/**
|
|
100
187
|
* Update snapshot files
|
|
101
188
|
*
|
|
@@ -116,6 +203,25 @@ interface UserOptions {
|
|
|
116
203
|
* Custom reporter for output
|
|
117
204
|
*/
|
|
118
205
|
reporter?: Reporter;
|
|
206
|
+
/**
|
|
207
|
+
* Enable multi-threading
|
|
208
|
+
*
|
|
209
|
+
* @default true
|
|
210
|
+
*/
|
|
211
|
+
threads?: boolean;
|
|
212
|
+
/**
|
|
213
|
+
* Maximum number of threads
|
|
214
|
+
*
|
|
215
|
+
* @default available CPUs
|
|
216
|
+
*/
|
|
217
|
+
maxThreads?: number;
|
|
218
|
+
/**
|
|
219
|
+
* Minimum number of threads
|
|
220
|
+
*
|
|
221
|
+
* @default available CPUs
|
|
222
|
+
*/
|
|
223
|
+
minThreads?: number;
|
|
224
|
+
interpretDefault?: boolean;
|
|
119
225
|
}
|
|
120
226
|
interface CliOptions extends UserOptions {
|
|
121
227
|
/**
|
|
@@ -140,128 +246,5 @@ interface ResolvedConfig extends Omit<Required<CliOptions>, 'config' | 'filters'
|
|
|
140
246
|
depsExternal: (string | RegExp)[];
|
|
141
247
|
snapshotOptions: SnapshotStateOptions;
|
|
142
248
|
}
|
|
143
|
-
declare type RunMode = 'run' | 'skip' | 'only' | 'todo';
|
|
144
|
-
declare type TaskState = RunMode | 'pass' | 'fail';
|
|
145
|
-
declare type ComputeMode = 'serial' | 'concurrent';
|
|
146
|
-
interface TaskBase {
|
|
147
|
-
id: string;
|
|
148
|
-
name: string;
|
|
149
|
-
mode: RunMode;
|
|
150
|
-
computeMode: ComputeMode;
|
|
151
|
-
suite?: Suite;
|
|
152
|
-
file?: File;
|
|
153
|
-
result?: TaskResult;
|
|
154
|
-
}
|
|
155
|
-
interface TaskResult {
|
|
156
|
-
state: TaskState;
|
|
157
|
-
start: number;
|
|
158
|
-
end?: number;
|
|
159
|
-
error?: unknown;
|
|
160
|
-
}
|
|
161
|
-
declare type TaskResultPack = [id: string, result: TaskResult | undefined];
|
|
162
|
-
interface Suite extends TaskBase {
|
|
163
|
-
type: 'suite';
|
|
164
|
-
tasks: Task[];
|
|
165
|
-
}
|
|
166
|
-
interface File extends Suite {
|
|
167
|
-
filepath: string;
|
|
168
|
-
}
|
|
169
|
-
interface Test extends TaskBase {
|
|
170
|
-
type: 'test';
|
|
171
|
-
suite: Suite;
|
|
172
|
-
result?: TaskResult;
|
|
173
|
-
}
|
|
174
|
-
declare type Task = Test | Suite | File;
|
|
175
|
-
declare type TestFunction = () => Awaitable<void>;
|
|
176
|
-
declare type TestCollectorFn = (name: string, fn: TestFunction, timeout?: number) => void;
|
|
177
|
-
interface ConcurrentCollector {
|
|
178
|
-
(name: string, fn: TestFunction, timeout?: number): void;
|
|
179
|
-
only: TestCollectorFn;
|
|
180
|
-
skip: TestCollectorFn;
|
|
181
|
-
todo: (name: string) => void;
|
|
182
|
-
}
|
|
183
|
-
interface OnlyCollector {
|
|
184
|
-
(name: string, fn: TestFunction, timeout?: number): void;
|
|
185
|
-
concurrent: TestCollectorFn;
|
|
186
|
-
}
|
|
187
|
-
interface SkipCollector {
|
|
188
|
-
(name: string, fn: TestFunction, timeout?: number): void;
|
|
189
|
-
concurrent: TestCollectorFn;
|
|
190
|
-
}
|
|
191
|
-
interface TodoCollector {
|
|
192
|
-
(name: string): void;
|
|
193
|
-
concurrent: (name: string) => void;
|
|
194
|
-
}
|
|
195
|
-
interface TestCollector {
|
|
196
|
-
(name: string, fn: TestFunction, timeout?: number): void;
|
|
197
|
-
concurrent: ConcurrentCollector;
|
|
198
|
-
only: OnlyCollector;
|
|
199
|
-
skip: SkipCollector;
|
|
200
|
-
todo: TodoCollector;
|
|
201
|
-
}
|
|
202
|
-
declare type HookListener<T extends any[]> = (...args: T) => Awaitable<void>;
|
|
203
|
-
interface SuiteHooks {
|
|
204
|
-
beforeAll: HookListener<[Suite]>[];
|
|
205
|
-
afterAll: HookListener<[Suite]>[];
|
|
206
|
-
beforeEach: HookListener<[Test, Suite]>[];
|
|
207
|
-
afterEach: HookListener<[Test, Suite]>[];
|
|
208
|
-
}
|
|
209
|
-
interface SuiteCollector {
|
|
210
|
-
readonly name: string;
|
|
211
|
-
readonly mode: RunMode;
|
|
212
|
-
type: 'collector';
|
|
213
|
-
test: TestCollector;
|
|
214
|
-
tasks: (Suite | Test | SuiteCollector)[];
|
|
215
|
-
collect: (file?: File) => Promise<Suite>;
|
|
216
|
-
clear: () => void;
|
|
217
|
-
on: <T extends keyof SuiteHooks>(name: T, ...fn: SuiteHooks[T]) => void;
|
|
218
|
-
}
|
|
219
|
-
declare type TestFactory = (test: (name: string, fn: TestFunction) => void) => Awaitable<void>;
|
|
220
|
-
interface GlobalContext {
|
|
221
|
-
tasks: (SuiteCollector | Test)[];
|
|
222
|
-
currentSuite: SuiteCollector | null;
|
|
223
|
-
}
|
|
224
|
-
interface Reporter {
|
|
225
|
-
onStart?: (files?: string[]) => Awaitable<void>;
|
|
226
|
-
onFinished?: (files?: File[]) => Awaitable<void>;
|
|
227
|
-
onTaskUpdate?: (pack: TaskResultPack) => Awaitable<void>;
|
|
228
|
-
onWatcherStart?: () => Awaitable<void>;
|
|
229
|
-
onWatcherRerun?: (files: string[], trigger: string) => Awaitable<void>;
|
|
230
|
-
}
|
|
231
|
-
interface ModuleCache {
|
|
232
|
-
promise?: Promise<any>;
|
|
233
|
-
exports?: any;
|
|
234
|
-
transformResult?: TransformResult;
|
|
235
|
-
}
|
|
236
|
-
interface WorkerContext {
|
|
237
|
-
port: MessagePort;
|
|
238
|
-
config: ResolvedConfig;
|
|
239
|
-
files: string[];
|
|
240
|
-
invalidates?: string[];
|
|
241
|
-
}
|
|
242
|
-
interface RpcMap {
|
|
243
|
-
workerReady: [[], void];
|
|
244
|
-
fetch: [[id: string], TransformResult | null | undefined];
|
|
245
|
-
onCollected: [[files: File[]], void];
|
|
246
|
-
onFinished: [[], void];
|
|
247
|
-
onTaskUpdate: [[pack: TaskResultPack], void];
|
|
248
|
-
onWatcherStart: [[], void];
|
|
249
|
-
onWatcherRerun: [[files: string[], trigger: string], void];
|
|
250
|
-
snapshotSaved: [[snapshot: SnapshotResult], void];
|
|
251
|
-
}
|
|
252
|
-
declare type RpcCall = <T extends keyof RpcMap>(method: T, ...args: RpcMap[T][0]) => Promise<RpcMap[T][1]>;
|
|
253
|
-
declare type RpcSend = <T extends keyof RpcMap>(method: T, ...args: RpcMap[T][0]) => void;
|
|
254
|
-
declare type RpcPayload<T extends keyof RpcMap = keyof RpcMap> = {
|
|
255
|
-
id: string;
|
|
256
|
-
method: T;
|
|
257
|
-
args: RpcMap[T][0];
|
|
258
|
-
};
|
|
259
|
-
interface VitestContext {
|
|
260
|
-
config: ResolvedConfig;
|
|
261
|
-
server: ViteDevServer;
|
|
262
|
-
state: StateManager;
|
|
263
|
-
snapshot: SnapshotManager;
|
|
264
|
-
reporter: Reporter;
|
|
265
|
-
}
|
|
266
249
|
|
|
267
|
-
export { CliOptions as C, File as F, GlobalContext as G, HookListener as H,
|
|
250
|
+
export { CliOptions as C, File as F, GlobalContext as G, HookListener as H, ResolvedConfig as R, SnapshotResult as S, TaskResultPack as T, UserOptions as U, TestFactory as a, SuiteCollector as b, TestFunction as c, SuiteHooks as d, RunMode as e, TaskState as f, ComputeMode as g, TaskBase as h, TaskResult as i, Suite as j, Test as k, Task as l, TestCollector as m, Reporter as n, SnapshotData as o, SnapshotUpdateState as p, SnapshotStateOptions as q, SnapshotMatchOptions as r, UncheckedSnapshot as s, SnapshotSummary as t };
|
package/dist/runtime/entry.d.ts
CHANGED
|
@@ -1,8 +1,6 @@
|
|
|
1
|
-
import { R as ResolvedConfig } from '../
|
|
2
|
-
import 'worker_threads';
|
|
1
|
+
import { R as ResolvedConfig } from '../options-654578ef';
|
|
3
2
|
import '@antfu/utils';
|
|
4
|
-
import '
|
|
5
|
-
import 'jest-snapshot/build/State';
|
|
3
|
+
import 'pretty-format';
|
|
6
4
|
|
|
7
5
|
declare function run(files: string[], config: ResolvedConfig): Promise<void>;
|
|
8
6
|
|
package/dist/runtime/entry.js
CHANGED
|
@@ -1 +1,19 @@
|
|
|
1
|
-
import{getNames,hasFailed,hasTests,interpretOnlyMode,packSnapshotState,partitionSuiteChildren}from"../chunk-4STHXS4C.js";import{clearContext,context,createSuiteHooks,defaultSuite,getFn,getHooks,setHooks}from"../chunk-SLHZBXI2.js";import"../chunk-2PVIVCXM.js";import{init_esm_shims}from"../chunk-64PJVUUV.js";init_esm_shims();init_esm_shims();init_esm_shims();import chai from"chai";import SinonChai from"sinon-chai";import Subset from"chai-subset";init_esm_shims();init_esm_shims();import path from"path";import Snap from"jest-snapshot";import{expect}from"chai";init_esm_shims();var rpc=async(method,...args)=>{var _a;return(_a=process.__vitest_worker__)==null?void 0:_a.rpc(method,...args)},send=async(method,...args)=>{var _a;return(_a=process.__vitest_worker__)==null?void 0:_a.send(method,...args)};var{SnapshotState}=Snap,resolveSnapshotPath=testPath=>path.join(path.join(path.dirname(testPath),"__snapshots__"),`${path.basename(testPath)}.snap`),SnapshotClient=class{test;testFile="";snapshotState;setTest(test){this.test=test,this.testFile!==this.test.file.filepath&&(this.snapshotState&&this.saveSnap(),this.testFile=this.test.file.filepath,this.snapshotState=new SnapshotState(resolveSnapshotPath(this.testFile),process.__vitest_worker__.config.snapshotOptions))}clearTest(){this.test=void 0}assert(received,message){if(!this.test)throw new Error("Snapshot can't not be used outside of test");let{actual,expected,key,pass}=this.snapshotState.match({testName:getNames(this.test).slice(1).join(" > "),received,isInline:!1});pass||expect(actual.trim()).equals(expected?expected.trim():"",message||`Snapshot name: \`${key}\``)}async saveSnap(){if(!this.testFile||!this.snapshotState)return;let result=packSnapshotState(this.testFile,this.snapshotState);await rpc("snapshotSaved",result),this.testFile="",this.snapshotState=void 0}};var _client;function getSnapshotClient(){return _client||(_client=new SnapshotClient),_client}function SnapshotPlugin(){return function(chai2,utils){for(let key of["matchSnapshot","toMatchSnapshot"])utils.addMethod(chai2.Assertion.prototype,key,function(message){let expected=utils.flag(this,"object");getSnapshotClient().assert(expected,message)})}}init_esm_shims();function JestChaiExpect(){return(chai2,utils)=>{function def(name,fn){let addMethod=n=>{utils.addMethod(chai2.Assertion.prototype,n,fn)};Array.isArray(name)?name.forEach(n=>addMethod(n)):addMethod(name)}def("toEqual",function(expected){return this.eql(expected)}),def("toStrictEqual",function(expected){return this.equal(expected)}),def("toBe",function(expected){return this.equal(expected)}),def("toMatchObject",function(expected){return this.containSubset(expected)}),def("toMatch",function(expected){return typeof expected=="string"?this.include(expected):this.match(expected)}),def("toContain",function(item){return this.contain(item)}),def("toContainEqual",function(expected){let obj=utils.flag(this,"object"),index=Array.from(obj).findIndex(item=>{try{chai2.assert.deepEqual(item,expected)}catch{return!1}return!0});this.assert(index!==-1,"expected #{this} to deep equally contain #{exp}","expected #{this} to not deep equally contain #{exp}",expected)}),def("toBeTruthy",function(){let obj=utils.flag(this,"object");this.assert(Boolean(obj),"expected #{this} to be truthy","expected #{this} to not be truthy",obj)}),def("toBeFalsy",function(){let obj=utils.flag(this,"object");this.assert(!obj,"expected #{this} to be falsy","expected #{this} to not be falsy",obj)}),def("toBeGreaterThan",function(expected){return this.to.greaterThan(expected)}),def("toBeGreaterThanOrEqual",function(expected){return this.to.greaterThanOrEqual(expected)}),def("toBeLessThan",function(expected){return this.to.lessThan(expected)}),def("toBeLessThanOrEqual",function(expected){return this.to.lessThanOrEqual(expected)}),def("toBeNaN",function(){return this.be.NaN}),def("toBeUndefined",function(){return this.be.undefined}),def("toBeNull",function(){return this.be.null}),def("toBeDefined",function(){return this.not.be.undefined}),def("toBeInstanceOf",function(obj){return this.instanceOf(obj)}),def(["toHaveBeenCalledTimes","toBeCalledTimes"],function(number){return this.callCount(number)}),def("toHaveBeenCalledOnce",function(){return this.callCount(1)}),def(["toHaveBeenCalled","toBeCalled"],function(){return this.called}),def(["toHaveBeenCalledWith","toBeCalledWith"],function(...args){return this.calledWith(...args)}),def(["toThrow","toThrowError"],function(){utils.flag(this,"negate")?this.not.to.throw():this.to.throw()}),def(["toHaveReturned","toReturn"],function(){let spy=utils.flag(this,"object"),calledAndNotThrew=spy.called&&!spy.alwaysThrew();this.assert(calledAndNotThrew,"expected spy to be successfully called at least once","expected spy not to be successfully called",calledAndNotThrew,!calledAndNotThrew)}),def(["toHaveReturnedTimes","toReturnTimes"],function(times){let successfullReturns=utils.flag(this,"object").getCalls().reduce((success,call)=>call.threw()?success:++success,0);this.assert(successfullReturns===times,`expected spy to be successfully called ${times} times`,`expected spy not to be successfully called ${times} times`,`expected number of returns: ${times}`,`recieved number of returns: ${successfullReturns}`)}),def(["toHaveReturnedWith","toReturnWith"],function(value){return this.returned(value)}),def(["toHaveLastReturnedWith","lastReturnedWith"],function(value){let spy=utils.flag(this,"object"),lastReturn=spy.lastCall.returned(value);this.assert(lastReturn,"expected last spy call to return #{exp}","expected last spy call not to return #{exp}",value,spy.lastCall.returnValue)});let ordinalOf=i=>{let j=i%10,k=i%100;return j===1&&k!==11?`${i}st`:j===2&&k!==12?`${i}nd`:j===3&&k!==13?`${i}rd`:`${i}th`};def(["toHaveNthReturnedWith","nthReturnedWith"],function(nthCall,value){let spy=utils.flag(this,"object"),isNot=utils.flag(this,"negate"),call=spy.getCall(nthCall-1),ordinalCall=`${ordinalOf(nthCall)} call`;!isNot&&call.threw()&&chai2.assert.fail(`expected ${ordinalCall} to return #{exp}, but instead it threw an error`);let nthCallReturn=call.returned(value);this.assert(nthCallReturn,`expected ${ordinalCall} spy call to return #{exp}`,`expected ${ordinalCall} spy call not to return #{exp}`,value,call.returnValue)})}}var installed=!1;async function setupChai(){installed||(chai.use(SinonChai),chai.use(JestChaiExpect()),chai.use(Subset),chai.use(SnapshotPlugin()),installed=!0)}async function setupEnv(config){if(await setupChai(),config.global&&(await import("../global-PPDEK7CI.js")).registerApiGlobally(),config.dom==="happy-dom")return(await import("../happy-dom-EZVJENUI.js")).setupHappyDOM(globalThis).restore;if(config.dom)return(await import("../jsdom-VHB26LUJ.js")).setupJSDOM(globalThis).restore}init_esm_shims();import{performance as performance2}from"perf_hooks";init_esm_shims();import{basename}from"path";import{performance}from"perf_hooks";import{nanoid}from"nanoid";init_esm_shims();function processError(err){return err&&(err.stack&&(err.stackStr=String(err.stack)),err.name&&(err.nameStr=String(err.name)),err)}async function collectTests(paths){let files=[];for(let filepath of paths){let file={id:nanoid(),name:basename(filepath),type:"suite",mode:"run",computeMode:"serial",filepath,tasks:[]};setHooks(file,createSuiteHooks()),clearContext();try{await import(filepath);for(let c of[defaultSuite,...context.tasks])if(c.type==="test")file.tasks.push(c);else{let suite=await c.collect(file);(suite.name||suite.tasks.length)&&file.tasks.push(suite)}}catch(e){file.result={start:performance.now(),state:"fail",error:processError(e)},process.stdout.write("\0")}files.push(file)}let tasks=files.reduce((tasks2,file)=>tasks2.concat(file.tasks),[]);return interpretOnlyMode(tasks),tasks.forEach(i=>{i.type==="suite"&&(i.mode==="skip"?i.tasks.forEach(c=>c.mode==="run"&&(c.mode="skip")):interpretOnlyMode(i.tasks))}),files}async function callHook(suite,name,args){await Promise.all(getHooks(suite)[name].map(fn=>fn(...args)))}function updateTask(task){return rpc("onTaskUpdate",[task.id,task.result])}async function runTest(test){if(test.mode==="run"){test.result={start:performance2.now(),state:"run"},updateTask(test),getSnapshotClient().setTest(test);try{await callHook(test.suite,"beforeEach",[test,test.suite]),await getFn(test)(),test.result.state="pass"}catch(e){test.result.state="fail",test.result.error=processError(e)}try{await callHook(test.suite,"afterEach",[test,test.suite])}catch(e){test.result.state="fail",test.result.error=processError(e)}getSnapshotClient().clearTest(),test.result.end=performance2.now(),updateTask(test)}}async function runSuite(suite){var _a;if(((_a=suite.result)==null?void 0:_a.state)!=="fail"){if(suite.result={start:performance2.now(),state:"run"},updateTask(suite),suite.mode==="skip")suite.result.state="skip";else if(suite.mode==="todo")suite.result.state="todo";else try{await callHook(suite,"beforeAll",[suite]);for(let tasksGroup of partitionSuiteChildren(suite)){let computeMode=tasksGroup[0].computeMode;if(computeMode==="serial")for(let c of tasksGroup)await runSuiteChild(c);else computeMode==="concurrent"&&await Promise.all(tasksGroup.map(c=>runSuiteChild(c)))}await callHook(suite,"afterAll",[suite])}catch(e){suite.result.state="fail",suite.result.error=processError(e)}suite.result.end=performance2.now(),suite.mode==="run"&&(hasTests(suite)?hasFailed(suite)?suite.result.state="fail":suite.result.state="pass":(suite.result.state="fail",suite.result.error||(suite.result.error=new Error(`No tests found in suite ${suite.name}`)))),updateTask(suite)}}async function runSuiteChild(c){return c.type==="test"?runTest(c):runSuite(c)}async function runSuites(suites){for(let suite of suites)await runSuite(suite)}async function startTests(paths){let files=await collectTests(paths);send("onCollected",files),await runSuites(files),await getSnapshotClient().saveSnap()}async function run(files,config){let restore=await setupEnv(config);await startTests(files),restore==null||restore()}export{run};
|
|
1
|
+
import{getNames,hasFailed,hasTests,interpretOnlyMode,packSnapshotState,partitionSuiteChildren}from"../chunk-H3VLV7UP.js";import{clearContext,context,createSuiteHooks,defaultSuite,getFn,getHooks,setHooks}from"../chunk-3VLG4URE.js";import{__commonJS,__spreadValues,__toModule,init_esm_shims}from"../chunk-CNY47EZT.js";var require_natural_compare=__commonJS({"node_modules/.pnpm/natural-compare@1.4.0/node_modules/natural-compare/index.js"(exports,module){init_esm_shims();var naturalCompare2=function(a,b){var i,codeA,codeB=1,posA=0,posB=0,alphabet=String.alphabet;function getCode(str,pos,code){if(code){for(i=pos;code=getCode(str,i),code<76&&code>65;)++i;return+str.slice(pos-1,i)}return code=alphabet&&alphabet.indexOf(str.charAt(pos)),code>-1?code+76:(code=str.charCodeAt(pos)||0,code<45||code>127?code:code<46?65:code<48?code-1:code<58?code+18:code<65?code-11:code<91?code+11:code<97?code-37:code<123?code+5:code-63)}if((a+="")!=(b+="")){for(;codeB;)if(codeA=getCode(a,posA++),codeB=getCode(b,posB++),codeA<76&&codeB<76&&codeA>66&&codeB>66&&(codeA=getCode(a,posA,posA),codeB=getCode(b,posB,posA=i),posB=i),codeA!=codeB)return codeA<codeB?-1:1}return 0};try{module.exports=naturalCompare2}catch{String.naturalCompare=naturalCompare2}}});init_esm_shims();init_esm_shims();init_esm_shims();init_esm_shims();var node_default={name:"node",async setup(){return{teardown(){}}}};init_esm_shims();init_esm_shims();var LIVING_KEYS=["DOMException","URL","URLSearchParams","EventTarget","NamedNodeMap","Node","Attr","Element","DocumentFragment","DOMImplementation","Document","XMLDocument","CharacterData","Text","CDATASection","ProcessingInstruction","Comment","DocumentType","NodeList","HTMLCollection","HTMLOptionsCollection","DOMStringMap","DOMTokenList","StyleSheetList","HTMLElement","HTMLHeadElement","HTMLTitleElement","HTMLBaseElement","HTMLLinkElement","HTMLMetaElement","HTMLStyleElement","HTMLBodyElement","HTMLHeadingElement","HTMLParagraphElement","HTMLHRElement","HTMLPreElement","HTMLUListElement","HTMLOListElement","HTMLLIElement","HTMLMenuElement","HTMLDListElement","HTMLDivElement","HTMLAnchorElement","HTMLAreaElement","HTMLBRElement","HTMLButtonElement","HTMLCanvasElement","HTMLDataElement","HTMLDataListElement","HTMLDetailsElement","HTMLDialogElement","HTMLDirectoryElement","HTMLFieldSetElement","HTMLFontElement","HTMLFormElement","HTMLHtmlElement","HTMLImageElement","HTMLInputElement","HTMLLabelElement","HTMLLegendElement","HTMLMapElement","HTMLMarqueeElement","HTMLMediaElement","HTMLMeterElement","HTMLModElement","HTMLOptGroupElement","HTMLOptionElement","HTMLOutputElement","HTMLPictureElement","HTMLProgressElement","HTMLQuoteElement","HTMLScriptElement","HTMLSelectElement","HTMLSlotElement","HTMLSourceElement","HTMLSpanElement","HTMLTableCaptionElement","HTMLTableCellElement","HTMLTableColElement","HTMLTableElement","HTMLTimeElement","HTMLTableRowElement","HTMLTableSectionElement","HTMLTemplateElement","HTMLTextAreaElement","HTMLUnknownElement","HTMLFrameElement","HTMLFrameSetElement","HTMLIFrameElement","HTMLEmbedElement","HTMLObjectElement","HTMLParamElement","HTMLVideoElement","HTMLAudioElement","HTMLTrackElement","SVGElement","SVGGraphicsElement","SVGSVGElement","SVGTitleElement","SVGAnimatedString","SVGNumber","SVGStringList","Event","CloseEvent","CustomEvent","MessageEvent","ErrorEvent","HashChangeEvent","PopStateEvent","StorageEvent","ProgressEvent","PageTransitionEvent","UIEvent","FocusEvent","InputEvent","MouseEvent","KeyboardEvent","TouchEvent","CompositionEvent","WheelEvent","BarProp","External","Location","History","Screen","Performance","Navigator","PluginArray","MimeTypeArray","Plugin","MimeType","FileReader","Blob","File","FileList","ValidityState","DOMParser","XMLSerializer","FormData","XMLHttpRequestEventTarget","XMLHttpRequestUpload","XMLHttpRequest","WebSocket","NodeFilter","NodeIterator","TreeWalker","AbstractRange","Range","StaticRange","Selection","Storage","CustomElementRegistry","ShadowRoot","MutationObserver","MutationRecord","Headers","AbortController","AbortSignal"],OTHER_KEYS=["addEventListener","alert","atob","blur","btoa","close","confirm","createPopup","dispatchEvent","document","focus","frames","getComputedStyle","history","innerHeight","innerWidth","length","location","moveBy","moveTo","name","navigator","open","outerHeight","outerWidth","pageXOffset","pageYOffset","parent","postMessage","print","prompt","removeEventListener","resizeBy","resizeTo","screen","screenLeft","screenTop","screenX","screenY","scroll","scrollBy","scrollLeft","scrollTo","scrollTop","scrollX","scrollY","self","stop","top","window"],KEYS=LIVING_KEYS.concat(OTHER_KEYS);var jsdom_default={name:"jsdom",async setup(global){let{JSDOM}=await import("jsdom"),dom=new JSDOM("<!DOCTYPE html>",{pretendToBeVisual:!0,runScripts:"dangerously",url:"http://localhost:3000"}),keys=KEYS.concat(Object.getOwnPropertyNames(dom.window)).filter(k=>!k.startsWith("_")).filter(k=>!(k in global));for(let key of keys)global[key]=dom.window[key];return{teardown(global2){keys.forEach(key=>delete global2[key])}}}};init_esm_shims();var happy_dom_default={name:"happy-dom",async setup(global){let{Window}=await import("happy-dom"),win=new Window,keys=KEYS.concat(Object.getOwnPropertyNames(win)).filter(k=>!k.startsWith("_")).filter(k=>!(k in global));for(let key of keys)global[key]=win[key];return{teardown(global2){win.happyDOM.cancelAsync(),keys.forEach(key=>delete global2[key])}}}};var environments={node:node_default,jsdom:jsdom_default,"happy-dom":happy_dom_default};init_esm_shims();import chai from"chai";import SinonChai from"sinon-chai";import Subset from"chai-subset";init_esm_shims();init_esm_shims();import path2 from"path";import{expect}from"chai";init_esm_shims();var rpc=async(method,...args)=>{var _a;return(_a=process.__vitest_worker__)==null?void 0:_a.rpc(method,...args)},send=async(method,...args)=>{var _a;return(_a=process.__vitest_worker__)==null?void 0:_a.send(method,...args)};init_esm_shims();import fs2 from"fs";init_esm_shims();var import_natural_compare=__toModule(require_natural_compare());import path from"path";import fs from"fs";import{format as prettyFormat}from"pretty-format";init_esm_shims();import{plugins as prettyFormatPlugins}from"pretty-format";var{DOMCollection,DOMElement,Immutable,ReactElement,ReactTestComponent,AsymmetricMatcher}=prettyFormatPlugins,PLUGINS=[ReactTestComponent,ReactElement,DOMElement,DOMCollection,Immutable,AsymmetricMatcher];var getSerializers=()=>PLUGINS;var SNAPSHOT_VERSION="1",writeSnapshotVersion=()=>`// Vitest Snapshot v${SNAPSHOT_VERSION}`,testNameToKey=(testName,count)=>`${testName} ${count}`,keyToTestName=key=>{if(!/ \d+$/.test(key))throw new Error("Snapshot keys must end with a number.");return key.replace(/ \d+$/,"")},getSnapshotData=(snapshotPath,update)=>{let data=Object.create(null),snapshotContents="",dirty=!1;if(fs.existsSync(snapshotPath))try{snapshotContents=fs.readFileSync(snapshotPath,"utf8"),new Function("exports",snapshotContents)(data)}catch{}return(update==="all"||update==="new")&&snapshotContents&&(dirty=!0),{data,dirty}},addExtraLineBreaks=string=>string.includes(`
|
|
2
|
+
`)?`
|
|
3
|
+
${string}
|
|
4
|
+
`:string,removeExtraLineBreaks=string=>string.length>2&&string.startsWith(`
|
|
5
|
+
`)&&string.endsWith(`
|
|
6
|
+
`)?string.slice(1,-1):string,escapeRegex=!0,printFunctionName=!1;function serialize(val,indent=2,formatOverrides={}){return normalizeNewlines(prettyFormat(val,__spreadValues({escapeRegex,indent,plugins:getSerializers(),printFunctionName},formatOverrides)))}function escapeBacktickString(str){return str.replace(/`|\\|\${/g,"\\$&")}function printBacktickString(str){return`\`${escapeBacktickString(str)}\``}function ensureDirectoryExists(filePath){try{fs.mkdirSync(path.join(path.dirname(filePath)),{recursive:!0})}catch{}}function normalizeNewlines(string){return string.replace(/\r\n|\r/g,`
|
|
7
|
+
`)}function saveSnapshotFile(snapshotData,snapshotPath){let snapshots=Object.keys(snapshotData).sort(import_natural_compare.default).map(key=>`exports[${printBacktickString(key)}] = ${printBacktickString(normalizeNewlines(snapshotData[key]))};`);ensureDirectoryExists(snapshotPath),fs.writeFileSync(snapshotPath,`${writeSnapshotVersion()}
|
|
8
|
+
|
|
9
|
+
${snapshots.join(`
|
|
10
|
+
|
|
11
|
+
`)}
|
|
12
|
+
`)}var SnapshotState=class{_counters;_dirty;_index;_updateSnapshot;_snapshotData;_initialData;_snapshotPath;_uncheckedKeys;_snapshotFormat;added;expand;matched;unmatched;updated;constructor(snapshotPath,options){this._snapshotPath=snapshotPath;let{data,dirty}=getSnapshotData(this._snapshotPath,options.updateSnapshot);this._initialData=data,this._snapshotData=data,this._dirty=dirty,this._uncheckedKeys=new Set(Object.keys(this._snapshotData)),this._counters=new Map,this._index=0,this.expand=options.expand||!1,this.added=0,this.matched=0,this.unmatched=0,this._updateSnapshot=options.updateSnapshot,this.updated=0,this._snapshotFormat=options.snapshotFormat||{}}markSnapshotsAsCheckedForTest(testName){this._uncheckedKeys.forEach(uncheckedKey=>{keyToTestName(uncheckedKey)===testName&&this._uncheckedKeys.delete(uncheckedKey)})}_addSnapshot(key,receivedSerialized,options){this._dirty=!0,this._snapshotData[key]=receivedSerialized}clear(){this._snapshotData=this._initialData,this._counters=new Map,this._index=0,this.added=0,this.matched=0,this.unmatched=0,this.updated=0}save(){let hasExternalSnapshots=Object.keys(this._snapshotData).length,isEmpty=!hasExternalSnapshots,status={deleted:!1,saved:!1};return(this._dirty||this._uncheckedKeys.size)&&!isEmpty?(hasExternalSnapshots&&saveSnapshotFile(this._snapshotData,this._snapshotPath),status.saved=!0):!hasExternalSnapshots&&fs2.existsSync(this._snapshotPath)&&(this._updateSnapshot==="all"&&fs2.unlinkSync(this._snapshotPath),status.deleted=!0),status}getUncheckedCount(){return this._uncheckedKeys.size||0}getUncheckedKeys(){return Array.from(this._uncheckedKeys)}removeUncheckedKeys(){this._updateSnapshot==="all"&&this._uncheckedKeys.size&&(this._dirty=!0,this._uncheckedKeys.forEach(key=>delete this._snapshotData[key]),this._uncheckedKeys.clear())}match({testName,received,key,inlineSnapshot,isInline,error}){this._counters.set(testName,(this._counters.get(testName)||0)+1);let count=Number(this._counters.get(testName));key||(key=testNameToKey(testName,count)),isInline&&this._snapshotData[key]!==void 0||this._uncheckedKeys.delete(key);let receivedSerialized=addExtraLineBreaks(serialize(received,void 0,this._snapshotFormat)),expected=isInline?inlineSnapshot:this._snapshotData[key],pass=expected===receivedSerialized,hasSnapshot=expected!==void 0,snapshotIsPersisted=isInline||fs2.existsSync(this._snapshotPath);return pass&&!isInline&&(this._snapshotData[key]=receivedSerialized),hasSnapshot&&this._updateSnapshot==="all"||(!hasSnapshot||!snapshotIsPersisted)&&(this._updateSnapshot==="new"||this._updateSnapshot==="all")?(this._updateSnapshot==="all"?pass?this.matched++:(hasSnapshot?this.updated++:this.added++,this._addSnapshot(key,receivedSerialized,{error,isInline})):(this._addSnapshot(key,receivedSerialized,{error,isInline}),this.added++),{actual:"",count,expected:"",key,pass:!0}):pass?(this.matched++,{actual:"",count,expected:"",key,pass:!0}):(this.unmatched++,{actual:removeExtraLineBreaks(receivedSerialized),count,expected:expected!==void 0?removeExtraLineBreaks(expected):void 0,key,pass:!1})}fail(testName,_received,key){this._counters.set(testName,(this._counters.get(testName)||0)+1);let count=Number(this._counters.get(testName));return key||(key=testNameToKey(testName,count)),this._uncheckedKeys.delete(key),this.unmatched++,key}};var resolveSnapshotPath=testPath=>path2.join(path2.join(path2.dirname(testPath),"__snapshots__"),`${path2.basename(testPath)}.snap`),SnapshotClient=class{test;testFile="";snapshotState;setTest(test){this.test=test,this.testFile!==this.test.file.filepath&&(this.snapshotState&&this.saveSnap(),this.testFile=this.test.file.filepath,this.snapshotState=new SnapshotState(resolveSnapshotPath(this.testFile),process.__vitest_worker__.config.snapshotOptions))}clearTest(){this.test=void 0}assert(received,message){if(!this.test)throw new Error("Snapshot can't not be used outside of test");let{actual,expected,key,pass}=this.snapshotState.match({testName:getNames(this.test).slice(1).join(" > "),received,isInline:!1});pass||expect(actual.trim()).equals(expected?expected.trim():"",message||`Snapshot name: \`${key}\``)}async saveSnap(){if(!this.testFile||!this.snapshotState)return;let result=packSnapshotState(this.testFile,this.snapshotState);await rpc("snapshotSaved",result),this.testFile="",this.snapshotState=void 0}};var _client;function getSnapshotClient(){return _client||(_client=new SnapshotClient),_client}function SnapshotPlugin(){return function(chai2,utils){for(let key of["matchSnapshot","toMatchSnapshot"])utils.addMethod(chai2.Assertion.prototype,key,function(message){let expected=utils.flag(this,"object");getSnapshotClient().assert(expected,message)})}}init_esm_shims();function JestChaiExpect(){return(chai2,utils)=>{function def(name,fn){let addMethod=n=>{utils.addMethod(chai2.Assertion.prototype,n,fn)};Array.isArray(name)?name.forEach(n=>addMethod(n)):addMethod(name)}def("toEqual",function(expected){return this.eql(expected)}),def("toStrictEqual",function(expected){return this.equal(expected)}),def("toBe",function(expected){return this.equal(expected)}),def("toMatchObject",function(expected){return this.containSubset(expected)}),def("toMatch",function(expected){return typeof expected=="string"?this.include(expected):this.match(expected)}),def("toContain",function(item){return this.contain(item)}),def("toContainEqual",function(expected){let obj=utils.flag(this,"object"),index=Array.from(obj).findIndex(item=>{try{chai2.assert.deepEqual(item,expected)}catch{return!1}return!0});this.assert(index!==-1,"expected #{this} to deep equally contain #{exp}","expected #{this} to not deep equally contain #{exp}",expected)}),def("toBeTruthy",function(){let obj=utils.flag(this,"object");this.assert(Boolean(obj),"expected #{this} to be truthy","expected #{this} to not be truthy",obj)}),def("toBeFalsy",function(){let obj=utils.flag(this,"object");this.assert(!obj,"expected #{this} to be falsy","expected #{this} to not be falsy",obj)}),def("toBeGreaterThan",function(expected){return this.to.greaterThan(expected)}),def("toBeGreaterThanOrEqual",function(expected){return this.to.greaterThanOrEqual(expected)}),def("toBeLessThan",function(expected){return this.to.lessThan(expected)}),def("toBeLessThanOrEqual",function(expected){return this.to.lessThanOrEqual(expected)}),def("toBeNaN",function(){return this.be.NaN}),def("toBeUndefined",function(){return this.be.undefined}),def("toBeNull",function(){return this.be.null}),def("toBeDefined",function(){return this.not.be.undefined}),def("toBeInstanceOf",function(obj){return this.instanceOf(obj)}),def("toHaveLength",function(length){return this.have.length(length)}),def("toBeCloseTo",function(number,numDigits=2){return utils.expectTypes(this,["number"]),this.closeTo(number,numDigits)});function isSpy(putativeSpy){return typeof putativeSpy=="function"&&typeof putativeSpy.getCall=="function"&&typeof putativeSpy.calledWithExactly=="function"}function isCall(putativeCall){return putativeCall&&isSpy(putativeCall.proxy)}let assertIsMock=assertion=>{if(!isSpy(assertion._obj)&&!isCall(assertion._obj))throw new TypeError(`${utils.inspect(assertion._obj)} is not a spy or a call to a spy!`)};def(["toHaveBeenCalledTimes","toBeCalledTimes"],function(number){return assertIsMock(this),this.callCount(number)}),def("toHaveBeenCalledOnce",function(){return assertIsMock(this),this.callCount(1)}),def(["toHaveBeenCalled","toBeCalled"],function(){return assertIsMock(this),this.called}),def(["toHaveBeenCalledWith","toBeCalledWith"],function(...args){return assertIsMock(this),this.calledWith(...args)});let ordinalOf=i=>{let j=i%10,k=i%100;return j===1&&k!==11?`${i}st`:j===2&&k!==12?`${i}nd`:j===3&&k!==13?`${i}rd`:`${i}th`};def(["toHaveBeenNthCalledWith","nthCalledWith"],function(times,...args){assertIsMock(this);let nthCall=utils.flag(this,"object").getCall(times-1);this.assert(nthCall.calledWith(...args),`expected ${ordinalOf(times)} spy call to have been called with #{exp}`,`expected ${ordinalOf(times)} spy call not to have been called with #{exp}`,args,nthCall.args)}),def(["toHaveBeenLastCalledWith","lastCalledWith"],function(...args){assertIsMock(this);let spy=utils.flag(this,"object"),lastCall=spy.getCall(spy.returnValues.length-1);this.assert(lastCall.calledWith(...args),"expected last spy call to have been called with #{exp}","expected last spy call not to have been called with #{exp}",args,lastCall.args)}),def(["toThrow","toThrowError"],function(expected){utils.flag(this,"negate")?this.not.to.throw(expected):this.to.throw(expected)}),def(["toHaveReturned","toReturn"],function(){assertIsMock(this);let spy=utils.flag(this,"object"),calledAndNotThrew=spy.called&&!spy.alwaysThrew();this.assert(calledAndNotThrew,"expected spy to be successfully called at least once","expected spy not to be successfully called",calledAndNotThrew,!calledAndNotThrew)}),def(["toHaveReturnedTimes","toReturnTimes"],function(times){assertIsMock(this);let successfullReturns=utils.flag(this,"object").getCalls().reduce((success,call)=>call.threw()?success:++success,0);this.assert(successfullReturns===times,`expected spy to be successfully called ${times} times`,`expected spy not to be successfully called ${times} times`,`expected number of returns: ${times}`,`recieved number of returns: ${successfullReturns}`)}),def(["toHaveReturnedWith","toReturnWith"],function(value){return assertIsMock(this),this.returned(value)}),def(["toHaveLastReturnedWith","lastReturnedWith"],function(value){assertIsMock(this);let spy=utils.flag(this,"object"),lastReturn=spy.lastCall.returned(value);this.assert(lastReturn,"expected last spy call to return #{exp}","expected last spy call not to return #{exp}",value,spy.lastCall.returnValue)}),def(["toHaveNthReturnedWith","nthReturnedWith"],function(nthCall,value){assertIsMock(this);let spy=utils.flag(this,"object"),isNot=utils.flag(this,"negate"),call=spy.getCall(nthCall-1),ordinalCall=`${ordinalOf(nthCall)} call`;!isNot&&call.threw()&&chai2.assert.fail(`expected ${ordinalCall} to return #{exp}, but instead it threw an error`);let nthCallReturn=call.returned(value);this.assert(nthCallReturn,`expected ${ordinalCall} spy call to return #{exp}`,`expected ${ordinalCall} spy call not to return #{exp}`,value,call.returnValue)})}}var installed=!1;async function setupChai(){installed||(chai.use(SinonChai),chai.use(JestChaiExpect()),chai.use(Subset),chai.use(SnapshotPlugin()),installed=!0)}async function setupGlobalEnv(config){await setupChai(),config.global&&(await import("../global-E2TE3466.js")).registerApiGlobally()}async function withEnv(name,fn){let env=await environments[name].setup(globalThis);try{await fn()}finally{await env.teardown(globalThis)}}init_esm_shims();import{performance as performance2}from"perf_hooks";init_esm_shims();import{basename}from"path";import{performance}from"perf_hooks";import{nanoid}from"nanoid";init_esm_shims();function processError(err){return err&&(err.stack&&(err.stackStr=String(err.stack)),err.name&&(err.nameStr=String(err.name)),err)}async function collectTests(paths){let files=[];for(let filepath of paths){let file={id:nanoid(),name:basename(filepath),type:"suite",mode:"run",computeMode:"serial",filepath,tasks:[]};setHooks(file,createSuiteHooks()),clearContext();try{await import(filepath);for(let c of[defaultSuite,...context.tasks])if(c.type==="test")file.tasks.push(c);else{let suite=await c.collect(file);(suite.name||suite.tasks.length)&&file.tasks.push(suite)}}catch(e){file.result={start:performance.now(),state:"fail",error:processError(e)},process.stdout.write("\0")}files.push(file)}let tasks=files.reduce((tasks2,file)=>tasks2.concat(file.tasks),[]);return interpretOnlyMode(tasks),tasks.forEach(i=>{i.type==="suite"&&(i.mode==="skip"?i.tasks.forEach(c=>c.mode==="run"&&(c.mode="skip")):interpretOnlyMode(i.tasks))}),files}async function callHook(suite,name,args){await Promise.all(getHooks(suite)[name].map(fn=>fn(...args)))}function updateTask(task){return rpc("onTaskUpdate",[task.id,task.result])}async function runTest(test){if(test.mode==="run"){test.result={start:performance2.now(),state:"run"},updateTask(test),getSnapshotClient().setTest(test);try{await callHook(test.suite,"beforeEach",[test,test.suite]),await getFn(test)(),test.result.state="pass"}catch(e){test.result.state="fail",test.result.error=processError(e)}try{await callHook(test.suite,"afterEach",[test,test.suite])}catch(e){test.result.state="fail",test.result.error=processError(e)}getSnapshotClient().clearTest(),test.result.end=performance2.now(),updateTask(test)}}async function runSuite(suite){var _a;if(((_a=suite.result)==null?void 0:_a.state)!=="fail"){if(suite.result={start:performance2.now(),state:"run"},updateTask(suite),suite.mode==="skip")suite.result.state="skip";else if(suite.mode==="todo")suite.result.state="todo";else try{await callHook(suite,"beforeAll",[suite]);for(let tasksGroup of partitionSuiteChildren(suite)){let computeMode=tasksGroup[0].computeMode;if(computeMode==="serial")for(let c of tasksGroup)await runSuiteChild(c);else computeMode==="concurrent"&&await Promise.all(tasksGroup.map(c=>runSuiteChild(c)))}await callHook(suite,"afterAll",[suite])}catch(e){suite.result.state="fail",suite.result.error=processError(e)}suite.result.end=performance2.now(),suite.mode==="run"&&(hasTests(suite)?hasFailed(suite)?suite.result.state="fail":suite.result.state="pass":(suite.result.state="fail",suite.result.error||(suite.result.error=new Error(`No tests found in suite ${suite.name}`)))),updateTask(suite)}}async function runSuiteChild(c){return c.type==="test"?runTest(c):runSuite(c)}async function runSuites(suites){for(let suite of suites)await runSuite(suite)}async function startTests(paths){let files=await collectTests(paths);send("onCollected",files),await runSuites(files),await getSnapshotClient().saveSnap()}async function run(files,config){await setupGlobalEnv(config),await withEnv(config.environment,async()=>{await startTests(files)})}export{run};
|
|
13
|
+
/*
|
|
14
|
+
* @version 1.4.0
|
|
15
|
+
* @date 2015-10-26
|
|
16
|
+
* @stability 3 - Stable
|
|
17
|
+
* @author Lauri Rooden (https://github.com/litejs/natural-compare-lite)
|
|
18
|
+
* @license MIT License
|
|
19
|
+
*/
|
|
@@ -1,11 +1,12 @@
|
|
|
1
|
-
import '../index';
|
|
2
|
-
import { R as ResolvedConfig
|
|
3
|
-
import 'chai';
|
|
4
|
-
import 'sinon';
|
|
1
|
+
import { RpcCall, RpcSend, WorkerContext } from '../index';
|
|
2
|
+
import { R as ResolvedConfig } from '../options-654578ef';
|
|
5
3
|
import 'worker_threads';
|
|
6
|
-
import '@antfu/utils';
|
|
7
4
|
import 'vite';
|
|
8
|
-
import '
|
|
5
|
+
import '../general-39d52683';
|
|
6
|
+
import '@antfu/utils';
|
|
7
|
+
import 'chai';
|
|
8
|
+
import 'sinon';
|
|
9
|
+
import 'pretty-format';
|
|
9
10
|
|
|
10
11
|
declare function init(ctx: WorkerContext): Promise<(files: string[], config: ResolvedConfig) => Promise<void>>;
|
|
11
12
|
declare function run(ctx: WorkerContext): Promise<void>;
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import{distDir,init_esm_shims}from"../chunk-CNY47EZT.js";init_esm_shims();import{resolve as resolve2}from"path";import{nanoid}from"nanoid";init_esm_shims();import{builtinModules,createRequire}from"module";import{fileURLToPath,pathToFileURL}from"url";import{dirname,resolve}from"path";import vm from"vm";import{slash}from"@antfu/utils";var defaultInline=["vitest/dist","vitest/src","@vue","@vueuse","vue-demi","vue",/virtual:/,/\.ts$/,/\/esm\/.*\.js$/,/\.(es|esm|esm-browser|esm-bundler|es6).js$/],depsExternal=[/\.cjs.js$/],isWindows=process.platform==="win32",stubRequests={"/@vite/client":{injectQuery:id=>id,createHotContext(){return{accept:()=>{},prune:()=>{}}},updateStyle(){}}};async function interpretedImport(path,interpretDefault){let mod=await import(path);if(interpretDefault&&"__esModule"in mod&&"default"in mod){let defaultExport=mod.default;return"default"in defaultExport||Object.defineProperty(defaultExport,"default",{enumerable:!0,configurable:!0,get(){return defaultExport}}),defaultExport}return mod}async function executeInViteNode(options){let{moduleCache:moduleCache2,root,files,fetch}=options,externaled=new Set(builtinModules),result=[];for(let file of files)result.push(await cachedRequest(`/@fs/${slash(resolve(file))}`,[]));return result;async function directRequest(id,fsPath,callstack){callstack=[...callstack,id];let request=async dep=>{var _a;if(callstack.includes(dep)){let cacheKey=toFilePath(dep,root);if(!((_a=moduleCache2.get(cacheKey))==null?void 0:_a.exports))throw new Error(`Circular dependency detected
|
|
2
|
+
Stack:
|
|
3
|
+
${[...callstack,dep].reverse().map(p=>`- ${p}`).join(`
|
|
4
|
+
`)}`);return moduleCache2.get(cacheKey).exports}return cachedRequest(dep,callstack)};if(id in stubRequests)return stubRequests[id];let result2=await fetch(id);if(!result2)throw new Error(`failed to load ${id}`);let url=pathToFileURL(fsPath).href,exports={};setCache(fsPath,{transformResult:result2,exports});let __filename2=fileURLToPath(url),context={require:createRequire(url),__filename:__filename2,__dirname:dirname(__filename2),__vite_ssr_import__:request,__vite_ssr_dynamic_import__:request,__vite_ssr_exports__:exports,__vite_ssr_exportAll__:obj=>exportAll(exports,obj),__vite_ssr_import_meta__:{url}};return await vm.runInThisContext(`async (${Object.keys(context).join(",")})=>{${result2.code}
|
|
5
|
+
}`,{filename:fsPath,lineOffset:0})(...Object.values(context)),exports}function setCache(id,mod){moduleCache2.has(id)?Object.assign(moduleCache2.get(id),mod):moduleCache2.set(id,mod)}async function cachedRequest(rawId,callstack){var _a,_b;let id=normalizeId(rawId);if(externaled.has(id))return interpretedImport(id,options.interpretDefault);let fsPath=toFilePath(id,root),importPath=patchWindowsImportPath(fsPath);if(externaled.has(importPath)||await shouldExternalize(importPath,options))return externaled.add(importPath),interpretedImport(importPath,options.interpretDefault);if((_a=moduleCache2.get(fsPath))==null?void 0:_a.promise)return(_b=moduleCache2.get(fsPath))==null?void 0:_b.promise;let promise=directRequest(id,fsPath,callstack);return setCache(fsPath,{promise}),await promise}function exportAll(exports,sourceModule){for(let key in sourceModule)if(key!=="default")try{Object.defineProperty(exports,key,{enumerable:!0,configurable:!0,get(){return sourceModule[key]}})}catch{}}}function normalizeId(id){return id&&id.startsWith("/@id/__x00__")&&(id=`\0${id.slice("/@id/__x00__".length)}`),id&&id.startsWith("/@id/")&&(id=id.slice("/@id/".length)),id.startsWith("__vite-browser-external:")&&(id=id.slice("__vite-browser-external:".length)),id.startsWith("node:")&&(id=id.slice("node:".length)),id}async function shouldExternalize(id,config){return matchExternalizePattern(id,config.inline)?!1:matchExternalizePattern(id,config.external)||matchExternalizePattern(id,depsExternal)?!0:matchExternalizePattern(id,defaultInline)?!1:id.includes("/node_modules/")}function toFilePath(id,root){id=slash(id);let absolute=id.startsWith("/@fs/")?id.slice(4):id.startsWith(dirname(root))?id:id.startsWith("/")?slash(resolve(root,id.slice(1))):id;return absolute.startsWith("//")&&(absolute=absolute.slice(1)),isWindows&&absolute.startsWith("/")?pathToFileURL(absolute.slice(1)).href:absolute}function matchExternalizePattern(id,patterns){for(let ex of patterns)if(typeof ex=="string"){if(id.includes(`/node_modules/${ex}/`))return!0}else if(ex.test(id))return!0;return!1}function patchWindowsImportPath(path){return path.match(/^\w:\//)?`/${path}`:path}var _run,moduleCache=new Map;async function init(ctx){if(_run)return _run;let{config}=ctx;return _run=(await executeInViteNode({root:config.root,files:[resolve2(distDir,"runtime/entry.js")],fetch(id){return process.__vitest_worker__.rpc("fetch",id)},inline:config.depsInline,external:config.depsExternal,interpretDefault:config.interpretDefault,moduleCache}))[0].run,_run}async function run(ctx){process.stdout.write("\0");let{config,port}=ctx,rpcPromiseMap=new Map;process.__vitest_worker__={config,rpc:(method,...args)=>new Promise((resolve3,reject)=>{let id=nanoid();rpcPromiseMap.set(id,{resolve:resolve3,reject}),port.postMessage({method,args,id})}),send(method,...args){port.postMessage({method,args})}},port.addListener("message",async data=>{let api=rpcPromiseMap.get(data.id);api&&(data.error?api.reject(data.error):api.resolve(data.result))});let run2=await init(ctx);return ctx.invalidates&&ctx.invalidates.forEach(i=>moduleCache.delete(i)),ctx.files.forEach(i=>moduleCache.delete(i)),run2(ctx.files,ctx.config)}export{run as default,init};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "vitest",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.64",
|
|
4
4
|
"description": "A blazing fast unit test framework powered by Vite",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"vite",
|
|
@@ -48,32 +48,28 @@
|
|
|
48
48
|
"prepublishOnly": "nr build",
|
|
49
49
|
"release": "bumpp --commit --push --tag && esmo scripts/publish.ts",
|
|
50
50
|
"test": "node bin/vitest.mjs -r test/core",
|
|
51
|
-
"test:all": "pnpm -r --stream --filter !vitest run test --"
|
|
51
|
+
"test:all": "pnpm -r --stream --filter !vitest run test --",
|
|
52
|
+
"test:ci": "pnpm -r --stream --filter !vitest --filter !@vitest/test-fails run test --",
|
|
53
|
+
"docs": "npm -C docs run dev",
|
|
54
|
+
"docs:build": "npm -C docs run build",
|
|
55
|
+
"docs:serve": "npm -C docs run serve"
|
|
52
56
|
},
|
|
53
57
|
"dependencies": {
|
|
54
58
|
"@antfu/utils": "^0.3.0",
|
|
55
|
-
"@jest/test-result": "^27.4.2",
|
|
56
59
|
"@types/chai": "^4.3.0",
|
|
57
60
|
"@types/sinon-chai": "^3.2.6",
|
|
58
|
-
"c8": "^7.10.0",
|
|
59
61
|
"chai": "^4.3.4",
|
|
60
62
|
"chai-subset": "^1.6.0",
|
|
61
63
|
"cli-truncate": "^3.1.0",
|
|
62
64
|
"diff": "^5.0.0",
|
|
63
|
-
"elegant-spinner": "^3.0.0",
|
|
64
65
|
"fast-glob": "^3.2.7",
|
|
65
|
-
"figures": "^4.0.0",
|
|
66
66
|
"find-up": "^6.2.0",
|
|
67
|
-
"happy-dom": "^2.24.5",
|
|
68
|
-
"jest-snapshot": "^27.4.2",
|
|
69
|
-
"jest-util": "^27.4.2",
|
|
70
|
-
"jsdom": "^19.0.0",
|
|
71
|
-
"nanoid": "^3.1.30",
|
|
72
|
-
"log-symbols": "^4.1.0",
|
|
73
67
|
"log-update": "^5.0.0",
|
|
74
|
-
"
|
|
68
|
+
"micromatch": "^4.0.4",
|
|
69
|
+
"nanoid": "^3.1.30",
|
|
75
70
|
"picocolors": "^1.0.0",
|
|
76
|
-
"piscina": "^3.
|
|
71
|
+
"piscina": "^3.2.0",
|
|
72
|
+
"pretty-format": "^27.4.2",
|
|
77
73
|
"sade": "^1.7.4",
|
|
78
74
|
"sinon": "^12.0.1",
|
|
79
75
|
"sinon-chai": "^3.7.0",
|
|
@@ -82,27 +78,46 @@
|
|
|
82
78
|
"strip-ansi": "^7.0.1"
|
|
83
79
|
},
|
|
84
80
|
"devDependencies": {
|
|
85
|
-
"@antfu/eslint-config": "^0.
|
|
86
|
-
"@antfu/ni": "^0.
|
|
81
|
+
"@antfu/eslint-config": "^0.13.1",
|
|
82
|
+
"@antfu/ni": "^0.12.0",
|
|
87
83
|
"@types/chai-subset": "^1.3.3",
|
|
88
84
|
"@types/diff": "^5.0.1",
|
|
89
85
|
"@types/jsdom": "^16.2.13",
|
|
86
|
+
"@types/micromatch": "^4.0.2",
|
|
87
|
+
"@types/natural-compare": "^1.4.1",
|
|
90
88
|
"@types/node": "^16.11.12",
|
|
91
89
|
"@types/sade": "^1.7.3",
|
|
92
90
|
"@types/sinon": "^10.0.6",
|
|
93
91
|
"@types/source-map-support": "^0.5.4",
|
|
94
92
|
"bumpp": "^7.1.1",
|
|
93
|
+
"c8": "^7.10.0",
|
|
95
94
|
"eslint": "^8.4.1",
|
|
96
95
|
"esno": "^0.12.1",
|
|
96
|
+
"happy-dom": "^2.24.5",
|
|
97
|
+
"jsdom": "^19.0.0",
|
|
97
98
|
"npm-run-all": "^4.1.5",
|
|
98
99
|
"rimraf": "^3.0.2",
|
|
99
|
-
"tsup": "^5.
|
|
100
|
-
"typescript": "^4.5.
|
|
100
|
+
"tsup": "^5.11.1",
|
|
101
|
+
"typescript": "^4.5.3",
|
|
101
102
|
"vite": "^2.7.1"
|
|
102
103
|
},
|
|
103
104
|
"peerDependencies": {
|
|
105
|
+
"c8": "*",
|
|
106
|
+
"happy-dom": "*",
|
|
107
|
+
"jsdom": "*",
|
|
104
108
|
"vite": "^2.7.1"
|
|
105
109
|
},
|
|
110
|
+
"peerDependenciesMeta": {
|
|
111
|
+
"happy-dom": {
|
|
112
|
+
"optional": true
|
|
113
|
+
},
|
|
114
|
+
"jsdom": {
|
|
115
|
+
"optional": true
|
|
116
|
+
},
|
|
117
|
+
"c8": {
|
|
118
|
+
"optional": true
|
|
119
|
+
}
|
|
120
|
+
},
|
|
106
121
|
"engines": {
|
|
107
122
|
"node": ">=16.0.0"
|
|
108
123
|
}
|
package/dist/chunk-2AYT2TPD.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{init_esm_shims}from"./chunk-64PJVUUV.js";init_esm_shims();var LIVING_KEYS=["DOMException","URL","URLSearchParams","EventTarget","NamedNodeMap","Node","Attr","Element","DocumentFragment","DOMImplementation","Document","XMLDocument","CharacterData","Text","CDATASection","ProcessingInstruction","Comment","DocumentType","NodeList","HTMLCollection","HTMLOptionsCollection","DOMStringMap","DOMTokenList","StyleSheetList","HTMLElement","HTMLHeadElement","HTMLTitleElement","HTMLBaseElement","HTMLLinkElement","HTMLMetaElement","HTMLStyleElement","HTMLBodyElement","HTMLHeadingElement","HTMLParagraphElement","HTMLHRElement","HTMLPreElement","HTMLUListElement","HTMLOListElement","HTMLLIElement","HTMLMenuElement","HTMLDListElement","HTMLDivElement","HTMLAnchorElement","HTMLAreaElement","HTMLBRElement","HTMLButtonElement","HTMLCanvasElement","HTMLDataElement","HTMLDataListElement","HTMLDetailsElement","HTMLDialogElement","HTMLDirectoryElement","HTMLFieldSetElement","HTMLFontElement","HTMLFormElement","HTMLHtmlElement","HTMLImageElement","HTMLInputElement","HTMLLabelElement","HTMLLegendElement","HTMLMapElement","HTMLMarqueeElement","HTMLMediaElement","HTMLMeterElement","HTMLModElement","HTMLOptGroupElement","HTMLOptionElement","HTMLOutputElement","HTMLPictureElement","HTMLProgressElement","HTMLQuoteElement","HTMLScriptElement","HTMLSelectElement","HTMLSlotElement","HTMLSourceElement","HTMLSpanElement","HTMLTableCaptionElement","HTMLTableCellElement","HTMLTableColElement","HTMLTableElement","HTMLTimeElement","HTMLTableRowElement","HTMLTableSectionElement","HTMLTemplateElement","HTMLTextAreaElement","HTMLUnknownElement","HTMLFrameElement","HTMLFrameSetElement","HTMLIFrameElement","HTMLEmbedElement","HTMLObjectElement","HTMLParamElement","HTMLVideoElement","HTMLAudioElement","HTMLTrackElement","SVGElement","SVGGraphicsElement","SVGSVGElement","SVGTitleElement","SVGAnimatedString","SVGNumber","SVGStringList","Event","CloseEvent","CustomEvent","MessageEvent","ErrorEvent","HashChangeEvent","PopStateEvent","StorageEvent","ProgressEvent","PageTransitionEvent","UIEvent","FocusEvent","InputEvent","MouseEvent","KeyboardEvent","TouchEvent","CompositionEvent","WheelEvent","BarProp","External","Location","History","Screen","Performance","Navigator","PluginArray","MimeTypeArray","Plugin","MimeType","FileReader","Blob","File","FileList","ValidityState","DOMParser","XMLSerializer","FormData","XMLHttpRequestEventTarget","XMLHttpRequestUpload","XMLHttpRequest","WebSocket","NodeFilter","NodeIterator","TreeWalker","AbstractRange","Range","StaticRange","Selection","Storage","CustomElementRegistry","ShadowRoot","MutationObserver","MutationRecord","Headers","AbortController","AbortSignal"],OTHER_KEYS=["addEventListener","alert","atob","blur","btoa","close","confirm","createPopup","dispatchEvent","document","focus","frames","getComputedStyle","history","innerHeight","innerWidth","length","location","moveBy","moveTo","name","navigator","open","outerHeight","outerWidth","pageXOffset","pageYOffset","parent","postMessage","print","prompt","removeEventListener","resizeBy","resizeTo","screen","screenLeft","screenTop","screenX","screenY","scroll","scrollBy","scrollLeft","scrollTo","scrollTop","scrollX","scrollY","self","stop","top","window"],KEYS=LIVING_KEYS.concat(OTHER_KEYS);export{KEYS};
|
package/dist/chunk-2PVIVCXM.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{init_esm_shims}from"./chunk-64PJVUUV.js";init_esm_shims();import{resolve}from"path";import{fileURLToPath}from"url";var distDir=resolve(fileURLToPath(import.meta.url),"../../dist"),defaultTestTimeout=5e3,defaultHookTimeout=5e3,defaultIncludes=["**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}"],defaultExcludes=["**/node_modules/**","**/dist/**"],globalApis=["suite","test","describe","it","chai","expect","assert","sinon","spy","mock","stub","beforeAll","afterAll","beforeEach","afterEach"];export{distDir,defaultTestTimeout,defaultHookTimeout,defaultIncludes,defaultExcludes,globalApis};
|
package/dist/chunk-4STHXS4C.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{init_esm_shims}from"./chunk-64PJVUUV.js";init_esm_shims();import{toArray}from"@antfu/utils";function partitionSuiteChildren(suite){let tasksGroup=[],tasksGroups=[];for(let c of suite.tasks)tasksGroup.length===0||c.computeMode===tasksGroup[0].computeMode?tasksGroup.push(c):(tasksGroups.push(tasksGroup),tasksGroup=[c]);return tasksGroup.length>0&&tasksGroups.push(tasksGroup),tasksGroups}function interpretOnlyMode(items){items.some(i=>i.mode==="only")&&items.forEach(i=>{i.mode==="run"?i.mode="skip":i.mode==="only"&&(i.mode="run")})}function getTests(suite){return toArray(suite).flatMap(s=>s.tasks.flatMap(c=>c.type==="test"?[c]:getTests(c)))}function getSuites(suite){return toArray(suite).flatMap(s=>s.type==="suite"?[s,...getSuites(s.tasks)]:[])}function hasTests(suite){return toArray(suite).some(s=>s.tasks.some(c=>c.type==="test"||hasTests(c)))}function hasFailed(suite){return toArray(suite).some(s=>{var _a;return((_a=s.result)==null?void 0:_a.state)==="fail"||s.type==="suite"&&hasFailed(s.tasks)})}function getNames(task){let names=[task.name],current=task;for(;(current==null?void 0:current.suite)||(current==null?void 0:current.file);)current=current.suite||current.file,(current==null?void 0:current.name)&&names.unshift(current.name);return names}init_esm_shims();import Test from"@jest/test-result";var{makeEmptyAggregatedTestResult}=Test,emptySummary=options=>{let summary=makeEmptyAggregatedTestResult().snapshot;return summary.didUpdate=options.updateSnapshot==="all",summary},packSnapshotState=(filepath,snapshotState)=>{let snapshot={filepath,added:0,fileDeleted:!1,matched:0,unchecked:0,uncheckedKeys:[],unmatched:0,updated:0},uncheckedCount=snapshotState.getUncheckedCount(),uncheckedKeys=snapshotState.getUncheckedKeys();uncheckedCount&&snapshotState.removeUncheckedKeys();let status=snapshotState.save();return snapshot.fileDeleted=status.deleted,snapshot.added=snapshotState.added,snapshot.matched=snapshotState.matched,snapshot.unmatched=snapshotState.unmatched,snapshot.updated=snapshotState.updated,snapshot.unchecked=status.deleted?0:uncheckedCount,snapshot.uncheckedKeys=Array.from(uncheckedKeys),snapshot},addSnapshotResult=(snapshotSummary,snapshotResult)=>{snapshotResult.added&&snapshotSummary.filesAdded++,snapshotResult.fileDeleted&&snapshotSummary.filesRemoved++,snapshotResult.unmatched&&snapshotSummary.filesUnmatched++,snapshotResult.updated&&snapshotSummary.filesUpdated++,snapshotSummary.added+=snapshotResult.added,snapshotSummary.matched+=snapshotResult.matched,snapshotSummary.unchecked+=snapshotResult.unchecked,snapshotResult.uncheckedKeys&&snapshotResult.uncheckedKeys.length>0&&snapshotSummary.uncheckedKeysByFile.push({filePath:snapshotResult.filepath,keys:snapshotResult.uncheckedKeys}),snapshotSummary.unmatched+=snapshotResult.unmatched,snapshotSummary.updated+=snapshotResult.updated,snapshotSummary.total+=snapshotResult.added+snapshotResult.matched+snapshotResult.unmatched+snapshotResult.updated};export{partitionSuiteChildren,interpretOnlyMode,getTests,getSuites,hasTests,hasFailed,getNames,emptySummary,packSnapshotState,addSnapshotResult};
|
package/dist/chunk-SLHZBXI2.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{defaultHookTimeout,defaultTestTimeout}from"./chunk-2PVIVCXM.js";import{init_esm_shims}from"./chunk-64PJVUUV.js";init_esm_shims();import{nanoid}from"nanoid";init_esm_shims();var context={tasks:[],currentSuite:null};init_esm_shims();var fnMap=new WeakMap,hooksMap=new WeakMap;function setFn(key,fn){fnMap.set(key,fn)}function getFn(key){return fnMap.get(key)}function setHooks(key,hooks){hooksMap.set(key,hooks)}function getHooks(key){return hooksMap.get(key)}var suite=createSuite(),defaultSuite=suite("");function getCurrentSuite(){return context.currentSuite||defaultSuite}function createSuiteHooks(){return{beforeAll:[],afterAll:[],beforeEach:[],afterEach:[]}}function createSuiteCollector(name,factory=()=>{},mode,suiteComputeMode){var _a;let tasks=[],factoryQueue=[],suite2;initSuite();let test2=createTestCollector((name2,fn,mode2,computeMode)=>{let test3={id:nanoid(),type:"test",name:name2,mode:mode2,computeMode:computeMode??suiteComputeMode??"serial",suite:void 0};setFn(test3,fn),tasks.push(test3)}),collector={type:"collector",name,mode,test:test2,tasks,collect,clear,on:addHook};function addHook(name2,...fn){getHooks(suite2)[name2].push(...fn)}function initSuite(){suite2={id:nanoid(),type:"suite",computeMode:"serial",name,mode,tasks:[]},setHooks(suite2,createSuiteHooks())}function clear(){tasks.length=0,factoryQueue.length=0,initSuite()}async function collect(file){if(factoryQueue.length=0,factory){let prev=context.currentSuite;context.currentSuite=collector,await factory(test2),context.currentSuite=prev}let allChildren=await Promise.all([...factoryQueue,...tasks].map(i=>i.type==="collector"?i.collect(file):i));return suite2.file=file,suite2.tasks=allChildren,allChildren.forEach(task=>{task.suite=suite2,file&&(task.file=file)}),suite2}return(_a=context.currentSuite)==null||_a.tasks.push(collector),collector}function createTestCollector(collectTest){function test2(name,fn,timeout){collectTest(name,withTimeout(fn,timeout),"run")}test2.concurrent=concurrent,test2.skip=skip,test2.only=only,test2.todo=todo;function concurrent(name,fn,timeout){collectTest(name,withTimeout(fn,timeout),"run","concurrent")}concurrent.skip=(name,fn,timeout)=>collectTest(name,withTimeout(fn,timeout),"skip","concurrent"),concurrent.only=(name,fn,timeout)=>collectTest(name,withTimeout(fn,timeout),"only","concurrent"),concurrent.todo=todo;function skip(name,fn,timeout){collectTest(name,withTimeout(fn,timeout),"skip")}skip.concurrent=concurrent.skip;function only(name,fn,timeout){collectTest(name,withTimeout(fn,timeout),"only")}only.concurrent=concurrent.only;function todo(name){collectTest(name,()=>{},"todo")}return todo.concurrent=todo,test2}var test=function(){function test2(name,fn,timeout){return getCurrentSuite().test(name,fn,timeout)}function concurrent(name,fn,timeout){return getCurrentSuite().test.concurrent(name,fn,timeout)}concurrent.skip=(name,fn,timeout)=>getCurrentSuite().test.concurrent.skip(name,fn,timeout),concurrent.only=(name,fn,timeout)=>getCurrentSuite().test.concurrent.only(name,fn,timeout),concurrent.todo=name=>getCurrentSuite().test.concurrent.todo(name);function skip(name,fn,timeout){return getCurrentSuite().test.skip(name,fn,timeout)}skip.concurrent=(name,fn,timeout)=>getCurrentSuite().test.skip.concurrent(name,fn,timeout);function only(name,fn,timeout){return getCurrentSuite().test.only(name,fn,timeout)}only.concurrent=(name,fn,timeout)=>getCurrentSuite().test.only.concurrent(name,fn,timeout);function todo(name){return getCurrentSuite().test.todo(name)}return todo.concurrent=name=>getCurrentSuite().test.todo.concurrent(name),test2.concurrent=concurrent,test2.skip=skip,test2.only=only,test2.todo=todo,test2}();function createSuite(){function suite2(suiteName,factory){return createSuiteCollector(suiteName,factory,"run")}function concurrent(suiteName,factory){return createSuiteCollector(suiteName,factory,"run","concurrent")}concurrent.skip=(suiteName,factory)=>createSuiteCollector(suiteName,factory,"skip","concurrent"),concurrent.only=(suiteName,factory)=>createSuiteCollector(suiteName,factory,"only","concurrent"),concurrent.todo=suiteName=>createSuiteCollector(suiteName,void 0,"todo");function skip(suiteName,factory){return createSuiteCollector(suiteName,factory,"skip")}skip.concurrent=concurrent.skip;function only(suiteName,factory){return createSuiteCollector(suiteName,factory,"only")}only.concurrent=concurrent.only;function todo(suiteName){return createSuiteCollector(suiteName,void 0,"todo")}return todo.concurrent=concurrent.todo,suite2.concurrent=concurrent,suite2.skip=skip,suite2.only=only,suite2.todo=todo,suite2}var describe=suite,it=test,beforeAll=(fn,timeout=defaultHookTimeout)=>getCurrentSuite().on("beforeAll",withTimeout(fn,timeout)),afterAll=(fn,timeout=defaultHookTimeout)=>getCurrentSuite().on("afterAll",withTimeout(fn,timeout)),beforeEach=(fn,timeout=defaultHookTimeout)=>getCurrentSuite().on("beforeEach",withTimeout(fn,timeout)),afterEach=(fn,timeout=defaultHookTimeout)=>getCurrentSuite().on("afterEach",withTimeout(fn,timeout));function clearContext(){context.tasks.length=0,defaultSuite.clear(),context.currentSuite=defaultSuite}function withTimeout(fn,timeout=defaultTestTimeout){return timeout<=0||timeout===1/0?fn:(...args)=>Promise.race([fn(...args),new Promise((resolve,reject)=>{let timer=setTimeout(()=>{clearTimeout(timer),reject(new Error(`Test timed out in ${timeout}ms.`))},timeout);timer.unref()})])}export{context,getFn,setHooks,getHooks,suite,defaultSuite,createSuiteHooks,test,describe,it,beforeAll,afterAll,beforeEach,afterEach,clearContext};
|
package/dist/global-PPDEK7CI.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{src_exports}from"./chunk-BC6SKI3B.js";import"./chunk-SLHZBXI2.js";import{globalApis}from"./chunk-2PVIVCXM.js";import{init_esm_shims}from"./chunk-64PJVUUV.js";init_esm_shims();function registerApiGlobally(){globalApis.forEach(api=>{globalThis[api]=src_exports[api]})}export{registerApiGlobally};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{KEYS}from"./chunk-2AYT2TPD.js";import{init_esm_shims}from"./chunk-64PJVUUV.js";init_esm_shims();import{Window}from"happy-dom";function setupHappyDOM(global){let win=new Window,keys=KEYS.concat(Object.getOwnPropertyNames(win)).filter(k=>!k.startsWith("_")).filter(k=>!(k in global));for(let key of keys)global[key]=win[key];return{dom:win,restore(){win.happyDOM.cancelAsync(),keys.forEach(key=>delete global[key])}}}export{setupHappyDOM};
|
package/dist/jsdom-VHB26LUJ.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{KEYS}from"./chunk-2AYT2TPD.js";import{init_esm_shims}from"./chunk-64PJVUUV.js";init_esm_shims();import{JSDOM}from"jsdom";function setupJSDOM(global){let dom=new JSDOM("<!DOCTYPE html>",{pretendToBeVisual:!0,runScripts:"dangerously",url:"http://localhost:3000"}),keys=KEYS.concat(Object.getOwnPropertyNames(dom.window)).filter(k=>!k.startsWith("_")).filter(k=>!(k in global));for(let key of keys)global[key]=dom.window[key];return{dom,restore(){keys.forEach(key=>delete global[key])}}}export{setupJSDOM};
|
package/dist/node/worker.js
DELETED
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
import{distDir}from"../chunk-2PVIVCXM.js";import{init_esm_shims}from"../chunk-64PJVUUV.js";init_esm_shims();import{resolve as resolve2}from"path";import{nanoid}from"nanoid";init_esm_shims();import{builtinModules,createRequire}from"module";import{fileURLToPath,pathToFileURL}from"url";import{dirname,resolve}from"path";import vm from"vm";import{isValidNodeImport}from"mlly";var defaultInline=["vitest/dist","vitest/src","@vue","@vueuse","vue-demi","vue",/virtual:/,/\.ts$/,/\/esm\/.*\.js$/,/\.(es|esm|esm-browser|esm-bundler|es6).js$/],depsExternal=[/\.cjs.js$/],isWindows=process.platform==="win32",stubRequests={"/@vite/client":{injectQuery:id=>id,createHotContext(){return{accept:()=>{},prune:()=>{}}},updateStyle(){}}};async function executeInViteNode({moduleCache:moduleCache2,root,files,fetch,inline,external}){let externaled=new Set(builtinModules),result=[];for(let file of files)result.push(await cachedRequest(`/@fs/${slash(resolve(file))}`,[]));return result;async function directRequest(id,fsPath,callstack){callstack=[...callstack,id];let request=async dep=>{var _a;if(callstack.includes(dep)){let cacheKey=toFilePath(dep,root);if(!((_a=moduleCache2.get(cacheKey))==null?void 0:_a.exports))throw new Error(`Circular dependency detected
|
|
2
|
-
Stack:
|
|
3
|
-
${[...callstack,dep].reverse().map(p=>`- ${p}`).join(`
|
|
4
|
-
`)}`);return moduleCache2.get(cacheKey).exports}return cachedRequest(dep,callstack)};if(id in stubRequests)return stubRequests[id];let result2=await fetch(id);if(!result2)throw new Error(`failed to load ${id}`);let url=pathToFileURL(fsPath).href,exports={};setCache(fsPath,{transformResult:result2,exports});let __filename2=fileURLToPath(url),context={require:createRequire(url),__filename:__filename2,__dirname:dirname(__filename2),__vite_ssr_import__:request,__vite_ssr_dynamic_import__:request,__vite_ssr_exports__:exports,__vite_ssr_exportAll__:obj=>exportAll(exports,obj),__vite_ssr_import_meta__:{url}};return await vm.runInThisContext(`async (${Object.keys(context).join(",")}) => { ${result2.code} }`,{filename:fsPath,lineOffset:0})(...Object.values(context)),exports}function setCache(id,mod){moduleCache2.has(id)?Object.assign(moduleCache2.get(id),mod):moduleCache2.set(id,mod)}async function shouldExternalize(id){return matchExternalizePattern(id,inline)?!1:matchExternalizePattern(id,external)||matchExternalizePattern(id,depsExternal)?!0:matchExternalizePattern(id,defaultInline)?!1:id.includes("/node_modules/")&&await isValidNodeImport(id)}async function cachedRequest(rawId,callstack){var _a,_b;let id=normalizeId(rawId);if(externaled.has(id))return import(id);let fsPath=toFilePath(id,root),importPath=patchWindowsImportPath(fsPath);if(externaled.has(importPath)||await shouldExternalize(importPath))return externaled.add(importPath),import(importPath);if((_a=moduleCache2.get(fsPath))==null?void 0:_a.promise)return(_b=moduleCache2.get(fsPath))==null?void 0:_b.promise;let promise=directRequest(id,fsPath,callstack);return setCache(fsPath,{promise}),await promise}function exportAll(exports,sourceModule){for(let key in sourceModule)if(key!=="default")try{Object.defineProperty(exports,key,{enumerable:!0,configurable:!0,get(){return sourceModule[key]}})}catch{}}}function normalizeId(id){return id&&id.startsWith("/@id/__x00__")&&(id=`\0${id.slice("/@id/__x00__".length)}`),id&&id.startsWith("/@id/")&&(id=id.slice("/@id/".length)),id.startsWith("__vite-browser-external:")&&(id=id.slice("__vite-browser-external:".length)),id.startsWith("node:")&&(id=id.slice("node:".length)),id}function toFilePath(id,root){id=slash(id);let absolute=id.startsWith("/@fs/")?id.slice(4):id.startsWith(dirname(root))?id:id.startsWith("/")?slash(resolve(root,id.slice(1))):id;return absolute.startsWith("//")&&(absolute=absolute.slice(1)),isWindows&&absolute.startsWith("/")?pathToFileURL(absolute.slice(1)).href:absolute}function slash(path){return path.replace(/\\/g,"/")}function matchExternalizePattern(id,patterns){for(let ex of patterns)if(typeof ex=="string"){if(id.includes(`/node_modules/${ex}/`))return!0}else if(ex.test(id))return!0;return!1}function patchWindowsImportPath(path){return path.match(/^\w:\//)?`/${path}`:path}var _run,moduleCache=new Map;async function init(ctx){if(_run)return _run;let{config}=ctx;return _run=(await executeInViteNode({root:config.root,files:[resolve2(distDir,"runtime/entry.js")],fetch(id){return process.__vitest_worker__.rpc("fetch",id)},inline:config.depsInline,external:config.depsExternal,moduleCache}))[0].run,_run}async function run(ctx){process.stdout.write("\0");let{config,port}=ctx,rpcPromiseMap=new Map;process.__vitest_worker__={config,rpc:(method,...args)=>new Promise((resolve3,reject)=>{let id=nanoid();rpcPromiseMap.set(id,{resolve:resolve3,reject}),port.postMessage({method,args,id})}),send(method,...args){port.postMessage({method,args})}},port.addListener("message",async data=>{let api=rpcPromiseMap.get(data.id);api&&(data.error?api.reject(data.error):api.resolve(data.result))});let run2=await init(ctx);return ctx.invalidates&&ctx.invalidates.forEach(i=>moduleCache.delete(i)),ctx.files.forEach(i=>moduleCache.delete(i)),run2(ctx.files,ctx.config)}export{run as default,init};
|