@ricsam/isolate-test-utils 0.1.1 → 0.1.2

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,1778 +0,0 @@
1
- /**
2
- * Isolate type definitions as string constants.
3
- *
4
- * These are the canonical source for isolated-vm global type definitions.
5
- * The .d.ts files in each package are generated from these strings during build.
6
- *
7
- * @example
8
- * import { TYPE_DEFINITIONS } from "@ricsam/isolate-test-utils";
9
- *
10
- * // Use with ts-morph for type checking code strings
11
- * project.createSourceFile("types.d.ts", TYPE_DEFINITIONS.fetch);
12
- */
13
-
14
- /**
15
- * Type definitions for @ricsam/isolate-core globals.
16
- *
17
- * Includes: ReadableStream, WritableStream, TransformStream, Blob, File, URL, URLSearchParams, DOMException
18
- */
19
- export const CORE_TYPES = `/**
20
- * Global Type Definitions for @ricsam/isolate-core
21
- *
22
- * These types define the globals injected by setupCore() into an isolated-vm context.
23
- * Use these types to typecheck user code that will run inside the V8 isolate.
24
- *
25
- * @example
26
- * // In your tsconfig.isolate.json
27
- * {
28
- * "compilerOptions": {
29
- * "lib": ["ESNext", "DOM"]
30
- * }
31
- * }
32
- *
33
- * // Then reference this file or use ts-morph for code strings
34
- */
35
-
36
- export {};
37
-
38
- declare global {
39
- // ============================================
40
- // Web Streams API
41
- // ============================================
42
-
43
- /**
44
- * A readable stream of data.
45
- * @see https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream
46
- */
47
- const ReadableStream: typeof globalThis.ReadableStream;
48
-
49
- /**
50
- * A writable stream of data.
51
- * @see https://developer.mozilla.org/en-US/docs/Web/API/WritableStream
52
- */
53
- const WritableStream: typeof globalThis.WritableStream;
54
-
55
- /**
56
- * A transform stream that can be used to pipe data through a transformer.
57
- * @see https://developer.mozilla.org/en-US/docs/Web/API/TransformStream
58
- */
59
- const TransformStream: typeof globalThis.TransformStream;
60
-
61
- /**
62
- * Default reader for ReadableStream
63
- * @see https://developer.mozilla.org/en-US/docs/Web/API/ReadableStreamDefaultReader
64
- */
65
- const ReadableStreamDefaultReader: typeof globalThis.ReadableStreamDefaultReader;
66
-
67
- /**
68
- * Default writer for WritableStream
69
- * @see https://developer.mozilla.org/en-US/docs/Web/API/WritableStreamDefaultWriter
70
- */
71
- const WritableStreamDefaultWriter: typeof globalThis.WritableStreamDefaultWriter;
72
-
73
- // ============================================
74
- // Blob and File APIs
75
- // ============================================
76
-
77
- /**
78
- * A file-like object of immutable, raw data.
79
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Blob
80
- */
81
- const Blob: typeof globalThis.Blob;
82
-
83
- /**
84
- * A file object representing a file.
85
- * @see https://developer.mozilla.org/en-US/docs/Web/API/File
86
- */
87
- const File: typeof globalThis.File;
88
-
89
- // ============================================
90
- // URL APIs
91
- // ============================================
92
-
93
- /**
94
- * Interface for URL manipulation.
95
- * @see https://developer.mozilla.org/en-US/docs/Web/API/URL
96
- */
97
- const URL: typeof globalThis.URL;
98
-
99
- /**
100
- * Utility for working with URL query strings.
101
- * @see https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams
102
- */
103
- const URLSearchParams: typeof globalThis.URLSearchParams;
104
-
105
- // ============================================
106
- // Error Handling
107
- // ============================================
108
-
109
- /**
110
- * Exception type for DOM operations.
111
- * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMException
112
- */
113
- const DOMException: typeof globalThis.DOMException;
114
- }
115
- `;
116
-
117
- /**
118
- * Type definitions for @ricsam/isolate-fetch globals.
119
- *
120
- * Includes: Headers, Request, Response, AbortController, AbortSignal, FormData, fetch, serve, Server, ServerWebSocket
121
- */
122
- export const FETCH_TYPES = `/**
123
- * Global Type Definitions for @ricsam/isolate-fetch
124
- *
125
- * These types define the globals injected by setupFetch() into an isolated-vm context.
126
- * Use these types to typecheck user code that will run inside the V8 isolate.
127
- *
128
- * @example
129
- * // Typecheck isolate code with serve()
130
- * type WebSocketData = { id: number; connectedAt: number };
131
- *
132
- * serve({
133
- * fetch(request, server) {
134
- * if (request.url.includes("/ws")) {
135
- * // server.upgrade knows data should be WebSocketData
136
- * server.upgrade(request, { data: { id: 123, connectedAt: Date.now() } });
137
- * return new Response(null, { status: 101 });
138
- * }
139
- * return new Response("Hello!");
140
- * },
141
- * websocket: {
142
- * // Type hint - specifies the type of ws.data
143
- * data: {} as WebSocketData,
144
- * message(ws, message) {
145
- * // ws.data is typed as WebSocketData
146
- * console.log("User", ws.data.id, "says:", message);
147
- * ws.send("Echo: " + message);
148
- * }
149
- * }
150
- * });
151
- */
152
-
153
- export {};
154
-
155
- declare global {
156
- // ============================================
157
- // Standard Fetch API (from lib.dom)
158
- // ============================================
159
-
160
- /**
161
- * Headers class for HTTP headers manipulation.
162
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Headers
163
- */
164
- const Headers: typeof globalThis.Headers;
165
-
166
- /**
167
- * Request class for HTTP requests.
168
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Request
169
- */
170
- const Request: typeof globalThis.Request;
171
-
172
- /**
173
- * Response class for HTTP responses.
174
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Response
175
- */
176
- const Response: typeof globalThis.Response;
177
-
178
- /**
179
- * AbortController for cancelling fetch requests.
180
- * @see https://developer.mozilla.org/en-US/docs/Web/API/AbortController
181
- */
182
- const AbortController: typeof globalThis.AbortController;
183
-
184
- /**
185
- * AbortSignal for listening to abort events.
186
- * @see https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal
187
- */
188
- const AbortSignal: typeof globalThis.AbortSignal;
189
-
190
- /**
191
- * FormData for constructing form data.
192
- * @see https://developer.mozilla.org/en-US/docs/Web/API/FormData
193
- */
194
- const FormData: typeof globalThis.FormData;
195
-
196
- /**
197
- * Fetch function for making HTTP requests.
198
- * @see https://developer.mozilla.org/en-US/docs/Web/API/fetch
199
- */
200
- function fetch(
201
- input: RequestInfo | URL,
202
- init?: RequestInit
203
- ): Promise<Response>;
204
-
205
- // ============================================
206
- // Isolate-specific: serve() API
207
- // ============================================
208
-
209
- /**
210
- * Server interface for handling WebSocket upgrades within serve() handlers.
211
- *
212
- * @typeParam T - The type of data associated with WebSocket connections
213
- */
214
- interface Server<T = unknown> {
215
- /**
216
- * Upgrade an HTTP request to a WebSocket connection.
217
- *
218
- * @param request - The incoming HTTP request to upgrade
219
- * @param options - Optional data to associate with the WebSocket connection
220
- * @returns true if upgrade will proceed, false otherwise
221
- *
222
- * @example
223
- * serve({
224
- * fetch(request, server) {
225
- * if (server.upgrade(request, { data: { userId: 123 } })) {
226
- * return new Response(null, { status: 101 });
227
- * }
228
- * return new Response("Upgrade failed", { status: 400 });
229
- * }
230
- * });
231
- */
232
- upgrade(request: Request, options?: { data?: T }): boolean;
233
- }
234
-
235
- /**
236
- * ServerWebSocket interface for WebSocket connections within serve() handlers.
237
- *
238
- * @typeParam T - The type of data associated with this WebSocket connection
239
- */
240
- interface ServerWebSocket<T = unknown> {
241
- /**
242
- * User data associated with this connection.
243
- * Set via \`server.upgrade(request, { data: ... })\`.
244
- */
245
- readonly data: T;
246
-
247
- /**
248
- * Send a message to the client.
249
- *
250
- * @param message - The message to send (string, ArrayBuffer, or Uint8Array)
251
- */
252
- send(message: string | ArrayBuffer | Uint8Array): void;
253
-
254
- /**
255
- * Close the WebSocket connection.
256
- *
257
- * @param code - Optional close code (default: 1000)
258
- * @param reason - Optional close reason
259
- */
260
- close(code?: number, reason?: string): void;
261
-
262
- /**
263
- * WebSocket ready state.
264
- * - 0: CONNECTING
265
- * - 1: OPEN
266
- * - 2: CLOSING
267
- * - 3: CLOSED
268
- */
269
- readonly readyState: number;
270
- }
271
-
272
- /**
273
- * Options for the serve() function.
274
- *
275
- * @typeParam T - The type of data associated with WebSocket connections
276
- */
277
- interface ServeOptions<T = unknown> {
278
- /**
279
- * Handler for HTTP requests.
280
- *
281
- * @param request - The incoming HTTP request
282
- * @param server - Server interface for WebSocket upgrades
283
- * @returns Response or Promise resolving to Response
284
- */
285
- fetch(request: Request, server: Server<T>): Response | Promise<Response>;
286
-
287
- /**
288
- * WebSocket event handlers.
289
- */
290
- websocket?: {
291
- /**
292
- * Type hint for WebSocket data. The value is not used at runtime.
293
- * Specifies the type of \`ws.data\` for all handlers and \`server.upgrade()\`.
294
- *
295
- * @example
296
- * websocket: {
297
- * data: {} as { userId: string },
298
- * message(ws, message) {
299
- * // ws.data.userId is typed as string
300
- * }
301
- * }
302
- */
303
- data?: T;
304
-
305
- /**
306
- * Called when a WebSocket connection is opened.
307
- *
308
- * @param ws - The WebSocket connection
309
- */
310
- open?(ws: ServerWebSocket<T>): void | Promise<void>;
311
-
312
- /**
313
- * Called when a message is received.
314
- *
315
- * @param ws - The WebSocket connection
316
- * @param message - The received message (string or ArrayBuffer)
317
- */
318
- message?(
319
- ws: ServerWebSocket<T>,
320
- message: string | ArrayBuffer
321
- ): void | Promise<void>;
322
-
323
- /**
324
- * Called when the connection is closed.
325
- *
326
- * @param ws - The WebSocket connection
327
- * @param code - The close code
328
- * @param reason - The close reason
329
- */
330
- close?(
331
- ws: ServerWebSocket<T>,
332
- code: number,
333
- reason: string
334
- ): void | Promise<void>;
335
-
336
- /**
337
- * Called when an error occurs.
338
- *
339
- * @param ws - The WebSocket connection
340
- * @param error - The error that occurred
341
- */
342
- error?(ws: ServerWebSocket<T>, error: Error): void | Promise<void>;
343
- };
344
- }
345
-
346
- /**
347
- * Register an HTTP server handler in the isolate.
348
- *
349
- * Only one serve() handler can be active at a time.
350
- * Calling serve() again replaces the previous handler.
351
- *
352
- * @param options - Server configuration including fetch handler and optional WebSocket handlers
353
- *
354
- * @example
355
- * type WsData = { connectedAt: number };
356
- *
357
- * serve({
358
- * fetch(request, server) {
359
- * const url = new URL(request.url);
360
- *
361
- * if (url.pathname === "/ws") {
362
- * if (server.upgrade(request, { data: { connectedAt: Date.now() } })) {
363
- * return new Response(null, { status: 101 });
364
- * }
365
- * }
366
- *
367
- * if (url.pathname === "/api/hello") {
368
- * return Response.json({ message: "Hello!" });
369
- * }
370
- *
371
- * return new Response("Not Found", { status: 404 });
372
- * },
373
- * websocket: {
374
- * data: {} as WsData,
375
- * open(ws) {
376
- * console.log("Connected at:", ws.data.connectedAt);
377
- * },
378
- * message(ws, message) {
379
- * ws.send("Echo: " + message);
380
- * },
381
- * close(ws, code, reason) {
382
- * console.log("Closed:", code, reason);
383
- * }
384
- * }
385
- * });
386
- */
387
- function serve<T = unknown>(options: ServeOptions<T>): void;
388
- }
389
- `;
390
-
391
- /**
392
- * Type definitions for @ricsam/isolate-fs globals.
393
- *
394
- * Includes: fs namespace, FileSystemHandle, FileSystemFileHandle, FileSystemDirectoryHandle, FileSystemWritableFileStream
395
- */
396
- export const FS_TYPES = `/**
397
- * Global Type Definitions for @ricsam/isolate-fs
398
- *
399
- * These types define the globals injected by setupFs() into an isolated-vm context.
400
- * Use these types to typecheck user code that will run inside the V8 isolate.
401
- *
402
- * @example
403
- * // Typecheck isolate code with file system access
404
- * const root = await getDirectory("/data");
405
- * const fileHandle = await root.getFileHandle("config.json");
406
- * const file = await fileHandle.getFile();
407
- * const content = await file.text();
408
- */
409
-
410
- export {};
411
-
412
- declare global {
413
- // ============================================
414
- // getDirectory - Isolate-specific entry point
415
- // ============================================
416
-
417
- /**
418
- * Get a directory handle for the given path.
419
- *
420
- * The host controls which paths are accessible. Invalid or unauthorized
421
- * paths will throw an error.
422
- *
423
- * @param path - The path to request from the host
424
- * @returns A promise resolving to a directory handle
425
- * @throws If the path is not allowed or doesn't exist
426
- *
427
- * @example
428
- * const root = await getDirectory("/");
429
- * const dataDir = await getDirectory("/data");
430
- */
431
- function getDirectory(path: string): Promise<FileSystemDirectoryHandle>;
432
-
433
- // ============================================
434
- // File System Access API
435
- // ============================================
436
-
437
- /**
438
- * Base interface for file system handles.
439
- */
440
- interface FileSystemHandle {
441
- /**
442
- * The kind of handle: "file" or "directory".
443
- */
444
- readonly kind: "file" | "directory";
445
-
446
- /**
447
- * The name of the file or directory.
448
- */
449
- readonly name: string;
450
-
451
- /**
452
- * Compare two handles to check if they reference the same entry.
453
- *
454
- * @param other - Another FileSystemHandle to compare against
455
- * @returns true if both handles reference the same entry
456
- */
457
- isSameEntry(other: FileSystemHandle): Promise<boolean>;
458
- }
459
-
460
- /**
461
- * Handle for a file in the file system.
462
- */
463
- interface FileSystemFileHandle extends FileSystemHandle {
464
- /**
465
- * Always "file" for file handles.
466
- */
467
- readonly kind: "file";
468
-
469
- /**
470
- * Get the file contents as a File object.
471
- *
472
- * @returns A promise resolving to a File object
473
- *
474
- * @example
475
- * const file = await fileHandle.getFile();
476
- * const text = await file.text();
477
- */
478
- getFile(): Promise<File>;
479
-
480
- /**
481
- * Create a writable stream for writing to the file.
482
- *
483
- * @param options - Options for the writable stream
484
- * @returns A promise resolving to a writable stream
485
- *
486
- * @example
487
- * const writable = await fileHandle.createWritable();
488
- * await writable.write("Hello, World!");
489
- * await writable.close();
490
- */
491
- createWritable(options?: {
492
- /**
493
- * If true, keeps existing file data. Otherwise, truncates the file.
494
- */
495
- keepExistingData?: boolean;
496
- }): Promise<FileSystemWritableFileStream>;
497
- }
498
-
499
- /**
500
- * Handle for a directory in the file system.
501
- */
502
- interface FileSystemDirectoryHandle extends FileSystemHandle {
503
- /**
504
- * Always "directory" for directory handles.
505
- */
506
- readonly kind: "directory";
507
-
508
- /**
509
- * Get a file handle within this directory.
510
- *
511
- * @param name - The name of the file
512
- * @param options - Options for getting the file handle
513
- * @returns A promise resolving to a file handle
514
- * @throws If the file doesn't exist and create is not true
515
- *
516
- * @example
517
- * const file = await dir.getFileHandle("data.json");
518
- * const newFile = await dir.getFileHandle("output.txt", { create: true });
519
- */
520
- getFileHandle(
521
- name: string,
522
- options?: {
523
- /**
524
- * If true, creates the file if it doesn't exist.
525
- */
526
- create?: boolean;
527
- }
528
- ): Promise<FileSystemFileHandle>;
529
-
530
- /**
531
- * Get a subdirectory handle within this directory.
532
- *
533
- * @param name - The name of the subdirectory
534
- * @param options - Options for getting the directory handle
535
- * @returns A promise resolving to a directory handle
536
- * @throws If the directory doesn't exist and create is not true
537
- *
538
- * @example
539
- * const subdir = await dir.getDirectoryHandle("logs");
540
- * const newDir = await dir.getDirectoryHandle("cache", { create: true });
541
- */
542
- getDirectoryHandle(
543
- name: string,
544
- options?: {
545
- /**
546
- * If true, creates the directory if it doesn't exist.
547
- */
548
- create?: boolean;
549
- }
550
- ): Promise<FileSystemDirectoryHandle>;
551
-
552
- /**
553
- * Remove a file or directory within this directory.
554
- *
555
- * @param name - The name of the entry to remove
556
- * @param options - Options for removal
557
- * @throws If the entry doesn't exist or cannot be removed
558
- *
559
- * @example
560
- * await dir.removeEntry("old-file.txt");
561
- * await dir.removeEntry("old-dir", { recursive: true });
562
- */
563
- removeEntry(
564
- name: string,
565
- options?: {
566
- /**
567
- * If true, removes directories recursively.
568
- */
569
- recursive?: boolean;
570
- }
571
- ): Promise<void>;
572
-
573
- /**
574
- * Resolve the path from this directory to a descendant handle.
575
- *
576
- * @param possibleDescendant - A handle that may be a descendant
577
- * @returns An array of path segments, or null if not a descendant
578
- *
579
- * @example
580
- * const path = await root.resolve(nestedFile);
581
- * // ["subdir", "file.txt"]
582
- */
583
- resolve(possibleDescendant: FileSystemHandle): Promise<string[] | null>;
584
-
585
- /**
586
- * Iterate over entries in this directory.
587
- *
588
- * @returns An async iterator of [name, handle] pairs
589
- *
590
- * @example
591
- * for await (const [name, handle] of dir.entries()) {
592
- * console.log(name, handle.kind);
593
- * }
594
- */
595
- entries(): AsyncIterableIterator<[string, FileSystemHandle]>;
596
-
597
- /**
598
- * Iterate over entry names in this directory.
599
- *
600
- * @returns An async iterator of names
601
- *
602
- * @example
603
- * for await (const name of dir.keys()) {
604
- * console.log(name);
605
- * }
606
- */
607
- keys(): AsyncIterableIterator<string>;
608
-
609
- /**
610
- * Iterate over handles in this directory.
611
- *
612
- * @returns An async iterator of handles
613
- *
614
- * @example
615
- * for await (const handle of dir.values()) {
616
- * console.log(handle.name, handle.kind);
617
- * }
618
- */
619
- values(): AsyncIterableIterator<FileSystemHandle>;
620
-
621
- /**
622
- * Async iterator support for directory entries.
623
- *
624
- * @example
625
- * for await (const [name, handle] of dir) {
626
- * console.log(name, handle.kind);
627
- * }
628
- */
629
- [Symbol.asyncIterator](): AsyncIterableIterator<[string, FileSystemHandle]>;
630
- }
631
-
632
- /**
633
- * Parameters for write operations on FileSystemWritableFileStream.
634
- */
635
- interface WriteParams {
636
- /**
637
- * The type of write operation.
638
- * - "write": Write data at the current position or specified position
639
- * - "seek": Move the file position
640
- * - "truncate": Truncate the file to a specific size
641
- */
642
- type: "write" | "seek" | "truncate";
643
-
644
- /**
645
- * The data to write (for "write" type).
646
- */
647
- data?: string | ArrayBuffer | Uint8Array | Blob;
648
-
649
- /**
650
- * The position to write at or seek to.
651
- */
652
- position?: number;
653
-
654
- /**
655
- * The size to truncate to (for "truncate" type).
656
- */
657
- size?: number;
658
- }
659
-
660
- /**
661
- * Writable stream for writing to a file.
662
- * Extends WritableStream with file-specific operations.
663
- */
664
- interface FileSystemWritableFileStream extends WritableStream<Uint8Array> {
665
- /**
666
- * Write data to the file.
667
- *
668
- * @param data - The data to write
669
- * @returns A promise that resolves when the write completes
670
- *
671
- * @example
672
- * await writable.write("Hello, World!");
673
- * await writable.write(new Uint8Array([1, 2, 3]));
674
- * await writable.write({ type: "write", data: "text", position: 0 });
675
- */
676
- write(
677
- data: string | ArrayBuffer | Uint8Array | Blob | WriteParams
678
- ): Promise<void>;
679
-
680
- /**
681
- * Seek to a position in the file.
682
- *
683
- * @param position - The byte position to seek to
684
- * @returns A promise that resolves when the seek completes
685
- *
686
- * @example
687
- * await writable.seek(0); // Seek to beginning
688
- * await writable.write("Overwrite");
689
- */
690
- seek(position: number): Promise<void>;
691
-
692
- /**
693
- * Truncate the file to a specific size.
694
- *
695
- * @param size - The size to truncate to
696
- * @returns A promise that resolves when the truncation completes
697
- *
698
- * @example
699
- * await writable.truncate(100); // Keep only first 100 bytes
700
- */
701
- truncate(size: number): Promise<void>;
702
- }
703
- }
704
- `;
705
-
706
- /**
707
- * Type definitions for @ricsam/isolate-test-environment globals.
708
- *
709
- * Includes: describe, it, test, expect, beforeAll, afterAll, beforeEach, afterEach
710
- */
711
- export const TEST_ENV_TYPES = `/**
712
- * Global Type Definitions for @ricsam/isolate-test-environment
713
- *
714
- * These types define the globals injected by setupTestEnvironment() into an isolated-vm context.
715
- * Use these types to typecheck user code that will run inside the V8 isolate.
716
- *
717
- * @example
718
- * describe("Math operations", () => {
719
- * it("should add numbers", () => {
720
- * expect(1 + 1).toBe(2);
721
- * });
722
- * });
723
- */
724
-
725
- export {};
726
-
727
- declare global {
728
- // ============================================
729
- // Test Structure
730
- // ============================================
731
-
732
- /**
733
- * Define a test suite.
734
- *
735
- * @param name - The name of the test suite
736
- * @param fn - Function containing tests and nested suites
737
- *
738
- * @example
739
- * describe("Calculator", () => {
740
- * it("adds numbers", () => {
741
- * expect(1 + 1).toBe(2);
742
- * });
743
- * });
744
- */
745
- function describe(name: string, fn: () => void): void;
746
-
747
- namespace describe {
748
- /**
749
- * Skip this suite and all its tests.
750
- */
751
- function skip(name: string, fn: () => void): void;
752
-
753
- /**
754
- * Only run this suite (and other .only suites).
755
- */
756
- function only(name: string, fn: () => void): void;
757
-
758
- /**
759
- * Mark suite as todo (skipped with different status).
760
- */
761
- function todo(name: string, fn?: () => void): void;
762
- }
763
-
764
- /**
765
- * Define a test case.
766
- *
767
- * @param name - The name of the test
768
- * @param fn - The test function (can be async)
769
- *
770
- * @example
771
- * it("should work", () => {
772
- * expect(true).toBe(true);
773
- * });
774
- *
775
- * it("should work async", async () => {
776
- * const result = await Promise.resolve(42);
777
- * expect(result).toBe(42);
778
- * });
779
- */
780
- function it(name: string, fn: () => void | Promise<void>): void;
781
-
782
- namespace it {
783
- /**
784
- * Skip this test.
785
- */
786
- function skip(name: string, fn?: () => void | Promise<void>): void;
787
-
788
- /**
789
- * Only run this test (and other .only tests).
790
- */
791
- function only(name: string, fn: () => void | Promise<void>): void;
792
-
793
- /**
794
- * Mark test as todo.
795
- */
796
- function todo(name: string, fn?: () => void | Promise<void>): void;
797
- }
798
-
799
- /**
800
- * Alias for it().
801
- */
802
- function test(name: string, fn: () => void | Promise<void>): void;
803
-
804
- namespace test {
805
- /**
806
- * Skip this test.
807
- */
808
- function skip(name: string, fn?: () => void | Promise<void>): void;
809
-
810
- /**
811
- * Only run this test (and other .only tests).
812
- */
813
- function only(name: string, fn: () => void | Promise<void>): void;
814
-
815
- /**
816
- * Mark test as todo.
817
- */
818
- function todo(name: string, fn?: () => void | Promise<void>): void;
819
- }
820
-
821
- // ============================================
822
- // Lifecycle Hooks
823
- // ============================================
824
-
825
- /**
826
- * Run once before all tests in the current suite.
827
- *
828
- * @param fn - Setup function (can be async)
829
- */
830
- function beforeAll(fn: () => void | Promise<void>): void;
831
-
832
- /**
833
- * Run once after all tests in the current suite.
834
- *
835
- * @param fn - Teardown function (can be async)
836
- */
837
- function afterAll(fn: () => void | Promise<void>): void;
838
-
839
- /**
840
- * Run before each test in the current suite (and nested suites).
841
- *
842
- * @param fn - Setup function (can be async)
843
- */
844
- function beforeEach(fn: () => void | Promise<void>): void;
845
-
846
- /**
847
- * Run after each test in the current suite (and nested suites).
848
- *
849
- * @param fn - Teardown function (can be async)
850
- */
851
- function afterEach(fn: () => void | Promise<void>): void;
852
-
853
- // ============================================
854
- // Assertions
855
- // ============================================
856
-
857
- /**
858
- * Matchers for assertions.
859
- */
860
- interface Matchers<T> {
861
- /**
862
- * Strict equality (===).
863
- */
864
- toBe(expected: T): void;
865
-
866
- /**
867
- * Deep equality.
868
- */
869
- toEqual(expected: unknown): void;
870
-
871
- /**
872
- * Deep equality with type checking.
873
- */
874
- toStrictEqual(expected: unknown): void;
875
-
876
- /**
877
- * Check if value is truthy.
878
- */
879
- toBeTruthy(): void;
880
-
881
- /**
882
- * Check if value is falsy.
883
- */
884
- toBeFalsy(): void;
885
-
886
- /**
887
- * Check if value is null.
888
- */
889
- toBeNull(): void;
890
-
891
- /**
892
- * Check if value is undefined.
893
- */
894
- toBeUndefined(): void;
895
-
896
- /**
897
- * Check if value is defined (not undefined).
898
- */
899
- toBeDefined(): void;
900
-
901
- /**
902
- * Check if value is NaN.
903
- */
904
- toBeNaN(): void;
905
-
906
- /**
907
- * Check if number is greater than expected.
908
- */
909
- toBeGreaterThan(n: number): void;
910
-
911
- /**
912
- * Check if number is greater than or equal to expected.
913
- */
914
- toBeGreaterThanOrEqual(n: number): void;
915
-
916
- /**
917
- * Check if number is less than expected.
918
- */
919
- toBeLessThan(n: number): void;
920
-
921
- /**
922
- * Check if number is less than or equal to expected.
923
- */
924
- toBeLessThanOrEqual(n: number): void;
925
-
926
- /**
927
- * Check if array/string contains item/substring.
928
- */
929
- toContain(item: unknown): void;
930
-
931
- /**
932
- * Check length of array/string.
933
- */
934
- toHaveLength(length: number): void;
935
-
936
- /**
937
- * Check if object has property (optionally with value).
938
- */
939
- toHaveProperty(key: string, value?: unknown): void;
940
-
941
- /**
942
- * Check if function throws.
943
- */
944
- toThrow(expected?: string | RegExp | Error): void;
945
-
946
- /**
947
- * Check if string matches pattern.
948
- */
949
- toMatch(pattern: string | RegExp): void;
950
-
951
- /**
952
- * Check if object matches subset of properties.
953
- */
954
- toMatchObject(object: object): void;
955
-
956
- /**
957
- * Check if value is instance of class.
958
- */
959
- toBeInstanceOf(constructor: Function): void;
960
-
961
- /**
962
- * Negate the matcher.
963
- */
964
- not: Matchers<T>;
965
-
966
- /**
967
- * Await promise and check resolved value.
968
- */
969
- resolves: Matchers<Awaited<T>>;
970
-
971
- /**
972
- * Await promise and check rejection.
973
- */
974
- rejects: Matchers<unknown>;
975
- }
976
-
977
- /**
978
- * Create an expectation for a value.
979
- *
980
- * @param actual - The value to test
981
- * @returns Matchers for the value
982
- *
983
- * @example
984
- * expect(1 + 1).toBe(2);
985
- * expect({ a: 1 }).toEqual({ a: 1 });
986
- * expect(() => { throw new Error(); }).toThrow();
987
- * expect(promise).resolves.toBe(42);
988
- */
989
- function expect<T>(actual: T): Matchers<T>;
990
- }
991
- `;
992
-
993
- /**
994
- * Type definitions for @ricsam/isolate-console globals.
995
- *
996
- * Includes: console.log, warn, error, debug, info, trace, dir, table, time, timeEnd, timeLog, count, countReset, clear, assert, group, groupCollapsed, groupEnd
997
- */
998
- export const CONSOLE_TYPES = `/**
999
- * Global Type Definitions for @ricsam/isolate-console
1000
- *
1001
- * These types define the globals injected by setupConsole() into an isolated-vm context.
1002
- * Use these types to typecheck user code that will run inside the V8 isolate.
1003
- */
1004
-
1005
- export {};
1006
-
1007
- declare global {
1008
- /**
1009
- * Console interface for logging and debugging.
1010
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Console
1011
- */
1012
- interface Console {
1013
- /**
1014
- * Log a message to the console.
1015
- * @param data - Values to log
1016
- */
1017
- log(...data: unknown[]): void;
1018
-
1019
- /**
1020
- * Log a warning message.
1021
- * @param data - Values to log
1022
- */
1023
- warn(...data: unknown[]): void;
1024
-
1025
- /**
1026
- * Log an error message.
1027
- * @param data - Values to log
1028
- */
1029
- error(...data: unknown[]): void;
1030
-
1031
- /**
1032
- * Log a debug message.
1033
- * @param data - Values to log
1034
- */
1035
- debug(...data: unknown[]): void;
1036
-
1037
- /**
1038
- * Log an info message.
1039
- * @param data - Values to log
1040
- */
1041
- info(...data: unknown[]): void;
1042
-
1043
- /**
1044
- * Log a stack trace.
1045
- * @param data - Values to log with the trace
1046
- */
1047
- trace(...data: unknown[]): void;
1048
-
1049
- /**
1050
- * Display an object in a formatted way.
1051
- * @param item - Object to display
1052
- * @param options - Display options
1053
- */
1054
- dir(item: unknown, options?: object): void;
1055
-
1056
- /**
1057
- * Display tabular data.
1058
- * @param tabularData - Data to display as a table
1059
- * @param properties - Optional array of property names to include
1060
- */
1061
- table(tabularData: unknown, properties?: string[]): void;
1062
-
1063
- /**
1064
- * Start a timer.
1065
- * @param label - Timer label (default: "default")
1066
- */
1067
- time(label?: string): void;
1068
-
1069
- /**
1070
- * End a timer and log the elapsed time.
1071
- * @param label - Timer label (default: "default")
1072
- */
1073
- timeEnd(label?: string): void;
1074
-
1075
- /**
1076
- * Log the elapsed time of a timer without ending it.
1077
- * @param label - Timer label (default: "default")
1078
- * @param data - Additional values to log
1079
- */
1080
- timeLog(label?: string, ...data: unknown[]): void;
1081
-
1082
- /**
1083
- * Log an error if the assertion is false.
1084
- * @param condition - Condition to test
1085
- * @param data - Values to log if assertion fails
1086
- */
1087
- assert(condition?: boolean, ...data: unknown[]): void;
1088
-
1089
- /**
1090
- * Increment and log a counter.
1091
- * @param label - Counter label (default: "default")
1092
- */
1093
- count(label?: string): void;
1094
-
1095
- /**
1096
- * Reset a counter.
1097
- * @param label - Counter label (default: "default")
1098
- */
1099
- countReset(label?: string): void;
1100
-
1101
- /**
1102
- * Clear the console.
1103
- */
1104
- clear(): void;
1105
-
1106
- /**
1107
- * Start an inline group.
1108
- * @param data - Group label
1109
- */
1110
- group(...data: unknown[]): void;
1111
-
1112
- /**
1113
- * Start a collapsed inline group.
1114
- * @param data - Group label
1115
- */
1116
- groupCollapsed(...data: unknown[]): void;
1117
-
1118
- /**
1119
- * End the current inline group.
1120
- */
1121
- groupEnd(): void;
1122
- }
1123
-
1124
- /**
1125
- * Console object for logging and debugging.
1126
- */
1127
- const console: Console;
1128
- }
1129
- `;
1130
-
1131
- /**
1132
- * Type definitions for @ricsam/isolate-encoding globals.
1133
- *
1134
- * Includes: atob, btoa
1135
- */
1136
- export const ENCODING_TYPES = `/**
1137
- * Global Type Definitions for @ricsam/isolate-encoding
1138
- *
1139
- * These types define the globals injected by setupEncoding() into an isolated-vm context.
1140
- * Use these types to typecheck user code that will run inside the V8 isolate.
1141
- */
1142
-
1143
- export {};
1144
-
1145
- declare global {
1146
- /**
1147
- * Decodes a Base64-encoded string.
1148
- *
1149
- * @param encodedData - The Base64 string to decode
1150
- * @returns The decoded string
1151
- * @throws DOMException if the input is not valid Base64
1152
- *
1153
- * @example
1154
- * atob("SGVsbG8="); // "Hello"
1155
- */
1156
- function atob(encodedData: string): string;
1157
-
1158
- /**
1159
- * Encodes a string to Base64.
1160
- *
1161
- * @param stringToEncode - The string to encode (must contain only Latin1 characters)
1162
- * @returns The Base64 encoded string
1163
- * @throws DOMException if the string contains characters outside Latin1 range (0-255)
1164
- *
1165
- * @example
1166
- * btoa("Hello"); // "SGVsbG8="
1167
- */
1168
- function btoa(stringToEncode: string): string;
1169
- }
1170
- `;
1171
-
1172
- /**
1173
- * Type definitions for @ricsam/isolate-crypto globals.
1174
- *
1175
- * Includes: crypto.subtle, crypto.getRandomValues, crypto.randomUUID, CryptoKey
1176
- */
1177
- export const CRYPTO_TYPES = `/**
1178
- * Global Type Definitions for @ricsam/isolate-crypto
1179
- *
1180
- * These types define the globals injected by setupCrypto() into an isolated-vm context.
1181
- * Use these types to typecheck user code that will run inside the V8 isolate.
1182
- *
1183
- * @example
1184
- * // Generate random bytes
1185
- * const arr = new Uint8Array(16);
1186
- * crypto.getRandomValues(arr);
1187
- *
1188
- * // Generate UUID
1189
- * const uuid = crypto.randomUUID();
1190
- *
1191
- * // Use SubtleCrypto
1192
- * const key = await crypto.subtle.generateKey(
1193
- * { name: "AES-GCM", length: 256 },
1194
- * true,
1195
- * ["encrypt", "decrypt"]
1196
- * );
1197
- */
1198
-
1199
- export {};
1200
-
1201
- declare global {
1202
- /**
1203
- * CryptoKey represents a cryptographic key.
1204
- * @see https://developer.mozilla.org/en-US/docs/Web/API/CryptoKey
1205
- */
1206
- interface CryptoKey {
1207
- /**
1208
- * The type of key: "public", "private", or "secret".
1209
- */
1210
- readonly type: "public" | "private" | "secret";
1211
-
1212
- /**
1213
- * Whether the key can be exported.
1214
- */
1215
- readonly extractable: boolean;
1216
-
1217
- /**
1218
- * The algorithm used by this key.
1219
- */
1220
- readonly algorithm: KeyAlgorithm;
1221
-
1222
- /**
1223
- * The usages allowed for this key.
1224
- */
1225
- readonly usages: ReadonlyArray<KeyUsage>;
1226
- }
1227
-
1228
- /**
1229
- * CryptoKey constructor (keys cannot be constructed directly).
1230
- */
1231
- const CryptoKey: {
1232
- prototype: CryptoKey;
1233
- };
1234
-
1235
- /**
1236
- * SubtleCrypto interface for cryptographic operations.
1237
- * @see https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto
1238
- */
1239
- interface SubtleCrypto {
1240
- /**
1241
- * Generate a digest (hash) of the given data.
1242
- *
1243
- * @param algorithm - Hash algorithm (e.g., "SHA-256", "SHA-384", "SHA-512")
1244
- * @param data - Data to hash
1245
- * @returns Promise resolving to the hash as ArrayBuffer
1246
- */
1247
- digest(
1248
- algorithm: AlgorithmIdentifier,
1249
- data: BufferSource
1250
- ): Promise<ArrayBuffer>;
1251
-
1252
- /**
1253
- * Generate a new cryptographic key or key pair.
1254
- *
1255
- * @param algorithm - Key generation algorithm
1256
- * @param extractable - Whether the key can be exported
1257
- * @param keyUsages - Allowed key usages
1258
- * @returns Promise resolving to a CryptoKey or CryptoKeyPair
1259
- */
1260
- generateKey(
1261
- algorithm: RsaHashedKeyGenParams | EcKeyGenParams | AesKeyGenParams | HmacKeyGenParams,
1262
- extractable: boolean,
1263
- keyUsages: KeyUsage[]
1264
- ): Promise<CryptoKey | CryptoKeyPair>;
1265
-
1266
- /**
1267
- * Sign data using a private key.
1268
- *
1269
- * @param algorithm - Signing algorithm
1270
- * @param key - Private key to sign with
1271
- * @param data - Data to sign
1272
- * @returns Promise resolving to the signature as ArrayBuffer
1273
- */
1274
- sign(
1275
- algorithm: AlgorithmIdentifier,
1276
- key: CryptoKey,
1277
- data: BufferSource
1278
- ): Promise<ArrayBuffer>;
1279
-
1280
- /**
1281
- * Verify a signature.
1282
- *
1283
- * @param algorithm - Signing algorithm
1284
- * @param key - Public key to verify with
1285
- * @param signature - Signature to verify
1286
- * @param data - Data that was signed
1287
- * @returns Promise resolving to true if valid, false otherwise
1288
- */
1289
- verify(
1290
- algorithm: AlgorithmIdentifier,
1291
- key: CryptoKey,
1292
- signature: BufferSource,
1293
- data: BufferSource
1294
- ): Promise<boolean>;
1295
-
1296
- /**
1297
- * Encrypt data.
1298
- *
1299
- * @param algorithm - Encryption algorithm
1300
- * @param key - Encryption key
1301
- * @param data - Data to encrypt
1302
- * @returns Promise resolving to encrypted data as ArrayBuffer
1303
- */
1304
- encrypt(
1305
- algorithm: AlgorithmIdentifier,
1306
- key: CryptoKey,
1307
- data: BufferSource
1308
- ): Promise<ArrayBuffer>;
1309
-
1310
- /**
1311
- * Decrypt data.
1312
- *
1313
- * @param algorithm - Decryption algorithm
1314
- * @param key - Decryption key
1315
- * @param data - Data to decrypt
1316
- * @returns Promise resolving to decrypted data as ArrayBuffer
1317
- */
1318
- decrypt(
1319
- algorithm: AlgorithmIdentifier,
1320
- key: CryptoKey,
1321
- data: BufferSource
1322
- ): Promise<ArrayBuffer>;
1323
-
1324
- /**
1325
- * Import a key from external data.
1326
- *
1327
- * @param format - Key format ("raw", "pkcs8", "spki", "jwk")
1328
- * @param keyData - Key data
1329
- * @param algorithm - Key algorithm
1330
- * @param extractable - Whether the key can be exported
1331
- * @param keyUsages - Allowed key usages
1332
- * @returns Promise resolving to a CryptoKey
1333
- */
1334
- importKey(
1335
- format: "raw" | "pkcs8" | "spki" | "jwk",
1336
- keyData: BufferSource | JsonWebKey,
1337
- algorithm: AlgorithmIdentifier,
1338
- extractable: boolean,
1339
- keyUsages: KeyUsage[]
1340
- ): Promise<CryptoKey>;
1341
-
1342
- /**
1343
- * Export a key.
1344
- *
1345
- * @param format - Export format ("raw", "pkcs8", "spki", "jwk")
1346
- * @param key - Key to export
1347
- * @returns Promise resolving to ArrayBuffer or JsonWebKey
1348
- */
1349
- exportKey(
1350
- format: "raw" | "pkcs8" | "spki" | "jwk",
1351
- key: CryptoKey
1352
- ): Promise<ArrayBuffer | JsonWebKey>;
1353
-
1354
- /**
1355
- * Derive bits from a key.
1356
- *
1357
- * @param algorithm - Derivation algorithm
1358
- * @param baseKey - Base key for derivation
1359
- * @param length - Number of bits to derive
1360
- * @returns Promise resolving to derived bits as ArrayBuffer
1361
- */
1362
- deriveBits(
1363
- algorithm: AlgorithmIdentifier,
1364
- baseKey: CryptoKey,
1365
- length: number
1366
- ): Promise<ArrayBuffer>;
1367
-
1368
- /**
1369
- * Derive a new key from a base key.
1370
- *
1371
- * @param algorithm - Derivation algorithm
1372
- * @param baseKey - Base key for derivation
1373
- * @param derivedKeyType - Type of key to derive
1374
- * @param extractable - Whether the derived key can be exported
1375
- * @param keyUsages - Allowed usages for derived key
1376
- * @returns Promise resolving to a CryptoKey
1377
- */
1378
- deriveKey(
1379
- algorithm: AlgorithmIdentifier,
1380
- baseKey: CryptoKey,
1381
- derivedKeyType: AlgorithmIdentifier,
1382
- extractable: boolean,
1383
- keyUsages: KeyUsage[]
1384
- ): Promise<CryptoKey>;
1385
-
1386
- /**
1387
- * Wrap a key for secure export.
1388
- *
1389
- * @param format - Key format
1390
- * @param key - Key to wrap
1391
- * @param wrappingKey - Key to wrap with
1392
- * @param wrapAlgorithm - Wrapping algorithm
1393
- * @returns Promise resolving to wrapped key as ArrayBuffer
1394
- */
1395
- wrapKey(
1396
- format: "raw" | "pkcs8" | "spki" | "jwk",
1397
- key: CryptoKey,
1398
- wrappingKey: CryptoKey,
1399
- wrapAlgorithm: AlgorithmIdentifier
1400
- ): Promise<ArrayBuffer>;
1401
-
1402
- /**
1403
- * Unwrap a wrapped key.
1404
- *
1405
- * @param format - Key format
1406
- * @param wrappedKey - Wrapped key data
1407
- * @param unwrappingKey - Key to unwrap with
1408
- * @param unwrapAlgorithm - Unwrapping algorithm
1409
- * @param unwrappedKeyAlgorithm - Algorithm for the unwrapped key
1410
- * @param extractable - Whether the unwrapped key can be exported
1411
- * @param keyUsages - Allowed usages for unwrapped key
1412
- * @returns Promise resolving to a CryptoKey
1413
- */
1414
- unwrapKey(
1415
- format: "raw" | "pkcs8" | "spki" | "jwk",
1416
- wrappedKey: BufferSource,
1417
- unwrappingKey: CryptoKey,
1418
- unwrapAlgorithm: AlgorithmIdentifier,
1419
- unwrappedKeyAlgorithm: AlgorithmIdentifier,
1420
- extractable: boolean,
1421
- keyUsages: KeyUsage[]
1422
- ): Promise<CryptoKey>;
1423
- }
1424
-
1425
- /**
1426
- * Crypto interface providing cryptographic functionality.
1427
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Crypto
1428
- */
1429
- interface Crypto {
1430
- /**
1431
- * SubtleCrypto interface for cryptographic operations.
1432
- */
1433
- readonly subtle: SubtleCrypto;
1434
-
1435
- /**
1436
- * Fill a TypedArray with cryptographically random values.
1437
- *
1438
- * @param array - TypedArray to fill (max 65536 bytes)
1439
- * @returns The same array, filled with random values
1440
- *
1441
- * @example
1442
- * const arr = new Uint8Array(16);
1443
- * crypto.getRandomValues(arr);
1444
- */
1445
- getRandomValues<T extends ArrayBufferView | null>(array: T): T;
1446
-
1447
- /**
1448
- * Generate a random UUID v4.
1449
- *
1450
- * @returns A random UUID string
1451
- *
1452
- * @example
1453
- * const uuid = crypto.randomUUID();
1454
- * // "550e8400-e29b-41d4-a716-446655440000"
1455
- */
1456
- randomUUID(): string;
1457
- }
1458
-
1459
- /**
1460
- * Crypto object providing cryptographic functionality.
1461
- */
1462
- const crypto: Crypto;
1463
- }
1464
- `;
1465
-
1466
- /**
1467
- * Type definitions for @ricsam/isolate-path globals.
1468
- *
1469
- * Includes: path.join, path.normalize, path.basename, path.dirname, path.extname,
1470
- * path.isAbsolute, path.parse, path.format, path.resolve, path.relative,
1471
- * path.cwd, path.sep, path.delimiter
1472
- */
1473
- export const PATH_TYPES = `/**
1474
- * Global Type Definitions for @ricsam/isolate-path
1475
- *
1476
- * These types define the globals injected by setupPath() into an isolated-vm context.
1477
- * Use these types to typecheck user code that will run inside the V8 isolate.
1478
- *
1479
- * @example
1480
- * // Typecheck isolate code with path operations
1481
- * const joined = path.join('/foo', 'bar', 'baz');
1482
- * const resolved = path.resolve('relative/path');
1483
- * const cwd = path.cwd();
1484
- */
1485
-
1486
- export {};
1487
-
1488
- declare global {
1489
- /**
1490
- * Parsed path object returned by path.parse().
1491
- */
1492
- interface ParsedPath {
1493
- /** The root of the path (e.g., "/" for absolute paths, "" for relative) */
1494
- root: string;
1495
- /** The directory portion of the path */
1496
- dir: string;
1497
- /** The file name including extension */
1498
- base: string;
1499
- /** The file extension (e.g., ".txt") */
1500
- ext: string;
1501
- /** The file name without extension */
1502
- name: string;
1503
- }
1504
-
1505
- /**
1506
- * Input object for path.format().
1507
- */
1508
- interface FormatInputPathObject {
1509
- root?: string;
1510
- dir?: string;
1511
- base?: string;
1512
- ext?: string;
1513
- name?: string;
1514
- }
1515
-
1516
- /**
1517
- * Path utilities for POSIX paths.
1518
- * @see https://nodejs.org/api/path.html
1519
- */
1520
- namespace path {
1521
- /**
1522
- * Join path segments with the platform-specific separator.
1523
- *
1524
- * @param paths - Path segments to join
1525
- * @returns The joined path, normalized
1526
- *
1527
- * @example
1528
- * path.join('/foo', 'bar', 'baz'); // "/foo/bar/baz"
1529
- * path.join('foo', 'bar', '..', 'baz'); // "foo/baz"
1530
- */
1531
- function join(...paths: string[]): string;
1532
-
1533
- /**
1534
- * Normalize a path, resolving '..' and '.' segments.
1535
- *
1536
- * @param p - The path to normalize
1537
- * @returns The normalized path
1538
- *
1539
- * @example
1540
- * path.normalize('/foo/bar/../baz'); // "/foo/baz"
1541
- * path.normalize('/foo//bar'); // "/foo/bar"
1542
- */
1543
- function normalize(p: string): string;
1544
-
1545
- /**
1546
- * Get the last portion of a path (the file name).
1547
- *
1548
- * @param p - The path
1549
- * @param ext - Optional extension to remove from the result
1550
- * @returns The base name of the path
1551
- *
1552
- * @example
1553
- * path.basename('/foo/bar/baz.txt'); // "baz.txt"
1554
- * path.basename('/foo/bar/baz.txt', '.txt'); // "baz"
1555
- */
1556
- function basename(p: string, ext?: string): string;
1557
-
1558
- /**
1559
- * Get the directory name of a path.
1560
- *
1561
- * @param p - The path
1562
- * @returns The directory portion of the path
1563
- *
1564
- * @example
1565
- * path.dirname('/foo/bar/baz.txt'); // "/foo/bar"
1566
- * path.dirname('/foo'); // "/"
1567
- */
1568
- function dirname(p: string): string;
1569
-
1570
- /**
1571
- * Get the extension of a path.
1572
- *
1573
- * @param p - The path
1574
- * @returns The extension including the dot, or empty string
1575
- *
1576
- * @example
1577
- * path.extname('file.txt'); // ".txt"
1578
- * path.extname('file.tar.gz'); // ".gz"
1579
- * path.extname('.bashrc'); // ""
1580
- */
1581
- function extname(p: string): string;
1582
-
1583
- /**
1584
- * Check if a path is absolute.
1585
- *
1586
- * @param p - The path to check
1587
- * @returns True if the path is absolute
1588
- *
1589
- * @example
1590
- * path.isAbsolute('/foo/bar'); // true
1591
- * path.isAbsolute('foo/bar'); // false
1592
- */
1593
- function isAbsolute(p: string): boolean;
1594
-
1595
- /**
1596
- * Parse a path into its components.
1597
- *
1598
- * @param p - The path to parse
1599
- * @returns An object with root, dir, base, ext, and name properties
1600
- *
1601
- * @example
1602
- * path.parse('/foo/bar/baz.txt');
1603
- * // { root: "/", dir: "/foo/bar", base: "baz.txt", ext: ".txt", name: "baz" }
1604
- */
1605
- function parse(p: string): ParsedPath;
1606
-
1607
- /**
1608
- * Build a path from an object.
1609
- *
1610
- * @param pathObject - Object with path components
1611
- * @returns The formatted path string
1612
- *
1613
- * @example
1614
- * path.format({ dir: '/foo/bar', base: 'baz.txt' }); // "/foo/bar/baz.txt"
1615
- * path.format({ root: '/', name: 'file', ext: '.txt' }); // "/file.txt"
1616
- */
1617
- function format(pathObject: FormatInputPathObject): string;
1618
-
1619
- /**
1620
- * Resolve a sequence of paths to an absolute path.
1621
- * Processes paths from right to left, prepending each until an absolute path is formed.
1622
- * Uses the configured working directory for relative paths.
1623
- *
1624
- * @param paths - Path segments to resolve
1625
- * @returns The resolved absolute path
1626
- *
1627
- * @example
1628
- * // With cwd set to "/home/user"
1629
- * path.resolve('foo/bar'); // "/home/user/foo/bar"
1630
- * path.resolve('/foo', 'bar'); // "/foo/bar"
1631
- * path.resolve('/foo', '/bar', 'baz'); // "/bar/baz"
1632
- */
1633
- function resolve(...paths: string[]): string;
1634
-
1635
- /**
1636
- * Compute the relative path from one path to another.
1637
- *
1638
- * @param from - The source path
1639
- * @param to - The destination path
1640
- * @returns The relative path from 'from' to 'to'
1641
- *
1642
- * @example
1643
- * path.relative('/foo/bar', '/foo/baz'); // "../baz"
1644
- * path.relative('/foo', '/foo/bar/baz'); // "bar/baz"
1645
- */
1646
- function relative(from: string, to: string): string;
1647
-
1648
- /**
1649
- * Get the configured working directory.
1650
- *
1651
- * @returns The current working directory
1652
- *
1653
- * @example
1654
- * path.cwd(); // "/home/user" (or whatever was configured)
1655
- */
1656
- function cwd(): string;
1657
-
1658
- /**
1659
- * The platform-specific path segment separator.
1660
- * Always "/" for POSIX paths.
1661
- */
1662
- const sep: string;
1663
-
1664
- /**
1665
- * The platform-specific path delimiter.
1666
- * Always ":" for POSIX paths.
1667
- */
1668
- const delimiter: string;
1669
- }
1670
- }
1671
- `;
1672
-
1673
- /**
1674
- * Type definitions for @ricsam/isolate-timers globals.
1675
- *
1676
- * Includes: setTimeout, setInterval, clearTimeout, clearInterval
1677
- */
1678
- export const TIMERS_TYPES = `/**
1679
- * Global Type Definitions for @ricsam/isolate-timers
1680
- *
1681
- * These types define the globals injected by setupTimers() into an isolated-vm context.
1682
- * Use these types to typecheck user code that will run inside the V8 isolate.
1683
- *
1684
- * @example
1685
- * const timeoutId = setTimeout(() => {
1686
- * console.log("fired!");
1687
- * }, 1000);
1688
- *
1689
- * clearTimeout(timeoutId);
1690
- *
1691
- * const intervalId = setInterval(() => {
1692
- * console.log("tick");
1693
- * }, 100);
1694
- *
1695
- * clearInterval(intervalId);
1696
- */
1697
-
1698
- export {};
1699
-
1700
- declare global {
1701
- /**
1702
- * Schedule a callback to execute after a delay.
1703
- *
1704
- * @param callback - The function to call after the delay
1705
- * @param ms - The delay in milliseconds (default: 0)
1706
- * @param args - Additional arguments to pass to the callback
1707
- * @returns A timer ID that can be passed to clearTimeout
1708
- *
1709
- * @example
1710
- * const id = setTimeout(() => console.log("done"), 1000);
1711
- * setTimeout((a, b) => console.log(a, b), 100, "hello", "world");
1712
- */
1713
- function setTimeout(
1714
- callback: (...args: unknown[]) => void,
1715
- ms?: number,
1716
- ...args: unknown[]
1717
- ): number;
1718
-
1719
- /**
1720
- * Schedule a callback to execute repeatedly at a fixed interval.
1721
- *
1722
- * @param callback - The function to call at each interval
1723
- * @param ms - The interval in milliseconds (minimum: 4ms)
1724
- * @param args - Additional arguments to pass to the callback
1725
- * @returns A timer ID that can be passed to clearInterval
1726
- *
1727
- * @example
1728
- * const id = setInterval(() => console.log("tick"), 1000);
1729
- */
1730
- function setInterval(
1731
- callback: (...args: unknown[]) => void,
1732
- ms?: number,
1733
- ...args: unknown[]
1734
- ): number;
1735
-
1736
- /**
1737
- * Cancel a timeout previously scheduled with setTimeout.
1738
- *
1739
- * @param id - The timer ID returned by setTimeout
1740
- *
1741
- * @example
1742
- * const id = setTimeout(() => {}, 1000);
1743
- * clearTimeout(id);
1744
- */
1745
- function clearTimeout(id: number | undefined): void;
1746
-
1747
- /**
1748
- * Cancel an interval previously scheduled with setInterval.
1749
- *
1750
- * @param id - The timer ID returned by setInterval
1751
- *
1752
- * @example
1753
- * const id = setInterval(() => {}, 1000);
1754
- * clearInterval(id);
1755
- */
1756
- function clearInterval(id: number | undefined): void;
1757
- }
1758
- `;
1759
-
1760
- /**
1761
- * Map of package names to their type definitions.
1762
- */
1763
- export const TYPE_DEFINITIONS = {
1764
- core: CORE_TYPES,
1765
- console: CONSOLE_TYPES,
1766
- crypto: CRYPTO_TYPES,
1767
- encoding: ENCODING_TYPES,
1768
- fetch: FETCH_TYPES,
1769
- fs: FS_TYPES,
1770
- path: PATH_TYPES,
1771
- testEnvironment: TEST_ENV_TYPES,
1772
- timers: TIMERS_TYPES,
1773
- } as const;
1774
-
1775
- /**
1776
- * Type for the keys of TYPE_DEFINITIONS.
1777
- */
1778
- export type TypeDefinitionKey = keyof typeof TYPE_DEFINITIONS;