Open History to see the last commit
1import * as NetService from "@t3tools/shared/Net";
2import {
3 OtlpHeadersFromString,
4 OtlpProtocol,
5 type SignalExport,
6} from "@t3tools/shared/observability";
7import * as OtelEnvironment from "@t3tools/shared/otelEnvironment";
8import { parsePersistedServerObservabilitySettings } from "@t3tools/shared/serverSettings";
9import { DesktopBackendBootstrap, PortSchema } from "@t3tools/contracts";
10import * as Config from "effect/Config";
11import * as Duration from "effect/Duration";
12import * as Effect from "effect/Effect";
13import * as FileSystem from "effect/FileSystem";
14import * as LogLevel from "effect/LogLevel";
15import * as Option from "effect/Option";
16import * as Path from "effect/Path";
17import * as Redacted from "effect/Redacted";
18import * as Schema from "effect/Schema";
19import * as SchemaIssue from "effect/SchemaIssue";
20import * as SchemaTransformation from "effect/SchemaTransformation";
21import { Argument, Flag } from "effect/cli";
22import * as CliError from "effect/cli/CliError";
23
24import { readBootstrapEnvelope } from "../bootstrap.ts";
25import * as ServerConfig from "../config.ts";
26import { expandHomePath, resolveBaseDir } from "../os-jank.ts";
27import { isProcessAlive, readPersistedServerRuntimeState } from "../serverRuntimeState.ts";
28
29const modeFlag = Flag.Literals("mode", ServerConfig.RuntimeMode.literals).pipe(
30 Flag.withDescription("Runtime mode. `desktop` keeps loopback defaults unless overridden."),
31 Flag.optional,
32);
33const portFlag = Flag.Int("port").pipe(
34 Flag.withSchema(PortSchema),
35 Flag.withDescription("Port for the HTTP/WebSocket server."),
36 Flag.optional,
37);
38const hostFlag = Flag.String("host").pipe(
39 Flag.withDescription("Host/interface to bind (for example 127.0.0.1, 0.0.0.0, or a Tailnet IP)."),
40 Flag.optional,
41);
42export const baseDirFlag = Flag.String("base-dir").pipe(
43 Flag.withDescription(
44 "Explicit T3 Code data directory; runtime state is stored under userdata (equivalent to T3CODE_HOME).",
45 ),
46 Flag.optional,
47);
48const devUrlFlag = Flag.String("dev-url").pipe(
49 Flag.withSchema(Schema.URLFromString),
50 Flag.withDescription("Dev web URL to proxy/redirect to (equivalent to VITE_DEV_SERVER_URL)."),
51 Flag.optional,
52);
53const noBrowserFlag = Flag.Boolean("no-browser").pipe(
54 Flag.withDescription("Disable automatic browser opening."),
55 Flag.optional,
56);
57const bootstrapFdFlag = Flag.Int("bootstrap-fd").pipe(
58 Flag.withSchema(Schema.Int),
59 Flag.withDescription("Read one-time bootstrap secrets from the given file descriptor."),
60 Flag.optional,
61);
62const autoBootstrapProjectFromCwdFlag = Flag.Boolean("auto-bootstrap-project-from-cwd").pipe(
63 Flag.withDescription(
64 "Create a project for the current working directory on startup when missing.",
65 ),
66 Flag.optional,
67);
68const logWebSocketEventsFlag = Flag.Boolean("log-websocket-events").pipe(
69 Flag.withDescription(
70 "Emit server-side logs for outbound WebSocket push traffic (equivalent to T3CODE_LOG_WS_EVENTS).",
71 ),
72 Flag.withAlias("log-ws-events"),
73 Flag.optional,
74);
75const tailscaleServeFlag = Flag.Boolean("tailscale-serve").pipe(
76 Flag.withDescription(
77 "Configure Tailscale Serve to expose this backend over HTTPS on the Tailnet.",
78 ),
79 Flag.optional,
80);
81const tailscaleServePortFlag = Flag.Int("tailscale-serve-port").pipe(
82 Flag.withSchema(PortSchema),
83 Flag.withDescription("HTTPS port for Tailscale Serve when --tailscale-serve is enabled."),
84 Flag.optional,
85);
86
87export const traceFileConfig = Config.String("T3CODE_TRACE_FILE").pipe(
88 Config.option,
89 Config.map(Option.getOrUndefined),
90);
91export const traceMaxFilesConfig = Config.Int("T3CODE_TRACE_MAX_FILES").pipe(
92 Config.withDefault(10),
93);
94
95const EnvServerConfig = Config.all({
96 logLevel: Config.LogLevel("T3CODE_LOG_LEVEL").pipe(Config.withDefault("Info")),
97 traceMinLevel: Config.LogLevel("T3CODE_TRACE_MIN_LEVEL").pipe(Config.withDefault("Info")),
98 traceTimingEnabled: Config.Boolean("T3CODE_TRACE_TIMING_ENABLED").pipe(Config.withDefault(true)),
99 traceFile: traceFileConfig,
100 traceMaxBytes: Config.Int("T3CODE_TRACE_MAX_BYTES").pipe(Config.withDefault(10 * 1024 * 1024)),
101 traceMaxFiles: traceMaxFilesConfig,
102 traceBatchWindowMs: Config.Int("T3CODE_TRACE_BATCH_WINDOW_MS").pipe(Config.withDefault(1_000)),
103 otlpTracesUrl: Config.String("T3CODE_OTLP_TRACES_URL").pipe(
104 Config.option,
105 Config.map(Option.getOrUndefined),
106 ),
107 otlpMetricsUrl: Config.String("T3CODE_OTLP_METRICS_URL").pipe(
108 Config.option,
109 Config.map(Option.getOrUndefined),
110 ),
111 otlpLogsUrl: Config.String("T3CODE_OTLP_LOGS_URL").pipe(
112 Config.option,
113 Config.map(Option.getOrUndefined),
114 ),
115 otlpExportIntervalMs: Config.Int("T3CODE_OTLP_EXPORT_INTERVAL_MS").pipe(
116 Config.withDefault(10_000),
117 ),
118 otlpHeaders: Config.schema(OtlpHeadersFromString, "T3CODE_OTLP_HEADERS").pipe(
119 Config.option,
120 Config.map(Option.getOrUndefined),
121 ),
122 otlpProtocol: Config.schema(OtlpProtocol, "T3CODE_OTLP_PROTOCOL").pipe(
123 Config.withDefault("http/json"),
124 ),
125 mode: Config.schema(ServerConfig.RuntimeMode, "T3CODE_MODE").pipe(
126 Config.option,
127 Config.map(Option.getOrUndefined),
128 ),
129 port: Config.Port("T3CODE_PORT").pipe(Config.option, Config.map(Option.getOrUndefined)),
130 host: Config.String("T3CODE_HOST").pipe(Config.option, Config.map(Option.getOrUndefined)),
131 t3Home: Config.String("T3CODE_HOME").pipe(Config.option, Config.map(Option.getOrUndefined)),
132 devUrl: Config.URL("VITE_DEV_SERVER_URL").pipe(Config.option, Config.map(Option.getOrUndefined)),
133 devAllowedOrigins: Config.String("T3CODE_DEV_ALLOWED_ORIGINS").pipe(
134 Config.withDefault(""),
135 Config.map((value) =>
136 value
137 .split(",")
138 .map((entry) => entry.trim())
139 .filter((entry) => entry.length > 0),
140 ),
141 ),
142 noBrowser: Config.Boolean("T3CODE_NO_BROWSER").pipe(
143 Config.option,
144 Config.map(Option.getOrUndefined),
145 ),
146 bootstrapFd: Config.Int("T3CODE_BOOTSTRAP_FD").pipe(
147 Config.option,
148 Config.map(Option.getOrUndefined),
149 ),
150 autoBootstrapProjectFromCwd: Config.Boolean("T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD").pipe(
151 Config.option,
152 Config.map(Option.getOrUndefined),
153 ),
154 logWebSocketEvents: Config.Boolean("T3CODE_LOG_WS_EVENTS").pipe(
155 Config.option,
156 Config.map(Option.getOrUndefined),
157 ),
158 tailscaleServeEnabled: Config.Boolean("T3CODE_TAILSCALE_SERVE").pipe(
159 Config.option,
160 Config.map(Option.getOrUndefined),
161 ),
162 tailscaleServePort: Config.Port("T3CODE_TAILSCALE_SERVE_PORT").pipe(
163 Config.option,
164 Config.map(Option.getOrUndefined),
165 ),
166});
167
168const DevAuthTokenConfig = Config.Redacted("T3CODE_DEV_AUTH_TOKEN").pipe(
169 Config.map((token) => Redacted.make(Redacted.value(token).trim())),
170 Config.mapEffect((token) =>
171 Redacted.value(token).length === 0 || Redacted.value(token).length >= 32
172 ? Effect.succeed(token)
173 : Effect.fail(
174 new Config.ConfigError(
175 new Schema.SchemaError(
176 new SchemaIssue.InvalidValue({
177 message: "T3CODE_DEV_AUTH_TOKEN must contain at least 32 characters.",
178 }),
179 ),
180 ),
181 ),
182 ),
183 Config.option,
184 Config.map(Option.filter((token) => Redacted.value(token).length > 0)),
185 Config.map(Option.getOrUndefined),
186);
187
188export interface CliServerFlags {
189 readonly mode: Option.Option<ServerConfig.RuntimeMode>;
190 readonly port: Option.Option<number>;
191 readonly host: Option.Option<string>;
192 readonly baseDir: Option.Option<string>;
193 readonly cwd: Option.Option<string>;
194 readonly devUrl: Option.Option<URL>;
195 readonly noBrowser: Option.Option<boolean>;
196 readonly bootstrapFd: Option.Option<number>;
197 readonly autoBootstrapProjectFromCwd: Option.Option<boolean>;
198 readonly logWebSocketEvents: Option.Option<boolean>;
199 readonly tailscaleServeEnabled: Option.Option<boolean>;
200 readonly tailscaleServePort: Option.Option<number>;
201}
202
203export interface CliAuthLocationFlags {
204 readonly baseDir: Option.Option<string>;
205 readonly devUrl?: Option.Option<URL>;
206}
207
208export const authLocationFlags = {
209 baseDir: baseDirFlag,
210 devUrl: devUrlFlag,
211} as const;
212
213export const projectLocationFlags = {
214 baseDir: baseDirFlag,
215} as const;
216
217export const sharedServerCommandFlags = {
218 mode: modeFlag,
219 port: portFlag,
220 host: hostFlag,
221 baseDir: baseDirFlag,
222 cwd: Argument.String("cwd").pipe(
223 Argument.withDescription(
224 "Working directory for provider sessions (defaults to the current directory).",
225 ),
226 Argument.optional,
227 ),
228 devUrl: devUrlFlag,
229 noBrowser: noBrowserFlag,
230 bootstrapFd: bootstrapFdFlag,
231 autoBootstrapProjectFromCwd: autoBootstrapProjectFromCwdFlag,
232 logWebSocketEvents: logWebSocketEventsFlag,
233 tailscaleServeEnabled: tailscaleServeFlag,
234 tailscaleServePort: tailscaleServePortFlag,
235} as const;
236
237const resolveOptionPrecedence = <Value>(
238 ...values: ReadonlyArray<Option.Option<Value>>
239): Option.Option<Value> => Option.firstSomeOf(values);
240
241const loadPersistedObservabilitySettings = Effect.fn(function* (settingsPath: string) {
242 const fs = yield* FileSystem.FileSystem;
243 const exists = yield* fs.exists(settingsPath).pipe(Effect.orElseSucceed(() => false));
244 if (!exists) {
245 return { otlpTracesUrl: undefined, otlpMetricsUrl: undefined, otlpLogsUrl: undefined };
246 }
247
248 const raw = yield* fs.readFileString(settingsPath).pipe(Effect.orElseSucceed(() => ""));
249 return parsePersistedServerObservabilitySettings(raw);
250});
251
252export const resolveServerConfig = Effect.fn("config.resolveServerConfig")(function* (
253 flags: CliServerFlags,
254 cliLogLevel: Option.Option<LogLevel.LogLevel>,
255 options?: {
256 readonly startupPresentation?: ServerConfig.StartupPresentation;
257 readonly forceAutoBootstrapProjectFromCwd?: boolean;
258 readonly rejectRunningServer?: boolean;
259 },
260) {
261 const { findAvailablePort } = yield* NetService.NetService;
262 const path = yield* Path.Path;
263 const fs = yield* FileSystem.FileSystem;
264 const env = yield* EnvServerConfig;
265 const normalizedFlags = {
266 mode: flags.mode ?? Option.none(),
267 port: flags.port ?? Option.none(),
268 host: flags.host ?? Option.none(),
269 baseDir: flags.baseDir ?? Option.none(),
270 cwd: flags.cwd ?? Option.none(),
271 devUrl: flags.devUrl ?? Option.none(),
272 noBrowser: flags.noBrowser ?? Option.none(),
273 bootstrapFd: flags.bootstrapFd ?? Option.none(),
274 autoBootstrapProjectFromCwd: flags.autoBootstrapProjectFromCwd ?? Option.none(),
275 logWebSocketEvents: flags.logWebSocketEvents ?? Option.none(),
276 tailscaleServeEnabled: flags.tailscaleServeEnabled ?? Option.none(),
277 tailscaleServePort: flags.tailscaleServePort ?? Option.none(),
278 } satisfies CliServerFlags;
279 const bootstrapFd = Option.getOrUndefined(normalizedFlags.bootstrapFd) ?? env.bootstrapFd;
280 const bootstrapEnvelope =
281 bootstrapFd !== undefined
282 ? yield* readBootstrapEnvelope(DesktopBackendBootstrap, bootstrapFd)
283 : Option.none();
284 const bootstrap = Option.getOrUndefined(bootstrapEnvelope);
285
286 const mode: ServerConfig.RuntimeMode = Option.getOrElse(
287 resolveOptionPrecedence(
288 normalizedFlags.mode,
289 Option.fromUndefinedOr(env.mode),
290 Option.fromUndefinedOr(bootstrap?.mode),
291 ),
292 () => "web",
293 );
294
295 const port = yield* Option.match(
296 resolveOptionPrecedence(
297 normalizedFlags.port,
298 Option.fromUndefinedOr(env.port),
299 Option.fromUndefinedOr(bootstrap?.port),
300 ),
301 {
302 onSome: (value) => Effect.succeed(value),
303 onNone: () => {
304 if (mode === "desktop") {
305 return Effect.succeed(ServerConfig.DEFAULT_PORT);
306 }
307 return findAvailablePort(ServerConfig.DEFAULT_PORT);
308 },
309 },
310 );
311 const devUrl = Option.getOrElse(
312 resolveOptionPrecedence(normalizedFlags.devUrl, Option.fromUndefinedOr(env.devUrl)),
313 () => undefined,
314 );
315 const devAuthToken =
316 mode === "web" && devUrl !== undefined ? yield* DevAuthTokenConfig : undefined;
317 const explicitBaseDir = resolveOptionPrecedence(
318 normalizedFlags.baseDir,
319 Option.fromUndefinedOr(env.t3Home),
320 ).pipe(Option.filter((value) => value.trim().length > 0));
321 const baseDir = yield* resolveBaseDir(
322 Option.getOrUndefined(
323 resolveOptionPrecedence(explicitBaseDir, Option.fromUndefinedOr(bootstrap?.t3Home)),
324 ),
325 );
326 const rawCwd = Option.getOrElse(normalizedFlags.cwd, () => process.cwd());
327 const cwd = path.resolve(yield* expandHomePath(rawCwd.trim()));
328 const derivedPaths = yield* ServerConfig.deriveServerPaths(baseDir, devUrl, {
329 baseDirIsExplicit: Option.isSome(explicitBaseDir),
330 });
331 // An interactive CLI must not start over a discovered server. Lifetime locking
332 // and supervisor handoff are separate; this preflight cannot arbitrate two starts.
333 if (options?.rejectRunningServer && mode === "web") {
334 const runtime = yield* readPersistedServerRuntimeState(derivedPaths.serverRuntimeStatePath);
335 // A killed container can leave a record with the new server's own PID.
336 if (
337 Option.isSome(runtime) &&
338 runtime.value.pid > 0 &&
339 runtime.value.pid !== process.pid &&
340 isProcessAlive(runtime.value.pid)
341 ) {
342 return yield* new CliError.UserError({
343 cause: `A T3 Code server is already running for ${baseDir} (pid ${runtime.value.pid}, ${runtime.value.origin}). Connect to that server, stop it before starting another, or use a different --base-dir.`,
344 });
345 }
346 }
347 yield* fs.makeDirectory(cwd, { recursive: true });
348 yield* ServerConfig.ensureServerDirectories(derivedPaths);
349 const persistedObservabilitySettings = yield* loadPersistedObservabilitySettings(
350 derivedPaths.settingsPath,
351 );
352 const serverTracePath = env.traceFile ?? derivedPaths.serverTracePath;
353 yield* fs.makeDirectory(path.dirname(serverTracePath), { recursive: true });
354 const startupPresentation = options?.startupPresentation ?? "browser";
355 const isHeadlessStartup = startupPresentation === "headless";
356 const noBrowser = Option.getOrElse(
357 resolveOptionPrecedence(
358 isHeadlessStartup ? Option.some(true) : Option.none(),
359 normalizedFlags.noBrowser,
360 Option.fromUndefinedOr(env.noBrowser),
361 Option.fromUndefinedOr(bootstrap?.noBrowser),
362 ),
363 () => mode === "desktop",
364 );
365 const desktopBootstrapToken = bootstrap?.desktopBootstrapToken;
366 const desktopBootstrapSecret = bootstrap?.desktopBootstrapSecret;
367 const shellEnvironmentPrepared = bootstrap?.shellEnvironmentPrepared;
368 const desktopTelemetryFd = bootstrap?.desktopTelemetryFd;
369 const desktopTelemetryControlFd = bootstrap?.desktopTelemetryControlFd;
370 const desktopBrowserFd = bootstrap?.desktopBrowserFd;
371 const desktopBrowserControlFd = bootstrap?.desktopBrowserControlFd;
372 const resourceMonitorPath = bootstrap?.resourceMonitorPath;
373 const autoBootstrapProjectFromCwd = Option.getOrElse(
374 resolveOptionPrecedence(
375 Option.fromUndefinedOr(options?.forceAutoBootstrapProjectFromCwd),
376 isHeadlessStartup ? Option.some(false) : Option.none(),
377 normalizedFlags.autoBootstrapProjectFromCwd,
378 Option.fromUndefinedOr(env.autoBootstrapProjectFromCwd),
379 ),
380 () => mode === "web",
381 );
382 const logWebSocketEvents = Option.getOrElse(
383 resolveOptionPrecedence(
384 normalizedFlags.logWebSocketEvents,
385 Option.fromUndefinedOr(env.logWebSocketEvents),
386 ),
387 () => Boolean(devUrl),
388 );
389 const tailscaleServeEnabled = Option.getOrElse(
390 resolveOptionPrecedence(
391 normalizedFlags.tailscaleServeEnabled,
392 Option.fromUndefinedOr(env.tailscaleServeEnabled),
393 Option.fromUndefinedOr(bootstrap?.tailscaleServeEnabled),
394 ),
395 () => false,
396 );
397 const tailscaleServePort = Option.getOrElse(
398 resolveOptionPrecedence(
399 normalizedFlags.tailscaleServePort,
400 Option.fromUndefinedOr(env.tailscaleServePort),
401 Option.fromUndefinedOr(bootstrap?.tailscaleServePort),
402 ),
403 () => 443,
404 );
405 const staticDir = devUrl ? undefined : yield* ServerConfig.resolveStaticDir();
406 const host = Option.getOrElse(
407 resolveOptionPrecedence(
408 normalizedFlags.host,
409 Option.fromUndefinedOr(env.host),
410 Option.fromUndefinedOr(bootstrap?.host),
411 ),
412 () => (mode === "desktop" ? "127.0.0.1" : undefined),
413 );
414 const logLevel = Option.getOrElse(cliLogLevel, () => env.logLevel);
415
416 const otel = yield* OtelEnvironment.load;
417
418 const signalExport: SignalExport = {
419 protocol: env.otlpProtocol,
420 headers: env.otlpHeaders,
421 exportIntervalMs: env.otlpExportIntervalMs,
422 };
423 const traces = OtelEnvironment.resolveSignalEndpoint(
424 otel,
425 "traces",
426 { url: env.otlpTracesUrl, export: signalExport },
427 bootstrap?.otlpTracesUrl,
428 persistedObservabilitySettings.otlpTracesUrl,
429 );
430 const metrics = OtelEnvironment.resolveSignalEndpoint(
431 otel,
432 "metrics",
433 { url: env.otlpMetricsUrl, export: signalExport },
434 bootstrap?.otlpMetricsUrl,
435 persistedObservabilitySettings.otlpMetricsUrl,
436 );
437 const logs = OtelEnvironment.resolveSignalEndpoint(
438 otel,
439 "logs",
440 { url: env.otlpLogsUrl, export: signalExport },
441 bootstrap?.otlpLogsUrl,
442 persistedObservabilitySettings.otlpLogsUrl,
443 );
444
445 const config: ServerConfig.ServerConfig["Service"] = {
446 logLevel,
447 traceMinLevel: env.traceMinLevel,
448 traceTimingEnabled: env.traceTimingEnabled,
449 traceBatchWindowMs: env.traceBatchWindowMs,
450 traceMaxBytes: env.traceMaxBytes,
451 traceMaxFiles: env.traceMaxFiles,
452 otlpTracesUrl: traces?.url,
453 otlpMetricsUrl: metrics?.url,
454 otlpLogsUrl: logs?.url,
455 otlpTracesExport: traces?.export ?? signalExport,
456 otlpMetricsExport: metrics?.export ?? signalExport,
457 otlpLogsExport: logs?.export ?? signalExport,
458 otelEnvironment: otel,
459 mode,
460 port,
461 cwd,
462 baseDir,
463 ...derivedPaths,
464 serverTracePath,
465 host,
466 staticDir,
467 devUrl,
468 ...(devAuthToken === undefined ? {} : { devAuthToken }),
469 devAllowedOrigins: env.devAllowedOrigins,
470 noBrowser,
471 startupPresentation,
472 desktopBootstrapToken,
473 ...(desktopBootstrapSecret === undefined ? {} : { desktopBootstrapSecret }),
474 ...(shellEnvironmentPrepared === undefined ? {} : { shellEnvironmentPrepared }),
475 desktopTelemetryFd,
476 desktopTelemetryControlFd,
477 desktopBrowserFd,
478 desktopBrowserControlFd,
479 resourceMonitorPath,
480 autoBootstrapProjectFromCwd,
481 logWebSocketEvents,
482 tailscaleServeEnabled,
483 tailscaleServePort,
484 };
485
486 return config;
487});
488
489export const resolveCliAuthConfig = (
490 flags: CliAuthLocationFlags,
491 cliLogLevel: Option.Option<LogLevel.LogLevel>,
492) =>
493 resolveServerConfig(
494 {
495 mode: Option.none(),
496 port: Option.none(),
497 host: Option.none(),
498 baseDir: flags.baseDir,
499 cwd: Option.none(),
500 devUrl: flags.devUrl ?? Option.none(),
501 noBrowser: Option.none(),
502 bootstrapFd: Option.none(),
503 autoBootstrapProjectFromCwd: Option.none(),
504 logWebSocketEvents: Option.none(),
505 tailscaleServeEnabled: Option.none(),
506 tailscaleServePort: Option.none(),
507 },
508 cliLogLevel,
509 );
510
511const DurationShorthandPattern = /^(?<value>\d+)(?<unit>ms|s|m|h|d|w)$/i;
512
513const parseDurationInput = (value: string): Duration.Duration | null => {
514 const trimmed = value.trim();
515 if (trimmed.length === 0) return null;
516
517 const shorthand = DurationShorthandPattern.exec(trimmed);
518 const normalizedInput = shorthand?.groups
519 ? (() => {
520 const amountText = shorthand.groups.value;
521 const unitText = shorthand.groups.unit;
522 if (typeof amountText !== "string" || typeof unitText !== "string") {
523 return null;
524 }
525
526 const amount = Number.parseInt(amountText, 10);
527 if (!Number.isFinite(amount)) return null;
528
529 switch (unitText.toLowerCase()) {
530 case "ms":
531 return `${amount} millis`;
532 case "s":
533 return `${amount} seconds`;
534 case "m":
535 return `${amount} minutes`;
536 case "h":
537 return `${amount} hours`;
538 case "d":
539 return `${amount} days`;
540 case "w":
541 return `${amount} weeks`;
542 default:
543 return null;
544 }
545 })()
546 : (trimmed as Duration.Input);
547
548 if (normalizedInput === null) return null;
549
550 const decoded = Duration.fromInput(normalizedInput as Duration.Input);
551 return Option.isSome(decoded) ? decoded.value : null;
552};
553
554export const DurationFromString = Schema.String.pipe(
555 Schema.decodeTo(
556 Schema.Duration,
557 SchemaTransformation.transformEffect({
558 decode: (value) => {
559 const duration = parseDurationInput(value);
560 if (duration !== null) {
561 return Effect.succeed(duration);
562 }
563 return Effect.fail(
564 new SchemaIssue.InvalidValue({
565 message: "Invalid duration. Use values like 5m, 1h, 30d, or 15 minutes.",
566 }),
567 );
568 },
569 encode: (duration) => Effect.succeed(Duration.format(duration)),
570 }),
571 ),
572);