@grest-ts/testkit 0.0.5

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.
Files changed (200) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +413 -0
  3. package/dist/src/GGBundleTest.d.ts +8 -0
  4. package/dist/src/GGBundleTest.d.ts.map +1 -0
  5. package/dist/src/GGBundleTest.js +75 -0
  6. package/dist/src/GGBundleTest.js.map +1 -0
  7. package/dist/src/GGTest.d.ts +131 -0
  8. package/dist/src/GGTest.d.ts.map +1 -0
  9. package/dist/src/GGTest.js +245 -0
  10. package/dist/src/GGTest.js.map +1 -0
  11. package/dist/src/GGTestContext.d.ts +36 -0
  12. package/dist/src/GGTestContext.d.ts.map +1 -0
  13. package/dist/src/GGTestContext.js +63 -0
  14. package/dist/src/GGTestContext.js.map +1 -0
  15. package/dist/src/GGTestRunner.d.ts +108 -0
  16. package/dist/src/GGTestRunner.d.ts.map +1 -0
  17. package/dist/src/GGTestRunner.js +242 -0
  18. package/dist/src/GGTestRunner.js.map +1 -0
  19. package/dist/src/GGTestRuntime.d.ts +103 -0
  20. package/dist/src/GGTestRuntime.d.ts.map +1 -0
  21. package/dist/src/GGTestRuntime.js +219 -0
  22. package/dist/src/GGTestRuntime.js.map +1 -0
  23. package/dist/src/GGTestRuntimeWorker.d.ts +41 -0
  24. package/dist/src/GGTestRuntimeWorker.d.ts.map +1 -0
  25. package/dist/src/GGTestRuntimeWorker.js +136 -0
  26. package/dist/src/GGTestRuntimeWorker.js.map +1 -0
  27. package/dist/src/GGTestSharedRef.d.ts +35 -0
  28. package/dist/src/GGTestSharedRef.d.ts.map +1 -0
  29. package/dist/src/GGTestSharedRef.js +126 -0
  30. package/dist/src/GGTestSharedRef.js.map +1 -0
  31. package/dist/src/GGTestkitExtensionsDiscovery.d.ts +21 -0
  32. package/dist/src/GGTestkitExtensionsDiscovery.d.ts.map +1 -0
  33. package/dist/src/GGTestkitExtensionsDiscovery.js +24 -0
  34. package/dist/src/GGTestkitExtensionsDiscovery.js.map +1 -0
  35. package/dist/src/IGGLocalDiscoveryServer.d.ts +16 -0
  36. package/dist/src/IGGLocalDiscoveryServer.d.ts.map +1 -0
  37. package/dist/src/IGGLocalDiscoveryServer.js +2 -0
  38. package/dist/src/IGGLocalDiscoveryServer.js.map +1 -0
  39. package/dist/src/callOn/GGCallOnSelector.d.ts +42 -0
  40. package/dist/src/callOn/GGCallOnSelector.d.ts.map +1 -0
  41. package/dist/src/callOn/GGCallOnSelector.js +35 -0
  42. package/dist/src/callOn/GGCallOnSelector.js.map +1 -0
  43. package/dist/src/callOn/GGContractClass.implement.d.ts +8 -0
  44. package/dist/src/callOn/GGContractClass.implement.d.ts.map +1 -0
  45. package/dist/src/callOn/GGContractClass.implement.js +31 -0
  46. package/dist/src/callOn/GGContractClass.implement.js.map +1 -0
  47. package/dist/src/callOn/GGTestActionForLocatorOnCall.d.ts +28 -0
  48. package/dist/src/callOn/GGTestActionForLocatorOnCall.d.ts.map +1 -0
  49. package/dist/src/callOn/GGTestActionForLocatorOnCall.js +118 -0
  50. package/dist/src/callOn/GGTestActionForLocatorOnCall.js.map +1 -0
  51. package/dist/src/callOn/TestableIPC.d.ts +72 -0
  52. package/dist/src/callOn/TestableIPC.d.ts.map +1 -0
  53. package/dist/src/callOn/TestableIPC.js +34 -0
  54. package/dist/src/callOn/TestableIPC.js.map +1 -0
  55. package/dist/src/callOn/callOn.d.ts +113 -0
  56. package/dist/src/callOn/callOn.d.ts.map +1 -0
  57. package/dist/src/callOn/callOn.js +122 -0
  58. package/dist/src/callOn/callOn.js.map +1 -0
  59. package/dist/src/callOn/registerOnCallHandler.d.ts +13 -0
  60. package/dist/src/callOn/registerOnCallHandler.d.ts.map +1 -0
  61. package/dist/src/callOn/registerOnCallHandler.js +111 -0
  62. package/dist/src/callOn/registerOnCallHandler.js.map +1 -0
  63. package/dist/src/index-node.d.ts +35 -0
  64. package/dist/src/index-node.d.ts.map +1 -0
  65. package/dist/src/index-node.js +50 -0
  66. package/dist/src/index-node.js.map +1 -0
  67. package/dist/src/mockable/GGMockable.d.ts +19 -0
  68. package/dist/src/mockable/GGMockable.d.ts.map +1 -0
  69. package/dist/src/mockable/GGMockable.js +2 -0
  70. package/dist/src/mockable/GGMockable.js.map +1 -0
  71. package/dist/src/mockable/GGMockableCall.d.ts +2 -0
  72. package/dist/src/mockable/GGMockableCall.d.ts.map +1 -0
  73. package/dist/src/mockable/GGMockableCall.js +41 -0
  74. package/dist/src/mockable/GGMockableCall.js.map +1 -0
  75. package/dist/src/mockable/GGMockableIPC.d.ts +17 -0
  76. package/dist/src/mockable/GGMockableIPC.d.ts.map +1 -0
  77. package/dist/src/mockable/GGMockableIPC.js +8 -0
  78. package/dist/src/mockable/GGMockableIPC.js.map +1 -0
  79. package/dist/src/mockable/GGMockableInterceptor.d.ts +24 -0
  80. package/dist/src/mockable/GGMockableInterceptor.d.ts.map +1 -0
  81. package/dist/src/mockable/GGMockableInterceptor.js +32 -0
  82. package/dist/src/mockable/GGMockableInterceptor.js.map +1 -0
  83. package/dist/src/mockable/GGMockableInterceptorsServer.d.ts +12 -0
  84. package/dist/src/mockable/GGMockableInterceptorsServer.d.ts.map +1 -0
  85. package/dist/src/mockable/GGMockableInterceptorsServer.js +55 -0
  86. package/dist/src/mockable/GGMockableInterceptorsServer.js.map +1 -0
  87. package/dist/src/mockable/mockable.d.ts +46 -0
  88. package/dist/src/mockable/mockable.d.ts.map +1 -0
  89. package/dist/src/mockable/mockable.js +47 -0
  90. package/dist/src/mockable/mockable.js.map +1 -0
  91. package/dist/src/runner/InlineRunner.d.ts +12 -0
  92. package/dist/src/runner/InlineRunner.d.ts.map +1 -0
  93. package/dist/src/runner/InlineRunner.js +42 -0
  94. package/dist/src/runner/InlineRunner.js.map +1 -0
  95. package/dist/src/runner/IsolatedRunner.d.ts +17 -0
  96. package/dist/src/runner/IsolatedRunner.d.ts.map +1 -0
  97. package/dist/src/runner/IsolatedRunner.js +155 -0
  98. package/dist/src/runner/IsolatedRunner.js.map +1 -0
  99. package/dist/src/runner/RuntimeRunner.d.ts +14 -0
  100. package/dist/src/runner/RuntimeRunner.d.ts.map +1 -0
  101. package/dist/src/runner/RuntimeRunner.js +2 -0
  102. package/dist/src/runner/RuntimeRunner.js.map +1 -0
  103. package/dist/src/runner/WorkerRunner.d.ts +17 -0
  104. package/dist/src/runner/WorkerRunner.d.ts.map +1 -0
  105. package/dist/src/runner/WorkerRunner.js +155 -0
  106. package/dist/src/runner/WorkerRunner.js.map +1 -0
  107. package/dist/src/runner/isolated-loader.mjs +91 -0
  108. package/dist/src/runner/worker-loader.mjs +49 -0
  109. package/dist/src/testers/GGCallInterceptor.d.ts +71 -0
  110. package/dist/src/testers/GGCallInterceptor.d.ts.map +1 -0
  111. package/dist/src/testers/GGCallInterceptor.js +170 -0
  112. package/dist/src/testers/GGCallInterceptor.js.map +1 -0
  113. package/dist/src/testers/GGMockWith.d.ts +30 -0
  114. package/dist/src/testers/GGMockWith.d.ts.map +1 -0
  115. package/dist/src/testers/GGMockWith.js +70 -0
  116. package/dist/src/testers/GGMockWith.js.map +1 -0
  117. package/dist/src/testers/GGSpyWith.d.ts +40 -0
  118. package/dist/src/testers/GGSpyWith.d.ts.map +1 -0
  119. package/dist/src/testers/GGSpyWith.js +90 -0
  120. package/dist/src/testers/GGSpyWith.js.map +1 -0
  121. package/dist/src/testers/GGTestAction.d.ts +126 -0
  122. package/dist/src/testers/GGTestAction.d.ts.map +1 -0
  123. package/dist/src/testers/GGTestAction.js +245 -0
  124. package/dist/src/testers/GGTestAction.js.map +1 -0
  125. package/dist/src/testers/GGTestComponent.d.ts +15 -0
  126. package/dist/src/testers/GGTestComponent.d.ts.map +1 -0
  127. package/dist/src/testers/GGTestComponent.js +2 -0
  128. package/dist/src/testers/GGTestComponent.js.map +1 -0
  129. package/dist/src/testers/GGTestSelector.d.ts +54 -0
  130. package/dist/src/testers/GGTestSelector.d.ts.map +1 -0
  131. package/dist/src/testers/GGTestSelector.js +179 -0
  132. package/dist/src/testers/GGTestSelector.js.map +1 -0
  133. package/dist/src/testers/IGGTestInterceptor.d.ts +8 -0
  134. package/dist/src/testers/IGGTestInterceptor.d.ts.map +1 -0
  135. package/dist/src/testers/IGGTestInterceptor.js +2 -0
  136. package/dist/src/testers/IGGTestInterceptor.js.map +1 -0
  137. package/dist/src/testers/IGGTestWith.d.ts +13 -0
  138. package/dist/src/testers/IGGTestWith.d.ts.map +1 -0
  139. package/dist/src/testers/IGGTestWith.js +2 -0
  140. package/dist/src/testers/IGGTestWith.js.map +1 -0
  141. package/dist/src/testers/RuntimeSelector.d.ts +117 -0
  142. package/dist/src/testers/RuntimeSelector.d.ts.map +1 -0
  143. package/dist/src/testers/RuntimeSelector.js +2 -0
  144. package/dist/src/testers/RuntimeSelector.js.map +1 -0
  145. package/dist/src/tsconfig.json +17 -0
  146. package/dist/src/utils/GGExpectations.d.ts +18 -0
  147. package/dist/src/utils/GGExpectations.d.ts.map +1 -0
  148. package/dist/src/utils/GGExpectations.js +59 -0
  149. package/dist/src/utils/GGExpectations.js.map +1 -0
  150. package/dist/src/utils/GGTestError.d.ts +13 -0
  151. package/dist/src/utils/GGTestError.d.ts.map +1 -0
  152. package/dist/src/utils/GGTestError.js +26 -0
  153. package/dist/src/utils/GGTestError.js.map +1 -0
  154. package/dist/src/utils/captureStack.d.ts +9 -0
  155. package/dist/src/utils/captureStack.d.ts.map +1 -0
  156. package/dist/src/utils/captureStack.js +51 -0
  157. package/dist/src/utils/captureStack.js.map +1 -0
  158. package/dist/tsconfig.publish.tsbuildinfo +1 -0
  159. package/package.json +66 -0
  160. package/src/GGBundleTest.ts +89 -0
  161. package/src/GGTest.ts +318 -0
  162. package/src/GGTestContext.ts +74 -0
  163. package/src/GGTestRunner.ts +308 -0
  164. package/src/GGTestRuntime.ts +265 -0
  165. package/src/GGTestRuntimeWorker.ts +159 -0
  166. package/src/GGTestSharedRef.ts +116 -0
  167. package/src/GGTestkitExtensionsDiscovery.ts +26 -0
  168. package/src/IGGLocalDiscoveryServer.ts +16 -0
  169. package/src/callOn/GGCallOnSelector.ts +61 -0
  170. package/src/callOn/GGContractClass.implement.ts +43 -0
  171. package/src/callOn/GGTestActionForLocatorOnCall.ts +134 -0
  172. package/src/callOn/TestableIPC.ts +81 -0
  173. package/src/callOn/callOn.ts +224 -0
  174. package/src/callOn/registerOnCallHandler.ts +123 -0
  175. package/src/index-node.ts +64 -0
  176. package/src/mockable/GGMockable.ts +22 -0
  177. package/src/mockable/GGMockableCall.ts +45 -0
  178. package/src/mockable/GGMockableIPC.ts +20 -0
  179. package/src/mockable/GGMockableInterceptor.ts +44 -0
  180. package/src/mockable/GGMockableInterceptorsServer.ts +69 -0
  181. package/src/mockable/mockable.ts +71 -0
  182. package/src/runner/InlineRunner.ts +47 -0
  183. package/src/runner/IsolatedRunner.ts +179 -0
  184. package/src/runner/RuntimeRunner.ts +15 -0
  185. package/src/runner/WorkerRunner.ts +179 -0
  186. package/src/runner/isolated-loader.mjs +91 -0
  187. package/src/runner/worker-loader.mjs +49 -0
  188. package/src/testers/GGCallInterceptor.ts +224 -0
  189. package/src/testers/GGMockWith.ts +92 -0
  190. package/src/testers/GGSpyWith.ts +115 -0
  191. package/src/testers/GGTestAction.ts +333 -0
  192. package/src/testers/GGTestComponent.ts +16 -0
  193. package/src/testers/GGTestSelector.ts +223 -0
  194. package/src/testers/IGGTestInterceptor.ts +11 -0
  195. package/src/testers/IGGTestWith.ts +15 -0
  196. package/src/testers/RuntimeSelector.ts +151 -0
  197. package/src/tsconfig.json +17 -0
  198. package/src/utils/GGExpectations.ts +78 -0
  199. package/src/utils/GGTestError.ts +37 -0
  200. package/src/utils/captureStack.ts +54 -0
@@ -0,0 +1,47 @@
1
+ import type {RuntimeRunner} from "./RuntimeRunner";
2
+ import {GGTestRuntimeWorker} from "../GGTestRuntimeWorker";
3
+ import {GGTestEnvConfig} from "../GGTestRuntime";
4
+ import {GGLocatorScope} from "@grest-ts/locator";
5
+
6
+ export class InlineRunner implements RuntimeRunner {
7
+
8
+ private controlClient?: GGTestRuntimeWorker;
9
+
10
+ constructor(
11
+ private readonly config: GGTestEnvConfig,
12
+ private readonly runtimeFactory?: () => any
13
+ ) {
14
+ }
15
+
16
+ async start(): Promise<void> {
17
+ // Use setTimeout + enterBlank() to create a fully isolated async context.
18
+ // This gives the inline runtime its own context tree where GGLog.init()
19
+ // creates an independent log context, similar to how Worker/Isolated modes
20
+ // naturally get separate contexts by running in different threads/processes.
21
+ const factory = this.runtimeFactory;
22
+ await new Promise<void>((resolve, reject) => {
23
+ setTimeout(async () => {
24
+ try {
25
+ // Create blank context - inline runtime should not inherit test context
26
+ new GGLocatorScope("GGInlineRunner").enter();
27
+ this.controlClient = new GGTestRuntimeWorker(this.config);
28
+ // Pass factory to avoid dynamic import() which causes duplicate
29
+ // module loading in Vite/vitest environments
30
+ await this.controlClient.start(factory);
31
+ resolve();
32
+ } catch (err) {
33
+ reject(err);
34
+ }
35
+ }, 0);
36
+ });
37
+ }
38
+
39
+ async stopRuntime(): Promise<void> {
40
+ await this.controlClient?.stopRuntime();
41
+ }
42
+
43
+ async shutdown(): Promise<void> {
44
+ await this.controlClient?.shutdown();
45
+ this.controlClient = undefined;
46
+ }
47
+ }
@@ -0,0 +1,179 @@
1
+ import type {RuntimeRunner} from "./RuntimeRunner";
2
+ import {type ChildProcess, spawn} from "child_process";
3
+ import {GGLog} from "@grest-ts/logger";
4
+ import {GGTestEnvConfig} from "../GGTestRuntime";
5
+
6
+ const PROCESS_READY = "IsolatedRunner:READY"
7
+ const GG_ISOLATED_CONFIG = "GG_ISOLATED_CONFIG";
8
+
9
+ export class IsolatedRunner implements RuntimeRunner {
10
+ private process?: ChildProcess;
11
+
12
+ private static isolatedLoaderPath: string | undefined;
13
+
14
+ /**
15
+ * Set the path to the isolated-loader.mjs file.
16
+ * Called by @grest-ts/testkit-vitest to inject the path.
17
+ */
18
+ public static setIsolatedLoaderPath(path: string): void {
19
+ this.isolatedLoaderPath = path;
20
+ }
21
+
22
+ constructor(private config: GGTestEnvConfig) {
23
+ }
24
+
25
+ async start(): Promise<void> {
26
+ if (!IsolatedRunner.isolatedLoaderPath) {
27
+ throw new Error(
28
+ "Isolated loader path not set!\n" +
29
+ "Make sure to import '@grest-ts/testkit-vitest' in your vitest setup."
30
+ );
31
+ }
32
+
33
+ GGLog.debug(this, 'Starting isolated process for: ' + this.config.executablePath);
34
+
35
+ this.process = spawn('npx', ['tsx', IsolatedRunner.isolatedLoaderPath!, this.config.executablePath], {
36
+ env: {
37
+ ...process.env,
38
+ [GG_ISOLATED_CONFIG]: JSON.stringify(this.config)
39
+ },
40
+ stdio: ['pipe', 'pipe', 'pipe'], // pipe all streams so we can forward them properly
41
+ shell: true // Required for Windows to find npx
42
+ });
43
+
44
+ // Forward stderr to console.error so vitest can capture and sequence it
45
+ this.process.stderr?.setEncoding('utf8');
46
+ this.process.stderr?.on('data', (data: string) => {
47
+ const lines = data.split('\n');
48
+ for (const line of lines) {
49
+ if (line) console.error(line);
50
+ }
51
+ });
52
+
53
+ // Wait for process to signal ready via stdout
54
+ await new Promise<void>((resolve, reject) => {
55
+ if (!this.process) {
56
+ reject(new Error('Process failed to start'));
57
+ return;
58
+ }
59
+
60
+ const timeout = setTimeout(() => {
61
+ this.process?.kill('SIGKILL');
62
+ reject(new Error(`Process did not send READY signal within 10 seconds`));
63
+ }, 10000);
64
+
65
+ // Watch stdout for READY signal and forward all output using console.log
66
+ // so vitest can capture and sequence it properly with test output
67
+ this.process.stdout?.setEncoding('utf8');
68
+ let ready = false;
69
+ const onData = (data: string) => {
70
+ const lines = data.split('\n');
71
+ for (const line of lines) {
72
+ if (line) console.log(line);
73
+ }
74
+ if (!ready && data.includes(PROCESS_READY)) {
75
+ clearTimeout(timeout);
76
+ GGLog.debug(this, 'Process ready');
77
+ ready = true;
78
+ resolve();
79
+ }
80
+ };
81
+ this.process.stdout?.on('data', onData);
82
+
83
+ this.process.once('error', (err) => {
84
+ clearTimeout(timeout);
85
+ reject(err);
86
+ });
87
+
88
+ this.process.once('exit', (code) => {
89
+ if (code !== 0 && code !== null) {
90
+ clearTimeout(timeout);
91
+ reject(new Error(`Process exited with code ${code} before sending READY signal`));
92
+ }
93
+ });
94
+ });
95
+ }
96
+
97
+ async stopRuntime(): Promise<void> {
98
+ if (!this.process) {
99
+ return;
100
+ }
101
+
102
+ GGLog.debug(this, 'Stopping runtime in process...');
103
+
104
+ const RUNTIME_STOPPED = 'IsolatedRunner:RUNTIME_STOPPED';
105
+
106
+ return new Promise<void>((resolve, reject) => {
107
+ if (!this.process) {
108
+ resolve();
109
+ return;
110
+ }
111
+
112
+ const timeout = setTimeout(() => {
113
+ GGLog.error(this, 'Timeout waiting for runtime to stop');
114
+ reject(new Error('Timeout waiting for runtime to stop'));
115
+ }, 5000);
116
+
117
+ // Listen for RUNTIME_STOPPED signal in stdout
118
+ const onData = (data: string) => {
119
+ if (data.includes(RUNTIME_STOPPED)) {
120
+ clearTimeout(timeout);
121
+ this.process?.stdout?.off('data', onData);
122
+ GGLog.debug(this, 'Runtime stopped in process');
123
+ resolve();
124
+ }
125
+ };
126
+ this.process.stdout?.on('data', onData);
127
+
128
+ // Send stop runtime command via stdin
129
+ try {
130
+ this.process.stdin?.write('STOP_RUNTIME\n');
131
+ GGLog.debug(this, 'Sent stop runtime command via stdin');
132
+ } catch (error) {
133
+ clearTimeout(timeout);
134
+ GGLog.error(this, 'Error sending stop runtime command', error);
135
+ reject(error);
136
+ }
137
+ });
138
+ }
139
+
140
+ async shutdown(): Promise<void> {
141
+ if (!this.process) {
142
+ return;
143
+ }
144
+
145
+ GGLog.debug(this, 'Shutting down process...');
146
+
147
+ return new Promise<void>((resolve) => {
148
+ if (!this.process) {
149
+ resolve();
150
+ return;
151
+ }
152
+
153
+ this.process.once('exit', () => {
154
+ clearTimeout(forceKillTimeout);
155
+ this.process = undefined;
156
+ GGLog.debug(this, 'Process shut down');
157
+ resolve();
158
+ });
159
+
160
+ // Send shutdown message via stdin (works cross-platform, unlike SIGTERM on Windows)
161
+ try {
162
+ this.process.stdin?.write('SHUTDOWN\n');
163
+ this.process.stdin?.end();
164
+ GGLog.debug(this, 'Sent shutdown command via stdin');
165
+ } catch (error) {
166
+ GGLog.error(this, 'Error sending shutdown command', error);
167
+ }
168
+
169
+ // Force kill after 2 seconds if still running
170
+ const forceKillTimeout = setTimeout(() => {
171
+ if (this.process && !this.process.killed) {
172
+ GGLog.debug(this, 'Process did not exit gracefully, force killing');
173
+ this.process.kill('SIGKILL');
174
+ this.process = undefined;
175
+ }
176
+ }, 2000);
177
+ });
178
+ }
179
+ }
@@ -0,0 +1,15 @@
1
+ export interface RuntimeRunner {
2
+ start(): Promise<void>;
3
+
4
+ /**
5
+ * Stop the GGRuntime (teardown services) but keep the worker/IPC alive.
6
+ * This allows log retrieval after the runtime has stopped.
7
+ */
8
+ stopRuntime(): Promise<void>;
9
+
10
+ /**
11
+ * Fully shutdown the worker, including IPC disconnection.
12
+ * After this, no commands can be sent.
13
+ */
14
+ shutdown(): Promise<void>;
15
+ }
@@ -0,0 +1,179 @@
1
+ import type {RuntimeRunner} from "./RuntimeRunner";
2
+ import {Worker} from "worker_threads";
3
+ import {GGLog} from "@grest-ts/logger";
4
+ import {GGTestEnvConfig} from "../GGTestRuntime";
5
+
6
+ export class WorkerRunner implements RuntimeRunner {
7
+ private worker?: Worker;
8
+
9
+ private static workerLoaderPath: string | undefined;
10
+
11
+ /**
12
+ * Set the path to the worker-loader.mjs file.
13
+ * Called by @grest-ts/testkit-vitest to inject the path.
14
+ */
15
+ public static setWorkerLoaderPath(path: string): void {
16
+ this.workerLoaderPath = path;
17
+ }
18
+
19
+ constructor(private readonly config: GGTestEnvConfig) {
20
+ }
21
+
22
+ async start(): Promise<void> {
23
+ GGLog.debug(this, 'Starting worker: ' + this.config.executablePath);
24
+
25
+ if (!WorkerRunner.workerLoaderPath) {
26
+ throw new Error(
27
+ "Worker loader path not set!\n" +
28
+ "Make sure to import '@grest-ts/testkit-vitest' in your vitest setup."
29
+ );
30
+ }
31
+ const workerLoaderPath = WorkerRunner.workerLoaderPath;
32
+
33
+ this.worker = new Worker(workerLoaderPath, {
34
+ workerData: this.config,
35
+ stdout: true,
36
+ stderr: true
37
+ });
38
+
39
+ // Forward worker stdout to parent's console using console.log
40
+ // so vitest can capture and sequence it properly with test output
41
+ this.worker.stdout.on('data', (data: Buffer) => {
42
+ const str = data.toString();
43
+ // Split by newlines and log each line (trimming trailing newline)
44
+ const lines = str.split('\n');
45
+ for (const line of lines) {
46
+ if (line) console.log(line);
47
+ }
48
+ });
49
+
50
+ // Forward worker stderr to parent's console
51
+ this.worker.stderr.on('data', (data: Buffer) => {
52
+ const str = data.toString();
53
+ const lines = str.split('\n');
54
+ for (const line of lines) {
55
+ if (line) console.error(line);
56
+ }
57
+ });
58
+
59
+ // Wait for worker to signal ready
60
+ try {
61
+ await new Promise<void>((resolve, reject) => {
62
+ if (!this.worker) {
63
+ reject(new Error('Worker failed to start'));
64
+ return;
65
+ }
66
+
67
+ const timeout = setTimeout(() => {
68
+ // CRITICAL: Terminate worker on timeout to prevent leak
69
+ this.worker?.terminate();
70
+ reject(new Error('Worker did not start within 10 seconds'));
71
+ }, 10000);
72
+
73
+ const messageHandler = (msg: any) => {
74
+ if (msg.type === 'ready') {
75
+ clearTimeout(timeout);
76
+ this.worker?.off('message', messageHandler);
77
+ // Monitor for unexpected worker exit after successful startup
78
+ this.worker?.on('exit', (code) => {
79
+ GGLog.error(this, `Worker exited unexpectedly with code ${code}`);
80
+ });
81
+ GGLog.debug(this, 'Worker ready');
82
+ resolve();
83
+ } else if (msg.type === 'error') {
84
+ clearTimeout(timeout);
85
+ this.worker?.off('message', messageHandler);
86
+ this.worker?.terminate();
87
+ reject(new Error(`Runtime worker startup failed! ${msg.error}`));
88
+ }
89
+ };
90
+
91
+ this.worker.on('message', messageHandler);
92
+
93
+ this.worker.once('error', (err) => {
94
+ clearTimeout(timeout);
95
+ this.worker?.terminate();
96
+ reject(err);
97
+ });
98
+
99
+ this.worker.once('exit', (code) => {
100
+ if (code !== 0) {
101
+ clearTimeout(timeout);
102
+ reject(new Error(`Worker exited with code ${code}`));
103
+ }
104
+ });
105
+ });
106
+ } catch (error) {
107
+ // Ensure worker is cleaned up on any error
108
+ this.worker = undefined;
109
+ throw error;
110
+ }
111
+ }
112
+
113
+ async stopRuntime(): Promise<void> {
114
+ if (!this.worker) {
115
+ return;
116
+ }
117
+
118
+ GGLog.debug(this, 'Stopping runtime in worker...');
119
+
120
+ return new Promise<void>((resolve, reject) => {
121
+ if (!this.worker) {
122
+ resolve();
123
+ return;
124
+ }
125
+
126
+ const timeout = setTimeout(() => {
127
+ GGLog.error(this, 'Timeout waiting for runtime to stop');
128
+ reject(new Error('Timeout waiting for runtime to stop'));
129
+ }, 5000);
130
+
131
+ const messageHandler = (msg: any) => {
132
+ if (msg.type === 'runtimeStopped') {
133
+ clearTimeout(timeout);
134
+ this.worker?.off('message', messageHandler);
135
+ GGLog.debug(this, 'Runtime stopped in worker');
136
+ resolve();
137
+ }
138
+ };
139
+
140
+ this.worker.on('message', messageHandler);
141
+ this.worker.postMessage({type: 'stopRuntime'});
142
+ });
143
+ }
144
+
145
+ async shutdown(): Promise<void> {
146
+ if (!this.worker) {
147
+ return;
148
+ }
149
+
150
+ GGLog.debug(this, 'Shutting down worker...');
151
+
152
+ return new Promise<void>((resolve) => {
153
+ if (!this.worker) {
154
+ resolve();
155
+ return;
156
+ }
157
+
158
+ this.worker.once('exit', () => {
159
+ clearTimeout(forceTerminateTimeout);
160
+ this.worker = undefined;
161
+ GGLog.debug(this, 'Worker shut down');
162
+ resolve();
163
+ });
164
+
165
+ // Send shutdown message for graceful shutdown
166
+ this.worker.postMessage({type: 'shutdown'});
167
+
168
+ // Force terminate after 2 seconds if graceful shutdown doesn't work
169
+ const forceTerminateTimeout = setTimeout(() => {
170
+ if (this.worker) {
171
+ GGLog.debug(this, 'Force terminating worker (timeout)');
172
+ this.worker.terminate();
173
+ this.worker = undefined;
174
+ resolve();
175
+ }
176
+ }, 2000);
177
+ });
178
+ }
179
+ }
@@ -0,0 +1,91 @@
1
+ /**
2
+ * Isolated process loader for ES modules
3
+ * This file is the entry point for isolated test processes
4
+ *
5
+ * Usage: npx tsx isolated-loader.mjs <runtime-source-url>
6
+ * Environment: GG_ISOLATED_CONFIG must be set with JSON config
7
+ */
8
+ import {register} from 'tsx/esm/api';
9
+ import {pathToFileURL} from 'url';
10
+
11
+ // Register tsx to handle TypeScript with ESM
12
+ register();
13
+
14
+ // Get the runtime source URL from command line args (can be file:// URL or path)
15
+ let runtimeSourceUrl = process.argv[2];
16
+ if (!runtimeSourceUrl) {
17
+ console.error('Usage: npx tsx isolated-loader.mjs <runtime-source-url>');
18
+ process.exit(1);
19
+ }
20
+
21
+ // Convert to file:// URL if it's a path
22
+ if (!runtimeSourceUrl.startsWith('file:')) {
23
+ runtimeSourceUrl = pathToFileURL(runtimeSourceUrl).href;
24
+ }
25
+
26
+ const GG_ISOLATED_CONFIG = "GG_ISOLATED_CONFIG";
27
+ const PROCESS_READY = "IsolatedRunner:READY";
28
+
29
+ // Get config from environment
30
+ const configJson = process.env[GG_ISOLATED_CONFIG];
31
+ if (!configJson) {
32
+ console.error('GG_ISOLATED_CONFIG not set');
33
+ process.exit(1);
34
+ }
35
+
36
+ // Import runtime and testkit dependencies
37
+ const {GGRuntime} = await import('@grest-ts/runtime');
38
+ const {GGTestRuntimeWorker} = await import('@grest-ts/testkit');
39
+ const {GGLog} = await import('@grest-ts/logger');
40
+
41
+ const config = JSON.parse(configJson);
42
+
43
+ // Override cli() to intercept runtime startup in isolated mode
44
+
45
+ GGRuntime.cli = async function(moduleUrl) {
46
+ // Still set SOURCE_MODULE_URL for testkit compatibility
47
+ this.SOURCE_MODULE_URL = moduleUrl;
48
+
49
+ // Start the runtime via test worker instead of normal startup
50
+ const controlClient = new GGTestRuntimeWorker(config);
51
+
52
+ try {
53
+ await controlClient.start(() => new this());
54
+
55
+ // Signal to parent process that we're ready
56
+ console.log(PROCESS_READY);
57
+
58
+ const stopRuntime = async () => {
59
+ // Stop the GGRuntime but keep process alive for log retrieval
60
+ await controlClient.stopRuntime();
61
+ console.log('IsolatedRunner:RUNTIME_STOPPED');
62
+ };
63
+
64
+ const shutdown = async () => {
65
+ // Fully shutdown process
66
+ await controlClient.shutdown();
67
+ process.exit(0);
68
+ };
69
+
70
+ // Listen for commands via stdin
71
+ process.stdin.setEncoding('utf8');
72
+ process.stdin.on('data', (data) => {
73
+ const message = data.toString().trim();
74
+ if (message === 'STOP_RUNTIME') {
75
+ GGLog.debug({name: 'IsolatedLoader'}, 'Received stop runtime command');
76
+ stopRuntime();
77
+ } else if (message === 'SHUTDOWN') {
78
+ GGLog.debug({name: 'IsolatedLoader'}, 'Received shutdown command');
79
+ shutdown();
80
+ }
81
+ });
82
+ process.on('SIGTERM', shutdown);
83
+ process.on('SIGINT', shutdown);
84
+ } catch (err) {
85
+ GGLog.error({name: 'IsolatedLoader'}, 'Failed to start isolated runtime', err);
86
+ process.exit(1);
87
+ }
88
+ };
89
+
90
+ // Import the runtime source - this will call the overridden cli()
91
+ await import(runtimeSourceUrl);
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Worker loader for ES modules
3
+ * This file is loaded by worker threads to execute test runtimes
4
+ *
5
+ * workerData is GGTestEnvConfig: { executablePath, testRouterPort, testId, runtimeId, initialCommands }
6
+ */
7
+ import {register} from 'tsx/esm/api';
8
+ import {parentPort, workerData} from 'worker_threads';
9
+
10
+ // Register tsx to handle TypeScript with ESM
11
+ register();
12
+
13
+ // Catch unhandled errors in worker thread
14
+ process.on('uncaughtException', (err) => {
15
+ console.error(`[WorkerThread ${workerData?.runtimeId}] Uncaught exception:`, err);
16
+ });
17
+ process.on('unhandledRejection', (reason) => {
18
+ console.error(`[WorkerThread ${workerData?.runtimeId}] Unhandled rejection:`, reason);
19
+ });
20
+
21
+ // workerData is GGTestEnvConfig directly
22
+ const config = workerData;
23
+
24
+ // Import control client from @grest-ts/testkit
25
+ const {GGTestRuntimeWorker} = await import('@grest-ts/testkit');
26
+
27
+ // Create control client
28
+ const controlClient = new GGTestRuntimeWorker(config);
29
+
30
+ // Start the runtime
31
+ try {
32
+ await controlClient.start();
33
+ parentPort.postMessage({type: 'ready'});
34
+ } catch (err) {
35
+ parentPort.postMessage({type: 'error', error: err.stack || err.message});
36
+ }
37
+
38
+ // Handle messages from parent
39
+ parentPort.on('message', async (msg) => {
40
+ if (msg.type === 'stopRuntime') {
41
+ // Stop the GGRuntime but keep worker alive for log retrieval
42
+ await controlClient.stopRuntime();
43
+ parentPort.postMessage({type: 'runtimeStopped'});
44
+ } else if (msg.type === 'shutdown') {
45
+ // Fully shutdown worker
46
+ await controlClient.shutdown();
47
+ process.exit(0);
48
+ }
49
+ });