@livestore/utils-dev 0.0.0-snapshot-1c345a0e6695466bdc7c4483444e7b3513620261 → 0.0.0-snapshot-92c31f56117b4fd377b66f55163ed565795c5e4c

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 (72) 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/FileLogger.d.ts +14 -0
  11. package/dist/node/FileLogger.d.ts.map +1 -0
  12. package/dist/node/FileLogger.js +151 -0
  13. package/dist/node/FileLogger.js.map +1 -0
  14. package/dist/node/WranglerDevServer/WranglerDevServer.d.ts +51 -0
  15. package/dist/node/WranglerDevServer/WranglerDevServer.d.ts.map +1 -0
  16. package/dist/node/WranglerDevServer/WranglerDevServer.js +102 -0
  17. package/dist/node/WranglerDevServer/WranglerDevServer.js.map +1 -0
  18. package/dist/node/WranglerDevServer/WranglerDevServer.test.d.ts +2 -0
  19. package/dist/node/WranglerDevServer/WranglerDevServer.test.d.ts.map +1 -0
  20. package/dist/node/WranglerDevServer/WranglerDevServer.test.js +186 -0
  21. package/dist/node/WranglerDevServer/WranglerDevServer.test.js.map +1 -0
  22. package/dist/node/WranglerDevServer/fixtures/cf-worker.d.ts +8 -0
  23. package/dist/node/WranglerDevServer/fixtures/cf-worker.d.ts.map +1 -0
  24. package/dist/node/WranglerDevServer/fixtures/cf-worker.js +11 -0
  25. package/dist/node/WranglerDevServer/fixtures/cf-worker.js.map +1 -0
  26. package/dist/node/WranglerDevServer/process-tree-manager.d.ts +55 -0
  27. package/dist/node/WranglerDevServer/process-tree-manager.d.ts.map +1 -0
  28. package/dist/node/WranglerDevServer/process-tree-manager.js +178 -0
  29. package/dist/node/WranglerDevServer/process-tree-manager.js.map +1 -0
  30. package/dist/node/cmd.d.ts +27 -0
  31. package/dist/node/cmd.d.ts.map +1 -0
  32. package/dist/node/cmd.js +55 -0
  33. package/dist/node/cmd.js.map +1 -0
  34. package/dist/node/mod.d.ts +7 -13
  35. package/dist/node/mod.d.ts.map +1 -1
  36. package/dist/node/mod.js +22 -37
  37. package/dist/node/mod.js.map +1 -1
  38. package/dist/node-vitest/Vitest.d.ts +52 -0
  39. package/dist/node-vitest/Vitest.d.ts.map +1 -0
  40. package/dist/node-vitest/Vitest.js +98 -0
  41. package/dist/node-vitest/Vitest.js.map +1 -0
  42. package/dist/node-vitest/Vitest.test.d.ts +2 -0
  43. package/dist/node-vitest/Vitest.test.d.ts.map +1 -0
  44. package/dist/node-vitest/Vitest.test.js +59 -0
  45. package/dist/node-vitest/Vitest.test.js.map +1 -0
  46. package/dist/node-vitest/global.d.ts +2 -0
  47. package/dist/node-vitest/global.d.ts.map +1 -0
  48. package/dist/node-vitest/{polyfill.js → global.js} +1 -1
  49. package/dist/node-vitest/global.js.map +1 -0
  50. package/dist/node-vitest/mod.d.ts +2 -1
  51. package/dist/node-vitest/mod.d.ts.map +1 -1
  52. package/dist/node-vitest/mod.js +2 -1
  53. package/dist/node-vitest/mod.js.map +1 -1
  54. package/package.json +16 -23
  55. package/src/node/DockerComposeService/DockerComposeService.test.ts +91 -0
  56. package/src/node/DockerComposeService/DockerComposeService.ts +252 -0
  57. package/src/node/DockerComposeService/test-fixtures/docker-compose.yml +4 -0
  58. package/src/node/FileLogger.ts +206 -0
  59. package/src/node/WranglerDevServer/WranglerDevServer.test.ts +268 -0
  60. package/src/node/WranglerDevServer/WranglerDevServer.ts +206 -0
  61. package/src/node/WranglerDevServer/fixtures/cf-worker.ts +11 -0
  62. package/src/node/WranglerDevServer/fixtures/wrangler.toml +11 -0
  63. package/src/node/WranglerDevServer/process-tree-manager.ts +263 -0
  64. package/src/node/cmd.ts +99 -0
  65. package/src/node/mod.ts +39 -77
  66. package/src/node-vitest/Vitest.test.ts +101 -0
  67. package/src/node-vitest/Vitest.ts +221 -0
  68. package/src/node-vitest/mod.ts +3 -1
  69. package/dist/node-vitest/polyfill.d.ts +0 -2
  70. package/dist/node-vitest/polyfill.d.ts.map +0 -1
  71. package/dist/node-vitest/polyfill.js.map +0 -1
  72. /package/src/node-vitest/{polyfill.ts → global.ts} +0 -0
@@ -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,206 @@
1
+ import * as fs from 'node:fs'
2
+ import path from 'node:path'
3
+ import util from 'node:util'
4
+ import {
5
+ Cause,
6
+ Effect,
7
+ FiberId,
8
+ HashMap,
9
+ Inspectable,
10
+ Layer,
11
+ List,
12
+ Logger,
13
+ type LogLevel,
14
+ LogSpan,
15
+ ReadonlyArray,
16
+ } from '@livestore/utils/effect'
17
+
18
+ export const makeFileLogger = (
19
+ logFilePath: string,
20
+ options?: {
21
+ readonly threadName: string
22
+ readonly colors?: boolean
23
+ },
24
+ ) =>
25
+ Layer.unwrapScoped(
26
+ Effect.gen(function* () {
27
+ yield* Effect.sync(() => fs.mkdirSync(path.dirname(logFilePath), { recursive: true }))
28
+
29
+ const logFile = yield* Effect.acquireRelease(
30
+ Effect.sync(() => fs.openSync(logFilePath, 'a', 0o666)),
31
+ (fd) => Effect.sync(() => fs.closeSync(fd)),
32
+ )
33
+
34
+ return Logger.replace(
35
+ Logger.defaultLogger,
36
+ prettyLoggerTty({
37
+ colors: options?.colors ?? false,
38
+ stderr: false,
39
+ formatDate: (date) => `${defaultDateFormat(date)} ${options?.threadName ?? ''}`,
40
+ onLog: (str) => fs.writeSync(logFile, str),
41
+ }),
42
+ )
43
+ }),
44
+ )
45
+
46
+ const withColor = (text: string, ...colors: ReadonlyArray<string>) => {
47
+ let out = ''
48
+ for (let i = 0; i < colors.length; i++) {
49
+ out += `\x1b[${colors[i]}m`
50
+ }
51
+ return `${out}${text}\x1b[0m`
52
+ }
53
+ const withColorNoop = (text: string, ..._colors: ReadonlyArray<string>) => text
54
+
55
+ const colors = {
56
+ bold: '1',
57
+ red: '31',
58
+ green: '32',
59
+ yellow: '33',
60
+ blue: '34',
61
+ cyan: '36',
62
+ white: '37',
63
+ gray: '90',
64
+ black: '30',
65
+ bgBrightRed: '101',
66
+ } as const
67
+
68
+ const logLevelColors: Record<LogLevel.LogLevel['_tag'], ReadonlyArray<string>> = {
69
+ None: [],
70
+ All: [],
71
+ Trace: [colors.gray],
72
+ Debug: [colors.blue],
73
+ Info: [colors.green],
74
+ Warning: [colors.yellow],
75
+ Error: [colors.red],
76
+ Fatal: [colors.bgBrightRed, colors.black],
77
+ }
78
+
79
+ export const defaultDateFormat = (date: Date): string =>
80
+ `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}:${date
81
+ .getSeconds()
82
+ .toString()
83
+ .padStart(2, '0')}.${date.getMilliseconds().toString().padStart(3, '0')}`
84
+
85
+ export const structuredMessage = (u: unknown): unknown => {
86
+ switch (typeof u) {
87
+ case 'bigint':
88
+ case 'function':
89
+ case 'symbol': {
90
+ return String(u)
91
+ }
92
+ default: {
93
+ return Inspectable.toJSON(u)
94
+ }
95
+ }
96
+ }
97
+
98
+ const consoleLogToString = (...s: any[]) => {
99
+ if (s.length === 0) return ''
100
+ const [first, ...rest] = s
101
+ if (typeof first === 'string') {
102
+ return rest.length > 0 ? util.format(first, ...rest.map(structuredMessage)) : first
103
+ }
104
+ return s
105
+ .map((v) => {
106
+ if (typeof v === 'string') return v
107
+ return util.inspect(structuredMessage(v), {
108
+ depth: 3,
109
+ colors: false,
110
+ compact: false,
111
+ breakLength: 120,
112
+ })
113
+ })
114
+ .join(' ')
115
+ }
116
+
117
+ export const prettyLoggerTty = (options: {
118
+ readonly colors: boolean
119
+ readonly stderr: boolean
120
+ readonly formatDate: (date: Date) => string
121
+ readonly onLog?: (str: string) => void
122
+ }) => {
123
+ const color = options.colors ? withColor : withColorNoop
124
+ return Logger.make<unknown, string>(({ annotations, cause, date, fiberId, logLevel, message: message_, spans }) => {
125
+ let str = ''
126
+
127
+ const log = (...s: any[]) => {
128
+ str += `${consoleLogToString(...s)}\n`
129
+ options.onLog?.(str)
130
+ }
131
+
132
+ const logIndented = (...s: any[]) => {
133
+ str += `${consoleLogToString(...s).replace(/^/gm, ' ')}\n`
134
+ options.onLog?.(str)
135
+ }
136
+
137
+ const message = ReadonlyArray.ensure(message_)
138
+
139
+ let firstLine =
140
+ color(`[${options.formatDate(date)}]`, colors.white) +
141
+ ` ${color(logLevel.label, ...logLevelColors[logLevel._tag])}` +
142
+ ` (${FiberId.threadName(fiberId)})`
143
+
144
+ if (List.isCons(spans)) {
145
+ const now = date.getTime()
146
+ const render = LogSpan.render(now)
147
+ for (const span of spans) {
148
+ firstLine += ` ${render(span)}`
149
+ }
150
+ }
151
+
152
+ firstLine += ':'
153
+ let messageIndex = 0
154
+ if (message.length > 0) {
155
+ const firstMaybeString = structuredMessage(message[0])
156
+ if (typeof firstMaybeString === 'string') {
157
+ firstLine += ` ${color(firstMaybeString, colors.bold, colors.cyan)}`
158
+ messageIndex++
159
+ }
160
+ }
161
+
162
+ log(firstLine)
163
+ // if (!processIsBun) console.group()
164
+
165
+ if (!Cause.isEmpty(cause)) {
166
+ logIndented(Cause.pretty(cause, { renderErrorCause: true }))
167
+ }
168
+
169
+ if (messageIndex < message.length) {
170
+ for (; messageIndex < message.length; messageIndex++) {
171
+ const msg = message[messageIndex]
172
+ if (typeof msg === 'object' && msg !== null) {
173
+ logIndented(
174
+ util.inspect(structuredMessage(msg), {
175
+ depth: 3,
176
+ colors: false,
177
+ compact: false,
178
+ breakLength: 120,
179
+ }),
180
+ )
181
+ } else {
182
+ logIndented(Inspectable.redact(msg))
183
+ }
184
+ }
185
+ }
186
+
187
+ if (HashMap.size(annotations) > 0) {
188
+ for (const [key, value] of annotations) {
189
+ const formattedValue =
190
+ typeof value === 'object' && value !== null
191
+ ? util.inspect(structuredMessage(value), {
192
+ depth: 3,
193
+ colors: false,
194
+ compact: false,
195
+ breakLength: 120,
196
+ })
197
+ : Inspectable.redact(value)
198
+ logIndented(color(`${key}:`, colors.bold, colors.white), formattedValue)
199
+ }
200
+ }
201
+
202
+ // if (!processIsBun) console.groupEnd()
203
+
204
+ return str
205
+ })
206
+ }