@livestore/utils-dev 0.4.0-dev.5 → 0.4.0-dev.6

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 (52) hide show
  1. package/dist/.tsbuildinfo.json +1 -1
  2. package/dist/node/DockerComposeService/DockerComposeService.d.ts +48 -0
  3. package/dist/node/DockerComposeService/DockerComposeService.d.ts.map +1 -0
  4. package/dist/node/DockerComposeService/DockerComposeService.js +107 -0
  5. package/dist/node/DockerComposeService/DockerComposeService.js.map +1 -0
  6. package/dist/node/DockerComposeService/DockerComposeService.test.d.ts +2 -0
  7. package/dist/node/DockerComposeService/DockerComposeService.test.d.ts.map +1 -0
  8. package/dist/node/DockerComposeService/DockerComposeService.test.js +64 -0
  9. package/dist/node/DockerComposeService/DockerComposeService.test.js.map +1 -0
  10. package/dist/node/WranglerDevServer/WranglerDevServer.d.ts +52 -0
  11. package/dist/node/WranglerDevServer/WranglerDevServer.d.ts.map +1 -0
  12. package/dist/node/WranglerDevServer/WranglerDevServer.js +122 -0
  13. package/dist/node/WranglerDevServer/WranglerDevServer.js.map +1 -0
  14. package/dist/node/WranglerDevServer/WranglerDevServer.test.d.ts +2 -0
  15. package/dist/node/WranglerDevServer/WranglerDevServer.test.d.ts.map +1 -0
  16. package/dist/node/WranglerDevServer/WranglerDevServer.test.js +179 -0
  17. package/dist/node/WranglerDevServer/WranglerDevServer.test.js.map +1 -0
  18. package/dist/node/WranglerDevServer/fixtures/cf-worker.d.ts +8 -0
  19. package/dist/node/WranglerDevServer/fixtures/cf-worker.d.ts.map +1 -0
  20. package/dist/node/WranglerDevServer/fixtures/cf-worker.js +11 -0
  21. package/dist/node/WranglerDevServer/fixtures/cf-worker.js.map +1 -0
  22. package/dist/node/WranglerDevServer/process-tree-manager.d.ts +55 -0
  23. package/dist/node/WranglerDevServer/process-tree-manager.d.ts.map +1 -0
  24. package/dist/node/WranglerDevServer/process-tree-manager.js +178 -0
  25. package/dist/node/WranglerDevServer/process-tree-manager.js.map +1 -0
  26. package/dist/node/mod.d.ts +3 -2
  27. package/dist/node/mod.d.ts.map +1 -1
  28. package/dist/node/mod.js +3 -2
  29. package/dist/node/mod.js.map +1 -1
  30. package/dist/node/vitest-docker-compose-setup.d.ts +1 -1
  31. package/dist/node-vitest/Vitest.d.ts +37 -3
  32. package/dist/node-vitest/Vitest.d.ts.map +1 -1
  33. package/dist/node-vitest/Vitest.js +75 -1
  34. package/dist/node-vitest/Vitest.js.map +1 -1
  35. package/dist/node-vitest/Vitest.test.d.ts +2 -0
  36. package/dist/node-vitest/Vitest.test.d.ts.map +1 -0
  37. package/dist/node-vitest/Vitest.test.js +59 -0
  38. package/dist/node-vitest/Vitest.test.js.map +1 -0
  39. package/package.json +5 -7
  40. package/src/node/DockerComposeService/DockerComposeService.test.ts +91 -0
  41. package/src/node/DockerComposeService/DockerComposeService.ts +252 -0
  42. package/src/node/DockerComposeService/test-fixtures/docker-compose.yml +4 -0
  43. package/src/node/WranglerDevServer/WranglerDevServer.test.ts +266 -0
  44. package/src/node/WranglerDevServer/WranglerDevServer.ts +266 -0
  45. package/src/node/WranglerDevServer/fixtures/cf-worker.ts +11 -0
  46. package/src/node/WranglerDevServer/fixtures/wrangler.toml +11 -0
  47. package/src/node/WranglerDevServer/process-tree-manager.ts +263 -0
  48. package/src/node/mod.ts +16 -2
  49. package/src/node-vitest/Vitest.test.ts +101 -0
  50. package/src/node-vitest/Vitest.ts +167 -5
  51. package/src/node/vitest-docker-compose-setup.ts +0 -182
  52. package/src/node/vitest-wrangler-setup.ts +0 -132
package/package.json CHANGED
@@ -1,9 +1,10 @@
1
1
  {
2
2
  "name": "@livestore/utils-dev",
3
- "version": "0.4.0-dev.5",
3
+ "version": "0.4.0-dev.6",
4
4
  "type": "module",
5
5
  "sideEffects": [
6
- "./src/node-vitest/global.ts"
6
+ "./src/node-vitest/global.ts",
7
+ "./dist/node-vitest/global.js"
7
8
  ],
8
9
  "exports": {
9
10
  "./node": "./dist/node/mod.js",
@@ -18,7 +19,7 @@
18
19
  "@opentelemetry/sdk-metrics": "2.0.1",
19
20
  "@opentelemetry/sdk-trace-base": "2.0.1",
20
21
  "@opentelemetry/sdk-trace-node": "2.0.1",
21
- "@livestore/utils": "0.4.0-dev.5"
22
+ "@livestore/utils": "0.4.0-dev.6"
22
23
  },
23
24
  "devDependencies": {},
24
25
  "files": [
@@ -29,10 +30,7 @@
29
30
  "license": "Apache-2.0",
30
31
  "peerDependencies": {},
31
32
  "publishConfig": {
32
- "access": "public",
33
- "sideEffects": [
34
- "./dist/node-vitest/global.js"
35
- ]
33
+ "access": "public"
36
34
  },
37
35
  "scripts": {
38
36
  "test": "echo 'No tests for utils-dev'"
@@ -0,0 +1,91 @@
1
+ import path from 'node:path'
2
+ import { Duration, Effect, Layer, Stream } from '@livestore/utils/effect'
3
+ import { PlatformNode } from '@livestore/utils/node'
4
+ import { Vitest } from '@livestore/utils-dev/node-vitest'
5
+ import { expect } from 'vitest'
6
+ import { type DockerComposeArgs, DockerComposeService } from './DockerComposeService.ts'
7
+
8
+ const testTimeout = 30_000
9
+ const testFixturePath = path.join(import.meta.dirname, 'test-fixtures')
10
+
11
+ const DockerComposeTest = (args: Partial<DockerComposeArgs> = {}) =>
12
+ DockerComposeService.Default({
13
+ cwd: testFixturePath,
14
+ ...args,
15
+ })
16
+
17
+ Vitest.describe('DockerComposeService', { timeout: testTimeout }, () => {
18
+ Vitest.describe('Basic Operations', () => {
19
+ const withBasicTest = (args: Partial<DockerComposeArgs> = {}) =>
20
+ Vitest.makeWithTestCtx({
21
+ timeout: testTimeout,
22
+ makeLayer: () => DockerComposeTest(args).pipe(Layer.provide(PlatformNode.NodeContext.layer)),
23
+ })
24
+
25
+ Vitest.scopedLive('can pull docker images', (test) =>
26
+ Effect.gen(function* () {
27
+ const dockerCompose = yield* DockerComposeService
28
+
29
+ // Test that pull operation works (should succeed for hello-world image)
30
+ yield* dockerCompose.pull
31
+ }).pipe(withBasicTest()(test)),
32
+ )
33
+
34
+ Vitest.scopedLive('can start and stop docker compose services', (test) =>
35
+ Effect.gen(function* () {
36
+ const dockerCompose = yield* DockerComposeService
37
+
38
+ // Start the service
39
+ yield* dockerCompose.start({ detached: true })
40
+
41
+ // Stop the service
42
+ yield* dockerCompose.stop
43
+ }).pipe(withBasicTest({ serviceName: 'hello-world' })(test)),
44
+ )
45
+
46
+ Vitest.scopedLive('can get logs from docker compose services', (test) =>
47
+ Effect.gen(function* () {
48
+ const dockerCompose = yield* DockerComposeService
49
+
50
+ // Start the service first
51
+ yield* dockerCompose.start({ detached: true })
52
+
53
+ // Get logs (should contain at least the "Hello from Docker!" message)
54
+ const firstLogLine = yield* dockerCompose.logs().pipe(Stream.runHead)
55
+
56
+ expect(firstLogLine._tag).toBe('Some')
57
+
58
+ // Stop the service
59
+ yield* dockerCompose.stop
60
+ }).pipe(withBasicTest({ serviceName: 'hello-world' })(test)),
61
+ )
62
+ })
63
+
64
+ Vitest.describe('Health Check Operations', () => {
65
+ const withHealthCheckTest = (args: Partial<DockerComposeArgs> = {}) =>
66
+ Vitest.makeWithTestCtx({
67
+ timeout: testTimeout,
68
+ makeLayer: () => DockerComposeTest(args).pipe(Layer.provide(PlatformNode.NodeContext.layer)),
69
+ })
70
+
71
+ Vitest.scopedLive('handles health check timeout gracefully', (test) =>
72
+ Effect.gen(function* () {
73
+ const dockerCompose = yield* DockerComposeService
74
+
75
+ // Test starting with a health check that will timeout (invalid URL)
76
+ const result = yield* dockerCompose
77
+ .start({
78
+ detached: true,
79
+ healthCheck: {
80
+ url: 'http://localhost:99999/nonexistent',
81
+ timeout: Duration.seconds(2),
82
+ },
83
+ })
84
+ .pipe(Effect.either)
85
+
86
+ // Should fail due to health check timeout
87
+ expect(result._tag).toBe('Left')
88
+ }).pipe(withHealthCheckTest({ serviceName: 'hello-world' })(test)),
89
+ )
90
+ })
91
+ })
@@ -0,0 +1,252 @@
1
+ import { omitUndefineds } from '@livestore/utils'
2
+ import {
3
+ Command,
4
+ type CommandExecutor,
5
+ Duration,
6
+ Effect,
7
+ type PlatformError,
8
+ Schedule,
9
+ Schema,
10
+ type Scope,
11
+ Stream,
12
+ } from '@livestore/utils/effect'
13
+
14
+ export class DockerComposeError extends Schema.TaggedError<DockerComposeError>()('DockerComposeError', {
15
+ cause: Schema.Defect,
16
+ message: Schema.String,
17
+ }) {}
18
+
19
+ export interface DockerComposeArgs {
20
+ readonly cwd: string
21
+ readonly serviceName?: string
22
+ }
23
+
24
+ export interface StartOptions {
25
+ readonly detached?: boolean
26
+ readonly env?: Record<string, string>
27
+ readonly healthCheck?: {
28
+ readonly url: string
29
+ readonly timeout?: Duration.Duration
30
+ readonly interval?: Duration.Duration
31
+ }
32
+ }
33
+
34
+ export interface LogsOptions {
35
+ readonly follow?: boolean
36
+ readonly tail?: number
37
+ readonly since?: string
38
+ }
39
+
40
+ export interface DockerComposeOperations {
41
+ readonly pull: Effect.Effect<void, DockerComposeError | PlatformError.PlatformError>
42
+ readonly start: (
43
+ options?: StartOptions,
44
+ ) => Effect.Effect<void, DockerComposeError | PlatformError.PlatformError, Scope.Scope>
45
+ readonly stop: Effect.Effect<void, DockerComposeError | PlatformError.PlatformError>
46
+ readonly logs: (
47
+ options?: LogsOptions,
48
+ ) => Stream.Stream<string, DockerComposeError | PlatformError.PlatformError, Scope.Scope>
49
+ }
50
+
51
+ export class DockerComposeService extends Effect.Service<DockerComposeService>()('DockerComposeService', {
52
+ scoped: (args: DockerComposeArgs) =>
53
+ Effect.gen(function* () {
54
+ const { cwd, serviceName } = args
55
+
56
+ const commandExecutorContext = yield* Effect.context<CommandExecutor.CommandExecutor>()
57
+
58
+ const pull = Effect.gen(function* () {
59
+ yield* Effect.log(`Pulling Docker Compose images in ${cwd}`)
60
+
61
+ yield* Command.make('docker', 'compose', 'pull').pipe(
62
+ Command.workingDirectory(cwd),
63
+ Command.exitCode,
64
+ Effect.flatMap((exitCode: number) =>
65
+ exitCode === 0
66
+ ? Effect.void
67
+ : Effect.fail(
68
+ new DockerComposeError({
69
+ cause: new Error(`Docker compose pull failed with exit code ${exitCode}`),
70
+ message: `Docker compose pull failed with exit code ${exitCode}`,
71
+ }),
72
+ ),
73
+ ),
74
+ Effect.provide(commandExecutorContext),
75
+ )
76
+
77
+ yield* Effect.log(`Successfully pulled Docker Compose images`)
78
+ }).pipe(Effect.withSpan('pullDockerComposeImages'))
79
+
80
+ const start = (options: StartOptions = {}) =>
81
+ Effect.gen(function* () {
82
+ const { detached = true, healthCheck } = options
83
+
84
+ // Build start command
85
+ const baseArgs = ['docker', 'compose', 'up']
86
+ if (detached) baseArgs.push('-d')
87
+ if (serviceName) baseArgs.push(serviceName)
88
+
89
+ const command = yield* Command.make(baseArgs[0]!, ...baseArgs.slice(1)).pipe(
90
+ Command.workingDirectory(cwd),
91
+ Command.env(options.env ?? {}),
92
+ Command.start,
93
+ Effect.catchAll((cause) =>
94
+ Effect.fail(
95
+ new DockerComposeError({
96
+ cause,
97
+ message: `Failed to start Docker Compose services in ${cwd}`,
98
+ }),
99
+ ),
100
+ ),
101
+ Effect.provide(commandExecutorContext),
102
+ )
103
+
104
+ // Wait for command completion
105
+ yield* command.exitCode.pipe(
106
+ Effect.flatMap((exitCode: number) =>
107
+ exitCode === 0
108
+ ? Effect.void
109
+ : Effect.fail(
110
+ new DockerComposeError({
111
+ cause: new Error(`Docker compose exited with code ${exitCode}`),
112
+ message: `Docker Compose failed to start with exit code ${exitCode}`,
113
+ }),
114
+ ),
115
+ ),
116
+ Effect.provide(commandExecutorContext),
117
+ )
118
+
119
+ // Perform health check if requested
120
+ if (healthCheck) {
121
+ yield* performHealthCheck(healthCheck).pipe(Effect.provide(commandExecutorContext))
122
+ }
123
+
124
+ yield* Effect.log(`Docker Compose services started successfully in ${cwd}`)
125
+ }).pipe(Effect.withSpan('startDockerCompose'))
126
+
127
+ const stop = Effect.gen(function* () {
128
+ yield* Effect.log(`Stopping Docker Compose services in ${cwd}`)
129
+
130
+ const stopCommand = serviceName
131
+ ? Command.make('docker', 'compose', 'stop', serviceName)
132
+ : Command.make('docker', 'compose', 'stop')
133
+
134
+ yield* stopCommand.pipe(
135
+ Command.workingDirectory(cwd),
136
+ Command.exitCode,
137
+ Effect.flatMap((exitCode: number) =>
138
+ exitCode === 0
139
+ ? Effect.void
140
+ : Effect.fail(
141
+ new DockerComposeError({
142
+ cause: new Error(`Docker compose stop exited with code ${exitCode}`),
143
+ message: `Failed to stop Docker Compose services`,
144
+ }),
145
+ ),
146
+ ),
147
+ Effect.provide(commandExecutorContext),
148
+ )
149
+
150
+ yield* Effect.log(`Docker Compose services stopped successfully`)
151
+ }).pipe(Effect.withSpan('stopDockerCompose'))
152
+
153
+ const logs = (options: LogsOptions = {}) =>
154
+ Effect.gen(function* () {
155
+ const { follow = false, tail, since } = options
156
+
157
+ const baseArgs = ['docker', 'compose', 'logs']
158
+ if (follow) baseArgs.push('-f')
159
+ if (tail) baseArgs.push('--tail', tail.toString())
160
+ if (since) baseArgs.push('--since', since)
161
+ if (serviceName) baseArgs.push(serviceName)
162
+
163
+ const command = yield* Command.make(baseArgs[0]!, ...baseArgs.slice(1)).pipe(
164
+ Command.workingDirectory(cwd),
165
+ Command.start,
166
+ Effect.catchAll((cause) =>
167
+ Effect.fail(
168
+ new DockerComposeError({
169
+ cause,
170
+ message: `Failed to read Docker Compose logs in ${cwd}`,
171
+ }),
172
+ ),
173
+ ),
174
+ Effect.provide(commandExecutorContext),
175
+ )
176
+
177
+ return command.stdout.pipe(
178
+ Stream.decodeText('utf8'),
179
+ Stream.splitLines,
180
+ Stream.mapError(
181
+ (cause) =>
182
+ new DockerComposeError({
183
+ cause,
184
+ message: `Error reading Docker Compose logs in ${cwd}`,
185
+ }),
186
+ ),
187
+ )
188
+ }).pipe(Stream.unwrapScoped)
189
+
190
+ return { pull, start, stop, logs }
191
+ }),
192
+ }) {}
193
+
194
+ const performHealthCheck = ({
195
+ url,
196
+ timeout = Duration.minutes(2),
197
+ interval = Duration.seconds(2),
198
+ }: {
199
+ url: string
200
+ timeout?: Duration.Duration
201
+ interval?: Duration.Duration
202
+ }): Effect.Effect<void, DockerComposeError, CommandExecutor.CommandExecutor | Scope.Scope> =>
203
+ Effect.gen(function* () {
204
+ yield* Effect.log(`Performing health check on ${url}`)
205
+
206
+ const checkHealth = Command.make('curl', '-f', '-s', url).pipe(
207
+ Command.exitCode,
208
+ Effect.map((code: number) => code === 0),
209
+ Effect.catchAll(() => Effect.succeed(false)),
210
+ )
211
+
212
+ const healthCheck = checkHealth.pipe(
213
+ Effect.repeat({
214
+ while: (healthy: boolean) => !healthy,
215
+ schedule: Schedule.fixed(interval),
216
+ }),
217
+ Effect.timeout(timeout),
218
+ Effect.catchAll(() =>
219
+ Effect.fail(
220
+ new DockerComposeError({
221
+ cause: new Error('Health check timeout'),
222
+ message: `Health check failed for ${url} after ${Duration.toMillis(timeout)}ms`,
223
+ }),
224
+ ),
225
+ ),
226
+ )
227
+
228
+ yield* healthCheck
229
+ yield* Effect.log(`Health check passed for ${url}`)
230
+ })
231
+
232
+ // Convenience function for scoped Docker Compose operations with automatic cleanup
233
+ export const startDockerComposeServicesScoped = (
234
+ args: DockerComposeArgs & {
235
+ healthCheck?: StartOptions['healthCheck']
236
+ },
237
+ ): Effect.Effect<
238
+ void,
239
+ DockerComposeError | PlatformError.PlatformError,
240
+ DockerComposeService | CommandExecutor.CommandExecutor | Scope.Scope
241
+ > =>
242
+ Effect.gen(function* () {
243
+ const dockerCompose = yield* DockerComposeService
244
+
245
+ // Start the services
246
+ yield* dockerCompose.start({
247
+ ...omitUndefineds({ healthCheck: args.healthCheck ? args.healthCheck : undefined }),
248
+ })
249
+
250
+ // Add cleanup finalizer to the current scope
251
+ yield* Effect.addFinalizer(() => dockerCompose.stop.pipe(Effect.orDie))
252
+ })
@@ -0,0 +1,4 @@
1
+ services:
2
+ hello-world:
3
+ image: hello-world
4
+ profiles: [manual] # Don't auto-start this service
@@ -0,0 +1,266 @@
1
+ import { Effect, Exit, FetchHttpClient, Fiber, Layer, Scope } from '@livestore/utils/effect'
2
+ import { PlatformNode } from '@livestore/utils/node'
3
+ import { Vitest } from '@livestore/utils-dev/node-vitest'
4
+ import { expect } from 'vitest'
5
+ import {
6
+ type StartWranglerDevServerArgs,
7
+ WranglerDevServerError,
8
+ WranglerDevServerService,
9
+ } from './WranglerDevServer.ts'
10
+
11
+ const testTimeout = 60_000
12
+
13
+ const withTestCtx = Vitest.makeWithTestCtx({
14
+ timeout: testTimeout,
15
+ makeLayer: () => PlatformNode.NodeContext.layer,
16
+ })
17
+
18
+ const WranglerDevServerTest = (args: Partial<StartWranglerDevServerArgs> = {}) =>
19
+ WranglerDevServerService.Default({
20
+ cwd: `${import.meta.dirname}/fixtures`,
21
+ ...args,
22
+ }).pipe(Layer.provide(FetchHttpClient.layer))
23
+
24
+ Vitest.describe('WranglerDevServer', { timeout: testTimeout }, () => {
25
+ Vitest.describe('Basic Operations', () => {
26
+ const withBasicTest = (args: Partial<StartWranglerDevServerArgs> = {}) =>
27
+ Vitest.makeWithTestCtx({
28
+ timeout: testTimeout,
29
+ makeLayer: () => WranglerDevServerTest(args).pipe(Layer.provide(PlatformNode.NodeContext.layer)),
30
+ })
31
+
32
+ Vitest.scopedLive('should start wrangler dev server and return port', (test) =>
33
+ Effect.gen(function* () {
34
+ const server = yield* WranglerDevServerService
35
+
36
+ expect(server.port).toBeGreaterThan(0)
37
+ expect(server.url).toMatch(/http:\/\/localhost:\d+/)
38
+ expect(typeof server.processId).toBe('number')
39
+ expect(server.processId).toBeGreaterThan(0)
40
+ }).pipe(withBasicTest()(test)),
41
+ )
42
+
43
+ Vitest.scopedLive('should use specified port when provided', (test) =>
44
+ Effect.gen(function* () {
45
+ const server = yield* WranglerDevServerService
46
+
47
+ expect(server.port).toBe(54443)
48
+ expect(server.url).toBe(`http://localhost:54443`)
49
+ }).pipe(withBasicTest({ port: 54443 })(test)),
50
+ )
51
+ })
52
+
53
+ Vitest.describe('Resource Management', () => {
54
+ Vitest.scopedLive('should cleanup processes on scope close', (test) =>
55
+ Effect.gen(function* () {
56
+ let processId: number | undefined
57
+
58
+ // Create a separate scope for the server
59
+ const serverScope = yield* Scope.make()
60
+
61
+ const server = yield* Effect.provide(
62
+ WranglerDevServerService,
63
+ WranglerDevServerTest().pipe(Layer.provide(PlatformNode.NodeContext.layer)),
64
+ ).pipe(Scope.extend(serverScope))
65
+
66
+ processId = server.processId
67
+ expect(processId).toBeGreaterThan(0)
68
+ expect(server.port).toBeGreaterThan(0)
69
+ expect(server.url).toMatch(/http:\/\/localhost:\d+/)
70
+
71
+ // Close scope to trigger cleanup
72
+ yield* Scope.close(serverScope, Exit.succeed(void 0))
73
+
74
+ // Wait for cleanup to complete
75
+ yield* Effect.sleep('2 seconds')
76
+
77
+ // Verify process is terminated
78
+ const isRunning2 = yield* Effect.promise(() => {
79
+ try {
80
+ process.kill(processId!, 0)
81
+ return Promise.resolve(true)
82
+ } catch {
83
+ return Promise.resolve(false)
84
+ }
85
+ })
86
+ expect(isRunning2).toBe(false)
87
+ }).pipe(withTestCtx(test)),
88
+ )
89
+
90
+ Vitest.scopedLive('should handle interruption with fast cleanup', (test) =>
91
+ Effect.gen(function* () {
92
+ let processId: number | undefined
93
+
94
+ const fiber = yield* Effect.fork(
95
+ Effect.provide(
96
+ Effect.gen(function* () {
97
+ const server = yield* WranglerDevServerService
98
+ processId = server.processId
99
+ yield* Effect.sleep('30 seconds') // Keep running
100
+ return server
101
+ }),
102
+ WranglerDevServerTest().pipe(Layer.provide(PlatformNode.NodeContext.layer)),
103
+ ),
104
+ )
105
+
106
+ // Wait for server to start
107
+ yield* Effect.sleep('3 seconds')
108
+
109
+ expect(processId).toBeGreaterThan(0)
110
+
111
+ // Interrupt and measure cleanup time
112
+ const start = Date.now()
113
+ yield* Fiber.interrupt(fiber)
114
+ const elapsed = Date.now() - start
115
+
116
+ // Should use fast cleanup (500ms timeout) + some overhead
117
+ expect(elapsed).toBeLessThan(1500) // Allow some overhead
118
+
119
+ // Wait for cleanup to complete
120
+ yield* Effect.sleep('1 second')
121
+
122
+ // Verify process is terminated
123
+ const isRunningAfter = yield* Effect.promise(() => {
124
+ try {
125
+ process.kill(processId!, 0)
126
+ return Promise.resolve(true)
127
+ } catch {
128
+ return Promise.resolve(false)
129
+ }
130
+ })
131
+ expect(isRunningAfter).toBe(false)
132
+ }).pipe(withTestCtx(test)),
133
+ )
134
+ })
135
+
136
+ Vitest.describe('Error Handling', () => {
137
+ const withErrorTest = (args: Partial<StartWranglerDevServerArgs> = {}) =>
138
+ Vitest.makeWithTestCtx({
139
+ timeout: testTimeout,
140
+ makeLayer: () => WranglerDevServerTest(args).pipe(Layer.provide(PlatformNode.NodeContext.layer)),
141
+ })
142
+
143
+ Vitest.scopedLive('should handle missing wrangler.toml but should timeout', (test) =>
144
+ Effect.gen(function* () {
145
+ const error = yield* WranglerDevServerService.pipe(
146
+ Effect.provide(
147
+ WranglerDevServerTest({
148
+ cwd: '/tmp',
149
+ wranglerConfigPath: '/dev/null',
150
+ connectTimeout: '500 millis',
151
+ }).pipe(Layer.provide(PlatformNode.NodeContext.layer)),
152
+ ),
153
+ Effect.flip,
154
+ )
155
+
156
+ expect(error).toBeInstanceOf(WranglerDevServerError)
157
+ }).pipe(Vitest.withTestCtx(test)),
158
+ )
159
+
160
+ Vitest.scopedLive('should handle invalid working directory', (test) =>
161
+ Effect.gen(function* () {
162
+ const result = yield* WranglerDevServerService.pipe(
163
+ Effect.provide(
164
+ WranglerDevServerTest({
165
+ cwd: '/completely/nonexistent/directory',
166
+ }).pipe(Layer.provide(PlatformNode.NodeContext.layer)),
167
+ ),
168
+ Effect.either,
169
+ )
170
+
171
+ expect(result._tag).toBe('Left')
172
+ if (result._tag === 'Left') {
173
+ expect(result.left).toBeInstanceOf(WranglerDevServerError)
174
+ }
175
+ }).pipe(Vitest.withTestCtx(test)),
176
+ )
177
+
178
+ Vitest.scopedLive('should timeout if server fails to start', (test) =>
179
+ Effect.gen(function* () {
180
+ // Create a command that will never output "Ready on"
181
+ const result = yield* WranglerDevServerService.pipe(
182
+ // Override the timeout for this test to be shorter
183
+ Effect.timeout('5 seconds'),
184
+ Effect.either,
185
+ )
186
+
187
+ // This might succeed or fail depending on actual wrangler behavior
188
+ // The main point is testing timeout functionality
189
+ expect(['Left', 'Right']).toContain(result._tag)
190
+ }).pipe(withErrorTest()(test)),
191
+ )
192
+ })
193
+
194
+ Vitest.describe('Process Tree Cleanup', () => {
195
+ const withCleanupTest = (args: Partial<StartWranglerDevServerArgs> = {}) =>
196
+ Vitest.makeWithTestCtx({
197
+ timeout: testTimeout,
198
+ makeLayer: () => WranglerDevServerTest(args).pipe(Layer.provide(PlatformNode.NodeContext.layer)),
199
+ })
200
+
201
+ Vitest.scopedLive('should clean up child workerd processes', (test) =>
202
+ Effect.gen(function* () {
203
+ let processId: number | undefined
204
+
205
+ const server = yield* WranglerDevServerService
206
+ processId = server.processId
207
+
208
+ // Wait for wrangler to spawn workerd children
209
+ yield* Effect.sleep('3 seconds')
210
+
211
+ // Find any child processes (workerd)
212
+ const children = yield* Effect.promise(async () => {
213
+ const { exec } = require('node:child_process')
214
+ const { promisify } = require('node:util')
215
+ const execAsync = promisify(exec)
216
+
217
+ try {
218
+ if (!processId) throw new Error('processId is undefined')
219
+ const { stdout } = await execAsync(`ps -o pid,ppid -ax | grep -E "^\\s*[0-9]+\\s+${processId}\\s*$"`)
220
+ return stdout
221
+ .trim()
222
+ .split('\n')
223
+ .map((line: string) => {
224
+ const match = line.trim().match(/^\s*(\d+)\s+\d+\s*$/)
225
+ return match?.[1] ? Number.parseInt(match[1], 10) : null
226
+ })
227
+ .filter((pid: number | null): pid is number => pid !== null)
228
+ } catch {
229
+ return []
230
+ }
231
+ })
232
+
233
+ console.log(`Found ${children.length} child processes:`, children)
234
+
235
+ // The scope will close here and should clean up all processes
236
+ }).pipe(withCleanupTest()(test)),
237
+ )
238
+ })
239
+
240
+ Vitest.describe('Service Pattern', () => {
241
+ const withServiceTest = (args: Partial<StartWranglerDevServerArgs> = {}) =>
242
+ Vitest.makeWithTestCtx({
243
+ timeout: testTimeout,
244
+ makeLayer: () => WranglerDevServerTest(args).pipe(Layer.provide(PlatformNode.NodeContext.layer)),
245
+ })
246
+
247
+ Vitest.scopedLive('should work with service pattern', (test) =>
248
+ Effect.gen(function* () {
249
+ const server = yield* WranglerDevServerService
250
+
251
+ expect(server.port).toBeGreaterThan(0)
252
+ expect(server.url).toMatch(/http:\/\/localhost:\d+/)
253
+ expect(server.processId).toBeGreaterThan(0)
254
+ }).pipe(withServiceTest()(test)),
255
+ )
256
+
257
+ Vitest.scopedLive('should work with custom port via service', (test) =>
258
+ Effect.gen(function* () {
259
+ const server = yield* WranglerDevServerService
260
+
261
+ expect(server.port).toBe(54444)
262
+ expect(server.url).toBe('http://localhost:54444')
263
+ }).pipe(withServiceTest({ port: 54444 })(test)),
264
+ )
265
+ })
266
+ })