Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

config.ts

573 lines20.8 KB

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>;
202​
203export interface CliAuthLocationFlags {
204 readonly baseDir: Option.Option<string>;
205 readonly devUrl?: Option.Option<URL>;
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 = (
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 Effect.gen(function* () {
262 const { findAvailablePort } = yield* NetService.NetService;
263 const path = yield* Path.Path;
264 const fs = yield* FileSystem.FileSystem;
265 const env = yield* EnvServerConfig;
266 const normalizedFlags = {
267 mode: flags.mode ?? Option.none(),
268 port: flags.port ?? Option.none(),
269 host: flags.host ?? Option.none(),
270 baseDir: flags.baseDir ?? Option.none(),
271 cwd: flags.cwd ?? Option.none(),
272 devUrl: flags.devUrl ?? Option.none(),
273 noBrowser: flags.noBrowser ?? Option.none(),
274 bootstrapFd: flags.bootstrapFd ?? Option.none(),
275 autoBootstrapProjectFromCwd: flags.autoBootstrapProjectFromCwd ?? Option.none(),
276 logWebSocketEvents: flags.logWebSocketEvents ?? Option.none(),
277 tailscaleServeEnabled: flags.tailscaleServeEnabled ?? Option.none(),
278 tailscaleServePort: flags.tailscaleServePort ?? Option.none(),
279 } satisfies CliServerFlags;
280 const bootstrapFd = Option.getOrUndefined(normalizedFlags.bootstrapFd) ?? env.bootstrapFd;
281 const bootstrapEnvelope =
282 bootstrapFd !== undefined
283 ? yield* readBootstrapEnvelope(DesktopBackendBootstrap, bootstrapFd)
284 : Option.none();
285 const bootstrap = Option.getOrUndefined(bootstrapEnvelope);
286​
287 const mode: ServerConfig.RuntimeMode = Option.getOrElse(
288 resolveOptionPrecedence(
289 normalizedFlags.mode,
290 Option.fromUndefinedOr(env.mode),
291 Option.fromUndefinedOr(bootstrap?.mode),
292 ),
293 () => "web",
294 );
295​
296 const port = yield* Option.match(
297 resolveOptionPrecedence(
298 normalizedFlags.port,
299 Option.fromUndefinedOr(env.port),
300 Option.fromUndefinedOr(bootstrap?.port),
301 ),
302 {
303 onSome: (value) => Effect.succeed(value),
304 onNone: () => {
305 if (mode === "desktop") {
306 return Effect.succeed(ServerConfig.DEFAULT_PORT);
307 }
308 return findAvailablePort(ServerConfig.DEFAULT_PORT);
309 },
310 },
311 );
312 const devUrl = Option.getOrElse(
313 resolveOptionPrecedence(normalizedFlags.devUrl, Option.fromUndefinedOr(env.devUrl)),
314 () => undefined,
315 );
316 const devAuthToken =
317 mode === "web" && devUrl !== undefined ? yield* DevAuthTokenConfig : undefined;
318 const explicitBaseDir = resolveOptionPrecedence(
319 normalizedFlags.baseDir,
320 Option.fromUndefinedOr(env.t3Home),
321 ).pipe(Option.filter((value) => value.trim().length > 0));
322 const baseDir = yield* resolveBaseDir(
323 Option.getOrUndefined(
324 resolveOptionPrecedence(explicitBaseDir, Option.fromUndefinedOr(bootstrap?.t3Home)),
325 ),
326 );
327 const rawCwd = Option.getOrElse(normalizedFlags.cwd, () => process.cwd());
328 const cwd = path.resolve(yield* expandHomePath(rawCwd.trim()));
329 const derivedPaths = yield* ServerConfig.deriveServerPaths(baseDir, devUrl, {
330 baseDirIsExplicit: Option.isSome(explicitBaseDir),
331 });
332 // An interactive CLI must not start over a discovered server. Lifetime locking
333 // and supervisor handoff are separate; this preflight cannot arbitrate two starts.
334 if (options?.rejectRunningServer && mode === "web") {
335 const runtime = yield* readPersistedServerRuntimeState(derivedPaths.serverRuntimeStatePath);
336 // A killed container can leave a record with the new server's own PID.
337 if (
338 Option.isSome(runtime) &&
339 runtime.value.pid > 0 &&
340 runtime.value.pid !== process.pid &&
341 isProcessAlive(runtime.value.pid)
342 ) {
343 return yield* new CliError.UserError({
344 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.`,
345 });
346 }
347 }
348 yield* fs.makeDirectory(cwd, { recursive: true });
349 yield* ServerConfig.ensureServerDirectories(derivedPaths);
350 const persistedObservabilitySettings = yield* loadPersistedObservabilitySettings(
351 derivedPaths.settingsPath,
352 );
353 const serverTracePath = env.traceFile ?? derivedPaths.serverTracePath;
354 yield* fs.makeDirectory(path.dirname(serverTracePath), { recursive: true });
355 const startupPresentation = options?.startupPresentation ?? "browser";
356 const isHeadlessStartup = startupPresentation === "headless";
357 const noBrowser = Option.getOrElse(
358 resolveOptionPrecedence(
359 isHeadlessStartup ? Option.some(true) : Option.none(),
360 normalizedFlags.noBrowser,
361 Option.fromUndefinedOr(env.noBrowser),
362 Option.fromUndefinedOr(bootstrap?.noBrowser),
363 ),
364 () => mode === "desktop",
365 );
366 const desktopBootstrapToken = bootstrap?.desktopBootstrapToken;
367 const desktopBootstrapSecret = bootstrap?.desktopBootstrapSecret;
368 const shellEnvironmentPrepared = bootstrap?.shellEnvironmentPrepared;
369 const desktopTelemetryFd = bootstrap?.desktopTelemetryFd;
370 const desktopTelemetryControlFd = bootstrap?.desktopTelemetryControlFd;
371 const desktopBrowserFd = bootstrap?.desktopBrowserFd;
372 const desktopBrowserControlFd = bootstrap?.desktopBrowserControlFd;
373 const resourceMonitorPath = bootstrap?.resourceMonitorPath;
374 const autoBootstrapProjectFromCwd = Option.getOrElse(
375 resolveOptionPrecedence(
376 Option.fromUndefinedOr(options?.forceAutoBootstrapProjectFromCwd),
377 isHeadlessStartup ? Option.some(false) : Option.none(),
378 normalizedFlags.autoBootstrapProjectFromCwd,
379 Option.fromUndefinedOr(env.autoBootstrapProjectFromCwd),
380 ),
381 () => mode === "web",
382 );
383 const logWebSocketEvents = Option.getOrElse(
384 resolveOptionPrecedence(
385 normalizedFlags.logWebSocketEvents,
386 Option.fromUndefinedOr(env.logWebSocketEvents),
387 ),
388 () => Boolean(devUrl),
389 );
390 const tailscaleServeEnabled = Option.getOrElse(
391 resolveOptionPrecedence(
392 normalizedFlags.tailscaleServeEnabled,
393 Option.fromUndefinedOr(env.tailscaleServeEnabled),
394 Option.fromUndefinedOr(bootstrap?.tailscaleServeEnabled),
395 ),
396 () => false,
397 );
398 const tailscaleServePort = Option.getOrElse(
399 resolveOptionPrecedence(
400 normalizedFlags.tailscaleServePort,
401 Option.fromUndefinedOr(env.tailscaleServePort),
402 Option.fromUndefinedOr(bootstrap?.tailscaleServePort),
403 ),
404 () => 443,
405 );
406 const staticDir = devUrl ? undefined : yield* ServerConfig.resolveStaticDir();
407 const host = Option.getOrElse(
408 resolveOptionPrecedence(
409 normalizedFlags.host,
410 Option.fromUndefinedOr(env.host),
411 Option.fromUndefinedOr(bootstrap?.host),
412 ),
413 () => (mode === "desktop" ? "127.0.0.1" : undefined),
414 );
415 const logLevel = Option.getOrElse(cliLogLevel, () => env.logLevel);
416​
417 const otel = yield* OtelEnvironment.load;
418​
419 const signalExport: SignalExport = {
420 protocol: env.otlpProtocol,
421 headers: env.otlpHeaders,
422 exportIntervalMs: env.otlpExportIntervalMs,
423 };
424 const traces = OtelEnvironment.resolveSignalEndpoint(
425 otel,
426 "traces",
427 { url: env.otlpTracesUrl, export: signalExport },
428 bootstrap?.otlpTracesUrl,
429 persistedObservabilitySettings.otlpTracesUrl,
430 );
431 const metrics = OtelEnvironment.resolveSignalEndpoint(
432 otel,
433 "metrics",
434 { url: env.otlpMetricsUrl, export: signalExport },
435 bootstrap?.otlpMetricsUrl,
436 persistedObservabilitySettings.otlpMetricsUrl,
437 );
438 const logs = OtelEnvironment.resolveSignalEndpoint(
439 otel,
440 "logs",
441 { url: env.otlpLogsUrl, export: signalExport },
442 bootstrap?.otlpLogsUrl,
443 persistedObservabilitySettings.otlpLogsUrl,
444 );
445​
446 const config: ServerConfig.ServerConfig["Service"] = {
447 logLevel,
448 traceMinLevel: env.traceMinLevel,
449 traceTimingEnabled: env.traceTimingEnabled,
450 traceBatchWindowMs: env.traceBatchWindowMs,
451 traceMaxBytes: env.traceMaxBytes,
452 traceMaxFiles: env.traceMaxFiles,
453 otlpTracesUrl: traces?.url,
454 otlpMetricsUrl: metrics?.url,
455 otlpLogsUrl: logs?.url,
456 otlpTracesExport: traces?.export ?? signalExport,
457 otlpMetricsExport: metrics?.export ?? signalExport,
458 otlpLogsExport: logs?.export ?? signalExport,
459 otelEnvironment: otel,
460 mode,
461 port,
462 cwd,
463 baseDir,
464 ...derivedPaths,
465 serverTracePath,
466 host,
467 staticDir,
468 devUrl,
469 ...(devAuthToken === undefined ? {} : { devAuthToken }),
470 devAllowedOrigins: env.devAllowedOrigins,
471 noBrowser,
472 startupPresentation,
473 desktopBootstrapToken,
474 ...(desktopBootstrapSecret === undefined ? {} : { desktopBootstrapSecret }),
475 ...(shellEnvironmentPrepared === undefined ? {} : { shellEnvironmentPrepared }),
476 desktopTelemetryFd,
477 desktopTelemetryControlFd,
478 desktopBrowserFd,
479 desktopBrowserControlFd,
480 resourceMonitorPath,
481 autoBootstrapProjectFromCwd,
482 logWebSocketEvents,
483 tailscaleServeEnabled,
484 tailscaleServePort,
485 };
486​
487 return config;
488 });
489​
490export const resolveCliAuthConfig = (
491 flags: CliAuthLocationFlags,
492 cliLogLevel: Option.Option<LogLevel.LogLevel>,
493) =>
494 resolveServerConfig(
495 {
496 mode: Option.none(),
497 port: Option.none(),
498 host: Option.none(),
499 baseDir: flags.baseDir,
500 cwd: Option.none(),
501 devUrl: flags.devUrl ?? Option.none(),
502 noBrowser: Option.none(),
503 bootstrapFd: Option.none(),
504 autoBootstrapProjectFromCwd: Option.none(),
505 logWebSocketEvents: Option.none(),
506 tailscaleServeEnabled: Option.none(),
507 tailscaleServePort: Option.none(),
508 },
509 cliLogLevel,
510 );
511​
512const DurationShorthandPattern = /^(?<value>\d+)(?<unit>ms|s|m|h|d|w)$/i;
513​
514const parseDurationInput = (value: string): Duration.Duration | null => {
515 const trimmed = value.trim();
516 if (trimmed.length === 0) return null;
517​
518 const shorthand = DurationShorthandPattern.exec(trimmed);
519 const normalizedInput = shorthand?.groups
520 ? (() => {
521 const amountText = shorthand.groups.value;
522 const unitText = shorthand.groups.unit;
523 if (typeof amountText !== "string" || typeof unitText !== "string") {
524 return null;
525 }
526​
527 const amount = Number.parseInt(amountText, 10);
528 if (!Number.isFinite(amount)) return null;
529​
530 switch (unitText.toLowerCase()) {
531 case "ms":
532 return `${amount} millis`;
533 case "s":
534 return `${amount} seconds`;
535 case "m":
536 return `${amount} minutes`;
537 case "h":
538 return `${amount} hours`;
539 case "d":
540 return `${amount} days`;
541 case "w":
542 return `${amount} weeks`;
543 default:
544 return null;
545 }
546 })()
547 : (trimmed as Duration.Input);
548​
549 if (normalizedInput === null) return null;
550​
551 const decoded = Duration.fromInput(normalizedInput as Duration.Input);
552 return Option.isSome(decoded) ? decoded.value : null;
553};
554​
555export const DurationFromString = Schema.String.pipe(
556 Schema.decodeTo(
557 Schema.Duration,
558 SchemaTransformation.transformEffect({
559 decode: (value) => {
560 const duration = parseDurationInput(value);
561 if (duration !== null) {
562 return Effect.succeed(duration);
563 }
564 return Effect.fail(
565 new SchemaIssue.InvalidValue({
566 message: "Invalid duration. Use values like 5m, 1h, 30d, or 15 minutes.",
567 }),
568 );
569 },
570 encode: (duration) => Effect.succeed(Duration.format(duration)),
571 }),
572 ),
573);