eventservice 1.4.3 → 1.5.0

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.
@@ -1,109 +1,113 @@
1
- import EventService from "../src/EventService";
2
-
3
- it("on => fire", async () => {
4
- (console as any).EventServiceDebug = true;
5
- EventService.on("1", async (name: string) => {
6
- return `Hello ${name}!`;
7
- });
8
-
9
- const result: string = await EventService.fire<string>("1", "World");
10
- expect(result).toEqual("Hello World!");
11
-
12
- EventService.off("1");
13
- (console as any).EventServiceDebug = false;
14
- });
15
-
16
- it("on with throwing an exception => fire", async () => {
17
- EventService.on("1", async () => {
18
- throw new Error("Some Error");
19
- });
20
-
21
- await expect(EventService.fire("1", "World")).rejects.toThrow(Error);
22
- EventService.off("1");
23
- });
24
-
25
- it("on => fire => off => fire", async () => {
26
- EventService.on("1", async (name: string) => `Hello ${name}!`, "key");
27
-
28
- const result: string = await EventService.fire<string>("1", "World");
29
- expect(result).toEqual("Hello World!");
30
-
31
- EventService.off("1", "key");
32
-
33
- expect((EventService as any).subscriptions["1"].length).toEqual(0);
34
-
35
- const anotherResult: string | undefined = await EventService.fire<string>("1", "World");
36
- console.info(anotherResult);
37
- expect(anotherResult).toBeUndefined();
38
- });
39
-
40
- it("nested subscriptions. on => on => fire", async () => {
41
- EventService.on("2", async () => "Hello");
42
-
43
- EventService.on("1", async (name: string) => {
44
- const phrase: string = await EventService.fire<string>("2");
45
- return `${phrase} ${name}!`;
46
- });
47
-
48
- const result: string = await EventService.fire<string>("1", "John");
49
- expect(result).toEqual("Hello John!");
50
-
51
- EventService.off("2");
52
- EventService.off("1");
53
- });
54
-
55
- it("two subscriptions with the same name. on => on => => fire", async () => {
56
- EventService.on("97", async (name: string) => {
57
- `Hello ${name}`;
58
- });
59
-
60
- EventService.on("97", async (name: string) => {
61
- return `${name}!`;
62
- });
63
-
64
- const result: string = await EventService.fire<string>("97", "Alex");
65
- expect(result).toEqual("Alex!");
66
- EventService.off("97");
67
- });
68
-
69
- it("two nested subscriptions with the same name. on => on => => fire", async () => {
70
- EventService.on("987", async (name: string) => {
71
- return `Hello ${name}`;
72
- });
73
-
74
- EventService.on("987", async (name: string) => {
75
- return `${name}!`;
76
- });
77
-
78
- const result: string = await EventService.fire<string>("987", "Mack");
79
- expect(result).toEqual("Hello Mack!");
80
- EventService.off("987");
81
- });
82
-
83
- it("fire with no subscriptions", async () => {
84
- const result = await EventService.fire("123");
85
- expect(result).toBeUndefined();
86
- });
87
-
88
- it("off without subscriptions", () => {
89
- EventService.off("1234");
90
- });
91
-
92
- it("clear", async () => {
93
- EventService.on("2", async () => "Hello");
94
-
95
- EventService.on("1", async (name: string) => {
96
- const phrase: string = await EventService.fire<string>("2");
97
- return `${phrase} ${name}!`;
98
- });
99
-
100
- const result: string = await EventService.fire<string>("1", "John");
101
- expect(result).toEqual("Hello John!");
102
-
103
- EventService.clear();
104
- expect((EventService as any).subscriptions["1"]).toBeUndefined();
105
- expect((EventService as any).subscriptions["2"]).toBeUndefined();
106
-
107
- const anotherResult: string = await EventService.fire<string>("1", "John");
108
- expect(anotherResult).toBeUndefined();
109
- });
1
+ import EventService from "../src/EventService";
2
+ import { expect, it } from "vitest";
3
+
4
+ it("on => fire", async () => {
5
+ (console as any).EventServiceDebug = true;
6
+ EventService.on("1", async (name: string) => {
7
+ return `Hello ${name}!`;
8
+ });
9
+
10
+ const result: string = await EventService.fire<string>("1", "World");
11
+ expect(result).toEqual("Hello World!");
12
+
13
+ EventService.off("1");
14
+ (console as any).EventServiceDebug = false;
15
+ });
16
+
17
+ it("on with throwing an exception => fire", async () => {
18
+ EventService.on("1", async () => {
19
+ throw new Error("Some Error");
20
+ });
21
+
22
+ await expect(EventService.fire("1", "World")).rejects.toThrow(Error);
23
+ EventService.off("1");
24
+ });
25
+
26
+ it("on => fire => off => fire", async () => {
27
+ EventService.on("1", async (name: string) => `Hello ${name}!`, "key");
28
+
29
+ const result: string = await EventService.fire<string>("1", "World");
30
+ expect(result).toEqual("Hello World!");
31
+
32
+ EventService.off("1", "key");
33
+
34
+ expect((EventService as any).subscriptions["1"].length).toEqual(0);
35
+
36
+ const anotherResult: string | undefined = await EventService.fire<string>(
37
+ "1",
38
+ "World",
39
+ );
40
+ console.info(anotherResult);
41
+ expect(anotherResult).toBeUndefined();
42
+ });
43
+
44
+ it("nested subscriptions. on => on => fire", async () => {
45
+ EventService.on("2", async () => "Hello");
46
+
47
+ EventService.on("1", async (name: string) => {
48
+ const phrase: string = await EventService.fire<string>("2");
49
+ return `${phrase} ${name}!`;
50
+ });
51
+
52
+ const result: string = await EventService.fire<string>("1", "John");
53
+ expect(result).toEqual("Hello John!");
54
+
55
+ EventService.off("2");
56
+ EventService.off("1");
57
+ });
58
+
59
+ it("two subscriptions with the same name. on => on => => fire", async () => {
60
+ EventService.on("97", async (name: string) => {
61
+ `Hello ${name}`;
62
+ });
63
+
64
+ EventService.on("97", async (name: string) => {
65
+ return `${name}!`;
66
+ });
67
+
68
+ const result: string = await EventService.fire<string>("97", "Alex");
69
+ expect(result).toEqual("Alex!");
70
+ EventService.off("97");
71
+ });
72
+
73
+ it("two nested subscriptions with the same name. on => on => => fire", async () => {
74
+ EventService.on("987", async (name: string) => {
75
+ return `Hello ${name}`;
76
+ });
77
+
78
+ EventService.on("987", async (name: string) => {
79
+ return `${name}!`;
80
+ });
81
+
82
+ const result: string = await EventService.fire<string>("987", "Mack");
83
+ expect(result).toEqual("Hello Mack!");
84
+ EventService.off("987");
85
+ });
86
+
87
+ it("fire with no subscriptions", async () => {
88
+ const result = await EventService.fire("123");
89
+ expect(result).toBeUndefined();
90
+ });
91
+
92
+ it("off without subscriptions", () => {
93
+ EventService.off("1234");
94
+ });
95
+
96
+ it("clear", async () => {
97
+ EventService.on("2", async () => "Hello");
98
+
99
+ EventService.on("1", async (name: string) => {
100
+ const phrase: string = await EventService.fire<string>("2");
101
+ return `${phrase} ${name}!`;
102
+ });
103
+
104
+ const result: string = await EventService.fire<string>("1", "John");
105
+ expect(result).toEqual("Hello John!");
106
+
107
+ EventService.clear();
108
+ expect((EventService as any).subscriptions["1"]).toBeUndefined();
109
+ expect((EventService as any).subscriptions["2"]).toBeUndefined();
110
+
111
+ const anotherResult: string = await EventService.fire<string>("1", "John");
112
+ expect(anotherResult).toBeUndefined();
113
+ });
@@ -9,7 +9,7 @@ export default class EventService {
9
9
  * @param callback The function callback that will be invoked when event will be fired
10
10
  * @param key The optional param. The key of subscription. Used to identify the subscription for method `off`
11
11
  */
12
- static on<T>(eventName: string, callback: (eventData?: any, prevSubscriptionResult?: any) => Promise<T>, key?: string): void;
12
+ static on<T>(eventName: string, callback: (eventData?: any, prevSubscriptionResult?: any) => Promise<T>, key?: string | null): void;
13
13
  /**
14
14
  * Unsubscribe from event
15
15
  * @param eventName The name of event
@@ -22,7 +22,7 @@ export default class EventService {
22
22
  * @param eventName The name of event
23
23
  * @param eventData The data that will be passed to subscriber's callback method
24
24
  */
25
- static fire<T>(eventName: string, eventData?: any): Promise<T>;
25
+ static fire<T, TData extends T | undefined>(eventName: string, eventData?: TData): Promise<T | undefined>;
26
26
  static clear(): void;
27
27
  private static subscriptions;
28
28
  private static fireExecute;
@@ -9,8 +9,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
9
9
  });
10
10
  };
11
11
  var __generator = (this && this.__generator) || function (thisArg, body) {
12
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
13
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
12
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
13
+ return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
14
14
  function verb(n) { return function (v) { return step([n, v]); }; }
15
15
  function step(op) {
16
16
  if (f) throw new TypeError("Generator is already executing.");
@@ -35,12 +35,16 @@ var __generator = (this && this.__generator) || function (thisArg, body) {
35
35
  if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
36
36
  }
37
37
  };
38
- var __importDefault = (this && this.__importDefault) || function (mod) {
39
- return (mod && mod.__esModule) ? mod : { "default": mod };
38
+ var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
39
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
40
+ if (ar || !(i in from)) {
41
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
42
+ ar[i] = from[i];
43
+ }
44
+ }
45
+ return to.concat(ar || Array.prototype.slice.call(from));
40
46
  };
41
47
  Object.defineProperty(exports, "__esModule", { value: true });
42
- var lodash_clone_1 = __importDefault(require("lodash.clone"));
43
- var lodash_pull_1 = __importDefault(require("lodash.pull"));
44
48
  var EventService = /** @class */ (function () {
45
49
  function EventService() {
46
50
  }
@@ -56,7 +60,7 @@ var EventService = /** @class */ (function () {
56
60
  EventService.subscriptions[eventName] = [];
57
61
  EventService.subscriptions[eventName].push({
58
62
  key: key,
59
- action: callback
63
+ action: callback,
60
64
  });
61
65
  };
62
66
  /**
@@ -84,7 +88,7 @@ var EventService = /** @class */ (function () {
84
88
  EventService.log("Event '".concat(eventName, "' has been executed: ").concat(EventService.subscriptions[eventName] ? EventService.subscriptions[eventName].length : 0), eventData);
85
89
  if (!EventService.subscriptions[eventName])
86
90
  return [2 /*return*/, undefined];
87
- return [2 /*return*/, EventService.fireExecute((0, lodash_clone_1.default)(EventService.subscriptions[eventName]), eventData)];
91
+ return [2 /*return*/, EventService.fireExecute(__spreadArray([], EventService.subscriptions[eventName], true), eventData)];
88
92
  });
89
93
  });
90
94
  };
@@ -93,19 +97,21 @@ var EventService = /** @class */ (function () {
93
97
  };
94
98
  EventService.fireExecute = function (subscriptions, eventData) {
95
99
  return __awaiter(this, void 0, void 0, function () {
96
- var subscription, actionResult;
100
+ var subscription, rest, actionResult;
97
101
  return __generator(this, function (_a) {
98
102
  switch (_a.label) {
99
103
  case 0:
100
- subscription = subscriptions[0];
101
- if (!subscription)
104
+ subscription = subscriptions[0], rest = subscriptions.slice(1);
105
+ if (!subscription) {
102
106
  return [2 /*return*/, undefined];
107
+ }
103
108
  return [4 /*yield*/, subscription.action(eventData)];
104
109
  case 1:
105
110
  actionResult = _a.sent();
106
- if (subscriptions.length <= 1)
111
+ if (rest.length === 0) {
107
112
  return [2 /*return*/, actionResult];
108
- return [2 /*return*/, EventService.fireExecute((0, lodash_pull_1.default)(subscriptions, subscription), actionResult === undefined ? eventData : actionResult)];
113
+ }
114
+ return [2 /*return*/, EventService.fireExecute(rest, actionResult === undefined ? eventData : actionResult)];
109
115
  }
110
116
  });
111
117
  });
@@ -1 +1 @@
1
- {"version":3,"file":"EventService.js","sourceRoot":"","sources":["../../src/EventService.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,8DAAiC;AACjC,4DAA+B;AAO/B;IAoEI;IAAwB,CAAC;IAlEzB;;;;;OAKG;IACW,eAAE,GAAhB,UAAoB,SAAiB,EAAE,QAAuE,EAAE,GAAkB;QAAlB,oBAAA,EAAA,UAAkB;QAC9H,IAAI,CAAC,YAAY,CAAC,aAAa,CAAC,SAAS,CAAC;YAAE,YAAY,CAAC,aAAa,CAAC,SAAS,CAAC,GAAG,EAAE,CAAC;QACvF,YAAY,CAAC,aAAa,CAAC,SAAS,CAAC,CAAC,IAAI,CAAC;YACvC,GAAG,EAAE,GAAG;YACR,MAAM,EAAE,QAAQ;SACnB,CAAC,CAAC;IACP,CAAC;IAED;;;;OAIG;IACW,gBAAG,GAAjB,UAAkB,SAAiB,EAAE,GAAyB;QAAzB,oBAAA,EAAA,UAAyB;QAC1D,YAAY,CAAC,GAAG,CAAC,6BAAqB,SAAS,mBAAO,GAAG,QAAI,CAAC,CAAC;QA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AAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,YAAY,CACtD,EAAC;;;;KACH;IAEc,gBAAG,GAAlB,UAAoC,OAAiB,EAAE,IAAY;QACjE,IAAI,OAAO,IAAK,OAAe,CAAC,iBAAiB,EAAE,CAAC;YAClD,OAAO,CAAC,GAAG,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC;QAC7B,CAAC;IACH,CAAC;IApCc,0BAAa,GAKxB,EAAE,CAAC;IAkCT,mBAAC;CAAA,AArGD,IAqGC;kBArGoB,YAAY"}
package/package.json CHANGED
@@ -1,33 +1,27 @@
1
- {
2
- "name": "eventservice",
3
- "description": "The Promise-based simple event bus service",
4
- "version": "1.4.3",
5
- "main": "./dist/index.js",
6
- "scripts": {
7
- "build": "tsc",
8
- "lint": "tslint index.ts",
9
- "pretest": "npm run lint",
10
- "test": "jest"
11
- },
12
- "publishConfig": {
13
- "registry": "https://registry.npmjs.org"
14
- },
15
- "author": "Alexey Ripenko <alexey@ripenko.ru>",
16
- "license": "MIT",
17
- "repository": {
18
- "type": "git",
19
- "url": "git@github.com:ripenko/eventservice.git"
20
- },
21
- "dependencies": {
22
- "lodash.clone": "4.5.0",
23
- "lodash.pull": "4.1.0"
24
- },
25
- "devDependencies": {
26
- "@types/lodash.clone": "4.5.7",
27
- "@types/lodash.pull": "4.1.7",
28
- "@types/jest": "29.5.1",
29
- "typescript": "5.0.4",
30
- "jest": "29.5.0",
31
- "ts-jest": "29.1.0"
32
- }
33
- }
1
+ {
2
+ "name": "eventservice",
3
+ "description": "The Promise-based simple event bus service",
4
+ "version": "1.5.0",
5
+ "main": "./dist/index.js",
6
+ "scripts": {
7
+ "build": "tsc",
8
+ "lint": "tslint index.ts",
9
+ "pretest": "npm run lint",
10
+ "test": "vitest",
11
+ "test:run": "vitest run"
12
+ },
13
+ "publishConfig": {
14
+ "registry": "https://registry.npmjs.org"
15
+ },
16
+ "author": "Alexey Ripenko <alexey@ripenko.ru>",
17
+ "license": "MIT",
18
+ "repository": {
19
+ "type": "git",
20
+ "url": "git@github.com:ripenko/eventservice.git"
21
+ },
22
+ "dependencies": {},
23
+ "devDependencies": {
24
+ "typescript": "5.9.3",
25
+ "vitest": "^4.1.0"
26
+ }
27
+ }
@@ -1,78 +1,107 @@
1
- import clone from "lodash.clone";
2
- import pull from "lodash.pull";
3
-
4
- export declare var environment: {
5
- isDev: boolean;
6
- isProd: boolean;
7
- };
8
-
9
- export default class EventService {
10
-
11
- /**
12
- * Subscribe to event
13
- * @param eventName The name of event
14
- * @param callback The function callback that will be invoked when event will be fired
15
- * @param key The optional param. The key of subscription. Used to identify the subscription for method `off`
16
- */
17
- public static on<T>(eventName: string, callback: (eventData?: any, prevSubscriptionResult?: any) => Promise<T>, key: string = null): void {
18
- if (!EventService.subscriptions[eventName]) EventService.subscriptions[eventName] = [];
19
- EventService.subscriptions[eventName].push({
20
- key: key,
21
- action: callback
22
- });
23
- }
24
-
25
- /**
26
- * Unsubscribe from event
27
- * @param eventName The name of event
28
- * @param key The key that identify subscription. Use certain key that has been given in method `on`
29
- */
30
- public static off(eventName: string, key: string | null = null): void {
31
- EventService.log(`EventService.off("${eventName}", "${key}")`);
32
- if (!EventService.subscriptions[eventName]) return;
33
- EventService.subscriptions[eventName] = EventService.subscriptions[eventName].filter(x => x.key !== key);
34
- EventService.log(`EventService.subscription["${eventName}"]`, EventService.subscriptions[eventName]);
35
- }
36
-
37
- /**
38
- * Fire event.
39
- * Also this method will wait for subscriber callback.
40
- * @param eventName The name of event
41
- * @param eventData The data that will be passed to subscriber's callback method
42
- */
43
- public static async fire<T>(eventName: string, eventData?: any): Promise<T> {
44
- EventService.log(`Event '${eventName}' has been executed: ${EventService.subscriptions[eventName] ? EventService.subscriptions[eventName].length : 0}`, eventData);
45
- if (!EventService.subscriptions[eventName]) return undefined;
46
- return EventService.fireExecute<T>(clone(EventService.subscriptions[eventName]), eventData);
47
- }
48
-
49
- public static clear(): void {
50
- EventService.subscriptions = {};
51
- }
52
-
53
- private static subscriptions: {
54
- [name: string]: Array<{
55
- key: string;
56
- action: (eventData: any) => Promise<any>;
57
- }>;
58
- } = {};
59
-
60
- private static async fireExecute<T>(
61
- subscriptions: Array<{ key: string; action: (eventData: any) => Promise<T> }>,
62
- eventData: T): Promise<T> {
63
- const subscription = subscriptions[0];
64
- if (!subscription) return undefined;
65
-
66
- const actionResult: T = await subscription.action(eventData);
67
- if (subscriptions.length <= 1) return actionResult;
68
- return EventService.fireExecute<T>(pull(subscriptions, subscription), actionResult === undefined ? eventData : actionResult);
69
- }
70
-
71
- private static log<TMessage, TData>(message: TMessage, data?: TData): void {
72
- if (console && (console as any).EventServiceDebug) {
73
- console.log(message, data);
74
- }
75
- }
76
-
77
- private constructor() { }
78
- }
1
+ export declare var environment: {
2
+ isDev: boolean;
3
+ isProd: boolean;
4
+ };
5
+
6
+ export default class EventService {
7
+ /**
8
+ * Subscribe to event
9
+ * @param eventName The name of event
10
+ * @param callback The function callback that will be invoked when event will be fired
11
+ * @param key The optional param. The key of subscription. Used to identify the subscription for method `off`
12
+ */
13
+ public static on<T>(
14
+ eventName: string,
15
+ callback: (eventData?: any, prevSubscriptionResult?: any) => Promise<T>,
16
+ key: string | null = null,
17
+ ): void {
18
+ if (!EventService.subscriptions[eventName])
19
+ EventService.subscriptions[eventName] = [];
20
+ EventService.subscriptions[eventName].push({
21
+ key: key,
22
+ action: callback,
23
+ });
24
+ }
25
+
26
+ /**
27
+ * Unsubscribe from event
28
+ * @param eventName The name of event
29
+ * @param key The key that identify subscription. Use certain key that has been given in method `on`
30
+ */
31
+ public static off(eventName: string, key: string | null = null): void {
32
+ EventService.log(`EventService.off("${eventName}", "${key}")`);
33
+ if (!EventService.subscriptions[eventName]) return;
34
+ EventService.subscriptions[eventName] = EventService.subscriptions[
35
+ eventName
36
+ ].filter((x) => x.key !== key);
37
+ EventService.log(
38
+ `EventService.subscription["${eventName}"]`,
39
+ EventService.subscriptions[eventName],
40
+ );
41
+ }
42
+
43
+ /**
44
+ * Fire event.
45
+ * Also this method will wait for subscriber callback.
46
+ * @param eventName The name of event
47
+ * @param eventData The data that will be passed to subscriber's callback method
48
+ */
49
+ public static async fire<T, TData extends T | undefined>(
50
+ eventName: string,
51
+ eventData?: TData,
52
+ ): Promise<T | undefined> {
53
+ EventService.log(
54
+ `Event '${eventName}' has been executed: ${EventService.subscriptions[eventName] ? EventService.subscriptions[eventName].length : 0}`,
55
+ eventData,
56
+ );
57
+ if (!EventService.subscriptions[eventName]) return undefined;
58
+ return EventService.fireExecute<T>(
59
+ [...EventService.subscriptions[eventName]],
60
+ eventData,
61
+ );
62
+ }
63
+
64
+ public static clear(): void {
65
+ EventService.subscriptions = {};
66
+ }
67
+
68
+ private static subscriptions: {
69
+ [name: string]: Array<{
70
+ key: string | null;
71
+ action: (eventData: any) => Promise<any>;
72
+ }>;
73
+ } = {};
74
+
75
+ private static async fireExecute<T>(
76
+ subscriptions: Array<{
77
+ key: string | null;
78
+ action: (eventData: any) => Promise<T>;
79
+ }>,
80
+ eventData: T | undefined,
81
+ ): Promise<T | undefined> {
82
+ const [subscription, ...rest] = subscriptions;
83
+
84
+ if (!subscription) {
85
+ return undefined;
86
+ }
87
+
88
+ const actionResult = await subscription.action(eventData);
89
+
90
+ if (rest.length === 0) {
91
+ return actionResult;
92
+ }
93
+
94
+ return EventService.fireExecute<T>(
95
+ rest,
96
+ actionResult === undefined ? eventData : actionResult,
97
+ );
98
+ }
99
+
100
+ private static log<TMessage, TData>(message: TMessage, data?: TData): void {
101
+ if (console && (console as any).EventServiceDebug) {
102
+ console.log(message, data);
103
+ }
104
+ }
105
+
106
+ private constructor() {}
107
+ }
package/tsconfig.json CHANGED
@@ -1,23 +1,25 @@
1
- {
2
- "compilerOptions": {
3
- "outDir": "./dist/",
4
- "sourceMap": true,
5
- "declaration": true,
6
- "noImplicitAny": true,
7
- "module": "commonjs",
8
- "moduleResolution": "node",
9
- "esModuleInterop": true,
10
- "noUnusedLocals": true,
11
- "noImplicitReturns": true,
12
- "traceResolution": false,
13
- "allowSyntheticDefaultImports": true,
14
- "target": "es5",
15
- "lib": [
16
- "dom",
17
- "es2015"
18
- ]
19
- },
20
- "include": [
21
- "./index.ts"
22
- ]
1
+ {
2
+ "compilerOptions": {
3
+ "outDir": "./dist/",
4
+ "sourceMap": true,
5
+ "declaration": true,
6
+ "noImplicitAny": true,
7
+ "module": "commonjs",
8
+ "moduleResolution": "node",
9
+ "esModuleInterop": true,
10
+ "noUnusedLocals": true,
11
+ "noImplicitReturns": true,
12
+ "traceResolution": false,
13
+ "allowSyntheticDefaultImports": true,
14
+ "forceConsistentCasingInFileNames": true,
15
+ "strict": true,
16
+ "target": "es5",
17
+ "lib": [
18
+ "dom",
19
+ "es2015"
20
+ ]
21
+ },
22
+ "include": [
23
+ "./index.ts"
24
+ ]
23
25
  }
@@ -0,0 +1,15 @@
1
+ import { defineConfig } from "vitest/config";
2
+
3
+ export default defineConfig({
4
+ test: {
5
+ environment: "node",
6
+ globals: false,
7
+ include: ["__tests__/**/*.test.ts"],
8
+ coverage: {
9
+ provider: "v8",
10
+ reporter: ["text", "html"],
11
+ include: ["__tests__/**/*.ts"],
12
+ exclude: ["__tests__/**/*.test.ts", "__tests__/**/*.spec.ts"],
13
+ },
14
+ },
15
+ });
package/jest.config.js DELETED
@@ -1,192 +0,0 @@
1
- // For a detailed explanation regarding each configuration property, visit:
2
- // https://jestjs.io/docs/en/configuration.html
3
-
4
- module.exports = {
5
- // All imported modules in your tests should be mocked automatically
6
- // automock: false,
7
-
8
- // Stop running tests after `n` failures
9
- // bail: 0,
10
-
11
- // Respect "browser" field in package.json when resolving modules
12
- // browser: false,
13
-
14
- // The directory where Jest should store its cached dependency information
15
- // cacheDirectory: "C:\\Users\\aripenko\\AppData\\Local\\Temp\\jest",
16
-
17
- // Automatically clear mock calls and instances between every test
18
- clearMocks: true,
19
-
20
- // Indicates whether the coverage information should be collected while executing the test
21
- collectCoverage: true,
22
-
23
- // An array of glob patterns indicating a set of files for which coverage information should be collected
24
- // collectCoverageFrom: null,
25
-
26
- // The directory where Jest should output its coverage files
27
- coverageDirectory: "coverage",
28
-
29
- // An array of regexp pattern strings used to skip coverage collection
30
- // coveragePathIgnorePatterns: [
31
- // "\\\\node_modules\\\\"
32
- // ],
33
-
34
- // A list of reporter names that Jest uses when writing coverage reports
35
- // coverageReporters: [
36
- // "json",
37
- // "text",
38
- // "lcov",
39
- // "clover"
40
- // ],
41
-
42
- // An object that configures minimum threshold enforcement for coverage results
43
- // coverageThreshold: null,
44
-
45
- // A path to a custom dependency extractor
46
- // dependencyExtractor: null,
47
-
48
- // Make calling deprecated APIs throw helpful error messages
49
- // errorOnDeprecated: false,
50
-
51
- // Force coverage collection from ignored files using an array of glob patterns
52
- // forceCoverageMatch: [],
53
-
54
- // A path to a module which exports an async function that is triggered once before all test suites
55
- // globalSetup: null,
56
-
57
- // A path to a module which exports an async function that is triggered once after all test suites
58
- // globalTeardown: null,
59
-
60
- // A set of global variables that need to be available in all test environments
61
- // globals: {
62
-
63
- // },
64
-
65
- // An array of directory names to be searched recursively up from the requiring module's location
66
- moduleDirectories: [
67
- "node_modules",
68
- "src"
69
- ],
70
-
71
- // An array of file extensions your modules use
72
- // moduleFileExtensions: [
73
- // "js",
74
- // "json",
75
- // "jsx",
76
- // "ts",
77
- // "tsx",
78
- // "node"
79
- // ],
80
-
81
- // A map from regular expressions to module names that allow to stub out resources with a single module
82
- moduleNameMapper: {
83
- "^src/(.+)$": "<rootDir>/src/$1"
84
- },
85
-
86
- // An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader
87
- // modulePathIgnorePatterns: [],
88
-
89
- // Activates notifications for test results
90
- // notify: false,
91
-
92
- // An enum that specifies notification mode. Requires { notify: true }
93
- // notifyMode: "failure-change",
94
-
95
- // A preset that is used as a base for Jest's configuration
96
- // preset: null,
97
-
98
- // Run tests from one or more projects
99
- // projects: null,
100
-
101
- // Use this configuration option to add custom reporters to Jest
102
- // reporters: undefined,
103
-
104
- // Automatically reset mock state between every test
105
- // resetMocks: false,
106
-
107
- // Reset the module registry before running each individual test
108
- // resetModules: false,
109
-
110
- // A path to a custom resolver
111
- // resolver: null,
112
-
113
- // Automatically restore mock state between every test
114
- // restoreMocks: false,
115
-
116
- // The root directory that Jest should scan for tests and modules within
117
- // rootDir: null,
118
-
119
- // A list of paths to directories that Jest should use to search for files in
120
- roots: [
121
- "<rootDir>/__tests__"
122
- ],
123
-
124
- // Allows you to use a custom runner instead of Jest's default test runner
125
- // runner: "jest-runner",
126
-
127
- // The paths to modules that run some code to configure or set up the testing environment before each test
128
- // setupFiles: [],
129
-
130
- // A list of paths to modules that run some code to configure or set up the testing framework before each test
131
- // setupFilesAfterEnv: [],
132
-
133
- // A list of paths to snapshot serializer modules Jest should use for snapshot testing
134
- // snapshotSerializers: [],
135
-
136
- // The test environment that will be used for testing
137
- testEnvironment: "node",
138
-
139
- // Options that will be passed to the testEnvironment
140
- // testEnvironmentOptions: {},
141
-
142
- // Adds a location field to test results
143
- // testLocationInResults: false,
144
-
145
- // The glob patterns Jest uses to detect test files
146
- // testMatch: [
147
- // "**/__tests__/**/*.[jt]s?(x)",
148
- // "**/?(*.)+(spec|test).[tj]s?(x)"
149
- // ],
150
-
151
- // An array of regexp pattern strings that are matched against all test paths, matched tests are skipped
152
- // testPathIgnorePatterns: [
153
- // "\\\\node_modules\\\\"
154
- // ],
155
-
156
- // The regexp pattern or array of patterns that Jest uses to detect test files
157
- // testRegex: [],
158
-
159
- // This option allows the use of a custom results processor
160
- // testResultsProcessor: null,
161
-
162
- // This option allows use of a custom test runner
163
- // testRunner: "jasmine2",
164
-
165
- // This option sets the URL for the jsdom environment. It is reflected in properties such as location.href
166
- // testURL: "http://localhost",
167
-
168
- // Setting this value to "fake" allows the use of fake timers for functions such as "setTimeout"
169
- // timers: "real",
170
-
171
- // A map from regular expressions to paths to transformers
172
- transform: {
173
- "^.+\\.tsx?$": "ts-jest"
174
- },
175
-
176
- // An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation
177
- // transformIgnorePatterns: [
178
- // "\\\\node_modules\\\\"
179
- // ],
180
-
181
- // An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them
182
- // unmockedModulePathPatterns: undefined,
183
-
184
- // Indicates whether each individual test should be reported during the run
185
- // verbose: null,
186
-
187
- // An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode
188
- // watchPathIgnorePatterns: [],
189
-
190
- // Whether to use watchman for file crawling
191
- // watchman: true,
192
- };