@dion-js/extension-test-utils 0.1.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.
package/biome.json ADDED
@@ -0,0 +1,4 @@
1
+ {
2
+ "$schema": "https://biomejs.dev/schemas/2.1.1/schema.json",
3
+ "extends": ["@dion-js/config/biome.json"]
4
+ }
package/package.json ADDED
@@ -0,0 +1,21 @@
1
+ {
2
+ "name": "@dion-js/extension-test-utils",
3
+ "version": "0.1.0",
4
+ "type": "module",
5
+ "exports": {
6
+ ".": "./src/main.ts"
7
+ },
8
+ "dependencies": {
9
+ "image-url-validator": "^1.0.4",
10
+ "m3u8-parser": "^7.2.0",
11
+ "node-fetch": "^3.3.2",
12
+ "@dion-js/extension-types": "0.3.1",
13
+ "@dion-js/runtime-types": "0.3.1"
14
+ },
15
+ "devDependencies": {
16
+ "@types/m3u8-parser": "^7.2.2",
17
+ "@dion-js/config": "0.1.2",
18
+ "@dion-js/extension-types": "0.3.1",
19
+ "@types/bun": "^1.2.19"
20
+ }
21
+ }
package/src/main.ts ADDED
@@ -0,0 +1,315 @@
1
+ import { type Mock, mock } from "bun:test";
2
+ import { Adapter, ExtensionClient, ManagerClient } from "@dion-js/runtime";
3
+ import type {
4
+ Action,
5
+ CustomUI,
6
+ Entry,
7
+ EntryDetailed,
8
+ ExtensionData,
9
+ Link,
10
+ Permission,
11
+ Source,
12
+ } from "@dion-js/runtime-types/runtime";
13
+ import { Parser } from "m3u8-parser";
14
+ import fetch from "node-fetch";
15
+ import { join, dirname } from "node:path";
16
+
17
+ export class MockExtensionClient {
18
+ name: string;
19
+ client: ExtensionClient;
20
+ loadData: Mock<(err: Error | null, key: string) => string>;
21
+ storeData: Mock<(err: Error | null, key: string, value: string) => void>;
22
+ doAction: Mock<(err: Error | null, action: Action) => void>;
23
+ requestPermission: Mock<
24
+ (
25
+ err: Error | null,
26
+ permission: Permission,
27
+ msg?: string | undefined | null,
28
+ ) => boolean
29
+ >;
30
+ getPath: Mock<(err: Error | null) => string>;
31
+ constructor(extdata: ExtensionData, basepath: string) {
32
+ this.name = extdata.name;
33
+ this.loadData = mock((_err: any, _arg: any) => "");
34
+ this.storeData = mock((_err: any, _key: any, _arg: any) => {});
35
+ this.doAction = mock((_err: any, _action: any) => {});
36
+ this.requestPermission = mock((_err: any, _asd: any) => {
37
+ return false;
38
+ });
39
+ this.getPath = mock(() => {
40
+ return `${basepath}/${extdata.name}`;
41
+ });
42
+ this.client = new ExtensionClient(
43
+ this.loadData,
44
+ this.storeData,
45
+ this.doAction,
46
+ this.requestPermission,
47
+ this.getPath,
48
+ );
49
+ }
50
+ }
51
+
52
+ export class MockManagerClient {
53
+ client: ManagerClient;
54
+ extensions: MockExtensionClient[];
55
+ managerpath: string;
56
+ getClient: Mock<(err: Error | null, arg: ExtensionData) => ExtensionClient>;
57
+ getPath: Mock<(err: Error | null) => string>;
58
+
59
+ constructor(managerpath: string = ".") {
60
+ this.managerpath = managerpath;
61
+ this.extensions = [];
62
+ this.getClient = mock((_err: any, extdata: any) => {
63
+ const ext = new MockExtensionClient(extdata, managerpath);
64
+ this.extensions.push(ext);
65
+ return ext.client;
66
+ });
67
+ this.getPath = mock((_err: any) => {
68
+ return managerpath;
69
+ });
70
+ this.client = new ManagerClient(this.getClient, this.getPath);
71
+ }
72
+ }
73
+
74
+ export async function getTestExtension(client: ManagerClient) {
75
+ const adapter = await Adapter.init(client);
76
+ const ext = (await adapter.getExtensions())[0];
77
+ if (ext === undefined)
78
+ throw new Error("Extension couldnt be loaded! Maybe build failed?");
79
+ return ext;
80
+ }
81
+
82
+ export async function wait(ms: number): Promise<void> {
83
+ return new Promise((resolve, _reject) => {
84
+ setTimeout(resolve, ms);
85
+ });
86
+ }
87
+
88
+ var lock: Promise<void> | undefined;
89
+ export async function ratelimit(ms: number) {
90
+ if (lock !== undefined) await lock;
91
+ lock = wait(ms);
92
+ }
93
+
94
+ const time = 50;
95
+
96
+ function assert(condition: boolean, message: string): asserts condition {
97
+ if (!condition) throw new Error(message);
98
+ }
99
+
100
+ export async function assertValidM3U8(
101
+ link: Link,
102
+ options?: {
103
+ assertmsg?: string;
104
+ },
105
+ ) {
106
+ console.log(`Checking ${link.url}`);
107
+ await ratelimit(time);
108
+ const response = await fetch(link.url, { headers: link.header ?? undefined });
109
+ assert(
110
+ response.ok,
111
+ `${options?.assertmsg} ${link.url} is not a valid url or not reachable`,
112
+ );
113
+ const parser = new Parser({
114
+ uri: link.url,
115
+ });
116
+ parser.push(await response.text());
117
+ parser.end();
118
+ assert(
119
+ parser.manifest.segments.length > 0,
120
+ `${options} ${link.url} is not a valid m3u8 url`,
121
+ );
122
+ }
123
+
124
+ export async function assertValidImageURL(
125
+ link: Link,
126
+ options?: {
127
+ assertmsg?: string;
128
+ },
129
+ ) {
130
+ await ratelimit(time);
131
+ const response = await fetch(link.url, { headers: link.header ?? undefined });
132
+ assert(
133
+ response.ok,
134
+ `${options?.assertmsg} ${link.url} is not a valid url or not reachable`,
135
+ );
136
+ assert(
137
+ response.headers
138
+ .get("content-type")
139
+ ?.toLocaleLowerCase()
140
+ .includes("image") ?? false,
141
+ `${options?.assertmsg} ${link.url} is not an image url`,
142
+ );
143
+ }
144
+
145
+ export async function assertValidURL(
146
+ link: Link,
147
+ options?: {
148
+ assertmsg?: string;
149
+ },
150
+ ) {
151
+ await ratelimit(time);
152
+ const response = await fetch(link.url, { headers: link.header ?? undefined });
153
+ assert(
154
+ response.ok,
155
+ `${options?.assertmsg} ${link.url} is not a valid url or not reachable`,
156
+ );
157
+ }
158
+
159
+ function sample<T>(arr: T[] | undefined | null, n: number): T[] {
160
+ if (arr === undefined || arr === null) return [];
161
+ if (arr.length <= n) return arr;
162
+ const result = new Array(n);
163
+ for (let i = 0; i < n; i++) {
164
+ result[i] = arr[Math.floor(Math.random() * arr.length)];
165
+ }
166
+ return result;
167
+ }
168
+
169
+ function getTitle(entry: Entry | EntryDetailed) {
170
+ if ("title" in entry) return entry.title;
171
+ return entry.titles[0];
172
+ }
173
+
174
+ export async function assertValidEntry(entry: Entry | EntryDetailed) {
175
+ await assertValidURL(
176
+ { url: entry.url },
177
+ {
178
+ assertmsg: `Entry ${getTitle(entry)} (${entry.id}) has no valid entry.url`,
179
+ },
180
+ );
181
+ if (entry.cover !== undefined && entry.cover !== null) {
182
+ await assertValidImageURL(entry.cover, {
183
+ assertmsg: `Entry ${getTitle(entry)} (${entry.id}) has no valid entry.cover`,
184
+ });
185
+ }
186
+ if ("episodes" in entry) {
187
+ for (const episode of sample(entry.episodes, 5)) {
188
+ await assertValidURL(
189
+ { url: episode.url },
190
+ {
191
+ assertmsg: `Entry ${getTitle(entry)} (${entry.id}) has an invalid episode url ${episode.url} for episode ${episode.name}`,
192
+ },
193
+ );
194
+ }
195
+ }
196
+ if ("ui" in entry && entry.ui !== undefined && entry.ui !== null) {
197
+ assertValidUI(entry.ui);
198
+ }
199
+ }
200
+
201
+ function assertValidUI(ui: CustomUI) {
202
+ if ("children" in ui && ui.children !== undefined && ui.children !== null) {
203
+ for (const child of ui.children) {
204
+ assertValidUI(child);
205
+ }
206
+ }
207
+ switch (ui.type) {
208
+ case "EntryCard":
209
+ assertValidEntry(ui.entry);
210
+ break;
211
+ case "Image":
212
+ assertValidImageURL(ui.image, {
213
+ assertmsg: `CustomUI has an invalid image url ${ui.image}`,
214
+ });
215
+ break;
216
+ case "Link":
217
+ assertValidURL(
218
+ { url: ui.link },
219
+ {
220
+ assertmsg: `CustomUI has an invalid link ${ui.link}`,
221
+ },
222
+ );
223
+ break; //TODO Assert Timestamps
224
+ }
225
+ }
226
+
227
+ export async function assertValidEntries(entries: (Entry | EntryDetailed)[]) {
228
+ for (const entry of sample(entries, 5)) {
229
+ await assertValidEntry(entry);
230
+ }
231
+ }
232
+
233
+ export async function assertValidSource(source: Source) {
234
+ switch (source.type) {
235
+ case "Epub":
236
+ case "Pdf":
237
+ await assertValidURL(source.link, {
238
+ assertmsg: `Source ${source.type} has no valid link`,
239
+ });
240
+ break;
241
+ case "Audio":
242
+ for (const chapter of sample(source.sources, 5)) {
243
+ await assertValidURL(chapter.url, {
244
+ assertmsg: `Source ${source.type} has an invalid source ${chapter.name} ${chapter.url}`,
245
+ });
246
+ }
247
+ break;
248
+ case "Imagelist":
249
+ for (const image of sample(source.links, 5)) {
250
+ await assertValidImageURL(image, {
251
+ assertmsg: `Source ${source.type} has an invalid image url ${image}`,
252
+ });
253
+ }
254
+ for (const audio of sample(source.audio, 5)) {
255
+ await assertValidURL(audio.link, {
256
+ assertmsg: `Source ${source.type} has an invalid url ${audio.link}`,
257
+ });
258
+ }
259
+ break;
260
+ case "Video":
261
+ for (const videosource of source.sources) {
262
+ await assertValidM3U8(videosource.url, {
263
+ assertmsg: `Source ${videosource.name} has no valid link`,
264
+ });
265
+ }
266
+ for (const subtitle of sample(source.sub, 5)) {
267
+ await assertValidURL(subtitle.url, {
268
+ assertmsg: `Source ${source.type} has an invalid ${subtitle.title} subtitle link ${subtitle.url}`,
269
+ });
270
+ }
271
+ break;
272
+ }
273
+ }
274
+
275
+ export async function isValidEntry(entry: Entry | EntryDetailed) {
276
+ try {
277
+ await assertValidEntry(entry);
278
+ return true;
279
+ } catch (e) {
280
+ if (e instanceof Error) {
281
+ console.error(e.message);
282
+ } else {
283
+ console.error(e);
284
+ }
285
+ return false;
286
+ }
287
+ }
288
+
289
+ export async function isValidEntries(entries: (Entry | EntryDetailed)[]) {
290
+ try {
291
+ await assertValidEntries(entries);
292
+ return true;
293
+ } catch (e) {
294
+ if (e instanceof Error) {
295
+ console.error(e.message);
296
+ } else {
297
+ console.error(e);
298
+ }
299
+ return false;
300
+ }
301
+ }
302
+
303
+ export async function isValidSource(source: Source) {
304
+ try {
305
+ await assertValidSource(source);
306
+ return true;
307
+ } catch (e) {
308
+ if (e instanceof Error) {
309
+ console.error(e.message);
310
+ } else {
311
+ console.error(e);
312
+ }
313
+ return false;
314
+ }
315
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,14 @@
1
+ {
2
+ "include": ["src/**/*"],
3
+ "compilerOptions": {
4
+ "types": ["bun"],
5
+ "target": "ESNext",
6
+ "strict": true,
7
+ "moduleResolution": "nodenext",
8
+ "module": "nodenext",
9
+ "noUnusedLocals": true,
10
+ "noUnusedParameters": true,
11
+ "esModuleInterop": true,
12
+ "allowSyntheticDefaultImports": true
13
+ }
14
+ }